| 1 | import { |
| 2 | ArchiveError, |
| 3 | OrchestrationV2ThreadDetailSnapshot, |
| 4 | type EnvironmentId, |
| 5 | type ThreadId, |
| 6 | } from "@t3tools/contracts"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as Schema from "effect/Schema"; |
| 9 | import * as SubscriptionRef from "effect/SubscriptionRef"; |
| 10 | import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; |
| 11 | import * as HubConnection from "../connection/hub.ts"; |
| 12 | |
| 13 | export const fetchArchivedThreadSnapshot = Effect.fn( |
| 14 | "clientRuntime.state.fetchArchivedThreadSnapshot", |
| 15 | )(function* (environmentId: EnvironmentId, threadId: ThreadId) { |
| 16 | const hub = yield* HubConnection.HubConnection; |
| 17 | const connection = (yield* SubscriptionRef.get(hub.state)).connection; |
| 18 | if (!connection) return yield* new ArchiveError({ reason: "unavailable" }); |
| 19 | const http = yield* HttpClient.HttpClient; |
| 20 | return yield* HttpClientRequest.get( |
| 21 | `${connection.httpBaseUrl}/api/archive/catalog/${encodeURIComponent(environmentId)}/${encodeURIComponent(threadId)}`, |
| 22 | ).pipe( |
| 23 | HttpClientRequest.setHeaders(yield* hub.headers), |
| 24 | http.execute, |
| 25 | Effect.provideService(FetchHttpClient.RequestInit, { redirect: "error" }), |
| 26 | Effect.flatMap(HttpClientResponse.filterStatusOk), |
| 27 | Effect.flatMap( |
| 28 | HttpClientResponse.schemaBodyJson(Schema.toCodecJson(OrchestrationV2ThreadDetailSnapshot)), |
| 29 | ), |
| 30 | Effect.filterOrFail( |
| 31 | (snapshot) => |
| 32 | snapshot.projection.thread.id === threadId && |
| 33 | snapshot.projection.thread.archivedAt !== null, |
| 34 | () => new ArchiveError({ reason: "integrity" }), |
| 35 | ), |
| 36 | Effect.timeout("10 seconds"), |
| 37 | ); |
| 38 | }); |