prostgles-server 3.0.64 → 3.0.67

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 (123) hide show
  1. package/dist/AuthHandler.d.ts +11 -11
  2. package/dist/AuthHandler.d.ts.map +1 -1
  3. package/dist/DBSchemaBuilder.d.ts +3 -3
  4. package/dist/DBSchemaBuilder.d.ts.map +1 -1
  5. package/dist/DboBuilder/QueryBuilder/Functions.d.ts +3 -3
  6. package/dist/DboBuilder/QueryBuilder/Functions.d.ts.map +1 -1
  7. package/dist/DboBuilder/QueryBuilder/QueryBuilder.d.ts +3 -3
  8. package/dist/DboBuilder/QueryBuilder/QueryBuilder.d.ts.map +1 -1
  9. package/dist/DboBuilder/TableHandler.d.ts +1 -1
  10. package/dist/DboBuilder/TableHandler.d.ts.map +1 -1
  11. package/dist/DboBuilder/ViewHandler.d.ts +5 -4
  12. package/dist/DboBuilder/ViewHandler.d.ts.map +1 -1
  13. package/dist/DboBuilder/ViewHandler.js +7 -134
  14. package/dist/DboBuilder/ViewHandler.js.map +1 -1
  15. package/dist/DboBuilder/delete.js +1 -1
  16. package/dist/DboBuilder/delete.js.map +1 -1
  17. package/dist/DboBuilder/insert.js +1 -1
  18. package/dist/DboBuilder/insert.js.map +1 -1
  19. package/dist/DboBuilder/insertDataParse.js +1 -1
  20. package/dist/DboBuilder/insertDataParse.js.map +1 -1
  21. package/dist/DboBuilder/runSQL.js +1 -1
  22. package/dist/DboBuilder/runSQL.js.map +1 -1
  23. package/dist/DboBuilder/subscribe.d.ts +11 -0
  24. package/dist/DboBuilder/subscribe.d.ts.map +1 -0
  25. package/dist/DboBuilder/subscribe.js +190 -0
  26. package/dist/DboBuilder/subscribe.js.map +1 -0
  27. package/dist/DboBuilder/update.js +1 -1
  28. package/dist/DboBuilder/update.js.map +1 -1
  29. package/dist/DboBuilder.d.ts +24 -24
  30. package/dist/DboBuilder.d.ts.map +1 -1
  31. package/dist/DboBuilder.js +1 -1
  32. package/dist/DboBuilder.js.map +1 -1
  33. package/dist/FileManager.d.ts +6 -6
  34. package/dist/FileManager.d.ts.map +1 -1
  35. package/dist/FileManager.js +17 -17
  36. package/dist/FileManager.js.map +1 -1
  37. package/dist/Filtering.d.ts +1 -1
  38. package/dist/Filtering.d.ts.map +1 -1
  39. package/dist/PostgresNotifListenManager.d.ts +1 -1
  40. package/dist/PostgresNotifListenManager.d.ts.map +1 -1
  41. package/dist/Prostgles.d.ts +14 -14
  42. package/dist/Prostgles.d.ts.map +1 -1
  43. package/dist/Prostgles.js +12 -12
  44. package/dist/Prostgles.js.map +1 -1
  45. package/dist/{PubSubManager.d.ts → PubSubManager/PubSubManager.d.ts} +24 -21
  46. package/dist/PubSubManager/PubSubManager.d.ts.map +1 -0
  47. package/dist/PubSubManager/PubSubManager.js +754 -0
  48. package/dist/PubSubManager/PubSubManager.js.map +1 -0
  49. package/dist/PubSubManager/initPubSubManager.d.ts +3 -0
  50. package/dist/PubSubManager/initPubSubManager.d.ts.map +1 -0
  51. package/dist/PubSubManager/initPubSubManager.js +616 -0
  52. package/dist/PubSubManager/initPubSubManager.js.map +1 -0
  53. package/dist/PublishParser.d.ts +32 -32
  54. package/dist/PublishParser.d.ts.map +1 -1
  55. package/dist/PublishParser.js +1 -1
  56. package/dist/PublishParser.js.map +1 -1
  57. package/dist/SchemaWatch.d.ts +1 -1
  58. package/dist/SchemaWatch.d.ts.map +1 -1
  59. package/dist/SyncReplication.d.ts +6 -6
  60. package/dist/SyncReplication.d.ts.map +1 -1
  61. package/dist/SyncReplication.js +1 -1
  62. package/dist/SyncReplication.js.map +1 -1
  63. package/dist/TableConfig.d.ts +21 -21
  64. package/dist/TableConfig.d.ts.map +1 -1
  65. package/dist/TableConfig.js +13 -13
  66. package/dist/TableConfig.js.map +1 -1
  67. package/dist/shortestPath.d.ts +1 -1
  68. package/dist/shortestPath.d.ts.map +1 -1
  69. package/dist/validation.d.ts +9 -9
  70. package/dist/validation.d.ts.map +1 -1
  71. package/dist/validation.js +1 -1
  72. package/dist/validation.js.map +1 -1
  73. package/lib/DboBuilder/ViewHandler.d.ts +4 -3
  74. package/lib/DboBuilder/ViewHandler.d.ts.map +1 -1
  75. package/lib/DboBuilder/ViewHandler.js +7 -134
  76. package/lib/DboBuilder/ViewHandler.ts +15 -164
  77. package/lib/DboBuilder/delete.js +1 -1
  78. package/lib/DboBuilder/delete.ts +1 -1
  79. package/lib/DboBuilder/insert.js +1 -1
  80. package/lib/DboBuilder/insert.ts +1 -1
  81. package/lib/DboBuilder/insertDataParse.js +1 -1
  82. package/lib/DboBuilder/insertDataParse.ts +1 -1
  83. package/lib/DboBuilder/runSQL.js +1 -1
  84. package/lib/DboBuilder/runSQL.ts +1 -1
  85. package/lib/DboBuilder/subscribe.d.ts +11 -0
  86. package/lib/DboBuilder/subscribe.d.ts.map +1 -0
  87. package/lib/DboBuilder/subscribe.js +189 -0
  88. package/lib/DboBuilder/subscribe.ts +230 -0
  89. package/lib/DboBuilder/update.js +1 -1
  90. package/lib/DboBuilder/update.ts +1 -1
  91. package/lib/DboBuilder.d.ts +1 -1
  92. package/lib/DboBuilder.d.ts.map +1 -1
  93. package/lib/DboBuilder.js +1 -1
  94. package/lib/DboBuilder.ts +1 -1
  95. package/lib/Prostgles.js +1 -1
  96. package/lib/Prostgles.ts +1 -1
  97. package/lib/{PubSubManager.d.ts → PubSubManager/PubSubManager.d.ts} +20 -17
  98. package/lib/PubSubManager/PubSubManager.d.ts.map +1 -0
  99. package/lib/PubSubManager/PubSubManager.js +776 -0
  100. package/lib/PubSubManager/PubSubManager.ts +998 -0
  101. package/lib/PubSubManager/initPubSubManager.d.ts +3 -0
  102. package/lib/PubSubManager/initPubSubManager.d.ts.map +1 -0
  103. package/lib/PubSubManager/initPubSubManager.js +615 -0
  104. package/lib/PubSubManager/initPubSubManager.ts +630 -0
  105. package/lib/PublishParser.js +1 -1
  106. package/lib/PublishParser.ts +1 -1
  107. package/lib/SyncReplication.d.ts +1 -1
  108. package/lib/SyncReplication.d.ts.map +1 -1
  109. package/lib/SyncReplication.js +1 -1
  110. package/lib/SyncReplication.ts +1 -1
  111. package/lib/TableConfig.js +1 -1
  112. package/lib/TableConfig.ts +1 -1
  113. package/lib/validation.js +1 -1
  114. package/lib/validation.ts +1 -1
  115. package/package.json +6 -5
  116. package/tests/client/PID.txt +1 -1
  117. package/tests/server/package-lock.json +9 -7
  118. package/dist/PubSubManager.d.ts.map +0 -1
  119. package/dist/PubSubManager.js +0 -1398
  120. package/dist/PubSubManager.js.map +0 -1
  121. package/lib/PubSubManager.d.ts.map +0 -1
  122. package/lib/PubSubManager.js +0 -1420
  123. package/lib/PubSubManager.ts +0 -1655
@@ -0,0 +1,776 @@
1
+ "use strict";
2
+ /*---------------------------------------------------------------------------------------------
3
+ * Copyright (c) Stefan L. All rights reserved.
4
+ * Licensed under the MIT License. See LICENSE in the project root for license information.
5
+ *--------------------------------------------------------------------------------------------*/
6
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
7
+ if (k2 === undefined) k2 = k;
8
+ var desc = Object.getOwnPropertyDescriptor(m, k);
9
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
10
+ desc = { enumerable: true, get: function() { return m[k]; } };
11
+ }
12
+ Object.defineProperty(o, k2, desc);
13
+ }) : (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ o[k2] = m[k];
16
+ }));
17
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
18
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
19
+ }) : function(o, v) {
20
+ o["default"] = v;
21
+ });
22
+ var __importStar = (this && this.__importStar) || function (mod) {
23
+ if (mod && mod.__esModule) return mod;
24
+ var result = {};
25
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
26
+ __setModuleDefault(result, mod);
27
+ return result;
28
+ };
29
+ var _a;
30
+ Object.defineProperty(exports, "__esModule", { value: true });
31
+ exports.omitKeys = exports.pickKeys = exports.PubSubManager = exports.log = exports.DEFAULT_SYNC_BATCH_SIZE = exports.asValue = void 0;
32
+ const utils_1 = require("../utils");
33
+ const DboBuilder_1 = require("../DboBuilder");
34
+ const Prostgles_1 = require("../Prostgles");
35
+ const initPubSubManager_1 = require("./initPubSubManager");
36
+ const Bluebird = __importStar(require("bluebird"));
37
+ const pgPromise = __importStar(require("pg-promise"));
38
+ const prostgles_types_1 = require("prostgles-types");
39
+ const SyncReplication_1 = require("../SyncReplication");
40
+ let pgp = pgPromise({
41
+ promiseLib: Bluebird
42
+ });
43
+ const asValue = (v) => pgp.as.format("$1", [v]);
44
+ exports.asValue = asValue;
45
+ exports.DEFAULT_SYNC_BATCH_SIZE = 50;
46
+ const log = (...args) => {
47
+ if (process.env.TEST_TYPE) {
48
+ console.log(...args);
49
+ }
50
+ };
51
+ exports.log = log;
52
+ class PubSubManager {
53
+ constructor(options) {
54
+ this.onSchemaChange = undefined;
55
+ this.NOTIF_TYPE = {
56
+ data: "data_has_changed",
57
+ schema: "schema_has_changed"
58
+ };
59
+ this.NOTIF_CHANNEL = {
60
+ preffix: 'prostgles_',
61
+ getFull: (appID) => {
62
+ const finalAppId = appID ?? this.appID;
63
+ if (!finalAppId)
64
+ throw "No appID";
65
+ return this.NOTIF_CHANNEL.preffix + finalAppId;
66
+ }
67
+ };
68
+ this.appCheckFrequencyMS = 10 * 1000;
69
+ this.destroyed = false;
70
+ this.destroy = () => {
71
+ this.destroyed = true;
72
+ if (this.appCheck) {
73
+ clearInterval(this.appCheck);
74
+ }
75
+ this.onSocketDisconnected();
76
+ // if(this.postgresNotifListenManager){
77
+ // this.postgresNotifListenManager.stopListening();
78
+ // }
79
+ if (!this.postgresNotifListenManager)
80
+ throw "this.postgresNotifListenManager missing";
81
+ this.postgresNotifListenManager.destroy();
82
+ };
83
+ this.canContinue = () => {
84
+ if (this.destroyed) {
85
+ console.trace("Could not start destroyed instance");
86
+ return false;
87
+ }
88
+ return true;
89
+ };
90
+ this.appChecking = false;
91
+ this.init = initPubSubManager_1.initPubSubManager.bind(this);
92
+ this.DB_OBJ_NAMES = {
93
+ trigger_add_remove_func: "prostgles.trigger_add_remove_func",
94
+ data_watch_func: "prostgles.prostgles_trigger_function",
95
+ schema_watch_func: "prostgles.schema_watch_func",
96
+ schema_watch_trigger: "prostgles_schema_watch_trigger_new"
97
+ };
98
+ this.prepareTriggers = async () => {
99
+ // SELECT * FROM pg_catalog.pg_event_trigger WHERE evtname
100
+ if (!this.appID)
101
+ throw "prepareTriggers failed: this.appID missing";
102
+ if (this.dboBuilder.prostgles.opts.watchSchema && !(await (0, Prostgles_1.isSuperUser)(this.db))) {
103
+ console.warn("prostgles watchSchema requires superuser db user. Will not watch using event triggers");
104
+ }
105
+ try {
106
+ await this.db.any(`
107
+ BEGIN;-- ISOLATION LEVEL SERIALIZABLE;
108
+
109
+ /** ${PubSubManager.EXCLUDE_QUERY_FROM_SCHEMA_WATCH_ID}
110
+ * Drop stale triggers
111
+ * */
112
+ DO
113
+ $do$
114
+ DECLARE trg RECORD;
115
+ q TEXT;
116
+ ev_trg_needed BOOLEAN := FALSE;
117
+ ev_trg_exists BOOLEAN := FALSE;
118
+ is_super_user BOOLEAN := FALSE;
119
+ BEGIN
120
+ --SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
121
+
122
+ LOCK TABLE prostgles.app_triggers IN ACCESS EXCLUSIVE MODE;
123
+ EXECUTE format(
124
+ $q$
125
+
126
+ CREATE TEMP TABLE %1$I AS --ON COMMIT DROP AS
127
+ SELECT * FROM prostgles.app_triggers;
128
+
129
+ DELETE FROM prostgles.app_triggers;
130
+
131
+ INSERT INTO prostgles.app_triggers
132
+ SELECT * FROM %1$I;
133
+
134
+ DROP TABLE IF EXISTS %1$I;
135
+ $q$,
136
+ ${(0, exports.asValue)('triggers_' + this.appID)}
137
+ );
138
+
139
+ is_super_user := EXISTS (select 1 from pg_user where usename = CURRENT_USER AND usesuper IS TRUE);
140
+ /**
141
+ * Delete stale app records
142
+ * */
143
+ DELETE FROM prostgles.apps
144
+ WHERE last_check < NOW() - 8 * check_frequency_ms * interval '1 millisecond';
145
+
146
+ DELETE FROM prostgles.app_triggers
147
+ WHERE app_id NOT IN (SELECT id FROM prostgles.apps);
148
+
149
+ /* DROP the old buggy schema watch trigger */
150
+ IF EXISTS (
151
+ SELECT 1 FROM pg_catalog.pg_event_trigger
152
+ WHERE evtname = 'prostgles_schema_watch_trigger'
153
+ ) AND is_super_user IS TRUE
154
+ THEN
155
+ DROP EVENT TRIGGER IF EXISTS prostgles_schema_watch_trigger;
156
+ END IF;
157
+
158
+ ev_trg_needed := EXISTS (SELECT 1 FROM prostgles.apps WHERE watching_schema IS TRUE);
159
+ ev_trg_exists := EXISTS (
160
+ SELECT 1 FROM pg_catalog.pg_event_trigger
161
+ WHERE evtname = ${(0, exports.asValue)(this.DB_OBJ_NAMES.schema_watch_trigger)}
162
+ );
163
+
164
+ -- RAISE NOTICE ' ev_trg_needed %, ev_trg_exists %', ev_trg_needed, ev_trg_exists;
165
+
166
+ /**
167
+ * DROP stale event trigger
168
+ * */
169
+ IF is_super_user IS TRUE AND ev_trg_needed IS FALSE AND ev_trg_exists IS TRUE THEN
170
+
171
+ SELECT format(
172
+ $$ DROP EVENT TRIGGER IF EXISTS %I ; $$
173
+ , ${(0, exports.asValue)(this.DB_OBJ_NAMES.schema_watch_trigger)}
174
+ )
175
+ INTO q;
176
+
177
+ --RAISE NOTICE ' DROP EVENT TRIGGER %', q;
178
+
179
+ EXECUTE q;
180
+
181
+ /**
182
+ * CREATE event trigger
183
+ * */
184
+ ELSIF
185
+ is_super_user IS TRUE
186
+ AND ev_trg_needed IS TRUE
187
+ AND ev_trg_exists IS FALSE
188
+ THEN
189
+
190
+ DROP EVENT TRIGGER IF EXISTS ${this.DB_OBJ_NAMES.schema_watch_trigger};
191
+ CREATE EVENT TRIGGER ${this.DB_OBJ_NAMES.schema_watch_trigger} ON ddl_command_end
192
+ WHEN TAG IN ('COMMENT', 'CREATE TABLE', 'ALTER TABLE', 'DROP TABLE', 'CREATE VIEW', 'DROP VIEW', 'ALTER VIEW', 'CREATE TABLE AS', 'SELECT INTO')
193
+ --WHEN TAG IN ('CREATE TABLE', 'ALTER TABLE', 'DROP TABLE', 'CREATE TRIGGER', 'DROP TRIGGER')
194
+ EXECUTE PROCEDURE ${this.DB_OBJ_NAMES.schema_watch_func}();
195
+
196
+ --RAISE NOTICE ' CREATED EVENT TRIGGER %', q;
197
+ END IF;
198
+
199
+
200
+ END
201
+ $do$;
202
+
203
+
204
+ COMMIT;
205
+ `).catch(e => {
206
+ console.error("prepareTriggers failed: ", e);
207
+ throw e;
208
+ });
209
+ return true;
210
+ }
211
+ catch (e) {
212
+ console.error("prepareTriggers failed: ", e);
213
+ throw e;
214
+ }
215
+ };
216
+ /* Relay relevant data to relevant subscriptions */
217
+ this.notifListener = async (data) => {
218
+ const str = data.payload;
219
+ if (!str) {
220
+ console.error("Empty notif?");
221
+ return;
222
+ }
223
+ const dataArr = str.split(PubSubManager.DELIMITER), notifType = dataArr[0];
224
+ (0, exports.log)(str);
225
+ if (notifType === this.NOTIF_TYPE.schema) {
226
+ if (this.onSchemaChange) {
227
+ const command = dataArr[1], event_type = dataArr[2], query = dataArr[3];
228
+ if (query) {
229
+ this.onSchemaChange({ command, query });
230
+ }
231
+ }
232
+ return;
233
+ }
234
+ if (notifType !== this.NOTIF_TYPE.data) {
235
+ console.error("Unexpected notif type: ", notifType);
236
+ return;
237
+ }
238
+ const table_name = dataArr[1], op_name = dataArr[2], condition_ids_str = dataArr[3];
239
+ // const triggers = await this.db.any("SELECT * FROM prostgles.triggers WHERE table_name = $1 AND id IN ($2:csv)", [table_name, condition_ids_str.split(",").map(v => +v)]);
240
+ // const conditions: string[] = triggers.map(t => t.condition);
241
+ (0, exports.log)("PG Trigger ->", dataArr.join("__"));
242
+ if (condition_ids_str && condition_ids_str.startsWith("error") &&
243
+ this._triggers && this._triggers[table_name] && this._triggers[table_name].length) {
244
+ const pref = "INTERNAL ERROR. Schema might have changed";
245
+ console.error(`${pref}: ${condition_ids_str}`);
246
+ this._triggers[table_name].map(c => {
247
+ const subs = this.getSubs(table_name, c);
248
+ subs.map(s => {
249
+ this.pushSubData(s, pref + ". Check server logs");
250
+ });
251
+ });
252
+ }
253
+ else if (condition_ids_str?.split(",").length &&
254
+ condition_ids_str?.split(",").every((c) => Number.isInteger(+c)) &&
255
+ this._triggers?.[table_name]?.length) {
256
+ const idxs = condition_ids_str.split(",").map(v => +v);
257
+ const conditions = this._triggers[table_name].filter((c, i) => idxs.includes(i));
258
+ (0, exports.log)("PG Trigger -> ", { table_name, op_name, condition_ids_str, conditions }, this._triggers[table_name]);
259
+ conditions.map(condition => {
260
+ const subs = this.getSubs(table_name, condition);
261
+ const syncs = this.getSyncs(table_name, condition);
262
+ syncs.map((s) => {
263
+ this.syncData(s, undefined, "trigger");
264
+ });
265
+ if (!subs) {
266
+ // console.error(`sub missing for ${table_name} ${condition}`, this.triggers);
267
+ // console.log(this.subs)
268
+ return;
269
+ }
270
+ /* Throttle the subscriptions */
271
+ for (var i = 0; i < subs.length; i++) {
272
+ var sub = subs[i];
273
+ if (this.dbo[sub.table_name] &&
274
+ sub.is_ready &&
275
+ (sub.socket_id && this.sockets[sub.socket_id]) || sub.func) {
276
+ const throttle = sub.throttle || 0;
277
+ if (sub.last_throttled <= Date.now() - throttle) {
278
+ /* It is assumed the policy was checked before this point */
279
+ this.pushSubData(sub);
280
+ // sub.last_throttled = Date.now();
281
+ }
282
+ else if (!sub.is_throttling) {
283
+ (0, exports.log)("throttling sub");
284
+ sub.is_throttling = setTimeout(() => {
285
+ (0, exports.log)("throttling finished. pushSubData...");
286
+ sub.is_throttling = null;
287
+ this.pushSubData(sub);
288
+ }, throttle); // sub.throttle);
289
+ }
290
+ }
291
+ }
292
+ });
293
+ }
294
+ else {
295
+ // if(!this._triggers || !this._triggers[table_name] || !this._triggers[table_name].length){
296
+ // console.warn(190, "Trigger sub not found. DROPPING TRIGGER", table_name, condition_ids_str, this._triggers);
297
+ // this.dropTrigger(table_name);
298
+ // } else {
299
+ // }
300
+ console.warn(190, "Trigger sub issue: ", table_name, condition_ids_str, this._triggers);
301
+ }
302
+ };
303
+ this.getActiveListeners = () => {
304
+ let result = [];
305
+ const upsert = (t, c) => {
306
+ if (!result.find(r => r.table_name === t && r.condition === c)) {
307
+ result.push({ table_name: t, condition: c });
308
+ }
309
+ };
310
+ (this.syncs || []).map(s => {
311
+ upsert(s.table_name, s.condition);
312
+ });
313
+ Object.keys(this.subs || {}).map(table_name => {
314
+ Object.keys(this.subs[table_name] || {}).map(condition => {
315
+ if (this.subs[table_name][condition].subs.length) {
316
+ upsert(table_name, condition);
317
+ }
318
+ });
319
+ });
320
+ return result;
321
+ };
322
+ this.checkIfTimescaleBug = async (table_name) => {
323
+ const schema = "_timescaledb_catalog", res = await this.db.oneOrNone("SELECT EXISTS( \
324
+ SELECT * \
325
+ FROM information_schema.tables \
326
+ WHERE 1 = 1 \
327
+ AND table_schema = ${schema} \
328
+ AND table_name = 'hypertable' \
329
+ );", { schema });
330
+ if (res.exists) {
331
+ let isHyperTable = await this.db.any("SELECT * FROM " + (0, prostgles_types_1.asName)(schema) + ".hypertable WHERE table_name = ${table_name};", { table_name, schema });
332
+ if (isHyperTable && isHyperTable.length) {
333
+ throw "Triggers do not work on timescaledb hypertables due to bug:\nhttps://github.com/timescale/timescaledb/issues/1084";
334
+ }
335
+ }
336
+ return true;
337
+ };
338
+ /*
339
+ A table will only have a trigger with all conditions (for different subs)
340
+ conditions = ["user_id = 1"]
341
+ fields = ["user_id"]
342
+ */
343
+ this.getMyTriggerQuery = async () => {
344
+ return pgp.as.format(`
345
+ SELECT * --, ROW_NUMBER() OVER(PARTITION BY table_name ORDER BY table_name, condition ) - 1 as id
346
+ FROM prostgles.v_triggers
347
+ WHERE app_id = $1
348
+ ORDER BY table_name, condition
349
+ `, [this.appID]);
350
+ };
351
+ this.addTriggerPool = undefined;
352
+ const { wsChannelNamePrefix, pgChannelName, onSchemaChange, dboBuilder } = options;
353
+ if (!dboBuilder.db || !dboBuilder.dbo) {
354
+ throw 'MISSING: db_pg, db';
355
+ }
356
+ this.onSchemaChange = onSchemaChange;
357
+ this.dboBuilder = dboBuilder;
358
+ this.sockets = {};
359
+ this.subs = {};
360
+ this.syncs = [];
361
+ this.socketChannelPreffix = wsChannelNamePrefix || "_psqlWS_";
362
+ (0, exports.log)("Created PubSubManager");
363
+ }
364
+ get db() {
365
+ return this.dboBuilder.db;
366
+ }
367
+ get dbo() {
368
+ return this.dboBuilder.dbo;
369
+ }
370
+ isReady() {
371
+ if (!this.postgresNotifListenManager)
372
+ throw "this.postgresNotifListenManager missing";
373
+ return this.postgresNotifListenManager.isListening();
374
+ }
375
+ getSubs(table_name, condition) {
376
+ return this.subs?.[table_name]?.[condition]?.subs;
377
+ }
378
+ getSyncs(table_name, condition) {
379
+ return (this.syncs || [])
380
+ .filter((s) => s.table_name === table_name && s.condition === condition);
381
+ }
382
+ pushSubData(sub, err) {
383
+ if (!sub)
384
+ throw "pushSubData: invalid sub";
385
+ const { table_name, filter, params, table_rules, socket_id, channel_name, func } = sub; //, subOne = false
386
+ sub.last_throttled = Date.now();
387
+ if (err) {
388
+ if (socket_id) {
389
+ this.sockets[socket_id].emit(channel_name, { err });
390
+ }
391
+ return true;
392
+ }
393
+ return new Promise(async (resolve, reject) => {
394
+ /* TODO: Retire subOne -> it's redundant */
395
+ // this.dbo[table_name][subOne? "findOne" : "find"](filter, params, null, table_rules)
396
+ if (!this.dbo?.[table_name]?.find) {
397
+ throw new Error(`1107 this.dbo.${table_name}.find`);
398
+ }
399
+ this.dbo?.[table_name]?.find?.(filter, params, undefined, table_rules)
400
+ .then(data => {
401
+ if (socket_id && this.sockets[socket_id]) {
402
+ (0, exports.log)("Pushed " + data.length + " records to sub");
403
+ this.sockets[socket_id].emit(channel_name, { data }, () => {
404
+ resolve(data);
405
+ });
406
+ /* TO DO: confirm receiving data or server will unsubscribe
407
+ { data }, (cb)=> { console.log(cb) });
408
+ */
409
+ }
410
+ else if (func) {
411
+ func(data);
412
+ resolve(data);
413
+ }
414
+ sub.last_throttled = Date.now();
415
+ }).catch(err => {
416
+ const errObj = { _err_msg: err.toString(), err };
417
+ if (socket_id && this.sockets[socket_id]) {
418
+ this.sockets[socket_id].emit(channel_name, { err: errObj });
419
+ }
420
+ else if (func) {
421
+ func({ err: errObj });
422
+ }
423
+ reject(errObj);
424
+ });
425
+ });
426
+ }
427
+ upsertSocket(socket, channel_name) {
428
+ if (socket && !this.sockets[socket.id]) {
429
+ this.sockets[socket.id] = socket;
430
+ socket.on("disconnect", () => this.onSocketDisconnected(socket));
431
+ }
432
+ }
433
+ async syncData(sync, clientData, source) {
434
+ return await (0, SyncReplication_1.syncData)(this, sync, clientData, source);
435
+ }
436
+ /**
437
+ * Returns a sync channel
438
+ * A sync channel is unique per socket for each filter
439
+ */
440
+ async addSync(syncParams) {
441
+ const { socket = null, table_info = null, table_rules, synced_field = null, allow_delete = false, id_fields = [], filter = {}, params, condition = "", throttle = 0 } = syncParams || {};
442
+ let conditionParsed = parseCondition(condition);
443
+ if (!socket || !table_info)
444
+ throw "socket or table_info missing";
445
+ const { name: table_name } = table_info, channel_name = `${this.socketChannelPreffix}.${table_name}.${JSON.stringify(filter)}.sync`;
446
+ if (!synced_field)
447
+ throw "synced_field missing from table_rules";
448
+ this.upsertSocket(socket, channel_name);
449
+ const upsertSync = () => {
450
+ let newSync = {
451
+ channel_name,
452
+ table_name,
453
+ filter,
454
+ condition: conditionParsed,
455
+ synced_field,
456
+ id_fields,
457
+ allow_delete,
458
+ table_rules,
459
+ throttle: Math.max(throttle || 0, table_rules?.sync?.throttle || 0),
460
+ batch_size: (0, utils_1.get)(table_rules, "sync.batch_size") || exports.DEFAULT_SYNC_BATCH_SIZE,
461
+ last_throttled: 0,
462
+ socket_id: socket.id,
463
+ is_sync: true,
464
+ last_synced: 0,
465
+ lr: undefined,
466
+ table_info,
467
+ is_syncing: false,
468
+ wal: undefined,
469
+ socket,
470
+ params
471
+ };
472
+ /* Only a sync per socket per table per condition allowed */
473
+ this.syncs = this.syncs || [];
474
+ let existing = this.syncs.find(s => s.socket_id === socket.id && s.channel_name === channel_name);
475
+ if (!existing) {
476
+ this.syncs.push(newSync);
477
+ // console.log("Added SYNC");
478
+ socket.removeAllListeners(channel_name + "unsync");
479
+ socket.once(channel_name + "unsync", (_data, cb) => {
480
+ this.onSocketDisconnected(socket, channel_name);
481
+ cb(null, { res: "ok" });
482
+ });
483
+ socket.removeAllListeners(channel_name);
484
+ socket.on(channel_name, (data, cb) => {
485
+ if (!data) {
486
+ cb({ err: "Unexpected request. Need data or onSyncRequest" });
487
+ return;
488
+ }
489
+ /*
490
+ */
491
+ /* Server will:
492
+ 1. Ask for last_synced emit(onSyncRequest)
493
+ 2. Ask for data >= server_synced emit(onPullRequest)
494
+ -> Upsert that data
495
+ 2. Push data >= last_synced emit(data.data)
496
+
497
+ Client will:
498
+ 1. Send last_synced on(onSyncRequest)
499
+ 2. Send data >= server_synced on(onPullRequest)
500
+ 3. Send data on CRUD emit(data.data | data.deleted)
501
+ 4. Upsert data.data | deleted on(data.data | data.deleted)
502
+ */
503
+ // if(data.data){
504
+ // console.error("THIS SHOUKD NEVER FIRE !! NEW DATA FROM SYNC");
505
+ // this.upsertClientData(newSync, data.data);
506
+ // } else
507
+ if (data.onSyncRequest) {
508
+ // console.log("syncData from socket")
509
+ this.syncData(newSync, data.onSyncRequest, "client");
510
+ // console.log("onSyncRequest ", socket._user)
511
+ }
512
+ else {
513
+ console.error("Unexpected sync request data from client: ", data);
514
+ }
515
+ });
516
+ // socket.emit(channel_name, { onSyncRequest: true }, (response) => {
517
+ // console.log(response)
518
+ // });
519
+ }
520
+ else {
521
+ console.error("UNCLOSED DUPLICATE SYNC FOUND");
522
+ }
523
+ return newSync;
524
+ };
525
+ // const { min_id, max_id, count, max_synced } = params;
526
+ let sync = upsertSync();
527
+ await this.addTrigger({ table_name, condition: conditionParsed });
528
+ return channel_name;
529
+ }
530
+ /* Must return a channel for socket */
531
+ /* The distinct list of channel names must have a corresponding trigger in the database */
532
+ async addSub(subscriptionParams) {
533
+ const { socket, func = null, table_info = null, table_rules, filter = {}, params = {}, condition = "", throttle = 0, //subOne = false,
534
+ viewOptions } = subscriptionParams || {};
535
+ let validated_throttle = subscriptionParams.throttle || 10;
536
+ if ((!socket && !func) || !table_info)
537
+ throw "socket/func or table_info missing";
538
+ const pubThrottle = (0, utils_1.get)(table_rules, ["subscribe", "throttle"]) || 0;
539
+ if (pubThrottle && Number.isInteger(pubThrottle) && pubThrottle > 0) {
540
+ validated_throttle = pubThrottle;
541
+ }
542
+ if (throttle && Number.isInteger(throttle) && throttle >= pubThrottle) {
543
+ validated_throttle = throttle;
544
+ }
545
+ const channel_name = `${this.socketChannelPreffix}.${table_info.name}.${JSON.stringify(filter)}.${JSON.stringify(params)}.${"m"}.sub`;
546
+ this.upsertSocket(socket, channel_name);
547
+ const upsertSub = (newSubData) => {
548
+ const { table_name, condition: _cond, is_ready = false, parentSubParams } = newSubData, condition = parseCondition(_cond), newSub = {
549
+ socket,
550
+ table_name: table_info.name,
551
+ table_info,
552
+ filter,
553
+ params,
554
+ table_rules,
555
+ channel_name,
556
+ parentSubParams,
557
+ func: func ?? undefined,
558
+ socket_id: socket?.id,
559
+ throttle: validated_throttle,
560
+ is_throttling: null,
561
+ last_throttled: 0,
562
+ is_ready,
563
+ };
564
+ this.subs[table_name] = this.subs[table_name] ?? {};
565
+ this.subs[table_name][condition] = this.subs[table_name][condition] ?? { subs: [] };
566
+ this.subs[table_name][condition].subs = this.subs[table_name][condition].subs ?? [];
567
+ // console.log("1034 upsertSub", this.subs)
568
+ const sub_idx = this.subs[table_name][condition].subs.findIndex(s => s.channel_name === channel_name &&
569
+ (socket && s.socket_id === socket.id ||
570
+ func && s.func === func));
571
+ if (sub_idx < 0) {
572
+ this.subs[table_name][condition].subs.push(newSub);
573
+ if (socket) {
574
+ const chnUnsub = channel_name + "unsubscribe";
575
+ socket.removeAllListeners(chnUnsub);
576
+ socket.once(chnUnsub, (_data, cb) => {
577
+ const res = this.onSocketDisconnected(socket, channel_name);
578
+ cb(null, { res });
579
+ });
580
+ }
581
+ }
582
+ else {
583
+ this.subs[table_name][condition].subs[sub_idx] = newSub;
584
+ }
585
+ if (is_ready) {
586
+ this.pushSubData(newSub);
587
+ }
588
+ };
589
+ if (table_info.is_view) {
590
+ if (viewOptions?.relatedTables.length) {
591
+ viewOptions?.relatedTables.map(async (relatedTable) => {
592
+ const params = {
593
+ table_name: relatedTable.tableName,
594
+ condition: relatedTable.condition,
595
+ parentSubParams: {
596
+ ...subscriptionParams,
597
+ channel_name
598
+ },
599
+ };
600
+ upsertSub({
601
+ ...params,
602
+ is_ready: false
603
+ });
604
+ await this.addTrigger(params);
605
+ upsertSub({
606
+ ...params,
607
+ is_ready: true
608
+ });
609
+ });
610
+ return channel_name;
611
+ }
612
+ else {
613
+ throw "PubSubManager: view parent_tables missing";
614
+ }
615
+ /* */
616
+ }
617
+ else {
618
+ /* Just a table, add table + condition trigger */
619
+ // console.log(table_info, 202);
620
+ upsertSub({
621
+ table_name: table_info.name,
622
+ condition: parseCondition(condition),
623
+ parentSubParams: undefined,
624
+ is_ready: false
625
+ });
626
+ await this.addTrigger({
627
+ table_name: table_info.name,
628
+ condition: parseCondition(condition),
629
+ });
630
+ upsertSub({
631
+ table_name: table_info.name,
632
+ condition: parseCondition(condition),
633
+ parentSubParams: undefined,
634
+ is_ready: true
635
+ });
636
+ return channel_name;
637
+ }
638
+ }
639
+ removeLocalSub(table_name, condition, func) {
640
+ let cond = parseCondition(condition);
641
+ if ((0, utils_1.get)(this.subs, [table_name, cond, "subs"])) {
642
+ this.subs[table_name][cond].subs.map((sub, i) => {
643
+ if (sub.func && sub.func === func) {
644
+ this.subs[table_name][cond].subs.splice(i, 1);
645
+ }
646
+ });
647
+ }
648
+ else {
649
+ console.error("Could not unsubscribe. Subscription might not have initialised yet");
650
+ }
651
+ }
652
+ onSocketDisconnected(socket, channel_name) {
653
+ // process.on('warning', e => {
654
+ // console.warn(e.stack)
655
+ // });
656
+ // console.log("onSocketDisconnected", channel_name, this.syncs)
657
+ if (this.subs) {
658
+ Object.keys(this.subs).map(table_name => {
659
+ Object.keys(this.subs[table_name]).map(condition => {
660
+ this.subs[table_name][condition].subs.map((sub, i) => {
661
+ /**
662
+ * If a channel name is specified then delete triggers
663
+ */
664
+ if ((socket && sub.socket_id === socket.id) &&
665
+ (!channel_name || sub.channel_name === channel_name)) {
666
+ this.subs[table_name][condition].subs.splice(i, 1);
667
+ if (!this.subs[table_name][condition].subs.length) {
668
+ delete this.subs[table_name][condition];
669
+ if ((0, prostgles_types_1.isEmpty)(this.subs[table_name])) {
670
+ delete this.subs[table_name];
671
+ }
672
+ }
673
+ }
674
+ });
675
+ });
676
+ });
677
+ }
678
+ if (this.syncs) {
679
+ this.syncs = this.syncs.filter(s => {
680
+ const matchesSocket = Boolean(socket && s.socket_id !== socket.id);
681
+ if (channel_name) {
682
+ return matchesSocket || s.channel_name !== channel_name;
683
+ }
684
+ return matchesSocket;
685
+ });
686
+ }
687
+ if (!socket) {
688
+ }
689
+ else if (!channel_name) {
690
+ delete this.sockets[socket.id];
691
+ }
692
+ else {
693
+ socket.removeAllListeners(channel_name);
694
+ socket.removeAllListeners(channel_name + "unsync");
695
+ socket.removeAllListeners(channel_name + "unsubscribe");
696
+ }
697
+ return "ok";
698
+ }
699
+ async addTrigger(params, viewOptions) {
700
+ try {
701
+ let { table_name, condition } = { ...params };
702
+ if (!table_name)
703
+ throw "MISSING table_name";
704
+ if (!this.appID)
705
+ throw "MISSING appID";
706
+ if (!condition || !condition.trim().length) {
707
+ condition = "TRUE";
708
+ }
709
+ // console.log(1623, { app_id, addTrigger: { table_name, condition } });
710
+ await this.checkIfTimescaleBug(table_name);
711
+ const trgVals = {
712
+ tbl: (0, exports.asValue)(table_name),
713
+ cond: (0, exports.asValue)(condition),
714
+ };
715
+ await this.db.any(`
716
+ BEGIN WORK;
717
+ LOCK TABLE prostgles.app_triggers IN ACCESS EXCLUSIVE MODE;
718
+
719
+ INSERT INTO prostgles.app_triggers (table_name, condition, app_id, related_view_name, related_view_def)
720
+ VALUES (${trgVals.tbl}, ${trgVals.cond}, ${(0, exports.asValue)(this.appID)}, ${viewOptions?.viewName ?? null}, ${viewOptions?.definition ?? null})
721
+ ON CONFLICT DO NOTHING;
722
+
723
+ COMMIT WORK;
724
+ `);
725
+ (0, exports.log)("addTrigger.. ", { table_name, condition });
726
+ const triggers = await this.db.any(await this.getMyTriggerQuery());
727
+ this._triggers = {};
728
+ triggers.map(t => {
729
+ this._triggers = this._triggers || {};
730
+ this._triggers[t.table_name] = this._triggers[t.table_name] || [];
731
+ if (!this._triggers[t.table_name].includes(t.condition)) {
732
+ this._triggers[t.table_name].push(t.condition);
733
+ }
734
+ });
735
+ (0, exports.log)("trigger added.. ", { table_name, condition });
736
+ return true;
737
+ // console.log("1612", JSON.stringify(triggers, null, 2))
738
+ // console.log("1613",JSON.stringify(this._triggers, null, 2))
739
+ }
740
+ catch (e) {
741
+ console.trace("Failed adding trigger", e);
742
+ // throw e
743
+ }
744
+ }
745
+ }
746
+ exports.PubSubManager = PubSubManager;
747
+ _a = PubSubManager;
748
+ PubSubManager.DELIMITER = '|$prstgls$|';
749
+ // ,datname
750
+ // ,usename
751
+ // ,client_hostname
752
+ // ,client_port
753
+ // ,backend_start
754
+ // ,query_start
755
+ // ,query
756
+ // ,state
757
+ // console.log(await _db.any(`
758
+ // SELECT pid, application_name, state
759
+ // FROM pg_stat_activity
760
+ // WHERE application_name IS NOT NULL AND application_name != '' -- state = 'active';
761
+ // `))
762
+ PubSubManager.canCreate = async (db) => {
763
+ const canExecute = await (0, DboBuilder_1.canEXECUTE)(db);
764
+ const isSuperUs = await (0, Prostgles_1.isSuperUser)(db);
765
+ return { canExecute, isSuperUs, yes: canExecute && isSuperUs };
766
+ };
767
+ PubSubManager.create = async (options) => {
768
+ const res = new PubSubManager(options);
769
+ return await res.init();
770
+ };
771
+ PubSubManager.SCHEMA_ALTERING_QUERIES = ['CREATE TABLE', 'ALTER TABLE', 'DROP TABLE', 'CREATE VIEW', 'DROP VIEW', 'ALTER VIEW', 'CREATE TABLE AS', 'SELECT INTO'];
772
+ PubSubManager.EXCLUDE_QUERY_FROM_SCHEMA_WATCH_ID = "prostgles internal query that should be excluded from ";
773
+ const parseCondition = (condition) => Boolean(condition && condition.trim().length) ? condition : "TRUE";
774
+ var prostgles_types_2 = require("prostgles-types");
775
+ Object.defineProperty(exports, "pickKeys", { enumerable: true, get: function () { return prostgles_types_2.pickKeys; } });
776
+ Object.defineProperty(exports, "omitKeys", { enumerable: true, get: function () { return prostgles_types_2.omitKeys; } });