@dxos/functions 0.5.3-main.59db342 → 0.5.3-main.61bbff4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/dist/lib/browser/index.mjs +829 -265
  2. package/dist/lib/browser/index.mjs.map +4 -4
  3. package/dist/lib/browser/meta.json +1 -1
  4. package/dist/lib/node/index.cjs +817 -266
  5. package/dist/lib/node/index.cjs.map +4 -4
  6. package/dist/lib/node/meta.json +1 -1
  7. package/dist/types/src/handler.d.ts +33 -12
  8. package/dist/types/src/handler.d.ts.map +1 -1
  9. package/dist/types/src/index.d.ts +3 -1
  10. package/dist/types/src/index.d.ts.map +1 -1
  11. package/dist/types/src/registry/function-registry.d.ts +24 -0
  12. package/dist/types/src/registry/function-registry.d.ts.map +1 -0
  13. package/dist/types/src/registry/function-registry.test.d.ts +2 -0
  14. package/dist/types/src/registry/function-registry.test.d.ts.map +1 -0
  15. package/dist/types/src/registry/index.d.ts +2 -0
  16. package/dist/types/src/registry/index.d.ts.map +1 -0
  17. package/dist/types/src/runtime/dev-server.d.ts +15 -7
  18. package/dist/types/src/runtime/dev-server.d.ts.map +1 -1
  19. package/dist/types/src/runtime/dev-server.test.d.ts +2 -0
  20. package/dist/types/src/runtime/dev-server.test.d.ts.map +1 -0
  21. package/dist/types/src/runtime/scheduler.d.ts +14 -15
  22. package/dist/types/src/runtime/scheduler.d.ts.map +1 -1
  23. package/dist/types/src/testing/functions-integration.test.d.ts +2 -0
  24. package/dist/types/src/testing/functions-integration.test.d.ts.map +1 -0
  25. package/dist/types/src/testing/index.d.ts +4 -0
  26. package/dist/types/src/testing/index.d.ts.map +1 -0
  27. package/dist/types/src/testing/setup.d.ts +5 -0
  28. package/dist/types/src/testing/setup.d.ts.map +1 -0
  29. package/dist/types/src/testing/test/handler.d.ts +4 -0
  30. package/dist/types/src/testing/test/handler.d.ts.map +1 -0
  31. package/dist/types/src/testing/test/index.d.ts +3 -0
  32. package/dist/types/src/testing/test/index.d.ts.map +1 -0
  33. package/dist/types/src/testing/types.d.ts +9 -0
  34. package/dist/types/src/testing/types.d.ts.map +1 -0
  35. package/dist/types/src/testing/util.d.ts +3 -0
  36. package/dist/types/src/testing/util.d.ts.map +1 -0
  37. package/dist/types/src/trigger/index.d.ts +2 -0
  38. package/dist/types/src/trigger/index.d.ts.map +1 -0
  39. package/dist/types/src/trigger/trigger-registry.d.ts +40 -0
  40. package/dist/types/src/trigger/trigger-registry.d.ts.map +1 -0
  41. package/dist/types/src/trigger/trigger-registry.test.d.ts +2 -0
  42. package/dist/types/src/trigger/trigger-registry.test.d.ts.map +1 -0
  43. package/dist/types/src/trigger/type/index.d.ts +5 -0
  44. package/dist/types/src/trigger/type/index.d.ts.map +1 -0
  45. package/dist/types/src/trigger/type/subscription-trigger.d.ts +4 -0
  46. package/dist/types/src/trigger/type/subscription-trigger.d.ts.map +1 -0
  47. package/dist/types/src/trigger/type/timer-trigger.d.ts +4 -0
  48. package/dist/types/src/trigger/type/timer-trigger.d.ts.map +1 -0
  49. package/dist/types/src/trigger/type/webhook-trigger.d.ts +4 -0
  50. package/dist/types/src/trigger/type/webhook-trigger.d.ts.map +1 -0
  51. package/dist/types/src/trigger/type/websocket-trigger.d.ts +13 -0
  52. package/dist/types/src/trigger/type/websocket-trigger.d.ts.map +1 -0
  53. package/dist/types/src/types.d.ts +188 -0
  54. package/dist/types/src/types.d.ts.map +1 -0
  55. package/dist/types/tools/schema.d.ts +2 -0
  56. package/dist/types/tools/schema.d.ts.map +1 -0
  57. package/package.json +23 -11
  58. package/schema/functions.json +197 -0
  59. package/src/handler.ts +56 -26
  60. package/src/index.ts +3 -1
  61. package/src/registry/function-registry.test.ts +105 -0
  62. package/src/registry/function-registry.ts +84 -0
  63. package/src/registry/index.ts +5 -0
  64. package/src/runtime/dev-server.test.ts +60 -0
  65. package/src/runtime/dev-server.ts +104 -52
  66. package/src/runtime/scheduler.test.ts +154 -21
  67. package/src/runtime/scheduler.ts +76 -152
  68. package/src/testing/functions-integration.test.ts +99 -0
  69. package/src/testing/index.ts +7 -0
  70. package/src/testing/setup.ts +45 -0
  71. package/src/testing/test/handler.ts +15 -0
  72. package/src/testing/test/index.ts +7 -0
  73. package/src/testing/types.ts +9 -0
  74. package/src/testing/util.ts +16 -0
  75. package/src/trigger/index.ts +5 -0
  76. package/src/trigger/trigger-registry.test.ts +229 -0
  77. package/src/trigger/trigger-registry.ts +176 -0
  78. package/src/trigger/type/index.ts +8 -0
  79. package/src/trigger/type/subscription-trigger.ts +73 -0
  80. package/src/trigger/type/timer-trigger.ts +44 -0
  81. package/src/trigger/type/webhook-trigger.ts +47 -0
  82. package/src/trigger/type/websocket-trigger.ts +91 -0
  83. package/src/types.ts +101 -0
  84. package/dist/types/src/manifest.d.ts +0 -26
  85. package/dist/types/src/manifest.d.ts.map +0 -1
  86. package/src/manifest.ts +0 -42
package/src/handler.ts CHANGED
@@ -8,31 +8,61 @@ 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): No response?
12
- export interface Response {
13
- status(code: number): Response;
14
- }
11
+ // TODO(burdon): Model after http request. Ref Lambda/OpenFaaS.
12
+ // https://docs.aws.amazon.com/lambda/latest/dg/typescript-handler.html
13
+ // https://www.serverless.com/framework/docs/providers/aws/guide/serverless.yml/#functions
14
+ // https://www.npmjs.com/package/aws-lambda
15
+
16
+ /**
17
+ * Function handler.
18
+ */
19
+ export type FunctionHandler<TData = {}, TMeta = {}> = (params: {
20
+ context: FunctionContext;
21
+ event: FunctionEvent<TData, TMeta>;
22
+ response: FunctionResponse;
23
+ }) => Promise<FunctionResponse | void>;
15
24
 
16
- // TODO(burdon): Limit access to individual space?
25
+ /**
26
+ * Function context.
27
+ */
17
28
  export interface FunctionContext {
29
+ // TODO(burdon): Limit access to individual space.
18
30
  client: Client;
31
+ // TODO(burdon): Replace with storage service abstraction.
19
32
  dataDir?: string;
20
33
  }
21
34
 
22
- // TODO(burdon): Model after http request. Ref Lambda/OpenFaaS.
23
- // https://docs.aws.amazon.com/lambda/latest/dg/typescript-handler.html
24
- export type FunctionHandler<T extends {}> = (params: {
25
- event: T;
26
- context: FunctionContext;
27
- response: Response;
28
- }) => Promise<Response | void>;
35
+ /**
36
+ * Event payload.
37
+ */
38
+ export type FunctionEvent<TData = {}, TMeta = {}> = {
39
+ data: FunctionEventMeta<TMeta> & TData;
40
+ };
41
+
42
+ /**
43
+ * Metadata from trigger.
44
+ */
45
+ export type FunctionEventMeta<TMeta = {}> = {
46
+ meta: TMeta;
47
+ };
48
+
49
+ /**
50
+ * Function response.
51
+ */
52
+ export interface FunctionResponse {
53
+ status(code: number): FunctionResponse;
54
+ }
55
+
56
+ //
57
+ // Subscription utils.
58
+ //
29
59
 
30
- export type FunctionSubscriptionEvent = {
31
- space?: string; // TODO(burdon): Convert to PublicKey.
60
+ export type RawSubscriptionData = {
61
+ spaceKey?: string;
32
62
  objects?: string[];
33
63
  };
34
64
 
35
- export type FunctionSubscriptionEvent2 = {
65
+ export type SubscriptionData = {
36
66
  space?: Space;
37
67
  objects?: EchoReactiveObject<any>[];
38
68
  };
@@ -47,22 +77,22 @@ export type FunctionSubscriptionEvent2 = {
47
77
  *
48
78
  * NOTE: Get space key from devtools or `dx space list --json`
49
79
  */
50
- export const subscriptionHandler = (
51
- handler: FunctionHandler<FunctionSubscriptionEvent2>,
52
- ): FunctionHandler<FunctionSubscriptionEvent> => {
53
- return ({ event, context, ...rest }) => {
80
+ export const subscriptionHandler = <TMeta>(
81
+ handler: FunctionHandler<SubscriptionData, TMeta>,
82
+ ): FunctionHandler<RawSubscriptionData, TMeta> => {
83
+ return ({ event: { data }, context, ...rest }) => {
54
84
  const { client } = context;
55
- const space = event.space ? client.spaces.get(PublicKey.from(event.space)) : undefined;
56
- const objects =
57
- space &&
58
- event.objects?.map<EchoReactiveObject<any> | undefined>((id) => space!.db.getObjectById(id)).filter(nonNullable);
85
+ const space = data.spaceKey ? client.spaces.get(PublicKey.from(data.spaceKey)) : undefined;
86
+ const objects = space
87
+ ? data.objects?.map<EchoReactiveObject<any> | undefined>((id) => space!.db.getObjectById(id)).filter(nonNullable)
88
+ : [];
59
89
 
60
- if (!!event.space && !space) {
61
- log.warn('invalid space', { event });
90
+ if (!!data.spaceKey && !space) {
91
+ log.warn('invalid space', { data });
62
92
  } else {
63
93
  log.info('handler', { space: space?.key.truncate(), objects: objects?.length });
64
94
  }
65
95
 
66
- return handler({ event: { space, objects }, context, ...rest });
96
+ return handler({ event: { data: { ...data, space, objects } }, context, ...rest });
67
97
  };
68
98
  };
package/src/index.ts CHANGED
@@ -3,5 +3,7 @@
3
3
  //
4
4
 
5
5
  export * from './handler';
6
- export * from './manifest';
6
+ export * from './registry';
7
7
  export * from './runtime';
8
+ export * from './trigger';
9
+ export * from './types';
@@ -0,0 +1,105 @@
1
+ //
2
+ // Copyright 2023 DXOS.org
3
+ //
4
+
5
+ import { expect } from 'chai';
6
+
7
+ import { Trigger } from '@dxos/async';
8
+ import { type Client } from '@dxos/client';
9
+ import { TestBuilder } from '@dxos/client/testing';
10
+ import { Context } from '@dxos/context';
11
+ import { Filter } from '@dxos/echo-db';
12
+ import { create } from '@dxos/echo-schema';
13
+ import { describe, test } from '@dxos/test';
14
+ import { range } from '@dxos/util';
15
+
16
+ import { FunctionRegistry } from './function-registry';
17
+ import { createInitializedClients } from '../testing';
18
+ import { FunctionDef, type FunctionManifest } from '../types';
19
+
20
+ const testManifest: FunctionManifest = {
21
+ functions: [
22
+ {
23
+ uri: 'dxos.functions.test/hello',
24
+ route: '/hello',
25
+ handler: 'test',
26
+ },
27
+ ],
28
+ };
29
+
30
+ describe('function registry', () => {
31
+ let ctx: Context;
32
+ let testBuilder: TestBuilder;
33
+ beforeEach(async () => {
34
+ ctx = new Context();
35
+ testBuilder = new TestBuilder();
36
+ });
37
+ afterEach(async () => {
38
+ await ctx.dispose();
39
+ await testBuilder.destroy();
40
+ });
41
+
42
+ describe('register', () => {
43
+ test('creates new functions', async () => {
44
+ const client = (await createInitializedClients(testBuilder))[0];
45
+ const registry = createRegistry(client);
46
+ const space = await client.spaces.create();
47
+ await registry.register(space, testManifest);
48
+ const { objects: definitions } = await space.db.query(Filter.schema(FunctionDef)).run();
49
+ expect(definitions.length).to.eq(1);
50
+ expect(definitions[0].uri).to.eq(testManifest.functions?.[0]?.uri);
51
+ });
52
+
53
+ test('de-duplicates by function URI', async () => {
54
+ const client = (await createInitializedClients(testBuilder))[0];
55
+ const registry = createRegistry(client);
56
+ const space = await client.spaces.create();
57
+ const existing = space.db.add(create(FunctionDef, { ...testManifest.functions![0] }));
58
+ await registry.register(space, testManifest);
59
+ const { objects: definitions } = await space.db.query(Filter.schema(FunctionDef)).run();
60
+ expect(definitions.length).to.eq(1);
61
+ expect(definitions[0].uri).to.eq(existing.uri);
62
+ });
63
+ });
64
+
65
+ describe('onFunctionsRegistered', () => {
66
+ test('called with all registered when opened', async () => {
67
+ const client = (await createInitializedClients(testBuilder))[0];
68
+ const registry = createRegistry(client);
69
+ const space = await client.spaces.create();
70
+ const definitions = range(3, () => create(FunctionDef, { ...testManifest.functions![0] }));
71
+ definitions.forEach((def) => space.db.add(def));
72
+
73
+ const functionRegistered = new Trigger<FunctionDef[]>();
74
+ registry.onFunctionsRegistered.on((fn) => {
75
+ functionRegistered.wake(fn.newFunctions);
76
+ });
77
+ void registry.open(ctx);
78
+ const functions = await functionRegistered.wait();
79
+ const expected = definitions.map((def) => def.uri).sort();
80
+ expect(functions.map((fn) => fn.uri).sort()).to.deep.eq(expected);
81
+ });
82
+
83
+ test('called when a new functions is added', async () => {
84
+ const client = (await createInitializedClients(testBuilder))[0];
85
+ const registry = createRegistry(client);
86
+ const space = await client.spaces.create();
87
+
88
+ const functionRegistered = new Trigger<FunctionDef>();
89
+ registry.onFunctionsRegistered.on((fn) => {
90
+ expect(fn.newFunctions.length).to.eq(1);
91
+ functionRegistered.wake(fn.newFunctions[0]);
92
+ });
93
+ await registry.open(ctx);
94
+ await registry.register(space, testManifest);
95
+ const registered = await functionRegistered.wait();
96
+ expect(registered.uri).to.eq(testManifest.functions![0].uri);
97
+ });
98
+ });
99
+
100
+ const createRegistry = (client: Client) => {
101
+ const registry = new FunctionRegistry(client);
102
+ ctx.onDispose(() => registry.close());
103
+ return registry;
104
+ };
105
+ });
@@ -0,0 +1,84 @@
1
+ //
2
+ // Copyright 2024 DXOS.org
3
+ //
4
+
5
+ import { Event } from '@dxos/async';
6
+ import { type Client } from '@dxos/client';
7
+ import { create, Filter, type Space } from '@dxos/client/echo';
8
+ import { type Context, Resource } from '@dxos/context';
9
+ import { PublicKey } from '@dxos/keys';
10
+ import { ComplexMap } from '@dxos/util';
11
+
12
+ import { FunctionDef, type FunctionManifest } from '../types';
13
+
14
+ export type FunctionsRegisteredEvent = {
15
+ space: Space;
16
+ newFunctions: FunctionDef[];
17
+ };
18
+
19
+ export class FunctionRegistry extends Resource {
20
+ private readonly _functionBySpaceKey = new ComplexMap<PublicKey, FunctionDef[]>(PublicKey.hash);
21
+
22
+ public readonly onFunctionsRegistered = new Event<FunctionsRegisteredEvent>();
23
+
24
+ constructor(private readonly _client: Client) {
25
+ super();
26
+ }
27
+
28
+ public getFunctions(space: Space): FunctionDef[] {
29
+ return this._functionBySpaceKey.get(space.key) ?? [];
30
+ }
31
+
32
+ /**
33
+ * The method loads function definitions from the manifest into the space.
34
+ * We first load all the definitions from the space to deduplicate by functionId.
35
+ */
36
+ // TODO(burdon): This should not be space specific (they are static for the agent).
37
+ public async register(space: Space, manifest: FunctionManifest): Promise<void> {
38
+ if (!manifest.functions?.length) {
39
+ return;
40
+ }
41
+ if (!space.db.graph.runtimeSchemaRegistry.hasSchema(FunctionDef)) {
42
+ space.db.graph.runtimeSchemaRegistry.registerSchema(FunctionDef);
43
+ }
44
+
45
+ const { objects: existingDefinitions } = await space.db.query(Filter.schema(FunctionDef)).run();
46
+ const newDefinitions = getNewDefinitions(manifest.functions, existingDefinitions);
47
+ const reactiveObjects = newDefinitions.map((template) => create(FunctionDef, { ...template }));
48
+ reactiveObjects.forEach((obj) => space.db.add(obj));
49
+ }
50
+
51
+ protected override async _open(): Promise<void> {
52
+ const spaceListSubscription = this._client.spaces.subscribe(async (spaces) => {
53
+ for (const space of spaces) {
54
+ if (this._functionBySpaceKey.has(space.key)) {
55
+ continue;
56
+ }
57
+ const registered: FunctionDef[] = [];
58
+ this._functionBySpaceKey.set(space.key, registered);
59
+ await space.waitUntilReady();
60
+ if (this._ctx.disposed) {
61
+ break;
62
+ }
63
+
64
+ const functionsSubscription = space.db.query(Filter.schema(FunctionDef)).subscribe((definitions) => {
65
+ const newFunctions = getNewDefinitions(definitions.objects, registered);
66
+ if (newFunctions.length > 0) {
67
+ registered.push(...newFunctions);
68
+ this.onFunctionsRegistered.emit({ space, newFunctions });
69
+ }
70
+ });
71
+ this._ctx.onDispose(functionsSubscription);
72
+ }
73
+ });
74
+ this._ctx.onDispose(() => spaceListSubscription.unsubscribe());
75
+ }
76
+
77
+ protected override async _close(_: Context): Promise<void> {
78
+ this._functionBySpaceKey.clear();
79
+ }
80
+ }
81
+
82
+ const getNewDefinitions = <T extends { uri: string }>(candidateList: T[], existing: FunctionDef[]): T[] => {
83
+ return candidateList.filter((candidate) => existing.find((def) => def.uri === candidate.uri) == null);
84
+ };
@@ -0,0 +1,5 @@
1
+ //
2
+ // Copyright 2024 DXOS.org
3
+ //
4
+
5
+ export * from './function-registry';
@@ -0,0 +1,60 @@
1
+ //
2
+ // Copyright 2023 DXOS.org
3
+ //
4
+
5
+ import { expect } from 'chai';
6
+ import path from 'path';
7
+
8
+ import { waitForCondition } from '@dxos/async';
9
+ import { type Client } from '@dxos/client';
10
+ import { TestBuilder } from '@dxos/client/testing';
11
+ import { describe, test } from '@dxos/test';
12
+
13
+ import { DevServer } from './dev-server';
14
+ import { FunctionRegistry } from '../registry';
15
+ import { createFunctionRuntime } from '../testing';
16
+ import { type FunctionManifest } from '../types';
17
+
18
+ describe('dev server', () => {
19
+ let client: Client;
20
+ let testBuilder: TestBuilder;
21
+ before(async () => {
22
+ testBuilder = new TestBuilder();
23
+ client = await createFunctionRuntime(testBuilder);
24
+ expect(client.services.services.FunctionRegistryService).to.exist;
25
+ });
26
+
27
+ after(async () => {
28
+ await testBuilder.destroy();
29
+ });
30
+
31
+ test('start/stop', async () => {
32
+ const manifest: FunctionManifest = {
33
+ functions: [
34
+ {
35
+ uri: 'example.com/function/test',
36
+ route: 'test',
37
+ handler: 'test',
38
+ },
39
+ ],
40
+ };
41
+
42
+ const registry = new FunctionRegistry(client);
43
+ const server = new DevServer(client, registry, {
44
+ baseDir: path.join(__dirname, '../testing'),
45
+ });
46
+ const space = await client.spaces.create();
47
+ await registry.register(space, manifest);
48
+ await server.start();
49
+
50
+ // TODO(burdon): Doesn't shut down cleanly.
51
+ // Error: invariant violation [this._client.services.services.FunctionRegistryService]
52
+ testBuilder.ctx.onDispose(() => server.stop());
53
+ expect(server).to.exist;
54
+
55
+ await waitForCondition({ condition: () => server.functions.length > 0 });
56
+
57
+ await server.invoke('test', {});
58
+ expect(server.stats.seq).to.eq(1);
59
+ });
60
+ });
@@ -7,18 +7,19 @@ import { getPort } from 'get-port-please';
7
7
  import type http from 'http';
8
8
  import { join } from 'node:path';
9
9
 
10
- import { Trigger } from '@dxos/async';
10
+ import { Event, Trigger } from '@dxos/async';
11
11
  import { type Client } from '@dxos/client';
12
+ import { Context } from '@dxos/context';
12
13
  import { invariant } from '@dxos/invariant';
13
14
  import { log } from '@dxos/log';
14
15
 
15
- import { type FunctionContext, type FunctionHandler, type Response } from '../handler';
16
- import { type FunctionDef, type FunctionManifest } from '../manifest';
16
+ import { type FunctionContext, type FunctionEvent, type FunctionHandler, type FunctionResponse } from '../handler';
17
+ import { type FunctionRegistry } from '../registry';
18
+ import { type FunctionDef } from '../types';
17
19
 
18
20
  export type DevServerOptions = {
21
+ baseDir: string;
19
22
  port?: number;
20
- directory: string;
21
- manifest: FunctionManifest;
22
23
  reload?: boolean;
23
24
  dataDir?: string;
24
25
  };
@@ -27,20 +28,37 @@ export type DevServerOptions = {
27
28
  * Functions dev server provides a local HTTP server for testing functions.
28
29
  */
29
30
  export class DevServer {
31
+ private _ctx = createContext();
32
+
30
33
  // Function handlers indexed by name (URL path).
31
34
  private readonly _handlers: Record<string, { def: FunctionDef; handler: FunctionHandler<any> }> = {};
32
35
 
33
36
  private _server?: http.Server;
34
37
  private _port?: number;
35
- private _registrationId?: string;
38
+ private _functionServiceRegistration?: string;
36
39
  private _proxy?: string;
37
40
  private _seq = 0;
38
41
 
42
+ public readonly update = new Event<number>();
43
+
39
44
  // prettier-ignore
40
45
  constructor(
41
46
  private readonly _client: Client,
47
+ private readonly _functionsRegistry: FunctionRegistry,
42
48
  private readonly _options: DevServerOptions,
43
- ) {}
49
+ ) {
50
+ this._functionsRegistry.onFunctionsRegistered.on(async ({ newFunctions }) => {
51
+ newFunctions.forEach((def) => this._load(def));
52
+ await this._safeUpdateRegistration();
53
+ log('new functions loaded', { newFunctions });
54
+ });
55
+ }
56
+
57
+ get stats() {
58
+ return {
59
+ seq: this._seq,
60
+ };
61
+ }
44
62
 
45
63
  get endpoint() {
46
64
  invariant(this._port);
@@ -55,30 +73,26 @@ export class DevServer {
55
73
  return Object.values(this._handlers);
56
74
  }
57
75
 
58
- async initialize() {
59
- for (const def of this._options.manifest.functions) {
60
- try {
61
- await this._load(def);
62
- } catch (err) {
63
- log.error('parsing function (check manifest)', err);
64
- }
65
- }
66
- }
67
-
68
76
  async start() {
77
+ invariant(!this._server);
78
+ log.info('starting...');
79
+ this._ctx = createContext();
80
+
81
+ // TODO(burdon): Move to hono.
69
82
  const app = express();
70
83
  app.use(express.json());
71
84
 
72
- app.post('/:name', async (req, res) => {
73
- const { name } = req.params;
85
+ app.post('/:path', async (req, res) => {
86
+ const { path } = req.params;
74
87
  try {
75
- log.info('calling', { name });
88
+ log.info('calling', { path });
76
89
  if (this._options.reload) {
77
- const { def } = this._handlers[name];
90
+ const { def } = this._handlers['/' + path];
78
91
  await this._load(def, true);
79
92
  }
80
93
 
81
- res.statusCode = await this._invoke(name, req.body);
94
+ // TODO(burdon): Get function context.
95
+ res.statusCode = await this.invoke('/' + path, req.body);
82
96
  res.end();
83
97
  } catch (err: any) {
84
98
  log.catch(err);
@@ -94,72 +108,110 @@ export class DevServer {
94
108
  // Register functions.
95
109
  const { registrationId, endpoint } = await this._client.services.services.FunctionRegistryService!.register({
96
110
  endpoint: this.endpoint,
97
- functions: this.functions.map(({ def: { name } }) => ({ name })),
98
111
  });
99
112
 
100
- log.info('registered', { registrationId, endpoint });
101
- this._registrationId = registrationId;
113
+ log.info('registered', { endpoint });
102
114
  this._proxy = endpoint;
115
+ this._functionServiceRegistration = registrationId;
116
+
117
+ // Open after registration, so that it can be updated with the list of function definitions.
118
+ await this._functionsRegistry.open(this._ctx);
103
119
  } catch (err: any) {
104
120
  await this.stop();
105
121
  throw new Error('FunctionRegistryService not available (check plugin is configured).');
106
122
  }
123
+
124
+ log.info('started', { port: this._port });
107
125
  }
108
126
 
109
127
  async stop() {
128
+ invariant(this._server);
129
+ log.info('stopping...');
130
+
110
131
  const trigger = new Trigger();
111
- this._server?.close(async () => {
112
- if (this._registrationId) {
113
- await this._client.services.services.FunctionRegistryService!.unregister({
114
- registrationId: this._registrationId,
115
- });
132
+ this._server.close(async () => {
133
+ log.info('server stopped');
134
+ try {
135
+ if (this._functionServiceRegistration) {
136
+ invariant(this._client.services.services.FunctionRegistryService);
137
+ await this._client.services.services.FunctionRegistryService.unregister({
138
+ registrationId: this._functionServiceRegistration,
139
+ });
140
+
141
+ log.info('unregistered', { registrationId: this._functionServiceRegistration });
142
+ this._functionServiceRegistration = undefined;
143
+ this._proxy = undefined;
144
+ }
116
145
 
117
- log.info('unregistered', { registrationId: this._registrationId });
118
- this._registrationId = undefined;
119
- this._proxy = undefined;
146
+ trigger.wake();
147
+ } catch (err) {
148
+ trigger.throw(err as Error);
120
149
  }
121
-
122
- trigger.wake();
123
150
  });
124
151
 
125
152
  await trigger.wait();
126
153
  this._port = undefined;
127
154
  this._server = undefined;
155
+ log.info('stopped');
128
156
  }
129
157
 
130
158
  /**
131
159
  * Load function.
132
160
  */
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 });
161
+ private async _load(def: FunctionDef, force = false) {
162
+ const { uri, route, handler } = def;
163
+ const filePath = join(this._options.baseDir, handler);
164
+ log.info('loading', { uri, force });
137
165
 
138
166
  // Remove from cache.
139
- if (flush) {
167
+ if (force) {
140
168
  Object.keys(require.cache)
141
- .filter((key) => key.startsWith(path))
142
- .forEach((key) => delete require.cache[key]);
169
+ .filter((key) => key.startsWith(filePath))
170
+ .forEach((key) => {
171
+ delete require.cache[key];
172
+ });
143
173
  }
144
174
 
175
+ // TODO(burdon): Import types.
145
176
  // eslint-disable-next-line @typescript-eslint/no-var-requires
146
- const module = require(path);
177
+ const module = require(filePath);
147
178
  if (typeof module.default !== 'function') {
148
- throw new Error(`Handler must export default function: ${id}`);
179
+ throw new Error(`Handler must export default function: ${uri}`);
149
180
  }
150
181
 
151
- this._handlers[name] = { def, handler: module.default };
182
+ this._handlers[route] = { def, handler: module.default };
183
+ }
184
+
185
+ private async _safeUpdateRegistration(): Promise<void> {
186
+ invariant(this._functionServiceRegistration);
187
+ try {
188
+ await this._client.services.services.FunctionRegistryService!.updateRegistration({
189
+ registrationId: this._functionServiceRegistration,
190
+ functions: this.functions.map(({ def: { id, route } }) => ({ id, route })),
191
+ });
192
+ } catch (e) {
193
+ log.catch(e);
194
+ }
152
195
  }
153
196
 
154
197
  /**
155
- * Invoke function handler.
198
+ * Invoke function.
156
199
  */
157
- private async _invoke(name: string, event: any) {
200
+ public async invoke(path: string, data: any): Promise<number> {
158
201
  const seq = ++this._seq;
159
202
  const now = Date.now();
160
203
 
161
- log.info('req', { seq, name });
162
- const { handler } = this._handlers[name];
204
+ log.info('req', { seq, path });
205
+ const statusCode = await this._invoke(path, { data });
206
+
207
+ log.info('res', { seq, path, statusCode, duration: Date.now() - now });
208
+ this.update.emit(statusCode);
209
+ return statusCode;
210
+ }
211
+
212
+ private async _invoke(path: string, event: FunctionEvent) {
213
+ const { handler } = this._handlers[path] ?? {};
214
+ invariant(handler, `invalid path: ${path}`);
163
215
 
164
216
  const context: FunctionContext = {
165
217
  client: this._client,
@@ -167,7 +219,7 @@ export class DevServer {
167
219
  };
168
220
 
169
221
  let statusCode = 200;
170
- const response: Response = {
222
+ const response: FunctionResponse = {
171
223
  status: (code: number) => {
172
224
  statusCode = code;
173
225
  return response;
@@ -175,8 +227,8 @@ export class DevServer {
175
227
  };
176
228
 
177
229
  await handler({ context, event, response });
178
- log.info('res', { seq, name, statusCode, duration: Date.now() - now });
179
-
180
230
  return statusCode;
181
231
  }
182
232
  }
233
+
234
+ const createContext = () => new Context({ name: 'DevServer' });