@elaraai/e3-types 1.0.104 → 1.0.106

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.
@@ -25,7 +25,7 @@ import {
25
25
  encodeBeast2PagedFor,
26
26
  sha256Hex,
27
27
  } from '@elaraai/east';
28
- import { encodeDatasetBlob, writeCollectionManifest, type CollectionSegmentRef } from './dataset-blob.js';
28
+ import { encodeDatasetBlob, writeCollectionManifest, type CollectionSegmentRef, type SegmentSink } from './dataset-blob.js';
29
29
 
30
30
  const TableType = DictType(StringType, IntegerType);
31
31
 
@@ -36,29 +36,32 @@ function rowsOf(n: number): SortedMap<string, bigint> {
36
36
  compareFor(StringType));
37
37
  }
38
38
 
39
- /** A write the test ends, as the store would: stored, or failed. */
40
- interface HeldWrite {
41
- hash: string;
39
+ /** A sink that stores nothing, and answers each object's hash. */
40
+ const hashing: SegmentSink = (batch) => Promise.resolve(batch.map((bytes) => sha256Hex(bytes)));
41
+
42
+ /** A batch the test ends, as the store would: stored, or failed. */
43
+ interface HeldBatch {
44
+ hashes: string[];
42
45
  end: (failure?: Error) => void;
43
46
  }
44
47
 
45
- /** A sink whose writes are held until the test ends each one: the writes in
46
- * flight, and the hash of every object it was handed, in order. */
47
- function heldSink(): { sink: (bytes: Uint8Array) => Promise<string>; open: HeldWrite[]; calls: string[] } {
48
- const open: HeldWrite[] = [];
49
- const calls: string[] = [];
50
- const sink = (bytes: Uint8Array): Promise<string> => new Promise((resolve, reject) => {
51
- const hash = sha256Hex(bytes);
52
- calls.push(hash);
53
- const write: HeldWrite = {
54
- hash,
48
+ /** A sink whose batches are held until the test ends each one: the batches in
49
+ * flight, and the hashes of every batch it was handed, in order. */
50
+ function heldSink(): { sink: SegmentSink; open: HeldBatch[]; calls: string[][] } {
51
+ const open: HeldBatch[] = [];
52
+ const calls: string[][] = [];
53
+ const sink: SegmentSink = (batch) => new Promise((resolve, reject) => {
54
+ const hashes = batch.map((bytes) => sha256Hex(bytes));
55
+ calls.push(hashes);
56
+ const held: HeldBatch = {
57
+ hashes,
55
58
  end: (failure) => {
56
- open.splice(open.indexOf(write), 1);
57
- if (failure === undefined) resolve(hash);
59
+ open.splice(open.indexOf(held), 1);
60
+ if (failure === undefined) resolve(hashes);
58
61
  else reject(failure);
59
62
  },
60
63
  };
61
- open.push(write);
64
+ open.push(held);
62
65
  });
63
66
  return { sink, open, calls };
64
67
  }
@@ -83,11 +86,11 @@ describe('writeCollectionManifest', () => {
83
86
  Array.from({ length: 20_000 }, (_, i): [string, bigint] => [`k${String(i).padStart(6, '0')}`, BigInt(i)]),
84
87
  compareFor(StringType));
85
88
  const objects = new Map<string, Uint8Array>();
86
- const manifest = await writeCollectionManifest(TableType, [{ elements: value.entries() }], async (bytes) => {
89
+ const manifest = await writeCollectionManifest(TableType, [{ elements: value.entries() }], async (batch) => batch.map((bytes) => {
87
90
  const hash = sha256Hex(bytes);
88
91
  objects.set(hash, bytes);
89
92
  return hash;
90
- });
93
+ }));
91
94
 
92
95
  const expectedObjects = new Map<string, Uint8Array>();
93
96
  let expected: Uint8Array | undefined;
@@ -108,11 +111,11 @@ describe('writeCollectionManifest', () => {
108
111
  Array.from({ length: 20_000 }, (_, i): [string, bigint] => [`k${String(i).padStart(6, '0')}`, BigInt(i)]),
109
112
  compareFor(StringType));
110
113
  const objects = new Map<string, Uint8Array>();
111
- const sink = async (bytes: Uint8Array): Promise<string> => {
114
+ const sink: SegmentSink = async (batch) => batch.map((bytes) => {
112
115
  const hash = sha256Hex(bytes);
113
116
  objects.set(hash, bytes);
114
117
  return hash;
115
- };
118
+ });
116
119
  const whole = await writeCollectionManifest(TableType, [{ elements: value.entries() }], sink);
117
120
  const entries = decodeCollectionManifest(whole).entries;
118
121
  const half = entries.length >> 1;
@@ -134,10 +137,10 @@ describe('writeCollectionManifest', () => {
134
137
  const again = await writeCollectionManifest(TableType, [
135
138
  { segments: carried },
136
139
  { elements: value.entries(decodeBeast2FenceFor(StringType)(entries[half]!.fence) as string) },
137
- ], async (bytes) => {
138
- const hash = await sink(bytes);
139
- written.add(hash);
140
- return hash;
140
+ ], async (batch) => {
141
+ const hashes = await sink(batch);
142
+ for (const hash of hashes) written.add(hash);
143
+ return hashes;
141
144
  });
142
145
 
143
146
  assert.deepEqual(again, whole, 'the same manifest');
@@ -145,34 +148,45 @@ describe('writeCollectionManifest', () => {
145
148
  for (const entry of entries.slice(0, half)) assert.ok(!written.has(entry.hash), `segment ${entry.hash.slice(0, 8)} is carried`);
146
149
  });
147
150
 
148
- it('has the sink write the objects at once, as many as it is given, in order, and returns once every one is stored', async () => {
151
+ it('hands the sink the objects in order, in full batches, one in flight while the next is gathered, and returns once every one is stored', async () => {
149
152
  const value = rowsOf(20_000);
150
- const expected = await writeCollectionManifest(TableType, [{ elements: value.entries() }], async (bytes) => sha256Hex(bytes));
151
- const entries = decodeCollectionManifest(expected).entries;
152
- const objects = entries.length + 1;
153
+ const expected = await writeCollectionManifest(TableType, [{ elements: value.entries() }], hashing);
154
+ const { entries, header } = decodeCollectionManifest(expected);
153
155
  const { sink, open, calls } = heldSink();
154
156
  let manifest: Uint8Array | undefined;
155
- const writing = writeCollectionManifest(TableType, [{ elements: value.entries() }], sink, { inFlight: 3 })
157
+ const writing = writeCollectionManifest(TableType, [{ elements: value.entries() }], sink, { batch: 3 })
156
158
  .then((bytes) => {
157
159
  manifest = bytes;
158
160
  });
159
161
 
160
- // Each write ends only when the test ends it, the last begun first, so the
161
- // writes end in another order than they began. Between ends, the writer
162
- // has as many in flight as it may: three, or the objects left.
162
+ // Each batch is stored only when the test ends it. Between ends, one batch
163
+ // is in flight, and the writer sends the next only once it is stored.
163
164
  while (manifest === undefined) {
164
- const inFlight = (): number => Math.min(3, objects - (calls.length - open.length));
165
- await until(() => manifest !== undefined || open.length === inFlight(), 'as many writes in flight as may be');
165
+ await until(() => manifest !== undefined || open.length > 0, 'a batch in flight');
166
166
  await turns(20);
167
167
  if (manifest !== undefined) break;
168
- assert.equal(open.length, inFlight(), `${open.length} writes in flight, of ${calls.length} begun`);
169
- open.at(-1)!.end();
168
+ assert.equal(open.length, 1, `${open.length} batches in flight, of ${calls.length} sent`);
169
+ open[0]!.end();
170
170
  }
171
171
  await writing;
172
172
 
173
- assert.deepEqual(manifest, expected, 'the manifest a write at a time writes, each entry in its place');
174
- assert.deepEqual(calls, [...entries.map((entry) => entry.hash), decodeCollectionManifest(expected).header],
175
- 'the segments, in order, and then the header');
173
+ assert.deepEqual(manifest, expected, 'the manifest a write of each object writes, each entry in its place');
174
+ assert.deepEqual(calls.flat(), [...entries.map((entry) => entry.hash), header], 'the segments, in order, and then the header');
175
+ assert.ok(calls.slice(0, -1).every((batch) => batch.length === 3), 'every batch but the last is full');
176
+ assert.ok(calls.at(-1)!.length <= 3, 'and the last holds what is left');
177
+ });
178
+
179
+ it('hands a collection of a few segments to the sink in one batch', async () => {
180
+ const value = rowsOf(4_000);
181
+ const { entries, header } = decodeCollectionManifest(await writeCollectionManifest(TableType, [{ elements: value.entries() }], hashing));
182
+ assert.ok(entries.length > 1, 'the value spans segments');
183
+ const calls: string[][] = [];
184
+ await writeCollectionManifest(TableType, [{ elements: value.entries() }], async (batch) => {
185
+ const hashes = await hashing(batch);
186
+ calls.push(hashes);
187
+ return hashes;
188
+ });
189
+ assert.deepEqual(calls, [[...entries.map((entry) => entry.hash), header]]);
176
190
  });
177
191
 
178
192
  /** A writer's failure, once it has failed: read through a function, which
@@ -187,57 +201,59 @@ describe('writeCollectionManifest', () => {
187
201
  return () => settled;
188
202
  }
189
203
 
190
- it('starts no write after one fails, and throws its failure once the writes in flight have ended', async () => {
204
+ it('sends no batch after one fails, and throws its failure', async () => {
191
205
  const { sink, open, calls } = heldSink();
192
- const writing = writeCollectionManifest(TableType, [{ elements: rowsOf(20_000).entries() }], sink, { inFlight: 3 });
206
+ const writing = writeCollectionManifest(TableType, [{ elements: rowsOf(20_000).entries() }], sink, { batch: 3 });
193
207
  const settled = failureOf(writing);
194
- await until(() => open.length === 3, 'three writes in flight');
195
- const failure = new Error('the store is gone');
196
- open[1]!.end(failure);
208
+ await until(() => open.length === 1, 'a batch in flight');
209
+ // The next batch gathered, waiting for this one
197
210
  await turns(20);
198
- assert.equal(calls.length, 3, 'nothing is begun after a write fails');
199
- assert.equal(settled(), undefined, 'the writer waits for the writes still in flight');
200
-
201
- for (const write of [...open]) write.end();
202
- await writing.catch(() => {});
211
+ const failure = new Error('the store is gone');
212
+ open[0]!.end(failure);
213
+ await until(() => settled() !== undefined, "the writer's end");
214
+ assert.equal(calls.length, 1, 'nothing is sent after a batch fails');
203
215
  assert.equal(settled()?.failure, failure);
204
216
  });
205
217
 
206
- it('throws a failure among the last writes, which no write after it meets', async () => {
218
+ it("throws a failure of the last batch, the header's", async () => {
207
219
  const value = rowsOf(20_000);
208
- const { header } = decodeCollectionManifest(
209
- await writeCollectionManifest(TableType, [{ elements: value.entries() }], async (bytes) => sha256Hex(bytes)));
220
+ const { header } = decodeCollectionManifest(await writeCollectionManifest(TableType, [{ elements: value.entries() }], hashing));
210
221
  const { sink, open } = heldSink();
211
- const writing = writeCollectionManifest(TableType, [{ elements: value.entries() }], sink, { inFlight: 3 });
222
+ const writing = writeCollectionManifest(TableType, [{ elements: value.entries() }], sink, { batch: 3 });
212
223
  const settled = failureOf(writing);
213
- // Every object is stored but the header, the last begun.
224
+ // Every batch is stored but the one holding the header, the last sent.
214
225
  const failure = new Error('the store is gone');
215
226
  for (;;) {
216
- await until(() => settled() !== undefined || open.length > 0, 'a write in flight, or the writer\'s end');
227
+ await until(() => settled() !== undefined || open.length > 0, 'a batch in flight, or the writer\'s end');
217
228
  if (settled() !== undefined) break;
218
- const write = open[0]!;
219
- write.end(write.hash === header ? failure : undefined);
229
+ const batch = open[0]!;
230
+ batch.end(batch.hashes.includes(header) ? failure : undefined);
220
231
  }
221
232
  assert.equal(settled()?.failure, failure);
222
233
  });
223
234
 
224
- it('throws a piece\'s failure once the writes in flight have ended', async () => {
225
- const { sink, open } = heldSink();
226
- // Rows in order, then one out of it.
235
+ it('throws a piece\'s failure once the batch in flight has ended', async () => {
236
+ // A batch larger than half the segments the rows before the one out of
237
+ // order are cut into, and no larger than they: one batch is sent, and the
238
+ // next is never full, so the row out of order is read with a batch in flight.
239
+ const segments = decodeCollectionManifest(await writeCollectionManifest(TableType, [{ elements: rowsOf(20_000).entries() }], hashing))
240
+ .entries.length;
241
+ const { sink, open, calls } = heldSink();
227
242
  let disordered = false;
228
243
  function* rows(): Generator<[string, bigint]> {
229
244
  yield* rowsOf(20_000).entries();
230
245
  disordered = true;
231
246
  yield ['a', 0n];
232
247
  }
233
- const writing = writeCollectionManifest(TableType, [{ elements: rows() }], sink, { inFlight: 64 });
248
+ const writing = writeCollectionManifest(TableType, [{ elements: rows() }], sink, { batch: (segments >> 1) + 1 });
234
249
  const settled = failureOf(writing);
235
250
  await until(() => disordered, 'the row out of order');
236
251
  await turns(20);
237
- assert.ok(open.length > 0, 'segments are in flight');
238
- assert.equal(settled(), undefined, 'the writer waits for the writes still in flight');
252
+ assert.equal(calls.length, 1, 'one batch is sent');
253
+ assert.equal(open.length, 1, 'and in flight');
254
+ assert.equal(settled(), undefined, 'the writer waits for the batch in flight');
239
255
 
240
- for (const write of [...open]) write.end();
256
+ open[0]!.end();
241
257
  await writing.catch(() => {});
242
258
  const failure = settled()?.failure;
243
259
  assert.ok(failure instanceof Error, 'the piece\'s failure');
@@ -255,9 +271,9 @@ describe('encodeDatasetBlob', () => {
255
271
  const whole = encodeBeast2For(RowType)(row);
256
272
  assert.deepEqual(encodeDatasetBlob(RowType, row), whole);
257
273
  const sunk: Uint8Array[] = [];
258
- assert.deepEqual(await encodeDatasetBlob(RowType, row, async (bytes) => {
259
- sunk.push(bytes);
260
- return sha256Hex(bytes);
274
+ assert.deepEqual(await encodeDatasetBlob(RowType, row, async (batch) => {
275
+ sunk.push(...batch);
276
+ return hashing(batch);
261
277
  }), whole, 'a sink changes nothing for a value that is not a collection');
262
278
  assert.deepEqual(sunk, []);
263
279
  });
@@ -50,67 +50,92 @@ import {
50
50
  } from './collection-manifest.js';
51
51
 
52
52
  /**
53
- * Writes one object and answers with its content hash.
53
+ * Writes a batch of objects, no one of which names another, and answers their
54
+ * content hashes in the order given.
54
55
  *
55
56
  * @remarks
56
57
  * The whole of the object store this module needs. Content-addressed, so
57
58
  * writing bytes already stored is a no-op that returns the same hash — which is
58
- * exactly how a new state shares its unchanged segments with the old one.
59
+ * exactly how a new state shares its unchanged segments with the old one. A
60
+ * store whose writes are requests sends a batch as a few (e3-core's
61
+ * `ObjectStore.writeMany`).
59
62
  */
60
- export type SegmentSink = (bytes: Uint8Array) => Promise<string>;
63
+ export type SegmentSink = (objects: readonly Uint8Array[]) => Promise<string[]>;
61
64
 
62
65
  /**
63
- * How many objects {@link writeCollectionManifest} has a sink write at once,
66
+ * The most objects {@link writeCollectionManifest} hands its sink in one batch,
64
67
  * unless its caller says otherwise: a store whose writes are round trips is
65
68
  * waited on once for this many segments, rather than once for each.
66
69
  */
67
- export const SEGMENT_WRITES_IN_FLIGHT = 16;
70
+ export const SEGMENT_WRITE_BATCH = 16;
68
71
 
69
72
  /**
70
- * The writes of one manifest's objects: each started in the order it is
71
- * handed over, at most `width` in flight, and none left running once the
72
- * manifest's writer returns.
73
+ * The writes of one manifest's objects, in batches: each object gathered in
74
+ * the order it is handed over, a batch sent once it holds `width` objects or
75
+ * the last object is handed over, one batch in flight while the next is
76
+ * gathered, and none left running once the manifest's writer returns.
73
77
  *
74
78
  * @internal
75
79
  */
76
80
  class SinkWrites {
77
- private readonly inFlight = new Set<Promise<void>>();
81
+ /** The objects gathered for the next batch, each with what it is told. */
82
+ private gathered: Array<{ bytes: Uint8Array; named: (hash: string) => void }> = [];
83
+ /** The batch in flight, which settles without throwing. */
84
+ private inFlight: Promise<void> | undefined;
78
85
  private failure: { error: unknown } | undefined;
79
86
 
80
87
  constructor(private readonly sink: SegmentSink, private readonly width: number) {}
81
88
 
82
89
  /**
83
- * Starts writing `bytes` once fewer than `width` writes are in flight.
90
+ * Gathers `bytes` for the next batch, and sends the batch once it holds
91
+ * `width` objects and the batch before it is stored.
84
92
  *
85
93
  * @param bytes - The object
86
94
  * @param named - Told the object's hash once it is stored
87
- * @throws The first failed write's error, once one has failed: nothing more
88
- * is started after it.
95
+ * @throws The failed batch's error, once one has failed: nothing more is
96
+ * sent after it.
89
97
  */
90
98
  async start(bytes: Uint8Array, named: (hash: string) => void): Promise<void> {
91
- while (this.failure === undefined && this.inFlight.size >= this.width) await Promise.race(this.inFlight);
92
99
  if (this.failure !== undefined) throw this.failure.error;
93
- const write: Promise<void> = this.sink(bytes)
94
- .then(named, (error: unknown) => {
100
+ this.gathered.push({ bytes, named });
101
+ if (this.gathered.length >= this.width) await this.send();
102
+ }
103
+
104
+ /**
105
+ * Sends the objects gathered, once the batch in flight is stored.
106
+ *
107
+ * @throws The failed batch's error, once one has failed.
108
+ */
109
+ private async send(): Promise<void> {
110
+ await this.settled();
111
+ if (this.failure !== undefined) throw this.failure.error;
112
+ const batch = this.gathered;
113
+ if (batch.length === 0) return;
114
+ this.gathered = [];
115
+ const sent: Promise<void> = this.sink(batch.map(({ bytes }) => bytes))
116
+ .then((hashes) => {
117
+ batch.forEach(({ named }, i) => named(hashes[i]!));
118
+ }, (error: unknown) => {
95
119
  this.failure ??= { error };
96
120
  })
97
121
  .finally(() => {
98
- this.inFlight.delete(write);
122
+ if (this.inFlight === sent) this.inFlight = undefined;
99
123
  });
100
- this.inFlight.add(write);
124
+ this.inFlight = sent;
101
125
  }
102
126
 
103
- /** Waits for every write started, whatever its outcome. */
127
+ /** Waits for the batch in flight, whatever its outcome. */
104
128
  async settled(): Promise<void> {
105
- await Promise.all(this.inFlight);
129
+ while (this.inFlight !== undefined) await this.inFlight;
106
130
  }
107
131
 
108
132
  /**
109
- * Waits for every write started.
133
+ * Sends what is gathered, and waits for every batch.
110
134
  *
111
- * @throws The first failed write's error.
135
+ * @throws The failed batch's error.
112
136
  */
113
137
  async stored(): Promise<void> {
138
+ await this.send();
114
139
  await this.settled();
115
140
  if (this.failure !== undefined) throw this.failure.error;
116
141
  }
@@ -163,33 +188,35 @@ export type CollectionPiece = Beast2RecutPiece<EastType, CollectionSegmentRef>;
163
188
  * Writer's own: a piece's segments are carried over only when that is the
164
189
  * header they are under, which is the caller's to establish.
165
190
  *
166
- * The objects are written at once, `inFlight` at a time — the segments in
167
- * order, then the header — and the manifest is returned once every one is
168
- * stored, so the caller stores the manifest after the objects it names. The
169
- * sink is called in segment order, and each segment's blob is held until its
170
- * write ends.
191
+ * The objects go to the sink in batches of up to `batch` — the segments in
192
+ * order, then the header — one batch in flight while the next is gathered, so
193
+ * a collection of a few segments is one batch however its pieces arrive, and
194
+ * a large one keeps a batch in flight as it is cut. A batch is sent once it is
195
+ * full, or once the header is cut, and the manifest is returned once every
196
+ * object is stored, so the caller stores the manifest after the objects it
197
+ * names. Each segment's blob is held until its batch is stored.
171
198
  *
172
199
  * @param type - The collection type (Array / Set / Dict)
173
200
  * @param pieces - The collection's pieces, in order
174
- * @param sink - Writes one object and returns its hash
175
- * @param options - `inFlight`, the most objects the sink writes at once
176
- * (default {@link SEGMENT_WRITES_IN_FLIGHT})
201
+ * @param sink - Writes a batch of objects and returns their hashes
202
+ * @param options - `batch`, the most objects the sink is handed at once
203
+ * (default {@link SEGMENT_WRITE_BATCH})
177
204
  * @returns The manifest's bytes — the caller stores them, and its hash is the
178
205
  * dataset's content address
179
206
  * @throws {Error} When a piece's elements do not ascend (Set / Dict), a
180
207
  * segment's blob is not the one segment its reference describes, or the sink
181
- * rejects: once the writes in flight have ended, so none runs on after the
208
+ * rejects: once the batch in flight has ended, so none runs on after the
182
209
  * writer returns.
183
210
  */
184
211
  export async function writeCollectionManifest(
185
212
  type: EastType | EastTypeValue,
186
213
  pieces: Iterable<CollectionPiece> | AsyncIterable<CollectionPiece>,
187
214
  sink: SegmentSink,
188
- options: { inFlight?: number } = {},
215
+ options: { batch?: number } = {},
189
216
  ): Promise<Uint8Array> {
190
217
  const typeValue = asTypeValue(type);
191
218
  const entries: CollectionManifestEntry[] = [];
192
- const writes = new SinkWrites(sink, options.inFlight ?? SEGMENT_WRITES_IN_FLIGHT);
219
+ const writes = new SinkWrites(sink, options.batch ?? SEGMENT_WRITE_BATCH);
193
220
  /** Writes a segment the manifest names at the place it takes now. */
194
221
  const write = (blob: Uint8Array, fence: Uint8Array, count: number): Promise<void> => {
195
222
  const at = entries.push({ hash: '', fence, count: BigInt(count), bytes: BigInt(blob.byteLength) }) - 1;
@@ -246,7 +273,7 @@ export async function writeCollectionManifest(
246
273
  *
247
274
  * @param type - The dataset's declared type (an `EastType` or its homoiconic value)
248
275
  * @param value - The value to encode
249
- * @param sink - Writes one object and returns its hash
276
+ * @param sink - Writes a batch of objects and returns their hashes
250
277
  * @returns The beast2 bytes to store — the manifest, for a collection written
251
278
  * through a sink; otherwise the value's own blob
252
279
  */
package/src/dataset.ts CHANGED
@@ -115,11 +115,9 @@ export type DataTreeType<T extends EastType> =
115
115
  */
116
116
  export function DataTreeType<T extends EastType>(type: T): DataTreeType<T> {
117
117
  if (type.type === "Struct") {
118
- const fields: Record<string, DataRefType> = {};
119
- for (const key of Object.keys(type.fields)) {
120
- fields[key] = DataRefType;
121
- }
122
- return StructType(fields) as DataTreeType<T>;
118
+ // The fields in the struct's order, as a list: an object would list a
119
+ // field named like an integer first (#1574)
120
+ return StructType(Object.keys(type.fields).map((key) => [key, DataRefType] as const)) as DataTreeType<T>;
123
121
  } else {
124
122
  throw new Error(`DataTreeType not implemented for type .${type.type}`);
125
123
  }
@@ -0,0 +1,137 @@
1
+ /**
2
+ * Copyright (c) 2025 Elara AI Pty Ltd
3
+ * Dual-licensed under AGPL-3.0 and commercial license. See LICENSE for details.
4
+ */
5
+
6
+ /**
7
+ * A kept function call, as a repository's call store keeps it
8
+ * (east-workspace#1554).
9
+ *
10
+ * A call of a named function through a workspace is filed when it starts,
11
+ * runs where its backend runs calls, and is kept once it ends, until the
12
+ * lifetime its end gives it; so is a one-shot started as a call, its caller's
13
+ * program run as an anonymous function. The store keeps what readers are
14
+ * shown, the call as the API answers it ({@link FunctionCallType}). Beside it,
15
+ * it keeps what the call's run needs and no reader is shown: the function
16
+ * object it runs, the runner it runs on, whether it runs verbose, its
17
+ * deadline, and a request to cancel it.
18
+ *
19
+ * It is stored state (`WIRE_MIGRATION.md`): a change to its type ships a
20
+ * repository upgrade step.
21
+ */
22
+
23
+ import {
24
+ BooleanType, DateTimeType, IntegerType, OptionType, StringType, StructType, decodeBeast2For, encodeBeast2For, type ValueTypeOf,
25
+ } from '@elaraai/east';
26
+ import { FunctionCallType } from './api.js';
27
+ import { RunnerType } from './runner.js';
28
+
29
+ /**
30
+ * A request to cancel a running call: who asked, and when.
31
+ *
32
+ * @property by - Who asked, as the host's auth names them; `none` without an
33
+ * identity
34
+ * @property at - When they asked
35
+ */
36
+ export const FunctionCallCancelType = StructType({
37
+ by: OptionType(StringType),
38
+ at: DateTimeType,
39
+ });
40
+ export type FunctionCallCancelType = typeof FunctionCallCancelType;
41
+
42
+ /** A request to cancel a running call. */
43
+ export type FunctionCallCancel = ValueTypeOf<typeof FunctionCallCancelType>;
44
+
45
+ /**
46
+ * How long a call is kept once it ends, by how it ended, in milliseconds: the
47
+ * lifetimes the host that filed it gives, which whatever records its end
48
+ * applies.
49
+ *
50
+ * @property succeeded - A call that succeeded, or was cancelled
51
+ * @property failed - A call that failed, was refused (`invalid`), returned too
52
+ * large a value, timed out, or was lost
53
+ */
54
+ export const FunctionCallKeepType = StructType({
55
+ succeeded: IntegerType,
56
+ failed: IntegerType,
57
+ });
58
+ export type FunctionCallKeepType = typeof FunctionCallKeepType;
59
+
60
+ /** How long a call is kept once it ends. */
61
+ export type FunctionCallKeep = ValueTypeOf<typeof FunctionCallKeepType>;
62
+
63
+ /**
64
+ * A kept call, as its store keeps it.
65
+ *
66
+ * @property call - The call as readers are shown it
67
+ * @property workspace - The workspace it was called through
68
+ * @property functionObject - The hash of the function object it runs: the one
69
+ * the deployed package named when it started, whatever is deployed since;
70
+ * for a one-shot call, the anonymous one its start stored, naming the
71
+ * caller's program, its types and its runner, and no inputs
72
+ * @property runner - The runner it runs on: the function's own, or one the
73
+ * call named and its caller's grant allowed; a one-shot call's own
74
+ * @property verbose - Whether a stock runner runs it with `-v`
75
+ * @property deadline - When its timeout ends: a call still recorded running
76
+ * once its deadline and a grace have passed is lost
77
+ * @property cancel - A request to cancel it, once one is made
78
+ * @property keep - How long it is kept once it ends, by how it ended
79
+ */
80
+ export const FunctionCallJobType = StructType({
81
+ call: FunctionCallType,
82
+ workspace: StringType,
83
+ functionObject: StringType,
84
+ runner: RunnerType,
85
+ verbose: BooleanType,
86
+ deadline: DateTimeType,
87
+ cancel: OptionType(FunctionCallCancelType),
88
+ keep: FunctionCallKeepType,
89
+ });
90
+ export type FunctionCallJobType = typeof FunctionCallJobType;
91
+
92
+ /** A kept call, as its store keeps it. */
93
+ export type FunctionCallJob = ValueTypeOf<typeof FunctionCallJobType>;
94
+
95
+ const encodeJob = encodeBeast2For(FunctionCallJobType);
96
+ const decodeJob = decodeBeast2For(FunctionCallJobType);
97
+
98
+ /**
99
+ * Encode a kept call as its store keeps it, in beast2.
100
+ *
101
+ * @param job - The call
102
+ * @returns Its bytes
103
+ */
104
+ export function encodeFunctionCallJob(job: FunctionCallJob): Uint8Array {
105
+ return encodeJob(job);
106
+ }
107
+
108
+ /**
109
+ * Decode a kept call from its store's bytes.
110
+ *
111
+ * @param bytes - The call's bytes, as {@link encodeFunctionCallJob} wrote them
112
+ * @returns The call
113
+ * @throws {Error} When the bytes are not a kept call of this release's form
114
+ */
115
+ export function decodeFunctionCallJob(bytes: Uint8Array): FunctionCallJob {
116
+ return decodeJob(bytes);
117
+ }
118
+
119
+ /**
120
+ * What a kept call names, which gc keeps while the call is kept: the function
121
+ * object it runs, and with it the program the object names; each value
122
+ * argument's object; the version of each dataset argument and each input it
123
+ * read; and its value once it succeeded. A one-shot call's function object is
124
+ * its own, which no package names, so the call alone keeps it, and its
125
+ * program, for as long as it runs and is kept.
126
+ *
127
+ * @param job - The call
128
+ * @returns The hashes it names: its function object's, then its arguments' in
129
+ * order, then its inputs', then its value's
130
+ */
131
+ export function functionCallRoots(job: FunctionCallJob): string[] {
132
+ const { call } = job;
133
+ const roots = [job.functionObject, ...call.args.map((arg) => (arg.type === 'value' ? arg.value : arg.value.hash))];
134
+ for (const input of call.inputs) roots.push(input.hash);
135
+ if (call.state.type === 'succeeded') roots.push(call.state.value.value);
136
+ return roots;
137
+ }
package/src/index.ts CHANGED
@@ -112,6 +112,19 @@ export {
112
112
  decodeFunctionObject,
113
113
  } from './function.js';
114
114
 
115
+ // Kept function calls, as a repository's call store keeps them
116
+ export {
117
+ FunctionCallCancelType,
118
+ type FunctionCallCancel,
119
+ FunctionCallKeepType,
120
+ type FunctionCallKeep,
121
+ FunctionCallJobType,
122
+ type FunctionCallJob,
123
+ encodeFunctionCallJob,
124
+ decodeFunctionCallJob,
125
+ functionCallRoots,
126
+ } from './function-call.js';
127
+
115
128
  // Record objects
116
129
  export {
117
130
  RecordCommitType,
@@ -298,7 +311,7 @@ export {
298
311
  isCollectionRoot,
299
312
  encodeDatasetBlob,
300
313
  writeCollectionManifest,
301
- SEGMENT_WRITES_IN_FLIGHT,
314
+ SEGMENT_WRITE_BATCH,
302
315
  type CollectionSegmentRef,
303
316
  type CollectionPiece,
304
317
  type SegmentSink,
@@ -443,6 +456,17 @@ export {
443
456
  SplitCallProgressType,
444
457
  SplitCallStatusType,
445
458
  SplitCallPlanType,
459
+ // Function calls, kept for a lifetime
460
+ FunctionCallStateType,
461
+ FunctionCallArgType,
462
+ FunctionCallSummaryType,
463
+ FunctionCallType,
464
+ FunctionCallStatusType,
465
+ FunctionCallAnswerType,
466
+ FunctionCallPageType,
467
+ FUNCTION_CALLS_PAGE_DEFAULT,
468
+ FUNCTION_CALLS_PAGE_MAX,
469
+ SplitCallReportType,
446
470
  MutationCallRequestType,
447
471
  MutationResultType,
448
472
  RecordMigrationAppliedType,
@@ -519,6 +543,14 @@ export {
519
543
  type SplitCallProgress,
520
544
  type SplitCallStatus,
521
545
  type SplitCallPlan,
546
+ type FunctionCallState,
547
+ type FunctionCallArg,
548
+ type FunctionCallSummary,
549
+ type FunctionCall,
550
+ type FunctionCallStatus,
551
+ type FunctionCallAnswer,
552
+ type FunctionCallPage,
553
+ type SplitCallReport,
522
554
  type MutationCallRequest,
523
555
  type MutationResult,
524
556
  type RecordMigrationApplied,