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, MuseSdkError } 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) =>
30 Effect.tryPromise({
31 try: () => host.close(),
32 catch: (cause) => new MuseSdkError({ operation: "close", cause }),
33 }).pipe(Effect.ignore),
34 { interruptible: true },
35 );
36 return host.initializeResult.museHome;
37 }),
38 );
39 }),
40 {
41 capacity: 32,
42 // Retry unavailable installations, but keep resolved homes across scans.
43 timeToLive: (exit) =>
44 Exit.isSuccess(exit) && exit.value ? Duration.infinity : Duration.seconds(30),
45 },
46 );
47 const resolve: MuseUsageHome["Service"]["resolve"] = Effect.fn("MuseUsageHome.resolve")(
48 function* ({ binaryPath, environment }) {
49 // Cache keys compare structurally. Omitted and undefined variables both
50 // disappear from the child process environment and must share an entry.
51 return yield* Cache.get(cache, {
52 binaryPath,
53 environment: Object.fromEntries(
54 Object.entries(environment).filter(([, value]) => value !== undefined),
55 ),
56 }).pipe(Effect.orElseSucceed(() => undefined));
57 },
58 );
59 return MuseUsageHome.of({ resolve });
60});
61
62export const layer = Layer.effect(MuseUsageHome, make);