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

CloudLink.test.ts

269 lines10.7 KB

1import { EnvironmentId } from "@t3tools/contracts";
2import { assert, it } from "@effect/vitest";
3import * as Effect from "effect/Effect";
4import * as Fiber from "effect/Fiber";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import * as FetchHttpClient from "effect/http/FetchHttpClient";
8import { HttpClient, HttpServer } from "effect/http";
9import * as NetAddress from "effect/net/NetAddress";
10import * as NodeServices from "@effect/platform-node/NodeServices";
11​
12import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
13import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
14import * as ServerConfig from "../config.ts";
15import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
16import * as AgentAwarenessRelay from "../relay/AgentAwarenessRelay.ts";
17import * as CliTokenManager from "./CliTokenManager.ts";
18import * as CloudLink from "./CloudLink.ts";
19import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
20import {
21 HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET,
22 PUBLISH_AGENT_ACTIVITY_SECRET,
23 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
24 RELAY_URL_SECRET,
25} from "./config.ts";
26​
27const encode = (value: string) => new TextEncoder().encode(value);
28​
29const withService = <A, E>(
30 options: {
31 readonly failHoldWrite?: boolean;
32 readonly failActivityWrite?: boolean;
33 readonly relayFails?: boolean;
34 readonly failActivityRead?: boolean;
35 readonly failHoldRead?: boolean;
36 readonly holdFirstRelayCall?: {
37 readonly started: () => void;
38 readonly released: Promise<void>;
39 };
40 },
41 body: (input: {
42 readonly preferences: { readonly update: CloudLink.CloudLink["Service"]["updatePreferences"] };
43 readonly stored: Map<string, Uint8Array>;
44 readonly relayCalls: Array<boolean>;
45 }) => Effect.Effect<A, E, never>,
46) =>
47 Effect.gen(function* () {
48 const stored = new Map<string, Uint8Array>([
49 [RELAY_URL_SECRET, encode("https://relay.test")],
50 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, encode("credential")],
51 [HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET, encode("false")],
52 [PUBLISH_AGENT_ACTIVITY_SECRET, encode("false")],
53 ]);
54 const relayCalls: Array<boolean> = [];
55 const fetch: typeof globalThis.fetch = Object.assign(
56 (_input: Parameters<typeof globalThis.fetch>[0], init?: RequestInit) => {
57 const payload = JSON.parse(String(init?.body)) as { holdWebhooksWhileOffline: boolean };
58 relayCalls.push(payload.holdWebhooksWhileOffline);
59 if (relayCalls.length === 1 && options.holdFirstRelayCall) {
60 options.holdFirstRelayCall.started();
61 return options.holdFirstRelayCall.released.then(() => Response.json(payload));
62 }
63 return options.relayFails
64 ? Promise.resolve(new Response("unavailable", { status: 503 }))
65 : Promise.resolve(Response.json(payload));
66 },
67 { preconnect: () => {} },
68 );
69 const layerDependencies = Layer.mergeAll(
70 Layer.mock(ServerSecretStore.ServerSecretStore)({
71 get: (name) =>
72 (options.failActivityRead && name === PUBLISH_AGENT_ACTIVITY_SECRET) ||
73 (options.failHoldRead && name === HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET)
74 ? Effect.fail(
75 new ServerSecretStore.SecretStoreReadError({
76 resource: name,
77 cause: new Error("busy"),
78 }),
79 )
80 : Effect.succeed(Option.fromNullishOr(stored.get(name))),
81 set: (name, value) =>
82 (options.failHoldWrite && name === HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET) ||
83 (options.failActivityWrite && name === PUBLISH_AGENT_ACTIVITY_SECRET)
84 ? Effect.fail(
85 new ServerSecretStore.SecretStorePersistError({
86 resource: name,
87 cause: new Error("read-only"),
88 }),
89 )
90 : Effect.sync(() => void stored.set(name, value)),
91 }),
92 Layer.mock(ServerEnvironment.ServerEnvironment)({
93 getEnvironmentId: Effect.succeed(EnvironmentId.make("environment-1")),
94 }),
95 Layer.mock(AgentAwarenessRelay.AgentAwarenessRelay)({ requestCatchUp: () => Effect.void }),
96 Layer.mock(ManagedEndpointRuntime.CloudManagedEndpointRuntime)({}),
97 Layer.mock(EnvironmentAuth.EnvironmentAuth)({}),
98 Layer.mock(CliTokenManager.CloudCliTokenManager)({}),
99 Layer.mock(HttpServer.HttpServer)({
100 address: NetAddress.inetAddressFromIpStringUnsafe("127.0.0.1", 3773),
101 }),
102 Layer.mock(ServerConfig.ServerConfig)({} as ServerConfig.ServerConfig["Service"]),
103 Layer.succeed(
104 HttpClient.HttpClient,
105 HttpClient.make(() => Effect.die("unused")),
106 ),
107 NodeServices.layer,
108 );
109 return yield* Effect.gen(function* () {
110 const link = yield* CloudLink.CloudLink;
111 return yield* body({ preferences: { update: link.updatePreferences }, stored, relayCalls });
112 }).pipe(
113 Effect.provide(CloudLink.layer.pipe(Layer.provide(layerDependencies))),
114 Effect.provideService(FetchHttpClient.Fetch, fetch),
115 );
116 });
117​
118it.effect("tells the relay before saving the hold setting locally", () =>
119 withService({}, ({ preferences, stored, relayCalls }) =>
120 Effect.gen(function* () {
121 yield* preferences.update({ publishAgentActivity: true, holdWebhooksWhileOffline: true });
122 assert.deepEqual(relayCalls, [true]);
123 assert.equal(
124 new TextDecoder().decode(stored.get(HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET)),
125 "true",
126 );
127 }),
128 ),
129);
130​
131it.effect("puts the relay back when the local save fails", () =>
132 withService({ failHoldWrite: true }, ({ preferences, stored, relayCalls }) =>
133 Effect.gen(function* () {
134 const error = yield* preferences
135 .update({ publishAgentActivity: true, holdWebhooksWhileOffline: true })
136 .pipe(Effect.flip);
137 assert.deepInclude(error, {
138 _tag: "CloudLinkInternalError",
139 operation: "persist-preferences",
140 });
141 assert.deepEqual(relayCalls, [true, false]);
142 assert.equal(
143 new TextDecoder().decode(stored.get(HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET)),
144 "false",
145 );
146 }),
147 ),
148);
149​
150it.effect("leaves the relay untouched when the activity setting can't be saved", () =>
151 withService({ failActivityWrite: true }, ({ preferences, stored, relayCalls }) =>
152 Effect.gen(function* () {
153 const error = yield* preferences
154 .update({ publishAgentActivity: true, holdWebhooksWhileOffline: true })
155 .pipe(Effect.flip);
156 assert.deepInclude(error, {
157 _tag: "CloudLinkInternalError",
158 operation: "persist-preferences",
159 });
160 assert.deepEqual(relayCalls, []);
161 assert.equal(
162 new TextDecoder().decode(stored.get(HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET)),
163 "false",
164 );
165 }),
166 ),
167);
168​
169it.effect("keeps both settings unchanged when the relay refuses the hold change", () =>
170 withService({ relayFails: true }, ({ preferences, stored }) =>
171 Effect.gen(function* () {
172 yield* preferences
173 .update({ publishAgentActivity: true, holdWebhooksWhileOffline: true })
174 .pipe(Effect.flip);
175 assert.equal(new TextDecoder().decode(stored.get(PUBLISH_AGENT_ACTIVITY_SECRET)), "false");
176 assert.equal(
177 new TextDecoder().decode(stored.get(HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET)),
178 "false",
179 );
180 }),
181 ),
182);
183​
184it.effect("changes nothing when the current activity setting can't be read", () =>
185 withService({ failActivityRead: true, relayFails: true }, ({ preferences, stored, relayCalls }) =>
186 Effect.gen(function* () {
187 const error = yield* preferences
188 .update({ publishAgentActivity: true, holdWebhooksWhileOffline: true })
189 .pipe(Effect.flip);
190 assert.deepInclude(error, { _tag: "CloudLinkInternalError", operation: "read-preferences" });
191 assert.deepEqual(relayCalls, []);
192 assert.equal(new TextDecoder().decode(stored.get(PUBLISH_AGENT_ACTIVITY_SECRET)), "false");
193 }),
194 ),
195);
196​
197it.effect("two overlapping updates are applied one after the other", () => {
198 let release!: () => void;
199 let started!: () => void;
200 const released = new Promise<void>((resolve) => {
201 release = resolve;
202 });
203 const firstAtRelay = new Promise<void>((resolve) => {
204 started = resolve;
205 });
206 return withService({ holdFirstRelayCall: { started, released } }, ({ preferences, stored }) =>
207 Effect.gen(function* () {
208 const first = yield* preferences
209 .update({ publishAgentActivity: true, holdWebhooksWhileOffline: true })
210 .pipe(Effect.forkChild);
211 yield* Effect.promise(() => firstAtRelay);
212 const second = yield* preferences
213 .update({ publishAgentActivity: false, holdWebhooksWhileOffline: false })
214 .pipe(Effect.forkChild);
215 yield* Effect.yieldNow;
216 assert.equal(new TextDecoder().decode(stored.get(PUBLISH_AGENT_ACTIVITY_SECRET)), "true");
217 release();
218 yield* Fiber.join(first);
219 yield* Fiber.join(second);
220 assert.equal(new TextDecoder().decode(stored.get(PUBLISH_AGENT_ACTIVITY_SECRET)), "false");
221 assert.equal(
222 new TextDecoder().decode(stored.get(HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET)),
223 "false",
224 );
225 }),
226 );
227});
228​
229it.effect("changes nothing when the current hold setting can't be read", () =>
230 withService({ failHoldRead: true, failHoldWrite: true }, ({ preferences, stored, relayCalls }) =>
231 Effect.gen(function* () {
232 stored.set(HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET, encode("true"));
233 const error = yield* preferences
234 .update({ publishAgentActivity: true, holdWebhooksWhileOffline: false })
235 .pipe(Effect.flip);
236 assert.deepInclude(error, { _tag: "CloudLinkInternalError", operation: "read-preferences" });
237 assert.deepEqual(relayCalls, []);
238 assert.equal(new TextDecoder().decode(stored.get(PUBLISH_AGENT_ACTIVITY_SECRET)), "false");
239 }),
240 ),
241);
242​
243it.effect("an update the client walks away from still finishes", () => {
244 let release!: () => void;
245 let started!: () => void;
246 const released = new Promise<void>((resolve) => {
247 release = resolve;
248 });
249 const atRelay = new Promise<void>((resolve) => {
250 started = resolve;
251 });
252 return withService({ holdFirstRelayCall: { started, released } }, ({ preferences, stored }) =>
253 Effect.gen(function* () {
254 const update = yield* preferences
255 .update({ publishAgentActivity: true, holdWebhooksWhileOffline: true })
256 .pipe(Effect.forkChild);
257 yield* Effect.promise(() => atRelay);
258 const interrupted = yield* Fiber.interrupt(update).pipe(Effect.forkChild);
259 yield* Effect.yieldNow;
260 release();
261 yield* Fiber.join(interrupted);
262 assert.equal(new TextDecoder().decode(stored.get(PUBLISH_AGENT_ACTIVITY_SECRET)), "true");
263 assert.equal(
264 new TextDecoder().decode(stored.get(HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET)),
265 "true",
266 );
267 }),
268 );
269});