@heybejs/core 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@heybejs/core",
3
- "version": "1.2.0",
3
+ "version": "1.3.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "exports": "./src/index.ts",
@@ -1,11 +1,12 @@
1
1
  import type { Router } from "../router";
2
+ import { needsInstaller } from "./installer";
2
3
 
3
4
  const PROXY_HEADERS = ["CF-Connecting-IP", "Fly-Client-IP", "X-Forwarded-For"];
4
5
 
5
6
  // PB apis/health.go
6
7
  export function registerHealthRoutes(router: Router): void {
7
8
  router.route("GET", "/api/health", (e) => {
8
- let data = {};
9
+ let data: Record<string, unknown> = {};
9
10
  if (e.hasSuperuserAuth()) {
10
11
  const headers = [
11
12
  ...e.app.settings.current().trustedProxy.headers,
@@ -18,6 +19,7 @@ export function registerHealthRoutes(router: Router): void {
18
19
  headers.find((h) => (e.req.headers.get(h) ?? "") !== "") ?? "",
19
20
  };
20
21
  }
22
+ if (needsInstaller(e.app)) data.needsSetup = true;
21
23
  return e.json(200, { message: "API is healthy.", code: 200, data });
22
24
  });
23
25
  }
@@ -5,7 +5,7 @@ import { internalRecords } from "../../records/internal";
5
5
 
6
6
  const TOKEN_DURATION_SECONDS = 30 * 60;
7
7
 
8
- function needsInstaller(app: App): boolean {
8
+ export function needsInstaller(app: App): boolean {
9
9
  const row = app.db.get<{ total: number }>(
10
10
  "SELECT COUNT(*) AS total FROM _superusers WHERE email != ?",
11
11
  [INSTALLER_EMAIL],
@@ -36,9 +36,6 @@ export const isSameAuth = (a: AuthState | null, b: AuthState | null) =>
36
36
  a.record.id === b.record.id &&
37
37
  a.collection.id === b.collection.id;
38
38
 
39
- const dryCacheKey = (action: Action, record: RecordModel) =>
40
- `${action}/${record.collection.name}/${record.id}`;
41
-
42
39
  // PB realtimeCanAccessRecord: the rule (null is superuser only), then the subscription filter.
43
40
  function canAccess(
44
41
  app: App,
@@ -71,7 +68,7 @@ function canAccess(
71
68
  }
72
69
  }
73
70
 
74
- // canAccess, run against the committed data for the delete messages
71
+ // canAccess, run against the committed data for the messages built before a write
75
72
  type Access = (
76
73
  c: Collection,
77
74
  id: string,
@@ -79,6 +76,11 @@ type Access = (
79
76
  info: RequestInfo,
80
77
  ) => boolean;
81
78
 
79
+ const committedAccess =
80
+ (app: App): Access =>
81
+ (...args) =>
82
+ app.db.committed(() => canAccess(app, ...args));
83
+
82
84
  async function message(
83
85
  app: App,
84
86
  access: Access,
@@ -122,17 +124,16 @@ async function message(
122
124
  return { name: topic, data: JSON.stringify({ record: json, action }) };
123
125
  }
124
126
 
125
- // PB realtimeBroadcastRecord: one message per matching subscription the client may read; with
126
- // `dryCache` they are kept on the client under the delete key instead of sent.
127
- async function broadcastRecord(
128
- app: App,
129
- action: Action,
130
- record: RecordModel,
131
- dryCache: boolean,
132
- access: Access,
133
- ): Promise<void> {
134
- const clients = app.realtime.clients();
135
- if (clients.length === 0) return;
127
+ interface Target {
128
+ client: Client;
129
+ topic: string;
130
+ rule: string | null;
131
+ info: RequestInfo;
132
+ auth: AuthState | null;
133
+ }
134
+
135
+ // every subscription of every client that points at the record, with the rule that guards it
136
+ function targetsOf(app: App, record: RecordModel): Target[] {
136
137
  const c = record.collection;
137
138
  const id = record.id;
138
139
  const topics: [string, string | null][] = [
@@ -143,47 +144,100 @@ async function broadcastRecord(
143
144
  [`${c.name}?`, c.listRule],
144
145
  [`${c.id}?`, c.listRule],
145
146
  ];
146
- const key = dryCacheKey(action, record);
147
- for (const client of clients) {
148
- for (const [prefix, rule] of topics) {
149
- const subs = client.subscriptions(prefix);
150
- if (subs.size === 0) continue;
151
- const auth = clientAuth(client);
152
- for (const [topic, options] of subs) {
153
- const info: RequestInfo = {
154
- auth: auth?.record ?? null,
155
- authCollection: auth?.collection.name ?? null,
156
- body: {},
157
- query: options.query,
158
- headers: options.headers,
159
- method: "GET",
160
- context: "realtime",
161
- };
162
- if (!access(c, id, rule, info)) continue;
163
- const m = await message(app, access, record, action, topic, info, auth);
164
- if (!m) continue;
165
- if (!dryCache) client.send(m);
166
- else client.set(key, [...((client.get(key) as Message[]) ?? []), m]);
167
- }
168
- }
147
+ const targets: Target[] = [];
148
+ for (const client of app.realtime.clients()) {
149
+ const auth = clientAuth(client);
150
+ for (const [prefix, rule] of topics)
151
+ for (const [topic, options] of client.subscriptions(prefix))
152
+ targets.push({
153
+ client,
154
+ topic,
155
+ rule,
156
+ auth,
157
+ info: {
158
+ auth: auth?.record ?? null,
159
+ authCollection: auth?.collection.name ?? null,
160
+ body: {},
161
+ query: options.query,
162
+ headers: options.headers,
163
+ method: "GET",
164
+ context: "realtime",
165
+ },
166
+ });
169
167
  }
168
+ return targets;
170
169
  }
171
170
 
172
- async function broadcastLogged(
171
+ const canSee = (access: Access, record: RecordModel, t: Target) =>
172
+ access(record.collection, record.id, t.rule, t.info);
173
+
174
+ const messageFor = (
175
+ app: App,
176
+ access: Access,
177
+ record: RecordModel,
178
+ action: Action,
179
+ t: Target,
180
+ ) => message(app, access, record, action, t.topic, t.info, t.auth);
181
+
182
+ // PB realtimeBroadcastRecord: one message per matching subscription the client may read
183
+ async function broadcastRecord(
173
184
  app: App,
174
185
  action: Action,
175
186
  record: RecordModel,
176
- dryCache = false,
177
187
  ): Promise<void> {
188
+ const access: Access = (...args) => canAccess(app, ...args);
189
+ for (const t of targetsOf(app, record)) {
190
+ if (!canSee(access, record, t)) continue;
191
+ const m = await messageFor(app, access, record, action, t);
192
+ if (m) t.client.send(m);
193
+ }
194
+ }
195
+
196
+ async function logged<T>(fn: () => Promise<T> | T, fallback: T): Promise<T> {
178
197
  try {
179
- // like PB, only the access checks of the delete messages leave its transaction
180
- const access: Access = dryCache
181
- ? (...args) => app.db.committed(() => canAccess(app, ...args))
182
- : (...args) => canAccess(app, ...args);
183
- await broadcastRecord(app, action, record, dryCache, access);
198
+ return await fn();
184
199
  } catch (err) {
185
200
  logUnexpected(err);
201
+ return fallback;
202
+ }
203
+ }
204
+
205
+ // the subscriptions that may read the record in the committed data
206
+ function readers(app: App, record: RecordModel): Target[] {
207
+ const access = committedAccess(app);
208
+ return targetsOf(app, record).filter((t) => canSee(access, record, t));
209
+ }
210
+
211
+ async function deleteMessages(app: App, record: RecordModel) {
212
+ const access = committedAccess(app);
213
+ const out: [Client, Message][] = [];
214
+ for (const t of readers(app, record)) {
215
+ const m = await messageFor(app, access, record, "delete", t);
216
+ if (m) out.push([t.client, m]);
186
217
  }
218
+ return out;
219
+ }
220
+
221
+ // A subscriber that could read the record before an update and cannot now gets a delete built
222
+ // from the old record, or its screen keeps showing it until a reload.
223
+ async function sendHidden(app: App, before: RecordModel, seen: Target[]) {
224
+ const access: Access = (...args) => canAccess(app, ...args);
225
+ for (const t of seen) {
226
+ if (!t.client.hasSubscription(t.topic) || canSee(access, before, t))
227
+ continue;
228
+ const m = await messageFor(app, access, before, "delete", t);
229
+ if (m) t.client.send(m);
230
+ }
231
+ }
232
+
233
+ // Runs `after` once the write committed: right away outside a transaction, else when it ends.
234
+ // A rollback drops it.
235
+ async function afterCommit(app: App, after: () => Promise<void>) {
236
+ let done: Promise<void> | undefined;
237
+ app.db.onComplete((err) => {
238
+ if (err === null) done = logged(after, undefined);
239
+ });
240
+ await done;
187
241
  }
188
242
 
189
243
  function eachAuthClient(
@@ -259,47 +313,51 @@ export function registerRealtimeHooks(app: App): void {
259
313
 
260
314
  h.onModelAfterCreateSuccess.bind(async (e) => {
261
315
  if (e.model instanceof RecordModel)
262
- await broadcastLogged(e.app, "create", e.model);
316
+ await logged(
317
+ () => broadcastRecord(e.app, "create", e.model as RecordModel),
318
+ undefined,
319
+ );
263
320
  return e.next();
264
321
  }, late);
265
322
 
266
323
  h.onModelAfterUpdateSuccess.bind(async (e) => {
267
324
  if (e.model instanceof RecordModel)
268
- await broadcastLogged(e.app, "update", e.model);
325
+ await logged(
326
+ () => broadcastRecord(e.app, "update", e.model as RecordModel),
327
+ undefined,
328
+ );
269
329
  return e.next();
270
330
  }, late);
271
331
 
272
- // the delete messages are built before the delete
273
- h.onModelDelete.bind(
332
+ // Both hooks look at who can read the record before the write, with the committed data.
333
+ // They run innermost so the other hooks have changed the record already.
334
+ h.onModelUpdate.bind(
274
335
  async (e) => {
275
336
  const r = e.model;
276
- if (r instanceof RecordModel)
277
- await broadcastLogged(e.app, "delete", r, true);
278
- return e.next();
337
+ if (!(r instanceof RecordModel)) return e.next();
338
+ const before = r.original();
339
+ // a record created and updated through one object has no original to show
340
+ const seen =
341
+ before.id === r.id
342
+ ? await logged(() => readers(e.app, before), [])
343
+ : [];
344
+ await e.next();
345
+ if (seen.length > 0)
346
+ await afterCommit(e.app, () => sendHidden(e.app, before, seen));
279
347
  },
280
348
  { priority: 99 },
281
349
  );
282
350
 
283
- h.onModelAfterDeleteSuccess.bind((e) => {
284
- const r = e.model;
285
- if (r instanceof RecordModel) {
286
- const key = dryCacheKey("delete", r);
287
- for (const client of e.app.realtime.clients()) {
288
- const messages = client.get(key) as Message[] | undefined;
289
- if (!messages) continue;
290
- client.unset(key);
291
- for (const m of messages) client.send(m);
292
- }
293
- }
294
- return e.next();
295
- }, late);
296
-
297
- h.onModelAfterDeleteError.bind((e) => {
298
- const r = e.model;
299
- if (r instanceof RecordModel) {
300
- const key = dryCacheKey("delete", r);
301
- for (const client of e.app.realtime.clients()) client.unset(key);
302
- }
303
- return e.next();
304
- }, late);
351
+ h.onModelDelete.bind(
352
+ async (e) => {
353
+ const r = e.model;
354
+ if (!(r instanceof RecordModel)) return e.next();
355
+ const messages = await logged(() => deleteMessages(e.app, r), []);
356
+ await e.next();
357
+ await afterCommit(e.app, async () => {
358
+ for (const [client, m] of messages) client.send(m);
359
+ });
360
+ },
361
+ { priority: 99 },
362
+ );
305
363
  }