@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,286 @@
1
+ // Cluster sharding (decision 0030): entity types, entity refs, and the regions that route to
2
+ // them. An entity ref names an entity by its type and id, never by where it lives, so it stays
3
+ // good when its shard moves, and it travels on the wire as `{ "$entity": { type, id } }`. Every
4
+ // message to an entity is encoded where it's sent and decoded where the entity runs, even on the
5
+ // same node, so placement never changes what arrives (decision 0025).
6
+ import { actor } from '../actor.js';
7
+ import { checkInt, checkKeys, describe } from '../checks.js';
8
+ import { ActorNameError } from '../errors.js';
9
+ import { isValidName } from '../names.js';
10
+ import { checkStrategy, supervise } from '../supervision.js';
11
+ import { leaseKeeper } from './leases.js';
12
+ import { timedStore } from './timed-store.js';
13
+ import { Internal, regionDef } from './region.js';
14
+ import { utf8Bytes } from './remoting.js';
15
+ import { entityPath } from './shard.js';
16
+ import { keyOf } from './table.js';
17
+ const OPTIONS = new Set([
18
+ 'type',
19
+ 'entity',
20
+ 'shardCount',
21
+ 'supervision',
22
+ 'host',
23
+ 'schema',
24
+ 'bufferSize',
25
+ 'passivation',
26
+ 'remember',
27
+ 'rebalanceMs',
28
+ 'maxHandoffs',
29
+ ]);
30
+ const LEASE_OPTIONS = new Set(['ttlMs', 'renewMs', 'marginMs', 'storeTimeoutMs']);
31
+ const MAX_SHARDS = 65_536;
32
+ const MEMBER_EVENTS = new Set([
33
+ 'memberUp',
34
+ 'memberLeaving',
35
+ 'memberDown',
36
+ 'memberRemoved',
37
+ 'reachability',
38
+ ]);
39
+ /** Checks `joinCluster`'s `leases` option, and fills in the defaults. */
40
+ export function checkLeases(leases) {
41
+ if (leases === undefined) {
42
+ return { ttlMs: 10_000, renewMs: 3_000, marginMs: 2_000, storeTimeoutMs: 3_000 };
43
+ }
44
+ checkKeys(leases, LEASE_OPTIONS, 'joinCluster: leases');
45
+ const { ttlMs = 10_000, renewMs = 3_000, marginMs = 2_000 } = leases;
46
+ const { storeTimeoutMs = renewMs } = leases;
47
+ checkInt(ttlMs, 'joinCluster: leases.ttlMs');
48
+ checkInt(renewMs, 'joinCluster: leases.renewMs');
49
+ checkInt(marginMs, 'joinCluster: leases.marginMs', { min: 0 });
50
+ checkInt(storeTimeoutMs, 'joinCluster: leases.storeTimeoutMs');
51
+ if (renewMs >= ttlMs - marginMs) {
52
+ throw new TypeError(`joinCluster: leases.renewMs must be less than ttlMs - marginMs, so a renewal lands ` +
53
+ `before the deadline, got ${String(renewMs)} with ttlMs ${String(ttlMs)} and marginMs ${String(marginMs)}`);
54
+ }
55
+ return { ttlMs, renewMs, marginMs, storeTimeoutMs };
56
+ }
57
+ /** Whether `value` has a shard store's shape. */
58
+ export function isShardStore(value) {
59
+ if (typeof value !== 'object' || value === null)
60
+ return false;
61
+ const s = value;
62
+ return ['acquire', 'renewAll', 'release', 'holders', 'remember', 'forget', 'remembered'].every((name) => typeof s[name] === 'function');
63
+ }
64
+ /** Sharding for one node. */
65
+ export function startSharding(env) {
66
+ const { hooks, remoting } = env;
67
+ const { address, uid } = remoting.self;
68
+ const holder = keyOf(address, uid);
69
+ const types = new Map();
70
+ const names = new WeakMap();
71
+ // Regions that have stopped, which nothing more is sent to.
72
+ const stopped = new Set();
73
+ const waitingForStop = [];
74
+ const allStopped = () => [...types.keys()].every((type) => stopped.has(type));
75
+ let guardian;
76
+ let keeper;
77
+ let stopping;
78
+ const tellRegions = (msg) => {
79
+ for (const [type, { region }] of types)
80
+ if (!stopped.has(type))
81
+ region.tell(msg);
82
+ };
83
+ // Members change on the event stream, in order with everything else.
84
+ const unsubscribe = env.system.events.subscribe((event) => {
85
+ if (!MEMBER_EVENTS.has(event.type))
86
+ return;
87
+ const own = 'address' in event && event.address === address && 'uid' in event && event.uid === uid;
88
+ if (own && (event.type === 'memberLeaving' || event.type === 'memberDown')) {
89
+ stopping ??= event.type === 'memberDown' ? 'downed' : 'leaving';
90
+ tellRegions(new Internal({ t: 'stop', reason: stopping }));
91
+ return;
92
+ }
93
+ // A leaving node still follows the members, to hand its shards to the right ones.
94
+ if (stopping !== 'downed')
95
+ tellRegions(new Internal({ t: 'members' }));
96
+ });
97
+ void env.system.whenTerminated.then(() => {
98
+ unsubscribe();
99
+ keeper?.close();
100
+ });
101
+ const { storeTimeoutMs, ...timing } = env.leases;
102
+ // One wrapper for every caller: the keeper, the regions and their shards.
103
+ const store = env.store === undefined
104
+ ? undefined
105
+ : timedStore(env.store, storeTimeoutMs, (task, ms) => hooks.scheduler.setTimer(task, ms));
106
+ const keeperFor = (store) => {
107
+ keeper ??= leaseKeeper({
108
+ store,
109
+ holder,
110
+ scheduler: hooks.scheduler,
111
+ ...timing,
112
+ onLost: (lease, token) => {
113
+ const slash = lease.indexOf('/');
114
+ const registered = types.get(lease.slice(0, slash));
115
+ registered?.region.tell(new Internal({ t: 'lost', shard: Number(lease.slice(slash + 1)), token }));
116
+ },
117
+ });
118
+ return keeper;
119
+ };
120
+ const entityRef = (type, id) => {
121
+ const path = entityPath(type, id);
122
+ const ref = hooks.makeRef(path, (message) => {
123
+ const registered = types.get(type);
124
+ if (registered === undefined) {
125
+ hooks.log.warn(`sharding: a message to ${path}, a type this node hasn't initialised`, {
126
+ recipient: path,
127
+ });
128
+ hooks.deadLetter(path, message, 'unreachable');
129
+ return;
130
+ }
131
+ const { codec } = remoting;
132
+ const encoded = codec.encode(message);
133
+ const problem = !encoded.ok
134
+ ? encoded.problem
135
+ : utf8Bytes(encoded.text) > env.maxFrameBytes
136
+ ? `it is ${String(utf8Bytes(encoded.text))} bytes, over maxFrameBytes (${String(env.maxFrameBytes)})`
137
+ : undefined;
138
+ if (!encoded.ok || problem !== undefined) {
139
+ hooks.log.warn(`sharding: a message to ${path} can't be sent: ${String(problem)}`, {
140
+ recipient: path,
141
+ });
142
+ hooks.deadLetter(path, message, 'unserializable');
143
+ return;
144
+ }
145
+ const sender = hooks.sender();
146
+ registered.region.tell(sender === undefined
147
+ ? { t: 'deliver', id, m: encoded.text }
148
+ : { t: 'deliver', id, m: encoded.text, from: codec.uri(sender) });
149
+ });
150
+ names.set(ref, { type, id });
151
+ return ref;
152
+ };
153
+ remoting.setEntities({
154
+ identify: (ref) => names.get(ref),
155
+ ref: ({ type, id }) => entityRef(type, id),
156
+ });
157
+ const api = Object.freeze({
158
+ init(opts) {
159
+ const checked = checkInit(opts);
160
+ const { type, shardCount } = checked;
161
+ if (store === undefined) {
162
+ throw new TypeError('sharding.init: the cluster has no shard store: pass joinCluster a `shards` option');
163
+ }
164
+ if (types.has(type))
165
+ throw new Error(`sharding.init: "${type}" is already initialised`);
166
+ guardian ??= hooks.spawnSystem(actor({ initial: null, receive: (s) => s }), 'sharding');
167
+ // Filled in as the region starts.
168
+ const cache = { holders: undefined };
169
+ const region = hooks.spawnSystem(regionDef({
170
+ type,
171
+ hooks,
172
+ codec: remoting.codec,
173
+ entity: checked.entity,
174
+ spawn: { supervision: checked.supervision },
175
+ schema: checked.schema,
176
+ shardCount,
177
+ host: checked.host,
178
+ bufferSize: checked.bufferSize,
179
+ idleMs: checked.idleMs,
180
+ remember: checked.remember,
181
+ rebalanceMs: checked.rebalanceMs,
182
+ maxHandoffs: checked.maxHandoffs,
183
+ remoting,
184
+ store,
185
+ keeper: checked.host ? keeperFor(store) : undefined,
186
+ members: env.members,
187
+ showHolders: (holders) => {
188
+ cache.holders = holders;
189
+ },
190
+ changed: env.changed,
191
+ onStopped: () => {
192
+ stopped.add(type);
193
+ if (allStopped())
194
+ for (const resolve of waitingForStop.splice(0))
195
+ resolve();
196
+ },
197
+ }), type, undefined, guardian);
198
+ types.set(type, { region, shardCount, host: checked.host, cache });
199
+ region.tell(stopping === undefined
200
+ ? new Internal({ t: 'members' })
201
+ : new Internal({ t: 'stop', reason: stopping }));
202
+ return Object.freeze({
203
+ type,
204
+ shardCount,
205
+ ref(id) {
206
+ if (!isValidName(id)) {
207
+ throw new ActorNameError(`entity id must be 1 to 64 letters, digits, ".", "_", "~" or "-", starting with a letter or digit, got ${describe(id)}`);
208
+ }
209
+ return entityRef(type, id);
210
+ },
211
+ });
212
+ },
213
+ });
214
+ return {
215
+ api,
216
+ entityTypes: () => [...types].map(([type, { shardCount, host, cache }]) => ({
217
+ type,
218
+ shardCount,
219
+ host,
220
+ owners: [...(cache.holders ?? [])].sort(([a], [b]) => a - b),
221
+ })),
222
+ whenStopped: () => allStopped()
223
+ ? Promise.resolve()
224
+ : new Promise((resolve) => {
225
+ waitingForStop.push(resolve);
226
+ }),
227
+ };
228
+ }
229
+ const PASSIVATION_OPTIONS = new Set(['idleMs']);
230
+ function checkInit(opts) {
231
+ checkKeys(opts, OPTIONS, 'sharding.init');
232
+ const { type, entity, shardCount = 64, supervision = supervise.stop(), host = true, schema, bufferSize = 1_000, passivation, remember = false, rebalanceMs = 2_000, maxHandoffs = 2, } = opts;
233
+ if (!isValidName(type)) {
234
+ throw new TypeError(`sharding.init: type must be an actor name, such as "show", got ${describe(type)}`);
235
+ }
236
+ if (typeof entity !== 'function') {
237
+ throw new TypeError('sharding.init: entity must be a function from an id to an actor');
238
+ }
239
+ checkInt(shardCount, 'sharding.init: shardCount');
240
+ if (shardCount > MAX_SHARDS) {
241
+ throw new TypeError(`sharding.init: shardCount must be at most ${String(MAX_SHARDS)}, got ${String(shardCount)}`);
242
+ }
243
+ checkStrategy(supervision, 'sharding.init: supervision');
244
+ if (typeof host !== 'boolean') {
245
+ throw new TypeError(`sharding.init: host must be a boolean, got ${describe(host)}`);
246
+ }
247
+ if (schema !== undefined && !isStandardSchema(schema)) {
248
+ throw new TypeError('sharding.init: schema must be a Standard Schema, with ~standard.validate');
249
+ }
250
+ checkInt(bufferSize, 'sharding.init: bufferSize');
251
+ let idleMs;
252
+ if (passivation !== undefined) {
253
+ checkKeys(passivation, PASSIVATION_OPTIONS, 'sharding.init: passivation');
254
+ idleMs = passivation.idleMs;
255
+ checkInt(idleMs, 'sharding.init: passivation.idleMs');
256
+ }
257
+ if (typeof remember !== 'boolean') {
258
+ throw new TypeError(`sharding.init: remember must be a boolean, got ${describe(remember)}`);
259
+ }
260
+ if (remember && idleMs !== undefined) {
261
+ throw new TypeError('sharding.init: a type with remember: true can’t passivate, since that would forget its entities');
262
+ }
263
+ checkInt(rebalanceMs, 'sharding.init: rebalanceMs');
264
+ checkInt(maxHandoffs, 'sharding.init: maxHandoffs');
265
+ return {
266
+ type,
267
+ entity,
268
+ shardCount,
269
+ supervision,
270
+ host,
271
+ schema,
272
+ bufferSize,
273
+ idleMs,
274
+ remember,
275
+ rebalanceMs,
276
+ maxHandoffs,
277
+ };
278
+ }
279
+ function isStandardSchema(value) {
280
+ if ((typeof value !== 'object' && typeof value !== 'function') || value === null)
281
+ return false;
282
+ const props = value['~standard'];
283
+ return (typeof props === 'object' &&
284
+ props !== null &&
285
+ typeof props.validate === 'function');
286
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Where an incarnation is in its life, in the order it moves through them. `removed` is a
3
+ * tombstone: hidden from `members()`, but kept so stale gossip can't bring the entry back.
4
+ */
5
+ export type Status = 'up' | 'leaving' | 'down' | 'removed';
6
+ /** One incarnation of one node. */
7
+ export interface Entry {
8
+ readonly address: string;
9
+ readonly uid: number;
10
+ readonly status: Status;
11
+ }
12
+ /** Entries by key, sorted by address, then uid, so every node walks them in the same order. */
13
+ export type Table = ReadonlyMap<string, Entry>;
14
+ /** An entry's key: `address#uid`, as a lease holder is named. */
15
+ export declare function keyOf(address: string, uid: number): string;
16
+ /** Whether `a` is further along than `b`. */
17
+ export declare function isAfter(a: Status, b: Status): boolean;
18
+ /** A table of `entries`, sorted. A key given twice keeps its furthest status. */
19
+ export declare function tableOf(entries: Iterable<Entry>): Table;
20
+ /** Every entry of both tables, each with the furthest status either has for it. */
21
+ export declare function merge(a: Table, b: Table): Table;
22
+ /** `table` with the entry at `key` moved to `status`, if that's further along. */
23
+ export declare function advance(table: Table, entry: Entry): Table;
24
+ /** Whether two tables hold the same entries. */
25
+ export declare function sameTable(a: Table, b: Table): boolean;
26
+ /** A table as gossip carries it: `[address, uid, status]` triples. */
27
+ export declare function encodeTable(table: Table): [string, number, Status][];
28
+ /** A table from gossip, or `undefined` if `value` isn't one. */
29
+ export declare function decodeTable(value: unknown, isAddress: (a: string) => boolean): Table | undefined;
@@ -0,0 +1,74 @@
1
+ // The member table as a plain value (decision 0028). One entry per incarnation of a node, keyed by
2
+ // its address and uid, since uids are random and can't say which incarnation came later. A status
3
+ // only moves forward, so merging two tables keeps each entry's furthest status: commutative,
4
+ // associative and idempotent, and gossip converges in any order with no coordinator.
5
+ const RANK = { up: 0, leaving: 1, down: 2, removed: 3 };
6
+ /** An entry's key: `address#uid`, as a lease holder is named. */
7
+ export function keyOf(address, uid) {
8
+ return `${address}#${String(uid)}`;
9
+ }
10
+ /** Whether `a` is further along than `b`. */
11
+ export function isAfter(a, b) {
12
+ return RANK[a] > RANK[b];
13
+ }
14
+ /** A table of `entries`, sorted. A key given twice keeps its furthest status. */
15
+ export function tableOf(entries) {
16
+ const byKey = new Map();
17
+ for (const entry of entries) {
18
+ const key = keyOf(entry.address, entry.uid);
19
+ const known = byKey.get(key);
20
+ if (known === undefined || isAfter(entry.status, known.status))
21
+ byKey.set(key, entry);
22
+ }
23
+ const sorted = [...byKey.values()].sort(compare);
24
+ return new Map(sorted.map((e) => [keyOf(e.address, e.uid), e]));
25
+ }
26
+ /** Every entry of both tables, each with the furthest status either has for it. */
27
+ export function merge(a, b) {
28
+ return tableOf([...a.values(), ...b.values()]);
29
+ }
30
+ /** `table` with the entry at `key` moved to `status`, if that's further along. */
31
+ export function advance(table, entry) {
32
+ const known = table.get(keyOf(entry.address, entry.uid));
33
+ if (known !== undefined && !isAfter(entry.status, known.status))
34
+ return table;
35
+ return tableOf([...table.values(), entry]);
36
+ }
37
+ /** Whether two tables hold the same entries. */
38
+ export function sameTable(a, b) {
39
+ if (a.size !== b.size)
40
+ return false;
41
+ for (const [key, entry] of a) {
42
+ if (b.get(key)?.status !== entry.status)
43
+ return false;
44
+ }
45
+ return true;
46
+ }
47
+ /** A table as gossip carries it: `[address, uid, status]` triples. */
48
+ export function encodeTable(table) {
49
+ return [...table.values()].map((e) => [e.address, e.uid, e.status]);
50
+ }
51
+ /** A table from gossip, or `undefined` if `value` isn't one. */
52
+ export function decodeTable(value, isAddress) {
53
+ if (!Array.isArray(value))
54
+ return undefined;
55
+ const entries = [];
56
+ for (const item of value) {
57
+ if (!Array.isArray(item) || item.length !== 3)
58
+ return undefined;
59
+ const [address, uid, status] = item;
60
+ if (typeof address !== 'string' || !isAddress(address))
61
+ return undefined;
62
+ if (typeof uid !== 'number' || !Number.isSafeInteger(uid) || uid < 0)
63
+ return undefined;
64
+ if (typeof status !== 'string' || !Object.hasOwn(RANK, status))
65
+ return undefined;
66
+ entries.push({ address, uid, status: status });
67
+ }
68
+ return tableOf(entries);
69
+ }
70
+ function compare(a, b) {
71
+ if (a.address !== b.address)
72
+ return a.address < b.address ? -1 : 1;
73
+ return a.uid - b.uid;
74
+ }
@@ -0,0 +1,4 @@
1
+ import { type SetTimer } from '../timeout.js';
2
+ import type { ShardStore } from './shard-store.js';
3
+ /** `store`, with every call failing if it hasn't answered within `ms`. */
4
+ export declare function timedStore(store: ShardStore, ms: number, setTimer: SetTimer): ShardStore;
@@ -0,0 +1,19 @@
1
+ // Every shard store call the cluster makes, timed on the node's scheduler (decision 0036). Each
2
+ // caller already treats a failed call as one to retry or log, so a timeout reuses that path. A
3
+ // renewal that times out counts as failed, and the holder's deadline still drops the lease
4
+ // (decision 0029). An acquire that times out may have been granted: the holder's next acquire
5
+ // finds the lease its own and keeps it. Never exported.
6
+ import { withTimeout } from '../timeout.js';
7
+ /** `store`, with every call failing if it hasn't answered within `ms`. */
8
+ export function timedStore(store, ms, setTimer) {
9
+ const timed = (call, promise) => withTimeout(promise, ms, setTimer, () => new Error(`shard store: ${call} did not answer within ${String(ms)} ms`));
10
+ return {
11
+ acquire: (lease, holder, ttlMs) => timed('acquire', store.acquire(lease, holder, ttlMs)),
12
+ renewAll: (holder, ttlMs) => timed('renewAll', store.renewAll(holder, ttlMs)),
13
+ release: (lease, holder, token) => timed('release', store.release(lease, holder, token)),
14
+ holders: (prefix) => timed('holders', store.holders(prefix)),
15
+ remember: (shard, id) => timed('remember', store.remember(shard, id)),
16
+ forget: (shard, id) => timed('forget', store.forget(shard, id)),
17
+ remembered: (shard) => timed('remembered', store.remembered(shard)),
18
+ };
19
+ }
@@ -0,0 +1,29 @@
1
+ /** Carries text frames between this node and others. */
2
+ export interface Transport {
3
+ /** The address other nodes reach this one at, such as `node-1:2552`. */
4
+ readonly address: string;
5
+ /**
6
+ * Starts accepting connections, and calls `onConnection` with each one. Resolves once other
7
+ * nodes can connect. A transport that refuses a peer, in either direction, says why through
8
+ * `onRefused`, so the node can log it: a peer that failed to prove a secret, say.
9
+ */
10
+ listen(onConnection: (connection: Connection) => void, onRefused?: (reason: string) => void): Promise<void>;
11
+ /** Returns at once. Frames sent before it opens wait for it, in order. */
12
+ connect(address: string): Connection;
13
+ /** Stops listening and closes every connection. */
14
+ close(): Promise<void>;
15
+ }
16
+ /** One connection between two nodes. Frames arrive in the order they were sent, or not at all. */
17
+ export interface Connection {
18
+ /** Never throws. A frame sent on a closed connection is dropped, and `onClose` has said so. */
19
+ send(frame: string): void;
20
+ /** Calls `listener` with each frame that arrives. */
21
+ onFrame(listener: (frame: string) => void): void;
22
+ /**
23
+ * Calls `listener` once, when the connection closes, from either end. `error` says why, when
24
+ * it didn't close cleanly: it never opened, or the other end vanished.
25
+ */
26
+ onClose(listener: (error?: unknown) => void): void;
27
+ /** Closes the connection. Frames already sent are still delivered. */
28
+ close(): void;
29
+ }
@@ -0,0 +1,4 @@
1
+ // What remoting needs from a network (decision 0026): text frames between addresses, in order per
2
+ // connection, at most once. A transport knows nothing about actors, so milestone 5 can swap the
3
+ // network underneath without touching remoting.
4
+ export {};
@@ -0,0 +1,90 @@
1
+ import type { SystemHooks } from '../internal.js';
2
+ import type { AnyRef } from '../types.js';
3
+ /** One incarnation of one node: where other nodes reach it, and its uid, new on every start. */
4
+ export interface NodeId {
5
+ /** The cluster's name, which every node in it shares. */
6
+ readonly cluster: string;
7
+ /** The address other nodes reach this one at, such as `node-1:2552`. */
8
+ readonly address: string;
9
+ readonly uid: number;
10
+ }
11
+ /** A parsed ref URI: `troupe://<cluster>@<address>#<uid><path>`. */
12
+ export interface RefAddress extends NodeId {
13
+ /** The actor's path on its node, such as `/user/box-office`. */
14
+ readonly path: string;
15
+ }
16
+ /** What a codec needs from its node. */
17
+ export interface CodecOptions {
18
+ /** This node. */
19
+ readonly self: NodeId;
20
+ /** The system's hooks, to find local actors by path and to make dead refs. */
21
+ readonly hooks: SystemHooks;
22
+ /**
23
+ * Makes a ref to an actor on another node, or an old incarnation of one: remoting's job.
24
+ * `uri` is the ref's full path.
25
+ */
26
+ readonly remote: (uri: string, address: RefAddress) => AnyRef;
27
+ /**
28
+ * Sharding's entity refs, once a cluster has sharding (decision 0030). Read on every use, since
29
+ * sharding starts after the codec.
30
+ */
31
+ readonly entities?: () => EntityRefs | undefined;
32
+ }
33
+ /** An entity's name: its type and its id. Both are actor names. */
34
+ export interface EntityName {
35
+ readonly type: string;
36
+ readonly id: string;
37
+ }
38
+ /** What the codec needs from sharding, to put entity refs on the wire and take them off. */
39
+ export interface EntityRefs {
40
+ /** The entity an entity ref names, or `undefined` for any other value. */
41
+ identify(ref: object): EntityName | undefined;
42
+ /** The entity ref for an entity named on the wire. */
43
+ ref(name: EntityName): AnyRef;
44
+ }
45
+ /** What encoding a message gives. */
46
+ export type Encoded = {
47
+ readonly ok: true;
48
+ readonly text: string;
49
+ } | {
50
+ readonly ok: false;
51
+ readonly problem: string;
52
+ };
53
+ /** What decoding a frame's text gives. */
54
+ export type Decoded = {
55
+ readonly ok: true;
56
+ readonly value: unknown;
57
+ } | {
58
+ readonly ok: false;
59
+ readonly problem: string;
60
+ };
61
+ /** Encodes and decodes messages for one node. */
62
+ export interface Codec {
63
+ /**
64
+ * The message as JSON text, with every ref as a `{ "$ref": uri }`, every entity ref as a
65
+ * `{ "$entity": { "type", "id" } }`, and every key that starts with `$` given one more, so data
66
+ * can't forge a marker. A problem names the first part that
67
+ * isn't JSON plus refs this system made.
68
+ */
69
+ encode(message: unknown): Encoded;
70
+ /** The text back as a message, with its refs resolved. A problem names the first bad part. */
71
+ decode(text: string): Decoded;
72
+ /**
73
+ * A value already parsed from JSON back as a message, as {@link Codec.decode} does for text:
74
+ * for a message inside a frame that has been parsed once (decision 0026).
75
+ */
76
+ decodeValue(parsed: unknown): Decoded;
77
+ /** The full URI of a path on this node, for a ref or a sender that leaves it. */
78
+ uri(path: string): string;
79
+ }
80
+ export declare const CLUSTER_NAME: RegExp;
81
+ export declare const ADDRESS: RegExp;
82
+ /**
83
+ * Makes the codec for one node.
84
+ * @throws TypeError if `self` has a bad cluster name, address or uid.
85
+ */
86
+ export declare function createCodec(opts: CodecOptions): Codec;
87
+ /** Parses a ref URI, or gives `undefined` if `text` isn't one. */
88
+ export declare function parseRefUri(text: string): RefAddress | undefined;
89
+ /** Throws `TypeError` unless `id` is a usable node identity. */
90
+ export declare function checkNodeId(id: NodeId): void;