@dxos/functions 0.8.4-main.72ec0f3 → 0.8.4-main.7996785055

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 (84) hide show
  1. package/README.md +4 -6
  2. package/dist/lib/neutral/chunk-GEM2K7BA.mjs +56 -0
  3. package/dist/lib/neutral/chunk-GEM2K7BA.mjs.map +7 -0
  4. package/dist/lib/neutral/fib-XBUKWUUS.mjs +22 -0
  5. package/dist/lib/neutral/fib-XBUKWUUS.mjs.map +7 -0
  6. package/dist/lib/neutral/index.mjs +960 -0
  7. package/dist/lib/neutral/index.mjs.map +7 -0
  8. package/dist/lib/neutral/meta.json +1 -0
  9. package/dist/lib/neutral/reply-XBQTXDLZ.mjs +18 -0
  10. package/dist/lib/neutral/reply-XBQTXDLZ.mjs.map +7 -0
  11. package/dist/lib/neutral/sleep-TLQKHAK2.mjs +14 -0
  12. package/dist/lib/neutral/sleep-TLQKHAK2.mjs.map +7 -0
  13. package/dist/types/src/errors.d.ts +24 -32
  14. package/dist/types/src/errors.d.ts.map +1 -1
  15. package/dist/types/src/example/definitions.d.ts +11 -0
  16. package/dist/types/src/example/definitions.d.ts.map +1 -0
  17. package/dist/types/src/example/fib.d.ts +3 -2
  18. package/dist/types/src/example/fib.d.ts.map +1 -1
  19. package/dist/types/src/example/index.d.ts +3 -11
  20. package/dist/types/src/example/index.d.ts.map +1 -1
  21. package/dist/types/src/example/reply.d.ts +2 -1
  22. package/dist/types/src/example/reply.d.ts.map +1 -1
  23. package/dist/types/src/example/sleep.d.ts +3 -2
  24. package/dist/types/src/example/sleep.d.ts.map +1 -1
  25. package/dist/types/src/protocol/functions-ai-http-client.d.ts +12 -0
  26. package/dist/types/src/protocol/functions-ai-http-client.d.ts.map +1 -0
  27. package/dist/types/src/protocol/protocol.d.ts +2 -2
  28. package/dist/types/src/protocol/protocol.d.ts.map +1 -1
  29. package/dist/types/src/sdk.d.ts +2 -79
  30. package/dist/types/src/sdk.d.ts.map +1 -1
  31. package/dist/types/src/services/credentials.d.ts +6 -4
  32. package/dist/types/src/services/credentials.d.ts.map +1 -1
  33. package/dist/types/src/services/event-logger.d.ts +25 -31
  34. package/dist/types/src/services/event-logger.d.ts.map +1 -1
  35. package/dist/types/src/services/function-invocation-service.d.ts +9 -3
  36. package/dist/types/src/services/function-invocation-service.d.ts.map +1 -1
  37. package/dist/types/src/services/index.d.ts +0 -1
  38. package/dist/types/src/services/index.d.ts.map +1 -1
  39. package/dist/types/src/services/queues.d.ts +4 -4
  40. package/dist/types/src/services/queues.d.ts.map +1 -1
  41. package/dist/types/src/services/tracing.d.ts +38 -3
  42. package/dist/types/src/services/tracing.d.ts.map +1 -1
  43. package/dist/types/src/types/Script.d.ts +9 -16
  44. package/dist/types/src/types/Script.d.ts.map +1 -1
  45. package/dist/types/src/types/Trigger.d.ts +57 -76
  46. package/dist/types/src/types/Trigger.d.ts.map +1 -1
  47. package/dist/types/src/types/TriggerEvent.d.ts +44 -13
  48. package/dist/types/src/types/TriggerEvent.d.ts.map +1 -1
  49. package/dist/types/src/types/index.d.ts +0 -1
  50. package/dist/types/src/types/index.d.ts.map +1 -1
  51. package/dist/types/src/types/url.d.ts +6 -5
  52. package/dist/types/src/types/url.d.ts.map +1 -1
  53. package/dist/types/tsconfig.tsbuildinfo +1 -1
  54. package/package.json +23 -17
  55. package/src/errors.ts +4 -4
  56. package/src/example/definitions.ts +48 -0
  57. package/src/example/fib.ts +14 -24
  58. package/src/example/forex-effect.ts +1 -1
  59. package/src/example/index.ts +7 -8
  60. package/src/example/reply.ts +10 -13
  61. package/src/example/sleep.ts +8 -17
  62. package/src/protocol/functions-ai-http-client.ts +67 -0
  63. package/src/protocol/protocol.ts +196 -84
  64. package/src/sdk.ts +4 -194
  65. package/src/services/credentials.ts +31 -15
  66. package/src/services/event-logger.ts +2 -2
  67. package/src/services/function-invocation-service.ts +18 -3
  68. package/src/services/index.ts +0 -2
  69. package/src/services/queues.ts +5 -7
  70. package/src/services/tracing.ts +64 -4
  71. package/src/types/Script.ts +13 -8
  72. package/src/types/Trigger.ts +31 -17
  73. package/src/types/TriggerEvent.ts +29 -29
  74. package/src/types/index.ts +0 -1
  75. package/src/types/url.ts +6 -5
  76. package/dist/lib/browser/index.mjs +0 -927
  77. package/dist/lib/browser/index.mjs.map +0 -7
  78. package/dist/lib/browser/meta.json +0 -1
  79. package/dist/lib/node-esm/index.mjs +0 -928
  80. package/dist/lib/node-esm/index.mjs.map +0 -7
  81. package/dist/lib/node-esm/meta.json +0 -1
  82. package/dist/types/src/types/Function.d.ts +0 -58
  83. package/dist/types/src/types/Function.d.ts.map +0 -1
  84. package/src/types/Function.ts +0 -62
@@ -2,44 +2,54 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
+ import * as AnthropicClient from '@effect/ai-anthropic/AnthropicClient';
5
6
  import * as Effect from 'effect/Effect';
6
7
  import * as Layer from 'effect/Layer';
7
8
  import * as Schema from 'effect/Schema';
8
9
  import * as SchemaAST from 'effect/SchemaAST';
9
10
 
10
- import { AiService } from '@dxos/ai';
11
- import { Type } from '@dxos/echo';
12
- import { EchoClient } from '@dxos/echo-db';
13
- import { acquireReleaseResource } from '@dxos/effect';
14
- import { failedInvariant, invariant } from '@dxos/invariant';
11
+ import { AiModelResolver, AiService } from '@dxos/ai';
12
+ import { AnthropicResolver } from '@dxos/ai/resolvers';
13
+ import { LifecycleState, Resource } from '@dxos/context';
14
+ import { Database, Feed, JsonSchema, Ref, type Type } from '@dxos/echo';
15
+ import { refFromEncodedReference } from '@dxos/echo/internal';
16
+ import { EchoClient, type EchoDatabaseImpl, type QueueFactory, createFeedServiceLayer } from '@dxos/echo-db';
17
+ import { runAndForwardErrors } from '@dxos/effect';
18
+ import { assertState, failedInvariant, invariant } from '@dxos/invariant';
15
19
  import { PublicKey } from '@dxos/keys';
16
20
  import { type FunctionProtocol } from '@dxos/protocols';
17
21
 
18
22
  import { FunctionError } from '../errors';
19
- import { FunctionDefinition, type FunctionServices } from '../sdk';
20
- import { CredentialsService, DatabaseService, FunctionInvocationService, TracingService } from '../services';
21
- import { QueueService } from '../services';
23
+ import { type FunctionServices } from '../sdk';
24
+ import { CredentialsService, FunctionInvocationService, QueueService, TracingService } from '../services';
25
+ import { Operation } from '@dxos/operation';
26
+
27
+ import { FunctionsAiHttpClient } from './functions-ai-http-client';
22
28
 
23
29
  /**
24
30
  * Wraps a function handler made with `defineFunction` to a protocol that the functions-runtime expects.
25
31
  */
26
- export const wrapFunctionHandler = (func: FunctionDefinition): FunctionProtocol.Func => {
27
- if (!FunctionDefinition.isFunction(func)) {
28
- throw new TypeError('Invalid function definition');
32
+ export const wrapFunctionHandler = (func: Operation.WithHandler<Operation.Definition.Any>): FunctionProtocol.Func => {
33
+ if (!Operation.isOperationWithHandler(func)) {
34
+ throw new TypeError('Expected operation with handler');
29
35
  }
30
36
 
37
+ const serviceTags = func.services.map((service) => service.key);
38
+
31
39
  return {
32
40
  meta: {
33
- key: func.key,
34
- name: func.name,
35
- description: func.description,
36
- inputSchema: Type.toJsonSchema(func.inputSchema),
37
- outputSchema: func.outputSchema === undefined ? undefined : Type.toJsonSchema(func.outputSchema),
38
- services: func.services,
41
+ key: func.meta.key,
42
+ name: func.meta.name,
43
+ description: func.meta.description,
44
+ inputSchema: JsonSchema.toJsonSchema(func.input),
45
+ outputSchema: func.output === undefined ? undefined : JsonSchema.toJsonSchema(func.output),
46
+ services: func.services.map((service) => service.key),
39
47
  },
40
48
  handler: async ({ data, context }) => {
41
49
  if (
42
- (func.services.includes(DatabaseService.key) || func.services.includes(QueueService.key)) &&
50
+ (serviceTags.includes(Database.Service.key) ||
51
+ serviceTags.includes(QueueService.key) ||
52
+ serviceTags.includes(Feed.Service.key)) &&
43
53
  (!context.services.dataService || !context.services.queryService)
44
54
  ) {
45
55
  throw new FunctionError({
@@ -47,99 +57,201 @@ export const wrapFunctionHandler = (func: FunctionDefinition): FunctionProtocol.
47
57
  });
48
58
  }
49
59
 
60
+ // eslint-disable-next-line no-useless-catch
50
61
  try {
51
- if (!SchemaAST.isAnyKeyword(func.inputSchema.ast)) {
52
- Schema.validateSync(func.inputSchema)(data);
62
+ if (!SchemaAST.isAnyKeyword(func.input.ast)) {
63
+ try {
64
+ Schema.validateSync(func.input)(data);
65
+ } catch (error) {
66
+ throw new FunctionError({ message: 'Invalid input schema', cause: error });
67
+ }
53
68
  }
54
69
 
55
- let result = await func.handler({
56
- // TODO(dmaretskyi): Fix the types.
57
- context: context as any,
58
- data,
59
- });
70
+ await using funcContext = await new FunctionContext(context).open();
71
+
72
+ if (func.types.length > 0) {
73
+ invariant(funcContext.db, 'Database is required for functions with types');
74
+ await funcContext.db.graph.schemaRegistry.register(func.types as Type.AnyEntity[]);
75
+ }
76
+
77
+ const dataWithDecodedRefs =
78
+ funcContext.db && !SchemaAST.isAnyKeyword(func.input.ast)
79
+ ? decodeRefsFromSchema(func.input.ast, data, funcContext.db)
80
+ : data;
81
+
82
+ let result: any = await func.handler(dataWithDecodedRefs);
60
83
 
61
84
  if (Effect.isEffect(result)) {
62
- result = await Effect.runPromise(
85
+ result = await runAndForwardErrors(
63
86
  (result as Effect.Effect<unknown, unknown, FunctionServices>).pipe(
64
87
  Effect.orDie,
65
- Effect.provide(createServiceLayer(context)),
88
+ Effect.provide(funcContext.createLayer()),
66
89
  ),
67
90
  );
68
91
  }
69
92
 
70
- if (func.outputSchema && !SchemaAST.isAnyKeyword(func.outputSchema.ast)) {
71
- Schema.validateSync(func.outputSchema)(result);
93
+ if (func.output && !SchemaAST.isAnyKeyword(func.output.ast)) {
94
+ Schema.validateSync(func.output)(result);
72
95
  }
73
96
 
74
97
  return result;
75
98
  } catch (error) {
76
- if (FunctionError.is(error)) {
77
- throw error;
78
- } else {
79
- throw new FunctionError({
80
- cause: error,
81
- context: { func: func.key },
82
- });
83
- }
99
+ // TODO(dmaretskyi): We might do error wrapping here and add extra context.
100
+ throw error;
84
101
  }
85
102
  },
86
103
  };
87
104
  };
88
105
 
89
106
  /**
90
- * Creates a layer of services for the function.
107
+ * Container for services and context for a function.
91
108
  */
92
- const createServiceLayer = (context: FunctionProtocol.Context): Layer.Layer<FunctionServices> => {
93
- return Layer.unwrapScoped(
94
- Effect.gen(function* () {
95
- let client: EchoClient | undefined;
96
-
97
- if (context.services.dataService && context.services.queryService) {
98
- client = yield* acquireReleaseResource(() => {
99
- invariant(context.services.dataService && context.services.queryService);
100
- // TODO(dmaretskyi): Queues service.
101
- return new EchoClient().connectToService({
102
- dataService: context.services.dataService,
103
- queryService: context.services.queryService,
104
- queueService: context.services.queueService,
105
- });
106
- });
107
- }
109
+ class FunctionContext extends Resource {
110
+ readonly context: FunctionProtocol.Context;
111
+ readonly client: EchoClient | undefined;
112
+ db: EchoDatabaseImpl | undefined;
113
+ queues: QueueFactory | undefined;
108
114
 
109
- const db =
110
- client && context.spaceId
111
- ? yield* acquireReleaseResource(() =>
112
- client.constructDatabase({
113
- spaceId: context.spaceId ?? failedInvariant(),
114
- spaceKey: PublicKey.fromHex(context.spaceKey ?? failedInvariant('spaceKey missing in context')),
115
- reactiveSchemaQuery: false,
116
- }),
117
- )
118
- : undefined;
119
-
120
- if (db) {
121
- console.log('Setting space root', context.spaceRootUrl);
122
- yield* Effect.promise(() =>
123
- db!.setSpaceRoot(context.spaceRootUrl ?? failedInvariant('spaceRootUrl missing in context')),
124
- );
125
- }
115
+ constructor(context: FunctionProtocol.Context) {
116
+ super();
117
+ this.context = context;
118
+ if (context.services.dataService && context.services.queryService) {
119
+ this.client = new EchoClient().connectToService({
120
+ dataService: context.services.dataService,
121
+ queryService: context.services.queryService,
122
+ queueService: context.services.queueService,
123
+ });
124
+ }
125
+ }
126
126
 
127
- const queues = client && context.spaceId ? client.constructQueueFactory(context.spaceId) : undefined;
127
+ override async _open() {
128
+ await this.client?.open();
129
+ this.db =
130
+ this.client && this.context.spaceId
131
+ ? this.client.constructDatabase({
132
+ spaceId: this.context.spaceId ?? failedInvariant(),
133
+ spaceKey: PublicKey.fromHex(this.context.spaceKey ?? failedInvariant('spaceKey missing in context')),
134
+ reactiveSchemaQuery: false,
135
+ preloadSchemaOnOpen: false,
136
+ })
137
+ : undefined;
128
138
 
129
- const dbLayer = db ? DatabaseService.layer(db) : DatabaseService.notAvailable;
130
- const queuesLayer = queues ? QueueService.layer(queues) : QueueService.notAvailable;
131
- const credentials = dbLayer
132
- ? CredentialsService.layerFromDatabase().pipe(Layer.provide(dbLayer))
133
- : CredentialsService.configuredLayer([]);
134
- const functionInvocationService = MockedFunctionInvocationService;
135
- const aiService = AiService.notAvailable;
136
- const tracing = TracingService.layerNoop;
139
+ await this.db?.setSpaceRoot(this.context.spaceRootUrl ?? failedInvariant('spaceRootUrl missing in context'));
140
+ await this.db?.open();
141
+ this.queues =
142
+ this.client && this.context.spaceId ? this.client.constructQueueFactory(this.context.spaceId) : undefined;
143
+ }
137
144
 
138
- return Layer.mergeAll(dbLayer, queuesLayer, credentials, functionInvocationService, aiService, tracing);
139
- }),
140
- );
141
- };
145
+ override async _close() {
146
+ await this.db?.close();
147
+ await this.client?.close();
148
+ }
149
+
150
+ createLayer(): Layer.Layer<FunctionServices> {
151
+ assertState(this._lifecycleState === LifecycleState.OPEN, 'FunctionContext is not open');
152
+
153
+ const dbLayer = this.db ? Database.layer(this.db) : Database.notAvailable;
154
+ const queuesLayer = this.queues ? QueueService.layer(this.queues) : QueueService.notAvailable;
155
+ const feedLayer = this.queues ? createFeedServiceLayer(this.queues) : Feed.notAvailable;
156
+ const credentials = dbLayer
157
+ ? CredentialsService.layerFromDatabase({ caching: true }).pipe(Layer.provide(dbLayer))
158
+ : CredentialsService.configuredLayer([]);
159
+ const functionInvocationService = MockedFunctionInvocationService;
160
+ const tracing = TracingService.layerNoop;
161
+
162
+ const aiLayer = this.context.services.functionsAiService
163
+ ? AiModelResolver.AiModelResolver.buildAiService.pipe(
164
+ Layer.provide(
165
+ AnthropicResolver.make().pipe(
166
+ Layer.provide(
167
+ AnthropicClient.layer({
168
+ // Note: It doesn't matter what is base url here, it will be proxied to ai gateway in edge.
169
+ apiUrl: 'http://internal/provider/anthropic',
170
+ }).pipe(Layer.provide(FunctionsAiHttpClient.layer(this.context.services.functionsAiService))),
171
+ ),
172
+ ),
173
+ ),
174
+ )
175
+ : AiService.notAvailable;
176
+
177
+ return Layer.mergeAll(dbLayer, queuesLayer, feedLayer, credentials, functionInvocationService, aiLayer, tracing);
178
+ }
179
+ }
142
180
 
143
181
  const MockedFunctionInvocationService = Layer.succeed(FunctionInvocationService, {
144
182
  invokeFunction: () => Effect.die('Calling functions from functions is not implemented yet.'),
183
+ resolveFunction: () => Effect.die('Not implemented.'),
145
184
  });
185
+
186
+ const decodeRefsFromSchema = (ast: SchemaAST.AST, value: unknown, db: EchoDatabaseImpl): unknown => {
187
+ if (value == null) {
188
+ return value;
189
+ }
190
+
191
+ const encoded = SchemaAST.encodedBoundAST(ast);
192
+ if (Ref.isRefType(encoded)) {
193
+ if (Ref.isRef(value)) {
194
+ return value;
195
+ }
196
+
197
+ if (typeof value === 'object' && value !== null && typeof (value as any)['/'] === 'string') {
198
+ const resolver = db.graph.createRefResolver({ context: { space: db.spaceId } });
199
+ return refFromEncodedReference(value as any, resolver);
200
+ }
201
+
202
+ return value;
203
+ }
204
+
205
+ switch (encoded._tag) {
206
+ case 'TypeLiteral': {
207
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
208
+ return value;
209
+ }
210
+ const result: Record<string, unknown> = { ...(value as any) };
211
+ for (const prop of SchemaAST.getPropertySignatures(encoded)) {
212
+ const key = prop.name.toString();
213
+ if (key in result) {
214
+ result[key] = decodeRefsFromSchema(prop.type, (result as any)[key], db);
215
+ }
216
+ }
217
+ return result;
218
+ }
219
+
220
+ case 'TupleType': {
221
+ if (!Array.isArray(value)) {
222
+ return value;
223
+ }
224
+
225
+ // For arrays, effect uses TupleType with empty elements and a single rest element.
226
+ if (encoded.elements.length === 0 && encoded.rest.length === 1) {
227
+ const elementType = encoded.rest[0].type;
228
+ return (value as unknown[]).map((item) => decodeRefsFromSchema(elementType, item, db));
229
+ }
230
+
231
+ return value;
232
+ }
233
+
234
+ case 'Union': {
235
+ // Optional values are represented as union with undefined.
236
+ const nonUndefined = encoded.types.filter((t) => !SchemaAST.isUndefinedKeyword(t));
237
+ if (nonUndefined.length === 1) {
238
+ return decodeRefsFromSchema(nonUndefined[0], value, db);
239
+ }
240
+
241
+ // For other unions we can't safely pick a branch without validating.
242
+ return value;
243
+ }
244
+
245
+ case 'Suspend': {
246
+ return decodeRefsFromSchema(encoded.f(), value, db);
247
+ }
248
+
249
+ case 'Refinement': {
250
+ return decodeRefsFromSchema(encoded.from, value, db);
251
+ }
252
+
253
+ default: {
254
+ return value;
255
+ }
256
+ }
257
+ };
package/src/sdk.ts CHANGED
@@ -2,14 +2,8 @@
2
2
  // Copyright 2023 DXOS.org
3
3
  //
4
4
 
5
- import type * as Context from 'effect/Context';
6
- import * as Effect from 'effect/Effect';
7
- import * as Schema from 'effect/Schema';
8
-
9
5
  import { type AiService } from '@dxos/ai';
10
- import { Obj, Type } from '@dxos/echo';
11
- import { type DatabaseService } from '@dxos/echo-db';
12
- import { assertArgument, failedInvariant } from '@dxos/invariant';
6
+ import { type Database, type Feed } from '@dxos/echo';
13
7
 
14
8
  import {
15
9
  type CredentialsService,
@@ -17,8 +11,6 @@ import {
17
11
  type QueueService,
18
12
  type TracingService,
19
13
  } from './services';
20
- import { Function } from './types';
21
- import { getUserFunctionIdInMetadata, setUserFunctionIdInMetadata } from './types';
22
14
 
23
15
  // TODO(burdon): Model after http request. Ref Lambda/OpenFaaS.
24
16
  // https://docs.aws.amazon.com/lambda/latest/dg/typescript-handler.html
@@ -37,190 +29,8 @@ export type FunctionServices =
37
29
  | InvocationServices
38
30
  | AiService.AiService
39
31
  | CredentialsService
40
- | DatabaseService
32
+ | Database.Service
33
+ // TODO(wittjosiah): Remove QueueService — use Feed.Service instead.
41
34
  | QueueService
35
+ | Feed.Service
42
36
  | FunctionInvocationService;
43
-
44
- /**
45
- * Function handler.
46
- */
47
- export type FunctionHandler<TData = {}, TOutput = any, S extends FunctionServices = FunctionServices> = (params: {
48
- /**
49
- * Context available to the function.
50
- */
51
- context: FunctionContext;
52
-
53
- /**
54
- * Data passed as the input to the function.
55
- * Must match the function's input schema.
56
- * This will be the payload from the trigger or other data passed into the function in a workflow.
57
- */
58
- data: TData;
59
- }) => TOutput | Promise<TOutput> | Effect.Effect<TOutput, any, S>;
60
-
61
- /**
62
- * Function context.
63
- */
64
- export interface FunctionContext {
65
- // TODO(dmaretskyi): Consider what we should put into context.
66
- }
67
-
68
- const typeId = Symbol.for('@dxos/functions/FunctionDefinition');
69
-
70
- export type FunctionDefinition<T = any, O = any, S extends FunctionServices = FunctionServices> = {
71
- [typeId]: true;
72
- key: string;
73
- name: string;
74
- description?: string;
75
- inputSchema: Schema.Schema<T, any>;
76
- outputSchema?: Schema.Schema<O, any>;
77
-
78
- /**
79
- * Keys of the required services.
80
- */
81
- services: readonly string[];
82
-
83
- handler: FunctionHandler<T, O, S>;
84
- meta?: {
85
- /**
86
- * Tools that are projected from functions have this annotation.
87
- *
88
- * deployedFunctionId:
89
- * - Backend deployment ID assigned by the EDGE function service (typically a UUID).
90
- * - Used for remote invocation via `FunctionInvocationService` → `RemoteFunctionExecutionService`.
91
- * - Persisted on the corresponding ECHO `Function.Function` object's metadata under the
92
- * `FUNCTIONS_META_KEY` and retrieved with `getUserFunctionIdInMetadata`.
93
- */
94
- deployedFunctionId?: string;
95
- };
96
- };
97
-
98
- export declare namespace FunctionDefinition {
99
- export type Any = FunctionDefinition<any, any, any>;
100
- export type Input<T extends Any> = T extends FunctionDefinition<infer I, infer _O, infer _S> ? I : never;
101
- export type Output<T extends Any> = T extends FunctionDefinition<infer _I, infer O, infer _S> ? O : never;
102
- export type Services<T extends Any> = T extends FunctionDefinition<infer _I, infer _O, infer S> ? S : never;
103
- }
104
-
105
- export type FunctionProps<T, O> = {
106
- key: string;
107
- name: string;
108
- description?: string;
109
- inputSchema: Schema.Schema<T, any>;
110
- outputSchema?: Schema.Schema<O, any>;
111
- // TODO(dmaretskyi): This currently doesn't cause a compile-time error if the handler requests a service that is not specified
112
- services?: readonly Context.Tag<any, any>[];
113
-
114
- handler: FunctionHandler<T, O, FunctionServices>;
115
- };
116
-
117
- // TODO(dmaretskyi): Output type doesn't get typechecked.
118
- export const defineFunction: {
119
- <I, O>(params: FunctionProps<I, O>): FunctionDefinition<I, O, FunctionServices>;
120
- } = ({ key, name, description, inputSchema, outputSchema = Schema.Any, handler, services }) => {
121
- if (!Schema.isSchema(inputSchema)) {
122
- throw new Error('Input schema must be a valid schema');
123
- }
124
- if (typeof handler !== 'function') {
125
- throw new Error('Handler must be a function');
126
- }
127
-
128
- // Captures the function definition location.
129
- const limit = Error.stackTraceLimit;
130
- Error.stackTraceLimit = 2;
131
- const traceError = new Error();
132
- Error.stackTraceLimit = limit;
133
- let cache: false | string = false;
134
- const captureStackTrace = () => {
135
- if (cache !== false) {
136
- return cache;
137
- }
138
- if (traceError.stack !== undefined) {
139
- const stack = traceError.stack.split('\n');
140
- if (stack[2] !== undefined) {
141
- cache = stack[2].trim();
142
- return cache;
143
- }
144
- }
145
- };
146
-
147
- const handlerWithSpan = (...args: any[]) => {
148
- const result = (handler as any)(...args);
149
- if (Effect.isEffect(result)) {
150
- return Effect.withSpan(result, `${key ?? name}`, {
151
- captureStackTrace,
152
- });
153
- }
154
- return result;
155
- };
156
-
157
- return {
158
- [typeId]: true,
159
- key,
160
- name,
161
- description,
162
- inputSchema,
163
- outputSchema,
164
- handler: handlerWithSpan,
165
- services: !services ? [] : getServiceKeys(services),
166
- } satisfies FunctionDefinition.Any;
167
- };
168
-
169
- const getServiceKeys = (services: readonly Context.Tag<any, any>[]) => {
170
- return services.map((tag: any) => {
171
- if (typeof tag.key === 'string') {
172
- return tag.key;
173
- }
174
- console.log(tag);
175
- failedInvariant();
176
- });
177
- };
178
-
179
- export const FunctionDefinition = {
180
- make: defineFunction,
181
- isFunction: (value: unknown): value is FunctionDefinition.Any => {
182
- return typeof value === 'object' && value !== null && Symbol.for('@dxos/functions/FunctionDefinition') in value;
183
- },
184
- serialize: (functionDef: FunctionDefinition.Any): Function.Function => {
185
- assertArgument(FunctionDefinition.isFunction(functionDef), 'functionDef');
186
- return serializeFunction(functionDef);
187
- },
188
- deserialize: (functionObj: Function.Function): FunctionDefinition.Any => {
189
- assertArgument(Obj.instanceOf(Function.Function, functionObj), 'functionObj');
190
- return deserializeFunction(functionObj);
191
- },
192
- };
193
-
194
- export const serializeFunction = (functionDef: FunctionDefinition.Any): Function.Function => {
195
- const fn = Function.make({
196
- key: functionDef.key,
197
- name: functionDef.name,
198
- version: '0.1.0',
199
- description: functionDef.description,
200
- inputSchema: Type.toJsonSchema(functionDef.inputSchema),
201
- outputSchema: !functionDef.outputSchema ? undefined : Type.toJsonSchema(functionDef.outputSchema),
202
- services: functionDef.services,
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: Function.Function): 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
- services: functionObj.services ?? [],
222
- meta: {
223
- deployedFunctionId: getUserFunctionIdInMetadata(Obj.getMeta(functionObj)),
224
- },
225
- };
226
- };
@@ -11,7 +11,7 @@ import * as Layer from 'effect/Layer';
11
11
  import * as Redacted from 'effect/Redacted';
12
12
 
13
13
  import { Query } from '@dxos/echo';
14
- import { DatabaseService } from '@dxos/echo-db';
14
+ import { Database } from '@dxos/echo';
15
15
  import { AccessToken } from '@dxos/types';
16
16
 
17
17
  export type CredentialQuery = {
@@ -60,7 +60,12 @@ export class CredentialsService extends Context.Tag('@dxos/functions/Credentials
60
60
  static configuredLayer = (credentials: ServiceCredential[]) =>
61
61
  Layer.succeed(CredentialsService, new ConfiguredCredentialsService(credentials));
62
62
 
63
- static layerConfig = (credentials: { service: string; apiKey: Config.Config<Redacted.Redacted<string>> }[]) =>
63
+ static layerConfig = (
64
+ credentials: {
65
+ service: string;
66
+ apiKey: Config.Config<Redacted.Redacted<string>>;
67
+ }[],
68
+ ) =>
64
69
  Layer.effect(
65
70
  CredentialsService,
66
71
  Effect.gen(function* () {
@@ -77,20 +82,34 @@ export class CredentialsService extends Context.Tag('@dxos/functions/Credentials
77
82
  }),
78
83
  );
79
84
 
80
- static layerFromDatabase = () =>
85
+ static layerFromDatabase = ({ caching = false }: { caching?: boolean } = {}) =>
81
86
  Layer.effect(
82
87
  CredentialsService,
83
88
  Effect.gen(function* () {
84
- const dbService = yield* DatabaseService;
89
+ const dbService = yield* Database.Service;
90
+ const cache = new Map<string, ServiceCredential[]>();
91
+
85
92
  const queryCredentials = async (query: CredentialQuery): Promise<ServiceCredential[]> => {
86
- const { objects: accessTokens } = await dbService.db.query(Query.type(AccessToken.AccessToken)).run();
87
- return accessTokens
93
+ const cacheKey = JSON.stringify(query);
94
+ if (caching && cache.has(cacheKey)) {
95
+ return cache.get(cacheKey)!;
96
+ }
97
+
98
+ const accessTokens = await dbService.db.query(Query.type(AccessToken.AccessToken)).run();
99
+ const credentials = accessTokens
88
100
  .filter((accessToken) => accessToken.source === query.service)
89
101
  .map((accessToken) => ({
90
102
  service: accessToken.source,
91
103
  apiKey: accessToken.token,
92
104
  }));
105
+
106
+ if (caching) {
107
+ cache.set(cacheKey, credentials);
108
+ }
109
+
110
+ return credentials;
93
111
  };
112
+
94
113
  return {
95
114
  getCredential: async (query) => {
96
115
  const credentials = await queryCredentials(query);
@@ -131,13 +150,10 @@ export class ConfiguredCredentialsService implements Context.Tag.Service<Credent
131
150
  }
132
151
 
133
152
  /**
134
- * Maps the request to include the API key from the credential.
153
+ * Maps the request to include the given token in the Authorization header.
135
154
  */
136
- export const withAuthorization = (query: CredentialQuery, kind?: 'Bearer' | 'Basic') =>
137
- HttpClient.mapRequestEffect(
138
- Effect.fnUntraced(function* (request) {
139
- const key = yield* CredentialsService.getApiKey(query).pipe(Effect.map(Redacted.value));
140
- const authorization = kind ? `${kind} ${key}` : key;
141
- return HttpClientRequest.setHeader(request, 'Authorization', authorization);
142
- }),
143
- );
155
+ export const withAuthorization = (token: string, kind?: 'Bearer' | 'Basic') =>
156
+ HttpClient.mapRequest((request) => {
157
+ const authorization = kind ? `${kind} ${token}` : token;
158
+ return HttpClientRequest.setHeader(request, 'Authorization', authorization);
159
+ });
@@ -52,7 +52,7 @@ export type ComputeEventPayload = Schema.Schema.Type<typeof ComputeEventPayload>
52
52
 
53
53
  export const ComputeEvent = Schema.Struct({
54
54
  payload: ComputeEventPayload,
55
- }).pipe(Type.Obj({ typename: 'dxos.org/type/ComputeEvent', version: '0.1.0' }));
55
+ }).pipe(Type.object({ typename: 'org.dxos.type.compute-event', version: '0.1.0' }));
56
56
 
57
57
  /**
58
58
  * Logs event for the compute workflows.
@@ -75,7 +75,7 @@ export class ComputeEventLogger extends Context.Tag('@dxos/functions/ComputeEven
75
75
  const tracing = yield* TracingService;
76
76
  return {
77
77
  log: (event: ComputeEventPayload) => {
78
- tracing.write(Obj.make(ComputeEvent, { payload: event }));
78
+ tracing.write(Obj.make(ComputeEvent, { payload: event }), tracing.getTraceContext());
79
79
  },
80
80
  nodeId: undefined,
81
81
  };