Open History to see the last commit
1import * as Cache from "effect/Cache";
2import * as Context from "effect/Context";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
5import * as Exit from "effect/Exit";
6import * as Layer from "effect/Layer";
7
8import { createMuseSdkHostEffect } from "./sdk.ts";
9
10export class MuseUsageHome extends Context.Service<
11 MuseUsageHome,
12 {
13 readonly resolve: (input: {
14 readonly binaryPath: string;
15 readonly environment: NodeJS.ProcessEnv;
16 }) => Effect.Effect<string | undefined>;
17 }
18>()("@t3tools/provider-muse/server/MuseUsageHome") {}
19
20const make = Effect.gen(function* () {
21 const cache = yield* Cache.makeWith(
22 Effect.fn("MuseUsageHome.initialize")(function* (
23 input: Parameters<MuseUsageHome["Service"]["resolve"]>[0],
24 ) {
25 return yield* Effect.scoped(
26 Effect.gen(function* () {
27 const host = yield* Effect.acquireRelease(
28 createMuseSdkHostEffect({ ...input, readOnly: true, startupTimeoutMs: 5_000 }),
29 (host) => Effect.tryPromise(() => host.close()).pipe(Effect.ignore),
30 { interruptible: true },
31 );
32 return host.initializeResult.museHome;
33 }),
34 );
35 }),
36 {
37 capacity: 32,
38 // Retry unavailable installations, but keep resolved homes across scans.
39 timeToLive: (exit) =>
40 Exit.isSuccess(exit) && exit.value ? Duration.infinity : Duration.seconds(30),
41 },
42 );
43 const resolve: MuseUsageHome["Service"]["resolve"] = Effect.fn("MuseUsageHome.resolve")(
44 function* ({ binaryPath, environment }) {
45 // Cache keys compare structurally. Omitted and undefined variables both
46 // disappear from the child process environment and must share an entry.
47 return yield* Cache.get(cache, {
48 binaryPath,
49 environment: Object.fromEntries(
50 Object.entries(environment).filter(([, value]) => value !== undefined),
51 ),
52 }).pipe(Effect.orElseSucceed(() => undefined));
53 },
54 );
55 return MuseUsageHome.of({ resolve });
56});
57
58export const layer = Layer.effect(MuseUsageHome, make);