1import { ArchiveError } from "@t3tools/contracts";
2import * as Config from "effect/Config";
3import * as Context from "effect/Context";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import * as Redacted from "effect/Redacted";
8import * as SharedServer from "../environment/SharedServer.ts";
9
10export class ArchiveConnection extends Context.Service<
11 ArchiveConnection,
12 {
13 readonly enabled: Effect.Effect<boolean, ArchiveError>;
14 readonly target: Effect.Effect<
15 Option.Option<{ readonly url: string; readonly authorization: string }>,
16 ArchiveError
17 >;
18 }
19>()("t3/archive/ArchiveConnection") {}
20
21export const layerLegacy = Layer.effect(
22 ArchiveConnection,
23 Effect.gen(function* () {
24 const shared = yield* SharedServer.SharedServer;
25 const enabled = yield* Config.Boolean("T3CODE_ARCHIVE_OFFLOAD").pipe(
26 Config.withDefault(false),
27 Effect.orDie,
28 );
29 return ArchiveConnection.of({
30 enabled: Effect.succeed(enabled),
31 target: shared.connection.pipe(
32 Effect.map(
33 Option.map((connection) => ({
34 url: connection.url,
35 authorization: `Bearer ${connection.token}`,
36 })),
37 ),
38 Effect.mapError(
39 (cause) => new ArchiveError({ reason: "unavailable", cause: Redacted.make(cause) }),
40 ),
41 ),
42 });
43 }),
44);