@dxos/functions 0.8.4-main.72ec0f3 → 0.8.4-main.74a063c4e0
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.
- package/README.md +4 -6
- package/dist/lib/neutral/Trace.mjs +38 -0
- package/dist/lib/neutral/Trace.mjs.map +7 -0
- package/dist/lib/neutral/chunk-5T7GOX2V.mjs +149 -0
- package/dist/lib/neutral/chunk-5T7GOX2V.mjs.map +7 -0
- package/dist/lib/neutral/chunk-IVDUS56O.mjs +49 -0
- package/dist/lib/neutral/chunk-IVDUS56O.mjs.map +7 -0
- package/dist/lib/neutral/chunk-J5LGTIGS.mjs +10 -0
- package/dist/lib/neutral/chunk-J5LGTIGS.mjs.map +7 -0
- package/dist/lib/neutral/fib-N45KAC7C.mjs +23 -0
- package/dist/lib/neutral/fib-N45KAC7C.mjs.map +7 -0
- package/dist/lib/neutral/index.mjs +1266 -0
- package/dist/lib/neutral/index.mjs.map +7 -0
- package/dist/lib/neutral/meta.json +1 -0
- package/dist/lib/neutral/reply-EUEPKNJF.mjs +19 -0
- package/dist/lib/neutral/reply-EUEPKNJF.mjs.map +7 -0
- package/dist/lib/neutral/sleep-PUK3D4FF.mjs +15 -0
- package/dist/lib/neutral/sleep-PUK3D4FF.mjs.map +7 -0
- package/dist/types/src/Trace.d.ts +155 -0
- package/dist/types/src/Trace.d.ts.map +1 -0
- package/dist/types/src/errors.d.ts +24 -32
- package/dist/types/src/errors.d.ts.map +1 -1
- package/dist/types/src/example/definitions.d.ts +11 -0
- package/dist/types/src/example/definitions.d.ts.map +1 -0
- package/dist/types/src/example/fib.d.ts +3 -2
- package/dist/types/src/example/fib.d.ts.map +1 -1
- package/dist/types/src/example/index.d.ts +3 -11
- package/dist/types/src/example/index.d.ts.map +1 -1
- package/dist/types/src/example/reply.d.ts +2 -1
- package/dist/types/src/example/reply.d.ts.map +1 -1
- package/dist/types/src/example/sleep.d.ts +3 -2
- package/dist/types/src/example/sleep.d.ts.map +1 -1
- package/dist/types/src/index.d.ts +4 -0
- package/dist/types/src/index.d.ts.map +1 -1
- package/dist/types/src/process/Process.d.ts +247 -0
- package/dist/types/src/process/Process.d.ts.map +1 -0
- package/dist/types/src/process/ServiceResolver.d.ts +74 -0
- package/dist/types/src/process/ServiceResolver.d.ts.map +1 -0
- package/dist/types/src/process/StorageService.d.ts +58 -0
- package/dist/types/src/process/StorageService.d.ts.map +1 -0
- package/dist/types/src/protocol/functions-ai-http-client.d.ts +12 -0
- package/dist/types/src/protocol/functions-ai-http-client.d.ts.map +1 -0
- package/dist/types/src/protocol/protocol.d.ts +2 -2
- package/dist/types/src/protocol/protocol.d.ts.map +1 -1
- package/dist/types/src/sdk.d.ts +4 -79
- package/dist/types/src/sdk.d.ts.map +1 -1
- package/dist/types/src/services/credentials.d.ts +6 -4
- package/dist/types/src/services/credentials.d.ts.map +1 -1
- package/dist/types/src/services/event-logger.d.ts +25 -31
- package/dist/types/src/services/event-logger.d.ts.map +1 -1
- package/dist/types/src/services/function-invocation-service.d.ts +9 -3
- package/dist/types/src/services/function-invocation-service.d.ts.map +1 -1
- package/dist/types/src/services/index.d.ts +0 -1
- package/dist/types/src/services/index.d.ts.map +1 -1
- package/dist/types/src/services/queues.d.ts +8 -5
- package/dist/types/src/services/queues.d.ts.map +1 -1
- package/dist/types/src/services/tracing.d.ts +61 -4
- package/dist/types/src/services/tracing.d.ts.map +1 -1
- package/dist/types/src/types/Script.d.ts +10 -16
- package/dist/types/src/types/Script.d.ts.map +1 -1
- package/dist/types/src/types/Trigger.d.ts +57 -76
- package/dist/types/src/types/Trigger.d.ts.map +1 -1
- package/dist/types/src/types/TriggerEvent.d.ts +44 -13
- package/dist/types/src/types/TriggerEvent.d.ts.map +1 -1
- package/dist/types/src/types/index.d.ts +0 -1
- package/dist/types/src/types/index.d.ts.map +1 -1
- package/dist/types/src/types/url.d.ts +6 -5
- package/dist/types/src/types/url.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +29 -17
- package/src/Trace.ts +202 -0
- package/src/errors.ts +5 -5
- package/src/example/definitions.ts +49 -0
- package/src/example/fib.ts +15 -24
- package/src/example/forex-effect.ts +1 -1
- package/src/example/index.ts +7 -8
- package/src/example/reply.ts +11 -13
- package/src/example/sleep.ts +9 -16
- package/src/index.ts +4 -0
- package/src/process/Process.ts +486 -0
- package/src/process/ServiceResolver.ts +174 -0
- package/src/process/StorageService.ts +99 -0
- package/src/protocol/functions-ai-http-client.ts +67 -0
- package/src/protocol/protocol.test.ts +0 -1
- package/src/protocol/protocol.ts +206 -84
- package/src/sdk.ts +7 -194
- package/src/services/credentials.ts +31 -15
- package/src/services/event-logger.ts +2 -2
- package/src/services/function-invocation-service.ts +19 -3
- package/src/services/index.ts +0 -2
- package/src/services/queues.ts +15 -8
- package/src/services/tracing.ts +97 -5
- package/src/types/Script.ts +14 -9
- package/src/types/Trigger.ts +33 -18
- package/src/types/TriggerEvent.ts +29 -29
- package/src/types/index.ts +0 -1
- package/src/types/url.ts +6 -5
- package/dist/lib/browser/index.mjs +0 -927
- package/dist/lib/browser/index.mjs.map +0 -7
- package/dist/lib/browser/meta.json +0 -1
- package/dist/lib/node-esm/index.mjs +0 -928
- package/dist/lib/node-esm/index.mjs.map +0 -7
- package/dist/lib/node-esm/meta.json +0 -1
- package/dist/types/src/types/Function.d.ts +0 -58
- package/dist/types/src/types/Function.d.ts.map +0 -1
- package/src/types/Function.ts +0 -62
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2026 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
import * as Context from 'effect/Context';
|
|
6
|
+
import * as Effect from 'effect/Effect';
|
|
7
|
+
import * as Option from 'effect/Option';
|
|
8
|
+
import * as Pipeable from 'effect/Pipeable';
|
|
9
|
+
import * as Schema from 'effect/Schema';
|
|
10
|
+
|
|
11
|
+
export interface Service {
|
|
12
|
+
/** Read a value by key. Returns `None` if key does not exist. */
|
|
13
|
+
get<S extends Schema.Schema<any, string, any>>(
|
|
14
|
+
schema: S,
|
|
15
|
+
key: string,
|
|
16
|
+
): Effect.Effect<Option.Option<Schema.Schema.Type<S>>, never, Schema.Schema.Context<S>>;
|
|
17
|
+
|
|
18
|
+
/** Write a value for the given key. */
|
|
19
|
+
set<S extends Schema.Schema<any, string, any>>(
|
|
20
|
+
schema: S,
|
|
21
|
+
key: string,
|
|
22
|
+
value: Schema.Schema.Type<S>,
|
|
23
|
+
): Effect.Effect<void, never, Schema.Schema.Context<S>>;
|
|
24
|
+
|
|
25
|
+
/** Remove a key. */
|
|
26
|
+
delete(key: string): Effect.Effect<void>;
|
|
27
|
+
|
|
28
|
+
/** List all keys, optionally filtered by prefix. */
|
|
29
|
+
list(prefix?: string): Effect.Effect<readonly string[]>;
|
|
30
|
+
|
|
31
|
+
/** Remove all keys managed by this scoped store. */
|
|
32
|
+
clear(): Effect.Effect<void>;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Scoped key-value storage service for processes.
|
|
37
|
+
* Each process receives its own namespaced instance via the process manager.
|
|
38
|
+
* Construct a live implementation with `StorageService.layer` from `@dxos/functions-runtime`.
|
|
39
|
+
*/
|
|
40
|
+
export class StorageService extends Context.Tag('@dxos/functions/StorageService')<StorageService, Service>() {}
|
|
41
|
+
|
|
42
|
+
export const get = Effect.serviceFunctionEffect(StorageService, (_) => _.get);
|
|
43
|
+
export const set = Effect.serviceFunctionEffect(StorageService, (_) => _.set);
|
|
44
|
+
export const deleteKey = Effect.serviceFunctionEffect(StorageService, (_) => _.delete);
|
|
45
|
+
export const list = Effect.serviceFunctionEffect(StorageService, (_) => _.list);
|
|
46
|
+
export const clear = Effect.serviceFunctionEffect(StorageService, (_) => _.clear);
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Typed key in a storage service.
|
|
50
|
+
*/
|
|
51
|
+
export interface Key<T> extends Pipeable.Pipeable {
|
|
52
|
+
readonly key: string;
|
|
53
|
+
|
|
54
|
+
get: Effect.Effect<Option.Option<T>, never, StorageService>;
|
|
55
|
+
set(value: T): Effect.Effect<void, never, StorageService>;
|
|
56
|
+
delete(): Effect.Effect<void, never, StorageService>;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Create a typed key in a storage service.
|
|
61
|
+
*/
|
|
62
|
+
export const key = <S extends Schema.Schema<any, string, any>>(schema: S, key: string): Key<Schema.Schema.Type<S>> => {
|
|
63
|
+
return {
|
|
64
|
+
key,
|
|
65
|
+
get: get(schema, key),
|
|
66
|
+
set: (value: Schema.Schema.Type<S>) => set(schema, key, value),
|
|
67
|
+
delete: () => deleteKey(key),
|
|
68
|
+
pipe(...args: any) {
|
|
69
|
+
return Pipeable.pipeArguments(this, arguments);
|
|
70
|
+
},
|
|
71
|
+
};
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Typed key in a storage service with a default value.
|
|
76
|
+
*/
|
|
77
|
+
export interface KeyWithDefault<T, U> extends Pipeable.Pipeable {
|
|
78
|
+
readonly key: string;
|
|
79
|
+
get: Effect.Effect<T | U, never, StorageService>;
|
|
80
|
+
set(value: U): Effect.Effect<void, never, StorageService>;
|
|
81
|
+
delete(): Effect.Effect<void, never, StorageService>;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Assign a default value to a key if it is not present.
|
|
86
|
+
*/
|
|
87
|
+
export const withDefault =
|
|
88
|
+
<T>(getDefault: () => NoInfer<T>) =>
|
|
89
|
+
(key: Key<T>): KeyWithDefault<T, T> => {
|
|
90
|
+
return {
|
|
91
|
+
key: key.key,
|
|
92
|
+
get: key.get.pipe(Effect.map(Option.getOrElse(() => getDefault()))),
|
|
93
|
+
set: (value) => key.set(value),
|
|
94
|
+
delete: () => key.delete(),
|
|
95
|
+
pipe(...args: any) {
|
|
96
|
+
return Pipeable.pipeArguments(this, arguments);
|
|
97
|
+
},
|
|
98
|
+
};
|
|
99
|
+
};
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2025 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
import * as Headers from '@effect/platform/Headers';
|
|
6
|
+
import * as HttpClient from '@effect/platform/HttpClient';
|
|
7
|
+
import * as HttpClientError from '@effect/platform/HttpClientError';
|
|
8
|
+
import * as HttpClientResponse from '@effect/platform/HttpClientResponse';
|
|
9
|
+
import * as Effect from 'effect/Effect';
|
|
10
|
+
import * as FiberRef from 'effect/FiberRef';
|
|
11
|
+
import * as Layer from 'effect/Layer';
|
|
12
|
+
import * as Stream from 'effect/Stream';
|
|
13
|
+
|
|
14
|
+
import { log } from '@dxos/log';
|
|
15
|
+
import { type EdgeFunctionEnv, ErrorCodec } from '@dxos/protocols';
|
|
16
|
+
/**
|
|
17
|
+
* Copy pasted from https://github.com/Effect-TS/effect/blob/main/packages/platform/src/internal/fetchHttpClient.ts
|
|
18
|
+
*/
|
|
19
|
+
export const requestInitTagKey = '@effect/platform/FetchHttpClient/FetchOptions';
|
|
20
|
+
|
|
21
|
+
export class FunctionsAiHttpClient {
|
|
22
|
+
static make = (service: EdgeFunctionEnv.FunctionsAiService) =>
|
|
23
|
+
HttpClient.make((request, url, signal, fiber) => {
|
|
24
|
+
const context = fiber.getFiberRef(FiberRef.currentContext);
|
|
25
|
+
const options: RequestInit = context.unsafeMap.get(requestInitTagKey) ?? {};
|
|
26
|
+
const headers = options.headers
|
|
27
|
+
? Headers.merge(Headers.fromInput(options.headers), request.headers)
|
|
28
|
+
: request.headers;
|
|
29
|
+
|
|
30
|
+
const send = (body: BodyInit | undefined) =>
|
|
31
|
+
Effect.tryPromise({
|
|
32
|
+
try: () =>
|
|
33
|
+
service.fetch(
|
|
34
|
+
new Request(url, {
|
|
35
|
+
...options,
|
|
36
|
+
method: request.method,
|
|
37
|
+
headers,
|
|
38
|
+
body,
|
|
39
|
+
// Note: Don't pass signal - it can't be serialized through RPC
|
|
40
|
+
}),
|
|
41
|
+
),
|
|
42
|
+
catch: (cause) => {
|
|
43
|
+
log.error('Failed to fetch', { errorSerialized: ErrorCodec.encode(cause as Error) });
|
|
44
|
+
return new HttpClientError.RequestError({
|
|
45
|
+
request,
|
|
46
|
+
reason: 'Transport',
|
|
47
|
+
cause,
|
|
48
|
+
});
|
|
49
|
+
},
|
|
50
|
+
}).pipe(Effect.map((response) => HttpClientResponse.fromWeb(request, response)));
|
|
51
|
+
|
|
52
|
+
switch (request.body._tag) {
|
|
53
|
+
case 'Raw':
|
|
54
|
+
case 'Uint8Array':
|
|
55
|
+
return send(request.body.body as any);
|
|
56
|
+
case 'FormData':
|
|
57
|
+
return send(request.body.formData);
|
|
58
|
+
case 'Stream':
|
|
59
|
+
return Stream.toReadableStreamEffect(request.body.stream).pipe(Effect.flatMap(send));
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
return send(undefined);
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
static layer = (service: EdgeFunctionEnv.FunctionsAiService) =>
|
|
66
|
+
Layer.succeed(HttpClient.HttpClient, FunctionsAiHttpClient.make(service));
|
|
67
|
+
}
|
|
@@ -7,7 +7,6 @@ import { describe, test } from 'vitest';
|
|
|
7
7
|
import { FunctionError } from '../errors';
|
|
8
8
|
import fibFunc from '../example/fib';
|
|
9
9
|
import replyFunc from '../example/reply';
|
|
10
|
-
|
|
11
10
|
import { wrapFunctionHandler } from './protocol';
|
|
12
11
|
|
|
13
12
|
describe('wrapFunctionHandler', () => {
|
package/src/protocol/protocol.ts
CHANGED
|
@@ -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 {
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
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 { EchoClient, type EchoDatabaseImpl, type QueueFactory, createFeedServiceLayer } from '@dxos/echo-db';
|
|
16
|
+
import { refFromEncodedReference } from '@dxos/echo/internal';
|
|
17
|
+
import { runAndForwardErrors } from '@dxos/effect';
|
|
18
|
+
import { assertState, failedInvariant, invariant } from '@dxos/invariant';
|
|
15
19
|
import { PublicKey } from '@dxos/keys';
|
|
20
|
+
import { Operation } from '@dxos/operation';
|
|
16
21
|
import { type FunctionProtocol } from '@dxos/protocols';
|
|
17
22
|
|
|
18
23
|
import { FunctionError } from '../errors';
|
|
19
|
-
import {
|
|
20
|
-
import { CredentialsService,
|
|
21
|
-
import
|
|
24
|
+
import { type FunctionServices } from '../sdk';
|
|
25
|
+
import { CredentialsService, FunctionInvocationService, QueueService, TracingService } from '../services';
|
|
26
|
+
import * as Trace from '../Trace';
|
|
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:
|
|
27
|
-
if (!
|
|
28
|
-
throw new TypeError('
|
|
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:
|
|
37
|
-
outputSchema: func.
|
|
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
|
-
(
|
|
50
|
+
(serviceTags.includes(Database.Service.key) ||
|
|
51
|
+
serviceTags.includes(QueueService.key) ||
|
|
52
|
+
serviceTags.includes(Feed.FeedService.key)) &&
|
|
43
53
|
(!context.services.dataService || !context.services.queryService)
|
|
44
54
|
) {
|
|
45
55
|
throw new FunctionError({
|
|
@@ -47,99 +57,211 @@ 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.
|
|
52
|
-
|
|
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
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
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
|
|
85
|
+
result = await runAndForwardErrors(
|
|
63
86
|
(result as Effect.Effect<unknown, unknown, FunctionServices>).pipe(
|
|
64
87
|
Effect.orDie,
|
|
65
|
-
Effect.provide(
|
|
88
|
+
Effect.provide(funcContext.createLayer()),
|
|
66
89
|
),
|
|
67
90
|
);
|
|
68
91
|
}
|
|
69
92
|
|
|
70
|
-
if (func.
|
|
71
|
-
Schema.validateSync(func.
|
|
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
|
-
|
|
77
|
-
|
|
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
|
-
*
|
|
107
|
+
* Container for services and context for a function.
|
|
91
108
|
*/
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
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
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
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
|
-
|
|
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
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
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
|
-
|
|
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(
|
|
178
|
+
dbLayer,
|
|
179
|
+
queuesLayer,
|
|
180
|
+
feedLayer,
|
|
181
|
+
credentials,
|
|
182
|
+
functionInvocationService,
|
|
183
|
+
aiLayer,
|
|
184
|
+
tracing,
|
|
185
|
+
// TODO(dmaretskyi): Forward trace events.
|
|
186
|
+
Trace.writerLayerNoop,
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
142
190
|
|
|
143
191
|
const MockedFunctionInvocationService = Layer.succeed(FunctionInvocationService, {
|
|
144
192
|
invokeFunction: () => Effect.die('Calling functions from functions is not implemented yet.'),
|
|
193
|
+
resolveFunction: () => Effect.die('Not implemented.'),
|
|
145
194
|
});
|
|
195
|
+
|
|
196
|
+
const decodeRefsFromSchema = (ast: SchemaAST.AST, value: unknown, db: EchoDatabaseImpl): unknown => {
|
|
197
|
+
if (value == null) {
|
|
198
|
+
return value;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const encoded = SchemaAST.encodedBoundAST(ast);
|
|
202
|
+
if (Ref.isRefType(encoded)) {
|
|
203
|
+
if (Ref.isRef(value)) {
|
|
204
|
+
return value;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
if (typeof value === 'object' && value !== null && typeof (value as any)['/'] === 'string') {
|
|
208
|
+
const resolver = db.graph.createRefResolver({ context: { space: db.spaceId } });
|
|
209
|
+
return refFromEncodedReference(value as any, resolver);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
return value;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
switch (encoded._tag) {
|
|
216
|
+
case 'TypeLiteral': {
|
|
217
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
218
|
+
return value;
|
|
219
|
+
}
|
|
220
|
+
const result: Record<string, unknown> = { ...(value as any) };
|
|
221
|
+
for (const prop of SchemaAST.getPropertySignatures(encoded)) {
|
|
222
|
+
const key = prop.name.toString();
|
|
223
|
+
if (key in result) {
|
|
224
|
+
result[key] = decodeRefsFromSchema(prop.type, (result as any)[key], db);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
return result;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
case 'TupleType': {
|
|
231
|
+
if (!Array.isArray(value)) {
|
|
232
|
+
return value;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// For arrays, effect uses TupleType with empty elements and a single rest element.
|
|
236
|
+
if (encoded.elements.length === 0 && encoded.rest.length === 1) {
|
|
237
|
+
const elementType = encoded.rest[0].type;
|
|
238
|
+
return (value as unknown[]).map((item) => decodeRefsFromSchema(elementType, item, db));
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
return value;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
case 'Union': {
|
|
245
|
+
// Optional values are represented as union with undefined.
|
|
246
|
+
const nonUndefined = encoded.types.filter((t) => !SchemaAST.isUndefinedKeyword(t));
|
|
247
|
+
if (nonUndefined.length === 1) {
|
|
248
|
+
return decodeRefsFromSchema(nonUndefined[0], value, db);
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// For other unions we can't safely pick a branch without validating.
|
|
252
|
+
return value;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
case 'Suspend': {
|
|
256
|
+
return decodeRefsFromSchema(encoded.f(), value, db);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
case 'Refinement': {
|
|
260
|
+
return decodeRefsFromSchema(encoded.from, value, db);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
default: {
|
|
264
|
+
return value;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
};
|