Open History to see the last commit
1/**
2 * A `ProviderHost.ProviderHost` for driver and adapter tests. Its directories live in a
3 * scoped temp directory, settings are fixed, and background work always runs
4 * unless the test says otherwise.
5 *
6 * @module provider-testing/host
7 */
8import { DEFAULT_SERVER_SETTINGS, type ServerSettings } from "@t3tools/contracts";
9import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
10import * as Effect from "effect/Effect";
11import * as FileSystem from "effect/FileSystem";
12import * as Layer from "effect/Layer";
13import * as Option from "effect/Option";
14import * as Path from "effect/Path";
15import * as Stream from "effect/Stream";
16
17export interface TestProviderHostOptions {
18 /** Session fallback cwd. Defaults to the test process cwd. */
19 readonly cwd?: string;
20 readonly settings?: ServerSettings;
21 /** Whether background work such as status probes may run. Defaults to `true`. */
22 readonly runBackgroundWork?: boolean;
23}
24
25export const layerTestProviderHost = (
26 options: TestProviderHostOptions = {},
27): Layer.Layer<ProviderHost.ProviderHost, never, FileSystem.FileSystem | Path.Path> =>
28 Layer.effect(
29 ProviderHost.ProviderHost,
30 Effect.gen(function* () {
31 const fileSystem = yield* FileSystem.FileSystem;
32 const path = yield* Path.Path;
33 const baseDir = yield* fileSystem
34 .makeTempDirectoryScoped({ prefix: "t3-provider-host-" })
35 .pipe(Effect.orDie);
36 const stateDir = path.join(baseDir, "userdata");
37 const providerStatusCacheDir = path.join(baseDir, "caches");
38 const attachmentsDir = path.join(stateDir, "attachments");
39 for (const directory of [stateDir, providerStatusCacheDir, attachmentsDir]) {
40 yield* fileSystem.makeDirectory(directory, { recursive: true }).pipe(Effect.orDie);
41 }
42 const settings = options.settings ?? DEFAULT_SERVER_SETTINGS;
43 const credentials = new Map<string, Uint8Array>();
44 return ProviderHost.ProviderHost.of({
45 paths: {
46 cwd: options.cwd ?? process.cwd(),
47 baseDir,
48 stateDir,
49 providerStatusCacheDir,
50 attachmentsDir,
51 },
52 settings: {
53 get: Effect.succeed(settings),
54 changes: Stream.empty,
55 subscribe: Effect.succeed(Stream.empty),
56 },
57 shouldRunBackgroundWork: () => Effect.succeed(options.runBackgroundWork ?? true),
58 // Tests store attachments flat under the attachments directory by id.
59 resolveAttachmentPath: (attachment) => path.join(attachmentsDir, attachment.id),
60 // Credentials live in memory for the layer's lifetime.
61 credentials: (namespace, bindingId) =>
62 Effect.sync(() => {
63 const key = `${namespace}:${bindingId}`;
64 return {
65 binding: { owner: "t3" as const, key },
66 get: Effect.sync(() => Option.fromUndefinedOr(credentials.get(key))),
67 set: (value: Uint8Array) => Effect.sync(() => void credentials.set(key, value)),
68 remove: Effect.sync(() => void credentials.delete(key)),
69 };
70 }),
71 });
72 }),
73 );