@protobase/server 0.129.1 → 0.130.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/dist/assistant/query-runner/grants-sql.js +32 -0
- package/dist/assistant/query-runner/query-input.js +33 -0
- package/dist/assistant/query-runner/query-module.js +44 -0
- package/dist/assistant/query-runner/query-runner.d.ts +8 -11
- package/dist/assistant/query-runner/query-runner.js +15 -57
- package/dist/assistant/query-runner/read-query.js +54 -0
- package/dist/assistant/query-runner/runner-sql.js +4 -20
- package/dist/assistant/query-runner/steps/001-role.js +19 -0
- package/dist/auth-store.d.ts +2 -2
- package/dist/auth-store.js +3 -3
- package/dist/better-auth/auth-schema.d.ts +13 -4
- package/dist/better-auth/auth-schema.js +40 -32
- package/dist/better-auth/auth-settings.d.ts +59 -11
- package/dist/better-auth/auth-settings.js +57 -13
- package/dist/better-auth/auth-tables.d.ts +6 -3
- package/dist/better-auth/auth-tables.js +12 -7
- package/dist/better-auth/authenticator.js +10 -2
- package/dist/better-auth/create-auth.d.ts +62 -7
- package/dist/better-auth/create-auth.js +55 -14
- package/dist/better-auth/device-sign-in-check.js +13 -0
- package/dist/better-auth/names/declaration.d.ts +18 -5
- package/dist/better-auth/names/declaration.js +3 -1
- package/dist/better-auth/names/modules/auth.js +9 -0
- package/dist/better-auth/names/modules/index.d.ts +34 -4
- package/dist/better-auth/names/modules/organizations.js +10 -3
- package/dist/better-auth/names/modules/personal-access-tokens.js +6 -3
- package/dist/better-auth/names/modules-on.js +25 -2
- package/dist/better-auth/names/resolve-names.d.ts +9 -1
- package/dist/better-auth/names/resolve-names.js +15 -9
- package/dist/better-auth/organizations/accept-invitation.js +5 -4
- package/dist/better-auth/organizations/add-every-user.js +3 -2
- package/dist/better-auth/organizations/host-scope.d.ts +10 -0
- package/dist/better-auth/organizations/host-scope.js +15 -0
- package/dist/better-auth/organizations/host.d.ts +12 -6
- package/dist/better-auth/organizations/host.js +99 -61
- package/dist/better-auth/organizations/kept-organizations.d.ts +21 -0
- package/dist/better-auth/organizations/kept-organizations.js +62 -0
- package/dist/better-auth/organizations/member-endpoints.js +4 -3
- package/dist/better-auth/organizations/options.d.ts +15 -0
- package/dist/better-auth/organizations/options.js +19 -1
- package/dist/better-auth/organizations/people-endpoint.js +3 -2
- package/dist/better-auth/organizations/pinned-membership.js +81 -0
- package/dist/better-auth/organizations/pinned-sessions.js +46 -0
- package/dist/better-auth/organizations/session-organization.js +3 -2
- package/dist/better-auth/organizations/store.d.ts +1 -1
- package/dist/better-auth/organizations/store.js +14 -9
- package/dist/better-auth/personal-access-tokens/pinned-tokens.js +23 -0
- package/dist/better-auth/personal-access-tokens/token-plugin.js +75 -54
- package/dist/better-auth/personal-access-tokens/token-sessions.js +6 -3
- package/dist/better-auth/personal-access-tokens/token-store.js +15 -11
- package/dist/better-auth/store/adoption.js +25 -10
- package/dist/better-auth/store/drift.js +5 -4
- package/dist/better-auth/store/legacy-record.d.ts +10 -0
- package/dist/better-auth/store/legacy-record.js +56 -0
- package/dist/better-auth/store/migration-sql.js +31 -26
- package/dist/better-auth/store/offline/archive-revival.d.ts +11 -0
- package/dist/better-auth/store/offline/archive-revival.js +25 -0
- package/dist/better-auth/store/offline/baseline-store.d.ts +11 -7
- package/dist/better-auth/store/offline/baseline-store.js +15 -12
- package/dist/better-auth/store/offline/contract-gate.d.ts +18 -0
- package/dist/better-auth/store/offline/contract-gate.js +35 -0
- package/dist/better-auth/store/offline/module-archive.d.ts +41 -0
- package/dist/better-auth/store/offline/module-archive.js +95 -0
- package/dist/better-auth/store/offline/module-delete.d.ts +22 -0
- package/dist/better-auth/store/offline/module-delete.js +99 -0
- package/dist/better-auth/store/offline/module-switches.d.ts +32 -0
- package/dist/better-auth/store/offline/module-switches.js +113 -0
- package/dist/better-auth/store/offline/name-changes.d.ts +4 -1
- package/dist/better-auth/store/offline/name-changes.js +5 -2
- package/dist/better-auth/store/offline/offline-steps.d.ts +21 -7
- package/dist/better-auth/store/offline/offline-steps.js +29 -20
- package/dist/better-auth/store/offline/retired-watch.d.ts +5 -0
- package/dist/better-auth/store/offline/retired-watch.js +43 -0
- package/dist/better-auth/store/offline/settings-names.d.ts +3 -2
- package/dist/better-auth/store/offline/settings-names.js +10 -3
- package/dist/better-auth/store/offline/store-model.d.ts +27 -1
- package/dist/better-auth/store/offline/store-model.js +22 -5
- package/dist/better-auth/store/resources-outside.js +1 -1
- package/dist/better-auth/store/step-record.d.ts +13 -0
- package/dist/better-auth/store/step-record.js +59 -0
- package/dist/better-auth/store/steps/index.js +6 -1
- package/dist/better-auth/store/steps/legacy-versions.d.ts +7 -0
- package/dist/better-auth/store/steps/legacy-versions.js +4 -0
- package/dist/better-auth/store/steps/organizations/003-default-organization.js +113 -0
- package/dist/better-auth/store/steps/render.d.ts +3 -0
- package/dist/better-auth/store/steps/render.js +48 -25
- package/dist/better-auth/store/steps/step-lint.d.ts +14 -0
- package/dist/better-auth/store/steps/step-lint.js +31 -10
- package/dist/better-auth/store/steps/step.d.ts +18 -0
- package/dist/better-auth/store/steps/step.js +7 -1
- package/dist/better-auth/store/store-db.d.ts +6 -0
- package/dist/better-auth/store/store-db.js +11 -5
- package/dist/better-auth/store/store-names.d.ts +4 -0
- package/dist/better-auth/store/store-sql.d.ts +1 -1
- package/dist/better-auth/token-standing.js +12 -7
- package/dist/better-auth/users.d.ts +7 -2
- package/dist/better-auth/users.js +25 -3
- package/dist/built-in-resources.js +1 -1
- package/dist/calls/calls-module.js +42 -0
- package/dist/calls/calls-sql.js +4 -30
- package/dist/changes/capture-names.d.ts +3 -1
- package/dist/changes/capture-names.js +5 -2
- package/dist/changes/capture-schema-sql.d.ts +10 -0
- package/dist/changes/capture-schema-sql.js +21 -0
- package/dist/changes/capture-schema.d.ts +0 -18
- package/dist/changes/capture-schema.js +1 -74
- package/dist/changes/capture-sql.js +30 -24
- package/dist/changes/changes-input.js +36 -0
- package/dist/changes/changes-module.js +44 -0
- package/dist/changes/read-capture.js +67 -0
- package/dist/changes/steps/001-outbox.js +23 -0
- package/dist/channels/sends-module.js +37 -0
- package/dist/channels/sends-schema-sql.js +5 -5
- package/dist/comments/comments-module.js +30 -0
- package/dist/comments/comments-sql.js +1 -22
- package/dist/computed/buckets-sql.d.ts +5 -1
- package/dist/computed/buckets-sql.js +39 -46
- package/dist/computed/{buckets-schema.d.ts → buckets-targets.d.ts} +2 -3
- package/dist/computed/buckets-targets.js +50 -0
- package/dist/computed/computed-input.js +65 -0
- package/dist/computed/computed-module.js +102 -0
- package/dist/computed/formula-sql.js +14 -1
- package/dist/computed/read-computed.js +100 -0
- package/dist/computed/rollup-sql.js +13 -10
- package/dist/config-exports.d.ts +2 -2
- package/dist/create-admin.js +21 -5
- package/dist/derived/derived-module.js +89 -0
- package/dist/derived/derived-sql.js +1 -47
- package/dist/functions/define-function.d.ts +10 -4
- package/dist/functions/routes.js +5 -3
- package/dist/functions/supabase-routes.js +7 -5
- package/dist/history/history-module.js +34 -0
- package/dist/index.d.ts +19 -28
- package/dist/index.js +11 -21
- package/dist/internal.d.ts +30 -10
- package/dist/internal.js +26 -8
- package/dist/jobs/functions-sql.js +7 -11
- package/dist/jobs/job-data.js +36 -0
- package/dist/jobs/job-types.d.ts +6 -3
- package/dist/jobs/jobs-module.d.ts +5 -0
- package/dist/jobs/jobs-module.js +84 -0
- package/dist/jobs/run-job.d.ts +1 -1
- package/dist/jobs/run-job.js +7 -5
- package/dist/jobs/runtime.d.ts +9 -4
- package/dist/jobs/runtime.js +11 -6
- package/dist/jobs/schema.d.ts +0 -11
- package/dist/jobs/schema.js +1 -59
- package/dist/jobs/steps/001-pg-boss-45.js +483 -0
- package/dist/live/notices-module.js +30 -0
- package/dist/live/notices-sql.js +2 -1
- package/dist/mail/feedback/feedback-schema.js +3 -30
- package/dist/mail/feedback/mail-feedback-module.js +37 -0
- package/dist/mail/unsubscribe/unsubscribe-schema.js +3 -21
- package/dist/mail/unsubscribe/unsubscribes-module.js +31 -0
- package/dist/migration-record/check-record.d.ts +9 -7
- package/dist/migration-record/check-record.js +12 -11
- package/dist/migration-record/module-needs.js +30 -0
- package/dist/migration-record/read-record.js +27 -15
- package/dist/migration-record/record-model.d.ts +7 -2
- package/dist/migration-record/record-model.js +14 -6
- package/dist/migration-record/startup-decision.js +18 -7
- package/dist/migration-sql/additive-statements.d.ts +4 -0
- package/dist/migration-sql/additive-statements.js +105 -0
- package/dist/notifications/devices-module.js +61 -0
- package/dist/notifications/history-module.js +50 -0
- package/dist/notifications/notifications-targets.js +23 -0
- package/dist/notifications/read-table.js +16 -0
- package/dist/notifications/schema-sql.js +1 -22
- package/dist/notifications/schema.js +1 -101
- package/dist/notifications/table-names.js +40 -0
- package/dist/organization-scope/app-scope.js +38 -0
- package/dist/organization-scope/auth-request-organization.js +71 -0
- package/dist/organization-scope/organization-tables.js +20 -0
- package/dist/organization-scope/sign-in-organization.js +21 -0
- package/dist/package.js +1 -1
- package/dist/personal-mail/shared-sender-store.js +4 -2
- package/dist/realtime/relay/realtime-relay-module.js +37 -0
- package/dist/relation-found.js +6 -0
- package/dist/relay/read-relay.js +85 -0
- package/dist/relay/realtime-members-sql.js +51 -28
- package/dist/relay/relay-module.js +53 -0
- package/dist/relay/relay-targets.js +28 -0
- package/dist/relay/session-end.js +1 -3
- package/dist/relay/sessions-sql.js +4 -27
- package/dist/rest/table-routes.js +9 -2
- package/dist/schema-modules/feature-schemas-sql.d.ts +40 -0
- package/dist/schema-modules/feature-schemas-sql.js +51 -0
- package/dist/schema-modules/module-difference.d.ts +31 -0
- package/dist/schema-modules/module-difference.js +98 -0
- package/dist/schema-modules/modules-sql.js +13 -0
- package/dist/schema-modules/modules.d.ts +37 -0
- package/dist/schema-modules/modules.js +56 -0
- package/dist/schema-modules/needed-modules.d.ts +41 -0
- package/dist/schema-modules/needed-modules.js +61 -0
- package/dist/schema-modules/resource-difference.js +83 -0
- package/dist/schema-modules/schema-module.d.ts +112 -0
- package/dist/schema-modules/schema-module.js +8 -0
- package/dist/status/status-module.js +63 -0
- package/dist/status/status-targets.js +21 -0
- package/dist/types.d.ts +6 -1
- package/dist/user-tables/reloading-admin.d.ts +1 -0
- package/dist/user-tables/reloading-admin.js +1 -0
- package/dist/user-tables/schema-sql.js +1 -14
- package/dist/user-tables/schema.js +4 -27
- package/dist/user-tables/user-tables-module.js +38 -0
- package/dist/webhooks/table/delivery-log-module.js +36 -0
- package/dist/webhooks/table/owner-roles.js +3 -2
- package/dist/webhooks/table/schema-sql.js +27 -26
- package/dist/webhooks/table/webhooks-schema-module.js +63 -0
- package/dist/webhooks/table/webhooks-targets.js +26 -0
- package/dist/webhooks/webhooks.js +1 -1
- package/dist/workflows/custom-steps/custom-steps-module.js +51 -0
- package/dist/workflows/custom-steps/custom-steps-sql.js +10 -7
- package/dist/workflows/custom-steps/runners-sql.js +10 -7
- package/dist/workflows/read-catalogue.js +23 -0
- package/dist/workflows/schema-sql.js +12 -9
- package/dist/workflows/status-sql.js +12 -6
- package/dist/workflows/storage/storage-module.js +39 -0
- package/dist/workflows/storage/storage-sql.js +8 -5
- package/dist/workflows/workflows-schema-module.js +49 -0
- package/dist/workflows/workflows-tables-sql.js +32 -0
- package/dist/workflows/workflows-targets.js +16 -0
- package/package.json +6 -6
- package/dist/assistant/query-runner/runner-plan.js +0 -30
- package/dist/better-auth/store/migrations-table.js +0 -27
- package/dist/better-auth/store/modules-off.js +0 -17
- package/dist/calls/calls-sql.d.ts +0 -11
- package/dist/changes/capture-plan.js +0 -79
- package/dist/channels/sends-schema.d.ts +0 -7
- package/dist/channels/sends-schema.js +0 -18
- package/dist/comments/comments-sql.d.ts +0 -14
- package/dist/computed/buckets-plan.d.ts +0 -2
- package/dist/computed/buckets-plan.js +0 -88
- package/dist/computed/buckets-schema.js +0 -39
- package/dist/computed/computed-plan.js +0 -81
- package/dist/computed/computed-schema.d.ts +0 -16
- package/dist/computed/computed-schema.js +0 -63
- package/dist/derived/derived-sql.d.ts +0 -12
- package/dist/mail/feedback/feedback-schema.d.ts +0 -7
- package/dist/mail/unsubscribe/unsubscribe-schema.d.ts +0 -10
- package/dist/notifications/schema.d.ts +0 -14
- package/dist/realtime/relay/relay-schema.d.ts +0 -7
- package/dist/realtime/relay/relay-schema.js +0 -20
- package/dist/relay/realtime-members-schema.js +0 -67
- package/dist/relay/relay-schema.d.ts +0 -14
- package/dist/relay/relay-schema.js +0 -28
- package/dist/status/schema.d.ts +0 -12
- package/dist/status/schema.js +0 -33
- package/dist/user-tables/schema.d.ts +0 -11
- package/dist/webhooks/table/schema.d.ts +0 -16
- package/dist/webhooks/table/schema.js +0 -56
- package/dist/workflows/schema.d.ts +0 -13
- package/dist/workflows/schema.js +0 -88
|
@@ -1,105 +1,5 @@
|
|
|
1
|
-
import { migrationCommand } from "../changes/capture-schema.js";
|
|
2
|
-
import { historyNames, notificationsNames } from "./options.js";
|
|
3
|
-
import { deviceKindChecksSql, deviceSessionColumnSql, devicesTableSql, qualified } from "./schema-sql.js";
|
|
4
|
-
import { historyTableSql } from "./history-sql.js";
|
|
5
|
-
import { legacyKindChecks } from "./legacy-kind-checks.js";
|
|
6
1
|
import { sql } from "kysely";
|
|
7
2
|
//#region src/notifications/schema.ts
|
|
8
|
-
/** Auth's users table, as the store names it: devices point at it. */
|
|
9
|
-
const authUsersTable = (auth) => ({
|
|
10
|
-
schema: auth.names.schema,
|
|
11
|
-
table: auth.names.table("user").name
|
|
12
|
-
});
|
|
13
3
|
const regclass = async (db, name) => (await sql`select to_regclass(${name})::oid as oid`.execute(db)).rows[0].oid;
|
|
14
|
-
const userIdType = async (db, users, of = {
|
|
15
|
-
feature: "notifications",
|
|
16
|
-
rows: "devices"
|
|
17
|
-
}) => {
|
|
18
|
-
const oid = await regclass(db, qualified(users));
|
|
19
|
-
if (oid === null) throw new Error(`${of.feature}: auth's users table ${qualified(users)} is not in the app's database, so ${of.rows} cannot point at it`);
|
|
20
|
-
const { rows } = await sql`select format_type(atttypid, atttypmod) as type from pg_attribute where attrelid = ${oid} and attname = 'id'`.execute(db);
|
|
21
|
-
return rows[0].type;
|
|
22
|
-
};
|
|
23
|
-
const columnsOf = async (db, oid) => (await sql`select attname as name, attnum as num from pg_attribute where attrelid = ${oid} and attnum > 0 and not attisdropped`.execute(db)).rows;
|
|
24
|
-
const uniqueOn = async (db, oid, num) => (await sql`select exists (select from pg_index where indrelid = ${oid} and indisunique and indpred is null and indexprs is null and indnatts = 1 and indkey[0] = ${num}) as found`.execute(db)).rows[0].found;
|
|
25
|
-
const cascadesFrom = async (db, oid, num, users) => (await sql`select exists (select from pg_constraint where conrelid = ${oid} and contype = 'f' and confdeltype = 'c'
|
|
26
|
-
and conkey = array[${num}]::int2[] and confrelid = to_regclass(${qualified(users)})) as found`.execute(db)).rows[0].found;
|
|
27
|
-
const lacksSessionColumn = async (db, names) => {
|
|
28
|
-
const oid = await regclass(db, qualified(names));
|
|
29
|
-
return oid !== null && !(await columnsOf(db, oid)).some((row) => row.name === names.columns.session_id);
|
|
30
|
-
};
|
|
31
|
-
const kindChecksWithoutRelay = async (db, names) => {
|
|
32
|
-
const oid = await regclass(db, qualified(names));
|
|
33
|
-
if (oid === null) return [];
|
|
34
|
-
const { rows } = await sql`select c.conname as name, pg_get_constraintdef(c.oid) as def from pg_constraint c
|
|
35
|
-
join pg_attribute a on a.attrelid = c.conrelid and a.attnum = any(c.conkey)
|
|
36
|
-
where c.conrelid = ${oid} and c.contype = 'c' and a.attname = ${names.columns.kind} order by c.conname`.execute(db);
|
|
37
|
-
return legacyKindChecks(rows, names.columns);
|
|
38
|
-
};
|
|
39
|
-
/**
|
|
40
|
-
* The SQL that adds the tables `notifications` keeps devices and each user's history in, under the names its options
|
|
41
|
-
* give; with `auth`, their user columns point at auth's users table. Each table is left out when it exists or a store
|
|
42
|
-
* of the app's own replaces it; an existing devices table without its session column gets that column, and one whose
|
|
43
|
-
* checks allow no relay devices gets checks that do. `undefined` when nothing is left.
|
|
44
|
-
*/
|
|
45
|
-
const notificationsMigration = async (db, options = {}, auth) => {
|
|
46
|
-
const devices = !options.store && notificationsNames(options);
|
|
47
|
-
const history = !options.historyStore && historyNames(options);
|
|
48
|
-
const missing = async (names) => names && await regclass(db, qualified(names)) === null;
|
|
49
|
-
const [needsDevices, needsHistory] = [await missing(devices), await missing(history)];
|
|
50
|
-
const needsSession = devices && !needsDevices && await lacksSessionColumn(db, devices);
|
|
51
|
-
const oldChecks = devices && !needsDevices ? await kindChecksWithoutRelay(db, devices) : [];
|
|
52
|
-
if (!needsDevices && !needsHistory && !needsSession && oldChecks.length === 0) return void 0;
|
|
53
|
-
const users = auth && authUsersTable(auth);
|
|
54
|
-
const user = users && (needsDevices || needsHistory) ? {
|
|
55
|
-
type: await userIdType(db, users),
|
|
56
|
-
references: `${qualified(users)} (id)`
|
|
57
|
-
} : { type: "text" };
|
|
58
|
-
const statements = [
|
|
59
|
-
...needsDevices && devices ? devicesTableSql(devices, user) : [],
|
|
60
|
-
...needsSession && devices ? [deviceSessionColumnSql(devices)] : [],
|
|
61
|
-
...oldChecks.length > 0 && devices ? [deviceKindChecksSql(devices, oldChecks)] : [],
|
|
62
|
-
...needsHistory && history ? historyTableSql(history, user) : []
|
|
63
|
-
];
|
|
64
|
-
return `${[...new Set(statements)].join(";\n\n")};`;
|
|
65
|
-
};
|
|
66
|
-
const missingTable = (what, table) => /* @__PURE__ */ new Error(`The ${what} table ${table} of notifications is missing. Write it as a migration with \`${migrationCommand}\`, apply it with the project's migrations, then start again.`);
|
|
67
|
-
/**
|
|
68
|
-
* Refuses to start while the devices table lacks what `notifications` needs, naming it: the table, each column under
|
|
69
|
-
* its configured name, a unique index on the token alone, which moving a device relies on, and with `auth` a foreign key
|
|
70
|
-
* from the user column that deletes a user's devices with the user. Nothing to check with a store of the app's own.
|
|
71
|
-
*/
|
|
72
|
-
const checkDevicesTable = async (db, options, users) => {
|
|
73
|
-
if (options.store) return;
|
|
74
|
-
const names = notificationsNames(options);
|
|
75
|
-
const devices = qualified(names);
|
|
76
|
-
const oid = await regclass(db, devices);
|
|
77
|
-
if (oid === null) throw missingTable("devices", devices);
|
|
78
|
-
const found = await columnsOf(db, oid);
|
|
79
|
-
const numOf = (column) => found.find((row) => row.name === names.columns[column])?.num;
|
|
80
|
-
const missing = Object.keys(names.columns).find((column) => numOf(column) === void 0);
|
|
81
|
-
if (missing !== void 0) throw new Error(`The devices table ${devices} has no column "${names.columns[missing]}": add it, or name the table's own with notifications: { devices: { columns: { ${missing}: ... } } } in protobase.config.ts`);
|
|
82
|
-
if (!await uniqueOn(db, oid, numOf("token"))) throw new Error(`The devices table ${devices} needs a unique index on its token column "${names.columns.token}" alone, which moving a device to the user who registers it relies on`);
|
|
83
|
-
if (users && !await cascadesFrom(db, oid, numOf("user_id"), users)) throw new Error(`The devices table ${devices} needs a foreign key from "${names.columns.user_id}" to ${qualified(users)} with on delete cascade, so a deleted user's devices go with them`);
|
|
84
|
-
};
|
|
85
|
-
/** Refuses to start while the history table lacks its table, a column or, with `auth`, the cascading foreign key. */
|
|
86
|
-
const checkHistoryTable = async (db, options, users) => {
|
|
87
|
-
if (options.historyStore) return;
|
|
88
|
-
const names = historyNames(options);
|
|
89
|
-
const history = qualified(names);
|
|
90
|
-
const oid = await regclass(db, history);
|
|
91
|
-
if (oid === null) throw missingTable("history", history);
|
|
92
|
-
const found = await columnsOf(db, oid);
|
|
93
|
-
const numOf = (column) => found.find((row) => row.name === names.columns[column])?.num;
|
|
94
|
-
const missing = Object.keys(names.columns).find((column) => numOf(column) === void 0);
|
|
95
|
-
if (missing !== void 0) throw new Error(`The history table ${history} has no column "${names.columns[missing]}": add it, or name the table's own with notifications: { history: { columns: { ${missing}: ... } } } in protobase.config.ts`);
|
|
96
|
-
if (users && !await cascadesFrom(db, oid, numOf("user_id"), users)) throw new Error(`The history table ${history} needs a foreign key from "${names.columns.user_id}" to ${qualified(users)} with on delete cascade, so a deleted user's history goes with them`);
|
|
97
|
-
};
|
|
98
|
-
/** Refuses to start while the devices or the history table lacks what `notifications` needs, naming it. */
|
|
99
|
-
const checkNotificationsSchema = async (db, options = {}, auth) => {
|
|
100
|
-
const users = auth && authUsersTable(auth);
|
|
101
|
-
await checkDevicesTable(db, options, users);
|
|
102
|
-
await checkHistoryTable(db, options, users);
|
|
103
|
-
};
|
|
104
4
|
//#endregion
|
|
105
|
-
export {
|
|
5
|
+
export { regclass };
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { qualified } from "./schema-sql.js";
|
|
2
|
+
//#region src/notifications/table-names.ts
|
|
3
|
+
/** The auth store's users table, or the table that holds the user ids (`users.keyTable`), and the type of its ids. */
|
|
4
|
+
const usersTarget = (store) => {
|
|
5
|
+
if (!store) return {
|
|
6
|
+
users: "",
|
|
7
|
+
idType: "text"
|
|
8
|
+
};
|
|
9
|
+
const users = store.users.keyTable ?? {
|
|
10
|
+
schema: store.schema,
|
|
11
|
+
table: store.names.table("user").name
|
|
12
|
+
};
|
|
13
|
+
return {
|
|
14
|
+
users: qualified(users),
|
|
15
|
+
idType: store.uuidIds ? "uuid" : "text"
|
|
16
|
+
};
|
|
17
|
+
};
|
|
18
|
+
/** A table's names and the users it points at, as a module's names. */
|
|
19
|
+
const moduleNames = ({ schema, table, columns }, { users, idType }) => ({
|
|
20
|
+
schema,
|
|
21
|
+
table,
|
|
22
|
+
users,
|
|
23
|
+
user_id_type: idType,
|
|
24
|
+
...Object.fromEntries(Object.entries(columns).map(([column, name]) => [`column.${column}`, name]))
|
|
25
|
+
});
|
|
26
|
+
/** The table's names and the users it points at from a module's names, for `columns`. */
|
|
27
|
+
const tableNames = (names, columns) => ({
|
|
28
|
+
table: {
|
|
29
|
+
schema: names.schema,
|
|
30
|
+
table: names.table,
|
|
31
|
+
columns: Object.fromEntries(columns.map((column) => [column, names[`column.${column}`]]))
|
|
32
|
+
},
|
|
33
|
+
user: {
|
|
34
|
+
type: names.user_id_type,
|
|
35
|
+
...names.users && { references: `${names.users} (id)` }
|
|
36
|
+
},
|
|
37
|
+
users: names.users || void 0
|
|
38
|
+
});
|
|
39
|
+
//#endregion
|
|
40
|
+
export { moduleNames, tableNames, usersTarget };
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { keptNamesOf } from "../better-auth/organizations/kept-organizations.js";
|
|
2
|
+
import { noOrganizationTables, organizationTables, sessionOrganization } from "./organization-tables.js";
|
|
3
|
+
//#region src/organization-scope/app-scope.ts
|
|
4
|
+
const unscoped = {
|
|
5
|
+
tables: noOrganizationTables,
|
|
6
|
+
pinned: void 0,
|
|
7
|
+
organizationOf: () => void 0
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* The app's scope, read once the store says whether organizations were on. With organizations on, the session's
|
|
11
|
+
* active organization. While they are off after being on, the tables they kept, under their names with organizations
|
|
12
|
+
* on, and the pinned organization, for work about none and for a session of it, whose `tenant` is its id; a session
|
|
13
|
+
* of another tenant, such as an outside app's, works in none. An app that never had organizations scopes nothing.
|
|
14
|
+
*/
|
|
15
|
+
const appScope = ({ organizations, names, pinned }) => {
|
|
16
|
+
if (organizations) {
|
|
17
|
+
const on = {
|
|
18
|
+
tables: organizationTables(names),
|
|
19
|
+
pinned: void 0,
|
|
20
|
+
organizationOf: sessionOrganization
|
|
21
|
+
};
|
|
22
|
+
return async () => on;
|
|
23
|
+
}
|
|
24
|
+
const kept = names && pinned && keptNamesOf(names);
|
|
25
|
+
if (!kept) return async () => unscoped;
|
|
26
|
+
const tables = organizationTables(kept);
|
|
27
|
+
return async () => {
|
|
28
|
+
const pin = await pinned();
|
|
29
|
+
if (!pin) return unscoped;
|
|
30
|
+
return {
|
|
31
|
+
tables,
|
|
32
|
+
pinned: pin.id,
|
|
33
|
+
organizationOf: (session) => session?.tenant === pin.id ? pin.id : void 0
|
|
34
|
+
};
|
|
35
|
+
};
|
|
36
|
+
};
|
|
37
|
+
//#endregion
|
|
38
|
+
export { appScope };
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { inSignInScope } from "./sign-in-organization.js";
|
|
2
|
+
import { authBasePath } from "../better-auth/auth-base-path.js";
|
|
3
|
+
import { everyOrganization } from "@protobase/query";
|
|
4
|
+
//#region src/organization-scope/auth-request-organization.ts
|
|
5
|
+
const acrossPaths = {
|
|
6
|
+
"/organization/list": "a user lists the organizations they are a member of",
|
|
7
|
+
"/organization/list-user-invitations": "a user lists the invitations to their address, from every organization",
|
|
8
|
+
"/organization/get-invitation": "an invitation is found by its id for the person it invites, before they are a member",
|
|
9
|
+
"/organization/reject-invitation": "an invitation is found by its id for the person it invites, before they are a member",
|
|
10
|
+
"/organization/cancel-invitation": "an invitation is found by its id, before the caller's right is checked in its organization",
|
|
11
|
+
"/organization/create": "creating an organization counts the creator's organizations and makes them the new one's first member"
|
|
12
|
+
};
|
|
13
|
+
const bodyOrganization = async (request) => {
|
|
14
|
+
if (request.method !== "POST" || !request.headers.get("content-type")?.includes("application/json")) return;
|
|
15
|
+
let body;
|
|
16
|
+
try {
|
|
17
|
+
body = await request.clone().json();
|
|
18
|
+
} catch (error) {
|
|
19
|
+
if (error instanceof SyntaxError) return;
|
|
20
|
+
throw error;
|
|
21
|
+
}
|
|
22
|
+
const named = body?.organizationId;
|
|
23
|
+
return typeof named === "string" && named !== "" ? named : void 0;
|
|
24
|
+
};
|
|
25
|
+
/** A request that names one organization in its query and another in its body, which is refused. */
|
|
26
|
+
const conflictingOrganizations = Symbol("the query and the body name different organizations");
|
|
27
|
+
const namedOrganization = async (request) => {
|
|
28
|
+
const inQuery = new URL(request.url).searchParams.get("organizationId") || void 0;
|
|
29
|
+
if (request.method !== "POST") return inQuery;
|
|
30
|
+
const inBody = await bodyOrganization(request);
|
|
31
|
+
if (inQuery !== void 0 && inBody !== void 0 && inQuery !== inBody) return conflictingOrganizations;
|
|
32
|
+
return inBody ?? inQuery;
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* The organization an `/api/auth/*` request works in: every organization for the endpoints that read across them, saying
|
|
36
|
+
* why; the one it names as `organizationId` where its endpoint reads it, where Better Auth checks the caller's membership
|
|
37
|
+
* itself (`conflictingOrganizations` when a POST names two); for another
|
|
38
|
+
* organization endpoint, the session's active organization (`activeOrganization`, read only then); none for the rest,
|
|
39
|
+
* sign-in, sessions and tokens among them, whose reads of the organization's tables name the organization they read in
|
|
40
|
+
* or why they cross organizations.
|
|
41
|
+
*/
|
|
42
|
+
const authRequestOrganization = async (request, activeOrganization) => {
|
|
43
|
+
const path = new URL(request.url).pathname.slice(authBasePath.length);
|
|
44
|
+
const across = acrossPaths[path];
|
|
45
|
+
if (across) return everyOrganization(across);
|
|
46
|
+
const named = await namedOrganization(request);
|
|
47
|
+
if (named !== void 0) return named;
|
|
48
|
+
if (path.startsWith("/organization/")) return activeOrganization();
|
|
49
|
+
};
|
|
50
|
+
/**
|
|
51
|
+
* `answer`, Better Auth's handler, with each request's sign-in queries in the organization it works in
|
|
52
|
+
* (`authRequestOrganization`); promises it starts, its background tasks too, stay there. A request naming two
|
|
53
|
+
* organizations is refused with `400`.
|
|
54
|
+
*/
|
|
55
|
+
const answerInOrganization = (answer, activeOrganization) => async (request) => {
|
|
56
|
+
const organization = await authRequestOrganization(request, () => activeOrganization(request));
|
|
57
|
+
if (organization === conflictingOrganizations) return Response.json({
|
|
58
|
+
code: "CONFLICTING_ORGANIZATIONS",
|
|
59
|
+
message: "Name the organization once: the query and the body name different ones."
|
|
60
|
+
}, { status: 400 });
|
|
61
|
+
return inSignInScope(organization, () => answer(request));
|
|
62
|
+
};
|
|
63
|
+
/** The active organization of the request's session, read without refreshing it; none without a session. */
|
|
64
|
+
const sessionActiveOrganization = (auth) => async (request) => {
|
|
65
|
+
return ((await auth.api.getSession({
|
|
66
|
+
headers: request.headers,
|
|
67
|
+
query: { disableRefresh: true }
|
|
68
|
+
}))?.session)?.activeOrganizationId ?? void 0;
|
|
69
|
+
};
|
|
70
|
+
//#endregion
|
|
71
|
+
export { answerInOrganization, authRequestOrganization, conflictingOrganizations, sessionActiveOrganization };
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
//#region src/organization-scope/organization-tables.ts
|
|
2
|
+
/**
|
|
3
|
+
* The store's tables whose rows each belong to one organization, under the names the app gives them, on their
|
|
4
|
+
* `organization_id`: `member`, `invitation` and `personal_access_token` while organizations are on, none otherwise.
|
|
5
|
+
*/
|
|
6
|
+
const organizationTables = (names) => ({ tables: Object.values(names?.tables ?? {}).flatMap((table) => {
|
|
7
|
+
const column = table.columns.organization_id;
|
|
8
|
+
if (table.scope !== "organization" || !column) return [];
|
|
9
|
+
return [{
|
|
10
|
+
...table.schema !== void 0 && { schema: table.schema },
|
|
11
|
+
table: table.name,
|
|
12
|
+
column: column.name
|
|
13
|
+
}];
|
|
14
|
+
}) });
|
|
15
|
+
/** No scoped table: the scope of an app without organizations. */
|
|
16
|
+
const noOrganizationTables = { tables: [] };
|
|
17
|
+
/** The organization a session works in: its active one, with organizations on; none for anyone else. */
|
|
18
|
+
const sessionOrganization = (session) => session?.organization?.id;
|
|
19
|
+
//#endregion
|
|
20
|
+
export { noOrganizationTables, organizationTables, sessionOrganization };
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { everyOrganization } from "@protobase/query";
|
|
2
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
3
|
+
//#region src/organization-scope/sign-in-organization.ts
|
|
4
|
+
const current = new AsyncLocalStorage();
|
|
5
|
+
/**
|
|
6
|
+
* Where sign-in's database (`appAuthOptions`) finds the organization each query works in: the one the work around it
|
|
7
|
+
* set with `inOrganization`, every one within `acrossOrganizations`, and none outside both, which sees no row of the
|
|
8
|
+
* organization's tables and writes none.
|
|
9
|
+
*/
|
|
10
|
+
const signInOrganization = () => current.getStore();
|
|
11
|
+
/** Runs `work` with sign-in's queries kept to `scope`: an organization, none, or every one (`everyOrganization`). */
|
|
12
|
+
const inSignInScope = (scope, work) => current.run(scope, work);
|
|
13
|
+
/** Runs `work` with sign-in's queries kept to `organization`; undefined keeps them to none. */
|
|
14
|
+
const inOrganization = (organization, work) => current.run(organization, work);
|
|
15
|
+
/**
|
|
16
|
+
* Runs `work` with sign-in's queries reading every organization's rows: `reason` says why the work crosses
|
|
17
|
+
* organizations, such as "a user lists their own memberships". Refused without one.
|
|
18
|
+
*/
|
|
19
|
+
const acrossOrganizations = (reason, work) => current.run(everyOrganization(reason), work);
|
|
20
|
+
//#endregion
|
|
21
|
+
export { acrossOrganizations, inOrganization, inSignInScope, signInOrganization };
|
package/dist/package.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { acrossOrganizations } from "../organization-scope/sign-in-organization.js";
|
|
1
2
|
import { sql } from "kysely";
|
|
2
3
|
//#region src/personal-mail/shared-sender-store.ts
|
|
3
4
|
/**
|
|
@@ -17,7 +18,7 @@ const sharedSenderReader = (store, { organizations, verifiers }) => async (userI
|
|
|
17
18
|
const proved = verifiers.length === 0 ? sql`null::timestamptz` : sql`(select max(${v.settled_at}) from ${verification} where ${v.sender_id} = ${sender}.id and ${v.verifier} = any(${[...verifiers]}::text[]) and ${v.state} = 'verified' and ${v.valid_until} > now())`;
|
|
18
19
|
const inReach = member ? sql`and ${sender}.${c.user_id} in (select theirs.${member.columns.user_id} from ${member} as mine join ${member} as theirs on theirs.${member.columns.organization_id} = mine.${member.columns.organization_id} where mine.${member.columns.user_id} = ${userId})` : sql``;
|
|
19
20
|
const named = id === void 0 ? sql`` : sql`and ${sender}.id = ${id}`;
|
|
20
|
-
const
|
|
21
|
+
const query = sql`select ${sender}.id, ${sender}.${c.user_id} as "userId", ${sender}.${c.connection_id} as "connectionId", ${sender}.${c.address} as address,
|
|
21
22
|
${sender}.${c.name} as name, ${sender}.${c.shared_at} as "sharedAt", ${sender}.${c.signature} as signature, false as "isDefault", ${sender}.${c.created_at} as "createdAt",
|
|
22
23
|
${sender}.${c.typed_at} as "typedAt", ${sender}.${c.listed_at} as "listedAt", ${sender}.${c.provider_state} as "providerState",
|
|
23
24
|
${sender}.${c.provider_state_read_at} as "providerStateReadAt", ${sender}.${c.removed_at} as "removedAt",
|
|
@@ -26,7 +27,8 @@ const sharedSenderReader = (store, { organizations, verifiers }) => async (userI
|
|
|
26
27
|
from ${sender}
|
|
27
28
|
left join ${account} on ${account}.id = ${sender}.${c.connection_id} and ${account}.${a.user_id} = ${sender}.${c.user_id}
|
|
28
29
|
where ${sender}.${c.shared_at} is not null and ${sender}.${c.user_id} <> ${userId} ${named} ${inReach}
|
|
29
|
-
order by ${sender}.${c.created_at}, ${sender}.${c.address_key}, ${sender}.id
|
|
30
|
+
order by ${sender}.${c.created_at}, ${sender}.${c.address_key}, ${sender}.id`;
|
|
31
|
+
const { rows } = await (member ? acrossOrganizations("a user reads the addresses shared with them by people of their own organizations", () => query.execute(s.db)) : query.execute(s.db));
|
|
30
32
|
return rows.map((row) => ({
|
|
31
33
|
...row,
|
|
32
34
|
account: row.account && {
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { relaySchema, relaySchemaSql, relayTables, spacedTables } from "./relay-schema-sql.js";
|
|
2
|
+
import { sql } from "kysely";
|
|
3
|
+
//#region src/realtime/relay/realtime-relay-module.ts
|
|
4
|
+
/**
|
|
5
|
+
* The `realtime_relay` schema as the database has it: step 1 once every table is there with its `space` column.
|
|
6
|
+
* Refuses one written before the record channels, which no step records.
|
|
7
|
+
*/
|
|
8
|
+
const readRealtimeRelay = async (db) => {
|
|
9
|
+
const names = relayTables.map((table) => `${relaySchema}.${table}`);
|
|
10
|
+
const { rows } = await sql`select
|
|
11
|
+
(select count(*)::int from unnest(${names}::text[]) as name where to_regclass(name) is not null) as found,
|
|
12
|
+
(select count(*)::int from information_schema.columns where table_schema = ${relaySchema} and table_name = any(${[...spacedTables]}::text[]) and column_name = 'space') as spaced`.execute(db);
|
|
13
|
+
const { found, spaced } = rows[0];
|
|
14
|
+
if (found === 0) return;
|
|
15
|
+
if (found < relayTables.length || spaced < spacedTables.length) throw new Error(`The ${relaySchema} schema lacks tables or columns no step of this version of Protobase records: bring it there with \`protobase migration\` and \`protobase migrate\` of Protobase 0.14.2 first, then run this command again`);
|
|
16
|
+
return {
|
|
17
|
+
lastStep: 1,
|
|
18
|
+
replaceables: {}
|
|
19
|
+
};
|
|
20
|
+
};
|
|
21
|
+
/** The `realtime_relay` schema that carries broadcasts and presence between the processes serving the app. Never dropped. */
|
|
22
|
+
const realtimeRelayModule = {
|
|
23
|
+
label: `the ${relaySchema} schema`,
|
|
24
|
+
title: "The relay of Realtime broadcasts and presence between the processes serving the app",
|
|
25
|
+
steps: [{
|
|
26
|
+
step: 1,
|
|
27
|
+
name: "relay",
|
|
28
|
+
title: "The frames, presences, processes and rates tables",
|
|
29
|
+
additive: true,
|
|
30
|
+
sql: () => relaySchemaSql
|
|
31
|
+
}],
|
|
32
|
+
replaceables: [],
|
|
33
|
+
resourceReplaceables: [],
|
|
34
|
+
read: readRealtimeRelay
|
|
35
|
+
};
|
|
36
|
+
//#endregion
|
|
37
|
+
export { realtimeRelayModule };
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { sql } from "kysely";
|
|
2
|
+
//#region src/relation-found.ts
|
|
3
|
+
/** Whether the database has a relation of the name, as SQL writes it, such as `"webhooks"."subscriptions"`. Only reads the catalogue. */
|
|
4
|
+
const relationFound = async (db, name) => (await sql`select to_regclass(${name}) is not null as found`.execute(db)).rows[0].found;
|
|
5
|
+
//#endregion
|
|
6
|
+
export { relationFound };
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { sessionsCurrent } from "./sessions-sql.js";
|
|
2
|
+
import { argsOf, realtimeMembersTable, realtimeSchema } from "./realtime-members-sql.js";
|
|
3
|
+
import { resourceEntry } from "../schema-modules/resource-difference.js";
|
|
4
|
+
import { sql } from "kysely";
|
|
5
|
+
//#region src/relay/read-relay.ts
|
|
6
|
+
const triggerArgs = (hex) => new TextDecoder().decode(Buffer.from(hex, "hex")).split("\0").slice(0, -1);
|
|
7
|
+
const readTriggers = async (db) => (await sql`select t.tgrelid::regclass::text as "table",
|
|
8
|
+
n.nspname as schema, c.relname, t.tgname as name,
|
|
9
|
+
encode(t.tgargs, 'hex') as args,
|
|
10
|
+
t.tgenabled in ('O', 'A') and not exists (
|
|
11
|
+
with recursive clones as (select oid, tgenabled from pg_trigger where tgparentid = t.oid
|
|
12
|
+
union all select c.oid, c.tgenabled from pg_trigger c join clones on c.tgparentid = clones.oid)
|
|
13
|
+
select from clones where tgenabled not in ('O', 'A')
|
|
14
|
+
) as enabled,
|
|
15
|
+
array(select tree.relid::regclass::text from pg_partition_tree(t.tgrelid) as tree where tree.relid <> t.tgrelid order by 1) as partitions
|
|
16
|
+
from pg_trigger t join pg_proc p on p.oid = t.tgfoid join pg_namespace pn on pn.oid = p.pronamespace
|
|
17
|
+
join pg_class c on c.oid = t.tgrelid join pg_namespace n on n.oid = c.relnamespace
|
|
18
|
+
where pn.nspname = ${realtimeSchema} and p.proname = 'members_kept' and t.tgparentid = 0`.execute(db)).rows.map((row) => ({
|
|
19
|
+
...row,
|
|
20
|
+
args: triggerArgs(row.args)
|
|
21
|
+
}));
|
|
22
|
+
const regclassText = async (db, tables) => (await sql`select to_regclass(name)::text as text from unnest(${tables}::text[]) with ordinality as listed(name, place) order by place`.execute(db)).rows.map((row) => row.text);
|
|
23
|
+
/**
|
|
24
|
+
* Whether `found` keeps `listed` on its table `rel`: the row trigger and a truncate trigger on it and on each of its
|
|
25
|
+
* partitions, with its arguments, every one firing.
|
|
26
|
+
*/
|
|
27
|
+
const keeps = (found, listed, rel) => {
|
|
28
|
+
const args = argsOf(listed).join("\0");
|
|
29
|
+
const own = found.filter((trigger) => trigger.args.join("\0") === args && (trigger.table === rel || found.some((root) => root.table === rel && root.partitions.includes(trigger.table))));
|
|
30
|
+
const row = own.find((trigger) => trigger.table === rel && trigger.name === "realtime_members");
|
|
31
|
+
if (!row) return false;
|
|
32
|
+
return [rel, ...row.partitions].every((table) => own.some((trigger) => trigger.table === table && trigger.name === "realtime_members_truncated")) && own.every((trigger) => trigger.enabled);
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* The relay's objects as the database has them for `input`: step 1 once `realtime.members` is there, the sessions
|
|
36
|
+
* trigger at its version when it stands on the sessions table with this version's function, the members functions at
|
|
37
|
+
* the version their comment names, and each listed resource whose table has the triggers this version writes, else at
|
|
38
|
+
* no digest, so they are written again; and the row triggers on tables no listed resource has, by the resource their
|
|
39
|
+
* first argument names, so they are dropped. Refuses members functions of a version no step records.
|
|
40
|
+
*/
|
|
41
|
+
const readRelay = (members) => async (db, input) => {
|
|
42
|
+
const [state] = (await sql`select to_regclass(${realtimeMembersTable}) is not null as table,
|
|
43
|
+
(select obj_description(p.oid, 'pg_proc') from pg_proc p join pg_namespace n on n.oid = p.pronamespace where n.nspname = ${realtimeSchema} and p.proname = 'members_kept' and p.pronargs = 0) as comment`.execute(db)).rows;
|
|
44
|
+
const sessions = await sessionsCurrent(db, input.names.sessions);
|
|
45
|
+
if (!state.table && !sessions) return;
|
|
46
|
+
const version = state.comment?.match(/^Protobase realtime members (\d+)$/)?.[1];
|
|
47
|
+
if (state.comment && Number(version) !== 3) throw new Error(`The functions that keep realtime.members are at ${version === void 0 ? "a version" : `version ${version}`} no step of this version of Protobase records: bring them to version 3 with \`protobase migration\` and \`protobase migrate\` of Protobase 0.14.2 first, then run this command again`);
|
|
48
|
+
const found = await readTriggers(db);
|
|
49
|
+
const given = Object.entries(input.resources[members.name] ?? {});
|
|
50
|
+
const rels = await regclassText(db, given.map(([, { input: listed }]) => listed.table));
|
|
51
|
+
const entries = {};
|
|
52
|
+
given.forEach(([key, one], i) => {
|
|
53
|
+
const rel = rels[i];
|
|
54
|
+
if (!rel || !found.some((trigger) => trigger.table === rel && trigger.name === "realtime_members")) return;
|
|
55
|
+
const entry = resourceEntry(members, input.names, one);
|
|
56
|
+
entries[key] = keeps(found, one.input, rel) ? entry : {
|
|
57
|
+
...entry,
|
|
58
|
+
digest: ""
|
|
59
|
+
};
|
|
60
|
+
});
|
|
61
|
+
for (const trigger of found) {
|
|
62
|
+
const [resource] = trigger.args;
|
|
63
|
+
if (trigger.name !== "realtime_members" || resource === void 0 || rels.includes(trigger.table)) continue;
|
|
64
|
+
const key = entries[resource] ? `${resource} on ${trigger.table}` : resource;
|
|
65
|
+
entries[key] = {
|
|
66
|
+
version: members.version,
|
|
67
|
+
digest: "",
|
|
68
|
+
table: {
|
|
69
|
+
schema: trigger.schema,
|
|
70
|
+
name: trigger.relname
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
return {
|
|
75
|
+
lastStep: state.table ? 1 : 0,
|
|
76
|
+
replaceables: {
|
|
77
|
+
...sessions && { sessions: 1 },
|
|
78
|
+
...version !== void 0 && { members: 3 }
|
|
79
|
+
},
|
|
80
|
+
names: input.names,
|
|
81
|
+
...Object.keys(entries).length > 0 && { resources: { [members.name]: entries } }
|
|
82
|
+
};
|
|
83
|
+
};
|
|
84
|
+
//#endregion
|
|
85
|
+
export { readRelay };
|
|
@@ -16,16 +16,8 @@ const listedTable = ({ model, field }) => ({
|
|
|
16
16
|
deleted: model.softDelete === void 0 ? "" : model.fields[model.softDelete].column
|
|
17
17
|
});
|
|
18
18
|
const literal = (text) => `'${text.replaceAll("'", "''")}'`;
|
|
19
|
-
/**
|
|
20
|
-
|
|
21
|
-
* tickets and co-members; `listed_members`, the user ids one state of a record lists, none once soft-deleted; and the
|
|
22
|
-
* trigger function. A truncate, of the table or of one of its partitions, writes the resource's members again from the
|
|
23
|
-
* table as it stands, so a truncated partition's siblings keep theirs. After each write that changes a record's key, members or soft
|
|
24
|
-
* delete, as it stands after every trigger before it, it writes the members of the record's old and new keys again
|
|
25
|
-
* from the table: row triggers that run after the write fire once the statement wrote every row, so a statement that
|
|
26
|
-
* swaps two records' keys leaves each key with the members its record lists.
|
|
27
|
-
*/
|
|
28
|
-
const baseSql = [
|
|
19
|
+
/** The members table, keyed by channel so a notice's audience is read by its key, with an index by person for their tickets and co-members. */
|
|
20
|
+
const membersTableSql = [
|
|
29
21
|
`create schema if not exists ${realtimeSchema}`,
|
|
30
22
|
`create table if not exists ${realtimeMembersTable} (
|
|
31
23
|
resource text not null,
|
|
@@ -33,7 +25,17 @@ const baseSql = [
|
|
|
33
25
|
user_id text not null,
|
|
34
26
|
primary key (resource, channel_key, user_id)
|
|
35
27
|
)`,
|
|
36
|
-
`create index if not exists members_by_user on ${realtimeMembersTable} (user_id, resource)
|
|
28
|
+
`create index if not exists members_by_user on ${realtimeMembersTable} (user_id, resource)`
|
|
29
|
+
];
|
|
30
|
+
/**
|
|
31
|
+
* `listed_members`, the user ids one state of a record lists, none once soft-deleted; and the trigger function. A
|
|
32
|
+
* truncate, of the table or of one of its partitions, writes the resource's members again from the table as it stands,
|
|
33
|
+
* so a truncated partition's siblings keep theirs. After each write that changes a record's key, members or soft
|
|
34
|
+
* delete, as it stands after every trigger before it, it writes the members of the record's old and new keys again
|
|
35
|
+
* from the table: row triggers that run after the write fire once the statement wrote every row, so a statement that
|
|
36
|
+
* swaps two records' keys leaves each key with the members its record lists.
|
|
37
|
+
*/
|
|
38
|
+
const membersFunctionsSql = [
|
|
37
39
|
`create or replace function ${realtimeSchema}.listed_members(entry jsonb, members_column text, deleted_column text) returns setof text
|
|
38
40
|
language sql immutable as $$
|
|
39
41
|
select distinct member from jsonb_array_elements_text(
|
|
@@ -88,14 +90,33 @@ const argsOf = ({ resource, key, members, deleted }) => [
|
|
|
88
90
|
members,
|
|
89
91
|
deleted
|
|
90
92
|
];
|
|
91
|
-
|
|
92
|
-
const
|
|
93
|
-
|
|
93
|
+
const refusedSql = (table) => `exists (select from pg_class c where c.oid = ${literal(table)}::regclass and (c.relispartition or (c.relkind <> 'p' and exists (select from pg_inherits i where i.inhrelid = c.oid or i.inhparent = c.oid))))`;
|
|
94
|
+
const partitionsSql = (table) => `select relid from pg_partition_tree(to_regclass(${literal(table)})) where relid <> to_regclass(${literal(table)})`;
|
|
95
|
+
/**
|
|
96
|
+
* The triggers that keep `realtime.members` on one listed table, written whole: its row trigger, cloned onto its
|
|
97
|
+
* partitions by Postgres, and its truncate trigger on it and on each partition it has as the statements run, then its
|
|
98
|
+
* rows written again from the table. A partition or inheriting table is refused. Writes made while the triggers are
|
|
99
|
+
* off, such as with `session_replication_role = replica`, are not kept until they are written again.
|
|
100
|
+
*/
|
|
101
|
+
const listedTableSql = (listed) => {
|
|
94
102
|
const { resource, table, key, members, deleted } = listed;
|
|
103
|
+
const args = argsOf(listed).map(literal).join(", ");
|
|
95
104
|
return [
|
|
96
|
-
`
|
|
97
|
-
|
|
98
|
-
|
|
105
|
+
`do $members$ begin
|
|
106
|
+
if ${refusedSql(table)} then
|
|
107
|
+
raise exception 'realtime.members cannot keep the members of %: a partition or a table in an inheritance tree is not supported as a channel resource whose records list their members; use the partitioned table itself', ${literal(table)};
|
|
108
|
+
end if;
|
|
109
|
+
end $members$`,
|
|
110
|
+
`drop trigger if exists ${rowTrigger} on ${table}`,
|
|
111
|
+
`drop trigger if exists ${truncateTrigger} on ${table}`,
|
|
112
|
+
`create trigger ${rowTrigger} after insert or delete or update on ${table} for each row execute function ${realtimeSchema}.members_kept(${args})`,
|
|
113
|
+
`create trigger ${truncateTrigger} after truncate on ${table} for each statement execute function ${realtimeSchema}.members_kept(${args})`,
|
|
114
|
+
`do $members$ declare part regclass; begin
|
|
115
|
+
for part in ${partitionsSql(table)} loop
|
|
116
|
+
execute format('drop trigger if exists ${truncateTrigger} on %s', part);
|
|
117
|
+
execute format('create trigger ${truncateTrigger} after truncate on %s for each statement execute function ${realtimeSchema}.members_kept(%s)', part, ${literal(args)});
|
|
118
|
+
end loop;
|
|
119
|
+
end $members$`,
|
|
99
120
|
`delete from ${realtimeMembersTable} where resource = ${literal(resource)}`,
|
|
100
121
|
`insert into ${realtimeMembersTable} (resource, channel_key, user_id)
|
|
101
122
|
select ${literal(resource)}, to_jsonb(t) ->> ${literal(key)}, member from ${table} t
|
|
@@ -104,17 +125,19 @@ const listedTableSql = (listed, partitions) => {
|
|
|
104
125
|
];
|
|
105
126
|
};
|
|
106
127
|
/**
|
|
107
|
-
*
|
|
108
|
-
*
|
|
109
|
-
* of its partitions (`partitions`, by listed table, as SQL names each) included, its rows written again
|
|
110
|
-
* from the table, and the rows of resources no longer listed deleted. Writes made while the triggers are off, such as
|
|
111
|
-
* with `session_replication_role = replica`, are not kept until the next migration that writes it.
|
|
128
|
+
* Drops the triggers that keep `realtime.members` on a table, on its partitions too, then the rows of each resource
|
|
129
|
+
* whose row trigger stands nowhere any more, by the resource its first argument names.
|
|
112
130
|
*/
|
|
113
|
-
const
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
131
|
+
const dropListedSql = (table) => [
|
|
132
|
+
`drop trigger if exists ${rowTrigger} on ${table}`,
|
|
133
|
+
`drop trigger if exists ${truncateTrigger} on ${table}`,
|
|
134
|
+
`do $members$ declare part regclass; begin
|
|
135
|
+
for part in ${partitionsSql(table)} loop
|
|
136
|
+
execute format('drop trigger if exists ${truncateTrigger} on %s', part);
|
|
137
|
+
end loop;
|
|
138
|
+
end $members$`,
|
|
139
|
+
`delete from ${realtimeMembersTable} m where not exists (select from pg_trigger t where t.tgname = '${rowTrigger}' and t.tgparentid = 0
|
|
140
|
+
and t.tgfoid = '${realtimeSchema}.members_kept()'::regprocedure and convert_from(substring(t.tgargs from 1 for position('\\x00'::bytea in t.tgargs) - 1), 'UTF8') = m.resource)`
|
|
118
141
|
];
|
|
119
142
|
//#endregion
|
|
120
|
-
export { argsOf, listedTable, membersComment,
|
|
143
|
+
export { argsOf, dropListedSql, listedTable, listedTableSql, membersComment, membersFunctionsSql, membersTableSql, realtimeMembersTable, realtimeSchema, rowTrigger, truncateTrigger };
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { qualified } from "../notifications/schema-sql.js";
|
|
2
|
+
import { sessionsSql } from "./sessions-sql.js";
|
|
3
|
+
import { dropListedSql, listedTableSql, membersFunctionsSql, membersTableSql } from "./realtime-members-sql.js";
|
|
4
|
+
import { readRelay } from "./read-relay.js";
|
|
5
|
+
//#region src/relay/relay-module.ts
|
|
6
|
+
const statements = (list) => `${list.join(";\n\n")};`;
|
|
7
|
+
/** The triggers that keep `realtime.members` from one channel resource's records that list their members. */
|
|
8
|
+
const members = {
|
|
9
|
+
name: "members",
|
|
10
|
+
title: "The triggers that keep realtime.members",
|
|
11
|
+
version: 1,
|
|
12
|
+
compatibleFrom: 1,
|
|
13
|
+
sql: (_names, input) => statements(listedTableSql(input)),
|
|
14
|
+
drop: (_names, table) => statements(dropListedSql(qualified({
|
|
15
|
+
schema: table.schema,
|
|
16
|
+
table: table.name
|
|
17
|
+
}))),
|
|
18
|
+
keptWhileOthers: false
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* What the realtime relay needs of the app's database: the trigger that closes a deleted sign-in session's sockets, on
|
|
22
|
+
* the sessions table the auth store names (`names.sessions`, as SQL names it), which queues a job, so it is written
|
|
23
|
+
* after the auth store's steps and the jobs schema; and `realtime.members` with the triggers that keep it from the
|
|
24
|
+
* channel records that list their members. Its table is never dropped.
|
|
25
|
+
*/
|
|
26
|
+
const relayModule = {
|
|
27
|
+
label: "the realtime relay",
|
|
28
|
+
title: "The trigger that closes a deleted sign-in session's sockets on the realtime relay, and realtime.members with the triggers that keep it from the channel records that list their members",
|
|
29
|
+
steps: [{
|
|
30
|
+
step: 1,
|
|
31
|
+
name: "members",
|
|
32
|
+
title: "The realtime.members table",
|
|
33
|
+
additive: true,
|
|
34
|
+
sql: () => statements(membersTableSql)
|
|
35
|
+
}],
|
|
36
|
+
replaceables: [{
|
|
37
|
+
name: "sessions",
|
|
38
|
+
title: "The trigger that closes a deleted session's sockets",
|
|
39
|
+
version: 1,
|
|
40
|
+
compatibleFrom: 1,
|
|
41
|
+
sql: (names) => statements(sessionsSql(names.sessions))
|
|
42
|
+
}, {
|
|
43
|
+
name: "members",
|
|
44
|
+
title: "The functions that keep realtime.members",
|
|
45
|
+
version: 3,
|
|
46
|
+
compatibleFrom: 3,
|
|
47
|
+
sql: () => statements(membersFunctionsSql)
|
|
48
|
+
}],
|
|
49
|
+
resourceReplaceables: [members],
|
|
50
|
+
read: readRelay(members)
|
|
51
|
+
};
|
|
52
|
+
//#endregion
|
|
53
|
+
export { relayModule };
|