-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathSpacetimeDBClient.cs
More file actions
940 lines (809 loc) · 36.9 KB
/
SpacetimeDBClient.cs
File metadata and controls
940 lines (809 loc) · 36.9 KB
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using SpacetimeDB.BSATN;
using SpacetimeDB.ClientApi;
using Thread = System.Threading.Thread;
namespace SpacetimeDB
{
public sealed class DbConnectionBuilder<DbConnection>
where DbConnection : IDbConnection, new()
{
readonly DbConnection conn = new();
string? uri;
string? nameOrAddress;
string? token;
Compression? compression;
bool light;
public DbConnection Build()
{
if (uri == null)
{
throw new InvalidOperationException("Building DbConnection with a null uri. Call WithUri() first.");
}
if (nameOrAddress == null)
{
throw new InvalidOperationException("Building DbConnection with a null nameOrAddress. Call WithModuleName() first.");
}
conn.Connect(token, uri, nameOrAddress, compression ?? Compression.Brotli, light);
#if UNITY_5_3_OR_NEWER
if (SpacetimeDBNetworkManager._instance != null)
{
SpacetimeDBNetworkManager._instance.AddConnection(conn);
}
#endif
return conn;
}
public DbConnectionBuilder<DbConnection> WithUri(string uri)
{
this.uri = uri;
return this;
}
public DbConnectionBuilder<DbConnection> WithModuleName(string nameOrAddress)
{
this.nameOrAddress = nameOrAddress;
return this;
}
public DbConnectionBuilder<DbConnection> WithToken(string? token)
{
this.token = token;
return this;
}
public DbConnectionBuilder<DbConnection> WithCompression(Compression compression)
{
this.compression = compression;
return this;
}
public DbConnectionBuilder<DbConnection> WithLightMode(bool light)
{
this.light = light;
return this;
}
public delegate void ConnectCallback(DbConnection conn, Identity identity, string token);
public DbConnectionBuilder<DbConnection> OnConnect(ConnectCallback cb)
{
conn.AddOnConnect((identity, token) => cb(conn, identity, token));
return this;
}
public delegate void ConnectErrorCallback(Exception e);
public DbConnectionBuilder<DbConnection> OnConnectError(ConnectErrorCallback cb)
{
conn.AddOnConnectError(e => cb(e));
return this;
}
public delegate void DisconnectCallback(DbConnection conn, Exception? e);
public DbConnectionBuilder<DbConnection> OnDisconnect(DisconnectCallback cb)
{
conn.AddOnDisconnect(e => cb(conn, e));
return this;
}
}
public interface IDbConnection
{
internal void Connect(string? token, string uri, string addressOrName, Compression compression, bool light);
internal void AddOnConnect(Action<Identity, string> cb);
internal void AddOnConnectError(WebSocket.ConnectErrorEventHandler cb);
internal void AddOnDisconnect(WebSocket.CloseEventHandler cb);
internal void LegacySubscribe(ISubscriptionHandle handle, string[] querySqls);
internal QueryId? Subscribe(ISubscriptionHandle handle, string[] querySqls);
internal void Unsubscribe(QueryId queryId);
void FrameTick();
void Disconnect();
internal Task<T[]> RemoteQuery<T>(string query) where T : IStructuralReadWrite, new();
void InternalCallReducer<T>(T args, CallReducerFlags flags)
where T : IReducerArgs, new();
}
public abstract class DbConnectionBase<DbConnection, Tables, Reducer> : IDbConnection
where DbConnection : DbConnectionBase<DbConnection, Tables, Reducer>, new()
where Tables : RemoteTablesBase
{
public static DbConnectionBuilder<DbConnection> Builder() => new();
internal event Action<Identity, string>? onConnect;
/// <summary>
/// Called when an exception occurs when sending a message.
/// </summary>
[Obsolete]
public event Action<Exception>? onSendError;
/// <summary>
/// Dictionary of legacy subscriptions, keyed by request ID rather than query ID.
/// Only used for `SubscribeToAllTables()`.
/// </summary>
private readonly Dictionary<uint, ISubscriptionHandle> legacySubscriptions = new();
/// <summary>
/// Dictionary of subscriptions, keyed by query ID.
/// </summary>
private readonly Dictionary<uint, ISubscriptionHandle> subscriptions = new();
/// <summary>
/// Allocates query IDs.
/// </summary>
private UintAllocator queryIdAllocator;
public readonly ConnectionId ConnectionId = ConnectionId.Random();
public Identity? Identity { get; private set; }
internal WebSocket webSocket;
private bool connectionClosed;
public abstract Tables Db { get; }
protected abstract Reducer ToReducer(TransactionUpdate update);
protected abstract IEventContext ToEventContext(Event<Reducer> Event);
protected abstract IReducerEventContext ToReducerEventContext(ReducerEvent<Reducer> reducerEvent);
protected abstract ISubscriptionEventContext MakeSubscriptionEventContext();
protected abstract IErrorContext ToErrorContext(Exception errorContext);
private readonly Dictionary<Guid, TaskCompletionSource<OneOffQueryResponse>> waitingOneOffQueries = new();
private bool isClosing;
private readonly Thread networkMessageParseThread;
public readonly Stats stats = new();
protected DbConnectionBase()
{
var options = new WebSocket.ConnectOptions
{
//v1.bin.spacetimedb
//v1.text.spacetimedb
Protocol = "v1.bsatn.spacetimedb"
};
webSocket = new WebSocket(options);
webSocket.OnMessage += OnMessageReceived;
webSocket.OnSendError += a => onSendError?.Invoke(a);
#if UNITY_5_3_OR_NEWER
webSocket.OnClose += (e) =>
{
if (SpacetimeDBNetworkManager._instance != null)
{
SpacetimeDBNetworkManager._instance.RemoveConnection(this);
}
};
#if UNITY_WEBGL && !UNITY_EDITOR
if (SpacetimeDBNetworkManager._instance != null)
SpacetimeDBNetworkManager._instance.StartCoroutine(ParseMessages());
#endif
#endif
#if !(UNITY_WEBGL && !UNITY_EDITOR)
// For targets other than webgl we start a thread to parse messages
networkMessageParseThread = new Thread(ParseMessages);
networkMessageParseThread.Start();
#endif
}
internal struct UnparsedMessage
{
/// <summary>
/// The bytes of the message.
/// </summary>
public byte[] bytes;
/// <summary>
/// The timestamp the message came off the wire.
/// </summary>
public DateTime timestamp;
/// <summary>
/// The ID assigned by the message parsing queue tracker.
/// </summary>
public uint parseQueueTrackerId;
}
internal struct ParsedMessage
{
public ServerMessage message;
public ParsedDatabaseUpdate dbOps;
public DateTime receiveTimestamp;
public uint applyQueueTrackerId;
public ReducerEvent<Reducer>? reducerEvent;
}
private readonly BlockingCollection<UnparsedMessage> _parseQueue =
new(new ConcurrentQueue<UnparsedMessage>());
private readonly BlockingCollection<ParsedMessage> _applyQueue =
new(new ConcurrentQueue<ParsedMessage>());
internal static bool IsTesting;
internal bool HasMessageToApply => _applyQueue.Count > 0;
private readonly CancellationTokenSource _parseCancellationTokenSource = new();
private CancellationToken _parseCancellationToken => _parseCancellationTokenSource.Token;
private static readonly Status Committed = new Status.Committed(default);
private static readonly Status OutOfEnergy = new Status.OutOfEnergy(default);
/// <summary>
/// Get a description of a message suitable for storing in the tracker metadata.
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
internal string TrackerMetadataForMessage(ServerMessage message) => message switch
{
ServerMessage.TransactionUpdate(var transactionUpdate) => $"type={nameof(ServerMessage.TransactionUpdate)},reducer={transactionUpdate.ReducerCall.ReducerName}",
_ => $"type={message.GetType().Name}"
};
#if UNITY_WEBGL && !UNITY_EDITOR
internal IEnumerator ParseMessages()
#else
internal void ParseMessages()
#endif
{
while (!isClosing)
{
#if UNITY_WEBGL && !UNITY_EDITOR
yield return null;
while (_parseQueue.Count > 0)
#endif
try
{
var message = _parseQueue.Take(_parseCancellationToken);
var parsedMessage = ParseMessage(message);
_applyQueue.Add(parsedMessage, _parseCancellationToken);
}
catch (OperationCanceledException)
{
#if UNITY_WEBGL && !UNITY_EDITOR
break;
#else
return; // Normal shutdown
#endif
}
}
IEnumerable<(IRemoteTableHandle, TableUpdate)> GetTables(DatabaseUpdate updates)
{
foreach (var update in updates.Tables)
{
var tableName = update.TableName;
var table = Db.GetTable(tableName);
if (table == null)
{
Log.Error($"Unknown table name: {tableName}");
continue;
}
yield return (table, update);
}
}
ParsedDatabaseUpdate ParseLegacySubscription(InitialSubscription initSub)
{
var dbOps = ParsedDatabaseUpdate.New();
// This is all of the inserts
int cap = initSub.DatabaseUpdate.Tables.Sum(a => (int)a.NumRows);
// First apply all of the state
foreach (var (table, update) in GetTables(initSub.DatabaseUpdate))
{
table.ParseInsertOnly(update, dbOps);
}
return dbOps;
}
/// <summary>
/// TODO: the dictionary is here for backwards compatibility and can be removed
/// once we get rid of legacy subscriptions.
/// </summary>
ParsedDatabaseUpdate ParseSubscribeMultiApplied(SubscribeMultiApplied subscribeMultiApplied)
{
var dbOps = ParsedDatabaseUpdate.New();
foreach (var (table, update) in GetTables(subscribeMultiApplied.Update))
{
table.ParseInsertOnly(update, dbOps);
}
return dbOps;
}
ParsedDatabaseUpdate ParseUnsubscribeMultiApplied(UnsubscribeMultiApplied unsubMultiApplied)
{
var dbOps = ParsedDatabaseUpdate.New();
foreach (var (table, update) in GetTables(unsubMultiApplied.Update))
{
table.ParseDeleteOnly(update, dbOps);
}
return dbOps;
}
ParsedDatabaseUpdate ParseDatabaseUpdate(DatabaseUpdate updates)
{
var dbOps = ParsedDatabaseUpdate.New();
foreach (var (table, update) in GetTables(updates))
{
table.Parse(update, dbOps);
}
return dbOps;
}
void ParseOneOffQuery(OneOffQueryResponse resp)
{
/// This case does NOT produce a list of DBOps, because it should not modify the client cache state!
var messageId = new Guid(resp.MessageId.ToArray());
if (!waitingOneOffQueries.Remove(messageId, out var resultSource))
{
Log.Error($"Response to unknown one-off-query: {messageId}");
return;
}
resultSource.SetResult(resp);
}
ParsedMessage ParseMessage(UnparsedMessage unparsed)
{
var dbOps = ParsedDatabaseUpdate.New();
var message = CompressionHelpers.DecompressDecodeMessage(unparsed.bytes);
var trackerMetadata = TrackerMetadataForMessage(message);
stats.ParseMessageQueueTracker.FinishTrackingRequest(unparsed.parseQueueTrackerId, trackerMetadata);
var parseStart = DateTime.UtcNow;
ReducerEvent<Reducer>? reducerEvent = default;
switch (message)
{
case ServerMessage.InitialSubscription(var initSub):
stats.SubscriptionRequestTracker.FinishTrackingRequest(initSub.RequestId, unparsed.timestamp);
dbOps = ParseLegacySubscription(initSub);
break;
case ServerMessage.SubscribeApplied(var subscribeApplied):
break;
case ServerMessage.SubscribeMultiApplied(var subscribeMultiApplied):
stats.SubscriptionRequestTracker.FinishTrackingRequest(subscribeMultiApplied.RequestId, unparsed.timestamp);
dbOps = ParseSubscribeMultiApplied(subscribeMultiApplied);
break;
case ServerMessage.SubscriptionError(var subscriptionError):
// do nothing; main thread will warn.
if (subscriptionError.RequestId.HasValue)
{
stats.SubscriptionRequestTracker.FinishTrackingRequest(subscriptionError.RequestId.Value, unparsed.timestamp);
}
break;
case ServerMessage.UnsubscribeApplied(var unsubscribeApplied):
// do nothing; main thread will warn.
break;
case ServerMessage.UnsubscribeMultiApplied(var unsubscribeMultiApplied):
stats.SubscriptionRequestTracker.FinishTrackingRequest(unsubscribeMultiApplied.RequestId, unparsed.timestamp);
dbOps = ParseUnsubscribeMultiApplied(unsubscribeMultiApplied);
break;
case ServerMessage.TransactionUpdate(var transactionUpdate):
// Convert the generic event arguments in to a domain specific event object
var hostDuration = (TimeSpan)transactionUpdate.TotalHostExecutionDuration;
stats.AllReducersTracker.InsertRequest(hostDuration, $"reducer={transactionUpdate.ReducerCall.ReducerName}");
try
{
reducerEvent = new(
(DateTimeOffset)transactionUpdate.Timestamp,
transactionUpdate.Status switch
{
UpdateStatus.Committed => Committed,
UpdateStatus.OutOfEnergy => OutOfEnergy,
UpdateStatus.Failed(var reason) => new Status.Failed(reason),
_ => throw new InvalidOperationException()
},
transactionUpdate.CallerIdentity,
transactionUpdate.CallerConnectionId,
transactionUpdate.EnergyQuantaUsed.Quanta,
ToReducer(transactionUpdate));
}
catch (Exception)
{
// Failing to parse the ReducerEvent is fine, it just means we should
// call downstream stuff with an UnknownTransaction.
// See ApplyMessage
}
var callerIdentity = transactionUpdate.CallerIdentity;
if (callerIdentity == Identity && transactionUpdate.CallerConnectionId == ConnectionId)
{
// This was a request that we initiated
var requestId = transactionUpdate.ReducerCall.RequestId;
// Make sure we mark the request as having finished when it came off the wire.
// That's why we use unparsed.timestamp, rather than DateTime.UtcNow.
// See ReducerRequestTracker's comment.
if (!stats.ReducerRequestTracker.FinishTrackingRequest(requestId, unparsed.timestamp))
{
Log.Warn($"Failed to finish tracking reducer request: {requestId}");
}
}
if (transactionUpdate.Status is UpdateStatus.Committed(var committed))
{
dbOps = ParseDatabaseUpdate(committed);
}
break;
case ServerMessage.TransactionUpdateLight(var update):
dbOps = ParseDatabaseUpdate(update.Update);
break;
case ServerMessage.IdentityToken(var identityToken):
break;
case ServerMessage.OneOffQueryResponse(var resp):
ParseOneOffQuery(resp);
break;
default:
throw new InvalidOperationException();
}
stats.ParseMessageTracker.InsertRequest(parseStart, trackerMetadata);
var applyTracker = stats.ApplyMessageQueueTracker.StartTrackingRequest(trackerMetadata);
return new ParsedMessage { message = message, dbOps = dbOps, receiveTimestamp = unparsed.timestamp, applyQueueTrackerId = applyTracker, reducerEvent = reducerEvent };
}
}
public void Disconnect()
{
isClosing = true;
connectionClosed = true;
// Only try to close if the connection is active
if (webSocket.IsConnected)
{
webSocket.Close();
}
#if UNITY_WEBGL && !UNITY_EDITOR
else if (webSocket.IsConnecting)
#else
else if (webSocket.IsConnecting || webSocket.IsNoneState)
#endif
{
webSocket.Abort(); // forceful during connecting
}
_parseCancellationTokenSource.Cancel();
}
/// <summary>
/// Connect to a remote spacetime instance.
/// </summary>
/// <param name="uri"> URI of the SpacetimeDB server (ex: https://testnet.spacetimedb.com)
/// <param name="addressOrName">The name or address of the database to connect to</param>
void IDbConnection.Connect(string? token, string uri, string addressOrName, Compression compression, bool light)
{
isClosing = false;
uri = uri.Replace("http://", "ws://");
uri = uri.Replace("https://", "wss://");
if (!uri.StartsWith("ws://") && !uri.StartsWith("wss://"))
{
uri = $"ws://{uri}";
}
// Things fail surprisingly if we have a trailing slash, because we later manually append strings
// like `/foo` and then end up with `//` in the URI.
uri = uri.TrimEnd('/');
Log.Info($"SpacetimeDBClient: Connecting to {uri} {addressOrName}");
if (!IsTesting)
{
#if UNITY_WEBGL && !UNITY_EDITOR
async Task Function()
#else
Task.Run(async () =>
#endif
{
try
{
await webSocket.Connect(token, uri, addressOrName, ConnectionId, compression, light);
}
catch (Exception e)
{
if (connectionClosed)
{
Log.Info("Connection closed gracefully.");
return;
}
Log.Exception(e);
}
#if UNITY_WEBGL && !UNITY_EDITOR
}
_ = Function();
#else
});
#endif
}
}
private void ApplyUpdate(IEventContext eventContext, ParsedDatabaseUpdate dbOps)
{
// First trigger OnBeforeDelete
foreach (var (table, update) in dbOps.Updates)
{
table.PreApply(eventContext, update);
}
foreach (var (table, update) in dbOps.Updates)
{
table.Apply(eventContext, update);
}
foreach (var (table, _) in dbOps.Updates)
{
table.PostApply(eventContext);
}
}
protected abstract bool Dispatch(IReducerEventContext context, Reducer reducer);
private void ApplyMessage(ParsedMessage parsed)
{
var message = parsed.message;
var dbOps = parsed.dbOps;
var timestamp = parsed.receiveTimestamp;
stats.ApplyMessageQueueTracker.FinishTrackingRequest(parsed.applyQueueTrackerId);
var applyStart = DateTime.UtcNow;
switch (message)
{
case ServerMessage.InitialSubscription(var initialSubscription):
{
var eventContext = MakeSubscriptionEventContext();
var legacyEventContext = ToEventContext(new Event<Reducer>.SubscribeApplied());
ApplyUpdate(legacyEventContext, dbOps);
if (legacySubscriptions.TryGetValue(initialSubscription.RequestId, out var subscription))
{
try
{
subscription.OnApplied(eventContext, new SubscriptionAppliedType.LegacyActive(new()));
}
catch (Exception e)
{
Log.Exception(e);
}
}
break;
}
case ServerMessage.SubscribeApplied(var subscribeApplied):
Log.Warn($"Unexpected SubscribeApplied (we only expect to get SubscribeMultiApplied): {subscribeApplied}");
break;
case ServerMessage.SubscribeMultiApplied(var subscribeMultiApplied):
{
var eventContext = MakeSubscriptionEventContext();
var legacyEventContext = ToEventContext(new Event<Reducer>.SubscribeApplied());
ApplyUpdate(legacyEventContext, dbOps);
if (subscriptions.TryGetValue(subscribeMultiApplied.QueryId.Id, out var subscription))
{
try
{
subscription.OnApplied(eventContext, new SubscriptionAppliedType.Active(subscribeMultiApplied.QueryId));
}
catch (Exception e)
{
Log.Exception(e);
}
}
break;
}
case ServerMessage.SubscriptionError(var subscriptionError):
{
Log.Warn($"Subscription Error: ${subscriptionError.Error}");
// TODO: should I use a more specific exception type here?
var exception = new Exception(subscriptionError.Error);
var eventContext = ToErrorContext(exception);
var legacyEventContext = ToEventContext(new Event<Reducer>.SubscribeError(exception));
ApplyUpdate(legacyEventContext, dbOps);
if (subscriptionError.QueryId.HasValue)
{
if (subscriptions.TryGetValue(subscriptionError.QueryId.Value, out var subscription))
{
try
{
subscription.OnError(eventContext);
}
catch (Exception e)
{
Log.Exception(e);
}
}
}
else
{
Log.Warn("Received general subscription failure, disconnecting.");
Disconnect();
}
break;
}
case ServerMessage.UnsubscribeApplied(var unsubscribeApplied):
Log.Warn($"Unexpected UnsubscribeApplied (we only expect to get UnsubscribeMultiApplied): {unsubscribeApplied}");
break;
case ServerMessage.UnsubscribeMultiApplied(var unsubscribeMultiApplied):
{
var eventContext = MakeSubscriptionEventContext();
var legacyEventContext = ToEventContext(new Event<Reducer>.UnsubscribeApplied());
ApplyUpdate(legacyEventContext, dbOps);
if (subscriptions.TryGetValue(unsubscribeMultiApplied.QueryId.Id, out var subscription))
{
try
{
subscription.OnEnded(eventContext);
}
catch (Exception e)
{
Log.Exception(e);
}
}
}
break;
case ServerMessage.TransactionUpdateLight(var update):
{
var eventContext = ToEventContext(new Event<Reducer>.UnknownTransaction());
ApplyUpdate(eventContext, dbOps);
break;
}
case ServerMessage.TransactionUpdate(var transactionUpdate):
{
if (parsed.reducerEvent is { } reducerEvent)
{
var legacyEventContext = ToEventContext(new Event<Reducer>.Reducer(reducerEvent));
ApplyUpdate(legacyEventContext, dbOps);
var eventContext = ToReducerEventContext(reducerEvent);
Dispatch(eventContext, reducerEvent.Reducer);
// don't invoke OnUnhandledReducerError, that's [Obsolete].
}
else
{
var legacyEventContext = ToEventContext(new Event<Reducer>.UnknownTransaction());
ApplyUpdate(legacyEventContext, dbOps);
}
break;
}
case ServerMessage.IdentityToken(var identityToken):
try
{
Identity = identityToken.Identity;
onConnect?.Invoke(identityToken.Identity, identityToken.Token);
}
catch (Exception e)
{
Log.Exception(e);
}
break;
case ServerMessage.OneOffQueryResponse:
/* OneOffQuery is async and handles its own responses */
break;
default:
throw new InvalidOperationException();
}
stats.ApplyMessageTracker.InsertRequest(applyStart, TrackerMetadataForMessage(message));
}
// Note: this method is called from unit tests.
internal void OnMessageReceived(byte[] bytes, DateTime timestamp)
{
_parseQueue.Add(new UnparsedMessage { bytes = bytes, timestamp = timestamp, parseQueueTrackerId = stats.ParseMessageQueueTracker.StartTrackingRequest() });
}
// TODO: this should become [Obsolete] but for now is used by autogenerated code.
void IDbConnection.InternalCallReducer<T>(T args, CallReducerFlags flags)
{
if (!webSocket.IsConnected)
{
Log.Error("Cannot call reducer, not connected to server!");
return;
}
webSocket.Send(new ClientMessage.CallReducer(new CallReducer(
args.ReducerName,
IStructuralReadWrite.ToBytes(args).ToList(),
stats.ReducerRequestTracker.StartTrackingRequest(args.ReducerName),
(byte)flags
)));
}
void IDbConnection.LegacySubscribe(ISubscriptionHandle handle, string[] querySqls)
{
if (!webSocket.IsConnected)
{
Log.Error("Cannot subscribe, not connected to server!");
return;
}
var id = stats.SubscriptionRequestTracker.StartTrackingRequest();
legacySubscriptions[id] = handle;
webSocket.Send(new ClientMessage.Subscribe(
new Subscribe
{
RequestId = id,
QueryStrings = querySqls.ToList()
}
));
}
QueryId? IDbConnection.Subscribe(ISubscriptionHandle handle, string[] querySqls)
{
if (!webSocket.IsConnected)
{
Log.Error("Cannot subscribe, not connected to server!");
return null;
}
var id = stats.SubscriptionRequestTracker.StartTrackingRequest();
// We use a distinct ID from the request ID as a sanity check that we're not
// casting request IDs to query IDs anywhere in the new code path.
var queryId = queryIdAllocator.Next();
subscriptions[queryId] = handle;
webSocket.Send(new ClientMessage.SubscribeMulti(
new SubscribeMulti
{
RequestId = id,
QueryStrings = querySqls.ToList(),
QueryId = new QueryId(queryId),
}
));
return new QueryId(queryId);
}
/// Usage: SpacetimeDBClientBase.instance.OneOffQuery<Message>("SELECT * FROM table WHERE sender = \"bob\"");
[Obsolete("This is replaced by ctx.Db.TableName.RemoteQuery(\"WHERE ...\")", false)]
public Task<T[]> OneOffQuery<T>(string query) where T : IStructuralReadWrite, new() =>
((IDbConnection)this).RemoteQuery<T>(query);
async Task<T[]> IDbConnection.RemoteQuery<T>(string query)
{
var messageId = Guid.NewGuid();
var resultSource = new TaskCompletionSource<OneOffQueryResponse>();
waitingOneOffQueries[messageId] = resultSource;
// unsanitized here, but writes will be prevented serverside.
// the best they can do is send multiple selects, which will just result in them getting no data back.
var requestId = stats.OneOffRequestTracker.StartTrackingRequest();
webSocket.Send(new ClientMessage.OneOffQuery(new OneOffQuery
{
MessageId = messageId.ToByteArray().ToList(),
QueryString = query,
}));
// Suspend for an arbitrary amount of time
var result = await resultSource.Task;
if (!stats.OneOffRequestTracker.FinishTrackingRequest(requestId))
{
Log.Warn($"Failed to finish tracking one off request: {requestId}");
}
T[] LogAndThrow(string error)
{
error = $"While processing one-off-query `{query}`, ID {messageId}: {error}";
Log.Error(error);
throw new Exception(error);
}
// The server got back to us
if (result.Error != null && result.Error != "")
{
return LogAndThrow($"Server error: {result.Error}");
}
if (result.Tables.Count != 1)
{
return LogAndThrow($"Expected a single table, but got {result.Tables.Count}");
}
var resultTable = result.Tables[0];
var cacheTable = Db.GetTable(resultTable.TableName);
if (cacheTable?.ClientTableType != typeof(T))
{
return LogAndThrow($"Mismatched result type, expected {typeof(T)} but got {resultTable.TableName}");
}
var (resultReader, resultCount) = CompressionHelpers.ParseRowList(resultTable.Rows);
var output = new T[resultCount];
for (int i = 0; i < resultCount; i++)
{
output[i] = IStructuralReadWrite.Read<T>(resultReader);
}
return output;
}
public bool IsActive => webSocket.IsConnected;
public void FrameTick()
{
webSocket.Update();
while (_applyQueue.TryTake(out var parsedMessage))
{
ApplyMessage(parsedMessage);
}
}
void IDbConnection.Unsubscribe(QueryId queryId)
{
if (!subscriptions.ContainsKey(queryId.Id))
{
Log.Warn($"Unsubscribing from a subscription that the DbConnection does not know about, with QueryId {queryId.Id}");
}
var requestId = stats.SubscriptionRequestTracker.StartTrackingRequest();
webSocket.Send(new ClientMessage.UnsubscribeMulti(new()
{
RequestId = requestId,
QueryId = queryId
}));
}
void IDbConnection.AddOnConnect(Action<Identity, string> cb) => onConnect += cb;
void IDbConnection.AddOnConnectError(WebSocket.ConnectErrorEventHandler cb) => webSocket.OnConnectError += cb;
void IDbConnection.AddOnDisconnect(WebSocket.CloseEventHandler cb) => webSocket.OnClose += cb;
}
/// <summary>
/// Represents the result of parsing a database update message from SpacetimeDB.
/// Contains updates for all tables affected by the update, with each entry mapping a table handle
/// to its respective set of row changes (by primary key or row instance).
///
/// Note: Due to C#'s struct constructor limitations, you must use <see cref="ParsedDatabaseUpdate.New"/>
/// to create new instances.
/// Do not use the default constructor, as it will not initialize the Updates dictionary.
/// </summary>
internal struct ParsedDatabaseUpdate
{
// Map: table handles -> (primary key -> IStructuralReadWrite).
// If a particular table has no primary key, the "primary key" is just the row itself.
// This is valid because any [SpacetimeDB.Type] automatically has a correct Equals and HashSet implementation.
public Dictionary<IRemoteTableHandle, IParsedTableUpdate> Updates;
// Can't override the default constructor. Make sure you use this one!
public static ParsedDatabaseUpdate New()
{
ParsedDatabaseUpdate result;
result.Updates = new();
return result;
}
/// <summary>
/// Returns the <see cref="IParsedTableUpdate"/> for the specified table.
/// If no update exists for the table, a new one is allocated and added to the Updates dictionary.
/// </summary>
public IParsedTableUpdate UpdateForTable(IRemoteTableHandle table)
{
if (!Updates.TryGetValue(table, out var delta))
{
delta = table.MakeParsedTableUpdate();
Updates[table] = delta;
}
return delta;
}
}
internal struct UintAllocator
{
private uint lastAllocated;
/// <summary>
/// Allocate a new ID in a thread-unsafe way.
/// </summary>
/// <returns>A previously-unused ID.</returns>
public uint Next()
{
lastAllocated++;
return lastAllocated;
}
}
}