@dxos/functions 0.8.4-main.5acf9ea → 0.8.4-main.5ad4a44

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 (142) hide show
  1. package/dist/lib/browser/bundler/index.mjs +61 -39
  2. package/dist/lib/browser/bundler/index.mjs.map +3 -3
  3. package/dist/lib/browser/chunk-J5LGTIGS.mjs +10 -0
  4. package/dist/lib/browser/chunk-J5LGTIGS.mjs.map +7 -0
  5. package/dist/lib/browser/chunk-LKYT2SAL.mjs +665 -0
  6. package/dist/lib/browser/chunk-LKYT2SAL.mjs.map +7 -0
  7. package/dist/lib/browser/edge/index.mjs +22 -8
  8. package/dist/lib/browser/edge/index.mjs.map +3 -3
  9. package/dist/lib/browser/index.mjs +1025 -131
  10. package/dist/lib/browser/index.mjs.map +4 -4
  11. package/dist/lib/browser/meta.json +1 -1
  12. package/dist/lib/browser/testing/index.mjs +80 -8
  13. package/dist/lib/browser/testing/index.mjs.map +3 -3
  14. package/dist/lib/node-esm/bundler/index.mjs +60 -39
  15. package/dist/lib/node-esm/bundler/index.mjs.map +3 -3
  16. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs +11 -0
  17. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs.map +7 -0
  18. package/dist/lib/node-esm/chunk-NAQIKLZB.mjs +667 -0
  19. package/dist/lib/node-esm/chunk-NAQIKLZB.mjs.map +7 -0
  20. package/dist/lib/node-esm/edge/index.mjs +21 -8
  21. package/dist/lib/node-esm/edge/index.mjs.map +3 -3
  22. package/dist/lib/node-esm/index.mjs +1025 -131
  23. package/dist/lib/node-esm/index.mjs.map +4 -4
  24. package/dist/lib/node-esm/meta.json +1 -1
  25. package/dist/lib/node-esm/testing/index.mjs +80 -8
  26. package/dist/lib/node-esm/testing/index.mjs.map +3 -3
  27. package/dist/types/src/bundler/bundler.d.ts +11 -12
  28. package/dist/types/src/bundler/bundler.d.ts.map +1 -1
  29. package/dist/types/src/edge/functions.d.ts +3 -2
  30. package/dist/types/src/edge/functions.d.ts.map +1 -1
  31. package/dist/types/src/errors.d.ts +89 -20
  32. package/dist/types/src/errors.d.ts.map +1 -1
  33. package/dist/types/src/examples/fib.d.ts +7 -0
  34. package/dist/types/src/examples/fib.d.ts.map +1 -0
  35. package/dist/types/src/examples/index.d.ts +4 -0
  36. package/dist/types/src/examples/index.d.ts.map +1 -0
  37. package/dist/types/src/examples/reply.d.ts +3 -0
  38. package/dist/types/src/examples/reply.d.ts.map +1 -0
  39. package/dist/types/src/examples/sleep.d.ts +5 -0
  40. package/dist/types/src/examples/sleep.d.ts.map +1 -0
  41. package/dist/types/src/executor/executor.d.ts +7 -1
  42. package/dist/types/src/executor/executor.d.ts.map +1 -1
  43. package/dist/types/src/handler.d.ts +56 -9
  44. package/dist/types/src/handler.d.ts.map +1 -1
  45. package/dist/types/src/index.d.ts +3 -1
  46. package/dist/types/src/index.d.ts.map +1 -1
  47. package/dist/types/src/schema.d.ts +11 -6
  48. package/dist/types/src/schema.d.ts.map +1 -1
  49. package/dist/types/src/services/credentials.d.ts +19 -3
  50. package/dist/types/src/services/credentials.d.ts.map +1 -1
  51. package/dist/types/src/services/database.d.ts +43 -6
  52. package/dist/types/src/services/database.d.ts.map +1 -1
  53. package/dist/types/src/services/event-logger.d.ts +4 -1
  54. package/dist/types/src/services/event-logger.d.ts.map +1 -1
  55. package/dist/types/src/services/function-invocation-service.d.ts +28 -0
  56. package/dist/types/src/services/function-invocation-service.d.ts.map +1 -0
  57. package/dist/types/src/services/function-invocation-service.test.d.ts +2 -0
  58. package/dist/types/src/services/function-invocation-service.test.d.ts.map +1 -0
  59. package/dist/types/src/services/index.d.ts +4 -3
  60. package/dist/types/src/services/index.d.ts.map +1 -1
  61. package/dist/types/src/services/local-function-execution.d.ts +27 -4
  62. package/dist/types/src/services/local-function-execution.d.ts.map +1 -1
  63. package/dist/types/src/services/queues.d.ts +21 -5
  64. package/dist/types/src/services/queues.d.ts.map +1 -1
  65. package/dist/types/src/services/remote-function-execution-service.d.ts +11 -4
  66. package/dist/types/src/services/remote-function-execution-service.d.ts.map +1 -1
  67. package/dist/types/src/services/service-container.d.ts +3 -2
  68. package/dist/types/src/services/service-container.d.ts.map +1 -1
  69. package/dist/types/src/services/service-registry.d.ts +3 -1
  70. package/dist/types/src/services/service-registry.d.ts.map +1 -1
  71. package/dist/types/src/services/tracing.d.ts +37 -4
  72. package/dist/types/src/services/tracing.d.ts.map +1 -1
  73. package/dist/types/src/testing/layer.d.ts +11 -3
  74. package/dist/types/src/testing/layer.d.ts.map +1 -1
  75. package/dist/types/src/testing/logger.d.ts +1 -1
  76. package/dist/types/src/testing/logger.d.ts.map +1 -1
  77. package/dist/types/src/testing/persist-database.test.d.ts +2 -0
  78. package/dist/types/src/testing/persist-database.test.d.ts.map +1 -0
  79. package/dist/types/src/testing/services.d.ts +2 -2
  80. package/dist/types/src/testing/services.d.ts.map +1 -1
  81. package/dist/types/src/trace.d.ts +21 -23
  82. package/dist/types/src/trace.d.ts.map +1 -1
  83. package/dist/types/src/triggers/index.d.ts +4 -0
  84. package/dist/types/src/triggers/index.d.ts.map +1 -0
  85. package/dist/types/src/triggers/input-builder.d.ts +3 -0
  86. package/dist/types/src/triggers/input-builder.d.ts.map +1 -0
  87. package/dist/types/src/triggers/invocation-tracer.d.ts +37 -0
  88. package/dist/types/src/triggers/invocation-tracer.d.ts.map +1 -0
  89. package/dist/types/src/triggers/trigger-dispatcher.d.ts +78 -0
  90. package/dist/types/src/triggers/trigger-dispatcher.d.ts.map +1 -0
  91. package/dist/types/src/triggers/trigger-dispatcher.test.d.ts +2 -0
  92. package/dist/types/src/triggers/trigger-dispatcher.test.d.ts.map +1 -0
  93. package/dist/types/src/triggers/trigger-state-store.d.ts +28 -0
  94. package/dist/types/src/triggers/trigger-state-store.d.ts.map +1 -0
  95. package/dist/types/src/types.d.ts +71 -252
  96. package/dist/types/src/types.d.ts.map +1 -1
  97. package/dist/types/src/url.d.ts +11 -7
  98. package/dist/types/src/url.d.ts.map +1 -1
  99. package/dist/types/tsconfig.tsbuildinfo +1 -1
  100. package/package.json +41 -50
  101. package/src/bundler/bundler.test.ts +8 -9
  102. package/src/bundler/bundler.ts +38 -35
  103. package/src/edge/functions.ts +8 -5
  104. package/src/errors.ts +13 -5
  105. package/src/examples/fib.ts +32 -0
  106. package/src/examples/index.ts +7 -0
  107. package/src/examples/reply.ts +21 -0
  108. package/src/examples/sleep.ts +24 -0
  109. package/src/executor/executor.ts +14 -10
  110. package/src/handler.ts +125 -20
  111. package/src/index.ts +3 -3
  112. package/src/schema.ts +16 -2
  113. package/src/services/credentials.ts +85 -5
  114. package/src/services/database.ts +119 -18
  115. package/src/services/event-logger.ts +5 -2
  116. package/src/services/function-invocation-service.test.ts +81 -0
  117. package/src/services/function-invocation-service.ts +84 -0
  118. package/src/services/index.ts +4 -3
  119. package/src/services/local-function-execution.ts +104 -21
  120. package/src/services/queues.ts +36 -10
  121. package/src/services/remote-function-execution-service.ts +40 -43
  122. package/src/services/service-container.ts +6 -4
  123. package/src/services/service-registry.test.ts +4 -1
  124. package/src/services/service-registry.ts +7 -3
  125. package/src/services/tracing.ts +109 -10
  126. package/src/testing/layer.ts +87 -4
  127. package/src/testing/logger.ts +2 -1
  128. package/src/testing/persist-database.test.ts +87 -0
  129. package/src/testing/services.ts +4 -3
  130. package/src/trace.ts +19 -21
  131. package/src/triggers/index.ts +7 -0
  132. package/src/triggers/input-builder.ts +35 -0
  133. package/src/triggers/invocation-tracer.ts +101 -0
  134. package/src/triggers/trigger-dispatcher.test.ts +665 -0
  135. package/src/triggers/trigger-dispatcher.ts +533 -0
  136. package/src/triggers/trigger-state-store.ts +61 -0
  137. package/src/types.ts +44 -37
  138. package/src/url.ts +14 -11
  139. package/dist/lib/browser/chunk-6PTFLPCO.mjs +0 -462
  140. package/dist/lib/browser/chunk-6PTFLPCO.mjs.map +0 -7
  141. package/dist/lib/node-esm/chunk-NYJ2TSXO.mjs +0 -464
  142. package/dist/lib/node-esm/chunk-NYJ2TSXO.mjs.map +0 -7
@@ -0,0 +1,84 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+ import * as Context from 'effect/Context';
5
+ import * as Effect from 'effect/Effect';
6
+ import * as Layer from 'effect/Layer';
7
+
8
+ import { AiService } from '@dxos/ai';
9
+
10
+ import { type FunctionDefinition } from '../handler';
11
+
12
+ import { CredentialsService } from './credentials';
13
+ import { DatabaseService } from './database';
14
+ import {
15
+ FunctionImplementationResolver,
16
+ type InvocationServices,
17
+ LocalFunctionExecutionService,
18
+ } from './local-function-execution';
19
+ import { QueueService } from './queues';
20
+ import { RemoteFunctionExecutionService } from './remote-function-execution-service';
21
+
22
+ export class FunctionInvocationService extends Context.Tag('@dxos/functions/FunctionInvocationService')<
23
+ FunctionInvocationService,
24
+ {
25
+ invokeFunction<I, O>(functionDef: FunctionDefinition<I, O>, input: I): Effect.Effect<O, never, InvocationServices>;
26
+ }
27
+ >() {
28
+ static invokeFunction = Effect.serviceFunctionEffect(FunctionInvocationService, (_) => _.invokeFunction);
29
+
30
+ static layer = Layer.effect(
31
+ FunctionInvocationService,
32
+ Effect.gen(function* () {
33
+ const localExecutioner = yield* LocalFunctionExecutionService;
34
+ const remoteExecutioner = yield* RemoteFunctionExecutionService;
35
+
36
+ return {
37
+ invokeFunction: <I, O>(
38
+ functionDef: FunctionDefinition<I, O>,
39
+ input: I,
40
+ ): Effect.Effect<O, never, InvocationServices> =>
41
+ Effect.gen(function* () {
42
+ if (functionDef.meta?.deployedFunctionId) {
43
+ return yield* remoteExecutioner.callFunction<I, O>(functionDef.meta.deployedFunctionId, input);
44
+ }
45
+
46
+ return yield* localExecutioner.invokeFunction(functionDef, input);
47
+ }),
48
+ } satisfies Context.Tag.Service<FunctionInvocationService>;
49
+ }),
50
+ );
51
+
52
+ // TODO(dmaretskyi): Don't provide `FunctionImplementationResolver`.
53
+ static layerTest = ({
54
+ functions = [],
55
+ }: {
56
+ functions?: FunctionDefinition<any, any>[];
57
+ } = {}): Layer.Layer<
58
+ FunctionInvocationService,
59
+ never,
60
+ AiService.AiService | CredentialsService | DatabaseService | QueueService
61
+ > =>
62
+ FunctionInvocationService.layer.pipe(
63
+ Layer.provide(LocalFunctionExecutionService.layerLive),
64
+ Layer.provide(FunctionImplementationResolver.layerTest({ functions })),
65
+ Layer.provide(RemoteFunctionExecutionService.layerMock),
66
+ );
67
+
68
+ // TODO(dmaretskyi): This shouldn't default to all services being not available.
69
+ // TODO(dmaretskyi): Don't provide `FunctionImplementationResolver`.
70
+ /**
71
+ * @deprecated Use {@link layerTest} instead.
72
+ */
73
+ static layerTestMocked = ({
74
+ functions,
75
+ }: {
76
+ functions: FunctionDefinition<any, any>[];
77
+ }): Layer.Layer<FunctionInvocationService> =>
78
+ FunctionInvocationService.layerTest({ functions }).pipe(
79
+ Layer.provide(AiService.notAvailable),
80
+ Layer.provide(CredentialsService.configuredLayer([])),
81
+ Layer.provide(DatabaseService.notAvailable),
82
+ Layer.provide(QueueService.notAvailable),
83
+ );
84
+ }
@@ -2,11 +2,12 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
+ export * from './credentials';
5
6
  export * from './database';
7
+ export * from './event-logger';
8
+ export * from './function-invocation-service';
9
+ export * from './local-function-execution';
6
10
  export * from './queues';
7
11
  export * from './service-container';
8
- export * from './credentials';
9
12
  export * from './tracing';
10
- export * from './event-logger';
11
13
  export * from './remote-function-execution-service';
12
- export * from './local-function-execution';
@@ -2,47 +2,104 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { Context, Effect, Layer, Schema } from 'effect';
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';
6
9
 
10
+ import { AiService } from '@dxos/ai';
7
11
  import { todo } from '@dxos/debug';
12
+ import { log } from '@dxos/log';
8
13
 
14
+ import { FunctionError, FunctionNotFoundError } from '../errors';
9
15
  import type { FunctionContext, FunctionDefinition } from '../handler';
10
- import type { Services } from './service-container';
11
- import { FunctionError } from '../errors';
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;
12
29
 
13
30
  export class LocalFunctionExecutionService extends Context.Tag('@dxos/functions/LocalFunctionExecutionService')<
14
31
  LocalFunctionExecutionService,
15
32
  {
16
33
  // TODO(dmaretskyi): This should take function id instead of the definition object.
17
34
  // TODO(dmaretskyi): Services should be satisfied from environment rather then bubbled up.
18
- invokeFunction(fnDef: FunctionDefinition<any, any>, input: unknown): Effect.Effect<unknown, never, Services>;
35
+ invokeFunction<I, O>(functionDef: FunctionDefinition<I, O>, input: I): Effect.Effect<O, never, InvocationServices>;
19
36
  }
20
37
  >() {
21
- static layer = Layer.succeed(LocalFunctionExecutionService, {
22
- invokeFunction: (fnDef, input) => invokeFunction(fnDef, input),
23
- });
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);
24
75
  }
25
76
 
26
- const invokeFunction = (fnDef: FunctionDefinition<any, any>, input: any): Effect.Effect<unknown, never, Services> =>
77
+ const invokeFunction = (
78
+ functionDef: FunctionDefinition<any, any>,
79
+ input: any,
80
+ ): Effect.Effect<unknown, never, Services> =>
27
81
  Effect.gen(function* () {
28
- // Assert input matches schema
29
- const assertInput = fnDef.inputSchema.pipe(Schema.asserts);
30
- (assertInput as any)(input);
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
+ }
31
89
 
32
90
  const context: FunctionContext = {
91
+ space: undefined,
33
92
  getService: () => todo(),
34
93
  getSpace: async (_spaceId: any) => {
35
94
  throw new Error('Not available. Use the database service instead.');
36
95
  },
37
- space: undefined,
38
- get ai(): never {
39
- throw new Error('Not available. Use the ai service instead.');
40
- },
41
96
  };
42
97
 
98
+ log.info('invoking function', { name: functionDef.name, input });
99
+
43
100
  // TODO(dmaretskyi): This should be delegated to a function invoker service.
44
101
  const data = yield* Effect.gen(function* () {
45
- const result = fnDef.handler({ context, data: input });
102
+ const result = functionDef.handler({ context, data: input });
46
103
  if (Effect.isEffect(result)) {
47
104
  return yield* (result as Effect.Effect<unknown, unknown, Services>).pipe(Effect.orDie);
48
105
  } else if (
@@ -58,13 +115,39 @@ const invokeFunction = (fnDef: FunctionDefinition<any, any>, input: any): Effect
58
115
  }).pipe(
59
116
  Effect.orDie,
60
117
  Effect.catchAllDefect((defect) =>
61
- Effect.die(new FunctionError('Error running function', { context: { name: fnDef.name }, cause: defect })),
118
+ Effect.die(new FunctionError({ context: { name: functionDef.name }, cause: defect })),
62
119
  ),
63
120
  );
64
121
 
65
- // Assert output matches schema
66
- const assertOutput = fnDef.outputSchema?.pipe(Schema.asserts);
67
- (assertOutput as any)(data);
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
+ }
68
131
 
69
132
  return data;
70
- }).pipe(Effect.withSpan('invokeFunction', { attributes: { name: fnDef.name } }));
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
+ }
@@ -2,9 +2,13 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { Context, Layer } from 'effect';
5
+ import * as Context from 'effect/Context';
6
+ import * as Effect from 'effect/Effect';
7
+ import * as Layer from 'effect/Layer';
6
8
 
9
+ import type { Obj, Relation } from '@dxos/echo';
7
10
  import type { Queue, QueueAPI, QueueFactory } from '@dxos/echo-db';
11
+ import type { DXN, QueueSubspaceTag } from '@dxos/keys';
8
12
 
9
13
  /**
10
14
  * Gives access to all queues.
@@ -21,30 +25,50 @@ export class QueueService extends Context.Tag('@dxos/functions/QueueService')<
21
25
  * The queue that is used to store the context of the current research.
22
26
  * @deprecated Use `ContextQueueService` instead.
23
27
  */
24
- readonly contextQueue: Queue | undefined;
28
+ readonly queue: Queue | undefined;
25
29
  }
26
30
  >() {
27
31
  static notAvailable = Layer.succeed(QueueService, {
28
32
  queues: {
29
- get(dxn) {
33
+ get(_dxn) {
30
34
  throw new Error('Queues not available');
31
35
  },
32
36
  create() {
33
37
  throw new Error('Queues not available');
34
38
  },
35
39
  },
36
- contextQueue: undefined,
40
+ queue: undefined,
37
41
  });
38
42
 
39
- static make = (queues: QueueFactory, contextQueue?: Queue): Context.Tag.Service<QueueService> => {
43
+ static make = (queues: QueueFactory, queue?: Queue): Context.Tag.Service<QueueService> => {
40
44
  return {
41
45
  queues,
42
- contextQueue,
46
+ queue,
43
47
  };
44
48
  };
45
49
 
46
- static makeLayer = (queues: QueueFactory, contextQueue?: Queue): Layer.Layer<QueueService> =>
47
- Layer.succeed(QueueService, QueueService.make(queues, contextQueue));
50
+ static layer = (queues: QueueFactory, queue?: Queue): Layer.Layer<QueueService> =>
51
+ Layer.succeed(QueueService, QueueService.make(queues, queue));
52
+
53
+ /**
54
+ * Gets a queue by its DXN.
55
+ */
56
+ static getQueue = <T extends Obj.Any | Relation.Any = Obj.Any | Relation.Any>(
57
+ dxn: DXN,
58
+ ): Effect.Effect<Queue<T>, never, QueueService> => QueueService.pipe(Effect.map(({ queues }) => queues.get<T>(dxn)));
59
+
60
+ /**
61
+ * Creates a new queue.
62
+ */
63
+ static createQueue = <T extends Obj.Any | Relation.Any = Obj.Any | Relation.Any>(options?: {
64
+ subspaceTag?: QueueSubspaceTag;
65
+ }): Effect.Effect<Queue<T>, never, QueueService> =>
66
+ QueueService.pipe(Effect.map(({ queues }) => queues.create<T>(options)));
67
+
68
+ static append = <T extends Obj.Any | Relation.Any = Obj.Any | Relation.Any>(
69
+ queue: Queue<T>,
70
+ objects: T[],
71
+ ): Effect.Effect<void> => Effect.promise(() => queue.append(objects));
48
72
  }
49
73
 
50
74
  /**
@@ -53,6 +77,8 @@ export class QueueService extends Context.Tag('@dxos/functions/QueueService')<
53
77
  export class ContextQueueService extends Context.Tag('@dxos/functions/ContextQueueService')<
54
78
  ContextQueueService,
55
79
  {
56
- readonly contextQueue: Queue;
80
+ readonly queue: Queue;
57
81
  }
58
- >() {}
82
+ >() {
83
+ static layer = (queue: Queue) => Layer.succeed(ContextQueueService, { queue });
84
+ }
@@ -2,65 +2,62 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { Context, Layer } from 'effect';
5
+ import * as Context from 'effect/Context';
6
+ import * as Effect from 'effect/Effect';
7
+ import * as Layer from 'effect/Layer';
6
8
 
7
9
  import type { SpaceId } from '@dxos/keys';
8
10
 
11
+ import { FunctionError } from '../errors';
12
+ import { getInvocationUrl } from '../url';
13
+
9
14
  /**
10
15
  * Allows calling into other functions.
11
16
  */
12
17
  export class RemoteFunctionExecutionService extends Context.Tag('@dxos/functions/RemoteFunctionExecutionService')<
13
18
  RemoteFunctionExecutionService,
14
19
  {
15
- callFunction(deployedFunctionId: string, input: any, spaceId?: SpaceId): Promise<any>;
20
+ callFunction<I, O>(deployedFunctionId: string, input: I): Effect.Effect<O>;
16
21
  }
17
22
  >() {
18
- static fromClient(baseUrl: string, spaceId: SpaceId): Context.Tag.Service<RemoteFunctionExecutionService> {
19
- return {
20
- callFunction: async (deployedFunctionId: string, input: any) => {
21
- const url = getInvocationUrl(deployedFunctionId, baseUrl, { spaceId });
22
- const result = await fetch(url, {
23
- method: 'POST',
24
- headers: { 'Content-Type': 'application/json' },
25
- body: JSON.stringify(input),
26
- });
27
- if (result.status >= 300 || result.status < 200) {
28
- throw new Error('Failed to invoke function', { cause: new Error(`HTTP error: ${await result.text()}`) });
29
- }
30
- return await result.json();
31
- },
32
- };
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
+ });
33
53
  }
34
54
 
35
55
  static mock = (): Context.Tag.Service<RemoteFunctionExecutionService> => {
36
56
  return {
37
- callFunction: async (deployedFunctionId: string, input: any) => {
38
- return input;
39
- },
57
+ callFunction: <I, O>(deployedFunctionId: string, input: I): Effect.Effect<O> =>
58
+ Effect.succeed(input as unknown as O),
40
59
  };
41
60
  };
42
61
 
43
- static mockLayer = Layer.succeed(RemoteFunctionExecutionService, RemoteFunctionExecutionService.mock());
62
+ static layerMock = Layer.succeed(RemoteFunctionExecutionService, RemoteFunctionExecutionService.mock());
44
63
  }
45
-
46
- // TODO(dmaretskyi): Reconcile with `getInvocationUrl` in `@dxos/functions/edge`.
47
- const getInvocationUrl = (functionUrl: string, edgeUrl: string, options: InvocationOptions = {}) => {
48
- const baseUrl = new URL('functions/', edgeUrl);
49
-
50
- // Leading slashes cause the URL to be treated as an absolute path.
51
- const relativeUrl = functionUrl.replace(/^\//, '');
52
- const url = new URL(`./${relativeUrl}`, baseUrl.toString());
53
- options.spaceId && url.searchParams.set('spaceId', options.spaceId);
54
- options.subjectId && url.searchParams.set('subjectId', options.subjectId);
55
- url.protocol = isSecure(url.protocol) ? 'https' : 'http';
56
- return url.toString();
57
- };
58
-
59
- const isSecure = (protocol: string) => {
60
- return protocol === 'https:' || protocol === 'wss:';
61
- };
62
-
63
- type InvocationOptions = {
64
- spaceId?: SpaceId;
65
- subjectId?: string;
66
- };
@@ -2,7 +2,8 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { type Context, Layer } from 'effect';
5
+ import type * as Context from 'effect/Context';
6
+ import * as Layer from 'effect/Layer';
6
7
 
7
8
  import { AiService } from '@dxos/ai';
8
9
  import { entries } from '@dxos/util';
@@ -20,7 +21,7 @@ import { TracingService } from './tracing';
20
21
  * List of all services.
21
22
  */
22
23
  const SERVICES = {
23
- ai: AiService,
24
+ ai: AiService.AiService,
24
25
  credentials: CredentialsService,
25
26
  database: DatabaseService,
26
27
  eventLogger: ComputeEventLogger,
@@ -88,9 +89,10 @@ export class ServiceContainer {
88
89
  return new ServiceContainer().setServices({ ...this._services });
89
90
  }
90
91
 
91
- // TODO(dmaretskyi): `getService` is designed to error at runtime if the service is not available, but layer forces us to provide all services and makes stubs for the ones that are not available.
92
+ // TODO(dmaretskyi): `getService` is designed to error at runtime if the service is not available, but Layer forces us to provide all services and makes stubs for the ones that are not available.
92
93
  createLayer(): Layer.Layer<Services> {
93
- const ai = this._services.ai != null ? Layer.succeed(AiService, this._services.ai) : AiService.notAvailable;
94
+ const ai =
95
+ this._services.ai != null ? Layer.succeed(AiService.AiService, this._services.ai) : AiService.notAvailable;
94
96
  const credentials = Layer.succeed(
95
97
  CredentialsService,
96
98
  this._services.credentials ?? new ConfiguredCredentialsService(),
@@ -3,7 +3,10 @@
3
3
  //
4
4
 
5
5
  import { describe, it } from '@effect/vitest';
6
- import { Context, Effect, Layer, Option } from 'effect';
6
+ import * as Context from 'effect/Context';
7
+ import * as Effect from 'effect/Effect';
8
+ import * as Layer from 'effect/Layer';
9
+ import * as Option from 'effect/Option';
7
10
 
8
11
  import { ServiceRegistry } from './service-registry';
9
12
 
@@ -2,7 +2,10 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { Context, Effect, flow, type Option } from 'effect';
5
+ import * as Context from 'effect/Context';
6
+ import * as Effect from 'effect/Effect';
7
+ import * as Function from 'effect/Function';
8
+ import type * as Option from 'effect/Option';
6
9
 
7
10
  import { ServiceNotAvailableError } from '../errors';
8
11
 
@@ -40,7 +43,8 @@ export class ServiceRegistry extends Context.Tag('@dxos/functions/ServiceRegistr
40
43
  E | ServiceNotAvailableError,
41
44
  Exclude<R, { [K in keyof Tags]: Context.Tag.Identifier<Tags[K]> }[number]> | ServiceRegistry
42
45
  >;
43
- } = (...tags) => (flow as any)(...tags.map((tag) => Effect.provideServiceEffect(tag, ServiceRegistry.resolve(tag))));
46
+ } = (...tags) =>
47
+ (Function.flow as any)(...tags.map((tag) => Effect.provideServiceEffect(tag, ServiceRegistry.resolve(tag))));
44
48
 
45
49
  static provideOrDie: {
46
50
  <Tags extends [Context.Tag<any, any>, ...Context.Tag<any, any>[]]>(
@@ -53,7 +57,7 @@ export class ServiceRegistry extends Context.Tag('@dxos/functions/ServiceRegistr
53
57
  Exclude<R, { [K in keyof Tags]: Context.Tag.Identifier<Tags[K]> }[number]> | ServiceRegistry
54
58
  >;
55
59
  } = (...tags) =>
56
- (flow as any)(
60
+ (Function.flow as any)(
57
61
  ...tags.map((tag) => Effect.provideServiceEffect(tag, ServiceRegistry.resolve(tag).pipe(Effect.orDie))),
58
62
  );
59
63
  }