@dxos/functions 0.1.52 → 0.1.53-main.01cbc6b
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/README.md +68 -3
- package/dist/lib/browser/index.mjs +251 -76
- package/dist/lib/browser/index.mjs.map +4 -4
- package/dist/lib/browser/meta.json +1 -1
- package/dist/lib/node/index.cjs +251 -75
- package/dist/lib/node/index.cjs.map +4 -4
- package/dist/lib/node/meta.json +1 -1
- package/dist/types/src/function.d.ts +30 -0
- package/dist/types/src/function.d.ts.map +1 -0
- package/dist/types/src/function.test.d.ts +2 -0
- package/dist/types/src/function.test.d.ts.map +1 -0
- package/dist/types/src/index.d.ts +1 -1
- package/dist/types/src/index.d.ts.map +1 -1
- package/dist/types/src/runtime/dev-server.d.ts +25 -0
- package/dist/types/src/runtime/dev-server.d.ts.map +1 -0
- package/dist/types/src/runtime/index.d.ts +2 -6
- package/dist/types/src/runtime/index.d.ts.map +1 -1
- package/dist/types/src/runtime/trigger-manager.d.ts +19 -0
- package/dist/types/src/runtime/trigger-manager.d.ts.map +1 -0
- package/package.json +9 -5
- package/src/function.ts +40 -0
- package/src/index.ts +1 -1
- package/src/runtime/dev-server.ts +131 -0
- package/src/runtime/index.ts +2 -90
- package/src/runtime/trigger-manager.ts +138 -0
- package/dist/types/src/functions.test.d.ts +0 -2
- package/dist/types/src/functions.test.d.ts.map +0 -1
- package/dist/types/src/interface.d.ts +0 -13
- package/dist/types/src/interface.d.ts.map +0 -1
- package/src/interface.ts +0 -20
- /package/src/{functions.test.ts → function.test.ts} +0 -0
package/README.md
CHANGED
|
@@ -1,11 +1,76 @@
|
|
|
1
|
-
# @dxos/
|
|
1
|
+
# @dxos/functions
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Functions SDK.
|
|
4
4
|
|
|
5
5
|
## Installation
|
|
6
6
|
|
|
7
7
|
```bash
|
|
8
|
-
pnpm i @dxos/
|
|
8
|
+
pnpm i @dxos/functions
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Writing functions
|
|
12
|
+
|
|
13
|
+
Create a manifest file at the package root:
|
|
14
|
+
|
|
15
|
+
```yaml
|
|
16
|
+
functions:
|
|
17
|
+
hello:
|
|
18
|
+
description: Test function.
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
> NOTE: The function name must match the filename (e.g., `src/functions/hello.ts`).
|
|
22
|
+
|
|
23
|
+
Create an example function:
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
import { FunctionContext } from '@dxos/functions';
|
|
27
|
+
|
|
28
|
+
export default (event: any, context: FunctionContext) => {
|
|
29
|
+
const identity = context.client.halo.identity.get();
|
|
30
|
+
return context
|
|
31
|
+
.status(200)
|
|
32
|
+
.succeed({
|
|
33
|
+
message: `Hello ${identity?.profile?.displayName}`
|
|
34
|
+
});
|
|
35
|
+
};
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## Running functions with the dev server:
|
|
39
|
+
|
|
40
|
+
Configure the agent to run functions on a given port:
|
|
41
|
+
|
|
42
|
+
```yaml
|
|
43
|
+
# ~/.config/dx/profile/default.yml
|
|
44
|
+
runtime:
|
|
45
|
+
agent:
|
|
46
|
+
functions:
|
|
47
|
+
port: 7001
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Start functions in dev mode (from the related package):
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
dx function dev-server -r ts-node/register --verbose
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
> NOTE: `-r ts-node/register` configures native TypesScript support.
|
|
57
|
+
|
|
58
|
+
Install `nodemon` to support live reloading:
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
npm i -g nodemon
|
|
62
|
+
|
|
63
|
+
nodemon -w ./src -e ts --exec $(git rev-parse --show-toplevel)/packages/devtools/cli/bin/dev \
|
|
64
|
+
function dev-server -r ts-node/register --verbose
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## Invoking functions
|
|
68
|
+
|
|
69
|
+
> NOTE: The port (7001) must match the one in config.
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
curl -X POST -H 'Content-Type: application/json' -w '\n' \
|
|
73
|
+
http://localhost:7001/dev/hello --data '{ "message": "Hello World!" }'
|
|
9
74
|
```
|
|
10
75
|
|
|
11
76
|
## DXOS Resources
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import "@dxos/node-std/globals"
|
|
1
|
+
import "@dxos/node-std/globals";
|
|
2
2
|
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
3
3
|
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
4
4
|
}) : x)(function(x) {
|
|
@@ -7,91 +7,266 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
|
|
|
7
7
|
throw new Error('Dynamic require of "' + x + '" is not supported');
|
|
8
8
|
});
|
|
9
9
|
|
|
10
|
-
// packages/core/functions/src/runtime/
|
|
10
|
+
// packages/core/functions/src/runtime/dev-server.ts
|
|
11
11
|
import express from "express";
|
|
12
|
-
import {
|
|
13
|
-
import { extname, join } from "@dxos/node-std/path";
|
|
12
|
+
import { join } from "@dxos/node-std/path";
|
|
14
13
|
import { getPortPromise } from "portfinder";
|
|
14
|
+
import { Trigger } from "@dxos/async";
|
|
15
15
|
import { log } from "@dxos/log";
|
|
16
|
-
var
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
16
|
+
var __dxlog_file = "/home/runner/work/dxos/dxos/packages/core/functions/src/runtime/dev-server.ts";
|
|
17
|
+
var DEFAULT_PORT = 7e3;
|
|
18
|
+
var DevServer = class {
|
|
19
|
+
// prettier-ignore
|
|
20
|
+
constructor(_client, _options) {
|
|
21
|
+
this._client = _client;
|
|
22
|
+
this._options = _options;
|
|
23
|
+
this._functionHandlers = {};
|
|
24
|
+
}
|
|
25
|
+
get port() {
|
|
26
|
+
return this._port;
|
|
27
|
+
}
|
|
28
|
+
get endpoint() {
|
|
29
|
+
return this._port ? `http://localhost:${this._port}` : void 0;
|
|
30
|
+
}
|
|
31
|
+
get functions() {
|
|
32
|
+
return Object.keys(this._functionHandlers);
|
|
33
|
+
}
|
|
34
|
+
async initialize() {
|
|
35
|
+
for (const [name, _] of Object.entries(this._options.manifest.functions)) {
|
|
36
|
+
try {
|
|
37
|
+
const module = __require(join(this._options.directory, name));
|
|
38
|
+
const handler = module.default;
|
|
39
|
+
if (typeof handler !== "function") {
|
|
40
|
+
throw new Error(`Handler must export default function: ${name}`);
|
|
41
|
+
}
|
|
42
|
+
this._functionHandlers[name] = handler;
|
|
43
|
+
} catch (err) {
|
|
44
|
+
log.error("parsing function (check functions.yml manifest)", err, {
|
|
45
|
+
F: __dxlog_file,
|
|
46
|
+
L: 63,
|
|
47
|
+
S: this,
|
|
48
|
+
C: (f, a) => f(...a)
|
|
49
|
+
});
|
|
32
50
|
}
|
|
33
|
-
const functionName = file.slice(0, -extname(file).length);
|
|
34
|
-
functionHandlers[functionName] = handler;
|
|
35
|
-
} catch (e) {
|
|
36
|
-
console.error(e);
|
|
37
51
|
}
|
|
38
52
|
}
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
53
|
+
async start() {
|
|
54
|
+
const app = express();
|
|
55
|
+
app.use(express.json());
|
|
56
|
+
app.post("/:functionName", async (req, res) => {
|
|
57
|
+
const functionName = req.params.functionName;
|
|
58
|
+
log("invoke", {
|
|
59
|
+
function: functionName,
|
|
60
|
+
data: req.body
|
|
61
|
+
}, {
|
|
62
|
+
F: __dxlog_file,
|
|
63
|
+
L: 74,
|
|
64
|
+
S: this,
|
|
65
|
+
C: (f, a) => f(...a)
|
|
66
|
+
});
|
|
67
|
+
const builder = {
|
|
68
|
+
status: (code) => {
|
|
69
|
+
res.statusCode = code;
|
|
70
|
+
return builder;
|
|
71
|
+
},
|
|
72
|
+
succeed: (result = {}) => {
|
|
73
|
+
res.end(JSON.stringify(result));
|
|
74
|
+
return builder;
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
const context = {
|
|
78
|
+
client: this._client,
|
|
79
|
+
status: builder.status.bind(builder)
|
|
80
|
+
};
|
|
81
|
+
void (async () => {
|
|
82
|
+
try {
|
|
83
|
+
await this._functionHandlers[functionName](req.body, context);
|
|
84
|
+
} catch (err) {
|
|
85
|
+
res.statusCode = 500;
|
|
86
|
+
res.end(err.message);
|
|
87
|
+
}
|
|
88
|
+
})();
|
|
89
|
+
});
|
|
90
|
+
this._port = await getPortPromise({
|
|
91
|
+
startPort: DEFAULT_PORT
|
|
92
|
+
});
|
|
93
|
+
this._server = app.listen(this._port);
|
|
94
|
+
const { registrationId } = await this._client.services.services.FunctionRegistryService.register({
|
|
95
|
+
endpoint: this.endpoint,
|
|
96
|
+
functions: this.functions.map((name) => ({
|
|
97
|
+
name
|
|
98
|
+
}))
|
|
99
|
+
});
|
|
100
|
+
this._registrationId = registrationId;
|
|
101
|
+
}
|
|
102
|
+
async stop() {
|
|
103
|
+
var _a;
|
|
104
|
+
const trigger = new Trigger();
|
|
105
|
+
(_a = this._server) == null ? void 0 : _a.close(async () => {
|
|
106
|
+
if (this._registrationId) {
|
|
107
|
+
await this._client.services.services.FunctionRegistryService.unregister({
|
|
108
|
+
registrationId: this._registrationId
|
|
109
|
+
});
|
|
110
|
+
this._registrationId = void 0;
|
|
54
111
|
}
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
112
|
+
trigger.wake();
|
|
113
|
+
});
|
|
114
|
+
await trigger.wait();
|
|
115
|
+
this._server = void 0;
|
|
116
|
+
this._port = void 0;
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
// packages/core/functions/src/runtime/trigger-manager.ts
|
|
121
|
+
import assert from "@dxos/node-std/assert";
|
|
122
|
+
import { DeferredTask } from "@dxos/async";
|
|
123
|
+
import { Context } from "@dxos/context";
|
|
124
|
+
import { createSubscription } from "@dxos/echo-schema";
|
|
125
|
+
import { log as log2 } from "@dxos/log";
|
|
126
|
+
import { ComplexMap } from "@dxos/util";
|
|
127
|
+
var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/core/functions/src/runtime/trigger-manager.ts";
|
|
128
|
+
var TriggerManager = class {
|
|
129
|
+
constructor(_client, _triggers, _invokeOptions) {
|
|
130
|
+
this._client = _client;
|
|
131
|
+
this._triggers = _triggers;
|
|
132
|
+
this._invokeOptions = _invokeOptions;
|
|
133
|
+
this._mounts = new ComplexMap(({ name, spaceKey }) => `${spaceKey.toHex()}:${name}`);
|
|
134
|
+
}
|
|
135
|
+
async start() {
|
|
136
|
+
this._client.spaces.subscribe(async (spaces) => {
|
|
137
|
+
for (const space of spaces) {
|
|
138
|
+
await space.waitUntilReady();
|
|
139
|
+
for (const trigger of this._triggers) {
|
|
140
|
+
await this.mount(new Context(), space, trigger);
|
|
141
|
+
}
|
|
66
142
|
}
|
|
67
|
-
})();
|
|
68
|
-
});
|
|
69
|
-
app.listen(port);
|
|
70
|
-
const functionNames = Object.keys(functionHandlers);
|
|
71
|
-
const { registrationId } = await options.client.services.services.FunctionRegistryService.register({
|
|
72
|
-
endpoint: `http://localhost:${port}`,
|
|
73
|
-
functions: functionNames.map((name) => ({
|
|
74
|
-
name
|
|
75
|
-
}))
|
|
76
|
-
});
|
|
77
|
-
process.on("SIGINT", async () => {
|
|
78
|
-
await options.client.services.services.FunctionRegistryService.unregister({
|
|
79
|
-
registrationId
|
|
80
143
|
});
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
144
|
+
}
|
|
145
|
+
async stop() {
|
|
146
|
+
for (const { name, spaceKey } of this._mounts.keys()) {
|
|
147
|
+
await this.unmount(name, spaceKey);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
async mount(ctx, space, trigger) {
|
|
151
|
+
const key = {
|
|
152
|
+
name: trigger.function,
|
|
153
|
+
spaceKey: space.key
|
|
154
|
+
};
|
|
155
|
+
const exists = this._mounts.get(key);
|
|
156
|
+
if (!exists) {
|
|
157
|
+
this._mounts.set(key, {
|
|
158
|
+
ctx,
|
|
159
|
+
trigger
|
|
160
|
+
});
|
|
161
|
+
log2("mount", {
|
|
162
|
+
space: space.key,
|
|
163
|
+
trigger
|
|
164
|
+
}, {
|
|
165
|
+
F: __dxlog_file2,
|
|
166
|
+
L: 59,
|
|
167
|
+
S: this,
|
|
168
|
+
C: (f, a) => f(...a)
|
|
169
|
+
});
|
|
170
|
+
if (ctx.disposed) {
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
const objectIds = /* @__PURE__ */ new Set();
|
|
174
|
+
const task = new DeferredTask(ctx, async () => {
|
|
175
|
+
await this.invokeFunction(this._invokeOptions, trigger.function, {
|
|
176
|
+
space: space.key,
|
|
177
|
+
objects: Array.from(objectIds)
|
|
178
|
+
});
|
|
179
|
+
});
|
|
180
|
+
let count = 0;
|
|
181
|
+
const subscription = createSubscription(({ added, updated }) => {
|
|
182
|
+
for (const object of added) {
|
|
183
|
+
objectIds.add(object.id);
|
|
184
|
+
}
|
|
185
|
+
for (const object of updated) {
|
|
186
|
+
objectIds.add(object.id);
|
|
187
|
+
}
|
|
188
|
+
log2("updated", {
|
|
189
|
+
trigger,
|
|
190
|
+
space: space.key,
|
|
191
|
+
objects: objectIds.size,
|
|
192
|
+
count
|
|
193
|
+
}, {
|
|
194
|
+
F: __dxlog_file2,
|
|
195
|
+
L: 82,
|
|
196
|
+
S: this,
|
|
197
|
+
C: (f, a) => f(...a)
|
|
198
|
+
});
|
|
199
|
+
task.schedule();
|
|
200
|
+
count++;
|
|
201
|
+
});
|
|
202
|
+
ctx.onDispose(() => subscription.unsubscribe());
|
|
203
|
+
const query = space.db.query({
|
|
204
|
+
"@type": trigger.subscription.type,
|
|
205
|
+
...trigger.subscription.props
|
|
206
|
+
});
|
|
207
|
+
const unsubscribe = query.subscribe(({ objects }) => {
|
|
208
|
+
subscription.update(objects);
|
|
209
|
+
});
|
|
210
|
+
ctx.onDispose(() => unsubscribe());
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
async unmount(name, spaceKey) {
|
|
214
|
+
var _a;
|
|
215
|
+
const key = {
|
|
216
|
+
name,
|
|
217
|
+
spaceKey
|
|
218
|
+
};
|
|
219
|
+
const { ctx } = (_a = this._mounts.get(key)) != null ? _a : {};
|
|
220
|
+
if (ctx) {
|
|
221
|
+
this._mounts.delete(key);
|
|
222
|
+
await ctx.dispose();
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
async invokeFunction(options, functionName, data) {
|
|
226
|
+
const { endpoint, runtime } = options;
|
|
227
|
+
assert(endpoint, "Missing endpoint");
|
|
228
|
+
assert(runtime, "Missing runtime");
|
|
229
|
+
try {
|
|
230
|
+
log2("invoke", {
|
|
231
|
+
function: functionName
|
|
232
|
+
}, {
|
|
233
|
+
F: __dxlog_file2,
|
|
234
|
+
L: 123,
|
|
235
|
+
S: this,
|
|
236
|
+
C: (f, a) => f(...a)
|
|
237
|
+
});
|
|
238
|
+
const url = `${endpoint}/${runtime}/${functionName}`;
|
|
239
|
+
const res = await fetch(url, {
|
|
240
|
+
method: "POST",
|
|
241
|
+
body: JSON.stringify(data),
|
|
242
|
+
headers: {
|
|
243
|
+
"Content-Type": "application/json"
|
|
244
|
+
}
|
|
245
|
+
});
|
|
246
|
+
log2("result", {
|
|
247
|
+
function: functionName,
|
|
248
|
+
result: await res.json()
|
|
249
|
+
}, {
|
|
250
|
+
F: __dxlog_file2,
|
|
251
|
+
L: 133,
|
|
252
|
+
S: this,
|
|
253
|
+
C: (f, a) => f(...a)
|
|
254
|
+
});
|
|
255
|
+
} catch (err) {
|
|
256
|
+
log2.error("error", {
|
|
257
|
+
function: functionName,
|
|
258
|
+
error: err.message
|
|
259
|
+
}, {
|
|
260
|
+
F: __dxlog_file2,
|
|
261
|
+
L: 135,
|
|
262
|
+
S: this,
|
|
263
|
+
C: (f, a) => f(...a)
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
}
|
|
93
267
|
};
|
|
94
268
|
export {
|
|
95
|
-
|
|
269
|
+
DevServer,
|
|
270
|
+
TriggerManager
|
|
96
271
|
};
|
|
97
272
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../../../src/runtime/
|
|
4
|
-
"sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport express from 'express';\nimport
|
|
5
|
-
"mappings": ";;;;;;;;;;AAIA,OAAOA,aAAa;
|
|
6
|
-
"names": ["express", "
|
|
3
|
+
"sources": ["../../../src/runtime/dev-server.ts", "../../../src/runtime/trigger-manager.ts"],
|
|
4
|
+
"sourcesContent": ["//\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(), space, trigger);\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, space: Space, trigger: FunctionTrigger) {\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 log('mount', { space: space.key, trigger });\n if (ctx.disposed) {\n return;\n }\n\n // TODO(burdon): Why DeferredTask? How to pass objectIds to function?\n const objectIds = new Set<string>();\n const task = new DeferredTask(ctx, async () => {\n await this.invokeFunction(this._invokeOptions, trigger.function, {\n space: space.key,\n objects: Array.from(objectIds),\n });\n });\n\n let count = 0;\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 log('updated', {\n trigger,\n space: space.key,\n objects: objectIds.size,\n count,\n });\n\n task.schedule();\n count++;\n });\n\n ctx.onDispose(() => subscription.unsubscribe());\n\n // TODO(burdon): DSL for query (replace props).\n const query = space.db.query({ '@type': trigger.subscription.type, ...trigger.subscription.props });\n const unsubscribe = query.subscribe(({ objects }) => {\n subscription.update(objects);\n });\n\n // TODO(burdon): Option to trigger on first subscription.\n // TODO(burdon): After restart not triggered.\n\n ctx.onDispose(() => unsubscribe());\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": ";;;;;;;;;;AAIA,OAAOA,aAAa;AAEpB,SAASC,YAAY;AACrB,SAASC,sBAAsB;AAE/B,SAASC,eAAe;AAExB,SAASC,WAAW;;AAIpB,IAAMC,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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QAAO,MAAE;AAC9CI,qBAAac,OAAOlB,OAAAA;MACtB,CAAA;AAKAX,UAAIuB,UAAU,MAAMC,YAAAA,CAAAA;IACtB;EACF;EAEA,MAAczB,QAAQZ,MAAcC,UAAqB;AA3G3D;AA4GI,UAAMa,MAAM;MAAEd;MAAMC;IAAS;AAC7B,UAAM,EAAEY,IAAG,KAAK,UAAKd,QAAQkB,IAAIH,GAAAA,MAAjB,YAAyB,CAAC;AAC1C,QAAID,KAAK;AACP,WAAKd,QAAQ4C,OAAO7B,GAAAA;AACpB,YAAMD,IAAI+B,QAAO;IACnB;EACF;EAEA,MAAcrB,eAAesB,SAAwBC,cAAsBC,MAAW;AACpF,UAAM,EAAEC,UAAUC,QAAO,IAAKJ;AAC9BzD,WAAO4D,UAAU,kBAAA;AACjB5D,WAAO6D,SAAS,iBAAA;AAEhB,QAAI;AACFzD,MAAAA,KAAI,UAAU;QAAEuB,UAAU+B;MAAa,GAAA;;;;;;AACvC,YAAMI,MAAM,GAAGF,YAAYC,WAAWH;AACtC,YAAMK,MAAM,MAAMC,MAAMF,KAAK;QAC3BG,QAAQ;QACRC,MAAMC,KAAKC,UAAUT,IAAAA;QACrBU,SAAS;UACP,gBAAgB;QAClB;MACF,CAAA;AAEAjE,MAAAA,KAAI,UAAU;QAAEuB,UAAU+B;QAAcY,QAAQ,MAAMP,IAAIQ,KAAI;MAAG,GAAA;;;;;;IACnE,SAASC,KAAP;AACApE,MAAAA,KAAIqE,MAAM,SAAS;QAAE9C,UAAU+B;QAAce,OAAOD,IAAIE;MAAQ,GAAA;;;;;;IAClE;EACF;AACF;",
|
|
6
|
+
"names": ["express", "join", "getPortPromise", "Trigger", "log", "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", "assert", "DeferredTask", "Context", "createSubscription", "log", "ComplexMap", "TriggerManager", "constructor", "_client", "_triggers", "_invokeOptions", "_mounts", "name", "spaceKey", "toHex", "start", "spaces", "subscribe", "space", "waitUntilReady", "trigger", "mount", "stop", "keys", "unmount", "ctx", "key", "function", "exists", "get", "set", "disposed", "objectIds", "Set", "task", "invokeFunction", "objects", "Array", "from", "count", "subscription", "added", "updated", "object", "add", "id", "size", "schedule", "onDispose", "unsubscribe", "query", "db", "type", "props", "update", "delete", "dispose", "options", "functionName", "data", "endpoint", "runtime", "url", "res", "fetch", "method", "body", "JSON", "stringify", "headers", "result", "json", "err", "error", "message"]
|
|
7
7
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"inputs":{"packages/core/functions/src/
|
|
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":"@dxos/node-std/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},{"path":"<runtime>","kind":"import-statement","external":true}]},"packages/core/functions/src/runtime/trigger-manager.ts":{"bytes":15730,"imports":[{"path":"@dxos/node-std/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/browser/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":13972},"packages/core/functions/dist/lib/browser/index.mjs":{"imports":[{"path":"express","kind":"import-statement","external":true},{"path":"@dxos/node-std/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},{"path":"@dxos/node-std/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}],"exports":["DevServer","TriggerManager"],"entryPoint":"packages/core/functions/src/index.ts","inputs":{"packages/core/functions/src/index.ts":{"bytesInOutput":0},"packages/core/functions/src/runtime/dev-server.ts":{"bytesInOutput":3119},"packages/core/functions/src/runtime/index.ts":{"bytesInOutput":0},"packages/core/functions/src/runtime/trigger-manager.ts":{"bytesInOutput":3977}},"bytes":7692}}}
|