@dxos/echo 0.16.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (176) hide show
  1. package/dist/lib/Annotation.mjs +2 -2
  2. package/dist/lib/Database.mjs +1 -1
  3. package/dist/lib/Error.mjs +1 -1
  4. package/dist/lib/Feed.mjs +1 -1
  5. package/dist/lib/Format.mjs +2 -2
  6. package/dist/lib/Migration.mjs +1 -1
  7. package/dist/lib/chunk-Annotation.mjs +14 -11
  8. package/dist/lib/chunk-Annotation.mjs.map +1 -1
  9. package/dist/lib/chunk-Blob.mjs +1 -1
  10. package/dist/lib/chunk-Collection.mjs +1 -1
  11. package/dist/lib/chunk-Database.mjs +93 -7
  12. package/dist/lib/chunk-Database.mjs.map +1 -1
  13. package/dist/lib/chunk-Dataset.mjs +1 -1
  14. package/dist/lib/chunk-Entity.mjs +2 -2
  15. package/dist/lib/chunk-Entity.mjs.map +1 -1
  16. package/dist/lib/chunk-Error.mjs +13 -1
  17. package/dist/lib/chunk-Error.mjs.map +1 -1
  18. package/dist/lib/chunk-Feed.mjs +311 -17
  19. package/dist/lib/chunk-Feed.mjs.map +1 -1
  20. package/dist/lib/chunk-Filter.mjs +4 -3
  21. package/dist/lib/chunk-Filter.mjs.map +1 -1
  22. package/dist/lib/chunk-Format.mjs +2 -1
  23. package/dist/lib/chunk-Hypergraph.mjs +1 -1
  24. package/dist/lib/chunk-Hypergraph.mjs.map +1 -1
  25. package/dist/lib/chunk-Migration.mjs +155 -5
  26. package/dist/lib/chunk-Migration.mjs.map +1 -1
  27. package/dist/lib/chunk-Obj.mjs +12 -5
  28. package/dist/lib/chunk-Obj.mjs.map +1 -1
  29. package/dist/lib/chunk-Query.mjs +2 -2
  30. package/dist/lib/chunk-QueryResult.mjs.map +1 -1
  31. package/dist/lib/chunk-Ref2.mjs +2 -2
  32. package/dist/lib/chunk-Registry.mjs +1 -1
  33. package/dist/lib/chunk-Registry.mjs.map +1 -1
  34. package/dist/lib/chunk-Relation.mjs +5 -5
  35. package/dist/lib/chunk-Relation.mjs.map +1 -1
  36. package/dist/lib/chunk-Scope.mjs +16 -2
  37. package/dist/lib/chunk-Scope.mjs.map +1 -1
  38. package/dist/lib/chunk-Tag.mjs +4 -4
  39. package/dist/lib/chunk-Tag.mjs.map +1 -1
  40. package/dist/lib/chunk-Text.mjs +2 -2
  41. package/dist/lib/chunk-Type.mjs +26 -7
  42. package/dist/lib/chunk-Type.mjs.map +1 -1
  43. package/dist/lib/chunk-View.mjs +1 -1
  44. package/dist/lib/chunk-atom-snapshot.mjs +29 -1
  45. package/dist/lib/chunk-atom-snapshot.mjs.map +1 -1
  46. package/dist/lib/chunk-entity-dictionary.mjs +28 -19
  47. package/dist/lib/chunk-entity-dictionary.mjs.map +1 -1
  48. package/dist/lib/chunk-internal.mjs +231 -79
  49. package/dist/lib/chunk-internal.mjs.map +1 -1
  50. package/dist/lib/chunk-json-schema.mjs +1 -1
  51. package/dist/lib/chunk-ref.mjs +38 -34
  52. package/dist/lib/chunk-ref.mjs.map +1 -1
  53. package/dist/lib/chunk-select.mjs +7 -3
  54. package/dist/lib/chunk-select.mjs.map +1 -1
  55. package/dist/lib/index.mjs +2 -2
  56. package/dist/lib/internal.mjs +6 -6
  57. package/dist/lib/testing.mjs +2 -2
  58. package/dist/lib/testing.mjs.map +1 -1
  59. package/dist/types/src/Annotation.d.ts +1 -1
  60. package/dist/types/src/Annotation.d.ts.map +1 -1
  61. package/dist/types/src/Database.d.ts +30 -13
  62. package/dist/types/src/Database.d.ts.map +1 -1
  63. package/dist/types/src/Entity.d.ts +3 -4
  64. package/dist/types/src/Entity.d.ts.map +1 -1
  65. package/dist/types/src/Error.d.ts +36 -0
  66. package/dist/types/src/Error.d.ts.map +1 -1
  67. package/dist/types/src/Feed.d.ts +261 -18
  68. package/dist/types/src/Feed.d.ts.map +1 -1
  69. package/dist/types/src/Filter.d.ts +7 -1
  70. package/dist/types/src/Filter.d.ts.map +1 -1
  71. package/dist/types/src/Hypergraph.d.ts +1 -1
  72. package/dist/types/src/Migration.d.ts +213 -2
  73. package/dist/types/src/Migration.d.ts.map +1 -1
  74. package/dist/types/src/Migration.test.d.ts +2 -0
  75. package/dist/types/src/Migration.test.d.ts.map +1 -0
  76. package/dist/types/src/Obj.d.ts +4 -4
  77. package/dist/types/src/Obj.d.ts.map +1 -1
  78. package/dist/types/src/QueryResult.d.ts +16 -0
  79. package/dist/types/src/QueryResult.d.ts.map +1 -1
  80. package/dist/types/src/Relation.d.ts +3 -4
  81. package/dist/types/src/Relation.d.ts.map +1 -1
  82. package/dist/types/src/Scope.d.ts +32 -1
  83. package/dist/types/src/Scope.d.ts.map +1 -1
  84. package/dist/types/src/Tag.d.ts.map +1 -1
  85. package/dist/types/src/Type.d.ts +27 -2
  86. package/dist/types/src/Type.d.ts.map +1 -1
  87. package/dist/types/src/internal/Annotation/annotations.d.ts +35 -1
  88. package/dist/types/src/internal/Annotation/annotations.d.ts.map +1 -1
  89. package/dist/types/src/internal/Annotation/atoms.d.ts +2 -2
  90. package/dist/types/src/internal/Annotation/atoms.d.ts.map +1 -1
  91. package/dist/types/src/internal/Entity/api.d.ts +11 -0
  92. package/dist/types/src/internal/Entity/api.d.ts.map +1 -1
  93. package/dist/types/src/internal/Entity/model.d.ts +3 -2
  94. package/dist/types/src/internal/Entity/model.d.ts.map +1 -1
  95. package/dist/types/src/internal/Format/string.d.ts +5 -1
  96. package/dist/types/src/internal/Format/string.d.ts.map +1 -1
  97. package/dist/types/src/internal/Obj/atoms.d.ts +1 -1
  98. package/dist/types/src/internal/Obj/atoms.d.ts.map +1 -1
  99. package/dist/types/src/internal/Obj/json-serializer.d.ts.map +1 -1
  100. package/dist/types/src/internal/Query/pretty.d.ts.map +1 -1
  101. package/dist/types/src/internal/Ref/ref.d.ts +5 -1
  102. package/dist/types/src/internal/Ref/ref.d.ts.map +1 -1
  103. package/dist/types/src/internal/Ref/strong-deps.d.ts +3 -1
  104. package/dist/types/src/internal/Ref/strong-deps.d.ts.map +1 -1
  105. package/dist/types/src/internal/common/api/meta.d.ts +4 -5
  106. package/dist/types/src/internal/common/api/meta.d.ts.map +1 -1
  107. package/dist/types/src/internal/common/atom-snapshot.d.ts +10 -0
  108. package/dist/types/src/internal/common/atom-snapshot.d.ts.map +1 -1
  109. package/dist/types/src/internal/common/proxy/change-context.d.ts +4 -0
  110. package/dist/types/src/internal/common/proxy/change-context.d.ts.map +1 -1
  111. package/dist/types/src/internal/common/proxy/ownership.d.ts +5 -0
  112. package/dist/types/src/internal/common/proxy/ownership.d.ts.map +1 -1
  113. package/dist/types/src/internal/common/proxy/proxy-utils.d.ts.map +1 -1
  114. package/dist/types/src/internal/common/proxy/schema-validator.d.ts +17 -2
  115. package/dist/types/src/internal/common/proxy/schema-validator.d.ts.map +1 -1
  116. package/dist/types/src/internal/common/proxy/symbols.d.ts +10 -0
  117. package/dist/types/src/internal/common/proxy/symbols.d.ts.map +1 -1
  118. package/dist/types/src/internal/common/proxy/typed-handler.d.ts +0 -1
  119. package/dist/types/src/internal/common/proxy/typed-handler.d.ts.map +1 -1
  120. package/dist/types/src/internal/common/types/meta.d.ts +8 -4
  121. package/dist/types/src/internal/common/types/meta.d.ts.map +1 -1
  122. package/dist/types/src/internal/common/types/model-symbols.d.ts +6 -0
  123. package/dist/types/src/internal/common/types/model-symbols.d.ts.map +1 -1
  124. package/dist/types/src/internal/index.d.ts.map +1 -1
  125. package/dist/types/tsconfig.tsbuildinfo +1 -1
  126. package/package.json +19 -15
  127. package/src/Annotation.test.ts +34 -0
  128. package/src/Annotation.ts +3 -0
  129. package/src/Database.ts +46 -15
  130. package/src/Entity.ts +3 -4
  131. package/src/Error.ts +9 -0
  132. package/src/Feed.test.ts +160 -0
  133. package/src/Feed.ts +412 -29
  134. package/src/Filter.ts +8 -1
  135. package/src/Hypergraph.ts +1 -1
  136. package/src/Migration.test.ts +137 -0
  137. package/src/Migration.ts +376 -4
  138. package/src/Obj.test.ts +44 -4
  139. package/src/Obj.ts +19 -5
  140. package/src/QueryResult.ts +14 -0
  141. package/src/Relation.ts +3 -4
  142. package/src/Scope.ts +43 -1
  143. package/src/Tag.md +5 -6
  144. package/src/Tag.ts +3 -2
  145. package/src/Type.test.ts +52 -0
  146. package/src/Type.ts +75 -22
  147. package/src/Type.tst.ts +155 -0
  148. package/src/internal/Annotation/annotations.test.ts +19 -0
  149. package/src/internal/Annotation/annotations.ts +67 -1
  150. package/src/internal/Annotation/atoms.ts +10 -9
  151. package/src/internal/Entity/api.ts +20 -1
  152. package/src/internal/Entity/model.ts +3 -0
  153. package/src/internal/Filter/match.ts +2 -2
  154. package/src/internal/Format/string.ts +7 -2
  155. package/src/internal/JsonSchema/json-schema.test.ts +2 -2
  156. package/src/internal/Obj/atoms.ts +9 -5
  157. package/src/internal/Obj/json-serializer.test.ts +34 -7
  158. package/src/internal/Obj/json-serializer.ts +18 -3
  159. package/src/internal/Query/pretty.ts +3 -2
  160. package/src/internal/Ref/ref.test.ts +27 -2
  161. package/src/internal/Ref/ref.ts +18 -2
  162. package/src/internal/Ref/strong-deps.ts +21 -2
  163. package/src/internal/common/api/meta.ts +7 -8
  164. package/src/internal/common/atom-snapshot.ts +61 -0
  165. package/src/internal/common/proxy/change-context.ts +5 -0
  166. package/src/internal/common/proxy/change.test.ts +62 -31
  167. package/src/internal/common/proxy/json-serializer.ts +3 -2
  168. package/src/internal/common/proxy/ownership.ts +14 -1
  169. package/src/internal/common/proxy/proxy-utils.ts +7 -1
  170. package/src/internal/common/proxy/schema-validator.ts +116 -27
  171. package/src/internal/common/proxy/symbols.ts +12 -0
  172. package/src/internal/common/proxy/typed-handler.test.ts +43 -0
  173. package/src/internal/common/proxy/typed-handler.ts +105 -33
  174. package/src/internal/common/types/meta.ts +25 -20
  175. package/src/internal/common/types/model-symbols.ts +7 -0
  176. package/src/internal/index.ts +1 -2
package/src/Feed.ts CHANGED
@@ -5,26 +5,81 @@
5
5
  // @import-as-namespace
6
6
 
7
7
  import * as Context from 'effect/Context';
8
+ import * as Duration from 'effect/Duration';
8
9
  import * as Effect from 'effect/Effect';
9
10
  import * as Function from 'effect/Function';
10
11
  import * as Layer from 'effect/Layer';
12
+ import * as Option from 'effect/Option';
11
13
  import * as Schema from 'effect/Schema';
12
14
 
13
- import { KEY_QUEUE_POSITION } from '@dxos/echo-protocol';
15
+ import { KEY_FEED_BLOCK, KEY_FEED_BRANCH, KEY_FEED_FORK, KEY_FEED_PREV, KEY_QUEUE_POSITION } from '@dxos/echo-protocol';
14
16
  import { invariant } from '@dxos/invariant';
15
17
  import { DXN, EID, EntityId } from '@dxos/keys';
16
18
 
17
19
  import * as Annotation from './Annotation.ts';
18
20
  import * as Database from './Database.ts';
19
21
  import type * as Entity from './Entity.ts';
20
- import type * as Filter from './Filter.ts';
22
+ import * as Filter from './Filter.ts';
21
23
  import * as internal from './internal/index.ts';
22
24
  import * as Obj from './Obj.ts';
25
+ import * as Order from './Order.ts';
23
26
  import * as Query from './Query.ts';
24
27
  import type * as QueryResult from './QueryResult.ts';
25
28
  import * as Scope from './Scope.ts';
26
29
  import * as Type from './Type.ts';
27
30
 
31
+ //
32
+ // Options
33
+ //
34
+
35
+ /** The namespaces a feed can store its data under; `data` is the default. */
36
+ export const Namespace = Schema.Literals(['data', 'trace']);
37
+ export type Namespace = Schema.Schema.Type<typeof Namespace>;
38
+
39
+ /**
40
+ * Indexing options for a feed. Absent on a feed means indexing is enabled.
41
+ *
42
+ * A struct rather than a bare boolean so later options (which indexes to build) need no migration.
43
+ */
44
+ export const IndexingOptions = Schema.Struct({
45
+ /** When false, the feed's items are not indexed at all; there is no partial mode. */
46
+ enabled: Schema.Boolean,
47
+ /**
48
+ * Which branches the index holds: `main` (the default) or `all`. There is no selected subset.
49
+ * A feed whose items mutate objects keeps `main`; a feed of messages from people can index `all`.
50
+ */
51
+ mode: Schema.optional(Schema.Literals(['all', 'main'])),
52
+ });
53
+ export type IndexingOptions = Schema.Schema.Type<typeof IndexingOptions>;
54
+
55
+ /**
56
+ * Retention options for a feed. With both limits set, an item is dropped when it breaks either;
57
+ * an empty struct (or no `retention` on the feed) trims nothing.
58
+ *
59
+ * Live feed objects persist every `Obj.update` as a whole-object re-append, so superseded blocks are
60
+ * trimmed by these limits like any other block; retention does not compact them.
61
+ */
62
+ export const RetentionOptions = Schema.Struct({
63
+ /** Maximum number of items kept; the oldest beyond it are dropped. */
64
+ maxLength: Schema.Int.pipe(Schema.check(Schema.isGreaterThanOrEqualTo(1)), Schema.optional),
65
+
66
+ /**
67
+ * Maximum age of an item in milliseconds, measured from its append timestamp.
68
+ * Milliseconds rather than a `Duration` because ECHO stores plain JSON; {@link setRetention} converts.
69
+ */
70
+ maxAge: Schema.Finite.pipe(Schema.check(Schema.isGreaterThan(0)), Schema.optional),
71
+ });
72
+ export type RetentionOptions = Schema.Schema.Type<typeof RetentionOptions>;
73
+
74
+ /**
75
+ * A feed's indexing and retention options, as the indexer carries them down to the feed store.
76
+ */
77
+ export const FeedOptions = Schema.Struct({
78
+ indexing: Schema.optional(IndexingOptions),
79
+ retention: Schema.optional(RetentionOptions),
80
+ });
81
+ export type FeedOptions = Schema.Schema.Type<typeof FeedOptions>;
82
+
28
83
  /**
29
84
  * Runtime schema for a Feed object.
30
85
  *
@@ -47,7 +102,7 @@ export class Feed extends Type.makeObject<Feed>(DXN.make('org.dxos.type.feed', '
47
102
  * - `data`: Data feed (default).
48
103
  * - `trace`: Trace feed.
49
104
  */
50
- namespace: Schema.optional(Schema.Literals(['data', 'trace'])),
105
+ namespace: Schema.optional(Namespace),
51
106
 
52
107
  /**
53
108
  * Earliest item a pending rewind discards — set when a soft fork is decided but not yet expressed,
@@ -62,6 +117,12 @@ export class Feed extends Type.makeObject<Feed>(DXN.make('org.dxos.type.feed', '
62
117
  * order relative to the blocks.
63
118
  */
64
119
  rewindFrom: Schema.optional(Obj.ID.pipe(internal.FormInputAnnotation.set(false))),
120
+
121
+ /** Indexing options; absent means indexing is enabled. Set with {@link setIndexing}. */
122
+ indexing: IndexingOptions.pipe(internal.FormInputAnnotation.set(false), Schema.optional),
123
+
124
+ /** Retention options; absent means nothing is trimmed. Set with {@link setRetention}. */
125
+ retention: RetentionOptions.pipe(internal.FormInputAnnotation.set(false), Schema.optional),
65
126
  }).pipe(Annotation.IconAnnotation.set({ icon: 'ph--rows--regular', hue: 'yellow' })),
66
127
  ) {}
67
128
 
@@ -103,18 +164,13 @@ export const CursorAnnotation: Annotation.Annotation<Cursor> = Annotation.make({
103
164
  export const START: Cursor = Cursor.make('');
104
165
 
105
166
  /**
106
- * Retention options for a feed.
107
- *
108
- * Live feed objects persist every `Obj.update` as a whole-object re-append reusing the object's id
109
- * (see `EchoFeedCodec.encode`), so superseded blocks accumulate indefinitely — retention/compaction
110
- * of those superseded blocks (driven by these options, once implemented) is the reclaim mechanism.
111
- * TODO(wittjosiah): Implement when feed retention is supported (see `setRetention` below and
112
- * `FeedStore.appendLocal`).
167
+ * Input to {@link setRetention}: {@link RetentionOptions} with `maxAge` as any Duration input.
113
168
  */
114
- export interface RetentionOptions {
115
- /** Retain items after this cursor position. */
116
- // TODO(wittjosiah): Use FeedCursor from @dxos/feed?
117
- cursor?: string;
169
+ export interface SetRetentionOptions {
170
+ /** Maximum number of items kept; an integer of at least 1. */
171
+ maxLength?: number;
172
+ /** Maximum age of an item, measured from its append timestamp; must be positive and finite. */
173
+ maxAge?: Duration.Input;
118
174
  }
119
175
 
120
176
  /**
@@ -126,6 +182,51 @@ export interface AppendOptions {
126
182
  * Applies to the first item only; the rest of the batch chain implicitly in append order.
127
183
  */
128
184
  parent?: Entity.Unknown | Entity.Snapshot | EntityId;
185
+
186
+ /** The branch the appended items continue; omit for the root branch. */
187
+ branch?: BranchId;
188
+ }
189
+
190
+ /**
191
+ * Options for {@link fork}.
192
+ */
193
+ export interface ForkOptions {
194
+ /**
195
+ * The fork point: the item (at the block it was read from) or the block id that the new branch
196
+ * continues from. Its branch is the parent of the new branch.
197
+ */
198
+ at: Entity.Unknown | Entity.Snapshot | BlockId;
199
+ }
200
+
201
+ /**
202
+ * Options for {@link walk}.
203
+ */
204
+ export interface WalkOptions {
205
+ /**
206
+ * The branch the walk ends on; omit for the root branch, or for the branch of `begin` on a backward walk.
207
+ * `'all'` walks every branch of the feed in local order, each item once at its first block.
208
+ */
209
+ branch?: BranchId | null | 'all';
210
+ /** Starts after this item; read it off the last item of a page with {@link getLocalCursor}. */
211
+ begin?: LocalCursor;
212
+ /** Also gives the base item of each branch that forks at a block the walk gives. */
213
+ forks?: boolean;
214
+ /** `asc` walks from the root base to the branch; `desc` walks back to the root base. Defaults to `asc`. */
215
+ order?: 'asc' | 'desc';
216
+ /** The page size. */
217
+ limit?: number;
218
+ }
219
+
220
+ /**
221
+ * Options for {@link query}.
222
+ */
223
+ export interface QueryOptions {
224
+ /**
225
+ * Branches to read: branch ids, `null` for the main branch, or `'all'`. Defaults to the main branch only,
226
+ * so a private branch never reaches a reader that did not ask for it. Read a branch's ancestors with
227
+ * `'all'` (or the branches on its path) and pass the items to {@link readBranch}.
228
+ */
229
+ branches?: Scope.FeedScopeOptions['branches'];
129
230
  }
130
231
 
131
232
  /**
@@ -257,6 +358,10 @@ export const append = (
257
358
  if (options?.parent !== undefined && items.length > 0) {
258
359
  setParent(items[0], options.parent);
259
360
  }
361
+ if (options?.branch !== undefined) {
362
+ const branch = options.branch;
363
+ items.forEach((item) => internal.change(item, (mutable) => setBranchKey(mutable, branch)));
364
+ }
260
365
  return db.appendToFeed(feed, items, { origin });
261
366
  }),
262
367
  ),
@@ -284,6 +389,7 @@ export const remove = (
284
389
  db.removeFeedItemsByIds(
285
390
  feed,
286
391
  items.map((item) => item.id),
392
+ { branches: items.map((item) => getBranch(item) ?? null) },
287
393
  ),
288
394
  ),
289
395
  ),
@@ -449,6 +555,226 @@ export const history = <T extends Entity.Unknown | Entity.Snapshot>(
449
555
  return { items: reachable.reverse(), shallow };
450
556
  };
451
557
 
558
+ //
559
+ // Branches
560
+ //
561
+
562
+ /**
563
+ * The id of a branch: the block id (`<sequence>@<actorId>`) of the base block of the branch, as an
564
+ * opaque string. The root branch has no id; scopes and the index name it `null`.
565
+ */
566
+ export const BranchId = Schema.String.pipe(Schema.brand('@dxos/echo/Feed/BranchId'));
567
+ export type BranchId = Schema.Schema.Type<typeof BranchId>;
568
+
569
+ /** The id of a block within its feed, `<sequence>@<actorId>`. */
570
+ export type BlockId = string;
571
+
572
+ /**
573
+ * The foreign-key sources a store stamps on an item from the block it was read from: its block id, its
574
+ * branch, its fork flag (as the fork point) and its predecessor. A copy of the item into another feed
575
+ * drops them, since that feed has none of those blocks or branches.
576
+ */
577
+ export const BLOCK_KEYS: readonly string[] = [KEY_FEED_BLOCK, KEY_FEED_BRANCH, KEY_FEED_FORK, KEY_FEED_PREV];
578
+
579
+ /**
580
+ * The position of a walk on one device: the branch the walk is on and the last block it gave. Read it
581
+ * off an item with {@link getLocalCursor}; another device cannot use it.
582
+ */
583
+ export const LocalCursor = Schema.String.pipe(Schema.brand('@dxos/echo/Feed/LocalCursor'));
584
+ export type LocalCursor = Schema.Schema.Type<typeof LocalCursor>;
585
+
586
+ // A live object this client wrote carries the keys of its latest block hidden, so they never notify.
587
+ const keyOf = (item: Entity.Unknown | Entity.Snapshot, source: string): string | undefined =>
588
+ (internal.getFeedBlockKeys(item) ?? internal.getKeys(item, source)).find((key) => key.source === source)?.id;
589
+
590
+ /** Writes the branch key into an open change, so a caller can batch it with its other writes. */
591
+ const setBranchKey = (mutable: Entity.Mutable<Entity.Unknown>, branch: BranchId): void => {
592
+ internal.deleteKeys(mutable, KEY_FEED_BRANCH);
593
+ internal.getMetaChecked(mutable).keys.push(internal.foreignKey(KEY_FEED_BRANCH, branch));
594
+ };
595
+
596
+ /**
597
+ * The foreign key that puts an item on `branch`, for an item built with it in its meta (`Obj.make(…, { [Obj.Meta]: {
598
+ * keys: [Feed.branchKey(branch)] } })`); cheaper than {@link setBranch}, which opens a change on an item made without it.
599
+ *
600
+ * @performance O(1).
601
+ */
602
+ export const branchKey = (branch: BranchId): { readonly source: string; readonly id: string } => ({
603
+ source: KEY_FEED_BRANCH,
604
+ id: branch,
605
+ });
606
+
607
+ /**
608
+ * Puts an item on a branch: a later {@link append} of it continues `branch`, so items for several
609
+ * branches can be built before they are written. Must be called within an `Obj.update` callback.
610
+ *
611
+ * @performance O(k) in the item foreign-key count.
612
+ */
613
+ export const setBranch = (mutable: Entity.Mutable<Entity.Unknown>, branch: BranchId): void =>
614
+ setBranchKey(mutable, branch);
615
+
616
+ /**
617
+ * The branch of an item, as the store inferred it from the block the item was read from; `undefined`
618
+ * on the root branch.
619
+ *
620
+ * @performance O(k) in the item foreign-key count.
621
+ */
622
+ export const getBranch = (item: Entity.Unknown | Entity.Snapshot): BranchId | undefined => {
623
+ const branch = keyOf(item, KEY_FEED_BRANCH);
624
+ return branch === undefined ? undefined : BranchId.make(branch);
625
+ };
626
+
627
+ /**
628
+ * True when the item was read from the base block of a branch: its fork flag is set, and its
629
+ * predecessor is the fork point.
630
+ *
631
+ * @performance O(k) in the item foreign-key count.
632
+ */
633
+ export const isFork = (item: Entity.Unknown | Entity.Snapshot): boolean => keyOf(item, KEY_FEED_FORK) !== undefined;
634
+
635
+ /**
636
+ * The id of the block the item was read from; `undefined` on an item the store has not echoed yet.
637
+ *
638
+ * @performance O(k) in the item foreign-key count.
639
+ */
640
+ export const getBlockId = (item: Entity.Unknown | Entity.Snapshot): BlockId | undefined => keyOf(item, KEY_FEED_BLOCK);
641
+
642
+ /**
643
+ * The id of the predecessor of the block the item was read from: the head of its branch when it was
644
+ * written, or the fork point of a base block; `undefined` on the first block of a feed.
645
+ *
646
+ * @performance O(k) in the item foreign-key count.
647
+ */
648
+ export const getPredecessor = (item: Entity.Unknown | Entity.Snapshot): BlockId | undefined =>
649
+ keyOf(item, KEY_FEED_PREV);
650
+
651
+ /**
652
+ * The cursor a walk resumes after this item; `undefined` on an item the store has not echoed yet.
653
+ *
654
+ * @performance O(k) in the item foreign-key count.
655
+ */
656
+ export const getLocalCursor = (item: Entity.Unknown | Entity.Snapshot): LocalCursor | undefined => {
657
+ const block = getBlockId(item);
658
+ return block === undefined ? undefined : LocalCursor.make(`${getBranch(item) ?? ''}|${block}`);
659
+ };
660
+
661
+ /**
662
+ * Starts a new branch: the first item is appended as the base block of the branch, with the fork
663
+ * point `at` as its predecessor, and the rest continue the branch. Returns the id of the branch, the
664
+ * block id of its base, once the base is written.
665
+ *
666
+ * @example
667
+ * ```ts
668
+ * const branch = yield* Feed.fork(feed, [reply], { at: message });
669
+ * yield* Feed.append(feed, [followUp], { branch });
670
+ * ```
671
+ *
672
+ * @performance Async; one append for the base, then one for the rest.
673
+ */
674
+ export const fork = Effect.fn('Feed.fork')(function* (
675
+ feed: Feed,
676
+ items: Entity.Unknown[],
677
+ options: ForkOptions,
678
+ ): Effect.fn.Return<BranchId, never, Database.Service> {
679
+ const { db } = yield* Database.Service;
680
+ const [base, ...rest] = items;
681
+ invariant(base !== undefined, 'fork: pass at least the base item');
682
+ const branch = yield* Effect.promise(() => db.forkFeed(feed, base, { at: options.at }));
683
+ if (rest.length > 0) {
684
+ yield* append(feed, rest, { branch });
685
+ }
686
+ return branch;
687
+ }, Database.withSpaceId);
688
+
689
+ /**
690
+ * Returns what a read of one branch sees: the items of its ancestors up to each fork point, then the
691
+ * items of the branch itself. Omit `branch` for the root branch.
692
+ *
693
+ * A feed appended as `A1, A2, A3, B1(fork at A2), A4, B2` reads `A1, A2, A3, A4` on the root branch and
694
+ * `A1, A2, B1, B2` on branch `B1`.
695
+ *
696
+ * `items` must be in **append order**, as read from the feed with `branches: 'all'`. The read is
697
+ * `shallow` when the base of a branch or its fork point is missing from `items` (a base or fork point
698
+ * that was updated is read at its latest block, which is not the one the branch names); the branch's
699
+ * own items are still returned. A walk ({@link walk}) reads blocks, so it has no such gap.
700
+ *
701
+ * @performance O(n) in items; one pass to group them and one walk up the branch's ancestors.
702
+ */
703
+ export const readBranch = <T extends Entity.Unknown | Entity.Snapshot>(
704
+ items: readonly T[],
705
+ branch?: BranchId,
706
+ ): History<T> => {
707
+ const indexByBlock = new Map<BlockId, number>();
708
+ const byBranch = new Map<BranchId | undefined, number[]>();
709
+ items.forEach((item, index) => {
710
+ const block = getBlockId(item);
711
+ if (block !== undefined) {
712
+ indexByBlock.set(block, index);
713
+ }
714
+ const key = getBranch(item);
715
+ const members = byBranch.get(key) ?? [];
716
+ members.push(index);
717
+ byBranch.set(key, members);
718
+ });
719
+
720
+ const resolve = (target: BranchId | undefined): { indices: number[]; shallow: boolean } => {
721
+ const own = byBranch.get(target) ?? [];
722
+ if (target === undefined) {
723
+ return { indices: own, shallow: false };
724
+ }
725
+ const baseIndex = indexByBlock.get(target);
726
+ const forkPoint = baseIndex === undefined ? undefined : keyOf(items[baseIndex], KEY_FEED_FORK);
727
+ // A fork point at or after the base is a cycle or a forward reference; requiring it to be strictly
728
+ // earlier also makes each step up the tree move to an earlier base, so the walk ends.
729
+ const forkIndex = forkPoint === undefined ? undefined : indexByBlock.get(forkPoint);
730
+ if (baseIndex === undefined || forkIndex === undefined || forkIndex >= baseIndex) {
731
+ return { indices: own, shallow: true };
732
+ }
733
+ const parent = resolve(getBranch(items[forkIndex]));
734
+ return { indices: [...parent.indices.filter((index) => index <= forkIndex), ...own], shallow: parent.shallow };
735
+ };
736
+
737
+ const { indices, shallow } = resolve(branch);
738
+ return { items: indices.map((index) => items[index]), shallow };
739
+ };
740
+
741
+ /**
742
+ * Walks a feed along the path from the root branch to `branch`, in local order: a wrapper of the
743
+ * walk query, which reads the same as
744
+ *
745
+ * ```ts
746
+ * Database.query(
747
+ * Query.select(Filter.and(filter, Filter.feedCursor({ begin, positions: 'local' })))
748
+ * .from(Scope.feed(feedUri, { walk: { branch, forks } }))
749
+ * .orderBy(Order.natural(order))
750
+ * .limit(limit),
751
+ * );
752
+ * ```
753
+ *
754
+ * A forward walk gives each branch on the path up to the fork point of the next; a backward walk
755
+ * goes from `begin` (or the head of `branch`) back to the root base. Each item comes once, at the place
756
+ * of its first block on the path, with the content of its latest one. Resume with {@link getLocalCursor}
757
+ * of the last item of a page.
758
+ *
759
+ * @performance O(1) to build; a page reads every block of the path.
760
+ */
761
+ export const walk = <F extends Filter.Any>(
762
+ feed: Feed,
763
+ filter: F,
764
+ options: WalkOptions = {},
765
+ ): QueryResult.QueryResultEffect<Filter.Type<F>, never, Database.Service> => {
766
+ const feedUri = getFeedUri(feed);
767
+ invariant(feedUri, 'Feed must be stored in the database before accessing its contents');
768
+ const select =
769
+ options.begin === undefined
770
+ ? filter
771
+ : Filter.and(filter, Filter.feedCursor({ begin: options.begin, positions: 'local' }));
772
+ const query = Query.select(select)
773
+ .from(Scope.feed(feedUri.toString(), { walk: { branch: options.branch, forks: options.forks } }))
774
+ .orderBy(Order.natural(options.order ?? 'asc'));
775
+ return Database.query(options.limit === undefined ? query : query.limit(options.limit));
776
+ };
777
+
452
778
  /**
453
779
  * Creates a reactive query over items in a feed.
454
780
  *
@@ -479,20 +805,32 @@ export const history = <T extends Entity.Unknown | Entity.Snapshot>(
479
805
  * @performance O(1) to build; the result is lazy, so nothing executes until read.
480
806
  */
481
807
  export const query: {
482
- <Q extends Query.Any>(feed: Feed, query: Q): QueryResult.QueryResultEffect<Query.Type<Q>, never, Database.Service>;
483
- <F extends Filter.Any>(feed: Feed, filter: F): QueryResult.QueryResultEffect<Filter.Type<F>, never, Database.Service>;
808
+ <Q extends Query.Any>(
809
+ feed: Feed,
810
+ query: Q,
811
+ options?: QueryOptions,
812
+ ): QueryResult.QueryResultEffect<Query.Type<Q>, never, Database.Service>;
813
+ <F extends Filter.Any>(
814
+ feed: Feed,
815
+ filter: F,
816
+ options?: QueryOptions,
817
+ ): QueryResult.QueryResultEffect<Filter.Type<F>, never, Database.Service>;
484
818
  <Q extends Query.Any>(
485
819
  query: Q,
486
820
  ): (feed: Feed) => QueryResult.QueryResultEffect<Query.Type<Q>, never, Database.Service>;
487
821
  <F extends Filter.Any>(
488
822
  filter: F,
489
823
  ): (feed: Feed) => QueryResult.QueryResultEffect<Filter.Type<F>, never, Database.Service>;
490
- } = Function.dual(2, (feed: Feed, queryOrFilter: Query.Any | Filter.Any) => {
491
- const feedUri = getFeedUri(feed);
492
- invariant(feedUri, 'Feed must be stored in the database before accessing its contents');
493
- const query = Query.is(queryOrFilter) ? queryOrFilter : Query.select(queryOrFilter);
494
- return Database.query(query.from(Scope.feed(feedUri.toString())));
495
- });
824
+ // Data-first takes two or three arguments; data-last takes one, so arity alone tells them apart.
825
+ } = Function.dual(
826
+ (args) => args.length >= 2,
827
+ (feed: Feed, queryOrFilter: Query.Any | Filter.Any, options?: QueryOptions) => {
828
+ const feedUri = getFeedUri(feed);
829
+ invariant(feedUri, 'Feed must be stored in the database before accessing its contents');
830
+ const query = Query.is(queryOrFilter) ? queryOrFilter : Query.select(queryOrFilter);
831
+ return Database.query(query.from(Scope.feed(feedUri.toString(), { branches: options?.branches })));
832
+ },
833
+ );
496
834
 
497
835
  /**
498
836
  * Syncs the feed with the server.
@@ -528,16 +866,61 @@ export const getSyncState = (feed: Feed): Effect.Effect<SyncState, never, Databa
528
866
  );
529
867
 
530
868
  /**
531
- * Sets the local retention policy for a feed.
532
- * Currently stubbed — feeds do not yet support retention.
869
+ * Sets the feed's indexing options on the feed object, in one change.
870
+ *
871
+ * Returns once the change is applied locally; the store stops indexing on its own index pass, which
872
+ * may run on another device.
873
+ *
874
+ * @example
875
+ * ```ts
876
+ * yield* Feed.setIndexing(feed, { enabled: false });
877
+ * ```
878
+ *
879
+ * @performance O(1); one object change.
880
+ */
881
+ export const setIndexing = (feed: Feed, options: IndexingOptions): Effect.Effect<void, Schema.SchemaError> =>
882
+ Schema.decodeUnknownEffect(IndexingOptions)(options).pipe(
883
+ Effect.map((indexing) =>
884
+ Obj.update(feed, (feed) => {
885
+ feed.indexing = indexing;
886
+ }),
887
+ ),
888
+ Effect.asVoid,
889
+ Effect.withSpan('Feed.setIndexing'),
890
+ );
891
+
892
+ /**
893
+ * Sets the feed's retention options on the feed object, in one change.
894
+ *
895
+ * Fails with the schema error, leaving the object unchanged, when `maxLength` is not an integer of
896
+ * at least 1 or `maxAge` is not a positive, finite duration. Returns once the change is applied
897
+ * locally; the store trims on its own index pass, which may run on another device.
533
898
  *
534
899
  * @example
535
900
  * ```ts
536
- * yield* Feed.setRetention(feed, { count: 1000 });
901
+ * yield* Feed.setRetention(feed, { maxLength: 1000, maxAge: Duration.days(7) });
537
902
  * ```
538
903
  *
539
- * @performance O(1); currently a no-op.
904
+ * @performance O(1); one object change.
540
905
  */
541
- // TODO(dmaretskyi): Implement when feed retention is supported.
542
- export const setRetention = (_feed: Feed, _options: RetentionOptions): Effect.Effect<void, never, Database.Service> =>
543
- Effect.void;
906
+ export const setRetention = (feed: Feed, options: SetRetentionOptions): Effect.Effect<void, Schema.SchemaError> =>
907
+ Schema.decodeUnknownEffect(RetentionOptions)({
908
+ // Keys are omitted rather than set to undefined, which ECHO does not store.
909
+ ...(options.maxLength !== undefined ? { maxLength: options.maxLength } : {}),
910
+ ...(options.maxAge !== undefined ? { maxAge: durationToMillis(options.maxAge) } : {}),
911
+ }).pipe(
912
+ Effect.map((retention) =>
913
+ Obj.update(feed, (feed) => {
914
+ feed.retention = retention;
915
+ }),
916
+ ),
917
+ Effect.asVoid,
918
+ Effect.withSpan('Feed.setRetention'),
919
+ );
920
+
921
+ /** An unparseable duration maps to NaN so the schema, not this conversion, reports it. */
922
+ const durationToMillis = (input: Duration.Input): number =>
923
+ Duration.fromInput(input).pipe(
924
+ Option.map(Duration.toMillis),
925
+ Option.getOrElse(() => Number.NaN),
926
+ );
package/src/Filter.ts CHANGED
@@ -505,9 +505,15 @@ export const created = (range: TimeRange): Any => _timeRangeFilter('createdAt',
505
505
  */
506
506
  export type FeedCursorRange = {
507
507
  /** Read after this cursor. Defaults to the start of the feed ({@link Feed.START}). */
508
- begin?: Feed.Cursor;
508
+ begin?: Feed.Cursor | Feed.LocalCursor;
509
509
  /** Read up to but not including this cursor. Defaults to the end of the feed. */
510
510
  end?: Feed.Cursor;
511
+ /**
512
+ * The order the cursors are positions in: `edge`, the position the authority assigned
513
+ * ({@link Feed.getCursor}), or `local`, a walk's local cursor ({@link Feed.getLocalCursor}).
514
+ * Defaults to `local` in a walk scope and `edge` elsewhere.
515
+ */
516
+ positions?: 'local' | 'edge';
511
517
  };
512
518
 
513
519
  /**
@@ -537,6 +543,7 @@ export const feedCursor = (range: FeedCursorRange = {}): Any =>
537
543
  type: 'feed-cursor',
538
544
  ...(range.begin !== undefined ? { begin: range.begin } : {}),
539
545
  ...(range.end !== undefined ? { end: range.end } : {}),
546
+ ...(range.positions !== undefined ? { positions: range.positions } : {}),
540
547
  });
541
548
 
542
549
  export type ChildOfOptions = {
package/src/Hypergraph.ts CHANGED
@@ -49,7 +49,7 @@ export interface Hypergraph extends Database.Queryable {
49
49
  /**
50
50
  * In-process registry of keyed objects and static schema types.
51
51
  * Populated at startup via `registry.add(objects)` / `registry.add(schemas)`.
52
- * Queries that include no explicit from() clause will fan out to this registry automatically.
52
+ * A query reads this registry only when its from() clause names `Scope.registry()`.
53
53
  */
54
54
  get registry(): Registry.Registry;
55
55