@dxos/functions 0.5.3-main.f752aaa → 0.5.3-main.fffc127

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-4D4I3YMJ.mjs +86 -0
  2. package/dist/lib/browser/chunk-4D4I3YMJ.mjs.map +7 -0
  3. package/dist/lib/browser/index.mjs +884 -457
  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 +868 -447
  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 +37 -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 +162 -107
  64. package/dist/types/src/types.d.ts.map +1 -1
  65. package/package.json +33 -15
  66. package/schema/functions.json +144 -103
  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 +61 -73
  76. package/src/runtime/scheduler.ts +91 -270
  77. package/src/testing/functions-integration.test.ts +100 -0
  78. package/src/testing/index.ts +7 -0
  79. package/src/testing/setup.ts +43 -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 +272 -0
  86. package/src/trigger/trigger-registry.ts +211 -0
  87. package/src/trigger/type/index.ts +8 -0
  88. package/src/trigger/type/subscription-trigger.ts +86 -0
  89. package/src/trigger/type/timer-trigger.ts +45 -0
  90. package/src/trigger/type/webhook-trigger.ts +48 -0
  91. package/src/trigger/type/websocket-trigger.ts +92 -0
  92. package/src/types.ts +87 -48
@@ -29,87 +29,207 @@ 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");
79
+ var import_get_port_please2 = require("get-port-please");
47
80
  var import_node_http = __toESM(require("node:http"));
81
+ var import_log8 = require("@dxos/log");
48
82
  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";
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";
65
163
  var subscriptionHandler = (handler) => {
66
- return ({ event, context, ...rest }) => {
164
+ return ({ event: { data }, context, ...rest }) => {
67
165
  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
166
+ const space = data.spaceKey ? client.spaces.get(import_client.PublicKey.from(data.spaceKey)) : void 0;
167
+ const objects = space ? data.objects?.map((id) => space.db.getObjectById(id)).filter(import_util2.nonNullable) : [];
168
+ if (!!data.spaceKey && !space) {
169
+ import_log2.log.warn("invalid space", {
170
+ data
73
171
  }, {
74
- F: __dxlog_file,
75
- L: 68,
172
+ F: __dxlog_file2,
173
+ L: 91,
76
174
  S: void 0,
77
175
  C: (f, a) => f(...a)
78
176
  });
79
177
  } else {
80
- import_log.log.info("handler", {
178
+ import_log2.log.info("handler", {
81
179
  space: space?.key.truncate(),
82
180
  objects: objects?.length
83
181
  }, {
84
- F: __dxlog_file,
85
- L: 70,
182
+ F: __dxlog_file2,
183
+ L: 93,
86
184
  S: void 0,
87
185
  C: (f, a) => f(...a)
88
186
  });
89
187
  }
90
188
  return handler({
91
189
  event: {
92
- space,
93
- objects
190
+ data: {
191
+ ...data,
192
+ space,
193
+ objects
194
+ }
94
195
  },
95
196
  context,
96
197
  ...rest
97
198
  });
98
199
  };
99
200
  };
100
- 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";
101
202
  var DevServer = class {
102
- // prettier-ignore
103
- constructor(_client, _options) {
203
+ constructor(_client, _functionsRegistry, _options) {
104
204
  this._client = _client;
205
+ this._functionsRegistry = _functionsRegistry;
105
206
  this._options = _options;
207
+ this._ctx = createContext();
106
208
  this._handlers = {};
107
209
  this._seq = 0;
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
+ });
223
+ }
224
+ get stats() {
225
+ return {
226
+ seq: this._seq
227
+ };
108
228
  }
109
229
  get endpoint() {
110
230
  (0, import_invariant.invariant)(this._port, void 0, {
111
- F: __dxlog_file2,
112
- L: 46,
231
+ F: __dxlog_file3,
232
+ L: 64,
113
233
  S: this,
114
234
  A: [
115
235
  "this._port",
@@ -124,44 +244,46 @@ var DevServer = class {
124
244
  get functions() {
125
245
  return Object.values(this._handlers);
126
246
  }
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
247
  async start() {
248
+ (0, import_invariant.invariant)(!this._server, void 0, {
249
+ F: __dxlog_file3,
250
+ L: 77,
251
+ S: this,
252
+ A: [
253
+ "!this._server",
254
+ ""
255
+ ]
256
+ });
257
+ import_log3.log.info("starting...", void 0, {
258
+ F: __dxlog_file3,
259
+ L: 78,
260
+ S: this,
261
+ C: (f, a) => f(...a)
262
+ });
263
+ this._ctx = createContext();
142
264
  const app = (0, import_express.default)();
143
265
  app.use(import_express.default.json());
144
- app.post("/:name", async (req, res) => {
145
- const { name } = req.params;
266
+ app.post("/:path", async (req, res) => {
267
+ const { path: path2 } = req.params;
146
268
  try {
147
- import_log2.log.info("calling", {
148
- name
269
+ import_log3.log.info("calling", {
270
+ path: path2
149
271
  }, {
150
- F: __dxlog_file2,
151
- L: 75,
272
+ F: __dxlog_file3,
273
+ L: 88,
152
274
  S: this,
153
275
  C: (f, a) => f(...a)
154
276
  });
155
277
  if (this._options.reload) {
156
- const { def } = this._handlers[name];
278
+ const { def } = this._handlers["/" + path2];
157
279
  await this._load(def, true);
158
280
  }
159
- res.statusCode = await this._invoke(name, req.body);
281
+ res.statusCode = await this.invoke("/" + path2, req.body);
160
282
  res.end();
161
283
  } catch (err) {
162
- import_log2.log.catch(err, void 0, {
163
- F: __dxlog_file2,
164
- L: 84,
284
+ import_log3.log.catch(err, void 0, {
285
+ F: __dxlog_file3,
286
+ L: 98,
165
287
  S: this,
166
288
  C: (f, a) => f(...a)
167
289
  });
@@ -180,93 +302,195 @@ var DevServer = class {
180
302
  this._server = app.listen(this._port);
181
303
  try {
182
304
  const { registrationId, endpoint } = await this._client.services.services.FunctionRegistryService.register({
183
- endpoint: this.endpoint,
184
- functions: this.functions.map(({ def: { name } }) => ({
185
- name
186
- }))
305
+ endpoint: this.endpoint
187
306
  });
188
- import_log2.log.info("registered", {
189
- registrationId,
307
+ import_log3.log.info("registered", {
190
308
  endpoint
191
309
  }, {
192
- F: __dxlog_file2,
193
- L: 100,
310
+ F: __dxlog_file3,
311
+ L: 113,
194
312
  S: this,
195
313
  C: (f, a) => f(...a)
196
314
  });
197
- this._registrationId = registrationId;
198
315
  this._proxy = endpoint;
316
+ this._functionServiceRegistration = registrationId;
317
+ await this._functionsRegistry.open(this._ctx);
199
318
  } catch (err) {
200
319
  await this.stop();
201
320
  throw new Error("FunctionRegistryService not available (check plugin is configured).");
202
321
  }
322
+ import_log3.log.info("started", {
323
+ port: this._port
324
+ }, {
325
+ F: __dxlog_file3,
326
+ L: 124,
327
+ S: this,
328
+ C: (f, a) => f(...a)
329
+ });
203
330
  }
204
331
  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;
332
+ (0, import_invariant.invariant)(this._server, void 0, {
333
+ F: __dxlog_file3,
334
+ L: 128,
335
+ S: this,
336
+ A: [
337
+ "this._server",
338
+ ""
339
+ ]
340
+ });
341
+ import_log3.log.info("stopping...", void 0, {
342
+ F: __dxlog_file3,
343
+ L: 129,
344
+ S: this,
345
+ C: (f, a) => f(...a)
346
+ });
347
+ const trigger = new import_async2.Trigger();
348
+ this._server.close(async () => {
349
+ import_log3.log.info("server stopped", void 0, {
350
+ F: __dxlog_file3,
351
+ L: 133,
352
+ S: this,
353
+ C: (f, a) => f(...a)
354
+ });
355
+ try {
356
+ if (this._functionServiceRegistration) {
357
+ (0, import_invariant.invariant)(this._client.services.services.FunctionRegistryService, void 0, {
358
+ F: __dxlog_file3,
359
+ L: 136,
360
+ S: this,
361
+ A: [
362
+ "this._client.services.services.FunctionRegistryService",
363
+ ""
364
+ ]
365
+ });
366
+ await this._client.services.services.FunctionRegistryService.unregister({
367
+ registrationId: this._functionServiceRegistration
368
+ });
369
+ import_log3.log.info("unregistered", {
370
+ registrationId: this._functionServiceRegistration
371
+ }, {
372
+ F: __dxlog_file3,
373
+ L: 141,
374
+ S: this,
375
+ C: (f, a) => f(...a)
376
+ });
377
+ this._functionServiceRegistration = void 0;
378
+ this._proxy = void 0;
379
+ }
380
+ trigger.wake();
381
+ } catch (err) {
382
+ trigger.throw(err);
221
383
  }
222
- trigger.wake();
223
384
  });
224
385
  await trigger.wait();
225
386
  this._port = void 0;
226
387
  this._server = void 0;
388
+ import_log3.log.info("stopped", void 0, {
389
+ F: __dxlog_file3,
390
+ L: 155,
391
+ S: this,
392
+ C: (f, a) => f(...a)
393
+ });
227
394
  }
228
395
  /**
229
396
  * Load function.
230
397
  */
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
398
+ async _load(def, force) {
399
+ const { uri, route, handler } = def;
400
+ const filePath = (0, import_node_path.join)(this._options.baseDir, handler);
401
+ import_log3.log.info("loading", {
402
+ uri,
403
+ force
236
404
  }, {
237
- F: __dxlog_file2,
238
- L: 136,
405
+ F: __dxlog_file3,
406
+ L: 164,
239
407
  S: this,
240
408
  C: (f, a) => f(...a)
241
409
  });
242
- if (flush) {
243
- Object.keys(__require.cache).filter((key) => key.startsWith(path)).forEach((key) => delete __require.cache[key]);
410
+ if (force) {
411
+ Object.keys(import_chunk_3UYUR5N5.__require.cache).filter((key) => key.startsWith(filePath)).forEach((key) => {
412
+ delete import_chunk_3UYUR5N5.__require.cache[key];
413
+ });
244
414
  }
245
- const module2 = __require(path);
415
+ const module2 = (0, import_chunk_3UYUR5N5.__require)(filePath);
246
416
  if (typeof module2.default !== "function") {
247
- throw new Error(`Handler must export default function: ${id}`);
417
+ throw new Error(`Handler must export default function: ${uri}`);
248
418
  }
249
- this._handlers[name] = {
419
+ this._handlers[route] = {
250
420
  def,
251
421
  handler: module2.default
252
422
  };
253
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
+ }
254
451
  /**
255
- * Invoke function handler.
452
+ * Invoke function.
256
453
  */
257
- async _invoke(name, event) {
454
+ async invoke(path2, data) {
258
455
  const seq = ++this._seq;
259
456
  const now = Date.now();
260
- import_log2.log.info("req", {
457
+ import_log3.log.info("req", {
261
458
  seq,
262
- name
459
+ path: path2
263
460
  }, {
264
- F: __dxlog_file2,
265
- L: 161,
461
+ F: __dxlog_file3,
462
+ L: 204,
463
+ S: this,
464
+ C: (f, a) => f(...a)
465
+ });
466
+ const statusCode = await this._invoke(path2, {
467
+ data
468
+ });
469
+ import_log3.log.info("res", {
470
+ seq,
471
+ path: path2,
472
+ statusCode,
473
+ duration: Date.now() - now
474
+ }, {
475
+ F: __dxlog_file3,
476
+ L: 207,
266
477
  S: this,
267
478
  C: (f, a) => f(...a)
268
479
  });
269
- const { handler } = this._handlers[name];
480
+ this.update.emit(statusCode);
481
+ return statusCode;
482
+ }
483
+ async _invoke(path2, event) {
484
+ const { handler } = this._handlers[path2] ?? {};
485
+ (0, import_invariant.invariant)(handler, `invalid path: ${path2}`, {
486
+ F: __dxlog_file3,
487
+ L: 214,
488
+ S: this,
489
+ A: [
490
+ "handler",
491
+ "`invalid path: ${path}`"
492
+ ]
493
+ });
270
494
  const context = {
271
495
  client: this._client,
272
496
  dataDir: this._options.dataDir
@@ -283,439 +507,636 @@ var DevServer = class {
283
507
  event,
284
508
  response
285
509
  });
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
510
  return statusCode;
298
511
  }
299
512
  };
300
- 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";
301
517
  var Scheduler = class {
302
- constructor(_client, _manifest, _options = {}) {
303
- this._client = _client;
304
- this._manifest = _manifest;
518
+ constructor(functions, triggers, _options = {}) {
519
+ this.functions = functions;
520
+ this.triggers = triggers;
305
521
  this._options = _options;
306
- this._mounts = new import_util2.ComplexMap(({ id, spaceKey }) => `${spaceKey.toHex()}:${id}`);
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
+ });
307
530
  }
308
531
  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
- });
532
+ await this._ctx.dispose();
533
+ this._ctx = createContext2();
534
+ await this.functions.open(this._ctx);
535
+ await this.triggers.open(this._ctx);
317
536
  }
318
537
  async stop() {
319
- for (const { id, spaceKey } of this._mounts.keys()) {
320
- await this.unmount(id, spaceKey);
321
- }
538
+ await this._ctx.dispose();
539
+ await this.functions.close();
540
+ await this.triggers.close();
322
541
  }
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
- ]
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);
337
550
  });
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,
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", {
346
557
  trigger
347
558
  }, {
348
- F: __dxlog_file3,
559
+ F: __dxlog_file4,
349
560
  L: 78,
350
561
  S: this,
351
562
  C: (f, a) => f(...a)
352
563
  });
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
- }
564
+ return;
368
565
  }
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();
379
- }
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
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
386
571
  }, {
387
- F: __dxlog_file3,
388
- L: 117,
572
+ F: __dxlog_file4,
573
+ L: 86,
389
574
  S: this,
390
575
  C: (f, a) => f(...a)
391
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
+ });
604
+ }
605
+ async _execFunction(def, trigger, { data, meta }) {
606
+ let status = 0;
607
+ try {
608
+ const payload = Object.assign({}, meta && {
609
+ meta
610
+ }, data);
392
611
  const { endpoint, callback } = this._options;
393
612
  if (endpoint) {
394
- await fetch(`${this._options.endpoint}/${def.name}`, {
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
618
+ }, {
619
+ F: __dxlog_file4,
620
+ L: 113,
621
+ S: this,
622
+ C: (f, a) => f(...a)
623
+ });
624
+ const response = await fetch(url, {
395
625
  method: "POST",
396
626
  headers: {
397
627
  "Content-Type": "application/json"
398
628
  },
399
- body: JSON.stringify(data)
629
+ body: JSON.stringify(payload)
400
630
  });
631
+ status = response.status;
401
632
  } else if (callback) {
402
- await callback(data);
633
+ import_log4.log.info("exec", {
634
+ function: def.uri
635
+ }, {
636
+ F: __dxlog_file4,
637
+ L: 124,
638
+ S: this,
639
+ C: (f, a) => f(...a)
640
+ });
641
+ status = await callback(payload) ?? 200;
642
+ }
643
+ if (status && status >= 400) {
644
+ throw new Error(`Response: ${status}`);
403
645
  }
404
- import_log3.log.info("done", {
405
- function: def.id
646
+ import_log4.log.info("done", {
647
+ function: def.uri,
648
+ status
406
649
  }, {
407
- F: __dxlog_file3,
408
- L: 133,
650
+ F: __dxlog_file4,
651
+ L: 134,
409
652
  S: this,
410
653
  C: (f, a) => f(...a)
411
654
  });
412
655
  } catch (err) {
413
- import_log3.log.error("error", {
414
- function: def.id,
656
+ import_log4.log.error("error", {
657
+ function: def.uri,
415
658
  error: err.message
416
659
  }, {
417
- F: __dxlog_file3,
418
- L: 135,
660
+ F: __dxlog_file4,
661
+ L: 136,
419
662
  S: this,
420
663
  C: (f, a) => f(...a)
421
664
  });
665
+ status = 500;
422
666
  }
667
+ return status;
423
668
  }
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
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
434
714
  }, {
435
- F: __dxlog_file3,
436
- L: 147,
437
- S: this,
715
+ F: __dxlog_file5,
716
+ L: 57,
717
+ S: void 0,
438
718
  C: (f, a) => f(...a)
439
719
  });
440
- const { cron } = trigger;
441
- const task = new import_async2.DeferredTask(ctx, async () => {
442
- await this._execFunction(def, {
443
- space: 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)
444
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)
445
800
  });
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
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
460
821
  }, {
461
- F: __dxlog_file3,
462
- L: 167,
463
- 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,
464
840
  C: (f, a) => f(...a)
465
841
  });
466
- task.schedule();
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,
864
+ C: (f, a) => f(...a)
865
+ });
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
+ }
467
889
  }
468
890
  });
469
- job.start();
470
- 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
+ }
471
908
  }
472
- /**
473
- * Webhook.
474
- */
475
- async _createWebhook(ctx, space, def, trigger) {
476
- 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", {
477
937
  space: space.key,
478
938
  trigger
479
939
  }, {
480
- F: __dxlog_file3,
481
- L: 180,
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,
482
977
  S: this,
483
978
  C: (f, a) => f(...a)
484
979
  });
485
- const { port } = trigger;
486
- const server = import_node_http.default.createServer(async (req, res) => {
487
- await this._execFunction(def, {
488
- space: space.key
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
+ ];
996
+ }
997
+ return (0, import_echo2.create)(import_chunk_3UYUR5N5.FunctionTrigger, trigger, {
998
+ keys
489
999
  });
490
1000
  });
491
- server.listen(port, () => {
492
- import_log3.log.info("started webhook", {
493
- 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)
494
1007
  }, {
495
- F: __dxlog_file3,
496
- L: 189,
1008
+ F: __dxlog_file9,
1009
+ L: 120,
497
1010
  S: this,
498
1011
  C: (f, a) => f(...a)
499
1012
  });
500
1013
  });
501
- ctx.onDispose(() => {
502
- server.close();
503
- });
1014
+ if (added.length > 0) {
1015
+ await space.db.flush();
1016
+ }
504
1017
  }
505
- /**
506
- * Websocket.
507
- */
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
515
- }, {
516
- F: __dxlog_file3,
517
- L: 213,
1018
+ async _open() {
1019
+ import_log5.log.info("open...", void 0, {
1020
+ F: __dxlog_file9,
1021
+ L: 129,
518
1022
  S: this,
519
1023
  C: (f, a) => f(...a)
520
1024
  });
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
- }
1025
+ const spaceListSubscription = this._client.spaces.subscribe(async (spaces) => {
1026
+ for (const space of spaces) {
1027
+ if (this._triggersBySpaceKey.has(space.key)) {
1028
+ continue;
579
1029
  }
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
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
589
1041
  }, {
590
- F: __dxlog_file3,
591
- L: 256,
1042
+ F: __dxlog_file9,
1043
+ L: 146,
592
1044
  S: this,
593
1045
  C: (f, a) => f(...a)
594
1046
  });
595
- await (0, import_async2.sleep)(wait * 1e3);
596
- }
1047
+ await this._handleRemovedTriggers(space, current, registered);
1048
+ this._handleNewTriggers(space, current, registered);
1049
+ }));
597
1050
  }
598
- }
599
- ctx.onDispose(() => {
600
- 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)
601
1058
  });
602
1059
  }
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,
1060
+ async _close(_) {
1061
+ import_log5.log.info("close...", void 0, {
1062
+ F: __dxlog_file9,
1063
+ L: 159,
613
1064
  S: this,
614
1065
  C: (f, a) => f(...a)
615
1066
  });
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
- });
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)
622
1073
  });
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,
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,
631
1090
  S: this,
632
1091
  C: (f, a) => f(...a)
633
1092
  });
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
- }
662
- }
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);
663
1107
  }
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
- });
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);
670
1128
  }
671
1129
  };
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
1130
  // Annotate the CommonJS export names for ESM import in node:
715
1131
  0 && (module.exports = {
716
1132
  DevServer,
1133
+ FUNCTION_SCHEMA,
1134
+ FunctionDef,
717
1135
  FunctionManifestSchema,
1136
+ FunctionRegistry,
1137
+ FunctionTrigger,
718
1138
  Scheduler,
1139
+ TriggerRegistry,
719
1140
  subscriptionHandler
720
1141
  });
721
1142
  //# sourceMappingURL=index.cjs.map