@dxos/functions 0.3.9-main.4e30508 → 0.3.9-main.4e39f3a
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.
- package/dist/lib/browser/index.mjs +123 -72
- package/dist/lib/browser/index.mjs.map +4 -4
- package/dist/lib/browser/meta.json +1 -1
- package/dist/lib/node/index.cjs +119 -76
- package/dist/lib/node/index.cjs.map +4 -4
- package/dist/lib/node/meta.json +1 -1
- package/dist/types/src/handler.d.ts +9 -2
- package/dist/types/src/handler.d.ts.map +1 -1
- package/dist/types/src/manifest.d.ts +1 -1
- package/dist/types/src/manifest.d.ts.map +1 -1
- package/dist/types/src/runtime/scheduler.d.ts +8 -3
- package/dist/types/src/runtime/scheduler.d.ts.map +1 -1
- package/dist/types/src/runtime/scheduler.test.d.ts +2 -0
- package/dist/types/src/runtime/scheduler.test.d.ts.map +1 -0
- package/package.json +9 -9
- package/src/handler.ts +28 -3
- package/src/manifest.ts +2 -2
- package/src/runtime/dev-server.ts +1 -1
- package/src/runtime/scheduler.test.ts +57 -0
- package/src/runtime/scheduler.ts +95 -72
- package/dist/types/src/function.test.d.ts +0 -2
- package/dist/types/src/function.test.d.ts.map +0 -1
- package/src/function.test.ts +0 -7
package/dist/lib/node/index.cjs
CHANGED
|
@@ -29,9 +29,13 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
29
29
|
var node_exports = {};
|
|
30
30
|
__export(node_exports, {
|
|
31
31
|
DevServer: () => DevServer,
|
|
32
|
-
Scheduler: () => Scheduler
|
|
32
|
+
Scheduler: () => Scheduler,
|
|
33
|
+
subscriptionHandler: () => subscriptionHandler
|
|
33
34
|
});
|
|
34
35
|
module.exports = __toCommonJS(node_exports);
|
|
36
|
+
var import_client = require("@dxos/client");
|
|
37
|
+
var import_echo_schema = require("@dxos/echo-schema");
|
|
38
|
+
var import_util = require("@dxos/util");
|
|
35
39
|
var import_express = __toESM(require("express"));
|
|
36
40
|
var import_get_port_please = require("get-port-please");
|
|
37
41
|
var import_node_path = require("node:path");
|
|
@@ -42,10 +46,10 @@ var import_cron = require("cron");
|
|
|
42
46
|
var import_async2 = require("@dxos/async");
|
|
43
47
|
var import_echo = require("@dxos/client/echo");
|
|
44
48
|
var import_context = require("@dxos/context");
|
|
45
|
-
var
|
|
49
|
+
var import_echo_schema2 = require("@dxos/echo-schema");
|
|
46
50
|
var import_invariant2 = require("@dxos/invariant");
|
|
47
51
|
var import_log2 = require("@dxos/log");
|
|
48
|
-
var
|
|
52
|
+
var import_util2 = require("@dxos/util");
|
|
49
53
|
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
50
54
|
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
51
55
|
}) : x)(function(x) {
|
|
@@ -53,6 +57,21 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
|
|
|
53
57
|
return require.apply(this, arguments);
|
|
54
58
|
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
55
59
|
});
|
|
60
|
+
var subscriptionHandler = (handler) => {
|
|
61
|
+
return ({ event, context, ...rest }) => {
|
|
62
|
+
const { client } = context;
|
|
63
|
+
const space = event.space ? client.spaces.get(import_client.PublicKey.from(event.space)) : void 0;
|
|
64
|
+
const objects = space && event.objects?.map((id) => space.db.getObjectById(id)).filter(import_util.nonNullable).filter(import_echo_schema.isTypedObject);
|
|
65
|
+
return handler({
|
|
66
|
+
event: {
|
|
67
|
+
space,
|
|
68
|
+
objects
|
|
69
|
+
},
|
|
70
|
+
context,
|
|
71
|
+
...rest
|
|
72
|
+
});
|
|
73
|
+
};
|
|
74
|
+
};
|
|
56
75
|
var __dxlog_file = "/home/runner/work/dxos/dxos/packages/core/functions/src/runtime/dev-server.ts";
|
|
57
76
|
var DevServer = class {
|
|
58
77
|
// prettier-ignore
|
|
@@ -118,6 +137,7 @@ var DevServer = class {
|
|
|
118
137
|
}
|
|
119
138
|
});
|
|
120
139
|
this._port = await (0, import_get_port_please.getPort)({
|
|
140
|
+
host: "localhost",
|
|
121
141
|
port: 7200,
|
|
122
142
|
portRange: [
|
|
123
143
|
7200,
|
|
@@ -246,11 +266,11 @@ var DevServer = class {
|
|
|
246
266
|
};
|
|
247
267
|
var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/core/functions/src/runtime/scheduler.ts";
|
|
248
268
|
var Scheduler = class {
|
|
249
|
-
constructor(_client, _manifest, _options) {
|
|
269
|
+
constructor(_client, _manifest, _options = {}) {
|
|
250
270
|
this._client = _client;
|
|
251
271
|
this._manifest = _manifest;
|
|
252
272
|
this._options = _options;
|
|
253
|
-
this._mounts = new
|
|
273
|
+
this._mounts = new import_util2.ComplexMap(({ id, spaceKey }) => `${spaceKey.toHex()}:${id}`);
|
|
254
274
|
}
|
|
255
275
|
async start() {
|
|
256
276
|
this._client.spaces.subscribe(async (spaces) => {
|
|
@@ -275,7 +295,7 @@ var Scheduler = class {
|
|
|
275
295
|
const def = this._manifest.functions.find((config) => config.id === trigger.function);
|
|
276
296
|
(0, import_invariant2.invariant)(def, `Function not found: ${trigger.function}`, {
|
|
277
297
|
F: __dxlog_file2,
|
|
278
|
-
L:
|
|
298
|
+
L: 63,
|
|
279
299
|
S: this,
|
|
280
300
|
A: [
|
|
281
301
|
"def",
|
|
@@ -293,7 +313,7 @@ var Scheduler = class {
|
|
|
293
313
|
trigger
|
|
294
314
|
}, {
|
|
295
315
|
F: __dxlog_file2,
|
|
296
|
-
L:
|
|
316
|
+
L: 69,
|
|
297
317
|
S: this,
|
|
298
318
|
C: (f, a) => f(...a)
|
|
299
319
|
});
|
|
@@ -301,63 +321,10 @@ var Scheduler = class {
|
|
|
301
321
|
return;
|
|
302
322
|
}
|
|
303
323
|
if (trigger.schedule) {
|
|
304
|
-
|
|
305
|
-
await this.execFunction(def, {
|
|
306
|
-
space: space.key
|
|
307
|
-
});
|
|
308
|
-
});
|
|
309
|
-
const job = new import_cron.CronJob(trigger.schedule, () => task.schedule());
|
|
310
|
-
job.start();
|
|
311
|
-
ctx.onDispose(() => job.stop());
|
|
324
|
+
this._createTimer(ctx, space, def, trigger);
|
|
312
325
|
}
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
const task = new import_async2.DeferredTask(ctx, async () => {
|
|
316
|
-
await this.execFunction(def, {
|
|
317
|
-
space: space.key,
|
|
318
|
-
objects: Array.from(objectIds)
|
|
319
|
-
});
|
|
320
|
-
});
|
|
321
|
-
const subscriptions = [];
|
|
322
|
-
const subscription = (0, import_echo_schema.createSubscription)(({ added, updated }) => {
|
|
323
|
-
for (const object of added) {
|
|
324
|
-
objectIds.add(object.id);
|
|
325
|
-
}
|
|
326
|
-
for (const object of updated) {
|
|
327
|
-
objectIds.add(object.id);
|
|
328
|
-
}
|
|
329
|
-
task.schedule();
|
|
330
|
-
});
|
|
331
|
-
subscriptions.push(() => subscription.unsubscribe());
|
|
332
|
-
const { type, props, deep, delay } = trigger.subscription;
|
|
333
|
-
const update = ({ objects }) => {
|
|
334
|
-
subscription.update(objects);
|
|
335
|
-
if (deep) {
|
|
336
|
-
import_log2.log.info("update", {
|
|
337
|
-
type,
|
|
338
|
-
deep,
|
|
339
|
-
objects: objects.length
|
|
340
|
-
}, {
|
|
341
|
-
F: __dxlog_file2,
|
|
342
|
-
L: 114,
|
|
343
|
-
S: this,
|
|
344
|
-
C: (f, a) => f(...a)
|
|
345
|
-
});
|
|
346
|
-
for (const object of objects) {
|
|
347
|
-
const content = object.content;
|
|
348
|
-
if (content instanceof import_echo.TextObject) {
|
|
349
|
-
subscriptions.push(content[import_echo_schema.subscribe]((0, import_async2.debounce)(() => subscription.update([
|
|
350
|
-
object
|
|
351
|
-
]), 1e3)));
|
|
352
|
-
}
|
|
353
|
-
}
|
|
354
|
-
}
|
|
355
|
-
};
|
|
356
|
-
const query = space.db.query(import_echo_schema.Filter.typename(type, props));
|
|
357
|
-
subscriptions.push(query.subscribe(delay ? (0, import_async2.debounce)(update, delay * 1e3) : update));
|
|
358
|
-
ctx.onDispose(() => {
|
|
359
|
-
subscriptions.forEach((unsubscribe) => unsubscribe());
|
|
360
|
-
});
|
|
326
|
+
for (const triggerSubscription of trigger.subscriptions ?? []) {
|
|
327
|
+
this._createSubscription(ctx, space, def, triggerSubscription);
|
|
361
328
|
}
|
|
362
329
|
}
|
|
363
330
|
}
|
|
@@ -372,29 +339,104 @@ var Scheduler = class {
|
|
|
372
339
|
await ctx.dispose();
|
|
373
340
|
}
|
|
374
341
|
}
|
|
375
|
-
|
|
342
|
+
_createTimer(ctx, space, def, trigger) {
|
|
343
|
+
const task = new import_async2.DeferredTask(ctx, async () => {
|
|
344
|
+
await this._execFunction(def, {
|
|
345
|
+
space: space.key
|
|
346
|
+
});
|
|
347
|
+
});
|
|
348
|
+
(0, import_invariant2.invariant)(trigger.schedule, void 0, {
|
|
349
|
+
F: __dxlog_file2,
|
|
350
|
+
L: 103,
|
|
351
|
+
S: this,
|
|
352
|
+
A: [
|
|
353
|
+
"trigger.schedule",
|
|
354
|
+
""
|
|
355
|
+
]
|
|
356
|
+
});
|
|
357
|
+
const job = new import_cron.CronJob(trigger.schedule, () => task.schedule());
|
|
358
|
+
job.start();
|
|
359
|
+
ctx.onDispose(() => job.stop());
|
|
360
|
+
}
|
|
361
|
+
_createSubscription(ctx, space, def, triggerSubscription) {
|
|
362
|
+
const objectIds = /* @__PURE__ */ new Set();
|
|
363
|
+
const task = new import_async2.DeferredTask(ctx, async () => {
|
|
364
|
+
await this._execFunction(def, {
|
|
365
|
+
space: space.key,
|
|
366
|
+
objects: Array.from(objectIds)
|
|
367
|
+
});
|
|
368
|
+
});
|
|
369
|
+
const subscriptions = [];
|
|
370
|
+
const subscription = (0, import_echo_schema2.createSubscription)(({ added, updated }) => {
|
|
371
|
+
for (const object of added) {
|
|
372
|
+
objectIds.add(object.id);
|
|
373
|
+
}
|
|
374
|
+
for (const object of updated) {
|
|
375
|
+
objectIds.add(object.id);
|
|
376
|
+
}
|
|
377
|
+
task.schedule();
|
|
378
|
+
});
|
|
379
|
+
subscriptions.push(() => subscription.unsubscribe());
|
|
380
|
+
const { type, props, deep, delay } = triggerSubscription;
|
|
381
|
+
const update = ({ objects }) => {
|
|
382
|
+
subscription.update(objects);
|
|
383
|
+
if (deep) {
|
|
384
|
+
import_log2.log.info("update", {
|
|
385
|
+
type,
|
|
386
|
+
deep,
|
|
387
|
+
objects: objects.length
|
|
388
|
+
}, {
|
|
389
|
+
F: __dxlog_file2,
|
|
390
|
+
L: 139,
|
|
391
|
+
S: this,
|
|
392
|
+
C: (f, a) => f(...a)
|
|
393
|
+
});
|
|
394
|
+
for (const object of objects) {
|
|
395
|
+
const content = object.content;
|
|
396
|
+
if (content instanceof import_echo.TextObject) {
|
|
397
|
+
subscriptions.push(content[import_echo_schema2.subscribe]((0, import_async2.debounce)(() => subscription.update([
|
|
398
|
+
object
|
|
399
|
+
]), 1e3)));
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
};
|
|
404
|
+
const query = space.db.query(import_echo_schema2.Filter.typename(type, props));
|
|
405
|
+
subscriptions.push(query.subscribe(delay ? (0, import_async2.debounce)(update, delay * 1e3) : update));
|
|
406
|
+
ctx.onDispose(() => {
|
|
407
|
+
subscriptions.forEach((unsubscribe) => unsubscribe());
|
|
408
|
+
});
|
|
409
|
+
}
|
|
410
|
+
async _execFunction(def, data) {
|
|
376
411
|
try {
|
|
377
412
|
(0, import_log2.log)("request", {
|
|
378
413
|
function: def.id
|
|
379
414
|
}, {
|
|
380
415
|
F: __dxlog_file2,
|
|
381
|
-
L:
|
|
416
|
+
L: 161,
|
|
382
417
|
S: this,
|
|
383
418
|
C: (f, a) => f(...a)
|
|
384
419
|
});
|
|
385
|
-
const
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
420
|
+
const { endpoint, callback } = this._options;
|
|
421
|
+
let status = 0;
|
|
422
|
+
if (endpoint) {
|
|
423
|
+
const response = await fetch(`${this._options.endpoint}/${def.name}`, {
|
|
424
|
+
method: "POST",
|
|
425
|
+
headers: {
|
|
426
|
+
"Content-Type": "application/json"
|
|
427
|
+
},
|
|
428
|
+
body: JSON.stringify(data)
|
|
429
|
+
});
|
|
430
|
+
status = response.status;
|
|
431
|
+
} else if (callback) {
|
|
432
|
+
status = await callback(data);
|
|
433
|
+
}
|
|
392
434
|
(0, import_log2.log)("result", {
|
|
393
435
|
function: def.id,
|
|
394
|
-
result:
|
|
436
|
+
result: status
|
|
395
437
|
}, {
|
|
396
438
|
F: __dxlog_file2,
|
|
397
|
-
L:
|
|
439
|
+
L: 180,
|
|
398
440
|
S: this,
|
|
399
441
|
C: (f, a) => f(...a)
|
|
400
442
|
});
|
|
@@ -404,7 +446,7 @@ var Scheduler = class {
|
|
|
404
446
|
error: err.message
|
|
405
447
|
}, {
|
|
406
448
|
F: __dxlog_file2,
|
|
407
|
-
L:
|
|
449
|
+
L: 182,
|
|
408
450
|
S: this,
|
|
409
451
|
C: (f, a) => f(...a)
|
|
410
452
|
});
|
|
@@ -414,6 +456,7 @@ var Scheduler = class {
|
|
|
414
456
|
// Annotate the CommonJS export names for ESM import in node:
|
|
415
457
|
0 && (module.exports = {
|
|
416
458
|
DevServer,
|
|
417
|
-
Scheduler
|
|
459
|
+
Scheduler,
|
|
460
|
+
subscriptionHandler
|
|
418
461
|
});
|
|
419
462
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../../../src/runtime/dev-server.ts", "../../../src/runtime/scheduler.ts"],
|
|
4
|
-
"sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport express from 'express';\nimport { getPort } from 'get-port-please';\nimport type http from 'http';\nimport { join } from 'node:path';\n\nimport { Trigger } from '@dxos/async';\nimport { type Client } from '@dxos/client';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\n\nimport { type FunctionContext, type FunctionHandler, type Response } from '../handler';\nimport { type FunctionDef, type FunctionManifest } from '../manifest';\n\nexport type DevServerOptions = {\n port?: number;\n directory: string;\n manifest: FunctionManifest;\n reload?: boolean;\n dataDir?: string;\n};\n\n/**\n * Functions dev server provides a local HTTP server for testing functions.\n */\nexport class DevServer {\n // Function handlers indexed by name (URL path).\n private readonly _handlers: Record<string, { def: FunctionDef; handler: FunctionHandler<any> }> = {};\n\n private _server?: http.Server;\n private _port?: number;\n private _registrationId?: string;\n private _proxy?: string;\n private _seq = 0;\n\n // prettier-ignore\n constructor(\n private readonly _client: Client,\n private readonly _options: DevServerOptions,\n ) {}\n\n get endpoint() {\n invariant(this._port);\n return `http://localhost:${this._port}`;\n }\n\n get proxy() {\n return this._proxy;\n }\n\n get functions() {\n return Object.values(this._handlers);\n }\n\n async initialize() {\n for (const def of this._options.manifest.functions) {\n try {\n await this._load(def);\n } catch (err) {\n log.error('parsing function (check manifest)', err);\n }\n }\n }\n\n async start() {\n const app = express();\n app.use(express.json());\n\n app.post('/:name', async (req, res) => {\n const { name } = req.params;\n try {\n if (this._options.reload) {\n const { def } = this._handlers[name];\n await this._load(def, true);\n }\n\n res.statusCode = await this._invoke(name, req.body);\n res.end();\n } catch (err: any) {\n log.catch(err);\n res.statusCode = 500;\n res.end();\n }\n });\n\n this._port = await getPort({ port: 7200, portRange: [7200, 7299] });\n this._server = app.listen(this._port);\n\n try {\n // Register functions.\n const { registrationId, endpoint } = await this._client.services.services.FunctionRegistryService!.register({\n endpoint: this.endpoint,\n functions: this.functions.map(({ def: { name } }) => ({ name })),\n });\n\n log.info('registered', { registrationId, endpoint });\n this._registrationId = registrationId;\n this._proxy = endpoint;\n } catch (err: any) {\n await this.stop();\n throw new Error('FunctionRegistryService not available (check plugin is configured).');\n }\n }\n\n async stop() {\n const trigger = new Trigger();\n this._server?.close(async () => {\n if (this._registrationId) {\n await this._client.services.services.FunctionRegistryService!.unregister({\n registrationId: this._registrationId,\n });\n\n log.info('unregistered', { registrationId: this._registrationId });\n this._registrationId = undefined;\n this._proxy = undefined;\n }\n\n trigger.wake();\n });\n\n await trigger.wait();\n this._port = undefined;\n this._server = undefined;\n }\n\n /**\n * Load function.\n */\n private async _load(def: FunctionDef, flush = false) {\n const { id, name, handler } = def;\n const path = join(this._options.directory, handler);\n log.info('loading', { id });\n\n // Remove from cache.\n if (flush) {\n Object.keys(require.cache)\n .filter((key) => key.startsWith(path))\n .forEach((key) => delete require.cache[key]);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const module = require(path);\n if (typeof module.default !== 'function') {\n throw new Error(`Handler must export default function: ${id}`);\n }\n\n this._handlers[name] = { def, handler: module.default };\n }\n\n /**\n * Invoke function handler.\n */\n private async _invoke(name: string, event: any) {\n const seq = ++this._seq;\n const now = Date.now();\n\n log.info('req', { seq, name });\n const { handler } = this._handlers[name];\n\n const context: FunctionContext = {\n client: this._client,\n dataDir: this._options.dataDir,\n };\n\n let statusCode = 200;\n const response: Response = {\n status: (code: number) => {\n statusCode = code;\n return response;\n },\n };\n\n await handler({ context, event, response });\n log.info('res', { seq, name, statusCode, duration: Date.now() - now });\n\n return statusCode;\n }\n}\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { CronJob } from 'cron';\n\nimport { debounce, DeferredTask } from '@dxos/async';\nimport { type Client, type PublicKey } from '@dxos/client';\nimport { type Space, TextObject } from '@dxos/client/echo';\nimport { Context } from '@dxos/context';\nimport { Filter, createSubscription, type Query, subscribe } from '@dxos/echo-schema';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\nimport { ComplexMap } from '@dxos/util';\n\nimport { type FunctionDef, type FunctionManifest, type FunctionTrigger } from '../manifest';\n\ntype SchedulerOptions = {\n endpoint: string;\n};\n\n/**\n * Functions scheduler.\n */\n// TODO(burdon): Create tests.\nexport class Scheduler {\n // Map of mounted functions.\n private readonly _mounts = new ComplexMap<\n { id: string; spaceKey: PublicKey },\n { ctx: Context; trigger: FunctionTrigger }\n >(({ id, spaceKey }) => `${spaceKey.toHex()}:${id}`);\n\n constructor(\n private readonly _client: Client,\n private readonly _manifest: FunctionManifest,\n private readonly _options: SchedulerOptions,\n ) {}\n\n async start() {\n this._client.spaces.subscribe(async (spaces) => {\n for (const space of spaces) {\n await space.waitUntilReady();\n for (const trigger of this._manifest.triggers ?? []) {\n await this.mount(new Context(), space, trigger);\n }\n }\n });\n }\n\n async stop() {\n for (const { id, spaceKey } of this._mounts.keys()) {\n await this.unmount(id, spaceKey);\n }\n }\n\n private async mount(ctx: Context, space: Space, trigger: FunctionTrigger) {\n const key = { id: trigger.function, spaceKey: space.key };\n const def = this._manifest.functions.find((config) => config.id === trigger.function);\n invariant(def, `Function not found: ${trigger.function}`);\n\n const exists = this._mounts.get(key);\n if (!exists) {\n this._mounts.set(key, { ctx, trigger });\n log('mount', { space: space.key, trigger });\n if (ctx.disposed) {\n return;\n }\n\n // Cron schedule.\n if (trigger.schedule) {\n const task = new DeferredTask(ctx, async () => {\n await this.execFunction(def, {\n space: space.key,\n });\n });\n\n // TODO(burdon): Check greater than 30s min (use cron-parser).\n const job = new CronJob(trigger.schedule, () => task.schedule());\n\n job.start();\n ctx.onDispose(() => job.stop());\n }\n\n // ECHO subscription.\n if (trigger.subscription) {\n const objectIds = new Set<string>();\n const task = new DeferredTask(ctx, async () => {\n await this.execFunction(def, {\n space: space.key,\n objects: Array.from(objectIds),\n });\n });\n\n // TODO(burdon): Standardize subscription handles.\n const subscriptions: (() => void)[] = [];\n const subscription = createSubscription(({ added, updated }) => {\n for (const object of added) {\n objectIds.add(object.id);\n }\n for (const object of updated) {\n objectIds.add(object.id);\n }\n\n task.schedule();\n });\n subscriptions.push(() => subscription.unsubscribe());\n\n const { type, props, deep, delay } = trigger.subscription;\n const update = ({ objects }: Query) => {\n subscription.update(objects);\n\n // TODO(burdon): Hack to monitor changes to Document's text object.\n if (deep) {\n log.info('update', { type, deep, objects: objects.length });\n for (const object of objects) {\n const content = object.content;\n if (content instanceof TextObject) {\n subscriptions.push(content[subscribe](debounce(() => subscription.update([object]), 1_000)));\n }\n }\n }\n };\n\n // TODO(burdon): [Bug]: all callbacks are fired on the first mutation.\n // TODO(burdon): [Bug]: not updated when document is deleted (either top or hierarchically).\n const query = space.db.query(Filter.typename(type, props));\n subscriptions.push(query.subscribe(delay ? debounce(update, delay * 1_000) : update));\n\n ctx.onDispose(() => {\n subscriptions.forEach((unsubscribe) => unsubscribe());\n });\n }\n }\n }\n\n private async unmount(id: string, spaceKey: PublicKey) {\n const key = { id, spaceKey };\n const { ctx } = this._mounts.get(key) ?? {};\n if (ctx) {\n this._mounts.delete(key);\n await ctx.dispose();\n }\n }\n\n private async execFunction(def: FunctionDef, data: any) {\n try {\n log('request', { function: def.id });\n const response = await fetch(`${this._options.endpoint}/${def.name}`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(data),\n });\n\n // const result = await response.json();\n log('result', { function: def.id, result: response.status });\n } catch (err: any) {\n log.error('error', { function: def.id, error: err.message });\n }\n }\n}\n"],
|
|
5
|
-
"mappings": "
|
|
6
|
-
"names": ["import_async", "import_invariant", "import_log", "DevServer", "constructor", "_client", "_options", "_handlers", "_seq", "endpoint", "invariant", "_port", "proxy", "_proxy", "functions", "Object", "values", "initialize", "def", "manifest", "_load", "err", "log", "error", "start", "app", "express", "use", "json", "post", "req", "res", "name", "params", "reload", "statusCode", "_invoke", "body", "end", "catch", "getPort", "port", "portRange", "_server", "listen", "registrationId", "services", "FunctionRegistryService", "register", "
|
|
3
|
+
"sources": ["../../../src/handler.ts", "../../../src/runtime/dev-server.ts", "../../../src/runtime/scheduler.ts"],
|
|
4
|
+
"sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport { type Client, PublicKey } from '@dxos/client';\nimport { type Space } from '@dxos/client/echo';\nimport { isTypedObject, type TypedObject } from '@dxos/echo-schema';\nimport { nonNullable } from '@dxos/util';\n\n// TODO(burdon): No response?\nexport interface Response {\n status(code: number): Response;\n}\n\n// TODO(burdon): Limit access to individual space?\nexport interface FunctionContext {\n client: Client;\n dataDir?: string;\n}\n\n// TODO(burdon): Model after http request. Ref Lambda/OpenFaaS.\n// https://docs.aws.amazon.com/lambda/latest/dg/typescript-handler.html\nexport type FunctionHandler<T extends {}> = (params: {\n event: T;\n context: FunctionContext;\n response: Response;\n}) => Promise<Response | void>;\n\nexport type FunctionSubscriptionEvent = {\n space?: string; // TODO(burdon): Convert to PublicKey.\n objects?: string[];\n};\n\nexport type FunctionSubscriptionEvent2 = {\n space?: Space;\n objects?: TypedObject[];\n};\n\nexport const subscriptionHandler = (\n handler: FunctionHandler<FunctionSubscriptionEvent2>,\n): FunctionHandler<FunctionSubscriptionEvent> => {\n return ({ event, context, ...rest }) => {\n const { client } = context;\n const space = event.space ? client.spaces.get(PublicKey.from(event.space)) : undefined;\n const objects =\n space &&\n event.objects\n ?.map<TypedObject | undefined>((id) => space!.db.getObjectById(id))\n .filter(nonNullable)\n .filter(isTypedObject);\n\n return handler({ event: { space, objects }, context, ...rest });\n };\n};\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport express from 'express';\nimport { getPort } from 'get-port-please';\nimport type http from 'http';\nimport { join } from 'node:path';\n\nimport { Trigger } from '@dxos/async';\nimport { type Client } from '@dxos/client';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\n\nimport { type FunctionContext, type FunctionHandler, type Response } from '../handler';\nimport { type FunctionDef, type FunctionManifest } from '../manifest';\n\nexport type DevServerOptions = {\n port?: number;\n directory: string;\n manifest: FunctionManifest;\n reload?: boolean;\n dataDir?: string;\n};\n\n/**\n * Functions dev server provides a local HTTP server for testing functions.\n */\nexport class DevServer {\n // Function handlers indexed by name (URL path).\n private readonly _handlers: Record<string, { def: FunctionDef; handler: FunctionHandler<any> }> = {};\n\n private _server?: http.Server;\n private _port?: number;\n private _registrationId?: string;\n private _proxy?: string;\n private _seq = 0;\n\n // prettier-ignore\n constructor(\n private readonly _client: Client,\n private readonly _options: DevServerOptions,\n ) {}\n\n get endpoint() {\n invariant(this._port);\n return `http://localhost:${this._port}`;\n }\n\n get proxy() {\n return this._proxy;\n }\n\n get functions() {\n return Object.values(this._handlers);\n }\n\n async initialize() {\n for (const def of this._options.manifest.functions) {\n try {\n await this._load(def);\n } catch (err) {\n log.error('parsing function (check manifest)', err);\n }\n }\n }\n\n async start() {\n const app = express();\n app.use(express.json());\n\n app.post('/:name', async (req, res) => {\n const { name } = req.params;\n try {\n if (this._options.reload) {\n const { def } = this._handlers[name];\n await this._load(def, true);\n }\n\n res.statusCode = await this._invoke(name, req.body);\n res.end();\n } catch (err: any) {\n log.catch(err);\n res.statusCode = 500;\n res.end();\n }\n });\n\n this._port = await getPort({ host: 'localhost', port: 7200, portRange: [7200, 7299] });\n this._server = app.listen(this._port);\n\n try {\n // Register functions.\n const { registrationId, endpoint } = await this._client.services.services.FunctionRegistryService!.register({\n endpoint: this.endpoint,\n functions: this.functions.map(({ def: { name } }) => ({ name })),\n });\n\n log.info('registered', { registrationId, endpoint });\n this._registrationId = registrationId;\n this._proxy = endpoint;\n } catch (err: any) {\n await this.stop();\n throw new Error('FunctionRegistryService not available (check plugin is configured).');\n }\n }\n\n async stop() {\n const trigger = new Trigger();\n this._server?.close(async () => {\n if (this._registrationId) {\n await this._client.services.services.FunctionRegistryService!.unregister({\n registrationId: this._registrationId,\n });\n\n log.info('unregistered', { registrationId: this._registrationId });\n this._registrationId = undefined;\n this._proxy = undefined;\n }\n\n trigger.wake();\n });\n\n await trigger.wait();\n this._port = undefined;\n this._server = undefined;\n }\n\n /**\n * Load function.\n */\n private async _load(def: FunctionDef, flush = false) {\n const { id, name, handler } = def;\n const path = join(this._options.directory, handler);\n log.info('loading', { id });\n\n // Remove from cache.\n if (flush) {\n Object.keys(require.cache)\n .filter((key) => key.startsWith(path))\n .forEach((key) => delete require.cache[key]);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const module = require(path);\n if (typeof module.default !== 'function') {\n throw new Error(`Handler must export default function: ${id}`);\n }\n\n this._handlers[name] = { def, handler: module.default };\n }\n\n /**\n * Invoke function handler.\n */\n private async _invoke(name: string, event: any) {\n const seq = ++this._seq;\n const now = Date.now();\n\n log.info('req', { seq, name });\n const { handler } = this._handlers[name];\n\n const context: FunctionContext = {\n client: this._client,\n dataDir: this._options.dataDir,\n };\n\n let statusCode = 200;\n const response: Response = {\n status: (code: number) => {\n statusCode = code;\n return response;\n },\n };\n\n await handler({ context, event, response });\n log.info('res', { seq, name, statusCode, duration: Date.now() - now });\n\n return statusCode;\n }\n}\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { CronJob } from 'cron';\n\nimport { debounce, DeferredTask } from '@dxos/async';\nimport { type Client, type PublicKey } from '@dxos/client';\nimport { type Space, TextObject } from '@dxos/client/echo';\nimport { Context } from '@dxos/context';\nimport { Filter, createSubscription, type Query, subscribe } from '@dxos/echo-schema';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\nimport { ComplexMap } from '@dxos/util';\n\nimport { type FunctionSubscriptionEvent } from '../handler';\nimport { type FunctionDef, type FunctionManifest, type FunctionTrigger, type TriggerSubscription } from '../manifest';\n\ntype Callback = (data: FunctionSubscriptionEvent) => Promise<number>;\n\ntype SchedulerOptions = {\n endpoint?: string;\n callback?: Callback;\n};\n\n/**\n * Functions scheduler.\n */\n// TODO(burdon): Create tests.\nexport class Scheduler {\n // Map of mounted functions.\n private readonly _mounts = new ComplexMap<\n { id: string; spaceKey: PublicKey },\n { ctx: Context; trigger: FunctionTrigger }\n >(({ id, spaceKey }) => `${spaceKey.toHex()}:${id}`);\n\n constructor(\n private readonly _client: Client,\n private readonly _manifest: FunctionManifest,\n private readonly _options: SchedulerOptions = {},\n ) {}\n\n async start() {\n this._client.spaces.subscribe(async (spaces) => {\n for (const space of spaces) {\n await space.waitUntilReady();\n for (const trigger of this._manifest.triggers ?? []) {\n await this.mount(new Context(), space, trigger);\n }\n }\n });\n }\n\n async stop() {\n for (const { id, spaceKey } of this._mounts.keys()) {\n await this.unmount(id, spaceKey);\n }\n }\n\n private async mount(ctx: Context, space: Space, trigger: FunctionTrigger) {\n const key = { id: trigger.function, spaceKey: space.key };\n const def = this._manifest.functions.find((config) => config.id === trigger.function);\n invariant(def, `Function not found: ${trigger.function}`);\n\n // Currently supports only one trigger declaration per function.\n const exists = this._mounts.get(key);\n if (!exists) {\n this._mounts.set(key, { ctx, trigger });\n log('mount', { space: space.key, trigger });\n if (ctx.disposed) {\n return;\n }\n\n // Timer.\n if (trigger.schedule) {\n this._createTimer(ctx, space, def, trigger);\n }\n\n // Subscription.\n for (const triggerSubscription of trigger.subscriptions ?? []) {\n this._createSubscription(ctx, space, def, triggerSubscription);\n }\n }\n }\n\n private async unmount(id: string, spaceKey: PublicKey) {\n const key = { id, spaceKey };\n const { ctx } = this._mounts.get(key) ?? {};\n if (ctx) {\n this._mounts.delete(key);\n await ctx.dispose();\n }\n }\n\n private _createTimer(ctx: Context, space: Space, def: FunctionDef, trigger: FunctionTrigger) {\n const task = new DeferredTask(ctx, async () => {\n await this._execFunction(def, {\n space: space.key,\n });\n });\n\n // TODO(burdon): Check greater than 30s min (use cron-parser).\n invariant(trigger.schedule);\n const job = new CronJob(trigger.schedule, () => task.schedule());\n\n job.start();\n ctx.onDispose(() => job.stop());\n }\n\n private _createSubscription(ctx: Context, space: Space, def: FunctionDef, triggerSubscription: TriggerSubscription) {\n const objectIds = new Set<string>();\n const task = new DeferredTask(ctx, async () => {\n await this._execFunction(def, {\n space: space.key,\n objects: Array.from(objectIds),\n });\n });\n\n // TODO(burdon): Standardize subscription handles.\n const subscriptions: (() => void)[] = [];\n const subscription = createSubscription(({ added, updated }) => {\n for (const object of added) {\n objectIds.add(object.id);\n }\n for (const object of updated) {\n objectIds.add(object.id);\n }\n\n task.schedule();\n });\n subscriptions.push(() => subscription.unsubscribe());\n\n const { type, props, deep, delay } = triggerSubscription;\n const update = ({ objects }: Query) => {\n subscription.update(objects);\n\n // TODO(burdon): Hack to monitor changes to Document's text object.\n if (deep) {\n log.info('update', { type, deep, objects: objects.length });\n for (const object of objects) {\n const content = object.content;\n if (content instanceof TextObject) {\n subscriptions.push(content[subscribe](debounce(() => subscription.update([object]), 1_000)));\n }\n }\n }\n };\n\n // TODO(burdon): [Bug]: all callbacks are fired on the first mutation.\n // TODO(burdon): [Bug]: not updated when document is deleted (either top or hierarchically).\n const query = space.db.query(Filter.typename(type, props));\n subscriptions.push(query.subscribe(delay ? debounce(update, delay * 1_000) : update));\n\n ctx.onDispose(() => {\n subscriptions.forEach((unsubscribe) => unsubscribe());\n });\n }\n\n private async _execFunction(def: FunctionDef, data: any) {\n try {\n log('request', { function: def.id });\n const { endpoint, callback } = this._options;\n let status = 0;\n if (endpoint) {\n // TODO(burdon): Move out of scheduler (generalize as callback).\n const response = await fetch(`${this._options.endpoint}/${def.name}`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(data),\n });\n\n status = response.status;\n } else if (callback) {\n status = await callback(data);\n }\n\n // const result = await response.json();\n log('result', { function: def.id, result: status });\n } catch (err: any) {\n log.error('error', { function: def.id, error: err.message });\n }\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,oBAAuC;AAEvC,yBAAgD;AAChD,kBAA4B;ACH5B,qBAAoB;AACpB,6BAAwB;AAExB,uBAAqB;AAErB,mBAAwB;AAExB,uBAA0B;AAC1B,iBAAoB;ACRpB,kBAAwB;AAExB,IAAAA,gBAAuC;AAEvC,kBAAuC;AACvC,qBAAwB;AACxB,IAAAC,sBAAkE;AAClE,IAAAC,oBAA0B;AAC1B,IAAAC,cAAoB;AACpB,IAAAC,eAA2B;;;;;;;;AFyBpB,IAAMC,sBAAsB,CACjCC,YAAAA;AAEA,SAAO,CAAC,EAAEC,OAAOC,SAAS,GAAGC,KAAAA,MAAM;AACjC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AI;UACpE0G,QAAQ;UACRC,SAAS;YACP,gBAAgB;UAClB;UACAtG,MAAMuG,KAAKC,UAAUN,IAAAA;QACvB,CAAA;AAEA1D,iBAASD,SAASC;MACpB,WAAW2D,UAAU;AACnB3D,iBAAS,MAAM2D,SAASD,IAAAA;MAC1B;AAGAjH,sBAAAA,KAAI,UAAU;QAAEuE,UAAU3E,IAAIrB;QAAIiJ,QAAQjE;MAAO,GAAA;;;;;;IACnD,SAASxD,KAAU;AACjBC,kBAAAA,IAAIC,MAAM,SAAS;QAAEsE,UAAU3E,IAAIrB;QAAI0B,OAAOF,IAAI0H;MAAQ,GAAA;;;;;;IAC5D;EACF;AACF;",
|
|
6
|
+
"names": ["import_async", "import_echo_schema", "import_invariant", "import_log", "import_util", "subscriptionHandler", "handler", "event", "context", "rest", "client", "space", "spaces", "get", "PublicKey", "from", "undefined", "objects", "map", "id", "db", "getObjectById", "filter", "nonNullable", "isTypedObject", "DevServer", "constructor", "_client", "_options", "_handlers", "_seq", "endpoint", "invariant", "_port", "proxy", "_proxy", "functions", "Object", "values", "initialize", "def", "manifest", "_load", "err", "log", "error", "start", "app", "express", "use", "json", "post", "req", "res", "name", "params", "reload", "statusCode", "_invoke", "body", "end", "catch", "getPort", "host", "port", "portRange", "_server", "listen", "registrationId", "services", "FunctionRegistryService", "register", "info", "_registrationId", "stop", "Error", "trigger", "Trigger", "close", "unregister", "wake", "wait", "flush", "path", "join", "directory", "keys", "require", "cache", "key", "startsWith", "forEach", "module", "default", "seq", "now", "Date", "dataDir", "response", "status", "code", "duration", "Scheduler", "_manifest", "_mounts", "ComplexMap", "spaceKey", "toHex", "subscribe", "waitUntilReady", "triggers", "mount", "Context", "unmount", "ctx", "function", "find", "config", "exists", "set", "disposed", "schedule", "_createTimer", "triggerSubscription", "subscriptions", "_createSubscription", "delete", "dispose", "task", "DeferredTask", "_execFunction", "job", "CronJob", "onDispose", "objectIds", "Set", "Array", "subscription", "createSubscription", "added", "updated", "object", "add", "push", "unsubscribe", "type", "props", "deep", "delay", "update", "length", "content", "TextObject", "debounce", "query", "Filter", "typename", "data", "callback", "fetch", "method", "headers", "JSON", "stringify", "result", "message"]
|
|
7
7
|
}
|
package/dist/lib/node/meta.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"inputs":{"packages/core/functions/src/handler.ts":{"bytes":
|
|
1
|
+
{"inputs":{"packages/core/functions/src/handler.ts":{"bytes":4072,"imports":[{"path":"@dxos/client","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/manifest.ts":{"bytes":1863,"imports":[],"format":"esm"},"packages/core/functions/src/runtime/dev-server.ts":{"bytes":18840,"imports":[{"path":"express","kind":"import-statement","external":true},{"path":"get-port-please","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"<runtime>","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/runtime/scheduler.ts":{"bytes":22471,"imports":[{"path":"cron","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/client/echo","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}],"format":"esm"},"packages/core/functions/src/runtime/index.ts":{"bytes":566,"imports":[{"path":"packages/core/functions/src/runtime/dev-server.ts","kind":"import-statement","original":"./dev-server"},{"path":"packages/core/functions/src/runtime/scheduler.ts","kind":"import-statement","original":"./scheduler"}],"format":"esm"},"packages/core/functions/src/index.ts":{"bytes":637,"imports":[{"path":"packages/core/functions/src/handler.ts","kind":"import-statement","original":"./handler"},{"path":"packages/core/functions/src/manifest.ts","kind":"import-statement","original":"./manifest"},{"path":"packages/core/functions/src/runtime/index.ts","kind":"import-statement","original":"./runtime"}],"format":"esm"}},"outputs":{"packages/core/functions/dist/lib/node/index.cjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":21909},"packages/core/functions/dist/lib/node/index.cjs":{"imports":[{"path":"@dxos/client","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true},{"path":"express","kind":"import-statement","external":true},{"path":"get-port-please","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"cron","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/client/echo","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}],"exports":["DevServer","Scheduler","subscriptionHandler"],"entryPoint":"packages/core/functions/src/index.ts","inputs":{"packages/core/functions/src/handler.ts":{"bytesInOutput":589},"packages/core/functions/src/index.ts":{"bytesInOutput":0},"packages/core/functions/src/runtime/dev-server.ts":{"bytesInOutput":4792},"packages/core/functions/src/runtime/index.ts":{"bytesInOutput":0},"packages/core/functions/src/runtime/scheduler.ts":{"bytesInOutput":5475}},"bytes":11470}}}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { type Client } from '@dxos/client';
|
|
2
|
+
import { type Space } from '@dxos/client/echo';
|
|
3
|
+
import { type TypedObject } from '@dxos/echo-schema';
|
|
2
4
|
export interface Response {
|
|
3
5
|
status(code: number): Response;
|
|
4
6
|
}
|
|
@@ -12,7 +14,12 @@ export type FunctionHandler<T extends {}> = (params: {
|
|
|
12
14
|
response: Response;
|
|
13
15
|
}) => Promise<Response | void>;
|
|
14
16
|
export type FunctionSubscriptionEvent = {
|
|
15
|
-
space
|
|
16
|
-
objects
|
|
17
|
+
space?: string;
|
|
18
|
+
objects?: string[];
|
|
17
19
|
};
|
|
20
|
+
export type FunctionSubscriptionEvent2 = {
|
|
21
|
+
space?: Space;
|
|
22
|
+
objects?: TypedObject[];
|
|
23
|
+
};
|
|
24
|
+
export declare const subscriptionHandler: (handler: FunctionHandler<FunctionSubscriptionEvent2>) => FunctionHandler<FunctionSubscriptionEvent>;
|
|
18
25
|
//# sourceMappingURL=handler.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handler.d.ts","sourceRoot":"","sources":["../../../src/handler.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,KAAK,MAAM,
|
|
1
|
+
{"version":3,"file":"handler.d.ts","sourceRoot":"","sources":["../../../src/handler.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,KAAK,MAAM,EAAa,MAAM,cAAc,CAAC;AACtD,OAAO,EAAE,KAAK,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAAiB,KAAK,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAIpE,MAAM,WAAW,QAAQ;IACvB,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,QAAQ,CAAC;CAChC;AAGD,MAAM,WAAW,eAAe;IAC9B,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAID,MAAM,MAAM,eAAe,CAAC,CAAC,SAAS,EAAE,IAAI,CAAC,MAAM,EAAE;IACnD,KAAK,EAAE,CAAC,CAAC;IACT,OAAO,EAAE,eAAe,CAAC;IACzB,QAAQ,EAAE,QAAQ,CAAC;CACpB,KAAK,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,CAAC;AAE/B,MAAM,MAAM,yBAAyB,GAAG;IACtC,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;CACpB,CAAC;AAEF,MAAM,MAAM,0BAA0B,GAAG;IACvC,KAAK,CAAC,EAAE,KAAK,CAAC;IACd,OAAO,CAAC,EAAE,WAAW,EAAE,CAAC;CACzB,CAAC;AAEF,eAAO,MAAM,mBAAmB,YACrB,gBAAgB,0BAA0B,CAAC,KACnD,gBAAgB,yBAAyB,CAa3C,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manifest.d.ts","sourceRoot":"","sources":["../../../src/manifest.ts"],"names":[],"mappings":"AAOA,MAAM,MAAM,WAAW,GAAG;IAExB,EAAE,EAAE,MAAM,CAAC;IAEX,IAAI,EAAE,MAAM,CAAC;IAEb,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB,CAAC;AAGF,MAAM,MAAM,mBAAmB,GAAG;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAC5B,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB,CAAC;AAKF,MAAM,MAAM,eAAe,GAAG;IAC5B,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,
|
|
1
|
+
{"version":3,"file":"manifest.d.ts","sourceRoot":"","sources":["../../../src/manifest.ts"],"names":[],"mappings":"AAOA,MAAM,MAAM,WAAW,GAAG;IAExB,EAAE,EAAE,MAAM,CAAC;IAEX,IAAI,EAAE,MAAM,CAAC;IAEb,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB,CAAC;AAGF,MAAM,MAAM,mBAAmB,GAAG;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAC5B,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB,CAAC;AAKF,MAAM,MAAM,eAAe,GAAG;IAC5B,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,aAAa,CAAC,EAAE,mBAAmB,EAAE,CAAC;CACvC,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,gBAAgB,GAAG;IAC7B,SAAS,EAAE,WAAW,EAAE,CAAC;IACzB,QAAQ,EAAE,eAAe,EAAE,CAAC;CAC7B,CAAC"}
|
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
import { type Client } from '@dxos/client';
|
|
2
|
+
import { type FunctionSubscriptionEvent } from '../handler';
|
|
2
3
|
import { type FunctionManifest } from '../manifest';
|
|
4
|
+
type Callback = (data: FunctionSubscriptionEvent) => Promise<number>;
|
|
3
5
|
type SchedulerOptions = {
|
|
4
|
-
endpoint
|
|
6
|
+
endpoint?: string;
|
|
7
|
+
callback?: Callback;
|
|
5
8
|
};
|
|
6
9
|
/**
|
|
7
10
|
* Functions scheduler.
|
|
@@ -11,12 +14,14 @@ export declare class Scheduler {
|
|
|
11
14
|
private readonly _manifest;
|
|
12
15
|
private readonly _options;
|
|
13
16
|
private readonly _mounts;
|
|
14
|
-
constructor(_client: Client, _manifest: FunctionManifest, _options
|
|
17
|
+
constructor(_client: Client, _manifest: FunctionManifest, _options?: SchedulerOptions);
|
|
15
18
|
start(): Promise<void>;
|
|
16
19
|
stop(): Promise<void>;
|
|
17
20
|
private mount;
|
|
18
21
|
private unmount;
|
|
19
|
-
private
|
|
22
|
+
private _createTimer;
|
|
23
|
+
private _createSubscription;
|
|
24
|
+
private _execFunction;
|
|
20
25
|
}
|
|
21
26
|
export {};
|
|
22
27
|
//# sourceMappingURL=scheduler.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scheduler.d.ts","sourceRoot":"","sources":["../../../../src/runtime/scheduler.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,KAAK,MAAM,EAAkB,MAAM,cAAc,CAAC;AAQ3D,OAAO,EAAoB,KAAK,gBAAgB,
|
|
1
|
+
{"version":3,"file":"scheduler.d.ts","sourceRoot":"","sources":["../../../../src/runtime/scheduler.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,KAAK,MAAM,EAAkB,MAAM,cAAc,CAAC;AAQ3D,OAAO,EAAE,KAAK,yBAAyB,EAAE,MAAM,YAAY,CAAC;AAC5D,OAAO,EAAoB,KAAK,gBAAgB,EAAkD,MAAM,aAAa,CAAC;AAEtH,KAAK,QAAQ,GAAG,CAAC,IAAI,EAAE,yBAAyB,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;AAErE,KAAK,gBAAgB,GAAG;IACtB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,QAAQ,CAAC;CACrB,CAAC;AAEF;;GAEG;AAEH,qBAAa,SAAS;IAQlB,OAAO,CAAC,QAAQ,CAAC,OAAO;IACxB,OAAO,CAAC,QAAQ,CAAC,SAAS;IAC1B,OAAO,CAAC,QAAQ,CAAC,QAAQ;IAR3B,OAAO,CAAC,QAAQ,CAAC,OAAO,CAG6B;gBAGlC,OAAO,EAAE,MAAM,EACf,SAAS,EAAE,gBAAgB,EAC3B,QAAQ,GAAE,gBAAqB;IAG5C,KAAK;IAWL,IAAI;YAMI,KAAK;YA0BL,OAAO;IASrB,OAAO,CAAC,YAAY;IAepB,OAAO,CAAC,mBAAmB;YAiDb,aAAa;CA0B5B"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scheduler.test.d.ts","sourceRoot":"","sources":["../../../../src/runtime/scheduler.test.ts"],"names":[],"mappings":""}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dxos/functions",
|
|
3
|
-
"version": "0.3.9-main.
|
|
3
|
+
"version": "0.3.9-main.4e39f3a",
|
|
4
4
|
"description": "Functions SDK and runtime.",
|
|
5
5
|
"homepage": "https://dxos.org",
|
|
6
6
|
"bugs": "https://github.com/dxos/dxos/issues",
|
|
@@ -24,14 +24,14 @@
|
|
|
24
24
|
"deepsignal": "1.4.0-shallow.0",
|
|
25
25
|
"express": "^4.17.1",
|
|
26
26
|
"get-port-please": "^3.1.1",
|
|
27
|
-
"@dxos/async": "0.3.9-main.
|
|
28
|
-
"@dxos/
|
|
29
|
-
"@dxos/
|
|
30
|
-
"@dxos/echo-schema": "0.3.9-main.
|
|
31
|
-
"@dxos/invariant": "0.3.9-main.
|
|
32
|
-
"@dxos/node-std": "0.3.9-main.
|
|
33
|
-
"@dxos/util": "0.3.9-main.
|
|
34
|
-
"@dxos/log": "0.3.9-main.
|
|
27
|
+
"@dxos/async": "0.3.9-main.4e39f3a",
|
|
28
|
+
"@dxos/client": "0.3.9-main.4e39f3a",
|
|
29
|
+
"@dxos/context": "0.3.9-main.4e39f3a",
|
|
30
|
+
"@dxos/echo-schema": "0.3.9-main.4e39f3a",
|
|
31
|
+
"@dxos/invariant": "0.3.9-main.4e39f3a",
|
|
32
|
+
"@dxos/node-std": "0.3.9-main.4e39f3a",
|
|
33
|
+
"@dxos/util": "0.3.9-main.4e39f3a",
|
|
34
|
+
"@dxos/log": "0.3.9-main.4e39f3a"
|
|
35
35
|
},
|
|
36
36
|
"devDependencies": {
|
|
37
37
|
"@types/express": "^4.17.17"
|
package/src/handler.ts
CHANGED
|
@@ -2,7 +2,10 @@
|
|
|
2
2
|
// Copyright 2023 DXOS.org
|
|
3
3
|
//
|
|
4
4
|
|
|
5
|
-
import { type Client } from '@dxos/client';
|
|
5
|
+
import { type Client, PublicKey } from '@dxos/client';
|
|
6
|
+
import { type Space } from '@dxos/client/echo';
|
|
7
|
+
import { isTypedObject, type TypedObject } from '@dxos/echo-schema';
|
|
8
|
+
import { nonNullable } from '@dxos/util';
|
|
6
9
|
|
|
7
10
|
// TODO(burdon): No response?
|
|
8
11
|
export interface Response {
|
|
@@ -24,6 +27,28 @@ export type FunctionHandler<T extends {}> = (params: {
|
|
|
24
27
|
}) => Promise<Response | void>;
|
|
25
28
|
|
|
26
29
|
export type FunctionSubscriptionEvent = {
|
|
27
|
-
space
|
|
28
|
-
objects
|
|
30
|
+
space?: string; // TODO(burdon): Convert to PublicKey.
|
|
31
|
+
objects?: string[];
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
export type FunctionSubscriptionEvent2 = {
|
|
35
|
+
space?: Space;
|
|
36
|
+
objects?: TypedObject[];
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
export const subscriptionHandler = (
|
|
40
|
+
handler: FunctionHandler<FunctionSubscriptionEvent2>,
|
|
41
|
+
): FunctionHandler<FunctionSubscriptionEvent> => {
|
|
42
|
+
return ({ event, context, ...rest }) => {
|
|
43
|
+
const { client } = context;
|
|
44
|
+
const space = event.space ? client.spaces.get(PublicKey.from(event.space)) : undefined;
|
|
45
|
+
const objects =
|
|
46
|
+
space &&
|
|
47
|
+
event.objects
|
|
48
|
+
?.map<TypedObject | undefined>((id) => space!.db.getObjectById(id))
|
|
49
|
+
.filter(nonNullable)
|
|
50
|
+
.filter(isTypedObject);
|
|
51
|
+
|
|
52
|
+
return handler({ event: { space, objects }, context, ...rest });
|
|
53
|
+
};
|
|
29
54
|
};
|
package/src/manifest.ts
CHANGED
|
@@ -20,7 +20,7 @@ export type TriggerSubscription = {
|
|
|
20
20
|
type: string;
|
|
21
21
|
spaceKey: string;
|
|
22
22
|
props?: Record<string, any>;
|
|
23
|
-
deep?: boolean;
|
|
23
|
+
deep?: boolean; // Watch changes to object (not just creation).
|
|
24
24
|
delay?: number;
|
|
25
25
|
};
|
|
26
26
|
|
|
@@ -30,7 +30,7 @@ export type TriggerSubscription = {
|
|
|
30
30
|
export type FunctionTrigger = {
|
|
31
31
|
function: string;
|
|
32
32
|
schedule?: string;
|
|
33
|
-
|
|
33
|
+
subscriptions?: TriggerSubscription[];
|
|
34
34
|
};
|
|
35
35
|
|
|
36
36
|
/**
|