@dxos/functions 0.8.3 → 0.8.4-main.3f58842

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 (96) hide show
  1. package/dist/lib/browser/bundler/index.mjs +21 -10
  2. package/dist/lib/browser/bundler/index.mjs.map +3 -3
  3. package/dist/lib/browser/{chunk-WEFZUEL2.mjs → chunk-3NGCSUEW.mjs} +106 -78
  4. package/dist/lib/browser/chunk-3NGCSUEW.mjs.map +7 -0
  5. package/dist/lib/browser/edge/index.mjs +2 -2
  6. package/dist/lib/browser/edge/index.mjs.map +1 -1
  7. package/dist/lib/browser/index.mjs +40 -23
  8. package/dist/lib/browser/index.mjs.map +4 -4
  9. package/dist/lib/browser/meta.json +1 -1
  10. package/dist/lib/browser/testing/index.mjs +71 -8
  11. package/dist/lib/browser/testing/index.mjs.map +4 -4
  12. package/dist/lib/node-esm/bundler/index.mjs +21 -10
  13. package/dist/lib/node-esm/bundler/index.mjs.map +3 -3
  14. package/dist/lib/node-esm/{chunk-LIYPMWNQ.mjs → chunk-FJ2MU7TL.mjs} +106 -78
  15. package/dist/lib/node-esm/chunk-FJ2MU7TL.mjs.map +7 -0
  16. package/dist/lib/node-esm/edge/index.mjs +2 -2
  17. package/dist/lib/node-esm/edge/index.mjs.map +1 -1
  18. package/dist/lib/node-esm/index.mjs +40 -23
  19. package/dist/lib/node-esm/index.mjs.map +4 -4
  20. package/dist/lib/node-esm/meta.json +1 -1
  21. package/dist/lib/node-esm/testing/index.mjs +71 -8
  22. package/dist/lib/node-esm/testing/index.mjs.map +4 -4
  23. package/dist/types/src/bundler/bundler.d.ts +1 -2
  24. package/dist/types/src/bundler/bundler.d.ts.map +1 -1
  25. package/dist/types/src/edge/functions.d.ts +1 -1
  26. package/dist/types/src/edge/functions.d.ts.map +1 -1
  27. package/dist/types/src/errors.d.ts +68 -0
  28. package/dist/types/src/errors.d.ts.map +1 -0
  29. package/dist/types/src/executor/executor.d.ts.map +1 -1
  30. package/dist/types/src/handler.d.ts +10 -12
  31. package/dist/types/src/handler.d.ts.map +1 -1
  32. package/dist/types/src/index.d.ts +1 -0
  33. package/dist/types/src/index.d.ts.map +1 -1
  34. package/dist/types/src/schema.d.ts +4 -4
  35. package/dist/types/src/services/credentials.d.ts +3 -2
  36. package/dist/types/src/services/credentials.d.ts.map +1 -1
  37. package/dist/types/src/services/database.d.ts +20 -2
  38. package/dist/types/src/services/database.d.ts.map +1 -1
  39. package/dist/types/src/services/index.d.ts +0 -1
  40. package/dist/types/src/services/index.d.ts.map +1 -1
  41. package/dist/types/src/services/queues.d.ts +15 -3
  42. package/dist/types/src/services/queues.d.ts.map +1 -1
  43. package/dist/types/src/services/service-container.d.ts +27 -15
  44. package/dist/types/src/services/service-container.d.ts.map +1 -1
  45. package/dist/types/src/services/service-registry.d.ts +29 -0
  46. package/dist/types/src/services/service-registry.d.ts.map +1 -0
  47. package/dist/types/src/services/service-registry.test.d.ts +2 -0
  48. package/dist/types/src/services/service-registry.test.d.ts.map +1 -0
  49. package/dist/types/src/services/tracing.d.ts +11 -1
  50. package/dist/types/src/services/tracing.d.ts.map +1 -1
  51. package/dist/types/src/testing/index.d.ts +1 -0
  52. package/dist/types/src/testing/index.d.ts.map +1 -1
  53. package/dist/types/src/testing/layer.d.ts +10 -0
  54. package/dist/types/src/testing/layer.d.ts.map +1 -0
  55. package/dist/types/src/testing/services.d.ts +66 -9
  56. package/dist/types/src/testing/services.d.ts.map +1 -1
  57. package/dist/types/src/translations.d.ts +9 -9
  58. package/dist/types/src/translations.d.ts.map +1 -1
  59. package/dist/types/src/types.d.ts +8 -8
  60. package/dist/types/tsconfig.tsbuildinfo +1 -1
  61. package/package.json +31 -26
  62. package/src/bundler/bundler.test.ts +1 -1
  63. package/src/bundler/bundler.ts +26 -4
  64. package/src/edge/functions.ts +1 -1
  65. package/src/errors.ts +13 -0
  66. package/src/executor/executor.ts +15 -8
  67. package/src/handler.ts +28 -21
  68. package/src/index.ts +1 -0
  69. package/src/services/credentials.ts +9 -3
  70. package/src/services/database.ts +44 -2
  71. package/src/services/index.ts +0 -1
  72. package/src/services/queues.ts +24 -6
  73. package/src/services/service-container.ts +39 -35
  74. package/src/services/service-registry.test.ts +42 -0
  75. package/src/services/service-registry.ts +56 -0
  76. package/src/services/tracing.ts +16 -1
  77. package/src/testing/index.ts +1 -0
  78. package/src/testing/layer.ts +31 -0
  79. package/src/testing/services.ts +150 -14
  80. package/src/translations.ts +4 -4
  81. package/dist/lib/browser/chunk-WEFZUEL2.mjs.map +0 -7
  82. package/dist/lib/node/bundler/index.cjs +0 -260
  83. package/dist/lib/node/bundler/index.cjs.map +0 -7
  84. package/dist/lib/node/chunk-IJAE7FZK.cjs +0 -320
  85. package/dist/lib/node/chunk-IJAE7FZK.cjs.map +0 -7
  86. package/dist/lib/node/edge/index.cjs +0 -94
  87. package/dist/lib/node/edge/index.cjs.map +0 -7
  88. package/dist/lib/node/index.cjs +0 -522
  89. package/dist/lib/node/index.cjs.map +0 -7
  90. package/dist/lib/node/meta.json +0 -1
  91. package/dist/lib/node/testing/index.cjs +0 -43
  92. package/dist/lib/node/testing/index.cjs.map +0 -7
  93. package/dist/lib/node-esm/chunk-LIYPMWNQ.mjs.map +0 -7
  94. package/dist/types/src/services/ai.d.ts +0 -12
  95. package/dist/types/src/services/ai.d.ts.map +0 -1
  96. package/src/services/ai.ts +0 -32
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dxos/functions",
3
- "version": "0.8.3",
3
+ "version": "0.8.4-main.3f58842",
4
4
  "description": "Functions API and runtime.",
5
5
  "homepage": "https://dxos.org",
6
6
  "bugs": "https://github.com/dxos/dxos/issues",
@@ -9,11 +9,6 @@
9
9
  "sideEffects": true,
10
10
  "type": "module",
11
11
  "exports": {
12
- ".": {
13
- "types": "./dist/types/src/index.d.ts",
14
- "browser": "./dist/lib/browser/index.mjs",
15
- "node": "./dist/lib/node-esm/index.mjs"
16
- },
17
12
  "./bundler": {
18
13
  "types": "./dist/types/src/bundler/index.d.ts",
19
14
  "browser": "./dist/lib/browser/bundler/index.mjs",
@@ -24,6 +19,11 @@
24
19
  "browser": "./dist/lib/browser/edge/index.mjs",
25
20
  "node": "./dist/lib/node-esm/edge/index.mjs"
26
21
  },
22
+ ".": {
23
+ "types": "./dist/types/src/index.d.ts",
24
+ "browser": "./dist/lib/browser/index.mjs",
25
+ "node": "./dist/lib/node-esm/index.mjs"
26
+ },
27
27
  "./testing": {
28
28
  "types": "./dist/types/src/testing/index.d.ts",
29
29
  "browser": "./dist/lib/browser/testing/index.mjs",
@@ -47,38 +47,43 @@
47
47
  "src"
48
48
  ],
49
49
  "dependencies": {
50
+ "@effect/platform": "0.89.0",
50
51
  "@preact/signals-core": "^1.9.0",
51
52
  "cron": "^3.1.6",
52
53
  "cron-schedule": "^5.0.4",
53
- "effect": "3.14.21",
54
+ "effect": "3.17.0",
54
55
  "esbuild-wasm": "^0.16.14",
55
56
  "express": "^4.19.2",
56
57
  "get-port-please": "^3.1.1",
58
+ "i18next": "^24.2.1",
57
59
  "iso-did": "^1.6.0",
58
60
  "ws": "^8.14.2",
59
- "@dxos/ai": "0.8.3",
60
- "@dxos/client": "0.8.3",
61
- "@dxos/async": "0.8.3",
62
- "@dxos/crypto": "0.8.3",
63
- "@dxos/echo": "0.8.3",
64
- "@dxos/context": "0.8.3",
65
- "@dxos/echo-protocol": "0.8.3",
66
- "@dxos/echo-db": "0.8.3",
67
- "@dxos/echo-schema": "0.8.3",
68
- "@dxos/edge-client": "0.8.3",
69
- "@dxos/invariant": "0.8.3",
70
- "@dxos/keys": "0.8.3",
71
- "@dxos/live-object": "0.8.3",
72
- "@dxos/log": "0.8.3",
73
- "@dxos/node-std": "0.8.3",
74
- "@dxos/protocols": "0.8.3",
75
- "@dxos/schema": "0.8.3",
76
- "@dxos/util": "0.8.3"
61
+ "@dxos/ai": "0.8.4-main.3f58842",
62
+ "@dxos/async": "0.8.4-main.3f58842",
63
+ "@dxos/client": "0.8.4-main.3f58842",
64
+ "@dxos/context": "0.8.4-main.3f58842",
65
+ "@dxos/crypto": "0.8.4-main.3f58842",
66
+ "@dxos/echo-db": "0.8.4-main.3f58842",
67
+ "@dxos/echo-pipeline": "0.8.4-main.3f58842",
68
+ "@dxos/echo": "0.8.4-main.3f58842",
69
+ "@dxos/echo-protocol": "0.8.4-main.3f58842",
70
+ "@dxos/echo-schema": "0.8.4-main.3f58842",
71
+ "@dxos/edge-client": "0.8.4-main.3f58842",
72
+ "@dxos/effect": "0.8.4-main.3f58842",
73
+ "@dxos/errors": "0.8.4-main.3f58842",
74
+ "@dxos/invariant": "0.8.4-main.3f58842",
75
+ "@dxos/keys": "0.8.4-main.3f58842",
76
+ "@dxos/log": "0.8.4-main.3f58842",
77
+ "@dxos/live-object": "0.8.4-main.3f58842",
78
+ "@dxos/node-std": "0.8.4-main.3f58842",
79
+ "@dxos/protocols": "0.8.4-main.3f58842",
80
+ "@dxos/util": "0.8.4-main.3f58842",
81
+ "@dxos/schema": "0.8.4-main.3f58842"
77
82
  },
78
83
  "devDependencies": {
79
84
  "@types/express": "^4.17.17",
80
85
  "@types/ws": "^7.4.0",
81
- "@dxos/agent": "0.8.3"
86
+ "@dxos/agent": "0.8.4-main.3f58842"
82
87
  },
83
88
  "publishConfig": {
84
89
  "access": "public"
@@ -37,7 +37,7 @@ describe('Bundler', () => {
37
37
  expect(result.error).to.not.exist;
38
38
  });
39
39
 
40
- // TODO(dmaretskyi): Flaky on CI: https://cloud.nx.app/runs/Hjcifa8Ccq/task/plugin-script%3Atest
40
+ // TODO(dmaretskyi): Flaky on CI.
41
41
  test.skip('HTTPS Import', async () => {
42
42
  const bundler = new Bundler({ platform: 'node', sandboxedModules: [], remoteModules: {} });
43
43
  const result = await bundler.bundle({
@@ -2,10 +2,12 @@
2
2
  // Copyright 2023 DXOS.org
3
3
  //
4
4
 
5
- import { type BuildOptions } from 'esbuild';
6
- import { build, initialize, type BuildResult, type Plugin } from 'esbuild-wasm';
5
+ import { FetchHttpClient, HttpClient } from '@effect/platform';
6
+ import { Duration, Effect, pipe, Schedule } from 'effect';
7
+ import { type BuildOptions, type Loader, build, initialize, type BuildResult, type Plugin } from 'esbuild-wasm';
7
8
 
8
9
  import { subtleCrypto } from '@dxos/crypto';
10
+ import { runAndForwardErrors } from '@dxos/effect';
9
11
  import { invariant } from '@dxos/invariant';
10
12
  import { log } from '@dxos/log';
11
13
 
@@ -242,6 +244,9 @@ const analyzeSourceFileImports = (code: string): ParsedImport[] => {
242
244
  });
243
245
  };
244
246
 
247
+ const MAX_RETRIES = 5;
248
+ const INITIAL_DELAY = 1_000;
249
+
245
250
  const httpPlugin: Plugin = {
246
251
  name: 'http',
247
252
  setup: (build) => {
@@ -263,8 +268,25 @@ const httpPlugin: Plugin = {
263
268
  // When a URL is loaded, we want to actually download the content from the internet.
264
269
  // This has just enough logic to be able to handle the example import from unpkg.com but in reality this would probably need to be more complex.
265
270
  build.onLoad({ filter: /.*/, namespace: 'http-url' }, async (args) => {
266
- const response = await fetch(args.path);
267
- return { contents: await response.text(), loader: 'jsx' };
271
+ return Effect.gen(function* () {
272
+ const response = yield* HttpClient.get(args.path);
273
+ if (response.status !== 200) {
274
+ throw new Error(`failed to fetch: ${response.status}`);
275
+ }
276
+
277
+ const text = yield* response.text;
278
+ return { contents: text, loader: 'jsx' as Loader };
279
+ }).pipe(
280
+ Effect.retry(
281
+ pipe(
282
+ Schedule.exponential(Duration.millis(INITIAL_DELAY)),
283
+ Schedule.jittered,
284
+ Schedule.intersect(Schedule.recurs(MAX_RETRIES - 1)),
285
+ ),
286
+ ),
287
+ Effect.provide(FetchHttpClient.layer),
288
+ runAndForwardErrors,
289
+ );
268
290
  });
269
291
  },
270
292
  };
@@ -8,7 +8,7 @@ import { type Client } from '@dxos/client';
8
8
  import { createEdgeIdentity } from '@dxos/client/edge';
9
9
  import { EdgeHttpClient } from '@dxos/edge-client';
10
10
  import { invariant } from '@dxos/invariant';
11
- import type { PublicKey } from '@dxos/keys';
11
+ import { type PublicKey } from '@dxos/keys';
12
12
  import { log } from '@dxos/log';
13
13
  import { type UploadFunctionResponseBody } from '@dxos/protocols';
14
14
 
package/src/errors.ts ADDED
@@ -0,0 +1,13 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { BaseError } from '@dxos/errors';
6
+
7
+ export class ServiceNotAvailableError extends BaseError.extend('SERVICE_NOT_AVAILABLE') {
8
+ constructor(serviceName: string) {
9
+ super(`Service not available: ${serviceName}`);
10
+ }
11
+ }
12
+
13
+ export class FunctionError extends BaseError.extend('FUNCTION_ERROR') {}
@@ -5,9 +5,10 @@
5
5
  import { Effect, Schema } from 'effect';
6
6
 
7
7
  import type { SpaceId } from '@dxos/client/echo';
8
+ import { runAndForwardErrors } from '@dxos/effect';
8
9
 
9
10
  import type { FunctionContext, FunctionDefinition } from '../handler';
10
- import type { ServiceContainer } from '../services';
11
+ import type { ServiceContainer, Services } from '../services';
11
12
 
12
13
  export class FunctionExecutor {
13
14
  constructor(private readonly _services: ServiceContainer) {}
@@ -32,16 +33,22 @@ export class FunctionExecutor {
32
33
  },
33
34
  };
34
35
 
35
- const result = await fnDef.handler({ context, data: input });
36
-
37
- // Assert output matches schema
38
- const assertOutput = fnDef.outputSchema?.pipe(Schema.asserts);
39
- (assertOutput as any)(result);
36
+ const result = fnDef.handler({ context, data: input });
40
37
 
38
+ let data: unknown;
41
39
  if (Effect.isEffect(result)) {
42
- return Effect.runPromise(result as any);
40
+ data = await (result as Effect.Effect<unknown, unknown, Services>).pipe(
41
+ Effect.provide(this._services.createLayer()),
42
+ runAndForwardErrors,
43
+ );
44
+ } else {
45
+ data = await result;
43
46
  }
44
47
 
45
- return result as any;
48
+ // Assert output matches schema
49
+ const assertOutput = fnDef.outputSchema?.pipe(Schema.asserts);
50
+ (assertOutput as any)(data);
51
+
52
+ return data as any;
46
53
  }
47
54
  }
package/src/handler.ts CHANGED
@@ -6,11 +6,13 @@ import { Schema, type Context, type Effect } from 'effect';
6
6
 
7
7
  import { type AiServiceClient } from '@dxos/ai';
8
8
  // import { type Space } from '@dxos/client/echo';
9
- import type { CoreDatabase, EchoDatabase } from '@dxos/echo-db';
9
+ import type { EchoDatabase } from '@dxos/echo-db';
10
10
  import { type HasId } from '@dxos/echo-schema';
11
11
  import { type SpaceId, type DXN } from '@dxos/keys';
12
12
  import { type QueryResult } from '@dxos/protocols';
13
13
 
14
+ import type { Services } from './services';
15
+
14
16
  // TODO(burdon): Model after http request. Ref Lambda/OpenFaaS.
15
17
  // https://docs.aws.amazon.com/lambda/latest/dg/typescript-handler.html
16
18
  // https://www.serverless.com/framework/docs/providers/aws/guide/serverless.yml/#functions
@@ -31,26 +33,26 @@ export type FunctionHandler<TData = {}, TOutput = any> = (params: {
31
33
  * This will be the payload from the trigger or other data passed into the function in a workflow.
32
34
  */
33
35
  data: TData;
34
- }) => TOutput | Promise<TOutput> | Effect.Effect<TOutput, any>;
36
+ }) => TOutput | Promise<TOutput> | Effect.Effect<TOutput, any, Services>;
35
37
 
36
38
  /**
37
39
  * Function context.
38
40
  */
39
41
  export interface FunctionContext {
40
42
  /**
41
- * Resolves a service available to the function.
42
- * @throws if the service is not available.
43
+ * Space from which the function was invoked.
43
44
  */
44
- getService: <T extends Context.Tag<any, any>>(tag: T) => Context.Tag.Service<T>;
45
+ space: SpaceAPI | undefined;
45
46
 
46
- getSpace: (spaceId: SpaceId) => Promise<SpaceAPI>;
47
+ ai: AiServiceClient;
47
48
 
48
49
  /**
49
- * Space from which the function was invoked.
50
+ * Resolves a service available to the function.
51
+ * @throws if the service is not available.
50
52
  */
51
- space: SpaceAPI | undefined;
53
+ getService: <T extends Context.Tag<any, any>>(tag: T) => Context.Tag.Service<T>;
52
54
 
53
- ai: AiServiceClient;
55
+ getSpace: (spaceId: SpaceId) => Promise<SpaceAPI>;
54
56
  }
55
57
 
56
58
  export interface FunctionContextAi {
@@ -74,12 +76,9 @@ export interface QueuesAPI {
74
76
  */
75
77
  export interface SpaceAPI {
76
78
  get id(): SpaceId;
77
- /**
78
- * @deprecated
79
- */
80
- get crud(): CoreDatabase;
81
79
  get db(): EchoDatabase;
82
- // TODO(dmaretskyi): Align with echo api --- queues.get(id).append(items);
80
+
81
+ // TODO(dmaretskyi): Align with echo api: queues.get(id).append(items);
83
82
  get queues(): QueuesAPI;
84
83
  }
85
84
 
@@ -89,6 +88,7 @@ const __assertFunctionSpaceIsCompatibleWithTheClientSpace = () => {
89
88
  };
90
89
 
91
90
  export type FunctionDefinition<T = {}, O = any> = {
91
+ name: string;
92
92
  description?: string;
93
93
  inputSchema: Schema.Schema<T, any>;
94
94
  outputSchema?: Schema.Schema<O, any>;
@@ -96,18 +96,25 @@ export type FunctionDefinition<T = {}, O = any> = {
96
96
  };
97
97
 
98
98
  // TODO(dmaretskyi): Bind input type to function handler.
99
- export const defineFunction = <T, O>(params: FunctionDefinition<T, O>): FunctionDefinition<T, O> => {
100
- if (!Schema.isSchema(params.inputSchema)) {
99
+ export const defineFunction = <T, O>({
100
+ name,
101
+ description,
102
+ inputSchema,
103
+ outputSchema = Schema.Any,
104
+ handler,
105
+ }: FunctionDefinition<T, O>): FunctionDefinition<T, O> => {
106
+ if (!Schema.isSchema(inputSchema)) {
101
107
  throw new Error('Input schema must be a valid schema');
102
108
  }
103
- if (typeof params.handler !== 'function') {
109
+ if (typeof handler !== 'function') {
104
110
  throw new Error('Handler must be a function');
105
111
  }
106
112
 
107
113
  return {
108
- description: params.description,
109
- inputSchema: params.inputSchema,
110
- outputSchema: params.outputSchema ?? Schema.Any,
111
- handler: params.handler,
114
+ name,
115
+ description,
116
+ inputSchema,
117
+ outputSchema,
118
+ handler,
112
119
  };
113
120
  };
package/src/index.ts CHANGED
@@ -9,5 +9,6 @@ export * from './types';
9
9
  export * from './url';
10
10
  export * from './services';
11
11
  export * from './executor';
12
+ export * from './errors';
12
13
 
13
14
  // Blow up cache
@@ -2,7 +2,7 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { Context } from 'effect';
5
+ import { Context, Effect } from 'effect';
6
6
 
7
7
  type CredentialQuery = {
8
8
  service?: string;
@@ -10,7 +10,7 @@ type CredentialQuery = {
10
10
 
11
11
  // TODO(dmaretskyi): Unify with other apis.
12
12
  // packages/sdk/schema/src/common/access-token.ts
13
- type ServiceCredential = {
13
+ export type ServiceCredential = {
14
14
  service: string;
15
15
 
16
16
  // TODO(dmaretskyi): Build out.
@@ -31,7 +31,13 @@ export class CredentialsService extends Context.Tag('CredentialsService')<
31
31
  */
32
32
  getCredential: (query: CredentialQuery) => Promise<ServiceCredential>;
33
33
  }
34
- >() {}
34
+ >() {
35
+ static getCredential = (query: CredentialQuery): Effect.Effect<ServiceCredential, never, CredentialsService> =>
36
+ Effect.gen(function* () {
37
+ const credentials = yield* CredentialsService;
38
+ return yield* Effect.promise(() => credentials.getCredential(query));
39
+ });
40
+ }
35
41
 
36
42
  export class ConfiguredCredentialsService implements Context.Tag.Service<CredentialsService> {
37
43
  constructor(private readonly credentials: ServiceCredential[] = []) {}
@@ -2,9 +2,11 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { Context, Layer } from 'effect';
5
+ import { Context, Effect, Layer } from 'effect';
6
6
 
7
- import type { EchoDatabase } from '@dxos/echo-db';
7
+ import type { Filter, Live, Obj, Query, Ref, Relation } from '@dxos/echo';
8
+ import type { EchoDatabase, OneShotQueryResult, QueryResult } from '@dxos/echo-db';
9
+ import type { DXN } from '@dxos/keys';
8
10
 
9
11
  export class DatabaseService extends Context.Tag('DatabaseService')<
10
12
  DatabaseService,
@@ -25,4 +27,44 @@ export class DatabaseService extends Context.Tag('DatabaseService')<
25
27
  },
26
28
  };
27
29
  };
30
+
31
+ static resolve: (dxn: DXN) => Effect.Effect<Obj.Any | Relation.Any, Error, DatabaseService> = Effect.fn(
32
+ function* (dxn) {
33
+ const { db } = yield* DatabaseService;
34
+ return yield* Effect.tryPromise({
35
+ try: () =>
36
+ db.graph.createRefResolver({ context: { space: db.spaceId } }).resolve(dxn) as Promise<
37
+ Obj.Any | Relation.Any
38
+ >,
39
+ catch: (error) => error as Error,
40
+ });
41
+ },
42
+ );
43
+
44
+ static loadRef: <T>(ref: Ref.Ref<T>) => Effect.Effect<T, never, never> = Effect.fn(function* (ref) {
45
+ return yield* Effect.promise(() => ref.load());
46
+ });
47
+
48
+ /**
49
+ * Creates a `QueryResult` object that can be subscribed to.
50
+ */
51
+ static query: {
52
+ <Q extends Query.Any>(query: Q): Effect.Effect<QueryResult<Live<Query.Type<Q>>>, never, DatabaseService>;
53
+ <F extends Filter.Any>(filter: F): Effect.Effect<QueryResult<Live<Filter.Type<F>>>, never, DatabaseService>;
54
+ } = (queryOrFilter: Query.Any | Filter.Any) =>
55
+ DatabaseService.pipe(
56
+ Effect.map(({ db }) => db.query(queryOrFilter as any)),
57
+ Effect.withSpan('DatabaseService.query'),
58
+ );
59
+
60
+ /**
61
+ * Executes the query once and returns the results.
62
+ */
63
+ static runQuery: {
64
+ <Q extends Query.Any>(query: Q): Effect.Effect<OneShotQueryResult<Live<Query.Type<Q>>>, never, DatabaseService>;
65
+ <F extends Filter.Any>(filter: F): Effect.Effect<OneShotQueryResult<Live<Filter.Type<F>>>, never, DatabaseService>;
66
+ } = (queryOrFilter: Query.Any | Filter.Any) =>
67
+ DatabaseService.query(queryOrFilter as any).pipe(
68
+ Effect.flatMap((queryResult) => Effect.promise(() => queryResult.run())),
69
+ );
28
70
  }
@@ -2,7 +2,6 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- export * from './ai';
6
5
  export * from './database';
7
6
  export * from './queues';
8
7
  export * from './service-container';
@@ -4,34 +4,52 @@
4
4
 
5
5
  import { Context, Layer } from 'effect';
6
6
 
7
- import type { Queue, QueueFactory } from '@dxos/echo-db';
7
+ import type { Queue, QueueAPI, QueueFactory } from '@dxos/echo-db';
8
8
 
9
+ /**
10
+ * Gives access to all queues.
11
+ */
9
12
  export class QueueService extends Context.Tag('QueueService')<
10
13
  QueueService,
11
14
  {
12
15
  /**
13
16
  * API to access the queues.
14
17
  */
15
- readonly queues: QueueFactory;
18
+ readonly queues: QueueAPI;
16
19
 
17
20
  /**
18
21
  * The queue that is used to store the context of the current research.
22
+ * @deprecated Use `ContextQueueService` instead.
19
23
  */
20
- // TODO(dmaretskyi): Is this really part of the queue service?
21
24
  readonly contextQueue: Queue | undefined;
22
25
  }
23
26
  >() {
24
27
  static notAvailable = Layer.succeed(QueueService, {
25
- get queues(): QueueFactory {
26
- throw new Error('Queues not available');
28
+ queues: {
29
+ get(dxn) {
30
+ throw new Error('Queues not available');
31
+ },
32
+ create() {
33
+ throw new Error('Queues not available');
34
+ },
27
35
  },
28
36
  contextQueue: undefined,
29
37
  });
30
38
 
31
- static make = (queues: QueueFactory, contextQueue: Queue | undefined): Context.Tag.Service<QueueService> => {
39
+ static make = (queues: QueueFactory, contextQueue?: Queue): Context.Tag.Service<QueueService> => {
32
40
  return {
33
41
  queues,
34
42
  contextQueue,
35
43
  };
36
44
  };
37
45
  }
46
+
47
+ /**
48
+ * Gives access to a specific queue passed as a context.
49
+ */
50
+ export class ContextQueueService extends Context.Tag('ContextQueueService')<
51
+ ContextQueueService,
52
+ {
53
+ readonly contextQueue: Queue;
54
+ }
55
+ >() {}
@@ -2,9 +2,11 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { Layer, type Context } from 'effect';
5
+ import { type Context, Layer } from 'effect';
6
+
7
+ import { AiService } from '@dxos/ai';
8
+ import { entries } from '@dxos/util';
6
9
 
7
- import { AiService } from './ai';
8
10
  import { ConfiguredCredentialsService, CredentialsService } from './credentials';
9
11
  import { DatabaseService } from './database';
10
12
  import { EventLogger } from './event-logger';
@@ -12,55 +14,53 @@ import { FunctionCallService } from './function-call-service';
12
14
  import { QueueService } from './queues';
13
15
  import { TracingService } from './tracing';
14
16
 
17
+ // TODO(dmaretskyi): Refactor this module to only rely on tags and not the human-assigned names.
18
+
15
19
  /**
16
- * List of all service tags and their names.
20
+ * List of all services.
17
21
  */
18
- export interface ServiceTagRecord {
19
- ai: AiService;
20
- credentials: CredentialsService;
21
- database: DatabaseService;
22
- eventLogger: EventLogger;
23
- functionCallService: FunctionCallService;
24
- tracing: TracingService;
25
- queues: QueueService;
26
- }
22
+ const SERVICES = {
23
+ ai: AiService,
24
+ credentials: CredentialsService,
25
+ database: DatabaseService,
26
+ eventLogger: EventLogger,
27
+ functionCallService: FunctionCallService,
28
+ queues: QueueService,
29
+ tracing: TracingService,
30
+ } as const satisfies Record<string, Context.TagClass<any, string, any>>;
31
+
32
+ /**
33
+ * Mapping of service names to their tags.
34
+ */
35
+ export type ServiceTagRecord = {
36
+ [K in keyof typeof SERVICES]: (typeof SERVICES)[K] extends { new (_: never): infer T } ? T : never;
37
+ };
27
38
 
28
39
  /**
29
- * List of all services and their runtime types.
40
+ * Mapping of service names to their runtime types.
30
41
  */
31
42
  export type ServiceRecord = {
32
43
  [K in keyof ServiceTagRecord]: Context.Tag.Service<ServiceTagRecord[K]>;
33
44
  };
34
45
 
35
46
  /**
36
- * Union of all services.
47
+ * Union of all services tags.
37
48
  */
38
49
  export type Services = ServiceTagRecord[keyof ServiceTagRecord];
39
50
 
40
- const SERVICE_MAPPING: Record<string, keyof ServiceRecord> = {
41
- [AiService.key]: 'ai',
42
- [CredentialsService.key]: 'credentials',
43
- [DatabaseService.key]: 'database',
44
- [EventLogger.key]: 'eventLogger',
45
- [FunctionCallService.key]: 'functionCallService',
46
- [QueueService.key]: 'queues',
47
- [TracingService.key]: 'tracing',
48
- };
51
+ const SERVICE_MAPPING: Record<string, keyof ServiceRecord> = Object.fromEntries(
52
+ entries(SERVICES).map(([name, tag]) => [tag.key, name]),
53
+ );
49
54
 
50
- export const SERVICE_TAGS: Context.Tag<any, any>[] = [
51
- AiService,
52
- CredentialsService,
53
- DatabaseService,
54
- EventLogger,
55
- FunctionCallService,
56
- TracingService,
57
- QueueService,
58
- ];
55
+ export const SERVICE_TAGS: Context.Tag<any, any>[] = Object.values(SERVICES);
59
56
 
60
57
  const DEFAULT_SERVICES: Partial<ServiceRecord> = {
61
58
  tracing: TracingService.noop,
62
59
  };
63
60
 
61
+ /**
62
+ * @deprecated
63
+ */
64
64
  export class ServiceContainer {
65
65
  private _services: Partial<ServiceRecord> = { ...DEFAULT_SERVICES };
66
66
 
@@ -74,13 +74,14 @@ export class ServiceContainer {
74
74
  return this;
75
75
  }
76
76
 
77
- getService<T extends Context.Tag<any, any>>(tag: T): Context.Tag.Service<T> {
77
+ getService<Id, T>(tag: Context.Tag<Id, T>): T {
78
78
  const serviceKey = SERVICE_MAPPING[tag.key];
79
79
  const service = serviceKey != null ? this._services[serviceKey] : undefined;
80
80
  if (!service) {
81
81
  throw new Error(`Service not available: ${tag.key}`);
82
82
  }
83
- return service as Context.Tag.Service<T>;
83
+
84
+ return service as T;
84
85
  }
85
86
 
86
87
  clone(): ServiceContainer {
@@ -90,7 +91,10 @@ export class ServiceContainer {
90
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.
91
92
  createLayer(): Layer.Layer<Services> {
92
93
  const ai = this._services.ai != null ? Layer.succeed(AiService, this._services.ai) : AiService.notAvailable;
93
- const credentials = Layer.succeed(CredentialsService, new ConfiguredCredentialsService());
94
+ const credentials = Layer.succeed(
95
+ CredentialsService,
96
+ this._services.credentials ?? new ConfiguredCredentialsService(),
97
+ );
94
98
  const database =
95
99
  this._services.database != null
96
100
  ? Layer.succeed(DatabaseService, this._services.database)
@@ -0,0 +1,42 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { describe, it } from '@effect/vitest';
6
+ import { Context, Effect, Layer, Option } from 'effect';
7
+
8
+ import { ServiceRegistry } from './service-registry';
9
+
10
+ class MyTag extends Context.Tag('MyTag')<MyTag, { value: string }>() {}
11
+
12
+ const mockRegistry = Layer.succeed(ServiceRegistry, {
13
+ resolve: (tag) => ((tag as any) === MyTag ? Option.some({ value: 'test' } as any) : Option.none()),
14
+ });
15
+
16
+ describe('ServiceRegistry', () => {
17
+ it.effect(
18
+ 'provide',
19
+ Effect.fn(function* ({ expect }) {
20
+ const body = Effect.gen(function* () {
21
+ const { value } = yield* MyTag;
22
+ expect(value).toEqual('test');
23
+ });
24
+
25
+ const eff = body.pipe(ServiceRegistry.provide(MyTag));
26
+ yield* eff;
27
+ }, Effect.provide(mockRegistry)),
28
+ );
29
+
30
+ it.effect(
31
+ 'provide or die',
32
+ Effect.fn(function* ({ expect }) {
33
+ const body = Effect.gen(function* () {
34
+ const { value } = yield* MyTag;
35
+ expect(value).toEqual('test');
36
+ });
37
+
38
+ const eff = body.pipe(ServiceRegistry.provideOrDie(MyTag));
39
+ yield* eff;
40
+ }, Effect.provide(mockRegistry)),
41
+ );
42
+ });