@dxos/functions 0.1.52 → 0.1.53-main.00be1a9

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.
@@ -30,96 +30,275 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // packages/core/functions/src/index.ts
31
31
  var src_exports = {};
32
32
  __export(src_exports, {
33
- runFunctions: () => runFunctions
33
+ DevServer: () => DevServer,
34
+ TriggerManager: () => TriggerManager
34
35
  });
35
36
  module.exports = __toCommonJS(src_exports);
36
37
 
37
- // packages/core/functions/src/runtime/index.ts
38
+ // packages/core/functions/src/runtime/dev-server.ts
38
39
  var import_express = __toESM(require("express"));
39
- var import_promises = require("node:fs/promises");
40
40
  var import_node_path = require("node:path");
41
41
  var import_portfinder = require("portfinder");
42
+ var import_async = require("@dxos/async");
42
43
  var import_log = require("@dxos/log");
43
- var FUNCTION_EXTENSIONS = [
44
- ".js",
45
- ".ts"
46
- ];
47
- var runFunctions = async (options) => {
48
- const files = await (0, import_promises.readdir)(options.functionsDirectory);
49
- const functionHandlers = {};
50
- for (const file of files) {
51
- if (!FUNCTION_EXTENSIONS.some((ext) => (0, import_node_path.extname)(file) === ext)) {
52
- continue;
53
- }
54
- try {
55
- const module2 = require((0, import_node_path.join)(options.functionsDirectory, file));
56
- const handler = module2.default;
57
- if (typeof handler !== "function") {
58
- throw new Error(`Function ${file} does not export a default function`);
44
+ var __dxlog_file = "/home/runner/work/dxos/dxos/packages/core/functions/src/runtime/dev-server.ts";
45
+ var DEFAULT_PORT = 7e3;
46
+ var DevServer = class {
47
+ // prettier-ignore
48
+ constructor(_client, _options) {
49
+ this._client = _client;
50
+ this._options = _options;
51
+ this._functionHandlers = {};
52
+ }
53
+ get port() {
54
+ return this._port;
55
+ }
56
+ get endpoint() {
57
+ return this._port ? `http://localhost:${this._port}` : void 0;
58
+ }
59
+ get functions() {
60
+ return Object.keys(this._functionHandlers);
61
+ }
62
+ async initialize() {
63
+ for (const [name, _] of Object.entries(this._options.manifest.functions)) {
64
+ try {
65
+ const module2 = require((0, import_node_path.join)(this._options.directory, name));
66
+ const handler = module2.default;
67
+ if (typeof handler !== "function") {
68
+ throw new Error(`Handler must export default function: ${name}`);
69
+ }
70
+ this._functionHandlers[name] = handler;
71
+ } catch (err) {
72
+ import_log.log.error("parsing function (check functions.yml manifest)", err, {
73
+ F: __dxlog_file,
74
+ L: 63,
75
+ S: this,
76
+ C: (f, a) => f(...a)
77
+ });
59
78
  }
60
- const functionName = file.slice(0, -(0, import_node_path.extname)(file).length);
61
- functionHandlers[functionName] = handler;
62
- } catch (e) {
63
- console.error(e);
64
79
  }
65
80
  }
66
- const port = await (0, import_portfinder.getPortPromise)({
67
- startPort: 7e3
68
- });
69
- const app = (0, import_express.default)();
70
- app.use(import_express.default.json());
71
- app.post("/:functionName", async (req, res) => {
72
- const functionName = req.params.functionName;
73
- const replyBuilder = {
74
- status: (code) => {
75
- res.statusCode = code;
76
- return replyBuilder;
77
- },
78
- succeed: (result) => {
79
- res.end(JSON.stringify(result));
80
- return replyBuilder;
81
+ async start() {
82
+ const app = (0, import_express.default)();
83
+ app.use(import_express.default.json());
84
+ app.post("/:functionName", async (req, res) => {
85
+ const functionName = req.params.functionName;
86
+ (0, import_log.log)("invoke", {
87
+ function: functionName,
88
+ data: req.body
89
+ }, {
90
+ F: __dxlog_file,
91
+ L: 74,
92
+ S: this,
93
+ C: (f, a) => f(...a)
94
+ });
95
+ const builder = {
96
+ status: (code) => {
97
+ res.statusCode = code;
98
+ return builder;
99
+ },
100
+ succeed: (result = {}) => {
101
+ res.end(JSON.stringify(result));
102
+ return builder;
103
+ }
104
+ };
105
+ const context = {
106
+ client: this._client,
107
+ status: builder.status.bind(builder)
108
+ };
109
+ void (async () => {
110
+ try {
111
+ await this._functionHandlers[functionName](req.body, context);
112
+ } catch (err) {
113
+ res.statusCode = 500;
114
+ res.end(err.message);
115
+ }
116
+ })();
117
+ });
118
+ this._port = await (0, import_portfinder.getPortPromise)({
119
+ startPort: DEFAULT_PORT
120
+ });
121
+ this._server = app.listen(this._port);
122
+ const { registrationId } = await this._client.services.services.FunctionRegistryService.register({
123
+ endpoint: this.endpoint,
124
+ functions: this.functions.map((name) => ({
125
+ name
126
+ }))
127
+ });
128
+ this._registrationId = registrationId;
129
+ }
130
+ async stop() {
131
+ var _a;
132
+ const trigger = new import_async.Trigger();
133
+ (_a = this._server) == null ? void 0 : _a.close(async () => {
134
+ if (this._registrationId) {
135
+ await this._client.services.services.FunctionRegistryService.unregister({
136
+ registrationId: this._registrationId
137
+ });
138
+ this._registrationId = void 0;
81
139
  }
82
- };
83
- const context = {
84
- client: options.client,
85
- status: replyBuilder.status.bind(replyBuilder)
86
- };
87
- void (async () => {
88
- try {
89
- await functionHandlers[functionName](req.body, context);
90
- } catch (err) {
91
- res.statusCode = 500;
92
- res.end(err.message);
140
+ trigger.wake();
141
+ });
142
+ await trigger.wait();
143
+ this._server = void 0;
144
+ this._port = void 0;
145
+ }
146
+ };
147
+
148
+ // packages/core/functions/src/runtime/trigger-manager.ts
149
+ var import_node_assert = __toESM(require("node:assert"));
150
+ var import_async2 = require("@dxos/async");
151
+ var import_context = require("@dxos/context");
152
+ var import_echo_schema = require("@dxos/echo-schema");
153
+ var import_log2 = require("@dxos/log");
154
+ var import_util = require("@dxos/util");
155
+ var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/core/functions/src/runtime/trigger-manager.ts";
156
+ var TriggerManager = class {
157
+ constructor(_client, _triggers, _invokeOptions) {
158
+ this._client = _client;
159
+ this._triggers = _triggers;
160
+ this._invokeOptions = _invokeOptions;
161
+ this._mounts = new import_util.ComplexMap(({ name, spaceKey }) => `${spaceKey.toHex()}:${name}`);
162
+ }
163
+ async start() {
164
+ this._client.spaces.subscribe(async (spaces) => {
165
+ for (const space of spaces) {
166
+ await space.waitUntilReady();
167
+ for (const trigger of this._triggers) {
168
+ await this.mount(new import_context.Context(), trigger, space);
169
+ }
93
170
  }
94
- })();
95
- });
96
- app.listen(port);
97
- const functionNames = Object.keys(functionHandlers);
98
- const { registrationId } = await options.client.services.services.FunctionRegistryService.register({
99
- endpoint: `http://localhost:${port}`,
100
- functions: functionNames.map((name) => ({
101
- name
102
- }))
103
- });
104
- process.on("SIGINT", async () => {
105
- await options.client.services.services.FunctionRegistryService.unregister({
106
- registrationId
107
171
  });
108
- process.exit();
109
- });
110
- import_log.log.info("functions runtime started", {
111
- port,
112
- functionNames,
113
- registrationId
114
- }, {
115
- file: "index.ts",
116
- line: 93,
117
- scope: void 0,
118
- callSite: (f, a) => f(...a)
119
- });
172
+ }
173
+ async stop() {
174
+ for (const { name, spaceKey } of this._mounts.keys()) {
175
+ await this.unmount(name, spaceKey);
176
+ }
177
+ }
178
+ async mount(ctx, trigger, space) {
179
+ const key = {
180
+ name: trigger.function,
181
+ spaceKey: space.key
182
+ };
183
+ const exists = this._mounts.get(key);
184
+ if (!exists) {
185
+ this._mounts.set(key, {
186
+ ctx,
187
+ trigger
188
+ });
189
+ if (ctx.disposed) {
190
+ return;
191
+ }
192
+ let count = 0;
193
+ const objectIds = /* @__PURE__ */ new Set();
194
+ const task = new import_async2.DeferredTask(ctx, async () => {
195
+ const updatedObjects = Array.from(objectIds);
196
+ objectIds.clear();
197
+ await this.invokeFunction(this._invokeOptions, trigger.function, {
198
+ space: space.key,
199
+ objects: updatedObjects
200
+ });
201
+ });
202
+ const selection = (0, import_echo_schema.createSubscription)(({ added, updated }) => {
203
+ for (const object of added) {
204
+ objectIds.add(object.id);
205
+ }
206
+ for (const object of updated) {
207
+ objectIds.add(object.id);
208
+ }
209
+ (0, import_log2.log)("updated", {
210
+ space: space.key,
211
+ objects: objectIds.size,
212
+ added: added.length,
213
+ updated: updated.length,
214
+ count
215
+ }, {
216
+ F: __dxlog_file2,
217
+ L: 86,
218
+ S: this,
219
+ C: (f, a) => f(...a)
220
+ });
221
+ task.schedule();
222
+ count++;
223
+ });
224
+ ctx.onDispose(() => selection.unsubscribe());
225
+ const query = space.db.query({
226
+ ...trigger.subscription.props,
227
+ "@type": trigger.subscription.type
228
+ });
229
+ const unsubscribe = query.subscribe(({ objects }) => {
230
+ selection.update(objects);
231
+ });
232
+ ctx.onDispose(unsubscribe);
233
+ (0, import_log2.log)("mounted", {
234
+ space: space.key,
235
+ trigger
236
+ }, {
237
+ F: __dxlog_file2,
238
+ L: 114,
239
+ S: this,
240
+ C: (f, a) => f(...a)
241
+ });
242
+ }
243
+ }
244
+ async unmount(name, spaceKey) {
245
+ var _a;
246
+ const key = {
247
+ name,
248
+ spaceKey
249
+ };
250
+ const { ctx } = (_a = this._mounts.get(key)) != null ? _a : {};
251
+ if (ctx) {
252
+ this._mounts.delete(key);
253
+ await ctx.dispose();
254
+ }
255
+ }
256
+ async invokeFunction(options, functionName, data) {
257
+ const { endpoint, runtime } = options;
258
+ (0, import_node_assert.default)(endpoint, "Missing endpoint");
259
+ (0, import_node_assert.default)(runtime, "Missing runtime");
260
+ try {
261
+ (0, import_log2.log)("invoke", {
262
+ function: functionName
263
+ }, {
264
+ F: __dxlog_file2,
265
+ L: 133,
266
+ S: this,
267
+ C: (f, a) => f(...a)
268
+ });
269
+ const url = `${endpoint}/${runtime}/${functionName}`;
270
+ const res = await fetch(url, {
271
+ method: "POST",
272
+ body: JSON.stringify(data),
273
+ headers: {
274
+ "Content-Type": "application/json"
275
+ }
276
+ });
277
+ (0, import_log2.log)("result", {
278
+ function: functionName,
279
+ result: await res.json()
280
+ }, {
281
+ F: __dxlog_file2,
282
+ L: 143,
283
+ S: this,
284
+ C: (f, a) => f(...a)
285
+ });
286
+ } catch (err) {
287
+ import_log2.log.error("error", {
288
+ function: functionName,
289
+ error: err.message
290
+ }, {
291
+ F: __dxlog_file2,
292
+ L: 145,
293
+ S: this,
294
+ C: (f, a) => f(...a)
295
+ });
296
+ }
297
+ }
120
298
  };
121
299
  // Annotate the CommonJS export names for ESM import in node:
122
300
  0 && (module.exports = {
123
- runFunctions
301
+ DevServer,
302
+ TriggerManager
124
303
  });
125
304
  //# sourceMappingURL=index.cjs.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../../src/index.ts", "../../../src/runtime/index.ts"],
4
- "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nexport * from './interface';\nexport * from './runtime';\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport express from 'express';\nimport { readdir } from 'node:fs/promises';\nimport { extname, join } from 'node:path';\nimport { getPortPromise } from 'portfinder';\n\nimport { Client } from '@dxos/client';\nimport { log } from '@dxos/log';\n\nimport { FunctionContext, FunctionHandler, Reply } from '../interface';\n\nconst FUNCTION_EXTENSIONS = ['.js', '.ts'];\n\nexport type FunctionsRuntimeParams = {\n client: Client;\n functionsDirectory: string;\n};\n\nexport const runFunctions = async (options: FunctionsRuntimeParams) => {\n const files = await readdir(options.functionsDirectory);\n\n const functionHandlers: Record<string, FunctionHandler> = {};\n\n for (const file of files) {\n if (!FUNCTION_EXTENSIONS.some((ext) => extname(file) === ext)) {\n continue;\n }\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const module = require(join(options.functionsDirectory, file));\n const handler = module.default;\n if (typeof handler !== 'function') {\n throw new Error(`Function ${file} does not export a default function`);\n }\n\n const functionName = file.slice(0, -extname(file).length);\n\n functionHandlers[functionName] = handler;\n } catch (e) {\n console.error(e);\n }\n }\n\n const port = await getPortPromise({ startPort: 7000 });\n\n const app = express();\n app.use(express.json());\n\n app.post('/:functionName', async (req, res) => {\n const functionName = req.params.functionName;\n\n const replyBuilder: Reply = {\n status: (code: number) => {\n res.statusCode = code;\n return replyBuilder;\n },\n succeed: (result: any) => {\n res.end(JSON.stringify(result));\n return replyBuilder;\n },\n };\n const context: FunctionContext = {\n client: options.client,\n status: replyBuilder.status.bind(replyBuilder),\n };\n\n void (async () => {\n try {\n await functionHandlers[functionName](req.body, context);\n } catch (err: any) {\n res.statusCode = 500;\n res.end(err.message);\n }\n })();\n });\n app.listen(port);\n\n const functionNames = Object.keys(functionHandlers);\n const { registrationId } = await options.client.services.services.FunctionRegistryService!.register({\n endpoint: `http://localhost:${port}`,\n functions: functionNames.map((name) => ({ name })),\n });\n\n process.on('SIGINT', async () => {\n await options.client.services.services.FunctionRegistryService!.unregister({ registrationId });\n process.exit();\n });\n\n log.info('functions runtime started', { port, functionNames, registrationId });\n};\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;ACIA,qBAAoB;AACpB,sBAAwB;AACxB,uBAA8B;AAC9B,wBAA+B;AAG/B,iBAAoB;AAIpB,IAAMA,sBAAsB;EAAC;EAAO;;AAO7B,IAAMC,eAAe,OAAOC,YAAoC;AACrE,QAAMC,QAAQ,UAAMC,yBAAQF,QAAQG,kBAAkB;AAEtD,QAAMC,mBAAoD,CAAC;AAE3D,aAAWC,QAAQJ,OAAO;AACxB,QAAI,CAACH,oBAAoBQ,KAAK,CAACC,YAAQC,0BAAQH,IAAAA,MAAUE,GAAAA,GAAM;AAC7D;IACF;AAEA,QAAI;AAEF,YAAME,UAASC,YAAQC,uBAAKX,QAAQG,oBAAoBE,IAAAA,CAAAA;AACxD,YAAMO,UAAUH,QAAOI;AACvB,UAAI,OAAOD,YAAY,YAAY;AACjC,cAAM,IAAIE,MAAM,YAAYT,yCAAyC;MACvE;AAEA,YAAMU,eAAeV,KAAKW,MAAM,GAAG,KAACR,0BAAQH,IAAAA,EAAMY,MAAM;AAExDb,uBAAiBW,YAAAA,IAAgBH;IACnC,SAASM,GAAP;AACAC,cAAQC,MAAMF,CAAAA;IAChB;EACF;AAEA,QAAMG,OAAO,UAAMC,kCAAe;IAAEC,WAAW;EAAK,CAAA;AAEpD,QAAMC,UAAMC,eAAAA,SAAAA;AACZD,MAAIE,IAAID,eAAAA,QAAQE,KAAI,CAAA;AAEpBH,MAAII,KAAK,kBAAkB,OAAOC,KAAKC,QAAQ;AAC7C,UAAMf,eAAec,IAAIE,OAAOhB;AAEhC,UAAMiB,eAAsB;MAC1BC,QAAQ,CAACC,SAAiB;AACxBJ,YAAIK,aAAaD;AACjB,eAAOF;MACT;MACAI,SAAS,CAACC,WAAgB;AACxBP,YAAIQ,IAAIC,KAAKC,UAAUH,MAAAA,CAAAA;AACvB,eAAOL;MACT;IACF;AACA,UAAMS,UAA2B;MAC/BC,QAAQ1C,QAAQ0C;MAChBT,QAAQD,aAAaC,OAAOU,KAAKX,YAAAA;IACnC;AAEA,UAAM,YAAY;AAChB,UAAI;AACF,cAAM5B,iBAAiBW,YAAAA,EAAcc,IAAIe,MAAMH,OAAAA;MACjD,SAASI,KAAP;AACAf,YAAIK,aAAa;AACjBL,YAAIQ,IAAIO,IAAIC,OAAO;MACrB;IACF,GAAA;EACF,CAAA;AACAtB,MAAIuB,OAAO1B,IAAAA;AAEX,QAAM2B,gBAAgBC,OAAOC,KAAK9C,gBAAAA;AAClC,QAAM,EAAE+C,eAAc,IAAK,MAAMnD,QAAQ0C,OAAOU,SAASA,SAASC,wBAAyBC,SAAS;IAClGC,UAAU,oBAAoBlC;IAC9BmC,WAAWR,cAAcS,IAAI,CAACC,UAAU;MAAEA;IAAK,EAAA;EACjD,CAAA;AAEAC,UAAQC,GAAG,UAAU,YAAY;AAC/B,UAAM5D,QAAQ0C,OAAOU,SAASA,SAASC,wBAAyBQ,WAAW;MAAEV;IAAe,CAAA;AAC5FQ,YAAQG,KAAI;EACd,CAAA;AAEAC,iBAAIC,KAAK,6BAA6B;IAAE3C;IAAM2B;IAAeG;EAAe,GAAA;;;;;;AAC9E;",
6
- "names": ["FUNCTION_EXTENSIONS", "runFunctions", "options", "files", "readdir", "functionsDirectory", "functionHandlers", "file", "some", "ext", "extname", "module", "require", "join", "handler", "default", "Error", "functionName", "slice", "length", "e", "console", "error", "port", "getPortPromise", "startPort", "app", "express", "use", "json", "post", "req", "res", "params", "replyBuilder", "status", "code", "statusCode", "succeed", "result", "end", "JSON", "stringify", "context", "client", "bind", "body", "err", "message", "listen", "functionNames", "Object", "keys", "registrationId", "services", "FunctionRegistryService", "register", "endpoint", "functions", "map", "name", "process", "on", "unregister", "exit", "log", "info"]
3
+ "sources": ["../../../src/index.ts", "../../../src/runtime/dev-server.ts", "../../../src/runtime/trigger-manager.ts"],
4
+ "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nexport * from './function';\nexport * from './runtime';\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport express from 'express';\nimport http from 'http';\nimport { join } from 'node:path';\nimport { getPortPromise } from 'portfinder';\n\nimport { Trigger } from '@dxos/async';\nimport { Client } from '@dxos/client';\nimport { log } from '@dxos/log';\n\nimport { FunctionContext, FunctionHandler, FunctionsManifest, Response } from '../function';\n\nconst DEFAULT_PORT = 7000;\n\nexport type DevServerOptions = {\n directory: string;\n manifest: FunctionsManifest;\n};\n\n/**\n * Functions dev server provides a local HTTP server for testing functions.\n */\nexport class DevServer {\n private readonly _functionHandlers: Record<string, FunctionHandler> = {};\n\n private _server?: http.Server;\n private _port?: number;\n private _registrationId?: string;\n\n // prettier-ignore\n constructor(\n private readonly _client: Client,\n private readonly _options: DevServerOptions\n ) {}\n\n get port() {\n return this._port;\n }\n\n get endpoint() {\n return this._port ? `http://localhost:${this._port}` : undefined;\n }\n\n get functions() {\n return Object.keys(this._functionHandlers);\n }\n\n async initialize() {\n for (const [name, _] of Object.entries(this._options.manifest.functions)) {\n try {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const module = require(join(this._options.directory, name));\n const handler = module.default;\n if (typeof handler !== 'function') {\n throw new Error(`Handler must export default function: ${name}`);\n }\n\n this._functionHandlers[name] = handler;\n } catch (err) {\n log.error('parsing function (check functions.yml manifest)', err);\n }\n }\n }\n\n async start() {\n const app = express();\n app.use(express.json());\n\n app.post('/:functionName', async (req, res) => {\n const functionName = req.params.functionName;\n log('invoke', { function: functionName, data: req.body });\n\n const builder: Response = {\n status: (code: number) => {\n res.statusCode = code;\n return builder;\n },\n succeed: (result = {}) => {\n res.end(JSON.stringify(result));\n return builder;\n },\n };\n\n const context: FunctionContext = {\n client: this._client,\n status: builder.status.bind(builder),\n };\n\n void (async () => {\n try {\n await this._functionHandlers[functionName](req.body, context);\n } catch (err: any) {\n res.statusCode = 500;\n res.end(err.message);\n }\n })();\n });\n\n this._port = await getPortPromise({ startPort: DEFAULT_PORT });\n this._server = app.listen(this._port);\n\n // TODO(burdon): Check plugin is registered.\n // TypeError: Cannot read properties of undefined (reading 'register')\n const { registrationId } = await this._client.services.services.FunctionRegistryService!.register({\n endpoint: this.endpoint!,\n functions: this.functions.map((name) => ({ name })),\n });\n this._registrationId = registrationId;\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 this._registrationId = undefined;\n }\n\n trigger.wake();\n });\n\n await trigger.wait();\n this._server = undefined;\n this._port = undefined;\n }\n}\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport assert from 'node:assert';\n\nimport { DeferredTask } from '@dxos/async';\nimport { Client, PublicKey } from '@dxos/client';\nimport type { Space } from '@dxos/client/echo';\nimport { Context } from '@dxos/context';\nimport { createSubscription } from '@dxos/echo-schema';\nimport { log } from '@dxos/log';\nimport { ComplexMap } from '@dxos/util';\n\nimport { FunctionTrigger } from '../function';\n\n// TODO(burdon): Rename.\nexport type InvokeOptions = {\n endpoint: string;\n runtime: string;\n};\n\nexport class TriggerManager {\n private readonly _mounts = new ComplexMap<\n { name: string; spaceKey: PublicKey },\n { ctx: Context; trigger: FunctionTrigger }\n >(({ name, spaceKey }) => `${spaceKey.toHex()}:${name}`);\n\n constructor(\n private readonly _client: Client,\n private readonly _triggers: FunctionTrigger[],\n private readonly _invokeOptions: InvokeOptions,\n ) {}\n\n async start() {\n // TODO(burdon): Make runtime configurable (via CLI)?\n this._client.spaces.subscribe(async (spaces) => {\n for (const space of spaces) {\n await space.waitUntilReady();\n for (const trigger of this._triggers) {\n // TODO(burdon): New context? Shared?\n await this.mount(new Context(), trigger, space);\n }\n }\n });\n }\n\n async stop() {\n for (const { name, spaceKey } of this._mounts.keys()) {\n await this.unmount(name, spaceKey);\n }\n }\n\n private async mount(ctx: Context, trigger: FunctionTrigger, space: Space) {\n const key = { name: trigger.function, spaceKey: space.key };\n const exists = this._mounts.get(key);\n if (!exists) {\n this._mounts.set(key, { ctx, trigger });\n if (ctx.disposed) {\n return;\n }\n\n // TODO(burdon): Factor out subscription/result delta.\n\n let count = 0;\n const objectIds = new Set<string>();\n const task = new DeferredTask(ctx, async () => {\n const updatedObjects = Array.from(objectIds);\n objectIds.clear();\n\n await this.invokeFunction(this._invokeOptions, trigger.function, {\n space: space.key,\n objects: updatedObjects,\n });\n });\n\n // TODO(burdon): Removed?\n const selection = 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 log('updated', {\n space: space.key,\n objects: objectIds.size,\n added: added.length,\n updated: updated.length,\n count,\n });\n\n // Exec if not first update.\n // if (count++) {\n task.schedule();\n count++;\n // }\n });\n\n ctx.onDispose(() => selection.unsubscribe());\n\n const query = space.db.query({ ...trigger.subscription.props, '@type': trigger.subscription.type });\n const unsubscribe = query.subscribe(({ objects }) => {\n selection.update(objects);\n });\n\n // TODO(burdon): Calculate diff.\n // Trigger first update, but don't schedule task.\n // selection.update(query.objects);\n\n ctx.onDispose(unsubscribe);\n\n log('mounted', { space: space.key, trigger });\n }\n }\n\n private async unmount(name: string, spaceKey: PublicKey) {\n const key = { name, 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 invokeFunction(options: InvokeOptions, functionName: string, data: any) {\n const { endpoint, runtime } = options;\n assert(endpoint, 'Missing endpoint');\n assert(runtime, 'Missing runtime');\n\n try {\n log('invoke', { function: functionName });\n const url = `${endpoint}/${runtime}/${functionName}`;\n const res = await fetch(url, {\n method: 'POST',\n body: JSON.stringify(data),\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n\n log('result', { function: functionName, result: await res.json() });\n } catch (err: any) {\n log.error('error', { function: functionName, error: err.message });\n }\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;ACIA,qBAAoB;AAEpB,uBAAqB;AACrB,wBAA+B;AAE/B,mBAAwB;AAExB,iBAAoB;;AAIpB,IAAMA,eAAe;AAUd,IAAMC,YAAN,MAAMA;;EAQXC,YACmBC,SACAC,UACjB;mBAFiBD;oBACAC;SATFC,oBAAqD,CAAC;EAUpE;EAEH,IAAIC,OAAO;AACT,WAAO,KAAKC;EACd;EAEA,IAAIC,WAAW;AACb,WAAO,KAAKD,QAAQ,oBAAoB,KAAKA,UAAUE;EACzD;EAEA,IAAIC,YAAY;AACd,WAAOC,OAAOC,KAAK,KAAKP,iBAAiB;EAC3C;EAEA,MAAMQ,aAAa;AACjB,eAAW,CAACC,MAAMC,CAAAA,KAAMJ,OAAOK,QAAQ,KAAKZ,SAASa,SAASP,SAAS,GAAG;AACxE,UAAI;AAEF,cAAMQ,UAASC,YAAQC,uBAAK,KAAKhB,SAASiB,WAAWP,IAAAA,CAAAA;AACrD,cAAMQ,UAAUJ,QAAOK;AACvB,YAAI,OAAOD,YAAY,YAAY;AACjC,gBAAM,IAAIE,MAAM,yCAAyCV,MAAM;QACjE;AAEA,aAAKT,kBAAkBS,IAAAA,IAAQQ;MACjC,SAASG,KAAP;AACAC,uBAAIC,MAAM,mDAAmDF,KAAAA;;;;;;MAC/D;IACF;EACF;EAEA,MAAMG,QAAQ;AACZ,UAAMC,UAAMC,eAAAA,SAAAA;AACZD,QAAIE,IAAID,eAAAA,QAAQE,KAAI,CAAA;AAEpBH,QAAII,KAAK,kBAAkB,OAAOC,KAAKC,QAAAA;AACrC,YAAMC,eAAeF,IAAIG,OAAOD;AAChCV,0BAAI,UAAU;QAAEY,UAAUF;QAAcG,MAAML,IAAI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GAAA;;;;;;AACvC,YAAMK,MAAM,GAAGH,YAAYC,WAAWH;AACtC,YAAMM,MAAM,MAAMC,MAAMF,KAAK;QAC3BG,QAAQ;QACRC,MAAMC,KAAKC,UAAUV,IAAAA;QACrBW,SAAS;UACP,gBAAgB;QAClB;MACF,CAAA;AAEA3B,2BAAI,UAAU;QAAEvB,UAAUsC;QAAca,QAAQ,MAAMP,IAAIQ,KAAI;MAAG,GAAA;;;;;;IACnE,SAASC,KAAP;AACA9B,sBAAI+B,MAAM,SAAS;QAAEtD,UAAUsC;QAAcgB,OAAOD,IAAIE;MAAQ,GAAA;;;;;;IAClE;EACF;AACF;",
6
+ "names": ["DEFAULT_PORT", "DevServer", "constructor", "_client", "_options", "_functionHandlers", "port", "_port", "endpoint", "undefined", "functions", "Object", "keys", "initialize", "name", "_", "entries", "manifest", "module", "require", "join", "directory", "handler", "default", "Error", "err", "log", "error", "start", "app", "express", "use", "json", "post", "req", "res", "functionName", "params", "function", "data", "body", "builder", "status", "code", "statusCode", "succeed", "result", "end", "JSON", "stringify", "context", "client", "bind", "message", "getPortPromise", "startPort", "_server", "listen", "registrationId", "services", "FunctionRegistryService", "register", "map", "_registrationId", "stop", "trigger", "Trigger", "close", "unregister", "wake", "wait", "import_async", "import_log", "TriggerManager", "constructor", "_client", "_triggers", "_invokeOptions", "_mounts", "ComplexMap", "name", "spaceKey", "toHex", "start", "spaces", "subscribe", "space", "waitUntilReady", "trigger", "mount", "Context", "stop", "keys", "unmount", "ctx", "key", "function", "exists", "get", "set", "disposed", "count", "objectIds", "Set", "task", "DeferredTask", "updatedObjects", "Array", "from", "clear", "invokeFunction", "objects", "selection", "createSubscription", "added", "updated", "object", "add", "id", "log", "size", "length", "schedule", "onDispose", "unsubscribe", "query", "db", "subscription", "props", "type", "update", "delete", "dispose", "options", "functionName", "data", "endpoint", "runtime", "assert", "url", "res", "fetch", "method", "body", "JSON", "stringify", "headers", "result", "json", "err", "error", "message"]
7
7
  }
@@ -1 +1 @@
1
- {"inputs":{"packages/core/functions/src/interface.ts":{"bytes":756,"imports":[]},"packages/core/functions/src/runtime/index.ts":{"bytes":9991,"imports":[{"path":"express","kind":"import-statement","external":true},{"path":"node:fs/promises","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"portfinder","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true}]},"packages/core/functions/src/index.ts":{"bytes":464,"imports":[{"path":"packages/core/functions/src/interface.ts","kind":"import-statement","original":"./interface"},{"path":"packages/core/functions/src/runtime/index.ts","kind":"import-statement","original":"./runtime"}]}},"outputs":{"packages/core/functions/dist/lib/node/index.cjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":5363},"packages/core/functions/dist/lib/node/index.cjs":{"imports":[{"path":"express","kind":"require-call","external":true},{"path":"node:fs/promises","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true},{"path":"portfinder","kind":"require-call","external":true},{"path":"@dxos/log","kind":"require-call","external":true}],"exports":[],"entryPoint":"packages/core/functions/src/index.ts","inputs":{"packages/core/functions/src/index.ts":{"bytesInOutput":129},"packages/core/functions/src/runtime/index.ts":{"bytesInOutput":2530}},"bytes":4286}}}
1
+ {"inputs":{"packages/core/functions/src/function.ts":{"bytes":1422,"imports":[]},"packages/core/functions/src/runtime/dev-server.ts":{"bytes":13335,"imports":[{"path":"express","kind":"import-statement","external":true},{"path":"node:path","kind":"import-statement","external":true},{"path":"portfinder","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true}]},"packages/core/functions/src/runtime/trigger-manager.ts":{"bytes":16423,"imports":[{"path":"node:assert","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/util","kind":"import-statement","external":true}]},"packages/core/functions/src/runtime/index.ts":{"bytes":584,"imports":[{"path":"packages/core/functions/src/runtime/dev-server.ts","kind":"import-statement","original":"./dev-server"},{"path":"packages/core/functions/src/runtime/trigger-manager.ts","kind":"import-statement","original":"./trigger-manager"}]},"packages/core/functions/src/index.ts":{"bytes":550,"imports":[{"path":"packages/core/functions/src/function.ts","kind":"import-statement","original":"./function"},{"path":"packages/core/functions/src/runtime/index.ts","kind":"import-statement","original":"./runtime"}]}},"outputs":{"packages/core/functions/dist/lib/node/index.cjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":14350},"packages/core/functions/dist/lib/node/index.cjs":{"imports":[{"path":"express","kind":"require-call","external":true},{"path":"node:path","kind":"require-call","external":true},{"path":"portfinder","kind":"require-call","external":true},{"path":"@dxos/async","kind":"require-call","external":true},{"path":"@dxos/log","kind":"require-call","external":true},{"path":"node:assert","kind":"require-call","external":true},{"path":"@dxos/async","kind":"require-call","external":true},{"path":"@dxos/context","kind":"require-call","external":true},{"path":"@dxos/echo-schema","kind":"require-call","external":true},{"path":"@dxos/log","kind":"require-call","external":true},{"path":"@dxos/util","kind":"require-call","external":true}],"exports":[],"entryPoint":"packages/core/functions/src/index.ts","inputs":{"packages/core/functions/src/index.ts":{"bytesInOutput":163},"packages/core/functions/src/runtime/dev-server.ts":{"bytesInOutput":3271},"packages/core/functions/src/runtime/index.ts":{"bytesInOutput":0},"packages/core/functions/src/runtime/trigger-manager.ts":{"bytesInOutput":4292}},"bytes":9432}}}
@@ -0,0 +1,30 @@
1
+ import { Client } from '@dxos/client';
2
+ export interface Response {
3
+ status(code: number): Response;
4
+ succeed(data?: object): Response;
5
+ }
6
+ export interface FunctionContext {
7
+ client: Client;
8
+ status(code: number): Response;
9
+ }
10
+ export interface FunctionHandler {
11
+ (event: any, context: FunctionContext): Promise<Response>;
12
+ }
13
+ export type FunctionsManifest = {
14
+ functions: Record<string, FunctionConfig>;
15
+ triggers: FunctionTrigger[];
16
+ };
17
+ export type FunctionConfig = {
18
+ description?: string;
19
+ };
20
+ export type FunctionTrigger = {
21
+ function: string;
22
+ subscription: TriggerSubscription;
23
+ };
24
+ export type TriggerSubscription = {
25
+ type: string;
26
+ spaceKey: string;
27
+ props?: Record<string, any>;
28
+ nested?: string[];
29
+ };
30
+ //# sourceMappingURL=function.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"function.d.ts","sourceRoot":"","sources":["../../../src/function.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAEtC,MAAM,WAAW,QAAQ;IACvB,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,QAAQ,CAAC;IAC/B,OAAO,CAAC,IAAI,CAAC,EAAE,MAAM,GAAG,QAAQ,CAAC;CAClC;AAED,MAAM,WAAW,eAAe;IAC9B,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,QAAQ,CAAC;CAChC;AAED,MAAM,WAAW,eAAe;IAC9B,CAAC,KAAK,EAAE,GAAG,EAAE,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;CAC3D;AAED,MAAM,MAAM,iBAAiB,GAAG;IAC9B,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;IAC1C,QAAQ,EAAE,eAAe,EAAE,CAAC;CAC7B,CAAC;AAEF,MAAM,MAAM,cAAc,GAAG;IAC3B,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB,CAAC;AAEF,MAAM,MAAM,eAAe,GAAG;IAC5B,QAAQ,EAAE,MAAM,CAAC;IACjB,YAAY,EAAE,mBAAmB,CAAC;CACnC,CAAC;AAEF,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,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;CACnB,CAAC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=function.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"function.test.d.ts","sourceRoot":"","sources":["../../../src/function.test.ts"],"names":[],"mappings":""}
@@ -1,3 +1,3 @@
1
- export * from './interface';
1
+ export * from './function';
2
2
  export * from './runtime';
3
3
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAIA,cAAc,aAAa,CAAC;AAC5B,cAAc,WAAW,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAIA,cAAc,YAAY,CAAC;AAC3B,cAAc,WAAW,CAAC"}
@@ -0,0 +1,25 @@
1
+ import { Client } from '@dxos/client';
2
+ import { FunctionsManifest } from '../function';
3
+ export type DevServerOptions = {
4
+ directory: string;
5
+ manifest: FunctionsManifest;
6
+ };
7
+ /**
8
+ * Functions dev server provides a local HTTP server for testing functions.
9
+ */
10
+ export declare class DevServer {
11
+ private readonly _client;
12
+ private readonly _options;
13
+ private readonly _functionHandlers;
14
+ private _server?;
15
+ private _port?;
16
+ private _registrationId?;
17
+ constructor(_client: Client, _options: DevServerOptions);
18
+ get port(): number | undefined;
19
+ get endpoint(): string | undefined;
20
+ get functions(): string[];
21
+ initialize(): Promise<void>;
22
+ start(): Promise<void>;
23
+ stop(): Promise<void>;
24
+ }
25
+ //# sourceMappingURL=dev-server.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dev-server.d.ts","sourceRoot":"","sources":["../../../../src/runtime/dev-server.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAGtC,OAAO,EAAoC,iBAAiB,EAAY,MAAM,aAAa,CAAC;AAI5F,MAAM,MAAM,gBAAgB,GAAG;IAC7B,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,iBAAiB,CAAC;CAC7B,CAAC;AAEF;;GAEG;AACH,qBAAa,SAAS;IASlB,OAAO,CAAC,QAAQ,CAAC,OAAO;IACxB,OAAO,CAAC,QAAQ,CAAC,QAAQ;IAT3B,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAAuC;IAEzE,OAAO,CAAC,OAAO,CAAC,CAAc;IAC9B,OAAO,CAAC,KAAK,CAAC,CAAS;IACvB,OAAO,CAAC,eAAe,CAAC,CAAS;gBAId,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,gBAAgB;IAG7C,IAAI,IAAI,uBAEP;IAED,IAAI,QAAQ,uBAEX;IAED,IAAI,SAAS,aAEZ;IAEK,UAAU;IAiBV,KAAK;IA8CL,IAAI;CAiBX"}
@@ -1,7 +1,3 @@
1
- import { Client } from '@dxos/client';
2
- export type FunctionsRuntimeParams = {
3
- client: Client;
4
- functionsDirectory: string;
5
- };
6
- export declare const runFunctions: (options: FunctionsRuntimeParams) => Promise<void>;
1
+ export * from './dev-server';
2
+ export * from './trigger-manager';
7
3
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/runtime/index.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAOtC,MAAM,MAAM,sBAAsB,GAAG;IACnC,MAAM,EAAE,MAAM,CAAC;IACf,kBAAkB,EAAE,MAAM,CAAC;CAC5B,CAAC;AAEF,eAAO,MAAM,YAAY,YAAmB,sBAAsB,kBAwEjE,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/runtime/index.ts"],"names":[],"mappings":"AAIA,cAAc,cAAc,CAAC;AAC7B,cAAc,mBAAmB,CAAC"}
@@ -0,0 +1,19 @@
1
+ import { Client } from '@dxos/client';
2
+ import { FunctionTrigger } from '../function';
3
+ export type InvokeOptions = {
4
+ endpoint: string;
5
+ runtime: string;
6
+ };
7
+ export declare class TriggerManager {
8
+ private readonly _client;
9
+ private readonly _triggers;
10
+ private readonly _invokeOptions;
11
+ private readonly _mounts;
12
+ constructor(_client: Client, _triggers: FunctionTrigger[], _invokeOptions: InvokeOptions);
13
+ start(): Promise<void>;
14
+ stop(): Promise<void>;
15
+ private mount;
16
+ private unmount;
17
+ private invokeFunction;
18
+ }
19
+ //# sourceMappingURL=trigger-manager.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trigger-manager.d.ts","sourceRoot":"","sources":["../../../../src/runtime/trigger-manager.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,MAAM,EAAa,MAAM,cAAc,CAAC;AAOjD,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAG9C,MAAM,MAAM,aAAa,GAAG;IAC1B,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;CACjB,CAAC;AAEF,qBAAa,cAAc;IAOvB,OAAO,CAAC,QAAQ,CAAC,OAAO;IACxB,OAAO,CAAC,QAAQ,CAAC,SAAS;IAC1B,OAAO,CAAC,QAAQ,CAAC,cAAc;IARjC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAGiC;gBAGtC,OAAO,EAAE,MAAM,EACf,SAAS,EAAE,eAAe,EAAE,EAC5B,cAAc,EAAE,aAAa;IAG1C,KAAK;IAaL,IAAI;YAMI,KAAK;YAgEL,OAAO;YASP,cAAc;CAqB7B"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@dxos/functions",
3
- "version": "0.1.52",
4
- "description": "Functions SDK.",
3
+ "version": "0.1.53-main.00be1a9",
4
+ "description": "Functions SDK and runtime.",
5
5
  "homepage": "https://dxos.org",
6
6
  "bugs": "https://github.com/dxos/dxos/issues",
7
7
  "license": "MIT",
@@ -21,9 +21,13 @@
21
21
  "dependencies": {
22
22
  "express": "4.17.1",
23
23
  "portfinder": "^1.0.32",
24
- "@dxos/client": "0.1.52",
25
- "@dxos/log": "0.1.52",
26
- "@dxos/node-std": "0.1.52"
24
+ "@dxos/async": "0.1.53-main.00be1a9",
25
+ "@dxos/client": "0.1.53-main.00be1a9",
26
+ "@dxos/context": "0.1.53-main.00be1a9",
27
+ "@dxos/echo-schema": "0.1.53-main.00be1a9",
28
+ "@dxos/log": "0.1.53-main.00be1a9",
29
+ "@dxos/node-std": "0.1.53-main.00be1a9",
30
+ "@dxos/util": "0.1.53-main.00be1a9"
27
31
  },
28
32
  "devDependencies": {
29
33
  "@types/express": "^4.17.17"
@@ -0,0 +1,40 @@
1
+ //
2
+ // Copyright 2023 DXOS.org
3
+ //
4
+
5
+ import { Client } from '@dxos/client';
6
+
7
+ export interface Response {
8
+ status(code: number): Response;
9
+ succeed(data?: object): Response;
10
+ }
11
+
12
+ export interface FunctionContext {
13
+ client: Client;
14
+ status(code: number): Response;
15
+ }
16
+
17
+ export interface FunctionHandler {
18
+ (event: any, context: FunctionContext): Promise<Response>;
19
+ }
20
+
21
+ export type FunctionsManifest = {
22
+ functions: Record<string, FunctionConfig>;
23
+ triggers: FunctionTrigger[];
24
+ };
25
+
26
+ export type FunctionConfig = {
27
+ description?: string;
28
+ };
29
+
30
+ export type FunctionTrigger = {
31
+ function: string;
32
+ subscription: TriggerSubscription;
33
+ };
34
+
35
+ export type TriggerSubscription = {
36
+ type: string;
37
+ spaceKey: string;
38
+ props?: Record<string, any>;
39
+ nested?: string[];
40
+ };
package/src/index.ts CHANGED
@@ -2,5 +2,5 @@
2
2
  // Copyright 2023 DXOS.org
3
3
  //
4
4
 
5
- export * from './interface';
5
+ export * from './function';
6
6
  export * from './runtime';