@dxos/functions 0.5.3-main.59db342 → 0.5.3-main.5e3471c

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 (97) 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 +915 -297
  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 +901 -290
  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 +3 -1
  26. package/dist/types/src/index.d.ts.map +1 -1
  27. package/dist/types/src/runtime/dev-server.d.ts +15 -7
  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 +15 -15
  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 +215 -0
  64. package/dist/types/src/types.d.ts.map +1 -0
  65. package/dist/types/tools/schema.d.ts +2 -0
  66. package/dist/types/tools/schema.d.ts.map +1 -0
  67. package/package.json +38 -13
  68. package/schema/functions.json +211 -0
  69. package/src/browser/index.ts +5 -0
  70. package/src/function/function-registry.test.ts +105 -0
  71. package/src/function/function-registry.ts +90 -0
  72. package/src/function/index.ts +5 -0
  73. package/src/handler.ts +56 -26
  74. package/src/index.ts +3 -1
  75. package/src/runtime/dev-server.test.ts +60 -0
  76. package/src/runtime/dev-server.ts +104 -53
  77. package/src/runtime/scheduler.test.ts +159 -21
  78. package/src/runtime/scheduler.ts +87 -150
  79. package/src/testing/functions-integration.test.ts +100 -0
  80. package/src/testing/index.ts +7 -0
  81. package/src/testing/setup.ts +43 -0
  82. package/src/testing/test/handler.ts +15 -0
  83. package/src/testing/test/index.ts +7 -0
  84. package/src/testing/types.ts +9 -0
  85. package/src/testing/util.ts +16 -0
  86. package/src/trigger/index.ts +5 -0
  87. package/src/trigger/trigger-registry.test.ts +272 -0
  88. package/src/trigger/trigger-registry.ts +211 -0
  89. package/src/trigger/type/index.ts +8 -0
  90. package/src/trigger/type/subscription-trigger.ts +86 -0
  91. package/src/trigger/type/timer-trigger.ts +45 -0
  92. package/src/trigger/type/webhook-trigger.ts +48 -0
  93. package/src/trigger/type/websocket-trigger.ts +92 -0
  94. package/src/types.ts +115 -0
  95. package/dist/types/src/manifest.d.ts +0 -26
  96. package/dist/types/src/manifest.d.ts.map +0 -1
  97. package/src/manifest.ts +0 -42
@@ -29,83 +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
+ 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,
32
37
  Scheduler: () => Scheduler,
38
+ TriggerRegistry: () => TriggerRegistry,
33
39
  subscriptionHandler: () => subscriptionHandler
34
40
  });
35
41
  module.exports = __toCommonJS(node_exports);
36
- 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");
37
47
  var import_log = require("@dxos/log");
38
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");
39
52
  var import_express = __toESM(require("express"));
40
53
  var import_get_port_please = require("get-port-please");
41
54
  var import_node_path = require("node:path");
42
- var import_async = require("@dxos/async");
43
- var import_invariant = require("@dxos/invariant");
44
- var import_log2 = require("@dxos/log");
45
- var import_cron = require("cron");
46
- var import_types = require("@braneframe/types");
47
55
  var import_async2 = require("@dxos/async");
48
- var import_echo = require("@dxos/client/echo");
49
- var import_context = require("@dxos/context");
50
- var import_invariant2 = require("@dxos/invariant");
56
+ var import_context2 = require("@dxos/context");
57
+ var import_invariant = require("@dxos/invariant");
51
58
  var import_log3 = require("@dxos/log");
52
- var import_util2 = require("@dxos/util");
53
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
54
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
55
- }) : x)(function(x) {
56
- if (typeof require !== "undefined")
57
- return require.apply(this, arguments);
58
- throw Error('Dynamic require of "' + x + '" is not supported');
59
- });
60
- var __dxlog_file = "/home/runner/work/dxos/dxos/packages/core/functions/src/handler.ts";
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");
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");
80
+ var import_node_http = __toESM(require("node:http"));
81
+ var import_log8 = require("@dxos/log");
82
+ var import_ws = __toESM(require("ws"));
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";
61
163
  var subscriptionHandler = (handler) => {
62
- return ({ event, context, ...rest }) => {
164
+ return ({ event: { data }, context, ...rest }) => {
63
165
  const { client } = context;
64
- const space = event.space ? client.spaces.get(import_client.PublicKey.from(event.space)) : void 0;
65
- const objects = space && event.objects?.map((id) => space.db.getObjectById(id)).filter(import_util.nonNullable);
66
- if (!!event.space && !space) {
67
- import_log.log.warn("invalid space", {
68
- 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
69
171
  }, {
70
- F: __dxlog_file,
71
- L: 61,
172
+ F: __dxlog_file2,
173
+ L: 91,
72
174
  S: void 0,
73
175
  C: (f, a) => f(...a)
74
176
  });
75
177
  } else {
76
- import_log.log.info("handler", {
178
+ import_log2.log.info("handler", {
77
179
  space: space?.key.truncate(),
78
180
  objects: objects?.length
79
181
  }, {
80
- F: __dxlog_file,
81
- L: 63,
182
+ F: __dxlog_file2,
183
+ L: 93,
82
184
  S: void 0,
83
185
  C: (f, a) => f(...a)
84
186
  });
85
187
  }
86
188
  return handler({
87
189
  event: {
88
- space,
89
- objects
190
+ data: {
191
+ ...data,
192
+ space,
193
+ objects
194
+ }
90
195
  },
91
196
  context,
92
197
  ...rest
93
198
  });
94
199
  };
95
200
  };
96
- 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";
97
202
  var DevServer = class {
98
- // prettier-ignore
99
- constructor(_client, _options) {
203
+ constructor(_client, _functionsRegistry, _options) {
100
204
  this._client = _client;
205
+ this._functionsRegistry = _functionsRegistry;
101
206
  this._options = _options;
207
+ this._ctx = createContext();
102
208
  this._handlers = {};
103
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
+ };
104
228
  }
105
229
  get endpoint() {
106
230
  (0, import_invariant.invariant)(this._port, void 0, {
107
- F: __dxlog_file2,
108
- L: 46,
231
+ F: __dxlog_file3,
232
+ L: 64,
109
233
  S: this,
110
234
  A: [
111
235
  "this._port",
@@ -120,44 +244,46 @@ var DevServer = class {
120
244
  get functions() {
121
245
  return Object.values(this._handlers);
122
246
  }
123
- async initialize() {
124
- for (const def of this._options.manifest.functions) {
125
- try {
126
- await this._load(def);
127
- } catch (err) {
128
- import_log2.log.error("parsing function (check manifest)", err, {
129
- F: __dxlog_file2,
130
- L: 63,
131
- S: this,
132
- C: (f, a) => f(...a)
133
- });
134
- }
135
- }
136
- }
137
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();
138
264
  const app = (0, import_express.default)();
139
265
  app.use(import_express.default.json());
140
- app.post("/:name", async (req, res) => {
141
- const { name } = req.params;
266
+ app.post("/:path", async (req, res) => {
267
+ const { path: path2 } = req.params;
142
268
  try {
143
- import_log2.log.info("calling", {
144
- name
269
+ import_log3.log.info("calling", {
270
+ path: path2
145
271
  }, {
146
- F: __dxlog_file2,
147
- L: 75,
272
+ F: __dxlog_file3,
273
+ L: 88,
148
274
  S: this,
149
275
  C: (f, a) => f(...a)
150
276
  });
151
277
  if (this._options.reload) {
152
- const { def } = this._handlers[name];
278
+ const { def } = this._handlers["/" + path2];
153
279
  await this._load(def, true);
154
280
  }
155
- res.statusCode = await this._invoke(name, req.body);
281
+ res.statusCode = await this.invoke("/" + path2, req.body);
156
282
  res.end();
157
283
  } catch (err) {
158
- import_log2.log.catch(err, void 0, {
159
- F: __dxlog_file2,
160
- L: 84,
284
+ import_log3.log.catch(err, void 0, {
285
+ F: __dxlog_file3,
286
+ L: 98,
161
287
  S: this,
162
288
  C: (f, a) => f(...a)
163
289
  });
@@ -176,93 +302,195 @@ var DevServer = class {
176
302
  this._server = app.listen(this._port);
177
303
  try {
178
304
  const { registrationId, endpoint } = await this._client.services.services.FunctionRegistryService.register({
179
- endpoint: this.endpoint,
180
- functions: this.functions.map(({ def: { name } }) => ({
181
- name
182
- }))
305
+ endpoint: this.endpoint
183
306
  });
184
- import_log2.log.info("registered", {
185
- registrationId,
307
+ import_log3.log.info("registered", {
186
308
  endpoint
187
309
  }, {
188
- F: __dxlog_file2,
189
- L: 100,
310
+ F: __dxlog_file3,
311
+ L: 113,
190
312
  S: this,
191
313
  C: (f, a) => f(...a)
192
314
  });
193
- this._registrationId = registrationId;
194
315
  this._proxy = endpoint;
316
+ this._functionServiceRegistration = registrationId;
317
+ await this._functionsRegistry.open(this._ctx);
195
318
  } catch (err) {
196
319
  await this.stop();
197
320
  throw new Error("FunctionRegistryService not available (check plugin is configured).");
198
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
+ });
199
330
  }
200
331
  async stop() {
201
- const trigger = new import_async.Trigger();
202
- this._server?.close(async () => {
203
- if (this._registrationId) {
204
- await this._client.services.services.FunctionRegistryService.unregister({
205
- registrationId: this._registrationId
206
- });
207
- import_log2.log.info("unregistered", {
208
- registrationId: this._registrationId
209
- }, {
210
- F: __dxlog_file2,
211
- L: 117,
212
- S: this,
213
- C: (f, a) => f(...a)
214
- });
215
- this._registrationId = void 0;
216
- 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);
217
383
  }
218
- trigger.wake();
219
384
  });
220
385
  await trigger.wait();
221
386
  this._port = void 0;
222
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
+ });
223
394
  }
224
395
  /**
225
396
  * Load function.
226
397
  */
227
- async _load(def, flush = false) {
228
- const { id, name, handler } = def;
229
- const path = (0, import_node_path.join)(this._options.directory, handler);
230
- import_log2.log.info("loading", {
231
- 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
232
404
  }, {
233
- F: __dxlog_file2,
234
- L: 136,
405
+ F: __dxlog_file3,
406
+ L: 164,
235
407
  S: this,
236
408
  C: (f, a) => f(...a)
237
409
  });
238
- if (flush) {
239
- 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
+ });
240
414
  }
241
- const module2 = __require(path);
415
+ const module2 = (0, import_chunk_3UYUR5N5.__require)(filePath);
242
416
  if (typeof module2.default !== "function") {
243
- throw new Error(`Handler must export default function: ${id}`);
417
+ throw new Error(`Handler must export default function: ${uri}`);
244
418
  }
245
- this._handlers[name] = {
419
+ this._handlers[route] = {
246
420
  def,
247
421
  handler: module2.default
248
422
  };
249
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
+ }
250
451
  /**
251
- * Invoke function handler.
452
+ * Invoke function.
252
453
  */
253
- async _invoke(name, event) {
454
+ async invoke(path2, data) {
254
455
  const seq = ++this._seq;
255
456
  const now = Date.now();
256
- import_log2.log.info("req", {
457
+ import_log3.log.info("req", {
257
458
  seq,
258
- name
459
+ path: path2
259
460
  }, {
260
- F: __dxlog_file2,
261
- L: 161,
461
+ F: __dxlog_file3,
462
+ L: 204,
262
463
  S: this,
263
464
  C: (f, a) => f(...a)
264
465
  });
265
- const { handler } = this._handlers[name];
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,
477
+ S: this,
478
+ C: (f, a) => f(...a)
479
+ });
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
+ });
266
494
  const context = {
267
495
  client: this._client,
268
496
  dataDir: this._options.dataDir
@@ -279,253 +507,636 @@ var DevServer = class {
279
507
  event,
280
508
  response
281
509
  });
282
- import_log2.log.info("res", {
283
- seq,
284
- name,
285
- statusCode,
286
- duration: Date.now() - now
287
- }, {
288
- F: __dxlog_file2,
289
- L: 178,
290
- S: this,
291
- C: (f, a) => f(...a)
292
- });
293
510
  return statusCode;
294
511
  }
295
512
  };
296
- 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";
297
517
  var Scheduler = class {
298
- constructor(_client, _manifest, _options = {}) {
299
- this._client = _client;
300
- this._manifest = _manifest;
518
+ constructor(functions, triggers, _options = {}) {
519
+ this.functions = functions;
520
+ this.triggers = triggers;
301
521
  this._options = _options;
302
- 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
+ });
303
530
  }
304
531
  async start() {
305
- this._client.spaces.subscribe(async (spaces) => {
306
- for (const space of spaces) {
307
- await space.waitUntilReady();
308
- for (const trigger of this._manifest.triggers ?? []) {
309
- await this.mount(new import_context.Context(), space, trigger);
310
- }
311
- }
312
- });
532
+ await this._ctx.dispose();
533
+ this._ctx = createContext2();
534
+ await this.functions.open(this._ctx);
535
+ await this.triggers.open(this._ctx);
313
536
  }
314
537
  async stop() {
315
- for (const { id, spaceKey } of this._mounts.keys()) {
316
- await this.unmount(id, spaceKey);
317
- }
538
+ await this._ctx.dispose();
539
+ await this.functions.close();
540
+ await this.triggers.close();
318
541
  }
319
- async mount(ctx, space, trigger) {
320
- const key = {
321
- id: trigger.function,
322
- spaceKey: space.key
323
- };
324
- const def = this._manifest.functions.find((config) => config.id === trigger.function);
325
- (0, import_invariant2.invariant)(def, `Function not found: ${trigger.function}`, {
326
- F: __dxlog_file3,
327
- L: 63,
328
- S: this,
329
- A: [
330
- "def",
331
- "`Function not found: ${trigger.function}`"
332
- ]
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);
333
550
  });
334
- const exists = this._mounts.get(key);
335
- if (!exists) {
336
- this._mounts.set(key, {
337
- ctx,
338
- trigger
339
- });
340
- (0, import_log3.log)("mount", {
341
- 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", {
342
557
  trigger
343
558
  }, {
344
- F: __dxlog_file3,
345
- L: 69,
559
+ F: __dxlog_file4,
560
+ L: 78,
346
561
  S: this,
347
562
  C: (f, a) => f(...a)
348
563
  });
349
- if (ctx.disposed) {
350
- return;
351
- }
352
- if (trigger.schedule) {
353
- this._createTimer(ctx, space, def, trigger);
354
- }
355
- for (const triggerSubscription of trigger.subscriptions ?? []) {
356
- this._createSubscription(ctx, space, def, triggerSubscription);
357
- }
358
- }
359
- }
360
- async unmount(id, spaceKey) {
361
- const key = {
362
- id,
363
- spaceKey
364
- };
365
- const { ctx } = this._mounts.get(key) ?? {};
366
- if (ctx) {
367
- this._mounts.delete(key);
368
- await ctx.dispose();
564
+ return;
369
565
  }
370
- }
371
- _createTimer(ctx, space, def, trigger) {
372
- const task = new import_async2.DeferredTask(ctx, async () => {
373
- await this._execFunction(def, {
374
- space: space.key
566
+ await this.triggers.activate(space, trigger, async (args) => {
567
+ const mutex = this._functionUriToCallMutex.get(definition.uri) ?? new import_async3.Mutex();
568
+ this._functionUriToCallMutex.set(definition.uri, mutex);
569
+ import_log4.log.info("function triggered, waiting for mutex", {
570
+ uri: definition.uri
571
+ }, {
572
+ F: __dxlog_file4,
573
+ L: 86,
574
+ S: this,
575
+ C: (f, a) => f(...a)
375
576
  });
376
- });
377
- (0, import_invariant2.invariant)(trigger.schedule, void 0, {
378
- F: __dxlog_file3,
379
- L: 102,
380
- S: this,
381
- A: [
382
- "trigger.schedule",
383
- ""
384
- ]
385
- });
386
- let last = 0;
387
- let run = 0;
388
- const job = import_cron.CronJob.from({
389
- cronTime: trigger.schedule,
390
- runOnInit: false,
391
- onTick: () => {
392
- const now = Date.now();
393
- const delta = last ? now - last : 0;
394
- last = now;
395
- run++;
396
- import_log3.log.info("tick", {
397
- space: space.key.truncate(),
398
- count: run,
399
- delta
577
+ return mutex.executeSynchronized(() => {
578
+ import_log4.log.info("mutex acquired", {
579
+ uri: definition.uri
400
580
  }, {
401
- F: __dxlog_file3,
402
- L: 116,
581
+ F: __dxlog_file4,
582
+ L: 88,
403
583
  S: this,
404
584
  C: (f, a) => f(...a)
405
585
  });
406
- task.schedule();
407
- }
586
+ return this._execFunction(definition, trigger, {
587
+ meta: trigger.meta ?? {},
588
+ data: {
589
+ ...args,
590
+ spaceKey: space.key
591
+ }
592
+ });
593
+ });
408
594
  });
409
- job.start();
410
- ctx.onDispose(() => job.stop());
411
- }
412
- _createSubscription(ctx, space, def, triggerSubscription) {
413
- import_log3.log.info("subscription", {
595
+ (0, import_log4.log)("activated trigger", {
414
596
  space: space.key,
415
- triggerSubscription
597
+ trigger
416
598
  }, {
417
- F: __dxlog_file3,
418
- L: 126,
599
+ F: __dxlog_file4,
600
+ L: 96,
419
601
  S: this,
420
602
  C: (f, a) => f(...a)
421
603
  });
422
- const objectIds = /* @__PURE__ */ new Set();
423
- const task = new import_async2.DeferredTask(ctx, async () => {
424
- await this._execFunction(def, {
425
- space: space.key,
426
- objects: Array.from(objectIds)
604
+ }
605
+ async _execFunction(def, trigger, { data, meta }) {
606
+ let status = 0;
607
+ try {
608
+ const payload = Object.assign({}, meta && {
609
+ meta
610
+ }, data);
611
+ const { endpoint, callback } = this._options;
612
+ if (endpoint) {
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, {
625
+ method: "POST",
626
+ headers: {
627
+ "Content-Type": "application/json"
628
+ },
629
+ body: JSON.stringify(payload)
630
+ });
631
+ status = response.status;
632
+ } else if (callback) {
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}`);
645
+ }
646
+ import_log4.log.info("done", {
647
+ function: def.uri,
648
+ status
649
+ }, {
650
+ F: __dxlog_file4,
651
+ L: 134,
652
+ S: this,
653
+ C: (f, a) => f(...a)
427
654
  });
428
- });
429
- const subscriptions = [];
430
- const subscription = (0, import_echo.createSubscription)(({ added, updated }) => {
431
- import_log3.log.info("updated", {
655
+ } catch (err) {
656
+ import_log4.log.error("error", {
657
+ function: def.uri,
658
+ error: err.message
659
+ }, {
660
+ F: __dxlog_file4,
661
+ L: 136,
662
+ S: this,
663
+ C: (f, a) => f(...a)
664
+ });
665
+ status = 500;
666
+ }
667
+ return status;
668
+ }
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", {
432
698
  added: added.length,
433
699
  updated: updated.length
434
700
  }, {
435
- F: __dxlog_file3,
436
- L: 139,
437
- S: this,
701
+ F: __dxlog_file5,
702
+ L: 47,
703
+ S: void 0,
438
704
  C: (f, a) => f(...a)
439
705
  });
440
- for (const object of added) {
441
- objectIds.add(object.id);
442
- }
443
- for (const object of updated) {
444
- objectIds.add(object.id);
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
714
+ }, {
715
+ F: __dxlog_file5,
716
+ L: 57,
717
+ S: void 0,
718
+ C: (f, a) => f(...a)
719
+ });
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
+ }
445
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)
772
+ });
446
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)
447
800
  });
448
- subscriptions.push(() => subscription.unsubscribe());
449
- const { type, props, deep, delay } = triggerSubscription;
450
- const update = ({ objects }) => {
451
- subscription.update(objects);
452
- if (deep) {
453
- import_log3.log.info("update", {
454
- type,
455
- deep,
456
- objects: objects.length
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
457
821
  }, {
458
- F: __dxlog_file3,
459
- L: 159,
460
- S: this,
822
+ F: __dxlog_file8,
823
+ L: 40,
824
+ S: void 0,
461
825
  C: (f, a) => f(...a)
462
826
  });
463
- for (const object of objects) {
464
- const content = object.content;
465
- if (content instanceof import_types.TextV0Type) {
466
- subscriptions.push((0, import_echo.getAutomergeObjectCore)(content).updates.on((0, import_async2.debounce)(() => subscription.update([
467
- object
468
- ]), 1e3)));
469
- }
827
+ if (spec.init) {
828
+ ws.send(new TextEncoder().encode(JSON.stringify(init)));
829
+ }
830
+ open.wake(true);
831
+ },
832
+ onclose: (event) => {
833
+ import_log9.log.info("closed", {
834
+ url,
835
+ code: event.code
836
+ }, {
837
+ F: __dxlog_file8,
838
+ L: 49,
839
+ S: void 0,
840
+ C: (f, a) => f(...a)
841
+ });
842
+ if (event.code === 1006) {
843
+ setTimeout(async () => {
844
+ import_log9.log.info(`reconnecting in ${options.retryDelay}s...`, {
845
+ url
846
+ }, {
847
+ F: __dxlog_file8,
848
+ L: 54,
849
+ S: void 0,
850
+ C: (f, a) => f(...a)
851
+ });
852
+ await createWebsocketTrigger(ctx, space, spec, callback, options);
853
+ }, options.retryDelay * 1e3);
854
+ }
855
+ open.wake(false);
856
+ },
857
+ onerror: (event) => {
858
+ import_log9.log.catch(event.error, {
859
+ url
860
+ }, {
861
+ F: __dxlog_file8,
862
+ L: 63,
863
+ S: void 0,
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
+ });
470
888
  }
471
889
  }
472
- };
473
- const query = space.db.query(import_echo.Filter.typename(type, props));
474
- subscriptions.push(query.subscribe(delay ? (0, import_async2.debounce)(update, delay * 1e3) : update));
475
- ctx.onDispose(() => {
476
- subscriptions.forEach((unsubscribe) => unsubscribe());
477
890
  });
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
+ }
908
+ }
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);
478
931
  }
479
- async _execFunction(def, data) {
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", {
937
+ space: space.key,
938
+ trigger
939
+ }, {
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;
480
960
  try {
481
- (0, import_log3.log)("request", {
482
- function: def.id
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,
977
+ S: this,
978
+ C: (f, a) => f(...a)
979
+ });
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
999
+ });
1000
+ });
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)
483
1007
  }, {
484
- F: __dxlog_file3,
485
- L: 183,
1008
+ F: __dxlog_file9,
1009
+ L: 120,
486
1010
  S: this,
487
1011
  C: (f, a) => f(...a)
488
1012
  });
489
- const { endpoint, callback } = this._options;
490
- let status = 0;
491
- if (endpoint) {
492
- const response = await fetch(`${this._options.endpoint}/${def.name}`, {
493
- method: "POST",
494
- headers: {
495
- "Content-Type": "application/json"
496
- },
497
- body: JSON.stringify(data)
498
- });
499
- status = response.status;
500
- } else if (callback) {
501
- status = await callback(data);
1013
+ });
1014
+ if (added.length > 0) {
1015
+ await space.db.flush();
1016
+ }
1017
+ }
1018
+ async _open() {
1019
+ import_log5.log.info("open...", void 0, {
1020
+ F: __dxlog_file9,
1021
+ L: 129,
1022
+ S: this,
1023
+ C: (f, a) => f(...a)
1024
+ });
1025
+ const spaceListSubscription = this._client.spaces.subscribe(async (spaces) => {
1026
+ for (const space of spaces) {
1027
+ if (this._triggersBySpaceKey.has(space.key)) {
1028
+ continue;
1029
+ }
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
1041
+ }, {
1042
+ F: __dxlog_file9,
1043
+ L: 146,
1044
+ S: this,
1045
+ C: (f, a) => f(...a)
1046
+ });
1047
+ await this._handleRemovedTriggers(space, current, registered);
1048
+ this._handleNewTriggers(space, current, registered);
1049
+ }));
502
1050
  }
503
- (0, import_log3.log)("result", {
504
- function: def.id,
505
- result: status
506
- }, {
507
- F: __dxlog_file3,
508
- L: 202,
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)
1058
+ });
1059
+ }
1060
+ async _close(_) {
1061
+ import_log5.log.info("close...", void 0, {
1062
+ F: __dxlog_file9,
1063
+ L: 159,
1064
+ S: this,
1065
+ C: (f, a) => f(...a)
1066
+ });
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)
1073
+ });
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,
509
1090
  S: this,
510
1091
  C: (f, a) => f(...a)
511
1092
  });
512
- } catch (err) {
513
- import_log3.log.error("error", {
514
- function: def.id,
515
- error: err.message
516
- }, {
517
- F: __dxlog_file3,
518
- L: 204,
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);
1107
+ }
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,
519
1116
  S: this,
520
1117
  C: (f, a) => f(...a)
521
1118
  });
1119
+ this.removed.emit({
1120
+ space,
1121
+ triggers: removed
1122
+ });
522
1123
  }
523
1124
  }
1125
+ _getTriggers(space, predicate) {
1126
+ const allSpaceTriggers = this._triggersBySpaceKey.get(space.key) ?? [];
1127
+ return allSpaceTriggers.filter(predicate).map((trigger) => trigger.trigger);
1128
+ }
524
1129
  };
525
1130
  // Annotate the CommonJS export names for ESM import in node:
526
1131
  0 && (module.exports = {
527
1132
  DevServer,
1133
+ FUNCTION_SCHEMA,
1134
+ FunctionDef,
1135
+ FunctionManifestSchema,
1136
+ FunctionRegistry,
1137
+ FunctionTrigger,
528
1138
  Scheduler,
1139
+ TriggerRegistry,
529
1140
  subscriptionHandler
530
1141
  });
531
1142
  //# sourceMappingURL=index.cjs.map