forked from rocicorp/replicache
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreplicache.ts
More file actions
597 lines (538 loc) · 16.4 KB
/
Copy pathreplicache.ts
File metadata and controls
597 lines (538 loc) · 16.4 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
import type {JSONValue, ToJSON} from './json.js';
import type {ScanOptions} from './scan-options.js';
import type {DatabaseInfo} from './database-info.js';
import type {
REPMInvoke,
Invoke,
OpenTransactionRequest,
} from './repm-invoker.js';
import {ReadTransactionImpl, WriteTransactionImpl} from './transactions.js';
import {ScanResult} from './scan-iterator.js';
import type {ReadTransaction, WriteTransaction} from './transactions.js';
export type Mutator<Return extends JSONValue | void, Args extends JSONValue> = (
args: Args,
) => Promise<Return | void>;
type MutatorImpl<Return extends JSONValue | void, Args extends JSONValue> = (
tx: WriteTransaction,
args: Args,
) => Promise<Return>;
type BeginSyncResult = {
syncID: string;
syncHead: string;
};
export const httpStatusUnauthorized = 401;
type MaybePromise<T> = T | Promise<T>;
export default class Replicache implements ReadTransaction {
private readonly _batchURL: string;
private _dataLayerAuth: string;
private readonly _diffServerAuth: string;
private readonly _diffServerURL: string;
private readonly _name: string;
private readonly _repmInvoke: REPMInvoke;
private _closed = false;
private _online = true;
protected _opened: Promise<unknown> | null = null;
private _root: Promise<string | undefined> = Promise.resolve(undefined);
private readonly _mutatorRegistry = new Map<
string,
MutatorImpl<JSONValue, JSONValue>
>();
private _syncPromise: Promise<void> | null = null;
private readonly _subscriptions = new Set<Subscription<unknown, unknown>>();
protected _syncInterval: number | null = 60_000;
// NodeJS has a non standard setTimeout function :'(
protected _timerId: ReturnType<typeof setTimeout> | 0 = 0;
onSync: ((syncing: boolean) => void) | null = null;
/**
* This gets called when we get an HTTP unauthorized from the client view or
* the batch endpoint. Set this to a function that will ask your user to
* reauthenticate.
*/
getDataLayerAuth:
| (() => MaybePromise<string | null | undefined>)
| null
| undefined = null;
constructor({
batchURL = '',
dataLayerAuth = '',
diffServerAuth = '',
diffServerURL,
name = 'default',
repmInvoke,
}: {
batchURL?: string;
dataLayerAuth?: string;
diffServerAuth?: string;
diffServerURL: string;
name?: string;
repmInvoke: REPMInvoke;
}) {
this._batchURL = batchURL;
this._dataLayerAuth = dataLayerAuth;
this._diffServerAuth = diffServerAuth;
this._diffServerURL = diffServerURL;
this._name = name;
this._repmInvoke = repmInvoke;
this._open();
}
/**
* Lists information about available local databases.
*/
static async list({
repmInvoke,
}: {
repmInvoke: REPMInvoke;
}): Promise<DatabaseInfo[]> {
const res = await repmInvoke('', 'list');
return res.databases;
}
private async _open(): Promise<void> {
this._opened = this._repmInvoke(this._name, 'open');
this._root = this._getRoot();
await this._root;
if (this._syncInterval !== null) {
await this.sync();
}
}
/**
* Completely delete a local database. Remote replicas in the group aren't affected.
*/
static async drop(
name: string,
{repmInvoke}: {repmInvoke: REPMInvoke},
): Promise<void> {
await repmInvoke(name, 'drop');
}
get online(): boolean {
return this._online;
}
get closed(): boolean {
return this._closed;
}
/**
* The duration between each `sync`. Set this to `null` to prevent syncing in
* the background.
*/
get syncInterval(): number | null {
return this._syncInterval;
}
set syncInterval(duration: number | null) {
if (this._timerId !== 0) {
clearTimeout(this._timerId);
this._timerId = 0;
}
this._syncInterval = duration;
this._scheduleSync();
}
private _scheduleSync(): void {
if (this._syncInterval !== null) {
this._timerId = setTimeout(() => this.sync(), this._syncInterval);
}
}
async close(): Promise<void> {
this._closed = true;
const p = this._invoke('close');
// Clear timer
// Clear subscriptions
for (const subscription of this._subscriptions) {
subscription.onDone?.();
}
this._subscriptions.clear();
await p;
}
private async _getRoot(): Promise<string | undefined> {
if (this._closed) {
return undefined;
}
const res = await this._invoke('getRoot');
return res.root;
}
private async _checkChange(root: string | undefined): Promise<void> {
const currentRoot = await this._root; // instantaneous except maybe first time
if (root !== undefined && root !== currentRoot) {
this._root = Promise.resolve(root);
await this._fireOnChange();
}
}
private _invoke: Invoke = async (
rpc: string,
args?: JSONValue | ToJSON,
): Promise<JSONValue> => {
await this._opened;
return await this._repmInvoke(this._name, rpc, args);
};
/** Get a single value from the database. */
get(key: string): Promise<JSONValue | undefined> {
return this.query(tx => tx.get(key));
}
/** Determines if a single key is present in the database. */
has(key: string): Promise<boolean> {
return this.query(tx => tx.has(key));
}
/**
* Gets many values from the database. This returns a `ScanResult` which
* implements `AsyncIterable`. It also has methods to iterate over the `keys`
* and `entries`.
* */
scan({prefix = '', start}: ScanOptions = {}): ScanResult {
let tx: ReadTransactionImpl;
return new ScanResult(
prefix,
start,
this._invoke,
async () => {
if (tx) {
return tx;
}
tx = new ReadTransactionImpl(this._invoke);
await tx.open({});
return tx;
},
true,
);
}
private async _sync(): Promise<void> {
try {
const beginSyncResult = await this._beginSync();
if (beginSyncResult.syncHead !== '00000000000000000000000000000000') {
await this._maybeEndSync(beginSyncResult);
}
this._online = true;
} catch (e) {
// We purposely don't rethrow here because a common case is that an
// exception is from beginSync() and we are offline. We don't want such
// cases to look so exceptional in the console output.
//
// TODO: we can rethrow here once replicache-internal is improved to not
// treat offlineness as an error.
console.info(`Error: ${e}`);
this._online = false;
}
}
protected async _beginSync(): Promise<BeginSyncResult> {
const beginSyncResult = await this._invoke('beginSync', {
batchPushURL: this._batchURL,
diffServerURL: this._diffServerURL,
dataLayerAuth: this._dataLayerAuth,
diffServerAuth: this._diffServerAuth,
});
const {syncInfo} = beginSyncResult;
let reauth = false;
function checkStatus(
data: {httpStatusCode?: number; errorMessage?: string},
serverName: string,
) {
const {httpStatusCode, errorMessage} = data;
if (errorMessage !== '') {
console.error(
`Got error response from ${serverName} server: ${httpStatusCode}: ${errorMessage}`,
);
}
if (httpStatusCode === httpStatusUnauthorized) {
reauth = true;
}
}
const {batchPushInfo} = syncInfo;
if (batchPushInfo) {
checkStatus(batchPushInfo, 'batch');
const mutationInfos = batchPushInfo.batchPushResponse.mutationInfos;
if (mutationInfos != null) {
for (const mutationInfo of mutationInfos) {
console.error(
`MutationInfo: ID: ${mutationInfo.id}, Error: ${mutationInfo.error}`,
);
}
}
}
checkStatus(syncInfo.clientViewInfo, 'client view');
if (reauth && this.getDataLayerAuth) {
const dataLayerAuth = await this.getDataLayerAuth();
if (dataLayerAuth != null) {
this._dataLayerAuth = dataLayerAuth;
// Try again now instead of waiting for another 5 seconds.
return await this._beginSync();
}
}
const syncHead = beginSyncResult.syncHead;
const {syncID} = syncInfo;
return {syncID, syncHead};
}
protected async _maybeEndSync(
beginSyncResult: BeginSyncResult,
): Promise<void> {
if (this._closed) {
return;
}
let {syncHead} = beginSyncResult;
const {replayMutations} = await this._invoke(
'maybeEndSync',
beginSyncResult,
);
if (!replayMutations || replayMutations.length === 0) {
// All done.
await this._checkChange(syncHead);
return;
}
// Replay.
for (const mutation of replayMutations) {
const {original} = mutation;
syncHead = await this._replay(
syncHead,
original,
mutation.name,
mutation.args,
);
}
const {syncID} = beginSyncResult;
await this._maybeEndSync({syncID, syncHead});
}
private async _replay<A extends JSONValue>(
basis: string,
original: string,
name: string,
args: A,
): Promise<string> {
const mutatorImpl = this._mutatorRegistry.get(name);
if (!mutatorImpl) {
console.error(`Unknown mutator ${name}`);
return basis;
}
const res = await this._mutate(name, mutatorImpl, args, {
invokeArgs: {
rebaseOpts: {basis, original},
},
shouldCheckChange: false,
});
return res.ref;
}
/**
* Synchronizes this cache with the server. New local mutations are sent to
* the server, and the latest server state is applied to the cache. Any local
* mutations not included in the new server state are replayed. See the
* Replicache design document for more information on sync:
* https://github.com/rocicorp/replicache/blob/master/design.md
*/
async sync(): Promise<void> {
if (this._closed) {
return;
}
if (this._syncPromise !== null) {
await this._syncPromise;
await this.sync();
return;
}
if (this._timerId !== 0) {
clearTimeout(this._timerId);
this._timerId = 0;
}
this._fireOnSync(true);
try {
this._syncPromise = this._sync();
await this._syncPromise;
} finally {
this._syncPromise = null;
this._fireOnSync(false);
this._scheduleSync();
}
}
private _fireOnSync(syncing: boolean): void {
queueMicrotask(() => this.onSync?.(syncing));
}
private async _fireOnChange(): Promise<void> {
const subscriptions = [...this._subscriptions];
const results = await this.query(async tx => {
const promises = subscriptions.map(async s => {
// Tag the result so we can deal with success vs error below.
try {
return {ok: true, value: await s.body(tx)};
} catch (ex) {
return {ok: false, error: ex};
}
});
return await Promise.all(promises);
});
for (let i = 0; i < subscriptions.length; i++) {
const result = results[i];
if (result.ok) {
subscriptions[i].onData(result.value);
} else {
subscriptions[i].onError?.(result.error);
}
}
}
/**
* Subcribe to changes to the underlying data. Every time the underlying data
* changes `onData` is called. The function is also called once the first time
* the subscription is added. There is currently no guarantee that the result
* of this subscription changes and it might get called with the same value
* over and over.
*
* This returns a function that can be used to cancel the subscription.
*
* If an error occurs in the `body` the `onError` function is called if
* present.
*/
subscribe<R, E>(
body: (tx: ReadTransaction) => Promise<R>,
{
onData,
onError,
onDone,
}: {
onData: (result: R) => void;
onError?: (error: E) => void;
onDone?: () => void;
},
): () => void {
const s = {body, onData, onError, onDone} as Subscription<unknown, unknown>;
this._subscriptions.add(s);
(async () => {
try {
const res = await this.query(s.body);
s.onData(res);
} catch (ex) {
s.onError?.(ex);
}
})();
return (): void => {
this._subscriptions.delete(s);
};
}
/**
* Query is used for read transactions. It is recommended to use transactions
* to ensure you get a consistent view across multiple calls to `get`, `has`
* and `scan`.
*/
async query<R>(body: (tx: ReadTransaction) => Promise<R> | R): Promise<R> {
const tx = new ReadTransactionImpl(this._invoke);
await tx.open({});
try {
return await body(tx);
} finally {
// No need to await the response.
tx.close();
}
}
/**
* Registers a *mutator*, which is used to make changes to the data.
*
* ## Replays
*
* Mutators run once when they are initially invoked, but they might also be
* *replayed* multiple times during sync. As such mutators should not modify
* application state directly. Also, it is important that the set of
* registered mutator names only grows over time. If Replicache syncs and
* needed mutator is not registered, it will substitute a no-op mutator, but
* this might be a poor user experience.
*
* ## Server application
*
* During sync, a description of each mutation is sent to the server's [batch
* endpoint](https://github.com/rocicorp/replicache/blob/master/README.md#step-5-upstream-sync)
* where it is applied. Once the mutation has been applied successfully, as
* indicated by the [client
* view](https://github.com/rocicorp/replicache/blob/master/README.md#step-2-downstream-sync)'s
* `lastMutationId` field, the local version of the mutation is removed. See
* the [design
* doc](https://github.com/rocicorp/replicache/blob/master/design.md) for
* additional details on the sync protocol.
*
* ## Transactionality
*
* Mutators are atomic: all their changes are applied together, or none are.
* Throwing an exception aborts the transaction. Otherwise, it is committed.
* As with [query] and [subscribe] all reads will see a consistent view of
* the cache while they run.
*/
register<Return extends JSONValue | void, Args extends JSONValue>(
name: string,
mutatorImpl: MutatorImpl<Return, Args>,
): Mutator<Return, Args> {
this._mutatorRegistry.set(
name,
(mutatorImpl as unknown) as MutatorImpl<JSONValue, JSONValue>,
);
return async (args: Args): Promise<Return> =>
(await this._mutate(name, mutatorImpl, args, {shouldCheckChange: true}))
.result;
}
private async _mutate<R extends JSONValue | void, A extends JSONValue>(
name: string,
mutatorImpl: MutatorImpl<R, A>,
args: A,
{
invokeArgs,
shouldCheckChange,
}: {invokeArgs?: OpenTransactionRequest; shouldCheckChange: boolean},
): Promise<{result: R; ref: string}> {
let actualInvokeArgs: OpenTransactionRequest = {args, name};
if (invokeArgs !== undefined) {
actualInvokeArgs = {...actualInvokeArgs, ...invokeArgs};
}
let result: R;
const tx = new WriteTransactionImpl(this._invoke);
await tx.open(actualInvokeArgs);
try {
result = await mutatorImpl(tx, args);
} catch (ex) {
// No need to await the response.
tx.close();
throw ex;
}
const commitRes = await tx.commit();
if (commitRes.retryCommit) {
return await this._mutate(name, mutatorImpl, args, {
invokeArgs,
shouldCheckChange,
});
}
const {ref} = commitRes;
if (shouldCheckChange) {
await this._checkChange(ref);
}
return {result, ref};
}
}
export class ReplicacheTest extends Replicache {
static async new({
batchURL,
dataLayerAuth,
diffServerAuth,
diffServerURL,
name = '',
repmInvoke,
}: {
diffServerURL: string;
batchURL?: string;
dataLayerAuth?: string;
diffServerAuth?: string;
name?: string;
repmInvoke: REPMInvoke;
}): Promise<ReplicacheTest> {
const rep = new ReplicacheTest({
batchURL,
dataLayerAuth,
diffServerAuth,
diffServerURL,
name,
repmInvoke,
});
await rep._opened;
// await this._root;
return rep;
}
/** @override */
protected _syncInterval: number | null = null;
beginSync(): Promise<BeginSyncResult> {
return super._beginSync();
}
maybeEndSync(beginSyncResult: BeginSyncResult): Promise<void> {
return super._maybeEndSync(beginSyncResult);
}
}
type Subscription<R, E> = {
body: (tx: ReadTransaction) => Promise<R>;
onData: (r: R) => void;
onError?: (e: E) => void;
onDone?: () => void;
};