@dxos/functions 0.5.3-main.3456876 → 0.5.3-main.3b535c7
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 +103 -235
- package/dist/lib/browser/index.mjs.map +3 -3
- package/dist/lib/browser/meta.json +1 -1
- package/dist/lib/node/index.cjs +102 -234
- package/dist/lib/node/index.cjs.map +3 -3
- package/dist/lib/node/meta.json +1 -1
- package/dist/types/src/handler.d.ts +4 -5
- package/dist/types/src/handler.d.ts.map +1 -1
- package/dist/types/src/runtime/dev-server.d.ts +5 -11
- package/dist/types/src/runtime/dev-server.d.ts.map +1 -1
- package/dist/types/src/runtime/scheduler.d.ts +4 -38
- package/dist/types/src/runtime/scheduler.d.ts.map +1 -1
- package/dist/types/src/types.d.ts +29 -51
- package/dist/types/src/types.d.ts.map +1 -1
- package/package.json +13 -15
- package/schema/functions.json +4 -12
- package/src/handler.ts +12 -12
- package/src/runtime/dev-server.ts +37 -71
- package/src/runtime/scheduler.test.ts +9 -13
- package/src/runtime/scheduler.ts +19 -60
- package/src/types.ts +6 -15
- package/dist/types/src/runtime/dev-server.test.d.ts +0 -2
- package/dist/types/src/runtime/dev-server.test.d.ts.map +0 -1
- package/dist/types/src/testing/test/handler.d.ts +0 -3
- package/dist/types/src/testing/test/handler.d.ts.map +0 -1
- package/dist/types/src/testing/test/index.d.ts +0 -3
- package/dist/types/src/testing/test/index.d.ts.map +0 -1
- package/src/runtime/dev-server.test.ts +0 -80
- package/src/testing/test/handler.ts +0 -9
- package/src/testing/test/index.ts +0 -7
package/schema/functions.json
CHANGED
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
|
3
3
|
"type": "object",
|
|
4
4
|
"required": [
|
|
5
|
-
"functions"
|
|
5
|
+
"functions",
|
|
6
|
+
"triggers"
|
|
6
7
|
],
|
|
7
8
|
"properties": {
|
|
8
9
|
"functions": {
|
|
@@ -11,7 +12,7 @@
|
|
|
11
12
|
"type": "object",
|
|
12
13
|
"required": [
|
|
13
14
|
"id",
|
|
14
|
-
"
|
|
15
|
+
"name",
|
|
15
16
|
"handler"
|
|
16
17
|
],
|
|
17
18
|
"properties": {
|
|
@@ -20,7 +21,7 @@
|
|
|
20
21
|
"description": "a string",
|
|
21
22
|
"title": "string"
|
|
22
23
|
},
|
|
23
|
-
"
|
|
24
|
+
"name": {
|
|
24
25
|
"type": "string",
|
|
25
26
|
"description": "a string",
|
|
26
27
|
"title": "string"
|
|
@@ -52,15 +53,6 @@
|
|
|
52
53
|
"description": "Function ID/URI.",
|
|
53
54
|
"title": "string"
|
|
54
55
|
},
|
|
55
|
-
"context": {
|
|
56
|
-
"type": "object",
|
|
57
|
-
"required": [],
|
|
58
|
-
"properties": {},
|
|
59
|
-
"additionalProperties": {
|
|
60
|
-
"$id": "/schemas/any",
|
|
61
|
-
"title": "any"
|
|
62
|
-
}
|
|
63
|
-
},
|
|
64
56
|
"timer": {
|
|
65
57
|
"type": "object",
|
|
66
58
|
"required": [
|
package/src/handler.ts
CHANGED
|
@@ -8,8 +8,9 @@ import { type EchoReactiveObject } from '@dxos/echo-schema';
|
|
|
8
8
|
import { log } from '@dxos/log';
|
|
9
9
|
import { nonNullable } from '@dxos/util';
|
|
10
10
|
|
|
11
|
+
// TODO(burdon): Context?
|
|
11
12
|
// Lambda-like function definitions.
|
|
12
|
-
// https://www.serverless.com/framework/docs/providers/aws/guide/serverless.yml/#functions
|
|
13
|
+
// See: https://www.serverless.com/framework/docs/providers/aws/guide/serverless.yml/#functions
|
|
13
14
|
// https://www.npmjs.com/package/aws-lambda
|
|
14
15
|
// https://docs.aws.amazon.com/lambda/latest/dg/typescript-handler.html
|
|
15
16
|
|
|
@@ -18,28 +19,27 @@ export interface Response {
|
|
|
18
19
|
status(code: number): Response;
|
|
19
20
|
}
|
|
20
21
|
|
|
22
|
+
// TODO(burdon): Limit access to individual space?
|
|
21
23
|
export interface FunctionContext {
|
|
22
|
-
// TODO(burdon): Limit access to individual space.
|
|
23
24
|
client: Client;
|
|
24
|
-
// TODO(burdon): Replace with storage service abstraction.
|
|
25
25
|
dataDir?: string;
|
|
26
|
-
// Data passed to function invocation.
|
|
27
|
-
data?: any;
|
|
28
26
|
}
|
|
29
27
|
|
|
30
28
|
// TODO(burdon): Model after http request. Ref Lambda/OpenFaaS.
|
|
29
|
+
// https://docs.aws.amazon.com/lambda/latest/dg/typescript-handler.html
|
|
31
30
|
export type FunctionHandler<T extends {}> = (params: {
|
|
32
31
|
event: T;
|
|
33
32
|
context: FunctionContext;
|
|
34
33
|
response: Response;
|
|
35
34
|
}) => Promise<Response | void>;
|
|
36
35
|
|
|
37
|
-
export type
|
|
38
|
-
|
|
36
|
+
export type FunctionSubscriptionEvent = {
|
|
37
|
+
space?: string; // TODO(burdon): Convert to PublicKey.
|
|
39
38
|
objects?: string[];
|
|
40
39
|
};
|
|
41
40
|
|
|
42
|
-
|
|
41
|
+
// TODO(burdon): ???
|
|
42
|
+
export type FunctionSubscriptionEvent2 = {
|
|
43
43
|
space?: Space;
|
|
44
44
|
objects?: EchoReactiveObject<any>[];
|
|
45
45
|
};
|
|
@@ -55,16 +55,16 @@ export type SubscriptionEvent = {
|
|
|
55
55
|
* NOTE: Get space key from devtools or `dx space list --json`
|
|
56
56
|
*/
|
|
57
57
|
export const subscriptionHandler = (
|
|
58
|
-
handler: FunctionHandler<
|
|
59
|
-
): FunctionHandler<
|
|
58
|
+
handler: FunctionHandler<FunctionSubscriptionEvent2>,
|
|
59
|
+
): FunctionHandler<FunctionSubscriptionEvent> => {
|
|
60
60
|
return ({ event, context, ...rest }) => {
|
|
61
61
|
const { client } = context;
|
|
62
|
-
const space = event.
|
|
62
|
+
const space = event.space ? client.spaces.get(PublicKey.from(event.space)) : undefined;
|
|
63
63
|
const objects =
|
|
64
64
|
space &&
|
|
65
65
|
event.objects?.map<EchoReactiveObject<any> | undefined>((id) => space!.db.getObjectById(id)).filter(nonNullable);
|
|
66
66
|
|
|
67
|
-
if (!!event.
|
|
67
|
+
if (!!event.space && !space) {
|
|
68
68
|
log.warn('invalid space', { event });
|
|
69
69
|
} else {
|
|
70
70
|
log.info('handler', { space: space?.key.truncate(), objects: objects?.length });
|
|
@@ -7,7 +7,7 @@ import { getPort } from 'get-port-please';
|
|
|
7
7
|
import type http from 'http';
|
|
8
8
|
import { join } from 'node:path';
|
|
9
9
|
|
|
10
|
-
import {
|
|
10
|
+
import { Trigger } from '@dxos/async';
|
|
11
11
|
import { type Client } from '@dxos/client';
|
|
12
12
|
import { invariant } from '@dxos/invariant';
|
|
13
13
|
import { log } from '@dxos/log';
|
|
@@ -16,9 +16,9 @@ import { type FunctionContext, type FunctionHandler, type Response } from '../ha
|
|
|
16
16
|
import { type FunctionDef, type FunctionManifest } from '../types';
|
|
17
17
|
|
|
18
18
|
export type DevServerOptions = {
|
|
19
|
-
manifest: FunctionManifest;
|
|
20
|
-
baseDir: string;
|
|
21
19
|
port?: number;
|
|
20
|
+
directory: string;
|
|
21
|
+
manifest: FunctionManifest;
|
|
22
22
|
reload?: boolean;
|
|
23
23
|
dataDir?: string;
|
|
24
24
|
};
|
|
@@ -32,24 +32,16 @@ export class DevServer {
|
|
|
32
32
|
|
|
33
33
|
private _server?: http.Server;
|
|
34
34
|
private _port?: number;
|
|
35
|
-
private
|
|
35
|
+
private _registrationId?: string;
|
|
36
36
|
private _proxy?: string;
|
|
37
37
|
private _seq = 0;
|
|
38
38
|
|
|
39
|
-
public readonly update = new Event<number>();
|
|
40
|
-
|
|
41
39
|
// prettier-ignore
|
|
42
40
|
constructor(
|
|
43
41
|
private readonly _client: Client,
|
|
44
42
|
private readonly _options: DevServerOptions,
|
|
45
43
|
) {}
|
|
46
44
|
|
|
47
|
-
get stats() {
|
|
48
|
-
return {
|
|
49
|
-
seq: this._seq,
|
|
50
|
-
};
|
|
51
|
-
}
|
|
52
|
-
|
|
53
45
|
get endpoint() {
|
|
54
46
|
invariant(this._port);
|
|
55
47
|
return `http://localhost:${this._port}`;
|
|
@@ -74,24 +66,19 @@ export class DevServer {
|
|
|
74
66
|
}
|
|
75
67
|
|
|
76
68
|
async start() {
|
|
77
|
-
invariant(!this._server);
|
|
78
|
-
log.info('starting...');
|
|
79
|
-
|
|
80
|
-
// TODO(burdon): Move to hono.
|
|
81
69
|
const app = express();
|
|
82
70
|
app.use(express.json());
|
|
83
71
|
|
|
84
|
-
app.post('/:
|
|
85
|
-
const {
|
|
72
|
+
app.post('/:name', async (req, res) => {
|
|
73
|
+
const { name } = req.params;
|
|
86
74
|
try {
|
|
87
|
-
log.info('calling', {
|
|
75
|
+
log.info('calling', { name });
|
|
88
76
|
if (this._options.reload) {
|
|
89
|
-
const { def } = this._handlers[
|
|
77
|
+
const { def } = this._handlers[name];
|
|
90
78
|
await this._load(def, true);
|
|
91
79
|
}
|
|
92
80
|
|
|
93
|
-
|
|
94
|
-
res.statusCode = await this.invoke('/' + path, req.body);
|
|
81
|
+
res.statusCode = await this._invoke(name, req.body);
|
|
95
82
|
res.end();
|
|
96
83
|
} catch (err: any) {
|
|
97
84
|
log.catch(err);
|
|
@@ -107,95 +94,72 @@ export class DevServer {
|
|
|
107
94
|
// Register functions.
|
|
108
95
|
const { registrationId, endpoint } = await this._client.services.services.FunctionRegistryService!.register({
|
|
109
96
|
endpoint: this.endpoint,
|
|
110
|
-
functions: this.functions.map(({ def: {
|
|
97
|
+
functions: this.functions.map(({ def: { name } }) => ({ name })),
|
|
111
98
|
});
|
|
112
99
|
|
|
113
|
-
log.info('registered', { endpoint });
|
|
100
|
+
log.info('registered', { registrationId, endpoint });
|
|
101
|
+
this._registrationId = registrationId;
|
|
114
102
|
this._proxy = endpoint;
|
|
115
|
-
this._functionServiceRegistration = registrationId;
|
|
116
103
|
} catch (err: any) {
|
|
117
104
|
await this.stop();
|
|
118
105
|
throw new Error('FunctionRegistryService not available (check plugin is configured).');
|
|
119
106
|
}
|
|
120
|
-
|
|
121
|
-
log.info('started', { port: this._port });
|
|
122
107
|
}
|
|
123
108
|
|
|
124
109
|
async stop() {
|
|
125
|
-
invariant(this._server);
|
|
126
|
-
log.info('stopping...');
|
|
127
|
-
|
|
128
110
|
const trigger = new Trigger();
|
|
129
|
-
this._server
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
await this._client.services.services.FunctionRegistryService.unregister({
|
|
135
|
-
registrationId: this._functionServiceRegistration,
|
|
136
|
-
});
|
|
137
|
-
|
|
138
|
-
log.info('unregistered', { registrationId: this._functionServiceRegistration });
|
|
139
|
-
this._functionServiceRegistration = undefined;
|
|
140
|
-
this._proxy = undefined;
|
|
141
|
-
}
|
|
111
|
+
this._server?.close(async () => {
|
|
112
|
+
if (this._registrationId) {
|
|
113
|
+
await this._client.services.services.FunctionRegistryService!.unregister({
|
|
114
|
+
registrationId: this._registrationId,
|
|
115
|
+
});
|
|
142
116
|
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
117
|
+
log.info('unregistered', { registrationId: this._registrationId });
|
|
118
|
+
this._registrationId = undefined;
|
|
119
|
+
this._proxy = undefined;
|
|
146
120
|
}
|
|
121
|
+
|
|
122
|
+
trigger.wake();
|
|
147
123
|
});
|
|
148
124
|
|
|
149
125
|
await trigger.wait();
|
|
150
126
|
this._port = undefined;
|
|
151
127
|
this._server = undefined;
|
|
152
|
-
log.info('stopped');
|
|
153
128
|
}
|
|
154
129
|
|
|
155
130
|
/**
|
|
156
131
|
* Load function.
|
|
157
132
|
*/
|
|
158
|
-
private async _load(def: FunctionDef,
|
|
159
|
-
const { id,
|
|
160
|
-
const
|
|
161
|
-
log.info('loading', { id
|
|
133
|
+
private async _load(def: FunctionDef, flush = false) {
|
|
134
|
+
const { id, name, handler } = def;
|
|
135
|
+
const path = join(this._options.directory, handler);
|
|
136
|
+
log.info('loading', { id });
|
|
162
137
|
|
|
163
138
|
// Remove from cache.
|
|
164
|
-
if (
|
|
139
|
+
if (flush) {
|
|
165
140
|
Object.keys(require.cache)
|
|
166
|
-
.filter((key) => key.startsWith(
|
|
167
|
-
.forEach((key) =>
|
|
168
|
-
delete require.cache[key];
|
|
169
|
-
});
|
|
141
|
+
.filter((key) => key.startsWith(path))
|
|
142
|
+
.forEach((key) => delete require.cache[key]);
|
|
170
143
|
}
|
|
171
144
|
|
|
172
145
|
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
173
|
-
const module = require(
|
|
146
|
+
const module = require(path);
|
|
174
147
|
if (typeof module.default !== 'function') {
|
|
175
148
|
throw new Error(`Handler must export default function: ${id}`);
|
|
176
149
|
}
|
|
177
150
|
|
|
178
|
-
this._handlers[
|
|
151
|
+
this._handlers[name] = { def, handler: module.default };
|
|
179
152
|
}
|
|
180
153
|
|
|
181
154
|
/**
|
|
182
|
-
* Invoke function.
|
|
155
|
+
* Invoke function handler.
|
|
183
156
|
*/
|
|
184
|
-
|
|
157
|
+
private async _invoke(name: string, event: any) {
|
|
185
158
|
const seq = ++this._seq;
|
|
186
159
|
const now = Date.now();
|
|
187
160
|
|
|
188
|
-
log.info('req', { seq,
|
|
189
|
-
const
|
|
190
|
-
|
|
191
|
-
log.info('res', { seq, path, statusCode, duration: Date.now() - now });
|
|
192
|
-
this.update.emit(statusCode);
|
|
193
|
-
return statusCode;
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
private async _invoke(path: string, event: any) {
|
|
197
|
-
const { handler } = this._handlers[path] ?? {};
|
|
198
|
-
invariant(handler, `invalid path: ${path}`);
|
|
161
|
+
log.info('req', { seq, name });
|
|
162
|
+
const { handler } = this._handlers[name];
|
|
199
163
|
|
|
200
164
|
const context: FunctionContext = {
|
|
201
165
|
client: this._client,
|
|
@@ -211,6 +175,8 @@ export class DevServer {
|
|
|
211
175
|
};
|
|
212
176
|
|
|
213
177
|
await handler({ context, event, response });
|
|
178
|
+
log.info('res', { seq, name, statusCode, duration: Date.now() - now });
|
|
179
|
+
|
|
214
180
|
return statusCode;
|
|
215
181
|
}
|
|
216
182
|
}
|
|
@@ -12,14 +12,14 @@ import { create, S, TypedObject } from '@dxos/echo-schema';
|
|
|
12
12
|
import { describe, test } from '@dxos/test';
|
|
13
13
|
|
|
14
14
|
import { Scheduler } from './scheduler';
|
|
15
|
-
import { type FunctionManifest
|
|
15
|
+
import { type FunctionManifest } from '../types';
|
|
16
16
|
|
|
17
17
|
// TODO(burdon): Test we can add and remove triggers.
|
|
18
18
|
describe('scheduler', () => {
|
|
19
19
|
let client: Client;
|
|
20
20
|
before(async () => {
|
|
21
21
|
const testBuilder = new TestBuilder();
|
|
22
|
-
client = new Client({ services: testBuilder.
|
|
22
|
+
client = new Client({ services: testBuilder.createLocal() });
|
|
23
23
|
await client.initialize();
|
|
24
24
|
await client.halo.createIdentity();
|
|
25
25
|
});
|
|
@@ -32,7 +32,7 @@ describe('scheduler', () => {
|
|
|
32
32
|
functions: [
|
|
33
33
|
{
|
|
34
34
|
id: 'example.com/function/test',
|
|
35
|
-
|
|
35
|
+
name: 'test',
|
|
36
36
|
handler: 'test',
|
|
37
37
|
},
|
|
38
38
|
],
|
|
@@ -70,7 +70,7 @@ describe('scheduler', () => {
|
|
|
70
70
|
functions: [
|
|
71
71
|
{
|
|
72
72
|
id: 'example.com/function/test',
|
|
73
|
-
|
|
73
|
+
name: 'test',
|
|
74
74
|
handler: 'test',
|
|
75
75
|
},
|
|
76
76
|
],
|
|
@@ -78,7 +78,7 @@ describe('scheduler', () => {
|
|
|
78
78
|
{
|
|
79
79
|
function: 'example.com/function/test',
|
|
80
80
|
webhook: {
|
|
81
|
-
|
|
81
|
+
port: 8080,
|
|
82
82
|
},
|
|
83
83
|
},
|
|
84
84
|
],
|
|
@@ -97,21 +97,17 @@ describe('scheduler', () => {
|
|
|
97
97
|
});
|
|
98
98
|
|
|
99
99
|
setTimeout(() => {
|
|
100
|
-
|
|
101
|
-
(mount) => mount.function === 'example.com/function/test',
|
|
102
|
-
)!.webhook!;
|
|
103
|
-
void fetch(`http://localhost:${mount.port}`);
|
|
100
|
+
void fetch('http://localhost:8080');
|
|
104
101
|
});
|
|
105
|
-
|
|
106
102
|
await done.wait();
|
|
107
103
|
});
|
|
108
104
|
|
|
109
|
-
test('websocket', async () => {
|
|
105
|
+
test.only('websocket', async () => {
|
|
110
106
|
const manifest: FunctionManifest = {
|
|
111
107
|
functions: [
|
|
112
108
|
{
|
|
113
109
|
id: 'example.com/function/test',
|
|
114
|
-
|
|
110
|
+
name: 'test',
|
|
115
111
|
handler: 'test',
|
|
116
112
|
},
|
|
117
113
|
],
|
|
@@ -166,7 +162,7 @@ describe('scheduler', () => {
|
|
|
166
162
|
functions: [
|
|
167
163
|
{
|
|
168
164
|
id: 'example.com/function/test',
|
|
169
|
-
|
|
165
|
+
name: 'test',
|
|
170
166
|
handler: 'test',
|
|
171
167
|
},
|
|
172
168
|
],
|
package/src/runtime/scheduler.ts
CHANGED
|
@@ -3,9 +3,7 @@
|
|
|
3
3
|
//
|
|
4
4
|
|
|
5
5
|
import { CronJob } from 'cron';
|
|
6
|
-
import { getPort } from 'get-port-please';
|
|
7
6
|
import http from 'node:http';
|
|
8
|
-
import path from 'node:path';
|
|
9
7
|
import WebSocket from 'ws';
|
|
10
8
|
|
|
11
9
|
import { TextV0Type } from '@braneframe/types';
|
|
@@ -17,6 +15,7 @@ import { invariant } from '@dxos/invariant';
|
|
|
17
15
|
import { log } from '@dxos/log';
|
|
18
16
|
import { ComplexMap } from '@dxos/util';
|
|
19
17
|
|
|
18
|
+
import { type FunctionSubscriptionEvent } from '../handler';
|
|
20
19
|
import {
|
|
21
20
|
type FunctionDef,
|
|
22
21
|
type FunctionManifest,
|
|
@@ -27,7 +26,7 @@ import {
|
|
|
27
26
|
type WebsocketTrigger,
|
|
28
27
|
} from '../types';
|
|
29
28
|
|
|
30
|
-
|
|
29
|
+
type Callback = (data: FunctionSubscriptionEvent) => Promise<void>;
|
|
31
30
|
|
|
32
31
|
export type SchedulerOptions = {
|
|
33
32
|
endpoint?: string;
|
|
@@ -35,14 +34,14 @@ export type SchedulerOptions = {
|
|
|
35
34
|
};
|
|
36
35
|
|
|
37
36
|
/**
|
|
38
|
-
* The scheduler triggers function
|
|
37
|
+
* The scheduler triggers function exectuion based on various triggers.
|
|
39
38
|
*/
|
|
40
39
|
export class Scheduler {
|
|
41
40
|
// Map of mounted functions.
|
|
42
41
|
private readonly _mounts = new ComplexMap<
|
|
43
|
-
{
|
|
42
|
+
{ id: string; spaceKey: PublicKey },
|
|
44
43
|
{ ctx: Context; trigger: FunctionTrigger }
|
|
45
|
-
>(({
|
|
44
|
+
>(({ id, spaceKey }) => `${spaceKey.toHex()}:${id}`);
|
|
46
45
|
|
|
47
46
|
constructor(
|
|
48
47
|
private readonly _client: Client,
|
|
@@ -50,13 +49,6 @@ export class Scheduler {
|
|
|
50
49
|
private readonly _options: SchedulerOptions = {},
|
|
51
50
|
) {}
|
|
52
51
|
|
|
53
|
-
get mounts() {
|
|
54
|
-
return Array.from(this._mounts.values()).reduce<FunctionTrigger[]>((acc, { trigger }) => {
|
|
55
|
-
acc.push(trigger);
|
|
56
|
-
return acc;
|
|
57
|
-
}, []);
|
|
58
|
-
}
|
|
59
|
-
|
|
60
52
|
async start() {
|
|
61
53
|
this._client.spaces.subscribe(async (spaces) => {
|
|
62
54
|
for (const space of spaces) {
|
|
@@ -74,11 +66,8 @@ export class Scheduler {
|
|
|
74
66
|
}
|
|
75
67
|
}
|
|
76
68
|
|
|
77
|
-
/**
|
|
78
|
-
* Mount trigger.
|
|
79
|
-
*/
|
|
80
69
|
private async mount(ctx: Context, space: Space, trigger: FunctionTrigger) {
|
|
81
|
-
const key = {
|
|
70
|
+
const key = { id: trigger.function, spaceKey: space.key };
|
|
82
71
|
const def = this._manifest.functions.find((config) => config.id === trigger.function);
|
|
83
72
|
invariant(def, `Function not found: ${trigger.function}`);
|
|
84
73
|
|
|
@@ -123,39 +112,27 @@ export class Scheduler {
|
|
|
123
112
|
}
|
|
124
113
|
|
|
125
114
|
// TODO(burdon): Pass in Space key (common context).
|
|
126
|
-
private async _execFunction(def: FunctionDef, data: any)
|
|
115
|
+
private async _execFunction(def: FunctionDef, data: any) {
|
|
127
116
|
try {
|
|
128
|
-
|
|
117
|
+
log.info('exec', { function: def.id });
|
|
129
118
|
const { endpoint, callback } = this._options;
|
|
130
119
|
if (endpoint) {
|
|
131
120
|
// TODO(burdon): Move out of scheduler (generalize as callback).
|
|
132
|
-
|
|
133
|
-
log.info('exec', { function: def.id, url });
|
|
134
|
-
const response = await fetch(url, {
|
|
121
|
+
await fetch(`${this._options.endpoint}/${def.name}`, {
|
|
135
122
|
method: 'POST',
|
|
136
123
|
headers: {
|
|
137
124
|
'Content-Type': 'application/json',
|
|
138
125
|
},
|
|
139
126
|
body: JSON.stringify(data),
|
|
140
127
|
});
|
|
141
|
-
|
|
142
|
-
status = response.status;
|
|
143
128
|
} else if (callback) {
|
|
144
|
-
|
|
145
|
-
status = (await callback(data)) ?? 200;
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
// Check errors.
|
|
149
|
-
if (status && status >= 400) {
|
|
150
|
-
throw new Error(`Response: ${status}`);
|
|
129
|
+
await callback(data);
|
|
151
130
|
}
|
|
152
131
|
|
|
153
132
|
// const result = await response.json();
|
|
154
|
-
log.info('done', { function: def.id
|
|
155
|
-
return status;
|
|
133
|
+
log.info('done', { function: def.id });
|
|
156
134
|
} catch (err: any) {
|
|
157
135
|
log.error('error', { function: def.id, error: err.message });
|
|
158
|
-
return 500;
|
|
159
136
|
}
|
|
160
137
|
}
|
|
161
138
|
|
|
@@ -171,7 +148,7 @@ export class Scheduler {
|
|
|
171
148
|
const { cron } = trigger;
|
|
172
149
|
|
|
173
150
|
const task = new DeferredTask(ctx, async () => {
|
|
174
|
-
await this._execFunction(def, {
|
|
151
|
+
await this._execFunction(def, { space: space.key });
|
|
175
152
|
});
|
|
176
153
|
|
|
177
154
|
let last = 0;
|
|
@@ -201,30 +178,15 @@ export class Scheduler {
|
|
|
201
178
|
*/
|
|
202
179
|
private async _createWebhook(ctx: Context, space: Space, def: FunctionDef, trigger: WebhookTrigger) {
|
|
203
180
|
log.info('webhook', { space: space.key, trigger });
|
|
181
|
+
const { port } = trigger;
|
|
204
182
|
|
|
205
|
-
// TODO(burdon):
|
|
183
|
+
// TODO(burdon): POST JSON.
|
|
206
184
|
const server = http.createServer(async (req, res) => {
|
|
207
|
-
|
|
208
|
-
res.statusCode = 405;
|
|
209
|
-
return res.end();
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
res.statusCode = await this._execFunction(def, { spaceKey: space.key });
|
|
213
|
-
res.end();
|
|
185
|
+
await this._execFunction(def, { space: space.key });
|
|
214
186
|
});
|
|
215
187
|
|
|
216
|
-
// TODO(burdon): Not used.
|
|
217
|
-
// const DEF_PORT_RANGE = { min: 7500, max: 7599 };
|
|
218
|
-
// const portRange = Object.assign({}, trigger.port, DEF_PORT_RANGE) as WebhookTrigger['port'];
|
|
219
|
-
const port = await getPort({
|
|
220
|
-
random: true,
|
|
221
|
-
// portRange: [portRange!.min, portRange!.max],
|
|
222
|
-
});
|
|
223
|
-
|
|
224
|
-
// TODO(burdon): Update trigger object with actual port.
|
|
225
188
|
server.listen(port, () => {
|
|
226
189
|
log.info('started webhook', { port });
|
|
227
|
-
trigger.port = port;
|
|
228
190
|
});
|
|
229
191
|
|
|
230
192
|
ctx.onDispose(() => {
|
|
@@ -234,7 +196,6 @@ export class Scheduler {
|
|
|
234
196
|
|
|
235
197
|
/**
|
|
236
198
|
* Websocket.
|
|
237
|
-
* NOTE: The port must be unique, so the same hook cannot be used for multiple spaces.
|
|
238
199
|
*/
|
|
239
200
|
private async _createWebsocket(
|
|
240
201
|
ctx: Context,
|
|
@@ -267,9 +228,8 @@ export class Scheduler {
|
|
|
267
228
|
open.wake(true);
|
|
268
229
|
},
|
|
269
230
|
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
log.info('closed', { url, code: event.code });
|
|
231
|
+
onclose: () => {
|
|
232
|
+
log.info('closed', { url });
|
|
273
233
|
open.wake(false);
|
|
274
234
|
},
|
|
275
235
|
|
|
@@ -280,7 +240,7 @@ export class Scheduler {
|
|
|
280
240
|
onmessage: async (event) => {
|
|
281
241
|
try {
|
|
282
242
|
const data = JSON.parse(new TextDecoder().decode(event.data as Uint8Array));
|
|
283
|
-
await this._execFunction(def, {
|
|
243
|
+
await this._execFunction(def, { space: space.key, data });
|
|
284
244
|
} catch (err) {
|
|
285
245
|
log.catch(err, { url });
|
|
286
246
|
}
|
|
@@ -311,7 +271,7 @@ export class Scheduler {
|
|
|
311
271
|
log.info('subscription', { space: space.key, trigger });
|
|
312
272
|
const objectIds = new Set<string>();
|
|
313
273
|
const task = new DeferredTask(ctx, async () => {
|
|
314
|
-
await this._execFunction(def, {
|
|
274
|
+
await this._execFunction(def, { space: space.key, objects: Array.from(objectIds) });
|
|
315
275
|
});
|
|
316
276
|
|
|
317
277
|
// TODO(burdon): Don't fire initially.
|
|
@@ -328,7 +288,6 @@ export class Scheduler {
|
|
|
328
288
|
|
|
329
289
|
task.schedule();
|
|
330
290
|
});
|
|
331
|
-
|
|
332
291
|
subscriptions.push(() => subscription.unsubscribe());
|
|
333
292
|
|
|
334
293
|
// TODO(burdon): Create queue. Only allow one invocation per trigger at a time?
|
package/src/types.ts
CHANGED
|
@@ -8,13 +8,9 @@ const TimerTriggerSchema = S.struct({
|
|
|
8
8
|
cron: S.string,
|
|
9
9
|
});
|
|
10
10
|
|
|
11
|
-
const WebhookTriggerSchema = S.
|
|
12
|
-
S.
|
|
13
|
-
|
|
14
|
-
// Assigned port.
|
|
15
|
-
port: S.optional(S.number),
|
|
16
|
-
}),
|
|
17
|
-
);
|
|
11
|
+
const WebhookTriggerSchema = S.struct({
|
|
12
|
+
port: S.number,
|
|
13
|
+
});
|
|
18
14
|
|
|
19
15
|
const WebsocketTriggerSchema = S.struct({
|
|
20
16
|
url: S.string,
|
|
@@ -43,10 +39,6 @@ const SubscriptionTriggerSchema = S.struct({
|
|
|
43
39
|
const FunctionTriggerSchema = S.struct({
|
|
44
40
|
function: S.string.pipe(S.description('Function ID/URI.')),
|
|
45
41
|
|
|
46
|
-
// Context passed to function.
|
|
47
|
-
context: S.optional(S.record(S.string, S.any)),
|
|
48
|
-
|
|
49
|
-
// Triggers.
|
|
50
42
|
timer: S.optional(TimerTriggerSchema),
|
|
51
43
|
webhook: S.optional(WebhookTriggerSchema),
|
|
52
44
|
websocket: S.optional(WebsocketTriggerSchema),
|
|
@@ -65,10 +57,9 @@ export type FunctionTrigger = S.Schema.Type<typeof FunctionTriggerSchema>;
|
|
|
65
57
|
// TODO(burdon): Name vs. path?
|
|
66
58
|
const FunctionDefSchema = S.struct({
|
|
67
59
|
id: S.string,
|
|
68
|
-
// name: S.string,
|
|
69
60
|
description: S.optional(S.string),
|
|
70
|
-
|
|
71
|
-
// TODO(burdon): NPM/GitHub
|
|
61
|
+
name: S.string,
|
|
62
|
+
// TODO(burdon): NPM/GitHub URL?
|
|
72
63
|
handler: S.string,
|
|
73
64
|
});
|
|
74
65
|
|
|
@@ -79,7 +70,7 @@ export type FunctionDef = S.Schema.Type<typeof FunctionDefSchema>;
|
|
|
79
70
|
*/
|
|
80
71
|
export const FunctionManifestSchema = S.struct({
|
|
81
72
|
functions: S.mutable(S.array(FunctionDefSchema)),
|
|
82
|
-
triggers: S.
|
|
73
|
+
triggers: S.mutable(S.array(FunctionTriggerSchema)),
|
|
83
74
|
});
|
|
84
75
|
|
|
85
76
|
export type FunctionManifest = S.Schema.Type<typeof FunctionManifestSchema>;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"dev-server.test.d.ts","sourceRoot":"","sources":["../../../../src/runtime/dev-server.test.ts"],"names":[],"mappings":""}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"handler.d.ts","sourceRoot":"","sources":["../../../../../src/testing/test/handler.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,KAAK,eAAe,EAAE,MAAM,eAAe,CAAC;AAErD,eAAO,MAAM,OAAO,EAAE,eAAe,CAAC,GAAG,CAExC,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../src/testing/test/index.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC,eAAe,OAAO,CAAC"}
|