@protobase/server 0.132.1 → 0.132.3

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/package.js CHANGED
@@ -1,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "0.132.1";
2
+ var version = "0.132.3";
3
3
  //#endregion
4
4
  export { version };
@@ -38,22 +38,32 @@ const membersCommands = (models, change) => (models.members.get(change.resource)
38
38
  users: [before.user]
39
39
  }] : []];
40
40
  });
41
- const listedIn = (listed, record) => {
41
+ const reachesOrganization = (listed, record) => listed.tenant !== void 0 && !present(record[listed.field]) && !(listed.model.softDelete !== void 0 && present(record[listed.model.softDelete]));
42
+ /** The organizations whose members a batch's channel records reach, before or after their change, which `membersOf` reads. */
43
+ const organizationsNoticed = (models, changes) => {
44
+ const found = changes.flatMap((change) => {
45
+ const listed = models.channels.get(change.resource)?.listed;
46
+ if (!listed?.tenant) return [];
47
+ return [change.before, change.after].flatMap((record) => record && reachesOrganization(listed, record) && present(record[listed.tenant]) ? [String(record[listed.tenant])] : []);
48
+ });
49
+ return [...new Set(found)];
50
+ };
51
+ const listedIn = (listed, record, organizations) => {
42
52
  if (!record) return;
43
53
  const value = record[listed.field];
44
54
  const deleted = listed.model.softDelete !== void 0 && present(record[listed.model.softDelete]);
45
- const users = Array.isArray(value) && !deleted ? value.filter(present).map(String) : [];
55
+ const users = reachesOrganization(listed, record) ? organizations.get(String(record[listed.tenant])) ?? [] : Array.isArray(value) && !deleted ? value.filter(present).map(String) : [];
46
56
  return {
47
57
  channel: channelName(listed.model.name, record[listed.model.primaryKey[0]]),
48
58
  users: new Set(users)
49
59
  };
50
60
  };
51
61
  const missing = (from, other) => [...from ?? []].filter((user) => !other?.has(user));
52
- const listedCommands = (models, change) => {
62
+ const listedCommands = (models, change, organizations) => {
53
63
  const listed = models.channels.get(change.resource)?.listed;
54
64
  if (!listed) return [];
55
- const before = change.operation === "create" || change.operation === "undelete" ? void 0 : listedIn(listed, change.before);
56
- const after = change.operation === "delete" ? void 0 : listedIn(listed, change.after);
65
+ const before = change.operation === "create" || change.operation === "undelete" ? void 0 : listedIn(listed, change.before, organizations);
66
+ const after = change.operation === "delete" ? void 0 : listedIn(listed, change.after, organizations);
57
67
  const moved = before && after && before.channel !== after.channel;
58
68
  const added = after ? missing(after.users, moved ? void 0 : before?.users) : [];
59
69
  const removed = before ? missing(before.users, moved ? void 0 : after?.users) : [];
@@ -93,6 +103,7 @@ const notice = (models, change, channel, members, moved) => {
93
103
  }
94
104
  };
95
105
  };
106
+ /** Tells only the people added to a channel, on `people`, which channel it is: nobody else learns who joined what. */
96
107
  const joinedCommand = (sequence, add) => ({
97
108
  kind: "publish",
98
109
  id: `${sequence}:${add.channel}:${joinedEvent}`,
@@ -107,10 +118,12 @@ const reaches = (command, open) => command.users === void 0 ? open.has(command.c
107
118
  * first and hears `joined` of it on `people`, then each channel the record was or is on hears one notice, then a person
108
119
  * who left it leaves. A channel with members hears it only through its members as the app's database has them
109
120
  * (`members`), and the person who joined or left; an open one through everyone joined to it, and only while its record is public (`open`), so sockets that joined
110
- * it before hear nothing once it is not. A notice of a channel with no one to reach is left out.
121
+ * it before hear nothing once it is not. A record that reaches its whole organization, before or after its change,
122
+ * moves its organization's members (`organizations`) as a list moves the people it lists. A notice of a channel with no
123
+ * one to reach is left out.
111
124
  */
112
- const changeCommands = (models, changes, members, open) => changes.flatMap((change) => {
113
- const moved = [...membersCommands(models, change), ...listedCommands(models, change)];
125
+ const changeCommands = (models, changes, members, open, organizations = /* @__PURE__ */ new Map()) => changes.flatMap((change) => {
126
+ const moved = [...membersCommands(models, change), ...listedCommands(models, change, organizations)];
114
127
  const notices = noticedChannels(models, change).map((channel) => notice(models, change, channel, members, moved)).filter((command) => reaches(command, open));
115
128
  return [
116
129
  ...moved.filter((command) => command.kind === "add").flatMap((add) => [add, joinedCommand(change.sequence, add)]),
@@ -119,4 +132,4 @@ const changeCommands = (models, changes, members, open) => changes.flatMap((chan
119
132
  ];
120
133
  });
121
134
  //#endregion
122
- export { audienceChannels, changeCommands, changeEvent, channelName, joinedEvent, noticedChannels, openChannels };
135
+ export { audienceChannels, changeCommands, changeEvent, channelName, joinedCommand, joinedEvent, noticedChannels, openChannels, organizationsNoticed };
@@ -0,0 +1,67 @@
1
+ import { channelName, organizationsNoticed } from "./change-commands.js";
2
+ import { organizationChannels, organizationWide, organizationsReached } from "./organization-channels-sql.js";
3
+ import { membersOf, organizationResources, organizationsOf } from "./organization-members.js";
4
+ //#region src/relay/organization-audience.ts
5
+ const none = () => ({
6
+ channels: /* @__PURE__ */ new Map(),
7
+ organizations: /* @__PURE__ */ new Map()
8
+ });
9
+ /**
10
+ * Of the named channels, those whose records reach their whole organization as they stand now, with its members; and
11
+ * the members of every organization the batch's records reach before or after their change, in the caller's
12
+ * transaction.
13
+ */
14
+ const organizationAudience = async (db, models, store, changes, channels) => {
15
+ const resources = organizationResources(models);
16
+ if (!store || resources.length === 0) return none();
17
+ const named = resources.flatMap(([resource, listed]) => {
18
+ const keys = channels.filter((channel) => channel.startsWith(`${resource}/`)).map((channel) => channel.slice(resource.length + 1));
19
+ return keys.length > 0 ? [{
20
+ resource,
21
+ listed,
22
+ keys
23
+ }] : [];
24
+ });
25
+ const wide = named.length > 0 ? (await organizationWide(named).execute(db)).rows : [];
26
+ const organizations = await membersOf(db, store, [.../* @__PURE__ */ new Set([...wide.map((row) => row.organization), ...organizationsNoticed(models, changes)])]);
27
+ return {
28
+ channels: new Map(wide.map((row) => [channelName(row.resource, row.channel), organizations.get(row.organization) ?? []])),
29
+ organizations
30
+ };
31
+ };
32
+ /** The channels whose records reach a whole organization the person is a member of: what their ticket lists beside their listed channels. */
33
+ const organizationMemberships = async (db, models, store, user) => {
34
+ const resources = organizationResources(models);
35
+ if (!store || resources.length === 0) return [];
36
+ const organizations = (await organizationsOf(db, store, [user])).get(user) ?? [];
37
+ if (organizations.length === 0) return [];
38
+ const { rows } = await organizationChannels(resources, organizations).execute(db);
39
+ return rows.map((row) => channelName(row.resource, row.channel));
40
+ };
41
+ /**
42
+ * By person, the members of each organization of theirs with a channel that reaches it, themselves included: who
43
+ * shares such a channel with them, and so hears of their presence.
44
+ */
45
+ const organizationCoMembers = async (db, models, store, people) => {
46
+ const found = /* @__PURE__ */ new Map();
47
+ const resources = organizationResources(models);
48
+ if (!store || resources.length === 0 || people.length === 0) return found;
49
+ const theirs = await organizationsOf(db, store, people);
50
+ const organizations = [...new Set([...theirs.values()].flat())];
51
+ if (organizations.length === 0) return found;
52
+ const { rows } = await organizationsReached(resources, organizations).execute(db);
53
+ const reached = await membersOf(db, store, rows.map((row) => row.organization));
54
+ for (const [person, joined] of theirs) {
55
+ const others = joined.flatMap((organization) => reached.get(organization) ?? []);
56
+ if (others.length > 0) found.set(person, others);
57
+ }
58
+ return found;
59
+ };
60
+ /** Two audiences by key as one, each key's people once. */
61
+ const mergedAudience = (a, b) => {
62
+ const merged = new Map(a);
63
+ for (const [key, people] of b) merged.set(key, [.../* @__PURE__ */ new Set([...merged.get(key) ?? [], ...people])]);
64
+ return merged;
65
+ };
66
+ //#endregion
67
+ export { mergedAudience, organizationAudience, organizationCoMembers, organizationMemberships };
@@ -0,0 +1,17 @@
1
+ import { quoteIdent, tableSql } from "../changes/capture-sql.js";
2
+ import { sql } from "kysely";
3
+ //#region src/relay/organization-channels-sql.ts
4
+ const column = (listed, field) => sql.raw(quoteIdent(listed.model.fields[field].column));
5
+ const open = (listed) => {
6
+ const deleted = listed.model.softDelete;
7
+ return deleted === void 0 ? sql`${column(listed, listed.field)} is null` : sql`${column(listed, listed.field)} is null and ${column(listed, deleted)} is null`;
8
+ };
9
+ const select = (resource, listed) => sql`select ${resource}::text as resource, ${column(listed, listed.model.primaryKey[0])}::text as channel, ${column(listed, listed.tenant)}::text as organization from ${sql.raw(tableSql(listed.model))}`;
10
+ /** The channels of these resources' records in these organizations that reach the whole organization, by the tenant column's index. */
11
+ const organizationChannels = (resources, organizations) => sql`${sql.join(resources.map(([resource, listed]) => sql`${select(resource, listed)} where ${column(listed, listed.tenant)} = any(${organizations}) and ${open(listed)}`), sql` union all `)}`;
12
+ /** Of the named records of each resource, by key, those that reach their whole organization, with it. */
13
+ const organizationWide = (named) => sql`${sql.join(named.map(({ resource, listed, keys }) => sql`${select(resource, listed)} where ${column(listed, listed.model.primaryKey[0])} = any(${keys}) and ${open(listed)}`), sql` union all `)}`;
14
+ /** Of these organizations, those with a record of these resources that reaches the whole organization. */
15
+ const organizationsReached = (resources, organizations) => sql`select distinct organization from (${organizationChannels(resources, organizations)}) as reached`;
16
+ //#endregion
17
+ export { organizationChannels, organizationWide, organizationsReached };
@@ -0,0 +1,73 @@
1
+ import { jobsSchema } from "../jobs/schema.js";
2
+ import { quoteIdent } from "../changes/capture-sql.js";
3
+ import { relaySchema } from "./sessions-sql.js";
4
+ import { sql } from "kysely";
5
+ //#region src/relay/organization-members-sql.ts
6
+ /** The job a change of who is in an organization queues, which moves them in or out of its organization-wide channels. */
7
+ const organizationMembersJob = "relay.organization-members";
8
+ /** The triggers on the member table: one each for inserts, updates and deletes, as a trigger with transition tables takes one event. */
9
+ const memberTriggers = {
10
+ insert: "relay_member_added",
11
+ update: "relay_member_moved",
12
+ delete: "relay_member_removed"
13
+ };
14
+ const functionName = `${relaySchema}.organization_members_changed()`;
15
+ /**
16
+ * The function's comment: its version and the member table's columns its body reads, so a function written for other
17
+ * column names reads as one to write again.
18
+ */
19
+ const memberFunctionComment = ({ organization, user }) => `Protobase relay organization members 1: ${organization}, ${user}`;
20
+ const literal = (text) => `'${text.replaceAll("'", "''")}'`;
21
+ /**
22
+ * The function and triggers that queue one `relay.organization-members` job for each statement that changes who is in
23
+ * an organization, in its transaction, with each `{ organization, user }` it puts in or takes out, whatever wrote it:
24
+ * an invitation accepted, a member removed, an organization or user deleted, or SQL. An update queues only the pairs
25
+ * it changes, so a new role queues nothing. The job reads who is a member as it stands, so a pair names only whom to
26
+ * look at again.
27
+ */
28
+ const memberTableSql = (member) => {
29
+ const { table, organization, user } = member;
30
+ const pairs = (from) => `select ${quoteIdent(organization)}::text as organization, ${quoteIdent(user)}::text as "user" from ${from}`;
31
+ const aggregate = (from) => `select jsonb_agg(distinct jsonb_build_object('organization', p.organization, 'user', p."user")) into moved from (${from}) as p`;
32
+ return [
33
+ `create schema if not exists ${relaySchema}`,
34
+ `create or replace function ${functionName} returns trigger
35
+ language plpgsql as $$
36
+ declare
37
+ moved jsonb;
38
+ begin
39
+ if tg_op = 'INSERT' then
40
+ ${aggregate(pairs("added"))};
41
+ elsif tg_op = 'DELETE' then
42
+ ${aggregate(pairs("removed"))};
43
+ else
44
+ ${aggregate(`(${pairs("added")} except ${pairs("removed")}) union (${pairs("removed")} except ${pairs("added")})`)};
45
+ end if;
46
+ if moved is not null then
47
+ perform ${jobsSchema}.enqueue('${organizationMembersJob}', jsonb_build_object('members', moved));
48
+ end if;
49
+ return null;
50
+ end
51
+ $$`,
52
+ `comment on function ${functionName} is ${literal(memberFunctionComment(member))}`,
53
+ ...Object.values(memberTriggers).map((name) => `drop trigger if exists ${name} on ${table}`),
54
+ `create trigger ${memberTriggers.insert} after insert on ${table} referencing new table as added for each statement execute function ${functionName}`,
55
+ `create trigger ${memberTriggers.update} after update on ${table} referencing old table as removed new table as added for each statement execute function ${functionName}`,
56
+ `create trigger ${memberTriggers.delete} after delete on ${table} referencing old table as removed for each statement execute function ${functionName}`
57
+ ];
58
+ };
59
+ /** Drops the triggers from the member table, then the function once no trigger calls it. */
60
+ const dropMemberTableSql = (table) => [...Object.values(memberTriggers).map((name) => `drop trigger if exists ${name} on ${table}`), `drop function if exists ${functionName}`];
61
+ /**
62
+ * The tables the triggers stand on, by schema and name, each with whether all three are there and fire (`complete`),
63
+ * and the comment of the function they call, which `memberFunctionComment` writes. Only reads the catalogue.
64
+ */
65
+ const memberTriggersFound = async (db) => (await sql`select n.nspname as schema, c.relname as name, c.oid::regclass::text as "table",
66
+ count(distinct t.tgname) = ${Object.keys(memberTriggers).length} and bool_and(t.tgenabled in ('O', 'A')) as complete,
67
+ max(obj_description(p.oid, 'pg_proc')) as comment
68
+ from pg_trigger t join pg_proc p on p.oid = t.tgfoid join pg_namespace pn on pn.oid = p.pronamespace
69
+ join pg_class c on c.oid = t.tgrelid join pg_namespace n on n.oid = c.relnamespace
70
+ where pn.nspname = ${relaySchema} and p.proname = 'organization_members_changed' and t.tgname = any(${Object.values(memberTriggers)}::text[])
71
+ group by n.nspname, c.relname, c.oid`.execute(db)).rows;
72
+ //#endregion
73
+ export { dropMemberTableSql, memberFunctionComment, memberTableSql, memberTriggers, memberTriggersFound, organizationMembersJob };
@@ -0,0 +1,48 @@
1
+ import { quoteIdent } from "../changes/capture-sql.js";
2
+ import { unscoped } from "@protobase/query";
3
+ import { sql } from "kysely";
4
+ //#region src/relay/organization-members.ts
5
+ const everyOrganization$1 = "the relay reaches the members of the organizations its channels are in";
6
+ /** The channel resources whose records with a null members field reach their organization, each with its listed model. */
7
+ const organizationResources = (models) => [...models.channels].flatMap(([resource, channel]) => channel.listed?.tenant ? [[resource, channel.listed]] : []);
8
+ /**
9
+ * The member table of the store's names when a channel reaches an organization, else undefined; refuses such a channel
10
+ * while organizations are off, as there are no members to reach.
11
+ */
12
+ const organizationMembersOf = (models, names) => {
13
+ const [first] = organizationResources(models);
14
+ if (!first) return;
15
+ const member = names?.tables.member;
16
+ if (!member) throw new Error(`realtime.relay.channels.${first[0]}.members.organization needs organizations (auth.organizations), whose members it reaches`);
17
+ return {
18
+ table: member.schema === void 0 ? member.name : `${member.schema}.${member.name}`,
19
+ organization: member.columns.organization_id.name,
20
+ user: member.columns.user_id.name
21
+ };
22
+ };
23
+ const column = (name) => sql.raw(quoteIdent(name));
24
+ const grouped = (rows) => {
25
+ const found = /* @__PURE__ */ new Map();
26
+ for (const row of rows) {
27
+ const group = found.get(row.by);
28
+ if (group) group.push(row.value);
29
+ else found.set(row.by, [row.value]);
30
+ }
31
+ return found;
32
+ };
33
+ /** By organization, the user ids of its members, through the member table's index by organization. */
34
+ const membersOf = async (db, store, organizations) => {
35
+ if (organizations.length === 0) return /* @__PURE__ */ new Map();
36
+ const { rows } = await sql`select ${column(store.organization)}::text as by, ${column(store.user)}::text as value
37
+ from ${unscoped(everyOrganization$1, store.table)} where ${column(store.organization)} = any(${organizations})`.execute(db);
38
+ return grouped(rows);
39
+ };
40
+ /** By person, the organizations they are a member of, through the member table's index by user. */
41
+ const organizationsOf = async (db, store, users) => {
42
+ if (users.length === 0) return /* @__PURE__ */ new Map();
43
+ const { rows } = await sql`select ${column(store.user)}::text as by, ${column(store.organization)}::text as value
44
+ from ${unscoped(everyOrganization$1, store.table)} where ${column(store.user)} = any(${users})`.execute(db);
45
+ return grouped(rows);
46
+ };
47
+ //#endregion
48
+ export { membersOf, organizationMembersOf, organizationResources, organizationsOf };
@@ -0,0 +1,33 @@
1
+ import { channelName, joinedCommand } from "./change-commands.js";
2
+ import { organizationChannels } from "./organization-channels-sql.js";
3
+ import { organizationResources, organizationsOf } from "./organization-members.js";
4
+ //#region src/relay/organization-moves.ts
5
+ /**
6
+ * The commands that bring each person's sockets in line with whether they are a member of the organization now, read
7
+ * once: someone who is joins every channel of its records that reach the whole organization and hears `joined` of
8
+ * each on `people`; someone who is not leaves them. `id` makes the `joined` notices' ids, so a retry sends the same.
9
+ */
10
+ const organizationMoves = async (db, models, store, pairs, id) => {
11
+ const resources = organizationResources(models);
12
+ if (resources.length === 0 || pairs.length === 0) return [];
13
+ const current = await organizationsOf(db, store, [...new Set(pairs.map((pair) => pair.user))]);
14
+ const { rows } = await organizationChannels(resources, [...new Set(pairs.map((pair) => pair.organization))]).execute(db);
15
+ const channels = /* @__PURE__ */ new Map();
16
+ for (const row of rows) channels.set(row.organization, [...channels.get(row.organization) ?? [], channelName(row.resource, row.channel)]);
17
+ const moves = {
18
+ add: /* @__PURE__ */ new Map(),
19
+ remove: /* @__PURE__ */ new Map()
20
+ };
21
+ for (const { organization, user } of pairs) {
22
+ const kind = current.get(user)?.includes(organization) ? "add" : "remove";
23
+ for (const channel of channels.get(organization) ?? []) moves[kind].set(channel, /* @__PURE__ */ new Set([...moves[kind].get(channel) ?? [], user]));
24
+ }
25
+ const commands = (kind) => [...moves[kind]].map(([channel, users]) => ({
26
+ kind,
27
+ channel,
28
+ users: [...users]
29
+ }));
30
+ return [...commands("add").flatMap((add) => [add, joinedCommand(id, add)]), ...commands("remove")];
31
+ };
32
+ //#endregion
33
+ export { organizationMoves };
@@ -1,4 +1,5 @@
1
1
  import { sessionsCurrent } from "./sessions-sql.js";
2
+ import { memberFunctionComment, memberTriggersFound } from "./organization-members-sql.js";
2
3
  import { argsOf, realtimeMembersTable, realtimeSchema } from "./realtime-members-sql.js";
3
4
  import { resourceEntry } from "../schema-modules/resource-difference.js";
4
5
  import { sql } from "kysely";
@@ -32,13 +33,45 @@ const keeps = (found, listed, rel) => {
32
33
  return [rel, ...row.partitions].every((table) => own.some((trigger) => trigger.table === table && trigger.name === "realtime_members_truncated")) && own.every((trigger) => trigger.enabled);
33
34
  };
34
35
  /**
36
+ * The organization trigger as the database has it for `input`: at the entry it writes when it stands on the member
37
+ * table `input` names with all three triggers, calling the function this version writes for the columns `input` names,
38
+ * at no digest when it is older or reads other columns, so it is written again,
39
+ * and at no digest under the table it is on when that is another table, so it is dropped.
40
+ */
41
+ const readOrganization = async (db, organization, input) => {
42
+ const found = await memberTriggersFound(db);
43
+ const given = input.resources[organization.name]?.member;
44
+ const [rel] = given ? await regclassText(db, [given.input.table]) : [];
45
+ const entries = {};
46
+ for (const trigger of found) {
47
+ if (given && trigger.table === rel) {
48
+ const entry = resourceEntry(organization, input.names, given);
49
+ entries.member = trigger.complete && trigger.comment === memberFunctionComment(given.input) ? entry : {
50
+ ...entry,
51
+ digest: ""
52
+ };
53
+ continue;
54
+ }
55
+ entries[given ? `member on ${trigger.table}` : "member"] = {
56
+ version: organization.version,
57
+ digest: "",
58
+ table: {
59
+ schema: trigger.schema,
60
+ name: trigger.name
61
+ }
62
+ };
63
+ }
64
+ return entries;
65
+ };
66
+ /**
35
67
  * The relay's objects as the database has them for `input`: step 1 once `realtime.members` is there, the sessions
36
68
  * trigger at its version when it stands on the sessions table with this version's function, the members functions at
37
69
  * the version their comment names, and each listed resource whose table has the triggers this version writes, else at
38
70
  * 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.
71
+ * first argument names, so they are dropped; and the organization trigger (`readOrganization`). Refuses members
72
+ * functions of a version no step records.
40
73
  */
41
- const readRelay = (members) => async (db, input) => {
74
+ const readRelay = (members, organization) => async (db, input) => {
42
75
  const [state] = (await sql`select to_regclass(${realtimeMembersTable}) is not null as table,
43
76
  (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
77
  const sessions = await sessionsCurrent(db, input.names.sessions);
@@ -71,6 +104,11 @@ const readRelay = (members) => async (db, input) => {
71
104
  }
72
105
  };
73
106
  }
107
+ const organizationEntries = await readOrganization(db, organization, input);
108
+ const resources = {
109
+ ...Object.keys(entries).length > 0 && { [members.name]: entries },
110
+ ...Object.keys(organizationEntries).length > 0 && { [organization.name]: organizationEntries }
111
+ };
74
112
  return {
75
113
  lastStep: state.table ? 1 : 0,
76
114
  replaceables: {
@@ -78,7 +116,7 @@ const readRelay = (members) => async (db, input) => {
78
116
  ...version !== void 0 && { members: 3 }
79
117
  },
80
118
  names: input.names,
81
- ...Object.keys(entries).length > 0 && { resources: { [members.name]: entries } }
119
+ ...Object.keys(resources).length > 0 && { resources }
82
120
  };
83
121
  };
84
122
  //#endregion
@@ -1,6 +1,7 @@
1
1
  import { defineJob } from "../jobs/define-job.js";
2
- import { RelayRefusal } from "./relay-commands.js";
3
2
  import { closeSessionsJob } from "./sessions-sql.js";
3
+ import { organizationMembersJob } from "./organization-members-sql.js";
4
+ import { RelayRefusal } from "./relay-commands.js";
4
5
  //#region src/relay/relay-jobs.ts
5
6
  /** The group the relay's commands run in, one job at a time, in the order the dispatches queued them. */
6
7
  const sendGroup = "relay";
@@ -13,8 +14,10 @@ const sendGroup = "relay";
13
14
  * - `relay.close-sessions`, which the delete of sign-in sessions queues: it closes their sockets.
14
15
  * - `relay.session-expiry`, queued at a ticket for its sign-in session's expiry: it closes the session's sockets once
15
16
  * it expired or is gone, and waits for the new expiry of one that was extended meanwhile.
17
+ * - `relay.organization-members`, which a change of the auth store's member table queues: it queues the commands that
18
+ * move those people in or out of the organization-wide channels, after the sends queued before it.
16
19
  */
17
- const relayJobs = ({ client, sessionEnd, report }) => {
20
+ const relayJobs = ({ client, sessionEnd, report, moves }) => {
18
21
  const send = defineJob({
19
22
  name: "relay.send",
20
23
  ordered: true,
@@ -55,7 +58,15 @@ const relayJobs = ({ client, sessionEnd, report }) => {
55
58
  jobs: [
56
59
  send,
57
60
  closeSessions,
58
- sessionExpiry
61
+ sessionExpiry,
62
+ defineJob({
63
+ name: organizationMembersJob,
64
+ retryDelay: "5 seconds",
65
+ run: async ({ members }, { db, job }) => {
66
+ const commands = await moves(db, members, job.id);
67
+ if (commands.length > 0) await send.enqueue(db, { commands }, { group: sendGroup });
68
+ }
69
+ })
59
70
  ],
60
71
  /** Queues a dispatch's commands, in its transaction; nothing when it has none. */
61
72
  queue: async (db, commands) => {
@@ -70,11 +81,15 @@ const relayJobs = ({ client, sessionEnd, report }) => {
70
81
  };
71
82
  /**
72
83
  * The relay's jobs while the app can use the relay but does not: `relay.close-sessions`, which the delete of sign-in
73
- * sessions queues all the same, completes at once, as no socket is open on the relay.
84
+ * sessions queues all the same, and `relay.organization-members`, which a change of who is in an organization does,
85
+ * complete at once, as no socket is open on the relay.
74
86
  */
75
87
  const idleRelayJobs = () => [defineJob({
76
88
  name: closeSessionsJob,
77
89
  run: async () => {}
90
+ }), defineJob({
91
+ name: organizationMembersJob,
92
+ run: async () => {}
78
93
  })];
79
94
  //#endregion
80
95
  export { idleRelayJobs, relayJobs };
@@ -19,7 +19,7 @@ const relayModels = (options, models) => {
19
19
  const model = byName.get(name);
20
20
  if (!model) throw new Error(`${at}: the app has no resource "${name}"`);
21
21
  if (model.primaryKey.length !== 1) throw new Error(`${at}: a channel resource needs a key of one field, as a channel is named <resource>/<key>`);
22
- const listed = channel.members && "field" in channel.members ? listedModel(channel.members.field, model, `${at}.members`) : void 0;
22
+ const listed = channel.members && "field" in channel.members ? listedModel(channel.members, model, `${at}.members`) : void 0;
23
23
  if (listed && !captured(model)) throw new Error(`${at}.members: the changes of "${name}" are not captured, so the relay would not hear who joins or leaves: declare .live() on it`);
24
24
  const own = channel.members && !("field" in channel.members) ? membersModel(channel.members, name, byName, `${at}.members`) : void 0;
25
25
  if (own && !captured(own.model)) throw new Error(`${at}.members: the changes of "${own.model.name}" are not captured, so the relay would not hear of them: declare .live() on it`);
@@ -69,13 +69,19 @@ const listedFieldProblem = (model, field) => {
69
69
  if (definition.sensitive) return `"${field}" of "${model.name}" is sensitive, so its changes never reach the relay`;
70
70
  if (model.historyIgnore?.includes(field)) return `"${field}" of "${model.name}" is ignored by its history, so its changes never reach the relay`;
71
71
  };
72
- const listedModel = (field, model, at) => {
72
+ const listedModel = ({ field, organization }, model, at) => {
73
73
  const problem = listedFieldProblem(model, field);
74
74
  if (problem) throw new Error(`${at}.field: ${problem}`);
75
- return {
75
+ if (organization === void 0) return {
76
76
  model,
77
77
  field
78
78
  };
79
+ if (!model.tenant) throw new Error(`${at}.organization: "${model.name}" has no tenant field (.tenant), so a record has no organization to reach`);
80
+ return {
81
+ model,
82
+ field,
83
+ tenant: model.tenant
84
+ };
79
85
  };
80
86
  const membersModel = (members, channel, byName, at) => {
81
87
  const model = byName.get(members.resource);
@@ -1,5 +1,6 @@
1
1
  import { qualified } from "../notifications/schema-sql.js";
2
2
  import { sessionsSql } from "./sessions-sql.js";
3
+ import { dropMemberTableSql, memberTableSql } from "./organization-members-sql.js";
3
4
  import { dropListedSql, listedTableSql, membersFunctionsSql, membersTableSql } from "./realtime-members-sql.js";
4
5
  import { readRelay } from "./read-relay.js";
5
6
  //#region src/relay/relay-module.ts
@@ -18,10 +19,27 @@ const members = {
18
19
  keptWhileOthers: false
19
20
  };
20
21
  /**
22
+ * The trigger on the auth store's member table that moves people in and out of the channels that reach their whole
23
+ * organization, written while a channel resource has such records, under the key `member`.
24
+ */
25
+ const organization = {
26
+ name: "organization",
27
+ title: "The triggers that follow who is in an organization for the relay's organization-wide channels",
28
+ version: 1,
29
+ compatibleFrom: 1,
30
+ sql: (_names, input) => statements(memberTableSql(input)),
31
+ drop: (_names, table) => statements(dropMemberTableSql(qualified({
32
+ schema: table.schema,
33
+ table: table.name
34
+ }))),
35
+ keptWhileOthers: false
36
+ };
37
+ /**
21
38
  * What the realtime relay needs of the app's database: the trigger that closes a deleted sign-in session's sockets, on
22
39
  * the sessions table the auth store names (`names.sessions`, as SQL names it), which queues a job, so it is written
23
40
  * 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.
41
+ * channel records that list their members, and with organization-wide channels the trigger that follows the auth
42
+ * store's member table. Its table is never dropped.
25
43
  */
26
44
  const relayModule = {
27
45
  label: "the realtime relay",
@@ -46,8 +64,8 @@ const relayModule = {
46
64
  compatibleFrom: 3,
47
65
  sql: () => statements(membersFunctionsSql)
48
66
  }],
49
- resourceReplaceables: [members],
50
- read: readRelay(members)
67
+ resourceReplaceables: [members, organization],
68
+ read: readRelay(members, organization)
51
69
  };
52
70
  //#endregion
53
71
  export { relayModule };
@@ -16,6 +16,12 @@ export type RelayMembers = {
16
16
  export type RelayListedMembers = {
17
17
  /** The channel resource's JSON field listing its members' user ids, such as `members`. */
18
18
  field: string;
19
+ /**
20
+ * `'when-null'`: a record whose field is null reaches every member of its tenant's organization, such as a public
21
+ * channel beside private ones that list their members; an empty list still reaches nobody. Needs a `.tenant` resource
22
+ * and organizations.
23
+ */
24
+ organization?: 'when-null';
19
25
  };
20
26
  /** A resource whose records are channels on the relay, `<resource>/<key>`. */
21
27
  export type RelayChannelOptions = {
@@ -41,7 +41,10 @@ const checkEvents = (where, events) => {
41
41
  const membersShape = (members) => {
42
42
  if (members === void 0) return true;
43
43
  if (typeof members !== "object" || members === null) return false;
44
- if ("field" in members) return nonEmpty(members.field) && Object.keys(members).length === 1;
44
+ if ("field" in members) {
45
+ const { field, organization, ...rest } = members;
46
+ return nonEmpty(field) && (organization === void 0 || organization === "when-null") && Object.keys(rest).length === 0;
47
+ }
45
48
  return nonEmpty(members.resource) && nonEmpty(members.channel) && nonEmpty(members.user);
46
49
  };
47
50
  /** The options, or an error naming what is wrong with their shape; `relayModels` checks them against the resources. */
@@ -54,7 +57,7 @@ const checkRelayOptions = (options) => {
54
57
  }
55
58
  if (typeof options.channels !== "object" || options.channels === null || Object.keys(options.channels).length === 0) throw new Error("realtime.relay.channels must name at least one channel resource");
56
59
  for (const [name, channel] of Object.entries(options.channels)) {
57
- if (!membersShape(channel?.members)) throw new Error(`realtime.relay.channels.${name}.members must be { resource, channel, user } or { field }`);
60
+ if (!membersShape(channel?.members)) throw new Error(`realtime.relay.channels.${name}.members must be { resource, channel, user } or { field, organization?: 'when-null' }`);
58
61
  if (channel?.mentions !== void 0 && !nonEmpty(channel.mentions)) throw new Error(`realtime.relay.channels.${name}.mentions must name a field`);
59
62
  if (channel?.events !== void 0) checkEvents(`realtime.relay.channels.${name}.events`, channel.events);
60
63
  }
@@ -8,6 +8,9 @@ import { readableKeys } from "../channels/records-readable.js";
8
8
  import { presenceCommands, presencePeople } from "./presence-commands.js";
9
9
  import { audienceChannels, changeCommands, openChannels } from "./change-commands.js";
10
10
  import { channelMembers, coMembers } from "./members-sql.js";
11
+ import { organizationMembersOf } from "./organization-members.js";
12
+ import { mergedAudience, organizationAudience, organizationCoMembers } from "./organization-audience.js";
13
+ import { organizationMoves } from "./organization-moves.js";
11
14
  import { presenceRoutes } from "./presence-route.js";
12
15
  import { presenceWriter } from "./presence-sql.js";
13
16
  import { publicChannels } from "./public-channels.js";
@@ -22,17 +25,23 @@ import { ticketRoutes } from "./ticket-route.js";
22
25
  const relayRuntime = (options, auth, deps) => {
23
26
  if (!auth) throw new Error("relay needs the app's own sign-in (auth), whose sessions its tickets name and end");
24
27
  const models = relayModels(options, deps.registry.entries.map((entry) => entry.model));
28
+ const organizations = organizationMembersOf(models, auth.names);
25
29
  const ends = sessionEnd(auth);
30
+ const moves = async (db, pairs, id) => organizations ? organizationMoves(db, models, organizations, pairs, id) : [];
26
31
  const jobs = relayJobs({
27
32
  client: relayClient(options),
28
33
  sessionEnd: ends,
29
- report: (error) => deps.report(error)
34
+ report: (error) => deps.report(error),
35
+ moves
30
36
  });
31
37
  const onChanges = async (trx, changes) => {
32
- const members = await channelMembers(trx, models, audienceChannels(models, changes));
38
+ const channels = audienceChannels(models, changes);
39
+ const wide = await organizationAudience(trx, models, organizations, changes, channels);
40
+ const members = mergedAudience(await channelMembers(trx, models, channels), wide.channels);
33
41
  const open = await publicChannels(deps.registry, (entry, keys) => readableKeys(deps, trx, anonymousSession(), entry, keys), openChannels(models, changes));
34
- const present = await coMembers(trx, models, presencePeople(models, changes));
35
- await jobs.queue(trx, [...changeCommands(models, changes, members, open), ...presenceCommands(models, changes, present)]);
42
+ const people = presencePeople(models, changes);
43
+ const present = mergedAudience(await coMembers(trx, models, people), await organizationCoMembers(trx, models, organizations, people));
44
+ await jobs.queue(trx, [...changeCommands(models, changes, members, open, wide.organizations), ...presenceCommands(models, changes, present)]);
36
45
  };
37
46
  const presenceApp = (key, presence) => {
38
47
  const write = presenceWriter(deps.db, presence);
@@ -61,6 +70,7 @@ const relayRuntime = (options, auth, deps) => {
61
70
  deps,
62
71
  options,
63
72
  models,
73
+ organizations,
64
74
  jobs,
65
75
  sessionEnd: ends
66
76
  }),
@@ -1,14 +1,31 @@
1
1
  import { relayModels } from "./relay-models.js";
2
2
  import { listedTable } from "./realtime-members-sql.js";
3
+ import { organizationMembersOf } from "./organization-members.js";
3
4
  //#region src/relay/relay-targets.ts
5
+ const memberInput = (table) => {
6
+ const input = {
7
+ table: String(table),
8
+ organization: table.columns.organization_id.name,
9
+ user: table.columns.user_id.name
10
+ };
11
+ return {
12
+ table: {
13
+ ...table.schema !== void 0 && { schema: table.schema },
14
+ name: table.name
15
+ },
16
+ input
17
+ };
18
+ };
4
19
  /**
5
20
  * What the relay module takes from the app for its channels (`appRelayChannels`): the sessions table of the auth store
6
- * `store` names, as SQL names it, and each channel resource whose records list their members, by its table. Refuses an
7
- * app without its own sign-in, whose sessions the relay's tickets name and end.
21
+ * `store` names, as SQL names it, each channel resource whose records list their members, by its table, and the store's
22
+ * member table under `member` when a channel's records reach their whole organization. Refuses an app without its own
23
+ * sign-in, whose sessions the relay's tickets name and end, and organization-wide channels without organizations.
8
24
  */
9
25
  const relayInput = (channels, models, store) => {
10
26
  if (!store) throw new Error("relay needs the app's own sign-in (auth), whose sessions its tickets name and end");
11
- const listed = [...relayModels({ channels }, models).channels.values()].flatMap((channel) => channel.listed ? [channel.listed] : []);
27
+ const relay = relayModels({ channels }, models);
28
+ const listed = [...relay.channels.values()].flatMap((channel) => channel.listed ? [channel.listed] : []);
12
29
  const members = Object.fromEntries(listed.map((one) => {
13
30
  const { table } = one.model;
14
31
  return [one.model.name, {
@@ -19,9 +36,13 @@ const relayInput = (channels, models, store) => {
19
36
  input: listedTable(one)
20
37
  }];
21
38
  }));
39
+ const organization = organizationMembersOf(relay, store.names) && { organization: { member: memberInput(store.names.table("member")) } };
22
40
  return {
23
41
  names: { sessions: String(store.names.table("session")) },
24
- resources: { members }
42
+ resources: {
43
+ members,
44
+ ...organization
45
+ }
25
46
  };
26
47
  };
27
48
  //#endregion
@@ -6,6 +6,7 @@ import { jsonBody, jsonOnly } from "../notifications/history-request.js";
6
6
  import { hasMembers } from "./relay-models.js";
7
7
  import { peopleChannel } from "./presence-commands.js";
8
8
  import { memberships } from "./members-sql.js";
9
+ import { organizationMemberships } from "./organization-audience.js";
9
10
  import { signTicket } from "./ticket.js";
10
11
  import { Hono } from "hono";
11
12
  import { bodyLimit } from "hono/body-limit";
@@ -30,12 +31,13 @@ const requestedChannels = (body) => {
30
31
  * channels it lists, the same list as its claims. A signed-in person's ticket names their sign-in session, so a device
31
32
  * that connects adds no session, and lists every channel they are a member of, as the members resources have it, and
32
33
  * `people`, which every signed-in person has and their contacts' presence is published on; a visitor's names an
33
- * anonymous session of its own and only receives. Both list the open channels asked for whose records are public, read
34
+ * anonymous session of its own and only receives. A channel whose record reaches its whole organization counts as one
35
+ * they are a member of in each organization they are a member of. Both list the open channels asked for whose records are public, read
34
36
  * by the anonymous role, as a read of the record decides it; one there is none of, one that is not public and one of a
35
37
  * resource with members are refused alike with `404`. A signed-in person's ticket queues the close of their session's
36
38
  * sockets at its expiry, once for each session.
37
39
  */
38
- const ticketRoutes = ({ deps, options, models, jobs, sessionEnd }) => {
40
+ const ticketRoutes = ({ deps, options, models, organizations, jobs, sessionEnd }) => {
39
41
  const app = new Hono();
40
42
  const openChannel = async (name) => {
41
43
  const slash = name.indexOf("/");
@@ -74,7 +76,11 @@ const ticketRoutes = ({ deps, options, models, jobs, sessionEnd }) => {
74
76
  const open = [];
75
77
  for (const name of asked) open.push(await openChannel(name));
76
78
  const subject = await subjectOf(session);
77
- const member = "user" in subject ? [peopleChannel, ...await memberships(deps.db, models, subject.user)] : [];
79
+ const member = "user" in subject ? [
80
+ peopleChannel,
81
+ ...await memberships(deps.db, models, subject.user),
82
+ ...await organizationMemberships(deps.db, models, organizations, subject.user)
83
+ ] : [];
78
84
  const channels = [.../* @__PURE__ */ new Set([...member, ...open])];
79
85
  if (channels.length > 200) throw new HttpProblem(422, "too-many-channels", "Unprocessable Content", `The ticket would list ${channels.length} channels, over the 200 the relay takes`);
80
86
  const { ticket, expiresAt } = await signTicket(options, subject, channels);
@@ -6,8 +6,10 @@ import { deleteErrors, readsDeleteCondition } from "./view-conversation-delete.j
6
6
  import { reactionsErrors, readsReactions } from "./view-conversation-reactions.js";
7
7
  import { readsThreads, threadErrors } from "./view-conversation-thread.js";
8
8
  import { messageFieldsProblems, messageTextProblems } from "@protobase/layout";
9
+ import { textPlaceholders } from "@protobase/schema/internal";
9
10
  //#region src/view-conversation-page.ts
10
11
  const datedTypes = ["date", "timestamp"];
12
+ const recordTextErrors = (prop, text, record) => textPlaceholders(text ?? "").filter((name) => !Object.hasOwn(record.fields, name)).map((name) => `${prop}: names field "${name}", which ${record.name} does not have`);
11
13
  const authorErrors = (model) => {
12
14
  if (model.author === void 0) return [`${model.name} has no .author(), so it cannot keep each reader's own position`];
13
15
  return model.fields[model.author]?.filterable ? [] : [`"${model.author}" on ${model.name} is not filterable, so a reader's own position cannot be found`];
@@ -54,6 +56,8 @@ const conversationPageErrors = (page, resource, models) => {
54
56
  ...typedErrors(target, "mentions", page.mentions, ["json"], "mentions are a JSON field of user ids"),
55
57
  ...typedErrors(record, "subtitle", page.subtitle, ["text"], "a subtitle is a text field"),
56
58
  ...typedErrors(record, "members", page.members, ["json"], "members are a JSON field of user ids"),
59
+ ...recordTextErrors("placeholder", page.placeholder, record),
60
+ ...recordTextErrors("empty", page.empty, record),
57
61
  ...page.readPosition ? readPositionErrors(page.readPosition, resource, target, models).map((error) => `readPosition: ${error}`) : [],
58
62
  ...page.reactions ? reactionsErrors(page.reactions, page.resource, models).map((error) => `reactions: ${error}`) : [],
59
63
  ...page.attachments ? attachmentsErrors(page.attachments, page.resource, models).map((error) => `attachments: ${error}`) : [],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/server",
3
- "version": "0.132.1",
3
+ "version": "0.132.3",
4
4
  "description": "The Protobase REST API as a Hono app, with Better Auth sign-in.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -44,11 +44,11 @@
44
44
  "@better-auth/sso": "^1.7.12",
45
45
  "@livekit/protocol": "1.53.1",
46
46
  "@modelcontextprotocol/server": "^2.3.1",
47
- "@protobase/layout": "0.132.1",
48
- "@protobase/query": "0.132.1",
49
- "@protobase/schema": "0.132.1",
50
- "@protobase/workflow-plugins": "0.132.1",
51
- "@protobase/workflows": "0.132.1",
47
+ "@protobase/layout": "0.132.3",
48
+ "@protobase/query": "0.132.3",
49
+ "@protobase/schema": "0.132.3",
50
+ "@protobase/workflow-plugins": "0.132.3",
51
+ "@protobase/workflows": "0.132.3",
52
52
  "@react-email/render": "^2.1.0",
53
53
  "@react-pdf/primitives": "^4.4.0",
54
54
  "@react-pdf/renderer": "^4.9.1",