| 1 | import { ArchiveError } from "@t3tools/contracts"; |
| 2 | import * as DateTime from "effect/DateTime"; |
| 3 | import * as Effect from "effect/Effect"; |
| 4 | import * as Layer from "effect/Layer"; |
| 5 | import * as Option from "effect/Option"; |
| 6 | import * as SourceConnection from "../environment/SourceConnection.ts"; |
| 7 | import * as ArchiveConnection from "./ArchiveConnection.ts"; |
| 8 | |
| 9 | export const layer = Layer.effect( |
| 10 | ArchiveConnection.ArchiveConnection, |
| 11 | Effect.gen(function* () { |
| 12 | const legacy = yield* ArchiveConnection.ArchiveConnection; |
| 13 | const source = yield* SourceConnection.SourceConnection; |
| 14 | return ArchiveConnection.ArchiveConnection.of({ |
| 15 | enabled: source.current.pipe( |
| 16 | Effect.flatMap((current) => |
| 17 | Option.isSome(current) ? Effect.succeed(true) : legacy.enabled, |
| 18 | ), |
| 19 | ), |
| 20 | target: Effect.gen(function* () { |
| 21 | const current = yield* source.current; |
| 22 | if (Option.isNone(current)) return yield* legacy.target; |
| 23 | const now = yield* DateTime.now; |
| 24 | if (current.value.expiresAt.epochMilliseconds <= now.epochMilliseconds) |
| 25 | return yield* new ArchiveError({ reason: "unavailable" }); |
| 26 | return Option.some({ |
| 27 | url: current.value.serverUrl, |
| 28 | authorization: current.value.authorization, |
| 29 | }); |
| 30 | }), |
| 31 | }); |
| 32 | }), |
| 33 | ).pipe(Layer.provide(ArchiveConnection.layerLegacy)); |