The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { |
| 2 | type DesktopSshEnvironmentTarget, |
| 3 | EnvironmentId, |
| 4 | type OrchestrationV2ShellSnapshot, |
| 5 | ORCHESTRATION_PROTOCOL_VERSION, |
| 6 | type ExecutionEnvironmentDescriptor, |
| 7 | type ServerConfig, |
| 8 | } from "@t3tools/contracts"; |
| 9 | import { describe, expect, it } from "@effect/vitest"; |
| 10 | import * as Context from "effect/Context"; |
| 11 | import * as Deferred from "effect/Deferred"; |
| 12 | import * as Effect from "effect/Effect"; |
| 13 | import * as Exit from "effect/Exit"; |
| 14 | import * as Fiber from "effect/Fiber"; |
| 15 | import * as Layer from "effect/Layer"; |
| 16 | import * as Option from "effect/Option"; |
| 17 | import * as Ref from "effect/Ref"; |
| 18 | import * as Result from "effect/Result"; |
| 19 | import * as Scheduler from "effect/Scheduler"; |
| 20 | import * as Scope from "effect/Scope"; |
| 21 | import * as Stream from "effect/Stream"; |
| 22 | import * as SubscriptionRef from "effect/SubscriptionRef"; |
| 23 | import * as Tracer from "effect/Tracer"; |
| 24 | |
| 25 | import * as ClientCapabilities from "../platform/capabilities.ts"; |
| 26 | import * as TokenStore from "../authorization/tokenStore.ts"; |
| 27 | import { |
| 28 | BearerConnectionCredential, |
| 29 | BearerConnectionProfile, |
| 30 | BearerConnectionRegistration, |
| 31 | type ConnectionCatalogEntry, |
| 32 | type ConnectionRegistration, |
| 33 | type ConnectionRoute, |
| 34 | PrimaryConnectionRegistration, |
| 35 | RelayConnectionRegistration, |
| 36 | SshConnectionProfile, |
| 37 | SshConnectionRegistration, |
| 38 | type ConnectionCredential, |
| 39 | type ConnectionProfile, |
| 40 | } from "./catalog.ts"; |
| 41 | import * as Connectivity from "./connectivity.ts"; |
| 42 | import * as ConnectionCredentialStore from "./credentialStore.ts"; |
| 43 | import * as ConnectionDriver from "./driver.ts"; |
| 44 | import type { RouteCheck } from "./driver.ts"; |
| 45 | import { connectionRouteId, connectionRouteKind } from "./routes.ts"; |
| 46 | import { |
| 47 | ConnectionTransientError, |
| 48 | ConnectionBlockedError, |
| 49 | BearerConnectionTarget, |
| 50 | PrimaryConnectionTarget, |
| 51 | RelayConnectionTarget, |
| 52 | SshConnectionTarget, |
| 53 | type ConnectionTarget, |
| 54 | type PreparedConnection, |
| 55 | type SupervisorConnectionState, |
| 56 | } from "./model.ts"; |
| 57 | import * as Persistence from "../platform/persistence.ts"; |
| 58 | import * as ConnectionProfileStore from "./profileStore.ts"; |
| 59 | import * as EnvironmentRegistry from "./registry.ts"; |
| 60 | import { |
| 61 | PullRequestRoutingPermissions, |
| 62 | type StoredPullRequestRoutingPermission, |
| 63 | makePullRequestRoutingPermissions, |
| 64 | } from "./pullRequestRoutingPermissions.ts"; |
| 65 | import * as RpcSession from "../rpc/session.ts"; |
| 66 | import * as EnvironmentSupervisor from "./supervisor.ts"; |
| 67 | import * as ConnectionWakeups from "./wakeups.ts"; |
| 68 | import { watchDiscoveredCompatibility } from "./layer.ts"; |
| 69 | import * as RelayEnvironmentDiscovery from "../relay/discovery.ts"; |
| 70 | import type { RelayEnvironmentStatusResponse } from "@t3tools/contracts/relay"; |
| 71 | import { runDesktopCommitWithReconnectObserver } from "../state/server.ts"; |
| 72 | import { v2ShellSnapshot } from "../state/orchestrationV2TestFixtures.ts"; |
| 73 | |
| 74 | const TARGET = new PrimaryConnectionTarget({ |
| 75 | environmentId: EnvironmentId.make("environment-1"), |
| 76 | label: "Test environment", |
| 77 | httpBaseUrl: "https://environment.example.test", |
| 78 | wsBaseUrl: "wss://environment.example.test", |
| 79 | }); |
| 80 | const SECOND_TARGET = new PrimaryConnectionTarget({ |
| 81 | environmentId: EnvironmentId.make("environment-2"), |
| 82 | label: "Second environment", |
| 83 | httpBaseUrl: "https://environment-2.example.test", |
| 84 | wsBaseUrl: "wss://environment-2.example.test", |
| 85 | }); |
| 86 | |
| 87 | const PREPARED: PreparedConnection = { |
| 88 | environmentId: TARGET.environmentId, |
| 89 | label: TARGET.label, |
| 90 | httpBaseUrl: TARGET.httpBaseUrl, |
| 91 | socketUrl: "wss://environment.example.test/ws", |
| 92 | httpAuthorization: null, |
| 93 | target: TARGET, |
| 94 | }; |
| 95 | |
| 96 | const RELAY_TARGET = new RelayConnectionTarget({ |
| 97 | environmentId: EnvironmentId.make("environment-relay"), |
| 98 | label: "Relay environment", |
| 99 | }); |
| 100 | const SECOND_RELAY_TARGET = new RelayConnectionTarget({ |
| 101 | environmentId: EnvironmentId.make("environment-relay-2"), |
| 102 | label: "Second relay environment", |
| 103 | }); |
| 104 | |
| 105 | const BEARER_TARGET = new BearerConnectionTarget({ |
| 106 | environmentId: EnvironmentId.make("environment-bearer"), |
| 107 | label: "Bearer environment", |
| 108 | connectionId: "bearer-connection", |
| 109 | }); |
| 110 | const BEARER_PROFILE = new BearerConnectionProfile({ |
| 111 | connectionId: BEARER_TARGET.connectionId, |
| 112 | environmentId: BEARER_TARGET.environmentId, |
| 113 | label: BEARER_TARGET.label, |
| 114 | httpBaseUrl: "https://bearer.example.test", |
| 115 | wsBaseUrl: "wss://bearer.example.test", |
| 116 | }); |
| 117 | const BEARER_CREDENTIAL = new BearerConnectionCredential({ |
| 118 | token: "bearer-token", |
| 119 | }); |
| 120 | |
| 121 | const SSH_TARGET: DesktopSshEnvironmentTarget = { |
| 122 | alias: "test", |
| 123 | hostname: "test.example.test", |
| 124 | username: "developer", |
| 125 | port: 22, |
| 126 | }; |
| 127 | const SSH_CONNECTION = new SshConnectionTarget({ |
| 128 | environmentId: EnvironmentId.make("environment-ssh"), |
| 129 | label: "SSH environment", |
| 130 | connectionId: "ssh-connection", |
| 131 | }); |
| 132 | const SSH_PROFILE = new SshConnectionProfile({ |
| 133 | connectionId: SSH_CONNECTION.connectionId, |
| 134 | environmentId: SSH_CONNECTION.environmentId, |
| 135 | label: SSH_CONNECTION.label, |
| 136 | target: SSH_TARGET, |
| 137 | }); |
| 138 | |
| 139 | const CACHED_SNAPSHOT: OrchestrationV2ShellSnapshot = { |
| 140 | ...v2ShellSnapshot, |
| 141 | snapshotSequence: 1, |
| 142 | }; |
| 143 | |
| 144 | interface SessionControl { |
| 145 | readonly closed: Deferred.Deferred<never, ConnectionTransientError>; |
| 146 | } |
| 147 | |
| 148 | const makeHarness = Effect.fn("TestEnvironmentRegistry.makeHarness")(function* ( |
| 149 | initialTargets: ReadonlyArray<ConnectionTarget>, |
| 150 | initialProfiles: ReadonlyArray<ConnectionProfile> = [], |
| 151 | initialCredentials: ReadonlyArray<readonly [string, ConnectionCredential]> = [], |
| 152 | options?: { |
| 153 | readonly prepareError?: ConnectionBlockedError; |
| 154 | readonly beforeSessionConnect?: (environmentId: EnvironmentId) => Effect.Effect<void>; |
| 155 | readonly beforeRegistrationRegister?: ( |
| 156 | registration: ConnectionRegistration, |
| 157 | ) => Effect.Effect<void, Persistence.ConnectionPersistenceError>; |
| 158 | readonly beforeRegistrationRemove?: ( |
| 159 | environmentId: EnvironmentId, |
| 160 | ) => Effect.Effect<void, Persistence.ConnectionPersistenceError>; |
| 161 | readonly beforeCredentialPut?: ( |
| 162 | connectionId: string, |
| 163 | ) => Effect.Effect<void, ConnectionTransientError>; |
| 164 | readonly checkRoute?: (route: ConnectionRoute) => RouteCheck; |
| 165 | readonly prepareRoute?: (target: ConnectionTarget) => ConnectionBlockedError | undefined; |
| 166 | readonly beforePrepareRoute?: ( |
| 167 | target: ConnectionTarget, |
| 168 | ) => Effect.Effect<ConnectionBlockedError | undefined>; |
| 169 | readonly initialDisabled?: ReadonlyArray<EnvironmentId>; |
| 170 | readonly directEndpoints?: ServerConfig["directEndpoints"]; |
| 171 | }, |
| 172 | ) { |
| 173 | const storedTargets = yield* Ref.make<ReadonlyArray<ConnectionTarget>>(initialTargets); |
| 174 | const shellCache = yield* Ref.make(new Map([[TARGET.environmentId, CACHED_SNAPSHOT]])); |
| 175 | const cacheClears = yield* Ref.make<ReadonlyArray<EnvironmentId>>([]); |
| 176 | const ownedDataClears = yield* Ref.make<ReadonlyArray<EnvironmentId>>([]); |
| 177 | const sessions = yield* Ref.make<ReadonlyArray<SessionControl>>([]); |
| 178 | const releasedSessions = yield* Ref.make(0); |
| 179 | const storedProfiles = yield* Ref.make( |
| 180 | new Map(initialProfiles.map((profile) => [profile.connectionId, profile])), |
| 181 | ); |
| 182 | const profileReadCount = yield* Ref.make(0); |
| 183 | const storedCredentials = yield* Ref.make(new Map(initialCredentials)); |
| 184 | const storedRemoteTokens = yield* Ref.make( |
| 185 | new Map([ |
| 186 | [ |
| 187 | SSH_CONNECTION.environmentId, |
| 188 | new TokenStore.RemoteDpopAccessToken({ |
| 189 | environmentId: SSH_CONNECTION.environmentId, |
| 190 | label: SSH_CONNECTION.label, |
| 191 | endpoint: { |
| 192 | httpBaseUrl: "https://ssh.example.test", |
| 193 | wsBaseUrl: "wss://ssh.example.test", |
| 194 | providerKind: "cloudflare_tunnel", |
| 195 | }, |
| 196 | accessToken: "cached-token", |
| 197 | expiresAtEpochMs: Number.MAX_SAFE_INTEGER, |
| 198 | dpopThumbprint: "thumbprint", |
| 199 | }), |
| 200 | ], |
| 201 | ]), |
| 202 | ); |
| 203 | const disconnectedSshTargets = yield* Ref.make<ReadonlyArray<DesktopSshEnvironmentTarget>>([]); |
| 204 | |
| 205 | const storedDisabled = yield* Ref.make<ReadonlySet<EnvironmentId>>( |
| 206 | new Set(options?.initialDisabled ?? []), |
| 207 | ); |
| 208 | const targetStore = Persistence.ConnectionTargetStore.of({ |
| 209 | list: Ref.get(storedTargets), |
| 210 | listDisabled: Ref.get(storedDisabled).pipe(Effect.map((ids) => [...ids])), |
| 211 | }); |
| 212 | const registrationStore = Persistence.ConnectionRegistrationStore.of({ |
| 213 | register: (registration, routes) => |
| 214 | Effect.gen(function* () { |
| 215 | yield* options?.beforeRegistrationRegister?.(registration) ?? Effect.void; |
| 216 | yield* Ref.update(storedTargets, (current) => |
| 217 | replaceRoutes(current, registration.target.environmentId, routes), |
| 218 | ); |
| 219 | switch (registration._tag) { |
| 220 | case "RelayConnectionRegistration": |
| 221 | return; |
| 222 | case "BearerConnectionRegistration": |
| 223 | case "SshConnectionRegistration": |
| 224 | yield* Ref.update(storedProfiles, (current) => { |
| 225 | const next = new Map(current); |
| 226 | next.set(registration.profile.connectionId, registration.profile); |
| 227 | return next; |
| 228 | }); |
| 229 | yield* Ref.update(storedCredentials, (current) => { |
| 230 | const next = new Map(current); |
| 231 | next.set(registration.target.connectionId, registration.credential); |
| 232 | return next; |
| 233 | }); |
| 234 | return; |
| 235 | } |
| 236 | }), |
| 237 | setRoutes: (environmentId, routes) => |
| 238 | Ref.update(storedTargets, (current) => replaceRoutes(current, environmentId, routes)), |
| 239 | remove: (environmentId) => |
| 240 | Effect.gen(function* () { |
| 241 | yield* options?.beforeRegistrationRemove?.(environmentId) ?? Effect.void; |
| 242 | const removed = (yield* Ref.get(storedTargets)).filter( |
| 243 | (target) => target.environmentId === environmentId, |
| 244 | ); |
| 245 | yield* Ref.update(storedTargets, (current) => |
| 246 | current.filter((target) => target.environmentId !== environmentId), |
| 247 | ); |
| 248 | for (const target of removed) { |
| 249 | if (target._tag === "BearerConnectionTarget" || target._tag === "SshConnectionTarget") { |
| 250 | yield* Ref.update(storedProfiles, (current) => { |
| 251 | const next = new Map(current); |
| 252 | next.delete(target.connectionId); |
| 253 | return next; |
| 254 | }); |
| 255 | yield* Ref.update(storedCredentials, (current) => { |
| 256 | const next = new Map(current); |
| 257 | next.delete(target.connectionId); |
| 258 | return next; |
| 259 | }); |
| 260 | } |
| 261 | } |
| 262 | yield* Ref.update(storedRemoteTokens, (current) => { |
| 263 | const next = new Map(current); |
| 264 | next.delete(environmentId); |
| 265 | return next; |
| 266 | }); |
| 267 | }), |
| 268 | setEnabled: (environmentId, enabled) => |
| 269 | Ref.update(storedDisabled, (current) => { |
| 270 | const next = new Set(current); |
| 271 | if (enabled) { |
| 272 | next.delete(environmentId); |
| 273 | } else { |
| 274 | next.add(environmentId); |
| 275 | } |
| 276 | return next; |
| 277 | }), |
| 278 | }); |
| 279 | const cacheStore = Persistence.EnvironmentCacheStore.of({ |
| 280 | loadShell: (environmentId) => |
| 281 | Ref.get(shellCache).pipe( |
| 282 | Effect.map((cache) => Option.fromUndefinedOr(cache.get(environmentId))), |
| 283 | ), |
| 284 | saveShell: (environmentId, snapshot) => |
| 285 | Ref.update(shellCache, (current) => { |
| 286 | const next = new Map(current); |
| 287 | next.set(environmentId, snapshot); |
| 288 | return next; |
| 289 | }), |
| 290 | loadThread: (_environmentId, _threadId) => Effect.succeedNone, |
| 291 | saveThread: (_environmentId, _thread) => Effect.void, |
| 292 | removeThread: (_environmentId, _threadId) => Effect.void, |
| 293 | loadServerConfig: () => Effect.succeedNone, |
| 294 | saveServerConfig: () => Effect.void, |
| 295 | loadVcsRefs: () => Effect.succeedNone, |
| 296 | saveVcsRefs: () => Effect.void, |
| 297 | removeVcsRefs: () => Effect.void, |
| 298 | clearVcsRefs: () => Effect.void, |
| 299 | clear: (environmentId) => |
| 300 | Ref.update(shellCache, (current) => { |
| 301 | const next = new Map(current); |
| 302 | next.delete(environmentId); |
| 303 | return next; |
| 304 | }).pipe( |
| 305 | Effect.andThen( |
| 306 | Ref.update(cacheClears, (environmentIds) => [...environmentIds, environmentId]), |
| 307 | ), |
| 308 | ), |
| 309 | }); |
| 310 | const ownedDataCleanup = Persistence.EnvironmentOwnedDataCleanup.of({ |
| 311 | clear: (environmentId) => |
| 312 | Ref.update(ownedDataClears, (environmentIds) => [...environmentIds, environmentId]), |
| 313 | }); |
| 314 | const networkStatus = yield* SubscriptionRef.make<"unknown" | "offline" | "online">("online"); |
| 315 | const connectivity = Connectivity.Connectivity.of({ |
| 316 | status: SubscriptionRef.get(networkStatus), |
| 317 | changes: SubscriptionRef.changes(networkStatus), |
| 318 | }); |
| 319 | const profileStore = ConnectionProfileStore.ConnectionProfileStore.of({ |
| 320 | get: (connectionId) => |
| 321 | Ref.update(profileReadCount, (count) => count + 1).pipe( |
| 322 | Effect.andThen(Ref.get(storedProfiles)), |
| 323 | Effect.map((current) => Option.fromUndefinedOr(current.get(connectionId))), |
| 324 | ), |
| 325 | put: (profile) => |
| 326 | Ref.update(storedProfiles, (current) => { |
| 327 | const next = new Map(current); |
| 328 | next.set(profile.connectionId, profile); |
| 329 | return next; |
| 330 | }), |
| 331 | remove: (connectionId) => |
| 332 | Ref.update(storedProfiles, (current) => { |
| 333 | const next = new Map(current); |
| 334 | next.delete(connectionId); |
| 335 | return next; |
| 336 | }), |
| 337 | }); |
| 338 | const credentialStore = ConnectionCredentialStore.ConnectionCredentialStore.of({ |
| 339 | get: (connectionId) => |
| 340 | Ref.get(storedCredentials).pipe( |
| 341 | Effect.map((current) => Option.fromUndefinedOr(current.get(connectionId))), |
| 342 | ), |
| 343 | put: (connectionId, credential) => |
| 344 | (options?.beforeCredentialPut?.(connectionId) ?? Effect.void).pipe( |
| 345 | Effect.andThen( |
| 346 | Ref.update(storedCredentials, (current) => { |
| 347 | const next = new Map(current); |
| 348 | next.set(connectionId, credential); |
| 349 | return next; |
| 350 | }), |
| 351 | ), |
| 352 | ), |
| 353 | remove: (connectionId) => |
| 354 | Ref.update(storedCredentials, (current) => { |
| 355 | const next = new Map(current); |
| 356 | next.delete(connectionId); |
| 357 | return next; |
| 358 | }), |
| 359 | }); |
| 360 | const tokenStore = TokenStore.RemoteDpopAccessTokenStore.of({ |
| 361 | get: (environmentId) => |
| 362 | Ref.get(storedRemoteTokens).pipe( |
| 363 | Effect.map((current) => Option.fromUndefinedOr(current.get(environmentId))), |
| 364 | ), |
| 365 | put: (token) => |
| 366 | Ref.update(storedRemoteTokens, (current) => { |
| 367 | const next = new Map(current); |
| 368 | next.set(token.environmentId, token); |
| 369 | return next; |
| 370 | }), |
| 371 | remove: (environmentId) => |
| 372 | Ref.update(storedRemoteTokens, (current) => { |
| 373 | const next = new Map(current); |
| 374 | next.delete(environmentId); |
| 375 | return next; |
| 376 | }), |
| 377 | }); |
| 378 | const sshGateway = ClientCapabilities.SshEnvironmentGateway.of({ |
| 379 | provision: () => Effect.die(new Error("SSH provisioning is not used.")), |
| 380 | prepare: () => Effect.die(new Error("SSH preparation is not used.")), |
| 381 | disconnect: (target) => Ref.update(disconnectedSshTargets, (current) => [...current, target]), |
| 382 | }); |
| 383 | const connectedRoutes = yield* Ref.make<ReadonlyArray<string>>([]); |
| 384 | const checkRoute = (route: ConnectionRoute) => |
| 385 | Effect.succeed(options?.checkRoute?.(route) ?? "unchecked"); |
| 386 | const connectRoute = (entry: ConnectionCatalogEntry, route: ConnectionRoute) => |
| 387 | Effect.gen(function* () { |
| 388 | const target = route.target; |
| 389 | const credential = |
| 390 | target._tag === "BearerConnectionTarget" |
| 391 | ? yield* credentialStore.get(target.connectionId) |
| 392 | : Option.none(); |
| 393 | const prepared: PreparedConnection = { |
| 394 | ...PREPARED, |
| 395 | environmentId: target.environmentId, |
| 396 | label: target.label, |
| 397 | httpAuthorization: |
| 398 | Option.isSome(credential) && credential.value._tag === "BearerConnectionCredential" |
| 399 | ? { _tag: "Bearer", token: credential.value.token } |
| 400 | : null, |
| 401 | target, |
| 402 | }; |
| 403 | if (options?.prepareError) return yield* options.prepareError; |
| 404 | const heldError = options?.beforePrepareRoute |
| 405 | ? yield* options.beforePrepareRoute(target) |
| 406 | : undefined; |
| 407 | if (heldError !== undefined) return yield* heldError; |
| 408 | const routeError = options?.prepareRoute?.(target); |
| 409 | if (routeError !== undefined) return yield* routeError; |
| 410 | yield* Ref.update(connectedRoutes, (current) => [...current, connectionRouteId(target)]); |
| 411 | yield* options?.beforeSessionConnect?.(target.environmentId) ?? Effect.void; |
| 412 | const closed = yield* Deferred.make<never, ConnectionTransientError>(); |
| 413 | yield* Ref.update(sessions, (current) => [...current, { closed }]); |
| 414 | const session = yield* Effect.acquireRelease( |
| 415 | Effect.succeed({ |
| 416 | client: {} as RpcSession.RpcSession["client"], |
| 417 | initialConfig: |
| 418 | options?.directEndpoints === undefined |
| 419 | ? Effect.die(new Error("Config is not used by registry tests.")) |
| 420 | : Effect.succeed({ directEndpoints: options.directEndpoints } as ServerConfig), |
| 421 | subscribeServerConfig: () => |
| 422 | options?.directEndpoints === undefined |
| 423 | ? Stream.never |
| 424 | : Stream.make({ |
| 425 | version: 1 as const, |
| 426 | type: "snapshot" as const, |
| 427 | config: { directEndpoints: options.directEndpoints } as ServerConfig, |
| 428 | }), |
| 429 | ready: Effect.void, |
| 430 | probe: Effect.void, |
| 431 | inboundFrames: Effect.succeed(0), |
| 432 | closed: Deferred.await(closed), |
| 433 | } satisfies RpcSession.RpcSession), |
| 434 | () => Ref.update(releasedSessions, (count) => count + 1), |
| 435 | ); |
| 436 | yield* session.ready; |
| 437 | return { prepared, session }; |
| 438 | }); |
| 439 | const driver = ConnectionDriver.ConnectionDriver.of({ |
| 440 | connect: (entry, reportProgress) => |
| 441 | reportProgress({ stage: "preparing" }).pipe( |
| 442 | Effect.andThen( |
| 443 | ConnectionDriver.connectOverRoutes(entry, checkRoute, (route) => |
| 444 | connectRoute(entry, route), |
| 445 | ), |
| 446 | ), |
| 447 | ), |
| 448 | preflight: (_entry, route) => |
| 449 | checkRoute(route).pipe( |
| 450 | Effect.map((check): ConnectionDriver.RoutePreflight => |
| 451 | check === "answered" ? "ready" : check, |
| 452 | ), |
| 453 | ), |
| 454 | checkHost: () => Effect.succeed<ConnectionDriver.RouteCheck>("unchecked"), |
| 455 | }); |
| 456 | |
| 457 | const layerCache = Layer.succeed(Persistence.EnvironmentCacheStore, cacheStore); |
| 458 | const layer = EnvironmentRegistry.layer.pipe( |
| 459 | Layer.provide( |
| 460 | Layer.mergeAll( |
| 461 | Layer.succeed(Persistence.ConnectionTargetStore, targetStore), |
| 462 | Layer.succeed(Persistence.ConnectionRegistrationStore, registrationStore), |
| 463 | Layer.succeed(ConnectionProfileStore.ConnectionProfileStore, profileStore), |
| 464 | Layer.succeed(ConnectionCredentialStore.ConnectionCredentialStore, credentialStore), |
| 465 | Layer.succeed(TokenStore.RemoteDpopAccessTokenStore, tokenStore), |
| 466 | Layer.succeed(ClientCapabilities.SshEnvironmentGateway, sshGateway), |
| 467 | Layer.succeed(Connectivity.Connectivity, connectivity), |
| 468 | Layer.succeed( |
| 469 | ConnectionWakeups.ConnectionWakeups, |
| 470 | ConnectionWakeups.ConnectionWakeups.of({ changes: Stream.never }), |
| 471 | ), |
| 472 | Layer.succeed(ConnectionDriver.ConnectionDriver, driver), |
| 473 | layerCache, |
| 474 | Layer.succeed(Persistence.EnvironmentOwnedDataCleanup, ownedDataCleanup), |
| 475 | ), |
| 476 | ), |
| 477 | ); |
| 478 | |
| 479 | return { |
| 480 | layer, |
| 481 | storedTargets, |
| 482 | shellCache, |
| 483 | cacheClears, |
| 484 | ownedDataClears, |
| 485 | sessions, |
| 486 | releasedSessions, |
| 487 | storedProfiles, |
| 488 | profileReadCount, |
| 489 | storedCredentials, |
| 490 | storedRemoteTokens, |
| 491 | storedDisabled, |
| 492 | disconnectedSshTargets, |
| 493 | networkStatus, |
| 494 | connectedRoutes, |
| 495 | }; |
| 496 | }); |
| 497 | |
| 498 | function routesOf(targets: ReadonlyArray<ConnectionTarget>, environmentId: EnvironmentId) { |
| 499 | return targets.filter((target) => target.environmentId === environmentId); |
| 500 | } |
| 501 | |
| 502 | function hasRoutes(targets: ReadonlyArray<ConnectionTarget>, environmentId: EnvironmentId) { |
| 503 | return routesOf(targets, environmentId).length > 0; |
| 504 | } |
| 505 | |
| 506 | function replaceRoutes( |
| 507 | current: ReadonlyArray<ConnectionTarget>, |
| 508 | environmentId: EnvironmentId, |
| 509 | routes: ReadonlyArray<ConnectionTarget>, |
| 510 | ): ReadonlyArray<ConnectionTarget> { |
| 511 | const firstIndex = current.findIndex((target) => target.environmentId === environmentId); |
| 512 | const others = current.filter((target) => target.environmentId !== environmentId); |
| 513 | const insertAt = |
| 514 | firstIndex === -1 |
| 515 | ? others.length |
| 516 | : current.slice(0, firstIndex).filter((target) => target.environmentId !== environmentId) |
| 517 | .length; |
| 518 | return [...others.slice(0, insertAt), ...routes, ...others.slice(insertAt)]; |
| 519 | } |
| 520 | |
| 521 | function registrySpanNames<A, E, R>(effect: Effect.Effect<A, E, R>) { |
| 522 | const names: Array<string> = []; |
| 523 | const tracer = Tracer.make({ |
| 524 | span: (options) => { |
| 525 | if (options.name.startsWith("EnvironmentRegistry.")) names.push(options.name); |
| 526 | return new Tracer.NativeSpan(options); |
| 527 | }, |
| 528 | }); |
| 529 | return effect.pipe(Effect.withTracer(tracer), Effect.as(names)); |
| 530 | } |
| 531 | |
| 532 | function awaitConnectionState( |
| 533 | registry: EnvironmentRegistry.EnvironmentRegistry["Service"], |
| 534 | environmentId: EnvironmentId, |
| 535 | predicate: (state: SupervisorConnectionState) => boolean, |
| 536 | ) { |
| 537 | return Effect.gen(function* () { |
| 538 | const current = yield* registry.state(environmentId); |
| 539 | if (predicate(current)) { |
| 540 | return current; |
| 541 | } |
| 542 | return yield* registry |
| 543 | .stateChanges(environmentId) |
| 544 | .pipe(Stream.filter(predicate), Stream.runHead, Effect.map(Option.getOrThrow)); |
| 545 | }); |
| 546 | } |
| 547 | |
| 548 | describe("EnvironmentRegistry", () => { |
| 549 | it.effect("replays connected state when arming a desktop commit observer", () => |
| 550 | Effect.gen(function* () { |
| 551 | const harness = yield* makeHarness([TARGET]); |
| 552 | |
| 553 | yield* Effect.gen(function* () { |
| 554 | const registry = yield* EnvironmentRegistry.EnvironmentRegistry; |
| 555 | yield* registry.start; |
| 556 | yield* awaitConnectionState( |
| 557 | registry, |
| 558 | TARGET.environmentId, |
| 559 | (state) => state.phase === "connected", |
| 560 | ); |
| 561 | |
| 562 | const commits = yield* Ref.make(0); |
| 563 | const result = yield* runDesktopCommitWithReconnectObserver( |
| 564 | registry.stateChanges(TARGET.environmentId), |
| 565 | Ref.update(commits, (count) => count + 1).pipe( |
| 566 | Effect.andThen(Effect.fail("commit refused")), |
| 567 | ), |
| 568 | ).pipe(Effect.flip, Effect.timeout("1 second")); |
| 569 | |
| 570 | expect(result).toBe("commit refused"); |
| 571 | expect(yield* Ref.get(commits)).toBe(1); |
| 572 | }).pipe(Effect.provide(harness.layer), Effect.scoped); |
| 573 | }), |
| 574 | ); |
| 575 | |
| 576 | it.effect("does not acquire a session after the registry scope has already closed", () => |
| 577 | Effect.gen(function* () { |
| 578 | const harness = yield* makeHarness([TARGET]); |
| 579 | const registryScope = yield* Scope.make(); |
| 580 | const context = yield* Layer.build(harness.layer).pipe(Scope.provide(registryScope)); |
| 581 | const registry = Context.get(context, EnvironmentRegistry.EnvironmentRegistry); |
| 582 | const dispatcher = new Scheduler.MixedScheduler("sync", () => () => {}).makeDispatcher(); |
| 583 | const scheduler: Scheduler.Scheduler = { |
| 584 | executionMode: "sync", |
| 585 | shouldYield: () => false, |
| 586 | makeDispatcher: () => dispatcher, |
| 587 | }; |
| 588 | |
| 589 | yield* Scope.close(registryScope, Exit.void); |
| 590 | yield* registry.start.pipe(Effect.provideService(Scheduler.Scheduler, scheduler)); |
| 591 | dispatcher.flush(); |
| 592 | |
| 593 | expect(yield* Ref.get(harness.sessions)).toHaveLength(0); |
| 594 | expect(yield* Ref.get(harness.releasedSessions)).toBe(0); |
| 595 | }), |
| 596 | ); |
| 597 | |
| 598 | it.effect("starts persisted environments independently", () => |
| 599 | Effect.gen(function* () { |
| 600 | const bothLoadsStarted = yield* Deferred.make<void>(); |
| 601 | const releaseLoads = yield* Deferred.make<void>(); |
| 602 | const loadCount = yield* Ref.make(0); |
| 603 | const harness = yield* makeHarness([TARGET, SECOND_TARGET], [], [], { |
| 604 | beforeSessionConnect: () => |
| 605 | Ref.updateAndGet(loadCount, (count) => count + 1).pipe( |
| 606 | Effect.tap((count) => |
| 607 | count === 2 ? Deferred.succeed(bothLoadsStarted, undefined) : Effect.void, |
| 608 | ), |
| 609 | Effect.andThen(Deferred.await(releaseLoads)), |
| 610 | ), |
| 611 | }); |
| 612 | |
| 613 | yield* Effect.gen(function* () { |
| 614 | const registry = yield* EnvironmentRegistry.EnvironmentRegistry; |
| 615 | const start = yield* Effect.forkChild(registry.start); |
| 616 | |
| 617 | yield* Deferred.await(bothLoadsStarted).pipe(Effect.timeout("1 second")); |
| 618 | yield* Deferred.succeed(releaseLoads, undefined); |
| 619 | yield* Fiber.join(start); |
| 620 | |
| 621 | expect(yield* Ref.get(loadCount)).toBe(2); |
| 622 | }).pipe(Effect.provide(harness.layer), Effect.scoped); |
| 623 | }), |
| 624 | ); |
| 625 | |
| 626 | it.effect("does not expose a persisted environment as disconnected while it starts", () => |
| 627 | Effect.gen(function* () { |
| 628 | const connectionStarted = yield* Deferred.make<void>(); |
| 629 | const finishConnection = yield* Deferred.make<void>(); |
| 630 | const harness = yield* makeHarness([TARGET], [], [], { |
| 631 | beforeSessionConnect: () => |
| 632 | Deferred.succeed(connectionStarted, undefined).pipe( |
| 633 | Effect.andThen(Deferred.await(finishConnection)), |
| 634 | ), |
| 635 | }); |
| 636 | |
| 637 | yield* Effect.gen(function* () { |
| 638 | const registry = yield* EnvironmentRegistry.EnvironmentRegistry; |
| 639 | expect((yield* registry.state(TARGET.environmentId)).phase).toBe("connecting"); |
| 640 | |
| 641 | yield* Deferred.await(connectionStarted); |
| 642 | expect((yield* registry.state(TARGET.environmentId)).phase).toBe("connecting"); |
| 643 | yield* Deferred.succeed(finishConnection, undefined); |
| 644 | }).pipe(Effect.provide(harness.layer), Effect.scoped); |
| 645 | }), |
| 646 | ); |
| 647 | |
| 648 | it.effect("preserves cached data on connection failure and clears it on explicit removal", () => |
| 649 | Effect.gen(function* () { |
| 650 | const harness = yield* makeHarness([TARGET]); |
| 651 | yield* Effect.gen(function* () { |
| 652 | const registry = yield* EnvironmentRegistry.EnvironmentRegistry; |
| 653 | yield* registry.start; |
| 654 | yield* awaitConnectionState( |
| 655 | registry, |
| 656 | TARGET.environmentId, |
| 657 | (state) => state.phase === "connected", |
| 658 | ); |
| 659 | const controls = yield* Ref.get(harness.sessions); |
| 660 | expect(controls).toHaveLength(1); |
| 661 | const active = controls[0]; |
| 662 | expect(active).toBeDefined(); |
| 663 | expect((yield* Ref.get(harness.shellCache)).get(TARGET.environmentId)).toEqual( |
| 664 | CACHED_SNAPSHOT, |
| 665 | ); |
| 666 | |
| 667 | const retryFiber = yield* Effect.forkChild( |
| 668 | awaitConnectionState( |
| 669 | registry, |
| 670 | TARGET.environmentId, |
| 671 | (state) => state.phase === "backoff", |
| 672 | ), |
| 673 | ); |
| 674 | yield* Effect.yieldNow; |
| 675 | yield* Deferred.fail( |
| 676 | active!.closed, |
| 677 | new ConnectionTransientError({ |
| 678 | reason: "transport", |
| 679 | detail: "Disconnected.", |
| 680 | }), |
| 681 | ); |
| 682 | yield* Fiber.join(retryFiber); |
| 683 | expect((yield* Ref.get(harness.shellCache)).get(TARGET.environmentId)).toEqual( |
| 684 | CACHED_SNAPSHOT, |
| 685 | ); |
| 686 | |
| 687 | yield* registry.remove(TARGET.environmentId); |
| 688 | expect(hasRoutes(yield* Ref.get(harness.storedTargets), TARGET.environmentId)).toBe(false); |
| 689 | expect((yield* Ref.get(harness.shellCache)).has(TARGET.environmentId)).toBe(false); |
| 690 | expect(yield* Ref.get(harness.cacheClears)).toEqual([TARGET.environmentId]); |
| 691 | expect((yield* SubscriptionRef.get(registry.entries)).has(TARGET.environmentId)).toBe( |
| 692 | false, |
| 693 | ); |
| 694 | }).pipe(Effect.provide(harness.layer)); |
| 695 | }), |
| 696 | ); |
| 697 | |
| 698 | it.effect("only a fresh health check for the rejected environment unlocks it", () => |
| 699 | Effect.gen(function* () { |
| 700 | const harness = yield* makeHarness([RELAY_TARGET, SECOND_RELAY_TARGET], [], [], { |
| 701 | initialDisabled: [RELAY_TARGET.environmentId], |
| 702 | }); |
| 703 | const descriptor = (environmentId: EnvironmentId): ExecutionEnvironmentDescriptor => ({ |
| 704 | environmentId, |
| 705 | label: "Server", |
| 706 | platform: { os: "linux", arch: "x64" }, |
| 707 | serverVersion: "1.0.0", |
| 708 | orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION, |
| 709 | capabilities: { repositoryIdentity: true }, |
| 710 | }); |
| 711 | const discovered = ( |
| 712 | value: ExecutionEnvironmentDescriptor, |
| 713 | checkedAt = "2026-09-15T00:00:00Z", |
| 714 | ) => { |
| 715 | const environment = { |
| 716 | environmentId: value.environmentId, |
| 717 | label: value.label, |
| 718 | endpoint: { |
| 719 | httpBaseUrl: "https://relay.example.test", |
| 720 | wsBaseUrl: "wss://relay.example.test", |
| 721 | providerKind: "manual" as const, |
| 722 | }, |
| 723 | linkedAt: "2026-09-15T00:00:00Z", |
| 724 | }; |
| 725 | const status: RelayEnvironmentStatusResponse = { |
| 726 | environmentId: value.environmentId, |
| 727 | endpoint: environment.endpoint, |
| 728 | status: "online", |
| 729 | checkedAt, |
| 730 | descriptor: value, |
| 731 | }; |
| 732 | return { |
| 733 | environment, |
| 734 | availability: "online" as const, |
| 735 | status: Option.some(status), |
| 736 | error: Option.none(), |
| 737 | }; |
| 738 | }; |
| 739 | const original = discovered(descriptor(RELAY_TARGET.environmentId)); |
| 740 | const discoveryState = |
| 741 | yield* SubscriptionRef.make<RelayEnvironmentDiscovery.RelayEnvironmentDiscoveryState>({ |
| 742 | ...RelayEnvironmentDiscovery.EMPTY_RELAY_ENVIRONMENT_DISCOVERY_STATE, |
| 743 | environments: new Map([[RELAY_TARGET.environmentId, original]]), |
| 744 | }); |
| 745 | const initial = yield* Deferred.make<void>(); |
| 746 | const unrelated = yield* Deferred.make<void>(); |
| 747 | const replayed = yield* Deferred.make<void>(); |
| 748 | const refreshed = yield* Deferred.make<void>(); |
| 749 | let firstEnvironmentCalls = 0; |
| 750 | let secondEnvironmentCalls = 0; |
| 751 | yield* Effect.gen(function* () { |
| 752 | const registry = yield* EnvironmentRegistry.EnvironmentRegistry; |
| 753 | yield* watchDiscoveredCompatibility().pipe( |
| 754 | Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, { |
| 755 | ...registry, |
| 756 | setCompatibility: (environmentId, error) => |
| 757 | registry.setCompatibility(environmentId, error).pipe( |
| 758 | Effect.andThen( |
| 759 | Effect.gen(function* () { |
| 760 | if (environmentId === RELAY_TARGET.environmentId) { |
| 761 | firstEnvironmentCalls += 1; |
| 762 | yield* Deferred.succeed( |
| 763 | firstEnvironmentCalls === 1 ? initial : refreshed, |
| 764 | undefined, |
| 765 | ); |
| 766 | } else { |
| 767 | secondEnvironmentCalls += 1; |
| 768 | yield* Deferred.succeed( |
| 769 | secondEnvironmentCalls === 1 ? unrelated : replayed, |
| 770 | undefined, |
| 771 | ); |
| 772 | } |
| 773 | }), |
| 774 | ), |
| 775 | ), |
| 776 | }), |
| 777 | Effect.provideService( |
| 778 | RelayEnvironmentDiscovery.RelayEnvironmentDiscovery, |
| 779 | RelayEnvironmentDiscovery.RelayEnvironmentDiscovery.of({ |
| 780 | state: discoveryState, |
| 781 | refresh: Effect.void, |
| 782 | }), |
| 783 | ), |
| 784 | Effect.forkScoped, |
| 785 | ); |
| 786 | yield* Deferred.await(initial); |
| 787 | const error = new ConnectionBlockedError({ |
| 788 | reason: "unsupported", |
| 789 | detail: "Socket discovered a newer protocol.", |
| 790 | }); |
| 791 | yield* registry.setCompatibility(RELAY_TARGET.environmentId, error); |
| 792 | yield* SubscriptionRef.update(discoveryState, (state) => ({ |
| 793 | ...state, |
| 794 | environments: new Map(state.environments).set( |
| 795 | SECOND_RELAY_TARGET.environmentId, |
| 796 | discovered(descriptor(SECOND_RELAY_TARGET.environmentId)), |
| 797 | ), |
| 798 | })); |
| 799 | yield* Deferred.await(unrelated); |
| 800 | expect( |
| 801 | (yield* SubscriptionRef.get(registry.entries)).get(RELAY_TARGET.environmentId) |
| 802 | ?.unsupportedReason, |
| 803 | ).toBe(error.message); |
| 804 | yield* SubscriptionRef.update(discoveryState, (state) => ({ |
| 805 | ...state, |
| 806 | refreshing: true, |
| 807 | environments: new Map(), |
| 808 | })); |
| 809 | yield* SubscriptionRef.update(discoveryState, (state) => ({ |
| 810 | ...state, |
| 811 | refreshing: false, |
| 812 | environments: new Map([ |
| 813 | [RELAY_TARGET.environmentId, discovered(descriptor(RELAY_TARGET.environmentId))], |
| 814 | [ |
| 815 | SECOND_RELAY_TARGET.environmentId, |
| 816 | discovered(descriptor(SECOND_RELAY_TARGET.environmentId), "2026-09-15T00:01:00Z"), |
| 817 | ], |
| 818 | ]), |
| 819 | })); |
| 820 | yield* Deferred.await(replayed); |
| 821 | expect( |
| 822 | (yield* SubscriptionRef.get(registry.entries)).get(RELAY_TARGET.environmentId) |
| 823 | ?.unsupportedReason, |
| 824 | ).toBe(error.message); |
| 825 | yield* SubscriptionRef.update(discoveryState, (state) => ({ |
| 826 | ...state, |
| 827 | environments: new Map(state.environments).set( |
| 828 | RELAY_TARGET.environmentId, |
| 829 | discovered(descriptor(RELAY_TARGET.environmentId), "2026-09-15T00:02:00Z"), |
| 830 | ), |
| 831 | })); |
| 832 | yield* Deferred.await(refreshed); |
| 833 | expect( |
| 834 | (yield* SubscriptionRef.get(registry.entries)).get(RELAY_TARGET.environmentId), |
| 835 | ).toMatchObject({ enabled: false }); |
| 836 | expect( |
| 837 | (yield* SubscriptionRef.get(registry.entries)).get(RELAY_TARGET.environmentId) |
| 838 | ?.unsupportedReason, |
| 839 | ).toBeUndefined(); |
| 840 | }).pipe(Effect.provide(harness.layer), Effect.scoped); |
| 841 | }), |
| 842 | ); |
| 843 | |
| 844 | it.effect("discovery leaves direct connections that share an environment id alone", () => |
| 845 | Effect.gen(function* () { |
| 846 | const harness = yield* makeHarness([TARGET, RELAY_TARGET]); |
| 847 | const discovered = (environmentId: EnvironmentId) => { |
| 848 | const endpoint = { |
| 849 | httpBaseUrl: "https://relay.example.test", |
| 850 | wsBaseUrl: "wss://relay.example.test", |
| 851 | providerKind: "manual" as const, |
| 852 | }; |
| 853 | return { |
| 854 | environment: { |
| 855 | environmentId, |
| 856 | label: "Preview server", |
| 857 | endpoint, |
| 858 | linkedAt: "2026-09-25T00:00:00Z", |
| 859 | }, |
| 860 | availability: "online" as const, |
| 861 | status: Option.some<RelayEnvironmentStatusResponse>({ |
| 862 | environmentId, |
| 863 | endpoint, |
| 864 | status: "online", |
| 865 | checkedAt: "2026-09-25T00:00:00Z", |
| 866 | descriptor: { |
| 867 | environmentId, |
| 868 | label: "Preview server", |
| 869 | platform: { os: "darwin", arch: "arm64" }, |
| 870 | serverVersion: "2.0.0", |
| 871 | orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION + 1, |
| 872 | capabilities: { repositoryIdentity: true }, |
| 873 | }, |
| 874 | }), |
| 875 | error: Option.none(), |
| 876 | }; |
| 877 | }; |
| 878 | yield* Effect.gen(function* () { |
| 879 | const registry = yield* EnvironmentRegistry.EnvironmentRegistry; |
| 880 | yield* registry.start; |
| 881 | yield* awaitConnectionState( |
| 882 | registry, |
| 883 | TARGET.environmentId, |
| 884 | (state) => state.phase === "connected", |
| 885 | ); |
| 886 | const relayChecked = yield* Deferred.make<void>(); |
| 887 | yield* watchDiscoveredCompatibility().pipe( |
| 888 | Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, { |
| 889 | ...registry, |
| 890 | setCompatibility: (environmentId, error) => |
| 891 | registry |
| 892 | .setCompatibility(environmentId, error) |
| 893 | .pipe( |
| 894 | Effect.andThen( |
| 895 | environmentId === RELAY_TARGET.environmentId |
| 896 | ? Deferred.succeed(relayChecked, undefined) |
| 897 | : Effect.void, |
| 898 | ), |
| 899 | ), |
| 900 | }), |
| 901 | Effect.provideService( |
| 902 | RelayEnvironmentDiscovery.RelayEnvironmentDiscovery, |
| 903 | RelayEnvironmentDiscovery.RelayEnvironmentDiscovery.of({ |
| 904 | state: |
| 905 | yield* SubscriptionRef.make<RelayEnvironmentDiscovery.RelayEnvironmentDiscoveryState>( |
| 906 | { |
| 907 | ...RelayEnvironmentDiscovery.EMPTY_RELAY_ENVIRONMENT_DISCOVERY_STATE, |
| 908 | environments: new Map([ |
| 909 | [TARGET.environmentId, discovered(TARGET.environmentId)], |
| 910 | [RELAY_TARGET.environmentId, discovered(RELAY_TARGET.environmentId)], |
| 911 | ]), |
| 912 | }, |
| 913 | ), |
| 914 | refresh: Effect.void, |
| 915 | }), |
| 916 | ), |
| 917 | Effect.forkScoped, |
| 918 | ); |
| 919 | yield* Deferred.await(relayChecked); |
| 920 | |
| 921 | const entries = yield* SubscriptionRef.get(registry.entries); |
| 922 | expect(entries.get(RELAY_TARGET.environmentId)?.unsupportedReason).toBeDefined(); |
| 923 | expect(entries.get(TARGET.environmentId)).toMatchObject({ enabled: true }); |
| 924 | expect(entries.get(TARGET.environmentId)?.unsupportedReason).toBeUndefined(); |
| 925 | expect((yield* registry.state(TARGET.environmentId)).phase).toBe("connected"); |
| 926 | }).pipe(Effect.provide(harness.layer), Effect.scoped); |
| 927 | }), |
| 928 | ); |
| 929 | |
| 930 | it.effect.each([false, true])( |
| 931 | "a switched-off environment stays off after compatibility clears (learned route: %s)", |
| 932 | (learned) => |
| 933 | Effect.gen(function* () { |
| 934 | const environmentId = BEARER_TARGET.environmentId; |
| 935 | const relay = new RelayConnectionTarget({ ...RELAY_TARGET, environmentId }); |
| 936 | const profile = new BearerConnectionProfile({ |
| 937 | ...BEARER_PROFILE, |
| 938 | learned: true, |
| 939 | authorization: "t3-connect", |
| 940 | }); |
| 941 | const harness = yield* makeHarness( |
| 942 | learned ? [relay, BEARER_TARGET] : [relay], |
| 943 | learned ? [profile] : [], |
| 944 | [], |
| 945 | { initialDisabled: [environmentId] }, |
| 946 | ); |
| 947 | yield* Effect.gen(function* () { |
| 948 | const registry = yield* EnvironmentRegistry.EnvironmentRegistry; |
| 949 | yield* registry.start; |
| 950 | const error = new ConnectionBlockedError({ |
| 951 | reason: "unsupported", |
| 952 | detail: "Use a compatible client.", |
| 953 | }); |
| 954 | yield* registry.setCompatibility(environmentId, error); |
| 955 | const entry = (yield* SubscriptionRef.get(registry.entries)).get(environmentId); |
| 956 | expect(entry).toMatchObject({ enabled: false, unsupportedReason: error.message }); |
| 957 | expect(yield* Effect.flip(registry.setEnabled(environmentId, true))).toMatchObject({ |
| 958 | reason: "unsupported", |
| 959 | }); |
| 960 | expect(yield* Ref.get(harness.sessions)).toHaveLength(0); |
| 961 | yield* registry.setCompatibility(environmentId, null); |
| 962 | expect((yield* SubscriptionRef.get(registry.entries)).get(environmentId)?.enabled).toBe( |
| 963 | false, |
| 964 | ); |
| 965 | expect(yield* registry.state(environmentId)).toMatchObject({ desired: false }); |
| 966 | expect(yield* Ref.get(harness.storedDisabled)).toEqual(new Set([environmentId])); |
| 967 | expect(yield* Ref.get(harness.sessions)).toHaveLength(0); |
| 968 | yield* registry.setEnabled(environmentId, true); |
| 969 | yield* awaitConnectionState( |
| 970 | registry, |
| 971 | environmentId, |
| 972 | (state) => state.phase === "connected", |
| 973 | ); |
| 974 | }).pipe(Effect.provide(harness.layer)); |
| 975 | }), |
| 976 | ); |
| 977 | |
| 978 | it.effect("protocol rejection preserves enablement through recovery and relaunch", () => |
| 979 | Effect.gen(function* () { |
| 980 | const error = new ConnectionBlockedError({ |
| 981 | reason: "unsupported", |
| 982 | detail: "Use a compatible client.", |
| 983 | }); |
| 984 | const rejection = yield* Ref.make<ConnectionBlockedError | undefined>(error); |
| 985 | const harness = yield* makeHarness([RELAY_TARGET], [], [], { |
| 986 | beforePrepareRoute: () => Ref.get(rejection), |
| 987 | }); |
| 988 | yield* Effect.gen(function* () { |
| 989 | const registry = yield* EnvironmentRegistry.EnvironmentRegistry; |
| 990 | yield* registry.start; |
| 991 | yield* SubscriptionRef.changes(registry.entries).pipe( |
| 992 | Stream.filter( |
| 993 | (entries) => entries.get(RELAY_TARGET.environmentId)?.unsupportedReason !== undefined, |
| 994 | ), |
| 995 | Stream.take(1), |
| 996 | Stream.runDrain, |
| 997 | ); |
| 998 | expect(yield* Ref.get(harness.storedDisabled)).toEqual(new Set()); |
| 999 | expect( |
| 1000 | (yield* SubscriptionRef.get(registry.entries)).get(RELAY_TARGET.environmentId), |
| 1001 | ).toMatchObject({ enabled: true, unsupportedReason: error.message }); |
| 1002 | yield* awaitConnectionState( |
| 1003 | registry, |
| 1004 | RELAY_TARGET.environmentId, |
| 1005 | (state) => !state.desired && state.phase === "available", |
| 1006 | ); |
| 1007 | expect(yield* Ref.get(harness.sessions)).toHaveLength(0); |
| 1008 | |
| 1009 | yield* Ref.set(rejection, undefined); |
| 1010 | yield* registry.setCompatibility(RELAY_TARGET.environmentId, null); |
| 1011 | yield* awaitConnectionState( |
| 1012 | registry, |
| 1013 | RELAY_TARGET.environmentId, |
| 1014 | (state) => state.phase === "connected", |
| 1015 | ); |
| 1016 | expect(yield* Ref.get(harness.sessions)).toHaveLength(1); |
| 1017 | yield* registry.setCompatibility(RELAY_TARGET.environmentId, error); |
| 1018 | yield* awaitConnectionState( |
| 1019 | registry, |
| 1020 | RELAY_TARGET.environmentId, |
| 1021 | (state) => !state.desired && state.phase === "available", |
| 1022 | ); |
| 1023 | expect(yield* Ref.get(harness.releasedSessions)).toBe(1); |
| 1024 | }).pipe(Effect.provide(harness.layer), Effect.scoped); |
| 1025 | |
| 1026 | yield* Effect.gen(function* () { |
| 1027 | const registry = yield* EnvironmentRegistry.EnvironmentRegistry; |
| 1028 | const entry = (yield* SubscriptionRef.get(registry.entries)).get( |
| 1029 | RELAY_TARGET.environmentId, |
| 1030 | ); |
| 1031 | expect(entry?.enabled).toBe(true); |
| 1032 | expect(entry?.unsupportedReason).toBeUndefined(); |
| 1033 | yield* registry.start; |
| 1034 | yield* awaitConnectionState( |
| 1035 | registry, |
| 1036 | RELAY_TARGET.environmentId, |
| 1037 | (state) => state.phase === "connected", |
| 1038 | ); |
| 1039 | }).pipe(Effect.provide(harness.layer), Effect.scoped); |
| 1040 | }), |
| 1041 | ); |
| 1042 | |
| 1043 | it.effect.each([ |
| 1044 | { outcome: "connects after a server update", compatible: true, relayFirst: false }, |
| 1045 | { outcome: "connects with a preferred relay route", compatible: true, relayFirst: true }, |
| 1046 | { outcome: "blocks again if still incompatible", compatible: false, relayFirst: false }, |
| 1047 | ])("retrying an unsupported saved URL $outcome", ({ compatible, relayFirst }) => |
| 1048 | Effect.gen(function* () { |
| 1049 | const environmentId = BEARER_TARGET.environmentId; |
| 1050 | const error = new ConnectionBlockedError({ |
| 1051 | reason: "unsupported", |
| 1052 | detail: "Update the server to use this client.", |
| 1053 | serverUpdateRequired: true, |
| 1054 | }); |
| 1055 | const relay = new RelayConnectionTarget({ |
| 1056 | environmentId, |
| 1057 | label: "Relay route", |
| 1058 | }); |
| 1059 | const attempts = yield* Ref.make(0); |
| 1060 | const retryStarted = yield* Deferred.make<void>(); |
| 1061 | const retryResult = yield* Deferred.make<ConnectionBlockedError | undefined>(); |
| 1062 | const harness = yield* makeHarness( |
| 1063 | relayFirst ? [relay, BEARER_TARGET] : [BEARER_TARGET], |
| 1064 | [BEARER_PROFILE], |
| 1065 | [[BEARER_TARGET.connectionId, BEARER_CREDENTIAL]], |
| 1066 | { |
| 1067 | beforePrepareRoute: () => |
| 1068 | Effect.gen(function* () { |
| 1069 | if ((yield* Ref.updateAndGet(attempts, (count) => count + 1)) === 1) return error; |
| 1070 | yield* Deferred.succeed(retryStarted, undefined); |
| 1071 | return yield* Deferred.await(retryResult); |
| 1072 | }), |
| 1073 | }, |
| 1074 | ); |
| 1075 | yield* Effect.gen(function* () { |
| 1076 | const registry = yield* EnvironmentRegistry.EnvironmentRegistry; |
| 1077 | yield* registry.start; |
| 1078 | const awaitUnsupported = SubscriptionRef.changes(registry.entries).pipe( |
| 1079 | Stream.filter((entries) => entries.get(environmentId)?.unsupportedReason !== undefined), |
| 1080 | Stream.take(1), |
| 1081 | Stream.runDrain, |
| 1082 | ); |
| 1083 | yield* awaitUnsupported; |
| 1084 | expect((yield* Ref.get(harness.storedDisabled)).has(environmentId)).toBe(false); |
| 1085 | expect((yield* SubscriptionRef.get(registry.entries)).get(environmentId)).toMatchObject({ |
| 1086 | target: relayFirst ? relay : BEARER_TARGET, |
| 1087 | enabled: true, |
| 1088 | unsupportedReason: error.message, |
| 1089 | serverUpdateRequired: true, |
| 1090 | }); |
| 1091 | expect(yield* Ref.get(attempts)).toBe(1); |
| 1092 | |
| 1093 | yield* registry.setEnabled(environmentId, true); |
| 1094 | yield* Deferred.await(retryStarted); |
| 1095 | const retrying = (yield* SubscriptionRef.get(registry.entries)).get(environmentId); |
| 1096 | expect(retrying?.enabled).toBe(true); |
| 1097 | expect(retrying?.unsupportedReason).toBeUndefined(); |
| 1098 | expect(retrying?.serverUpdateRequired).toBeUndefined(); |
| 1099 | expect((yield* Ref.get(harness.storedDisabled)).has(environmentId)).toBe(false); |
| 1100 | |
| 1101 | yield* Deferred.succeed(retryResult, compatible ? undefined : error); |
| 1102 | if (compatible) { |
| 1103 | yield* awaitConnectionState( |
| 1104 | registry, |
| 1105 | environmentId, |
| 1106 | (state) => state.phase === "connected", |
| 1107 | ); |
| 1108 | expect(yield* Ref.get(harness.sessions)).toHaveLength(1); |
| 1109 | } else { |
| 1110 | yield* awaitUnsupported; |
| 1111 | expect((yield* SubscriptionRef.get(registry.entries)).get(environmentId)).toMatchObject({ |
| 1112 | enabled: true, |
| 1113 | unsupportedReason: error.message, |
| 1114 | serverUpdateRequired: true, |
| 1115 | }); |
| 1116 | expect((yield* Ref.get(harness.storedDisabled)).has(environmentId)).toBe(false); |
| 1117 | expect(yield* Ref.get(harness.sessions)).toHaveLength(0); |
| 1118 | } |
| 1119 | expect(yield* Ref.get(attempts)).toBe(2); |
| 1120 | }).pipe(Effect.provide(harness.layer)); |
| 1121 | }), |
| 1122 | ); |
| 1123 | |
| 1124 | it.effect("switching an environment off disconnects it and persists the flag", () => |
| 1125 | Effect.gen(function* () { |
| 1126 | const harness = yield* makeHarness([RELAY_TARGET]); |
| 1127 | |
| 1128 | yield* Effect.gen(function* () { |
| 1129 | const registry = yield* EnvironmentRegistry.EnvironmentRegistry; |
| 1130 | yield* registry.start; |
| 1131 | yield* awaitConnectionState( |
| 1132 | registry, |
| 1133 | RELAY_TARGET.environmentId, |
| 1134 | (state) => state.phase === "connected", |
| 1135 | ); |
| 1136 | |
| 1137 | yield* registry.setEnabled(RELAY_TARGET.environmentId, false); |
| 1138 | yield* awaitConnectionState( |
| 1139 | registry, |
| 1140 | RELAY_TARGET.environmentId, |
| 1141 | (state) => state.phase === "available", |
| 1142 | ); |
| 1143 | |
| 1144 | const entry = (yield* SubscriptionRef.get(registry.entries)).get( |
| 1145 | RELAY_TARGET.environmentId, |
| 1146 | ); |
| 1147 | expect(entry?.enabled).toBe(false); |
| 1148 | expect((yield* Ref.get(harness.storedDisabled)).has(RELAY_TARGET.environmentId)).toBe(true); |
| 1149 | expect(hasRoutes(yield* Ref.get(harness.storedTargets), RELAY_TARGET.environmentId)).toBe( |
| 1150 | true, |
| 1151 | ); |
| 1152 | expect(yield* Ref.get(harness.releasedSessions)).toBe(1); |
| 1153 | |
| 1154 | yield* registry.setEnabled(RELAY_TARGET.environmentId, true); |
| 1155 | yield* awaitConnectionState( |
| 1156 | registry, |
| 1157 | RELAY_TARGET.environmentId, |
| 1158 | (state) => state.phase === "connected", |
| 1159 | ); |
| 1160 | expect((yield* Ref.get(harness.storedDisabled)).has(RELAY_TARGET.environmentId)).toBe( |
| 1161 | false, |
| 1162 | ); |
| 1163 | }).pipe(Effect.provide(harness.layer)); |
| 1164 | }), |
| 1165 | ); |
| 1166 | |
| 1167 | it.effect("re-registering a switched-off environment keeps it off", () => |
| 1168 | Effect.gen(function* () { |
| 1169 | const harness = yield* makeHarness([RELAY_TARGET], [], [], { |
| 1170 | initialDisabled: [RELAY_TARGET.environmentId], |
| 1171 | }); |
| 1172 | |
| 1173 | yield* Effect.gen(function* () { |
| 1174 | const registry = yield* EnvironmentRegistry.EnvironmentRegistry; |
| 1175 | yield* registry.start; |
| 1176 | yield* registry.register( |
| 1177 | new RelayConnectionRegistration({ |
| 1178 | target: new RelayConnectionTarget({ ...RELAY_TARGET, label: "Renamed" }), |
| 1179 | }), |
| 1180 | ); |
| 1181 | yield* Effect.yieldNow; |
| 1182 | |
| 1183 | const entry = (yield* SubscriptionRef.get(registry.entries)).get( |
| 1184 | RELAY_TARGET.environmentId, |
| 1185 | ); |
| 1186 | expect(entry?.target.label).toBe("Renamed"); |
| 1187 | expect(entry?.enabled).toBe(false); |
| 1188 | expect(yield* Ref.get(harness.sessions)).toHaveLength(0); |
| 1189 | }).pipe(Effect.provide(harness.layer)); |
| 1190 | }), |
| 1191 | ); |
| 1192 | |
| 1193 | it.effect("switching an SSH environment off tears down its managed backend", () => |
| 1194 | Effect.gen(function* () { |
| 1195 | const harness = yield* makeHarness([SSH_CONNECTION], [SSH_PROFILE]); |
| 1196 | |
| 1197 | yield* Effect.gen(function* () { |
| 1198 | const registry = yield* EnvironmentRegistry.EnvironmentRegistry; |
| 1199 | yield* registry.start; |
| 1200 | yield* awaitConnectionState( |
| 1201 | registry, |
| 1202 | SSH_CONNECTION.environmentId, |
| 1203 | (state) => state.phase === "connected", |
| 1204 | ); |
| 1205 | |
| 1206 | yield* registry.setEnabled(SSH_CONNECTION.environmentId, false); |
| 1207 | yield* awaitConnectionState( |
| 1208 | registry, |
| 1209 | SSH_CONNECTION.environmentId, |
| 1210 | (state) => state.phase === "available", |
| 1211 | ); |
| 1212 | |
| 1213 | expect(yield* Ref.get(harness.disconnectedSshTargets)).toEqual([SSH_TARGET]); |
| 1214 | expect(hasRoutes(yield* Ref.get(harness.storedTargets), SSH_CONNECTION.environmentId)).toBe( |
| 1215 | true, |
| 1216 | ); |
| 1217 | }).pipe(Effect.provide(harness.layer)); |
| 1218 | }), |
| 1219 | ); |
| 1220 | |
| 1221 | it.effect("moves durable streams to a replacement supervisor", () => |
| 1222 | Effect.gen(function* () { |
| 1223 | const replacement = new RelayConnectionTarget({ |
| 1224 | environmentId: RELAY_TARGET.environmentId, |
| 1225 | label: "Replacement relay environment", |
| 1226 | }); |
| 1227 | const harness = yield* makeHarness([RELAY_TARGET]); |
| 1228 | |
| 1229 | yield* Effect.gen(function* () { |
| 1230 | const registry = yield* EnvironmentRegistry.EnvironmentRegistry; |
| 1231 | const firstObserved = yield* Deferred.make<void>(); |
| 1232 | const secondObserved = yield* Deferred.make<void>(); |
| 1233 | const labels = yield* Ref.make<ReadonlyArray<string>>([]); |
| 1234 | yield* registry.start; |
| 1235 | yield* awaitConnectionState( |
| 1236 | registry, |
| 1237 | RELAY_TARGET.environmentId, |
| 1238 | (state) => state.phase === "connected", |
| 1239 | ); |
| 1240 | |
| 1241 | const subscription = yield* Effect.forkChild( |
| 1242 | registry |
| 1243 | .followStream( |
| 1244 | RELAY_TARGET.environmentId, |
| 1245 | Stream.unwrap( |
| 1246 | EnvironmentSupervisor.EnvironmentSupervisor.pipe( |
| 1247 | Effect.map((supervisor) => |
| 1248 | Stream.concat(Stream.succeed(supervisor.target.label), Stream.never), |
| 1249 | ), |
| 1250 | ), |
| 1251 | ), |
| 1252 | ) |
| 1253 | .pipe( |
| 1254 | Stream.tap((label) => |
| 1255 | Ref.updateAndGet(labels, (current) => [...current, label]).pipe( |
| 1256 | Effect.flatMap((current) => |
| 1257 | current.length === 1 |
| 1258 | ? Deferred.succeed(firstObserved, undefined) |
| 1259 | : Deferred.succeed(secondObserved, undefined), |
| 1260 | ), |
| 1261 | ), |
| 1262 | ), |
| 1263 | Stream.runDrain, |
| 1264 | ), |
| 1265 | ); |
| 1266 | |
| 1267 | yield* Deferred.await(firstObserved).pipe(Effect.timeout("1 second")); |
| 1268 | yield* registry.register(new RelayConnectionRegistration({ target: replacement })); |
| 1269 | yield* Deferred.await(secondObserved).pipe(Effect.timeout("1 second")); |
| 1270 | yield* Fiber.interrupt(subscription); |
| 1271 | |
| 1272 | expect(yield* Ref.get(labels)).toEqual([RELAY_TARGET.label, replacement.label]); |
| 1273 | }).pipe(Effect.provide(harness.layer), Effect.scoped); |
| 1274 | }), |
| 1275 | ); |
| 1276 | |
| 1277 | it.effect("moves prepared credential observers when re-pairing an unchanged environment", () => |
| 1278 | Effect.gen(function* () { |
| 1279 | const replacementCredential = new BearerConnectionCredential({ token: "replacement-token" }); |
| 1280 | const harness = yield* makeHarness( |
| 1281 | [BEARER_TARGET], |
| 1282 | [BEARER_PROFILE], |
| 1283 | [[BEARER_TARGET.connectionId, BEARER_CREDENTIAL]], |
| 1284 | ); |
| 1285 | |
| 1286 | yield* Effect.gen(function* () { |
| 1287 | const registry = yield* EnvironmentRegistry.EnvironmentRegistry; |
| 1288 | const initialObserved = yield* Deferred.make<void>(); |
| 1289 | const replacementObserved = yield* Deferred.make<void>(); |
| 1290 | const tokens = yield* Ref.make<ReadonlyArray<string>>([]); |
| 1291 | const followedSupervisors = yield* Ref.make(0); |
| 1292 | yield* registry.start; |
| 1293 | |
| 1294 | const subscription = yield* Effect.forkChild( |
| 1295 | registry |
| 1296 | .followStream( |
| 1297 | BEARER_TARGET.environmentId, |
| 1298 | Stream.unwrap( |
| 1299 | Effect.gen(function* () { |
| 1300 | const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor; |
| 1301 | yield* Ref.update(followedSupervisors, (count) => count + 1); |
| 1302 | return SubscriptionRef.changes(supervisor.prepared); |
| 1303 | }), |
| 1304 | ), |
| 1305 | ) |
| 1306 | .pipe( |
| 1307 | Stream.filterMap((prepared) => |
| 1308 | Option.isSome(prepared) && prepared.value.httpAuthorization?._tag === "Bearer" |
| 1309 | ? Result.succeed(prepared.value.httpAuthorization.token) |
| 1310 | : Result.failVoid, |
| 1311 | ), |
| 1312 | Stream.changes, |
| 1313 | Stream.runForEach((token) => |
| 1314 | Effect.gen(function* () { |
| 1315 | yield* Ref.update(tokens, (current) => [...current, token]); |
| 1316 | yield* Deferred.succeed( |
| 1317 | token === replacementCredential.token ? replacementObserved : initialObserved, |
| 1318 | undefined, |
| 1319 | ); |
| 1320 | }), |
| 1321 | ), |
| 1322 | ), |
| 1323 | ); |
| 1324 | |
| 1325 | yield* Deferred.await(initialObserved); |
| 1326 | yield* registry.register(new RelayConnectionRegistration({ target: RELAY_TARGET })); |
| 1327 | yield* awaitConnectionState( |
| 1328 | registry, |
| 1329 | RELAY_TARGET.environmentId, |
| 1330 | (state) => state.phase === "connected", |
| 1331 | ); |
| 1332 | yield* registry.register( |
| 1333 | new BearerConnectionRegistration({ |
| 1334 | target: new BearerConnectionTarget({ ...BEARER_TARGET }), |
| 1335 | profile: new BearerConnectionProfile({ ...BEARER_PROFILE }), |
| 1336 | credential: replacementCredential, |
| 1337 | }), |
| 1338 | ); |
| 1339 | yield* Deferred.await(replacementObserved); |
| 1340 | yield* Fiber.interrupt(subscription); |
| 1341 | |
| 1342 | expect(yield* Ref.get(tokens)).toEqual([ |
| 1343 | BEARER_CREDENTIAL.token, |
| 1344 | replacementCredential.token, |
| 1345 | ]); |
| 1346 | expect(yield* Ref.get(followedSupervisors)).toBe(2); |
| 1347 | }).pipe(Effect.provide(harness.layer), Effect.scoped); |
| 1348 | }), |
| 1349 | ); |
| 1350 | |
| 1351 | it.effect("removes all relay-owned data without touching non-cloud connections", () => |
| 1352 | Effect.gen(function* () { |
| 1353 | const harness = yield* makeHarness( |
| 1354 | [RELAY_TARGET, SECOND_RELAY_TARGET, BEARER_TARGET], |
| 1355 | [BEARER_PROFILE], |
| 1356 | [[BEARER_TARGET.connectionId, BEARER_CREDENTIAL]], |
| 1357 | ); |
| 1358 | |
| 1359 | yield* Effect.gen(function* () { |
| 1360 | const registry = yield* EnvironmentRegistry.EnvironmentRegistry; |
| 1361 | yield* registry.removeRelayEnvironments(); |
| 1362 | |
| 1363 | const targets = yield* Ref.get(harness.storedTargets); |
| 1364 | expect(hasRoutes(targets, RELAY_TARGET.environmentId)).toBe(false); |
| 1365 | expect(hasRoutes(targets, SECOND_RELAY_TARGET.environmentId)).toBe(false); |
| 1366 | expect(routesOf(targets, BEARER_TARGET.environmentId)).toEqual([BEARER_TARGET]); |
| 1367 | expect(yield* Ref.get(harness.cacheClears)).toEqual( |
| 1368 | expect.arrayContaining([RELAY_TARGET.environmentId, SECOND_RELAY_TARGET.environmentId]), |
| 1369 | ); |
| 1370 | expect(yield* Ref.get(harness.ownedDataClears)).toEqual( |
| 1371 | expect.arrayContaining([RELAY_TARGET.environmentId, SECOND_RELAY_TARGET.environmentId]), |
| 1372 | ); |
| 1373 | expect( |
| 1374 | (yield* SubscriptionRef.get(registry.entries)).has(BEARER_TARGET.environmentId), |
| 1375 | ).toBe(true); |
| 1376 | }).pipe(Effect.provide(harness.layer), Effect.scoped); |
| 1377 | }), |
| 1378 | ); |
| 1379 | |
| 1380 | it.effect("keeps the runtime registered when durable removal fails", () => |
| 1381 | Effect.gen(function* () { |
| 1382 | const harness = yield* makeHarness([RELAY_TARGET], [], [], { |
| 1383 | beforeRegistrationRemove: () => |
| 1384 | Effect.fail( |
| 1385 | new Persistence.ConnectionPersistenceError({ |
| 1386 | operation: "remove-connection", |
| 1387 | message: "Storage is unavailable.", |
| 1388 | }), |
| 1389 | ), |
| 1390 | }); |
| 1391 | |
| 1392 | yield* Effect.gen(function* () { |
| 1393 | const registry = yield* EnvironmentRegistry.EnvironmentRegistry; |
| 1394 | yield* registry.start; |
| 1395 | yield* awaitConnectionState( |
| 1396 | registry, |
| 1397 | RELAY_TARGET.environmentId, |
| 1398 | (state) => state.phase === "connected", |
| 1399 | ); |
| 1400 | |
| 1401 | const error = yield* Effect.flip(registry.removeRelayEnvironments()); |
| 1402 | |
| 1403 | expect(error._tag).toBe("ConnectionPersistenceError"); |
| 1404 | expect(yield* Ref.get(harness.releasedSessions)).toBe(0); |
| 1405 | expect((yield* SubscriptionRef.get(registry.entries)).has(RELAY_TARGET.environmentId)).toBe( |
| 1406 | true, |
| 1407 | ); |
| 1408 | expect(hasRoutes(yield* Ref.get(harness.storedTargets), RELAY_TARGET.environmentId)).toBe( |
| 1409 | true, |
| 1410 | ); |
| 1411 | expect(yield* Ref.get(harness.cacheClears)).toEqual([]); |
| 1412 | expect(yield* Ref.get(harness.ownedDataClears)).toEqual([]); |
| 1413 | }).pipe(Effect.provide(harness.layer), Effect.scoped); |
| 1414 | }), |
| 1415 | ); |
| 1416 | |
| 1417 | it.effect("a replaced platform bearer wakes a supervisor blocked on the old one", () => |
| 1418 | Effect.gen(function* () { |
| 1419 | let storedCredentials: Ref.Ref<Map<string, ConnectionCredential>> | undefined; |
| 1420 | const harness = yield* makeHarness([], [], [], { |
| 1421 | beforePrepareRoute: (target) => |
| 1422 | target._tag !== "BearerConnectionTarget" || storedCredentials === undefined |
| 1423 | ? Effect.undefined |
| 1424 | : Ref.get(storedCredentials).pipe( |
| 1425 | Effect.map((current) => { |
| 1426 | const stored = current.get(target.connectionId); |
| 1427 | return stored?._tag === "BearerConnectionCredential" && |
| 1428 | stored.token === "old-bearer" |
| 1429 | ? new ConnectionBlockedError({ reason: "authentication", detail: "revoked" }) |
| 1430 | : undefined; |
| 1431 | }), |
| 1432 | ), |
| 1433 | }); |
| 1434 | storedCredentials = harness.storedCredentials; |
| 1435 | |
| 1436 | yield* Effect.gen(function* () { |
| 1437 | const registry = yield* EnvironmentRegistry.EnvironmentRegistry; |
| 1438 | const registration = (token: string) => |
| 1439 | new BearerConnectionRegistration({ |
| 1440 | target: BEARER_TARGET, |
| 1441 | profile: BEARER_PROFILE, |
| 1442 | credential: new BearerConnectionCredential({ token }), |
| 1443 | }); |
| 1444 | yield* registry.reconcilePlatform([registration("old-bearer")]); |
| 1445 | yield* awaitConnectionState( |
| 1446 | registry, |
| 1447 | BEARER_TARGET.environmentId, |
| 1448 | (state) => state.phase === "blocked", |
| 1449 | ); |
| 1450 | |
| 1451 | yield* registry.reconcilePlatform([registration("new-bearer")]); |
| 1452 | |
| 1453 | yield* awaitConnectionState( |
| 1454 | registry, |
| 1455 | BEARER_TARGET.environmentId, |
| 1456 | (state) => state.phase === "connected", |
| 1457 | ); |
| 1458 | }).pipe(Effect.provide(harness.layer), Effect.scoped); |
| 1459 | }), |
| 1460 | ); |
| 1461 | |
| 1462 | it.effect("a replaced platform bearer reaches a connected session's HTTP requests", () => |
| 1463 | Effect.gen(function* () { |
| 1464 | let failCredentialWrites = false; |
| 1465 | const harness = yield* makeHarness([], [], [], { |
| 1466 | beforeCredentialPut: () => |
| 1467 | failCredentialWrites |
| 1468 | ? Effect.fail( |
| 1469 | new ConnectionTransientError({ |
| 1470 | reason: "remote-unavailable", |
| 1471 | detail: "Storage unavailable", |
| 1472 | }), |
| 1473 | ) |
| 1474 | : Effect.void, |
| 1475 | }); |
| 1476 | |
| 1477 | yield* Effect.gen(function* () { |
| 1478 | const registry = yield* EnvironmentRegistry.EnvironmentRegistry; |
| 1479 | const registration = (token: string) => |
| 1480 | new BearerConnectionRegistration({ |
| 1481 | target: BEARER_TARGET, |
| 1482 | profile: BEARER_PROFILE, |
| 1483 | credential: new BearerConnectionCredential({ token }), |
| 1484 | }); |
| 1485 | const preparedToken = registry.run( |
| 1486 | BEARER_TARGET.environmentId, |
| 1487 | EnvironmentSupervisor.EnvironmentSupervisor.pipe( |
| 1488 | Effect.flatMap((supervisor) => SubscriptionRef.get(supervisor.prepared)), |
| 1489 | Effect.map((prepared) => |
| 1490 | Option.isSome(prepared) && prepared.value.httpAuthorization?._tag === "Bearer" |
| 1491 | ? prepared.value.httpAuthorization.token |
| 1492 | : null, |
| 1493 | ), |
| 1494 | ), |
| 1495 | ); |
| 1496 | yield* registry.reconcilePlatform([registration("old-bearer")]); |
| 1497 | yield* awaitConnectionState( |
| 1498 | registry, |
| 1499 | BEARER_TARGET.environmentId, |
| 1500 | (state) => state.phase === "connected", |
| 1501 | ); |
| 1502 | expect(yield* preparedToken).toBe("old-bearer"); |
| 1503 | |
| 1504 | failCredentialWrites = true; |
| 1505 | yield* registry.reconcilePlatform([registration("new-bearer")]); |
| 1506 | expect(yield* preparedToken).toBe("old-bearer"); |
| 1507 | |
| 1508 | failCredentialWrites = false; |
| 1509 | yield* registry.reconcilePlatform([registration("new-bearer")]); |
| 1510 | |
| 1511 | expect(yield* preparedToken).toBe("new-bearer"); |
| 1512 | expect(yield* Ref.get(harness.sessions)).toHaveLength(1); |
| 1513 | }).pipe(Effect.provide(harness.layer), Effect.scoped); |
| 1514 | }), |
| 1515 | ); |
| 1516 | |
| 1517 | it.effect("a bearer replaced while an attempt is in flight retries with the new one", () => |
| 1518 | Effect.gen(function* () { |
| 1519 | const attemptStarted = yield* Deferred.make<void>(); |
| 1520 | const releaseFirstAttempt = yield* Deferred.make<void>(); |
| 1521 | const attempts = yield* Ref.make(0); |
| 1522 | const harness = yield* makeHarness([], [], [], { |
| 1523 | beforePrepareRoute: (target) => |
| 1524 | target._tag !== "BearerConnectionTarget" |
| 1525 | ? Effect.undefined |
| 1526 | : Ref.updateAndGet(attempts, (count) => count + 1).pipe( |
| 1527 | Effect.flatMap((count) => |
| 1528 | count === 1 |
| 1529 | ? Deferred.succeed(attemptStarted, undefined).pipe( |
| 1530 | Effect.andThen(Deferred.await(releaseFirstAttempt)), |
| 1531 | Effect.as( |
| 1532 | new ConnectionBlockedError({ |
| 1533 | reason: "authentication", |
| 1534 | detail: "revoked", |
| 1535 | }), |
| 1536 | ), |
| 1537 | ) |
| 1538 | : Effect.undefined, |
| 1539 | ), |
| 1540 | ), |
| 1541 | }); |
| 1542 | |
| 1543 | yield* Effect.gen(function* () { |
| 1544 | const registry = yield* EnvironmentRegistry.EnvironmentRegistry; |
| 1545 | const registration = (token: string) => |
| 1546 | new BearerConnectionRegistration({ |
| 1547 | target: BEARER_TARGET, |
| 1548 | profile: BEARER_PROFILE, |
| 1549 | credential: new BearerConnectionCredential({ token }), |
| 1550 | }); |
| 1551 | yield* registry.reconcilePlatform([registration("old-bearer")]); |
| 1552 | yield* Deferred.await(attemptStarted).pipe(Effect.timeout("1 second")); |
| 1553 | |
| 1554 | yield* registry |
| 1555 | .stateChanges(BEARER_TARGET.environmentId) |
| 1556 | .pipe(Stream.runDrain, Effect.forkScoped({ startImmediately: true })); |
| 1557 | yield* Effect.yieldNow; |
| 1558 | yield* registry.reconcilePlatform([registration("new-bearer")]); |
| 1559 | yield* Deferred.succeed(releaseFirstAttempt, undefined); |
| 1560 | |
| 1561 | yield* awaitConnectionState( |
| 1562 | registry, |
| 1563 | BEARER_TARGET.environmentId, |
| 1564 | (state) => state.phase === "connected", |
| 1565 | ); |
| 1566 | expect(yield* Ref.get(attempts)).toBeGreaterThanOrEqual(2); |
| 1567 | }).pipe(Effect.provide(harness.layer), Effect.scoped); |
| 1568 | }), |
| 1569 | ); |
| 1570 | |
| 1571 | it.effect("starts platform environments without persisting or removing them", () => |
| 1572 | Effect.gen(function* () { |
| 1573 | const harness = yield* makeHarness([]); |
| 1574 | |
| 1575 | yield* Effect.gen(function* () { |
| 1576 | const registry = yield* EnvironmentRegistry.EnvironmentRegistry; |
| 1577 | yield* registry.reconcilePlatform([new PrimaryConnectionRegistration({ target: TARGET })]); |
| 1578 | yield* awaitConnectionState( |
| 1579 | registry, |
| 1580 | TARGET.environmentId, |
| 1581 | (state) => state.phase === "connected", |
| 1582 | ); |
| 1583 | |
| 1584 | expect(hasRoutes(yield* Ref.get(harness.storedTargets), TARGET.environmentId)).toBe(false); |
| 1585 | expect( |
| 1586 | (yield* SubscriptionRef.get(registry.entries)).get(TARGET.environmentId)?.target, |
| 1587 | ).toEqual(TARGET); |
| 1588 | |
| 1589 | const error = yield* Effect.flip(registry.remove(TARGET.environmentId)); |
| 1590 | expect(error._tag).toBe("PlatformEnvironmentRemovalError"); |
| 1591 | expect( |
| 1592 | (yield* SubscriptionRef.get(registry.entries)).get(TARGET.environmentId)?.target, |
| 1593 | ).toEqual(TARGET); |
| 1594 | }).pipe(Effect.provide(harness.layer)); |
| 1595 | }), |
| 1596 | ); |
| 1597 | |
| 1598 | it.effect("applies overlapping platform snapshots in order", () => |
| 1599 | Effect.gen(function* () { |
| 1600 | const started = yield* Deferred.make<void>(); |
| 1601 | const resume = yield* Deferred.make<void>(); |
| 1602 | const harness = yield* makeHarness([TARGET]); |
| 1603 | const permissions = yield* makePullRequestRoutingPermissions({ |
| 1604 | read: Effect.succeed([ |
| 1605 | { environmentId: TARGET.environmentId, connectionKey: "saved", permission: "read-write" }, |
| 1606 | ]), |
| 1607 | write: () => |
| 1608 | Deferred.succeed(started, undefined).pipe(Effect.andThen(Deferred.await(resume))), |
| 1609 | }); |
| 1610 | |
| 1611 | yield* Effect.gen(function* () { |
| 1612 | const registry = yield* EnvironmentRegistry.EnvironmentRegistry; |
| 1613 | const installing = yield* registry |
| 1614 | .reconcilePlatform([new PrimaryConnectionRegistration({ target: TARGET })]) |
| 1615 | .pipe(Effect.forkChild({ startImmediately: true })); |
| 1616 | yield* Deferred.await(started); |
| 1617 | const removing = yield* registry |
| 1618 | .reconcilePlatform([]) |
| 1619 | .pipe(Effect.forkChild({ startImmediately: true })); |
| 1620 | yield* Deferred.succeed(resume, undefined); |
| 1621 | yield* Fiber.join(installing); |
| 1622 | yield* Fiber.join(removing); |
| 1623 | |
| 1624 | expect((yield* SubscriptionRef.get(registry.entries)).has(TARGET.environmentId)).toBe( |
| 1625 | false, |
| 1626 | ); |
| 1627 | expect(yield* registrySpanNames(registry.reconcilePlatform([]))).toEqual([]); |
| 1628 | }).pipe( |
| 1629 | Effect.provide(harness.layer), |
| 1630 | Effect.provideService(PullRequestRoutingPermissions, permissions), |
| 1631 | Effect.scoped, |
| 1632 | ); |
| 1633 | }), |
| 1634 | ); |
| 1635 | |
| 1636 | it.effect("gives platform registrations precedence over persisted registrations", () => |
| 1637 | Effect.gen(function* () { |
| 1638 | for (const registration of [ |
| 1639 | new PrimaryConnectionRegistration({ target: TARGET }), |
| 1640 | new BearerConnectionRegistration({ |
| 1641 | target: BEARER_TARGET, |
| 1642 | profile: BEARER_PROFILE, |
| 1643 | credential: new BearerConnectionCredential({ token: "platform-bearer" }), |
| 1644 | }), |
| 1645 | ]) { |
| 1646 | const target = registration.target; |
| 1647 | const shadowedTarget = |
| 1648 | registration._tag === "BearerConnectionRegistration" |
| 1649 | ? registration.target |
| 1650 | : new RelayConnectionTarget({ |
| 1651 | environmentId: target.environmentId, |
| 1652 | label: "Shadowed relay environment", |
| 1653 | }); |
| 1654 | let failRemoval = true; |
| 1655 | const harness = yield* makeHarness( |
| 1656 | [shadowedTarget], |
| 1657 | registration._tag === "BearerConnectionRegistration" ? [registration.profile] : [], |
| 1658 | registration._tag === "BearerConnectionRegistration" |
| 1659 | ? [ |
| 1660 | [ |
| 1661 | registration.target.connectionId, |
| 1662 | new BearerConnectionCredential({ token: "saved-bearer" }), |
| 1663 | ], |
| 1664 | ] |
| 1665 | : [], |
| 1666 | { |
| 1667 | beforeRegistrationRemove: () => |
| 1668 | failRemoval |
| 1669 | ? Effect.fail( |
| 1670 | new Persistence.ConnectionPersistenceError({ |
| 1671 | operation: "remove-connection", |
| 1672 | message: "Storage unavailable", |
| 1673 | }), |
| 1674 | ) |
| 1675 | : Effect.void, |
| 1676 | }, |
| 1677 | ); |
| 1678 | const permissions = yield* makePullRequestRoutingPermissions({ |
| 1679 | read: Effect.succeed([]), |
| 1680 | write: () => Effect.void, |
| 1681 | }); |
| 1682 | const shadowedEntry = { |
| 1683 | target: shadowedTarget, |
| 1684 | profile: |
| 1685 | registration._tag === "BearerConnectionRegistration" |
| 1686 | ? Option.some(registration.profile) |
| 1687 | : Option.none(), |
| 1688 | enabled: true, |
| 1689 | }; |
| 1690 | yield* permissions.set(shadowedEntry, "read-write"); |
| 1691 | |
| 1692 | yield* Effect.gen(function* () { |
| 1693 | const registry = yield* EnvironmentRegistry.EnvironmentRegistry; |
| 1694 | yield* registry.reconcilePlatform([registration]); |
| 1695 | expect(yield* permissions.get(shadowedEntry)).toBe("off"); |
| 1696 | expect(hasRoutes(yield* Ref.get(harness.storedTargets), target.environmentId)).toBe(true); |
| 1697 | |
| 1698 | failRemoval = false; |
| 1699 | yield* registry.reconcilePlatform([registration]); |
| 1700 | |
| 1701 | expect( |
| 1702 | (yield* SubscriptionRef.get(registry.entries)).get(target.environmentId)?.target, |
| 1703 | ).toEqual(target); |
| 1704 | expect(hasRoutes(yield* Ref.get(harness.storedTargets), target.environmentId)).toBe( |
| 1705 | false, |
| 1706 | ); |
| 1707 | if (registration._tag === "BearerConnectionRegistration") { |
| 1708 | expect( |
| 1709 | (yield* Ref.get(harness.storedCredentials)).get(registration.target.connectionId), |
| 1710 | ).toEqual(registration.credential); |
| 1711 | expect(yield* registrySpanNames(registry.reconcilePlatform([registration]))).toEqual( |
| 1712 | [], |
| 1713 | ); |
| 1714 | } |
| 1715 | |
| 1716 | yield* registry.register( |
| 1717 | new RelayConnectionRegistration({ |
| 1718 | target: new RelayConnectionTarget({ |
| 1719 | environmentId: target.environmentId, |
| 1720 | label: "Shadowed relay environment", |
| 1721 | }), |
| 1722 | }), |
| 1723 | ); |
| 1724 | |
| 1725 | expect( |
| 1726 | (yield* SubscriptionRef.get(registry.entries)).get(target.environmentId)?.target, |
| 1727 | ).toEqual(target); |
| 1728 | expect(hasRoutes(yield* Ref.get(harness.storedTargets), target.environmentId)).toBe( |
| 1729 | false, |
| 1730 | ); |
| 1731 | }).pipe( |
| 1732 | Effect.provide(harness.layer), |
| 1733 | Effect.provideService(PullRequestRoutingPermissions, permissions), |
| 1734 | Effect.scoped, |
| 1735 | ); |
| 1736 | } |
| 1737 | }), |
| 1738 | ); |
| 1739 | |
| 1740 | it.effect("rechecks platform ownership after waiting for the environment lease", () => |
| 1741 | Effect.gen(function* () { |
| 1742 | const registrationStarted = yield* Deferred.make<void>(); |
| 1743 | const continueRegistration = yield* Deferred.make<void>(); |
| 1744 | const shadowedTarget = new RelayConnectionTarget({ |
| 1745 | environmentId: TARGET.environmentId, |
| 1746 | label: "Shadowed relay environment", |
| 1747 | }); |
| 1748 | const harness = yield* makeHarness([], [], [], { |
| 1749 | beforeRegistrationRegister: () => |
| 1750 | Deferred.succeed(registrationStarted, undefined).pipe( |
| 1751 | Effect.andThen(Deferred.await(continueRegistration)), |
| 1752 | ), |
| 1753 | }); |
| 1754 | |
| 1755 | yield* Effect.gen(function* () { |
| 1756 | const registry = yield* EnvironmentRegistry.EnvironmentRegistry; |
| 1757 | const persistedRegistration = yield* registry |
| 1758 | .register(new RelayConnectionRegistration({ target: shadowedTarget })) |
| 1759 | .pipe(Effect.forkChild({ startImmediately: true })); |
| 1760 | yield* Deferred.await(registrationStarted); |
| 1761 | |
| 1762 | const platformRegistration = yield* registry |
| 1763 | .reconcilePlatform([new PrimaryConnectionRegistration({ target: TARGET })]) |
| 1764 | .pipe(Effect.forkChild({ startImmediately: true })); |
| 1765 | yield* Effect.yieldNow; |
| 1766 | const removal = yield* Effect.flip(registry.remove(TARGET.environmentId)).pipe( |
| 1767 | Effect.forkChild({ startImmediately: true }), |
| 1768 | ); |
| 1769 | |
| 1770 | yield* Deferred.succeed(continueRegistration, undefined); |
| 1771 | yield* Fiber.join(persistedRegistration); |
| 1772 | yield* Fiber.join(platformRegistration); |
| 1773 | const error = yield* Fiber.join(removal); |
| 1774 | |
| 1775 | expect(error._tag).toBe("PlatformEnvironmentRemovalError"); |
| 1776 | expect( |
| 1777 | (yield* SubscriptionRef.get(registry.entries)).get(TARGET.environmentId)?.target, |
| 1778 | ).toEqual(TARGET); |
| 1779 | }).pipe(Effect.provide(harness.layer), Effect.scoped); |
| 1780 | }), |
| 1781 | ); |
| 1782 | |
| 1783 | it.effect("does not reacquire a runtime while its registration is being removed", () => |
| 1784 | Effect.gen(function* () { |
| 1785 | const removalStarted = yield* Deferred.make<void>(); |
| 1786 | const continueRemoval = yield* Deferred.make<void>(); |
| 1787 | const harness = yield* makeHarness([TARGET], [], [], { |
| 1788 | beforeRegistrationRemove: () => |
| 1789 | Deferred.succeed(removalStarted, undefined).pipe( |
| 1790 | Effect.andThen(Deferred.await(continueRemoval)), |
| 1791 | ), |
| 1792 | }); |
| 1793 | |
| 1794 | yield* Effect.gen(function* () { |
| 1795 | const registry = yield* EnvironmentRegistry.EnvironmentRegistry; |
| 1796 | yield* registry.start; |
| 1797 | yield* awaitConnectionState( |
| 1798 | registry, |
| 1799 | TARGET.environmentId, |
| 1800 | (state) => state.phase === "connected", |
| 1801 | ); |
| 1802 | |
| 1803 | const removal = yield* Effect.forkChild(registry.remove(TARGET.environmentId)); |
| 1804 | yield* Deferred.await(removalStarted); |
| 1805 | |
| 1806 | const stateLookup = yield* Effect.forkChild( |
| 1807 | Effect.flip(registry.state(TARGET.environmentId)), |
| 1808 | ); |
| 1809 | yield* Effect.yieldNow; |
| 1810 | expect(yield* Ref.get(harness.sessions)).toHaveLength(1); |
| 1811 | |
| 1812 | yield* Deferred.succeed(continueRemoval, undefined); |
| 1813 | yield* Fiber.join(removal); |
| 1814 | const error = yield* Fiber.join(stateLookup); |
| 1815 | expect(error._tag).toBe("EnvironmentNotRegisteredError"); |
| 1816 | }).pipe(Effect.provide(harness.layer), Effect.scoped); |
| 1817 | }), |
| 1818 | ); |
| 1819 | |
| 1820 | it.effect("platform refreshes preserve unsupported state for the same endpoint", () => |
| 1821 | Effect.gen(function* () { |
| 1822 | const harness = yield* makeHarness([]); |
| 1823 | yield* Effect.gen(function* () { |
| 1824 | const registry = yield* EnvironmentRegistry.EnvironmentRegistry; |
| 1825 | const registration = new PrimaryConnectionRegistration({ target: TARGET }); |
| 1826 | yield* registry.reconcilePlatform([registration]); |
| 1827 | yield* awaitConnectionState( |
| 1828 | registry, |
| 1829 | TARGET.environmentId, |
| 1830 | (state) => state.phase === "connected", |
| 1831 | ); |
| 1832 | const error = new ConnectionBlockedError({ |
| 1833 | reason: "unsupported", |
| 1834 | detail: "Use a compatible client.", |
| 1835 | }); |
| 1836 | yield* registry.setCompatibility(TARGET.environmentId, error); |
| 1837 | yield* awaitConnectionState( |
| 1838 | registry, |
| 1839 | TARGET.environmentId, |
| 1840 | (state) => state.phase === "available", |
| 1841 | ); |
| 1842 | yield* registry.reconcilePlatform([registration]); |
| 1843 | yield* registry.reconcilePlatform([registration]); |
| 1844 | expect( |
| 1845 | (yield* SubscriptionRef.get(registry.entries)).get(TARGET.environmentId), |
| 1846 | ).toMatchObject({ enabled: true, unsupportedReason: error.message }); |
| 1847 | yield* registry.reconcilePlatform([ |
| 1848 | new PrimaryConnectionRegistration({ |
| 1849 | target: new PrimaryConnectionTarget({ ...TARGET, label: "Renamed" }), |
| 1850 | }), |
| 1851 | ]); |
| 1852 | expect(yield* registry.state(TARGET.environmentId)).toMatchObject({ |
| 1853 | desired: false, |
| 1854 | phase: "available", |
| 1855 | }); |
| 1856 | expect(yield* Ref.get(harness.sessions)).toHaveLength(1); |
| 1857 | yield* registry.reconcilePlatform([ |
| 1858 | new PrimaryConnectionRegistration({ |
| 1859 | target: new PrimaryConnectionTarget({ |
| 1860 | ...TARGET, |
| 1861 | httpBaseUrl: "https://changed.example.test", |
| 1862 | }), |
| 1863 | }), |
| 1864 | ]); |
| 1865 | yield* awaitConnectionState( |
| 1866 | registry, |
| 1867 | TARGET.environmentId, |
| 1868 | (state) => state.phase === "connected", |
| 1869 | ); |
| 1870 | expect( |
| 1871 | (yield* SubscriptionRef.get(registry.entries)).get(TARGET.environmentId) |
| 1872 | ?.unsupportedReason, |
| 1873 | ).toBeUndefined(); |
| 1874 | }).pipe(Effect.provide(harness.layer)); |
| 1875 | }), |
| 1876 | ); |
| 1877 | |
| 1878 | it.effect("keeps one session per environment across concurrent registrations and retries", () => |
| 1879 | Effect.gen(function* () { |
| 1880 | const harness = yield* makeHarness([]); |
| 1881 | |
| 1882 | yield* Effect.gen(function* () { |
| 1883 | const registry = yield* EnvironmentRegistry.EnvironmentRegistry; |
| 1884 | const registration = new PrimaryConnectionRegistration({ target: TARGET }); |
| 1885 | yield* Effect.all( |
| 1886 | Array.from({ length: 5 }, () => registry.reconcilePlatform([registration])), |
| 1887 | { concurrency: "unbounded", discard: true }, |
| 1888 | ); |
| 1889 | yield* awaitConnectionState( |
| 1890 | registry, |
| 1891 | TARGET.environmentId, |
| 1892 | (state) => state.phase === "connected", |
| 1893 | ); |
| 1894 | |
| 1895 | yield* Effect.all( |
| 1896 | [ |
| 1897 | ...Array.from({ length: 5 }, () => registry.reconcilePlatform([registration])), |
| 1898 | ...Array.from({ length: 5 }, () => registry.retryNow(TARGET.environmentId)), |
| 1899 | registry.reconcilePlatform([registration]), |
| 1900 | ], |
| 1901 | { concurrency: "unbounded", discard: true }, |
| 1902 | ); |
| 1903 | for (let attempt = 0; attempt < 100; attempt += 1) { |
| 1904 | yield* Effect.yieldNow; |
| 1905 | } |
| 1906 | |
| 1907 | expect(yield* Ref.get(harness.sessions)).toHaveLength(1); |
| 1908 | expect(yield* Ref.get(harness.releasedSessions)).toBe(0); |
| 1909 | expect(yield* registry.state(TARGET.environmentId)).toMatchObject({ |
| 1910 | phase: "connected", |
| 1911 | generation: 1, |
| 1912 | }); |
| 1913 | }).pipe(Effect.provide(harness.layer), Effect.scoped); |
| 1914 | }), |
| 1915 | ); |
| 1916 | |
| 1917 | it.effect("retains a healthy runtime when the platform repeats an identical registration", () => |
| 1918 | Effect.gen(function* () { |
| 1919 | const harness = yield* makeHarness([]); |
| 1920 | let failWrites = false; |
| 1921 | const permissions = yield* makePullRequestRoutingPermissions({ |
| 1922 | read: Effect.succeed([]), |
| 1923 | write: () => |
| 1924 | failWrites |
| 1925 | ? Effect.fail( |
| 1926 | new ConnectionTransientError({ |
| 1927 | reason: "remote-unavailable", |
| 1928 | detail: "Storage unavailable", |
| 1929 | }), |
| 1930 | ) |
| 1931 | : Effect.void, |
| 1932 | }); |
| 1933 | const entry = { target: TARGET, profile: Option.none(), enabled: true }; |
| 1934 | |
| 1935 | yield* Effect.gen(function* () { |
| 1936 | const registry = yield* EnvironmentRegistry.EnvironmentRegistry; |
| 1937 | const registration = new PrimaryConnectionRegistration({ target: TARGET }); |
| 1938 | yield* registry.reconcilePlatform([registration]); |
| 1939 | yield* awaitConnectionState( |
| 1940 | registry, |
| 1941 | TARGET.environmentId, |
| 1942 | (state) => state.phase === "connected", |
| 1943 | ); |
| 1944 | yield* permissions.set(entry, "read-write"); |
| 1945 | |
| 1946 | const repeated = yield* registrySpanNames( |
| 1947 | registry.reconcilePlatform([ |
| 1948 | new PrimaryConnectionRegistration({ target: new PrimaryConnectionTarget(TARGET) }), |
| 1949 | ]), |
| 1950 | ); |
| 1951 | |
| 1952 | expect(repeated).toEqual([]); |
| 1953 | expect(yield* Ref.get(harness.sessions)).toHaveLength(1); |
| 1954 | expect(yield* permissions.get(entry)).toBe("read-write"); |
| 1955 | |
| 1956 | const changedTarget = new PrimaryConnectionTarget({ |
| 1957 | ...TARGET, |
| 1958 | httpBaseUrl: "https://changed.example.test", |
| 1959 | }); |
| 1960 | failWrites = true; |
| 1961 | yield* registry.reconcilePlatform([ |
| 1962 | new PrimaryConnectionRegistration({ target: changedTarget }), |
| 1963 | ]); |
| 1964 | expect( |
| 1965 | (yield* SubscriptionRef.get(registry.entries)).get(TARGET.environmentId)?.target, |
| 1966 | ).toEqual(TARGET); |
| 1967 | |
| 1968 | failWrites = false; |
| 1969 | yield* registry.reconcilePlatform([ |
| 1970 | new PrimaryConnectionRegistration({ target: changedTarget }), |
| 1971 | ]); |
| 1972 | expect( |
| 1973 | (yield* SubscriptionRef.get(registry.entries)).get(TARGET.environmentId)?.target, |
| 1974 | ).toEqual(changedTarget); |
| 1975 | expect(yield* permissions.get(entry)).toBe("off"); |
| 1976 | yield* registry.reconcilePlatform([registration]); |
| 1977 | expect(yield* permissions.get(entry)).toBe("off"); |
| 1978 | |
| 1979 | yield* permissions.set(entry, "read-write"); |
| 1980 | failWrites = true; |
| 1981 | yield* registry.reconcilePlatform([]); |
| 1982 | expect((yield* SubscriptionRef.get(registry.entries)).has(TARGET.environmentId)).toBe(true); |
| 1983 | failWrites = false; |
| 1984 | yield* registry.reconcilePlatform([]); |
| 1985 | expect((yield* SubscriptionRef.get(registry.entries)).has(TARGET.environmentId)).toBe( |
| 1986 | false, |
| 1987 | ); |
| 1988 | expect(yield* permissions.get(entry)).toBe("off"); |
| 1989 | expect(yield* registrySpanNames(registry.reconcilePlatform([]))).toEqual([]); |
| 1990 | |
| 1991 | yield* registry.reconcilePlatform([registration]); |
| 1992 | expect(yield* permissions.get(entry)).toBe("off"); |
| 1993 | }).pipe( |
| 1994 | Effect.provide(harness.layer), |
| 1995 | Effect.provideService(PullRequestRoutingPermissions, permissions), |
| 1996 | Effect.scoped, |
| 1997 | ); |
| 1998 | }), |
| 1999 | ); |
| 2000 | |
| 2001 | it.effect("removes all owned SSH state only on explicit removal", () => |
| 2002 | Effect.gen(function* () { |
| 2003 | const harness = yield* makeHarness( |
| 2004 | [SSH_CONNECTION], |
| 2005 | [SSH_PROFILE], |
| 2006 | [ |
| 2007 | [ |
| 2008 | SSH_CONNECTION.connectionId, |
| 2009 | new BearerConnectionCredential({ token: "temporary-token" }), |
| 2010 | ], |
| 2011 | ], |
| 2012 | ); |
| 2013 | |
| 2014 | yield* Effect.gen(function* () { |
| 2015 | const registry = yield* EnvironmentRegistry.EnvironmentRegistry; |
| 2016 | yield* registry.start; |
| 2017 | yield* registry.remove(SSH_CONNECTION.environmentId); |
| 2018 | |
| 2019 | expect((yield* Ref.get(harness.storedProfiles)).has(SSH_CONNECTION.connectionId)).toBe( |
| 2020 | false, |
| 2021 | ); |
| 2022 | expect((yield* Ref.get(harness.storedCredentials)).has(SSH_CONNECTION.connectionId)).toBe( |
| 2023 | false, |
| 2024 | ); |
| 2025 | expect((yield* Ref.get(harness.storedRemoteTokens)).has(SSH_CONNECTION.environmentId)).toBe( |
| 2026 | false, |
| 2027 | ); |
| 2028 | expect(yield* Ref.get(harness.disconnectedSshTargets)).toEqual([SSH_TARGET]); |
| 2029 | }).pipe(Effect.provide(harness.layer)); |
| 2030 | }), |
| 2031 | ); |
| 2032 | }); |
| 2033 | |
| 2034 | describe("EnvironmentRegistry routes", () => { |
| 2035 | const LAN_TARGET = new BearerConnectionTarget({ |
| 2036 | environmentId: RELAY_TARGET.environmentId, |
| 2037 | label: RELAY_TARGET.label, |
| 2038 | connectionId: "bearer:lan", |
| 2039 | }); |
| 2040 | const LAN_PROFILE = new BearerConnectionProfile({ |
| 2041 | connectionId: LAN_TARGET.connectionId, |
| 2042 | environmentId: LAN_TARGET.environmentId, |
| 2043 | label: LAN_TARGET.label, |
| 2044 | httpBaseUrl: "http://192.168.1.10:3773/", |
| 2045 | wsBaseUrl: "ws://192.168.1.10:3773/", |
| 2046 | }); |
| 2047 | const lanRegistration = (target = LAN_TARGET, profile = LAN_PROFILE) => |
| 2048 | new BearerConnectionRegistration({ target, profile, credential: BEARER_CREDENTIAL }); |
| 2049 | |
| 2050 | it.effect("adds a paired LAN route ahead of T3 Connect instead of replacing it", () => |
| 2051 | Effect.gen(function* () { |
| 2052 | const harness = yield* makeHarness([RELAY_TARGET]); |
| 2053 | yield* Effect.gen(function* () { |
| 2054 | const registry = yield* EnvironmentRegistry.EnvironmentRegistry; |
| 2055 | yield* registry.register(lanRegistration()); |
| 2056 | |
| 2057 | expect(routesOf(yield* Ref.get(harness.storedTargets), LAN_TARGET.environmentId)).toEqual([ |
| 2058 | LAN_TARGET, |
| 2059 | RELAY_TARGET, |
| 2060 | ]); |
| 2061 | const entry = (yield* SubscriptionRef.get(registry.entries)).get(LAN_TARGET.environmentId); |
| 2062 | expect(entry?.target).toEqual(LAN_TARGET); |
| 2063 | expect(entry?.alternateRoutes?.map((route) => route.target)).toEqual([RELAY_TARGET]); |
| 2064 | }).pipe(Effect.provide(harness.layer), Effect.scoped); |
| 2065 | }), |
| 2066 | ); |
| 2067 | |
| 2068 | it.effect("re-pairing the same address replaces that route rather than adding another", () => |
| 2069 | Effect.gen(function* () { |
| 2070 | const harness = yield* makeHarness( |
| 2071 | [LAN_TARGET, RELAY_TARGET], |
| 2072 | [LAN_PROFILE], |
| 2073 | [[LAN_TARGET.connectionId, BEARER_CREDENTIAL]], |
| 2074 | ); |
| 2075 | yield* Effect.gen(function* () { |
| 2076 | const registry = yield* EnvironmentRegistry.EnvironmentRegistry; |
| 2077 | const repaired = new BearerConnectionTarget({ |
| 2078 | ...LAN_TARGET, |
| 2079 | connectionId: "bearer:lan-again", |
| 2080 | }); |
| 2081 | yield* registry.register( |
| 2082 | lanRegistration( |
| 2083 | repaired, |
| 2084 | new BearerConnectionProfile({ ...LAN_PROFILE, connectionId: repaired.connectionId }), |
| 2085 | ), |
| 2086 | ); |
| 2087 | |
| 2088 | expect(routesOf(yield* Ref.get(harness.storedTargets), LAN_TARGET.environmentId)).toEqual([ |
| 2089 | repaired, |
| 2090 | RELAY_TARGET, |
| 2091 | ]); |
| 2092 | }).pipe(Effect.provide(harness.layer), Effect.scoped); |
| 2093 | }), |
| 2094 | ); |
| 2095 | |
| 2096 | it.effect("re-pairing at another loopback address prefers the new route", () => |
| 2097 | Effect.gen(function* () { |
| 2098 | const loopback = (connectionId: string, host: string) => |
| 2099 | [ |
| 2100 | new BearerConnectionTarget({ ...LAN_TARGET, connectionId }), |
| 2101 | new BearerConnectionProfile({ |
| 2102 | ...LAN_PROFILE, |
| 2103 | connectionId, |
| 2104 | httpBaseUrl: `http://${host}:3773/`, |
| 2105 | wsBaseUrl: `ws://${host}:3773/`, |
| 2106 | }), |
| 2107 | ] as const; |
| 2108 | const [savedTarget, savedProfile] = loopback("bearer:ip", "127.0.0.1"); |
| 2109 | const [pastedTarget, pastedProfile] = loopback("bearer:localhost", "localhost"); |
| 2110 | const harness = yield* makeHarness( |
| 2111 | [savedTarget, RELAY_TARGET], |
| 2112 | [savedProfile], |
| 2113 | [[savedTarget.connectionId, BEARER_CREDENTIAL]], |
| 2114 | ); |
| 2115 | yield* Effect.gen(function* () { |
| 2116 | const registry = yield* EnvironmentRegistry.EnvironmentRegistry; |
| 2117 | yield* registry.register(lanRegistration(pastedTarget, pastedProfile)); |
| 2118 | |
| 2119 | expect(routesOf(yield* Ref.get(harness.storedTargets), LAN_TARGET.environmentId)).toEqual([ |
| 2120 | pastedTarget, |
| 2121 | savedTarget, |
| 2122 | RELAY_TARGET, |
| 2123 | ]); |
| 2124 | }).pipe(Effect.provide(harness.layer), Effect.scoped); |
| 2125 | }), |
| 2126 | ); |
| 2127 | |
| 2128 | it.effect( |
| 2129 | "adding a saved SSH host again replaces its route, whatever id it was saved under", |
| 2130 | () => |
| 2131 | Effect.gen(function* () { |
| 2132 | const harness = yield* makeHarness([SSH_CONNECTION], [SSH_PROFILE]); |
| 2133 | yield* Effect.gen(function* () { |
| 2134 | const registry = yield* EnvironmentRegistry.EnvironmentRegistry; |
| 2135 | const again = new SshConnectionTarget({ |
| 2136 | ...SSH_CONNECTION, |
| 2137 | connectionId: "ssh-connection-new-id", |
| 2138 | }); |
| 2139 | yield* registry.register( |
| 2140 | new SshConnectionRegistration({ |
| 2141 | target: again, |
| 2142 | profile: new SshConnectionProfile({ |
| 2143 | ...SSH_PROFILE, |
| 2144 | connectionId: again.connectionId, |
| 2145 | }), |
| 2146 | credential: BEARER_CREDENTIAL, |
| 2147 | }), |
| 2148 | ); |
| 2149 | |
| 2150 | expect( |
| 2151 | routesOf(yield* Ref.get(harness.storedTargets), SSH_CONNECTION.environmentId), |
| 2152 | ).toEqual([again]); |
| 2153 | }).pipe(Effect.provide(harness.layer), Effect.scoped); |
| 2154 | }), |
| 2155 | ); |
| 2156 | |
| 2157 | it.effect("signing out of T3 Connect keeps an environment that still has a LAN route", () => |
| 2158 | Effect.gen(function* () { |
| 2159 | const harness = yield* makeHarness( |
| 2160 | [LAN_TARGET, RELAY_TARGET, SECOND_RELAY_TARGET], |
| 2161 | [LAN_PROFILE], |
| 2162 | [[LAN_TARGET.connectionId, BEARER_CREDENTIAL]], |
| 2163 | ); |
| 2164 | yield* Effect.gen(function* () { |
| 2165 | const registry = yield* EnvironmentRegistry.EnvironmentRegistry; |
| 2166 | yield* registry.removeRelayEnvironments(); |
| 2167 | |
| 2168 | const targets = yield* Ref.get(harness.storedTargets); |
| 2169 | expect(routesOf(targets, LAN_TARGET.environmentId)).toEqual([LAN_TARGET]); |
| 2170 | expect(hasRoutes(targets, SECOND_RELAY_TARGET.environmentId)).toBe(false); |
| 2171 | expect(yield* Ref.get(harness.cacheClears)).toEqual([SECOND_RELAY_TARGET.environmentId]); |
| 2172 | expect( |
| 2173 | (yield* SubscriptionRef.get(registry.entries)).get(LAN_TARGET.environmentId)?.target, |
| 2174 | ).toEqual(LAN_TARGET); |
| 2175 | }).pipe(Effect.provide(harness.layer), Effect.scoped); |
| 2176 | }), |
| 2177 | ); |
| 2178 | |
| 2179 | it.effect("reorders routes and rejects an order that drops one", () => |
| 2180 | Effect.gen(function* () { |
| 2181 | const harness = yield* makeHarness( |
| 2182 | [LAN_TARGET, RELAY_TARGET], |
| 2183 | [LAN_PROFILE], |
| 2184 | [[LAN_TARGET.connectionId, BEARER_CREDENTIAL]], |
| 2185 | ); |
| 2186 | yield* Effect.gen(function* () { |
| 2187 | const registry = yield* EnvironmentRegistry.EnvironmentRegistry; |
| 2188 | yield* registry.reorderRoutes(LAN_TARGET.environmentId, ["relay", LAN_TARGET.connectionId]); |
| 2189 | expect(routesOf(yield* Ref.get(harness.storedTargets), LAN_TARGET.environmentId)).toEqual([ |
| 2190 | RELAY_TARGET, |
| 2191 | LAN_TARGET, |
| 2192 | ]); |
| 2193 | |
| 2194 | const error = yield* registry |
| 2195 | .reorderRoutes(LAN_TARGET.environmentId, ["relay"]) |
| 2196 | .pipe(Effect.flip); |
| 2197 | expect(error._tag).toBe("ConnectionBlockedError"); |
| 2198 | }).pipe(Effect.provide(harness.layer), Effect.scoped); |
| 2199 | }), |
| 2200 | ); |
| 2201 | |
| 2202 | it.effect("removing the last route forgets the environment", () => |
| 2203 | Effect.gen(function* () { |
| 2204 | const harness = yield* makeHarness( |
| 2205 | [LAN_TARGET, RELAY_TARGET], |
| 2206 | [LAN_PROFILE], |
| 2207 | [[LAN_TARGET.connectionId, BEARER_CREDENTIAL]], |
| 2208 | ); |
| 2209 | yield* Effect.gen(function* () { |
| 2210 | const registry = yield* EnvironmentRegistry.EnvironmentRegistry; |
| 2211 | yield* registry.removeRoute(LAN_TARGET.environmentId, LAN_TARGET.connectionId); |
| 2212 | expect(routesOf(yield* Ref.get(harness.storedTargets), LAN_TARGET.environmentId)).toEqual([ |
| 2213 | RELAY_TARGET, |
| 2214 | ]); |
| 2215 | expect(yield* Ref.get(harness.cacheClears)).toEqual([]); |
| 2216 | |
| 2217 | yield* registry.removeRoute(LAN_TARGET.environmentId, "relay"); |
| 2218 | expect(hasRoutes(yield* Ref.get(harness.storedTargets), LAN_TARGET.environmentId)).toBe( |
| 2219 | false, |
| 2220 | ); |
| 2221 | expect(yield* Ref.get(harness.cacheClears)).toEqual([LAN_TARGET.environmentId]); |
| 2222 | }).pipe(Effect.provide(harness.layer), Effect.scoped); |
| 2223 | }), |
| 2224 | ); |
| 2225 | |
| 2226 | it.effect( |
| 2227 | "revokes pull request routing trust when a route is added but keeps it on reorder", |
| 2228 | () => |
| 2229 | Effect.gen(function* () { |
| 2230 | const harness = yield* makeHarness([RELAY_TARGET]); |
| 2231 | let stored: ReadonlyArray<StoredPullRequestRoutingPermission> = []; |
| 2232 | const permissions = yield* makePullRequestRoutingPermissions({ |
| 2233 | read: Effect.sync(() => stored), |
| 2234 | write: (next) => Effect.sync(() => void (stored = next)), |
| 2235 | }); |
| 2236 | yield* Effect.gen(function* () { |
| 2237 | const registry = yield* EnvironmentRegistry.EnvironmentRegistry; |
| 2238 | const current = () => |
| 2239 | SubscriptionRef.get(registry.entries).pipe( |
| 2240 | Effect.map((entries) => entries.get(RELAY_TARGET.environmentId)!), |
| 2241 | ); |
| 2242 | yield* permissions.set(yield* current(), "read"); |
| 2243 | yield* registry.register(lanRegistration()); |
| 2244 | expect(yield* permissions.get(yield* current())).toBe("off"); |
| 2245 | |
| 2246 | yield* permissions.set(yield* current(), "read"); |
| 2247 | yield* registry.reorderRoutes(LAN_TARGET.environmentId, [ |
| 2248 | "relay", |
| 2249 | LAN_TARGET.connectionId, |
| 2250 | ]); |
| 2251 | expect(yield* permissions.get(yield* current())).toBe("read"); |
| 2252 | }).pipe( |
| 2253 | Effect.provide(harness.layer), |
| 2254 | Effect.provideService(PullRequestRoutingPermissions, permissions), |
| 2255 | Effect.scoped, |
| 2256 | ); |
| 2257 | }), |
| 2258 | ); |
| 2259 | |
| 2260 | it.effect("loads saved routes grouped by environment, in saved order", () => |
| 2261 | Effect.gen(function* () { |
| 2262 | const harness = yield* makeHarness( |
| 2263 | [LAN_TARGET, BEARER_TARGET, RELAY_TARGET], |
| 2264 | [LAN_PROFILE, BEARER_PROFILE], |
| 2265 | [ |
| 2266 | [LAN_TARGET.connectionId, BEARER_CREDENTIAL], |
| 2267 | [BEARER_TARGET.connectionId, BEARER_CREDENTIAL], |
| 2268 | ], |
| 2269 | ); |
| 2270 | yield* Effect.gen(function* () { |
| 2271 | const registry = yield* EnvironmentRegistry.EnvironmentRegistry; |
| 2272 | const entries = yield* SubscriptionRef.get(registry.entries); |
| 2273 | expect([...entries.keys()]).toEqual([ |
| 2274 | LAN_TARGET.environmentId, |
| 2275 | BEARER_TARGET.environmentId, |
| 2276 | ]); |
| 2277 | expect(entries.get(LAN_TARGET.environmentId)?.alternateRoutes?.[0]?.target).toEqual( |
| 2278 | RELAY_TARGET, |
| 2279 | ); |
| 2280 | }).pipe(Effect.provide(harness.layer), Effect.scoped); |
| 2281 | }), |
| 2282 | ); |
| 2283 | |
| 2284 | it.effect("saves the Tailscale mark when the server reports a learned address as tailnet", () => |
| 2285 | Effect.gen(function* () { |
| 2286 | const httpBaseUrl = "http://100.101.102.103:3773/"; |
| 2287 | const learnedId = `learned:${LAN_TARGET.environmentId}:http://100.101.102.103:3773@${LAN_TARGET.connectionId}`; |
| 2288 | const learned = new BearerConnectionTarget({ ...LAN_TARGET, connectionId: learnedId }); |
| 2289 | const learnedProfile = new BearerConnectionProfile({ |
| 2290 | connectionId: learnedId, |
| 2291 | environmentId: LAN_TARGET.environmentId, |
| 2292 | label: LAN_TARGET.label, |
| 2293 | httpBaseUrl, |
| 2294 | wsBaseUrl: "ws://100.101.102.103:3773/", |
| 2295 | learned: true, |
| 2296 | }); |
| 2297 | const harness = yield* makeHarness( |
| 2298 | [LAN_TARGET, learned], |
| 2299 | [LAN_PROFILE, learnedProfile], |
| 2300 | [[LAN_TARGET.connectionId, BEARER_CREDENTIAL]], |
| 2301 | { |
| 2302 | directEndpoints: [ |
| 2303 | { kind: "lan", httpBaseUrl: LAN_PROFILE.httpBaseUrl }, |
| 2304 | { kind: "tailnet", httpBaseUrl }, |
| 2305 | ], |
| 2306 | }, |
| 2307 | ); |
| 2308 | yield* Effect.gen(function* () { |
| 2309 | const registry = yield* EnvironmentRegistry.EnvironmentRegistry; |
| 2310 | yield* registry.start; |
| 2311 | yield* SubscriptionRef.changes(registry.entries).pipe( |
| 2312 | Stream.map((entries) => entries.get(LAN_TARGET.environmentId)?.alternateRoutes?.[0]), |
| 2313 | Stream.filter((route) => route !== undefined && connectionRouteKind(route) === "tailnet"), |
| 2314 | Stream.runHead, |
| 2315 | ); |
| 2316 | expect((yield* Ref.get(harness.storedProfiles)).get(learnedId)).toMatchObject({ |
| 2317 | network: "tailscale", |
| 2318 | learned: true, |
| 2319 | httpBaseUrl, |
| 2320 | }); |
| 2321 | }).pipe(Effect.provide(harness.layer), Effect.scoped); |
| 2322 | }), |
| 2323 | ); |
| 2324 | |
| 2325 | it.effect("drops a learned route whose profile was not saved instead of duplicating it", () => |
| 2326 | Effect.gen(function* () { |
| 2327 | const learnedId = `learned:${LAN_TARGET.environmentId}:100.64.0.9:3773@${LAN_TARGET.connectionId}`; |
| 2328 | const learned = new BearerConnectionTarget({ ...LAN_TARGET, connectionId: learnedId }); |
| 2329 | const harness = yield* makeHarness( |
| 2330 | [LAN_TARGET, learned, learned], |
| 2331 | [LAN_PROFILE], |
| 2332 | [[LAN_TARGET.connectionId, BEARER_CREDENTIAL]], |
| 2333 | ); |
| 2334 | yield* Effect.gen(function* () { |
| 2335 | const registry = yield* EnvironmentRegistry.EnvironmentRegistry; |
| 2336 | const entry = (yield* SubscriptionRef.get(registry.entries)).get(LAN_TARGET.environmentId); |
| 2337 | expect(entry?.target).toEqual(LAN_TARGET); |
| 2338 | expect(entry?.alternateRoutes ?? []).toEqual([]); |
| 2339 | }).pipe(Effect.provide(harness.layer), Effect.scoped); |
| 2340 | }), |
| 2341 | ); |
| 2342 | }); |