@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.
- package/CHANGELOG.md +21 -2
- package/README.md +132 -2
- package/dist/ask.d.ts +5 -1
- package/dist/ask.js +16 -0
- package/dist/backstage/index.d.ts +2 -1
- package/dist/backstage/index.js +1 -0
- package/dist/backstage/source.d.ts +1 -1
- package/dist/backstage/source.js +65 -2
- package/dist/backstage/types.d.ts +65 -4
- package/dist/backstage/types.js +2 -1
- package/dist/backstage-ui/assets/index-CG896RLZ.css +1 -0
- package/dist/backstage-ui/assets/index-DF_Xnc1u.js +9 -0
- package/dist/backstage-ui/index.html +2 -2
- package/dist/cell.d.ts +16 -14
- package/dist/cell.js +38 -13
- package/dist/checks.d.ts +10 -0
- package/dist/checks.js +34 -2
- package/dist/cluster/index.d.ts +6 -0
- package/dist/cluster/index.js +4 -0
- package/dist/cluster/leases.d.ts +37 -0
- package/dist/cluster/leases.js +132 -0
- package/dist/cluster/membership.d.ts +100 -0
- package/dist/cluster/membership.js +559 -0
- package/dist/cluster/memory.d.ts +31 -0
- package/dist/cluster/memory.js +187 -0
- package/dist/cluster/placement.d.ts +10 -0
- package/dist/cluster/placement.js +30 -0
- package/dist/cluster/postgres/index.d.ts +1 -0
- package/dist/cluster/postgres/index.js +3 -0
- package/dist/cluster/postgres/schema.d.ts +7 -0
- package/dist/cluster/postgres/schema.js +33 -0
- package/dist/cluster/postgres/schema.sql +18 -0
- package/dist/cluster/postgres/store.d.ts +28 -0
- package/dist/cluster/postgres/store.js +124 -0
- package/dist/cluster/region.d.ts +103 -0
- package/dist/cluster/region.js +843 -0
- package/dist/cluster/remoting.d.ts +79 -0
- package/dist/cluster/remoting.js +755 -0
- package/dist/cluster/shard-memory.d.ts +14 -0
- package/dist/cluster/shard-memory.js +92 -0
- package/dist/cluster/shard-store.d.ts +62 -0
- package/dist/cluster/shard-store.js +36 -0
- package/dist/cluster/shard.d.ts +54 -0
- package/dist/cluster/shard.js +278 -0
- package/dist/cluster/sharding.d.ts +109 -0
- package/dist/cluster/sharding.js +278 -0
- package/dist/cluster/table.d.ts +29 -0
- package/dist/cluster/table.js +74 -0
- package/dist/cluster/transport.d.ts +29 -0
- package/dist/cluster/transport.js +4 -0
- package/dist/cluster/wire.d.ts +90 -0
- package/dist/cluster/wire.js +177 -0
- package/dist/hash.d.ts +7 -0
- package/dist/hash.js +25 -0
- package/dist/internal.d.ts +134 -2
- package/dist/internal.js +12 -1
- package/dist/json.d.ts +44 -0
- package/dist/json.js +143 -0
- package/dist/node/cluster/frames.d.ts +31 -0
- package/dist/node/cluster/frames.js +73 -0
- package/dist/node/cluster/index.d.ts +1 -0
- package/dist/node/cluster/index.js +3 -0
- package/dist/node/cluster/tcp.d.ts +101 -0
- package/dist/node/cluster/tcp.js +416 -0
- package/dist/persistence/actor.js +1 -1
- package/dist/persistence/backend.d.ts +1 -10
- package/dist/persistence/backend.js +4 -34
- package/dist/persistence/postgres/index.d.ts +2 -1
- package/dist/persistence/postgres/index.js +1 -1
- package/dist/persistence/postgres/pool.d.ts +44 -0
- package/dist/persistence/postgres/pool.js +65 -0
- package/dist/persistence/postgres/postgres.d.ts +1 -33
- package/dist/persistence/postgres/postgres.js +4 -63
- package/dist/system.d.ts +1 -1
- package/dist/system.js +190 -24
- package/dist/types.d.ts +86 -3
- package/package.json +25 -4
- package/dist/backstage-ui/assets/index-Bg0MCiqs.css +0 -1
- package/dist/backstage-ui/assets/index-CeefBsDh.js +0 -9
- package/dist/persistence/json.d.ts +0 -7
- package/dist/persistence/json.js +0 -75
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
// An in-memory network: every node in one process, on one scheduler (decision 0026). Frames are
|
|
2
|
+
// strings, as on TCP, so the wire format runs as it would between processes. Everything happens
|
|
3
|
+
// on the scheduler, so a cluster on a ManualScheduler is deterministic: what the tests, the
|
|
4
|
+
// browser demo and milestone 5's simulation build on.
|
|
5
|
+
import { checkInt, checkKeys, describe } from '../checks.js';
|
|
6
|
+
const OPTIONS = new Set(['scheduler', 'latencyMs']);
|
|
7
|
+
/**
|
|
8
|
+
* Makes an in-memory network on `scheduler`. Every frame is delivered `latencyMs` after it's sent,
|
|
9
|
+
* in order per connection.
|
|
10
|
+
* @throws TypeError for options that can't be used.
|
|
11
|
+
*/
|
|
12
|
+
export function inMemoryNetwork(opts) {
|
|
13
|
+
checkKeys(opts, OPTIONS, 'inMemoryNetwork');
|
|
14
|
+
const { scheduler, latencyMs = 1 } = opts;
|
|
15
|
+
const given = scheduler;
|
|
16
|
+
if (typeof given?.setTimer !== 'function') {
|
|
17
|
+
throw new TypeError('inMemoryNetwork: scheduler must be a Scheduler');
|
|
18
|
+
}
|
|
19
|
+
checkInt(latencyMs, 'inMemoryNetwork: latencyMs', { min: 0 });
|
|
20
|
+
const hosts = new Map();
|
|
21
|
+
const later = (task) => {
|
|
22
|
+
scheduler.setTimer(task, latencyMs);
|
|
23
|
+
};
|
|
24
|
+
const connect = (from, address) => {
|
|
25
|
+
const local = new End(from, later, scheduler);
|
|
26
|
+
from.ends.add(local);
|
|
27
|
+
// Opening takes one latency, as frames do, so frames sent meanwhile arrive after it.
|
|
28
|
+
later(() => {
|
|
29
|
+
if (local.closed || from.gone)
|
|
30
|
+
return;
|
|
31
|
+
const target = hosts.get(address);
|
|
32
|
+
if (target?.onConnection === undefined) {
|
|
33
|
+
local.drop(new Error(`nothing listens at ${address}`));
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
const remote = new End(target, later, scheduler);
|
|
37
|
+
target.ends.add(remote);
|
|
38
|
+
local.peer = remote;
|
|
39
|
+
remote.peer = local;
|
|
40
|
+
target.onConnection(remote);
|
|
41
|
+
});
|
|
42
|
+
return local;
|
|
43
|
+
};
|
|
44
|
+
return {
|
|
45
|
+
transport(address) {
|
|
46
|
+
if (typeof address !== 'string' || address === '') {
|
|
47
|
+
throw new TypeError(`inMemoryNetwork: address must be a non-empty string, got ${describe(address)}`);
|
|
48
|
+
}
|
|
49
|
+
if (hosts.has(address)) {
|
|
50
|
+
throw new Error(`inMemoryNetwork: ${address} already has a live transport`);
|
|
51
|
+
}
|
|
52
|
+
const host = { address, onConnection: undefined, ends: new Set(), gone: false };
|
|
53
|
+
hosts.set(address, host);
|
|
54
|
+
return {
|
|
55
|
+
address,
|
|
56
|
+
listen(onConnection) {
|
|
57
|
+
if (host.gone)
|
|
58
|
+
return Promise.reject(new Error(`${address} has closed`));
|
|
59
|
+
if (host.onConnection !== undefined) {
|
|
60
|
+
return Promise.reject(new Error(`${address} is already listening`));
|
|
61
|
+
}
|
|
62
|
+
host.onConnection = onConnection;
|
|
63
|
+
return Promise.resolve();
|
|
64
|
+
},
|
|
65
|
+
connect(to) {
|
|
66
|
+
if (host.gone) {
|
|
67
|
+
const dead = new End(host, later, scheduler);
|
|
68
|
+
dead.drop(new Error(`${address} has closed`));
|
|
69
|
+
return dead;
|
|
70
|
+
}
|
|
71
|
+
return connect(host, to);
|
|
72
|
+
},
|
|
73
|
+
close() {
|
|
74
|
+
if (!host.gone) {
|
|
75
|
+
host.gone = true;
|
|
76
|
+
host.onConnection = undefined;
|
|
77
|
+
hosts.delete(address);
|
|
78
|
+
for (const end of [...host.ends])
|
|
79
|
+
end.close();
|
|
80
|
+
}
|
|
81
|
+
return Promise.resolve();
|
|
82
|
+
},
|
|
83
|
+
};
|
|
84
|
+
},
|
|
85
|
+
kill(address) {
|
|
86
|
+
const host = hosts.get(address);
|
|
87
|
+
if (host === undefined)
|
|
88
|
+
return;
|
|
89
|
+
host.gone = true;
|
|
90
|
+
host.onConnection = undefined;
|
|
91
|
+
hosts.delete(address);
|
|
92
|
+
for (const end of [...host.ends])
|
|
93
|
+
end.vanish();
|
|
94
|
+
},
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
/** One end of a connection. */
|
|
98
|
+
class End {
|
|
99
|
+
peer;
|
|
100
|
+
closed = false;
|
|
101
|
+
#host;
|
|
102
|
+
#later;
|
|
103
|
+
#scheduler;
|
|
104
|
+
#frameListeners = [];
|
|
105
|
+
#closeListeners = [];
|
|
106
|
+
#closeError;
|
|
107
|
+
// Its node was killed, so even frames it sent before are lost.
|
|
108
|
+
#vanished = false;
|
|
109
|
+
constructor(host, later, scheduler) {
|
|
110
|
+
this.#host = host;
|
|
111
|
+
this.#later = later;
|
|
112
|
+
this.#scheduler = scheduler;
|
|
113
|
+
}
|
|
114
|
+
send(frame) {
|
|
115
|
+
if (this.closed)
|
|
116
|
+
return;
|
|
117
|
+
this.#later(() => {
|
|
118
|
+
// Lost if this node was killed since, or the other end has closed.
|
|
119
|
+
const peer = this.peer;
|
|
120
|
+
if (this.#vanished || peer === undefined || peer.closed)
|
|
121
|
+
return;
|
|
122
|
+
peer.#emitFrame(frame);
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
onFrame(listener) {
|
|
126
|
+
this.#frameListeners.push(listener);
|
|
127
|
+
}
|
|
128
|
+
onClose(listener) {
|
|
129
|
+
const closed = this.#closeError;
|
|
130
|
+
if (closed === undefined) {
|
|
131
|
+
this.#closeListeners.push(listener);
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
this.#scheduler.runSoon(() => {
|
|
135
|
+
listener(...closeArgs(closed));
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
close() {
|
|
139
|
+
if (this.closed)
|
|
140
|
+
return;
|
|
141
|
+
this.finish({});
|
|
142
|
+
// The other end hears of it after the frames already sent, which arrive first.
|
|
143
|
+
this.#later(() => {
|
|
144
|
+
this.peer?.finish({});
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
/** Closes this end because it never opened, telling its listeners why. */
|
|
148
|
+
drop(error) {
|
|
149
|
+
this.finish({ error });
|
|
150
|
+
}
|
|
151
|
+
/** This end's node was killed: nothing is told here, and the other end hears of it as an error. */
|
|
152
|
+
vanish() {
|
|
153
|
+
this.#vanished = true;
|
|
154
|
+
if (this.closed)
|
|
155
|
+
return;
|
|
156
|
+
this.closed = true;
|
|
157
|
+
this.#closeError = {};
|
|
158
|
+
this.#host.ends.delete(this);
|
|
159
|
+
this.#frameListeners.length = 0;
|
|
160
|
+
this.#closeListeners.length = 0;
|
|
161
|
+
const peer = this.peer;
|
|
162
|
+
this.#later(() => {
|
|
163
|
+
peer?.finish({ error: new Error(`the connection to ${this.#host.address} was reset`) });
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
#emitFrame(frame) {
|
|
167
|
+
for (const listener of this.#frameListeners)
|
|
168
|
+
listener(frame);
|
|
169
|
+
}
|
|
170
|
+
/** Closes this end, telling its listeners on the scheduler. */
|
|
171
|
+
finish(how) {
|
|
172
|
+
if (this.closed)
|
|
173
|
+
return;
|
|
174
|
+
this.closed = true;
|
|
175
|
+
this.#closeError = how;
|
|
176
|
+
this.#host.ends.delete(this);
|
|
177
|
+
const listeners = this.#closeListeners.splice(0);
|
|
178
|
+
// Told on the scheduler, never inside the call that closed it, so a listener can't re-enter.
|
|
179
|
+
this.#scheduler.runSoon(() => {
|
|
180
|
+
for (const listener of listeners)
|
|
181
|
+
listener(...closeArgs(how));
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
function closeArgs(how) {
|
|
186
|
+
return 'error' in how ? [how.error] : [];
|
|
187
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** The shard an entity id belongs to: its 32-bit FNV-1a hash, modulo the type's shard count. */
|
|
2
|
+
export declare function shardOf(id: string, shardCount: number): number;
|
|
3
|
+
/** How much `address` wants `shard`. Mixed, so similar addresses and shard names spread evenly. */
|
|
4
|
+
export declare function score(shard: string, address: string): number;
|
|
5
|
+
/**
|
|
6
|
+
* The candidate with the highest score for `shard`, the lower address on a tie, or `undefined`
|
|
7
|
+
* when there are none. Adding a candidate moves to it only the shards it now tops, about one in
|
|
8
|
+
* N, and removing one moves only its own.
|
|
9
|
+
*/
|
|
10
|
+
export declare function desiredOwner(shard: string, candidates: Iterable<string>): string | undefined;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// Where entities and shards go (decision 0030). An entity id hashes to a shard, and a shard's
|
|
2
|
+
// desired owner is the candidate with the highest rendezvous score for it. Pure functions of their
|
|
3
|
+
// arguments, so every node computes the same answer from the same members, with no coordinator
|
|
4
|
+
// and no table to keep. Placement only says where a shard should be: the lease says where it is.
|
|
5
|
+
import { fnv1a, mix32 } from '../hash.js';
|
|
6
|
+
/** The shard an entity id belongs to: its 32-bit FNV-1a hash, modulo the type's shard count. */
|
|
7
|
+
export function shardOf(id, shardCount) {
|
|
8
|
+
return fnv1a(id) % shardCount;
|
|
9
|
+
}
|
|
10
|
+
/** How much `address` wants `shard`. Mixed, so similar addresses and shard names spread evenly. */
|
|
11
|
+
export function score(shard, address) {
|
|
12
|
+
return mix32(fnv1a(`${shard}@${address}`));
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* The candidate with the highest score for `shard`, the lower address on a tie, or `undefined`
|
|
16
|
+
* when there are none. Adding a candidate moves to it only the shards it now tops, about one in
|
|
17
|
+
* N, and removing one moves only its own.
|
|
18
|
+
*/
|
|
19
|
+
export function desiredOwner(shard, candidates) {
|
|
20
|
+
let best;
|
|
21
|
+
let bestScore = -1;
|
|
22
|
+
for (const address of candidates) {
|
|
23
|
+
const s = score(shard, address);
|
|
24
|
+
if (s > bestScore || (s === bestScore && best !== undefined && address < best)) {
|
|
25
|
+
best = address;
|
|
26
|
+
bestScore = s;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
return best;
|
|
30
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { postgresShardStore, type PostgresShardStore } from './store.js';
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The statements that create the shard store's schema and tables, if they're missing. Separate
|
|
3
|
+
* statements, because a pool that only speaks the extended query protocol runs one per query.
|
|
4
|
+
*/
|
|
5
|
+
export declare function shardStoreSchemaStatements(schema: string): string[];
|
|
6
|
+
/** The SQL that creates the shard store's schema and tables in `schema`, as one script. */
|
|
7
|
+
export declare function shardStoreSchemaSql(schema: string): string;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// The Postgres shard store's tables, in the journal's schema or any other the caller names. The
|
|
2
|
+
// build writes the default schema's SQL to dist/cluster/postgres/schema.sql, for people who manage
|
|
3
|
+
// migrations themselves. Every statement is safe to run again. No imports, so the build's
|
|
4
|
+
// write-sql script can load it from src/ with type stripping.
|
|
5
|
+
/**
|
|
6
|
+
* The statements that create the shard store's schema and tables, if they're missing. Separate
|
|
7
|
+
* statements, because a pool that only speaks the extended query protocol runs one per query.
|
|
8
|
+
*/
|
|
9
|
+
export function shardStoreSchemaStatements(schema) {
|
|
10
|
+
const s = `"${schema}"`;
|
|
11
|
+
return [
|
|
12
|
+
`CREATE SCHEMA IF NOT EXISTS ${s}`,
|
|
13
|
+
`CREATE TABLE IF NOT EXISTS ${s}.shard_leases (
|
|
14
|
+
name TEXT PRIMARY KEY,
|
|
15
|
+
holder TEXT NOT NULL,
|
|
16
|
+
-- Up by one every time the lease changes hands. A released lease keeps its row, so it never
|
|
17
|
+
-- goes back to 1.
|
|
18
|
+
token BIGINT NOT NULL,
|
|
19
|
+
-- On the database's clock, clock_timestamp(), never a node's (decision 0029). A released lease
|
|
20
|
+
-- expires at -infinity.
|
|
21
|
+
expires_at TIMESTAMPTZ NOT NULL
|
|
22
|
+
)`,
|
|
23
|
+
`CREATE TABLE IF NOT EXISTS ${s}.remembered_entities (
|
|
24
|
+
shard TEXT NOT NULL,
|
|
25
|
+
entity_id TEXT NOT NULL,
|
|
26
|
+
PRIMARY KEY (shard, entity_id)
|
|
27
|
+
)`,
|
|
28
|
+
];
|
|
29
|
+
}
|
|
30
|
+
/** The SQL that creates the shard store's schema and tables in `schema`, as one script. */
|
|
31
|
+
export function shardStoreSchemaSql(schema) {
|
|
32
|
+
return `${shardStoreSchemaStatements(schema).join(';\n\n')};\n`;
|
|
33
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
CREATE SCHEMA IF NOT EXISTS "troupe";
|
|
2
|
+
|
|
3
|
+
CREATE TABLE IF NOT EXISTS "troupe".shard_leases (
|
|
4
|
+
name TEXT PRIMARY KEY,
|
|
5
|
+
holder TEXT NOT NULL,
|
|
6
|
+
-- Up by one every time the lease changes hands. A released lease keeps its row, so it never
|
|
7
|
+
-- goes back to 1.
|
|
8
|
+
token BIGINT NOT NULL,
|
|
9
|
+
-- On the database's clock, clock_timestamp(), never a node's (decision 0029). A released lease
|
|
10
|
+
-- expires at -infinity.
|
|
11
|
+
expires_at TIMESTAMPTZ NOT NULL
|
|
12
|
+
);
|
|
13
|
+
|
|
14
|
+
CREATE TABLE IF NOT EXISTS "troupe".remembered_entities (
|
|
15
|
+
shard TEXT NOT NULL,
|
|
16
|
+
entity_id TEXT NOT NULL,
|
|
17
|
+
PRIMARY KEY (shard, entity_id)
|
|
18
|
+
);
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { type PgPool } from '../../persistence/postgres/pool.js';
|
|
2
|
+
import { type ShardStore } from '../shard-store.js';
|
|
3
|
+
/** The Postgres shard store, on the caller's pool. */
|
|
4
|
+
export interface PostgresShardStore extends ShardStore {
|
|
5
|
+
/**
|
|
6
|
+
* Creates the schema and tables if they're missing. Safe to run on every start, from several
|
|
7
|
+
* processes at once, and alongside the journal's `setup()` on the same schema. Skip it if you
|
|
8
|
+
* manage migrations yourself: the SQL ships as `dist/cluster/postgres/schema.sql`.
|
|
9
|
+
*/
|
|
10
|
+
setup(): Promise<void>;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* A shard store on Postgres, through the caller's own `pg`-compatible pool, so it adds no
|
|
14
|
+
* dependency and runs wherever the pool does (decision 0017). Its tables can share a schema with
|
|
15
|
+
* the journal's. Call `setup()` once to create them, or create them yourself.
|
|
16
|
+
*
|
|
17
|
+
* Expiry is judged on the database's own clock, `clock_timestamp()`, never a node's (decision
|
|
18
|
+
* 0029). An acquire is one `INSERT ... ON CONFLICT DO UPDATE` whose condition Postgres checks again
|
|
19
|
+
* under the row's lock, so two nodes racing for a lease can't both win, in one process or many.
|
|
20
|
+
*
|
|
21
|
+
* @param opts.pool The pool to run on. The store never ends it.
|
|
22
|
+
* @param opts.schema The schema for the tables: lower-case letters, digits and `_`. Default
|
|
23
|
+
* `troupe`, the journal's.
|
|
24
|
+
*/
|
|
25
|
+
export declare function postgresShardStore(opts: {
|
|
26
|
+
pool: PgPool;
|
|
27
|
+
schema?: string;
|
|
28
|
+
}): PostgresShardStore;
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { checkKeys, checkId, describe } from '../../checks.js';
|
|
2
|
+
import { checkPool, LOCK, LOCK_CLASS, schemaHash, toInt, transaction, } from '../../persistence/postgres/pool.js';
|
|
3
|
+
import { DEFAULT_SCHEMA, isSchemaName } from '../../persistence/postgres/schema.js';
|
|
4
|
+
import { byText, checkAcquire, checkEntity, checkPrefix, checkRelease, checkRenewAll, } from '../shard-store.js';
|
|
5
|
+
import { shardStoreSchemaStatements } from './schema.js';
|
|
6
|
+
const OPTIONS = new Set(['pool', 'schema']);
|
|
7
|
+
// A loser reads the winner back. If the lease was released or expired in between, it tries again,
|
|
8
|
+
// a few times at most, then reports whoever holds the row.
|
|
9
|
+
const ACQUIRE_ATTEMPTS = 3;
|
|
10
|
+
/**
|
|
11
|
+
* A shard store on Postgres, through the caller's own `pg`-compatible pool, so it adds no
|
|
12
|
+
* dependency and runs wherever the pool does (decision 0017). Its tables can share a schema with
|
|
13
|
+
* the journal's. Call `setup()` once to create them, or create them yourself.
|
|
14
|
+
*
|
|
15
|
+
* Expiry is judged on the database's own clock, `clock_timestamp()`, never a node's (decision
|
|
16
|
+
* 0029). An acquire is one `INSERT ... ON CONFLICT DO UPDATE` whose condition Postgres checks again
|
|
17
|
+
* under the row's lock, so two nodes racing for a lease can't both win, in one process or many.
|
|
18
|
+
*
|
|
19
|
+
* @param opts.pool The pool to run on. The store never ends it.
|
|
20
|
+
* @param opts.schema The schema for the tables: lower-case letters, digits and `_`. Default
|
|
21
|
+
* `troupe`, the journal's.
|
|
22
|
+
*/
|
|
23
|
+
export function postgresShardStore(opts) {
|
|
24
|
+
checkKeys(opts, OPTIONS, 'postgresShardStore');
|
|
25
|
+
const { pool, schema = DEFAULT_SCHEMA } = opts;
|
|
26
|
+
checkPool(pool, 'postgresShardStore');
|
|
27
|
+
if (!isSchemaName(schema)) {
|
|
28
|
+
throw new TypeError('postgresShardStore: schema must be lower-case letters, digits and _, starting with a ' +
|
|
29
|
+
`letter or _, at most 63, got ${describe(schema)}`);
|
|
30
|
+
}
|
|
31
|
+
const s = `"${schema}"`;
|
|
32
|
+
const lockKey = schemaHash(schema);
|
|
33
|
+
const EXPIRY = `clock_timestamp() + $3::double precision * interval '1 millisecond'`;
|
|
34
|
+
// The WHERE runs again once the row's lock is free, against what the other writer committed,
|
|
35
|
+
// so it decides every race. A lease still this holder's keeps its token. Any other change of
|
|
36
|
+
// hands, back to the same holder included, raises it.
|
|
37
|
+
const ACQUIRE = `INSERT INTO ${s}.shard_leases AS l (name, holder, token, expires_at)
|
|
38
|
+
VALUES ($1, $2, 1, ${EXPIRY})
|
|
39
|
+
ON CONFLICT (name) DO UPDATE SET
|
|
40
|
+
token = CASE WHEN l.holder = excluded.holder AND l.expires_at > clock_timestamp()
|
|
41
|
+
THEN l.token ELSE l.token + 1 END,
|
|
42
|
+
holder = excluded.holder,
|
|
43
|
+
expires_at = excluded.expires_at
|
|
44
|
+
WHERE l.holder = excluded.holder OR l.expires_at <= clock_timestamp()
|
|
45
|
+
RETURNING token`;
|
|
46
|
+
const HOLDER = `SELECT holder, expires_at > clock_timestamp() AS live
|
|
47
|
+
FROM ${s}.shard_leases WHERE name = $1`;
|
|
48
|
+
const RENEW = `UPDATE ${s}.shard_leases SET expires_at = clock_timestamp() + $2::double precision
|
|
49
|
+
* interval '1 millisecond'
|
|
50
|
+
WHERE holder = $1 AND expires_at > clock_timestamp()
|
|
51
|
+
RETURNING name`;
|
|
52
|
+
const RELEASE = `UPDATE ${s}.shard_leases SET expires_at = '-infinity'
|
|
53
|
+
WHERE name = $1 AND holder = $2 AND token = $3`;
|
|
54
|
+
// COLLATE "C" sorts by code point, as the in-memory store does, whatever the database's locale.
|
|
55
|
+
const HOLDERS = `SELECT name, holder FROM ${s}.shard_leases
|
|
56
|
+
WHERE starts_with(name, $1) AND expires_at > clock_timestamp() ORDER BY name COLLATE "C"`;
|
|
57
|
+
const REMEMBER = `INSERT INTO ${s}.remembered_entities (shard, entity_id) VALUES ($1, $2)
|
|
58
|
+
ON CONFLICT DO NOTHING`;
|
|
59
|
+
const FORGET = `DELETE FROM ${s}.remembered_entities WHERE shard = $1 AND entity_id = $2`;
|
|
60
|
+
const REMEMBERED = `SELECT entity_id FROM ${s}.remembered_entities WHERE shard = $1
|
|
61
|
+
ORDER BY entity_id COLLATE "C"`;
|
|
62
|
+
async function rows(text, values) {
|
|
63
|
+
const result = await pool.query(text, values);
|
|
64
|
+
return result.rows;
|
|
65
|
+
}
|
|
66
|
+
return {
|
|
67
|
+
async acquire(lease, holder, ttlMs) {
|
|
68
|
+
checkAcquire(lease, holder, ttlMs);
|
|
69
|
+
// In a read-committed transaction, whatever the database's default, so the upsert waits for
|
|
70
|
+
// a racing one instead of failing to serialize, and the read after it sees the winner.
|
|
71
|
+
return await transaction(pool, async (client) => {
|
|
72
|
+
let holderNow = '';
|
|
73
|
+
for (let attempt = 0; attempt < ACQUIRE_ATTEMPTS; attempt++) {
|
|
74
|
+
const [won] = (await client.query(ACQUIRE, [lease, holder, ttlMs])).rows;
|
|
75
|
+
if (won !== undefined)
|
|
76
|
+
return { acquired: true, token: toInt(won.token) };
|
|
77
|
+
const [row] = (await client.query(HOLDER, [lease])).rows;
|
|
78
|
+
if (row === undefined)
|
|
79
|
+
continue;
|
|
80
|
+
holderNow = row.holder;
|
|
81
|
+
if (row.live)
|
|
82
|
+
break;
|
|
83
|
+
}
|
|
84
|
+
return { acquired: false, holder: holderNow };
|
|
85
|
+
});
|
|
86
|
+
},
|
|
87
|
+
async renewAll(holder, ttlMs) {
|
|
88
|
+
checkRenewAll(holder, ttlMs);
|
|
89
|
+
// In a transaction for read committed, as acquire is, so it can't fail to serialize.
|
|
90
|
+
const renewed = await transaction(pool, async (client) => (await client.query(RENEW, [holder, ttlMs])).rows);
|
|
91
|
+
return renewed.map((r) => r.name).sort(byText);
|
|
92
|
+
},
|
|
93
|
+
async release(lease, holder, token) {
|
|
94
|
+
checkRelease(lease, holder, token);
|
|
95
|
+
await pool.query(RELEASE, [lease, holder, token]);
|
|
96
|
+
},
|
|
97
|
+
async holders(prefix) {
|
|
98
|
+
checkPrefix(prefix);
|
|
99
|
+
const found = await rows(HOLDERS, [prefix]);
|
|
100
|
+
return found.map((r) => ({ lease: r.name, holder: r.holder }));
|
|
101
|
+
},
|
|
102
|
+
async remember(shard, id) {
|
|
103
|
+
checkEntity(shard, id, 'remember');
|
|
104
|
+
await pool.query(REMEMBER, [shard, id]);
|
|
105
|
+
},
|
|
106
|
+
async forget(shard, id) {
|
|
107
|
+
checkEntity(shard, id, 'forget');
|
|
108
|
+
await pool.query(FORGET, [shard, id]);
|
|
109
|
+
},
|
|
110
|
+
async remembered(shard) {
|
|
111
|
+
checkId(shard, 'remembered: shard');
|
|
112
|
+
return (await rows(REMEMBERED, [shard])).map((r) => r.entity_id);
|
|
113
|
+
},
|
|
114
|
+
async setup() {
|
|
115
|
+
// Under the schema's advisory lock, which the journal's setup() takes too, so neither races
|
|
116
|
+
// the other, or itself in another process, to create the schema.
|
|
117
|
+
await transaction(pool, async (client) => {
|
|
118
|
+
await client.query(LOCK, [LOCK_CLASS, lockKey]);
|
|
119
|
+
for (const statement of shardStoreSchemaStatements(schema))
|
|
120
|
+
await client.query(statement);
|
|
121
|
+
});
|
|
122
|
+
},
|
|
123
|
+
};
|
|
124
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import type { ActorDef, AnyRef, Result } from '../types.js';
|
|
2
|
+
import type { LeaseKeeper } from './leases.js';
|
|
3
|
+
import type { Member } from './membership.js';
|
|
4
|
+
import type { Remoting } from './remoting.js';
|
|
5
|
+
import type { AcquireResult, LeaseHolder } from './shard-store.js';
|
|
6
|
+
import { type ShardEnv } from './shard.js';
|
|
7
|
+
/** What a region needs from its entity type and its node. */
|
|
8
|
+
export interface RegionEnv extends ShardEnv {
|
|
9
|
+
readonly shardCount: number;
|
|
10
|
+
readonly host: boolean;
|
|
11
|
+
readonly bufferSize: number;
|
|
12
|
+
/** How often a hosting region looks for shards to hand off. */
|
|
13
|
+
readonly rebalanceMs: number;
|
|
14
|
+
/** How many handoffs a region runs at once while rebalancing. */
|
|
15
|
+
readonly maxHandoffs: number;
|
|
16
|
+
readonly remoting: Remoting;
|
|
17
|
+
/** This node's leases. Only a hosting node has one. */
|
|
18
|
+
readonly keeper: LeaseKeeper | undefined;
|
|
19
|
+
/** The members as this node sees them, itself included. */
|
|
20
|
+
readonly members: () => readonly Member[];
|
|
21
|
+
/** Called once the region has stopped, so nothing more is sent to it. */
|
|
22
|
+
readonly onStopped: () => void;
|
|
23
|
+
/** Called as the region starts, with its holder cache, which inspectors read but never change. */
|
|
24
|
+
readonly showHolders: (holders: ReadonlyMap<number, string>) => void;
|
|
25
|
+
/** Called whenever the holder cache changes, so inspectors see shards move. */
|
|
26
|
+
readonly changed: () => void;
|
|
27
|
+
}
|
|
28
|
+
/** A message for an entity, on its way to its shard. */
|
|
29
|
+
export interface Envelope {
|
|
30
|
+
readonly id: string;
|
|
31
|
+
/** The message, as the codec encoded it. */
|
|
32
|
+
readonly m: string;
|
|
33
|
+
/** The original sender's full path, when it was known. */
|
|
34
|
+
readonly from?: string;
|
|
35
|
+
/** How many times regions have sent it back with `notOwner`. */
|
|
36
|
+
readonly bounces?: number;
|
|
37
|
+
}
|
|
38
|
+
/** Why a region stops its shards as it stops. */
|
|
39
|
+
export type StopReason = 'leaving' | 'downed';
|
|
40
|
+
/**
|
|
41
|
+
* What a region gets: from entity refs on its own node, a `deliver` with no `back`. From other
|
|
42
|
+
* regions, a `deliver` with `back` set to the sender's region, and the rest of the protocol.
|
|
43
|
+
*/
|
|
44
|
+
export type RegionMsg = (Envelope & {
|
|
45
|
+
readonly t: 'deliver';
|
|
46
|
+
readonly back?: AnyRef;
|
|
47
|
+
}) | {
|
|
48
|
+
readonly t: 'hello';
|
|
49
|
+
readonly shardCount: number;
|
|
50
|
+
readonly host: boolean;
|
|
51
|
+
readonly region: AnyRef;
|
|
52
|
+
readonly reply?: true;
|
|
53
|
+
} | {
|
|
54
|
+
readonly t: 'start';
|
|
55
|
+
readonly shard: number;
|
|
56
|
+
readonly back: AnyRef;
|
|
57
|
+
} | {
|
|
58
|
+
readonly t: 'home';
|
|
59
|
+
readonly shard: number;
|
|
60
|
+
readonly holder: string | null;
|
|
61
|
+
} | {
|
|
62
|
+
readonly t: 'notOwner';
|
|
63
|
+
readonly shard: number;
|
|
64
|
+
readonly holder: string;
|
|
65
|
+
readonly envelopes: readonly Envelope[];
|
|
66
|
+
} | Internal;
|
|
67
|
+
type InternalMsg = {
|
|
68
|
+
readonly t: 'members';
|
|
69
|
+
} | {
|
|
70
|
+
readonly t: 'retry';
|
|
71
|
+
readonly shard: number;
|
|
72
|
+
} | {
|
|
73
|
+
readonly t: 'holders';
|
|
74
|
+
readonly shard: number;
|
|
75
|
+
readonly result: Result<readonly LeaseHolder[]>;
|
|
76
|
+
} | {
|
|
77
|
+
readonly t: 'acquired';
|
|
78
|
+
readonly shard: number;
|
|
79
|
+
readonly result: Result<AcquireResult>;
|
|
80
|
+
} | {
|
|
81
|
+
readonly t: 'lost';
|
|
82
|
+
readonly shard: number;
|
|
83
|
+
readonly token: number;
|
|
84
|
+
} | {
|
|
85
|
+
readonly t: 'released';
|
|
86
|
+
readonly shard: number;
|
|
87
|
+
} | {
|
|
88
|
+
readonly t: 'rebalance';
|
|
89
|
+
} | {
|
|
90
|
+
readonly t: 'claim';
|
|
91
|
+
readonly result: Result<readonly LeaseHolder[]>;
|
|
92
|
+
} | {
|
|
93
|
+
readonly t: 'stop';
|
|
94
|
+
readonly reason: StopReason;
|
|
95
|
+
};
|
|
96
|
+
/** A message only this node can send its region: none decodes from the wire as one. */
|
|
97
|
+
export declare class Internal {
|
|
98
|
+
readonly msg: InternalMsg;
|
|
99
|
+
constructor(msg: InternalMsg);
|
|
100
|
+
}
|
|
101
|
+
/** The region actor's definition. Its routing state lives with the incarnation, not in state. */
|
|
102
|
+
export declare function regionDef(env: RegionEnv): ActorDef<RegionMsg, null>;
|
|
103
|
+
export {};
|