The best way to control Claude Code, Codex and more from any computer or phone

main
ts 64 lines 2.32 KB
Raw
1 import type { Url } from "@alchemy.run/redis";
2 import * as Binding from "alchemy/Binding";
3 import type { Resource } from "alchemy/Resource";
4 import * as Config from "effect/Config";
5 import * as Effect from "effect/Effect";
6 import * as Redacted from "effect/Redacted";
7 import type { ServiceBinding } from "./MountVolume.ts";
8 import { REDIS_URL_ENV, RedisUrlMissing, type Redis } from "./Redis.ts";
9
10 /**
11 * Shared scaffolding for Upstash Redis bindings.
12 *
13 * Each `{Op}Http.ts` is a thin `Layer.effect` over {@link makeRedisBinding}.
14 * Deploy-time registers the Redis add-on on the host so Service reconcile
15 * can attach it. The URL travels as `yield* redis.url` (RuntimeContext
16 * set/get). `REDIS_URL` written as an App secret is a fallback, not the
17 * primary path.
18 *
19 * The RESP client lives in `@alchemy.run/redis`. This file only wires the
20 * Fly host binding.
21 *
22 * NOT exported from `index.ts`.
23 */
24
25 const isFlyHost = (value: unknown): value is Resource<string, any, any, ServiceBinding> =>
26 typeof value === "object" &&
27 value !== null &&
28 ((value as { Type?: string }).Type === "Fly.Service" ||
29 (value as { Type?: string }).Type === "Fly.Machine");
30
31 const asPlain = (value: unknown): string | undefined => {
32 if (typeof value === "string" && value.length > 0) return value;
33 if (Redacted.isRedacted(value)) return value.pipe(Redacted.value, asPlain);
34 return undefined;
35 };
36
37 const redisUrlFromEnv = Config.Redacted(REDIS_URL_ENV).pipe(
38 Effect.map((value) => Redacted.value(value)),
39 );
40
41 export const makeRedisBinding = <Client>(options: { makeClient: (url: Url) => Client }) =>
42 Effect.succeed(
43 Effect.fn(function* (redis: Redis) {
44 if (!globalThis.__ALCHEMY_RUNTIME__) {
45 const host = yield* Binding.Host;
46 if (isFlyHost(host)) {
47 yield* host.bind`${redis}`({
48 redis: { name: redis.name, id: redis.redisId },
49 });
50 }
51 }
52
53 const urlFromResource = yield* redis.url;
54 const missing = new RedisUrlMissing({
55 resourceName: asPlain(redis.name) ?? redis.LogicalId,
56 });
57 const url: Url = Effect.gen(function* () {
58 const fromOutput = asPlain(yield* urlFromResource);
59 if (fromOutput !== undefined) return fromOutput;
60 return yield* redisUrlFromEnv.pipe(Effect.mapError(() => missing));
61 });
62 return options.makeClient(url);
63 }),
64 );