@dxos/functions-testing 0.8.4-main.03d5cd7b56

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 (45) hide show
  1. package/LICENSE +8 -0
  2. package/README.md +21 -0
  3. package/dist/lib/node-esm/index.mjs +2 -0
  4. package/dist/lib/node-esm/index.mjs.map +7 -0
  5. package/dist/lib/node-esm/meta.json +1 -0
  6. package/dist/lib/node-esm/testing/index.mjs +115 -0
  7. package/dist/lib/node-esm/testing/index.mjs.map +7 -0
  8. package/dist/types/src/bundle.test.d.ts +2 -0
  9. package/dist/types/src/bundle.test.d.ts.map +1 -0
  10. package/dist/types/src/cpu-limit.test.d.ts +2 -0
  11. package/dist/types/src/cpu-limit.test.d.ts.map +1 -0
  12. package/dist/types/src/edge-routine.test.d.ts +2 -0
  13. package/dist/types/src/edge-routine.test.d.ts.map +1 -0
  14. package/dist/types/src/functions/definitions.d.ts +13 -0
  15. package/dist/types/src/functions/definitions.d.ts.map +1 -0
  16. package/dist/types/src/functions/fib.d.ts +8 -0
  17. package/dist/types/src/functions/fib.d.ts.map +1 -0
  18. package/dist/types/src/functions/forex-effect.d.ts +7 -0
  19. package/dist/types/src/functions/forex-effect.d.ts.map +1 -0
  20. package/dist/types/src/functions/query.d.ts +5 -0
  21. package/dist/types/src/functions/query.d.ts.map +1 -0
  22. package/dist/types/src/functions/reply.d.ts +4 -0
  23. package/dist/types/src/functions/reply.d.ts.map +1 -0
  24. package/dist/types/src/functions/sleep.d.ts +6 -0
  25. package/dist/types/src/functions/sleep.d.ts.map +1 -0
  26. package/dist/types/src/index.d.ts +2 -0
  27. package/dist/types/src/index.d.ts.map +1 -0
  28. package/dist/types/src/testing/index.d.ts +2 -0
  29. package/dist/types/src/testing/index.d.ts.map +1 -0
  30. package/dist/types/src/testing/util.d.ts +16 -0
  31. package/dist/types/src/testing/util.d.ts.map +1 -0
  32. package/dist/types/tsconfig.tsbuildinfo +1 -0
  33. package/package.json +55 -0
  34. package/src/bundle.test.ts +20 -0
  35. package/src/cpu-limit.test.ts +151 -0
  36. package/src/edge-routine.test.ts +110 -0
  37. package/src/functions/definitions.ts +61 -0
  38. package/src/functions/fib.ts +23 -0
  39. package/src/functions/forex-effect.ts +48 -0
  40. package/src/functions/query.ts +19 -0
  41. package/src/functions/reply.ts +19 -0
  42. package/src/functions/sleep.ts +17 -0
  43. package/src/index.ts +5 -0
  44. package/src/testing/index.ts +5 -0
  45. package/src/testing/util.ts +130 -0
package/package.json ADDED
@@ -0,0 +1,55 @@
1
+ {
2
+ "name": "@dxos/functions-testing",
3
+ "version": "0.8.4-main.03d5cd7b56",
4
+ "description": "Functions tests",
5
+ "homepage": "https://dxos.org",
6
+ "bugs": "https://github.com/dxos/dxos/issues",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/dxos/dxos"
10
+ },
11
+ "license": "MIT",
12
+ "author": "info@dxos.org",
13
+ "sideEffects": true,
14
+ "type": "module",
15
+ "exports": {
16
+ ".": {
17
+ "types": "./dist/types/src/index.d.ts",
18
+ "browser": "./dist/lib/browser/index.mjs",
19
+ "node": "./dist/lib/node-esm/index.mjs"
20
+ },
21
+ "./testing": {
22
+ "types": "./dist/types/src/testing/index.d.ts",
23
+ "browser": "./dist/lib/browser/testing/index.mjs",
24
+ "node": "./dist/lib/node-esm/testing/index.mjs"
25
+ }
26
+ },
27
+ "types": "dist/types/src/index.d.ts",
28
+ "files": [
29
+ "dist",
30
+ "src"
31
+ ],
32
+ "dependencies": {
33
+ "@effect/platform": "0.94.4",
34
+ "@dxos/async": "0.8.4-main.03d5cd7b56",
35
+ "@dxos/assistant-toolkit": "0.8.4-main.03d5cd7b56",
36
+ "@dxos/compute": "0.8.4-main.03d5cd7b56",
37
+ "@dxos/context": "0.8.4-main.03d5cd7b56",
38
+ "@dxos/client": "0.8.4-main.03d5cd7b56",
39
+ "@dxos/echo": "0.8.4-main.03d5cd7b56",
40
+ "@dxos/functions-runtime": "0.8.4-main.03d5cd7b56",
41
+ "@dxos/config": "0.8.4-main.03d5cd7b56",
42
+ "@dxos/invariant": "0.8.4-main.03d5cd7b56",
43
+ "@dxos/functions": "0.8.4-main.03d5cd7b56",
44
+ "@dxos/log": "0.8.4-main.03d5cd7b56",
45
+ "@dxos/operation": "0.8.4-main.03d5cd7b56",
46
+ "@dxos/protocols": "0.8.4-main.03d5cd7b56",
47
+ "@dxos/schema": "0.8.4-main.03d5cd7b56",
48
+ "@dxos/functions-runtime-cloudflare": "0.8.4-main.03d5cd7b56",
49
+ "@dxos/util": "0.8.4-main.03d5cd7b56"
50
+ },
51
+ "publishConfig": {
52
+ "access": "public"
53
+ },
54
+ "beast": {}
55
+ }
@@ -0,0 +1,20 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { join } from 'node:path';
6
+ import { describe, it } from 'vitest';
7
+
8
+ import { bundleFunction } from '@dxos/functions-runtime/native';
9
+
10
+ import { writeBundle } from './testing';
11
+
12
+ describe('bundle', () => {
13
+ it('should bundle', async () => {
14
+ const result = await bundleFunction({
15
+ entryPoint: new URL('./functions/reply.ts', import.meta.url).pathname,
16
+ });
17
+ writeBundle('./dist/test/bundle-reply', result);
18
+ console.log(join('dist/test/bundle-reply', result.entryPoint));
19
+ });
20
+ });
@@ -0,0 +1,151 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { describe, test } from 'vitest';
6
+
7
+ import { Trigger } from '@dxos/compute';
8
+ import { configPreset } from '@dxos/config';
9
+ import { Context } from '@dxos/context';
10
+ import { Obj, Ref } from '@dxos/echo';
11
+ import { FunctionRuntimeKind } from '@dxos/protocols';
12
+
13
+ import { deployFunction, observeInvocations, setup, sync } from './testing';
14
+
15
+ const FIB_FUNCTION_PATH = new URL('./functions/fib.ts', import.meta.url).pathname;
16
+
17
+ // Test suite to explore who CPU time limits influence function execution.
18
+ describe('CPU limit', { tags: ['functions-e2e'] }, () => {
19
+ const config = configPreset({ edge: 'dev' });
20
+
21
+ test('invoke directly', { timeout: 120_000 }, async ({ expect }) => {
22
+ const { client, space, functionsServiceClient } = await setup(config);
23
+ const func = await deployFunction(
24
+ space,
25
+ functionsServiceClient,
26
+ FIB_FUNCTION_PATH,
27
+ FunctionRuntimeKind.enums.WORKERS_FOR_PLATFORMS,
28
+ );
29
+ const result = await functionsServiceClient.invoke(
30
+ Context.default(),
31
+ func,
32
+ {
33
+ iterations: 100,
34
+ },
35
+ {
36
+ spaceId: space.id,
37
+ },
38
+ );
39
+ console.log(result);
40
+ });
41
+
42
+ test('force-trigger', { timeout: 120_000 }, async ({ expect }) => {
43
+ const { client, space, functionsServiceClient } = await setup(config);
44
+ const func = await deployFunction(
45
+ space,
46
+ functionsServiceClient,
47
+ FIB_FUNCTION_PATH,
48
+ FunctionRuntimeKind.enums.WORKERS_FOR_PLATFORMS,
49
+ );
50
+ const trigger = space.db.add(
51
+ Obj.make(Trigger.Trigger, {
52
+ enabled: true,
53
+ function: Ref.make(func),
54
+ spec: Trigger.specTimer('* */30 * * * *'),
55
+ input: { iterations: 100 },
56
+ }),
57
+ );
58
+ await sync(space);
59
+ const result = await functionsServiceClient.forceRunCronTrigger(Context.default(), space.id, trigger.id);
60
+ console.log(result);
61
+ });
62
+
63
+ test('break CPU limit', { timeout: 120_000 }, async ({ expect }) => {
64
+ const { client, space, functionsServiceClient } = await setup(config);
65
+ const func = await deployFunction(
66
+ space,
67
+ functionsServiceClient,
68
+ FIB_FUNCTION_PATH,
69
+ FunctionRuntimeKind.enums.WORKERS_FOR_PLATFORMS,
70
+ );
71
+ const trigger = space.db.add(
72
+ Obj.make(Trigger.Trigger, {
73
+ enabled: true,
74
+ function: Ref.make(func),
75
+ spec: Trigger.specTimer('* */30 * * * *'),
76
+ input: { iterations: 1_000_000_000 },
77
+ }),
78
+ );
79
+ await sync(space);
80
+ {
81
+ const result = await functionsServiceClient.forceRunCronTrigger(Context.default(), space.id, trigger.id);
82
+ console.log(result);
83
+ }
84
+
85
+ {
86
+ const result = await functionsServiceClient.forceRunCronTrigger(Context.default(), space.id, trigger.id);
87
+ console.log(result);
88
+ }
89
+
90
+ {
91
+ Obj.update(trigger, (trigger) => {
92
+ trigger.input!.iterations = 100;
93
+ });
94
+ await sync(space);
95
+ const result = await functionsServiceClient.forceRunCronTrigger(Context.default(), space.id, trigger.id);
96
+ console.log(result);
97
+ }
98
+ });
99
+
100
+ test('observe invocations', { timeout: 520_000 }, async ({ expect }) => {
101
+ const { client, space, functionsServiceClient } = await setup(config);
102
+ const func = await deployFunction(
103
+ space,
104
+ functionsServiceClient,
105
+ FIB_FUNCTION_PATH,
106
+ FunctionRuntimeKind.enums.WORKERS_FOR_PLATFORMS,
107
+ );
108
+ const trigger = space.db.add(
109
+ Obj.make(Trigger.Trigger, {
110
+ enabled: true,
111
+ function: Ref.make(func),
112
+ spec: Trigger.specTimer('* * * * * *'),
113
+ input: { iterations: 1_000_000 },
114
+ }),
115
+ );
116
+ await sync(space);
117
+ await observeInvocations(space, 100);
118
+ });
119
+
120
+ test('break CPU limit through natural exection', { timeout: 520_000 }, async ({ expect }) => {
121
+ const { client, space, functionsServiceClient } = await setup(config);
122
+ const func = await deployFunction(
123
+ space,
124
+ functionsServiceClient,
125
+ FIB_FUNCTION_PATH,
126
+ FunctionRuntimeKind.enums.WORKERS_FOR_PLATFORMS,
127
+ );
128
+ const trigger = space.db.add(
129
+ Obj.make(Trigger.Trigger, {
130
+ enabled: true,
131
+ function: Ref.make(func),
132
+ spec: Trigger.specTimer('* * * * * *'),
133
+ input: { iterations: 100 },
134
+ }),
135
+ );
136
+ await sync(space);
137
+ await observeInvocations(space, 5);
138
+
139
+ Obj.update(trigger, (trigger) => {
140
+ trigger.input!.iterations = 1_000_000_000;
141
+ });
142
+ await sync(space);
143
+ await observeInvocations(space, 10);
144
+
145
+ Obj.update(trigger, (trigger) => {
146
+ trigger.input!.iterations = 100;
147
+ });
148
+ await sync(space);
149
+ await observeInvocations(space, 1_000);
150
+ });
151
+ });
@@ -0,0 +1,110 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ import * as Schema from 'effect/Schema';
6
+ import { describe, test } from 'vitest';
7
+
8
+ import { AgentPrompt, DatabaseBlueprint, Chat } from '@dxos/assistant-toolkit';
9
+ import { Client } from '@dxos/client';
10
+ import { Blueprint, Operation, Routine, Trigger } from '@dxos/compute';
11
+ import { configPreset } from '@dxos/config';
12
+ import { Context } from '@dxos/context';
13
+ import { Feed, Obj, Ref } from '@dxos/echo';
14
+ import { TestSchema } from '@dxos/echo/testing';
15
+ import { dbg, log } from '@dxos/log';
16
+ import { ErrorCodec } from '@dxos/protocols';
17
+ import { EdgeReplicationSetting } from '@dxos/protocols/proto/dxos/echo/metadata';
18
+ import { Text } from '@dxos/schema';
19
+ import { trim } from '@dxos/util';
20
+
21
+ import { sync } from './testing';
22
+
23
+ /**
24
+ * Cron trigger on EDGE runs {@link AgentPrompt} for a {@link Routine} that uses the Database
25
+ * blueprint Query tool against replicated ECHO documents.
26
+ *
27
+ * Prereq: local EDGE (`configPreset({ edge: 'local' })` → `http://localhost:8787`) with LLM
28
+ * available (API key and/or memo replay under `conversationsCache/`).
29
+ */
30
+ describe('Edge routine', { tags: ['functions-e2e'] }, () => {
31
+ const config = configPreset({ edge: 'local' });
32
+
33
+ test('timer trigger runs routine with database blueprint on edge', { timeout: 420_000 }, async ({ expect }) => {
34
+ await using client = await new Client({
35
+ config,
36
+ types: [
37
+ Operation.PersistentOperation,
38
+ Trigger.Trigger,
39
+ Routine.Routine,
40
+ Blueprint.Blueprint,
41
+ Feed.Feed,
42
+ Text.Text,
43
+ Chat.Chat,
44
+ TestSchema.Organization,
45
+ ],
46
+ }).initialize();
47
+
48
+ await client.halo.createIdentity();
49
+ const space = await client.spaces.create();
50
+ await space.waitUntilReady();
51
+
52
+ await space.internal.setEdgeReplicationPreference(EdgeReplicationSetting.ENABLED);
53
+
54
+ Obj.update(space.properties, (properties) => {
55
+ properties.computeEnvironment = 'edge';
56
+ });
57
+
58
+ space.db.add(Obj.make(TestSchema.Organization, { name: 'Acme Corp' }));
59
+ space.db.add(Obj.make(TestSchema.Organization, { name: 'Globex Industries' }));
60
+ space.db.add(Obj.make(TestSchema.Organization, { name: 'Initech' }));
61
+
62
+ const databaseBlueprint = space.db.add(DatabaseBlueprint.make());
63
+
64
+ const routine = space.db.add(
65
+ Routine.make({
66
+ name: 'edge-e2e-count-orgs-db-blueprint',
67
+ instructions: trim`
68
+ You have access to the Database blueprint tools.
69
+ Use the Query tool exactly once with typename "${TestSchema.Organization.typename}" and no other arguments.
70
+ Then call completeJob with the output object { "count": <number of rows returned by Query> }.
71
+ If you are unable to query -- fail.
72
+ Do not list schemas first.
73
+ `,
74
+ input: Schema.Struct({}),
75
+ output: Schema.Struct({
76
+ count: Schema.Number,
77
+ }),
78
+ blueprints: [Ref.make(databaseBlueprint)],
79
+ context: [],
80
+ }),
81
+ );
82
+ const fn = Operation.serialize(AgentPrompt);
83
+ dbg(Obj.toJSON(fn));
84
+
85
+ const trigger = space.db.add(
86
+ Obj.make(Trigger.Trigger, {
87
+ enabled: true,
88
+ function: Ref.make(fn),
89
+ spec: Trigger.specTimer('* * * * * *'),
90
+ input: {
91
+ prompt: Ref.make(routine),
92
+ input: {},
93
+ model: '@anthropic/claude-haiku-4-5',
94
+ },
95
+ }),
96
+ );
97
+
98
+ await sync(space);
99
+
100
+ log('trigger created and synced');
101
+ log.break();
102
+
103
+ const runResult: any = await client.edge.http.forceRunCronTrigger(Context.default(), space.id, trigger.id);
104
+ if (runResult._kind === 'error') {
105
+ throw ErrorCodec.decode(runResult.error);
106
+ }
107
+ log('trigger ran', { runResult });
108
+ expect(runResult.result.count).toBe(3);
109
+ });
110
+ });
@@ -0,0 +1,61 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import * as Schema from 'effect/Schema';
6
+
7
+ import { Operation } from '@dxos/compute';
8
+ import { Database } from '@dxos/echo';
9
+
10
+ export const Fibonacci = Operation.make({
11
+ meta: {
12
+ key: 'org.example.function.fib',
13
+ name: 'Fibonacci',
14
+ description: 'Function that calculates a Fibonacci number',
15
+ },
16
+ input: Schema.Struct({
17
+ iterations: Schema.optional(Schema.Number).annotations({
18
+ description: 'Number of iterations',
19
+ default: 100_000,
20
+ }),
21
+ }),
22
+ output: Schema.Struct({
23
+ result: Schema.String,
24
+ }),
25
+ });
26
+
27
+ export const Reply = Operation.make({
28
+ meta: {
29
+ key: 'org.example.function.reply',
30
+ name: 'Reply',
31
+ description: 'Function that echoes the input',
32
+ },
33
+ input: Schema.Any,
34
+ output: Schema.Any,
35
+ });
36
+
37
+ export const Sleep = Operation.make({
38
+ meta: {
39
+ key: 'org.example.function.sleep',
40
+ name: 'Sleep',
41
+ description: 'Function that sleeps for a given amount of time',
42
+ },
43
+ input: Schema.Struct({
44
+ duration: Schema.optional(Schema.Number).annotations({
45
+ description: 'Milliseconds to sleep',
46
+ default: 100_000,
47
+ }),
48
+ }),
49
+ output: Schema.Void,
50
+ });
51
+
52
+ export const QueryDb = Operation.make({
53
+ meta: {
54
+ key: 'org.example.function.query',
55
+ name: 'Query',
56
+ description: 'Queries the database',
57
+ },
58
+ input: Schema.Any,
59
+ output: Schema.Any,
60
+ services: [Database.Service],
61
+ });
@@ -0,0 +1,23 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import * as Effect from 'effect/Effect';
6
+
7
+ import { Operation } from '@dxos/compute';
8
+
9
+ import { Fibonacci } from './definitions';
10
+
11
+ export default Fibonacci.pipe(
12
+ Operation.withHandler(
13
+ Effect.fn(function* ({ iterations = 100_000 }) {
14
+ let a = 0n;
15
+ let b = 1n;
16
+ for (let i = 0; i < iterations; i++) {
17
+ a += b;
18
+ b = a - b;
19
+ }
20
+ return { result: a.toString() };
21
+ }),
22
+ ),
23
+ );
@@ -0,0 +1,48 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import * as FetchHttpClient from '@effect/platform/FetchHttpClient';
6
+ import * as HttpClient from '@effect/platform/HttpClient';
7
+ import * as HttpClientRequest from '@effect/platform/HttpClientRequest';
8
+ import * as HttpClientResponse from '@effect/platform/HttpClientResponse';
9
+ import * as Effect from 'effect/Effect';
10
+ import * as Schedule from 'effect/Schedule';
11
+ import * as Schema from 'effect/Schema';
12
+
13
+ import { Operation } from '@dxos/compute';
14
+
15
+ const ForexEffect = Operation.make({
16
+ meta: {
17
+ key: 'org.dxos.script.forex-effect',
18
+ name: 'Forex Effect',
19
+ description: 'Returns the exchange rate between two currencies.',
20
+ },
21
+ input: Schema.Struct({
22
+ from: Schema.String.annotations({ description: 'The source currency' }),
23
+ to: Schema.String.annotations({ description: 'The target currency' }),
24
+ }),
25
+ output: Schema.String.annotations({ description: 'The exchange rate between the two currencies' }),
26
+ });
27
+
28
+ export default ForexEffect.pipe(
29
+ Operation.withHandler(
30
+ Effect.fnUntraced(function* ({ from, to }) {
31
+ const res = yield* HttpClientRequest.get(`https://free.ratesdb.com/v1/rates?from=${from}&to=${to}`).pipe(
32
+ HttpClient.execute,
33
+ Effect.flatMap(
34
+ HttpClientResponse.schemaBodyJson(
35
+ Schema.Struct({
36
+ data: Schema.Struct({ rates: Schema.Record({ key: Schema.String, value: Schema.Number }) }),
37
+ }),
38
+ ),
39
+ ),
40
+ Effect.timeout('1 second'),
41
+ Effect.retry(Schedule.exponential(1_000).pipe(Schedule.compose(Schedule.recurs(3)))),
42
+ Effect.scoped,
43
+ );
44
+
45
+ return res.data.rates[to].toString();
46
+ }, Effect.provide(FetchHttpClient.layer)),
47
+ ),
48
+ );
@@ -0,0 +1,19 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import * as Effect from 'effect/Effect';
6
+
7
+ import { Operation } from '@dxos/compute';
8
+ import { Database, Filter, Query as EchoQuery } from '@dxos/echo';
9
+
10
+ import { QueryDb } from './definitions';
11
+
12
+ export default QueryDb.pipe(
13
+ Operation.withHandler(
14
+ Effect.fn(function* (data) {
15
+ const results = yield* Database.runQuery(EchoQuery.select(Filter.everything()));
16
+ return { count: results.length };
17
+ }),
18
+ ),
19
+ );
@@ -0,0 +1,19 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import * as Console from 'effect/Console';
6
+ import * as Effect from 'effect/Effect';
7
+
8
+ import { Operation } from '@dxos/compute';
9
+
10
+ import { Reply } from './definitions';
11
+
12
+ export default Reply.pipe(
13
+ Operation.withHandler(
14
+ Effect.fn(function* (data) {
15
+ yield* Console.log('reply', { data });
16
+ return data;
17
+ }),
18
+ ),
19
+ );
@@ -0,0 +1,17 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import * as Effect from 'effect/Effect';
6
+
7
+ import { Operation } from '@dxos/compute';
8
+
9
+ import { Sleep } from './definitions';
10
+
11
+ export default Sleep.pipe(
12
+ Operation.withHandler(
13
+ Effect.fn(function* ({ duration = 100_000 }) {
14
+ yield* Effect.sleep(duration);
15
+ }),
16
+ ),
17
+ );
package/src/index.ts ADDED
@@ -0,0 +1,5 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ export {};
@@ -0,0 +1,5 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ export * from './util';
@@ -0,0 +1,130 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import fs from 'node:fs';
6
+
7
+ import { sleep } from '@dxos/async';
8
+ import { Client, type Config } from '@dxos/client';
9
+ import { type Space } from '@dxos/client/echo';
10
+ import { Operation, Trigger } from '@dxos/compute';
11
+ import { Context } from '@dxos/context';
12
+ import { Feed, Obj } from '@dxos/echo';
13
+ import { InvocationTraceEndEvent, InvocationTraceStartEvent } from '@dxos/functions-runtime';
14
+ import { FunctionsServiceClient } from '@dxos/functions-runtime/edge';
15
+ import { bundleFunction } from '@dxos/functions-runtime/native';
16
+ import type { BundleResult } from '@dxos/functions-runtime/native';
17
+ import { ErrorCodec, type FunctionRuntimeKind } from '@dxos/protocols';
18
+ import { EdgeReplicationSetting } from '@dxos/protocols/proto/dxos/echo/metadata';
19
+
20
+ export const writeBundle = (path: string, bundle: BundleResult) => {
21
+ fs.mkdirSync(path, { recursive: true });
22
+ Object.entries(bundle.assets).forEach(([name, content]) => {
23
+ fs.writeFileSync(path + '/' + name, content);
24
+ });
25
+ };
26
+
27
+ export const setup = async (config: Config) => {
28
+ const client = await new Client({
29
+ config,
30
+ types: [Operation.PersistentOperation, Trigger.Trigger],
31
+ }).initialize();
32
+ await client.halo.createIdentity();
33
+
34
+ const space = await client.spaces.create();
35
+ await space.waitUntilReady();
36
+ await space.internal.setEdgeReplicationPreference(EdgeReplicationSetting.ENABLED);
37
+
38
+ const functionsServiceClient = FunctionsServiceClient.fromClient(client);
39
+
40
+ return { client, space, functionsServiceClient };
41
+ };
42
+
43
+ export const sync = async (space: Space) => {
44
+ await space.db.flush();
45
+ await space.internal.syncToEdge({
46
+ onProgress: (state) =>
47
+ console.log(state ? `${state.unsyncedDocumentCount} documents syncing...` : 'connecting to edge...'),
48
+ });
49
+ };
50
+
51
+ export const deployFunction = async (
52
+ space: Space,
53
+ functionsServiceClient: FunctionsServiceClient,
54
+ entryPoint: string,
55
+ runtime: FunctionRuntimeKind,
56
+ ): Promise<Operation.PersistentOperation> => {
57
+ const artifact = await bundleFunction({
58
+ entryPoint,
59
+ verbose: true,
60
+ });
61
+ const func = await functionsServiceClient.deploy(Context.default(), {
62
+ version: '0.0.1',
63
+ ownerPublicKey: space.key,
64
+ entryPoint: artifact.entryPoint,
65
+ assets: artifact.assets,
66
+ runtime,
67
+ });
68
+ space.db.add(func);
69
+
70
+ return func;
71
+ };
72
+
73
+ export const observeInvocations = async (space: Space, maxCount: number | null) => {
74
+ let initialCount = null;
75
+ const invocationData = new Map<
76
+ string,
77
+ {
78
+ count: number;
79
+ begin: InvocationTraceStartEvent;
80
+ end?: InvocationTraceEndEvent;
81
+ }
82
+ >();
83
+ let count = 0;
84
+ while (true) {
85
+ try {
86
+ const traceFeed = space.properties.invocationTraceFeed?.target;
87
+ const traceQueueDxn = traceFeed ? Feed.getQueueDxn(traceFeed) : undefined;
88
+ const invocations = traceQueueDxn ? ((await space.queues.get(traceQueueDxn).queryObjects()) ?? []) : [];
89
+
90
+ for (const invocation of invocations) {
91
+ if (Obj.instanceOf(InvocationTraceStartEvent, invocation)) {
92
+ if (invocationData.has(invocation.invocationId)) {
93
+ continue;
94
+ }
95
+ invocationData.set(invocation.invocationId, {
96
+ count: count++,
97
+ begin: invocation,
98
+ });
99
+ console.log(
100
+ `${count.toString().padStart(3, ' ')}: BEGIN ${invocation.runtime ?? '(unknown runtime)'} ${JSON.stringify(invocation.input)}`,
101
+ );
102
+ } else if (Obj.instanceOf(InvocationTraceEndEvent, invocation)) {
103
+ const data = invocationData.get(invocation.invocationId);
104
+ if (!data || !!data.end) {
105
+ continue;
106
+ }
107
+ data.end = invocation;
108
+
109
+ const outcome = data.end.outcome;
110
+ console.log(
111
+ `${data.count.toString().padStart(3, ' ')}: END outcome=${outcome} duration=${data.end.timestamp - data.begin.timestamp}`,
112
+ );
113
+ if (outcome === 'failure' && data.end.error) {
114
+ console.error(ErrorCodec.decode(data.end.error));
115
+ }
116
+ }
117
+ }
118
+ if (initialCount === null) {
119
+ initialCount = invocations.length;
120
+ }
121
+
122
+ if (maxCount !== null && invocationData.size >= maxCount + initialCount) {
123
+ break;
124
+ }
125
+ } catch (err) {
126
+ console.error(err);
127
+ }
128
+ await sleep(1_000);
129
+ }
130
+ };