@dxos/functions 0.8.4-main.ead640a → 0.8.4-main.f466a3d56e

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 (185) hide show
  1. package/LICENSE +102 -5
  2. package/README.md +5 -7
  3. package/dist/lib/neutral/index.mjs +602 -0
  4. package/dist/lib/neutral/index.mjs.map +7 -0
  5. package/dist/lib/neutral/meta.json +1 -0
  6. package/dist/types/src/index.d.ts +3 -9
  7. package/dist/types/src/index.d.ts.map +1 -1
  8. package/dist/types/src/protocol/functions-ai-http-client.d.ts +12 -0
  9. package/dist/types/src/protocol/functions-ai-http-client.d.ts.map +1 -0
  10. package/dist/types/src/protocol/functions-ai-http-client.test.d.ts +2 -0
  11. package/dist/types/src/protocol/functions-ai-http-client.test.d.ts.map +1 -0
  12. package/dist/types/src/protocol/index.d.ts +2 -0
  13. package/dist/types/src/protocol/index.d.ts.map +1 -0
  14. package/dist/types/src/protocol/protocol.d.ts +24 -0
  15. package/dist/types/src/protocol/protocol.d.ts.map +1 -0
  16. package/dist/types/src/protocol/protocol.test.d.ts +2 -0
  17. package/dist/types/src/protocol/protocol.test.d.ts.map +1 -0
  18. package/dist/types/src/sdk.d.ts +10 -0
  19. package/dist/types/src/sdk.d.ts.map +1 -0
  20. package/dist/types/src/services/credentials.d.ts +17 -38
  21. package/dist/types/src/services/credentials.d.ts.map +1 -1
  22. package/dist/types/src/services/function-invocation-service.d.ts +9 -19
  23. package/dist/types/src/services/function-invocation-service.d.ts.map +1 -1
  24. package/dist/types/src/services/index.d.ts +1 -6
  25. package/dist/types/src/services/index.d.ts.map +1 -1
  26. package/dist/types/src/services/queues.d.ts +1 -46
  27. package/dist/types/src/services/queues.d.ts.map +1 -1
  28. package/dist/types/src/services/tracing.d.ts +2 -56
  29. package/dist/types/src/services/tracing.d.ts.map +1 -1
  30. package/dist/types/src/types/index.d.ts +2 -0
  31. package/dist/types/src/types/index.d.ts.map +1 -0
  32. package/dist/types/src/types/url.d.ts +13 -0
  33. package/dist/types/src/types/url.d.ts.map +1 -0
  34. package/dist/types/tsconfig.tsbuildinfo +1 -1
  35. package/package.json +26 -64
  36. package/src/index.ts +3 -9
  37. package/src/protocol/functions-ai-http-client.test.ts +105 -0
  38. package/src/protocol/functions-ai-http-client.ts +141 -0
  39. package/src/{executor → protocol}/index.ts +1 -1
  40. package/src/protocol/protocol.test.ts +58 -0
  41. package/src/protocol/protocol.ts +455 -0
  42. package/src/sdk.ts +31 -0
  43. package/src/services/credentials.ts +81 -110
  44. package/src/services/function-invocation-service.ts +22 -70
  45. package/src/services/index.ts +1 -6
  46. package/src/services/queues.ts +1 -80
  47. package/src/services/tracing.ts +1 -136
  48. package/src/types/index.ts +5 -0
  49. package/src/types/url.ts +32 -0
  50. package/dist/lib/browser/bundler/index.mjs +0 -269
  51. package/dist/lib/browser/bundler/index.mjs.map +0 -7
  52. package/dist/lib/browser/chunk-J5LGTIGS.mjs +0 -10
  53. package/dist/lib/browser/chunk-J5LGTIGS.mjs.map +0 -7
  54. package/dist/lib/browser/chunk-LKYT2SAL.mjs +0 -665
  55. package/dist/lib/browser/chunk-LKYT2SAL.mjs.map +0 -7
  56. package/dist/lib/browser/edge/index.mjs +0 -83
  57. package/dist/lib/browser/edge/index.mjs.map +0 -7
  58. package/dist/lib/browser/index.mjs +0 -1395
  59. package/dist/lib/browser/index.mjs.map +0 -7
  60. package/dist/lib/browser/meta.json +0 -1
  61. package/dist/lib/browser/testing/index.mjs +0 -131
  62. package/dist/lib/browser/testing/index.mjs.map +0 -7
  63. package/dist/lib/node-esm/bundler/index.mjs +0 -270
  64. package/dist/lib/node-esm/bundler/index.mjs.map +0 -7
  65. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs +0 -11
  66. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs.map +0 -7
  67. package/dist/lib/node-esm/chunk-NAQIKLZB.mjs +0 -667
  68. package/dist/lib/node-esm/chunk-NAQIKLZB.mjs.map +0 -7
  69. package/dist/lib/node-esm/edge/index.mjs +0 -84
  70. package/dist/lib/node-esm/edge/index.mjs.map +0 -7
  71. package/dist/lib/node-esm/index.mjs +0 -1396
  72. package/dist/lib/node-esm/index.mjs.map +0 -7
  73. package/dist/lib/node-esm/meta.json +0 -1
  74. package/dist/lib/node-esm/testing/index.mjs +0 -132
  75. package/dist/lib/node-esm/testing/index.mjs.map +0 -7
  76. package/dist/types/src/bundler/bundler.d.ts +0 -49
  77. package/dist/types/src/bundler/bundler.d.ts.map +0 -1
  78. package/dist/types/src/bundler/bundler.test.d.ts +0 -2
  79. package/dist/types/src/bundler/bundler.test.d.ts.map +0 -1
  80. package/dist/types/src/bundler/index.d.ts +0 -2
  81. package/dist/types/src/bundler/index.d.ts.map +0 -1
  82. package/dist/types/src/edge/functions.d.ts +0 -17
  83. package/dist/types/src/edge/functions.d.ts.map +0 -1
  84. package/dist/types/src/edge/index.d.ts +0 -2
  85. package/dist/types/src/edge/index.d.ts.map +0 -1
  86. package/dist/types/src/errors.d.ts +0 -137
  87. package/dist/types/src/errors.d.ts.map +0 -1
  88. package/dist/types/src/examples/fib.d.ts +0 -7
  89. package/dist/types/src/examples/fib.d.ts.map +0 -1
  90. package/dist/types/src/examples/index.d.ts +0 -4
  91. package/dist/types/src/examples/index.d.ts.map +0 -1
  92. package/dist/types/src/examples/reply.d.ts +0 -3
  93. package/dist/types/src/examples/reply.d.ts.map +0 -1
  94. package/dist/types/src/examples/sleep.d.ts +0 -5
  95. package/dist/types/src/examples/sleep.d.ts.map +0 -1
  96. package/dist/types/src/executor/executor.d.ts +0 -14
  97. package/dist/types/src/executor/executor.d.ts.map +0 -1
  98. package/dist/types/src/executor/index.d.ts +0 -2
  99. package/dist/types/src/executor/index.d.ts.map +0 -1
  100. package/dist/types/src/handler.d.ts +0 -109
  101. package/dist/types/src/handler.d.ts.map +0 -1
  102. package/dist/types/src/schema.d.ts +0 -43
  103. package/dist/types/src/schema.d.ts.map +0 -1
  104. package/dist/types/src/services/database.d.ts +0 -67
  105. package/dist/types/src/services/database.d.ts.map +0 -1
  106. package/dist/types/src/services/event-logger.d.ts +0 -75
  107. package/dist/types/src/services/event-logger.d.ts.map +0 -1
  108. package/dist/types/src/services/function-invocation-service.test.d.ts +0 -2
  109. package/dist/types/src/services/function-invocation-service.test.d.ts.map +0 -1
  110. package/dist/types/src/services/local-function-execution.d.ts +0 -34
  111. package/dist/types/src/services/local-function-execution.d.ts.map +0 -1
  112. package/dist/types/src/services/remote-function-execution-service.d.ts +0 -22
  113. package/dist/types/src/services/remote-function-execution-service.d.ts.map +0 -1
  114. package/dist/types/src/services/service-container.d.ts +0 -57
  115. package/dist/types/src/services/service-container.d.ts.map +0 -1
  116. package/dist/types/src/services/service-registry.d.ts +0 -31
  117. package/dist/types/src/services/service-registry.d.ts.map +0 -1
  118. package/dist/types/src/services/service-registry.test.d.ts +0 -2
  119. package/dist/types/src/services/service-registry.test.d.ts.map +0 -1
  120. package/dist/types/src/testing/index.d.ts +0 -3
  121. package/dist/types/src/testing/index.d.ts.map +0 -1
  122. package/dist/types/src/testing/layer.d.ts +0 -18
  123. package/dist/types/src/testing/layer.d.ts.map +0 -1
  124. package/dist/types/src/testing/logger.d.ts +0 -5
  125. package/dist/types/src/testing/logger.d.ts.map +0 -1
  126. package/dist/types/src/testing/persist-database.test.d.ts +0 -2
  127. package/dist/types/src/testing/persist-database.test.d.ts.map +0 -1
  128. package/dist/types/src/testing/services.d.ts +0 -59
  129. package/dist/types/src/testing/services.d.ts.map +0 -1
  130. package/dist/types/src/trace.d.ts +0 -122
  131. package/dist/types/src/trace.d.ts.map +0 -1
  132. package/dist/types/src/translations.d.ts +0 -12
  133. package/dist/types/src/translations.d.ts.map +0 -1
  134. package/dist/types/src/triggers/index.d.ts +0 -4
  135. package/dist/types/src/triggers/index.d.ts.map +0 -1
  136. package/dist/types/src/triggers/input-builder.d.ts +0 -3
  137. package/dist/types/src/triggers/input-builder.d.ts.map +0 -1
  138. package/dist/types/src/triggers/invocation-tracer.d.ts +0 -37
  139. package/dist/types/src/triggers/invocation-tracer.d.ts.map +0 -1
  140. package/dist/types/src/triggers/trigger-dispatcher.d.ts +0 -78
  141. package/dist/types/src/triggers/trigger-dispatcher.d.ts.map +0 -1
  142. package/dist/types/src/triggers/trigger-dispatcher.test.d.ts +0 -2
  143. package/dist/types/src/triggers/trigger-dispatcher.test.d.ts.map +0 -1
  144. package/dist/types/src/triggers/trigger-state-store.d.ts +0 -28
  145. package/dist/types/src/triggers/trigger-state-store.d.ts.map +0 -1
  146. package/dist/types/src/types.d.ts +0 -230
  147. package/dist/types/src/types.d.ts.map +0 -1
  148. package/dist/types/src/url.d.ts +0 -21
  149. package/dist/types/src/url.d.ts.map +0 -1
  150. package/src/bundler/bundler.test.ts +0 -58
  151. package/src/bundler/bundler.ts +0 -295
  152. package/src/bundler/index.ts +0 -5
  153. package/src/edge/functions.ts +0 -67
  154. package/src/edge/index.ts +0 -9
  155. package/src/errors.ts +0 -21
  156. package/src/examples/fib.ts +0 -32
  157. package/src/examples/index.ts +0 -7
  158. package/src/examples/reply.ts +0 -21
  159. package/src/examples/sleep.ts +0 -24
  160. package/src/executor/executor.ts +0 -58
  161. package/src/handler.ts +0 -225
  162. package/src/schema.ts +0 -71
  163. package/src/services/database.ts +0 -175
  164. package/src/services/event-logger.ts +0 -121
  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 -665
  182. package/src/triggers/trigger-dispatcher.ts +0 -533
  183. package/src/triggers/trigger-state-store.ts +0 -61
  184. package/src/types.ts +0 -218
  185. package/src/url.ts +0 -55
@@ -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,121 +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 { Obj, Type } from '@dxos/echo';
11
- import { invariant } from '@dxos/invariant';
12
- import { LogLevel, log } from '@dxos/log';
13
-
14
- import { TracingService } from './tracing';
15
-
16
- export const ComputeEventPayload = Schema.Union(
17
- Schema.Struct({
18
- type: Schema.Literal('begin-compute'),
19
- nodeId: Schema.String,
20
- inputs: Schema.Record({ key: Schema.String, value: Schema.Any }),
21
- }),
22
- Schema.Struct({
23
- type: Schema.Literal('end-compute'),
24
- nodeId: Schema.String,
25
- outputs: Schema.Record({ key: Schema.String, value: Schema.Any }),
26
- }),
27
- Schema.Struct({
28
- type: Schema.Literal('compute-input'),
29
- nodeId: Schema.String,
30
- property: Schema.String,
31
- value: Schema.Any,
32
- }),
33
- Schema.Struct({
34
- type: Schema.Literal('compute-output'),
35
- nodeId: Schema.String,
36
- property: Schema.String,
37
- value: Schema.Any,
38
- }),
39
- Schema.Struct({
40
- type: Schema.Literal('custom'),
41
- nodeId: Schema.String,
42
- event: Schema.Any,
43
- }),
44
- );
45
- export type ComputeEventPayload = Schema.Schema.Type<typeof ComputeEventPayload>;
46
-
47
- export const ComputeEvent = Schema.Struct({
48
- payload: ComputeEventPayload,
49
- }).pipe(Type.Obj({ typename: 'dxos.org/type/ComputeEvent', version: '0.1.0' }));
50
-
51
- /**
52
- * Logs event for the compute workflows.
53
- */
54
- export class ComputeEventLogger extends Context.Tag('@dxos/functions/ComputeEventLogger')<
55
- ComputeEventLogger,
56
- { readonly log: (event: ComputeEventPayload) => void; readonly nodeId: string | undefined }
57
- >() {
58
- static noop: Context.Tag.Service<ComputeEventLogger> = {
59
- log: () => {},
60
- nodeId: undefined,
61
- };
62
-
63
- /**
64
- * Implements ComputeEventLogger using TracingService.
65
- */
66
- static layerFromTracing = Layer.effect(
67
- ComputeEventLogger,
68
- Effect.gen(function* () {
69
- const tracing = yield* TracingService;
70
- return {
71
- log: (event: ComputeEventPayload) => {
72
- tracing.write(Obj.make(ComputeEvent, { payload: event }));
73
- },
74
- nodeId: undefined,
75
- };
76
- }),
77
- );
78
- }
79
-
80
- export const logCustomEvent = (data: any) =>
81
- Effect.gen(function* () {
82
- const logger = yield* ComputeEventLogger;
83
- if (!logger.nodeId) {
84
- throw new Error('logCustomEvent must be called within a node compute function');
85
- }
86
- logger.log({
87
- type: 'custom',
88
- nodeId: logger.nodeId,
89
- event: data,
90
- });
91
- });
92
-
93
- export const createDefectLogger = <A, E, R>(): ((self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>) =>
94
- Effect.catchAll((error) =>
95
- Effect.gen(function* () {
96
- log.error('unhandled effect error', { error });
97
- throw error;
98
- }),
99
- );
100
-
101
- export const createEventLogger = (
102
- level: LogLevel,
103
- message: string = 'event',
104
- ): Context.Tag.Service<ComputeEventLogger> => {
105
- const logFunction = (
106
- {
107
- [LogLevel.WARN]: log.warn,
108
- [LogLevel.VERBOSE]: log.verbose,
109
- [LogLevel.DEBUG]: log.debug,
110
- [LogLevel.INFO]: log.info,
111
- [LogLevel.ERROR]: log.error,
112
- } as any
113
- )[level];
114
- invariant(logFunction);
115
- return {
116
- log: (event: ComputeEventPayload) => {
117
- logFunction(message, event);
118
- },
119
- nodeId: undefined,
120
- };
121
- };
@@ -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: 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
- }