-
Notifications
You must be signed in to change notification settings - Fork 3
/
Fairy.WebSocket.Subscribe.cs
196 lines (189 loc) · 9.55 KB
/
Fairy.WebSocket.Subscribe.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
using Neo.Json;
using Neo.Ledger;
using Neo.Network.P2P.Payloads;
using Neo.Persistence;
using Neo.SmartContract;
using Neo.SmartContract.Native;
using Neo.VM;
using System.Collections.Concurrent;
using System.Net.WebSockets;
namespace Neo.Plugins
{
public partial class Fairy : RpcServer
{
protected Block? committingBlock;
protected ConcurrentDictionary<NotifyEventArgs, UInt256> notifications = new();
protected ConcurrentDictionary<SemaphoreSlim, WebSocket> committingBlockSemaphores = new();
protected ConcurrentDictionary<SemaphoreSlim, WebSocket> notificationSemaphores = new();
protected DataCache? latestSnapshot;
protected void RegisterBlockchainEvents()
{
Blockchain.Committing += delegate (NeoSystem system, Block block, DataCache snapshot, IReadOnlyList<Blockchain.ApplicationExecuted> applicationExecutedList)
{
// block
committingBlock = block;
foreach (var item in committingBlockSemaphores)
item.Key.Release();
// notifications
if (notificationSemaphores.Count > 0)
{
latestSnapshot = snapshot;
notifications.Clear();
foreach (Blockchain.ApplicationExecuted app in applicationExecutedList)
foreach (NotifyEventArgs notification in app.Notifications)
if (app.Transaction != null)
notifications[notification] = app.Transaction.Hash;
foreach (var item in notificationSemaphores)
item.Key.Release();
}
};
}
[WebsocketControlMethod]
protected virtual JToken UnsubscribeLastAction(WebSocket webSocket, JArray _params, LinkedList<object> webSocketSubscriptions)
{
object o = webSocketSubscriptions.Last!.Value;
if (o is WebSocketSubscription)
{
WebSocketSubscription webSocketSubscription = (WebSocketSubscription)o;
webSocketSubscription.cancellationTokenSource.Cancel();
webSocketSubscriptions.RemoveLast();
return webSocketSubscription.ToJson();
}
else if (o is WebSocketSubscriptionNeoGoCompatible)
{
WebSocketSubscriptionNeoGoCompatible webSocketSubscriptionNeoGoCompatible = (WebSocketSubscriptionNeoGoCompatible)o;
JArray subscriptionId = new JArray();
subscriptionId.Add(webSocketSubscriptionNeoGoCompatible.subscriptionId.ToString("x"));
Unsubscribe(webSocket, subscriptionId);
return webSocketSubscriptionNeoGoCompatible.ToJson();
}
else
throw new NotImplementedException(webSocketSubscriptions.ToString());
}
[WebsocketControlMethod]
protected virtual JToken UnsubscribeMethod(WebSocket webSocket, JArray _params, LinkedList<object> webSocketSubscriptions)
{
string method = _params[0]!.AsString();
JArray returned = new();
LinkedListNode<object>? node = webSocketSubscriptions.Last;
while (node != null)
{
if (node is LinkedListNode<WebSocketSubscription> && ((WebSocketSubscription)node.Value).method == method)
{
webSocketSubscriptions.Remove(node);
WebSocketSubscription value = (WebSocketSubscription)node.Value;
value.cancellationTokenSource.Cancel();
returned.Add(value.ToJson());
node = node.Previous;
}
}
return returned;
}
[WebsocketMethod]
protected virtual Action SubscribeCommittingBlock(WebSocket webSocket, JArray _params, CancellationToken cancellationToken)
{
return async () =>
{
SemaphoreSlim semaphore = new(1);
committingBlockSemaphores[semaphore] = webSocket;
while (true)
{
try
{
await semaphore.WaitAsync();
switch (webSocket.State)
{
case WebSocketState.Open:
if (committingBlock != null)
await webSocket.SendAsync(committingBlock.ToJson(system.Settings).ToByteArray(false), WebSocketMessageType.Text, true, CancellationToken.None);
if (cancellationToken.IsCancellationRequested)
{
committingBlockSemaphores.Remove(semaphore, out _);
return;
}
break;
case WebSocketState.Closed:
committingBlockSemaphores.Remove(semaphore, out _);
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, webSocket.State.ToString(), CancellationToken.None);
webSocket.Dispose();
return;
default:
committingBlockSemaphores.Remove(semaphore, out _);
webSocket.Dispose();
return;
}
}
catch (Exception ex)
{
committingBlockSemaphores.Remove(semaphore, out _);
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, ex.StackTrace, CancellationToken.None);
webSocket.Dispose();
return;
}
}
};
}
[WebsocketMethod]
protected virtual Action SubscribeContractEvent(WebSocket webSocket, JArray _params, CancellationToken cancellationToken)
{
HashSet<UInt160> contracts = _params.Count > 0 ? ((JArray)_params[0]!).Select(v => UInt160.Parse(v!.AsString())).ToHashSet() : new();
HashSet<string> eventNames = _params.Count > 1 ? ((JArray)_params[1]!).Select(v => v!.AsString().ToLower()).ToHashSet() : new();
return async () =>
{
SemaphoreSlim semaphore = new(1);
notificationSemaphores[semaphore] = webSocket;
while (true)
{
try
{
await semaphore.WaitAsync();
switch (webSocket.State)
{
case WebSocketState.Open:
JArray json = new();
foreach (var item in notifications)
{
NotifyEventArgs notification = item.Key;
if (contracts.Count > 0 && !contracts.Contains(notification.ScriptHash))
continue;
if (eventNames.Count > 0 && !eventNames.Contains(notification.EventName.ToLower()))
continue;
JObject notificationJson = new();
notificationJson["tx"] = item.Value.ToString();
notificationJson["scripthash"] = notification.ScriptHash.ToString();
notificationJson["contractname"] = NativeContract.ContractManagement.GetContract(latestSnapshot, notification.ScriptHash)?.Manifest.Name;
notificationJson["eventname"] = notification.EventName;
notificationJson["eventargs"] = notification.State.ToJson();
json.Add(notificationJson);
}
if (json.Count > 0)
await webSocket.SendAsync(json.ToByteArray(false), WebSocketMessageType.Text, true, CancellationToken.None);
if (cancellationToken.IsCancellationRequested)
{
notificationSemaphores.Remove(semaphore, out _);
return;
}
break;
case WebSocketState.Closed:
notificationSemaphores.Remove(semaphore, out _);
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, webSocket.State.ToString(), CancellationToken.None);
webSocket.Dispose();
return;
default:
notificationSemaphores.Remove(semaphore, out _);
webSocket.Dispose();
return;
}
}
catch (Exception ex)
{
notificationSemaphores.Remove(semaphore, out _);
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, ex.StackTrace, CancellationToken.None);
webSocket.Dispose();
return;
}
}
};
}
}
}