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

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 (204) hide show
  1. package/dist/lib/neutral/index.mjs +1229 -0
  2. package/dist/lib/neutral/index.mjs.map +7 -0
  3. package/dist/lib/neutral/meta.json +1 -0
  4. package/dist/types/src/errors.d.ts +44 -60
  5. package/dist/types/src/errors.d.ts.map +1 -1
  6. package/dist/types/src/{examples → example}/fib.d.ts +1 -1
  7. package/dist/types/src/example/fib.d.ts.map +1 -0
  8. package/dist/types/src/example/forex-effect.d.ts +3 -0
  9. package/dist/types/src/example/forex-effect.d.ts.map +1 -0
  10. package/dist/types/src/example/index.d.ts +12 -0
  11. package/dist/types/src/example/index.d.ts.map +1 -0
  12. package/dist/types/src/{examples → example}/reply.d.ts +1 -1
  13. package/dist/types/src/example/reply.d.ts.map +1 -0
  14. package/dist/types/src/{examples → example}/sleep.d.ts +1 -1
  15. package/dist/types/src/example/sleep.d.ts.map +1 -0
  16. package/dist/types/src/index.d.ts +4 -8
  17. package/dist/types/src/index.d.ts.map +1 -1
  18. package/dist/types/src/operation-compatibility.test.d.ts +2 -0
  19. package/dist/types/src/operation-compatibility.test.d.ts.map +1 -0
  20. package/dist/types/src/protocol/functions-ai-http-client.d.ts +12 -0
  21. package/dist/types/src/protocol/functions-ai-http-client.d.ts.map +1 -0
  22. package/dist/types/src/protocol/index.d.ts +2 -0
  23. package/dist/types/src/protocol/index.d.ts.map +1 -0
  24. package/dist/types/src/protocol/protocol.d.ts +7 -0
  25. package/dist/types/src/protocol/protocol.d.ts.map +1 -0
  26. package/dist/types/src/protocol/protocol.test.d.ts +2 -0
  27. package/dist/types/src/protocol/protocol.test.d.ts.map +1 -0
  28. package/dist/types/src/sdk.d.ts +114 -0
  29. package/dist/types/src/sdk.d.ts.map +1 -0
  30. package/dist/types/src/services/credentials.d.ts +6 -4
  31. package/dist/types/src/services/credentials.d.ts.map +1 -1
  32. package/dist/types/src/services/event-logger.d.ts +33 -27
  33. package/dist/types/src/services/event-logger.d.ts.map +1 -1
  34. package/dist/types/src/services/function-invocation-service.d.ts +7 -19
  35. package/dist/types/src/services/function-invocation-service.d.ts.map +1 -1
  36. package/dist/types/src/services/index.d.ts +2 -4
  37. package/dist/types/src/services/index.d.ts.map +1 -1
  38. package/dist/types/src/services/queues.d.ts +4 -4
  39. package/dist/types/src/services/queues.d.ts.map +1 -1
  40. package/dist/types/src/services/tracing.d.ts +41 -12
  41. package/dist/types/src/services/tracing.d.ts.map +1 -1
  42. package/dist/types/src/types/Function.d.ts +52 -0
  43. package/dist/types/src/types/Function.d.ts.map +1 -0
  44. package/dist/types/src/types/Script.d.ts +21 -0
  45. package/dist/types/src/types/Script.d.ts.map +1 -0
  46. package/dist/types/src/types/Trigger.d.ts +121 -0
  47. package/dist/types/src/types/Trigger.d.ts.map +1 -0
  48. package/dist/types/src/types/TriggerEvent.d.ts +74 -0
  49. package/dist/types/src/types/TriggerEvent.d.ts.map +1 -0
  50. package/dist/types/src/types/index.d.ts +6 -0
  51. package/dist/types/src/types/index.d.ts.map +1 -0
  52. package/dist/types/src/types/url.d.ts +13 -0
  53. package/dist/types/src/types/url.d.ts.map +1 -0
  54. package/dist/types/tsconfig.tsbuildinfo +1 -1
  55. package/package.json +24 -63
  56. package/src/errors.ts +4 -4
  57. package/src/{examples → example}/fib.ts +1 -1
  58. package/src/example/forex-effect.ts +40 -0
  59. package/src/example/index.ts +13 -0
  60. package/src/{examples → example}/reply.ts +1 -1
  61. package/src/{examples → example}/sleep.ts +1 -1
  62. package/src/index.ts +4 -8
  63. package/src/operation-compatibility.test.ts +185 -0
  64. package/src/protocol/functions-ai-http-client.ts +67 -0
  65. package/src/{executor → protocol}/index.ts +1 -1
  66. package/src/protocol/protocol.test.ts +59 -0
  67. package/src/protocol/protocol.ts +262 -0
  68. package/src/sdk.ts +289 -0
  69. package/src/services/credentials.ts +32 -17
  70. package/src/services/event-logger.ts +10 -4
  71. package/src/services/function-invocation-service.ts +23 -70
  72. package/src/services/index.ts +2 -4
  73. package/src/services/queues.ts +5 -7
  74. package/src/services/tracing.ts +68 -44
  75. package/src/types/Function.ts +82 -0
  76. package/src/types/Script.ts +34 -0
  77. package/src/types/Trigger.ts +143 -0
  78. package/src/types/TriggerEvent.ts +62 -0
  79. package/src/types/index.ts +9 -0
  80. package/src/types/url.ts +32 -0
  81. package/dist/lib/browser/bundler/index.mjs +0 -269
  82. package/dist/lib/browser/bundler/index.mjs.map +0 -7
  83. package/dist/lib/browser/chunk-J5LGTIGS.mjs +0 -10
  84. package/dist/lib/browser/chunk-J5LGTIGS.mjs.map +0 -7
  85. package/dist/lib/browser/chunk-LKYT2SAL.mjs +0 -665
  86. package/dist/lib/browser/chunk-LKYT2SAL.mjs.map +0 -7
  87. package/dist/lib/browser/edge/index.mjs +0 -83
  88. package/dist/lib/browser/edge/index.mjs.map +0 -7
  89. package/dist/lib/browser/index.mjs +0 -1395
  90. package/dist/lib/browser/index.mjs.map +0 -7
  91. package/dist/lib/browser/meta.json +0 -1
  92. package/dist/lib/browser/testing/index.mjs +0 -131
  93. package/dist/lib/browser/testing/index.mjs.map +0 -7
  94. package/dist/lib/node-esm/bundler/index.mjs +0 -270
  95. package/dist/lib/node-esm/bundler/index.mjs.map +0 -7
  96. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs +0 -11
  97. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs.map +0 -7
  98. package/dist/lib/node-esm/chunk-NAQIKLZB.mjs +0 -667
  99. package/dist/lib/node-esm/chunk-NAQIKLZB.mjs.map +0 -7
  100. package/dist/lib/node-esm/edge/index.mjs +0 -84
  101. package/dist/lib/node-esm/edge/index.mjs.map +0 -7
  102. package/dist/lib/node-esm/index.mjs +0 -1396
  103. package/dist/lib/node-esm/index.mjs.map +0 -7
  104. package/dist/lib/node-esm/meta.json +0 -1
  105. package/dist/lib/node-esm/testing/index.mjs +0 -132
  106. package/dist/lib/node-esm/testing/index.mjs.map +0 -7
  107. package/dist/types/src/bundler/bundler.d.ts +0 -49
  108. package/dist/types/src/bundler/bundler.d.ts.map +0 -1
  109. package/dist/types/src/bundler/bundler.test.d.ts +0 -2
  110. package/dist/types/src/bundler/bundler.test.d.ts.map +0 -1
  111. package/dist/types/src/bundler/index.d.ts +0 -2
  112. package/dist/types/src/bundler/index.d.ts.map +0 -1
  113. package/dist/types/src/edge/functions.d.ts +0 -17
  114. package/dist/types/src/edge/functions.d.ts.map +0 -1
  115. package/dist/types/src/edge/index.d.ts +0 -2
  116. package/dist/types/src/edge/index.d.ts.map +0 -1
  117. package/dist/types/src/examples/fib.d.ts.map +0 -1
  118. package/dist/types/src/examples/index.d.ts +0 -4
  119. package/dist/types/src/examples/index.d.ts.map +0 -1
  120. package/dist/types/src/examples/reply.d.ts.map +0 -1
  121. package/dist/types/src/examples/sleep.d.ts.map +0 -1
  122. package/dist/types/src/executor/executor.d.ts +0 -14
  123. package/dist/types/src/executor/executor.d.ts.map +0 -1
  124. package/dist/types/src/executor/index.d.ts +0 -2
  125. package/dist/types/src/executor/index.d.ts.map +0 -1
  126. package/dist/types/src/handler.d.ts +0 -109
  127. package/dist/types/src/handler.d.ts.map +0 -1
  128. package/dist/types/src/schema.d.ts +0 -43
  129. package/dist/types/src/schema.d.ts.map +0 -1
  130. package/dist/types/src/services/database.d.ts +0 -67
  131. package/dist/types/src/services/database.d.ts.map +0 -1
  132. package/dist/types/src/services/function-invocation-service.test.d.ts +0 -2
  133. package/dist/types/src/services/function-invocation-service.test.d.ts.map +0 -1
  134. package/dist/types/src/services/local-function-execution.d.ts +0 -34
  135. package/dist/types/src/services/local-function-execution.d.ts.map +0 -1
  136. package/dist/types/src/services/remote-function-execution-service.d.ts +0 -22
  137. package/dist/types/src/services/remote-function-execution-service.d.ts.map +0 -1
  138. package/dist/types/src/services/service-container.d.ts +0 -57
  139. package/dist/types/src/services/service-container.d.ts.map +0 -1
  140. package/dist/types/src/services/service-registry.d.ts +0 -31
  141. package/dist/types/src/services/service-registry.d.ts.map +0 -1
  142. package/dist/types/src/services/service-registry.test.d.ts +0 -2
  143. package/dist/types/src/services/service-registry.test.d.ts.map +0 -1
  144. package/dist/types/src/testing/index.d.ts +0 -3
  145. package/dist/types/src/testing/index.d.ts.map +0 -1
  146. package/dist/types/src/testing/layer.d.ts +0 -18
  147. package/dist/types/src/testing/layer.d.ts.map +0 -1
  148. package/dist/types/src/testing/logger.d.ts +0 -5
  149. package/dist/types/src/testing/logger.d.ts.map +0 -1
  150. package/dist/types/src/testing/persist-database.test.d.ts +0 -2
  151. package/dist/types/src/testing/persist-database.test.d.ts.map +0 -1
  152. package/dist/types/src/testing/services.d.ts +0 -59
  153. package/dist/types/src/testing/services.d.ts.map +0 -1
  154. package/dist/types/src/trace.d.ts +0 -122
  155. package/dist/types/src/trace.d.ts.map +0 -1
  156. package/dist/types/src/translations.d.ts +0 -12
  157. package/dist/types/src/translations.d.ts.map +0 -1
  158. package/dist/types/src/triggers/index.d.ts +0 -4
  159. package/dist/types/src/triggers/index.d.ts.map +0 -1
  160. package/dist/types/src/triggers/input-builder.d.ts +0 -3
  161. package/dist/types/src/triggers/input-builder.d.ts.map +0 -1
  162. package/dist/types/src/triggers/invocation-tracer.d.ts +0 -37
  163. package/dist/types/src/triggers/invocation-tracer.d.ts.map +0 -1
  164. package/dist/types/src/triggers/trigger-dispatcher.d.ts +0 -78
  165. package/dist/types/src/triggers/trigger-dispatcher.d.ts.map +0 -1
  166. package/dist/types/src/triggers/trigger-dispatcher.test.d.ts +0 -2
  167. package/dist/types/src/triggers/trigger-dispatcher.test.d.ts.map +0 -1
  168. package/dist/types/src/triggers/trigger-state-store.d.ts +0 -28
  169. package/dist/types/src/triggers/trigger-state-store.d.ts.map +0 -1
  170. package/dist/types/src/types.d.ts +0 -230
  171. package/dist/types/src/types.d.ts.map +0 -1
  172. package/dist/types/src/url.d.ts +0 -21
  173. package/dist/types/src/url.d.ts.map +0 -1
  174. package/src/bundler/bundler.test.ts +0 -58
  175. package/src/bundler/bundler.ts +0 -295
  176. package/src/bundler/index.ts +0 -5
  177. package/src/edge/functions.ts +0 -67
  178. package/src/edge/index.ts +0 -9
  179. package/src/examples/index.ts +0 -7
  180. package/src/executor/executor.ts +0 -58
  181. package/src/handler.ts +0 -225
  182. package/src/schema.ts +0 -71
  183. package/src/services/database.ts +0 -175
  184. package/src/services/function-invocation-service.test.ts +0 -81
  185. package/src/services/local-function-execution.ts +0 -153
  186. package/src/services/remote-function-execution-service.ts +0 -63
  187. package/src/services/service-container.ts +0 -115
  188. package/src/services/service-registry.test.ts +0 -45
  189. package/src/services/service-registry.ts +0 -63
  190. package/src/testing/index.ts +0 -6
  191. package/src/testing/layer.ts +0 -114
  192. package/src/testing/logger.ts +0 -17
  193. package/src/testing/persist-database.test.ts +0 -87
  194. package/src/testing/services.ts +0 -115
  195. package/src/trace.ts +0 -178
  196. package/src/translations.ts +0 -20
  197. package/src/triggers/index.ts +0 -7
  198. package/src/triggers/input-builder.ts +0 -35
  199. package/src/triggers/invocation-tracer.ts +0 -101
  200. package/src/triggers/trigger-dispatcher.test.ts +0 -665
  201. package/src/triggers/trigger-dispatcher.ts +0 -533
  202. package/src/triggers/trigger-state-store.ts +0 -61
  203. package/src/types.ts +0 -218
  204. package/src/url.ts +0 -55
package/src/handler.ts DELETED
@@ -1,225 +0,0 @@
1
- //
2
- // Copyright 2023 DXOS.org
3
- //
4
-
5
- import type * as Context from 'effect/Context';
6
- import * as Effect from 'effect/Effect';
7
- import * as Schema from 'effect/Schema';
8
- import type * as Types from 'effect/Types';
9
-
10
- import { Obj, Type } from '@dxos/echo';
11
- import { type HasId } from '@dxos/echo/internal';
12
- import { type EchoDatabase } from '@dxos/echo-db';
13
- import { assertArgument } from '@dxos/invariant';
14
- import { type DXN, type SpaceId } from '@dxos/keys';
15
- import { type QueryResult } from '@dxos/protocols';
16
-
17
- import { FunctionType } from './schema';
18
- import { type Services } from './services';
19
- import { getUserFunctionIdInMetadata, setUserFunctionIdInMetadata } from './url';
20
-
21
- // TODO(burdon): Model after http request. Ref Lambda/OpenFaaS.
22
- // https://docs.aws.amazon.com/lambda/latest/dg/typescript-handler.html
23
- // https://www.serverless.com/framework/docs/providers/aws/guide/serverless.yml/#functions
24
- // https://www.npmjs.com/package/aws-lambda
25
-
26
- /**
27
- * Function handler.
28
- */
29
- export type FunctionHandler<TData = {}, TOutput = any> = (params: {
30
- /**
31
- * Services and context available to the function.
32
- */
33
- context: FunctionContext;
34
-
35
- /**
36
- * Data passed as the input to the function.
37
- * Must match the function's input schema.
38
- * This will be the payload from the trigger or other data passed into the function in a workflow.
39
- */
40
- data: TData;
41
- }) => TOutput | Promise<TOutput> | Effect.Effect<TOutput, any, Services>;
42
-
43
- /**
44
- * Function context.
45
- */
46
- export interface FunctionContext {
47
- /**
48
- * Space from which the function was invoked.
49
- */
50
- space: SpaceAPI | undefined;
51
-
52
- /**
53
- * Resolves a service available to the function.
54
- * @throws if the service is not available.
55
- */
56
- getService: <T extends Context.Tag<any, any>>(tag: T) => Context.Tag.Service<T>;
57
-
58
- getSpace: (spaceId: SpaceId) => Promise<SpaceAPI>;
59
- }
60
-
61
- export interface FunctionContextAi {
62
- // TODO(dmaretskyi): Refer to cloudflare AI docs for more comprehensive typedefs.
63
- run(model: string, inputs: any, options?: any): Promise<any>;
64
- }
65
-
66
- //
67
- // API.
68
- //
69
-
70
- // TODO(dmaretskyi): Temporary API to get the queues working.
71
- // TODO(dmaretskyi): To be replaced with integrating queues into echo.
72
- export interface QueuesAPI {
73
- queryQueue(queue: DXN, options?: {}): Promise<QueryResult>;
74
- insertIntoQueue(queue: DXN, objects: HasId[]): Promise<void>;
75
- }
76
-
77
- /**
78
- * Space interface available to functions.
79
- */
80
- export interface SpaceAPI {
81
- get id(): SpaceId;
82
- get db(): EchoDatabase;
83
-
84
- // TODO(dmaretskyi): Align with echo api: queues.get(id).append(items);
85
- get queues(): QueuesAPI;
86
- }
87
-
88
- // TODO(wittjosiah): Queues are incompatible.
89
- const __assertFunctionSpaceIsCompatibleWithTheClientSpace = () => {
90
- // const _: SpaceAPI = {} as Space;
91
- };
92
-
93
- const typeId = Symbol.for('@dxos/functions/FunctionDefinition');
94
-
95
- export type FunctionDefinition<T = any, O = any> = {
96
- [typeId]: true;
97
- key: string;
98
- name: string;
99
- description?: string;
100
- inputSchema: Schema.Schema<T, any>;
101
- outputSchema?: Schema.Schema<O, any>;
102
- handler: FunctionHandler<T, O>;
103
- meta?: {
104
- /**
105
- * Tools that are projected from functions have this annotation.
106
- *
107
- * deployedFunctionId:
108
- * - Backend deployment ID assigned by the EDGE function service (typically a UUID).
109
- * - Used for remote invocation via `FunctionInvocationService` → `RemoteFunctionExecutionService`.
110
- * - Persisted on the corresponding ECHO `FunctionType` object's metadata under the
111
- * `FUNCTIONS_META_KEY` and retrieved with `getUserFunctionIdInMetadata`.
112
- */
113
- deployedFunctionId?: string;
114
- };
115
- };
116
-
117
- // TODO(dmaretskyi): Output type doesn't get typechecked.
118
- export const defineFunction: {
119
- <I, O>(params: {
120
- key: string;
121
- name: string;
122
- description?: string;
123
- inputSchema: Schema.Schema<I, any>;
124
- outputSchema?: Schema.Schema<O, any>;
125
- handler: Types.NoInfer<FunctionHandler<I, O>>;
126
- }): FunctionDefinition<I, O>;
127
- } = ({ key, name, description, inputSchema, outputSchema = Schema.Any, handler }) => {
128
- if (!Schema.isSchema(inputSchema)) {
129
- throw new Error('Input schema must be a valid schema');
130
- }
131
- if (typeof handler !== 'function') {
132
- throw new Error('Handler must be a function');
133
- }
134
-
135
- // Captures the function definition location.
136
- const limit = Error.stackTraceLimit;
137
- Error.stackTraceLimit = 2;
138
- const traceError = new Error();
139
- Error.stackTraceLimit = limit;
140
- let cache: false | string = false;
141
- const captureStackTrace = () => {
142
- if (cache !== false) {
143
- return cache;
144
- }
145
- if (traceError.stack !== undefined) {
146
- const stack = traceError.stack.split('\n');
147
- if (stack[2] !== undefined) {
148
- cache = stack[2].trim();
149
- return cache;
150
- }
151
- }
152
- };
153
-
154
- const handlerWithSpan = (...args: any[]) => {
155
- const result = (handler as any)(...args);
156
- if (Effect.isEffect(result)) {
157
- return Effect.withSpan(result, `${key ?? name}`, {
158
- captureStackTrace,
159
- });
160
- }
161
- return result;
162
- };
163
-
164
- return {
165
- [typeId]: true,
166
- key,
167
- name,
168
- description,
169
- inputSchema,
170
- outputSchema,
171
- handler: handlerWithSpan,
172
- };
173
- };
174
-
175
- export const FunctionDefinition = {
176
- make: defineFunction,
177
- isFunction: (value: unknown): value is FunctionDefinition.Any => {
178
- return typeof value === 'object' && value !== null && Symbol.for('@dxos/functions/FunctionDefinition') in value;
179
- },
180
- serialize: (functionDef: FunctionDefinition.Any): FunctionType => {
181
- assertArgument(FunctionDefinition.isFunction(functionDef), 'functionDef');
182
- return serializeFunction(functionDef);
183
- },
184
- deserialize: (functionObj: FunctionType): FunctionDefinition.Any => {
185
- assertArgument(Obj.instanceOf(FunctionType, functionObj), 'functionObj');
186
- return deserializeFunction(functionObj);
187
- },
188
- };
189
- export declare namespace FunctionDefinition {
190
- export type Any = FunctionDefinition<any, any>;
191
- export type Input<T extends FunctionDefinition> = T extends FunctionDefinition<infer I, any> ? I : never;
192
- export type Output<T extends FunctionDefinition> = T extends FunctionDefinition<any, infer O> ? O : never;
193
- }
194
-
195
- export const serializeFunction = (functionDef: FunctionDefinition<any, any>): FunctionType => {
196
- const fn = Obj.make(FunctionType, {
197
- key: functionDef.key,
198
- name: functionDef.name,
199
- version: '0.1.0',
200
- description: functionDef.description,
201
- inputSchema: Type.toJsonSchema(functionDef.inputSchema),
202
- outputSchema: !functionDef.outputSchema ? undefined : Type.toJsonSchema(functionDef.outputSchema),
203
- });
204
- if (functionDef.meta?.deployedFunctionId) {
205
- setUserFunctionIdInMetadata(Obj.getMeta(fn), functionDef.meta.deployedFunctionId);
206
- }
207
- return fn;
208
- };
209
-
210
- export const deserializeFunction = (functionObj: FunctionType): FunctionDefinition<unknown, unknown> => {
211
- return {
212
- [typeId]: true,
213
- // TODO(dmaretskyi): Fix key.
214
- key: functionObj.key ?? functionObj.name,
215
- name: functionObj.name,
216
- description: functionObj.description,
217
- inputSchema: !functionObj.inputSchema ? Schema.Unknown : Type.toEffectSchema(functionObj.inputSchema),
218
- outputSchema: !functionObj.outputSchema ? undefined : Type.toEffectSchema(functionObj.outputSchema),
219
- // TODO(dmaretskyi): This should throw error.
220
- handler: () => {},
221
- meta: {
222
- deployedFunctionId: getUserFunctionIdInMetadata(Obj.getMeta(functionObj)),
223
- },
224
- };
225
- };
package/src/schema.ts DELETED
@@ -1,71 +0,0 @@
1
- //
2
- // Copyright 2024 DXOS.org
3
- //
4
-
5
- import * as Schema from 'effect/Schema';
6
-
7
- import { Type } from '@dxos/echo';
8
- import { JsonSchemaType, LabelAnnotation, Ref } from '@dxos/echo/internal';
9
- import { DataType } from '@dxos/schema';
10
-
11
- // TODO(burdon): Create namespace and remove Type suffix.
12
-
13
- /**
14
- * Source script.
15
- */
16
- export const ScriptType = Schema.Struct({
17
- name: Schema.optional(Schema.String),
18
- description: Schema.optional(Schema.String),
19
- // TODO(burdon): Change to hash of deployed content.
20
- // Whether source has changed since last deploy.
21
- changed: Schema.optional(Schema.Boolean),
22
- source: Ref(DataType.Text),
23
- }).pipe(
24
- Type.Obj({
25
- typename: 'dxos.org/type/Script',
26
- version: '0.1.0',
27
- }),
28
- LabelAnnotation.set(['name']),
29
- );
30
-
31
- export interface ScriptType extends Schema.Schema.Type<typeof ScriptType> {}
32
-
33
- /**
34
- * Function deployment.
35
- */
36
- export const FunctionType = Schema.Struct({
37
- /**
38
- * Global registry ID.
39
- * NOTE: The `key` property refers to the original registry entry.
40
- */
41
- // TODO(burdon): Create Format type for DXN-like ids, such as this and schema type.
42
- // TODO(dmaretskyi): Consider making it part of ECHO meta.
43
- // TODO(dmaretskyi): Make required.
44
- key: Schema.optional(Schema.String).annotations({
45
- description: 'Unique registration key for the blueprint',
46
- }),
47
-
48
- // TODO(burdon): Rename to id/uri?
49
- name: Schema.NonEmptyString,
50
- version: Schema.String,
51
-
52
- description: Schema.optional(Schema.String),
53
-
54
- // Reference to a source script if it exists within ECHO.
55
- // TODO(burdon): Don't ref ScriptType directly (core).
56
- source: Schema.optional(Ref(ScriptType)),
57
-
58
- inputSchema: Schema.optional(JsonSchemaType),
59
- outputSchema: Schema.optional(JsonSchemaType),
60
-
61
- // Local binding to a function name.
62
- binding: Schema.optional(Schema.String),
63
- }).pipe(
64
- Type.Obj({
65
- typename: 'dxos.org/type/Function',
66
- version: '0.1.0',
67
- }),
68
- LabelAnnotation.set(['name']),
69
- );
70
-
71
- export interface FunctionType extends Schema.Schema.Type<typeof FunctionType> {}
@@ -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
- });