@dxos/functions 0.8.4-main.a4bbb77 → 0.8.4-main.abd8ff62ef

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 (181) hide show
  1. package/README.md +4 -6
  2. package/dist/lib/neutral/index.mjs +475 -0
  3. package/dist/lib/neutral/index.mjs.map +7 -0
  4. package/dist/lib/neutral/meta.json +1 -0
  5. package/dist/types/src/index.d.ts +3 -9
  6. package/dist/types/src/index.d.ts.map +1 -1
  7. package/dist/types/src/protocol/functions-ai-http-client.d.ts +12 -0
  8. package/dist/types/src/protocol/functions-ai-http-client.d.ts.map +1 -0
  9. package/dist/types/src/protocol/index.d.ts +2 -0
  10. package/dist/types/src/protocol/index.d.ts.map +1 -0
  11. package/dist/types/src/protocol/protocol.d.ts +7 -0
  12. package/dist/types/src/protocol/protocol.d.ts.map +1 -0
  13. package/dist/types/src/protocol/protocol.test.d.ts +2 -0
  14. package/dist/types/src/protocol/protocol.test.d.ts.map +1 -0
  15. package/dist/types/src/sdk.d.ts +10 -0
  16. package/dist/types/src/sdk.d.ts.map +1 -0
  17. package/dist/types/src/services/credentials.d.ts +22 -39
  18. package/dist/types/src/services/credentials.d.ts.map +1 -1
  19. package/dist/types/src/services/function-invocation-service.d.ts +9 -20
  20. package/dist/types/src/services/function-invocation-service.d.ts.map +1 -1
  21. package/dist/types/src/services/index.d.ts +1 -6
  22. package/dist/types/src/services/index.d.ts.map +1 -1
  23. package/dist/types/src/services/queues.d.ts +1 -44
  24. package/dist/types/src/services/queues.d.ts.map +1 -1
  25. package/dist/types/src/services/tracing.d.ts +2 -54
  26. package/dist/types/src/services/tracing.d.ts.map +1 -1
  27. package/dist/types/src/types/index.d.ts +2 -0
  28. package/dist/types/src/types/index.d.ts.map +1 -0
  29. package/dist/types/src/types/url.d.ts +13 -0
  30. package/dist/types/src/types/url.d.ts.map +1 -0
  31. package/dist/types/tsconfig.tsbuildinfo +1 -1
  32. package/package.json +25 -72
  33. package/src/index.ts +3 -9
  34. package/src/protocol/functions-ai-http-client.ts +67 -0
  35. package/src/{executor → protocol}/index.ts +1 -1
  36. package/src/protocol/protocol.test.ts +58 -0
  37. package/src/protocol/protocol.ts +292 -0
  38. package/src/sdk.ts +29 -0
  39. package/src/services/credentials.ts +89 -112
  40. package/src/services/function-invocation-service.ts +22 -71
  41. package/src/services/index.ts +1 -6
  42. package/src/services/queues.ts +1 -78
  43. package/src/services/tracing.ts +1 -134
  44. package/src/types/index.ts +5 -0
  45. package/src/types/url.ts +32 -0
  46. package/dist/lib/browser/bundler/index.mjs +0 -265
  47. package/dist/lib/browser/bundler/index.mjs.map +0 -7
  48. package/dist/lib/browser/chunk-C2Z7LCJ2.mjs +0 -649
  49. package/dist/lib/browser/chunk-C2Z7LCJ2.mjs.map +0 -7
  50. package/dist/lib/browser/chunk-J5LGTIGS.mjs +0 -10
  51. package/dist/lib/browser/chunk-J5LGTIGS.mjs.map +0 -7
  52. package/dist/lib/browser/edge/index.mjs +0 -83
  53. package/dist/lib/browser/edge/index.mjs.map +0 -7
  54. package/dist/lib/browser/index.mjs +0 -1366
  55. package/dist/lib/browser/index.mjs.map +0 -7
  56. package/dist/lib/browser/meta.json +0 -1
  57. package/dist/lib/browser/testing/index.mjs +0 -129
  58. package/dist/lib/browser/testing/index.mjs.map +0 -7
  59. package/dist/lib/node-esm/bundler/index.mjs +0 -266
  60. package/dist/lib/node-esm/bundler/index.mjs.map +0 -7
  61. package/dist/lib/node-esm/chunk-AH3AZM2U.mjs +0 -651
  62. package/dist/lib/node-esm/chunk-AH3AZM2U.mjs.map +0 -7
  63. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs +0 -11
  64. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs.map +0 -7
  65. package/dist/lib/node-esm/edge/index.mjs +0 -84
  66. package/dist/lib/node-esm/edge/index.mjs.map +0 -7
  67. package/dist/lib/node-esm/index.mjs +0 -1367
  68. package/dist/lib/node-esm/index.mjs.map +0 -7
  69. package/dist/lib/node-esm/meta.json +0 -1
  70. package/dist/lib/node-esm/testing/index.mjs +0 -130
  71. package/dist/lib/node-esm/testing/index.mjs.map +0 -7
  72. package/dist/types/src/bundler/bundler.d.ts +0 -49
  73. package/dist/types/src/bundler/bundler.d.ts.map +0 -1
  74. package/dist/types/src/bundler/bundler.test.d.ts +0 -2
  75. package/dist/types/src/bundler/bundler.test.d.ts.map +0 -1
  76. package/dist/types/src/bundler/index.d.ts +0 -2
  77. package/dist/types/src/bundler/index.d.ts.map +0 -1
  78. package/dist/types/src/edge/functions.d.ts +0 -17
  79. package/dist/types/src/edge/functions.d.ts.map +0 -1
  80. package/dist/types/src/edge/index.d.ts +0 -2
  81. package/dist/types/src/edge/index.d.ts.map +0 -1
  82. package/dist/types/src/errors.d.ts +0 -137
  83. package/dist/types/src/errors.d.ts.map +0 -1
  84. package/dist/types/src/examples/fib.d.ts +0 -7
  85. package/dist/types/src/examples/fib.d.ts.map +0 -1
  86. package/dist/types/src/examples/index.d.ts +0 -4
  87. package/dist/types/src/examples/index.d.ts.map +0 -1
  88. package/dist/types/src/examples/reply.d.ts +0 -3
  89. package/dist/types/src/examples/reply.d.ts.map +0 -1
  90. package/dist/types/src/examples/sleep.d.ts +0 -5
  91. package/dist/types/src/examples/sleep.d.ts.map +0 -1
  92. package/dist/types/src/executor/executor.d.ts +0 -14
  93. package/dist/types/src/executor/executor.d.ts.map +0 -1
  94. package/dist/types/src/executor/index.d.ts +0 -2
  95. package/dist/types/src/executor/index.d.ts.map +0 -1
  96. package/dist/types/src/handler.d.ts +0 -106
  97. package/dist/types/src/handler.d.ts.map +0 -1
  98. package/dist/types/src/schema.d.ts +0 -43
  99. package/dist/types/src/schema.d.ts.map +0 -1
  100. package/dist/types/src/services/database.d.ts +0 -63
  101. package/dist/types/src/services/database.d.ts.map +0 -1
  102. package/dist/types/src/services/event-logger.d.ts +0 -72
  103. package/dist/types/src/services/event-logger.d.ts.map +0 -1
  104. package/dist/types/src/services/function-invocation-service.test.d.ts +0 -2
  105. package/dist/types/src/services/function-invocation-service.test.d.ts.map +0 -1
  106. package/dist/types/src/services/local-function-execution.d.ts +0 -32
  107. package/dist/types/src/services/local-function-execution.d.ts.map +0 -1
  108. package/dist/types/src/services/remote-function-execution-service.d.ts +0 -20
  109. package/dist/types/src/services/remote-function-execution-service.d.ts.map +0 -1
  110. package/dist/types/src/services/service-container.d.ts +0 -56
  111. package/dist/types/src/services/service-container.d.ts.map +0 -1
  112. package/dist/types/src/services/service-registry.d.ts +0 -29
  113. package/dist/types/src/services/service-registry.d.ts.map +0 -1
  114. package/dist/types/src/services/service-registry.test.d.ts +0 -2
  115. package/dist/types/src/services/service-registry.test.d.ts.map +0 -1
  116. package/dist/types/src/testing/index.d.ts +0 -3
  117. package/dist/types/src/testing/index.d.ts.map +0 -1
  118. package/dist/types/src/testing/layer.d.ts +0 -17
  119. package/dist/types/src/testing/layer.d.ts.map +0 -1
  120. package/dist/types/src/testing/logger.d.ts +0 -5
  121. package/dist/types/src/testing/logger.d.ts.map +0 -1
  122. package/dist/types/src/testing/persist-database.test.d.ts +0 -2
  123. package/dist/types/src/testing/persist-database.test.d.ts.map +0 -1
  124. package/dist/types/src/testing/services.d.ts +0 -59
  125. package/dist/types/src/testing/services.d.ts.map +0 -1
  126. package/dist/types/src/trace.d.ts +0 -122
  127. package/dist/types/src/trace.d.ts.map +0 -1
  128. package/dist/types/src/translations.d.ts +0 -12
  129. package/dist/types/src/translations.d.ts.map +0 -1
  130. package/dist/types/src/triggers/index.d.ts +0 -4
  131. package/dist/types/src/triggers/index.d.ts.map +0 -1
  132. package/dist/types/src/triggers/input-builder.d.ts +0 -3
  133. package/dist/types/src/triggers/input-builder.d.ts.map +0 -1
  134. package/dist/types/src/triggers/invocation-tracer.d.ts +0 -35
  135. package/dist/types/src/triggers/invocation-tracer.d.ts.map +0 -1
  136. package/dist/types/src/triggers/trigger-dispatcher.d.ts +0 -74
  137. package/dist/types/src/triggers/trigger-dispatcher.d.ts.map +0 -1
  138. package/dist/types/src/triggers/trigger-dispatcher.test.d.ts +0 -2
  139. package/dist/types/src/triggers/trigger-dispatcher.test.d.ts.map +0 -1
  140. package/dist/types/src/triggers/trigger-state-store.d.ts +0 -27
  141. package/dist/types/src/triggers/trigger-state-store.d.ts.map +0 -1
  142. package/dist/types/src/types.d.ts +0 -221
  143. package/dist/types/src/types.d.ts.map +0 -1
  144. package/dist/types/src/url.d.ts +0 -21
  145. package/dist/types/src/url.d.ts.map +0 -1
  146. package/src/bundler/bundler.test.ts +0 -58
  147. package/src/bundler/bundler.ts +0 -291
  148. package/src/bundler/index.ts +0 -5
  149. package/src/edge/functions.ts +0 -67
  150. package/src/edge/index.ts +0 -9
  151. package/src/errors.ts +0 -21
  152. package/src/examples/fib.ts +0 -31
  153. package/src/examples/index.ts +0 -7
  154. package/src/examples/reply.ts +0 -19
  155. package/src/examples/sleep.ts +0 -23
  156. package/src/executor/executor.ts +0 -57
  157. package/src/handler.ts +0 -222
  158. package/src/schema.ts +0 -68
  159. package/src/services/database.ts +0 -171
  160. package/src/services/event-logger.ts +0 -118
  161. package/src/services/function-invocation-service.test.ts +0 -79
  162. package/src/services/local-function-execution.ts +0 -150
  163. package/src/services/remote-function-execution-service.ts +0 -61
  164. package/src/services/service-container.ts +0 -114
  165. package/src/services/service-registry.test.ts +0 -42
  166. package/src/services/service-registry.ts +0 -59
  167. package/src/testing/index.ts +0 -6
  168. package/src/testing/layer.ts +0 -112
  169. package/src/testing/logger.ts +0 -16
  170. package/src/testing/persist-database.test.ts +0 -87
  171. package/src/testing/services.ts +0 -115
  172. package/src/trace.ts +0 -178
  173. package/src/translations.ts +0 -20
  174. package/src/triggers/index.ts +0 -7
  175. package/src/triggers/input-builder.ts +0 -35
  176. package/src/triggers/invocation-tracer.ts +0 -99
  177. package/src/triggers/trigger-dispatcher.test.ts +0 -651
  178. package/src/triggers/trigger-dispatcher.ts +0 -522
  179. package/src/triggers/trigger-state-store.ts +0 -60
  180. package/src/types.ts +0 -214
  181. package/src/url.ts +0 -55
@@ -1,118 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- import { Context, Effect, Layer, Schema } from 'effect';
6
-
7
- import { Obj, Type } from '@dxos/echo';
8
- import { invariant } from '@dxos/invariant';
9
- import { LogLevel, log } from '@dxos/log';
10
-
11
- import { TracingService } from './tracing';
12
-
13
- export const ComputeEventPayload = Schema.Union(
14
- Schema.Struct({
15
- type: Schema.Literal('begin-compute'),
16
- nodeId: Schema.String,
17
- inputs: Schema.Record({ key: Schema.String, value: Schema.Any }),
18
- }),
19
- Schema.Struct({
20
- type: Schema.Literal('end-compute'),
21
- nodeId: Schema.String,
22
- outputs: Schema.Record({ key: Schema.String, value: Schema.Any }),
23
- }),
24
- Schema.Struct({
25
- type: Schema.Literal('compute-input'),
26
- nodeId: Schema.String,
27
- property: Schema.String,
28
- value: Schema.Any,
29
- }),
30
- Schema.Struct({
31
- type: Schema.Literal('compute-output'),
32
- nodeId: Schema.String,
33
- property: Schema.String,
34
- value: Schema.Any,
35
- }),
36
- Schema.Struct({
37
- type: Schema.Literal('custom'),
38
- nodeId: Schema.String,
39
- event: Schema.Any,
40
- }),
41
- );
42
- export type ComputeEventPayload = Schema.Schema.Type<typeof ComputeEventPayload>;
43
-
44
- export const ComputeEvent = Schema.Struct({
45
- payload: ComputeEventPayload,
46
- }).pipe(Type.Obj({ typename: 'dxos.org/type/ComputeEvent', version: '0.1.0' }));
47
-
48
- /**
49
- * Logs event for the compute workflows.
50
- */
51
- export class ComputeEventLogger extends Context.Tag('@dxos/functions/ComputeEventLogger')<
52
- ComputeEventLogger,
53
- { readonly log: (event: ComputeEventPayload) => void; readonly nodeId: string | undefined }
54
- >() {
55
- static noop: Context.Tag.Service<ComputeEventLogger> = {
56
- log: () => {},
57
- nodeId: undefined,
58
- };
59
-
60
- /**
61
- * Implements ComputeEventLogger using TracingService.
62
- */
63
- static layerFromTracing = Layer.effect(
64
- ComputeEventLogger,
65
- Effect.gen(function* () {
66
- const tracing = yield* TracingService;
67
- return {
68
- log: (event: ComputeEventPayload) => {
69
- tracing.write(Obj.make(ComputeEvent, { payload: event }));
70
- },
71
- nodeId: undefined,
72
- };
73
- }),
74
- );
75
- }
76
-
77
- export const logCustomEvent = (data: any) =>
78
- Effect.gen(function* () {
79
- const logger = yield* ComputeEventLogger;
80
- if (!logger.nodeId) {
81
- throw new Error('logCustomEvent must be called within a node compute function');
82
- }
83
- logger.log({
84
- type: 'custom',
85
- nodeId: logger.nodeId,
86
- event: data,
87
- });
88
- });
89
-
90
- export const createDefectLogger = <A, E, R>(): ((self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>) =>
91
- Effect.catchAll((error) =>
92
- Effect.gen(function* () {
93
- log.error('unhandled effect error', { error });
94
- throw error;
95
- }),
96
- );
97
-
98
- export const createEventLogger = (
99
- level: LogLevel,
100
- message: string = 'event',
101
- ): Context.Tag.Service<ComputeEventLogger> => {
102
- const logFunction = (
103
- {
104
- [LogLevel.WARN]: log.warn,
105
- [LogLevel.VERBOSE]: log.verbose,
106
- [LogLevel.DEBUG]: log.debug,
107
- [LogLevel.INFO]: log.info,
108
- [LogLevel.ERROR]: log.error,
109
- } as any
110
- )[level];
111
- invariant(logFunction);
112
- return {
113
- log: (event: ComputeEventPayload) => {
114
- logFunction(message, event);
115
- },
116
- nodeId: undefined,
117
- };
118
- };
@@ -1,79 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- import { describe, expect, it } from '@effect/vitest';
6
- import { Effect, Layer, Schema } from 'effect';
7
-
8
- import { AiService } from '@dxos/ai';
9
-
10
- import { defineFunction } from '../handler';
11
- import { TestDatabaseLayer } from '../testing';
12
-
13
- import { FunctionInvocationService } from './function-invocation-service';
14
- import { FunctionImplementationResolver } from './local-function-execution';
15
-
16
- const TestLayer = Layer.mergeAll(AiService.model('@anthropic/claude-opus-4-0')).pipe(
17
- Layer.provideMerge(
18
- Layer.mergeAll(
19
- TestDatabaseLayer({
20
- indexing: { vector: true },
21
- types: [],
22
- }),
23
- FunctionInvocationService.layer,
24
- ),
25
- ),
26
- );
27
-
28
- describe('FunctionInvocationService', () => {
29
- it(
30
- 'should be defined',
31
- Effect.fnUntraced(function* () {
32
- const service = yield* FunctionInvocationService;
33
- expect(service).toBeDefined();
34
- }, Effect.provide(TestLayer)),
35
- );
36
-
37
- it(
38
- 'routes to local when implementation is available',
39
- Effect.fnUntraced(function* () {
40
- const add = defineFunction({
41
- key: 'example.org/function/add',
42
- name: 'add',
43
- inputSchema: Schema.Struct({ a: Schema.Number, b: Schema.Number }),
44
- outputSchema: Schema.Number,
45
- handler: ({ data }) => data.a + data.b,
46
- });
47
-
48
- const layer = TestLayer.pipe(Layer.provideMerge(FunctionImplementationResolver.layerTest({ functions: [add] })));
49
-
50
- const result = yield* Effect.gen(function* () {
51
- return yield* FunctionInvocationService.invokeFunction(add, { a: 2, b: 3 });
52
- }).pipe(Effect.provide(layer));
53
-
54
- expect(result).toEqual(5);
55
- }),
56
- );
57
-
58
- it(
59
- 'routes to remote when no local implementation is found',
60
- Effect.fnUntraced(function* () {
61
- // This function is not deployed, so mock layer will be used.
62
- const echo = defineFunction({
63
- key: 'example.org/function/echo',
64
- name: 'function-that-is-deployed',
65
- inputSchema: Schema.Unknown,
66
- outputSchema: Schema.Unknown,
67
- handler: () => {},
68
- });
69
-
70
- // No resolver provided → resolveFunctionImplementation will fail → remote path is used.
71
- const result = yield* Effect.gen(function* () {
72
- return yield* FunctionInvocationService.invokeFunction(echo, { hello: 'world' });
73
- }).pipe(Effect.provide(TestLayer));
74
-
75
- // RemoteFunctionExecutionService.mock echos input back.
76
- expect(result).toEqual({ hello: 'world', resolved: 'remote' });
77
- }),
78
- );
79
- });
@@ -1,150 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- import { Context, Effect, Layer, Schema } from 'effect';
6
-
7
- import { AiService } from '@dxos/ai';
8
- import { todo } from '@dxos/debug';
9
- import { log } from '@dxos/log';
10
-
11
- import { FunctionError, FunctionNotFoundError } from '../errors';
12
- import type { FunctionContext, FunctionDefinition } from '../handler';
13
-
14
- import { CredentialsService } from './credentials';
15
- import { DatabaseService } from './database';
16
- import { type ComputeEventLogger } from './event-logger';
17
- import { QueueService } from './queues';
18
- import { RemoteFunctionExecutionService } from './remote-function-execution-service';
19
- import type { Services } from './service-container';
20
- import { type TracingService } from './tracing';
21
-
22
- /**
23
- * Services that are provided at the function call site.
24
- */
25
- export type InvocationServices = TracingService | ComputeEventLogger;
26
-
27
- export class LocalFunctionExecutionService extends Context.Tag('@dxos/functions/LocalFunctionExecutionService')<
28
- LocalFunctionExecutionService,
29
- {
30
- // TODO(dmaretskyi): This should take function id instead of the definition object.
31
- // TODO(dmaretskyi): Services should be satisfied from environment rather then bubbled up.
32
- invokeFunction<I, O>(functionDef: FunctionDefinition<I, O>, input: I): Effect.Effect<O, never, InvocationServices>;
33
- }
34
- >() {
35
- static layerLive = Layer.effect(
36
- LocalFunctionExecutionService,
37
- Effect.gen(function* () {
38
- // TODO(dmaretskyi): Use `yield* Effect.context()`;
39
- const resolver = yield* FunctionImplementationResolver;
40
- const ai = yield* AiService.AiService;
41
- const credentials = yield* CredentialsService;
42
- const database = yield* DatabaseService;
43
- const queues = yield* QueueService;
44
- // TODO(mykola): Delete, should not be required for local execution.
45
- const functionCallService = yield* RemoteFunctionExecutionService;
46
- return {
47
- // TODO(dmaretskyi): Better error types.
48
- invokeFunction: <I, O>(
49
- functionDef: FunctionDefinition<I, O>,
50
- input: I,
51
- ): Effect.Effect<O, never, InvocationServices> =>
52
- Effect.gen(function* () {
53
- const resolved = yield* resolver.resolveFunctionImplementation(functionDef).pipe(Effect.orDie);
54
- const output = yield* invokeFunction(resolved, input);
55
- return output as O;
56
- }).pipe(
57
- Effect.provideService(AiService.AiService, ai),
58
- Effect.provideService(CredentialsService, credentials),
59
- Effect.provideService(DatabaseService, database),
60
- Effect.provideService(QueueService, queues),
61
- Effect.provideService(RemoteFunctionExecutionService, functionCallService),
62
- ),
63
- };
64
- }),
65
- );
66
-
67
- static invokeFunction: <F extends FunctionDefinition.Any>(
68
- functionDef: F,
69
- input: FunctionDefinition.Input<F>,
70
- ) => Effect.Effect<FunctionDefinition.Output<F>, never, Services | LocalFunctionExecutionService> =
71
- Effect.serviceFunctionEffect(LocalFunctionExecutionService, (_) => _.invokeFunction as any);
72
- }
73
-
74
- const invokeFunction = (
75
- functionDef: FunctionDefinition<any, any>,
76
- input: any,
77
- ): Effect.Effect<unknown, never, Services> =>
78
- Effect.gen(function* () {
79
- // Assert input matches schema
80
- try {
81
- const assertInput = functionDef.inputSchema.pipe(Schema.asserts);
82
- (assertInput as any)(input);
83
- } catch (e) {
84
- throw new FunctionError({ message: 'Invalid function input', context: { name: functionDef.name }, cause: e });
85
- }
86
-
87
- const context: FunctionContext = {
88
- space: undefined,
89
- getService: () => todo(),
90
- getSpace: async (_spaceId: any) => {
91
- throw new Error('Not available. Use the database service instead.');
92
- },
93
- };
94
-
95
- log.info('Invoking function', { name: functionDef.name, input });
96
-
97
- // TODO(dmaretskyi): This should be delegated to a function invoker service.
98
- const data = yield* Effect.gen(function* () {
99
- const result = functionDef.handler({ context, data: input });
100
- if (Effect.isEffect(result)) {
101
- return yield* (result as Effect.Effect<unknown, unknown, Services>).pipe(Effect.orDie);
102
- } else if (
103
- typeof result === 'object' &&
104
- result !== null &&
105
- 'then' in result &&
106
- typeof result.then === 'function'
107
- ) {
108
- return yield* Effect.promise(() => result);
109
- } else {
110
- return result;
111
- }
112
- }).pipe(
113
- Effect.orDie,
114
- Effect.catchAllDefect((defect) =>
115
- Effect.die(new FunctionError({ context: { name: functionDef.name }, cause: defect })),
116
- ),
117
- );
118
-
119
- log.info('Function completed', { name: functionDef.name, input, data });
120
-
121
- // Assert output matches schema
122
- try {
123
- const assertOutput = functionDef.outputSchema?.pipe(Schema.asserts);
124
- (assertOutput as any)(data);
125
- } catch (e) {
126
- throw new FunctionError({ message: 'Invalid function output', context: { name: functionDef.name }, cause: e });
127
- }
128
-
129
- return data;
130
- }).pipe(Effect.withSpan('invokeFunction', { attributes: { name: functionDef.name } }));
131
-
132
- export class FunctionImplementationResolver extends Context.Tag('@dxos/functions/FunctionImplementationResolver')<
133
- FunctionImplementationResolver,
134
- {
135
- resolveFunctionImplementation<I, O>(
136
- functionDef: FunctionDefinition<I, O>,
137
- ): Effect.Effect<FunctionDefinition<I, O>, FunctionNotFoundError>;
138
- }
139
- >() {
140
- static layerTest = ({ functions }: { functions: FunctionDefinition<any, any>[] }) =>
141
- Layer.succeed(FunctionImplementationResolver, {
142
- resolveFunctionImplementation: <I, O>(functionDef: FunctionDefinition<I, O>) => {
143
- const resolved = functions.find((f) => f.key === functionDef.key);
144
- if (!resolved) {
145
- return Effect.fail(new FunctionNotFoundError(functionDef.name));
146
- }
147
- return Effect.succeed(resolved);
148
- },
149
- });
150
- }
@@ -1,61 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- import { Context, Effect, Layer } from 'effect';
6
-
7
- import type { SpaceId } from '@dxos/keys';
8
-
9
- import { FunctionError } from '../errors';
10
- import { getInvocationUrl } from '../url';
11
-
12
- /**
13
- * Allows calling into other functions.
14
- */
15
- export class RemoteFunctionExecutionService extends Context.Tag('@dxos/functions/RemoteFunctionExecutionService')<
16
- RemoteFunctionExecutionService,
17
- {
18
- callFunction<I, O>(deployedFunctionId: string, input: I): Effect.Effect<O>;
19
- }
20
- >() {
21
- /**
22
- * @param baseUrl URL of the EDGE server.
23
- * @param spaceId - The space ID to invoke the function in. If not provided, the function will be without space context.
24
- * @returns
25
- */
26
- static fromClient(baseUrl: string, spaceId?: SpaceId): Layer.Layer<RemoteFunctionExecutionService> {
27
- return Layer.succeed(RemoteFunctionExecutionService, {
28
- callFunction: <I, O>(deployedFunctionId: string, input: I): Effect.Effect<O> =>
29
- Effect.gen(function* () {
30
- const url = getInvocationUrl(deployedFunctionId, baseUrl, { spaceId });
31
- const result = yield* Effect.promise(() =>
32
- fetch(url, {
33
- method: 'POST',
34
- headers: { 'Content-Type': 'application/json' },
35
- body: JSON.stringify(input),
36
- }),
37
- );
38
- if (result.status >= 300 || result.status < 200) {
39
- const text = yield* Effect.promise(() => result.text());
40
- return yield* Effect.die(
41
- new FunctionError({
42
- message: 'Failed to invoke function',
43
- cause: new Error(`HTTP error: ${text}`),
44
- }),
45
- );
46
- }
47
- const data = (yield* Effect.promise(() => result.json())) as O;
48
- return data;
49
- }),
50
- });
51
- }
52
-
53
- static mock = (): Context.Tag.Service<RemoteFunctionExecutionService> => {
54
- return {
55
- callFunction: <I, O>(deployedFunctionId: string, input: I): Effect.Effect<O> =>
56
- Effect.succeed(input as unknown as O),
57
- };
58
- };
59
-
60
- static layerMock = Layer.succeed(RemoteFunctionExecutionService, RemoteFunctionExecutionService.mock());
61
- }
@@ -1,114 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- import { type Context, Layer } from 'effect';
6
-
7
- import { AiService } from '@dxos/ai';
8
- import { entries } from '@dxos/util';
9
-
10
- import { ConfiguredCredentialsService, CredentialsService } from './credentials';
11
- import { DatabaseService } from './database';
12
- import { ComputeEventLogger } from './event-logger';
13
- import { QueueService } from './queues';
14
- import { RemoteFunctionExecutionService } from './remote-function-execution-service';
15
- import { TracingService } from './tracing';
16
-
17
- // TODO(dmaretskyi): Refactor this module to only rely on tags and not the human-assigned names.
18
-
19
- /**
20
- * List of all services.
21
- */
22
- const SERVICES = {
23
- ai: AiService.AiService,
24
- credentials: CredentialsService,
25
- database: DatabaseService,
26
- eventLogger: ComputeEventLogger,
27
- functionCallService: RemoteFunctionExecutionService,
28
- queues: QueueService,
29
- tracing: TracingService,
30
- } as const satisfies Record<string, Context.TagClass<any, string, any>>;
31
-
32
- /**
33
- * Mapping of service names to their tags.
34
- */
35
- export type ServiceTagRecord = {
36
- [K in keyof typeof SERVICES]: (typeof SERVICES)[K] extends { new (_: never): infer T } ? T : never;
37
- };
38
-
39
- /**
40
- * Mapping of service names to their runtime types.
41
- */
42
- export type ServiceRecord = {
43
- [K in keyof ServiceTagRecord]: Context.Tag.Service<ServiceTagRecord[K]>;
44
- };
45
-
46
- /**
47
- * Union of all services tags.
48
- */
49
- export type Services = ServiceTagRecord[keyof ServiceTagRecord];
50
-
51
- const SERVICE_MAPPING: Record<string, keyof ServiceRecord> = Object.fromEntries(
52
- entries(SERVICES).map(([name, tag]) => [tag.key, name]),
53
- );
54
-
55
- export const SERVICE_TAGS: Context.Tag<any, any>[] = Object.values(SERVICES);
56
-
57
- const DEFAULT_SERVICES: Partial<ServiceRecord> = {
58
- tracing: TracingService.noop,
59
- };
60
-
61
- /**
62
- * @deprecated
63
- */
64
- export class ServiceContainer {
65
- private _services: Partial<ServiceRecord> = { ...DEFAULT_SERVICES };
66
-
67
- /**
68
- * Set services.
69
- * @param services - Services to set.
70
- * @returns The container instance.
71
- */
72
- setServices(services: Partial<ServiceRecord>): this {
73
- this._services = { ...this._services, ...services };
74
- return this;
75
- }
76
-
77
- getService<Id, T>(tag: Context.Tag<Id, T>): T {
78
- const serviceKey = SERVICE_MAPPING[tag.key];
79
- const service = serviceKey != null ? this._services[serviceKey] : undefined;
80
- if (!service) {
81
- throw new Error(`Service not available: ${tag.key}`);
82
- }
83
-
84
- return service as T;
85
- }
86
-
87
- clone(): ServiceContainer {
88
- return new ServiceContainer().setServices({ ...this._services });
89
- }
90
-
91
- // 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.
92
- createLayer(): Layer.Layer<Services> {
93
- const ai =
94
- this._services.ai != null ? Layer.succeed(AiService.AiService, this._services.ai) : AiService.notAvailable;
95
- const credentials = Layer.succeed(
96
- CredentialsService,
97
- this._services.credentials ?? new ConfiguredCredentialsService(),
98
- );
99
- const database =
100
- this._services.database != null
101
- ? Layer.succeed(DatabaseService, this._services.database)
102
- : DatabaseService.notAvailable;
103
- const queues =
104
- this._services.queues != null ? Layer.succeed(QueueService, this._services.queues) : QueueService.notAvailable;
105
- const tracing = Layer.succeed(TracingService, this._services.tracing ?? TracingService.noop);
106
- const eventLogger = Layer.succeed(ComputeEventLogger, this._services.eventLogger ?? ComputeEventLogger.noop);
107
- const functionCallService = Layer.succeed(
108
- RemoteFunctionExecutionService,
109
- this._services.functionCallService ?? RemoteFunctionExecutionService.mock(),
110
- );
111
-
112
- return Layer.mergeAll(ai, credentials, database, queues, tracing, eventLogger, functionCallService);
113
- }
114
- }
@@ -1,42 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- import { describe, it } from '@effect/vitest';
6
- import { Context, Effect, Layer, Option } from 'effect';
7
-
8
- import { ServiceRegistry } from './service-registry';
9
-
10
- class MyTag extends Context.Tag('MyTag')<MyTag, { value: string }>() {}
11
-
12
- const mockRegistry = Layer.succeed(ServiceRegistry, {
13
- resolve: (tag) => ((tag as any) === MyTag ? Option.some({ value: 'test' } as any) : Option.none()),
14
- });
15
-
16
- describe('ServiceRegistry', () => {
17
- it.effect(
18
- 'provide',
19
- Effect.fn(function* ({ expect }) {
20
- const body = Effect.gen(function* () {
21
- const { value } = yield* MyTag;
22
- expect(value).toEqual('test');
23
- });
24
-
25
- const eff = body.pipe(ServiceRegistry.provide(MyTag));
26
- yield* eff;
27
- }, Effect.provide(mockRegistry)),
28
- );
29
-
30
- it.effect(
31
- 'provide or die',
32
- Effect.fn(function* ({ expect }) {
33
- const body = Effect.gen(function* () {
34
- const { value } = yield* MyTag;
35
- expect(value).toEqual('test');
36
- });
37
-
38
- const eff = body.pipe(ServiceRegistry.provideOrDie(MyTag));
39
- yield* eff;
40
- }, Effect.provide(mockRegistry)),
41
- );
42
- });
@@ -1,59 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- import { Context, Effect, type Option, flow } from 'effect';
6
-
7
- import { ServiceNotAvailableError } from '../errors';
8
-
9
- export namespace ServiceRegistry {
10
- export interface Service {
11
- resolve: <T extends Context.Tag<any, any>>(tag: T) => Option.Option<Context.Tag.Service<T>>;
12
- }
13
- }
14
-
15
- export class ServiceRegistry extends Context.Tag('@dxos/functions/ServiceRegistry')<
16
- ServiceRegistry,
17
- ServiceRegistry.Service
18
- >() {
19
- /**
20
- * Resolves the service from the registry.
21
- * @param tag Service tag to resolve.
22
- * @throws {@link ServiceNotAvailableError} if the service is not found.
23
- * @returns Effect that resolve to the service.
24
- */
25
- static resolve: <T extends Context.Tag<any, any>>(
26
- tag: T,
27
- ) => Effect.Effect<T, ServiceNotAvailableError, ServiceRegistry> = (tag) =>
28
- ServiceRegistry.pipe(
29
- Effect.flatMap((_) => _.resolve(tag)),
30
- Effect.mapError(() => new ServiceNotAvailableError(tag.key)),
31
- );
32
-
33
- static provide: {
34
- <Tags extends [Context.Tag<any, any>, ...Context.Tag<any, any>[]]>(
35
- ...tags: Tags
36
- ): <A, E, R>(
37
- effect: Effect.Effect<A, E, R>,
38
- ) => Effect.Effect<
39
- A,
40
- E | ServiceNotAvailableError,
41
- Exclude<R, { [K in keyof Tags]: Context.Tag.Identifier<Tags[K]> }[number]> | ServiceRegistry
42
- >;
43
- } = (...tags) => (flow as any)(...tags.map((tag) => Effect.provideServiceEffect(tag, ServiceRegistry.resolve(tag))));
44
-
45
- static provideOrDie: {
46
- <Tags extends [Context.Tag<any, any>, ...Context.Tag<any, any>[]]>(
47
- ...tags: Tags
48
- ): <A, E, R>(
49
- effect: Effect.Effect<A, E, R>,
50
- ) => Effect.Effect<
51
- A,
52
- E,
53
- Exclude<R, { [K in keyof Tags]: Context.Tag.Identifier<Tags[K]> }[number]> | ServiceRegistry
54
- >;
55
- } = (...tags) =>
56
- (flow as any)(
57
- ...tags.map((tag) => Effect.provideServiceEffect(tag, ServiceRegistry.resolve(tag).pipe(Effect.orDie))),
58
- );
59
- }
@@ -1,6 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- export * from './services';
6
- export * from './layer';