deno.land / x / replicache@v10.0.0-beta.0 / persist / clients.ts

نووسراو ببینە
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
import {assertHash, Hash, hashOf} from '../hash';import * as btree from '../btree/mod';import * as dag from '../dag/mod';import * as db from '../db/mod';import type * as sync from '../sync/mod';import type {ReadonlyJSONValue} from '../json';import {assertNotUndefined, assertNumber, assertObject} from '../asserts';import {hasOwn} from '../has-own';import {uuid as makeUuid} from '../uuid';import {getRefs, newSnapshotCommitData} from '../db/commit';import type {MaybePromise} from '../mod';
export type ClientMap = ReadonlyMap<sync.ClientID, Client>;
export type Client = { /** * A UNIX timestamp in milliseconds updated by the client once a minute * while it is active and everytime the client persists its state to * the perdag. * Should only be updated by the client represented by this structure. */ readonly heartbeatTimestampMs: number; /** * The hash of the commit in the perdag this client last persisted. * Should only be updated by the client represented by this structure. */ readonly headHash: Hash; /** * The mutationID of the commit at headHash (mutationID if it is a * local commit, lastMutationID if it is an index change or snapshot commit). * Should only be updated by the client represented by this structure. * Read by other clients to determine if there are unacknowledged pending * mutations for them to push on behalf of the client represented by this * structure. * This is redundant with information in the commit graph at headHash, * but allows other clients to determine if there are unacknowledged pending * mutations without having to load the commit graph at headHash. */ readonly mutationID: number; /** * The highest lastMutationID received from the server for this client. * * Should be updated by the client represented by this structure whenever * it persists its state to the perdag. * Read by other clients to determine if there are unacknowledged pending * mutations for them to push on behalf of the client represented by this * structure, and *updated* by other clients upon successfully pushing * pending mutations to avoid redundant pushes of those mutations. * * Note: This will be the same as the lastMutationID of the base snapshot of * the commit graph at headHash when written by the client represented by this * structure. However, when written by another client pushing pending * mutations on this client's behalf it will be different. This is because * the other client does not update the commit graph (it is unsafe to update * another client's commit graph). */ readonly lastServerAckdMutationID: number;};const CLIENTS_HEAD = 'clients';
function assertClient(value: unknown): asserts value is Client { assertObject(value); const {heartbeatTimestampMs, headHash} = value; assertNumber(heartbeatTimestampMs); assertHash(headHash);}
function chunkDataToClientMap(chunkData?: ReadonlyJSONValue): ClientMap { assertObject(chunkData); const clients = new Map(); for (const key in chunkData) { if (hasOwn(chunkData, key)) { const value = chunkData[key]; if (value !== undefined) { assertClient(value); clients.set(key, value); } } } return clients;}
function clientMapToChunkData( clients: ClientMap, dagWrite: dag.Write,): ReadonlyJSONValue { clients.forEach(client => { dagWrite.assertValidHash(client.headHash); }); return Object.fromEntries(clients);}
function clientMapToChunkDataNoHashValidation( clients: ClientMap,): ReadonlyJSONValue { return Object.fromEntries(clients);}
export async function getClients(dagRead: dag.Read): Promise<ClientMap> { const hash = await dagRead.getHead(CLIENTS_HEAD); return getClientsAtHash(hash, dagRead);}
async function getClientsAtHash( hash: Hash | undefined, dagRead: dag.Read,): Promise<ClientMap> { if (!hash) { return new Map(); } const chunk = await dagRead.getChunk(hash); return chunkDataToClientMap(chunk?.data);}
/** * Used to signal that a client does not exist. Maybe it was garbage collected? */export class ClientStateNotFoundError extends Error { name = 'ClientStateNotFoundError'; readonly id: string; constructor(id: sync.ClientID) { super(`Client state not found, id: ${id}`); this.id = id; }}
/** * Throws a `ClientStateNotFoundError` if the client does not exist. */export async function assertHasClientState( id: sync.ClientID, dagRead: dag.Read,): Promise<void> { if (!(await hasClientState(id, dagRead))) { throw new ClientStateNotFoundError(id); }}
export async function hasClientState( id: sync.ClientID, dagRead: dag.Read,): Promise<boolean> { return !!(await getClient(id, dagRead));}
export async function getClient( id: sync.ClientID, dagRead: dag.Read,): Promise<Client | undefined> { const clients = await getClients(dagRead); return clients.get(id);}
export async function initClient( dagStore: dag.Store,): Promise<[sync.ClientID, Client, ClientMap]> { const newClientID = makeUuid(); const updatedClients = await updateClients(async clients => { let bootstrapClient: Client | undefined; for (const client of clients.values()) { if ( !bootstrapClient || bootstrapClient.heartbeatTimestampMs < client.heartbeatTimestampMs ) { bootstrapClient = client; } }
let newClientCommitData; const chunksToPut = []; if (bootstrapClient) { const constBootstrapClient = bootstrapClient; newClientCommitData = await dagStore.withRead(async dagRead => { const bootstrapCommit = await db.baseSnapshot( constBootstrapClient.headHash, dagRead, ); // Copy the snapshot with one change: set last mutation id to 0. Replicache // server implementations expect new client ids to start with last mutation id 0. // If a server sees a new client id with a non-0 last mutation id, it may conclude // this is a very old client whose state has been garbage collected on the server. return newSnapshotCommitData( bootstrapCommit.meta.basisHash, 0 /* lastMutationID */, bootstrapCommit.meta.cookieJSON, bootstrapCommit.valueHash, bootstrapCommit.indexes, ); }); } else { // No existing snapshot to bootstrap from. Create empty snapshot. const emptyBTreeChunk = await dag.createChunkWithNativeHash( btree.emptyDataNode, [], ); chunksToPut.push(emptyBTreeChunk); newClientCommitData = newSnapshotCommitData( null /* basisHash */, 0 /* lastMutationID */, null /* cookie */, emptyBTreeChunk.hash, [] /* indexes */, ); }
const newClientCommitChunk = await dag.createChunkWithNativeHash( newClientCommitData, getRefs(newClientCommitData), ); chunksToPut.push(newClientCommitChunk);
return { clients: new Map(clients).set(newClientID, { heartbeatTimestampMs: Date.now(), headHash: newClientCommitChunk.hash, mutationID: 0, lastServerAckdMutationID: 0, }), chunksToPut, }; }, dagStore); const newClient = updatedClients.get(newClientID); assertNotUndefined(newClient); return [newClientID, newClient, updatedClients];}
function hashOfClients(clients: ClientMap): Promise<Hash> { const data = clientMapToChunkDataNoHashValidation(clients); return hashOf(data);}
export const noUpdates = Symbol();export type NoUpdates = typeof noUpdates;
export type ClientsUpdate = ( clients: ClientMap,) => MaybePromise< {clients: ClientMap; chunksToPut?: Iterable<dag.Chunk>} | NoUpdates>;
export async function updateClients( update: ClientsUpdate, dagStore: dag.Store,): Promise<ClientMap> { const [clients, clientsHash] = await dagStore.withRead(async dagRead => { const clientsHash = await dagRead.getHead(CLIENTS_HEAD); const clients = await getClientsAtHash(clientsHash, dagRead); return [clients, clientsHash]; }); return updateClientsInternal(update, clients, clientsHash, dagStore);}
async function updateClientsInternal( update: ClientsUpdate, clients: ClientMap, clientsHash: Hash | undefined, dagStore: dag.Store,): Promise<ClientMap> { const updateResults = await update(clients); if (updateResults === noUpdates) { return clients; } const {clients: updatedClients, chunksToPut} = updateResults; const updatedClientsHash = await hashOfClients(updatedClients); const result = await dagStore.withWrite(async dagWrite => { const currClientsHash = await dagWrite.getHead(CLIENTS_HEAD); if (currClientsHash !== clientsHash) { // Conflict! Someone else updated the ClientsMap. Retry update. return { updateApplied: false, clients: await getClientsAtHash(currClientsHash, dagWrite), clientsHash: currClientsHash, }; } const updatedClientsChunkData = clientMapToChunkData( updatedClients, dagWrite, ); const updateClientsRefs = Array.from( updatedClients.values(), client => client.headHash, ); const updateClientsChunk = dag.createChunkWithHash( updatedClientsHash, updatedClientsChunkData, updateClientsRefs, ); const chunksToPutPromises: Promise<void>[] = []; if (chunksToPut) { for (const chunk of chunksToPut) { chunksToPutPromises.push(dagWrite.putChunk(chunk)); } } await Promise.all([ ...chunksToPutPromises, dagWrite.putChunk(updateClientsChunk), dagWrite.setHead(CLIENTS_HEAD, updateClientsChunk.hash), ]); await dagWrite.commit(); return { updateApplied: true, clients: updatedClients, clientsHash: updatedClientsHash, }; }); if (result.updateApplied) { return result.clients; } else { return updateClientsInternal( update, result.clients, result.clientsHash, dagStore, ); }}
replicache

Version Info

Tagged at
2 years ago