@articollab/sync 0.0.0-stage → 0.12.0-beta.1
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/LICENSE +21 -0
- package/README.md +6 -2
- package/dist/client.d.ts +107 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +568 -0
- package/dist/client.js.map +1 -0
- package/dist/errors.d.ts +18 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +28 -0
- package/dist/errors.js.map +1 -0
- package/dist/host.d.ts +69 -0
- package/dist/host.d.ts.map +1 -0
- package/dist/host.js +334 -0
- package/dist/host.js.map +1 -0
- package/dist/http-client.d.ts +16 -0
- package/dist/http-client.d.ts.map +1 -0
- package/dist/http-client.js +82 -0
- package/dist/http-client.js.map +1 -0
- package/dist/http-handler.d.ts +87 -0
- package/dist/http-handler.d.ts.map +1 -0
- package/dist/http-handler.js +532 -0
- package/dist/http-handler.js.map +1 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +11 -0
- package/dist/index.js.map +1 -0
- package/dist/node.d.ts +31 -0
- package/dist/node.d.ts.map +1 -0
- package/dist/node.js +62 -0
- package/dist/node.js.map +1 -0
- package/dist/postgres.d.ts +45 -0
- package/dist/postgres.d.ts.map +1 -0
- package/dist/postgres.js +252 -0
- package/dist/postgres.js.map +1 -0
- package/dist/presence.d.ts +35 -0
- package/dist/presence.d.ts.map +1 -0
- package/dist/presence.js +118 -0
- package/dist/presence.js.map +1 -0
- package/dist/server-file-store.d.ts +19 -0
- package/dist/server-file-store.d.ts.map +1 -0
- package/dist/server-file-store.js +149 -0
- package/dist/server-file-store.js.map +1 -0
- package/dist/server-store.d.ts +59 -0
- package/dist/server-store.d.ts.map +1 -0
- package/dist/server-store.js +97 -0
- package/dist/server-store.js.map +1 -0
- package/dist/socket-client.d.ts +23 -0
- package/dist/socket-client.d.ts.map +1 -0
- package/dist/socket-client.js +219 -0
- package/dist/socket-client.js.map +1 -0
- package/dist/socket-handler.d.ts +78 -0
- package/dist/socket-handler.d.ts.map +1 -0
- package/dist/socket-handler.js +183 -0
- package/dist/socket-handler.js.map +1 -0
- package/dist/sse.d.ts +13 -0
- package/dist/sse.d.ts.map +1 -0
- package/dist/sse.js +61 -0
- package/dist/sse.js.map +1 -0
- package/dist/store.d.ts +79 -0
- package/dist/store.d.ts.map +1 -0
- package/dist/store.js +193 -0
- package/dist/store.js.map +1 -0
- package/package.json +60 -3
package/dist/node.js
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import * as nodeFs from "node:fs/promises";
|
|
3
|
+
import { dirname, basename, join, resolve } from "node:path";
|
|
4
|
+
import { acquireLock, closable } from "./store.js";
|
|
5
|
+
export { CheckpointLockedError } from "./store.js";
|
|
6
|
+
export { openFileServerStore } from "./server-file-store.js";
|
|
7
|
+
function isMissing(error) {
|
|
8
|
+
return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Opens a checkpoint file. Each save writes a temporary file in the same directory, flushes it and
|
|
12
|
+
* renames it over `path`, so the file always holds a complete checkpoint. Opening the same path
|
|
13
|
+
* twice in one process throws `CheckpointLockedError`; separate processes are not coordinated, so
|
|
14
|
+
* give each process its own file. Power-loss durability depends on the file system and is not promised.
|
|
15
|
+
*/
|
|
16
|
+
export async function openFileStore(path, options = {}) {
|
|
17
|
+
if (typeof path !== "string" || path.length === 0)
|
|
18
|
+
throw new TypeError("path must be a nonempty string");
|
|
19
|
+
const target = resolve(path);
|
|
20
|
+
const fs = options.fs ?? nodeFs;
|
|
21
|
+
const state = closable(await acquireLock(`articollab:file:${target}`, options.locks));
|
|
22
|
+
return {
|
|
23
|
+
load: () => state.run(async () => {
|
|
24
|
+
let text;
|
|
25
|
+
try {
|
|
26
|
+
text = await fs.readFile(target, "utf8");
|
|
27
|
+
}
|
|
28
|
+
catch (error) {
|
|
29
|
+
if (isMissing(error))
|
|
30
|
+
return undefined;
|
|
31
|
+
throw error;
|
|
32
|
+
}
|
|
33
|
+
try {
|
|
34
|
+
return JSON.parse(text);
|
|
35
|
+
}
|
|
36
|
+
catch (cause) {
|
|
37
|
+
throw new Error(`Checkpoint file is not valid JSON: ${target}`, { cause });
|
|
38
|
+
}
|
|
39
|
+
}),
|
|
40
|
+
save: (checkpoint) => state.run(async () => {
|
|
41
|
+
const temporary = join(dirname(target), `.${basename(target)}.${randomUUID()}.tmp`);
|
|
42
|
+
try {
|
|
43
|
+
const file = await fs.open(temporary, "wx");
|
|
44
|
+
try {
|
|
45
|
+
await file.writeFile(JSON.stringify(checkpoint), "utf8");
|
|
46
|
+
await file.sync();
|
|
47
|
+
}
|
|
48
|
+
finally {
|
|
49
|
+
await file.close();
|
|
50
|
+
}
|
|
51
|
+
await fs.rename(temporary, target);
|
|
52
|
+
}
|
|
53
|
+
catch (error) {
|
|
54
|
+
await fs.rm(temporary, { force: true }).catch(() => { });
|
|
55
|
+
throw error;
|
|
56
|
+
}
|
|
57
|
+
}),
|
|
58
|
+
clear: () => state.run(async () => { await fs.rm(target, { force: true }); }),
|
|
59
|
+
close() { state.close().catch(() => { }); },
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
//# sourceMappingURL=node.js.map
|
package/dist/node.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"node.js","sourceRoot":"","sources":["../src/node.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,KAAK,MAAM,MAAM,kBAAkB,CAAC;AAC3C,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAE7D,OAAO,EAAE,WAAW,EAAE,QAAQ,EAA8C,MAAM,YAAY,CAAC;AAE/F,OAAO,EAAE,qBAAqB,EAAwB,MAAM,YAAY,CA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-0,0 +1,45 @@
|
|
|
1
|
+
import type { ServerStore } from "./server-store.ts";
|
|
2
|
+
export { CheckpointLockedError } from "./store.ts";
|
|
3
|
+
export type { ServerStore } from "./server-store.ts";
|
|
4
|
+
/** The part of a Postgres connection the store uses; node-postgres `Client` and PGlite both fit. */
|
|
5
|
+
export interface PostgresClient {
|
|
6
|
+
query(text: string, values?: unknown[]): Promise<{
|
|
7
|
+
readonly rows: readonly unknown[];
|
|
8
|
+
}>;
|
|
9
|
+
}
|
|
10
|
+
export interface PostgresServerStoreOptions {
|
|
11
|
+
/**
|
|
12
|
+
* One dedicated connection, held by this store: its advisory lock and transactions belong to the
|
|
13
|
+
* connection's session. Pass `client` or `pool`, not both.
|
|
14
|
+
*/
|
|
15
|
+
readonly client?: PostgresClient;
|
|
16
|
+
/**
|
|
17
|
+
* Any connections, such as a node-postgres `Pool`: the store holds a lease instead of a lock, and
|
|
18
|
+
* runs every write as one statement that first checks it still holds the lease.
|
|
19
|
+
*/
|
|
20
|
+
readonly pool?: PostgresClient;
|
|
21
|
+
/** The document's key; one server per document. */
|
|
22
|
+
readonly document: string;
|
|
23
|
+
/** Prefix of the tables, `<table>_checkpoints`, `<table>_entries` and, with `pool`, `<table>_leases`. Default `"articollab"`. */
|
|
24
|
+
readonly table?: string;
|
|
25
|
+
/** With `pool`: milliseconds a lease lasts unless renewed. The store renews it every third of this. Default 30000. */
|
|
26
|
+
readonly leaseTtl?: number;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Opens one document's server log in Postgres: its checkpoint in `<table>_checkpoints` and the
|
|
30
|
+
* entries after it in `<table>_entries`, created when missing. Values are `json`, kept exactly as
|
|
31
|
+
* written. An append is one insert; a compaction replaces the checkpoint and deletes the entries
|
|
32
|
+
* in one step.
|
|
33
|
+
*
|
|
34
|
+
* Only one store of a document may be open, on any connection to the database; a second one throws
|
|
35
|
+
* `CheckpointLockedError`. Await `close()` before opening the store again elsewhere.
|
|
36
|
+
*
|
|
37
|
+
* With `client`, an advisory lock on that connection, held until `close()`, keeps others out. The
|
|
38
|
+
* caller owns the connection and should discard it if unlocking fails.
|
|
39
|
+
*
|
|
40
|
+
* With `pool`, the store holds a lease in `<table>_leases` and renews it while open. Every write
|
|
41
|
+
* checks the lease in the same statement, so once another store takes over an expired lease, this
|
|
42
|
+
* one's writes throw `CheckpointLockedError` instead of landing. `close()` releases the lease.
|
|
43
|
+
*/
|
|
44
|
+
export declare function openPostgresServerStore(options: PostgresServerStoreOptions): Promise<ServerStore>;
|
|
45
|
+
//# sourceMappingURL=postgres.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"postgres.d.ts","sourceRoot":"","sources":["../src/postgres.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAGrD,OAAO,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAC;AACnD,YAAY,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAErD,oGAAoG;AACpG,MAAM,WAAW,cAAc;IAC7B,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC;QAAE,QAAQ,CAAC,IAAI,EAAE,SAAS,OAAO,EAAE,CAAA;KAAE,CAAC,CAAC;CACzF;AAED,MAAM,WAAW,0BAA0B;IACzC;;;OAGG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,cAAc,CAAC;IACjC;;;OAGG;IACH,QAAQ,CAAC,IAAI,CAAC,EAAE,cAAc,CAAC;IAC/B,mDAAmD;IACnD,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,iIAAiI;IACjI,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IACxB,sHAAsH;IACtH,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;CAC5B;AA0CD;;;;;;;;;;;;;;;GAeG;AACH,wBAAsB,uBAAuB,CAAC,OAAO,EAAE,0BAA0B,GAAG,OAAO,CAAC,WAAW,CAAC,CAuGvG"}
|
package/dist/postgres.js
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
import { integerOption } from "@articollab/core/adapter";
|
|
2
|
+
import { CheckpointLockedError } from "./store.js";
|
|
3
|
+
export { CheckpointLockedError } from "./store.js";
|
|
4
|
+
const TABLE = /^[a-z_][a-z0-9_]{0,47}$/;
|
|
5
|
+
/**
|
|
6
|
+
* Documents open on each connection or pool, or the release of one closing. Advisory locks do not
|
|
7
|
+
* exclude their own session, and a lease is released only once the store finishes closing.
|
|
8
|
+
*/
|
|
9
|
+
const opened = new WeakMap();
|
|
10
|
+
/**
|
|
11
|
+
* The advisory lock key of a document: the first 64 bits of a SHA-256 of the table prefix and the
|
|
12
|
+
* document, as Postgres's two signed 32-bit halves, so distinct documents practically never share one.
|
|
13
|
+
*/
|
|
14
|
+
async function lockKey(table, document) {
|
|
15
|
+
const digest = new DataView(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(`articollab\0${table}\0${document}`)));
|
|
16
|
+
return [digest.getInt32(0), digest.getInt32(4)];
|
|
17
|
+
}
|
|
18
|
+
function column(rows, index, name) {
|
|
19
|
+
const row = rows[index];
|
|
20
|
+
if (typeof row !== "object" || row === null || !(name in row))
|
|
21
|
+
throw new Error(`Postgres returned no ${name} column`);
|
|
22
|
+
const value = Reflect.get(row, name);
|
|
23
|
+
return value;
|
|
24
|
+
}
|
|
25
|
+
function textColumn(rows, index, name) {
|
|
26
|
+
const value = column(rows, index, name);
|
|
27
|
+
if (typeof value !== "string")
|
|
28
|
+
throw new Error(`Postgres returned a non-text ${name} column`);
|
|
29
|
+
return value;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Opens one document's server log in Postgres: its checkpoint in `<table>_checkpoints` and the
|
|
33
|
+
* entries after it in `<table>_entries`, created when missing. Values are `json`, kept exactly as
|
|
34
|
+
* written. An append is one insert; a compaction replaces the checkpoint and deletes the entries
|
|
35
|
+
* in one step.
|
|
36
|
+
*
|
|
37
|
+
* Only one store of a document may be open, on any connection to the database; a second one throws
|
|
38
|
+
* `CheckpointLockedError`. Await `close()` before opening the store again elsewhere.
|
|
39
|
+
*
|
|
40
|
+
* With `client`, an advisory lock on that connection, held until `close()`, keeps others out. The
|
|
41
|
+
* caller owns the connection and should discard it if unlocking fails.
|
|
42
|
+
*
|
|
43
|
+
* With `pool`, the store holds a lease in `<table>_leases` and renews it while open. Every write
|
|
44
|
+
* checks the lease in the same statement, so once another store takes over an expired lease, this
|
|
45
|
+
* one's writes throw `CheckpointLockedError` instead of landing. `close()` releases the lease.
|
|
46
|
+
*/
|
|
47
|
+
export async function openPostgresServerStore(options) {
|
|
48
|
+
const { client, pool, document, table = "articollab" } = options;
|
|
49
|
+
if (client !== undefined && pool !== undefined)
|
|
50
|
+
throw new TypeError("Pass client or pool, not both");
|
|
51
|
+
const connection = client ?? pool;
|
|
52
|
+
if (typeof connection !== "object" || connection === null || typeof connection.query !== "function") {
|
|
53
|
+
throw new TypeError(`${pool === undefined ? "client" : "pool"} must have a query() method`);
|
|
54
|
+
}
|
|
55
|
+
if (typeof document !== "string" || document.length === 0)
|
|
56
|
+
throw new TypeError("document must be a nonempty string");
|
|
57
|
+
if (typeof table !== "string" || !TABLE.test(table)) {
|
|
58
|
+
throw new TypeError("table must be lowercase letters, digits and underscores, starting with a letter or underscore");
|
|
59
|
+
}
|
|
60
|
+
const leaseTtl = pool === undefined ? 0 : integerOption(options.leaseTtl ?? 30_000, "leaseTtl", 1);
|
|
61
|
+
if (pool === undefined && options.leaseTtl !== undefined)
|
|
62
|
+
throw new TypeError("leaseTtl needs a pool");
|
|
63
|
+
const checkpoints = `${table}_checkpoints`, entries = `${table}_entries`;
|
|
64
|
+
const documents = opened.get(connection) ?? new Map();
|
|
65
|
+
opened.set(connection, documents);
|
|
66
|
+
const name = `${table}\0${document}`;
|
|
67
|
+
// Reopening right after close() waits for its release instead of failing.
|
|
68
|
+
const previous = documents.get(name);
|
|
69
|
+
if (previous === true)
|
|
70
|
+
throw new CheckpointLockedError(`Server store is in use elsewhere: ${table} ${document}`);
|
|
71
|
+
await previous;
|
|
72
|
+
if (documents.has(name))
|
|
73
|
+
throw new CheckpointLockedError(`Server store is in use elsewhere: ${table} ${document}`);
|
|
74
|
+
documents.set(name, true);
|
|
75
|
+
let guard;
|
|
76
|
+
try {
|
|
77
|
+
const leaseTable = pool === undefined ? "" :
|
|
78
|
+
`CREATE TABLE IF NOT EXISTS ${table}_leases (document text PRIMARY KEY, epoch bigint NOT NULL,
|
|
79
|
+
owner text, expires_at timestamptz NOT NULL);`;
|
|
80
|
+
// Bootstrap once per transaction on one connection, even when query() uses a pool.
|
|
81
|
+
// The bigint lock key space is separate from the document guard's two integers.
|
|
82
|
+
await connection.query(`
|
|
83
|
+
DO $articollab$
|
|
84
|
+
BEGIN
|
|
85
|
+
PERFORM pg_catalog.pg_advisory_xact_lock(pg_catalog.hashtextextended('articollab:store-schema:${table}', 0));
|
|
86
|
+
CREATE TABLE IF NOT EXISTS ${checkpoints} (document text PRIMARY KEY, checkpoint json NOT NULL);
|
|
87
|
+
CREATE TABLE IF NOT EXISTS ${entries} (document text NOT NULL, position bigint NOT NULL,
|
|
88
|
+
entry json NOT NULL, PRIMARY KEY (document, position));
|
|
89
|
+
${leaseTable}
|
|
90
|
+
END;
|
|
91
|
+
$articollab$`);
|
|
92
|
+
guard = pool === undefined
|
|
93
|
+
? await lockedGuard(connection, table, document, checkpoints, entries)
|
|
94
|
+
: await leasedGuard(connection, table, document, checkpoints, entries, leaseTtl);
|
|
95
|
+
}
|
|
96
|
+
catch (error) {
|
|
97
|
+
documents.delete(name);
|
|
98
|
+
throw error;
|
|
99
|
+
}
|
|
100
|
+
/** The position of the next entry, once known. */
|
|
101
|
+
let next;
|
|
102
|
+
let closing;
|
|
103
|
+
let queue = Promise.resolve();
|
|
104
|
+
function serialized(work) {
|
|
105
|
+
if (closing !== undefined)
|
|
106
|
+
return Promise.reject(new Error("Checkpoint store is closed"));
|
|
107
|
+
const result = queue.then(work);
|
|
108
|
+
queue = result.catch(() => { });
|
|
109
|
+
return result;
|
|
110
|
+
}
|
|
111
|
+
async function position() {
|
|
112
|
+
if (next !== undefined)
|
|
113
|
+
return next;
|
|
114
|
+
const { rows } = await connection.query(`SELECT (SELECT count(*) FROM ${checkpoints} WHERE document = $1)::text AS saved, ` +
|
|
115
|
+
`(SELECT coalesce(max(position) + 1, 0) FROM ${entries} WHERE document = $1)::text AS next`, [document]);
|
|
116
|
+
if (textColumn(rows, 0, "saved") === "0")
|
|
117
|
+
throw new Error(`Server store has no checkpoint yet; compact first: ${table} ${document}`);
|
|
118
|
+
next = Number(textColumn(rows, 0, "next"));
|
|
119
|
+
return next;
|
|
120
|
+
}
|
|
121
|
+
return {
|
|
122
|
+
load: () => serialized(async () => {
|
|
123
|
+
const saved = await connection.query(`SELECT checkpoint::text AS checkpoint FROM ${checkpoints} WHERE document = $1`, [document]);
|
|
124
|
+
if (saved.rows.length === 0) {
|
|
125
|
+
next = undefined;
|
|
126
|
+
return undefined;
|
|
127
|
+
}
|
|
128
|
+
const checkpoint = JSON.parse(textColumn(saved.rows, 0, "checkpoint"));
|
|
129
|
+
const { rows } = await connection.query(`SELECT entry::text AS entry, (position + 1)::text AS next FROM ${entries} ` +
|
|
130
|
+
"WHERE document = $1 ORDER BY position", [document]);
|
|
131
|
+
next = rows.length === 0 ? 0 : Number(textColumn(rows, rows.length - 1, "next"));
|
|
132
|
+
return { checkpoint, entries: rows.map((_row, index) => JSON.parse(textColumn(rows, index, "entry"))) };
|
|
133
|
+
}),
|
|
134
|
+
append: (added) => serialized(async () => {
|
|
135
|
+
if (!Array.isArray(added))
|
|
136
|
+
throw new TypeError("entries must be an array");
|
|
137
|
+
if (added.length === 0)
|
|
138
|
+
return;
|
|
139
|
+
const start = await position();
|
|
140
|
+
await guard.append(start, added);
|
|
141
|
+
next = start + added.length;
|
|
142
|
+
}),
|
|
143
|
+
compact: (checkpoint) => serialized(async () => {
|
|
144
|
+
await guard.compact(checkpoint);
|
|
145
|
+
next = 0;
|
|
146
|
+
}),
|
|
147
|
+
close() {
|
|
148
|
+
if (closing !== undefined)
|
|
149
|
+
return closing;
|
|
150
|
+
closing = queue.then(async () => {
|
|
151
|
+
try {
|
|
152
|
+
await guard.release();
|
|
153
|
+
}
|
|
154
|
+
catch (error) {
|
|
155
|
+
// A failed query may leave the lock or lease held.
|
|
156
|
+
documents.set(name, true);
|
|
157
|
+
throw error;
|
|
158
|
+
}
|
|
159
|
+
documents.delete(name);
|
|
160
|
+
});
|
|
161
|
+
documents.set(name, closing);
|
|
162
|
+
return closing;
|
|
163
|
+
},
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
/** A dedicated connection's advisory lock; writes run in that session. */
|
|
167
|
+
async function lockedGuard(client, table, document, checkpoints, entries) {
|
|
168
|
+
const key = await lockKey(table, document);
|
|
169
|
+
const { rows } = await client.query("SELECT pg_try_advisory_lock($1, $2) AS locked", key);
|
|
170
|
+
if (column(rows, 0, "locked") !== true)
|
|
171
|
+
throw new CheckpointLockedError(`Server store is in use elsewhere: ${table} ${document}`);
|
|
172
|
+
return {
|
|
173
|
+
async append(start, added) {
|
|
174
|
+
await client.query(`INSERT INTO ${entries} (document, position, entry) ` +
|
|
175
|
+
"SELECT $1, $2::bigint + ordinality - 1, value FROM json_array_elements($3::json) WITH ORDINALITY AS t(value, ordinality)", [document, start, JSON.stringify(added)]);
|
|
176
|
+
},
|
|
177
|
+
async compact(checkpoint) {
|
|
178
|
+
await client.query("BEGIN");
|
|
179
|
+
try {
|
|
180
|
+
await client.query(`INSERT INTO ${checkpoints} (document, checkpoint) VALUES ($1, $2::json) ` +
|
|
181
|
+
"ON CONFLICT (document) DO UPDATE SET checkpoint = EXCLUDED.checkpoint", [document, JSON.stringify(checkpoint)]);
|
|
182
|
+
await client.query(`DELETE FROM ${entries} WHERE document = $1`, [document]);
|
|
183
|
+
await client.query("COMMIT");
|
|
184
|
+
}
|
|
185
|
+
catch (error) {
|
|
186
|
+
await client.query("ROLLBACK").catch(() => { });
|
|
187
|
+
throw error;
|
|
188
|
+
}
|
|
189
|
+
},
|
|
190
|
+
async release() {
|
|
191
|
+
const { rows: released } = await client.query("SELECT pg_advisory_unlock($1, $2) AS unlocked", key);
|
|
192
|
+
if (column(released, 0, "unlocked") !== true)
|
|
193
|
+
throw new Error(`Postgres did not release the server store lock: ${table} ${document}`);
|
|
194
|
+
},
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* A lease row with an epoch that grows with every new holder. Each write is one statement whose
|
|
199
|
+
* first step locks the lease row and checks this store still holds it, unexpired; a holder whose
|
|
200
|
+
* lease was taken over writes nothing.
|
|
201
|
+
*/
|
|
202
|
+
async function leasedGuard(pool, table, document, checkpoints, entries, ttl) {
|
|
203
|
+
const leases = `${table}_leases`;
|
|
204
|
+
const owner = crypto.randomUUID();
|
|
205
|
+
const duration = "$3::bigint * interval '1 millisecond'";
|
|
206
|
+
// Time comes from the database, so hosts with different clocks agree on when a lease expires.
|
|
207
|
+
const { rows } = await pool.query(`INSERT INTO ${leases} AS lease (document, epoch, owner, expires_at) ` +
|
|
208
|
+
`VALUES ($1, 1, $2, now() + ${duration}) ON CONFLICT (document) DO UPDATE ` +
|
|
209
|
+
"SET epoch = lease.epoch + 1, owner = EXCLUDED.owner, expires_at = EXCLUDED.expires_at " +
|
|
210
|
+
"WHERE lease.owner IS NULL OR lease.expires_at <= now() RETURNING epoch::text AS epoch", [document, owner, ttl]);
|
|
211
|
+
if (rows.length === 0)
|
|
212
|
+
throw new CheckpointLockedError(`Server store is in use elsewhere: ${table} ${document}`);
|
|
213
|
+
const epoch = textColumn(rows, 0, "epoch");
|
|
214
|
+
const lost = () => new CheckpointLockedError(`Server store lease was taken over: ${table} ${document}`);
|
|
215
|
+
const held = `held AS (SELECT 1 FROM ${leases} WHERE document = $1 AND owner = $2 AND epoch = $3::bigint ` +
|
|
216
|
+
"AND expires_at > now() FOR UPDATE)";
|
|
217
|
+
let renewing;
|
|
218
|
+
const renew = setInterval(() => {
|
|
219
|
+
renewing ??= pool.query(`UPDATE ${leases} SET expires_at = now() + $4::bigint * interval '1 millisecond' ` +
|
|
220
|
+
"WHERE document = $1 AND owner = $2 AND epoch = $3::bigint AND expires_at > now()", [document, owner, epoch, ttl])
|
|
221
|
+
// A failed renewal leaves the lease to expire; the next write then fails.
|
|
222
|
+
.catch(() => { })
|
|
223
|
+
.finally(() => { renewing = undefined; });
|
|
224
|
+
}, Math.max(1, Math.floor(ttl / 3)));
|
|
225
|
+
if (typeof renew === "object" && "unref" in renew)
|
|
226
|
+
renew.unref();
|
|
227
|
+
return {
|
|
228
|
+
async append(start, added) {
|
|
229
|
+
const { rows: inserted } = await pool.query(`WITH ${held} INSERT INTO ${entries} (document, position, entry) ` +
|
|
230
|
+
"SELECT $1, $4::bigint + ordinality - 1, value FROM json_array_elements($5::json) WITH ORDINALITY AS t(value, ordinality) " +
|
|
231
|
+
"WHERE EXISTS (SELECT 1 FROM held) RETURNING 1 AS inserted", [document, owner, epoch, start, JSON.stringify(added)]);
|
|
232
|
+
if (inserted.length !== added.length)
|
|
233
|
+
throw lost();
|
|
234
|
+
},
|
|
235
|
+
async compact(checkpoint) {
|
|
236
|
+
const { rows: saved } = await pool.query(`WITH ${held}, ` +
|
|
237
|
+
`saved AS (INSERT INTO ${checkpoints} (document, checkpoint) SELECT $1, $4::json WHERE EXISTS (SELECT 1 FROM held) ` +
|
|
238
|
+
"ON CONFLICT (document) DO UPDATE SET checkpoint = EXCLUDED.checkpoint RETURNING 1), " +
|
|
239
|
+
`removed AS (DELETE FROM ${entries} WHERE document = $1 AND EXISTS (SELECT 1 FROM saved)) ` +
|
|
240
|
+
"SELECT count(*)::text AS saved FROM saved", [document, owner, epoch, JSON.stringify(checkpoint)]);
|
|
241
|
+
if (textColumn(saved, 0, "saved") !== "1")
|
|
242
|
+
throw lost();
|
|
243
|
+
},
|
|
244
|
+
async release() {
|
|
245
|
+
clearInterval(renew);
|
|
246
|
+
await renewing;
|
|
247
|
+
// A lease already taken over stays with its new holder.
|
|
248
|
+
await pool.query(`UPDATE ${leases} SET owner = NULL, expires_at = now() WHERE document = $1 AND owner = $2 AND epoch = $3::bigint`, [document, owner, epoch]);
|
|
249
|
+
},
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
//# sourceMappingURL=postgres.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"postgres.js","sourceRoot":"","sources":["../src/postgres.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAGzD,OAAO,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAC;AAEnD,OAAO,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAC;AA2BnD,MAAM,KAAK,GAAG,yBAAyB,CAAC;AAExC;;;GAGG;AACH,MAAM,MAAM,GAAG,IAAI,OAAO,EAA6C,CAAC;AAExE;;;GAGG;AACH,KAAK,UAAU,OAAO,CAAC,KAAa,EAAE,QAAgB;IACpD,MAAM,MAAM,GAAG,IAAI,QAAQ,CAAC,MAAM,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,EAAE,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,eAAe,KAAK,KAAK,QAAQ,EAAE,CAAC,CAAC,CAAC,CAAC;IAClI,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC;AAClD,CAAC;AAED,SAAS,MAAM,CAAC,IAAwB,EAAE,KAAa,EAAE,IAAY;IACnE,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC;IACxB,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,GAAG,KAAK,IAAI,IAAI,CAAC,CAAC,IAAI,IAAI,GAAG,CAAC;QAAE,MAAM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AU,CAAC,KAAK,EAAE,CAAC,EAAE,OAAO,CAAC,KAAK,GAAG;gBAAE,MAAM,IAAI,EAAE,CAAC;QAC1D,CAAC;QACD,KAAK,CAAC,OAAO;YACX,aAAa,CAAC,KAAK,CAAC,CAAC;YACrB,MAAM,QAAQ,CAAC;YACf,wDAAwD;YACxD,MAAM,IAAI,CAAC,KAAK,CAAC,UAAU,MAAM,iGAAiG,EAChI,CAAC,QAAQ,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC;QAC9B,CAAC;KACF,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { JsonValue, PayloadSchema } from "@articollab/core";
|
|
2
|
+
export interface SyncPresenceOptions<P extends JsonValue = JsonValue> {
|
|
3
|
+
/** Validates this writer's state before it is sent, and peers' states as they arrive. */
|
|
4
|
+
readonly schema?: PayloadSchema<P>;
|
|
5
|
+
/** Milliseconds between re-sends of this writer's state, which keep it from expiring. Default 10000. */
|
|
6
|
+
readonly republishInterval?: number;
|
|
7
|
+
}
|
|
8
|
+
/** Ephemeral per-writer state, such as a name and a selection, shared with the other writers. */
|
|
9
|
+
export interface SyncPresence<P extends JsonValue = JsonValue> {
|
|
10
|
+
/** This writer's state; null when it shares none. */
|
|
11
|
+
readonly state: P | null;
|
|
12
|
+
/** The other writers' states by client ID, as the push channel last delivered them. */
|
|
13
|
+
readonly peers: ReadonlyMap<string, P>;
|
|
14
|
+
/**
|
|
15
|
+
* Shares `state`, or stops sharing with null. Sending is best-effort and retried by the re-sends.
|
|
16
|
+
* Once the client is closed or failed, a valid state is ignored.
|
|
17
|
+
*/
|
|
18
|
+
set(state: P | null): void;
|
|
19
|
+
/** Called whenever `peers` changes. Returns an unsubscribe function. */
|
|
20
|
+
on(event: "change", listener: (peers: ReadonlyMap<string, P>) => void): () => void;
|
|
21
|
+
}
|
|
22
|
+
/** The sync client's side of presence: what it shares, and what the push channel reports. */
|
|
23
|
+
export interface PresenceController<P extends JsonValue> {
|
|
24
|
+
readonly api: SyncPresence<P>;
|
|
25
|
+
/** A new push stream opened: the server will send every current state again. */
|
|
26
|
+
opened(): void;
|
|
27
|
+
/** One `{ clientId, state }` update from the push stream. */
|
|
28
|
+
received(update: unknown): void;
|
|
29
|
+
/** The push stream ended: nothing it reported is current any more. */
|
|
30
|
+
closed(): void;
|
|
31
|
+
/** Leaves, best-effort, and stops re-sending. */
|
|
32
|
+
close(): void;
|
|
33
|
+
}
|
|
34
|
+
export declare function createPresence<P extends JsonValue>(options: SyncPresenceOptions<P>, clientId: string, publish: (state: P | null) => Promise<void>): PresenceController<P>;
|
|
35
|
+
//# sourceMappingURL=presence.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"presence.d.ts","sourceRoot":"","sources":["../src/presence.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAGjE,MAAM,WAAW,mBAAmB,CAAC,CAAC,SAAS,SAAS,GAAG,SAAS;IAClE,yFAAyF;IACzF,QAAQ,CAAC,MAAM,CAAC,EAAE,aAAa,CAAC,CAAC,CAAC,CAAC;IACnC,wGAAwG;IACxG,QAAQ,CAAC,iBAAiB,CAAC,EAAE,MAAM,CAAC;CACrC;AAED,iGAAiG;AACjG,MAAM,WAAW,YAAY,CAAC,CAAC,SAAS,SAAS,GAAG,SAAS;IAC3D,qDAAqD;IACrD,QAAQ,CAAC,KAAK,EAAE,CAAC,GAAG,IAAI,CAAC;IACzB,uFAAuF;IACvF,QAAQ,CAAC,KAAK,EAAE,WAAW,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;IACvC;;;OAGG;IACH,GAAG,CAAC,KAAK,EAAE,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC;IAC3B,wEAAwE;IACxE,EAAE,CAAC,KAAK,EAAE,QAAQ,EAAE,QAAQ,EAAE,CAAC,KAAK,EAAE,WAAW,CAAC,MAAM,EAAE,CAAC,CAAC,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC;CACpF;AAED,6FAA6F;AAC7F,MAAM,WAAW,kBAAkB,CAAC,CAAC,SAAS,SAAS;IACrD,QAAQ,CAAC,GAAG,EAAE,YAAY,CAAC,CAAC,CAAC,CAAC;IAC9B,gFAAgF;IAChF,MAAM,IAAI,IAAI,CAAC;IACf,6DAA6D;IAC7D,QAAQ,CAAC,MAAM,EAAE,OAAO,GAAG,IAAI,CAAC;IAChC,sEAAsE;IACtE,MAAM,IAAI,IAAI,CAAC;IACf,iDAAiD;IACjD,KAAK,IAAI,IAAI,CAAC;CACf;AASD,wBAAgB,cAAc,CAAC,CAAC,SAAS,SAAS,EAChD,OAAO,EAAE,mBAAmB,CAAC,CAAC,CAAC,EAC/B,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,CAAC,KAAK,EAAE,CAAC,GAAG,IAAI,KAAK,OAAO,CAAC,IAAI,CAAC,GAC1C,kBAAkB,CAAC,CAAC,CAAC,CAqFvB"}
|
package/dist/presence.js
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { checkPayload, integerOption, validateJsonValue } from "@articollab/core/adapter";
|
|
2
|
+
/** Throws unless `state` is JSON that `schema` accepts. */
|
|
3
|
+
function checkState(schema, state) {
|
|
4
|
+
validateJsonValue(state, ["presence"]);
|
|
5
|
+
// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- validateJsonValue has just accepted it as JSON.
|
|
6
|
+
checkPayload(schema, state, ["presence"]);
|
|
7
|
+
}
|
|
8
|
+
export function createPresence(options, clientId, publish) {
|
|
9
|
+
const republishInterval = integerOption(options.republishInterval ?? 10_000, "presence.republishInterval", 1);
|
|
10
|
+
const { schema } = options;
|
|
11
|
+
let state = null;
|
|
12
|
+
let peers = new Map();
|
|
13
|
+
const listeners = new Set();
|
|
14
|
+
let queued;
|
|
15
|
+
let sending = false;
|
|
16
|
+
let timer;
|
|
17
|
+
let closed = false;
|
|
18
|
+
/** Sends the newest queued state; while a send is in flight only the newest is kept. */
|
|
19
|
+
function send(next) {
|
|
20
|
+
queued = { state: next };
|
|
21
|
+
if (sending)
|
|
22
|
+
return;
|
|
23
|
+
sending = true;
|
|
24
|
+
void (async () => {
|
|
25
|
+
while (queued !== undefined) {
|
|
26
|
+
const { state: current } = queued;
|
|
27
|
+
queued = undefined;
|
|
28
|
+
try {
|
|
29
|
+
await publish(current);
|
|
30
|
+
}
|
|
31
|
+
catch { /* Best-effort: the next re-send tries again. */ }
|
|
32
|
+
}
|
|
33
|
+
sending = false;
|
|
34
|
+
})();
|
|
35
|
+
}
|
|
36
|
+
function rearm() {
|
|
37
|
+
if (timer !== undefined)
|
|
38
|
+
clearInterval(timer);
|
|
39
|
+
timer = state === null || closed ? undefined : setInterval(() => { if (state !== null)
|
|
40
|
+
send(state); }, republishInterval);
|
|
41
|
+
}
|
|
42
|
+
function emit(next) {
|
|
43
|
+
peers = next;
|
|
44
|
+
for (const listener of [...listeners])
|
|
45
|
+
listener(peers);
|
|
46
|
+
}
|
|
47
|
+
return {
|
|
48
|
+
api: {
|
|
49
|
+
get state() { return state; },
|
|
50
|
+
get peers() { return peers; },
|
|
51
|
+
set(next) {
|
|
52
|
+
if (next !== null)
|
|
53
|
+
checkState(schema, next);
|
|
54
|
+
// A closed or failed client has left; editors may still report selections afterwards.
|
|
55
|
+
if (closed)
|
|
56
|
+
return;
|
|
57
|
+
state = next;
|
|
58
|
+
send(next);
|
|
59
|
+
rearm();
|
|
60
|
+
},
|
|
61
|
+
on(event, listener) {
|
|
62
|
+
if (event !== "change")
|
|
63
|
+
throw new Error(`Unknown event: ${String(event)}`);
|
|
64
|
+
listeners.add(listener);
|
|
65
|
+
return () => { listeners.delete(listener); };
|
|
66
|
+
},
|
|
67
|
+
},
|
|
68
|
+
opened() {
|
|
69
|
+
if (peers.size > 0)
|
|
70
|
+
emit(new Map());
|
|
71
|
+
// A restarted server forgot this writer; tell it again rather than wait for the next re-send.
|
|
72
|
+
if (state !== null && !closed)
|
|
73
|
+
send(state);
|
|
74
|
+
},
|
|
75
|
+
received(update) {
|
|
76
|
+
if (typeof update !== "object" || update === null || Array.isArray(update))
|
|
77
|
+
return;
|
|
78
|
+
const { clientId: peer, state: peerState } = update;
|
|
79
|
+
if (typeof peer !== "string" || peer === clientId)
|
|
80
|
+
return;
|
|
81
|
+
if (peerState === null) {
|
|
82
|
+
if (!peers.has(peer))
|
|
83
|
+
return;
|
|
84
|
+
const next = new Map(peers);
|
|
85
|
+
next.delete(peer);
|
|
86
|
+
emit(next);
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
// A peer on another version may send a state this writer's schema rejects: skip only that one.
|
|
90
|
+
try {
|
|
91
|
+
checkState(schema, peerState);
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Checked against this writer's schema above.
|
|
97
|
+
emit(new Map(peers).set(peer, peerState));
|
|
98
|
+
},
|
|
99
|
+
closed() {
|
|
100
|
+
if (peers.size > 0)
|
|
101
|
+
emit(new Map());
|
|
102
|
+
},
|
|
103
|
+
close() {
|
|
104
|
+
if (closed)
|
|
105
|
+
return;
|
|
106
|
+
closed = true;
|
|
107
|
+
if (timer !== undefined)
|
|
108
|
+
clearInterval(timer);
|
|
109
|
+
timer = undefined;
|
|
110
|
+
if (state !== null) {
|
|
111
|
+
state = null;
|
|
112
|
+
send(null);
|
|
113
|
+
}
|
|
114
|
+
listeners.clear();
|
|
115
|
+
},
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
//# sourceMappingURL=presence.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"presence.js","sourceRoot":"","sources":["../src/presence.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAqC1F,2DAA2D;AAC3D,SAAS,UAAU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AC,KAAK,CAAC,CAAC;YAC9C,KAAK,GAAG,SAAS,CAAC;YAClB,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;gBAAC,KAAK,GAAG,IAAI,CAAC;gBAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YAAC,CAAC;YACjD,SAAS,CAAC,KAAK,EAAE,CAAC;QACpB,CAAC;KACF,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { ServerStore } from "./server-store.ts";
|
|
2
|
+
import { type LockManagerLike } from "./store.ts";
|
|
3
|
+
export interface FileServerStoreOptions {
|
|
4
|
+
/** Defaults to `navigator.locks`; it excludes other stores in this process only. */
|
|
5
|
+
readonly locks?: LockManagerLike;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Opens a directory that holds one server: `checkpoint-<n>.json` and the entries after it, one JSON
|
|
9
|
+
* line each, in `log-<n>.jsonl`. Appends are flushed to disk before they resolve. A compaction
|
|
10
|
+
* writes `checkpoint-<n+1>.json` through a temporary file and a rename, starts a new log and then
|
|
11
|
+
* removes generation `n`, so an interrupted step leaves either the old or the new generation
|
|
12
|
+
* complete. A line cut short by a crash was never reported as saved and is dropped on load.
|
|
13
|
+
*
|
|
14
|
+
* Opening the same directory twice in one process throws `CheckpointLockedError`; separate
|
|
15
|
+
* processes are not coordinated, so give each process its own directory. Power-loss durability
|
|
16
|
+
* depends on the file system and is not promised.
|
|
17
|
+
*/
|
|
18
|
+
export declare function openFileServerStore(directory: string, options?: FileServerStoreOptions): Promise<ServerStore>;
|
|
19
|
+
//# sourceMappingURL=server-file-store.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server-file-store.d.ts","sourceRoot":"","sources":["../src/server-file-store.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AACrD,OAAO,EAAyB,KAAK,eAAe,EAAE,MAAM,YAAY,CAAC;AAEzE,MAAM,WAAW,sBAAsB;IACrC,oFAAoF;IACpF,QAAQ,CAAC,KAAK,CAAC,EAAE,eAAe,CAAC;CAClC;AAQD;;;;;;;;;;GAUG;AACH,wBAAsB,mBAAmB,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,GAAE,sBAA2B,GAAG,OAAO,CAAC,WAAW,CAAC,CAqGvH"}
|