@tinyactors/wasm 0.3.0 → 0.4.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.
package/index.d.ts CHANGED
@@ -4,6 +4,11 @@
4
4
  // order, with examples. Each declaration is a row of docs/api-map.md,
5
5
  // which names the core behind it.
6
6
  //
7
+ // The declarations come in three groups, as the README orders them: the
8
+ // application API first, then what operating a host takes, then the wire
9
+ // format. Every name is exported from the package's one entry; the groups
10
+ // say where an item fits, not where it is imported from.
11
+ //
7
12
  // Units: time is milliseconds (but telemetry.flushInterval, in the host's
8
13
  // clock ticks, and traceWatch's seconds); sessions are bigints (inputs also
9
14
  // take a safe integer from 1, and typed methods' results hold numbers);
@@ -29,6 +34,14 @@ declare global {
29
34
  }
30
35
  }
31
36
 
37
+ // =========================================================================
38
+ // THE APPLICATION API
39
+ // =========================================================================
40
+ //
41
+ // Charts, a Host with its processors, store and handlers, Actors: what an
42
+ // application writes against (README.md, from "A first program" to "Before
43
+ // you use it").
44
+
32
45
  // ---- values -------------------------------------------------------------
33
46
 
34
47
  /** An actor's session, as an input takes it: a `bigint` from 1 to
@@ -61,36 +74,6 @@ export type Value =
61
74
  * without narrowing first. What it holds at run time is a `Value`. */
62
75
  export type ReceivedValue = any;
63
76
 
64
- /** What `encode` writes: a {@link Value}, or one holding `Address`es,
65
- * which it writes as CBOR's tag 32 (an actor reference). */
66
- export type Encodable =
67
- | Value
68
- | Address
69
- | Encodable[]
70
- | { [key: string]: Encodable };
71
-
72
- /** A value as CBOR bytes, the form to store or send it in. An `Address`
73
- * is tag 32 on its text.
74
- *
75
- * Throws a `TinyactorsError`: `TA_ERROR_UNSUPPORTED` for what is not a
76
- * {@link Value} (a function, a symbol, a `Date`, a `Map`, a class's
77
- * instance, a typed array other than `Uint8Array`), `TA_ERROR_INVALID` for
78
- * what a value cannot hold (a string with a lone surrogate, a `bigint` past
79
- * 64 bits, a cycle or nesting deeper than 64). A getter's exception passes
80
- * through.
81
- *
82
- * @example
83
- * const bytes = encode({ sku: 'tea', qty: 2 });
84
- * decode(bytes); // { sku: 'tea', qty: 2 }
85
- */
86
- export function encode(value: Encodable): Uint8Array;
87
-
88
- /** The value of the one CBOR item that fills `bytes`: the inverse of
89
- * {@link encode}, tag 32 an `Address`. Throws a `TinyactorsError` (`TA_ERROR_INVALID`) for bytes
90
- * that are not one such item, a `TypeError` for an argument that is not
91
- * bytes. */
92
- export function decode(bytes: Uint8Array | ArrayBuffer): ReceivedValue;
93
-
94
77
  // ---- errors -------------------------------------------------------------
95
78
 
96
79
  /** The reason a call was refused, as `TinyactorsError.status` names it:
@@ -122,7 +105,7 @@ export type Status =
122
105
  *
123
106
  * @example
124
107
  * try { host.send(session, 'go'); }
125
- * catch (error) { if (error instanceof TinyactorsError && error.status === 'TA_ERROR_STALE') ... }
108
+ * catch (error) { if (error instanceof StaleError) ... } // the actor ended
126
109
  */
127
110
  export class TinyactorsError extends Error {
128
111
  constructor(
@@ -141,6 +124,25 @@ export class TinyactorsError extends Error {
141
124
  readonly status: Status | undefined;
142
125
  }
143
126
 
127
+ /** An actor, session, view or handle that does not exist (any more): a
128
+ * send to a session or name that ended, a thin view read after its batch, a
129
+ * typed method's `stale` error. Its `status` is `'TA_ERROR_STALE'`. */
130
+ export class StaleError extends TinyactorsError {}
131
+
132
+ /** A call the host cannot make now: a closed host, a snapshot from a
133
+ * handler, a typed method's `state` error. Its `status` is
134
+ * `'TA_ERROR_STATE'`. */
135
+ export class StateError extends TinyactorsError {}
136
+
137
+ /** An argument the host refused: a malformed config, image or address, a
138
+ * typed method's param. Its `status` is `'TA_ERROR_INVALID'`. */
139
+ export class InvalidError extends TinyactorsError {}
140
+
141
+ /** A value or a feature the host does not take: a value outside the value
142
+ * table, a chart that cannot hibernate. Its `status` is
143
+ * `'TA_ERROR_UNSUPPORTED'`. */
144
+ export class UnsupportedError extends TinyactorsError {}
145
+
144
146
  // ---- compiling ----------------------------------------------------------
145
147
 
146
148
  /** A document to compile: its name, which error messages and `src`
@@ -218,13 +220,16 @@ export interface Compiled extends Disposable {
218
220
  *
219
221
  * @example
220
222
  * const compiled = compileCharts([{ name: 'order.scxml', text }]);
221
- * const segment = host.addImage(compiled.image);
223
+ * const host = new Host(compiled, { system: 'shop' });
222
224
  * compiled.close();
223
225
  */
224
- export function compileCharts(sources: readonly Source[], resolver?: Resolver, options?: CompileOptions): Compiled;
226
+ export function compileCharts(sources: readonly Source[], options?: CompileOptions): Compiled;
225
227
 
226
- /** The options of `compileCharts` and `compileSystem`. */
228
+ /** The options of `compileCharts`, `compileSystem` and `compileDir`. */
227
229
  export interface CompileOptions {
230
+ /** Answers each `src` the sources do not hold (`compileDir`'s default
231
+ * reads them from its directory). */
232
+ readonly resolver?: Resolver;
228
233
  /** Every warning is an error, and the compile throws `CompileError`:
229
234
  * the compiler's own warnings and the syntax errors of the charts'
230
235
  * ECMAScript, which are warnings otherwise, since SCXML makes such an
@@ -233,92 +238,37 @@ export interface CompileOptions {
233
238
  }
234
239
 
235
240
  /** Compiles a system manifest: a `<system>` document of `<chart name
236
- * src>`s, read through `resolver`, and `<actor name chart>`s, which
237
- * `host.boot` spawns with their names. Throws `CompileError`. */
238
- export function compileSystem(manifest: Source, resolver?: Resolver, options?: CompileOptions): Compiled;
239
-
240
- /** A {@link Resolver} that reads each `src` as a file under `root`,
241
- * relative to the directory of the document that names it (`base`): a
242
- * document named `orders/order.scxml` asking for `payment.scxml` reads
243
- * `<root>/orders/payment.scxml`. It refuses with a `ResolveError` (a
244
- * compile error) a path that leaves `root` (`..` past it, an absolute
245
- * path, a symbolic link that points outside), a file that does not exist,
246
- * and text that is not UTF-8; another error of the file system is thrown
247
- * from the compile call as it is. `root` is resolved through its links
248
- * once, here: one that does not exist throws now. A document it read is
249
- * named by its `src` as written. (The convenience layer: JavaScript over
250
- * `node:fs`.)
241
+ * src>`s, read through `options.resolver`, and `<actor name chart>`s,
242
+ * which `host.boot` spawns with their names. Throws `CompileError`. */
243
+ export function compileSystem(manifest: Source, options?: CompileOptions): Compiled;
244
+
245
+ /** Compiles every `*.scxml` file under the directory `dir` (a path or a
246
+ * `file:` URL) into one image: keep an application's charts and their
247
+ * helper files (a `.js` a chart reads with `<script src>`, a chart it
248
+ * invokes with `<invoke src>`) in one directory, compile it once at
249
+ * startup, and give the result to any number of hosts. The charts are
250
+ * named by their path under `dir`, sorted (the first is the image's
251
+ * default boot chart); a `src` is read from under `dir`, relative to the
252
+ * document that names it, and one whose path leaves `dir` (`..` past it,
253
+ * an absolute path, a symbolic link pointing outside) is refused with a
254
+ * `ResolveError`, so a `CompileError`; give `options.resolver` to read
255
+ * them yourself. A directory with no chart, or a chart file whose real
256
+ * path leaves it, throws `TA_ERROR_INVALID`; an error of the file system
257
+ * is thrown as it is. Needs `node:fs` (`TA_ERROR_UNSUPPORTED` in a page).
251
258
  *
252
259
  * @example
253
- * host.addCharts({ 'orders/order.scxml': text }, { resolver: directoryResolver('charts') });
260
+ * const compiled = compileDir(new URL('./charts/', import.meta.url));
261
+ * const host = new Host(compiled, { system: 'chat' });
262
+ * compiled.close();
254
263
  */
255
- export function directoryResolver(root: string | URL): Resolver;
256
-
257
- // ---- addresses ----------------------------------------------------------
258
-
259
- /** An actor's address: `tinyactors://<system>/#_scxml_<session>`, or
260
- * `tinyactors://<system>/@<name>` for a named actor. Immutable. Its parts
261
- * are read from the text on each access, `undefined` for a part the text
262
- * lacks (any text makes an `Address`; one that is not an address has no
263
- * parts). */
264
- export class Address {
265
- constructor(text: string);
266
- /** The address of a session of system `system`. */
267
- static fromSession(system: string, session: Session): Address;
268
- /** The address of the actor named `name` in system `system`; the name is
269
- * percent-encoded. */
270
- static fromName(system: string, name: string): Address;
271
- readonly text: string;
272
- /** The system id. */
273
- readonly system: string | undefined;
274
- readonly session: bigint | undefined;
275
- /** The actor's name, decoded. */
276
- readonly name: string | undefined;
277
- /** The text. */
278
- toString(): string;
279
- /** The text, so `JSON.stringify` writes an address as a string, which
280
- * `new Address(text)` and `host.send` read back. */
281
- toJSON(): string;
282
- }
283
-
284
- // ---- BasicHTTP ----------------------------------------------------------
285
-
286
- /** A form field of a BasicHTTP message. */
287
- export interface HTTPField {
288
- name: string;
289
- value: string;
290
- }
291
-
292
- /** A BasicHTTP POST, the request SCXML's HTTP processor makes for a send. */
293
- export interface HTTPPost {
294
- /** `http://host[:port]/path`. */
295
- url: string;
296
- /** Written as the `_scxmleventname` field. */
297
- event?: string;
298
- fields?: readonly HTTPField[];
299
- /** The body, used when there are no fields; percent-encoded. */
300
- body?: string;
301
- }
302
-
303
- /** An incoming BasicHTTP request, read. */
304
- export interface HTTPRequest {
305
- readonly method: string;
306
- readonly target: string;
307
- /** The body as received. */
308
- readonly body: string;
309
- /** The `_scxmleventname` field, else `HTTP.<METHOD>`. */
310
- readonly event: string;
311
- /** The decoded form fields, but `_scxmleventname`. */
312
- readonly fields: readonly HTTPField[];
313
- }
264
+ export function compileDir(dir: string | URL, options?: { readonly resolver?: Resolver }): Compiled;
314
265
 
315
- /** The bytes of a BasicHTTP POST, to write to a socket. A URL that is not
316
- * `http://host[:port]/path` throws `TA_ERROR_INVALID`. */
317
- export function encodeHTTPPost(post: HTTPPost): Uint8Array;
318
-
319
- /** Reads an incoming BasicHTTP request: its event and form fields, for
320
- * `host.send`. A malformed request throws `TA_ERROR_INVALID`. */
321
- export function parseHTTPRequest(message: Uint8Array | ArrayBuffer): HTTPRequest;
266
+ /**
267
+ * The version of the package installed (`'0.4.0'`, or a development
268
+ * build's `'0.4.0-dev.20261119.3.gabc1234'`), as its package.json says.
269
+ * `@tinyactors/node/package.json` can be imported too.
270
+ */
271
+ export const version: string;
322
272
 
323
273
  // ---- the clock ----------------------------------------------------------
324
274
 
@@ -342,7 +292,7 @@ export class SimulatedClock {
342
292
  increment(ms: number): void;
343
293
  }
344
294
 
345
- // ---- what handlers get ----------------------------------------------------
295
+ // ---- what handlers get --------------------------------------------------
346
296
 
347
297
  /** One `<send>` of a chart, as an I/O processor's handler, the transport
348
298
  * or a service's `receive` gets it. A view of the host's memory: each
@@ -352,8 +302,12 @@ export class SimulatedClock {
352
302
  * the view stays valid, `answer` and `fail` included, while the host is
353
303
  * open. */
354
304
  export interface Send {
355
- /** The sender. */
305
+ /** The host that handed it out. */
306
+ readonly host: Host;
307
+ /** The sender's session. */
356
308
  readonly session: bigint;
309
+ /** The sender, as an {@link Actor} (a new one at each read). */
310
+ readonly sender: Actor;
357
311
  /** The event's name. */
358
312
  readonly event: string;
359
313
  /** `<send target>`: a string; an `Address` for the transport's sends;
@@ -404,25 +358,10 @@ export interface AnswerOptions {
404
358
  raw?: string;
405
359
  }
406
360
 
407
- /** An event for `host.send(message)` and `host.sendMany(items)`, in the
408
- * shape `send.message` has. Keys it does not know are ignored. */
409
- export interface SendMessage {
410
- /** A session, or an address (string or `Address`); a local address is
411
- * resolved to its actor. */
412
- target: Session | string | Address;
413
- event: string;
414
- data?: Value;
415
- /** The event's `_event.sendid`. */
416
- sendid?: string | null;
417
- /** The event's `_event.origin`: where an answer goes. */
418
- origin?: string | Address | null;
419
- /** The trace the event continues, as W3C text; text that does not parse
420
- * starts a new one. */
421
- traceparent?: string | null;
422
- }
423
-
424
361
  /** A `<log>` line: a view, valid while the log handler runs. */
425
362
  export interface LogEntry {
363
+ /** The host that handed it out. */
364
+ readonly host: Host;
426
365
  /** The actor that logged. */
427
366
  readonly session: bigint;
428
367
  /** `<log label>`; `''` when it has none. */
@@ -431,38 +370,11 @@ export interface LogEntry {
431
370
  readonly text: string;
432
371
  }
433
372
 
434
- /** An actor a migration moved: a view, valid while the handler runs. */
435
- export interface Migrated {
436
- readonly session: bigint;
437
- /** The segment of its new version. */
438
- readonly segment: number;
439
- /** The chart's name. */
440
- readonly chart: string;
441
- /** The migration's id, as `host.migrate` returned it. */
442
- readonly migration: number;
443
- }
444
-
445
- /** A session a migration could not move: it stays on its version.
446
- * `reason` names core's status, `'TA_ERROR_UNSUPPORTED'` when its state
447
- * cannot be written out (a value outside the value table). */
448
- export interface MigrationFailure {
449
- readonly session: bigint;
450
- readonly reason: string;
451
- }
452
-
453
- /** A migration's end: how many actors it moved, the ones it could not move
454
- * and why (they stay on their version), and the sessions its timeout left
455
- * behind. */
456
- export interface MigrationResult {
457
- readonly migration: number;
458
- readonly migrated: number;
459
- readonly failed: readonly MigrationFailure[];
460
- readonly pending: readonly bigint[];
461
- }
462
-
463
373
  /** An `<invoke>` of a service your program runs, as a service handler
464
374
  * gets it. A record: keep it and use it while the service runs. */
465
375
  export interface Invocation {
376
+ /** The host that runs the invocation. */
377
+ readonly host: Host;
466
378
  /** The invoking actor. */
467
379
  readonly session: bigint;
468
380
  /** The `<invoke id>`, or the id the host generated. */
@@ -499,142 +411,177 @@ export interface Service {
499
411
  * or an autoforwarded event); `send.type` is `undefined`. A throw, or a
500
412
  * promise that rejects, is a crash: the invoker gets
501
413
  * `error.communication` and the service is dropped. */
502
- receive?(host: Host, send: Send): void | Promise<void>;
414
+ receive?(send: Send): void | Promise<void>;
503
415
  /** The invoker left the state, which cancels the invocation. */
504
- stop?(host: Host): void;
416
+ stop?(): void;
505
417
  }
506
418
 
507
- // ---- the host -----------------------------------------------------------
419
+ // ---- the host's options -------------------------------------------------
508
420
 
509
- /** A chart's current version in a host, from `host.chart(name)`, for
510
- * `host.spawn`. */
511
- export interface ChartRef {
512
- /** The segment of the image that holds it. */
513
- readonly segment: number;
514
- /** Its index in that image. */
515
- readonly chart: number;
421
+ /** The handlers and choices of a host, `new Host(charts, options)`. A
422
+ * handler's error is reported after its turn: it goes to `onHandlerError`
423
+ * when there is one; else it rejects a waiting `host.idle()`, or is thrown
424
+ * as an uncaught exception. No handler takes the host: a view or record
425
+ * has `.host`. */
426
+ export interface HostOptions {
427
+ /** Required: this system's id, part of every address it hands out
428
+ * (`tinyactors://<system>/...`). No two systems that talk may share one,
429
+ * and `'tinyactors-ask'` is the binding's (`TA_ERROR_INVALID`). */
430
+ system: string;
431
+ /** The I/O processors the charts may send to (`<send type>`): an
432
+ * object of each type's {@link IOProcessor}, the config's
433
+ * `ioProcessors` in this order. Sends to another system need none: they
434
+ * go to `transport`. */
435
+ ioProcessors?: { [type: string]: IOProcessor };
436
+ /** The rest of the host's config. */
437
+ config?: HostConfig;
438
+ /** A `SimulatedClock`; without one the host reads the runtime's clock
439
+ * and arms a timer at its next deadline. */
440
+ clock?: SimulatedClock;
441
+ /** Where hibernated actors' blobs go: a WAKE (an event, a due delayed
442
+ * send, a migration for a hibernated actor) loads its blob from here and
443
+ * wakes it. Without a store a WAKE is dropped: the actor stays
444
+ * hibernated, and its events wait, until `host.wake`. */
445
+ store?: Store;
446
+ /** The most actors kept in memory (an integer from 1; needs `store`):
447
+ * after a turn that goes idle the host hibernates the actors past it
448
+ * into the store, the coldest first (`host.sweep`, `host.hibernate`); a
449
+ * migration's WAKE waits while the bound is reached, and loads as room
450
+ * is made. An actor not at rest, or holding what its datamodel cannot
451
+ * write out, stays. */
452
+ resident?: number;
453
+ /** `<log>` lines; without one they are dropped. */
454
+ log?: (entry: LogEntry) => Handled;
455
+ /** Your exporter: each OTLP traces or logs request the encoder wrote
456
+ * (protobuf, for a collector's `/v1/traces` or `/v1/logs`), as a
457
+ * `Uint8Array`. Needs `telemetry` in the config; without a handler the
458
+ * requests are dropped. It runs in the host's turn: start the post and
459
+ * return. At `close()` it gets the last requests; the promises it
460
+ * returns then are awaited by `[Symbol.asyncDispose]`. */
461
+ telemetry?: (signal: 'traces' | 'logs', data: Uint8Array) => Handled;
462
+ /** The handler of each `<invoke type>` your program runs: it returns the
463
+ * service, or a promise of it. Until the promise settles the sends to
464
+ * the invocation wait, in order; a rejection is a failed start, and the
465
+ * invoker gets `error.communication`. */
466
+ services?: { [type: string]: (invocation: Invocation) => Service | void | PromiseLike<Service | void> };
467
+ /** Sends to another system's address. Pass `send.message` to the other
468
+ * side's `host.send`. Without one, each such send is failed. A reply to
469
+ * an `actor.ask` never reaches it. */
470
+ transport?: (send: Send) => Handled;
471
+ /** Each top-level actor that reaches a final state, with its donedata
472
+ * (`undefined` for none). */
473
+ onDone?: (actor: Actor, donedata: ReceivedValue) => Handled;
474
+ /** Each top-level actor that faulted and ended (a `TinyactorsError`,
475
+ * status `TA_ERROR_FATAL`). */
476
+ onError?: (actor: Actor, error: TinyactorsError) => Handled;
477
+ /** A handler's error (a throw, or its promise's rejection), with the
478
+ * view or record it was handling (`undefined` for none; a thin view is
479
+ * readable while the hook runs). The send is failed as without it.
480
+ * Without it, the error is the turn's. */
481
+ onHandlerError?: (error: unknown, effect: Send | LogEntry | Migrated | Invocation | undefined) => void;
482
+ /** Each actor a migration moved. */
483
+ migrated?: (migrated: Migrated) => Handled;
484
+ /** The end of each migration. */
485
+ migrationDone?: (result: MigrationResult) => Handled;
486
+ /** Where chart code runs: `'native'` (the default), your own engine
487
+ * (`node:vm` contexts in @tinyactors/node), for trusted charts; or
488
+ * `'quickjs'`, the sandbox, for charts you do not trust (in
489
+ * @tinyactors/wasm the datamodel for a page whose policy forbids
490
+ * `'unsafe-eval'`). */
491
+ datamodel?: 'native' | 'quickjs';
492
+ /** The sandbox's limits, with `datamodel: 'quickjs'` only (else a
493
+ * `TypeError`). */
494
+ quickjs?: QuickJSOptions;
516
495
  }
517
496
 
518
- /** The host's config: plain values, checked by the host, every absent key
519
- * a default (the host's, never the package's). A key the host does not
520
- * take, or a value of the wrong type, throws a `TinyactorsError`
521
- * (`TA_ERROR_INVALID`) at `new Host`, with the host's `reason` and the key
522
- * as `path` (`system.maxActors`). `host.hostConfig()` answers the
523
- * config with every default filled in, as {@link EffectiveHostConfig}.
497
+ /** What `new Host` and `Host.restore` take as charts: a compile result
498
+ * (its image is read), an image's bytes, or an array of them, each added
499
+ * in order as a segment. */
500
+ export type Charts = Compiled | Uint8Array | ArrayBuffer | readonly (Compiled | Uint8Array | ArrayBuffer)[];
501
+
502
+ /** An I/O processor: the object that serves one `<send type>`, given as
503
+ * `options.ioProcessors[type]`. Its `receive` gets each send to the type,
504
+ * called on the object: answer or fail it there, or return a promise
505
+ * (every field of the send is read before the host moves on, and it may
506
+ * be answered when the promise gets there). A throw, or a promise that
507
+ * rejects before an answer, fails the send (`error.communication` for the
508
+ * sender) and is reported as the turn's error, or to `onHandlerError`. A
509
+ * plain function is a `TypeError`: switch on `send.event` in `receive`.
524
510
  *
525
511
  * @example
526
- * const config = { systemID: 'orders', system: { maxActors: 10_000 }, telemetry: { resource: { 'service.name': 'orders' } } };
512
+ * const database = {
513
+ * receive(send) {
514
+ * if (send.event === 'load') send.answer('loaded', { rows: [] });
515
+ * else send.fail();
516
+ * },
517
+ * };
527
518
  */
528
- export interface HostConfig {
529
- /** Required: this system's id, part of every address it hands out
530
- * (`tinyactors://<systemID>/...`). No two systems that talk may share
531
- * one. */
532
- systemID: string;
533
- /** The capacities of each new segment, each its first size, not a cap
534
- * (a pool that fills grows its segment). */
535
- system?: SystemConfig;
536
- /** The I/O processors the charts may send to (`<send type>`), at most
537
- * 16; each needs a handler in `options.ioProcessors`. Sends to another
538
- * system need none: they go to `options.transport`. */
539
- ioProcessors?: readonly IOProcessorConfig[];
540
- /** Actors a migration looks at per run (default 256). */
541
- migrateQuantum?: number;
542
- /** Present: the host has an OTLP encoder, and `options.telemetry` gets
543
- * its requests. Absent: none, and nothing is paid for it. */
544
- telemetry?: TelemetryConfig;
519
+ export interface IOProcessor {
520
+ receive(send: Send): Handled;
521
+ /** Its location, which `_ioprocessors` shows the charts. */
522
+ readonly location?: string;
545
523
  }
546
524
 
547
- /** An I/O processor of the config. */
548
- export interface IOProcessorConfig {
549
- /** The `<send type>` it serves. */
550
- type: string;
551
- /** Its location, which `_ioprocessors` shows the charts. */
552
- location?: string;
525
+ /** A store of hibernated actors' blobs, given as `options.store`: the host
526
+ * saves an actor's blob when it hibernates it (with `options.resident`),
527
+ * loads it when an event, a due delayed send or a migration comes for the
528
+ * actor (a WAKE), then wakes the actor and deletes the blob. Each method
529
+ * may return a value or a promise: the host waits for a promise (and so
530
+ * does `idle()`); a save still pending when its actor's WAKE comes is
531
+ * waited for first. A `save` that throws, or whose promise rejects, wakes
532
+ * the actor back from its blob (it stays in memory until a later turn), a
533
+ * `load` that throws leaves it hibernated; both are reported as a
534
+ * handler's error. `MemoryStore` and `SQLiteStore` are synchronous. */
535
+ export interface Store {
536
+ save(session: bigint, blob: Uint8Array): void | PromiseLike<void>;
537
+ load(session: bigint): Uint8Array | ArrayBuffer | PromiseLike<Uint8Array | ArrayBuffer>;
538
+ delete(session: bigint): void | PromiseLike<void>;
553
539
  }
554
540
 
555
- /** Each new segment's first sizes: unsigned integers, 0 or absent for the
556
- * host's default; larger values are clamped to the host's limits. */
557
- export interface SystemConfig {
558
- /** Default 64, at most 8388606. */
559
- maxActors?: number;
560
- /** Queued events; default 256. */
561
- maxEvents?: number;
562
- /** Delayed sends and timeouts; default 64. */
563
- maxTimers?: number;
564
- /** Actors that may be in a step at once; default 4. */
565
- workspaces?: number;
566
- /** Default 16. */
567
- maxRequests?: number;
568
- /** Default 64. */
569
- outbox?: number;
570
- /** Default 1000. */
571
- quantum?: number;
572
- /** Default 0: derived from the image and `maxActors`. */
573
- instanceBytes?: number;
574
- /** Default 16384 + 16 per actor of `maxActors`. */
575
- stringBytes?: number;
576
- /** The host's clock rate; default 1e9 (nanoseconds). */
577
- ticksPerSecond?: number;
578
- /** The trace journal; default 131072, at least 65536. */
579
- traceBytes?: number;
580
- /** Default `maxEvents`. */
581
- traceContexts?: number;
582
- /** Default 16, at most 255. */
583
- traceRules?: number;
584
- /** The seed of the trace IDs: the same seed gives the same IDs. Without
585
- * one, each new host draws a random seed (`crypto.getRandomValues`);
586
- * set it to reproduce a test's traces. */
587
- traceSeed?: number;
588
- /** Write trace records (default true), so export or a watch can be
589
- * turned on later. */
590
- tracing?: boolean;
541
+ /** A {@link Store} in a `Map`, in this process: for tests, and where the
542
+ * host's memory, not the process's, is what must stay small. */
543
+ export class MemoryStore implements Store {
544
+ constructor();
545
+ /** The blobs by session: what a test reads to see what was stored. */
546
+ readonly blobs: Map<bigint, Uint8Array>;
547
+ save(session: bigint, blob: Uint8Array): void;
548
+ /** The blob of `session`; a `StaleError` when there is none. */
549
+ load(session: bigint): Uint8Array;
550
+ delete(session: bigint): void;
591
551
  }
592
552
 
593
- /** The OTLP encoder: unsigned integers, 0 or absent for its default. */
594
- export interface TelemetryConfig {
595
- /** Default 1048576, from 65536 to 1073741824. */
596
- stagingBytes?: number;
597
- /** Default a quarter of `stagingBytes`. */
598
- logBytes?: number;
599
- /** Default 1024. */
600
- openSpans?: number;
601
- /** Default 8 per open span. */
602
- chunks?: number;
603
- /** Default 64. */
604
- scopes?: number;
605
- /** Default 256. */
606
- valueLimit?: number;
607
- /** Default 16384. */
608
- renderBytes?: number;
609
- /** Default 4096. */
610
- resourceBytes?: number;
611
- /** Default 65536. */
612
- metricBytes?: number;
613
- /** Default 64. */
614
- spanMetricCharts?: number;
615
- /** A request is ready this long after its first record, in the host's
616
- * clock ticks; 0 or absent: only when the staging is full. */
617
- flushInterval?: number;
618
- /** A macrostep is a root span linked to its cause (default false). */
619
- linkParents?: boolean;
620
- /** Event data and assigned values in the spans (default false: they may
621
- * hold personal data). */
622
- values?: boolean;
623
- /** `<log>`s and failed actions as log records (default true). */
624
- logs?: boolean;
625
- /** Attributes on every request (`service.name`, ...), at most 32. */
626
- resource?: { readonly [key: string]: string };
553
+ /** A {@link Store} in an SQLite database file, one row per actor in the
554
+ * table `tinyactors_blobs (session, blob)`, through the runtime's own
555
+ * SQLite (`node:sqlite` under node, `bun:sqlite` under bun),
556
+ * synchronously; `':memory:'` for no file. It is a cache of the host's
557
+ * actors, not their durability: a host's blobs wake only in that host or
558
+ * one restored from its snapshot, so keep the file with the snapshot. A
559
+ * runtime without SQLite (a page) throws `TA_ERROR_UNSUPPORTED`. */
560
+ export class SQLiteStore implements Store {
561
+ constructor(path: string);
562
+ /** The runtime's database object, for an application that reads the
563
+ * table itself. */
564
+ readonly database: any;
565
+ save(session: bigint, blob: Uint8Array): void;
566
+ /** The blob of `session`; a `StaleError` when there is none. */
567
+ load(session: bigint): Uint8Array;
568
+ delete(session: bigint): void;
569
+ /** Closes the database; the file keeps the blobs. */
570
+ close(): void;
627
571
  }
628
572
 
629
- /** The config a host runs with, every key present, as `hostConfig`
630
- * answers it: a host made from it answers the same. */
631
- export interface EffectiveHostConfig {
632
- readonly systemID: string;
633
- readonly system: Readonly<Required<SystemConfig>>;
634
- readonly ioProcessors: readonly Readonly<IOProcessorConfig>[];
635
- readonly migrateQuantum: number;
636
- /** Only when the host has an encoder. */
637
- readonly telemetry?: Readonly<Required<TelemetryConfig>>;
573
+ /** An I/O processor that spawns actors for charts: give it a type you
574
+ * name, `ioProcessors: { spawn: new Spawner() }`, and a chart sends it
575
+ * `{chart, name, params}` (`<send type="spawn" event="spawn">`). The new
576
+ * actor runs the chart's current version; the sender gets `spawned` with
577
+ * `{name, address}` and the send's `sendid`, or `error.communication`
578
+ * when the host cannot spawn it (a chart it does not have, data of
579
+ * another shape). A type no processor serves stays `error.execution`.
580
+ * It does not look names up: a name has one owner, the collection actor
581
+ * that spawns it and records the spawns it asked for. */
582
+ export class Spawner implements IOProcessor {
583
+ constructor();
584
+ receive(send: Send): void;
638
585
  }
639
586
 
640
587
  /** What a handler returns: nothing, or a promise (typed `unknown`, so a
@@ -644,55 +591,6 @@ export interface EffectiveHostConfig {
644
591
  * when the promise gets there. */
645
592
  export type Handled = unknown;
646
593
 
647
- /** The handlers and choices of a host. A handler's error is reported after
648
- * its turn: it rejects a waiting `host.idle()`, or else is thrown as an
649
- * uncaught exception. */
650
- export interface HostOptions {
651
- /** The handler of each I/O processor type the config lists. A listed
652
- * type without a handler fails each send to it; a handler for a type the
653
- * config does not list is a `TypeError`. */
654
- ioProcessors?: { [type: string]: (host: Host, send: Send) => Handled };
655
- /** Sends to another system's address. Pass `send.message` to the other
656
- * side's `host.send`. Without one, each such send is failed. */
657
- transport?: (host: Host, send: Send) => Handled;
658
- /** `<log>` lines; without one they are dropped. */
659
- log?: (host: Host, entry: LogEntry) => void;
660
- /** A `SimulatedClock`; without one the host reads the runtime's clock
661
- * and arms a timer at its next deadline. */
662
- clock?: SimulatedClock;
663
- /** Your exporter: each OTLP traces or logs request the encoder wrote
664
- * (protobuf, for a collector's `/v1/traces` or `/v1/logs`), as a
665
- * `Uint8Array`. Needs `telemetry` in the config; without a handler the
666
- * requests are dropped. It runs in the host's turn: start the post and
667
- * return. At `close()` it gets the last requests; the promises it
668
- * returns then are awaited by `[Symbol.asyncDispose]`. */
669
- telemetry?: (host: Host, signal: 'traces' | 'logs', data: Uint8Array) => Handled;
670
- /** A hibernated actor has work: an event or a due delayed send
671
- * (`migration` undefined), or a migration asks for it (its id). Load its
672
- * blob and call `host.wake`, now or later. Called once per hibernation;
673
- * without it the actor stays hibernated, and its events wait, until
674
- * `host.wake`. */
675
- wake?: (host: Host, session: bigint, migration: number | undefined) => Handled;
676
- /** Each actor a migration moved. */
677
- migrated?: (host: Host, migrated: Migrated) => void;
678
- /** The end of each migration. */
679
- migrationDone?: (host: Host, result: MigrationResult) => void;
680
- /** The handler of each `<invoke type>` your program runs: it returns the
681
- * service, or a promise of it. Until the promise settles the sends to
682
- * the invocation wait, in order; a rejection is a failed start, and the
683
- * invoker gets `error.communication`. */
684
- services?: { [type: string]: (host: Host, invocation: Invocation) => Service | void | PromiseLike<Service | void> };
685
- /** Where chart code runs: `'native'` (the default), your own engine
686
- * (`node:vm` contexts in @tinyactors/node), for trusted charts; or
687
- * `'quickjs'`, the sandbox, for charts you do not trust (in
688
- * @tinyactors/wasm the datamodel for a page whose policy forbids
689
- * `'unsafe-eval'`). */
690
- datamodel?: 'native' | 'quickjs';
691
- /** The sandbox's limits, with `datamodel: 'quickjs'` only (else a
692
- * `TypeError`). */
693
- quickjs?: QuickJSOptions;
694
- }
695
-
696
594
  /** The quickjs sandbox's limits. Absent: the engine's default. */
697
595
  export interface QuickJSOptions {
698
596
  /** Interrupt checks one evaluation may make before it is stopped with
@@ -712,16 +610,61 @@ export interface QuickJSOptions {
712
610
  realm?: 'auto' | 'isolated';
713
611
  }
714
612
 
715
- /** The options of `host.addCharts`. */
716
- export interface AddChartsOptions {
717
- /** The compile call's resolver, for each `src` the documents do not
718
- * answer. */
719
- resolver?: Resolver;
613
+ // ---- actors -------------------------------------------------------------
614
+
615
+ /** An actor of a host: what `host.spawn` and `host.actor` return, and what
616
+ * `send.sender` and `onDone` give. A small immutable value made where the
617
+ * API returns one: keeping one keeps nothing alive in the host, two for
618
+ * one actor are `equals` (key a `Map` by `id`), and one whose actor ended
619
+ * refuses what needs the actor (`StaleError`). Every call that takes a
620
+ * session takes an Actor. */
621
+ export class Actor {
622
+ /** An Actor of `host` for session `id`; `host.actor(id)` checks it is live. */
623
+ constructor(host: Host, id: bigint);
624
+ /** The actor's session: a `bigint`, core's `_sessionid`. */
625
+ readonly id: bigint;
626
+ /** The host it runs in (not enumerable). */
627
+ readonly host: Host;
628
+ /** `tinyactors://<system>/#_scxml_<id>`, the full form: what another
629
+ * system sends to. A chart sees this actor's sends' `_event.origin`
630
+ * either in it or as its fragment, `#_scxml_<id>`, so compare by the
631
+ * fragment. */
632
+ readonly address: Address;
633
+ /** `host.send(actor, event, data, options)`. */
634
+ send(event: string, data?: Value, options?: SendOptions): void;
635
+ /** Ends the actor now (`host.terminate`): no exit handlers, no done
636
+ * event; a hibernated one is woken to end, its blob deleted. */
637
+ terminate(): void;
638
+ /** `host.actorState({ session: actor })`. */
639
+ state(): Promise<ActorStateResult>;
640
+ /** `host.actorContext({ session: actor })`. */
641
+ context(): Promise<ActorContextResult>;
642
+ /** `host.actorGet({ session: actor })`. */
643
+ get(): Promise<ActorGetResult>;
644
+ /** Sends `event` with `data` and resolves with the actor's reply, `[event,
645
+ * data]`: the chart answers with `<send targetexpr="_event.origin"
646
+ * event="...">`. The event's origin is an address of the host's own
647
+ * (system `tinyactors-ask`), so the reply comes back here and never
648
+ * reaches your transport. No timeout of its own: `options.signal` (an
649
+ * `AbortSignal`) rejects it with the signal's reason and drops it; an ask
650
+ * pending at `close()` never settles. A refusal at the call (an actor that
651
+ * ended) rejects. */
652
+ ask(event: string, data?: Value, options?: { signal?: AbortSignal }): Promise<[string, ReceivedValue]>;
653
+ /** A promise of the actor's donedata, settled when it reaches a
654
+ * top-level final state (rejected with the error it ended with, a
655
+ * fault). The same promise while it is pending; an actor that ended
656
+ * already rejects with `StaleError`, a closed host `StateError`, and one
657
+ * pending at `close()` never settles. */
658
+ readonly done: Promise<ReceivedValue>;
659
+ /** Whether `other` is an Actor of the same host and session. */
660
+ equals(other: unknown): boolean;
661
+ /** `Actor(<id>)`. */
662
+ toString(): string;
720
663
  }
721
664
 
722
665
  /** The options of `host.spawn`. */
723
666
  export interface SpawnOptions {
724
- /** The actor's name: `host.actorByName` finds it, `_name` holds it, and
667
+ /** The actor's name: `host.actor(name)` finds it, `_name` holds it, and
725
668
  * its address is `tinyactors://<system>/@<name>`. */
726
669
  name?: string;
727
670
  /** Initial values: each key that names a top-level `<data>` replaces that
@@ -742,37 +685,26 @@ export interface SendOptions {
742
685
  origin?: string | Address;
743
686
  }
744
687
 
745
- /** The options of `host.migrate`. */
746
- export interface MigrateOptions {
747
- /** A chart's name; none: every chart. */
748
- chart?: string;
749
- /** One actor. */
750
- session?: Session;
751
- /** Ask the `wake` handler for the hibernated actors, with the
752
- * migration's id. */
753
- wake?: boolean;
754
- /** Milliseconds of the host's clock from now, rounded up to its next
755
- * tick; 0 or none: no timeout. */
756
- timeout?: number;
757
- }
688
+ // ---- the typed methods: their shapes, and an actor's --------------------
689
+
690
+ // As the host writes them (each method of the host's control plane). A
691
+ // session or a count in a result is a number; an integer past 2^53 would
692
+ // be a bigint, which only `trace.spans.decode`'s nanosecond times reach.
758
693
 
759
694
  /** A typed method's params, passed to the host as given (the host checks
760
695
  * them); `undefined` for none. Each method has its own type below. */
761
696
  export type Params = { [key: string]: Value } | undefined;
697
+
762
698
  /** The params of a method that takes none: `undefined` or `{}`. */
763
699
  export type NoParams = undefined | { readonly [key: string]: never };
700
+
764
701
  /** A typed method's result handler, called once, in a later turn, with the
765
702
  * method's result. */
766
- export type OnResult<R = Value> = (host: Host, result: R) => void;
703
+ export type OnResult<R = Value> = (result: R) => void;
704
+
767
705
  /** A typed method's error handler. Without one, the error rejects a
768
706
  * waiting `idle()` or is thrown as an uncaught exception. */
769
- export type OnError = (host: Host, error: TinyactorsError) => void;
770
-
771
- // ---- the typed methods' params and results ---------------------------
772
- //
773
- // As the host writes them (each method of the host's control plane). A
774
- // session or a count in a result is a number; an integer past 2^53 would
775
- // be a bigint, which only `trace.spans.decode`'s nanosecond times reach.
707
+ export type OnError = (error: TinyactorsError) => void;
776
708
 
777
709
  /** An active configuration, as xstate's `value`: an atomic state is its
778
710
  * id (`'s'`), a compound state `{ [state]: its active child }`, a parallel
@@ -781,8 +713,9 @@ export type StateValue = string | { readonly [state: string]: StateValue };
781
713
 
782
714
  /** The params of `actorState`, `actorContext` and `actorGet`. */
783
715
  export interface SessionParams {
784
- session: Session;
716
+ session: Session | Actor;
785
717
  }
718
+
786
719
  /** `actorState`'s result. */
787
720
  export interface ActorStateResult {
788
721
  readonly value: StateValue;
@@ -797,23 +730,12 @@ export interface ActorStateResult {
797
730
  */
798
731
  readonly history: { readonly [history: string]: StateValue };
799
732
  }
733
+
800
734
  /** `actorContext`'s result: each `<data>`, in the chart's order. */
801
735
  export interface ActorContextResult {
802
736
  readonly variables: { readonly [id: string]: ReceivedValue };
803
737
  }
804
- /** The params of `actorList`. */
805
- export interface ActorListParams {
806
- /** From the previous page; absent: the first. */
807
- cursor?: number;
808
- /** 1 to 512, default 256. */
809
- limit?: number;
810
- }
811
- /** `actorList`'s result: a page of sessions. */
812
- export interface ActorListResult {
813
- readonly sessions: readonly number[];
814
- /** The next page's cursor, opaque; `null` after the last page. */
815
- readonly cursor: number | null;
816
- }
738
+
817
739
  /** `actorGet`'s result. */
818
740
  export interface ActorGetResult {
819
741
  readonly session: number;
@@ -834,6 +756,7 @@ export interface ActorGetResult {
834
756
  /** How many delayed sends it has pending: more than `timers` holds when the list was cut. */
835
757
  readonly timersPending: number;
836
758
  }
759
+
837
760
  /** A pending delayed send, in `actorGet`'s `timers`. */
838
761
  export interface PendingSend {
839
762
  /** The send's id (its `id`, or the one `idlocation` was given); `null` when it has none. */
@@ -843,146 +766,8 @@ export interface PendingSend {
843
766
  /** When it fires: milliseconds on the clock `host.now()` reads. */
844
767
  readonly due: number;
845
768
  }
846
- /** A pool of a segment: its size, what it holds, the most it held. */
847
- export interface Pool {
848
- readonly capacity: number;
849
- readonly used: number;
850
- readonly highWater: number;
851
- }
852
- /** One live segment's pools, in `host.stats`. */
853
- export interface SegmentPools {
854
- /** The segment, as `addImage` returned it. */
855
- readonly segment: number;
856
- readonly actors: Pool;
857
- readonly events: Pool;
858
- readonly timers: Pool;
859
- readonly workspaces: Pool;
860
- readonly requests: Pool;
861
- /** The slab of instances and strings, in bytes. */
862
- readonly slabBytes: Pool;
863
- }
864
- /** One chart's counters, summed over every segment, retired versions
865
- * included. */
866
- export interface ChartStats {
867
- readonly name: string;
868
- readonly actors: number;
869
- readonly hibernated: number;
870
- readonly spawned: number;
871
- readonly ended: number;
872
- readonly turns: number;
873
- readonly macrosteps: number;
874
- readonly fuel: number;
875
- readonly errorsExecution: number;
876
- readonly errorsCommunication: number;
877
- readonly errorsPlatform: number;
878
- readonly faults: number;
879
- }
880
- /** `hostStats`'s result. */
881
- export interface HostStatsResult {
882
- readonly host: {
883
- readonly segments: number;
884
- readonly actors: number;
885
- readonly hibernated: number;
886
- readonly runnable: number;
887
- readonly migrations: number;
888
- /** The live segments' regions; the host's copies of the images are not
889
- * in it. */
890
- readonly regionBytes: number;
891
- readonly delivered: number;
892
- readonly routed: number;
893
- readonly migrated: number;
894
- readonly retired: number;
895
- readonly fuelClock: number;
896
- };
897
- /** One entry per live segment, in segment order. */
898
- readonly pools: readonly SegmentPools[];
899
- readonly charts: readonly ChartStats[];
900
- }
901
- /** A trace rule of `traceConfigure` and `traceWatch`: each absent field
902
- * matches anything. */
903
- export interface TraceRule {
904
- at?: 'start' | 'take';
905
- chart?: string;
906
- /** An actor's name; a trailing `*` makes it a prefix. */
907
- actor?: string;
908
- /** An event descriptor, SCXML's prefix rule. */
909
- event?: string;
910
- session?: Session;
911
- from?: readonly ('host' | 'actor' | 'timer' | 'spawn' | 'sampled' | 'unsampled')[];
912
- /** What a match decides (default `'keep'`); a number samples that share
913
- * of trace IDs. */
914
- sample?: 'keep' | 'sample' | 'drop' | number;
915
- detail?: TraceDetail;
916
- values?: boolean;
917
- perSecond?: number;
918
- burst?: number;
919
- }
920
- /** How much a trace records. */
921
- export type TraceDetail = 'summary' | 'decisions' | 'full' | 'off';
922
- /** The params of `traceConfigure`, which replace the last ones. */
923
- export interface TraceConfigureParams {
924
- /** Default `'summary'`. */
925
- detail?: TraceDetail;
926
- /** Default false. */
927
- values?: boolean;
928
- /** The share of new traces sampled, 0 to 1 (default 1). */
929
- sample?: number;
930
- /** False writes no records; traceparents still flow (default true). */
931
- records?: boolean;
932
- /** At most 32. */
933
- rules?: readonly TraceRule[];
934
- }
935
- /** The params of `traceWatch`. */
936
- export interface TraceWatchParams {
937
- /** At least one. */
938
- rules: readonly TraceRule[];
939
- /** On the host's clock; `null`: no end (default 900). */
940
- seconds?: number | null;
941
- }
942
- /** `traceWatch`'s result. */
943
- export interface TraceWatchResult {
944
- readonly id: number;
945
- }
946
- /** The params of `traceUnwatch`. */
947
- export interface TraceUnwatchParams {
948
- id: number;
949
- }
950
- /** The params of `traceSpansDecode`. */
951
- export interface TraceSpansDecodeParams {
952
- /** An OTLP traces request, as the telemetry handler gets it. */
953
- traces: Uint8Array;
954
- }
955
- /** A span event. */
956
- export interface SpanEvent {
957
- readonly name: string;
958
- readonly time: number | bigint;
959
- readonly attributes: { readonly [key: string]: ReceivedValue };
960
- }
961
- /** A span of `traceSpansDecode`. */
962
- export interface Span {
963
- /** Lowercase hex. */
964
- readonly trace: string;
965
- readonly span: string;
966
- /** `null` for a root span. */
967
- readonly parent: string | null;
968
- readonly name: string;
969
- /** OTLP's span kind. */
970
- readonly kind: number;
971
- /** Nanoseconds since the Unix epoch (a bigint past 2^53). */
972
- readonly start: number | bigint;
973
- readonly end: number | bigint;
974
- /** OTLP's status code. */
975
- readonly status: number;
976
- readonly statusMessage: string;
977
- readonly attributes: { readonly [key: string]: ReceivedValue };
978
- readonly events: readonly SpanEvent[];
979
- }
980
- /** `traceSpansDecode`'s result. */
981
- export interface TraceSpansDecodeResult {
982
- readonly spans: readonly Span[];
983
- }
984
- /** The result of the methods that answer nothing: `{}`. */
985
- export type EmptyResult = { readonly [key: string]: never };
769
+
770
+ // ---- the host -----------------------------------------------------------
986
771
 
987
772
  /** Runs actors: many charts, many images, from a handful of actors to
988
773
  * millions, on the runtime's event loop. Inputs (`spawn`, `send`, ...)
@@ -996,29 +781,25 @@ export type EmptyResult = { readonly [key: string]: never };
996
781
  * an answer included.
997
782
  *
998
783
  * @example
999
- * const host = new Host({ systemID: 'shop' }, { log: (host, entry) => console.log(entry.text) });
1000
- * host.addImage(compileCharts([{ name: 'order.scxml', text }]).image);
1001
- * const order = host.spawn(host.chart('order'));
1002
- * host.send(order, 'checkout');
784
+ * const compiled = compileCharts([{ name: 'order.scxml', text }]);
785
+ * const host = new Host(compiled, { system: 'shop', log: (entry) => console.log(entry.text) });
786
+ * compiled.close();
787
+ * const order = host.spawn('order');
788
+ * order.send('checkout');
1003
789
  * await host.idle();
1004
790
  * host.close();
1005
791
  */
1006
792
  export class Host implements Disposable, AsyncDisposable {
1007
- /** A host for `config`, with the handlers and choices of `options`.
1008
- * Throws `TinyactorsError` (`TA_ERROR_INVALID`) for a config the host
1009
- * does not take, `TypeError` for options it does not take. */
1010
- constructor(config: HostConfig, options?: HostOptions);
1011
- /** A new host running a snapshot `host.snapshot()` gave, with the config
1012
- * it was taken with (its `systemID` is checked) and the options `new Host`
1013
- * takes, its `datamodel` the snapshot's. Every session stays the same, and
1014
- * its clock goes on from the snapshot's time, whatever clock reads it.
1015
- * Invocations that were running are announced again to `services`, with
1016
- * `invocation.restored` true. A snapshot of a build whose layout differs
1017
- * throws `TA_ERROR_INVALID`. */
1018
- static restore(snapshot: Uint8Array | ArrayBuffer, config: HostConfig, options?: HostOptions): Host;
1019
-
1020
- /** The host's clock rate, `system.ticksPerSecond`. */
1021
- readonly ticksPerSecond: number;
793
+ // ---- the application API ----
794
+
795
+ /** A host of system `options.system` running `charts` (each image added
796
+ * in order, a segment each: `addImage`), with the handlers and choices
797
+ * of `options`. Throws `TinyactorsError` (`TA_ERROR_INVALID`) for a
798
+ * config the host does not take, `TypeError` for options it does not
799
+ * take. */
800
+ constructor(charts: Charts, options: HostOptions);
801
+ /** The system id, `options.system`. */
802
+ readonly system: string;
1022
803
  /** True once `close()` ran; every input of a closed host throws. */
1023
804
  readonly closed: boolean;
1024
805
  /** Milliseconds from the last idle turn to the next deadline (a delayed
@@ -1026,58 +807,28 @@ export class Host implements Disposable, AsyncDisposable {
1026
807
  * staged); `undefined` for none. An input given since that turn has not
1027
808
  * run yet, so its deadlines are not in it. */
1028
809
  readonly nextDeadline: number | undefined;
1029
- /** The quickjs engine's heap in bytes, every actor's together, read on
1030
- * each access (cheap): what `quickjs.memoryLimit` bounds. `undefined` on
1031
- * a native host and once closed. */
1032
- readonly quickjsHeapBytes: number | undefined;
1033
810
 
1034
- /** Loads a compiled image, which it copies, and returns its segment, a
1035
- * number. A chart whose name the host already has gets a new version:
1036
- * new actors are of it, running ones stay on theirs until `migrate`.
1037
- * Throws `TA_ERROR_INVALID` for bytes that are not an image. */
1038
- addImage(image: Uint8Array | ArrayBuffer): number;
1039
- /** The current version of chart `name`, for `spawn`. Throws
1040
- * `TA_ERROR_INVALID` when the host has no chart of that name. */
1041
- chart(name: string): ChartRef;
1042
- /** Compiles the documents of `charts` (`{ [name]: text }`, the first
1043
- * key the boot chart), adds the image and closes the compile result, in
1044
- * one call: `compileCharts`, `addImage` and `close()`. Returns the
1045
- * segment. Throws `compileCharts`'s `CompileError`, with every
1046
- * diagnostic, and adds nothing; `TypeError` for `charts` that is not an
1047
- * object or an option it does not take.
1048
- *
1049
- * @example
1050
- * host.addCharts({ 'order.scxml': text });
1051
- * const order = host.spawnChart('order');
1052
- */
1053
- addCharts(charts: { readonly [name: string]: string }, options?: AddChartsOptions): number;
1054
- /** Spawns the boot actors of the image of `segment`: a system manifest's
1055
- * `<actor>`s, or an actor of `compileCharts`' first chart. */
1056
- boot(segment: number): void;
1057
- /** Starts an actor of `ref` and returns its session. It runs in a later
1058
- * turn. */
1059
- spawn(ref: ChartRef, options?: SpawnOptions): bigint;
1060
- /** Starts an actor of the current version of chart `name`:
1061
- * `host.spawn(host.chart(name), options)`. */
1062
- spawnChart(name: string, options?: SpawnOptions): bigint;
811
+ /** Starts an actor of `chart`, a chart's name (its current version) or a
812
+ * `ChartRef` (a version), and returns it. It runs in a later turn.
813
+ * Throws `TA_ERROR_INVALID` for a chart the host does not have. */
814
+ spawn(chart: string | ChartRef, options?: SpawnOptions): Actor;
815
+ /** The live actor `which` names: a session, an Actor, the name it was
816
+ * spawned with (newest segment first), or an address of this system
817
+ * (text or an `Address`). Throws `StaleError` for no live actor,
818
+ * `InvalidError` for another system's address. */
819
+ actor(which: Session | Actor | string | Address): Actor;
820
+ /** Every live actor of the host (`actorList`, a page at a time), or the
821
+ * actors of the chart named `options.chart`. */
822
+ actors(options?: { chart?: string }): Promise<Actor[]>;
823
+
1063
824
  /** Puts `event`, with `data`, in the queue of the actor `target` names (a
1064
825
  * session or an address). Throws `TA_ERROR_STALE` for an actor that
1065
826
  * ended. */
1066
- send(target: Session | string | Address, event: string, data?: Value, options?: SendOptions): void;
827
+ send(target: Session | Actor | string | Address, event: string, data?: Value, options?: SendOptions): void;
1067
828
  /** The same, from a `SendMessage` (the transport's `send.message`). */
1068
829
  send(message: SendMessage): void;
1069
- /** Tells a sender that its send could not be delivered: the actor
1070
- * `sender` (a session or its address, the send's `origin`) gets
1071
- * `error.communication` with `sendid`. */
1072
- fail(sender: Session | string | Address, sendid?: string): void;
1073
- /** Sends each of `items` in order, and returns how many were taken: the
1074
- * rest, from the first one refused, were not sent. */
1075
- sendMany(items: readonly SendMessage[]): number;
1076
830
  /** Ends the actor. Throws `TA_ERROR_STALE` for one that already ended. */
1077
- terminate(session: Session): void;
1078
- /** The running actor spawned with `name`, newest segment first, or
1079
- * `undefined`. */
1080
- actorByName(name: string): bigint | undefined;
831
+ terminate(session: Session | Actor): void;
1081
832
 
1082
833
  /** Resolves at the next turn that finds nothing to do while no promise a
1083
834
  * handler returned is pending (an I/O processor's, a service's or its
@@ -1121,6 +872,54 @@ export class Host implements Disposable, AsyncDisposable {
1121
872
  actorContext(params: SessionParams, onResult: OnResult<ActorContextResult>, onError?: OnError | null): void;
1122
873
  /** `actorContext` given no handler: a promise of `{ variables }`. */
1123
874
  actorContext(params: SessionParams): Promise<ActorContextResult>;
875
+
876
+ /** Frees the host: the last telemetry requests go to the handler, the
877
+ * timer is cleared, pending typed methods and running services are
878
+ * dropped without being called. From a handler it waits for the end of
879
+ * the turn. Again: nothing. */
880
+ close(): void;
881
+ /** `close()`. */
882
+ [Symbol.dispose](): void;
883
+ /** `close()`, then the promises the telemetry handler returned at it. */
884
+ [Symbol.asyncDispose](): Promise<void>;
885
+
886
+
887
+ // ---- operating a host (README.md, "Operating a host") ----
888
+ //
889
+ // A snapshot and its restore; the clock's rate and quickjs's heap;
890
+ // images, segments and versions; the typed methods that inspect and
891
+ // trace the host (their two forms as above); metrics; hibernation by a
892
+ // policy of your own; migration.
893
+
894
+ /** A new host running a snapshot `host.snapshot()` gave, with the system
895
+ * it was taken with (checked) and the options `new Host` takes, its
896
+ * `datamodel` the snapshot's; of `charts`, the images the snapshot does
897
+ * not hold (compared by their bytes) are added after its own. Every
898
+ * session stays the same, and its clock goes on from the snapshot's
899
+ * time, whatever clock reads it. Invocations that were running are
900
+ * announced again to `services`, with `invocation.restored` true. A
901
+ * snapshot of a build whose layout differs throws `TA_ERROR_INVALID`. */
902
+ static restore(snapshot: Uint8Array | ArrayBuffer, charts: Charts, options: HostOptions): Host;
903
+
904
+ /** The host's clock rate, `system.ticksPerSecond`. */
905
+ readonly ticksPerSecond: number;
906
+ /** The quickjs engine's heap in bytes, every actor's together, read on
907
+ * each access (cheap): what `quickjs.memoryLimit` bounds. `undefined` on
908
+ * a native host and once closed. */
909
+ readonly quickjsHeapBytes: number | undefined;
910
+
911
+ /** Loads a compiled image, which it copies, and returns its segment, a
912
+ * number. A chart whose name the host already has gets a new version:
913
+ * new actors are of it, running ones stay on theirs until `migrate`.
914
+ * Throws `TA_ERROR_INVALID` for bytes that are not an image. */
915
+ addImage(image: Uint8Array | ArrayBuffer): number;
916
+ /** The current version of chart `name`, for `spawn`. Throws
917
+ * `TA_ERROR_INVALID` when the host has no chart of that name. */
918
+ chart(name: string): ChartRef;
919
+ /** Spawns the boot actors of the image of `segment`: a system manifest's
920
+ * `<actor>`s, or an actor of `compileCharts`' first chart. */
921
+ boot(segment: number): void;
922
+
1124
923
  /** The host's sessions a page at a time, `{ sessions, cursor }`, `cursor`
1125
924
  * `null` after the last page. Params `{ cursor?, limit? }` (1 to 512,
1126
925
  * default 256). */
@@ -1142,6 +941,7 @@ export class Host implements Disposable, AsyncDisposable {
1142
941
  hostConfig(params: NoParams, onResult: OnResult<EffectiveHostConfig>, onError?: OnError | null): void;
1143
942
  /** `hostConfig` given no handler: a promise of the effective config. */
1144
943
  hostConfig(params?: NoParams): Promise<EffectiveHostConfig>;
944
+
1145
945
  /** Sets what every actor traces: `{ detail, values, sample, records,
1146
946
  * rules }`. */
1147
947
  traceConfigure(params: TraceConfigureParams | undefined, onResult: OnResult<EmptyResult>, onError?: OnError | null): void;
@@ -1172,6 +972,7 @@ export class Host implements Disposable, AsyncDisposable {
1172
972
  * collector's `/v1/metrics`). `TA_ERROR_STATE` without `telemetry` in the
1173
973
  * config. */
1174
974
  metrics(): Uint8Array;
975
+
1175
976
  /** Finds cold actors: at most `limit` sessions that did not run since
1176
977
  * the previous sweep and can be hibernated now, looking at most at `maxScan`
1177
978
  * actors (each an integer from 0 to 2^32-1). The first sweep after an
@@ -1185,21 +986,22 @@ export class Host implements Disposable, AsyncDisposable {
1185
986
  * ended or never was, `TA_ERROR_UNSUPPORTED` when a variable holds what
1186
987
  * the datamodel cannot store (the message names it); it stays where it
1187
988
  * is then. */
1188
- hibernate(session: Session): Uint8Array;
989
+ hibernate(session: Session | Actor): Uint8Array;
1189
990
  /** Puts a hibernated actor back from the blob `hibernate` gave; its
1190
991
  * waiting events run at the next turn. Only its latest blob: one of an
1191
992
  * earlier hibernation (a store that fell behind) throws `TA_ERROR_STALE`,
1192
993
  * another session's `TA_ERROR_INVALID`, and the actor stays hibernated.
1193
994
  * On a restored host a blob of a hibernation made after the snapshot is
1194
995
  * taken too. */
1195
- wake(session: Session, blob: Uint8Array | ArrayBuffer): void;
996
+ wake(session: Session | Actor, blob: Uint8Array | ArrayBuffer): void;
997
+
1196
998
  /** Starts moving running actors (every chart's, `chart`'s, or one
1197
999
  * `session`) to the current version of their chart, in later turns; each
1198
1000
  * gets `error.platform.upgrade` with its old variables. Returns the
1199
- * migration's id, which `migrated`, `migrationDone` and the wake handler
1200
- * name. Throws `TA_ERROR_INVALID` for a chart the host does not have and
1001
+ * migration's id, which `migrated` and `migrationDone` name. Throws `TA_ERROR_INVALID` for a chart the host does not have and
1201
1002
  * `TA_ERROR_STALE` for a session that ended. */
1202
1003
  migrate(options?: MigrateOptions): number;
1004
+
1203
1005
  /** The whole host as one `Uint8Array`: every segment, the images, the system
1204
1006
  * id, the host's time (its clocks advanced first: the time of the call,
1205
1007
  * as `now()` reads it) and the datamodel's state, for `Host.restore` on the
@@ -1209,13 +1011,520 @@ export class Host implements Disposable, AsyncDisposable {
1209
1011
  * `TA_ERROR_UNSUPPORTED`. */
1210
1012
  snapshot(): Uint8Array;
1211
1013
 
1212
- /** Frees the host: the last telemetry requests go to the handler, the
1213
- * timer is cleared, pending typed methods and running services are
1214
- * dropped without being called. From a handler it waits for the end of
1215
- * the turn. Again: nothing. */
1216
- close(): void;
1217
- /** `close()`. */
1218
- [Symbol.dispose](): void;
1219
- /** `close()`, then the promises the telemetry handler returned at it. */
1220
- [Symbol.asyncDispose](): Promise<void>;
1014
+ // ---- wire format (README.md, "Wire format") ----
1015
+ //
1016
+ // A transport's messages delivered and failed on the receiving side;
1017
+ // `send(message)`, above, takes one too.
1018
+
1019
+ /** Tells a sender that its send could not be delivered: the actor
1020
+ * `sender` (a session or its address, the send's `origin`) gets
1021
+ * `error.communication` with `sendid`. */
1022
+ fail(sender: Session | Actor | string | Address, sendid?: string): void;
1023
+ /** Sends each of `items` in order, and returns how many were taken: the
1024
+ * rest, from the first one refused, were not sent. */
1025
+ sendMany(items: readonly SendMessage[]): number;
1026
+ }
1027
+
1028
+ // =========================================================================
1029
+ // OPERATING A HOST
1030
+ // =========================================================================
1031
+ //
1032
+ // What an operator's tools, a deploy script or an admin endpoint use: the
1033
+ // host's config and sizes, inspection, telemetry, hibernation by a policy
1034
+ // of your own, images, segments and migration, snapshots (README.md,
1035
+ // "Operating a host"). The Host's own methods for them are grouped in the
1036
+ // class, under the same heading.
1037
+
1038
+ // ---- config and sizes ---------------------------------------------------
1039
+
1040
+ /** The rest of the host's config, `options.config`: plain values, checked
1041
+ * by the host, every absent key a default (the host's, never the
1042
+ * package's). A key the host does not take, or a value of the wrong type,
1043
+ * throws a `TinyactorsError` (`TA_ERROR_INVALID`) at `new Host`, with the
1044
+ * host's `reason` and the key as `path` (`system.maxActors`). The system
1045
+ * id is `options.system` and the I/O processors `options.ioProcessors`:
1046
+ * a `systemID` or `ioProcessors` here is a `TypeError`.
1047
+ * `host.hostConfig()` answers the whole config with every default filled
1048
+ * in, as {@link EffectiveHostConfig}.
1049
+ *
1050
+ * @example
1051
+ * const config = { system: { maxActors: 10_000 }, telemetry: { resource: { 'service.name': 'orders' } } };
1052
+ */
1053
+ export interface HostConfig {
1054
+ /** The capacities of each new segment, each its first size, not a cap
1055
+ * (a pool that fills grows its segment). */
1056
+ system?: SystemConfig;
1057
+ /** Actors a migration looks at per run (default 256). */
1058
+ migrateQuantum?: number;
1059
+ /** Present: the host has an OTLP encoder, and `options.telemetry` gets
1060
+ * its requests. Absent: none, and nothing is paid for it. */
1061
+ telemetry?: TelemetryConfig;
1062
+ }
1063
+
1064
+ /** Each new segment's first sizes: unsigned integers, 0 or absent for the
1065
+ * host's default; larger values are clamped to the host's limits. */
1066
+ export interface SystemConfig {
1067
+ /** Default 64, at most 8388606. */
1068
+ maxActors?: number;
1069
+ /** Queued events; default 256. */
1070
+ maxEvents?: number;
1071
+ /** Delayed sends and timeouts; default 64. */
1072
+ maxTimers?: number;
1073
+ /** Actors that may be in a step at once; default 4. */
1074
+ workspaces?: number;
1075
+ /** Default 16. */
1076
+ maxRequests?: number;
1077
+ /** Default 64. */
1078
+ outbox?: number;
1079
+ /** Default 1000. */
1080
+ quantum?: number;
1081
+ /** Default 0: derived from the image and `maxActors`. */
1082
+ instanceBytes?: number;
1083
+ /** Default 16384 + 16 per actor of `maxActors`. */
1084
+ stringBytes?: number;
1085
+ /** The host's clock rate; default 1e9 (nanoseconds). */
1086
+ ticksPerSecond?: number;
1087
+ /** The trace journal; default 131072, at least 65536. */
1088
+ traceBytes?: number;
1089
+ /** Default `maxEvents`. */
1090
+ traceContexts?: number;
1091
+ /** Default 16, at most 255. */
1092
+ traceRules?: number;
1093
+ /** The seed of the trace IDs: the same seed gives the same IDs. Without
1094
+ * one, each new host draws a random seed (`crypto.getRandomValues`);
1095
+ * set it to reproduce a test's traces. */
1096
+ traceSeed?: number;
1097
+ /** Write trace records (default true), so export or a watch can be
1098
+ * turned on later. */
1099
+ tracing?: boolean;
1100
+ }
1101
+
1102
+ /** The OTLP encoder: unsigned integers, 0 or absent for its default. */
1103
+ export interface TelemetryConfig {
1104
+ /** Default 1048576, from 65536 to 1073741824. */
1105
+ stagingBytes?: number;
1106
+ /** Default a quarter of `stagingBytes`. */
1107
+ logBytes?: number;
1108
+ /** Default 1024. */
1109
+ openSpans?: number;
1110
+ /** Default 8 per open span. */
1111
+ chunks?: number;
1112
+ /** Default 64. */
1113
+ scopes?: number;
1114
+ /** Default 256. */
1115
+ valueLimit?: number;
1116
+ /** Default 16384. */
1117
+ renderBytes?: number;
1118
+ /** Default 4096. */
1119
+ resourceBytes?: number;
1120
+ /** Default 65536. */
1121
+ metricBytes?: number;
1122
+ /** Default 64. */
1123
+ spanMetricCharts?: number;
1124
+ /** A request is ready this long after its first record, in the host's
1125
+ * clock ticks; 0 or absent: only when the staging is full. */
1126
+ flushInterval?: number;
1127
+ /** A macrostep is a root span linked to its cause (default false). */
1128
+ linkParents?: boolean;
1129
+ /** Event data and assigned values in the spans (default false: they may
1130
+ * hold personal data). */
1131
+ values?: boolean;
1132
+ /** `<log>`s and failed actions as log records (default true). */
1133
+ logs?: boolean;
1134
+ /** Attributes on every request (`service.name`, ...), at most 32. */
1135
+ resource?: { readonly [key: string]: string };
1136
+ }
1137
+
1138
+ /** The config a host runs with, every key present, as `hostConfig`
1139
+ * answers it: a host made from it answers the same. */
1140
+ export interface EffectiveHostConfig {
1141
+ readonly systemID: string;
1142
+ readonly system: Readonly<Required<SystemConfig>>;
1143
+ /** The I/O processors, in the order `options.ioProcessors` gave them. */
1144
+ readonly ioProcessors: readonly { readonly type: string; readonly location?: string }[];
1145
+ readonly migrateQuantum: number;
1146
+ /** Only when the host has an encoder. */
1147
+ readonly telemetry?: Readonly<Required<TelemetryConfig>>;
1148
+ }
1149
+
1150
+ // ---- images, segments and migration -------------------------------------
1151
+
1152
+ /** A chart's current version in a host, from `host.chart(name)`, for
1153
+ * `host.spawn`. */
1154
+ export interface ChartRef {
1155
+ /** The segment of the image that holds it. */
1156
+ readonly segment: number;
1157
+ /** Its index in that image. */
1158
+ readonly chart: number;
1159
+ }
1160
+
1161
+ /** The options of `host.migrate`. */
1162
+ export interface MigrateOptions {
1163
+ /** A chart's name; none: every chart. */
1164
+ chart?: string;
1165
+ /** One actor. */
1166
+ session?: Session | Actor;
1167
+ /** Load the hibernated actors from the store (as `resident` allows),
1168
+ * for the migration to move. */
1169
+ wake?: boolean;
1170
+ /** Milliseconds of the host's clock from now, rounded up to its next
1171
+ * tick; 0 or none: no timeout. */
1172
+ timeout?: number;
1173
+ }
1174
+
1175
+ /** An actor a migration moved: a view, valid while the handler runs. */
1176
+ export interface Migrated {
1177
+ /** The host that handed it out. */
1178
+ readonly host: Host;
1179
+ readonly session: bigint;
1180
+ /** The segment of its new version. */
1181
+ readonly segment: number;
1182
+ /** The chart's name. */
1183
+ readonly chart: string;
1184
+ /** The migration's id, as `host.migrate` returned it. */
1185
+ readonly migration: number;
1186
+ }
1187
+
1188
+ /** A session a migration could not move: it stays on its version.
1189
+ * `reason` names core's status, `'TA_ERROR_UNSUPPORTED'` when its state
1190
+ * cannot be written out (a value outside the value table). */
1191
+ export interface MigrationFailure {
1192
+ readonly session: bigint;
1193
+ readonly reason: string;
1194
+ }
1195
+
1196
+ /** A migration's end: how many actors it moved, the ones it could not move
1197
+ * and why (they stay on their version), and the sessions its timeout left
1198
+ * behind. */
1199
+ export interface MigrationResult {
1200
+ readonly migration: number;
1201
+ readonly migrated: number;
1202
+ readonly failed: readonly MigrationFailure[];
1203
+ readonly pending: readonly bigint[];
1204
+ }
1205
+
1206
+ // ---- inspection ---------------------------------------------------------
1207
+
1208
+ /** The params of `actorList`. */
1209
+ export interface ActorListParams {
1210
+ /** From the previous page; absent: the first. */
1211
+ cursor?: number;
1212
+ /** 1 to 512, default 256. */
1213
+ limit?: number;
1214
+ }
1215
+
1216
+ /** `actorList`'s result: a page of sessions. */
1217
+ export interface ActorListResult {
1218
+ readonly sessions: readonly number[];
1219
+ /** The next page's cursor, opaque; `null` after the last page. */
1220
+ readonly cursor: number | null;
1221
+ }
1222
+
1223
+ /** A pool of a segment: its size, what it holds, the most it held. */
1224
+ export interface Pool {
1225
+ readonly capacity: number;
1226
+ readonly used: number;
1227
+ readonly highWater: number;
1228
+ }
1229
+
1230
+ /** One live segment's pools, in `host.stats`. */
1231
+ export interface SegmentPools {
1232
+ /** The segment, as `addImage` returned it. */
1233
+ readonly segment: number;
1234
+ readonly actors: Pool;
1235
+ readonly events: Pool;
1236
+ readonly timers: Pool;
1237
+ readonly workspaces: Pool;
1238
+ readonly requests: Pool;
1239
+ /** The slab of instances and strings, in bytes. */
1240
+ readonly slabBytes: Pool;
1241
+ }
1242
+
1243
+ /** One chart's counters, summed over every segment, retired versions
1244
+ * included. */
1245
+ export interface ChartStats {
1246
+ readonly name: string;
1247
+ readonly actors: number;
1248
+ readonly hibernated: number;
1249
+ readonly spawned: number;
1250
+ readonly ended: number;
1251
+ readonly turns: number;
1252
+ readonly macrosteps: number;
1253
+ readonly fuel: number;
1254
+ readonly errorsExecution: number;
1255
+ readonly errorsCommunication: number;
1256
+ readonly errorsPlatform: number;
1257
+ readonly faults: number;
1258
+ }
1259
+
1260
+ /** `hostStats`'s result. */
1261
+ export interface HostStatsResult {
1262
+ readonly host: {
1263
+ readonly segments: number;
1264
+ readonly actors: number;
1265
+ readonly hibernated: number;
1266
+ readonly runnable: number;
1267
+ readonly migrations: number;
1268
+ /** The live segments' regions; the host's copies of the images are not
1269
+ * in it. */
1270
+ readonly regionBytes: number;
1271
+ readonly delivered: number;
1272
+ readonly routed: number;
1273
+ readonly migrated: number;
1274
+ readonly retired: number;
1275
+ readonly fuelClock: number;
1276
+ };
1277
+ /** One entry per live segment, in segment order. */
1278
+ readonly pools: readonly SegmentPools[];
1279
+ readonly charts: readonly ChartStats[];
1280
+ }
1281
+
1282
+ // ---- tracing ------------------------------------------------------------
1283
+
1284
+ /** A trace rule of `traceConfigure` and `traceWatch`: each absent field
1285
+ * matches anything. */
1286
+ export interface TraceRule {
1287
+ at?: 'start' | 'take';
1288
+ chart?: string;
1289
+ /** An actor's name; a trailing `*` makes it a prefix. */
1290
+ actor?: string;
1291
+ /** An event descriptor, SCXML's prefix rule. */
1292
+ event?: string;
1293
+ session?: Session;
1294
+ from?: readonly ('host' | 'actor' | 'timer' | 'spawn' | 'sampled' | 'unsampled')[];
1295
+ /** What a match decides (default `'keep'`); a number samples that share
1296
+ * of trace IDs. */
1297
+ sample?: 'keep' | 'sample' | 'drop' | number;
1298
+ detail?: TraceDetail;
1299
+ values?: boolean;
1300
+ perSecond?: number;
1301
+ burst?: number;
1302
+ }
1303
+
1304
+ /** How much a trace records. */
1305
+ export type TraceDetail = 'summary' | 'decisions' | 'full' | 'off';
1306
+
1307
+ /** The params of `traceConfigure`, which replace the last ones. */
1308
+ export interface TraceConfigureParams {
1309
+ /** Default `'summary'`. */
1310
+ detail?: TraceDetail;
1311
+ /** Default false. */
1312
+ values?: boolean;
1313
+ /** The share of new traces sampled, 0 to 1 (default 1). */
1314
+ sample?: number;
1315
+ /** False writes no records; traceparents still flow (default true). */
1316
+ records?: boolean;
1317
+ /** At most 32. */
1318
+ rules?: readonly TraceRule[];
1319
+ }
1320
+
1321
+ /** The params of `traceWatch`. */
1322
+ export interface TraceWatchParams {
1323
+ /** At least one. */
1324
+ rules: readonly TraceRule[];
1325
+ /** On the host's clock; `null`: no end (default 900). */
1326
+ seconds?: number | null;
1327
+ }
1328
+
1329
+ /** `traceWatch`'s result. */
1330
+ export interface TraceWatchResult {
1331
+ readonly id: number;
1332
+ }
1333
+
1334
+ /** The params of `traceUnwatch`. */
1335
+ export interface TraceUnwatchParams {
1336
+ id: number;
1337
+ }
1338
+
1339
+ /** The params of `traceSpansDecode`. */
1340
+ export interface TraceSpansDecodeParams {
1341
+ /** An OTLP traces request, as the telemetry handler gets it. */
1342
+ traces: Uint8Array;
1343
+ }
1344
+
1345
+ /** A span event. */
1346
+ export interface SpanEvent {
1347
+ readonly name: string;
1348
+ readonly time: number | bigint;
1349
+ readonly attributes: { readonly [key: string]: ReceivedValue };
1350
+ }
1351
+
1352
+ /** A span of `traceSpansDecode`. */
1353
+ export interface Span {
1354
+ /** Lowercase hex. */
1355
+ readonly trace: string;
1356
+ readonly span: string;
1357
+ /** `null` for a root span. */
1358
+ readonly parent: string | null;
1359
+ readonly name: string;
1360
+ /** OTLP's span kind. */
1361
+ readonly kind: number;
1362
+ /** Nanoseconds since the Unix epoch (a bigint past 2^53). */
1363
+ readonly start: number | bigint;
1364
+ readonly end: number | bigint;
1365
+ /** OTLP's status code. */
1366
+ readonly status: number;
1367
+ readonly statusMessage: string;
1368
+ readonly attributes: { readonly [key: string]: ReceivedValue };
1369
+ readonly events: readonly SpanEvent[];
1370
+ }
1371
+
1372
+ /** `traceSpansDecode`'s result. */
1373
+ export interface TraceSpansDecodeResult {
1374
+ readonly spans: readonly Span[];
1375
+ }
1376
+
1377
+ /** The result of the methods that answer nothing: `{}`. */
1378
+ export type EmptyResult = { readonly [key: string]: never };
1379
+
1380
+ // =========================================================================
1381
+ // WIRE FORMAT
1382
+ // =========================================================================
1383
+ //
1384
+ // What values, sends and addresses become when they leave the process:
1385
+ // CBOR, a transport's messages, addresses read into their parts, SCXML's
1386
+ // BasicHTTP, an OTLP export read back (README.md, "Wire format"). An
1387
+ // application of one host and its own store needs none of it.
1388
+
1389
+ // ---- values as bytes ----------------------------------------------------
1390
+
1391
+ /** What `encode` writes: a {@link Value}, or one holding `Address`es,
1392
+ * which it writes as CBOR's tag 32 (an actor reference). */
1393
+ export type Encodable =
1394
+ | Value
1395
+ | Address
1396
+ | Encodable[]
1397
+ | { [key: string]: Encodable };
1398
+
1399
+ /** A value as CBOR bytes, the form to store or send it in. An `Address`
1400
+ * is tag 32 on its text.
1401
+ *
1402
+ * Throws a `TinyactorsError`: `TA_ERROR_UNSUPPORTED` for what is not a
1403
+ * {@link Value} (a function, a symbol, a `Date`, a `Map`, a class's
1404
+ * instance, a typed array other than `Uint8Array`), `TA_ERROR_INVALID` for
1405
+ * what a value cannot hold (a string with a lone surrogate, a `bigint` past
1406
+ * 64 bits, a cycle or nesting deeper than 64). A getter's exception passes
1407
+ * through.
1408
+ *
1409
+ * @example
1410
+ * const bytes = encode({ sku: 'tea', qty: 2 });
1411
+ * decode(bytes); // { sku: 'tea', qty: 2 }
1412
+ */
1413
+ export function encode(value: Encodable): Uint8Array;
1414
+
1415
+ /** The value of the one CBOR item that fills `bytes`: the inverse of
1416
+ * {@link encode}, tag 32 an `Address`. Throws a `TinyactorsError` (`TA_ERROR_INVALID`) for bytes
1417
+ * that are not one such item, a `TypeError` for an argument that is not
1418
+ * bytes. */
1419
+ export function decode(bytes: Uint8Array | ArrayBuffer): ReceivedValue;
1420
+
1421
+ // ---- addresses ----------------------------------------------------------
1422
+
1423
+ /** An actor's address: `tinyactors://<system>/#_scxml_<session>`, or
1424
+ * `tinyactors://<system>/@<name>` for a named actor. Immutable. Its parts
1425
+ * are read from the text on each access, `undefined` for a part the text
1426
+ * lacks (any text makes an `Address`; one that is not an address has no
1427
+ * parts). */
1428
+ export class Address {
1429
+ constructor(text: string);
1430
+ /** The address of a session of system `system`. */
1431
+ static fromSession(system: string, session: Session): Address;
1432
+ /** The address of the actor named `name` in system `system`; the name is
1433
+ * percent-encoded. */
1434
+ static fromName(system: string, name: string): Address;
1435
+ readonly text: string;
1436
+ /** The system id. */
1437
+ readonly system: string | undefined;
1438
+ readonly session: bigint | undefined;
1439
+ /** The actor's name, decoded. */
1440
+ readonly name: string | undefined;
1441
+ /** The text. */
1442
+ toString(): string;
1443
+ /** The text, so `JSON.stringify` writes an address as a string, which
1444
+ * `new Address(text)` and `host.send` read back. */
1445
+ toJSON(): string;
1446
+ }
1447
+
1448
+ // ---- other systems ------------------------------------------------------
1449
+
1450
+ /** An event for `host.send(message)` and `host.sendMany(items)`, in the
1451
+ * shape `send.message` has. Keys it does not know are ignored. */
1452
+ export interface SendMessage {
1453
+ /** A session, or an address (string or `Address`); a local address is
1454
+ * resolved to its actor. */
1455
+ target: Session | Actor | string | Address;
1456
+ event: string;
1457
+ data?: Value;
1458
+ /** The event's `_event.sendid`. */
1459
+ sendid?: string | null;
1460
+ /** The event's `_event.origin`: where an answer goes. */
1461
+ origin?: string | Address | null;
1462
+ /** The trace the event continues, as W3C text; text that does not parse
1463
+ * starts a new one. */
1464
+ traceparent?: string | null;
1465
+ }
1466
+
1467
+ // ---- BasicHTTP ----------------------------------------------------------
1468
+
1469
+ /** A form field of a BasicHTTP message. */
1470
+ export interface HTTPField {
1471
+ name: string;
1472
+ value: string;
1473
+ }
1474
+
1475
+ /** A BasicHTTP POST, the request SCXML's HTTP processor makes for a send. */
1476
+ export interface HTTPPost {
1477
+ /** `http://host[:port]/path`. */
1478
+ url: string;
1479
+ /** Written as the `_scxmleventname` field. */
1480
+ event?: string;
1481
+ fields?: readonly HTTPField[];
1482
+ /** The body, used when there are no fields; percent-encoded. */
1483
+ body?: string;
1484
+ }
1485
+
1486
+ /** An incoming BasicHTTP request, read. */
1487
+ export interface HTTPRequest {
1488
+ readonly method: string;
1489
+ readonly target: string;
1490
+ /** The body as received. */
1491
+ readonly body: string;
1492
+ /** The `_scxmleventname` field, else `HTTP.<METHOD>`. */
1493
+ readonly event: string;
1494
+ /** The decoded form fields, but `_scxmleventname`. */
1495
+ readonly fields: readonly HTTPField[];
1496
+ }
1497
+
1498
+ /** The bytes of a BasicHTTP POST, to write to a socket. A URL that is not
1499
+ * `http://host[:port]/path` throws `TA_ERROR_INVALID`. */
1500
+ export function encodeHTTPPost(post: HTTPPost): Uint8Array;
1501
+
1502
+ /** Reads an incoming BasicHTTP request: its event and form fields, for
1503
+ * `host.send`. A malformed request throws `TA_ERROR_INVALID`. */
1504
+ export function parseHTTPRequest(message: Uint8Array | ArrayBuffer): HTTPRequest;
1505
+
1506
+ // ---- an OTLP export, read back ------------------------------------------
1507
+
1508
+ /** The spans of an OTLP ExportTraceServiceRequest (the bytes a telemetry
1509
+ * handler gets for `'traces'`, or any exporter's), read without a host:
1510
+ * for tests and a collector of your own. Throws an `InvalidError` for bytes
1511
+ * that are not such a request, a `TypeError` for an argument that is not
1512
+ * bytes.
1513
+ *
1514
+ * @example
1515
+ * const spans = decodeTraces(data);
1516
+ * console.log(spans.map((span) => `${span.name} ${span.scope.attributes['tinyactors.chart.name']}`));
1517
+ */
1518
+ export function decodeTraces(bytes: Uint8Array | ArrayBuffer): DecodedSpan[];
1519
+
1520
+ /** A span as {@link decodeTraces} gives it: a {@link Span} and more of
1521
+ * what the request holds. */
1522
+ export interface DecodedSpan extends Span {
1523
+ /** OTLP's Span.flags. */
1524
+ readonly flags: number;
1525
+ readonly links: readonly { readonly trace: string; readonly span: string; readonly attributes: { readonly [key: string]: ReceivedValue } }[];
1526
+ /** Its resource's attributes (`service.name`, ...). */
1527
+ readonly resource: { readonly [key: string]: ReceivedValue };
1528
+ /** Its instrumentation scope. */
1529
+ readonly scope: { readonly name: string; readonly version: string; readonly attributes: { readonly [key: string]: ReceivedValue } };
1221
1530
  }