prostgles-server 4.2.440 → 4.2.442

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.
Files changed (59) hide show
  1. package/dist/DboBuilder/ViewHandler/ViewHandler.d.ts +6 -6
  2. package/dist/DboBuilder/ViewHandler/ViewHandler.d.ts.map +1 -1
  3. package/dist/DboBuilder/ViewHandler/ViewHandler.js +6 -8
  4. package/dist/DboBuilder/ViewHandler/ViewHandler.js.map +1 -1
  5. package/dist/DboBuilder/ViewHandler/subscribe.d.ts +4 -12
  6. package/dist/DboBuilder/ViewHandler/subscribe.d.ts.map +1 -1
  7. package/dist/DboBuilder/ViewHandler/subscribe.js +11 -25
  8. package/dist/DboBuilder/ViewHandler/subscribe.js.map +1 -1
  9. package/dist/Logging.d.ts +2 -1
  10. package/dist/Logging.d.ts.map +1 -1
  11. package/dist/PubSubManager/PubSubManager.d.ts +19 -11
  12. package/dist/PubSubManager/PubSubManager.d.ts.map +1 -1
  13. package/dist/PubSubManager/PubSubManager.js +35 -25
  14. package/dist/PubSubManager/PubSubManager.js.map +1 -1
  15. package/dist/PubSubManager/addSub.d.ts.map +1 -1
  16. package/dist/PubSubManager/addSub.js +6 -6
  17. package/dist/PubSubManager/addSub.js.map +1 -1
  18. package/dist/PubSubManager/init/getDataWatchFunctionQuery.d.ts.map +1 -1
  19. package/dist/PubSubManager/init/getDataWatchFunctionQuery.js +22 -1
  20. package/dist/PubSubManager/init/getDataWatchFunctionQuery.js.map +1 -1
  21. package/dist/PubSubManager/notifListener.js +3 -3
  22. package/dist/PubSubManager/notifListener.js.map +1 -1
  23. package/dist/PubSubManager/pushSubData.d.ts +1 -1
  24. package/dist/PubSubManager/pushSubData.d.ts.map +1 -1
  25. package/dist/PubSubManager/pushSubData.js +21 -42
  26. package/dist/PubSubManager/pushSubData.js.map +1 -1
  27. package/dist/PubSubManager/refreshTriggers.d.ts.map +1 -1
  28. package/dist/PubSubManager/refreshTriggers.js +6 -5
  29. package/dist/PubSubManager/refreshTriggers.js.map +1 -1
  30. package/dist/PublishParser/PublishParser.d.ts +2 -1
  31. package/dist/PublishParser/PublishParser.d.ts.map +1 -1
  32. package/dist/PublishParser/PublishParser.js +38 -18
  33. package/dist/PublishParser/PublishParser.js.map +1 -1
  34. package/dist/PublishParser/getSchemaFromPublish.js +11 -11
  35. package/dist/PublishParser/getSchemaFromPublish.js.map +1 -1
  36. package/dist/PublishParser/getTableRulesWithoutFileTable.d.ts.map +1 -1
  37. package/dist/PublishParser/getTableRulesWithoutFileTable.js +2 -2
  38. package/dist/PublishParser/getTableRulesWithoutFileTable.js.map +1 -1
  39. package/dist/initProstgles.d.ts.map +1 -1
  40. package/dist/initProstgles.js +13 -0
  41. package/dist/initProstgles.js.map +1 -1
  42. package/dist/runClientRequest.d.ts.map +1 -1
  43. package/dist/runClientRequest.js +2 -1
  44. package/dist/runClientRequest.js.map +1 -1
  45. package/lib/DboBuilder/ViewHandler/ViewHandler.ts +32 -30
  46. package/lib/DboBuilder/ViewHandler/subscribe.ts +22 -48
  47. package/lib/Logging.ts +3 -1
  48. package/lib/PubSubManager/PubSubManager.ts +50 -42
  49. package/lib/PubSubManager/addSub.ts +13 -8
  50. package/lib/PubSubManager/init/getDataWatchFunctionQuery.ts +28 -1
  51. package/lib/PubSubManager/notifListener.ts +8 -8
  52. package/lib/PubSubManager/pushSubData.ts +20 -35
  53. package/lib/PubSubManager/refreshTriggers.ts +9 -8
  54. package/lib/PublishParser/PublishParser.ts +43 -27
  55. package/lib/PublishParser/getSchemaFromPublish.ts +21 -21
  56. package/lib/PublishParser/getTableRulesWithoutFileTable.ts +5 -6
  57. package/lib/initProstgles.ts +18 -0
  58. package/lib/runClientRequest.ts +4 -3
  59. package/package.json +2 -2
@@ -20,11 +20,11 @@ import { initialiseEventTriggers } from "./initialiseEventTriggers";
20
20
  import { refreshTriggers } from "./refreshTriggers";
21
21
 
22
22
  import type { AnyObject, FieldFilter, SelectParams, WAL } from "prostgles-types";
23
- import { CHANNELS, type SubscribeOptions } from "prostgles-types";
23
+ import { CHANNELS, getSerialisableError, type SubscribeOptions } from "prostgles-types";
24
24
 
25
25
  import { find, pickKeys } from "prostgles-types";
26
- import type { LocalFuncs } from "../DboBuilder/ViewHandler/subscribe";
27
- import { getOnDataFunc, matchesLocalFuncs } from "../DboBuilder/ViewHandler/subscribe";
26
+ import type { OnData } from "../DboBuilder/ViewHandler/subscribe";
27
+ import { matchesLocalFuncs } from "../DboBuilder/ViewHandler/subscribe";
28
28
  import type { EventTypes } from "../Logging";
29
29
  import type { ParsedTableRule } from "../PublishParser/PublishParser";
30
30
  import { syncData } from "../SyncReplication";
@@ -109,7 +109,7 @@ export type SubscriptionParams = {
109
109
  subscribeOptions: SubscribeOptions;
110
110
  tracked_columns: string[] | undefined;
111
111
 
112
- localFuncs?: LocalFuncs;
112
+ onData?: OnData;
113
113
  socket: PRGLIOSocket | undefined;
114
114
 
115
115
  lastPushed: number;
@@ -125,7 +125,7 @@ export type Subscription = Pick<
125
125
  | "lastPushed"
126
126
  | "channel_name"
127
127
  | "is_ready"
128
- | "localFuncs"
128
+ | "onData"
129
129
  | "socket"
130
130
  | "socket_id"
131
131
  | "table_info"
@@ -136,7 +136,7 @@ export type Subscription = Pick<
136
136
  triggers: AddTriggerParams[];
137
137
  };
138
138
 
139
- export type PubSubManagerTriggers = Record<string, { condition: string; hash: string }[]>;
139
+ export type PubSubManagerTriggers = Map<string, { condition: string; hash: string }[]>;
140
140
 
141
141
  /**
142
142
  * Used to facilitate table subscribe and sync
@@ -165,7 +165,7 @@ export class PubSubManager {
165
165
  * Triggers used for sync/sub that reflect prostgles.app_triggers.
166
166
  * Updated through refreshTriggers()
167
167
  */
168
- _triggers: PubSubManagerTriggers = {};
168
+ _triggers: PubSubManagerTriggers = new Map();
169
169
  sockets: Record<string, PRGLIOSocket> = {};
170
170
 
171
171
  subs: Subscription[] = [];
@@ -218,13 +218,13 @@ export class PubSubManager {
218
218
 
219
219
  getClientSubs({
220
220
  channel_name,
221
- localFuncs,
221
+ onData,
222
222
  socket_id,
223
- }: Pick<Subscription, "localFuncs" | "socket_id" | "channel_name">): Subscription[] {
223
+ }: Pick<Subscription, "onData" | "socket_id" | "channel_name">): Subscription[] {
224
224
  return this.subs.filter((s) => {
225
225
  return (
226
226
  s.channel_name === channel_name &&
227
- (matchesLocalFuncs(localFuncs, s.localFuncs) || (socket_id && s.socket_id === socket_id))
227
+ (matchesLocalFuncs(onData, s.onData) || (socket_id && s.socket_id === socket_id))
228
228
  );
229
229
  });
230
230
  }
@@ -236,30 +236,31 @@ export class PubSubManager {
236
236
 
237
237
  removeSubscription = (
238
238
  channelName: string,
239
- subInfo: { type: "local"; localFuncs: LocalFuncs } | { type: "ws"; socket: PRGLIOSocket },
239
+ subInfo: { type: "local"; onData: OnData } | { type: "ws"; socket: PRGLIOSocket },
240
240
  ) => {
241
241
  const matchingSubIdx = this.subs.findIndex(
242
242
  (s) =>
243
243
  s.channel_name === channelName &&
244
244
  (subInfo.type === "local" ?
245
- getOnDataFunc(subInfo.localFuncs) === getOnDataFunc(s.localFuncs)
245
+ subInfo.onData === s.onData
246
246
  : subInfo.socket.id === s.socket?.id),
247
247
  );
248
- if (matchingSubIdx > -1) {
249
- const tableName = this.subs[matchingSubIdx]!.table_info.name;
250
- const oldActiveTriggers = this.getActiveTriggers(tableName);
248
+ const matchingSub = this.subs[matchingSubIdx];
249
+ if (matchingSub) {
250
+ /** Ensure we check and refresh related table/view triggers as well */
251
+ const oldActiveTriggers = this.getAllActiveTriggers();
251
252
  this.subs.splice(matchingSubIdx, 1);
252
- const newActiveTriggers = this.getActiveTriggers(tableName);
253
+ const newActiveTriggers = this.getAllActiveTriggers();
254
+ const tableNames = new Set(
255
+ [...oldActiveTriggers, ...newActiveTriggers].map((t) => t.tableName),
256
+ );
253
257
  if (newActiveTriggers.length < oldActiveTriggers.length) {
254
- this.deleteOrphanedTriggers(tableName);
258
+ this.deleteOrphanedTriggers(tableNames);
255
259
  }
256
260
  } else {
257
- console.error(
258
- "Could not unsubscribe localFunc. Subscription might not have initialised yet",
259
- {
260
- channelName,
261
- },
262
- );
261
+ console.error("Could not unsubscribe. Subscription might not have initialised yet", {
262
+ channelName,
263
+ });
263
264
  }
264
265
  };
265
266
 
@@ -272,11 +273,11 @@ export class PubSubManager {
272
273
  notifListener = notifListener.bind(this);
273
274
 
274
275
  getTriggerInfo = (tableName: string) => {
275
- const tableTriggerConditions = this._triggers[tableName]?.map((cond, idx) => ({
276
+ const tableTriggerConditions = this._triggers.get(tableName)?.map((triggerInfo, idx) => ({
276
277
  idx,
277
- ...cond,
278
- subs: this.getTriggerSubs(tableName, cond.condition),
279
- syncs: this.getSyncs(tableName, cond.condition),
278
+ ...triggerInfo,
279
+ subs: this.getTriggerSubs(tableName, triggerInfo.condition),
280
+ syncs: this.getSyncs(tableName, triggerInfo.condition),
280
281
  }));
281
282
  return tableTriggerConditions;
282
283
  };
@@ -287,13 +288,20 @@ export class PubSubManager {
287
288
  return activeTriggers;
288
289
  };
289
290
 
290
- getSubData = async (
291
- sub: Subscription,
292
- ): Promise<{ data: any[]; err?: undefined } | { data?: undefined; err: unknown }> => {
293
- const { table_info, filter, selectParams: params, table_rules, socket, localFuncs } = sub; //, subOne = false
291
+ getAllActiveTriggers = () => {
292
+ return Array.from(this._triggers.keys()).flatMap((tableName) => {
293
+ return this.getActiveTriggers(tableName).map((triggerInfo) => ({
294
+ ...triggerInfo,
295
+ tableName,
296
+ }));
297
+ });
298
+ };
299
+
300
+ getSubData = async (sub: Subscription) => {
301
+ const { table_info, filter, selectParams: params, table_rules, socket, onData } = sub; //, subOne = false
294
302
  const { name: table_name } = table_info;
295
303
  const tableHandler = this.dbo[table_name];
296
- if (!localFuncs && !socket) {
304
+ if (!onData && !socket) {
297
305
  throw new Error("Subscription must have either localFuncs or socket");
298
306
  }
299
307
  if (!tableHandler?.find) {
@@ -301,7 +309,7 @@ export class PubSubManager {
301
309
  }
302
310
 
303
311
  try {
304
- const data = await tableHandler.find(
312
+ const data = (await tableHandler.find(
305
313
  filter,
306
314
  params,
307
315
  undefined,
@@ -309,10 +317,10 @@ export class PubSubManager {
309
317
  socket && {
310
318
  clientReq: { socket },
311
319
  },
312
- );
320
+ )) as AnyObject[];
313
321
  return { data };
314
322
  } catch (err) {
315
- return { err };
323
+ return { err: getSerialisableError(err) || "Unknown error fetching subscription data" };
316
324
  }
317
325
  };
318
326
 
@@ -401,23 +409,23 @@ export class PubSubManager {
401
409
  /** Throttle trigger deletes */
402
410
  deletingOrphanedTriggers:
403
411
  | {
404
- tableNames: string[];
412
+ tableNames: Set<string>;
405
413
  timeout: NodeJS.Timeout;
406
414
  }
407
415
  | undefined;
408
- deleteOrphanedTriggers = (latestTableName: string) => {
416
+ deleteOrphanedTriggers = (latestTableNames: Set<string>) => {
409
417
  this.deletingOrphanedTriggers ??= {
410
- tableNames: [latestTableName],
418
+ tableNames: latestTableNames,
411
419
  timeout: setTimeout(() => {
412
420
  const tableNames = this.deletingOrphanedTriggers!.tableNames;
413
421
  this.deletingOrphanedTriggers = undefined;
414
- void deleteOrphanedTriggers.bind(this)(tableNames);
422
+ void deleteOrphanedTriggers.bind(this)(Array.from(tableNames));
415
423
  }, 1000),
416
424
  };
417
425
 
418
- if (!this.deletingOrphanedTriggers.tableNames.includes(latestTableName)) {
419
- this.deletingOrphanedTriggers.tableNames.push(latestTableName);
420
- }
426
+ latestTableNames.forEach((latestTableName) => {
427
+ this.deletingOrphanedTriggers?.tableNames.add(latestTableName);
428
+ });
421
429
  };
422
430
 
423
431
  addingTrigger: any;
@@ -1,7 +1,12 @@
1
1
  import type { SubscriptionChannels } from "prostgles-types";
2
2
  import type { VoidFunction } from "../SchemaWatch/SchemaWatch";
3
3
  import { tout } from "./init/initPubSubManager";
4
- import type { BasicCallback, PubSubManager, Subscription, SubscriptionParams } from "./PubSubManager";
4
+ import type {
5
+ BasicCallback,
6
+ PubSubManager,
7
+ Subscription,
8
+ SubscriptionParams,
9
+ } from "./PubSubManager";
5
10
  import { parseCondition } from "./PubSubManagerUtils";
6
11
  import type { AddTriggerParams } from "./addTrigger";
7
12
 
@@ -17,11 +22,11 @@ type AddSubResult = SubscriptionChannels & {
17
22
  /* The distinct list of {table_name, condition} must have a corresponding trigger in the database */
18
23
  export async function addSub(
19
24
  this: PubSubManager,
20
- subscriptionParams: Omit<AddSubscriptionParams, "channel_name" | "parentSubParams">
25
+ subscriptionParams: Omit<AddSubscriptionParams, "channel_name" | "parentSubParams">,
21
26
  ): Promise<AddSubResult> {
22
27
  const {
23
28
  socket,
24
- localFuncs,
29
+ onData,
25
30
  table_rules,
26
31
  filter = {},
27
32
  selectParams = {},
@@ -33,10 +38,10 @@ export async function addSub(
33
38
  } = subscriptionParams;
34
39
  const table_name = table_info.name;
35
40
 
36
- if (!socket && !localFuncs) {
41
+ if (!socket && !onData) {
37
42
  throw "socket AND func missing";
38
43
  }
39
- if (socket && localFuncs) {
44
+ if (socket && onData) {
40
45
  throw "addSub: cannot have socket AND func";
41
46
  }
42
47
 
@@ -50,7 +55,7 @@ export async function addSub(
50
55
  const newSub: Subscription = {
51
56
  channel_name,
52
57
  filter,
53
- localFuncs,
58
+ onData,
54
59
  selectParams: selectParams,
55
60
  lastPushed: 0,
56
61
  socket,
@@ -74,7 +79,7 @@ export async function addSub(
74
79
  const [matchingSub] = this.getClientSubs(newSub);
75
80
  if (matchingSub) {
76
81
  console.error(
77
- `Trying to add a duplicate ${localFuncs ? "local" : "socket"} sub for: ${channel_name}`
82
+ `Trying to add a duplicate ${onData ? "local" : "socket"} sub for: ${channel_name}`,
78
83
  );
79
84
  return result;
80
85
  }
@@ -104,7 +109,7 @@ export async function addSub(
104
109
  void this.pushSubData(newSub);
105
110
  };
106
111
 
107
- if (localFuncs) {
112
+ if (onData) {
108
113
  /**
109
114
  * Must ensure sub will start sending data after all triggers are set up.
110
115
  * Socket clients are not affected as they need to confirm they are ready to receive data
@@ -8,7 +8,7 @@ import { asValue, DELIMITER, NOTIF_CHANNEL, NOTIF_TYPE } from "../PubSubManagerU
8
8
  */
9
9
  export const udtNamesWithoutEqualityComparison = ["json", "xml"];
10
10
  export const getDataWatchFunctionQuery = (debugMode: boolean | undefined) => {
11
- return `
11
+ const dataWatchFunctionQuery = `
12
12
 
13
13
  CREATE OR REPLACE FUNCTION ${DB_OBJ_NAMES.data_watch_func}() RETURNS TRIGGER
14
14
  AS $$
@@ -161,6 +161,25 @@ export const getDataWatchFunctionQuery = (debugMode: boolean | undefined) => {
161
161
  COMMENT ON FUNCTION ${DB_OBJ_NAMES.data_watch_func} IS 'Prostgles internal function used to notify when data in the table changed';
162
162
 
163
163
  `;
164
+
165
+ /** Ensure every execute is followed by EXCEPTION catch to ensure we remove stale schema/faulty triggers */
166
+ const queryLines = dataWatchFunctionQuery
167
+ .split("\n")
168
+ .map((l) => l.trim())
169
+ .filter((l) => l);
170
+ queryLines.forEach((line, lineIndex) => {
171
+ const nextLine = queryLines[lineIndex + 1] ?? "";
172
+ if (
173
+ line.toUpperCase().startsWith("EXECUTE") &&
174
+ !nextLine.toUpperCase().startsWith("EXCEPTION")
175
+ ) {
176
+ throw new Error(
177
+ `Every EXECUTE statement in the data watch function must be followed by an EXCEPTION block to catch errors and avoid stale triggers. Problematic line: ${line}`,
178
+ );
179
+ }
180
+ });
181
+
182
+ return dataWatchFunctionQuery;
164
183
  };
165
184
 
166
185
  /**
@@ -208,6 +227,14 @@ IF TG_OP = 'UPDATE' THEN
208
227
 
209
228
  BEGIN
210
229
  EXECUTE query INTO changed_columns;
230
+ EXCEPTION WHEN OTHERS THEN
231
+
232
+ has_errors := TRUE;
233
+
234
+ GET STACKED DIAGNOSTICS
235
+ err_text = MESSAGE_TEXT,
236
+ err_detail = PG_EXCEPTION_DETAIL,
237
+ err_hint = PG_EXCEPTION_HINT;
211
238
  END;
212
239
 
213
240
  /* It is possible to get no changes */
@@ -101,21 +101,21 @@ export async function notifListener(this: PubSubManager, data: { payload: string
101
101
  } else if (conditionIds?.every((id) => Number.isInteger(id))) {
102
102
  state = "ok";
103
103
  const firedTableConditions = tableTriggerConditions.filter(({ idx }) =>
104
- conditionIds.includes(idx)
104
+ conditionIds.includes(idx),
105
105
  );
106
106
  const orphanedTableConditions = conditionIds.filter((condId) => {
107
107
  const tc = tableTriggerConditions.at(condId);
108
108
  return !tc || (tc.subs.length === 0 && tc.syncs.length === 0);
109
109
  });
110
110
  if (orphanedTableConditions.length) {
111
- void this.deleteOrphanedTriggers.bind(this)(table_name);
111
+ void this.deleteOrphanedTriggers(new Set(table_name));
112
112
  }
113
113
 
114
114
  firedTableConditions.map(({ subs, syncs }) => {
115
115
  log(
116
116
  "notifListener",
117
117
  subs.map((s) => s.channel_name),
118
- syncs.map((s) => s.channel_name)
118
+ syncs.map((s) => s.channel_name),
119
119
  );
120
120
 
121
121
  syncs.map((s) => {
@@ -128,8 +128,8 @@ export async function notifListener(this: PubSubManager, data: { payload: string
128
128
  (trg) =>
129
129
  this.dbo[trg.table_name] &&
130
130
  sub.is_ready &&
131
- ((sub.socket_id && this.sockets[sub.socket_id]) || sub.localFuncs)
132
- )
131
+ ((sub.socket_id && this.sockets[sub.socket_id]) || sub.onData),
132
+ ),
133
133
  );
134
134
 
135
135
  activeAndReadySubs.forEach((sub) => {
@@ -143,7 +143,7 @@ export async function notifListener(this: PubSubManager, data: { payload: string
143
143
  tracked_columns
144
144
  ) {
145
145
  const subFieldsHaveChanged = changedColumns.some((changedColumn) =>
146
- tracked_columns.includes(changedColumn)
146
+ tracked_columns.includes(changedColumn),
147
147
  );
148
148
  if (!subFieldsHaveChanged) return;
149
149
  }
@@ -181,11 +181,11 @@ export async function notifListener(this: PubSubManager, data: { payload: string
181
181
  state,
182
182
  op_name,
183
183
  condition_ids_str,
184
- tableTriggers: this._triggers[table_name],
184
+ tableTriggers: this._triggers.get(table_name),
185
185
  tableSyncs: JSON.stringify(
186
186
  this.syncs
187
187
  .filter((s) => s.table_name === table_name)
188
- .map((s) => pickKeys(s, ["condition", "socket_id"]))
188
+ .map((s) => pickKeys(s, ["condition", "socket_id"])),
189
189
  ),
190
190
  connectedSocketIds: this.connectedSocketIds,
191
191
  });
@@ -1,12 +1,10 @@
1
- import { getSerialisableError } from "prostgles-types";
2
- import { parseLocalFuncs } from "../DboBuilder/ViewHandler/subscribe";
3
1
  import type { EventTypes } from "../Logging";
4
2
  import type { Subscription } from "./PubSubManager";
5
3
  import { type PubSubManager } from "./PubSubManager";
6
4
  import { log } from "./PubSubManagerUtils";
7
5
 
8
6
  export async function pushSubData(this: PubSubManager, sub: Subscription, err?: any) {
9
- const { socket_id, channel_name } = sub;
7
+ const { socket_id, channel_name, onData } = sub;
10
8
 
11
9
  const onLog = (
12
10
  state: Extract<EventTypes.SyncOrSub, { type: "syncOrSub"; command: "pushSubData" }>["state"],
@@ -28,7 +26,6 @@ export async function pushSubData(this: PubSubManager, sub: Subscription, err?:
28
26
  onLog("sub_not_found");
29
27
  return;
30
28
  }
31
- const localFuncs = parseLocalFuncs(sub.localFuncs);
32
29
 
33
30
  if (err) {
34
31
  onLog("error");
@@ -39,40 +36,28 @@ export async function pushSubData(this: PubSubManager, sub: Subscription, err?:
39
36
  }
40
37
 
41
38
  sub.lastPushed = Date.now();
42
- return new Promise(async (resolve, reject) => {
43
- /* TODO: Retire subOne -> it's redundant */
44
39
 
45
- const { data, err } = await this.getSubData(sub);
40
+ const { data, err: subDataError } = await this.getSubData(sub);
46
41
 
47
- if (data) {
48
- if (socket_id && this.sockets[socket_id]) {
49
- log("Pushed " + data.length + " records to sub");
50
- onLog("Emiting to socket");
51
- this.sockets[socket_id].emit(channel_name, { data }, () => {
52
- resolve(data);
53
- });
42
+ if (subDataError !== undefined) {
43
+ onLog("fetch data error");
44
+ }
45
+ if (socket_id && this.sockets[socket_id]) {
46
+ log(`Pushing ${data?.length ?? 0} rows to socket`);
47
+ onLog("Emiting to socket");
48
+ this.sockets[socket_id].emit(
49
+ channel_name,
50
+ subDataError !== undefined ? { err: subDataError } : { data },
51
+ () => {
54
52
  /* TO DO: confirm receiving data or server will unsubscribe
55
53
  { data }, (cb)=> { console.log(cb) });
56
54
  */
57
- } else if (localFuncs) {
58
- onLog("pushed to local client");
59
- localFuncs.onData(data);
60
- resolve(data);
61
- } else {
62
- onLog("no client to push data to");
63
- }
64
- } else {
65
- onLog("fetch data error");
66
- const errObj = getSerialisableError(err) || "Unknown error fetching subscription data";
67
- if (socket_id && this.sockets[socket_id]) {
68
- this.sockets[socket_id].emit(channel_name, { err: errObj });
69
- } else if (localFuncs) {
70
- if (!localFuncs.onError) {
71
- console.error("Uncaught subscription error", err);
72
- }
73
- localFuncs.onError?.(errObj);
74
- }
75
- reject(errObj);
76
- }
77
- });
55
+ },
56
+ );
57
+ } else if (onData) {
58
+ onLog("pushed to local client");
59
+ onData(data ?? [], subDataError);
60
+ } else {
61
+ onLog("no client to push data to");
62
+ }
78
63
  }
@@ -2,27 +2,28 @@ import type { PubSubManager } from "./PubSubManager";
2
2
 
3
3
  export async function refreshTriggers(this: PubSubManager) {
4
4
  const start = Date.now();
5
- const triggers: {
5
+ const triggers = await this.db.any<{
6
6
  table_name: string;
7
7
  condition: string;
8
8
  condition_hash: string;
9
- }[] = await this.db.any(
9
+ }>(
10
10
  `
11
11
  SELECT *
12
12
  FROM prostgles.v_triggers
13
13
  WHERE app_id = $1
14
14
  ORDER BY table_name, condition
15
15
  `,
16
- [this.dboBuilder.prostgles.appId]
16
+ [this.dboBuilder.prostgles.appId],
17
17
  );
18
18
 
19
- const oldTriggers = { ...this._triggers };
19
+ const oldTriggers = new Map(this._triggers);
20
20
 
21
- this._triggers = {};
21
+ this._triggers = new Map();
22
22
  triggers.map((t) => {
23
- this._triggers[t.table_name] ??= [];
24
- if (!this._triggers[t.table_name]?.map((t) => t.condition).includes(t.condition)) {
25
- this._triggers[t.table_name]?.push({ condition: t.condition, hash: t.condition_hash });
23
+ this._triggers.set(t.table_name, this._triggers.get(t.table_name) ?? []);
24
+ const tableTriggers = this._triggers.get(t.table_name)!;
25
+ if (!tableTriggers.map((t) => t.condition).includes(t.condition)) {
26
+ tableTriggers.push({ condition: t.condition, hash: t.condition_hash });
26
27
  }
27
28
  });
28
29
 
@@ -104,37 +104,21 @@ export class PublishParser {
104
104
  command,
105
105
  clientReq,
106
106
  }: DboTableCommand): Promise<ParsedTableRule> {
107
+ const rules = await this.getParsedTableRule({ tableName, clientReq }, undefined);
107
108
  const clientInfo =
108
109
  clientReq && (await this.prostgles.authHandler.getSidAndUserFromRequest(clientReq));
109
110
  if (clientInfo === "new-session-redirect") {
110
111
  throw "new-session-redirect";
111
112
  }
112
- const rules = await this.getValidatedRequestRule(
113
- { tableName, command, clientReq },
114
- clientInfo,
115
- undefined,
116
- );
113
+ this.validateRequestRule({ tableName, command, clientReq }, rules, undefined);
117
114
  return rules;
118
115
  }
119
116
 
120
- async getValidatedRequestRule(
121
- { tableName, command, clientReq }: DboTableCommand,
117
+ async getParsedTableRule(
118
+ { tableName, clientReq }: Pick<DboTableCommand, "tableName" | "clientReq">,
122
119
  clientInfo: AuthResultWithSID | undefined,
123
- scope: PermissionScope | undefined,
124
120
  ): Promise<ParsedTableRule> {
125
- if (!command || !tableName) throw "command OR tableName are missing";
126
-
127
- const rule = RULE_TO_METHODS.find((rtms) => rtms.methods.some((v) => v === command));
128
- if (!rule) {
129
- throw "Invalid command: " + command;
130
- }
131
-
132
- if (scope) {
133
- const tableScope = scope.tables;
134
- if (!tableScope?.[tableName] || !tableScope[tableName][rule.sqlRule]) {
135
- throw `Invalid or disallowed command: ${tableName}.${command}. The PermissionsScope does not allow this command.`;
136
- }
137
- }
121
+ if (!tableName) throw "tableName missing";
138
122
 
139
123
  /* Must be local request -> allow everything */
140
124
  if (!clientReq) {
@@ -150,17 +134,51 @@ export class PublishParser {
150
134
  /* Must be from socket. Must have a publish */
151
135
  if (!this.publish) throw "publish is missing";
152
136
 
137
+ const tableErrors = clientReq.socket?.prostgles?.tableSchemaErrors[tableName];
153
138
  /* Get any publish errors for socket */
154
- const errorInfo = clientReq.socket?.prostgles?.tableSchemaErrors[tableName]?.[command];
155
-
156
- if (errorInfo) throw errorInfo.error;
139
+ Object.values(tableErrors ?? {}).forEach((errorInfo) => {
140
+ throw errorInfo.error;
141
+ });
157
142
 
158
143
  const tableRule = await this.getTableRules({ tableName, clientReq }, clientInfo);
159
- if (!tableRule)
144
+
145
+ if (!tableRule) {
160
146
  throw {
161
147
  stack: ["getValidatedRequestRule()"],
162
148
  message: "Invalid or disallowed table: " + tableName,
163
149
  };
150
+ }
151
+ return tableRule;
152
+ }
153
+
154
+ validateRequestRule(
155
+ { tableName, command }: DboTableCommand,
156
+ tableRule: ParsedTableRule,
157
+ scope: PermissionScope | undefined,
158
+ ) {
159
+ if (!command || !tableName) throw "command OR tableName are missing";
160
+
161
+ const rule = RULE_TO_METHODS.find((rtms) => rtms.methods.some((v) => v === command));
162
+ if (!rule) {
163
+ throw "Invalid command: " + command;
164
+ }
165
+
166
+ if (scope) {
167
+ if (scope.sql === "commited") {
168
+ // Allow all commands
169
+ } else if (scope.sql === "rolledback") {
170
+ if (rule.sqlRule === "select") {
171
+ // Allow select
172
+ } else {
173
+ throw `Invalid or disallowed command: ${tableName}.${command}. The PermissionsScope only allows ${scope.sql}`;
174
+ }
175
+ } else {
176
+ const tableScope = scope.tables;
177
+ if (!tableScope?.[tableName] || !tableScope[tableName][rule.sqlRule]) {
178
+ throw `Invalid or disallowed command: ${tableName}.${command}. The PermissionsScope does not allow this command.`;
179
+ }
180
+ }
181
+ }
164
182
 
165
183
  if (command === "upsert") {
166
184
  if (!tableRule.update || !tableRule.insert) {
@@ -177,8 +195,6 @@ export class PublishParser {
177
195
  message: `Invalid or disallowed command: ${tableName}.${command}`,
178
196
  };
179
197
  }
180
-
181
- return tableRule;
182
198
  }
183
199
 
184
200
  async getTableRules(