forked from rocicorp/replicache
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtransactions.ts
More file actions
337 lines (295 loc) · 9.25 KB
/
Copy pathtransactions.ts
File metadata and controls
337 lines (295 loc) · 9.25 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
import type {JSONValue} from './json.js';
import {
Invoke,
OpenTransactionRequest,
CommitTransactionResponse,
RPC,
CloseTransactionResponse,
} from './repm-invoker.js';
import {
KeyTypeForScanOptions,
ScanOptions,
ScanOptionsRPC,
toRPC,
} from './scan-options.js';
import {ScanResult} from './scan-iterator.js';
import {throwIfClosed} from './transaction-closed-error.js';
import {asyncIterableToArray} from './async-iterable-to-array.js';
/**
* ReadTransactions are used with [[Replicache.query]] and
* [[Replicache.subscribe]] and allows read operations on the
* database.
*/
export interface ReadTransaction {
/**
* Get a single value from the database. If the `key` is not present this
* returns `undefined`.
*/
get(key: string): Promise<JSONValue | 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>;
/**
* 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<O extends ScanOptions, K extends KeyTypeForScanOptions<O>>(
options?: O,
): ScanResult<K>;
/**
* Convenience form of [[scan]] which returns all the entries as an array.
* @deprecated Use `scan().entries().toArray()` instead
*/
scanAll(): Promise<[string, JSONValue][]>;
/**
* Convenience form of [[scan]] which returns all the entries as an array.
* @deprecated Use `scan().entries().toArray()` instead
*/
scanAll<O extends ScanOptions, K extends KeyTypeForScanOptions<O>>(
options?: O,
): Promise<[K, JSONValue][]>;
}
export class ReadTransactionImpl implements ReadTransaction {
private _transactionId = -1;
protected readonly _invoke: Invoke;
protected _closed = false;
protected readonly _openTransactionName:
| RPC.OpenTransaction
| RPC.OpenIndexTransaction = RPC.OpenTransaction;
constructor(invoke: Invoke) {
this._invoke = invoke;
}
async get(key: string): Promise<JSONValue | undefined> {
throwIfClosed(this);
const result = await this._invoke(RPC.Get, {
transactionId: this._transactionId,
key,
});
if (!result.has) {
return undefined;
}
return JSON.parse(result.value);
}
async has(key: string): Promise<boolean> {
throwIfClosed(this);
const result = await this._invoke(RPC.Has, {
transactionId: this._transactionId,
key,
});
return result['has'];
}
async isEmpty(): Promise<boolean> {
throwIfClosed(this);
let empty = true;
await this._invoke(RPC.Scan, {
transactionId: this._transactionId,
opts: {limit: 1},
receiver: () => (empty = false),
});
return empty;
}
scan<O extends ScanOptions, K extends KeyTypeForScanOptions<O>>(
options?: O,
): ScanResult<K> {
return new ScanResult(options, this._invoke, () => this, false);
}
async scanAll<O extends ScanOptions, K extends KeyTypeForScanOptions<O>>(
options?: O,
): Promise<[K, JSONValue][]> {
return asyncIterableToArray(
this.scan(options).entries() as AsyncIterable<[K, JSONValue]>,
);
}
get id(): number {
return this._transactionId;
}
get closed(): boolean {
return this._closed;
}
async open(args: OpenTransactionRequest): Promise<void> {
const {transactionId} = await this._invoke(this._openTransactionName, args);
this._transactionId = transactionId;
}
async close(): Promise<CloseTransactionResponse> {
this._closed = true;
return await this._invoke(RPC.CloseTransaction, {
transactionId: this._transactionId,
});
}
}
// An implementation of ReadTransaction that keeps track of `keys` and `scans`
// for use with Subscriptions.
export class SubscriptionTransactionWrapper implements ReadTransaction {
private readonly _keys: Set<string> = new Set();
private readonly _scans: ScanOptionsRPC[] = [];
private readonly _tx: ReadTransaction;
constructor(tx: ReadTransaction) {
this._tx = tx;
}
isEmpty(): Promise<boolean> {
// Any change to the subscription requires rerunning it.
this._scans.push({});
return this._tx.isEmpty();
}
get(key: string): Promise<JSONValue | undefined> {
// TODO(arv): Use override keyword once we are using TS4.3
this._keys.add(key);
return this._tx.get(key);
}
has(key: string): Promise<boolean> {
this._keys.add(key);
return this._tx.has(key);
}
scan<O extends ScanOptions, K extends KeyTypeForScanOptions<O>>(
options?: O,
): ScanResult<K> {
this._scans.push(toRPC(options));
return this._tx.scan(options);
}
async scanAll<O extends ScanOptions, K extends KeyTypeForScanOptions<O>>(
options?: O,
): Promise<[K, JSONValue][]> {
this._scans.push(toRPC(options));
return this._tx.scanAll(options);
}
get keys(): ReadonlySet<string> {
return this._keys;
}
get scans(): ScanOptionsRPC[] {
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>;
}
export class WriteTransactionImpl
extends ReadTransactionImpl
implements WriteTransaction
{
async put(key: string, value: JSONValue): Promise<void> {
throwIfClosed(this);
await this._invoke(RPC.Put, {
transactionId: this.id,
key,
value: JSON.stringify(value),
});
}
async del(key: string): Promise<boolean> {
throwIfClosed(this);
const result = await this._invoke(RPC.Del, {
transactionId: this.id,
key,
});
return result.ok;
}
async commit(
generateChangedKeys: boolean,
): Promise<CommitTransactionResponse> {
this._closed = true;
return await this._invoke(RPC.CommitTransaction, {
transactionId: this.id,
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.
*/
keyPrefix?: 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 ReadTransactionImpl
implements IndexTransaction
{
protected readonly _openTransactionName = RPC.OpenIndexTransaction;
async createIndex(options: CreateIndexDefinition): Promise<void> {
throwIfClosed(this);
await this._invoke(RPC.CreateIndex, {
transactionId: this.id,
name: options.name,
keyPrefix: options.keyPrefix || '',
jsonPointer: options.jsonPointer,
});
}
async dropIndex(name: string): Promise<void> {
throwIfClosed(this);
await this._invoke(RPC.DropIndex, {
transactionId: this.id,
name,
});
}
async commit(): Promise<CommitTransactionResponse> {
this._closed = true;
return await this._invoke(RPC.CommitTransaction, {
transactionId: this.id,
generateChangedKeys: false,
});
}
}