@dxos/functions 0.5.3-main.e76d664 → 0.5.3-main.eb56347

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