Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DesktopLocalEnvironmentAuth.ts

137 lines5.6 KB

1import { bootstrapRemoteBearerSession } from "@t3tools/client-runtime/authorization";
2import type { RemoteEnvironmentRequestError } from "@t3tools/client-runtime/rpc";
3import { PRIMARY_LOCAL_ENVIRONMENT_ID } from "@t3tools/contracts";
4import { currentDesktopBootstrapToken } from "@t3tools/shared/desktopBootstrapToken";
5import * as Clock from "effect/Clock";
6import * as Context from "effect/Context";
7import * as Duration from "effect/Duration";
8import * as Effect from "effect/Effect";
9import * as Layer from "effect/Layer";
10import * as Option from "effect/Option";
11import * as Ref from "effect/Ref";
12import * as Schedule from "effect/Schedule";
13import * as Schema from "effect/Schema";
14import * as Semaphore from "effect/Semaphore";
15import * as HttpClient from "effect/http/HttpClient";
16​
17import * as DesktopBackendPool from "./DesktopBackendPool.ts";
18​
19const BOOTSTRAP_TRANSIENT_RETRY_TIMEOUT = Duration.seconds(15);
20const BOOTSTRAP_TRANSIENT_RETRY_INTERVAL = Duration.millis(500);
21const TRANSIENT_BOOTSTRAP_STATUS_CODES = new Set([502, 503, 504]);
22// The window opens while the backend starts, and a cold start can outlast the
23// retry window above. The exchange waits for readiness first, up to this
24// bound, so a backend that never becomes ready still fails it.
25const BACKEND_START_TIMEOUT = Duration.minutes(2);
26​
27const isTransientBearerBootstrapError = (error: RemoteEnvironmentRequestError): boolean => {
28 switch (error._tag) {
29 case "RemoteEnvironmentAuthFetchError":
30 case "RemoteEnvironmentAuthTimeoutError":
31 return true;
32 case "RemoteEnvironmentAuthUndeclaredStatusError":
33 return TRANSIENT_BOOTSTRAP_STATUS_CODES.has(error.status);
34 default:
35 return false;
36 }
37};
38​
39export class DesktopLocalEnvironmentAuthBackendNotConfiguredError extends Schema.TaggedError<DesktopLocalEnvironmentAuthBackendNotConfiguredError>()(
40 "DesktopLocalEnvironmentAuthBackendNotConfiguredError",
41 {},
42) {
43 override get message(): string {
44 return "Local backend is not configured.";
45 }
47​
48export class DesktopLocalEnvironmentAuthSessionBootstrapError extends Schema.TaggedError<DesktopLocalEnvironmentAuthSessionBootstrapError>()(
49 "DesktopLocalEnvironmentAuthSessionBootstrapError",
50 { cause: Schema.Defect() },
51) {
52 override get message(): string {
53 return "Failed to create the local desktop bearer session.";
54 }
56​
57export const DesktopLocalEnvironmentAuthError = Schema.Union([
58 DesktopLocalEnvironmentAuthBackendNotConfiguredError,
59 DesktopLocalEnvironmentAuthSessionBootstrapError,
60]);
61export type DesktopLocalEnvironmentAuthError = typeof DesktopLocalEnvironmentAuthError.Type;
62​
63export class DesktopLocalEnvironmentAuth extends Context.Service<
64 DesktopLocalEnvironmentAuth,
65 {
66 readonly getBearerToken: Effect.Effect<string, DesktopLocalEnvironmentAuthError>;
67 }
68>()("@t3tools/desktop/backend/DesktopLocalEnvironmentAuth") {}
69​
70/** @public Service construction is part of the canonical Effect module API. */
71export const make = Effect.gen(function* () {
72 const pool = yield* DesktopBackendPool.DesktopBackendPool;
73 const httpClient = yield* HttpClient.HttpClient;
74 const tokenRef = yield* Ref.make(Option.none<string>());
75 const mutex = yield* Semaphore.make(1);
76​
77 const getBearerToken = mutex
78 .withPermits(1)(
79 Effect.gen(function* () {
80 const cached = yield* Ref.get(tokenRef);
81 if (Option.isSome(cached)) {
82 return cached.value;
83 }
84​
85 const instances = yield* pool.list;
86 const primary = instances.find((instance) => instance.id === PRIMARY_LOCAL_ENVIRONMENT_ID);
87 // Returns at once for a ready backend or one that is not running.
88 if (primary !== undefined) {
89 yield* primary.waitForReady(BACKEND_START_TIMEOUT);
90 }
91 const configOption = primary === undefined ? Option.none() : yield* primary.currentConfig;
92 if (Option.isNone(configOption)) {
93 return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError();
94 }
95 const config = configOption.value;
96 // A backend launched with the desktop secret accepts the current
97 // window's token, not the one frozen into its launch config; this
98 // exchange can run long after launch (e.g. after a suspend).
99 const secret = config.bootstrap.desktopBootstrapSecret;
100 const credential =
101 secret === undefined
102 ? config.bootstrap.desktopBootstrapToken
103 : currentDesktopBootstrapToken(secret, yield* Clock.currentTimeMillis);
104 if (!credential) {
105 return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError();
106 }
107 const session = yield* bootstrapRemoteBearerSession({
108 httpBaseUrl: config.httpBaseUrl.href,
109 credential,
110 clientMetadata: {
111 label: "T3 Code Desktop",
112 deviceType: "desktop",
113 },
114 }).pipe(
115 Effect.provideService(HttpClient.HttpClient, httpClient),
116 Effect.retry({
117 while: isTransientBearerBootstrapError,
118 schedule: Schedule.spaced(BOOTSTRAP_TRANSIENT_RETRY_INTERVAL),
119 }),
120 Effect.timeout(BOOTSTRAP_TRANSIENT_RETRY_TIMEOUT),
121 Effect.mapError(
122 (cause) =>
123 new DesktopLocalEnvironmentAuthSessionBootstrapError({
124 cause,
125 }),
126 ),
127 );
128 yield* Ref.set(tokenRef, Option.some(session.access_token));
129 return session.access_token;
130 }),
131 )
132 .pipe(Effect.withSpan("desktop.localEnvironmentAuth.getBearerToken"));
133​
134 return DesktopLocalEnvironmentAuth.of({ getBearerToken });
135});
136​
137export const layer = Layer.effect(DesktopLocalEnvironmentAuth, make);