@dxos/functions 0.5.3-main.43e79dd → 0.5.3-main.495a683

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 (100) hide show
  1. package/dist/lib/browser/chunk-366QG6IX.mjs +81 -0
  2. package/dist/lib/browser/chunk-366QG6IX.mjs.map +7 -0
  3. package/dist/lib/browser/index.mjs +849 -304
  4. package/dist/lib/browser/index.mjs.map +4 -4
  5. package/dist/lib/browser/meta.json +1 -1
  6. package/dist/lib/browser/types.mjs +12 -0
  7. package/dist/lib/browser/types.mjs.map +7 -0
  8. package/dist/lib/node/chunk-3VSJ57ZZ.cjs +97 -0
  9. package/dist/lib/node/chunk-3VSJ57ZZ.cjs.map +7 -0
  10. package/dist/lib/node/index.cjs +831 -297
  11. package/dist/lib/node/index.cjs.map +4 -4
  12. package/dist/lib/node/meta.json +1 -1
  13. package/dist/lib/node/types.cjs +33 -0
  14. package/dist/lib/node/types.cjs.map +7 -0
  15. package/dist/types/src/function/function-registry.d.ts +24 -0
  16. package/dist/types/src/function/function-registry.d.ts.map +1 -0
  17. package/dist/types/src/function/function-registry.test.d.ts +2 -0
  18. package/dist/types/src/function/function-registry.test.d.ts.map +1 -0
  19. package/dist/types/src/function/index.d.ts +2 -0
  20. package/dist/types/src/function/index.d.ts.map +1 -0
  21. package/dist/types/src/handler.d.ts +33 -12
  22. package/dist/types/src/handler.d.ts.map +1 -1
  23. package/dist/types/src/index.d.ts +3 -1
  24. package/dist/types/src/index.d.ts.map +1 -1
  25. package/dist/types/src/runtime/dev-server.d.ts +15 -7
  26. package/dist/types/src/runtime/dev-server.d.ts.map +1 -1
  27. package/dist/types/src/runtime/dev-server.test.d.ts +2 -0
  28. package/dist/types/src/runtime/dev-server.test.d.ts.map +1 -0
  29. package/dist/types/src/runtime/scheduler.d.ts +15 -15
  30. package/dist/types/src/runtime/scheduler.d.ts.map +1 -1
  31. package/dist/types/src/testing/functions-integration.test.d.ts +2 -0
  32. package/dist/types/src/testing/functions-integration.test.d.ts.map +1 -0
  33. package/dist/types/src/testing/index.d.ts +4 -0
  34. package/dist/types/src/testing/index.d.ts.map +1 -0
  35. package/dist/types/src/testing/setup.d.ts +5 -0
  36. package/dist/types/src/testing/setup.d.ts.map +1 -0
  37. package/dist/types/src/testing/test/handler.d.ts +4 -0
  38. package/dist/types/src/testing/test/handler.d.ts.map +1 -0
  39. package/dist/types/src/testing/test/index.d.ts +3 -0
  40. package/dist/types/src/testing/test/index.d.ts.map +1 -0
  41. package/dist/types/src/testing/types.d.ts +9 -0
  42. package/dist/types/src/testing/types.d.ts.map +1 -0
  43. package/dist/types/src/testing/util.d.ts +3 -0
  44. package/dist/types/src/testing/util.d.ts.map +1 -0
  45. package/dist/types/src/trigger/index.d.ts +2 -0
  46. package/dist/types/src/trigger/index.d.ts.map +1 -0
  47. package/dist/types/src/trigger/trigger-registry.d.ts +40 -0
  48. package/dist/types/src/trigger/trigger-registry.d.ts.map +1 -0
  49. package/dist/types/src/trigger/trigger-registry.test.d.ts +2 -0
  50. package/dist/types/src/trigger/trigger-registry.test.d.ts.map +1 -0
  51. package/dist/types/src/trigger/type/index.d.ts +5 -0
  52. package/dist/types/src/trigger/type/index.d.ts.map +1 -0
  53. package/dist/types/src/trigger/type/subscription-trigger.d.ts +4 -0
  54. package/dist/types/src/trigger/type/subscription-trigger.d.ts.map +1 -0
  55. package/dist/types/src/trigger/type/timer-trigger.d.ts +4 -0
  56. package/dist/types/src/trigger/type/timer-trigger.d.ts.map +1 -0
  57. package/dist/types/src/trigger/type/webhook-trigger.d.ts +4 -0
  58. package/dist/types/src/trigger/type/webhook-trigger.d.ts.map +1 -0
  59. package/dist/types/src/trigger/type/websocket-trigger.d.ts +13 -0
  60. package/dist/types/src/trigger/type/websocket-trigger.d.ts.map +1 -0
  61. package/dist/types/src/types.d.ts +202 -0
  62. package/dist/types/src/types.d.ts.map +1 -0
  63. package/dist/types/src/util.d.ts +15 -0
  64. package/dist/types/src/util.d.ts.map +1 -0
  65. package/dist/types/src/util.test.d.ts +2 -0
  66. package/dist/types/src/util.test.d.ts.map +1 -0
  67. package/dist/types/tools/schema.d.ts +2 -0
  68. package/dist/types/tools/schema.d.ts.map +1 -0
  69. package/package.json +38 -13
  70. package/schema/functions.json +206 -0
  71. package/src/function/function-registry.test.ts +105 -0
  72. package/src/function/function-registry.ts +90 -0
  73. package/src/function/index.ts +5 -0
  74. package/src/handler.ts +56 -26
  75. package/src/index.ts +3 -1
  76. package/src/runtime/dev-server.test.ts +60 -0
  77. package/src/runtime/dev-server.ts +104 -53
  78. package/src/runtime/scheduler.test.ts +154 -21
  79. package/src/runtime/scheduler.ts +83 -151
  80. package/src/testing/functions-integration.test.ts +99 -0
  81. package/src/testing/index.ts +7 -0
  82. package/src/testing/setup.ts +45 -0
  83. package/src/testing/test/handler.ts +15 -0
  84. package/src/testing/test/index.ts +7 -0
  85. package/src/testing/types.ts +9 -0
  86. package/src/testing/util.ts +16 -0
  87. package/src/trigger/index.ts +5 -0
  88. package/src/trigger/trigger-registry.test.ts +255 -0
  89. package/src/trigger/trigger-registry.ts +189 -0
  90. package/src/trigger/type/index.ts +8 -0
  91. package/src/trigger/type/subscription-trigger.ts +80 -0
  92. package/src/trigger/type/timer-trigger.ts +44 -0
  93. package/src/trigger/type/webhook-trigger.ts +47 -0
  94. package/src/trigger/type/websocket-trigger.ts +91 -0
  95. package/src/types.ts +103 -0
  96. package/src/util.test.ts +43 -0
  97. package/src/util.ts +48 -0
  98. package/dist/types/src/manifest.d.ts +0 -26
  99. package/dist/types/src/manifest.d.ts.map +0 -1
  100. package/src/manifest.ts +0 -42
@@ -0,0 +1,91 @@
1
+ //
2
+ // Copyright 2024 DXOS.org
3
+ //
4
+
5
+ import WebSocket from 'ws';
6
+
7
+ import { sleep, Trigger } from '@dxos/async';
8
+ import { type Context } from '@dxos/context';
9
+ import { log } from '@dxos/log';
10
+
11
+ import { type WebsocketTrigger } from '../../types';
12
+ import { type TriggerCallback, type TriggerContext, type TriggerFactory } from '../trigger-registry';
13
+
14
+ interface WebsocketTriggerOptions {
15
+ retryDelay: number;
16
+ maxAttempts: number;
17
+ }
18
+
19
+ /**
20
+ * Websocket.
21
+ * NOTE: The port must be unique, so the same hook cannot be used for multiple spaces.
22
+ */
23
+ export const createWebsocketTrigger: TriggerFactory<WebsocketTrigger, WebsocketTriggerOptions> = async (
24
+ ctx: Context,
25
+ triggerCtx: TriggerContext,
26
+ spec: WebsocketTrigger,
27
+ callback: TriggerCallback,
28
+ options: WebsocketTriggerOptions = { retryDelay: 2, maxAttempts: 5 },
29
+ ) => {
30
+ const { url, init } = spec;
31
+
32
+ let ws: WebSocket;
33
+ for (let attempt = 1; attempt <= options.maxAttempts; attempt++) {
34
+ const open = new Trigger<boolean>();
35
+
36
+ ws = new WebSocket(url);
37
+ Object.assign(ws, {
38
+ onopen: () => {
39
+ log.info('opened', { url });
40
+ if (spec.init) {
41
+ ws.send(new TextEncoder().encode(JSON.stringify(init)));
42
+ }
43
+
44
+ open.wake(true);
45
+ },
46
+
47
+ onclose: (event) => {
48
+ log.info('closed', { url, code: event.code });
49
+ // Reconnect if server closes (e.g., CF restart).
50
+ // https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent/code
51
+ if (event.code === 1006) {
52
+ setTimeout(async () => {
53
+ log.info(`reconnecting in ${options.retryDelay}s...`, { url });
54
+ await createWebsocketTrigger(ctx, triggerCtx, spec, callback, options);
55
+ }, options.retryDelay * 1_000);
56
+ }
57
+
58
+ open.wake(false);
59
+ },
60
+
61
+ onerror: (event) => {
62
+ log.catch(event.error, { url });
63
+ },
64
+
65
+ onmessage: async (event) => {
66
+ try {
67
+ log.info('message');
68
+ const data = JSON.parse(new TextDecoder().decode(event.data as Uint8Array));
69
+ await callback({ data });
70
+ } catch (err) {
71
+ log.catch(err, { url });
72
+ }
73
+ },
74
+ } satisfies Partial<WebSocket>);
75
+
76
+ const isOpen = await open.wait();
77
+ if (isOpen) {
78
+ break;
79
+ } else {
80
+ const wait = Math.pow(attempt, 2) * options.retryDelay;
81
+ if (attempt < options.maxAttempts) {
82
+ log.warn(`failed to connect; trying again in ${wait}s`, { attempt });
83
+ await sleep(wait * 1_000);
84
+ }
85
+ }
86
+ }
87
+
88
+ ctx.onDispose(() => {
89
+ ws?.close();
90
+ });
91
+ };
package/src/types.ts ADDED
@@ -0,0 +1,103 @@
1
+ //
2
+ // Copyright 2023 DXOS.org
3
+ //
4
+
5
+ import { RawObject, S, TypedObject } from '@dxos/echo-schema';
6
+
7
+ /**
8
+ * Type discriminator for TriggerSpec.
9
+ * Every spec has a type field of type FunctionTriggerType that we can use to understand which
10
+ * type we're working with.
11
+ * https://www.typescriptlang.org/docs/handbook/2/narrowing.html#discriminated-unions
12
+ */
13
+ export type FunctionTriggerType = 'subscription' | 'timer' | 'webhook' | 'websocket';
14
+
15
+ const SubscriptionTriggerSchema = S.struct({
16
+ type: S.literal('subscription'),
17
+ // TODO(burdon): Define query DSL (from ECHO).
18
+ filter: S.array(
19
+ S.struct({
20
+ type: S.string,
21
+ props: S.optional(S.record(S.string, S.any)),
22
+ }),
23
+ ),
24
+ options: S.optional(
25
+ S.struct({
26
+ // Watch changes to object (not just creation).
27
+ deep: S.optional(S.boolean),
28
+ // Debounce changes (delay in ms).
29
+ delay: S.optional(S.number),
30
+ }),
31
+ ),
32
+ });
33
+
34
+ export type SubscriptionTrigger = S.Schema.Type<typeof SubscriptionTriggerSchema>;
35
+
36
+ const TimerTriggerSchema = S.struct({
37
+ type: S.literal('timer'),
38
+ cron: S.string,
39
+ });
40
+
41
+ export type TimerTrigger = S.Schema.Type<typeof TimerTriggerSchema>;
42
+
43
+ const WebhookTriggerSchema = S.mutable(
44
+ S.struct({
45
+ type: S.literal('webhook'),
46
+ method: S.string,
47
+ // Assigned port.
48
+ port: S.optional(S.number),
49
+ }),
50
+ );
51
+
52
+ export type WebhookTrigger = S.Schema.Type<typeof WebhookTriggerSchema>;
53
+
54
+ const WebsocketTriggerSchema = S.struct({
55
+ type: S.literal('websocket'),
56
+ url: S.string,
57
+ init: S.optional(S.record(S.string, S.any)),
58
+ });
59
+
60
+ export type WebsocketTrigger = S.Schema.Type<typeof WebsocketTriggerSchema>;
61
+
62
+ const TriggerSpecSchema = S.union(
63
+ TimerTriggerSchema,
64
+ WebhookTriggerSchema,
65
+ WebsocketTriggerSchema,
66
+ SubscriptionTriggerSchema,
67
+ );
68
+
69
+ export type TriggerSpec = TimerTrigger | WebhookTrigger | WebsocketTrigger | SubscriptionTrigger;
70
+
71
+ /**
72
+ * Function definition.
73
+ */
74
+ export class FunctionDef extends TypedObject({
75
+ typename: 'dxos.org/type/FunctionDef',
76
+ version: '0.1.0',
77
+ })({
78
+ uri: S.string,
79
+ description: S.optional(S.string),
80
+ route: S.string,
81
+ // TODO(burdon): NPM/GitHub/Docker/CF URL?
82
+ handler: S.string,
83
+ }) {}
84
+
85
+ export class FunctionTrigger extends TypedObject({
86
+ typename: 'dxos.org/type/FunctionTrigger',
87
+ version: '0.1.0',
88
+ })({
89
+ function: S.string.pipe(S.description('Function URI.')),
90
+ // Context is merged into the event data passed to the function.
91
+ meta: S.optional(S.object),
92
+ spec: TriggerSpecSchema,
93
+ }) {}
94
+
95
+ /**
96
+ * Function manifest file.
97
+ */
98
+ export const FunctionManifestSchema = S.struct({
99
+ functions: S.optional(S.mutable(S.array(RawObject(FunctionDef)))),
100
+ triggers: S.optional(S.mutable(S.array(RawObject(FunctionTrigger)))),
101
+ });
102
+
103
+ export type FunctionManifest = S.Schema.Type<typeof FunctionManifestSchema>;
@@ -0,0 +1,43 @@
1
+ //
2
+ // Copyright 2024 DXOS.org
3
+ //
4
+
5
+ import { expect } from 'chai';
6
+
7
+ import { describe, test } from '@dxos/test';
8
+
9
+ import { diff, intersection } from './util';
10
+
11
+ describe('diff', () => {
12
+ test('returns the difference between two sets', () => {
13
+ {
14
+ const { added, updated, removed } = diff<number>([], [], (a, b) => a === b);
15
+ expect(added).to.deep.eq([]);
16
+ expect(updated).to.deep.eq([]);
17
+ expect(removed).to.deep.eq([]);
18
+ }
19
+ {
20
+ const previous = [1, 2, 3];
21
+ const next = [2, 3, 4];
22
+ const { added, updated, removed } = diff(previous, next, (a, b) => a === b);
23
+ expect(added).to.deep.eq([4]);
24
+ expect(updated).to.deep.eq([2, 3]);
25
+ expect(removed).to.deep.eq([1]);
26
+ }
27
+ {
28
+ const previous = [{ x: 1 }, { x: 2 }, { x: 3 }];
29
+ const next = [{ x: 2 }, { x: 3 }, { x: 4 }];
30
+ const { added, updated, removed } = diff(previous, next, (a, b) => a.x === b.x);
31
+ expect(added).to.deep.eq([{ x: 4 }]);
32
+ expect(updated).to.deep.eq([{ x: 2 }, { x: 3 }]);
33
+ expect(removed).to.deep.eq([{ x: 1 }]);
34
+ }
35
+ });
36
+
37
+ test('intersection', () => {
38
+ expect(intersection([1, 2, 3], [2, 3, 4], (a, b) => a === b)).to.deep.eq([2, 3]);
39
+ expect(
40
+ intersection([{ x: 1 }, { x: 2 }, { x: 3 }], [{ x: 2 }, { x: 3 }, { x: 4 }], (a, b) => a.x === b.x),
41
+ ).to.deep.eq([{ x: 2 }, { x: 3 }]);
42
+ });
43
+ });
package/src/util.ts ADDED
@@ -0,0 +1,48 @@
1
+ //
2
+ // Copyright 2024 DXOS.org
3
+ //
4
+
5
+ export type Comparator<A, B = A> = (a: A, b: B) => boolean;
6
+
7
+ export type DiffResult<A, B = A> = {
8
+ added: B[];
9
+ updated: A[];
10
+ removed: A[];
11
+ };
12
+
13
+ /**
14
+ *
15
+ * @param previous
16
+ * @param next
17
+ * @param comparator
18
+ */
19
+ // TODO(burdon): Factor out.
20
+ export const diff = <A, B = A>(
21
+ previous: readonly A[],
22
+ next: readonly B[],
23
+ comparator: Comparator<A, B>,
24
+ ): DiffResult<A, B> => {
25
+ const remaining = [...previous];
26
+ const result: DiffResult<A, B> = {
27
+ added: [],
28
+ updated: [],
29
+ removed: remaining,
30
+ };
31
+
32
+ // TODO(burdon): Mark and sweep.
33
+ for (const object of next) {
34
+ const index = remaining.findIndex((item) => comparator(item, object));
35
+ if (index === -1) {
36
+ result.added.push(object);
37
+ } else {
38
+ result.updated.push(remaining[index]);
39
+ remaining.splice(index, 1);
40
+ }
41
+ }
42
+
43
+ return result;
44
+ };
45
+
46
+ // TODO(burdon): Factor out.
47
+ export const intersection = <A, B = A>(a: A[], b: B[], comparator: Comparator<A, B>): A[] =>
48
+ a.filter((a) => b.find((b) => comparator(a, b)) !== undefined);
@@ -1,26 +0,0 @@
1
- export type FunctionDef = {
2
- id: string;
3
- name: string;
4
- handler: string;
5
- description?: string;
6
- };
7
- export type TriggerSubscription = {
8
- type: string;
9
- spaceKey: string;
10
- props?: Record<string, any>;
11
- deep?: boolean;
12
- delay?: number;
13
- };
14
- export type FunctionTrigger = {
15
- function: string;
16
- schedule?: string;
17
- subscriptions?: TriggerSubscription[];
18
- };
19
- /**
20
- * Function manifest file.
21
- */
22
- export type FunctionManifest = {
23
- functions: FunctionDef[];
24
- triggers: FunctionTrigger[];
25
- };
26
- //# sourceMappingURL=manifest.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"manifest.d.ts","sourceRoot":"","sources":["../../../src/manifest.ts"],"names":[],"mappings":"AAOA,MAAM,MAAM,WAAW,GAAG;IAExB,EAAE,EAAE,MAAM,CAAC;IAEX,IAAI,EAAE,MAAM,CAAC;IAEb,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB,CAAC;AAGF,MAAM,MAAM,mBAAmB,GAAG;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAC5B,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB,CAAC;AAKF,MAAM,MAAM,eAAe,GAAG;IAC5B,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,aAAa,CAAC,EAAE,mBAAmB,EAAE,CAAC;CACvC,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,gBAAgB,GAAG;IAC7B,SAAS,EAAE,WAAW,EAAE,CAAC;IACzB,QAAQ,EAAE,eAAe,EAAE,CAAC;CAC7B,CAAC"}
package/src/manifest.ts DELETED
@@ -1,42 +0,0 @@
1
- //
2
- // Copyright 2023 DXOS.org
3
- //
4
-
5
- // Lambda-like function definitions.
6
- // See: https://www.serverless.com/framework/docs/providers/aws/guide/serverless.yml/#functions
7
-
8
- export type FunctionDef = {
9
- // FQ function name.
10
- id: string;
11
- // URL path.
12
- name: string;
13
- // File path of handler.
14
- handler: string;
15
- description?: string;
16
- };
17
-
18
- // TODO(burdon): Query DSL.
19
- export type TriggerSubscription = {
20
- type: string;
21
- spaceKey: string;
22
- props?: Record<string, any>;
23
- deep?: boolean; // Watch changes to object (not just creation).
24
- delay?: number;
25
- };
26
-
27
- // TODO(burdon): Generalize binding.
28
- // https://www.npmjs.com/package/aws-lambda
29
- // https://docs.aws.amazon.com/lambda/latest/dg/typescript-handler.html
30
- export type FunctionTrigger = {
31
- function: string;
32
- schedule?: string;
33
- subscriptions?: TriggerSubscription[];
34
- };
35
-
36
- /**
37
- * Function manifest file.
38
- */
39
- export type FunctionManifest = {
40
- functions: FunctionDef[];
41
- triggers: FunctionTrigger[];
42
- };