@tinyactors/wasm 0.0.0-stage → 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 ADDED
@@ -0,0 +1,1530 @@
1
+ // The types of @tinyactors/node and @tinyactors/wasm, one API (docs/api-map.md
2
+ // says where @tinyactors/wasm differs today). Every export has a doc comment, which an
3
+ // editor shows on hover; README.md and docs/guide/ teach the same API in
4
+ // order, with examples. Each declaration is a row of docs/api-map.md,
5
+ // which names the core behind it.
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
+ //
12
+ // Units: time is milliseconds (but telemetry.flushInterval, in the host's
13
+ // clock ticks, and traceWatch's seconds); sessions are bigints (inputs also
14
+ // take a safe integer from 1, and typed methods' results hold numbers);
15
+ // bytes the host hands out are Uint8Arrays (Buffers in @tinyactors/node),
16
+ // copied once, yours to keep.
17
+
18
+ // ---- disposal ------------------------------------------------------------
19
+
20
+ // `Symbol.dispose`, `Symbol.asyncDispose`, `Disposable` and
21
+ // `AsyncDisposable`, which a `Host` and a compile result implement, as
22
+ // TypeScript's `esnext.disposable` lib and @types/node declare them: a
23
+ // project need not add that lib, and these merge with it where it does.
24
+ declare global {
25
+ interface SymbolConstructor {
26
+ readonly dispose: unique symbol;
27
+ readonly asyncDispose: unique symbol;
28
+ }
29
+ interface Disposable {
30
+ [Symbol.dispose](): void;
31
+ }
32
+ interface AsyncDisposable {
33
+ [Symbol.asyncDispose](): PromiseLike<void>;
34
+ }
35
+ }
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
+
45
+ // ---- values -------------------------------------------------------------
46
+
47
+ /** An actor's session, as an input takes it: a `bigint` from 1 to
48
+ * 2^64-1, or a number that is a safe integer from 1 (as a database or
49
+ * JSON gives one back). Anything else is a `TypeError`. The calls and
50
+ * views return a `bigint`; a typed method's result holds a number, so
51
+ * compare with `Number(session) === listed`. */
52
+ export type Session = bigint | number;
53
+
54
+ /** A value that crosses between your program and a chart: event data,
55
+ * spawn params, a typed method's result, and what `encode` and `decode`
56
+ * convert. Numbers that are safe integers stay integers; integers past
57
+ * 2^53 are `bigint`s (up to 64 bits). Plain objects only: a function, a
58
+ * `Map`, a `Date` or a class's instance is refused. Values are copied when
59
+ * they cross. Inside a value an actor's address is its text. */
60
+ export type Value =
61
+ | undefined
62
+ | null
63
+ | boolean
64
+ | number
65
+ | bigint
66
+ | string
67
+ | Uint8Array
68
+ | Value[]
69
+ | { [key: string]: Value };
70
+
71
+ /** A {@link Value} the host hands you (`send.data`, `invocation.data`,
72
+ * `decode`, a typed method's variables), typed `any` as `JSON.parse`'s
73
+ * result is: it holds whatever a chart put there, so you read its fields
74
+ * without narrowing first. What it holds at run time is a `Value`. */
75
+ export type ReceivedValue = any;
76
+
77
+ // ---- errors -------------------------------------------------------------
78
+
79
+ /** The reason a call was refused, as `TinyactorsError.status` names it:
80
+ * - `TA_ERROR_INVALID`: an argument the host does not take (a chart it
81
+ * does not have, a config key, malformed bytes);
82
+ * - `TA_ERROR_STALE`: something that ended or never was (a session, a
83
+ * view read after its handler returned, a closed compile result);
84
+ * - `TA_ERROR_STATE`: not now (a snapshot from a handler, a second
85
+ * answer, hibernating an actor that is not at rest);
86
+ * - `TA_ERROR_UNSUPPORTED`: a value outside the value table;
87
+ * - `TA_ERROR_NO_MEMORY`: a pool at its largest size, or the system
88
+ * allocator refused. */
89
+ export type Status =
90
+ | 'TA_ERROR_INVALID'
91
+ | 'TA_ERROR_NO_MEMORY'
92
+ | 'TA_ERROR_STATE'
93
+ | 'TA_ERROR_STALE'
94
+ | 'TA_ERROR_UNSUPPORTED'
95
+ | 'TA_ERROR_EXECUTION'
96
+ | 'TA_ERROR_COMMUNICATION'
97
+ | 'TA_ERROR_ABORTED'
98
+ | 'TA_ERROR_FATAL'
99
+ | (string & {});
100
+
101
+ /** An error the host reported. A refused call has a `status` to branch
102
+ * on; a typed method's error, and a refused config, have `code`, `reason`
103
+ * and `path`, as the host wrote them. The message is for
104
+ * people: do not match on it.
105
+ *
106
+ * @example
107
+ * try { host.send(session, 'go'); }
108
+ * catch (error) { if (error instanceof StaleError) ... } // the actor ended
109
+ */
110
+ export class TinyactorsError extends Error {
111
+ constructor(
112
+ message?: string,
113
+ options?: { code?: number; reason?: string; path?: string; status?: Status },
114
+ );
115
+ /** A typed method's error: its JSON-RPC code (`-32001` for a session that
116
+ * does not exist, `-32602` for a param it does not take, ...). */
117
+ readonly code: number | undefined;
118
+ /** A typed method's error: a word for its cause (`stale`, `type`,
119
+ * `unknown`, `range`, `missing`, `state`, ...). */
120
+ readonly reason: string | undefined;
121
+ /** A typed method's error: the param it is about (`params.session`). */
122
+ readonly path: string | undefined;
123
+ /** A refused call's reason. */
124
+ readonly status: Status | undefined;
125
+ }
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
+
146
+ // ---- compiling ----------------------------------------------------------
147
+
148
+ /** A document to compile: its name, which error messages and `src`
149
+ * attributes name, and its text. */
150
+ export interface Source {
151
+ name: string;
152
+ text: string;
153
+ }
154
+
155
+ /** One message of the compiler about a document. */
156
+ export interface Diagnostic {
157
+ readonly severity: 'error' | 'warning' | 'note';
158
+ /** The compiler's code for the kind of problem. */
159
+ readonly code: number;
160
+ /** The document's name, as its {@link Source} gave it. */
161
+ readonly file: string;
162
+ /** From 1. */
163
+ readonly line: number;
164
+ /** From 1. */
165
+ readonly column: number;
166
+ readonly message: string;
167
+ }
168
+
169
+ /** A compilation found an error, and compiled nothing. Its message is the
170
+ * first error as a compiler prints it, `file:line:column: error:
171
+ * message`; its status is `TA_ERROR_INVALID`. */
172
+ export class CompileError extends TinyactorsError {
173
+ /** Every diagnostic of the compilation: errors, warnings and notes. */
174
+ readonly diagnostics: readonly Diagnostic[];
175
+ }
176
+
177
+ /** Thrown by a {@link Resolver} to refuse a document: the refusal becomes
178
+ * a compile error of the resolved file, at `line` and `column` when given,
179
+ * and the compile call throws a `CompileError`. */
180
+ export class ResolveError extends TinyactorsError {
181
+ constructor(message: string, options?: { line?: number; column?: number });
182
+ readonly line: number | undefined;
183
+ readonly column: number | undefined;
184
+ }
185
+
186
+ /** Reads a document a chart names with `src` (`<invoke src>`, `<script
187
+ * src>`, `<data src>`, a manifest's `<chart src>`): the text of `source`,
188
+ * named by the document `base`. Called during the compile call only.
189
+ * Throw a `ResolveError` to refuse; any other error is thrown from the
190
+ * compile call as it is.
191
+ *
192
+ * @example
193
+ * const resolver = (base, source) => readFileSync(join(root, source), 'utf8');
194
+ */
195
+ export type Resolver = (base: string, source: string) => string;
196
+
197
+ /** What a compile call returns: the image and the compiler's warnings. */
198
+ export interface Compiled extends Disposable {
199
+ /** The compiled image, for `host.addImage`: a `Uint8Array`, copied on the
200
+ * first read and yours from then on (write it to a file, load it
201
+ * elsewhere). A first read after `close()` throws `TA_ERROR_STALE`. */
202
+ readonly image: Uint8Array;
203
+ /** The warnings and notes of the compilation. */
204
+ readonly diagnostics: readonly Diagnostic[];
205
+ /** Frees the compiler's memory now; the garbage collector does it
206
+ * otherwise. Read `image` first. */
207
+ close(): void;
208
+ /** `close()`. */
209
+ [Symbol.dispose](): void;
210
+ }
211
+
212
+ /** Compiles SCXML documents into one image. Each chart is known by its
213
+ * `<scxml name>`. A `src` is answered by a source of that name or by
214
+ * `resolver`. The first source is the boot chart, which `host.boot`
215
+ * spawns. Throws `CompileError` with every diagnostic. Every expression
216
+ * and script of an `"ecmascript"` chart is parsed by the engine, running
217
+ * nothing: a syntax error is a warning in `diagnostics` (`cond:
218
+ * SyntaxError: ...`, at its element's line and column, a script's own
219
+ * line), and an error with `warningsAsErrors`.
220
+ *
221
+ * @example
222
+ * const compiled = compileCharts([{ name: 'order.scxml', text }]);
223
+ * const host = new Host(compiled, { system: 'shop' });
224
+ * compiled.close();
225
+ */
226
+ export function compileCharts(sources: readonly Source[], options?: CompileOptions): Compiled;
227
+
228
+ /** The options of `compileCharts`, `compileSystem` and `compileDir`. */
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;
233
+ /** Every warning is an error, and the compile throws `CompileError`:
234
+ * the compiler's own warnings and the syntax errors of the charts'
235
+ * ECMAScript, which are warnings otherwise, since SCXML makes such an
236
+ * expression an `error.execution` when it is evaluated. */
237
+ readonly warningsAsErrors?: boolean;
238
+ }
239
+
240
+ /** Compiles a system manifest: a `<system>` document of `<chart name
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).
258
+ *
259
+ * @example
260
+ * const compiled = compileDir(new URL('./charts/', import.meta.url));
261
+ * const host = new Host(compiled, { system: 'chat' });
262
+ * compiled.close();
263
+ */
264
+ export function compileDir(dir: string | URL, options?: { readonly resolver?: Resolver }): Compiled;
265
+
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;
272
+
273
+ // ---- the clock ----------------------------------------------------------
274
+
275
+ /** A clock for tests and simulations, which moves only when you move it.
276
+ * Give it to a host as `options.clock`; a host on it arms no timer.
277
+ *
278
+ * @example
279
+ * const clock = new SimulatedClock();
280
+ * const host = new Host(config, { clock });
281
+ * clock.increment(30_000); // a 30-second timeout, at once
282
+ * await host.idle();
283
+ */
284
+ export class SimulatedClock {
285
+ constructor();
286
+ /** Milliseconds since the clock was made. */
287
+ readonly now: number;
288
+ /** Moves the clock `ms` forward and schedules a turn on every host made
289
+ * with it; `await host.idle()` to see what ran. What is due runs once, at
290
+ * the new time, and a delay it starts counts from there: to see each of
291
+ * several deadlines, step to each. */
292
+ increment(ms: number): void;
293
+ }
294
+
295
+ // ---- what handlers get --------------------------------------------------
296
+
297
+ /** One `<send>` of a chart, as an I/O processor's handler, the transport
298
+ * or a service's `receive` gets it. A view of the host's memory: each
299
+ * field is read on first access, while the handler runs; after the
300
+ * handler returned, a read throws `TA_ERROR_STALE`. When the handler
301
+ * returns a promise, every field is read before the host moves on, and
302
+ * the view stays valid, `answer` and `fail` included, while the host is
303
+ * open. */
304
+ export interface Send {
305
+ /** The host that handed it out. */
306
+ readonly host: Host;
307
+ /** The sender's session. */
308
+ readonly session: bigint;
309
+ /** The sender, as an {@link Actor} (a new one at each read). */
310
+ readonly sender: Actor;
311
+ /** The event's name. */
312
+ readonly event: string;
313
+ /** `<send target>`: a string; an `Address` for the transport's sends;
314
+ * `undefined` when the send has none. */
315
+ readonly target: string | Address | undefined;
316
+ /** `<send id>`, or the id the host generated; `undefined` when none. A
317
+ * generated id is unique in the sender's session only (each session's
318
+ * first is `send.1`): key by `session` and `sendid` together. */
319
+ readonly sendid: string | undefined;
320
+ /** The `<param>`s as an object, or the `<content>`'s value. */
321
+ readonly data: ReceivedValue;
322
+ /** The I/O processor's type; `undefined` for the transport and a service. */
323
+ readonly type: string | undefined;
324
+ /** The sender's address. */
325
+ readonly origin: Address | undefined;
326
+ /** The sending step's trace as W3C `traceparent` text, for the header of
327
+ * the request you make; `undefined` when untraced. */
328
+ readonly traceparent: string | undefined;
329
+ /** The outgoing half, `{ target, event, data, sendid, origin,
330
+ * traceparent }`: what `host.send(message)` takes on the other side,
331
+ * unchanged. The transport's reason to exist; present on every send. A
332
+ * text field the send lacks (`sendid`, `origin`, `traceparent`) is
333
+ * `null`, as in a Python host's message, so encoded it is absent to
334
+ * every binding. Its addresses are `Address`es, which `JSON.stringify` writes as their text
335
+ * (`toJSON`) and `encode` as tag 32. */
336
+ readonly message: SendMessage;
337
+ /** Sends `event` back to the sender, with this send's `sendid`. It
338
+ * continues the send's trace unless `options.traceparent` is given
339
+ * (`null`: a new trace). Once: a second answer, or one after `fail()`,
340
+ * throws `TA_ERROR_STATE`, as does a closed host. Returns `true` when the
341
+ * sender gets it, `false` when the sender ended meanwhile (an answer
342
+ * given after the handler returned): nothing is delivered. */
343
+ answer(event: string, data?: Value, options?: AnswerOptions): boolean;
344
+ /** Gives the sender `error.communication` with this send's `sendid`:
345
+ * the request could not be done. Returns `true` when the sender gets it,
346
+ * `false` when it ended meanwhile, as `answer`. */
347
+ fail(): boolean;
348
+ }
349
+
350
+ /** The options of `send.answer`. */
351
+ export interface AnswerOptions {
352
+ /** The answer's trace: W3C text, or `null` for a new trace. Absent: the
353
+ * send's. */
354
+ traceparent?: string | null;
355
+ /** The answer's `_event.origin`. */
356
+ origin?: string | Address;
357
+ /** The message as you read it, for the chart's `_event.raw`. */
358
+ raw?: string;
359
+ }
360
+
361
+ /** A `<log>` line: a view, valid while the log handler runs. */
362
+ export interface LogEntry {
363
+ /** The host that handed it out. */
364
+ readonly host: Host;
365
+ /** The actor that logged. */
366
+ readonly session: bigint;
367
+ /** `<log label>`; `''` when it has none. */
368
+ readonly label: string;
369
+ /** The value of `<log expr>`, as text. */
370
+ readonly text: string;
371
+ }
372
+
373
+ /** An `<invoke>` of a service your program runs, as a service handler
374
+ * gets it. A record: keep it and use it while the service runs. */
375
+ export interface Invocation {
376
+ /** The host that runs the invocation. */
377
+ readonly host: Host;
378
+ /** The invoking actor. */
379
+ readonly session: bigint;
380
+ /** The `<invoke id>`, or the id the host generated. */
381
+ readonly invokeid: string;
382
+ /** `<invoke type>`. */
383
+ readonly type: string;
384
+ /** `<invoke src>`. */
385
+ readonly src: string;
386
+ /** The `<param>`s as an object, or the `<content>`'s value. */
387
+ readonly data: ReceivedValue;
388
+ /** The invoking step's trace, as W3C text. */
389
+ readonly traceparent: string | undefined;
390
+ /** True when a restored host announces an invocation that was running
391
+ * at its snapshot: start it again, or a stand-in. */
392
+ readonly restored: boolean;
393
+ /** False once the invocation ended (done, cancelled, failed) or the host
394
+ * closed. */
395
+ readonly running: boolean;
396
+ /** Sends `event` to the invoker, with `_event.invokeid` set. Continues
397
+ * the invoke's trace unless given one (`null`: a new trace). Throws
398
+ * `TA_ERROR_STALE` once the invocation ended. */
399
+ sendBack(event: string, data?: Value, options?: { traceparent?: string | null }): void;
400
+ /** Ends the service: the invoker gets `done.invoke.<invokeid>` with
401
+ * `data`, and the service is dropped without `stop`. Throws
402
+ * `TA_ERROR_STALE` once the invocation ended. */
403
+ done(data?: Value, options?: { traceparent?: string | null }): void;
404
+ }
405
+
406
+ /** What a service handler returns: any object, kept by the host until the
407
+ * invocation ends, whose methods the host calls. At `host.close()` a
408
+ * running service is dropped, not stopped. */
409
+ export interface Service {
410
+ /** A send of the invoker to the service (`<send target="#_<invokeid>">`,
411
+ * or an autoforwarded event); `send.type` is `undefined`. A throw, or a
412
+ * promise that rejects, is a crash: the invoker gets
413
+ * `error.communication` and the service is dropped. */
414
+ receive?(send: Send): void | Promise<void>;
415
+ /** The invoker left the state, which cancels the invocation. */
416
+ stop?(): void;
417
+ }
418
+
419
+ // ---- the host's options -------------------------------------------------
420
+
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;
495
+ }
496
+
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`.
510
+ *
511
+ * @example
512
+ * const database = {
513
+ * receive(send) {
514
+ * if (send.event === 'load') send.answer('loaded', { rows: [] });
515
+ * else send.fail();
516
+ * },
517
+ * };
518
+ */
519
+ export interface IOProcessor {
520
+ receive(send: Send): Handled;
521
+ /** Its location, which `_ioprocessors` shows the charts. */
522
+ readonly location?: string;
523
+ }
524
+
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>;
539
+ }
540
+
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;
551
+ }
552
+
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;
571
+ }
572
+
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;
585
+ }
586
+
587
+ /** What a handler returns: nothing, or a promise (typed `unknown`, so a
588
+ * handler that returns another value, as `(host, send) => sent.push(send)`
589
+ * does, is one too; the host ignores it). A send whose handler returns a
590
+ * promise is read in full before the host moves on, and may be answered
591
+ * when the promise gets there. */
592
+ export type Handled = unknown;
593
+
594
+ /** The quickjs sandbox's limits. Absent: the engine's default. */
595
+ export interface QuickJSOptions {
596
+ /** Interrupt checks one evaluation may make before it is stopped with
597
+ * `error.execution` (default 1,000,000, which lets a busy loop run for
598
+ * many seconds). */
599
+ maxOps?: number;
600
+ /** Bytes for the whole engine, every actor together (default 1 GiB,
601
+ * `2 ** 30`; `Number.MAX_SAFE_INTEGER` is as good as none). An
602
+ * evaluation that needs more is stopped with `error.execution`, reason
603
+ * `'memory'`. */
604
+ memoryLimit?: number;
605
+ /** Bytes of native stack for JavaScript. */
606
+ stackLimit?: number;
607
+ /** `'auto'` (the default): the actors of a chart that declares no
608
+ * top-level names share one context and its builtins; `'isolated'`: a
609
+ * context per actor. */
610
+ realm?: 'auto' | 'isolated';
611
+ }
612
+
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;
663
+ }
664
+
665
+ /** The options of `host.spawn`. */
666
+ export interface SpawnOptions {
667
+ /** The actor's name: `host.actor(name)` finds it, `_name` holds it, and
668
+ * its address is `tinyactors://<system>/@<name>`. */
669
+ name?: string;
670
+ /** Initial values: each key that names a top-level `<data>` replaces that
671
+ * variable's initial value; keys that name none are left out. */
672
+ params?: Value;
673
+ /** The trace the actor's start continues, as W3C text. */
674
+ traceparent?: string;
675
+ }
676
+
677
+ /** The options of `host.send(target, event, data, options)`. */
678
+ export interface SendOptions {
679
+ /** The event's `_event.sendid`. */
680
+ sendid?: string;
681
+ /** The trace the event continues, as W3C text; text that does not parse
682
+ * starts a new one. */
683
+ traceparent?: string;
684
+ /** The event's `_event.origin`. */
685
+ origin?: string | Address;
686
+ }
687
+
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.
693
+
694
+ /** A typed method's params, passed to the host as given (the host checks
695
+ * them); `undefined` for none. Each method has its own type below. */
696
+ export type Params = { [key: string]: Value } | undefined;
697
+
698
+ /** The params of a method that takes none: `undefined` or `{}`. */
699
+ export type NoParams = undefined | { readonly [key: string]: never };
700
+
701
+ /** A typed method's result handler, called once, in a later turn, with the
702
+ * method's result. */
703
+ export type OnResult<R = Value> = (result: R) => void;
704
+
705
+ /** A typed method's error handler. Without one, the error rejects a
706
+ * waiting `idle()` or is thrown as an uncaught exception. */
707
+ export type OnError = (error: TinyactorsError) => void;
708
+
709
+ /** An active configuration, as xstate's `value`: an atomic state is its
710
+ * id (`'s'`), a compound state `{ [state]: its active child }`, a parallel
711
+ * state `{ [state]: { [region]: ... } }`, an atomic region `{}`. */
712
+ export type StateValue = string | { readonly [state: string]: StateValue };
713
+
714
+ /** The params of `actorState`, `actorContext` and `actorGet`. */
715
+ export interface SessionParams {
716
+ session: Session | Actor;
717
+ }
718
+
719
+ /** `actorState`'s result. */
720
+ export interface ActorStateResult {
721
+ readonly value: StateValue;
722
+ /**
723
+ * Where each history state the actor has recorded would return, by its
724
+ * id: its parent state as it would be entered again, in the shape of
725
+ * `value` (a deep history down to the atomic states it recorded; a
726
+ * shallow one names the child it recorded). A history state records when
727
+ * its parent is exited; one that has recorded nothing is absent, so this
728
+ * is `{}` before any exit. A hibernated actor's state is refused
729
+ * (`reason` `'state'`): wake it first.
730
+ */
731
+ readonly history: { readonly [history: string]: StateValue };
732
+ }
733
+
734
+ /** `actorContext`'s result: each `<data>`, in the chart's order. */
735
+ export interface ActorContextResult {
736
+ readonly variables: { readonly [id: string]: ReceivedValue };
737
+ }
738
+
739
+ /** `actorGet`'s result. */
740
+ export interface ActorGetResult {
741
+ readonly session: number;
742
+ readonly segment: number;
743
+ /** The chart's name. */
744
+ readonly chart: string;
745
+ /** The session that invoked it; `null` for a root actor. */
746
+ readonly parent: number | null;
747
+ /** Events waiting for it. */
748
+ readonly mailbox: number;
749
+ /** Services it runs. */
750
+ readonly invocations: number;
751
+ /**
752
+ * Its pending delayed sends (`<send delay>` not yet due, not cancelled),
753
+ * earliest first, at most 32: `timersPending` says how many it has.
754
+ */
755
+ readonly timers: readonly PendingSend[];
756
+ /** How many delayed sends it has pending: more than `timers` holds when the list was cut. */
757
+ readonly timersPending: number;
758
+ }
759
+
760
+ /** A pending delayed send, in `actorGet`'s `timers`. */
761
+ export interface PendingSend {
762
+ /** The send's id (its `id`, or the one `idlocation` was given); `null` when it has none. */
763
+ readonly sendid: string | null;
764
+ /** The event's name. */
765
+ readonly event: string;
766
+ /** When it fires: milliseconds on the clock `host.now()` reads. */
767
+ readonly due: number;
768
+ }
769
+
770
+ // ---- the host -----------------------------------------------------------
771
+
772
+ /** Runs actors: many charts, many images, from a handful of actors to
773
+ * millions, on the runtime's event loop. Inputs (`spawn`, `send`, ...)
774
+ * apply at once and schedule a turn; in its turns the host runs the actors
775
+ * and calls your handlers with what they sent out. There is no `run()`:
776
+ * `await host.idle()` waits until there is nothing left to do.
777
+ *
778
+ * An open host with a pending deadline keeps the process alive, as a
779
+ * `setTimeout` does; `close()` ends it. With no deadline it keeps nothing
780
+ * alive: the process may exit with the host open and actors waiting, for
781
+ * an answer included.
782
+ *
783
+ * @example
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');
789
+ * await host.idle();
790
+ * host.close();
791
+ */
792
+ export class Host implements Disposable, AsyncDisposable {
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;
803
+ /** True once `close()` ran; every input of a closed host throws. */
804
+ readonly closed: boolean;
805
+ /** Milliseconds from the last idle turn to the next deadline (a delayed
806
+ * send, a timeout, or the telemetry encoder's flush once records are
807
+ * staged); `undefined` for none. An input given since that turn has not
808
+ * run yet, so its deadlines are not in it. */
809
+ readonly nextDeadline: number | undefined;
810
+
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
+
824
+ /** Puts `event`, with `data`, in the queue of the actor `target` names (a
825
+ * session or an address). Throws `TA_ERROR_STALE` for an actor that
826
+ * ended. */
827
+ send(target: Session | Actor | string | Address, event: string, data?: Value, options?: SendOptions): void;
828
+ /** The same, from a `SendMessage` (the transport's `send.message`). */
829
+ send(message: SendMessage): void;
830
+ /** Ends the actor. Throws `TA_ERROR_STALE` for one that already ended. */
831
+ terminate(session: Session | Actor): void;
832
+
833
+ /** Resolves at the next turn that finds nothing to do while no promise a
834
+ * handler returned is pending (an I/O processor's, a service's or its
835
+ * `receive`'s, a wake, telemetry, log, migration or typed-method
836
+ * handler's): the same promise to every caller until then. A handler's
837
+ * promise that never settles keeps it pending, and so does a handler
838
+ * that awaits `idle()` itself. Rejects with the turn's first error (a
839
+ * handler's, a typed method's without `onError`), or with
840
+ * `TA_ERROR_STATE` when the host is closed first; on a closed host it
841
+ * returns a promise rejected so. It does not wait for promises your
842
+ * handlers start and do not return. */
843
+ idle(): Promise<void>;
844
+ /** The host's clock in milliseconds, read now: a `SimulatedClock`'s
845
+ * time, or the runtime's monotonic clock, on the scale the host's
846
+ * deadlines and `snapshot()` use, so a restored host's goes on from its
847
+ * snapshot's. A journal of inputs records it beside each input, and a
848
+ * replay on a restored host moves its clock to each reading. It reads
849
+ * and advances nothing; a closed host throws `TA_ERROR_STATE`. */
850
+ now(): number;
851
+
852
+ // The typed methods. Each has two forms. Given handlers, `onResult` or
853
+ // `onError` is called once, in a later turn, and the call returns
854
+ // nothing; an error with no `onError` is the turn's (`idle()` rejects
855
+ // with it). Given no handler, the call returns a promise that resolves
856
+ // with the result and rejects with the `TinyactorsError` (`code`,
857
+ // `reason`, `path`); a refusal at the call rejects too. A rejection is
858
+ // yours: without a `catch` it is an unhandled rejection, and `idle()`
859
+ // does not see it. Each reads the host when called; `close()` drops a
860
+ // pending method uncalled, and its promise never settles.
861
+
862
+ /** An actor's active states, `{ value, history }`: a state id, or `{
863
+ * parent: child }` for compound states. Params `{ session }`. `const {
864
+ * value } = await host.actorState({ session })`. */
865
+ actorState(params: SessionParams, onResult: OnResult<ActorStateResult>, onError?: OnError | null): void;
866
+ /** `actorState` given no handler: a promise of `{ value, history }`. */
867
+ actorState(params: SessionParams): Promise<ActorStateResult>;
868
+ /** An actor's variables, `{ variables }`. Params `{ session }`; refused
869
+ * for a hibernated actor. A variable that holds `undefined` reads
870
+ * `undefined`, apart from `null`; before the actor's first turn every
871
+ * variable is `undefined`, its spawn params included. */
872
+ actorContext(params: SessionParams, onResult: OnResult<ActorContextResult>, onError?: OnError | null): void;
873
+ /** `actorContext` given no handler: a promise of `{ variables }`. */
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
+
923
+ /** The host's sessions a page at a time, `{ sessions, cursor }`, `cursor`
924
+ * `null` after the last page. Params `{ cursor?, limit? }` (1 to 512,
925
+ * default 256). */
926
+ actorList(params: ActorListParams | undefined, onResult: OnResult<ActorListResult>, onError?: OnError | null): void;
927
+ /** `actorList` given no handler: a promise of a page, `{ sessions, cursor }`. */
928
+ actorList(params?: ActorListParams): Promise<ActorListResult>;
929
+ /** One actor, `{ session, segment, chart, parent, mailbox, invocations,
930
+ * timers, timersPending }`. Params `{ session }`. */
931
+ actorGet(params: SessionParams, onResult: OnResult<ActorGetResult>, onError?: OnError | null): void;
932
+ /** `actorGet` given no handler: a promise of the actor. */
933
+ actorGet(params: SessionParams): Promise<ActorGetResult>;
934
+ /** The host's counters, `{ host, pools, charts }`: `pools` has one entry
935
+ * per live segment with each pool's `capacity`, `used` and `highWater`.
936
+ * No params: `await host.hostStats()`. */
937
+ hostStats(params: NoParams, onResult: OnResult<HostStatsResult>, onError?: OnError | null): void;
938
+ /** `hostStats` given no handler: a promise of the counters. */
939
+ hostStats(params?: NoParams): Promise<HostStatsResult>;
940
+ /** The config the host runs with, every default filled in. No params. */
941
+ hostConfig(params: NoParams, onResult: OnResult<EffectiveHostConfig>, onError?: OnError | null): void;
942
+ /** `hostConfig` given no handler: a promise of the effective config. */
943
+ hostConfig(params?: NoParams): Promise<EffectiveHostConfig>;
944
+
945
+ /** Sets what every actor traces: `{ detail, values, sample, records,
946
+ * rules }`. */
947
+ traceConfigure(params: TraceConfigureParams | undefined, onResult: OnResult<EmptyResult>, onError?: OnError | null): void;
948
+ /** `traceConfigure` given no handler: a promise of `{}`. */
949
+ traceConfigure(params?: TraceConfigureParams): Promise<EmptyResult>;
950
+ /** Adds trace rules for a while: `{ rules, seconds }` (default 900);
951
+ * answers `{ id }`. */
952
+ traceWatch(params: TraceWatchParams, onResult: OnResult<TraceWatchResult>, onError?: OnError | null): void;
953
+ /** `traceWatch` given no handler: a promise of `{ id }`. */
954
+ traceWatch(params: TraceWatchParams): Promise<TraceWatchResult>;
955
+ /** Ends a watch early: `{ id }`. */
956
+ traceUnwatch(params: TraceUnwatchParams, onResult: OnResult<EmptyResult>, onError?: OnError | null): void;
957
+ /** `traceUnwatch` given no handler: a promise of `{}`. */
958
+ traceUnwatch(params: TraceUnwatchParams): Promise<EmptyResult>;
959
+ /** Ends every open span now, marked incomplete, for the telemetry handler.
960
+ * Refused without `telemetry` in the config. */
961
+ traceEnd(params: NoParams, onResult: OnResult<EmptyResult>, onError?: OnError | null): void;
962
+ /** `traceEnd` given no handler: a promise of `{}`. */
963
+ traceEnd(params?: NoParams): Promise<EmptyResult>;
964
+ /** The spans of a traces request: `{ traces }` (the bytes) answers `{
965
+ * spans }`, each with `trace`, `span`, `parent`, `name`, `start`, `end`,
966
+ * `attributes`, ... */
967
+ traceSpansDecode(params: TraceSpansDecodeParams, onResult: OnResult<TraceSpansDecodeResult>, onError?: OnError | null): void;
968
+ /** `traceSpansDecode` given no handler: a promise of `{ spans }`. */
969
+ traceSpansDecode(params: TraceSpansDecodeParams): Promise<TraceSpansDecodeResult>;
970
+
971
+ /** The host's counters now as an OTLP metrics request (a `Uint8Array`, for a
972
+ * collector's `/v1/metrics`). `TA_ERROR_STATE` without `telemetry` in the
973
+ * config. */
974
+ metrics(): Uint8Array;
975
+
976
+ /** Finds cold actors: at most `limit` sessions that did not run since
977
+ * the previous sweep and can be hibernated now, looking at most at `maxScan`
978
+ * actors (each an integer from 0 to 2^32-1). The first sweep after an
979
+ * actor ran skips it. */
980
+ sweep(maxScan: number, limit: number): bigint[];
981
+ /** Takes the actor out of memory and returns its blob (a `Uint8Array`) for
982
+ * your store. `TA_ERROR_STATE` when it is not at rest (events waiting, a
983
+ * step not over, running an invoked child or service) and when it is not
984
+ * resident (already hibernated, its wake asked for and not given): the
985
+ * status does not tell the two apart. `TA_ERROR_STALE` for a session that
986
+ * ended or never was, `TA_ERROR_UNSUPPORTED` when a variable holds what
987
+ * the datamodel cannot store (the message names it); it stays where it
988
+ * is then. */
989
+ hibernate(session: Session | Actor): Uint8Array;
990
+ /** Puts a hibernated actor back from the blob `hibernate` gave; its
991
+ * waiting events run at the next turn. Only its latest blob: one of an
992
+ * earlier hibernation (a store that fell behind) throws `TA_ERROR_STALE`,
993
+ * another session's `TA_ERROR_INVALID`, and the actor stays hibernated.
994
+ * On a restored host a blob of a hibernation made after the snapshot is
995
+ * taken too. */
996
+ wake(session: Session | Actor, blob: Uint8Array | ArrayBuffer): void;
997
+
998
+ /** Starts moving running actors (every chart's, `chart`'s, or one
999
+ * `session`) to the current version of their chart, in later turns; each
1000
+ * gets `error.platform.upgrade` with its old variables. Returns the
1001
+ * migration's id, which `migrated` and `migrationDone` name. Throws `TA_ERROR_INVALID` for a chart the host does not have and
1002
+ * `TA_ERROR_STALE` for a session that ended. */
1003
+ migrate(options?: MigrateOptions): number;
1004
+
1005
+ /** The whole host as one `Uint8Array`: every segment, the images, the system
1006
+ * id, the host's time (its clocks advanced first: the time of the call,
1007
+ * as `now()` reads it) and the datamodel's state, for `Host.restore` on the
1008
+ * same build of the package. Only when quiescent: from a handler, with an
1009
+ * effect or a reply pending, or during a migration it throws
1010
+ * `TA_ERROR_STATE`; a value outside the value table throws
1011
+ * `TA_ERROR_UNSUPPORTED`. */
1012
+ snapshot(): Uint8Array;
1013
+
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 } };
1530
+ }