@dxos/functions 0.6.10 → 0.6.11-staging.30cf5ba

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