@dxos/functions 0.5.3-main.bc67fdb → 0.5.3-main.bfb5bca

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 (85) hide show
  1. package/dist/lib/browser/chunk-4D4I3YMJ.mjs +86 -0
  2. package/dist/lib/browser/chunk-4D4I3YMJ.mjs.map +7 -0
  3. package/dist/lib/browser/index.mjs +752 -480
  4. package/dist/lib/browser/index.mjs.map +4 -4
  5. package/dist/lib/browser/meta.json +1 -1
  6. package/dist/lib/browser/types.mjs +14 -0
  7. package/dist/lib/browser/types.mjs.map +7 -0
  8. package/dist/lib/node/chunk-3UYUR5N5.cjs +103 -0
  9. package/dist/lib/node/chunk-3UYUR5N5.cjs.map +7 -0
  10. package/dist/lib/node/index.cjs +739 -473
  11. package/dist/lib/node/index.cjs.map +4 -4
  12. package/dist/lib/node/meta.json +1 -1
  13. package/dist/lib/node/types.cjs +35 -0
  14. package/dist/lib/node/types.cjs.map +7 -0
  15. package/dist/types/src/browser/index.d.ts +2 -0
  16. package/dist/types/src/browser/index.d.ts.map +1 -0
  17. package/dist/types/src/function/function-registry.d.ts +24 -0
  18. package/dist/types/src/function/function-registry.d.ts.map +1 -0
  19. package/dist/types/src/function/function-registry.test.d.ts +2 -0
  20. package/dist/types/src/function/function-registry.test.d.ts.map +1 -0
  21. package/dist/types/src/function/index.d.ts +2 -0
  22. package/dist/types/src/function/index.d.ts.map +1 -0
  23. package/dist/types/src/handler.d.ts.map +1 -1
  24. package/dist/types/src/index.d.ts +2 -0
  25. package/dist/types/src/index.d.ts.map +1 -1
  26. package/dist/types/src/runtime/dev-server.d.ts +7 -10
  27. package/dist/types/src/runtime/dev-server.d.ts.map +1 -1
  28. package/dist/types/src/runtime/scheduler.d.ts +11 -59
  29. package/dist/types/src/runtime/scheduler.d.ts.map +1 -1
  30. package/dist/types/src/testing/functions-integration.test.d.ts +2 -0
  31. package/dist/types/src/testing/functions-integration.test.d.ts.map +1 -0
  32. package/dist/types/src/testing/index.d.ts +4 -0
  33. package/dist/types/src/testing/index.d.ts.map +1 -0
  34. package/dist/types/src/testing/setup.d.ts +5 -0
  35. package/dist/types/src/testing/setup.d.ts.map +1 -0
  36. package/dist/types/src/testing/test/handler.d.ts +1 -0
  37. package/dist/types/src/testing/test/handler.d.ts.map +1 -1
  38. package/dist/types/src/testing/types.d.ts +9 -0
  39. package/dist/types/src/testing/types.d.ts.map +1 -0
  40. package/dist/types/src/testing/util.d.ts +3 -0
  41. package/dist/types/src/testing/util.d.ts.map +1 -0
  42. package/dist/types/src/trigger/index.d.ts +2 -0
  43. package/dist/types/src/trigger/index.d.ts.map +1 -0
  44. package/dist/types/src/trigger/trigger-registry.d.ts +37 -0
  45. package/dist/types/src/trigger/trigger-registry.d.ts.map +1 -0
  46. package/dist/types/src/trigger/trigger-registry.test.d.ts +2 -0
  47. package/dist/types/src/trigger/trigger-registry.test.d.ts.map +1 -0
  48. package/dist/types/src/trigger/type/index.d.ts +5 -0
  49. package/dist/types/src/trigger/type/index.d.ts.map +1 -0
  50. package/dist/types/src/trigger/type/subscription-trigger.d.ts +4 -0
  51. package/dist/types/src/trigger/type/subscription-trigger.d.ts.map +1 -0
  52. package/dist/types/src/trigger/type/timer-trigger.d.ts +4 -0
  53. package/dist/types/src/trigger/type/timer-trigger.d.ts.map +1 -0
  54. package/dist/types/src/trigger/type/webhook-trigger.d.ts +4 -0
  55. package/dist/types/src/trigger/type/webhook-trigger.d.ts.map +1 -0
  56. package/dist/types/src/trigger/type/websocket-trigger.d.ts +13 -0
  57. package/dist/types/src/trigger/type/websocket-trigger.d.ts.map +1 -0
  58. package/dist/types/src/types.d.ts +152 -119
  59. package/dist/types/src/types.d.ts.map +1 -1
  60. package/package.json +30 -14
  61. package/schema/functions.json +144 -116
  62. package/src/browser/index.ts +5 -0
  63. package/src/function/function-registry.test.ts +105 -0
  64. package/src/function/function-registry.ts +90 -0
  65. package/src/function/index.ts +5 -0
  66. package/src/index.ts +2 -0
  67. package/src/runtime/dev-server.test.ts +15 -35
  68. package/src/runtime/dev-server.ts +38 -21
  69. package/src/runtime/scheduler.test.ts +59 -75
  70. package/src/runtime/scheduler.ts +70 -297
  71. package/src/testing/functions-integration.test.ts +100 -0
  72. package/src/testing/index.ts +7 -0
  73. package/src/testing/setup.ts +43 -0
  74. package/src/testing/test/handler.ts +8 -2
  75. package/src/testing/types.ts +9 -0
  76. package/src/testing/util.ts +16 -0
  77. package/src/trigger/index.ts +5 -0
  78. package/src/trigger/trigger-registry.test.ts +272 -0
  79. package/src/trigger/trigger-registry.ts +211 -0
  80. package/src/trigger/type/index.ts +8 -0
  81. package/src/trigger/type/subscription-trigger.ts +86 -0
  82. package/src/trigger/type/timer-trigger.ts +45 -0
  83. package/src/trigger/type/webhook-trigger.ts +48 -0
  84. package/src/trigger/type/websocket-trigger.ts +92 -0
  85. package/src/types.ts +82 -54
@@ -29,61 +29,157 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
29
29
  var node_exports = {};
30
30
  __export(node_exports, {
31
31
  DevServer: () => DevServer,
32
- FunctionManifestSchema: () => FunctionManifestSchema,
32
+ FUNCTION_SCHEMA: () => import_chunk_3UYUR5N5.FUNCTION_SCHEMA,
33
+ FunctionDef: () => import_chunk_3UYUR5N5.FunctionDef,
34
+ FunctionManifestSchema: () => import_chunk_3UYUR5N5.FunctionManifestSchema,
35
+ FunctionRegistry: () => FunctionRegistry,
36
+ FunctionTrigger: () => import_chunk_3UYUR5N5.FunctionTrigger,
33
37
  Scheduler: () => Scheduler,
38
+ TriggerRegistry: () => TriggerRegistry,
34
39
  subscriptionHandler: () => subscriptionHandler
35
40
  });
36
41
  module.exports = __toCommonJS(node_exports);
37
- var import_client = require("@dxos/client");
42
+ var import_chunk_3UYUR5N5 = require("./chunk-3UYUR5N5.cjs");
43
+ var import_async = require("@dxos/async");
44
+ var import_echo = require("@dxos/client/echo");
45
+ var import_context = require("@dxos/context");
46
+ var import_keys = require("@dxos/keys");
38
47
  var import_log = require("@dxos/log");
39
48
  var import_util = require("@dxos/util");
49
+ var import_client = require("@dxos/client");
50
+ var import_log2 = require("@dxos/log");
51
+ var import_util2 = require("@dxos/util");
40
52
  var import_express = __toESM(require("express"));
41
53
  var import_get_port_please = require("get-port-please");
42
54
  var import_node_path = require("node:path");
43
- var import_async = require("@dxos/async");
55
+ var import_async2 = require("@dxos/async");
56
+ var import_context2 = require("@dxos/context");
44
57
  var import_invariant = require("@dxos/invariant");
45
- var import_log2 = require("@dxos/log");
58
+ var import_log3 = require("@dxos/log");
59
+ var import_node_path2 = __toESM(require("node:path"));
60
+ var import_async3 = require("@dxos/async");
61
+ var import_context3 = require("@dxos/context");
62
+ var import_log4 = require("@dxos/log");
63
+ var import_async4 = require("@dxos/async");
64
+ var import_echo2 = require("@dxos/client/echo");
65
+ var import_context4 = require("@dxos/context");
66
+ var import_echo_schema = require("@dxos/echo-schema");
67
+ var import_invariant2 = require("@dxos/invariant");
68
+ var import_keys2 = require("@dxos/keys");
69
+ var import_log5 = require("@dxos/log");
70
+ var import_util3 = require("@dxos/util");
71
+ var import_types = require("@braneframe/types");
72
+ var import_async5 = require("@dxos/async");
73
+ var import_echo3 = require("@dxos/client/echo");
74
+ var import_echo_db = require("@dxos/echo-db");
75
+ var import_log6 = require("@dxos/log");
46
76
  var import_cron = require("cron");
77
+ var import_async6 = require("@dxos/async");
78
+ var import_log7 = require("@dxos/log");
47
79
  var import_get_port_please2 = require("get-port-please");
48
80
  var import_node_http = __toESM(require("node:http"));
49
- var import_node_path2 = __toESM(require("node:path"));
81
+ var import_log8 = require("@dxos/log");
50
82
  var import_ws = __toESM(require("ws"));
51
- var import_types = require("@braneframe/types");
52
- var import_async2 = require("@dxos/async");
53
- var import_echo = require("@dxos/client/echo");
54
- var import_context = require("@dxos/context");
55
- var import_invariant2 = require("@dxos/invariant");
56
- var import_log3 = require("@dxos/log");
57
- var import_util2 = require("@dxos/util");
58
- var S = __toESM(require("@effect/schema/Schema"));
59
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
60
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
61
- }) : x)(function(x) {
62
- if (typeof require !== "undefined")
63
- return require.apply(this, arguments);
64
- throw Error('Dynamic require of "' + x + '" is not supported');
65
- });
66
- var __dxlog_file = "/home/runner/work/dxos/dxos/packages/core/functions/src/handler.ts";
83
+ var import_async7 = require("@dxos/async");
84
+ var import_log9 = require("@dxos/log");
85
+ var __dxlog_file = "/home/runner/work/dxos/dxos/packages/core/functions/src/function/function-registry.ts";
86
+ var FunctionRegistry = class extends import_context.Resource {
87
+ constructor(_client) {
88
+ super();
89
+ this._client = _client;
90
+ this._functionBySpaceKey = new import_util.ComplexMap(import_keys.PublicKey.hash);
91
+ this.registered = new import_async.Event();
92
+ }
93
+ getFunctions(space) {
94
+ return this._functionBySpaceKey.get(space.key) ?? [];
95
+ }
96
+ /**
97
+ * Loads function definitions from the manifest into the space.
98
+ * We first load all the definitions from the space to deduplicate by functionId.
99
+ */
100
+ async register(space, functions) {
101
+ (0, import_log.log)("register", {
102
+ space: space.key,
103
+ functions: functions?.length ?? 0
104
+ }, {
105
+ F: __dxlog_file,
106
+ L: 38,
107
+ S: this,
108
+ C: (f, a) => f(...a)
109
+ });
110
+ if (!functions?.length) {
111
+ return;
112
+ }
113
+ if (!space.db.graph.runtimeSchemaRegistry.hasSchema(import_chunk_3UYUR5N5.FunctionDef)) {
114
+ space.db.graph.runtimeSchemaRegistry.registerSchema(import_chunk_3UYUR5N5.FunctionDef);
115
+ }
116
+ const { objects: existing } = await space.db.query(import_echo.Filter.schema(import_chunk_3UYUR5N5.FunctionDef)).run();
117
+ const { added } = (0, import_util.diff)(existing, functions, (a, b) => a.uri === b.uri);
118
+ added.forEach((def) => space.db.add((0, import_echo.create)(import_chunk_3UYUR5N5.FunctionDef, def)));
119
+ }
120
+ async _open() {
121
+ import_log.log.info("opening...", void 0, {
122
+ F: __dxlog_file,
123
+ L: 54,
124
+ S: this,
125
+ C: (f, a) => f(...a)
126
+ });
127
+ const spacesSubscription = this._client.spaces.subscribe(async (spaces) => {
128
+ for (const space of spaces) {
129
+ if (this._functionBySpaceKey.has(space.key)) {
130
+ continue;
131
+ }
132
+ const registered = [];
133
+ this._functionBySpaceKey.set(space.key, registered);
134
+ await space.waitUntilReady();
135
+ if (this._ctx.disposed) {
136
+ break;
137
+ }
138
+ this._ctx.onDispose(space.db.query(import_echo.Filter.schema(import_chunk_3UYUR5N5.FunctionDef)).subscribe(({ objects }) => {
139
+ const { added } = (0, import_util.diff)(registered, objects, (a, b) => a.uri === b.uri);
140
+ if (added.length > 0) {
141
+ registered.push(...added);
142
+ this.registered.emit({
143
+ space,
144
+ added
145
+ });
146
+ }
147
+ }));
148
+ }
149
+ });
150
+ this._ctx.onDispose(() => spacesSubscription.unsubscribe());
151
+ }
152
+ async _close(_) {
153
+ import_log.log.info("closing...", void 0, {
154
+ F: __dxlog_file,
155
+ L: 87,
156
+ S: this,
157
+ C: (f, a) => f(...a)
158
+ });
159
+ this._functionBySpaceKey.clear();
160
+ }
161
+ };
162
+ var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/core/functions/src/handler.ts";
67
163
  var subscriptionHandler = (handler) => {
68
164
  return ({ event: { data }, context, ...rest }) => {
69
165
  const { client } = context;
70
166
  const space = data.spaceKey ? client.spaces.get(import_client.PublicKey.from(data.spaceKey)) : void 0;
71
- const objects = space ? data.objects?.map((id) => space.db.getObjectById(id)).filter(import_util.nonNullable) : [];
167
+ const objects = space ? data.objects?.map((id) => space.db.getObjectById(id)).filter(import_util2.nonNullable) : [];
72
168
  if (!!data.spaceKey && !space) {
73
- import_log.log.warn("invalid space", {
169
+ import_log2.log.warn("invalid space", {
74
170
  data
75
171
  }, {
76
- F: __dxlog_file,
172
+ F: __dxlog_file2,
77
173
  L: 91,
78
174
  S: void 0,
79
175
  C: (f, a) => f(...a)
80
176
  });
81
177
  } else {
82
- import_log.log.info("handler", {
178
+ import_log2.log.info("handler", {
83
179
  space: space?.key.truncate(),
84
180
  objects: objects?.length
85
181
  }, {
86
- F: __dxlog_file,
182
+ F: __dxlog_file2,
87
183
  L: 93,
88
184
  S: void 0,
89
185
  C: (f, a) => f(...a)
@@ -102,15 +198,28 @@ var subscriptionHandler = (handler) => {
102
198
  });
103
199
  };
104
200
  };
105
- var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/core/functions/src/runtime/dev-server.ts";
201
+ var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/core/functions/src/runtime/dev-server.ts";
106
202
  var DevServer = class {
107
- // prettier-ignore
108
- constructor(_client, _options) {
203
+ constructor(_client, _functionsRegistry, _options) {
109
204
  this._client = _client;
205
+ this._functionsRegistry = _functionsRegistry;
110
206
  this._options = _options;
207
+ this._ctx = createContext();
111
208
  this._handlers = {};
112
209
  this._seq = 0;
113
- this.update = new import_async.Event();
210
+ this.update = new import_async2.Event();
211
+ this._functionsRegistry.registered.on(async ({ added }) => {
212
+ added.forEach((def) => this._load(def));
213
+ await this._safeUpdateRegistration();
214
+ (0, import_log3.log)("new functions loaded", {
215
+ added
216
+ }, {
217
+ F: __dxlog_file3,
218
+ L: 53,
219
+ S: this,
220
+ C: (f, a) => f(...a)
221
+ });
222
+ });
114
223
  }
115
224
  get stats() {
116
225
  return {
@@ -119,8 +228,8 @@ var DevServer = class {
119
228
  }
120
229
  get endpoint() {
121
230
  (0, import_invariant.invariant)(this._port, void 0, {
122
- F: __dxlog_file2,
123
- L: 54,
231
+ F: __dxlog_file3,
232
+ L: 64,
124
233
  S: this,
125
234
  A: [
126
235
  "this._port",
@@ -135,23 +244,9 @@ var DevServer = class {
135
244
  get functions() {
136
245
  return Object.values(this._handlers);
137
246
  }
138
- async initialize() {
139
- for (const def of this._options.manifest.functions) {
140
- try {
141
- await this._load(def);
142
- } catch (err) {
143
- import_log2.log.error("parsing function (check manifest)", err, {
144
- F: __dxlog_file2,
145
- L: 71,
146
- S: this,
147
- C: (f, a) => f(...a)
148
- });
149
- }
150
- }
151
- }
152
247
  async start() {
153
248
  (0, import_invariant.invariant)(!this._server, void 0, {
154
- F: __dxlog_file2,
249
+ F: __dxlog_file3,
155
250
  L: 77,
156
251
  S: this,
157
252
  A: [
@@ -159,22 +254,23 @@ var DevServer = class {
159
254
  ""
160
255
  ]
161
256
  });
162
- import_log2.log.info("starting...", void 0, {
163
- F: __dxlog_file2,
257
+ import_log3.log.info("starting...", void 0, {
258
+ F: __dxlog_file3,
164
259
  L: 78,
165
260
  S: this,
166
261
  C: (f, a) => f(...a)
167
262
  });
263
+ this._ctx = createContext();
168
264
  const app = (0, import_express.default)();
169
265
  app.use(import_express.default.json());
170
266
  app.post("/:path", async (req, res) => {
171
267
  const { path: path2 } = req.params;
172
268
  try {
173
- import_log2.log.info("calling", {
269
+ import_log3.log.info("calling", {
174
270
  path: path2
175
271
  }, {
176
- F: __dxlog_file2,
177
- L: 87,
272
+ F: __dxlog_file3,
273
+ L: 88,
178
274
  S: this,
179
275
  C: (f, a) => f(...a)
180
276
  });
@@ -185,9 +281,9 @@ var DevServer = class {
185
281
  res.statusCode = await this.invoke("/" + path2, req.body);
186
282
  res.end();
187
283
  } catch (err) {
188
- import_log2.log.catch(err, void 0, {
189
- F: __dxlog_file2,
190
- L: 97,
284
+ import_log3.log.catch(err, void 0, {
285
+ F: __dxlog_file3,
286
+ L: 98,
191
287
  S: this,
192
288
  C: (f, a) => f(...a)
193
289
  });
@@ -206,64 +302,61 @@ var DevServer = class {
206
302
  this._server = app.listen(this._port);
207
303
  try {
208
304
  const { registrationId, endpoint } = await this._client.services.services.FunctionRegistryService.register({
209
- endpoint: this.endpoint,
210
- functions: this.functions.map(({ def: { id, path: path2 } }) => ({
211
- id,
212
- path: path2
213
- }))
305
+ endpoint: this.endpoint
214
306
  });
215
- import_log2.log.info("registered", {
307
+ import_log3.log.info("registered", {
216
308
  endpoint
217
309
  }, {
218
- F: __dxlog_file2,
310
+ F: __dxlog_file3,
219
311
  L: 113,
220
312
  S: this,
221
313
  C: (f, a) => f(...a)
222
314
  });
223
315
  this._proxy = endpoint;
224
316
  this._functionServiceRegistration = registrationId;
317
+ await this._functionsRegistry.open(this._ctx);
225
318
  } catch (err) {
226
319
  await this.stop();
227
320
  throw new Error("FunctionRegistryService not available (check plugin is configured).");
228
321
  }
229
- import_log2.log.info("started", {
322
+ import_log3.log.info("started", {
230
323
  port: this._port
231
324
  }, {
232
- F: __dxlog_file2,
233
- L: 121,
325
+ F: __dxlog_file3,
326
+ L: 124,
234
327
  S: this,
235
328
  C: (f, a) => f(...a)
236
329
  });
237
330
  }
238
331
  async stop() {
239
332
  (0, import_invariant.invariant)(this._server, void 0, {
240
- F: __dxlog_file2,
241
- L: 125,
333
+ F: __dxlog_file3,
334
+ L: 128,
242
335
  S: this,
243
336
  A: [
244
337
  "this._server",
245
338
  ""
246
339
  ]
247
340
  });
248
- import_log2.log.info("stopping...", void 0, {
249
- F: __dxlog_file2,
250
- L: 126,
341
+ import_log3.log.info("stopping...", void 0, {
342
+ F: __dxlog_file3,
343
+ L: 129,
251
344
  S: this,
252
345
  C: (f, a) => f(...a)
253
346
  });
254
- const trigger = new import_async.Trigger();
347
+ const trigger = new import_async2.Trigger();
255
348
  this._server.close(async () => {
256
- import_log2.log.info("server stopped", void 0, {
257
- F: __dxlog_file2,
258
- L: 130,
349
+ import_log3.log.info("server stopped", void 0, {
350
+ F: __dxlog_file3,
351
+ L: 133,
259
352
  S: this,
260
353
  C: (f, a) => f(...a)
261
354
  });
262
355
  try {
263
356
  if (this._functionServiceRegistration) {
264
357
  (0, import_invariant.invariant)(this._client.services.services.FunctionRegistryService, void 0, {
265
- F: __dxlog_file2,
266
- L: 133,
358
+ F: __dxlog_file3,
359
+ L: 136,
267
360
  S: this,
268
361
  A: [
269
362
  "this._client.services.services.FunctionRegistryService",
@@ -273,11 +366,11 @@ var DevServer = class {
273
366
  await this._client.services.services.FunctionRegistryService.unregister({
274
367
  registrationId: this._functionServiceRegistration
275
368
  });
276
- import_log2.log.info("unregistered", {
369
+ import_log3.log.info("unregistered", {
277
370
  registrationId: this._functionServiceRegistration
278
371
  }, {
279
- F: __dxlog_file2,
280
- L: 138,
372
+ F: __dxlog_file3,
373
+ L: 141,
281
374
  S: this,
282
375
  C: (f, a) => f(...a)
283
376
  });
@@ -292,9 +385,9 @@ var DevServer = class {
292
385
  await trigger.wait();
293
386
  this._port = void 0;
294
387
  this._server = void 0;
295
- import_log2.log.info("stopped", void 0, {
296
- F: __dxlog_file2,
297
- L: 152,
388
+ import_log3.log.info("stopped", void 0, {
389
+ F: __dxlog_file3,
390
+ L: 155,
298
391
  S: this,
299
392
  C: (f, a) => f(...a)
300
393
  });
@@ -302,58 +395,85 @@ var DevServer = class {
302
395
  /**
303
396
  * Load function.
304
397
  */
305
- async _load(def, force = false) {
306
- const { id, path: path2, handler } = def;
398
+ async _load(def, force) {
399
+ const { uri, route, handler } = def;
307
400
  const filePath = (0, import_node_path.join)(this._options.baseDir, handler);
308
- import_log2.log.info("loading", {
309
- id,
401
+ import_log3.log.info("loading", {
402
+ uri,
310
403
  force
311
404
  }, {
312
- F: __dxlog_file2,
313
- L: 161,
405
+ F: __dxlog_file3,
406
+ L: 164,
314
407
  S: this,
315
408
  C: (f, a) => f(...a)
316
409
  });
317
410
  if (force) {
318
- Object.keys(__require.cache).filter((key) => key.startsWith(filePath)).forEach((key) => {
319
- delete __require.cache[key];
411
+ Object.keys(import_chunk_3UYUR5N5.__require.cache).filter((key) => key.startsWith(filePath)).forEach((key) => {
412
+ delete import_chunk_3UYUR5N5.__require.cache[key];
320
413
  });
321
414
  }
322
- const module2 = __require(filePath);
415
+ const module2 = (0, import_chunk_3UYUR5N5.__require)(filePath);
323
416
  if (typeof module2.default !== "function") {
324
- throw new Error(`Handler must export default function: ${id}`);
417
+ throw new Error(`Handler must export default function: ${uri}`);
325
418
  }
326
- this._handlers[path2] = {
419
+ this._handlers[route] = {
327
420
  def,
328
421
  handler: module2.default
329
422
  };
330
423
  }
424
+ async _safeUpdateRegistration() {
425
+ (0, import_invariant.invariant)(this._functionServiceRegistration, void 0, {
426
+ F: __dxlog_file3,
427
+ L: 186,
428
+ S: this,
429
+ A: [
430
+ "this._functionServiceRegistration",
431
+ ""
432
+ ]
433
+ });
434
+ try {
435
+ await this._client.services.services.FunctionRegistryService.updateRegistration({
436
+ registrationId: this._functionServiceRegistration,
437
+ functions: this.functions.map(({ def: { id, route } }) => ({
438
+ id,
439
+ route
440
+ }))
441
+ });
442
+ } catch (err) {
443
+ import_log3.log.catch(err, void 0, {
444
+ F: __dxlog_file3,
445
+ L: 193,
446
+ S: this,
447
+ C: (f, a) => f(...a)
448
+ });
449
+ }
450
+ }
331
451
  /**
332
452
  * Invoke function.
333
453
  */
334
454
  async invoke(path2, data) {
335
455
  const seq = ++this._seq;
336
456
  const now = Date.now();
337
- import_log2.log.info("req", {
457
+ import_log3.log.info("req", {
338
458
  seq,
339
459
  path: path2
340
460
  }, {
341
- F: __dxlog_file2,
342
- L: 188,
461
+ F: __dxlog_file3,
462
+ L: 204,
343
463
  S: this,
344
464
  C: (f, a) => f(...a)
345
465
  });
346
466
  const statusCode = await this._invoke(path2, {
347
467
  data
348
468
  });
349
- import_log2.log.info("res", {
469
+ import_log3.log.info("res", {
350
470
  seq,
351
471
  path: path2,
352
472
  statusCode,
353
473
  duration: Date.now() - now
354
474
  }, {
355
- F: __dxlog_file2,
356
- L: 191,
475
+ F: __dxlog_file3,
476
+ L: 207,
357
477
  S: this,
358
478
  C: (f, a) => f(...a)
359
479
  });
@@ -363,8 +483,8 @@ var DevServer = class {
363
483
  async _invoke(path2, event) {
364
484
  const { handler } = this._handlers[path2] ?? {};
365
485
  (0, import_invariant.invariant)(handler, `invalid path: ${path2}`, {
366
- F: __dxlog_file2,
367
- L: 198,
486
+ F: __dxlog_file3,
487
+ L: 214,
368
488
  S: this,
369
489
  A: [
370
490
  "handler",
@@ -390,111 +510,114 @@ var DevServer = class {
390
510
  return statusCode;
391
511
  }
392
512
  };
393
- var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/core/functions/src/runtime/scheduler.ts";
513
+ var createContext = () => new import_context2.Context({
514
+ name: "DevServer"
515
+ });
516
+ var __dxlog_file4 = "/home/runner/work/dxos/dxos/packages/core/functions/src/runtime/scheduler.ts";
394
517
  var Scheduler = class {
395
- constructor(_client, _manifest, _options = {}) {
396
- this._client = _client;
397
- this._manifest = _manifest;
518
+ constructor(functions, triggers, _options = {}) {
519
+ this.functions = functions;
520
+ this.triggers = triggers;
398
521
  this._options = _options;
399
- this._mounts = new import_util2.ComplexMap(({ spaceKey, id }) => `${spaceKey.toHex()}:${id}`);
400
- }
401
- get mounts() {
402
- return Array.from(this._mounts.values()).reduce((acc, { trigger }) => {
403
- acc.push(trigger);
404
- return acc;
405
- }, []);
522
+ this._ctx = createContext2();
523
+ this._functionUriToCallMutex = /* @__PURE__ */ new Map();
524
+ this.functions.registered.on(async ({ space, added }) => {
525
+ await this._safeActivateTriggers(space, this.triggers.getInactiveTriggers(space), added);
526
+ });
527
+ this.triggers.registered.on(async ({ space, triggers: triggers2 }) => {
528
+ await this._safeActivateTriggers(space, triggers2, this.functions.getFunctions(space));
529
+ });
406
530
  }
407
531
  async start() {
408
- this._client.spaces.subscribe(async (spaces) => {
409
- for (const space of spaces) {
410
- await space.waitUntilReady();
411
- for (const trigger of this._manifest.triggers ?? []) {
412
- await this.mount(new import_context.Context(), space, trigger);
413
- }
414
- }
415
- });
532
+ await this._ctx.dispose();
533
+ this._ctx = createContext2();
534
+ await this.functions.open(this._ctx);
535
+ await this.triggers.open(this._ctx);
416
536
  }
417
537
  async stop() {
418
- for (const { id, spaceKey } of this._mounts.keys()) {
419
- await this.unmount(id, spaceKey);
420
- }
538
+ await this._ctx.dispose();
539
+ await this.functions.close();
540
+ await this.triggers.close();
421
541
  }
422
- /**
423
- * Mount trigger.
424
- */
425
- async mount(ctx, space, trigger) {
426
- const key = {
427
- spaceKey: space.key,
428
- id: trigger.function
429
- };
430
- const def = this._manifest.functions.find((config) => config.id === trigger.function);
431
- (0, import_invariant2.invariant)(def, `Function not found: ${trigger.function}`, {
432
- F: __dxlog_file3,
433
- L: 76,
434
- S: this,
435
- A: [
436
- "def",
437
- "`Function not found: ${trigger.function}`"
438
- ]
542
+ // TODO(burdon): Remove and update registries directly.
543
+ async register(space, manifest) {
544
+ await this.functions.register(space, manifest.functions);
545
+ await this.triggers.register(space, manifest);
546
+ }
547
+ async _safeActivateTriggers(space, triggers, functions) {
548
+ const mountTasks = triggers.map((trigger) => {
549
+ return this.activate(space, functions, trigger);
439
550
  });
440
- const exists = this._mounts.get(key);
441
- if (!exists) {
442
- this._mounts.set(key, {
443
- ctx,
444
- trigger
445
- });
446
- (0, import_log3.log)("mount", {
447
- space: space.key,
551
+ await Promise.all(mountTasks).catch(import_log4.log.catch);
552
+ }
553
+ async activate(space, functions, trigger) {
554
+ const definition = functions.find((def) => def.uri === trigger.function);
555
+ if (!definition) {
556
+ import_log4.log.info("function is not found for trigger", {
448
557
  trigger
449
558
  }, {
450
- F: __dxlog_file3,
451
- L: 82,
559
+ F: __dxlog_file4,
560
+ L: 78,
452
561
  S: this,
453
562
  C: (f, a) => f(...a)
454
563
  });
455
- if (ctx.disposed) {
456
- return;
457
- }
458
- if (trigger.timer) {
459
- await this._createTimer(ctx, space, def, trigger);
460
- }
461
- if (trigger.webhook) {
462
- await this._createWebhook(ctx, space, def, trigger);
463
- }
464
- if (trigger.websocket) {
465
- await this._createWebsocket(ctx, space, def, trigger);
466
- }
467
- if (trigger.subscription) {
468
- await this._createSubscription(ctx, space, def, trigger);
469
- }
470
- }
471
- }
472
- async unmount(id, spaceKey) {
473
- const key = {
474
- id,
475
- spaceKey
476
- };
477
- const { ctx } = this._mounts.get(key) ?? {};
478
- if (ctx) {
479
- this._mounts.delete(key);
480
- await ctx.dispose();
564
+ return;
481
565
  }
566
+ await this.triggers.activate(space, trigger, async (args) => {
567
+ const mutex = this._functionUriToCallMutex.get(definition.uri) ?? new import_async3.Mutex();
568
+ this._functionUriToCallMutex.set(definition.uri, mutex);
569
+ import_log4.log.info("function triggered, waiting for mutex", {
570
+ uri: definition.uri
571
+ }, {
572
+ F: __dxlog_file4,
573
+ L: 86,
574
+ S: this,
575
+ C: (f, a) => f(...a)
576
+ });
577
+ return mutex.executeSynchronized(() => {
578
+ import_log4.log.info("mutex acquired", {
579
+ uri: definition.uri
580
+ }, {
581
+ F: __dxlog_file4,
582
+ L: 88,
583
+ S: this,
584
+ C: (f, a) => f(...a)
585
+ });
586
+ return this._execFunction(definition, trigger, {
587
+ meta: trigger.meta ?? {},
588
+ data: {
589
+ ...args,
590
+ spaceKey: space.key
591
+ }
592
+ });
593
+ });
594
+ });
595
+ (0, import_log4.log)("activated trigger", {
596
+ space: space.key,
597
+ trigger
598
+ }, {
599
+ F: __dxlog_file4,
600
+ L: 96,
601
+ S: this,
602
+ C: (f, a) => f(...a)
603
+ });
482
604
  }
483
- async _execFunction(def, trigger, data) {
605
+ async _execFunction(def, trigger, { data, meta }) {
484
606
  let status = 0;
485
607
  try {
486
- const payload = Object.assign({}, {
487
- meta: trigger.meta
608
+ const payload = Object.assign({}, meta && {
609
+ meta
488
610
  }, data);
489
611
  const { endpoint, callback } = this._options;
490
612
  if (endpoint) {
491
- const url = import_node_path2.default.join(endpoint, def.path);
492
- import_log3.log.info("exec", {
493
- function: def.id,
494
- url
613
+ const url = import_node_path2.default.join(endpoint, def.route);
614
+ import_log4.log.info("exec", {
615
+ function: def.uri,
616
+ url,
617
+ triggerType: trigger.spec.type
495
618
  }, {
496
- F: __dxlog_file3,
497
- L: 128,
619
+ F: __dxlog_file4,
620
+ L: 113,
498
621
  S: this,
499
622
  C: (f, a) => f(...a)
500
623
  });
@@ -507,11 +630,11 @@ var Scheduler = class {
507
630
  });
508
631
  status = response.status;
509
632
  } else if (callback) {
510
- import_log3.log.info("exec", {
511
- function: def.id
633
+ import_log4.log.info("exec", {
634
+ function: def.uri
512
635
  }, {
513
- F: __dxlog_file3,
514
- L: 139,
636
+ F: __dxlog_file4,
637
+ L: 124,
515
638
  S: this,
516
639
  C: (f, a) => f(...a)
517
640
  });
@@ -520,22 +643,22 @@ var Scheduler = class {
520
643
  if (status && status >= 400) {
521
644
  throw new Error(`Response: ${status}`);
522
645
  }
523
- import_log3.log.info("done", {
524
- function: def.id,
646
+ import_log4.log.info("done", {
647
+ function: def.uri,
525
648
  status
526
649
  }, {
527
- F: __dxlog_file3,
528
- L: 149,
650
+ F: __dxlog_file4,
651
+ L: 134,
529
652
  S: this,
530
653
  C: (f, a) => f(...a)
531
654
  });
532
655
  } catch (err) {
533
- import_log3.log.error("error", {
534
- function: def.id,
656
+ import_log4.log.error("error", {
657
+ function: def.uri,
535
658
  error: err.message
536
659
  }, {
537
- F: __dxlog_file3,
538
- L: 151,
660
+ F: __dxlog_file4,
661
+ L: 136,
539
662
  S: this,
540
663
  C: (f, a) => f(...a)
541
664
  });
@@ -543,334 +666,477 @@ var Scheduler = class {
543
666
  }
544
667
  return status;
545
668
  }
546
- //
547
- // Triggers
548
- //
549
- /**
550
- * Cron timer.
551
- */
552
- async _createTimer(ctx, space, def, trigger) {
553
- import_log3.log.info("timer", {
554
- space: space.key,
555
- trigger
669
+ };
670
+ var createContext2 = () => new import_context3.Context({
671
+ name: "FunctionScheduler"
672
+ });
673
+ var __dxlog_file5 = "/home/runner/work/dxos/dxos/packages/core/functions/src/trigger/type/subscription-trigger.ts";
674
+ var createSubscriptionTrigger = async (ctx, space, spec, callback) => {
675
+ const objectIds = /* @__PURE__ */ new Set();
676
+ const task = new import_async5.UpdateScheduler(ctx, async () => {
677
+ if (objectIds.size > 0) {
678
+ const objects = Array.from(objectIds);
679
+ objectIds.clear();
680
+ await callback({
681
+ objects
682
+ });
683
+ }
684
+ }, {
685
+ maxFrequency: 4
686
+ });
687
+ const subscriptions = [];
688
+ const subscription = (0, import_echo_db.createSubscription)(({ added, updated }) => {
689
+ const sizeBefore = objectIds.size;
690
+ for (const object of added) {
691
+ objectIds.add(object.id);
692
+ }
693
+ for (const object of updated) {
694
+ objectIds.add(object.id);
695
+ }
696
+ if (objectIds.size > sizeBefore) {
697
+ import_log6.log.info("updated", {
698
+ added: added.length,
699
+ updated: updated.length
700
+ }, {
701
+ F: __dxlog_file5,
702
+ L: 47,
703
+ S: void 0,
704
+ C: (f, a) => f(...a)
705
+ });
706
+ task.trigger();
707
+ }
708
+ });
709
+ subscriptions.push(() => subscription.unsubscribe());
710
+ const { filter, options: { deep, delay } = {} } = spec;
711
+ const update = ({ objects }) => {
712
+ import_log6.log.info("update", {
713
+ objects: objects.length
556
714
  }, {
557
- F: __dxlog_file3,
558
- L: 166,
559
- S: this,
715
+ F: __dxlog_file5,
716
+ L: 57,
717
+ S: void 0,
560
718
  C: (f, a) => f(...a)
561
719
  });
562
- const spec = trigger.timer;
563
- const task = new import_async2.DeferredTask(ctx, async () => {
564
- await this._execFunction(def, trigger, {
565
- spaceKey: space.key
720
+ subscription.update(objects);
721
+ if (deep) {
722
+ for (const object of objects) {
723
+ const content = object.content;
724
+ if (content instanceof import_types.TextV0Type) {
725
+ subscriptions.push((0, import_echo_db.getAutomergeObjectCore)(content).updates.on((0, import_async5.debounce)(() => subscription.update([
726
+ object
727
+ ]), 1e3)));
728
+ }
729
+ }
730
+ }
731
+ };
732
+ import_log6.log.info("subscription", {
733
+ filter
734
+ }, {
735
+ F: __dxlog_file5,
736
+ L: 76,
737
+ S: void 0,
738
+ C: (f, a) => f(...a)
739
+ });
740
+ if (filter) {
741
+ const query = space.db.query(import_echo3.Filter.typename(filter[0].type, filter[0].props));
742
+ subscriptions.push(query.subscribe(delay ? (0, import_async5.debounce)(update, delay) : update));
743
+ }
744
+ ctx.onDispose(() => {
745
+ subscriptions.forEach((unsubscribe) => unsubscribe());
746
+ });
747
+ };
748
+ var __dxlog_file6 = "/home/runner/work/dxos/dxos/packages/core/functions/src/trigger/type/timer-trigger.ts";
749
+ var createTimerTrigger = async (ctx, space, spec, callback) => {
750
+ const task = new import_async6.DeferredTask(ctx, async () => {
751
+ await callback({});
752
+ });
753
+ let last = 0;
754
+ let run = 0;
755
+ const job = import_cron.CronJob.from({
756
+ cronTime: spec.cron,
757
+ runOnInit: false,
758
+ onTick: () => {
759
+ const now = Date.now();
760
+ const delta = last ? now - last : 0;
761
+ last = now;
762
+ run++;
763
+ import_log7.log.info("tick", {
764
+ space: space.key.truncate(),
765
+ count: run,
766
+ delta
767
+ }, {
768
+ F: __dxlog_file6,
769
+ L: 38,
770
+ S: void 0,
771
+ C: (f, a) => f(...a)
566
772
  });
773
+ task.schedule();
774
+ }
775
+ });
776
+ job.start();
777
+ ctx.onDispose(() => job.stop());
778
+ };
779
+ var __dxlog_file7 = "/home/runner/work/dxos/dxos/packages/core/functions/src/trigger/type/webhook-trigger.ts";
780
+ var createWebhookTrigger = async (ctx, space, spec, callback) => {
781
+ const server = import_node_http.default.createServer(async (req, res) => {
782
+ if (req.method !== spec.method) {
783
+ res.statusCode = 405;
784
+ return res.end();
785
+ }
786
+ res.statusCode = await callback({});
787
+ res.end();
788
+ });
789
+ const port = await (0, import_get_port_please2.getPort)({
790
+ random: true
791
+ });
792
+ server.listen(port, () => {
793
+ import_log8.log.info("started webhook", {
794
+ port
795
+ }, {
796
+ F: __dxlog_file7,
797
+ L: 41,
798
+ S: void 0,
799
+ C: (f, a) => f(...a)
567
800
  });
568
- let last = 0;
569
- let run = 0;
570
- const job = import_cron.CronJob.from({
571
- cronTime: spec.cron,
572
- runOnInit: false,
573
- onTick: () => {
574
- const now = Date.now();
575
- const delta = last ? now - last : 0;
576
- last = now;
577
- run++;
578
- import_log3.log.info("tick", {
579
- space: space.key.truncate(),
580
- count: run,
581
- delta
801
+ spec.port = port;
802
+ });
803
+ ctx.onDispose(() => {
804
+ server.close();
805
+ });
806
+ };
807
+ var __dxlog_file8 = "/home/runner/work/dxos/dxos/packages/core/functions/src/trigger/type/websocket-trigger.ts";
808
+ var createWebsocketTrigger = async (ctx, space, spec, callback, options = {
809
+ retryDelay: 2,
810
+ maxAttempts: 5
811
+ }) => {
812
+ const { url, init } = spec;
813
+ let ws;
814
+ for (let attempt = 1; attempt <= options.maxAttempts; attempt++) {
815
+ const open = new import_async7.Trigger();
816
+ ws = new import_ws.default(url);
817
+ Object.assign(ws, {
818
+ onopen: () => {
819
+ import_log9.log.info("opened", {
820
+ url
582
821
  }, {
583
- F: __dxlog_file3,
584
- L: 186,
585
- S: this,
822
+ F: __dxlog_file8,
823
+ L: 40,
824
+ S: void 0,
825
+ C: (f, a) => f(...a)
826
+ });
827
+ if (spec.init) {
828
+ ws.send(new TextEncoder().encode(JSON.stringify(init)));
829
+ }
830
+ open.wake(true);
831
+ },
832
+ onclose: (event) => {
833
+ import_log9.log.info("closed", {
834
+ url,
835
+ code: event.code
836
+ }, {
837
+ F: __dxlog_file8,
838
+ L: 49,
839
+ S: void 0,
840
+ C: (f, a) => f(...a)
841
+ });
842
+ if (event.code === 1006) {
843
+ setTimeout(async () => {
844
+ import_log9.log.info(`reconnecting in ${options.retryDelay}s...`, {
845
+ url
846
+ }, {
847
+ F: __dxlog_file8,
848
+ L: 54,
849
+ S: void 0,
850
+ C: (f, a) => f(...a)
851
+ });
852
+ await createWebsocketTrigger(ctx, space, spec, callback, options);
853
+ }, options.retryDelay * 1e3);
854
+ }
855
+ open.wake(false);
856
+ },
857
+ onerror: (event) => {
858
+ import_log9.log.catch(event.error, {
859
+ url
860
+ }, {
861
+ F: __dxlog_file8,
862
+ L: 63,
863
+ S: void 0,
586
864
  C: (f, a) => f(...a)
587
865
  });
588
- task.schedule();
866
+ },
867
+ onmessage: async (event) => {
868
+ try {
869
+ import_log9.log.info("message", void 0, {
870
+ F: __dxlog_file8,
871
+ L: 68,
872
+ S: void 0,
873
+ C: (f, a) => f(...a)
874
+ });
875
+ const data = JSON.parse(new TextDecoder().decode(event.data));
876
+ await callback({
877
+ data
878
+ });
879
+ } catch (err) {
880
+ import_log9.log.catch(err, {
881
+ url
882
+ }, {
883
+ F: __dxlog_file8,
884
+ L: 72,
885
+ S: void 0,
886
+ C: (f, a) => f(...a)
887
+ });
888
+ }
589
889
  }
590
890
  });
591
- job.start();
592
- ctx.onDispose(() => job.stop());
891
+ const isOpen = await open.wait();
892
+ if (isOpen) {
893
+ break;
894
+ } else {
895
+ const wait = Math.pow(attempt, 2) * options.retryDelay;
896
+ if (attempt < options.maxAttempts) {
897
+ import_log9.log.warn(`failed to connect; trying again in ${wait}s`, {
898
+ attempt
899
+ }, {
900
+ F: __dxlog_file8,
901
+ L: 83,
902
+ S: void 0,
903
+ C: (f, a) => f(...a)
904
+ });
905
+ await (0, import_async7.sleep)(wait * 1e3);
906
+ }
907
+ }
593
908
  }
594
- /**
595
- * Webhook.
596
- */
597
- async _createWebhook(ctx, space, def, trigger) {
598
- import_log3.log.info("webhook", {
909
+ ctx.onDispose(() => {
910
+ ws?.close();
911
+ });
912
+ };
913
+ var __dxlog_file9 = "/home/runner/work/dxos/dxos/packages/core/functions/src/trigger/trigger-registry.ts";
914
+ var triggerHandlers = {
915
+ subscription: createSubscriptionTrigger,
916
+ timer: createTimerTrigger,
917
+ webhook: createWebhookTrigger,
918
+ websocket: createWebsocketTrigger
919
+ };
920
+ var TriggerRegistry = class extends import_context4.Resource {
921
+ constructor(_client, _options) {
922
+ super();
923
+ this._client = _client;
924
+ this._options = _options;
925
+ this._triggersBySpaceKey = new import_util3.ComplexMap(import_keys2.PublicKey.hash);
926
+ this.registered = new import_async4.Event();
927
+ this.removed = new import_async4.Event();
928
+ }
929
+ getActiveTriggers(space) {
930
+ return this._getTriggers(space, (t) => t.activationCtx != null);
931
+ }
932
+ getInactiveTriggers(space) {
933
+ return this._getTriggers(space, (t) => t.activationCtx == null);
934
+ }
935
+ async activate(space, trigger, callback) {
936
+ (0, import_log5.log)("activate", {
599
937
  space: space.key,
600
938
  trigger
601
939
  }, {
602
- F: __dxlog_file3,
603
- L: 199,
940
+ F: __dxlog_file9,
941
+ L: 72,
942
+ S: this,
943
+ C: (f, a) => f(...a)
944
+ });
945
+ const activationCtx = new import_context4.Context({
946
+ name: `FunctionTrigger-${trigger.function}`
947
+ });
948
+ this._ctx.onDispose(() => activationCtx.dispose());
949
+ const registeredTrigger = this._triggersBySpaceKey.get(space.key)?.find((reg) => reg.trigger.id === trigger.id);
950
+ (0, import_invariant2.invariant)(registeredTrigger, `Trigger is not registered: ${trigger.function}`, {
951
+ F: __dxlog_file9,
952
+ L: 77,
953
+ S: this,
954
+ A: [
955
+ "registeredTrigger",
956
+ "`Trigger is not registered: ${trigger.function}`"
957
+ ]
958
+ });
959
+ registeredTrigger.activationCtx = activationCtx;
960
+ try {
961
+ const options = this._options?.[trigger.spec.type];
962
+ await triggerHandlers[trigger.spec.type](activationCtx, space, trigger.spec, callback, options);
963
+ } catch (err) {
964
+ delete registeredTrigger.activationCtx;
965
+ throw err;
966
+ }
967
+ }
968
+ /**
969
+ * Loads triggers from the manifest into the space.
970
+ */
971
+ async register(space, manifest) {
972
+ (0, import_log5.log)("register", {
973
+ space: space.key
974
+ }, {
975
+ F: __dxlog_file9,
976
+ L: 93,
604
977
  S: this,
605
978
  C: (f, a) => f(...a)
606
979
  });
607
- const spec = trigger.webhook;
608
- const server = import_node_http.default.createServer(async (req, res) => {
609
- if (req.method !== spec.method) {
610
- res.statusCode = 405;
611
- return res.end();
980
+ if (!manifest.triggers?.length) {
981
+ return;
982
+ }
983
+ if (!space.db.graph.runtimeSchemaRegistry.hasSchema(import_chunk_3UYUR5N5.FunctionTrigger)) {
984
+ space.db.graph.runtimeSchemaRegistry.registerSchema(import_chunk_3UYUR5N5.FunctionTrigger);
985
+ }
986
+ const manifestTriggers = manifest.triggers.map((trigger) => {
987
+ let keys = trigger[import_echo_schema.ECHO_ATTR_META]?.keys;
988
+ delete trigger[import_echo_schema.ECHO_ATTR_META];
989
+ if (!keys?.length) {
990
+ keys = [
991
+ (0, import_echo_schema.foreignKey)("manifest", [
992
+ trigger.function,
993
+ trigger.spec.type
994
+ ].join(":"))
995
+ ];
612
996
  }
613
- res.statusCode = await this._execFunction(def, trigger, {
614
- spaceKey: space.key
997
+ return (0, import_echo2.create)(import_chunk_3UYUR5N5.FunctionTrigger, trigger, {
998
+ keys
615
999
  });
616
- res.end();
617
1000
  });
618
- const port = await (0, import_get_port_please2.getPort)({
619
- random: true
620
- });
621
- server.listen(port, () => {
622
- import_log3.log.info("started webhook", {
623
- port
1001
+ const { objects: existing } = await space.db.query(import_echo2.Filter.schema(import_chunk_3UYUR5N5.FunctionTrigger)).run();
1002
+ const { added } = (0, import_util3.diff)(existing, manifestTriggers, import_echo_schema.compareForeignKeys);
1003
+ added.forEach((trigger) => {
1004
+ space.db.add(trigger);
1005
+ import_log5.log.info("added", {
1006
+ meta: (0, import_echo2.getMeta)(trigger)
624
1007
  }, {
625
- F: __dxlog_file3,
626
- L: 223,
1008
+ F: __dxlog_file9,
1009
+ L: 120,
627
1010
  S: this,
628
1011
  C: (f, a) => f(...a)
629
1012
  });
630
- spec.port = port;
631
- });
632
- ctx.onDispose(() => {
633
- server.close();
634
1013
  });
1014
+ if (added.length > 0) {
1015
+ await space.db.flush();
1016
+ }
635
1017
  }
636
- /**
637
- * Websocket.
638
- * NOTE: The port must be unique, so the same hook cannot be used for multiple spaces.
639
- */
640
- async _createWebsocket(ctx, space, def, trigger, options = {
641
- retryDelay: 2,
642
- maxAttempts: 5
643
- }) {
644
- import_log3.log.info("websocket", {
645
- space: space.key,
646
- trigger
647
- }, {
648
- F: __dxlog_file3,
649
- L: 249,
1018
+ async _open() {
1019
+ import_log5.log.info("open...", void 0, {
1020
+ F: __dxlog_file9,
1021
+ L: 129,
650
1022
  S: this,
651
1023
  C: (f, a) => f(...a)
652
1024
  });
653
- const spec = trigger.websocket;
654
- const { url, init } = spec;
655
- let ws;
656
- for (let attempt = 1; attempt <= options.maxAttempts; attempt++) {
657
- const open = new import_async2.Trigger();
658
- ws = new import_ws.default(url);
659
- Object.assign(ws, {
660
- onopen: () => {
661
- import_log3.log.info("opened", {
662
- url
663
- }, {
664
- F: __dxlog_file3,
665
- L: 260,
666
- S: this,
667
- C: (f, a) => f(...a)
668
- });
669
- if (spec.init) {
670
- ws.send(new TextEncoder().encode(JSON.stringify(init)));
671
- }
672
- open.wake(true);
673
- },
674
- onclose: (event) => {
675
- import_log3.log.info("closed", {
676
- url,
677
- code: event.code
678
- }, {
679
- F: __dxlog_file3,
680
- L: 269,
681
- S: this,
682
- C: (f, a) => f(...a)
683
- });
684
- if (event.code === 1006) {
685
- setTimeout(async () => {
686
- import_log3.log.info(`reconnecting in ${options.retryDelay}s...`, {
687
- url
688
- }, {
689
- F: __dxlog_file3,
690
- L: 274,
691
- S: this,
692
- C: (f, a) => f(...a)
693
- });
694
- await this._createWebsocket(ctx, space, def, trigger, options);
695
- }, options.retryDelay * 1e3);
696
- }
697
- open.wake(false);
698
- },
699
- onerror: (event) => {
700
- import_log3.log.catch(event.error, {
701
- url
702
- }, {
703
- F: __dxlog_file3,
704
- L: 283,
705
- S: this,
706
- C: (f, a) => f(...a)
707
- });
708
- },
709
- onmessage: async (event) => {
710
- try {
711
- const data = JSON.parse(new TextDecoder().decode(event.data));
712
- await this._execFunction(def, trigger, {
713
- spaceKey: space.key,
714
- data
715
- });
716
- } catch (err) {
717
- import_log3.log.catch(err, {
718
- url
719
- }, {
720
- F: __dxlog_file3,
721
- L: 291,
722
- S: this,
723
- C: (f, a) => f(...a)
724
- });
725
- }
1025
+ const spaceListSubscription = this._client.spaces.subscribe(async (spaces) => {
1026
+ for (const space of spaces) {
1027
+ if (this._triggersBySpaceKey.has(space.key)) {
1028
+ continue;
726
1029
  }
727
- });
728
- const isOpen = await open.wait();
729
- if (isOpen) {
730
- break;
731
- } else {
732
- const wait = Math.pow(attempt, 2) * options.retryDelay;
733
- if (attempt < options.maxAttempts) {
734
- import_log3.log.warn(`failed to connect; trying again in ${wait}s`, {
735
- attempt
1030
+ const registered = [];
1031
+ this._triggersBySpaceKey.set(space.key, registered);
1032
+ await space.waitUntilReady();
1033
+ if (this._ctx.disposed) {
1034
+ break;
1035
+ }
1036
+ this._ctx.onDispose(space.db.query(import_echo2.Filter.schema(import_chunk_3UYUR5N5.FunctionTrigger)).subscribe(async ({ objects: current }) => {
1037
+ import_log5.log.info("update", {
1038
+ space: space.key,
1039
+ registered: registered.length,
1040
+ current: current.length
736
1041
  }, {
737
- F: __dxlog_file3,
738
- L: 302,
1042
+ F: __dxlog_file9,
1043
+ L: 146,
739
1044
  S: this,
740
1045
  C: (f, a) => f(...a)
741
1046
  });
742
- await (0, import_async2.sleep)(wait * 1e3);
743
- }
1047
+ await this._handleRemovedTriggers(space, current, registered);
1048
+ this._handleNewTriggers(space, current, registered);
1049
+ }));
744
1050
  }
745
- }
746
- ctx.onDispose(() => {
747
- ws?.close();
1051
+ });
1052
+ this._ctx.onDispose(() => spaceListSubscription.unsubscribe());
1053
+ import_log5.log.info("opened", void 0, {
1054
+ F: __dxlog_file9,
1055
+ L: 155,
1056
+ S: this,
1057
+ C: (f, a) => f(...a)
748
1058
  });
749
1059
  }
750
- /**
751
- * ECHO subscription.
752
- */
753
- async _createSubscription(ctx, space, def, trigger) {
754
- import_log3.log.info("subscription", {
755
- space: space.key,
756
- trigger
757
- }, {
758
- F: __dxlog_file3,
759
- L: 317,
1060
+ async _close(_) {
1061
+ import_log5.log.info("close...", void 0, {
1062
+ F: __dxlog_file9,
1063
+ L: 159,
760
1064
  S: this,
761
1065
  C: (f, a) => f(...a)
762
1066
  });
763
- const spec = trigger.subscription;
764
- const objectIds = /* @__PURE__ */ new Set();
765
- const task = new import_async2.DeferredTask(ctx, async () => {
766
- await this._execFunction(def, trigger, {
767
- spaceKey: space.key,
768
- objects: Array.from(objectIds)
769
- });
1067
+ this._triggersBySpaceKey.clear();
1068
+ import_log5.log.info("closed", void 0, {
1069
+ F: __dxlog_file9,
1070
+ L: 161,
1071
+ S: this,
1072
+ C: (f, a) => f(...a)
770
1073
  });
771
- const subscriptions = [];
772
- const subscription = (0, import_echo.createSubscription)(({ added, updated }) => {
773
- import_log3.log.info("updated", {
774
- added: added.length,
775
- updated: updated.length
776
- }, {
777
- F: __dxlog_file3,
778
- L: 329,
1074
+ }
1075
+ _handleNewTriggers(space, current, registered) {
1076
+ const added = current.filter((candidate) => {
1077
+ return candidate.enabled && registered.find((reg) => reg.trigger.id === candidate.id) == null;
1078
+ });
1079
+ if (added.length > 0) {
1080
+ const newRegisteredTriggers = added.map((trigger) => ({
1081
+ trigger
1082
+ }));
1083
+ registered.push(...newRegisteredTriggers);
1084
+ import_log5.log.info("added", () => ({
1085
+ spaceKey: space.key,
1086
+ triggers: added.map((trigger) => trigger.function)
1087
+ }), {
1088
+ F: __dxlog_file9,
1089
+ L: 172,
779
1090
  S: this,
780
1091
  C: (f, a) => f(...a)
781
1092
  });
782
- for (const object of added) {
783
- objectIds.add(object.id);
784
- }
785
- for (const object of updated) {
786
- objectIds.add(object.id);
787
- }
788
- task.schedule();
789
- });
790
- subscriptions.push(() => subscription.unsubscribe());
791
- const { filter, options: { deep, delay } = {} } = spec;
792
- const update = ({ objects }) => {
793
- subscription.update(objects);
794
- if (deep) {
795
- import_log3.log.info("update", {
796
- objects: objects.length
797
- }, {
798
- F: __dxlog_file3,
799
- L: 349,
800
- S: this,
801
- C: (f, a) => f(...a)
802
- });
803
- for (const object of objects) {
804
- const content = object.content;
805
- if (content instanceof import_types.TextV0Type) {
806
- subscriptions.push((0, import_echo.getAutomergeObjectCore)(content).updates.on((0, import_async2.debounce)(() => subscription.update([
807
- object
808
- ]), 1e3)));
809
- }
810
- }
1093
+ this.registered.emit({
1094
+ space,
1095
+ triggers: added
1096
+ });
1097
+ }
1098
+ }
1099
+ async _handleRemovedTriggers(space, current, registered) {
1100
+ const removed = [];
1101
+ for (let i = registered.length - 1; i >= 0; i--) {
1102
+ const wasRemoved = current.filter((trigger) => trigger.enabled).find((trigger) => trigger.id === registered[i].trigger.id) == null;
1103
+ if (wasRemoved) {
1104
+ const unregistered = registered.splice(i, 1)[0];
1105
+ await unregistered.activationCtx?.dispose();
1106
+ removed.push(unregistered.trigger);
811
1107
  }
812
- };
813
- const query = space.db.query(import_echo.Filter.or(filter.map(({ type, props }) => import_echo.Filter.typename(type, props))));
814
- subscriptions.push(query.subscribe(delay ? (0, import_async2.debounce)(update, delay) : update));
815
- ctx.onDispose(() => {
816
- subscriptions.forEach((unsubscribe) => unsubscribe());
817
- });
1108
+ }
1109
+ if (removed.length > 0) {
1110
+ import_log5.log.info("removed", () => ({
1111
+ spaceKey: space.key,
1112
+ triggers: removed.map((trigger) => trigger.function)
1113
+ }), {
1114
+ F: __dxlog_file9,
1115
+ L: 198,
1116
+ S: this,
1117
+ C: (f, a) => f(...a)
1118
+ });
1119
+ this.removed.emit({
1120
+ space,
1121
+ triggers: removed
1122
+ });
1123
+ }
1124
+ }
1125
+ _getTriggers(space, predicate) {
1126
+ const allSpaceTriggers = this._triggersBySpaceKey.get(space.key) ?? [];
1127
+ return allSpaceTriggers.filter(predicate).map((trigger) => trigger.trigger);
818
1128
  }
819
1129
  };
820
- var TimerTriggerSchema = S.struct({
821
- cron: S.string
822
- });
823
- var WebhookTriggerSchema = S.mutable(S.struct({
824
- method: S.string,
825
- // Assigned port.
826
- port: S.optional(S.number)
827
- }));
828
- var WebsocketTriggerSchema = S.struct({
829
- url: S.string,
830
- init: S.optional(S.record(S.string, S.any))
831
- });
832
- var SubscriptionTriggerSchema = S.struct({
833
- spaceKey: S.optional(S.string),
834
- // TODO(burdon): Define query DSL.
835
- filter: S.array(S.struct({
836
- type: S.string,
837
- props: S.optional(S.record(S.string, S.any))
838
- })),
839
- options: S.optional(S.struct({
840
- // Watch changes to object (not just creation).
841
- deep: S.optional(S.boolean),
842
- // Debounce changes (delay in ms).
843
- delay: S.optional(S.number)
844
- }))
845
- });
846
- var FunctionTriggerSchema = S.struct({
847
- function: S.string.pipe(S.description("Function ID/URI.")),
848
- // Context passed to function.
849
- meta: S.optional(S.record(S.string, S.any)),
850
- // Triggers.
851
- timer: S.optional(TimerTriggerSchema),
852
- webhook: S.optional(WebhookTriggerSchema),
853
- websocket: S.optional(WebsocketTriggerSchema),
854
- subscription: S.optional(SubscriptionTriggerSchema)
855
- });
856
- var FunctionDefSchema = S.struct({
857
- id: S.string,
858
- // name: S.string,
859
- description: S.optional(S.string),
860
- // TODO(burdon): Rename route?
861
- path: S.string,
862
- // TODO(burdon): NPM/GitHub/Docker/CF URL?
863
- handler: S.string
864
- });
865
- var FunctionManifestSchema = S.struct({
866
- functions: S.mutable(S.array(FunctionDefSchema)),
867
- triggers: S.optional(S.mutable(S.array(FunctionTriggerSchema)))
868
- });
869
1130
  // Annotate the CommonJS export names for ESM import in node:
870
1131
  0 && (module.exports = {
871
1132
  DevServer,
1133
+ FUNCTION_SCHEMA,
1134
+ FunctionDef,
872
1135
  FunctionManifestSchema,
1136
+ FunctionRegistry,
1137
+ FunctionTrigger,
873
1138
  Scheduler,
1139
+ TriggerRegistry,
874
1140
  subscriptionHandler
875
1141
  });
876
1142
  //# sourceMappingURL=index.cjs.map