Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { describe, expect, it } from "@effect/vitest";
3import * as Deferred from "effect/Deferred";
4import * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
6import * as Fiber from "effect/Fiber";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Option from "effect/Option";
10import * as Path from "effect/Path";
11import * as PlatformError from "effect/PlatformError";
12import * as Schema from "effect/Schema";
13import * as TestClock from "effect/testing/TestClock";
14import * as Stream from "effect/Stream";
15import { HttpClient, HttpClientResponse, HttpServer, type HttpClientRequest } from "effect/http";
16import * as NetAddress from "effect/net/NetAddress";
17
18import { DESKTOP_UPDATE_RESTART_MARKER_FILE, EnvironmentId } from "@t3tools/contracts";
19import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
20import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
21import * as ServerConfigModule from "../config.ts";
22import { writeServiceState } from "../serviceLauncher.ts";
23import {
24 SERVICE_LAUNCHER_PROTOCOL,
25 SERVICE_STATE_FILE,
26 SERVICE_STOP_MARKER_FILE,
27 type ServiceUpdateRecord,
28} from "./serviceProtocol.ts";
29import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
30import * as AgentAwarenessRelay from "../relay/AgentAwarenessRelay.ts";
31import { CLOUD_CLI_DESIRED_LINK_SECRET } from "./CliState.ts";
32import * as CliTokenManager from "./CliTokenManager.ts";
33import { RelayManagedEndpointRecoveryRegistrationRequest } from "@t3tools/contracts/relay";
34import {
35 CLOUD_ENDPOINT_CONFIRMED_ORIGIN,
36 CLOUD_ENDPOINT_RUNTIME_CONFIG,
37 CLOUD_LINKED_USER_ID,
38 decodeConfirmedOrigin,
39 decodeRuntimeConfig,
40 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
41 RELAY_URL_SECRET,
42} from "./config.ts";
43import * as CloudLink from "./CloudLink.ts";
44import { consumeCloudReplayGuards } from "./CloudLink.ts";
45import { pendingServiceUpdateExists } from "./updateHandoff.ts";
46import {
47 managedTunnelStartupAction,
48 retryManagedTunnelRegistration,
49} from "./managedTunnelStartup.ts";
50import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
51
52const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") =>
53 new ServerSecretStore.SecretStorePersistError({
54 resource: "cloud replay guard",
55 cause: PlatformError.systemError({
56 _tag: tag,
57 module: "FileSystem",
58 method: "open",
59 pathOrDescriptor: "cloud-replay-guard.bin",
60 }),
61 });
62
63const unusedSecretStoreOperation = () => Effect.die("unused secret-store operation");
64// Linking wakes the awareness relay; these tests do not run it.
65const idleAwarenessRelay = AgentAwarenessRelay.AgentAwarenessRelay.of({
66 publishThread: () => Effect.void,
67 drain: Effect.void,
68 requestCatchUp: () => Effect.void,
69 start: () => Effect.void,
70});
71// The connect routes register recovery against the listening port; these tests
72// call the service directly.
73const idleHttpServer = HttpServer.HttpServer.of({
74 address: NetAddress.inetAddressFromIpStringUnsafe("127.0.0.1", 3773),
75 serve: (() => Effect.void) as HttpServer.HttpServer["Service"]["serve"],
76});
77
78const decodeManagedTunnelRecoveryRegistration = Schema.decodeUnknownEffect(
79 Schema.fromJsonString(RelayManagedEndpointRecoveryRegistrationRequest),
80);
81
82function makeSecretStore(
83 create: ServerSecretStore.ServerSecretStore["Service"]["create"],
84): ServerSecretStore.ServerSecretStore["Service"] {
85 return {
86 get: unusedSecretStoreOperation,
87 set: unusedSecretStoreOperation,
88 create,
89 getOrCreateRandom: unusedSecretStoreOperation,
90 remove: unusedSecretStoreOperation,
91 };
92}
93
94it("preserves messages surfaced by cloud 500 responses", () => {
95 const cause = new Error("cloud operation failed");
96
97 expect([
98 new EnvironmentAuth.ServerAuthLinkedCloudAccountVerificationError({ cause }).message,
99 new EnvironmentAuth.ServerAuthLinkedCloudAccountReadError({ cause }).message,
100 new EnvironmentAuth.ServerAuthLinkedCloudAccountMissingError({}).message,
101 new EnvironmentAuth.ServerAuthCloudLinkJwtSigningError({ cause }).message,
102 new EnvironmentAuth.ServerAuthCloudMintPublicKeyMissingError({}).message,
103 new EnvironmentAuth.ServerAuthCloudRelayIssuerMissingError({}).message,
104 new EnvironmentAuth.ServerAuthCloudHealthJwtSigningError({ cause }).message,
105 new EnvironmentAuth.ServerAuthCloudMintJwtSigningError({ cause }).message,
106 ]).toEqual([
107 "Could not verify the linked cloud account.",
108 "Could not read the linked cloud account.",
109 "Cloud linked user is not installed for this environment.",
110 "Failed to sign cloud link JWT.",
111 "Cloud mint public key is not installed for this environment.",
112 "Cloud relay issuer is not installed for this environment.",
113 "Failed to sign cloud health JWT.",
114 "Failed to sign cloud mint JWT.",
115 ]);
116});
117
118describe("consumeCloudReplayGuards", () => {
119 it.effect("reports already-created guards as replay conflicts", () =>
120 Effect.gen(function* () {
121 const consumed = yield* consumeCloudReplayGuards({
122 secrets: makeSecretStore(() => Effect.fail(storeFailure("AlreadyExists"))),
123 names: ["cloud-jti", "cloud-nonce"],
124 value: new Uint8Array(),
125 });
126
127 expect(consumed).toBe(false);
128 }),
129 );
130
131 it.effect("preserves replay-store availability failures", () =>
132 Effect.gen(function* () {
133 const failure = storeFailure("PermissionDenied");
134 const error = yield* Effect.flip(
135 consumeCloudReplayGuards({
136 secrets: makeSecretStore(() => Effect.fail(failure)),
137 names: ["cloud-jti", "cloud-nonce"],
138 value: new Uint8Array(),
139 }),
140 );
141
142 expect(error).toBe(failure);
143 }),
144 );
145});
146
147describe("reconcileDesiredCloudLink", () => {
148 it.effect("requires stored CLI authorization without exposing an HTTP endpoint", () =>
149 Effect.gen(function* () {
150 const link = yield* CloudLink.CloudLink;
151 const error = yield* Effect.flip(link.reconcileDesiredLink("http://127.0.0.1:3774"));
152
153 expect(error._tag).toBe("CloudLinkAuthorizationMissingError");
154 }).pipe(
155 Effect.provide(CloudLink.layer),
156 Effect.provideService(HttpServer.HttpServer, idleHttpServer),
157 Effect.provideService(
158 ServerConfigModule.ServerConfig,
159 ServerConfigModule.ServerConfig.of({} as ServerConfigModule.ServerConfig["Service"]),
160 ),
161 Effect.provideService(
162 ServerSecretStore.ServerSecretStore,
163 makeSecretStore(unusedSecretStoreOperation),
164 ),
165 Effect.provideService(
166 ServerEnvironment.ServerEnvironment,
167 ServerEnvironment.ServerEnvironment.of({
168 getEnvironmentId: unusedSecretStoreOperation(),
169 getDescriptor: unusedSecretStoreOperation(),
170 }),
171 ),
172 Effect.provideService(
173 ManagedEndpointRuntime.CloudManagedEndpointRuntime,
174 ManagedEndpointRuntime.CloudManagedEndpointRuntime.of({
175 applyConfig: unusedSecretStoreOperation,
176 recoveryRequests: Stream.empty,
177 requestRecovery: () => Effect.void,
178 tunnelConnected: Stream.empty,
179 withLinkStateLock: (effect) => effect,
180 } satisfies ManagedEndpointRuntime.CloudManagedEndpointRuntime["Service"]),
181 ),
182 Effect.provideService(
183 EnvironmentAuth.EnvironmentAuth,
184 EnvironmentAuth.EnvironmentAuth.of({} as EnvironmentAuth.EnvironmentAuth["Service"]),
185 ),
186 Effect.provideService(
187 CliTokenManager.CloudCliTokenManager,
188 CliTokenManager.CloudCliTokenManager.of({
189 get: unusedSecretStoreOperation(),
190 getExisting: Effect.succeedNone,
191 hasCredential: unusedSecretStoreOperation(),
192 store: () => unusedSecretStoreOperation(),
193 clear: unusedSecretStoreOperation(),
194 }),
195 ),
196 Effect.provideService(
197 HttpClient.HttpClient,
198 HttpClient.make(() => unusedSecretStoreOperation()),
199 ),
200 Effect.provideService(AgentAwarenessRelay.AgentAwarenessRelay, idleAwarenessRelay),
201 Effect.provide(NodeServices.layer),
202 ),
203 );
204});
205
206describe("releaseManagedTunnelOnShutdown", () => {
207 const cliToken: CliTokenManager.PersistedToken = {
208 accessToken: "cli-access-token",
209 refreshToken: "cli-refresh-token",
210 expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
211 };
212
213 function makeMemorySecretStore(initial: Iterable<readonly [string, string]> = []) {
214 const values = new Map<string, Uint8Array>(
215 Array.from(initial, ([name, value]) => [name, new TextEncoder().encode(value)] as const),
216 );
217 const store: ServerSecretStore.ServerSecretStore["Service"] = {
218 get: (name) => Effect.sync(() => Option.fromNullishOr(values.get(name))),
219 set: (name, value) =>
220 Effect.sync(() => {
221 values.set(name, value);
222 }),
223 create: (name, value) =>
224 Effect.sync(() => {
225 values.set(name, value);
226 }),
227 getOrCreateRandom: unusedSecretStoreOperation,
228 remove: (name) =>
229 Effect.sync(() => {
230 values.delete(name);
231 }),
232 };
233 return { store, values };
234 }
235
236 interface ReleaseHarness {
237 readonly store: ServerSecretStore.ServerSecretStore["Service"];
238 readonly applyConfigCalls: Array<unknown>;
239 readonly requests: Array<HttpClientRequest.HttpClientRequest>;
240 readonly onRequest?: (request: HttpClientRequest.HttpClientRequest) => Effect.Effect<void>;
241 readonly respond?: () => Response;
242 readonly respondEffect?: Effect.Effect<Response>;
243 }
244
245 // Writes the launcher's durable state file into this test's baseDir with
246 // the launcher's own writer; the release reads it to detect an in-flight
247 // update handoff.
248 const writeLauncherState = (update: ServiceUpdateRecord) =>
249 Effect.gen(function* () {
250 const path = yield* Path.Path;
251 const config = yield* ServerConfigModule.ServerConfig;
252 const statePath = path.join(config.baseDir, "runtime", SERVICE_STATE_FILE);
253 yield* Effect.promise(() =>
254 writeServiceState(statePath, {
255 protocol: SERVICE_LAUNCHER_PROTOCOL,
256 activeVersion: "0.0.30",
257 update,
258 }),
259 );
260 });
261
262 // Writes the marker the desktop app leaves just before it stops its backend
263 // to install an update, and returns when it was written.
264 const writeDesktopUpdateRestartMarker = Effect.gen(function* () {
265 const fs = yield* FileSystem.FileSystem;
266 const path = yield* Path.Path;
267 const config = yield* ServerConfigModule.ServerConfig;
268 const runtimeDir = path.join(config.baseDir, "runtime");
269 const markerPath = path.join(runtimeDir, DESKTOP_UPDATE_RESTART_MARKER_FILE);
270 yield* fs.makeDirectory(runtimeDir, { recursive: true });
271 yield* fs.writeFileString(markerPath, "");
272 const { mtime } = yield* fs.stat(markerPath);
273 return Option.getOrThrow(mtime).getTime();
274 });
275
276 const provideReleaseHarness =
277 (harness: ReleaseHarness) =>
278 <A, E, R>(effect: Effect.Effect<A, E, R>) =>
279 effect.pipe(
280 Effect.provide(CloudLink.layer),
281 Effect.provideService(HttpServer.HttpServer, idleHttpServer),
282 Effect.provideService(ServerSecretStore.ServerSecretStore, harness.store),
283 Effect.provideService(AgentAwarenessRelay.AgentAwarenessRelay, idleAwarenessRelay),
284 Effect.provideService(
285 ServerEnvironment.ServerEnvironment,
286 ServerEnvironment.ServerEnvironment.of({
287 getEnvironmentId: Effect.succeed(EnvironmentId.make("env_123")),
288 getDescriptor: Effect.die("unused"),
289 }),
290 ),
291 Effect.provideService(
292 ManagedEndpointRuntime.CloudManagedEndpointRuntime,
293 ManagedEndpointRuntime.CloudManagedEndpointRuntime.of({
294 applyConfig: (config) =>
295 Effect.sync(() => {
296 harness.applyConfigCalls.push(config);
297 return config === null
298 ? ({
299 status: "disabled",
300 } satisfies ManagedEndpointRuntime.CloudManagedEndpointRuntimeStatus)
301 : ({
302 status: "running",
303 providerKind: "cloudflare_tunnel",
304 pid: 123,
305 } satisfies ManagedEndpointRuntime.CloudManagedEndpointRuntimeStatus);
306 }),
307 recoveryRequests: Stream.empty,
308 requestRecovery: () => Effect.void,
309 tunnelConnected: Stream.empty,
310 withLinkStateLock: (effect) => effect,
311 }),
312 ),
313 Effect.provideService(
314 EnvironmentAuth.EnvironmentAuth,
315 EnvironmentAuth.EnvironmentAuth.of({} as EnvironmentAuth.EnvironmentAuth["Service"]),
316 ),
317 Effect.provideService(
318 CliTokenManager.CloudCliTokenManager,
319 CliTokenManager.CloudCliTokenManager.of({
320 get: unusedSecretStoreOperation(),
321 getExisting: Effect.succeedSome(cliToken),
322 hasCredential: unusedSecretStoreOperation(),
323 store: () => unusedSecretStoreOperation(),
324 clear: unusedSecretStoreOperation(),
325 }),
326 ),
327 Effect.provideService(
328 HttpClient.HttpClient,
329 HttpClient.make((request) =>
330 Effect.sync(() => {
331 harness.requests.push(request);
332 }).pipe(
333 Effect.andThen(harness.onRequest?.(request) ?? Effect.void),
334 Effect.andThen(
335 harness.respondEffect ??
336 Effect.sync(() => (harness.respond ?? (() => Response.json({ ok: true })))()),
337 ),
338 Effect.map((response) => HttpClientResponse.fromWeb(request, response)),
339 ),
340 ),
341 ),
342 // The release consults the launcher state file under the configured
343 // baseDir, so every harness run gets a scoped temp baseDir.
344 Effect.provide(
345 ServerConfigModule.layerTest("/", { prefix: "t3-http-release-test-" }).pipe(
346 Layer.provideMerge(NodeServices.layer),
347 ),
348 ),
349 Effect.scoped,
350 );
351
352 // The persisted state of a CLI-managed link whose tunnel is releasable.
353 const managedLinkSecrets = [
354 [CLOUD_ENDPOINT_RUNTIME_CONFIG, "runtime-config"],
355 [CLOUD_ENDPOINT_CONFIRMED_ORIGIN, "confirmed-origin"],
356 [RELAY_URL_SECRET, "https://relay.example.test"],
357 [CLOUD_CLI_DESIRED_LINK_SECRET, "managed"],
358 ] as const;
359
360 it.effect("does not recreate a link that was unlinked while startup registration retried", () => {
361 const { store, values } = makeMemorySecretStore(managedLinkSecrets);
362 const applyConfigCalls: Array<unknown> = [];
363 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
364
365 return Effect.gen(function* () {
366 const link = yield* CloudLink.CloudLink;
367 // Registration started while this marker existed. Unlink removes it
368 // before startup receives the relay's final not_linked response.
369 values.delete(CLOUD_CLI_DESIRED_LINK_SECRET);
370
371 expect(yield* link.reconcileDesiredLinkIfStillDesired("http://127.0.0.1:3773")).toBeNull();
372 expect(requests).toEqual([]);
373 expect(applyConfigCalls).toEqual([]);
374 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
375 });
376
377 it.effect("stops the connector, releases the relay tunnel, and drops the dead token", () => {
378 const { store, values } = makeMemorySecretStore(managedLinkSecrets);
379 const applyConfigCalls: Array<unknown> = [];
380 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
381
382 return Effect.gen(function* () {
383 const link = yield* CloudLink.CloudLink;
384 const released = yield* link.releaseManagedTunnelOnShutdown();
385
386 expect(released).toBe(true);
387 expect(applyConfigCalls).toEqual([null]);
388 expect(requests).toHaveLength(1);
389 const request = requests[0]!;
390 expect(request.method).toBe("DELETE");
391 expect(request.url).toBe(
392 "https://relay.example.test/v1/client/environment-links/env_123/tunnel",
393 );
394 expect(request.headers.authorization).toBe("Bearer cli-access-token");
395 expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(false);
396 expect(values.has(CLOUD_ENDPOINT_CONFIRMED_ORIGIN)).toBe(false);
397 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
398 });
399
400 it.effect("does nothing for links without a stored managed tunnel runtime config", () => {
401 const { store } = makeMemorySecretStore();
402 const applyConfigCalls: Array<unknown> = [];
403 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
404
405 return Effect.gen(function* () {
406 const link = yield* CloudLink.CloudLink;
407 const released = yield* link.releaseManagedTunnelOnShutdown();
408
409 expect(released).toBe(false);
410 expect(applyConfigCalls).toEqual([]);
411 expect(requests).toEqual([]);
412 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
413 });
414
415 it.effect("leaves the tunnel of a web/mobile-installed link untouched", () => {
416 // A managed runtime config without a CLI-desired link: the environment was
417 // linked by a web/mobile client, and nothing re-provisions the tunnel on
418 // the next boot, so shutdown must not release it.
419 const { store, values } = makeMemorySecretStore([
420 [CLOUD_ENDPOINT_RUNTIME_CONFIG, "runtime-config"],
421 [RELAY_URL_SECRET, "https://relay.example.test"],
422 ]);
423 const applyConfigCalls: Array<unknown> = [];
424 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
425
426 return Effect.gen(function* () {
427 const link = yield* CloudLink.CloudLink;
428 const released = yield* link.releaseManagedTunnelOnShutdown();
429
430 expect(released).toBe(false);
431 expect(applyConfigCalls).toEqual([]);
432 expect(requests).toEqual([]);
433 expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true);
434 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
435 });
436
437 it.effect("leaves the tunnel of a publish-only desired link untouched", () => {
438 const { store, values } = makeMemorySecretStore([
439 [CLOUD_ENDPOINT_RUNTIME_CONFIG, "runtime-config"],
440 [RELAY_URL_SECRET, "https://relay.example.test"],
441 [CLOUD_CLI_DESIRED_LINK_SECRET, "publish_only"],
442 ]);
443 const applyConfigCalls: Array<unknown> = [];
444 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
445
446 return Effect.gen(function* () {
447 const link = yield* CloudLink.CloudLink;
448 const released = yield* link.releaseManagedTunnelOnShutdown();
449
450 expect(released).toBe(false);
451 expect(applyConfigCalls).toEqual([]);
452 expect(requests).toEqual([]);
453 expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true);
454 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
455 });
456
457 it.effect("keeps the tunnel when shutdown hands off to a pending update", () => {
458 const { store, values } = makeMemorySecretStore(managedLinkSecrets);
459 const applyConfigCalls: Array<unknown> = [];
460 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
461
462 return Effect.gen(function* () {
463 const link = yield* CloudLink.CloudLink;
464 yield* writeLauncherState({
465 id: "update-1",
466 fromVersion: "0.0.30",
467 targetVersion: "0.0.31",
468 dbPath: "/tmp/state.sqlite",
469 status: "pending",
470 });
471
472 const released = yield* link.releaseManagedTunnelOnShutdown();
473
474 // The launcher restarts a server immediately, so the tunnel is not
475 // orphaned; keeping it avoids the hostname route re-propagation that
476 // dominates update downtime. The stored config must survive so the
477 // next boot respawns the connector against the same tunnel.
478 expect(released).toBe(false);
479 expect(applyConfigCalls).toEqual([]);
480 expect(requests).toEqual([]);
481 expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true);
482 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
483 });
484
485 it.effect("keeps the tunnel once when the desktop app restarts it for an update", () => {
486 const { store, values } = makeMemorySecretStore(managedLinkSecrets);
487 const applyConfigCalls: Array<unknown> = [];
488 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
489
490 return Effect.gen(function* () {
491 const link = yield* CloudLink.CloudLink;
492 yield* TestClock.setTime(yield* writeDesktopUpdateRestartMarker);
493
494 expect(yield* link.releaseManagedTunnelOnShutdown()).toBe(false);
495 expect(requests).toEqual([]);
496 expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true);
497
498 // The shutdown consumed the marker, so a later quit releases the tunnel.
499 expect(yield* link.releaseManagedTunnelOnShutdown()).toBe(true);
500 expect(requests).toHaveLength(1);
501 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
502 });
503
504 it.effect("releases the tunnel when the desktop update marker is stale", () => {
505 const { store } = makeMemorySecretStore(managedLinkSecrets);
506 const applyConfigCalls: Array<unknown> = [];
507 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
508
509 return Effect.gen(function* () {
510 const link = yield* CloudLink.CloudLink;
511 const writtenAt = yield* writeDesktopUpdateRestartMarker;
512 yield* TestClock.setTime(writtenAt + Duration.toMillis(Duration.minutes(2)));
513
514 expect(yield* link.releaseManagedTunnelOnShutdown()).toBe(true);
515 expect(requests).toHaveLength(1);
516 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
517 });
518
519 it.effect("still releases a pending update when the launcher is stopping", () => {
520 // `t3 service uninstall` or `systemctl stop` during the pending window:
521 // the launcher writes its stop marker before signalling the child, so no
522 // replacement server is coming and the tunnel must not be kept.
523 const { store, values } = makeMemorySecretStore(managedLinkSecrets);
524 const applyConfigCalls: Array<unknown> = [];
525 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
526
527 return Effect.gen(function* () {
528 const link = yield* CloudLink.CloudLink;
529 yield* writeLauncherState({
530 id: "update-1",
531 fromVersion: "0.0.30",
532 targetVersion: "0.0.31",
533 dbPath: "/tmp/state.sqlite",
534 status: "pending",
535 });
536 const fs = yield* FileSystem.FileSystem;
537 const path = yield* Path.Path;
538 const config = yield* ServerConfigModule.ServerConfig;
539 yield* fs.writeFileString(path.join(config.baseDir, "runtime", SERVICE_STOP_MARKER_FILE), "");
540
541 expect(yield* pendingServiceUpdateExists).toBe(true);
542 const released = yield* link.releaseManagedTunnelOnShutdown();
543
544 expect(released).toBe(true);
545 expect(requests).toHaveLength(1);
546 expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(false);
547 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
548 });
549
550 it.effect("still releases when the recorded update already settled", () => {
551 const { store, values } = makeMemorySecretStore(managedLinkSecrets);
552 const applyConfigCalls: Array<unknown> = [];
553 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
554
555 return Effect.gen(function* () {
556 const link = yield* CloudLink.CloudLink;
557 yield* writeLauncherState({
558 id: "update-1",
559 fromVersion: "0.0.30",
560 targetVersion: "0.0.31",
561 status: "committed",
562 });
563
564 const released = yield* link.releaseManagedTunnelOnShutdown();
565
566 expect(released).toBe(true);
567 expect(requests).toHaveLength(1);
568 expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(false);
569 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
570 });
571
572 it.effect("keeps a runtime config that a fast restart replaced mid-release", () => {
573 const { store, values } = makeMemorySecretStore(managedLinkSecrets);
574 const applyConfigCalls: Array<unknown> = [];
575 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
576 const freshConfig = new TextEncoder().encode("fresh-runtime-config");
577
578 return Effect.gen(function* () {
579 const link = yield* CloudLink.CloudLink;
580 const released = yield* link.releaseManagedTunnelOnShutdown();
581
582 expect(released).toBe(true);
583 // The finalizer only drops the config it released; the one written by
584 // the restarted process while the DELETE was in flight stays.
585 expect(values.get(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(freshConfig);
586 }).pipe(
587 provideReleaseHarness({
588 store,
589 applyConfigCalls,
590 requests,
591 respond: () => {
592 // A restarted process reconciled and stored a fresh connector config
593 // while this shutdown's release request was in flight.
594 values.set(CLOUD_ENDPOINT_RUNTIME_CONFIG, freshConfig);
595 return Response.json({ ok: true });
596 },
597 }),
598 );
599 });
600
601 it.effect("keeps the stored connector token when the relay skipped the release", () => {
602 // ok:false means a concurrent provision owns the recorded tunnel, so the
603 // stored runtime config (possibly freshly written by that provision) must
604 // survive.
605 const { store, values } = makeMemorySecretStore(managedLinkSecrets);
606 const applyConfigCalls: Array<unknown> = [];
607 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
608
609 return Effect.gen(function* () {
610 const link = yield* CloudLink.CloudLink;
611 const released = yield* link.releaseManagedTunnelOnShutdown();
612
613 expect(released).toBe(false);
614 expect(requests).toHaveLength(1);
615 expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true);
616 }).pipe(
617 provideReleaseHarness({
618 store,
619 applyConfigCalls,
620 requests,
621 respond: () => Response.json({ ok: false }),
622 }),
623 );
624 });
625
626 it.effect("keeps the stored connector token when the relay release request fails", () => {
627 const { store, values } = makeMemorySecretStore(managedLinkSecrets);
628 const applyConfigCalls: Array<unknown> = [];
629 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
630
631 return Effect.gen(function* () {
632 const link = yield* CloudLink.CloudLink;
633 const result = yield* Effect.result(link.releaseManagedTunnelOnShutdown());
634
635 expect(result._tag).toBe("Failure");
636 expect(requests).toHaveLength(1);
637 // The tunnel still exists, so the stored token stays valid across the
638 // restart and the next boot can bring the connector back immediately.
639 expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true);
640 }).pipe(
641 provideReleaseHarness({
642 store,
643 applyConfigCalls,
644 requests,
645 respond: () => Response.json({ ok: false }, { status: 503 }),
646 }),
647 );
648 });
649
650 it.effect("registers an existing tunnel and starts the confirmed connector", () => {
651 const { store } = makeMemorySecretStore([
652 [
653 CLOUD_ENDPOINT_RUNTIME_CONFIG,
654 '{"providerKind":"cloudflare_tunnel","connectorToken":"existing-token","tunnelId":"existing-tunnel"}',
655 ],
656 [RELAY_URL_SECRET, "https://relay.example.test"],
657 [CLOUD_LINKED_USER_ID, "user-123"],
658 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"],
659 ]);
660 const applyConfigCalls: Array<unknown> = [];
661 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
662
663 return Effect.gen(function* () {
664 const link = yield* CloudLink.CloudLink;
665 expect(yield* link.registerManagedTunnelRecovery("http://127.0.0.1:3773")).toMatchObject({
666 status: "ready",
667 });
668 expect(requests).toHaveLength(1);
669 expect(requests[0]?.method).toBe("POST");
670 expect(requests[0]?.url).toBe(
671 "https://relay.example.test/v1/environments/env_123/tunnel/recovery",
672 );
673 expect(requests[0]?.headers.authorization).toBe("Bearer environment-credential");
674 const body = requests[0]?.body;
675 expect(body?._tag).toBe("Uint8Array");
676 if (body?._tag === "Uint8Array") {
677 expect(
678 yield* decodeManagedTunnelRecoveryRegistration(new TextDecoder().decode(body.body)),
679 ).toMatchObject({
680 cloudUserId: "user-123",
681 tunnelId: "existing-tunnel",
682 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
683 });
684 }
685 expect(applyConfigCalls).toHaveLength(1);
686 }).pipe(
687 provideReleaseHarness({
688 store,
689 applyConfigCalls,
690 requests,
691 respond: () => Response.json({ status: "ready" }),
692 }),
693 );
694 });
695
696 it.effect("reconciles a changed port after a relay outage outlasts the startup fallback", () => {
697 const config = {
698 providerKind: "cloudflare_tunnel" as const,
699 connectorToken: "existing-token",
700 tunnelId: "existing-tunnel",
701 };
702 const { store } = makeMemorySecretStore([
703 [CLOUD_ENDPOINT_RUNTIME_CONFIG, JSON.stringify(config)],
704 [
705 CLOUD_ENDPOINT_CONFIRMED_ORIGIN,
706 JSON.stringify({
707 config,
708 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
709 }),
710 ],
711 [RELAY_URL_SECRET, "https://relay.example.test"],
712 [CLOUD_LINKED_USER_ID, "user-123"],
713 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"],
714 ]);
715 const applyConfigCalls: Array<unknown> = [];
716 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
717 let relayAvailable = false;
718 const localOrigin = "http://127.0.0.1:4884";
719
720 return Effect.gen(function* () {
721 const link = yield* CloudLink.CloudLink;
722 const fallbackStarted = yield* Deferred.make<void>();
723 const firstFailure = yield* Deferred.make<void>();
724 expect(yield* link.startManagedTunnelIfOriginConfirmed(localOrigin)).toBe(false);
725 const registration = yield* Effect.forkChild(
726 retryManagedTunnelRegistration(
727 link
728 .registerManagedTunnelRecovery(localOrigin)
729 .pipe(Effect.tapError(() => Deferred.succeed(firstFailure, undefined))),
730 CloudLink.shouldRetryCloudLink,
731 link
732 .startManagedTunnelIfOriginConfirmed(localOrigin, {
733 requireConfirmedOrigin: false,
734 })
735 .pipe(
736 Effect.orDie,
737 Effect.tap((started) => {
738 expect(started).toBe(true);
739 return Deferred.succeed(fallbackStarted, undefined);
740 }),
741 Effect.asVoid,
742 ),
743 ),
744 { startImmediately: true },
745 );
746 yield* Deferred.await(firstFailure);
747 yield* TestClock.adjust("15 minutes");
748 yield* Effect.raceFirst(
749 Deferred.await(fallbackStarted),
750 Fiber.join(registration).pipe(
751 Effect.andThen(Effect.die("Registration ended before starting the fallback")),
752 ),
753 );
754 expect(applyConfigCalls).toEqual([config]);
755 const attemptsBeforeRecovery = requests.length;
756
757 relayAvailable = true;
758 yield* TestClock.adjust("1 minute");
759 expect(yield* Fiber.join(registration)).toMatchObject({ status: "ready" });
760 expect(requests.length).toBeGreaterThan(attemptsBeforeRecovery);
761 const marker = yield* store.get(CLOUD_ENDPOINT_CONFIRMED_ORIGIN);
762 expect(Option.isSome(marker)).toBe(true);
763 if (Option.isSome(marker)) {
764 expect(
765 Option.getOrThrow(decodeConfirmedOrigin(new TextDecoder().decode(marker.value))),
766 ).toEqual({
767 config,
768 origin: { localHttpHost: "127.0.0.1", localHttpPort: 4884 },
769 });
770 }
771 }).pipe(
772 provideReleaseHarness({
773 store,
774 applyConfigCalls,
775 requests,
776 respond: () =>
777 relayAvailable
778 ? Response.json({ status: "ready" })
779 : Response.json({ message: "relay unavailable" }, { status: 503 }),
780 }),
781 );
782 });
783
784 it.effect(
785 "starts a connector with a marker for the current origin without contacting relay",
786 () => {
787 const configJson =
788 '{"providerKind":"cloudflare_tunnel","connectorToken":"existing-token","tunnelId":"existing-tunnel"}';
789 const config = {
790 providerKind: "cloudflare_tunnel" as const,
791 connectorToken: "existing-token",
792 tunnelId: "existing-tunnel",
793 };
794 const { store } = makeMemorySecretStore([
795 [CLOUD_ENDPOINT_RUNTIME_CONFIG, configJson],
796 [
797 CLOUD_ENDPOINT_CONFIRMED_ORIGIN,
798 `{"config":${configJson},"origin":{"localHttpHost":"127.0.0.1","localHttpPort":3773}}`,
799 ],
800 ]);
801 const applyConfigCalls: Array<unknown> = [];
802 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
803
804 return Effect.gen(function* () {
805 const link = yield* CloudLink.CloudLink;
806 expect(yield* link.startManagedTunnelIfOriginConfirmed("http://127.0.0.1:3773")).toBe(true);
807 expect(applyConfigCalls).toEqual([config]);
808 expect(requests).toEqual([]);
809 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
810 },
811 );
812
813 it.effect.each([
814 { name: "missing", marker: undefined, origin: "http://127.0.0.1:3773" },
815 {
816 name: "stale",
817 marker:
818 '{"config":{"providerKind":"cloudflare_tunnel","connectorToken":"existing-token","tunnelId":"existing-tunnel"},"origin":{"localHttpHost":"127.0.0.1","localHttpPort":3773}}',
819 origin: "http://127.0.0.1:4884",
820 },
821 ])("does not start a connector with a $name origin marker", ({ marker, origin }) => {
822 const entries: Array<readonly [string, string]> = [
823 [
824 CLOUD_ENDPOINT_RUNTIME_CONFIG,
825 '{"providerKind":"cloudflare_tunnel","connectorToken":"existing-token","tunnelId":"existing-tunnel"}',
826 ],
827 ];
828 if (marker !== undefined) entries.push([CLOUD_ENDPOINT_CONFIRMED_ORIGIN, marker]);
829 const { store } = makeMemorySecretStore(entries);
830 const applyConfigCalls: Array<unknown> = [];
831 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
832
833 return Effect.gen(function* () {
834 const link = yield* CloudLink.CloudLink;
835 expect(yield* link.startManagedTunnelIfOriginConfirmed(origin)).toBe(false);
836 expect(applyConfigCalls).toEqual([]);
837 expect(requests).toEqual([]);
838 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
839 });
840
841 it.effect(
842 "starts the stored connector without a marker when confirmation is not required",
843 () => {
844 const config = {
845 providerKind: "cloudflare_tunnel" as const,
846 connectorToken: "existing-token",
847 tunnelId: "existing-tunnel",
848 };
849 const { store } = makeMemorySecretStore([
850 [CLOUD_ENDPOINT_RUNTIME_CONFIG, JSON.stringify(config)],
851 ]);
852 const applyConfigCalls: Array<unknown> = [];
853 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
854
855 return Effect.gen(function* () {
856 const link = yield* CloudLink.CloudLink;
857 expect(
858 yield* link.startManagedTunnelIfOriginConfirmed("http://127.0.0.1:3773", {
859 requireConfirmedOrigin: false,
860 }),
861 ).toBe(true);
862 expect(applyConfigCalls).toEqual([config]);
863 expect(requests).toEqual([]);
864 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
865 },
866 );
867
868 it.effect.each(["replaced", "removed"] as const)(
869 "does not activate a tunnel when its runtime config is %s during registration",
870 (mutation) => {
871 const originalConfig =
872 '{"providerKind":"cloudflare_tunnel","connectorToken":"existing-token","tunnelId":"existing-tunnel"}';
873 const { store, values } = makeMemorySecretStore([
874 [CLOUD_ENDPOINT_RUNTIME_CONFIG, originalConfig],
875 [RELAY_URL_SECRET, "https://relay.example.test"],
876 [CLOUD_LINKED_USER_ID, "user-123"],
877 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"],
878 ]);
879 const applyConfigCalls: Array<unknown> = [];
880 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
881
882 return Effect.gen(function* () {
883 const link = yield* CloudLink.CloudLink;
884 expect(yield* link.registerManagedTunnelRecovery("http://127.0.0.1:3773")).toEqual({
885 status: "superseded",
886 });
887 expect(applyConfigCalls).toEqual([]);
888 expect(values.has(CLOUD_ENDPOINT_CONFIRMED_ORIGIN)).toBe(false);
889 }).pipe(
890 provideReleaseHarness({
891 store,
892 applyConfigCalls,
893 requests,
894 respond: () => {
895 if (mutation === "replaced") {
896 values.set(
897 CLOUD_ENDPOINT_RUNTIME_CONFIG,
898 new TextEncoder().encode(
899 '{"providerKind":"cloudflare_tunnel","connectorToken":"fresh-token","tunnelId":"fresh-tunnel"}',
900 ),
901 );
902 } else {
903 values.delete(CLOUD_ENDPOINT_RUNTIME_CONFIG);
904 }
905 return Response.json({ status: "ready" });
906 },
907 }),
908 );
909 },
910 );
911
912 it.effect("requests startup recovery for a legacy config without a recorded tunnel ID", () => {
913 const { store } = makeMemorySecretStore([
914 [
915 CLOUD_ENDPOINT_RUNTIME_CONFIG,
916 '{"providerKind":"cloudflare_tunnel","connectorToken":"token"}',
917 ],
918 [RELAY_URL_SECRET, "https://relay.example.test"],
919 [CLOUD_LINKED_USER_ID, "user-123"],
920 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"],
921 ]);
922 const applyConfigCalls: Array<unknown> = [];
923 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
924
925 return Effect.gen(function* () {
926 const link = yield* CloudLink.CloudLink;
927 const registration = yield* link.registerManagedTunnelRecovery("http://127.0.0.1:3773");
928 expect(registration).toEqual({
929 status: "recovery_required",
930 config: { providerKind: "cloudflare_tunnel", connectorToken: "token" },
931 });
932 expect(
933 managedTunnelStartupAction({
934 wantsCliLink: false,
935 registration,
936 }),
937 ).toEqual({
938 action: "request_recovery",
939 config: { providerKind: "cloudflare_tunnel", connectorToken: "token" },
940 });
941 expect(requests).toEqual([]);
942 expect(applyConfigCalls).toEqual([]);
943 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
944 });
945
946 it.effect("recovers a web-linked tunnel with its environment credential", () => {
947 const oldConfig =
948 '{"providerKind":"cloudflare_tunnel","connectorToken":"old-token","tunnelId":"old-tunnel"}';
949 const nextConfig = {
950 providerKind: "cloudflare_tunnel",
951 connectorToken: "new-token",
952 tunnelId: "new-tunnel",
953 } as const;
954 const { store, values } = makeMemorySecretStore([
955 [CLOUD_ENDPOINT_RUNTIME_CONFIG, oldConfig],
956 [RELAY_URL_SECRET, "https://relay.example.test"],
957 [CLOUD_LINKED_USER_ID, "user-123"],
958 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"],
959 ]);
960 const applyConfigCalls: Array<unknown> = [];
961 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
962
963 return Effect.gen(function* () {
964 const link = yield* CloudLink.CloudLink;
965 expect(yield* link.recoverManagedTunnel("http://127.0.0.1:3773")).toBe(true);
966 expect(requests).toHaveLength(1);
967 expect(requests[0]?.method).toBe("POST");
968 expect(requests[0]?.url).toBe("https://relay.example.test/v1/environments/env_123/tunnel");
969 expect(requests[0]?.headers.authorization).toBe("Bearer environment-credential");
970 expect(applyConfigCalls).toEqual([nextConfig]);
971 expect(
972 Option.getOrNull(
973 decodeRuntimeConfig(new TextDecoder().decode(values.get(CLOUD_ENDPOINT_RUNTIME_CONFIG))),
974 ),
975 ).toEqual(nextConfig);
976 }).pipe(
977 provideReleaseHarness({
978 store,
979 applyConfigCalls,
980 requests,
981 respond: () =>
982 Response.json({
983 endpoint: {
984 httpBaseUrl: "https://environment.example.test/",
985 wsBaseUrl: "wss://environment.example.test/ws",
986 providerKind: "cloudflare_tunnel",
987 },
988 endpointRuntime: nextConfig,
989 }),
990 }),
991 );
992 });
993
994 it.effect("allows managed tunnel provisioning to take longer than ten seconds", () =>
995 Effect.gen(function* () {
996 const oldConfig =
997 '{"providerKind":"cloudflare_tunnel","connectorToken":"old-token","tunnelId":"old-tunnel"}';
998 const nextConfig = {
999 providerKind: "cloudflare_tunnel" as const,
1000 connectorToken: "new-token",
1001 tunnelId: "new-tunnel",
1002 };
1003 const { store } = makeMemorySecretStore([
1004 [CLOUD_ENDPOINT_RUNTIME_CONFIG, oldConfig],
1005 [RELAY_URL_SECRET, "https://relay.example.test"],
1006 [CLOUD_LINKED_USER_ID, "user-123"],
1007 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"],
1008 ]);
1009 const applyConfigCalls: Array<unknown> = [];
1010 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
1011 const requestStarted = yield* Deferred.make<void>();
1012 const response = yield* Deferred.make<Response>();
1013 const recovery = yield* CloudLink.CloudLink.use((link) =>
1014 link.recoverManagedTunnel("http://127.0.0.1:3773"),
1015 ).pipe(
1016 provideReleaseHarness({
1017 store,
1018 applyConfigCalls,
1019 requests,
1020 onRequest: () => Deferred.succeed(requestStarted, undefined),
1021 respondEffect: Deferred.await(response),
1022 }),
1023 Effect.forkChild({ startImmediately: true }),
1024 );
1025
1026 yield* Deferred.await(requestStarted);
1027 expect(requests).toHaveLength(1);
1028 yield* TestClock.adjust("11 seconds");
1029 yield* Effect.yieldNow;
1030 yield* Deferred.succeed(
1031 response,
1032 Response.json({
1033 endpoint: {
1034 httpBaseUrl: "https://environment.example.test/",
1035 wsBaseUrl: "wss://environment.example.test/ws",
1036 providerKind: "cloudflare_tunnel",
1037 },
1038 endpointRuntime: nextConfig,
1039 }),
1040 );
1041
1042 expect(yield* Fiber.join(recovery)).toBe(true);
1043 expect(requests).toHaveLength(1);
1044 expect(applyConfigCalls).toEqual([nextConfig]);
1045 }),
1046 );
1047
1048 it.effect("does not recover an environment without a managed tunnel credential", () => {
1049 const { store } = makeMemorySecretStore([
1050 [CLOUD_ENDPOINT_RUNTIME_CONFIG, "old-config"],
1051 [RELAY_URL_SECRET, "https://relay.example.test"],
1052 ]);
1053 const applyConfigCalls: Array<unknown> = [];
1054 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
1055
1056 return Effect.gen(function* () {
1057 const link = yield* CloudLink.CloudLink;
1058 expect(yield* link.recoverManagedTunnel("http://127.0.0.1:3773")).toBe(false);
1059 expect(applyConfigCalls).toEqual([]);
1060 expect(requests).toEqual([]);
1061 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
1062 });
1063
1064 it.effect("ignores recovery requests for a tunnel that has already been replaced", () => {
1065 const { store } = makeMemorySecretStore([
1066 [
1067 CLOUD_ENDPOINT_RUNTIME_CONFIG,
1068 '{"providerKind":"cloudflare_tunnel","connectorToken":"current-token","tunnelId":"current-tunnel"}',
1069 ],
1070 [RELAY_URL_SECRET, "https://relay.example.test"],
1071 [CLOUD_LINKED_USER_ID, "user-123"],
1072 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"],
1073 ]);
1074 const applyConfigCalls: Array<unknown> = [];
1075 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
1076
1077 return Effect.gen(function* () {
1078 const link = yield* CloudLink.CloudLink;
1079 expect(
1080 yield* link.recoverManagedTunnel("http://127.0.0.1:3773", {
1081 providerKind: "cloudflare_tunnel",
1082 connectorToken: "old-token",
1083 tunnelId: "old-tunnel",
1084 }),
1085 ).toBe(false);
1086 expect(requests).toEqual([]);
1087 expect(applyConfigCalls).toEqual([]);
1088 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
1089 });
1090
1091 it.effect.each([
1092 { status: 401, rejection: "unauthorized" },
1093 { status: 403, rejection: "forbidden" },
1094 { status: 409, rejection: "rejected" },
1095 ])("preserves a permanent $status relay recovery failure", ({ status, rejection }) => {
1096 const { store } = makeMemorySecretStore([
1097 [CLOUD_ENDPOINT_RUNTIME_CONFIG, "old-config"],
1098 [RELAY_URL_SECRET, "https://relay.example.test"],
1099 [CLOUD_LINKED_USER_ID, "user-123"],
1100 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"],
1101 ]);
1102 const applyConfigCalls: Array<unknown> = [];
1103 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
1104
1105 return Effect.gen(function* () {
1106 const link = yield* CloudLink.CloudLink;
1107 const error = yield* Effect.flip(link.recoverManagedTunnel("http://127.0.0.1:3773"));
1108
1109 expect(error).toMatchObject({ _tag: "RelayRequestError", rejection });
1110 expect(CloudLink.shouldRetryCloudLink(error)).toBe(false);
1111 expect(requests).toHaveLength(1);
1112 expect(applyConfigCalls).toEqual([]);
1113 }).pipe(
1114 provideReleaseHarness({
1115 store,
1116 applyConfigCalls,
1117 requests,
1118 respond: () => Response.json({}, { status }),
1119 }),
1120 );
1121 });
1122
1123 it.effect("keeps a tunnel configuration replaced during recovery", () => {
1124 const { store, values } = makeMemorySecretStore([
1125 [CLOUD_ENDPOINT_RUNTIME_CONFIG, "old-config"],
1126 [RELAY_URL_SECRET, "https://relay.example.test"],
1127 [CLOUD_LINKED_USER_ID, "user-123"],
1128 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"],
1129 ]);
1130 const applyConfigCalls: Array<unknown> = [];
1131 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
1132 const freshConfig = new TextEncoder().encode("fresh-config");
1133
1134 return Effect.gen(function* () {
1135 const link = yield* CloudLink.CloudLink;
1136 expect(yield* link.recoverManagedTunnel("http://127.0.0.1:3773")).toBe(false);
1137 expect(values.get(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(freshConfig);
1138 expect(applyConfigCalls).toEqual([]);
1139 }).pipe(
1140 provideReleaseHarness({
1141 store,
1142 applyConfigCalls,
1143 requests,
1144 respond: () => {
1145 values.set(CLOUD_ENDPOINT_RUNTIME_CONFIG, freshConfig);
1146 return Response.json({
1147 endpoint: {
1148 httpBaseUrl: "https://environment.example.test/",
1149 wsBaseUrl: "wss://environment.example.test/ws",
1150 providerKind: "cloudflare_tunnel",
1151 },
1152 endpointRuntime: {
1153 providerKind: "cloudflare_tunnel",
1154 connectorToken: "replacement-token",
1155 },
1156 });
1157 },
1158 }),
1159 );
1160 });
1161});