@kylewillett/troupe 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/CHANGELOG.md +21 -2
  2. package/README.md +132 -2
  3. package/dist/ask.d.ts +5 -1
  4. package/dist/ask.js +16 -0
  5. package/dist/backstage/index.d.ts +2 -1
  6. package/dist/backstage/index.js +1 -0
  7. package/dist/backstage/source.d.ts +1 -1
  8. package/dist/backstage/source.js +65 -2
  9. package/dist/backstage/types.d.ts +65 -4
  10. package/dist/backstage/types.js +2 -1
  11. package/dist/backstage-ui/assets/index-CG896RLZ.css +1 -0
  12. package/dist/backstage-ui/assets/index-DF_Xnc1u.js +9 -0
  13. package/dist/backstage-ui/index.html +2 -2
  14. package/dist/cell.d.ts +16 -14
  15. package/dist/cell.js +38 -13
  16. package/dist/checks.d.ts +10 -0
  17. package/dist/checks.js +34 -2
  18. package/dist/cluster/index.d.ts +6 -0
  19. package/dist/cluster/index.js +4 -0
  20. package/dist/cluster/leases.d.ts +37 -0
  21. package/dist/cluster/leases.js +132 -0
  22. package/dist/cluster/membership.d.ts +100 -0
  23. package/dist/cluster/membership.js +559 -0
  24. package/dist/cluster/memory.d.ts +31 -0
  25. package/dist/cluster/memory.js +187 -0
  26. package/dist/cluster/placement.d.ts +10 -0
  27. package/dist/cluster/placement.js +30 -0
  28. package/dist/cluster/postgres/index.d.ts +1 -0
  29. package/dist/cluster/postgres/index.js +3 -0
  30. package/dist/cluster/postgres/schema.d.ts +7 -0
  31. package/dist/cluster/postgres/schema.js +33 -0
  32. package/dist/cluster/postgres/schema.sql +18 -0
  33. package/dist/cluster/postgres/store.d.ts +28 -0
  34. package/dist/cluster/postgres/store.js +124 -0
  35. package/dist/cluster/region.d.ts +103 -0
  36. package/dist/cluster/region.js +843 -0
  37. package/dist/cluster/remoting.d.ts +79 -0
  38. package/dist/cluster/remoting.js +755 -0
  39. package/dist/cluster/shard-memory.d.ts +14 -0
  40. package/dist/cluster/shard-memory.js +92 -0
  41. package/dist/cluster/shard-store.d.ts +62 -0
  42. package/dist/cluster/shard-store.js +36 -0
  43. package/dist/cluster/shard.d.ts +54 -0
  44. package/dist/cluster/shard.js +278 -0
  45. package/dist/cluster/sharding.d.ts +109 -0
  46. package/dist/cluster/sharding.js +278 -0
  47. package/dist/cluster/table.d.ts +29 -0
  48. package/dist/cluster/table.js +74 -0
  49. package/dist/cluster/transport.d.ts +29 -0
  50. package/dist/cluster/transport.js +4 -0
  51. package/dist/cluster/wire.d.ts +90 -0
  52. package/dist/cluster/wire.js +177 -0
  53. package/dist/hash.d.ts +7 -0
  54. package/dist/hash.js +25 -0
  55. package/dist/internal.d.ts +134 -2
  56. package/dist/internal.js +12 -1
  57. package/dist/json.d.ts +44 -0
  58. package/dist/json.js +143 -0
  59. package/dist/node/cluster/frames.d.ts +31 -0
  60. package/dist/node/cluster/frames.js +73 -0
  61. package/dist/node/cluster/index.d.ts +1 -0
  62. package/dist/node/cluster/index.js +3 -0
  63. package/dist/node/cluster/tcp.d.ts +101 -0
  64. package/dist/node/cluster/tcp.js +416 -0
  65. package/dist/persistence/actor.js +1 -1
  66. package/dist/persistence/backend.d.ts +1 -10
  67. package/dist/persistence/backend.js +4 -34
  68. package/dist/persistence/postgres/index.d.ts +2 -1
  69. package/dist/persistence/postgres/index.js +1 -1
  70. package/dist/persistence/postgres/pool.d.ts +44 -0
  71. package/dist/persistence/postgres/pool.js +65 -0
  72. package/dist/persistence/postgres/postgres.d.ts +1 -33
  73. package/dist/persistence/postgres/postgres.js +4 -63
  74. package/dist/system.d.ts +1 -1
  75. package/dist/system.js +190 -24
  76. package/dist/types.d.ts +86 -3
  77. package/package.json +25 -4
  78. package/dist/backstage-ui/assets/index-Bg0MCiqs.css +0 -1
  79. package/dist/backstage-ui/assets/index-CeefBsDh.js +0 -9
  80. package/dist/persistence/json.d.ts +0 -7
  81. package/dist/persistence/json.js +0 -75
@@ -4,8 +4,8 @@
4
4
  <meta charset="UTF-8" />
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
6
  <title>Backstage · Troupe</title>
7
- <script type="module" crossorigin src="./assets/index-CeefBsDh.js"></script>
8
- <link rel="stylesheet" crossorigin href="./assets/index-Bg0MCiqs.css">
7
+ <script type="module" crossorigin src="./assets/index-DF_Xnc1u.js"></script>
8
+ <link rel="stylesheet" crossorigin href="./assets/index-CG896RLZ.css">
9
9
  </head>
10
10
  <body>
11
11
  <div id="root"></div>
package/dist/cell.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { Dispatcher, Runnable } from './dispatcher.js';
2
2
  import type { EventBus } from './events.js';
3
- import { type CellInspection } from './internal.js';
3
+ import { type CellInspection, type Watcher, type WatchTarget } from './internal.js';
4
4
  import { type Logger } from './logger.js';
5
5
  import { Names } from './names.js';
6
6
  import { type SupervisorStrategy } from './supervision.js';
@@ -9,13 +9,9 @@ import type { ActorDef, ActorRef, AnyRef, Result, SpawnOptions } from './types.j
9
9
  type Failure = {
10
10
  readonly error: unknown;
11
11
  } | undefined;
12
- /** Something told when a watched cell terminates: another cell, or a testkit probe. */
13
- export interface Watcher {
14
- /** Tells the watcher that `target` has terminated. It must not throw. */
15
- notifyTerminated(target: CellNode): void;
16
- }
12
+ export type { Watcher } from './internal.js';
17
13
  /** What other cells, the guardian and the system see of a cell, whatever its types. */
18
- export interface CellNode extends Watcher {
14
+ export interface CellNode extends Watcher, WatchTarget {
19
15
  readonly ref: AnyRef;
20
16
  readonly name: string;
21
17
  readonly parent: ParentNode;
@@ -23,8 +19,8 @@ export interface CellNode extends Watcher {
23
19
  readonly failure: Failure;
24
20
  /** Asks the cell to stop after its current message, ahead of its queued messages. */
25
21
  requestStop(): void;
26
- /** Watchers of this cell, kept so it can notify them when it terminates. */
27
- readonly watchers: Set<Watcher>;
22
+ /** Asks the cell to stop once it has handled the messages already queued. */
23
+ stopWhenIdle(): void;
28
24
  /** Its children that haven't terminated, in spawn order. */
29
25
  readonly childCells: Map<string, CellNode>;
30
26
  /** What an inspector sees of it, read-only. */
@@ -66,12 +62,17 @@ export interface CellHost {
66
62
  * @returns False if it isn't, so the caller must wait on the promise itself.
67
63
  */
68
64
  onAskSettled(promise: unknown, listener: (result: Result<unknown>) => void): boolean;
69
- /** True once `terminate()` has been called. */
70
- terminating(): boolean;
65
+ /**
66
+ * True once `terminate()` has been called, for an actor at `path` under `/user`. Under
67
+ * `/system`, only once the system's termination tasks have settled.
68
+ */
69
+ terminating(path: string): boolean;
71
70
  /** Spawns an actor under `parent`, with every check `spawn` makes. */
72
71
  spawn<M, S>(parent: ParentNode, def: ActorDef<M, S>, name: string | undefined, opts: SpawnOptions | undefined): ActorRef<M>;
73
72
  /** The cell behind a ref, if it belongs to this system. */
74
73
  cellOf(ref: unknown): CellNode | undefined;
74
+ /** What watching `ref` watches: its cell, or a remote actor's stand-in (decision 0026). */
75
+ watchTargetOf(ref: unknown): WatchTarget | undefined;
75
76
  }
76
77
  /** A cell's checked spawn options. */
77
78
  export interface CellOptions {
@@ -114,7 +115,6 @@ export declare class Cell<M, S> implements Runnable, CellNode, ParentNode {
114
115
  readonly parent: ParentNode;
115
116
  readonly names: Names;
116
117
  readonly childCells: Map<string, CellNode>;
117
- readonly watchers: Set<Watcher>;
118
118
  constructor(name: string, path: string, def: ActorDef<M, S>, host: CellHost, opts: CellOptions, parent: ParentNode);
119
119
  get terminated(): boolean;
120
120
  get failure(): Failure;
@@ -122,8 +122,10 @@ export declare class Cell<M, S> implements Runnable, CellNode, ParentNode {
122
122
  /** Queues the actor's first step, which runs `initial`. */
123
123
  start(): void;
124
124
  requestStop(): void;
125
- notifyTerminated(target: CellNode): void;
125
+ stopWhenIdle(): void;
126
+ addWatcher(watcher: Watcher): void;
127
+ removeWatcher(watcher: Watcher): void;
128
+ notifyTerminated(target: WatchTarget): void;
126
129
  removeChild(child: CellNode): void;
127
130
  run(max: number): number;
128
131
  }
129
- export {};
package/dist/cell.js CHANGED
@@ -14,6 +14,11 @@ class PipeEnvelope {
14
14
  this.map = map;
15
15
  }
16
16
  }
17
+ /**
18
+ * The last item of a mailbox whose actor stops once it's dequeued: `stopWhenIdle`. A symbol no
19
+ * one else holds, so no user message can be it.
20
+ */
21
+ const STOP_MARKER = Symbol('troupe.stopWhenIdle');
17
22
  /** A mailbox item with the id of its `delivered`, wrapped only while message events are on. */
18
23
  class Tracked {
19
24
  id;
@@ -58,7 +63,8 @@ export class Cell {
58
63
  parent;
59
64
  names = new Names();
60
65
  childCells = new Map();
61
- watchers = new Set();
66
+ // Watchers of this cell, kept so it can notify them when it terminates.
67
+ #watchers = new Set();
62
68
  #watching = new Set();
63
69
  #def;
64
70
  #host;
@@ -152,6 +158,19 @@ export class Cell {
152
158
  this.#system.push({ type: 'stop' });
153
159
  this.#scheduleIfReady();
154
160
  }
161
+ stopWhenIdle() {
162
+ if (this.#stopping())
163
+ return;
164
+ // Past the capacity check: it's the system's, not a message, and nothing comes after it.
165
+ this.#mailbox.push(STOP_MARKER);
166
+ this.#scheduleIfReady();
167
+ }
168
+ addWatcher(watcher) {
169
+ this.#watchers.add(watcher);
170
+ }
171
+ removeWatcher(watcher) {
172
+ this.#watchers.delete(watcher);
173
+ }
155
174
  notifyTerminated(target) {
156
175
  if (this.#phase !== 'running' || !this.#watching.has(target))
157
176
  return;
@@ -261,6 +280,10 @@ export class Cell {
261
280
  item = envelope;
262
281
  }
263
282
  let msg;
283
+ if (item === STOP_MARKER) {
284
+ this.requestStop();
285
+ return;
286
+ }
264
287
  if (item instanceof TimerEnvelope) {
265
288
  // A cancelled or replaced timer's message is dropped here, even if it was already queued.
266
289
  if (!this.#timers.accept(item)) {
@@ -346,7 +369,7 @@ export class Cell {
346
369
  }
347
370
  /** Queues a message, or makes it a dead letter. Returns false for a dead letter. */
348
371
  #enqueue(item) {
349
- const reason = this.#host.terminating()
372
+ const reason = this.#host.terminating(this.path)
350
373
  ? 'terminated'
351
374
  : this.#stopping()
352
375
  ? 'stopped'
@@ -636,7 +659,7 @@ export class Cell {
636
659
  cell.requestStop();
637
660
  }
638
661
  #watch(ref) {
639
- const target = this.#cellOrThrow(ref, 'watch');
662
+ const target = this.#targetOrThrow(ref, 'watch');
640
663
  if (this.#phase !== 'running' || target === this || this.#watching.has(target))
641
664
  return;
642
665
  this.#watching.add(target);
@@ -644,25 +667,25 @@ export class Cell {
644
667
  this.notifyTerminated(target);
645
668
  }
646
669
  else {
647
- target.watchers.add(this);
670
+ target.addWatcher(this);
648
671
  }
649
672
  }
650
673
  #unwatch(ref) {
651
- const target = this.#cellOrThrow(ref, 'unwatch');
674
+ const target = this.#targetOrThrow(ref, 'unwatch');
652
675
  this.#watching.delete(target);
653
- target.watchers.delete(this);
676
+ target.removeWatcher(this);
654
677
  }
655
678
  #unwatchAll() {
656
679
  for (const target of this.#watching)
657
- target.watchers.delete(this);
680
+ target.removeWatcher(this);
658
681
  this.#watching.clear();
659
682
  }
660
- #cellOrThrow(ref, what) {
661
- const cell = this.#host.cellOf(ref);
662
- if (cell === undefined) {
683
+ #targetOrThrow(ref, what) {
684
+ const target = this.#host.watchTargetOf(ref);
685
+ if (target === undefined) {
663
686
  throw new TypeError(`${what}: the ref is not an actor of this system`);
664
687
  }
665
- return cell;
688
+ return target;
666
689
  }
667
690
  #beginStop(failure) {
668
691
  if (this.#stopping())
@@ -679,6 +702,8 @@ export class Cell {
679
702
  if (tracked)
680
703
  this.#tracked--;
681
704
  const item = tracked ? envelope.item : envelope;
705
+ if (item === STOP_MARKER)
706
+ continue;
682
707
  if (!(item instanceof TimerEnvelope)) {
683
708
  this.#deadLetter(item, 'stopped', tracked ? envelope.id : undefined);
684
709
  }
@@ -740,9 +765,9 @@ export class Cell {
740
765
  this.#phase = 'terminated';
741
766
  this.#unwatchAll();
742
767
  this.parent.removeChild(this);
743
- for (const watcher of this.watchers)
768
+ for (const watcher of [...this.#watchers])
744
769
  watcher.notifyTerminated(this);
745
- this.watchers.clear();
770
+ this.#watchers.clear();
746
771
  this.#host.events.publish(this.#failure === undefined
747
772
  ? { type: 'stopped', path: this.path }
748
773
  : { type: 'stopped', path: this.path, failure: this.#failure.error });
package/dist/checks.d.ts CHANGED
@@ -7,3 +7,13 @@ export declare function checkInt(value: unknown, what: string, { min, infinite }
7
7
  }): void;
8
8
  /** Renders a bad value for an error message. */
9
9
  export declare function describe(value: unknown): string;
10
+ /**
11
+ * Checks a backend's `clock` option, and returns a reader that rejects anything but integer ms.
12
+ * `where` names the backend in error messages.
13
+ */
14
+ export declare function wallClock(clock: unknown, where: string): () => number;
15
+ /**
16
+ * Throws unless `value` is a non-empty string that every backend can store as it is: a persistence
17
+ * id, tag or projection name, or a shard store's lease, holder or entity id.
18
+ */
19
+ export declare function checkId(value: unknown, what: string): void;
package/dist/checks.js CHANGED
@@ -1,5 +1,5 @@
1
- // Option checks shared by createActorSystem, spawn and supervise. Each throws TypeError, so a bad
2
- // option fails where it's passed in, never later.
1
+ // Option and argument checks shared by the core, the persistence backends and the cluster's
2
+ // stores. Each throws TypeError, so a bad option fails where it's passed in, never later.
3
3
  /** Throws unless `opts` is a plain object whose keys are all in `allowed`. */
4
4
  export function checkKeys(opts, allowed, where) {
5
5
  if (typeof opts !== 'object' || opts === null || Array.isArray(opts)) {
@@ -23,3 +23,35 @@ export function checkInt(value, what, { min = 1, infinite = false } = {}) {
23
23
  export function describe(value) {
24
24
  return typeof value === 'string' ? `"${value}"` : String(value);
25
25
  }
26
+ /**
27
+ * Checks a backend's `clock` option, and returns a reader that rejects anything but integer ms.
28
+ * `where` names the backend in error messages.
29
+ */
30
+ export function wallClock(clock, where) {
31
+ if (typeof clock !== 'function') {
32
+ throw new TypeError(`${where}: clock must be a function, got ${describe(clock)}`);
33
+ }
34
+ const read = clock;
35
+ return () => {
36
+ const time = read();
37
+ checkInt(time, `${where}: clock()`, { min: 0 });
38
+ return time;
39
+ };
40
+ }
41
+ // U+0000, or a surrogate with no partner. Postgres text can't hold the first, and neither
42
+ // database's UTF-8 can hold the second, so an id with either would be stored as something else.
43
+ // The `u` flag makes a valid pair one code point, which \p{Cs} doesn't match.
44
+ // eslint-disable-next-line no-control-regex -- U+0000 is the point.
45
+ const UNSTORABLE = /[\u0000\p{Cs}]/u;
46
+ /**
47
+ * Throws unless `value` is a non-empty string that every backend can store as it is: a persistence
48
+ * id, tag or projection name, or a shard store's lease, holder or entity id.
49
+ */
50
+ export function checkId(value, what) {
51
+ if (typeof value !== 'string' || value === '') {
52
+ throw new TypeError(`${what} must be a non-empty string, got ${describe(value)}`);
53
+ }
54
+ if (UNSTORABLE.test(value)) {
55
+ throw new TypeError(`${what} must not contain U+0000 or a lone surrogate`);
56
+ }
57
+ }
@@ -0,0 +1,6 @@
1
+ export { joinCluster, type Cluster, type ClusterOptions, type Member } from './membership.js';
2
+ export { inMemoryNetwork, type InMemoryNetwork, type InMemoryNetworkOptions } from './memory.js';
3
+ export type { Connection, Transport } from './transport.js';
4
+ export { inMemoryShardStore } from './shard-memory.js';
5
+ export type { AcquireResult, LeaseHolder, ShardStore } from './shard-store.js';
6
+ export type { EntityType, EntityTypeOptions, LeaseOptions, Sharding } from './sharding.js';
@@ -0,0 +1,4 @@
1
+ // The /cluster entry point: any runtime (decisions 0028, 0029, 0030). Export only from here.
2
+ export { joinCluster } from './membership.js';
3
+ export { inMemoryNetwork } from './memory.js';
4
+ export { inMemoryShardStore } from './shard-memory.js';
@@ -0,0 +1,37 @@
1
+ import type { Scheduler } from '../scheduler.js';
2
+ import type { AcquireResult, ShardStore } from './shard-store.js';
3
+ /** Options for {@link leaseKeeper}. Every time is in integer milliseconds. */
4
+ export interface LeaseKeeperOptions {
5
+ readonly store: ShardStore;
6
+ /** This node's holder name, `<address>#<uid>`. */
7
+ readonly holder: string;
8
+ readonly scheduler: Scheduler;
9
+ /** How long the store keeps a lease after each acquire or renewal. */
10
+ readonly ttlMs: number;
11
+ /** How often to renew. Less than `ttlMs - marginMs`, so a renewal lands before the deadline. */
12
+ readonly renewMs: number;
13
+ /** How long before the store's expiry this node gives a lease up. */
14
+ readonly marginMs: number;
15
+ /** Called once for each lease this node stops holding without releasing it. */
16
+ readonly onLost: (lease: string, token: number) => void;
17
+ }
18
+ /** The leases one node holds. */
19
+ export interface LeaseKeeper {
20
+ /** Asks the store for the lease. If it's granted, holds it, and renews it, from then on. */
21
+ acquire(lease: string): Promise<AcquireResult>;
22
+ /** Stops holding the lease at once, then gives it up in the store. */
23
+ release(lease: string): Promise<void>;
24
+ /** Whether this node holds the lease now, by its own clock. */
25
+ holds(lease: string): boolean;
26
+ /** The token this node holds the lease with, if it holds it. */
27
+ token(lease: string): number | undefined;
28
+ /** Stops renewing and forgets every lease, with no `onLost`. They expire in the store. */
29
+ close(): void;
30
+ }
31
+ /**
32
+ * Keeps one node's leases: acquires, renews every `renewMs` on the scheduler, and drops each at
33
+ * its deadline unless a renewal has moved it.
34
+ * @throws TypeError for options that can't be used, unknown ones included, or intervals whose
35
+ * renewals couldn't land before the deadline.
36
+ */
37
+ export declare function leaseKeeper(opts: LeaseKeeperOptions): LeaseKeeper;
@@ -0,0 +1,132 @@
1
+ // The holder's side of a lease (decision 0029). The store judges expiry on its clock, and this
2
+ // judges it on the node's own: it notes `scheduler.now()` before it sends a renewal, and once the
3
+ // store says yes, treats the lease as its own until that time plus `ttlMs` minus `marginMs`. The
4
+ // store started its `ttlMs` after this node noted the time, so this deadline comes first, as long
5
+ // as the two clocks run at about the same rate. Their readings are never compared.
6
+ //
7
+ // At the deadline the lease is lost, whether or not the store has answered, and `onLost` says so.
8
+ // A renewal that comes back after that can't win the lease back: only `acquire` can. Never
9
+ // exported: T6's shards use it.
10
+ import { checkInt, checkId, checkKeys } from '../checks.js';
11
+ const OPTIONS = new Set(['store', 'holder', 'scheduler', 'ttlMs', 'renewMs', 'marginMs', 'onLost']);
12
+ /**
13
+ * Keeps one node's leases: acquires, renews every `renewMs` on the scheduler, and drops each at
14
+ * its deadline unless a renewal has moved it.
15
+ * @throws TypeError for options that can't be used, unknown ones included, or intervals whose
16
+ * renewals couldn't land before the deadline.
17
+ */
18
+ export function leaseKeeper(opts) {
19
+ checkKeys(opts, OPTIONS, 'leaseKeeper');
20
+ const { store, holder, scheduler, ttlMs, renewMs, marginMs, onLost } = opts;
21
+ checkId(holder, 'leaseKeeper: holder');
22
+ checkInt(ttlMs, 'leaseKeeper: ttlMs');
23
+ checkInt(renewMs, 'leaseKeeper: renewMs');
24
+ checkInt(marginMs, 'leaseKeeper: marginMs', { min: 0 });
25
+ if (renewMs >= ttlMs - marginMs) {
26
+ throw new TypeError(`leaseKeeper: renewMs must be less than ttlMs - marginMs, so a renewal lands before the ` +
27
+ `deadline, got ${String(renewMs)} with ttlMs ${String(ttlMs)} and marginMs ${String(marginMs)}`);
28
+ }
29
+ const held = new Map();
30
+ let closed = false;
31
+ /** Moves a lease's deadline to `noted + ttlMs - marginMs`, if that's later. */
32
+ function extend(lease, entry, noted) {
33
+ const deadline = noted + ttlMs - marginMs;
34
+ if (deadline <= entry.deadline)
35
+ return;
36
+ entry.cancel();
37
+ entry.deadline = deadline;
38
+ entry.cancel = scheduler.setTimer(() => {
39
+ lose(lease, entry);
40
+ }, Math.max(0, deadline - scheduler.now()));
41
+ }
42
+ function lose(lease, entry) {
43
+ if (held.get(lease) !== entry)
44
+ return;
45
+ entry.cancel();
46
+ held.delete(lease);
47
+ onLost(lease, entry.token);
48
+ }
49
+ async function renew() {
50
+ if (held.size === 0)
51
+ return;
52
+ const noted = scheduler.now();
53
+ let renewed;
54
+ try {
55
+ renewed = await store.renewAll(holder, ttlMs);
56
+ }
57
+ catch {
58
+ // Keep trying on the next tick. The deadline stops the shard if none gets through.
59
+ return;
60
+ }
61
+ const yes = new Set(renewed);
62
+ for (const [lease, entry] of [...held]) {
63
+ if (yes.has(lease))
64
+ extend(lease, entry, noted);
65
+ // The store no longer has it as ours, though it did when this renewal was sent: someone
66
+ // released it, or the store's clock ran fast. Losing it early is always safe.
67
+ else if (entry.since < noted)
68
+ lose(lease, entry);
69
+ }
70
+ }
71
+ const cancelTick = (() => {
72
+ let cancel = () => { };
73
+ const tick = () => {
74
+ cancel = scheduler.setTimer(tick, renewMs);
75
+ void renew();
76
+ };
77
+ cancel = scheduler.setTimer(tick, renewMs);
78
+ return () => {
79
+ cancel();
80
+ };
81
+ })();
82
+ return {
83
+ async acquire(lease) {
84
+ checkId(lease, 'acquire: lease');
85
+ const noted = scheduler.now();
86
+ const result = await store.acquire(lease, holder, ttlMs);
87
+ if (!result.acquired)
88
+ return result;
89
+ if (closed) {
90
+ // Nobody will renew it, so hand it straight back rather than leave it to expire.
91
+ await store.release(lease, holder, result.token).catch(() => { });
92
+ return result;
93
+ }
94
+ const current = held.get(lease);
95
+ if (current?.token === result.token) {
96
+ extend(lease, current, noted);
97
+ return result;
98
+ }
99
+ if (current !== undefined)
100
+ lose(lease, current);
101
+ const entry = { token: result.token, since: noted, deadline: -Infinity, cancel() { } };
102
+ held.set(lease, entry);
103
+ // A deadline already past fires on the next timer turn, after the caller has the result.
104
+ extend(lease, entry, noted);
105
+ return result;
106
+ },
107
+ async release(lease) {
108
+ const entry = held.get(lease);
109
+ if (entry === undefined)
110
+ return;
111
+ entry.cancel();
112
+ held.delete(lease);
113
+ await store.release(lease, holder, entry.token);
114
+ },
115
+ holds(lease) {
116
+ const entry = held.get(lease);
117
+ return entry !== undefined && scheduler.now() < entry.deadline;
118
+ },
119
+ token(lease) {
120
+ return held.get(lease)?.token;
121
+ },
122
+ close() {
123
+ if (closed)
124
+ return;
125
+ closed = true;
126
+ cancelTick();
127
+ for (const entry of held.values())
128
+ entry.cancel();
129
+ held.clear();
130
+ },
131
+ };
132
+ }
@@ -0,0 +1,100 @@
1
+ import type { ActorSystem } from '../types.js';
2
+ import { type Remoting } from './remoting.js';
3
+ import type { ShardStore } from './shard-store.js';
4
+ import { type LeaseOptions, type Sharding } from './sharding.js';
5
+ import type { Transport } from './transport.js';
6
+ /** Options for {@link joinCluster}. Every interval is in integer milliseconds. */
7
+ export interface ClusterOptions {
8
+ /** The cluster's name, which every node shares: lower-case letters, digits and `-`. */
9
+ name: string;
10
+ /** How this node reaches the others. Its `address` is this node's. */
11
+ transport: Transport;
12
+ /**
13
+ * The addresses a node joins through. Only the first may form a cluster on its own, so two
14
+ * halves can't each form one at start-up. Every node should have the same list.
15
+ */
16
+ seeds: readonly string[];
17
+ /** How often this node heartbeats every other member, and gossips to one. Default 1,000. */
18
+ heartbeatMs?: number;
19
+ /** How long a member can go unheard before it's unreachable. Default 5,000. */
20
+ unreachableAfterMs?: number;
21
+ /** How long a member can stay unreachable before it's downed. Default 10,000. */
22
+ downAfterMs?: number;
23
+ /**
24
+ * How long the first seed tries the others before it forms a cluster on its own. Default
25
+ * 5,000. A node whose seeds are only itself forms one at once.
26
+ */
27
+ seedTimeoutMs?: number;
28
+ /** How many messages wait for a node that has no connection. Default 10,000. */
29
+ bufferSize?: number;
30
+ /** The largest frame this node sends, in UTF-8 bytes. Default 1 MiB. */
31
+ maxFrameBytes?: number;
32
+ /**
33
+ * Where shard leases live (decision 0029), shared by every node: `postgresShardStore` from
34
+ * `/cluster/postgres`, or `inMemoryShardStore` for nodes in one process. Needed for sharding.
35
+ */
36
+ shards?: ShardStore;
37
+ /** How this node times its shard leases. Every node should use the same. */
38
+ leases?: LeaseOptions;
39
+ }
40
+ /** One incarnation of a node, as this node sees it. */
41
+ export interface Member {
42
+ /** The address other nodes reach it at. */
43
+ readonly address: string;
44
+ /** Its uid, new on every start, so a restarted node is a new member. */
45
+ readonly uid: number;
46
+ /** `up`, `leaving` gracefully, or `down`: unreachable too long, by this node's or another's view. */
47
+ readonly status: 'up' | 'leaving' | 'down';
48
+ /** Whether this node hears its heartbeats. Each node's own view, never gossiped. */
49
+ readonly reachable: boolean;
50
+ }
51
+ /** This node's place in a cluster. */
52
+ export interface Cluster {
53
+ /** This node: its address, as other nodes reach it, and its uid, new on every start. */
54
+ readonly self: {
55
+ readonly address: string;
56
+ readonly uid: number;
57
+ };
58
+ /**
59
+ * The members as this node sees them, itself included, sorted by address: empty until it's in
60
+ * the cluster. A member that left is gone. One that was downed stays, as `down`, until a new
61
+ * incarnation at its address replaces it.
62
+ */
63
+ members(): readonly Member[];
64
+ /**
65
+ * Resolves once this node is in the cluster: a member that was up let it in, or it formed the
66
+ * cluster as the first seed. Rejects if the node leaves, is downed or terminates first.
67
+ */
68
+ readonly whenUp: Promise<void>;
69
+ /** Entity types, and refs to their entities (decision 0030). */
70
+ readonly sharding: Sharding;
71
+ /**
72
+ * Tells the others this node is leaving, hands each shard it holds off to its next owner,
73
+ * then tells them it has left and closes its connections. A shard's entities finish what they
74
+ * have first, a persist included, and messages that arrive meanwhile follow the shard. A shard
75
+ * no other node hosts is stopped, and its lease released. Resolves once the node has left.
76
+ * `system.terminate()` does the same, once everything under `/user` has stopped. Calling it
77
+ * again returns the same promise.
78
+ */
79
+ leave(): Promise<void>;
80
+ }
81
+ /** What tests can set that users can't. */
82
+ export interface ClusterInternals {
83
+ /** How long a tombstone stays in the table before it's pruned. Default 24 hours, as Akka's. */
84
+ pruneAfterMs?: number;
85
+ }
86
+ /** A cluster, and the remoting under it, for the package's own code and tests. */
87
+ export interface ClusterHandle {
88
+ readonly cluster: Cluster;
89
+ readonly remoting: Remoting;
90
+ }
91
+ /**
92
+ * Joins `system` to a cluster: listens on the transport, joins through a seed, and keeps the
93
+ * member table from then on. Returns at once: `whenUp` says when the node is in.
94
+ * @throws TypeError for options that can't be used, unknown ones included, or a system that
95
+ * wasn't made by `createActorSystem`.
96
+ * @throws Error if the system is already in a cluster.
97
+ */
98
+ export declare function joinCluster(system: ActorSystem, opts: ClusterOptions): Cluster;
99
+ /** {@link joinCluster}, with the remoting underneath and the options only tests set. */
100
+ export declare function startCluster(system: ActorSystem, opts: ClusterOptions, internals?: ClusterInternals): ClusterHandle;