-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathinterfaces.ts
774 lines (657 loc) · 28.3 KB
/
interfaces.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
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
// single: Return one value (the content of the store). Query ignored
// allkv: Query all key-values in a kv database. Similar to single, but enforces kv.
// kv: Query with a set of keys, return corresponding values.
// sortedkv: Query set of ranges. return kv map with contained values
export enum QueryType {
Single = 1,
KV = 2,
AllKV = 3,
Range = 4,
StaticRange = 5,
}
export enum ResultType {
// Raw = 0,
Single = 1,
KV = 2,
Range = 4,
}
// export type QueryType = 'single' | 'allkv' | 'kv' | 'range' | 'static range'
// export type ResultType = 'single' | 'kv' | 'range'
export type Version = Uint8Array
export type Source = string
export type Key = string // TODO: Relax this restriction.
export type KVPair<Val> = [Key, Val]
export type KVQuery = Set<Key>
// In the context of a store's sources (the first result matches the first of
// the stores' listed sources in storeinfo).
export type FullVersion = (Version | null)[]
export type VersionRange = {from: Version, to: Version}
// In the context of a store's sources
export type FullVersionRange = (VersionRange | null)[]
export type StaticKeySelector = {
k: Key,
isAfter: boolean, // is the key itself included
}
export type KeySelector = StaticKeySelector & {
offset: number, // walk + or - from the specified key
}
export type StaticRange = {
low: StaticKeySelector,
high: StaticKeySelector,
// If true, results will be returned in reverse lexicographical
// order beginning with range.high.
reverse?: boolean, // default false.
}
export type Range = {
low: KeySelector,
high: KeySelector,
reverse?: boolean, // as above, default false.
// If non-zero, limits the number of documents returned. TODO: Add marker in
// results somehow showing that there are more results after the limit.
limit?: number, // default 0.
}
export type RangeQuery = Range[]
export type StaticRangeQuery = StaticRange[]
// Outside in we have:
// 1. List of ranges
// 2. Document item in the list
// 3. Key / Value pair
export type RangeResult<Val> = [Key, Val][][]
// Wrapping single and allkv like this is sort of dumb, but it works better
// with TS type checks.
export type Query = {type: QueryType.Single | QueryType.AllKV, q: boolean} | {
type: QueryType.KV,
q: KVQuery,
} | {
type: QueryType.Range,
q: RangeQuery,
} | {
type: QueryType.StaticRange,
q: StaticRangeQuery,
}
// This is an internal type. Its sort of gross that it exists. I think
// eventually I'd like to move to using a single "empty" query type that
// completed queries end up at.
export type QueryData = boolean | KVQuery | StaticRangeQuery | RangeQuery
export type ResultData<Val> = any | Map<Key, Val> | RangeResult<Val>
// For now this is just used for snapshot replacements. It'll probably need work.
export type ReplaceQuery = {type: QueryType.Single | QueryType.AllKV, q: boolean} | {
type: QueryType.KV,
q: KVQuery,
} | {
type: QueryType.StaticRange,
q: StaticRangeQuery[], // !!
} // TODO: What should this be for full range queries?
export type ReplaceQueryData = boolean | KVQuery | StaticRangeQuery[]
export type ReplaceData<Val> = any | Map<Key, Val> | RangeResult<Val>[]
// export type Result = {
// type: 'single',
// d: any
// } | {
// type: 'kv',
// d: Map<Key, Val>
// }
export type SingleOp<Val> = {
readonly type: string,
readonly data?: any,
// Optional. Used when supportedTypes doesn't match.
readonly newval?: Val,
}
export type Metadata = {
uid?: string, // unique ID
ts?: number, // timestamp
}
// Only a list if the op type doesn't support compose. (Both set and rm support compose.)
export type Op<Val> = SingleOp<Val> | SingleOp<Val>[]
export type SingleTxn<Val> = Op<Val>
export type KVTxn<Val> = Map<Key, Op<Val>>
// Ideally this would be a sparse list. Not a big deal in practice though.
export type RangeTxn<Val> = [Key, Op<Val>][][]
// But which one? For stores which implement KV + Range, they'll (obviously)
// end up propogating a KVTxn through onTxn. Right now RangeTxn is only used
// for range subscriptions.
export type Txn<Val> = SingleTxn<Val> | KVTxn<Val> | RangeTxn<Val>
export type TxnWithMeta<Val> = {
versions: FullVersion, // Version after txn applied (nulls for parts unchanged)
txn: Txn<Val>,
meta: Metadata, // Unique ID generated by the client.
}
/**
* Fetch options. These options can be passed to `store.fetch()`.
*
* TODO: Note that not all stores currently support all options. Add tests &
* documentation for this.
*/
export type FetchOpts = {
/**
* Don't actually return values in returned data. Useful for figuring out the
* version. If unspecified, defaults to `false`.
*/
readonly noDocs?: boolean,
/**
* Request that results are returned at a version >= the version specified. If
* the store does not have data at the specified version yet, it should wait
* for results to be available before returning.
*/
readonly minVersion?: FullVersion
/**
* Request that the results are returned at the exact specified version.
* Stores should return VersionTooOldError if the version is too far in the
* past. This could take a version range instead, but I'm not sure
* what the stores would do with the full range information.
*
* TODO: This isn't currently tested or supported by most stores.
* TODO: Figure out how this should interact with minVersion.
*/
readonly atVersion?: FullVersion,
// Results already known at specified version. Return nothing in this case.
// readonly knownAtVersions?: FullVersion,
// TODO: knownDocs?
}
/**
* This describes the data returned by calls to `store.fetch()`.
*/
export type FetchResults<Val, R = ResultData<Val>> = {
/**
* The results returned by executing the query against the database
*/
results: R,
/**
* The range across which the result set is valid. See description of
* store.fetch for details.
*/
versions: FullVersionRange,
/**
* Optional. This is returned so implementors can bake out the query into a
* static query. Eg, a range query (with limits and offsets) will be baked out
* to a static range query with none of thatß, and returned alongside the data
* itself. This is currently only created & returned for range queries, but
* this may become useful for KV queries if limits can be specified in the
* fetch options.
*
* You should generally ignore this.
*/
bakedQuery?: Query,
// TODO: Maybe return a JSON-friendly opaque cursor structure here, which
// can be passed back to the store to continue the fetch results when limits
// are sent & applied.
}
/**
* This describes options supported by calls to GetOps.
*/
export type GetOpsOptions = {
/**
* Supported client-side operation types.
*/
readonly supportedTypes?: Set<string>,
// Ignore supportedTypes, just send full received ops. (default false)
// readonly raw?: boolean,
/**
* If we can't get all the requested operations, don't abort with an error but
* return what we can.
*/
readonly bestEffort?: boolean,
// Options NYI:
// - limitBytes: Limit on the amount of data to read & return. Advisory
// only. Will always try to make progress (that is, return at least one
// operation). There is no limitDocs equivalent because you can just
// shrink the requested range if thats what you're after. NYI
// - limitOps: Limit the number of operations returned. NYI
/** Limit the number of ops returned. Default: No limit. */
readonly limitOps?: number,
}
export type GetOpsResult<Val> = {
/**
* The operations returned by getOps.
*/
ops: TxnWithMeta<Val>[],
/**
* The range (from, to] of the returned set for each source, across which the
* results are valid. This will be the same as the input if all ops are
* available and included in the query, and there are no limits.
*/
versions: FullVersionRange,
}
// If the to version in a version range is empty, fetch the open range (from..]
// export type GetOpsFn<Val> = (q: Query, versions: FullVersionRange, opts?: GetOpsOptions) => Promise<GetOpsResult<Val>>
export type CatchupData<Val> = {
// This is more complicated than I'd like, but I'm reasonably happy with it.
// The problem is that catchup isn't always possible, so sometimes you just
// gotta send a diff with new documents in it; and you have no idea how you
// got there.
/** Replace the results in q with this result set, if it exists */
replace?: {
// This is a bit of a hack. If the query here contains more keys / ranges
// than the original request, they should be added to the active known
// set.
//
// Queries are currently only expanded, so this works but a QueryDelta
// would be better.
//
// Its awkward for ranges. For now the query contains a list of query
// parts matching the original query. Each part is either a noop or its a
// range query extension. (And then `with` is a standard KV[][]).
q: ReplaceQuery,
with: ReplaceData<Val>,
// This is the max version for each source of the replacement data. This
// becomes from:X if ingesting into a FullVersonRange.
versions: FullVersion,
},
txns: TxnWithMeta<Val>[], // ... then apply txns.
// This is the known upper end of the valid version range of the data
// returned by catchup. For subscriptions this is a diff from what has been
// reported previously, and usually it will just replay the max versions
// listen in txns. But when calling alwaysNotify, this will keep updating as
// the validity of the versions of the known data grows. This becomes to:X
// when ingesting into a FullVersionRange. All sources here must have either
// been passed in to subscribe / catchup or listed in a replace.
toVersion: FullVersion,
// Having received this update chunk, is the client now up-to-date?
caughtUp: boolean,
}
// The updates argument here could either work as
// {txn, v:fullrange}[]
// or
// {txn, source, v:version}[] like in getOps.
// Its inconsistent how it is now, but this also makes it much more convenient
// to aggregate.
export type CatchupOpts = {
// TODO: Probably more stuff needs to go in here.
readonly supportedTypes?: Set<string>,
readonly raw?: boolean,
readonly aggregate?: 'yes' | 'prefer no' | 'no',
readonly bestEffort?: boolean,
readonly limitDocs?: number,
readonly limitBytes?: number,
}
// export type CatchupFn<Val> = (q: Query, fromVersion: FullVersion, opts: CatchupOpts) => Promise<CatchupData<Val>>
export type SubscribeOpts = {
// Supported client-side operation types. Also forwarded to getOps.
readonly supportedTypes?: Set<string>,
// I'd like to get rid of this. If this is set, the subscription will
// track the value itself to support filtering by supported types.
// This should be an internal implementation detail.
readonly trackValues?: boolean,
// Ignore supportedTypes, just send full received ops. (default false)
readonly raw?: boolean,
// Can the store aggregate old updates into replacement data instead of
// sending the full operation set? This will not always be possible - for
// example, the backend server might have paged out / deleted old
// operations.
//
// If never is passed, the server should error if the full operation log is
// not available.
readonly aggregate?: 'yes' | 'prefer no' | 'no',
// bestEffort: if we can't get all the requested operations, don't error
// but return what we can. Passed through to catchup & getOps.
readonly bestEffort?: boolean,
// Always notify about version bumps even if the query results are empty?
// (default false)
readonly alwaysNotify?: boolean,
// Just subscribe to whatever's there, from the current version. If this is
// passed, fromVersion is ignored and you just get all operations as they're
// streamed live.
// Functionally equivalent to calling subscribe(q, (await fetch(q, {noDocs:true})).version)).
// readonly fromCurrent?: boolean,
// Subscribe from the specified version. If this is passed, we'll send ops
// TODO: Maybe rename current -> 'raw' ?
fromVersion?: FullVersion | 'current',
// NYI:
// - Follow symlinks? (NYI)
// - When we poll, how much data should we fetch? (opts.limitDocs, opts.limitBytes)
// - Stop the query after a certain number of operations (opts.limitOps) (NYI)
// readonly limitBytes: number,
}
export type AsyncIterableIteratorWithRet<T> = AsyncIterableIterator<T> & {
// AsyncIterableIterator declares the return function to be optional.
// Having a return function is compulsory - its how the subscription is closed.
// The value passed to return is ignored.
return(value?: any): Promise<IteratorResult<T>>,
}
export type Subscription<Val> = AsyncIterableIteratorWithRet<CatchupData<Val>>
export type MutateOptions = {
conflictKeys?: Key[], // TODO: Add conflict ranges.
meta?: Metadata,
}
// TODO: Consider wrapping ResultType + txn in an object like I did with Query.
// Also the TxnWithMeta is made from txn, versions and opts.meta. Might be better to just pass a TxnWithMeta straight in.
// export type MutateFn<Val> = (type: ResultType, txn: Txn<Val>, versions?: FullVersion, opts?: MutateOptions) => Promise<FullVersion>
export type OpsSupport = 'none' | 'partial' | 'all' // TODO
export type Capabilities = {
// TODO: Add a way to mark if we can subscribe over ranges or just static
// ranges
// These are bitsets.
readonly queryTypes: number,
readonly mutationTypes: number,
readonly ops?: OpsSupport, // TODO
}
export type StoreInfo = {
readonly uid: string, // Ideally, string or byte array or something.
// Unique and lexographically sorted.
readonly sources: Source[],
// Same length as the source list. This is kinda ugly, but its very infrequently used so,.
readonly sourceIsMonotonic: boolean[],
readonly capabilities: Capabilities,
// And ideally, recursive querying support.
[k: string]: any
}
export type TxnListener<Val> = (
source: Source,
fromV: Version, toV: Version,
type: ResultType, txn: Txn<Val>,
meta: Metadata
) => void
/**
* Stores are the beating heart of statecraft. Stores are a semantic wrapper
* around:
*
* - Some data (A single value or a set of key-value pairs)
* - A monotonically increasing version number (or multiple version numbers).
*
* The store interface is intended to be like studs on a lego brick - a
* composable, interoperable API for interacting with data that changes over
* time.
*
* The store interface is designed to be a generic way to access:
*
* - Databases
* - Files on disk
* - Values in memory
* - Computed views (computed lazily or eagerly)
* - Event sources
* - Any other API for remote data
*
* Most statecraft stores will not store data directly, but instead wrap or
* delegate the data storage to another store in turn.
*
* Note that store is an interface and not a class. Any javascript object which
* conforms to the store specification (below) is considered to be a store, and
* can be used in any place that stores are used. This includes throughout the
* core statecraft library.
*
* See other documentation for more high level details on stores.
*/
export interface Store<Val> {
/**
* Information about the store. This describes the store's unique identifier,
* list of root sources and supported query types.
*
* Exported GraphQL schemas will be added here too.
*/
readonly storeInfo: StoreInfo, // TODO: Should this be a promise?
/**
* Fetch data from the store based on the passed query.
*
* This is one of two normal functions for reading data from a store.
*
* @param query A description of the data to be fetched. For example,
* `{type:'kv', q:new Set(['a','b','c'])}`. See query documentation for
* details on query types. The valid query types for a given store are listed
* in the `storeInfo.capabilities.queryTypes` bitfield.
*
* @param opts Fetch options.
*
* @returns A promise to the corresponding result set, along with a version
* range at which that resulting data is valid.
*
* For example, imagine a query requests key `a`. In the database, `a` was
* last modified at version 100. The database is currently at version 200. The
* result set will contain the value of key `a` (well, a `Map` from `a` to its
* corresponding value). The returned version range will be from version 100
* to version 200.
*
* Some stores do not store all historical versions. In the example above, if
* the store only remembers versions 190-200, the returned version range is
* allowed to only specify that smaller version range.
*/
fetch(q: Query, opts?: FetchOpts): Promise<FetchResults<Val>>
/**
* Get all historical operations within the specified version range. The
* operations returned should be trimmed to values in the requested query set.
*
* Note that some stores will simply wrap an event log (like kafka). In this
* case, the store should only advertise supporting query types `AllKV` or
* `Single`, and the query itself may be ignored completely.
*
* @param versions `[{from, to}]` pairs for each source, or `null` if you
* don't care about operations of the named source. The data returned will be
* in the range of (from, to]. You can think of the results as the operations
* moving from a snapshot at version `from` to a snapshot at version version
* `to`. Pass `to:<Empty buffer>` to get all available operations from version
* `from` to the current point in time.
*
* @param opts Optional getOps options object. See GetOpsOptions for details.
*/
getOps(q: Query, versions: FullVersionRange, opts?: GetOpsOptions): Promise<GetOpsResult<Val>>
// For reconnecting, you can specify knownDocs, knownAtVersions
// - ... And something to specify the catchup mode (fast vs full)
// - opts.getFullHistortForDocs - or something like it.
// These options should usually appear together.
/**
* A subscription is a stream of catchup operations. These operations can be
* applied in order to observe the state of some data changing over time.
*
* There are 3 modes a subscription can run in, depending on the existance and
* value of `opts.fromVersion`:
*
* 1. *Fetch and subscribe*: This is the default if you don't pass any
* options, or don't specify `opts.fromVersion`. The first update from the
* subscription will contain a `replace: {...}` object with results as if
* you fetched the query directly. After the initial catchup object, the
* subscription is identical to a subscribe only query (below).
* 2. *Subscribe only*: Subscribe only queries are used when consuming
* application already has a snapshot of the data at some known version.
* Subscriptions run in subscribe only mode if you pass in
* `fromVersion:[...]` in the query options, specifying the version from
* which the client has operations. The store won't do any initial fetch,
* but instead will attempt to catch the client up from the specified
* version. Use `opts.aggregate` to control whether the server is allowed
* to aggregate the initial catchup. Note that some stores only store
* historical operations for a certain amount of time, or not at all. If
* the requested version is too old, the store may simply give the client
* application a fresh snapshot as the first update regardless of the state
* of the `fromVersion` option.
* 3. *Raw subscribe*: If you pass `fromVersion: 'current'`, you get all
* operations as they come in from whatever version the store thinks its
* at. No catchup is performed at all in this mode. Most applications will
* never use raw subscriptions.
*
* The subscription itself is an async iterator. This means you can read from
* the stream of operations with a `for await` loop:
*
* ```
* const sub = store.subscribe({type: QueryType.Single, q:true})
* for await (const catchup of sub) {
* // ...
* }
* ```
*
* However, the catchup objects themselves are quite complex, and they're
* awkward to consume directly. Almost all applications should use the
* standard catchup state machine to consume subscription catchup objects:
*
* ```
* const sub = store.subscribe({type: QueryType.KV, q:new Set([...])})
* for await (const data of statecraft.subValues(ResultType.KV, sub)) {
* console.log('query result set is now', data)
* }
* ```
*
* The state machine can also be driven manually:
*
* ```
* const sub = store.subscribe({type: QueryType.StaticRange, q:[
* {low: sel('a/x', true), high: sel('z')}
* ]})
* const machine = catchupStateMachine(ResultType.Range)
* ;(async () => {
* for await (const catchup of sub) {
* const {results, versions} = machine(catchup)
* console.log('query result set is now', results, 'at version', versions)
* }
* })()
* ```
*
* @param q A query defining the data that the consumer is interested in. Just
* like `fetch`, the query type must be listed in `storeInfo.capabilities.queryTypes`.
*
* @returns The subscription object. Note that this subscription is returned
* syncronously (immediately). But resulting data will only be available with
* the first update.
*/
subscribe(q: Query, opts?: SubscribeOpts): AsyncIterableIteratorWithRet<CatchupData<Val>>
/**
* Modify the db by applying the specified transaction. All database writes
* happen through this function.
*
* `mutate` is atomic. Stores guarantee that the transaction is either applied
* in its entirity or not applied at all.
*
* Calling mutate directly is not always recommended.
* - For simple writes, consider using the helper functions `setSingle`,
* `rmKV` or `setKV`.
* - For writes involving more complex logic and automatic retries in case of
* conflicts, consider using a `transaction`. This mirrors the API you use
* when interacting with more traditional databases.
*
* Ultimately however, all of these tools wrap calls to `mutate`.
*
* @param type The expected result type of the store. Most stores will only
* have one result type (`ResultType.Single` or `ResultType.KV`). The
* transaction's format must match the type passed here. Stores advertise
* their list of allowed result types via
*
* @param txn A transaction describing desired modifications to the database.
* The format of this object changes depending on the type of data in the
* store.
*
* - For single value stores, this is usually `{type:'set', data}` or
* `{type:'rm'}`.
* - For KV stores, this is a map from key to operation. For example, `new
* Map([['a',{type:'set',123}],['b',{type:'rm'}]])`.
*
* Other types can be registered via `statecraft.registerType`. This is useful
* for collaborative editing via OT or CRDT, or for custom complex data update
* functions like you would use for a multiplayer game.
*
* @param versions (*optional*): The version of the database at which this
* transaction is valid. If this transaction writes to any keys which have
* been modified more recently than the specified version, the transaction is
* considered to be in conflict and will be aborted. The transaction can also
* specify additional conflict keys via `opts.conflictKeys`.
*
* Note that if versions is not specified, the transaction will be applied
* some arbitrary current version. This means that you may overwrite changes
* from other users.
*
* @returns A promise to the resulting version of the store after the mutation
* has been applied.
*/
mutate(type: ResultType, txn: Txn<Val>, versions?: FullVersion, opts?: MutateOptions): Promise<FullVersion>
/**
* Close the store. This should free any resources allocated on behalf of the
* store, closing outgoing network sockets and associated file handles.
*
* This function is often a no-op.
*
* Stores should only recursively call `close()` on other stores created and
* owned locally.
*
* Likewise, store consumers should call `close()` on all stores created
* locally, even if those stores are only made as part of a data pipeline.
*/
close(): void,
/**
* Catchup is an optional method that can be added to stores to make
* subscription catchup faster (eg when a subscription is created from a
* specified version - which happens when a client reconnects).
*
* **This is rarely used**. Most stores will not implement catchup, and most
* applications will not call catchup.
*
* If this method is missing, catchup happens by calling `getOps` or `fetch`.
*/
catchup?(q: Query, fromVersion: FullVersion, opts: CatchupOpts): Promise<CatchupData<Val>>
// And potentially other helper methods and stuff.
// [k: string]: any
}
// We'll peel & export the function types back out of store to make it easy to refer to
// these types separately from stores.
export type FetchFn<Val> = Store<Val>['fetch']
export type CatchupFn<Val> = NonNullable<Store<Val>['catchup']>
export type GetOpsFn<Val> = Store<Val>['getOps']
export type SubscribeFn<Val> = Store<Val>['subscribe']
export type MutateFn<Val> = Store<Val>['mutate']
// This is a pretty standard OT type.
export interface Type<Snap, Op> {
name: string,
create(data?: any): Snap
apply(snapshot: Snap, op: Op): Snap
applyMut?(snapshot: Snap, op: Op): void
checkOp?(op: Op, snapshot: Snap): void // Check the op is valid and can apply to the given snapshot
// For core OT types:
// Not sure if transform should be optional. TODO.
transform?(op1: Op, op2: Op, side: 'left' | 'right'): Op,
// And transform cursor and stuff.
compose?(op1: Op, op2: Op): Op,
snapToJSON?(data: Snap): any,
snapFromJSON?(data: any): Snap,
opToJSON?(data: Op): any,
opFromJSON?(data: any): Op,
[p: string]: any
}
export type AnyOTType = Type<any, any>
// Basically, the replace section of catchup data.
export type CatchupReplace<Val, Q extends ReplaceQuery, R extends ReplaceData<Val>> = {q: Q, with: R}
export interface QueryOps<Q> {
// I want Val to be an associated type. I've been spoiled with rust...
type: QueryType
// createEmpty(q?: Q): Q
toJSON(q: Q): any
fromJSON(data: any): Q
mapKeys?(q: Q, fn: (k: Key, i: number) => Key | null): Q
/**
* Adapt the specified transaction (of the expected type) to the passed in
* query. If the transaction doesn't match any part of the query, returns
* null.
*/
adaptTxn<Val>(txn: Txn<Val>, query: QueryData): Txn<Val> | null
// a must be after b. Consumes a and b. Returns result.
composeCR<Val>(a: CatchupReplace<Val, any, any>, b: CatchupReplace<Val, any, any>): CatchupReplace<Val, any, any>
// Convert a fetch into a catchup replace object.
fetchToReplace<Val>(q: Q, data: ResultData<Val>): CatchupReplace<Val, any, any>
// Consumes q and snapshot
updateQuery(q: Q | null, op: ReplaceQueryData): Q
resultType: ResultOps<any, any, any> // For some reason ResultOps<any, Txn<any>> errors
}
// This would be nicer with Rust's associated types.
export interface ResultOps<Val, R, T> extends Type<R, T> {
type?: ResultType
// name: ResultType
compose(op1: T, op2: T): T
composeMut?(op1: T, op2: T): void
// Compose two consecutive result objects. Returns dest
composeResultsMut(dest: R, src: R): R
// Copy all items from src into dest. Returns dest.
copyInto?(dest: R, src: R): R
// Ughhhh the order of arguments here is so awkward.
mapEntries<Val>(snap: R, fn: (k: Key | null, v: Val) => [Key | null, Val] | null): R
mapEntriesAsync<Val>(snap: R, fn: (k: Key | null, v: Val) => Promise<[Key | null, Val] | null>): Promise<R>
map<In, Out>(snap: R, fn: (v: In, k: Key | null) => Out): R
mapAsync<In, Out>(snap: R, fn: (v: In, k: Key | null) => Promise<Out>): Promise<R>
mapTxn<In, Out>(op: Txn<In>, fn: (v: Op<In>, k: Key | null) => Op<Out>): Txn<Out>
mapTxnAsync<In, Out>(op: Txn<In>, fn: (v: Op<In>, k: Key | null) => Promise<Op<Out>>): Promise<Txn<Out>>
// TODO: Add another generic parameter for snap here. Its a ReplaceData object.
mapReplace<In, Out>(snap: any, fn: (v: In, k: Key | null) => Out): any
// These are compulsory.
snapToJSON(data: R): any
snapFromJSON(data: any): R
opToJSON(data: T): any
opFromJSON(data: any): T
// from(type: ResultType, snap: ResultData): R
getCorrespondingQuery(snap: R): Query
// Replace fancy types with {set} if they're not supported.
filterSupportedOps(T: T, values: R, supportedTypes: Set<string>): T
updateResults<Val>(snapshot: ResultData<Val>, q: ReplaceQuery, data: ReplaceData<Val>): ResultData<Val>
// TODO: replace.
}