forked from rocicorp/mono
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzero.ts
More file actions
1544 lines (1363 loc) · 46.6 KB
/
zero.ts
File metadata and controls
1544 lines (1363 loc) · 46.6 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
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {LogContext, LogLevel} from '@rocicorp/logger';
import {Resolver, resolver} from '@rocicorp/resolver';
import type {ExperimentalNoIndexDiff, MutatorDefs} from 'replicache';
import {dropDatabase} from 'replicache/src/persist/collect-idb-databases.js';
import type {Puller, PullerResultV1} from 'replicache/src/puller.js';
import type {Pusher, PusherResult} from 'replicache/src/pusher.js';
import {
ReplicacheImpl,
ReplicacheImplOptions,
} from 'replicache/src/replicache-impl.js';
import type {ReplicacheOptions} from 'replicache/src/replicache-options.js';
import type {ClientGroupID, ClientID} from 'replicache/src/sync/ids.js';
import type {PullRequestV0, PullRequestV1} from 'replicache/src/sync/pull.js';
import type {PushRequestV0, PushRequestV1} from 'replicache/src/sync/push.js';
import type {UpdateNeededReason as ReplicacheUpdateNeededReason} from 'replicache/src/types.js';
import {assert} from 'shared/src/asserts.js';
import {getDocumentVisibilityWatcher} from 'shared/src/document-visible.js';
import {getDocument} from 'shared/src/get-document.js';
import {must} from 'shared/src/must.js';
import {navigator} from 'shared/src/navigator.js';
import {sleep, sleepWithAbort} from 'shared/src/sleep.js';
import type {MaybePromise} from 'shared/src/types.js';
import * as valita from 'shared/src/valita.js';
import {
CRUDMutation,
CRUDMutationArg,
CRUD_MUTATION_NAME,
ConnectedMessage,
CustomMutation,
Downstream,
ErrorKind,
MutationType,
NullableVersion,
PingMessage,
PokeEndMessage,
PokePartMessage,
PokeStartMessage,
PushMessage,
downstreamSchema,
nullableVersionSchema,
type ErrorMessage,
} from 'zero-protocol';
import type {ChangeDesiredQueriesMessage} from 'zero-protocol/src/change-desired-queries.js';
import type {
PullRequestMessage,
PullResponseBody,
PullResponseMessage,
} from 'zero-protocol/src/pull.js';
import {ZeroContext} from './context.js';
import {Query} from 'zql/src/zql/query/query.js';
import {newQuery} from 'zql/src/zql/query/query-impl.js';
import {nanoid} from '../util/nanoid.js';
import {send} from '../util/socket.js';
import {
MakeCRUDMutate,
WithCRUD,
makeCRUDMutate,
makeCRUDMutator,
} from './crud.js';
import {shouldEnableAnalytics} from './enable-analytics.js';
import {toWSString, type HTTPString, type WSString} from './http-string.js';
import {ENTITIES_KEY_PREFIX} from './keys.js';
import {LogOptions, createLogOptions} from './log-options.js';
import {
DID_NOT_CONNECT_VALUE,
DisconnectReason,
MetricManager,
REPORT_INTERVAL_MS,
Series,
getLastConnectErrorValue,
} from './metrics.js';
import type {ZeroOptions} from './options.js';
import {QueryManager} from './query-manager.js';
import {reloadWithReason, reportReloadReason} from './reload-error-handler.js';
import {ServerError, isAuthError, isServerError} from './server-error.js';
import {getServer} from './server-option.js';
import {version} from './version.js';
import {PokeHandler} from './zero-poke-handler.js';
import {Schema} from 'zql/src/zql/query/schema.js';
import {SubscriptionsManagerImpl} from 'replicache/src/subscriptions.js';
export type SchemaDefs = {
readonly [table: string]: Schema;
};
export type NoRelations = Record<string, never>;
export type MakeEntityQueriesFromQueryDefs<SD extends SchemaDefs> = {
readonly [K in keyof SD]: Query<SD[K]>;
};
declare const TESTING: boolean;
export type TestingContext = {
puller: Puller;
pusher: Pusher;
setReload: (r: () => void) => void;
logOptions: LogOptions;
connectStart: () => number | undefined;
socketResolver: () => Resolver<WebSocket>;
connectionState: () => ConnectionState;
};
export const onSetConnectionStateSymbol = Symbol();
export const exposedToTestingSymbol = Symbol();
export const createLogOptionsSymbol = Symbol();
interface TestZero {
[exposedToTestingSymbol]?: TestingContext;
[onSetConnectionStateSymbol]?: (state: ConnectionState) => void;
[createLogOptionsSymbol]?: (options: {
consoleLogLevel: LogLevel;
server: string | null;
}) => LogOptions;
}
function asTestZero<QD extends SchemaDefs>(z: Zero<QD>): TestZero {
return z as TestZero;
}
export const enum ConnectionState {
Disconnected,
Connecting,
Connected,
}
export const RUN_LOOP_INTERVAL_MS = 5_000;
/**
* How frequently we should ping the server to keep the connection alive.
*/
export const PING_INTERVAL_MS = 5_000;
/**
* The amount of time we wait for a pong before we consider the ping timed out.
*/
export const PING_TIMEOUT_MS = 5_000;
/**
* The amount of time we wait for a pull response before we consider a pull
* request timed out.
*/
export const PULL_TIMEOUT_MS = 5_000;
export const DEFAULT_DISCONNECT_HIDDEN_DELAY_MS = 5_000;
/**
* The amount of time we wait for a connection to be established before we
* consider it timed out.
*/
export const CONNECT_TIMEOUT_MS = 10_000;
const CHECK_CONNECTIVITY_ON_ERROR_FREQUENCY = 6;
const NULL_LAST_MUTATION_ID_SENT = {clientID: '', id: -1} as const;
// When the protocol changes (pull, push, poke,...) we need to bump this.
const REFLECT_VERSION = 1;
/**
* The reason {@link onUpdateNeeded} was called.
*/
export type UpdateNeededReason =
// There is a new client group due to a new tab loading new code with
// different mutators, indexes, schema version, or format version.
// This tab cannot sync locally with this new tab until it updates to
// the new code.
| {type: 'NewClientGroup'}
// This is used when Zero tries to connect with a version that the server
// does not support
| {type: 'VersionNotSupported'};
export function serverAheadReloadReason(kind: string) {
return `Server reported that client is ahead of server (${kind}). This probably happened because the server is in development mode and restarted. Currently when this happens, the dev server loses its state and on reconnect sees the client as ahead. If you see this in other cases, it may be a bug in Zero.`;
}
function convertOnUpdateNeededReason(
reason: ReplicacheUpdateNeededReason,
): UpdateNeededReason {
return {type: reason.type};
}
const enum PingResult {
TimedOut = 0,
Success = 1,
}
// Keep in sync with packages/replicache/src/replicache-options.ts
export interface ReplicacheInternalAPI {
lastMutationID(): number;
}
const internalReplicacheImplMap = new WeakMap<object, ReplicacheImpl>();
export function getInternalReplicacheImplForTesting<
MD extends MutatorDefs,
QD extends SchemaDefs,
>(z: Zero<QD>): ReplicacheImpl<MD> {
return must(internalReplicacheImplMap.get(z)) as ReplicacheImpl<MD>;
}
export class Zero<QD extends SchemaDefs> {
readonly version = version;
readonly #rep: ReplicacheImpl<WithCRUD<MutatorDefs>>;
readonly #server: HTTPString | null;
readonly userID: string;
readonly #lc: LogContext;
readonly #logOptions: LogOptions;
readonly #enableAnalytics: boolean;
readonly #pokeHandler: PokeHandler;
readonly #queryManager: QueryManager;
#lastMutationIDSent: {clientID: string; id: number} =
NULL_LAST_MUTATION_ID_SENT;
#onPong: () => void = () => undefined;
#online = false;
/**
* `onOnlineChange` is called when the Zero instance's online status
* changes.
*/
onOnlineChange: ((online: boolean) => void) | null | undefined = null;
#onUpdateNeeded: ((reason: UpdateNeededReason) => void) | null;
readonly #jurisdiction: 'eu' | undefined;
// Last cookie used to initiate a connection
#connectCookie: NullableVersion = null;
// Total number of sockets successfully connected by this client
#connectedCount = 0;
// Number of messages received over currently connected socket. Reset
// on disconnect.
#messageCount = 0;
#connectedAt = 0;
// Reset on successful connection.
#connectErrorCount = 0;
#abortPingTimeout = () => {
// intentionally empty
};
readonly #zeroContext: ZeroContext;
/**
* `onUpdateNeeded` is called when a code update is needed.
*
* A code update can be needed because:
* - the server no longer supports the protocol version of the current code,
* - a new Zero client has created a new client group, because its code
* has different mutators, indexes, schema version and/or format version
* from this Zero client. This is likely due to the new client having
* newer code. A code update is needed to be able to locally sync with this
* new Zero client (i.e. to sync while offline, the clients can can
* still sync with each other via the server).
*
* The default behavior is to reload the page (using `location.reload()`). Set
* this to `null` or provide your own function to prevent the page from
* reloading automatically. You may want to provide your own function to
* display a toast to inform the end user there is a new version of your app
* available and prompting them to refresh.
*/
get onUpdateNeeded(): ((reason: UpdateNeededReason) => void) | null {
return this.#onUpdateNeeded;
}
set onUpdateNeeded(callback: ((reason: UpdateNeededReason) => void) | null) {
this.#onUpdateNeeded = callback;
this.#rep.onUpdateNeeded =
callback &&
(reason => {
callback(convertOnUpdateNeededReason(reason));
});
}
#connectResolver = resolver<void>();
#pendingPullsByRequestID: Map<string, Resolver<PullResponseBody>> = new Map();
#lastMutationIDReceived = 0;
#socket: WebSocket | undefined = undefined;
#socketResolver = resolver<WebSocket>();
#connectionStateChangeResolver = resolver<ConnectionState>();
/**
* This resolver is only used for rejections. It is awaited in the connected
* state (including when waiting for a pong). It is rejected when we get an
* invalid message or an 'error' message.
*/
#rejectMessageError: Resolver<never> | undefined = undefined;
#closeAbortController = new AbortController();
readonly #visibilityWatcher;
// We use an accessor pair to allow the subclass to override the setter.
#connectionState: ConnectionState = ConnectionState.Disconnected;
#setConnectionState(state: ConnectionState) {
if (state === this.#connectionState) {
return;
}
this.#connectionState = state;
this.#connectionStateChangeResolver.resolve(state);
this.#connectionStateChangeResolver = resolver();
if (TESTING) {
asTestZero(this)[onSetConnectionStateSymbol]?.(state);
}
}
#connectStart: number | undefined = undefined;
// Set on connect attempt if currently undefined.
// Reset to undefined when
// 1. client stops trying to connect because it is hidden
// 2. client encounters a connect error and canary request indicates
// the client is offline
// 2. client successfully connects
#totalToConnectStart: number | undefined = undefined;
readonly #options: ZeroOptions<QD>;
readonly query: MakeEntityQueriesFromQueryDefs<QD>;
#metrics: MetricManager;
// Store as field to allow test subclass to override. Web API doesn't allow
// overwriting location fields for security reasons.
#reload = () => location.reload();
/**
* Constructs a new Zero client.
*/
constructor(options: ZeroOptions<QD>) {
const {
userID,
onOnlineChange,
jurisdiction,
hiddenTabDisconnectDelay = DEFAULT_DISCONNECT_HIDDEN_DELAY_MS,
kvStore = 'idb',
schemas = {} as QD,
} = options;
if (!userID) {
throw new Error('ZeroOptions.userID must not be empty.');
}
const server = getServer(options.server);
this.#enableAnalytics = shouldEnableAnalytics(
server,
options.enableAnalytics,
);
if (jurisdiction !== undefined && jurisdiction !== 'eu') {
throw new Error('ZeroOptions.jurisdiction must be "eu" if present.');
}
if (hiddenTabDisconnectDelay < 0) {
throw new Error(
'ZeroOptions.hiddenTabDisconnectDelay must not be negative.',
);
}
this.onOnlineChange = onOnlineChange;
this.#options = options;
this.#logOptions = this.#createLogOptions({
consoleLogLevel: options.logLevel ?? 'error',
server: null, //server, // Reenable remote logging
enableAnalytics: this.#enableAnalytics,
});
const logOptions = this.#logOptions;
const replicacheMutators = {
['_zero_crud']: makeCRUDMutator(schemas),
};
const replicacheOptions: ReplicacheOptions<WithCRUD<MutatorDefs>> = {
schemaVersion: options.schemaVersion,
logLevel: logOptions.logLevel,
logSinks: [logOptions.logSink],
mutators: replicacheMutators,
name: `zero-${userID}`,
pusher: (req, reqID) => this.#pusher(req, reqID),
puller: (req, reqID) => this.#puller(req, reqID),
// TODO: Do we need these?
pushDelay: 0,
requestOptions: {
maxDelayMs: 0,
minDelayMs: 0,
},
licenseKey: 'zero-client-static-key',
kvStore,
};
const replicacheImplOptions: ReplicacheImplOptions = {
enableLicensing: false,
makeSubscriptionsManager: (queryInternal, lc) =>
new SubscriptionsManagerImpl(queryInternal, lc),
enableClientGroupForking: false,
};
const rep = new ReplicacheImpl(replicacheOptions, replicacheImplOptions);
this.#rep = rep;
if (TESTING) {
internalReplicacheImplMap.set(this, rep);
}
rep.getAuth = this.#getAuthToken;
this.#onUpdateNeeded = rep.onUpdateNeeded; // defaults to reload.
this.#server = server;
this.userID = userID;
this.#jurisdiction = jurisdiction;
this.#lc = new LogContext(
logOptions.logLevel,
{clientID: rep.clientID},
logOptions.logSink,
);
this.mutate = makeCRUDMutate<QD>(schemas, rep.mutate);
this.#queryManager = new QueryManager(rep.clientID, msg =>
this.#sendChangeDesiredQueries(msg),
);
this.#zeroContext = new ZeroContext(schemas, ast =>
this.#queryManager.add(ast),
);
rep.experimentalWatch(
diff => this.#zeroContext.processChanges(diff as ExperimentalNoIndexDiff),
{
prefix: ENTITIES_KEY_PREFIX,
initialValuesInFirstDiff: true,
},
);
this.query = this.#registerQueries(schemas);
reportReloadReason(this.#lc);
this.#metrics = new MetricManager({
reportIntervalMs: REPORT_INTERVAL_MS,
host: location.host,
source: 'client',
reporter: this.#enableAnalytics
? allSeries => this.#reportMetrics(allSeries)
: () => Promise.resolve(),
lc: this.#lc,
});
this.#metrics.tags.push(`version:${this.version}`);
this.#pokeHandler = new PokeHandler(
poke => this.#rep.poke(poke),
() => this.#onPokeError(),
rep.clientID,
this.#lc,
);
this.#visibilityWatcher = getDocumentVisibilityWatcher(
getDocument(),
hiddenTabDisconnectDelay,
this.#closeAbortController.signal,
);
void this.#runLoop();
if (TESTING) {
asTestZero(this)[exposedToTestingSymbol] = {
puller: this.#puller,
pusher: this.#pusher,
setReload: (r: () => void) => {
this.#reload = r;
},
logOptions: this.#logOptions,
connectStart: () => this.#connectStart,
socketResolver: () => this.#socketResolver,
connectionState: () => this.#connectionState,
};
}
}
#sendChangeDesiredQueries(msg: ChangeDesiredQueriesMessage): void {
if (this.#socket && this.#connectionState === ConnectionState.Connected) {
send(this.#socket, msg);
}
}
#createLogOptions(options: {
consoleLogLevel: LogLevel;
server: string | null;
enableAnalytics: boolean;
}): LogOptions {
if (TESTING) {
const testZero = asTestZero(this);
if (testZero[createLogOptionsSymbol]) {
return testZero[createLogOptionsSymbol](options);
}
}
return createLogOptions(options);
}
/**
* The name of the IndexedDB database in which the data of this
* instance of Zero is stored.
*/
get idbName(): string {
return this.#rep.idbName;
}
/**
* The schema version of the data understood by this application.
* See [[ZeroOptions.schemaVersion]].
*/
get schemaVersion(): string {
return this.#rep.schemaVersion;
}
/**
* The client ID for this instance of Zero. Each instance
* gets a unique client ID.
*/
get clientID(): ClientID {
return this.#rep.clientID;
}
get clientGroupID(): Promise<ClientGroupID> {
return this.#rep.clientGroupID;
}
/**
* Provides facilities to write data to Zero.
*
* `mutate` is a function as well as a "namespace" object for doing CRUD style
* mutations. When used as a function it is used to batch multiple mutations.
*
* ```ts
* await zero.mutate.issue.create({id: '1', title: 'First issue'});
* await zero.mutate.comment.create({id: '1', text: 'First comment', issueID: '1'});
*
* // or as a function:
* await zero.mutate(m => {
* await m.issue.create({id: '1', title: 'First issue'});
* await m.comment.create({id: '1', text: 'First comment', issueID: '1'});
* });
* ```
*
* The benefit of using the function form is that it allows you to batch
* multiple mutations together. This can be more efficient than making
* individual calls to `create`, `update`, `set`, and `delete`.
*
* The function form of `mutate` is not allowed to be called inside another
* `mutate` function. Doing so will throw an error.
*/
readonly mutate: MakeCRUDMutate<QD>;
/**
* Whether this Zero instance has been closed. Once a Zero instance has
* been closed it no longer syncs and you can no longer read or write data out
* of it. After it has been closed it is pretty much useless and should not be
* used any more.
*/
get closed(): boolean {
return this.#rep.closed;
}
/**
* Closes this Zero instance.
*
* When closed all subscriptions end and no more read or writes are allowed.
*/
close(): Promise<void> {
const lc = this.#lc.withContext('close');
if (this.#connectionState !== ConnectionState.Disconnected) {
this.#disconnect(lc, {
client: 'ClientClosed',
});
}
lc.debug?.('Aborting closeAbortController due to close()');
this.#closeAbortController.abort();
this.#metrics.stop();
return this.#rep.close();
}
#onMessage = (e: MessageEvent<string>) => {
const lc = this.#lc;
lc.debug?.('received message', e.data);
if (this.closed) {
lc.debug?.('ignoring message because already closed');
return;
}
const rejectInvalidMessage = (e?: unknown) =>
this.#rejectMessageError?.reject(
new Error(
`Invalid message received from server: ${
e instanceof Error ? e.message + '. ' : ''
}${data}`,
),
);
let downMessage: Downstream;
const {data} = e;
try {
downMessage = valita.parse(JSON.parse(data), downstreamSchema);
} catch (e) {
rejectInvalidMessage(e);
return;
}
this.#messageCount++;
switch (downMessage[0]) {
case 'connected':
return this.#handleConnectedMessage(lc, downMessage);
case 'error':
return this.#handleErrorMessage(lc, downMessage);
case 'pong':
return this.#onPong();
case 'pokeStart':
return this.#handlePokeStart(lc, downMessage);
case 'pokePart':
return this.#handlePokePart(lc, downMessage);
case 'pokeEnd':
return this.#handlePokeEnd(lc, downMessage);
case 'pull':
return this.#handlePullResponse(lc, downMessage);
default:
rejectInvalidMessage();
}
};
#onOpen = (e: Event) => {
const l = addWebSocketIDFromSocketToLogContext(
e.target as WebSocket,
this.#lc,
);
if (this.#connectStart === undefined) {
l.error?.(
'Got open event but connect start time is undefined. This should not happen.',
);
} else {
const now = Date.now();
const timeToOpenMs = now - this.#connectStart;
l.info?.('Got socket open event', {
navigatorOnline: navigator?.onLine,
timeToOpenMs,
});
}
};
#onClose = (e: CloseEvent) => {
const l = addWebSocketIDFromSocketToLogContext(
e.target as WebSocket,
this.#lc,
);
const {code, reason, wasClean} = e;
l.info?.('Got socket close event', {code, reason, wasClean});
const closeKind = wasClean ? 'CleanClose' : 'AbruptClose';
this.#connectResolver.reject(new CloseError(closeKind));
this.#disconnect(l, {client: closeKind});
};
// An error on the connection is fatal for the connection.
async #handleErrorMessage(
lc: LogContext,
downMessage: ErrorMessage,
): Promise<void> {
const [, kind, message] = downMessage;
if (kind === ErrorKind.VersionNotSupported) {
this.onUpdateNeeded?.({type: kind});
}
if (
kind === 'InvalidConnectionRequestLastMutationID' ||
kind === 'InvalidConnectionRequestBaseCookie'
) {
await dropDatabase(this.#rep.idbName);
reloadWithReason(lc, this.#reload, serverAheadReloadReason(kind));
}
const error = new ServerError(kind, message);
lc.info?.(`${kind}: ${message}}`);
this.#rejectMessageError?.reject(error);
lc.debug?.('Rejecting connect resolver due to error', error);
this.#connectResolver.reject(error);
this.#disconnect(lc, {server: kind});
}
async #handleConnectedMessage(
lc: LogContext,
connectedMessage: ConnectedMessage,
) {
const now = Date.now();
const [, connectBody] = connectedMessage;
lc = addWebSocketIDToLogContext(connectBody.wsid, lc);
if (this.#connectedCount === 0) {
this.#checkConnectivity('firstConnect');
} else if (this.#connectErrorCount > 0) {
this.#checkConnectivity('connectAfterError');
}
this.#connectedCount++;
this.#connectedAt = now;
this.#metrics.lastConnectError.clear();
const proceedingConnectErrorCount = this.#connectErrorCount;
this.#connectErrorCount = 0;
let timeToConnectMs = undefined;
let connectMsgLatencyMs = undefined;
if (this.#connectStart === undefined) {
lc.error?.(
'Got connected message but connect start time is undefined. This should not happen.',
);
} else {
timeToConnectMs = now - this.#connectStart;
this.#metrics.timeToConnectMs.set(timeToConnectMs);
connectMsgLatencyMs =
connectBody.timestamp !== undefined
? now - connectBody.timestamp
: undefined;
this.#connectStart = undefined;
}
let totalTimeToConnectMs = undefined;
if (this.#totalToConnectStart === undefined) {
lc.error?.(
'Got connected message but total to connect start time is undefined. This should not happen.',
);
} else {
totalTimeToConnectMs = now - this.#totalToConnectStart;
this.#totalToConnectStart = undefined;
}
this.#metrics.setConnected(timeToConnectMs ?? 0, totalTimeToConnectMs ?? 0);
lc.info?.('Connected', {
navigatorOnline: navigator?.onLine,
timeToConnectMs,
totalTimeToConnectMs,
connectMsgLatencyMs,
connectedCount: this.#connectedCount,
proceedingConnectErrorCount,
});
this.#lastMutationIDSent = NULL_LAST_MUTATION_ID_SENT;
lc.debug?.('Resolving connect resolver');
const queriesPatch = await this.#rep.query(tx =>
this.#queryManager.getQueriesPatch(tx),
);
assert(this.#socket);
send(this.#socket, [
'initConnection',
{
desiredQueriesPatch: queriesPatch,
},
]);
this.#setConnectionState(ConnectionState.Connected);
this.#connectResolver.resolve();
}
/**
* Starts a new connection. This will create the WebSocket that does the HTTP
* request to the server.
*
* {@link #connect} will throw an assertion error if the
* {@link #connectionState} is not {@link ConnectionState.Disconnected}.
* Callers MUST check the connection state before calling this method and log
* an error as needed.
*
* The function will resolve once the socket is connected. If you need to know
* when a connection has been established, as in we have received the
* {@link ConnectedMessage}, you should await the {@link #connectResolver}
* promise. The {@link #connectResolver} promise rejects if an error message
* is received before the connected message is received or if the connection
* attempt times out.
*/
async #connect(l: LogContext): Promise<void> {
assert(this.#server);
// All the callers check this state already.
assert(this.#connectionState === ConnectionState.Disconnected);
const wsid = nanoid();
l = addWebSocketIDToLogContext(wsid, l);
l.info?.('Connecting...', {navigatorOnline: navigator?.onLine});
this.#setConnectionState(ConnectionState.Connecting);
// connect() called but connect start time is defined. This should not
// happen.
assert(this.#connectStart === undefined);
const now = Date.now();
this.#connectStart = now;
if (this.#totalToConnectStart === undefined) {
this.#totalToConnectStart = now;
}
if (this.closed) {
return;
}
this.#connectCookie = valita.parse(
await this.#rep.cookie,
nullableVersionSchema,
);
if (this.closed) {
return;
}
// Reject connect after a timeout.
const timeoutID = setTimeout(() => {
l.debug?.('Rejecting connect resolver due to timeout');
this.#connectResolver.reject(new TimedOutError('Connect'));
this.#disconnect(l, {
client: 'ConnectTimeout',
});
}, CONNECT_TIMEOUT_MS);
const abortHandler = () => {
clearTimeout(timeoutID);
};
this.#closeAbortController.signal.addEventListener('abort', abortHandler);
const ws = createSocket(
toWSString(this.#server),
this.#connectCookie,
this.clientID,
await this.clientGroupID,
this.userID,
this.#rep.auth,
this.#jurisdiction,
this.#lastMutationIDReceived,
wsid,
this.#options.logLevel === 'debug',
l,
);
if (this.closed) {
return;
}
ws.addEventListener('message', this.#onMessage);
ws.addEventListener('open', this.#onOpen);
ws.addEventListener('close', this.#onClose);
this.#socket = ws;
this.#socketResolver.resolve(ws);
try {
l.debug?.('Waiting for connection to be acknowledged');
await this.#connectResolver.promise;
} finally {
clearTimeout(timeoutID);
this.#closeAbortController.signal.removeEventListener(
'abort',
abortHandler,
);
}
}
#disconnect(l: LogContext, reason: DisconnectReason): void {
if (this.#connectionState === ConnectionState.Connecting) {
this.#connectErrorCount++;
}
l.info?.('disconnecting', {
navigatorOnline: navigator?.onLine,
reason,
connectStart: this.#connectStart,
totalToConnectStart: this.#totalToConnectStart,
connectedAt: this.#connectedAt,
connectionDuration: this.#connectedAt
? Date.now() - this.#connectedAt
: 0,
messageCount: this.#messageCount,
connectionState: this.#connectionState,
connectErrorCount: this.#connectErrorCount,
});
switch (this.#connectionState) {
case ConnectionState.Connected: {
if (this.#connectStart !== undefined) {
l.error?.(
'disconnect() called while connected but connect start time is defined. This should not happen.',
);
// this._connectStart reset below.
}
break;
}
case ConnectionState.Connecting: {
this.#metrics.lastConnectError.set(getLastConnectErrorValue(reason));
this.#metrics.timeToConnectMs.set(DID_NOT_CONNECT_VALUE);
this.#metrics.setConnectError(reason);
if (
this.#connectErrorCount % CHECK_CONNECTIVITY_ON_ERROR_FREQUENCY ===
1
) {
this.#checkConnectivity(
`connectErrorCount=${this.#connectErrorCount}`,
);
}
// this._connectStart reset below.
if (this.#connectStart === undefined) {
l.error?.(
'disconnect() called while connecting but connect start time is undefined. This should not happen.',
);
}
break;
}
case ConnectionState.Disconnected:
l.error?.('disconnect() called while disconnected');
break;
}
this.#socketResolver = resolver();
l.debug?.('Creating new connect resolver');
this.#connectResolver = resolver();
this.#setConnectionState(ConnectionState.Disconnected);
this.#messageCount = 0;
this.#connectStart = undefined; // don't reset this._totalToConnectStart
this.#connectedAt = 0;
this.#socket?.removeEventListener('message', this.#onMessage);
this.#socket?.removeEventListener('open', this.#onOpen);
this.#socket?.removeEventListener('close', this.#onClose);
this.#socket?.close();
this.#socket = undefined;
this.#lastMutationIDSent = NULL_LAST_MUTATION_ID_SENT;
this.#pokeHandler.handleDisconnect();
}
async #handlePokeStart(_lc: LogContext, pokeMessage: PokeStartMessage) {
this.#abortPingTimeout();
await this.#pokeHandler.handlePokeStart(pokeMessage[1]);
}
async #handlePokePart(_lc: LogContext, pokeMessage: PokePartMessage) {
this.#abortPingTimeout();
const lastMutationIDChangeForSelf = await this.#pokeHandler.handlePokePart(
pokeMessage[1],
);
if (lastMutationIDChangeForSelf !== undefined) {
this.#lastMutationIDReceived = lastMutationIDChangeForSelf;
}
}
async #handlePokeEnd(_lc: LogContext, pokeMessage: PokeEndMessage) {
this.#abortPingTimeout();
await this.#pokeHandler.handlePokeEnd(pokeMessage[1]);
}
#onPokeError() {
const lc = this.#lc;
lc.info?.(
'poke error, disconnecting?',
this.#connectionState !== ConnectionState.Disconnected,
);
// It is theoretically possible that we get disconnected during the
// async poke above. Only disconnect if we are not already
// disconnected.
if (this.#connectionState !== ConnectionState.Disconnected) {
this.#disconnect(lc, {
client: 'UnexpectedBaseCookie',
});
}
}
#handlePullResponse(
lc: LogContext,
pullResponseMessage: PullResponseMessage,
) {
this.#abortPingTimeout();
const body = pullResponseMessage[1];
lc = lc.withContext('requestID', body.requestID);
lc.debug?.('Handling pull response', body);
const resolver = this.#pendingPullsByRequestID.get(body.requestID);
if (!resolver) {
// This can happen because resolvers are deleted
// from this._pendingPullsByRequestID when pulls timeout.
lc.debug?.('No resolver found');
return;
}
resolver.resolve(pullResponseMessage[1]);
}
async #pusher(
req: PushRequestV0 | PushRequestV1,
requestID: string,
): Promise<PusherResult> {
// The deprecation of pushVersion 0 predates zero-client
assert(req.pushVersion === 1);
// If we are connecting we wait until we are connected.