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

transactions.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
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
import type {LogContext} from '@rocicorp/logger';import {deepClone, JSONValue, ReadonlyJSONValue} from './json';import { isScanIndexOptions, KeyTypeForScanOptions, ScanIndexOptions, ScanOptions, toDbScanOptions,} from './scan-options';import {fromKeyForIndexScanInternal, ScanResultImpl} from './scan-iterator';import type {ScanResult} from './scan-iterator';import {throwIfClosed} from './transaction-closed-error';import * as db from './db/mod';import * as sync from './sync/mod';import type {Hash} from './hash';import type {ScanSubscriptionInfo} from './subscriptions';import type {ScanNoIndexOptions} from './mod.js';import {decodeIndexKey, IndexKey} from './db/index.js';
/** * ReadTransactions are used with [[Replicache.query]] and * [[Replicache.subscribe]] and allows read operations on the * database. */export interface ReadTransaction { readonly clientID: string;
/** * Get a single value from the database. If the `key` is not present this * returns `undefined`. */ get(key: string): Promise<ReadonlyJSONValue | undefined>;
/** Determines if a single `key` is present in the database. */ has(key: string): Promise<boolean>;
/** Whether the database is empty. */ isEmpty(): Promise<boolean>;
/** * Gets many values from the database. This returns a [[ScanResult]] which * implements `AsyncIterable`. It also has methods to iterate over the [[ScanResult.keys|keys]] * and [[ScanResult.entries|entries]]. * * If `options` has an `indexName`, then this does a scan over an index with * that name. A scan over an index uses a tuple for the key consisting of * `[secondary: string, primary: string]`. * * If the [[ScanResult]] is used after the `ReadTransaction` has been closed it * will throw a [[TransactionClosedError]]. */ scan(): ScanResult<string, ReadonlyJSONValue>;
/** * Gets many values from the database. This returns a [[ScanResult]] which * implements `AsyncIterable`. It also has methods to iterate over the [[ScanResult.keys|keys]] * and [[ScanResult.entries|entries]]. * * If `options` has an `indexName`, then this does a scan over an index with * that name. A scan over an index uses a tuple for the key consisting of * `[secondary: string, primary: string]`. * * If the [[ScanResult]] is used after the `ReadTransaction` has been closed it * will throw a [[TransactionClosedError]]. */ scan<Options extends ScanOptions>( options?: Options, ): ScanResult<KeyTypeForScanOptions<Options>, ReadonlyJSONValue>;}
let transactionIDCounter = 0;
export class ReadTransactionImpl< Value extends ReadonlyJSONValue = ReadonlyJSONValue,> implements ReadTransaction{ readonly clientID: string; protected readonly _dbtx: db.Read; protected readonly _lc: LogContext;
constructor( clientID: string, dbRead: db.Read, lc: LogContext, rpcName = 'openReadTransaction', ) { this.clientID = clientID; this._dbtx = dbRead; this._lc = lc .addContext(rpcName) .addContext('txid', transactionIDCounter++); }
async get(key: string): Promise<Value | undefined> { throwIfClosed(this._dbtx); const rv = await this._dbtx.get(key); if (this._dbtx instanceof db.Write) { return (rv && deepClone(rv)) as Value | undefined; } return rv as Value | undefined; }
async has(key: string): Promise<boolean> { throwIfClosed(this._dbtx); return this._dbtx.has(key); }
async isEmpty(): Promise<boolean> { throwIfClosed(this._dbtx); return this._dbtx.isEmpty(); }
scan(): ScanResult<string, Value>; scan<Options extends ScanOptions>( options?: Options, ): ScanResult<KeyTypeForScanOptions<Options>, Value>; scan<Options extends ScanOptions>( options?: Options, ): ScanResult<KeyTypeForScanOptions<Options>, Value> { return scan(options, this._dbtx, noop); }}
function noop(_: unknown): void { // empty}
function scan<Options extends ScanOptions, Value>( options: Options | undefined, dbRead: db.Read, onLimitKey: (inclusiveLimitKey: string) => void,): ScanResult<KeyTypeForScanOptions<Options>, Value> { const iter = getScanIterator(dbRead, options); return makeScanResultFromScanIteratorInternal( iter, options ?? ({} as Options), dbRead, onLimitKey, ) as ScanResult<KeyTypeForScanOptions<Options>, Value>;}
// An implementation of ReadTransaction that keeps track of `keys` and `scans`// for use with Subscriptions.export class SubscriptionTransactionWrapper extends ReadTransactionImpl<ReadonlyJSONValue> { private readonly _keys: Set<string> = new Set(); private readonly _scans: ScanSubscriptionInfo[] = [];
isEmpty(): Promise<boolean> { // Any change to the subscription requires rerunning it. this._scans.push({options: {}}); return super.isEmpty(); }
get(key: string): Promise<ReadonlyJSONValue | undefined> { this._keys.add(key); return super.get(key); }
has(key: string): Promise<boolean> { this._keys.add(key); return super.has(key); }
scan(): ScanResult<string, ReadonlyJSONValue>; scan<Options extends ScanOptions>( options?: Options, ): ScanResult<KeyTypeForScanOptions<Options>, ReadonlyJSONValue>; scan<Options extends ScanOptions>( options?: Options, ): ScanResult<KeyTypeForScanOptions<Options>, ReadonlyJSONValue> { const scanInfo: ScanSubscriptionInfo = { options: toDbScanOptions(options), inclusiveLimitKey: undefined, }; this._scans.push(scanInfo); return scan(options, this._dbtx, inclusiveLimitKey => { scanInfo.inclusiveLimitKey = inclusiveLimitKey; }); }
get keys(): ReadonlySet<string> { return this._keys; }
get scans(): ScanSubscriptionInfo[] { return this._scans; }}
/** * WriteTransactions are used with *mutators* which are registered using * [[ReplicacheOptions.mutators]] and allows read and write operations on the * database. */export interface WriteTransaction extends ReadTransaction { /** * Sets a single `value` in the database. The `value` will be encoded using * `JSON.stringify`. */ put(key: string, value: JSONValue): Promise<void>;
/** * Removes a `key` and its value from the database. Returns `true` if there was a * `key` to remove. */ del(key: string): Promise<boolean>;
/** * Overrides [[ReadTransaction.get]] to return a mutable [[JSONValue]]. */ get(key: string): Promise<JSONValue | undefined>;
/** * Overrides [[ReadTransaction.scan]] to return a mutable [[JSONValue]]. */ scan(): ScanResult<string, JSONValue>; scan<Options extends ScanOptions>( options?: Options, ): ScanResult<KeyTypeForScanOptions<Options>, JSONValue>;}
export class WriteTransactionImpl extends ReadTransactionImpl<JSONValue> implements WriteTransaction{ // use `declare` to specialize the type. protected declare readonly _dbtx: db.Write;
constructor( clientID: string, dbWrite: db.Write, lc: LogContext, rpcName = 'openWriteTransaction', ) { super(clientID, dbWrite, lc, rpcName); }
async put(key: string, value: JSONValue): Promise<void> { throwIfClosed(this._dbtx); await this._dbtx.put(this._lc, key, deepClone(value)); }
async del(key: string): Promise<boolean> { throwIfClosed(this._dbtx); return await this._dbtx.del(this._lc, key); }
async commit( generateChangedKeys: boolean, ): Promise<[Hash, sync.ChangedKeysMap]> { const txn = this._dbtx; throwIfClosed(txn);
const headName = txn.isRebase() ? sync.SYNC_HEAD_NAME : db.DEFAULT_HEAD_NAME; return await txn.commitWithChangedKeys(headName, generateChangedKeys); }}
export interface IndexTransaction extends ReadTransaction { /** * Creates a persistent secondary index in Replicache which can be used with * scan. * * If the named index already exists with the same definition this returns * success immediately. If the named index already exists, but with a * different definition an error is thrown. */ createIndex(def: CreateIndexDefinition): Promise<void>;
/** * Drops an index previously created with [[createIndex]]. */ dropIndex(name: string): Promise<void>;}
/** * The definition of an index. This is used with * [[Replicache.createIndex|createIndex]] when creating indexes. */export interface CreateIndexDefinition { /** The name of the index. This is used when you [[ReadTransaction.scan|scan]] over an index. */ name: string;
/** * The prefix, if any, to limit the index over. If not provided the values of * all keys are indexed. */ prefix?: string;
/** * A [JSON Pointer](https://tools.ietf.org/html/rfc6901) pointing at the sub * value inside each value to index over. * * For example, one might index over users' ages like so: * `createIndex({name: 'usersByAge', keyPrefix: '/user/', jsonPointer: '/age'})` */ jsonPointer: string;}
export class IndexTransactionImpl extends WriteTransactionImpl implements IndexTransaction{ constructor(clientID: string, dbWrite: db.Write, lc: LogContext) { super(clientID, dbWrite, lc, 'openIndexTransaction'); }
async createIndex(options: CreateIndexDefinition): Promise<void> { throwIfClosed(this._dbtx); await this._dbtx.createIndex( this._lc, options.name, options.prefix ?? '', options.jsonPointer, ); }
async dropIndex(name: string): Promise<void> { throwIfClosed(this._dbtx); await this._dbtx.dropIndex(name); }
async commit(): Promise<[Hash, sync.ChangedKeysMap]> { return super.commit(false); }}
type Entry<K> = readonly [key: K, value: ReadonlyJSONValue];
export type IndexKeyEntry = Entry<IndexKey>;
export type StringKeyEntry = Entry<string>;
export type EntryForOptions<Options extends ScanOptions> = Options extends ScanIndexOptions ? IndexKeyEntry : StringKeyEntry;
function getScanIterator<Options extends ScanOptions>( dbRead: db.Read, options: Options | undefined,): AsyncIterable<EntryForOptions<Options>> { if (options && isScanIndexOptions(options)) { return getScanIteratorForIndexMap(dbRead, options) as AsyncIterable< EntryForOptions<Options> >; }
return dbRead.map.scan(fromKeyForNonIndexScan(options)) as AsyncIterable< EntryForOptions<Options> >;}
export function fromKeyForNonIndexScan( options: ScanNoIndexOptions | undefined,): string { if (!options) { return ''; }
const {prefix = '', start} = options; if (start && start.key > prefix) { return start.key; } return prefix;}
function makeScanResultFromScanIteratorInternal< Options extends ScanOptions, Value,>( iter: AsyncIterable<EntryForOptions<Options>>, options: Options, dbRead: db.Read, onLimitKey: (inclusiveLimitKey: string) => void,): ScanResult<KeyTypeForScanOptions<Options>, Value> { return new ScanResultImpl(iter, options, dbRead, onLimitKey);}
async function* getScanIteratorForIndexMap( dbRead: db.Read, options: ScanIndexOptions,): AsyncIterable<IndexKeyEntry> { const map = await dbRead.getMapForIndex(options.indexName); for await (const entry of map.scan(fromKeyForIndexScanInternal(options))) { yield [decodeIndexKey(entry[0]), entry[1]]; }}
replicache

Version Info

Tagged at
2 years ago