@ultimat3/realtime 31.55.0 → 31.57.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/package.json +5 -5
- package/src/pg-publication.ts +150 -7
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ultimat3/realtime",
|
|
3
|
-
"version": "31.
|
|
3
|
+
"version": "31.57.0",
|
|
4
4
|
"description": "Three-tier realtime: channels, live queries, local-first sync — one protocol, one mutator shape",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ultimate",
|
|
@@ -55,10 +55,10 @@
|
|
|
55
55
|
"test": "bun test"
|
|
56
56
|
},
|
|
57
57
|
"dependencies": {
|
|
58
|
-
"@ultimat3/core": "31.
|
|
59
|
-
"@ultimat3/entity": "31.
|
|
60
|
-
"@ultimat3/policy": "31.
|
|
61
|
-
"@ultimat3/query": "31.
|
|
58
|
+
"@ultimat3/core": "31.57.0",
|
|
59
|
+
"@ultimat3/entity": "31.57.0",
|
|
60
|
+
"@ultimat3/policy": "31.57.0",
|
|
61
|
+
"@ultimat3/query": "31.57.0",
|
|
62
62
|
"nats": "2.29.3"
|
|
63
63
|
}
|
|
64
64
|
}
|
package/src/pg-publication.ts
CHANGED
|
@@ -20,8 +20,15 @@ export interface PublicationOutcome {
|
|
|
20
20
|
* `FOR TABLE`, because a table's OWNER may publish it without a superuser — and the app role that
|
|
21
21
|
* ran the migrations owns every entity table. Membership is read through `pg_publication_tables`,
|
|
22
22
|
* which also expands `FOR ALL TABLES` and `FOR TABLES IN SCHEMA`, so an operator's broader
|
|
23
|
-
* publication is recognised as complete rather than ALTERed into an error.
|
|
24
|
-
*
|
|
23
|
+
* publication is recognised as complete rather than ALTERed into an error. Under the default
|
|
24
|
+
* `publish_via_partition_root = false` that view lists a partitioned table's partitions, never the
|
|
25
|
+
* table, so a table also counts when the publication names it or a partitioned table above it
|
|
26
|
+
* (`pg_publication_rel`, which holds a partitioned one with no partition yet), or covers it by
|
|
27
|
+
* scope, `FOR ALL TABLES` or its schema, and Postgres can publish it (`pg_relation_is_publishable`:
|
|
28
|
+
* never an UNLOGGED one). Never by its partitions: those listed today say nothing of the next one.
|
|
29
|
+
* Read through the view alone, a published partitioned entity was ALTERed into 42710 on every
|
|
30
|
+
* boot. Cast through `regclass` so a table on the search path compares by the bare name the
|
|
31
|
+
* entity list uses.
|
|
25
32
|
*
|
|
26
33
|
* Never `DROP TABLE` from it: a table the operator added is theirs. A statement the role may not
|
|
27
34
|
* run is refused with the exact statement to run as a role that may — the refusal preflight always
|
|
@@ -34,28 +41,164 @@ export async function ensurePublication(
|
|
|
34
41
|
): Promise<PublicationOutcome> {
|
|
35
42
|
assertIdentifier('publication', publication);
|
|
36
43
|
const tables = [...entities].map((name) => assertIdentifier('entity', name)).sort();
|
|
44
|
+
// The server's version rides on the existence check: a schema scope is read only where one exists.
|
|
37
45
|
const exists = await connection.query(
|
|
38
|
-
`SELECT
|
|
46
|
+
`SELECT current_setting('server_version_num'), pubviaroot FROM pg_publication WHERE pubname = '${publication}'`,
|
|
39
47
|
);
|
|
40
48
|
if (exists.length === 0) {
|
|
49
|
+
const unloggedNew = await connection.query(unloggedBelowSql(tables));
|
|
50
|
+
if (unloggedNew.length > 0) throw unpublishablePartitions(unloggedNew);
|
|
41
51
|
const create = `CREATE PUBLICATION ${publication} FOR TABLE ${tables.join(', ')}`;
|
|
42
52
|
await attempt(connection, create, `no publication named "${publication}" exists`);
|
|
43
53
|
logger.info('realtime.publication.created', { publication, tables });
|
|
44
54
|
return { created: true, added: tables };
|
|
45
55
|
}
|
|
46
|
-
const
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
56
|
+
const schemas = Number(exists[0]?.[0]) >= SCHEMA_PUBLICATIONS_FROM;
|
|
57
|
+
const viaRoot = exists[0]?.[1] === 't';
|
|
58
|
+
const members = await connection.query(membersSql(publication, schemas, tables));
|
|
59
|
+
// 'u' rows are not members: an entity with an UNLOGGED partition, whose rows that partition's
|
|
60
|
+
// writes would never stream, whatever the publication carries.
|
|
61
|
+
const unlogged = members.filter((row) => row[1] === 'u' || row[1] === 'x');
|
|
62
|
+
if (unlogged.length > 0) throw unpublishablePartitions(unlogged);
|
|
63
|
+
// Under `publish_via_partition_root` a partition below a covered table reaches the stream under
|
|
64
|
+
// that ancestor's name, never its own: no ALTER changes that, so such an entity is refused.
|
|
65
|
+
const remapped = new Set(members.filter((row) => row[1] === 't').map((row) => row[0]));
|
|
66
|
+
const under = tables.filter((name) => remapped.has(name));
|
|
67
|
+
if (under.length > 0) throw remappedToAncestor(publication, under);
|
|
50
68
|
const present = new Set(members.map((row) => row[0]));
|
|
51
69
|
const missing = tables.filter((name) => !present.has(name));
|
|
52
70
|
if (missing.length === 0) return { created: false, added: [] };
|
|
71
|
+
// The same question of what the ALTER would add: a parent added over an entity partition renames
|
|
72
|
+
// it in the stream, and the next boot would refuse what this one let through.
|
|
73
|
+
if (viaRoot) {
|
|
74
|
+
const below = await connection.query(descendantsSql(missing));
|
|
75
|
+
const renamed = new Set(below.map((row) => row[0]));
|
|
76
|
+
const shadowed = tables.filter((name) => renamed.has(name));
|
|
77
|
+
if (shadowed.length > 0) throw remappedToAncestor(publication, shadowed);
|
|
78
|
+
}
|
|
53
79
|
const alter = `ALTER PUBLICATION ${publication} ADD TABLE ${missing.join(', ')}`;
|
|
54
80
|
await attempt(connection, alter, `publication "${publication}" lacks ${missing.join(', ')}`);
|
|
55
81
|
logger.info('realtime.publication.extended', { publication, tables: missing });
|
|
56
82
|
return { created: false, added: missing };
|
|
57
83
|
}
|
|
58
84
|
|
|
85
|
+
/** `FOR TABLES IN SCHEMA`, and its catalog `pg_publication_namespace`, arrived in Postgres 15. */
|
|
86
|
+
const SCHEMA_PUBLICATIONS_FROM = 150000;
|
|
87
|
+
|
|
88
|
+
/** A relation of `c` that a publication can carry: a table or partitioned table Postgres publishes. */
|
|
89
|
+
const PUBLISHABLE = "c.relkind IN ('r', 'p') AND pg_relation_is_publishable(c.oid)";
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Every table `publication` carries, by `regclass` text: what `pg_publication_tables` lists, and
|
|
93
|
+
* every table in the partition tree of one it covers — by name, `FOR ALL TABLES`, or a schema it
|
|
94
|
+
* names (`schemas`, on a server that has them). Only what Postgres can publish: the view lists an
|
|
95
|
+
* UNLOGGED partition of a named table, whose writes reach no WAL, so it is filtered like the rest.
|
|
96
|
+
* Each row's second column is 't' when the stream carries that table under an ancestor's name
|
|
97
|
+
* instead (`publish_via_partition_root`).
|
|
98
|
+
*/
|
|
99
|
+
const membersSql = (publication: string, schemas: boolean, entities: readonly string[]): string =>
|
|
100
|
+
`WITH pub AS (SELECT oid, puballtables, pubviaroot FROM pg_publication WHERE pubname = '${publication}'), ` +
|
|
101
|
+
'covered AS (SELECT rel.prrelid AS oid FROM pg_publication_rel rel JOIN pub ON pub.oid = rel.prpubid ' +
|
|
102
|
+
"UNION SELECT c.oid FROM pg_class c, pub WHERE pub.puballtables AND c.relkind IN ('r', 'p')" +
|
|
103
|
+
(schemas
|
|
104
|
+
? ' UNION SELECT c.oid FROM pg_class c ' +
|
|
105
|
+
'JOIN pg_publication_namespace ns ON ns.pnnspid = c.relnamespace ' +
|
|
106
|
+
"JOIN pub ON pub.oid = ns.pnpubid WHERE c.relkind IN ('r', 'p')"
|
|
107
|
+
: '') +
|
|
108
|
+
') ' +
|
|
109
|
+
// Joined by name, never cast through `regclass` input: that needs USAGE on the schema, and a
|
|
110
|
+
// published table in one the role cannot use would abort the read of every other.
|
|
111
|
+
"SELECT c.oid::regclass::text, 'f' FROM pg_publication_tables listed " +
|
|
112
|
+
'JOIN pg_namespace n ON n.nspname = listed.schemaname ' +
|
|
113
|
+
'JOIN pg_class c ON c.relnamespace = n.oid AND c.relname = listed.tablename ' +
|
|
114
|
+
`WHERE listed.pubname = '${publication}' AND ${PUBLISHABLE} ` +
|
|
115
|
+
`UNION SELECT c.oid::regclass::text, 'f' FROM covered JOIN pg_class c ON c.oid = covered.oid WHERE ${PUBLISHABLE} ` +
|
|
116
|
+
// A partition below a covered table: 't' when the publication sends it under that ancestor.
|
|
117
|
+
"UNION SELECT c.oid::regclass::text, CASE WHEN pub.pubviaroot AND tree.level > 0 THEN 't' ELSE 'f' END " +
|
|
118
|
+
'FROM pub, covered, pg_partition_tree(covered.oid) tree ' +
|
|
119
|
+
`JOIN pg_class c ON c.oid = tree.relid WHERE ${PUBLISHABLE} ` +
|
|
120
|
+
`UNION ${unloggedBelowSql(entities)}`;
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Each partition below an entity that Postgres cannot publish, as `[partition, kind]`: 'u' for an
|
|
124
|
+
* UNLOGGED one, 'x' for a foreign table. The entity itself is publishable, but a row routed to such
|
|
125
|
+
* a partition reaches no WAL, so its changes never stream.
|
|
126
|
+
*/
|
|
127
|
+
const unloggedBelowSql = (entities: readonly string[]): string =>
|
|
128
|
+
"SELECT tree.relid::regclass::text, CASE WHEN part.relkind = 'f' THEN 'x' ELSE 'u' END FROM unnest(ARRAY[" +
|
|
129
|
+
entities.map((name) => `'${name}'`).join(', ') +
|
|
130
|
+
// `to_regclass`, not a cast: an entity whose table is not migrated yet reaches the CREATE or
|
|
131
|
+
// ALTER below, whose failure `attempt` explains, instead of dying here as a raw cast error.
|
|
132
|
+
']::text[]) added, pg_partition_tree(to_regclass(added)) tree ' +
|
|
133
|
+
'JOIN pg_class part ON part.oid = tree.relid ' +
|
|
134
|
+
'WHERE tree.level > 0 AND NOT pg_relation_is_publishable(tree.relid)';
|
|
135
|
+
|
|
136
|
+
/** Every partition below `tables` (validated identifiers), by `regclass` text. */
|
|
137
|
+
const descendantsSql = (tables: readonly string[]): string =>
|
|
138
|
+
'SELECT tree.relid::regclass::text FROM unnest(ARRAY[' +
|
|
139
|
+
tables.map((name) => `'${name}'`).join(', ') +
|
|
140
|
+
']::text[]) added, pg_partition_tree(to_regclass(added)) tree WHERE tree.level > 0';
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* A name placed in prose or in a `--` comment: a control character (a line break ends the comment,
|
|
144
|
+
* so the rest of the name would run as SQL) or a line separator is shown as `\uXXXX`, and a literal
|
|
145
|
+
* backslash as `\\`, so a name spelled `\u000a` never reads as one holding a line break. A name in
|
|
146
|
+
* a statement is not this: it is the `regclass` text, which Postgres itself quotes.
|
|
147
|
+
*/
|
|
148
|
+
const visible = (name: string): string =>
|
|
149
|
+
Array.from(name, (char) => {
|
|
150
|
+
const code = char.charCodeAt(0);
|
|
151
|
+
const control =
|
|
152
|
+
code < 0x20 || (code >= 0x7f && code <= 0x9f) || code === 0x2028 || code === 0x2029;
|
|
153
|
+
if (control) return `\\u${code.toString(16).padStart(4, '0')}`;
|
|
154
|
+
return char === '\\' ? '\\\\' : char;
|
|
155
|
+
}).join('');
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* A partitioned entity with a partition that reaches no WAL: no publication change fixes it. An
|
|
159
|
+
* UNLOGGED one can be made logged; a foreign table cannot (`SET LOGGED` is refused for it), so it
|
|
160
|
+
* is replaced in a reviewed migration.
|
|
161
|
+
*/
|
|
162
|
+
const unpublishablePartitions = (
|
|
163
|
+
rows: readonly (readonly (string | null)[])[],
|
|
164
|
+
): ReplicationFailedError => {
|
|
165
|
+
const unlogged = rows.filter((row) => row[1] === 'u').map((row) => row[0] ?? '');
|
|
166
|
+
const foreign = rows.filter((row) => row[1] === 'x').map((row) => row[0] ?? '');
|
|
167
|
+
const parts = [
|
|
168
|
+
...(unlogged.length > 0 ? [`UNLOGGED partitions (${unlogged.map(visible).join(', ')})`] : []),
|
|
169
|
+
...(foreign.length > 0
|
|
170
|
+
? [`foreign-table partitions (${foreign.map(visible).join(', ')})`]
|
|
171
|
+
: []),
|
|
172
|
+
];
|
|
173
|
+
// An UNLOGGED partition is made logged in place. A foreign table cannot be, and dropping it
|
|
174
|
+
// first would leave its range with no partition, so no statement is emitted for it: the
|
|
175
|
+
// replacement is a reviewed migration.
|
|
176
|
+
const fixes = unlogged.map((name) => `ALTER TABLE ${name} SET LOGGED;`);
|
|
177
|
+
const replace =
|
|
178
|
+
foreign.length > 0
|
|
179
|
+
? `replace ${foreign.map(visible).join(', ')} with a regular partition of the same bounds in a reviewed migration (a bare DROP leaves its range with no partition), then `
|
|
180
|
+
: '';
|
|
181
|
+
return new ReplicationFailedError({
|
|
182
|
+
stage: 'preflight',
|
|
183
|
+
detail: `an entity table has ${parts.join(' and ')}: their writes reach no WAL, so no change to them ever streams`,
|
|
184
|
+
fix: `${fixes.join(' ')} -- ${replace}as its owner, restart the replicator`.trimStart(),
|
|
185
|
+
});
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Entities a `publish_via_partition_root` publication sends under an ancestor's name: the
|
|
190
|
+
* replicator would wait for changes to a table that never appears in the stream.
|
|
191
|
+
*/
|
|
192
|
+
const remappedToAncestor = (
|
|
193
|
+
publication: string,
|
|
194
|
+
tables: readonly string[],
|
|
195
|
+
): ReplicationFailedError =>
|
|
196
|
+
new ReplicationFailedError({
|
|
197
|
+
stage: 'preflight',
|
|
198
|
+
detail: `publication "${publication}" publishes via the partition root, so ${tables.join(', ')} reach the stream under an ancestor's name, never their own`,
|
|
199
|
+
fix: `ALTER PUBLICATION ${publication} SET (publish_via_partition_root = false); -- as its owner, then restart the replicator`,
|
|
200
|
+
});
|
|
201
|
+
|
|
59
202
|
/**
|
|
60
203
|
* Runs `statement`, or refuses with it. Only a server's ErrorResponse is this function's to
|
|
61
204
|
* explain — a dead socket is not a privilege question, so anything else propagates unchanged.
|