@dxos/functions 0.8.4-main.ae835ea → 0.8.4-main.bc674ce

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 (184) hide show
  1. package/dist/lib/browser/index.mjs +767 -884
  2. package/dist/lib/browser/index.mjs.map +4 -4
  3. package/dist/lib/browser/meta.json +1 -1
  4. package/dist/lib/node-esm/index.mjs +767 -884
  5. package/dist/lib/node-esm/index.mjs.map +4 -4
  6. package/dist/lib/node-esm/meta.json +1 -1
  7. package/dist/types/src/errors.d.ts +44 -60
  8. package/dist/types/src/errors.d.ts.map +1 -1
  9. package/dist/types/src/example/fib.d.ts +1 -1
  10. package/dist/types/src/example/index.d.ts +3 -3
  11. package/dist/types/src/example/index.d.ts.map +1 -1
  12. package/dist/types/src/example/reply.d.ts +1 -1
  13. package/dist/types/src/example/sleep.d.ts +1 -1
  14. package/dist/types/src/index.d.ts +2 -5
  15. package/dist/types/src/index.d.ts.map +1 -1
  16. package/dist/types/src/operation-compatibility.test.d.ts +2 -0
  17. package/dist/types/src/operation-compatibility.test.d.ts.map +1 -0
  18. package/dist/types/src/protocol/functions-ai-http-client.d.ts +12 -0
  19. package/dist/types/src/protocol/functions-ai-http-client.d.ts.map +1 -0
  20. package/dist/types/src/protocol/index.d.ts +2 -0
  21. package/dist/types/src/protocol/index.d.ts.map +1 -0
  22. package/dist/types/src/protocol/protocol.d.ts +7 -0
  23. package/dist/types/src/protocol/protocol.d.ts.map +1 -0
  24. package/dist/types/src/protocol/protocol.test.d.ts +2 -0
  25. package/dist/types/src/protocol/protocol.test.d.ts.map +1 -0
  26. package/dist/types/src/sdk.d.ts +114 -0
  27. package/dist/types/src/sdk.d.ts.map +1 -0
  28. package/dist/types/src/services/credentials.d.ts +6 -4
  29. package/dist/types/src/services/credentials.d.ts.map +1 -1
  30. package/dist/types/src/services/event-logger.d.ts +33 -27
  31. package/dist/types/src/services/event-logger.d.ts.map +1 -1
  32. package/dist/types/src/services/function-invocation-service.d.ts +7 -19
  33. package/dist/types/src/services/function-invocation-service.d.ts.map +1 -1
  34. package/dist/types/src/services/index.d.ts +2 -4
  35. package/dist/types/src/services/index.d.ts.map +1 -1
  36. package/dist/types/src/services/queues.d.ts +4 -4
  37. package/dist/types/src/services/queues.d.ts.map +1 -1
  38. package/dist/types/src/services/tracing.d.ts +41 -12
  39. package/dist/types/src/services/tracing.d.ts.map +1 -1
  40. package/dist/types/src/types/Function.d.ts +40 -35
  41. package/dist/types/src/types/Function.d.ts.map +1 -1
  42. package/dist/types/src/types/Script.d.ts +9 -16
  43. package/dist/types/src/types/Script.d.ts.map +1 -1
  44. package/dist/types/src/types/Trigger.d.ts +58 -76
  45. package/dist/types/src/types/Trigger.d.ts.map +1 -1
  46. package/dist/types/src/types/TriggerEvent.d.ts +43 -13
  47. package/dist/types/src/types/TriggerEvent.d.ts.map +1 -1
  48. package/dist/types/src/types/index.d.ts +1 -0
  49. package/dist/types/src/types/index.d.ts.map +1 -1
  50. package/dist/types/src/types/url.d.ts +13 -0
  51. package/dist/types/src/types/url.d.ts.map +1 -0
  52. package/dist/types/tsconfig.tsbuildinfo +1 -1
  53. package/package.json +23 -58
  54. package/src/errors.ts +4 -4
  55. package/src/example/fib.ts +1 -1
  56. package/src/example/reply.ts +1 -1
  57. package/src/example/sleep.ts +1 -1
  58. package/src/index.ts +2 -5
  59. package/src/operation-compatibility.test.ts +185 -0
  60. package/src/protocol/functions-ai-http-client.ts +67 -0
  61. package/src/{executor → protocol}/index.ts +1 -1
  62. package/src/protocol/protocol.test.ts +59 -0
  63. package/src/protocol/protocol.ts +262 -0
  64. package/src/{handler.ts → sdk.ts} +129 -66
  65. package/src/services/credentials.ts +32 -17
  66. package/src/services/event-logger.ts +10 -4
  67. package/src/services/function-invocation-service.ts +23 -70
  68. package/src/services/index.ts +2 -4
  69. package/src/services/queues.ts +5 -7
  70. package/src/services/tracing.ts +68 -44
  71. package/src/types/Function.ts +39 -8
  72. package/src/types/Script.ts +10 -9
  73. package/src/types/Trigger.ts +18 -14
  74. package/src/types/TriggerEvent.ts +29 -29
  75. package/src/types/index.ts +1 -0
  76. package/src/types/url.ts +32 -0
  77. package/dist/lib/browser/bundler/index.mjs +0 -256
  78. package/dist/lib/browser/bundler/index.mjs.map +0 -7
  79. package/dist/lib/browser/chunk-J5LGTIGS.mjs +0 -10
  80. package/dist/lib/browser/chunk-J5LGTIGS.mjs.map +0 -7
  81. package/dist/lib/browser/chunk-M6EXIREF.mjs +0 -610
  82. package/dist/lib/browser/chunk-M6EXIREF.mjs.map +0 -7
  83. package/dist/lib/browser/edge/index.mjs +0 -83
  84. package/dist/lib/browser/edge/index.mjs.map +0 -7
  85. package/dist/lib/browser/testing/index.mjs +0 -131
  86. package/dist/lib/browser/testing/index.mjs.map +0 -7
  87. package/dist/lib/node-esm/bundler/index.mjs +0 -257
  88. package/dist/lib/node-esm/bundler/index.mjs.map +0 -7
  89. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs +0 -11
  90. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs.map +0 -7
  91. package/dist/lib/node-esm/chunk-P3IATZMZ.mjs +0 -612
  92. package/dist/lib/node-esm/chunk-P3IATZMZ.mjs.map +0 -7
  93. package/dist/lib/node-esm/edge/index.mjs +0 -84
  94. package/dist/lib/node-esm/edge/index.mjs.map +0 -7
  95. package/dist/lib/node-esm/testing/index.mjs +0 -132
  96. package/dist/lib/node-esm/testing/index.mjs.map +0 -7
  97. package/dist/types/src/bundler/bundler.d.ts +0 -49
  98. package/dist/types/src/bundler/bundler.d.ts.map +0 -1
  99. package/dist/types/src/bundler/bundler.test.d.ts +0 -2
  100. package/dist/types/src/bundler/bundler.test.d.ts.map +0 -1
  101. package/dist/types/src/bundler/index.d.ts +0 -2
  102. package/dist/types/src/bundler/index.d.ts.map +0 -1
  103. package/dist/types/src/e2e/deploy.test.d.ts +0 -2
  104. package/dist/types/src/e2e/deploy.test.d.ts.map +0 -1
  105. package/dist/types/src/edge/functions.d.ts +0 -17
  106. package/dist/types/src/edge/functions.d.ts.map +0 -1
  107. package/dist/types/src/edge/index.d.ts +0 -2
  108. package/dist/types/src/edge/index.d.ts.map +0 -1
  109. package/dist/types/src/executor/executor.d.ts +0 -14
  110. package/dist/types/src/executor/executor.d.ts.map +0 -1
  111. package/dist/types/src/executor/index.d.ts +0 -2
  112. package/dist/types/src/executor/index.d.ts.map +0 -1
  113. package/dist/types/src/handler.d.ts +0 -102
  114. package/dist/types/src/handler.d.ts.map +0 -1
  115. package/dist/types/src/services/database.d.ts +0 -67
  116. package/dist/types/src/services/database.d.ts.map +0 -1
  117. package/dist/types/src/services/function-invocation-service.test.d.ts +0 -2
  118. package/dist/types/src/services/function-invocation-service.test.d.ts.map +0 -1
  119. package/dist/types/src/services/local-function-execution.d.ts +0 -34
  120. package/dist/types/src/services/local-function-execution.d.ts.map +0 -1
  121. package/dist/types/src/services/remote-function-execution-service.d.ts +0 -22
  122. package/dist/types/src/services/remote-function-execution-service.d.ts.map +0 -1
  123. package/dist/types/src/services/service-container.d.ts +0 -57
  124. package/dist/types/src/services/service-container.d.ts.map +0 -1
  125. package/dist/types/src/services/service-registry.d.ts +0 -31
  126. package/dist/types/src/services/service-registry.d.ts.map +0 -1
  127. package/dist/types/src/services/service-registry.test.d.ts +0 -2
  128. package/dist/types/src/services/service-registry.test.d.ts.map +0 -1
  129. package/dist/types/src/testing/index.d.ts +0 -3
  130. package/dist/types/src/testing/index.d.ts.map +0 -1
  131. package/dist/types/src/testing/layer.d.ts +0 -18
  132. package/dist/types/src/testing/layer.d.ts.map +0 -1
  133. package/dist/types/src/testing/logger.d.ts +0 -5
  134. package/dist/types/src/testing/logger.d.ts.map +0 -1
  135. package/dist/types/src/testing/persist-database.test.d.ts +0 -2
  136. package/dist/types/src/testing/persist-database.test.d.ts.map +0 -1
  137. package/dist/types/src/testing/services.d.ts +0 -59
  138. package/dist/types/src/testing/services.d.ts.map +0 -1
  139. package/dist/types/src/trace.d.ts +0 -122
  140. package/dist/types/src/trace.d.ts.map +0 -1
  141. package/dist/types/src/translations.d.ts +0 -12
  142. package/dist/types/src/translations.d.ts.map +0 -1
  143. package/dist/types/src/triggers/index.d.ts +0 -4
  144. package/dist/types/src/triggers/index.d.ts.map +0 -1
  145. package/dist/types/src/triggers/input-builder.d.ts +0 -3
  146. package/dist/types/src/triggers/input-builder.d.ts.map +0 -1
  147. package/dist/types/src/triggers/invocation-tracer.d.ts +0 -37
  148. package/dist/types/src/triggers/invocation-tracer.d.ts.map +0 -1
  149. package/dist/types/src/triggers/trigger-dispatcher.d.ts +0 -78
  150. package/dist/types/src/triggers/trigger-dispatcher.d.ts.map +0 -1
  151. package/dist/types/src/triggers/trigger-dispatcher.test.d.ts +0 -2
  152. package/dist/types/src/triggers/trigger-dispatcher.test.d.ts.map +0 -1
  153. package/dist/types/src/triggers/trigger-state-store.d.ts +0 -28
  154. package/dist/types/src/triggers/trigger-state-store.d.ts.map +0 -1
  155. package/dist/types/src/url.d.ts +0 -21
  156. package/dist/types/src/url.d.ts.map +0 -1
  157. package/src/bundler/bundler.test.ts +0 -58
  158. package/src/bundler/bundler.ts +0 -295
  159. package/src/bundler/index.ts +0 -5
  160. package/src/e2e/deploy.test.ts +0 -69
  161. package/src/edge/functions.ts +0 -67
  162. package/src/edge/index.ts +0 -9
  163. package/src/executor/executor.ts +0 -58
  164. package/src/services/database.ts +0 -175
  165. package/src/services/function-invocation-service.test.ts +0 -81
  166. package/src/services/local-function-execution.ts +0 -153
  167. package/src/services/remote-function-execution-service.ts +0 -63
  168. package/src/services/service-container.ts +0 -115
  169. package/src/services/service-registry.test.ts +0 -45
  170. package/src/services/service-registry.ts +0 -63
  171. package/src/testing/index.ts +0 -6
  172. package/src/testing/layer.ts +0 -114
  173. package/src/testing/logger.ts +0 -17
  174. package/src/testing/persist-database.test.ts +0 -87
  175. package/src/testing/services.ts +0 -115
  176. package/src/trace.ts +0 -178
  177. package/src/translations.ts +0 -20
  178. package/src/triggers/index.ts +0 -7
  179. package/src/triggers/input-builder.ts +0 -35
  180. package/src/triggers/invocation-tracer.ts +0 -101
  181. package/src/triggers/trigger-dispatcher.test.ts +0 -664
  182. package/src/triggers/trigger-dispatcher.ts +0 -521
  183. package/src/triggers/trigger-state-store.ts +0 -61
  184. package/src/url.ts +0 -55
@@ -1,58 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- import * as Effect from 'effect/Effect';
6
- import * as Schema from 'effect/Schema';
7
-
8
- import { type SpaceId } from '@dxos/client/echo';
9
- import { runAndForwardErrors } from '@dxos/effect';
10
-
11
- import type { FunctionContext, FunctionDefinition } from '../handler';
12
- import type { ServiceContainer, Services } from '../services';
13
-
14
- /**
15
- * @deprecated Use `FunctionInvocationService`
16
- */
17
- export class FunctionExecutor {
18
- constructor(private readonly _services: ServiceContainer) {}
19
-
20
- /**
21
- * Invoke function.
22
- */
23
- // TODO(dmaretskyi): Invocation context: queue, space, etc...
24
- async invoke<F extends FunctionDefinition<any, any>>(
25
- functionDef: F,
26
- input: F extends FunctionDefinition<infer I, infer _O> ? I : never,
27
- ): Promise<F extends FunctionDefinition<infer _I, infer O> ? O : never> {
28
- // Assert input matches schema
29
- const assertInput = functionDef.inputSchema.pipe(Schema.asserts);
30
- (assertInput as any)(input);
31
-
32
- const context: FunctionContext = {
33
- space: undefined,
34
- getService: this._services.getService.bind(this._services),
35
- getSpace: async (_spaceId: SpaceId) => {
36
- throw new Error('Not available. Use the database service instead.');
37
- },
38
- };
39
-
40
- const result = functionDef.handler({ context, data: input });
41
-
42
- let data: unknown;
43
- if (Effect.isEffect(result)) {
44
- data = await (result as Effect.Effect<unknown, unknown, Services>).pipe(
45
- Effect.provide(this._services.createLayer()),
46
- runAndForwardErrors,
47
- );
48
- } else {
49
- data = await result;
50
- }
51
-
52
- // Assert output matches schema
53
- const assertOutput = functionDef.outputSchema?.pipe(Schema.asserts);
54
- (assertOutput as any)(data);
55
-
56
- return data as any;
57
- }
58
- }
@@ -1,175 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- import * as Context from 'effect/Context';
6
- import * as Effect from 'effect/Effect';
7
- import * as Layer from 'effect/Layer';
8
- import * as Option from 'effect/Option';
9
- import type * as Schema from 'effect/Schema';
10
-
11
- import {
12
- type Filter,
13
- type Live,
14
- Obj,
15
- ObjectNotFoundError,
16
- type Query,
17
- type Ref,
18
- type Relation,
19
- type Type,
20
- } from '@dxos/echo';
21
- import type { EchoSchema } from '@dxos/echo/internal';
22
- import type { EchoDatabase, FlushOptions, OneShotQueryResult, QueryResult, SchemaRegistryQuery } from '@dxos/echo-db';
23
- import type { SchemaRegistryPreparedQuery } from '@dxos/echo-db';
24
- import { promiseWithCauseCapture } from '@dxos/effect';
25
- import { invariant } from '@dxos/invariant';
26
- import type { DXN } from '@dxos/keys';
27
-
28
- export class DatabaseService extends Context.Tag('@dxos/functions/DatabaseService')<
29
- DatabaseService,
30
- {
31
- readonly db: EchoDatabase;
32
- }
33
- >() {
34
- static notAvailable = Layer.succeed(DatabaseService, {
35
- get db(): EchoDatabase {
36
- throw new Error('Database not available');
37
- },
38
- });
39
-
40
- static make = (db: EchoDatabase): Context.Tag.Service<DatabaseService> => {
41
- return {
42
- get db() {
43
- return db;
44
- },
45
- };
46
- };
47
-
48
- static layer = (db: EchoDatabase): Layer.Layer<DatabaseService> => {
49
- return Layer.succeed(DatabaseService, DatabaseService.make(db));
50
- };
51
-
52
- /**
53
- * Resolves an object by its DXN.
54
- */
55
- static resolve: {
56
- // No type check.
57
- (dxn: DXN): Effect.Effect<Obj.Any | Relation.Any, never, DatabaseService>;
58
- // Check matches schema.
59
- <S extends Type.Obj.Any | Type.Relation.Any>(
60
- dxn: DXN,
61
- schema: S,
62
- ): Effect.Effect<Schema.Schema.Type<S>, ObjectNotFoundError, DatabaseService>;
63
- } = (<S extends Type.Obj.Any | Type.Relation.Any>(
64
- dxn: DXN,
65
- schema?: S,
66
- ): Effect.Effect<Schema.Schema.Type<S>, ObjectNotFoundError, DatabaseService> =>
67
- Effect.gen(function* () {
68
- const { db } = yield* DatabaseService;
69
- const object = yield* promiseWithCauseCapture(() =>
70
- db.graph
71
- .createRefResolver({
72
- context: {
73
- space: db.spaceId,
74
- },
75
- })
76
- .resolve(dxn),
77
- );
78
-
79
- if (!object) {
80
- return yield* Effect.fail(new ObjectNotFoundError(dxn));
81
- }
82
- invariant(!schema || Obj.instanceOf(schema, object), 'Object type mismatch.');
83
- return object as any;
84
- })) as any;
85
-
86
- /**
87
- * Loads an object reference.
88
- */
89
- static load: <T>(ref: Ref.Ref<T>) => Effect.Effect<T, ObjectNotFoundError, never> = Effect.fn(function* (ref) {
90
- const object = yield* promiseWithCauseCapture(() => ref.tryLoad());
91
- if (!object) {
92
- return yield* Effect.fail(new ObjectNotFoundError(ref.dxn));
93
- }
94
- return object;
95
- });
96
-
97
- /**
98
- * Loads an object reference option.
99
- */
100
- // TODO(burdon): Option?
101
- static loadOption: <T>(ref: Ref.Ref<T>) => Effect.Effect<Option.Option<T>, never, never> = Effect.fn(function* (ref) {
102
- const object = yield* DatabaseService.load(ref).pipe(
103
- Effect.catchTag('OBJECT_NOT_FOUND', () => Effect.succeed(undefined)),
104
- );
105
- return Option.fromNullable(object);
106
- });
107
-
108
- // TODO(burdon): Can we create a proxy for the following methods on EchoDatabase? Use @inheritDoc?
109
- // TODO(burdon): Figure out how to chain query().run();
110
-
111
- /**
112
- * @link EchoDatabase.add
113
- */
114
- static add = <T extends Obj.Any | Relation.Any>(obj: T): Effect.Effect<T, never, DatabaseService> =>
115
- DatabaseService.pipe(Effect.map(({ db }) => db.add(obj)));
116
-
117
- /**
118
- * @link EchoDatabase.remove
119
- */
120
- static remove = <T extends Obj.Any | Relation.Any>(obj: T): Effect.Effect<void, never, DatabaseService> =>
121
- DatabaseService.pipe(Effect.map(({ db }) => db.remove(obj)));
122
-
123
- /**
124
- * @link EchoDatabase.flush
125
- */
126
- static flush = (opts?: FlushOptions) =>
127
- DatabaseService.pipe(Effect.flatMap(({ db }) => promiseWithCauseCapture(() => db.flush(opts))));
128
-
129
- /**
130
- * @link EchoDatabase.getObjectById
131
- */
132
- static getObjectById = <T extends Obj.Any | Relation.Any>(
133
- id: string,
134
- ): Effect.Effect<Live<T> | undefined, never, DatabaseService> => {
135
- return DatabaseService.pipe(Effect.map(({ db }) => db.getObjectById(id)));
136
- };
137
-
138
- /**
139
- * Creates a `QueryResult` object that can be subscribed to.
140
- */
141
- static query: {
142
- <Q extends Query.Any>(query: Q): Effect.Effect<QueryResult<Live<Query.Type<Q>>>, never, DatabaseService>;
143
- <F extends Filter.Any>(filter: F): Effect.Effect<QueryResult<Live<Filter.Type<F>>>, never, DatabaseService>;
144
- } = (queryOrFilter: Query.Any | Filter.Any) =>
145
- DatabaseService.pipe(
146
- Effect.map(({ db }) => db.query(queryOrFilter as any)),
147
- Effect.withSpan('DatabaseService.query'),
148
- );
149
-
150
- /**
151
- * Executes the query once and returns the results.
152
- */
153
- static runQuery: {
154
- <Q extends Query.Any>(query: Q): Effect.Effect<OneShotQueryResult<Live<Query.Type<Q>>>, never, DatabaseService>;
155
- <F extends Filter.Any>(filter: F): Effect.Effect<OneShotQueryResult<Live<Filter.Type<F>>>, never, DatabaseService>;
156
- } = (queryOrFilter: Query.Any | Filter.Any) =>
157
- DatabaseService.query(queryOrFilter as any).pipe(
158
- Effect.flatMap((queryResult) => promiseWithCauseCapture(() => queryResult.run())),
159
- );
160
-
161
- static schemaQuery = <Q extends SchemaRegistryQuery>(
162
- query: Q,
163
- ): Effect.Effect<SchemaRegistryPreparedQuery<EchoSchema>, never, DatabaseService> =>
164
- DatabaseService.pipe(
165
- Effect.map(({ db }) => db.schemaRegistry.query(query)),
166
- Effect.withSpan('DatabaseService.schemaQuery'),
167
- );
168
-
169
- static runSchemaQuery = <Q extends SchemaRegistryQuery>(
170
- query: Q,
171
- ): Effect.Effect<EchoSchema[], never, DatabaseService> =>
172
- DatabaseService.schemaQuery(query).pipe(
173
- Effect.flatMap((queryResult) => promiseWithCauseCapture(() => queryResult.run())),
174
- );
175
- }
@@ -1,81 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- import { describe, expect, it } from '@effect/vitest';
6
- import * as Effect from 'effect/Effect';
7
- import * as Layer from 'effect/Layer';
8
- import * as Schema from 'effect/Schema';
9
-
10
- import { AiService } from '@dxos/ai';
11
-
12
- import { defineFunction } from '../handler';
13
- import { TestDatabaseLayer } from '../testing';
14
-
15
- import { FunctionInvocationService } from './function-invocation-service';
16
- import { FunctionImplementationResolver } from './local-function-execution';
17
-
18
- const TestLayer = Layer.mergeAll(AiService.model('@anthropic/claude-opus-4-0')).pipe(
19
- Layer.provideMerge(
20
- Layer.mergeAll(
21
- TestDatabaseLayer({
22
- indexing: { vector: true },
23
- types: [],
24
- }),
25
- FunctionInvocationService.layer,
26
- ),
27
- ),
28
- );
29
-
30
- describe('FunctionInvocationService', () => {
31
- it(
32
- 'should be defined',
33
- Effect.fnUntraced(function* () {
34
- const service = yield* FunctionInvocationService;
35
- expect(service).toBeDefined();
36
- }, Effect.provide(TestLayer)),
37
- );
38
-
39
- it(
40
- 'routes to local when implementation is available',
41
- Effect.fnUntraced(function* () {
42
- const add = defineFunction({
43
- key: 'example.org/function/add',
44
- name: 'add',
45
- inputSchema: Schema.Struct({ a: Schema.Number, b: Schema.Number }),
46
- outputSchema: Schema.Number,
47
- handler: ({ data }) => data.a + data.b,
48
- });
49
-
50
- const layer = TestLayer.pipe(Layer.provideMerge(FunctionImplementationResolver.layerTest({ functions: [add] })));
51
-
52
- const result = yield* Effect.gen(function* () {
53
- return yield* FunctionInvocationService.invokeFunction(add, { a: 2, b: 3 });
54
- }).pipe(Effect.provide(layer));
55
-
56
- expect(result).toEqual(5);
57
- }),
58
- );
59
-
60
- it(
61
- 'routes to remote when no local implementation is found',
62
- Effect.fnUntraced(function* () {
63
- // This function is not deployed, so mock layer will be used.
64
- const echo = defineFunction({
65
- key: 'example.org/function/echo',
66
- name: 'function-that-is-deployed',
67
- inputSchema: Schema.Unknown,
68
- outputSchema: Schema.Unknown,
69
- handler: () => {},
70
- });
71
-
72
- // No resolver provided → resolveFunctionImplementation will fail → remote path is used.
73
- const result = yield* Effect.gen(function* () {
74
- return yield* FunctionInvocationService.invokeFunction(echo, { hello: 'world' });
75
- }).pipe(Effect.provide(TestLayer));
76
-
77
- // RemoteFunctionExecutionService.mock echos input back.
78
- expect(result).toEqual({ hello: 'world', resolved: 'remote' });
79
- }),
80
- );
81
- });
@@ -1,153 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- import * as Context from 'effect/Context';
6
- import * as Effect from 'effect/Effect';
7
- import * as Layer from 'effect/Layer';
8
- import * as Schema from 'effect/Schema';
9
-
10
- import { AiService } from '@dxos/ai';
11
- import { todo } from '@dxos/debug';
12
- import { log } from '@dxos/log';
13
-
14
- import { FunctionError, FunctionNotFoundError } from '../errors';
15
- import type { FunctionContext, FunctionDefinition } from '../handler';
16
-
17
- import { CredentialsService } from './credentials';
18
- import { DatabaseService } from './database';
19
- import { type ComputeEventLogger } from './event-logger';
20
- import { QueueService } from './queues';
21
- import { RemoteFunctionExecutionService } from './remote-function-execution-service';
22
- import { type Services } from './service-container';
23
- import { type TracingService } from './tracing';
24
-
25
- /**
26
- * Services that are provided at the function call site.
27
- */
28
- export type InvocationServices = TracingService | ComputeEventLogger;
29
-
30
- export class LocalFunctionExecutionService extends Context.Tag('@dxos/functions/LocalFunctionExecutionService')<
31
- LocalFunctionExecutionService,
32
- {
33
- // TODO(dmaretskyi): This should take function id instead of the definition object.
34
- // TODO(dmaretskyi): Services should be satisfied from environment rather then bubbled up.
35
- invokeFunction<I, O>(functionDef: FunctionDefinition<I, O>, input: I): Effect.Effect<O, never, InvocationServices>;
36
- }
37
- >() {
38
- static layerLive = Layer.effect(
39
- LocalFunctionExecutionService,
40
- Effect.gen(function* () {
41
- // TODO(dmaretskyi): Use `yield* Effect.context()`;
42
- const resolver = yield* FunctionImplementationResolver;
43
- const ai = yield* AiService.AiService;
44
- const credentials = yield* CredentialsService;
45
- const database = yield* DatabaseService;
46
- const queues = yield* QueueService;
47
- // TODO(mykola): Delete, should not be required for local execution.
48
- const functionCallService = yield* RemoteFunctionExecutionService;
49
- return {
50
- // TODO(dmaretskyi): Better error types.
51
- invokeFunction: <I, O>(
52
- functionDef: FunctionDefinition<I, O>,
53
- input: I,
54
- ): Effect.Effect<O, never, InvocationServices> =>
55
- Effect.gen(function* () {
56
- const resolved = yield* resolver.resolveFunctionImplementation(functionDef).pipe(Effect.orDie);
57
- const output = yield* invokeFunction(resolved, input);
58
- return output as O;
59
- }).pipe(
60
- Effect.provideService(AiService.AiService, ai),
61
- Effect.provideService(CredentialsService, credentials),
62
- Effect.provideService(DatabaseService, database),
63
- Effect.provideService(QueueService, queues),
64
- Effect.provideService(RemoteFunctionExecutionService, functionCallService),
65
- ),
66
- };
67
- }),
68
- );
69
-
70
- static invokeFunction: <F extends FunctionDefinition.Any>(
71
- functionDef: F,
72
- input: FunctionDefinition.Input<F>,
73
- ) => Effect.Effect<FunctionDefinition.Output<F>, never, Services | LocalFunctionExecutionService> =
74
- Effect.serviceFunctionEffect(LocalFunctionExecutionService, (_) => _.invokeFunction as any);
75
- }
76
-
77
- const invokeFunction = (
78
- functionDef: FunctionDefinition<any, any>,
79
- input: any,
80
- ): Effect.Effect<unknown, never, Services> =>
81
- Effect.gen(function* () {
82
- // Assert input matches schema.
83
- try {
84
- const assertInput = functionDef.inputSchema.pipe(Schema.asserts);
85
- (assertInput as any)(input);
86
- } catch (e) {
87
- throw new FunctionError({ message: 'Invalid function input', context: { name: functionDef.name }, cause: e });
88
- }
89
-
90
- const context: FunctionContext = {
91
- space: undefined,
92
- getService: () => todo(),
93
- getSpace: async (_spaceId: any) => {
94
- throw new Error('Not available. Use the database service instead.');
95
- },
96
- };
97
-
98
- log.info('invoking function', { name: functionDef.name, input });
99
-
100
- // TODO(dmaretskyi): This should be delegated to a function invoker service.
101
- const data = yield* Effect.gen(function* () {
102
- const result = functionDef.handler({ context, data: input });
103
- if (Effect.isEffect(result)) {
104
- return yield* (result as Effect.Effect<unknown, unknown, Services>).pipe(Effect.orDie);
105
- } else if (
106
- typeof result === 'object' &&
107
- result !== null &&
108
- 'then' in result &&
109
- typeof result.then === 'function'
110
- ) {
111
- return yield* Effect.promise(() => result);
112
- } else {
113
- return result;
114
- }
115
- }).pipe(
116
- Effect.orDie,
117
- Effect.catchAllDefect((defect) =>
118
- Effect.die(new FunctionError({ context: { name: functionDef.name }, cause: defect })),
119
- ),
120
- );
121
-
122
- log.info('completed', { function: functionDef.name, input, data });
123
-
124
- // Assert output matches schema.
125
- try {
126
- const assertOutput = functionDef.outputSchema?.pipe(Schema.asserts);
127
- (assertOutput as any)(data);
128
- } catch (e) {
129
- throw new FunctionError({ message: 'Invalid function output', context: { name: functionDef.name }, cause: e });
130
- }
131
-
132
- return data;
133
- }).pipe(Effect.withSpan('invokeFunction', { attributes: { name: functionDef.name } }));
134
-
135
- export class FunctionImplementationResolver extends Context.Tag('@dxos/functions/FunctionImplementationResolver')<
136
- FunctionImplementationResolver,
137
- {
138
- resolveFunctionImplementation<I, O>(
139
- functionDef: FunctionDefinition<I, O>,
140
- ): Effect.Effect<FunctionDefinition<I, O>, FunctionNotFoundError>;
141
- }
142
- >() {
143
- static layerTest = ({ functions }: { functions: readonly FunctionDefinition<any, any>[] }) =>
144
- Layer.succeed(FunctionImplementationResolver, {
145
- resolveFunctionImplementation: <I, O>(functionDef: FunctionDefinition<I, O>) => {
146
- const resolved = functions.find((f) => f.key === functionDef.key);
147
- if (!resolved) {
148
- return Effect.fail(new FunctionNotFoundError(functionDef.name));
149
- }
150
- return Effect.succeed(resolved);
151
- },
152
- });
153
- }
@@ -1,63 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- import * as Context from 'effect/Context';
6
- import * as Effect from 'effect/Effect';
7
- import * as Layer from 'effect/Layer';
8
-
9
- import type { SpaceId } from '@dxos/keys';
10
-
11
- import { FunctionError } from '../errors';
12
- import { getInvocationUrl } from '../url';
13
-
14
- /**
15
- * Allows calling into other functions.
16
- */
17
- export class RemoteFunctionExecutionService extends Context.Tag('@dxos/functions/RemoteFunctionExecutionService')<
18
- RemoteFunctionExecutionService,
19
- {
20
- callFunction<I, O>(deployedFunctionId: string, input: I): Effect.Effect<O>;
21
- }
22
- >() {
23
- /**
24
- * @param baseUrl URL of the EDGE server.
25
- * @param spaceId - The space ID to invoke the function in. If not provided, the function will be without space context.
26
- * @returns
27
- */
28
- static fromClient(baseUrl: string, spaceId?: SpaceId): Layer.Layer<RemoteFunctionExecutionService> {
29
- return Layer.succeed(RemoteFunctionExecutionService, {
30
- callFunction: <I, O>(deployedFunctionId: string, input: I): Effect.Effect<O> =>
31
- Effect.gen(function* () {
32
- const url = getInvocationUrl(deployedFunctionId, baseUrl, { spaceId });
33
- const result = yield* Effect.promise(() =>
34
- fetch(url, {
35
- method: 'POST',
36
- headers: { 'Content-Type': 'application/json' },
37
- body: JSON.stringify(input),
38
- }),
39
- );
40
- if (result.status >= 300 || result.status < 200) {
41
- const text = yield* Effect.promise(() => result.text());
42
- return yield* Effect.die(
43
- new FunctionError({
44
- message: 'Failed to invoke function',
45
- cause: new Error(`HTTP error: ${text}`),
46
- }),
47
- );
48
- }
49
- const data = (yield* Effect.promise(() => result.json())) as O;
50
- return data;
51
- }),
52
- });
53
- }
54
-
55
- static mock = (): Context.Tag.Service<RemoteFunctionExecutionService> => {
56
- return {
57
- callFunction: <I, O>(deployedFunctionId: string, input: I): Effect.Effect<O> =>
58
- Effect.succeed(input as unknown as O),
59
- };
60
- };
61
-
62
- static layerMock = Layer.succeed(RemoteFunctionExecutionService, RemoteFunctionExecutionService.mock());
63
- }
@@ -1,115 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- import type * as Context from 'effect/Context';
6
- import * as Layer from 'effect/Layer';
7
-
8
- import { AiService } from '@dxos/ai';
9
- import { entries } from '@dxos/util';
10
-
11
- import { ConfiguredCredentialsService, CredentialsService } from './credentials';
12
- import { DatabaseService } from './database';
13
- import { ComputeEventLogger } from './event-logger';
14
- import { QueueService } from './queues';
15
- import { RemoteFunctionExecutionService } from './remote-function-execution-service';
16
- import { TracingService } from './tracing';
17
-
18
- // TODO(dmaretskyi): Refactor this module to only rely on tags and not the human-assigned names.
19
-
20
- /**
21
- * List of all services.
22
- */
23
- const SERVICES = {
24
- ai: AiService.AiService,
25
- credentials: CredentialsService,
26
- database: DatabaseService,
27
- eventLogger: ComputeEventLogger,
28
- functionCallService: RemoteFunctionExecutionService,
29
- queues: QueueService,
30
- tracing: TracingService,
31
- } as const satisfies Record<string, Context.TagClass<any, string, any>>;
32
-
33
- /**
34
- * Mapping of service names to their tags.
35
- */
36
- export type ServiceTagRecord = {
37
- [K in keyof typeof SERVICES]: (typeof SERVICES)[K] extends { new (_: never): infer T } ? T : never;
38
- };
39
-
40
- /**
41
- * Mapping of service names to their runtime types.
42
- */
43
- export type ServiceRecord = {
44
- [K in keyof ServiceTagRecord]: Context.Tag.Service<ServiceTagRecord[K]>;
45
- };
46
-
47
- /**
48
- * Union of all services tags.
49
- */
50
- export type Services = ServiceTagRecord[keyof ServiceTagRecord];
51
-
52
- const SERVICE_MAPPING: Record<string, keyof ServiceRecord> = Object.fromEntries(
53
- entries(SERVICES).map(([name, tag]) => [tag.key, name]),
54
- );
55
-
56
- export const SERVICE_TAGS: Context.Tag<any, any>[] = Object.values(SERVICES);
57
-
58
- const DEFAULT_SERVICES: Partial<ServiceRecord> = {
59
- tracing: TracingService.noop,
60
- };
61
-
62
- /**
63
- * @deprecated
64
- */
65
- export class ServiceContainer {
66
- private _services: Partial<ServiceRecord> = { ...DEFAULT_SERVICES };
67
-
68
- /**
69
- * Set services.
70
- * @param services - Services to set.
71
- * @returns The container instance.
72
- */
73
- setServices(services: Partial<ServiceRecord>): this {
74
- this._services = { ...this._services, ...services };
75
- return this;
76
- }
77
-
78
- getService<Id, T>(tag: Context.Tag<Id, T>): T {
79
- const serviceKey = SERVICE_MAPPING[tag.key];
80
- const service = serviceKey != null ? this._services[serviceKey] : undefined;
81
- if (!service) {
82
- throw new Error(`Service not available: ${tag.key}`);
83
- }
84
-
85
- return service as T;
86
- }
87
-
88
- clone(): ServiceContainer {
89
- return new ServiceContainer().setServices({ ...this._services });
90
- }
91
-
92
- // TODO(dmaretskyi): `getService` is designed to error at runtime if the service is not available, but Layer forces us to provide all services and makes stubs for the ones that are not available.
93
- createLayer(): Layer.Layer<Services> {
94
- const ai =
95
- this._services.ai != null ? Layer.succeed(AiService.AiService, this._services.ai) : AiService.notAvailable;
96
- const credentials = Layer.succeed(
97
- CredentialsService,
98
- this._services.credentials ?? new ConfiguredCredentialsService(),
99
- );
100
- const database =
101
- this._services.database != null
102
- ? Layer.succeed(DatabaseService, this._services.database)
103
- : DatabaseService.notAvailable;
104
- const queues =
105
- this._services.queues != null ? Layer.succeed(QueueService, this._services.queues) : QueueService.notAvailable;
106
- const tracing = Layer.succeed(TracingService, this._services.tracing ?? TracingService.noop);
107
- const eventLogger = Layer.succeed(ComputeEventLogger, this._services.eventLogger ?? ComputeEventLogger.noop);
108
- const functionCallService = Layer.succeed(
109
- RemoteFunctionExecutionService,
110
- this._services.functionCallService ?? RemoteFunctionExecutionService.mock(),
111
- );
112
-
113
- return Layer.mergeAll(ai, credentials, database, queues, tracing, eventLogger, functionCallService);
114
- }
115
- }
@@ -1,45 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- import { describe, it } from '@effect/vitest';
6
- import * as Context from 'effect/Context';
7
- import * as Effect from 'effect/Effect';
8
- import * as Layer from 'effect/Layer';
9
- import * as Option from 'effect/Option';
10
-
11
- import { ServiceRegistry } from './service-registry';
12
-
13
- class MyTag extends Context.Tag('MyTag')<MyTag, { value: string }>() {}
14
-
15
- const mockRegistry = Layer.succeed(ServiceRegistry, {
16
- resolve: (tag) => ((tag as any) === MyTag ? Option.some({ value: 'test' } as any) : Option.none()),
17
- });
18
-
19
- describe('ServiceRegistry', () => {
20
- it.effect(
21
- 'provide',
22
- Effect.fn(function* ({ expect }) {
23
- const body = Effect.gen(function* () {
24
- const { value } = yield* MyTag;
25
- expect(value).toEqual('test');
26
- });
27
-
28
- const eff = body.pipe(ServiceRegistry.provide(MyTag));
29
- yield* eff;
30
- }, Effect.provide(mockRegistry)),
31
- );
32
-
33
- it.effect(
34
- 'provide or die',
35
- Effect.fn(function* ({ expect }) {
36
- const body = Effect.gen(function* () {
37
- const { value } = yield* MyTag;
38
- expect(value).toEqual('test');
39
- });
40
-
41
- const eff = body.pipe(ServiceRegistry.provideOrDie(MyTag));
42
- yield* eff;
43
- }, Effect.provide(mockRegistry)),
44
- );
45
- });