@kylewillett/troupe 0.1.1 → 0.3.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 (106) hide show
  1. package/CHANGELOG.md +26 -1
  2. package/README.md +134 -4
  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 +19 -16
  15. package/dist/cell.js +46 -20
  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 +116 -0
  46. package/dist/cluster/sharding.js +286 -0
  47. package/dist/cluster/table.d.ts +29 -0
  48. package/dist/cluster/table.js +74 -0
  49. package/dist/cluster/timed-store.d.ts +4 -0
  50. package/dist/cluster/timed-store.js +19 -0
  51. package/dist/cluster/transport.d.ts +29 -0
  52. package/dist/cluster/transport.js +4 -0
  53. package/dist/cluster/wire.d.ts +90 -0
  54. package/dist/cluster/wire.js +177 -0
  55. package/dist/hash.d.ts +7 -0
  56. package/dist/hash.js +25 -0
  57. package/dist/index.d.ts +1 -0
  58. package/dist/index.js +1 -0
  59. package/dist/internal.d.ts +139 -2
  60. package/dist/internal.js +12 -1
  61. package/dist/json.d.ts +44 -0
  62. package/dist/json.js +143 -0
  63. package/dist/node/cluster/frames.d.ts +31 -0
  64. package/dist/node/cluster/frames.js +73 -0
  65. package/dist/node/cluster/index.d.ts +1 -0
  66. package/dist/node/cluster/index.js +3 -0
  67. package/dist/node/cluster/tcp.d.ts +101 -0
  68. package/dist/node/cluster/tcp.js +416 -0
  69. package/dist/persistence/actor.d.ts +9 -0
  70. package/dist/persistence/actor.js +21 -10
  71. package/dist/persistence/backend.d.ts +1 -10
  72. package/dist/persistence/backend.js +4 -34
  73. package/dist/persistence/errors.d.ts +19 -0
  74. package/dist/persistence/errors.js +22 -0
  75. package/dist/persistence/index.d.ts +1 -1
  76. package/dist/persistence/index.js +1 -1
  77. package/dist/persistence/postgres/index.d.ts +2 -1
  78. package/dist/persistence/postgres/index.js +1 -1
  79. package/dist/persistence/postgres/pool.d.ts +44 -0
  80. package/dist/persistence/postgres/pool.js +65 -0
  81. package/dist/persistence/postgres/postgres.d.ts +1 -33
  82. package/dist/persistence/postgres/postgres.js +4 -63
  83. package/dist/persistence/projection.d.ts +6 -0
  84. package/dist/persistence/projection.js +21 -5
  85. package/dist/rehearsal/clock.d.ts +54 -0
  86. package/dist/rehearsal/clock.js +203 -0
  87. package/dist/rehearsal/database.d.ts +116 -0
  88. package/dist/rehearsal/database.js +349 -0
  89. package/dist/rehearsal/loop.d.ts +57 -0
  90. package/dist/rehearsal/loop.js +153 -0
  91. package/dist/rehearsal/network.d.ts +120 -0
  92. package/dist/rehearsal/network.js +524 -0
  93. package/dist/rehearsal/ranges.d.ts +8 -0
  94. package/dist/rehearsal/ranges.js +27 -0
  95. package/dist/rehearsal/yield.d.ts +9 -0
  96. package/dist/rehearsal/yield.js +24 -0
  97. package/dist/system.d.ts +13 -1
  98. package/dist/system.js +204 -25
  99. package/dist/timeout.d.ts +8 -0
  100. package/dist/timeout.js +26 -0
  101. package/dist/types.d.ts +86 -3
  102. package/package.json +21 -2
  103. package/dist/backstage-ui/assets/index-Bg0MCiqs.css +0 -1
  104. package/dist/backstage-ui/assets/index-CeefBsDh.js +0 -9
  105. package/dist/persistence/json.d.ts +0 -7
  106. package/dist/persistence/json.js +0 -75
@@ -0,0 +1,14 @@
1
+ import { type ShardStore } from './shard-store.js';
2
+ /**
3
+ * A shard store in memory, for tests, demos and the browser, on any runtime. Every call does its
4
+ * work on a microtask, as a real store answers later, and nothing waits on time: a lease expires
5
+ * when the clock says so.
6
+ *
7
+ * It judges expiry on `clock`, its own, which no node's clock is compared with (decision 0029).
8
+ * Give a cluster on one `ManualScheduler` the scheduler's `now`, so leases expire in virtual time.
9
+ *
10
+ * @param opts.clock The store's clock, in integer ms. Defaults to `Date.now`.
11
+ */
12
+ export declare function inMemoryShardStore(opts?: {
13
+ clock?: () => number;
14
+ }): ShardStore;
@@ -0,0 +1,92 @@
1
+ import { checkKeys, checkId, wallClock } from '../checks.js';
2
+ import { byText, checkAcquire, checkEntity, checkPrefix, checkRelease, checkRenewAll, } from './shard-store.js';
3
+ const OPTIONS = new Set(['clock']);
4
+ /**
5
+ * A shard store in memory, for tests, demos and the browser, on any runtime. Every call does its
6
+ * work on a microtask, as a real store answers later, and nothing waits on time: a lease expires
7
+ * when the clock says so.
8
+ *
9
+ * It judges expiry on `clock`, its own, which no node's clock is compared with (decision 0029).
10
+ * Give a cluster on one `ManualScheduler` the scheduler's `now`, so leases expire in virtual time.
11
+ *
12
+ * @param opts.clock The store's clock, in integer ms. Defaults to `Date.now`.
13
+ */
14
+ export function inMemoryShardStore(opts = {}) {
15
+ checkKeys(opts, OPTIONS, 'inMemoryShardStore');
16
+ // The default clock, as for the journals' timestamps (decision 0015). Only this store reads it.
17
+ // eslint-disable-next-line no-restricted-properties
18
+ const { clock = Date.now } = opts;
19
+ const now = wallClock(clock, 'inMemoryShardStore');
20
+ const leases = new Map();
21
+ const entities = new Map();
22
+ const live = (lease, time) => lease !== undefined && time < lease.expiresAt;
23
+ return {
24
+ async acquire(name, holder, ttlMs) {
25
+ checkAcquire(name, holder, ttlMs);
26
+ await Promise.resolve();
27
+ const time = now();
28
+ const current = leases.get(name);
29
+ if (current !== undefined && live(current, time) && current.holder !== holder) {
30
+ return { acquired: false, holder: current.holder };
31
+ }
32
+ // Still this holder's: the same ownership, extended. Otherwise a new one.
33
+ const token = current !== undefined && live(current, time) ? current.token : (current?.token ?? 0) + 1;
34
+ leases.set(name, { holder, token, expiresAt: time + ttlMs });
35
+ return { acquired: true, token };
36
+ },
37
+ async renewAll(holder, ttlMs) {
38
+ checkRenewAll(holder, ttlMs);
39
+ await Promise.resolve();
40
+ const time = now();
41
+ const renewed = [];
42
+ for (const [name, lease] of leases) {
43
+ if (lease.holder !== holder || !live(lease, time))
44
+ continue;
45
+ leases.set(name, { ...lease, expiresAt: time + ttlMs });
46
+ renewed.push(name);
47
+ }
48
+ return renewed.sort(byText);
49
+ },
50
+ async release(name, holder, token) {
51
+ checkRelease(name, holder, token);
52
+ await Promise.resolve();
53
+ const current = leases.get(name);
54
+ if (current?.holder !== holder || current.token !== token)
55
+ return;
56
+ // Kept, expired, so the next owner's token carries on from this one.
57
+ leases.set(name, { ...current, expiresAt: -Infinity });
58
+ },
59
+ async holders(prefix) {
60
+ checkPrefix(prefix);
61
+ await Promise.resolve();
62
+ const time = now();
63
+ const found = [];
64
+ for (const [lease, current] of leases) {
65
+ if (lease.startsWith(prefix) && live(current, time)) {
66
+ found.push({ lease, holder: current.holder });
67
+ }
68
+ }
69
+ return found.sort((a, b) => byText(a.lease, b.lease));
70
+ },
71
+ async remember(shard, id) {
72
+ checkEntity(shard, id, 'remember');
73
+ await Promise.resolve();
74
+ let ids = entities.get(shard);
75
+ if (ids === undefined) {
76
+ ids = new Set();
77
+ entities.set(shard, ids);
78
+ }
79
+ ids.add(id);
80
+ },
81
+ async forget(shard, id) {
82
+ checkEntity(shard, id, 'forget');
83
+ await Promise.resolve();
84
+ entities.get(shard)?.delete(id);
85
+ },
86
+ async remembered(shard) {
87
+ checkId(shard, 'remembered: shard');
88
+ await Promise.resolve();
89
+ return [...(entities.get(shard) ?? [])].sort(byText);
90
+ },
91
+ };
92
+ }
@@ -0,0 +1,62 @@
1
+ /** The answer to {@link ShardStore.acquire}. */
2
+ export type AcquireResult = {
3
+ readonly acquired: true;
4
+ /** Goes up by one every time the lease changes hands, so a history can tell owners apart. */
5
+ readonly token: number;
6
+ } | {
7
+ readonly acquired: false;
8
+ /** Who holds it now. */
9
+ readonly holder: string;
10
+ };
11
+ /** A lease and its current holder, from {@link ShardStore.holders}. */
12
+ export interface LeaseHolder {
13
+ /** The lease's name, `<type>/<shard>`. */
14
+ readonly lease: string;
15
+ /** Who holds it, `<address>#<uid>`. */
16
+ readonly holder: string;
17
+ }
18
+ /**
19
+ * Where shard leases live, and the entities each shard remembers. A lease's name is
20
+ * `<type>/<shard>`, and a holder is `<address>#<uid>`, so a restarted node is a new holder that
21
+ * waits for its old incarnation's leases to expire.
22
+ *
23
+ * The store judges expiry on its own clock. A lease whose time is up is free, whatever its holder
24
+ * thinks. Holders judge it on theirs, and stop treating a lease as their own before the store
25
+ * would give it away. Every time is in integer milliseconds.
26
+ */
27
+ export interface ShardStore {
28
+ /**
29
+ * Takes the lease if it's free, expired or already this holder's, for `ttlMs` from now on the
30
+ * store's clock. Taking a lease that was free, released or expired raises its token by one,
31
+ * even for the holder that had it before. Taking one this holder still has keeps the token,
32
+ * and extends it.
33
+ */
34
+ acquire(lease: string, holder: string, ttlMs: number): Promise<AcquireResult>;
35
+ /** Extends every lease `holder` still holds by `ttlMs` from now, and returns their names, sorted. */
36
+ renewAll(holder: string, ttlMs: number): Promise<readonly string[]>;
37
+ /**
38
+ * Gives a lease up, if `holder` still holds it with `token`. Otherwise does nothing, so a holder
39
+ * that lost the lease can never release its next owner's.
40
+ */
41
+ release(lease: string, holder: string, token: number): Promise<void>;
42
+ /** The current holders of the unexpired leases whose names start with `prefix`, sorted by name. */
43
+ holders(prefix: string): Promise<readonly LeaseHolder[]>;
44
+ /** Records that `shard` has started entity `id`, for `remember: true`. */
45
+ remember(shard: string, id: string): Promise<void>;
46
+ /** Forgets entity `id` of `shard`. Forgetting one that isn't remembered does nothing. */
47
+ forget(shard: string, id: string): Promise<void>;
48
+ /** The entities `shard` remembers, sorted. */
49
+ remembered(shard: string): Promise<readonly string[]>;
50
+ }
51
+ /** Checks `acquire`'s arguments. */
52
+ export declare function checkAcquire(lease: unknown, holder: unknown, ttlMs: unknown): void;
53
+ /** Checks `renewAll`'s arguments. */
54
+ export declare function checkRenewAll(holder: unknown, ttlMs: unknown): void;
55
+ /** Checks `release`'s arguments. */
56
+ export declare function checkRelease(lease: unknown, holder: unknown, token: unknown): void;
57
+ /** Checks `holders`' prefix, which may be empty, to list every lease. */
58
+ export declare function checkPrefix(prefix: unknown): void;
59
+ /** Checks a shard and entity id, for `remember` and `forget`. */
60
+ export declare function checkEntity(shard: unknown, id: unknown, where: string): void;
61
+ /** Orders by UTF-16 code unit, which is code point order for the ids sharding uses. */
62
+ export declare function byText(a: string, b: string): number;
@@ -0,0 +1,36 @@
1
+ // Shard leases (decision 0029): a shard is owned by whoever holds its lease in the store, and by
2
+ // nothing else. The store judges expiry on its own clock, and each holder on its own (leases.ts),
3
+ // so no clock is ever compared with another. Every backend runs the same argument checks, from
4
+ // here, so they reject exactly the same calls.
5
+ import { checkId, checkInt } from '../checks.js';
6
+ /** Checks `acquire`'s arguments. */
7
+ export function checkAcquire(lease, holder, ttlMs) {
8
+ checkId(lease, 'acquire: lease');
9
+ checkId(holder, 'acquire: holder');
10
+ checkInt(ttlMs, 'acquire: ttlMs');
11
+ }
12
+ /** Checks `renewAll`'s arguments. */
13
+ export function checkRenewAll(holder, ttlMs) {
14
+ checkId(holder, 'renewAll: holder');
15
+ checkInt(ttlMs, 'renewAll: ttlMs');
16
+ }
17
+ /** Checks `release`'s arguments. */
18
+ export function checkRelease(lease, holder, token) {
19
+ checkId(lease, 'release: lease');
20
+ checkId(holder, 'release: holder');
21
+ checkInt(token, 'release: token');
22
+ }
23
+ /** Checks `holders`' prefix, which may be empty, to list every lease. */
24
+ export function checkPrefix(prefix) {
25
+ if (prefix !== '')
26
+ checkId(prefix, 'holders: prefix');
27
+ }
28
+ /** Checks a shard and entity id, for `remember` and `forget`. */
29
+ export function checkEntity(shard, id, where) {
30
+ checkId(shard, `${where}: shard`);
31
+ checkId(id, `${where}: id`);
32
+ }
33
+ /** Orders by UTF-16 code unit, which is code point order for the ids sharding uses. */
34
+ export function byText(a, b) {
35
+ return a < b ? -1 : a > b ? 1 : 0;
36
+ }
@@ -0,0 +1,54 @@
1
+ import { type SystemHooks } from '../internal.js';
2
+ import type { StandardSchemaV1 } from '../persistence/standard-schema.js';
3
+ import type { ActorDef, Result, SpawnOptions } from '../types.js';
4
+ import type { ShardStore } from './shard-store.js';
5
+ import type { Codec } from './wire.js';
6
+ /** A message for one entity, as its region hands it to the shard. */
7
+ export interface ShardDeliver {
8
+ readonly t: 'deliver';
9
+ readonly id: string;
10
+ /** The message, as the codec encoded it. */
11
+ readonly m: string;
12
+ /** The original sender's full path, when it was known. */
13
+ readonly from?: string;
14
+ }
15
+ type ShardInternalMsg = {
16
+ readonly t: 'drain';
17
+ } | {
18
+ readonly t: 'idle';
19
+ readonly id: string;
20
+ } | {
21
+ readonly t: 'remembered';
22
+ readonly result: Result<readonly string[]>;
23
+ } | {
24
+ readonly t: 'recall';
25
+ };
26
+ /** A message only this node can send a shard: none decodes from the wire as one. */
27
+ export declare class ShardInternal {
28
+ readonly msg: ShardInternalMsg;
29
+ constructor(msg: ShardInternalMsg);
30
+ }
31
+ /** What a shard gets. */
32
+ export type ShardMsg = ShardDeliver | ShardInternal;
33
+ /** What a shard needs from its entity type and its node. */
34
+ export interface ShardEnv {
35
+ readonly type: string;
36
+ readonly hooks: SystemHooks;
37
+ readonly codec: Codec;
38
+ readonly entity: (id: string) => ActorDef<unknown, unknown>;
39
+ readonly spawn: SpawnOptions;
40
+ readonly schema: StandardSchemaV1 | undefined;
41
+ /** Stop an entity that has had no message for this long. Undefined: never. */
42
+ readonly idleMs: number | undefined;
43
+ /** Record started entities in the store, and start them all again when the shard starts. */
44
+ readonly remember: boolean;
45
+ readonly store: ShardStore;
46
+ }
47
+ /** The path an entity's messages are addressed to, and dead letters name: `/sharding/<type>/<id>`. */
48
+ export declare function entityPath(type: string, id: string): string;
49
+ /**
50
+ * The shard actor's definition, for the shard whose lease is `lease`. Its state is nothing: its
51
+ * entities are its children, and what it knows of them lives with the incarnation.
52
+ */
53
+ export declare function shardDef(env: ShardEnv, lease: string): ActorDef<ShardMsg, null>;
54
+ export {};
@@ -0,0 +1,278 @@
1
+ // One shard of an entity type, at /system/sharding/<type>/<shard> on the node that holds its lease
2
+ // (decision 0030). It owns the shard's entities: it decodes each message its region hands it,
3
+ // checks it against the type's schema, and spawns the entity on its first message. Decoding here,
4
+ // on the entity's node, means an entity never shares an object with its sender, and a message
5
+ // that only works in memory fails on a one-node cluster as it would across nodes (decision 0025).
6
+ //
7
+ // The shard also stops its entities when they're idle (passivation) and when the shard moves
8
+ // (a drain, for a handoff). Either way an entity finishes what's in its mailbox first, a persist
9
+ // included, and what arrives meanwhile waits here for the entity's next incarnation, in order.
10
+ // With `remember`, the shard records the entities it starts in the store, and starts them all
11
+ // again wherever it starts next.
12
+ import { actor } from '../actor.js';
13
+ import { internalsOf } from '../internal.js';
14
+ /** A message only this node can send a shard: none decodes from the wire as one. */
15
+ export class ShardInternal {
16
+ msg;
17
+ constructor(msg) {
18
+ this.msg = msg;
19
+ }
20
+ }
21
+ /** The path an entity's messages are addressed to, and dead letters name: `/sharding/<type>/<id>`. */
22
+ export function entityPath(type, id) {
23
+ return `/sharding/${type}/${id}`;
24
+ }
25
+ /**
26
+ * The shard actor's definition, for the shard whose lease is `lease`. Its state is nothing: its
27
+ * entities are its children, and what it knows of them lives with the incarnation.
28
+ */
29
+ export function shardDef(env, lease) {
30
+ let shard;
31
+ return actor({
32
+ initial: (ctx) => {
33
+ shard = new Shard(env, lease, ctx);
34
+ return null;
35
+ },
36
+ receive(state, msg) {
37
+ if (msg instanceof ShardInternal) {
38
+ shard?.internal(msg.msg);
39
+ return state;
40
+ }
41
+ const checked = shard?.check(msg);
42
+ return checked === undefined ? state : checked.then(() => state);
43
+ },
44
+ onSignal(state, signal) {
45
+ if (signal.type === 'terminated')
46
+ shard?.entityStopped(signal.ref);
47
+ return state;
48
+ },
49
+ });
50
+ }
51
+ const RECALL_MIN_MS = 100;
52
+ const RECALL_MAX_MS = 2_000;
53
+ class Shard {
54
+ #env;
55
+ #lease;
56
+ #ctx;
57
+ #entities = new Map();
58
+ #byRef = new Map();
59
+ #remembered = new Set();
60
+ // Store writes in order, so a remember and a forget of one id never swap.
61
+ #writes = Promise.resolve();
62
+ #draining = false;
63
+ #recallAttempt = 0;
64
+ constructor(env, lease, ctx) {
65
+ this.#env = env;
66
+ this.#lease = lease;
67
+ this.#ctx = ctx;
68
+ if (env.remember)
69
+ this.#recall();
70
+ }
71
+ internal(msg) {
72
+ switch (msg.t) {
73
+ case 'drain':
74
+ this.#drain();
75
+ return;
76
+ case 'idle':
77
+ this.#onIdle(msg.id);
78
+ return;
79
+ case 'remembered':
80
+ this.#onRemembered(msg.result);
81
+ return;
82
+ case 'recall':
83
+ this.#recall();
84
+ return;
85
+ }
86
+ }
87
+ /** Decodes and checks a message, then delivers it. A promise while an async schema runs. */
88
+ check(msg) {
89
+ const { type, hooks, codec, schema } = this.#env;
90
+ const decoded = codec.decode(msg.m);
91
+ if (!decoded.ok) {
92
+ const recipient = entityPath(type, msg.id);
93
+ hooks.log.warn(`sharding: a message to ${recipient} can't be decoded: ${decoded.problem}`, {
94
+ recipient,
95
+ });
96
+ hooks.deadLetter(recipient, msg.m, 'unserializable');
97
+ return undefined;
98
+ }
99
+ if (schema === undefined) {
100
+ this.#deliver(msg.id, [{ value: decoded.value, from: msg.from }]);
101
+ return undefined;
102
+ }
103
+ const checked = (result) => {
104
+ if (result.issues === undefined)
105
+ this.#deliver(msg.id, [{ value: result.value, from: msg.from }]);
106
+ else
107
+ this.#invalid(msg.id, decoded.value, result.issues);
108
+ };
109
+ let result;
110
+ try {
111
+ result = schema['~standard'].validate(decoded.value);
112
+ }
113
+ catch (error) {
114
+ this.#invalid(msg.id, decoded.value, [{ message: `the schema threw: ${String(error)}` }]);
115
+ return undefined;
116
+ }
117
+ // An async schema holds the shard's mailbox, so the entity's messages stay in order.
118
+ if (!(result instanceof Promise)) {
119
+ checked(result);
120
+ return undefined;
121
+ }
122
+ return result.then(checked, (error) => {
123
+ this.#invalid(msg.id, decoded.value, [{ message: `the schema threw: ${String(error)}` }]);
124
+ });
125
+ }
126
+ #invalid(id, message, issues) {
127
+ const { hooks, type } = this.#env;
128
+ const recipient = entityPath(type, id);
129
+ hooks.log.warn(`sharding: a message to ${recipient} failed its schema`, { recipient, issues });
130
+ hooks.deadLetter(recipient, message, 'invalid');
131
+ }
132
+ /**
133
+ * Gives `messages` to entity `id`, starting it if it isn't running. While it's stopping they
134
+ * wait for its next incarnation. During a drain, an entity started here stops again once it
135
+ * has handled them.
136
+ */
137
+ #deliver(id, messages) {
138
+ let entity = this.#entities.get(id);
139
+ if (entity?.stopping === true) {
140
+ entity.held.push(...messages);
141
+ return;
142
+ }
143
+ if (entity === undefined) {
144
+ entity = this.#start(id, messages);
145
+ if (entity === undefined)
146
+ return;
147
+ }
148
+ const { hooks } = this.#env;
149
+ for (const { value, from } of messages)
150
+ hooks.tellFrom(entity.ref, value, from);
151
+ entity.lastAt = this.#ctx.now();
152
+ if (this.#draining)
153
+ this.#stopWhenIdle(entity);
154
+ }
155
+ /** Spawns entity `id`. On failure, `messages` are dead letters. */
156
+ #start(id, messages) {
157
+ const env = this.#env;
158
+ let ref;
159
+ try {
160
+ ref = this.#ctx.spawn(env.entity(id), id, env.spawn);
161
+ }
162
+ catch (error) {
163
+ this.#ctx.log.error(`sharding: could not start ${env.type} "${id}"`, { id, error });
164
+ for (const { value } of messages)
165
+ env.hooks.deadLetter(entityPath(env.type, id), value, 'stopped');
166
+ return undefined;
167
+ }
168
+ this.#ctx.watch(ref);
169
+ const entity = { id, ref, lastAt: this.#ctx.now(), stopping: false, held: [] };
170
+ this.#entities.set(id, entity);
171
+ this.#byRef.set(ref, id);
172
+ if (env.idleMs !== undefined)
173
+ this.#armIdle(id, env.idleMs);
174
+ if (env.remember && !this.#remembered.has(id)) {
175
+ this.#remembered.add(id);
176
+ this.#write('remember', id);
177
+ }
178
+ return entity;
179
+ }
180
+ #stopWhenIdle(entity) {
181
+ if (entity.stopping)
182
+ return;
183
+ entity.stopping = true;
184
+ this.#ctx.timers.cancel(idleKey(entity.id));
185
+ this.#env.hooks.stopWhenIdle(entity.ref);
186
+ }
187
+ entityStopped(ref) {
188
+ const id = this.#byRef.get(ref);
189
+ if (id === undefined)
190
+ return;
191
+ this.#byRef.delete(ref);
192
+ const entity = this.#entities.get(id);
193
+ this.#entities.delete(id);
194
+ this.#ctx.timers.cancel(idleKey(id));
195
+ if (entity === undefined)
196
+ return;
197
+ if (!entity.stopping) {
198
+ // It stopped itself, or its supervision stopped it: a remembered one is forgotten, and its
199
+ // next message starts it again.
200
+ if (this.#env.remember && this.#remembered.delete(id))
201
+ this.#write('forget', id);
202
+ }
203
+ else if (entity.held.length > 0) {
204
+ this.#deliver(id, entity.held);
205
+ }
206
+ this.#finishDrain();
207
+ }
208
+ // ---- passivation ----
209
+ #armIdle(id, delayMs) {
210
+ this.#ctx.timers.startSingle(idleKey(id), new ShardInternal({ t: 'idle', id }), delayMs);
211
+ }
212
+ #onIdle(id) {
213
+ const entity = this.#entities.get(id);
214
+ const idleMs = this.#env.idleMs;
215
+ if (entity === undefined || entity.stopping || idleMs === undefined)
216
+ return;
217
+ // One timer per entity, armed for what's left of the idle time rather than reset on every
218
+ // message.
219
+ const left = entity.lastAt + idleMs - this.#ctx.now();
220
+ if (left > 0)
221
+ this.#armIdle(id, left);
222
+ else
223
+ this.#stopWhenIdle(entity);
224
+ }
225
+ // ---- handoff ----
226
+ /** Stops every entity once it has handled what it has, then the shard itself. */
227
+ #drain() {
228
+ this.#draining = true;
229
+ for (const entity of this.#entities.values())
230
+ this.#stopWhenIdle(entity);
231
+ this.#finishDrain();
232
+ }
233
+ #finishDrain() {
234
+ if (this.#draining && this.#entities.size === 0)
235
+ this.#ctx.stop();
236
+ }
237
+ // ---- remembered entities ----
238
+ #recall() {
239
+ if (this.#draining)
240
+ return;
241
+ this.#ctx.pipeToSelf(this.#env.store.remembered(this.#lease), (result) => new ShardInternal({ t: 'remembered', result }));
242
+ }
243
+ #onRemembered(result) {
244
+ if (this.#draining)
245
+ return;
246
+ if (!result.ok) {
247
+ this.#ctx.log.warn(`sharding: could not read the entities ${this.#lease} remembers`, {
248
+ error: result.error,
249
+ });
250
+ this.#recallAttempt++;
251
+ const ceiling = Math.min(RECALL_MAX_MS, RECALL_MIN_MS * 2 ** (this.#recallAttempt - 1));
252
+ const delay = Math.round(ceiling * (0.5 + this.#env.hooks.random() / 2));
253
+ this.#ctx.timers.startSingle('recall', new ShardInternal({ t: 'recall' }), delay);
254
+ return;
255
+ }
256
+ for (const id of result.value) {
257
+ this.#remembered.add(id);
258
+ if (!this.#entities.has(id))
259
+ this.#start(id, []);
260
+ }
261
+ }
262
+ #write(op, id) {
263
+ const { store, hooks } = this.#env;
264
+ const lease = this.#lease;
265
+ this.#writes = this.#writes
266
+ .then(() => (op === 'remember' ? store.remember(lease, id) : store.forget(lease, id)))
267
+ .catch((error) => {
268
+ hooks.log.warn(`sharding: could not ${op} ${entityPath(this.#env.type, id)}`, {
269
+ id,
270
+ error,
271
+ });
272
+ });
273
+ internalsOf(this.#ctx).track(this.#writes);
274
+ }
275
+ }
276
+ function idleKey(id) {
277
+ return `idle-${id}`;
278
+ }
@@ -0,0 +1,116 @@
1
+ import type { EntityTypeInspection, SystemHooks } from '../internal.js';
2
+ import type { StandardSchemaV1 } from '../persistence/standard-schema.js';
3
+ import { type SupervisorStrategy } from '../supervision.js';
4
+ import type { ActorDef, ActorRef, ActorSystem } from '../types.js';
5
+ import type { Member } from './membership.js';
6
+ import { type Remoting } from './remoting.js';
7
+ import type { ShardStore } from './shard-store.js';
8
+ /** Options for {@link Sharding.init}. */
9
+ export interface EntityTypeOptions<M, S> {
10
+ /** The type's name, the same on every node: an actor name, such as `show`. */
11
+ type: string;
12
+ /** The entity with this id, made on its first message and after each stop. */
13
+ entity: (id: string) => ActorDef<M, S>;
14
+ /**
15
+ * How many shards the type's entities are spread over. The same on every node, and never
16
+ * changed on a running cluster: a node whose count differs is refused. Default 64.
17
+ */
18
+ shardCount?: number;
19
+ /** What happens when an entity fails (decision 0006). Default `supervise.stop()`. */
20
+ supervision?: SupervisorStrategy;
21
+ /** Whether this node hosts the type's shards, or only routes to them. Default true. */
22
+ host?: boolean;
23
+ /**
24
+ * Checks every message an entity gets, after it's decoded on the entity's node. One that fails
25
+ * is an `invalid` dead letter, with its issues logged. Any Standard Schema (decision 0018).
26
+ */
27
+ schema?: StandardSchemaV1<unknown, M>;
28
+ /** How many messages wait for each shard while its home is found. Default 1,000. */
29
+ bufferSize?: number;
30
+ /**
31
+ * Stop an entity that has had no message for `idleMs`. Messages that arrive as it stops go to
32
+ * its next incarnation, in order. Default: entities never passivate. Not with `remember`.
33
+ */
34
+ passivation?: {
35
+ idleMs: number;
36
+ };
37
+ /**
38
+ * Record each entity a shard starts in the shard store, and start every remembered entity as
39
+ * soon as its shard starts on a node, rather than on its next message. An entity that stops
40
+ * itself, or that its supervision stops, is forgotten. Default false.
41
+ */
42
+ remember?: boolean;
43
+ /** How often this node looks for shards it holds that belong elsewhere. Default 2,000. */
44
+ rebalanceMs?: number;
45
+ /** How many shards this node hands off at once while rebalancing. Default 2. */
46
+ maxHandoffs?: number;
47
+ }
48
+ /** An entity type, as {@link Sharding.init} registered it on this node. */
49
+ export interface EntityType<M> {
50
+ /** The type's name. */
51
+ readonly type: string;
52
+ /** How many shards its entities are spread over. */
53
+ readonly shardCount: number;
54
+ /**
55
+ * A ref to the entity with this id, wherever it lives now. Its path is `/sharding/<type>/<id>`
56
+ * on every node. It can't be watched, since an entity has no single incarnation to watch.
57
+ * @throws ActorNameError unless `id` is an actor name: 1 to 64 letters, digits, `.`, `_`, `~`
58
+ * or `-`, starting with a letter or digit.
59
+ */
60
+ ref(id: string): ActorRef<M>;
61
+ }
62
+ /** Entity types on this node. */
63
+ export interface Sharding {
64
+ /**
65
+ * Registers an entity type on this node, and starts its region. Every node that hosts the type
66
+ * calls it with the same `type` and `shardCount`.
67
+ * @throws TypeError for options that can't be used, unknown ones included, or a cluster that
68
+ * was given no shard store.
69
+ * @throws Error if this node has registered the type already.
70
+ */
71
+ init<M, S>(opts: EntityTypeOptions<M, S>): EntityType<M>;
72
+ }
73
+ /** How a node times its leases (decision 0029). Every time is in integer milliseconds. */
74
+ export interface LeaseOptions {
75
+ /** How long the store keeps a lease after each acquire or renewal. Default 10,000. */
76
+ ttlMs?: number;
77
+ /** How often this node renews its leases. Default 3,000. */
78
+ renewMs?: number;
79
+ /** How long before the store's expiry this node gives a lease up. Default 2,000. */
80
+ marginMs?: number;
81
+ /**
82
+ * How long each shard store call may take before this node gives up on it: an acquire, a
83
+ * renewal, a release, or a read of holders or remembered entities. Default `renewMs`. A
84
+ * renewal that times out counts as failed, and an acquire may still have been granted, so the
85
+ * next acquire finds the lease this node's own (decision 0036).
86
+ */
87
+ storeTimeoutMs?: number;
88
+ }
89
+ /** What sharding needs from its node. */
90
+ export interface ShardingEnv {
91
+ readonly system: ActorSystem;
92
+ readonly hooks: SystemHooks;
93
+ readonly remoting: Remoting;
94
+ readonly store: ShardStore | undefined;
95
+ readonly leases: Required<LeaseOptions>;
96
+ readonly maxFrameBytes: number;
97
+ readonly members: () => readonly Member[];
98
+ /** Tells inspectors that this node's view of its shards' owners may have changed. */
99
+ readonly changed: () => void;
100
+ }
101
+ /** Checks `joinCluster`'s `leases` option, and fills in the defaults. */
102
+ export declare function checkLeases(leases: unknown): Required<LeaseOptions>;
103
+ /** Whether `value` has a shard store's shape. */
104
+ export declare function isShardStore(value: unknown): value is ShardStore;
105
+ /** Sharding for one node, as its cluster sees it. */
106
+ export interface ShardingNode {
107
+ readonly api: Sharding;
108
+ /** Each entity type on this node, and the shard owners its region knows of, for inspectors. */
109
+ entityTypes(): EntityTypeInspection[];
110
+ /**
111
+ * Resolves once every region has stopped: after a leave, once each has handed its shards off.
112
+ */
113
+ whenStopped(): Promise<void>;
114
+ }
115
+ /** Sharding for one node. */
116
+ export declare function startSharding(env: ShardingEnv): ShardingNode;