Skip to content

Commit b1bc5ce

Browse files
fix(server): linking says why each address failed discovery (#30884)
1 parent 5e18314 commit b1bc5ce

2 files changed

Lines changed: 82 additions & 44 deletions

File tree

‎apps/server/src/peer/PeerLinks.test.ts‎

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -742,7 +742,7 @@ it.effect("linking a picked machine that answers nowhere names it and links noth
742742
.pipe(Effect.flip);
743743
expect(failed.reason).toBe("unreachable");
744744
expect(failed.message).toBe(
745-
`This environment could not reach Box at ${impostor.url}, http://192.168.1.20:3773.`,
745+
`This environment could not reach Box: ${new URL(impostor.url).origin} answered as another environment, Impostor. http://192.168.1.20:3773 is plain http, which would send the link's credentials unencrypted. Use its https address, or its Tailscale address.`,
746746
);
747747
expect(yield* a.links.list).toEqual([]);
748748
expect(yield* linkedSessions(impostor)).toEqual([]);
@@ -763,6 +763,29 @@ it.effect("linking a picked machine that answers nowhere names it and links noth
763763
).pipe(Effect.provide(NodeHttpServer.layerTest)),
764764
);
765765

766+
it.live("linking an address with nothing listening says so, unlike one that is not T3 Code", () =>
767+
Effect.scoped(
768+
Effect.gen(function* () {
769+
const closed = yield* Effect.scoped(
770+
serveRaw(() => Effect.succeed(HttpServerResponse.empty({ status: 404 }))),
771+
);
772+
const notT3 = yield* serveRaw(() =>
773+
Effect.succeed(
774+
HttpServerResponse.text("<h1>Not Found</h1>", { status: 404, contentType: "text/html" }),
775+
),
776+
);
777+
const a = yield* makeA(laptop);
778+
const linking = (url: string) =>
779+
a.links.link({ url, pairingCode: "unused", access: "auto" }).pipe(Effect.flip);
780+
expect((yield* linking(closed)).message).toBe(`${closed} did not answer (ECONNREFUSED).`);
781+
expect((yield* linking(notT3)).message).toBe(
782+
`${notT3} answered, but not as a T3 Code environment this version understands.`,
783+
);
784+
expect(yield* a.links.list).toEqual([]);
785+
}),
786+
).pipe(Effect.provide(NodeHttpServer.layerTest)),
787+
);
788+
766789
/** An https listener whose certificate this machine does not trust. */
767790
const serveUntrusted = Layer.build(
768791
Layer.fresh(

‎apps/server/src/peer/PeerLinks.ts‎

Lines changed: 58 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,14 @@ import {
55
EnvironmentHttpApi,
66
EnvironmentId,
77
type ExecutionEnvironmentCapabilities,
8-
type ExecutionEnvironmentDescriptor,
98
MCP_PEER_LINK_SOFTWARE_ID,
109
type PeerLink,
1110
type PeerLinkCreateInput,
1211
PeerLinkError,
1312
type PeerLinkSummary,
1413
} from "@t3tools/contracts";
1514
import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
15+
import * as Cause from "effect/Cause";
1616
import * as Context from "effect/Context";
1717
import * as Digest from "effect/crypto/Digest";
1818
import * as SecureRandom from "effect/crypto/SecureRandom";
@@ -31,6 +31,7 @@ import * as Schema from "effect/Schema";
3131
import * as SqlClient from "effect/sql/SqlClient";
3232
import * as FetchHttpClient from "effect/http/FetchHttpClient";
3333
import * as HttpClient from "effect/http/HttpClient";
34+
import * as HttpClientError from "effect/http/HttpClientError";
3435
import * as HttpApi from "effect/http-api/HttpApi";
3536
import * as HttpApiClient from "effect/http-api/HttpApiClient";
3637
import { isLocalLoopbackHost, isTailnetHost } from "@t3tools/shared/hostClassification";
@@ -176,6 +177,38 @@ const peerOrigin = (url: string) => {
176177
return Effect.succeed(parsed.origin);
177178
};
178179

180+
/** The system error under a failed connection, such as ECONNREFUSED or ENOTFOUND. */
181+
const connectionCode = (cause: unknown) =>
182+
[cause, Predicate.hasProperty(cause, "cause") ? cause.cause : undefined]
183+
.map((error) => (Predicate.hasProperty(error, "code") ? error.code : undefined))
184+
.find(Predicate.isString);
185+
186+
/** Why `origin` did not answer as T3 Code, short enough for a toast. Never echoes a body. */
187+
const probeFailure = (
188+
origin: string,
189+
error: HttpClientError.HttpClientError | Schema.SchemaError | Cause.TimeoutError,
190+
timeout: Duration.Duration,
191+
) => {
192+
const unreachable = (message: string) => new PeerLinkError({ reason: "unreachable", message });
193+
const certificate = certificateErrorCode(error);
194+
if (certificate !== undefined) {
195+
return unreachable(`${origin} presented a certificate this machine rejected (${certificate}).`);
196+
}
197+
if (Cause.isTimeoutError(error)) {
198+
return unreachable(`${origin} did not answer within ${Duration.toSeconds(timeout)} seconds.`);
199+
}
200+
if (HttpClientError.isHttpClientError(error) && error.reason._tag === "TransportError") {
201+
const code = connectionCode(error.reason.cause);
202+
return unreachable(
203+
code === undefined ? `${origin} did not answer.` : `${origin} did not answer (${code}).`,
204+
);
205+
}
206+
return new PeerLinkError({
207+
reason: "not_a_t3_environment",
208+
message: `${origin} answered, but not as a T3 Code environment this version understands.`,
209+
});
210+
};
211+
179212
/** Whether a host is this machine's own loopback. Tests serve their peers there, so they narrow it. */
180213
export const LoopbackHost = Context.Reference<(host: string) => boolean>(
181214
"t3/peer/PeerLinks/LoopbackHost",
@@ -217,41 +250,29 @@ const make = Effect.gen(function* () {
217250
Effect.provideService(HttpClient.HttpClient, peerHttpClient),
218251
);
219252

220-
/**
221-
* The environment answering at `origin`, or nothing when it does not answer
222-
* as T3 Code. A certificate this machine rejects fails instead, since
223-
* the peer may well be there.
224-
*/
225-
const describe = (origin: string) =>
226-
clientFor(origin).pipe(
253+
/** The environment answering at `origin`, or why nothing there answers as T3 Code. */
254+
const probe = (origin: string) => {
255+
const timeout = probeTimeout(origin);
256+
return clientFor(origin).pipe(
227257
Effect.flatMap((client) => client.metadata.descriptor()),
228258
// A brief network drop must not list a live peer as down; the timeout still bounds both tries.
229259
Effect.retry({
230260
times: 1,
231261
schedule: Schedule.spaced("1 second"),
232262
while: (error) => certificateErrorCode(error) === undefined,
233263
}),
234-
Effect.timeout(probeTimeout(origin)),
235-
Effect.asSome,
236-
Effect.catch((error) => {
237-
const code = certificateErrorCode(error);
238-
return code === undefined
239-
? Effect.succeed(Option.none<ExecutionEnvironmentDescriptor>())
240-
: Effect.fail(
241-
new PeerLinkError({
242-
reason: "unreachable",
243-
message: `${origin} presented a certificate this machine rejected (${code}).`,
244-
}),
245-
);
246-
}),
264+
Effect.timeout(timeout),
265+
// No cause: a decode error can carry the response body to the client.
266+
Effect.mapError((error) => probeFailure(origin, error, timeout)),
247267
);
268+
};
248269

249-
/** Whether `url` answers as `environmentId`, counting an untrusted certificate as no. */
270+
/** Whether `url` answers as `environmentId`, counting any failure as no. */
250271
const answersAs = Effect.fn("PeerLinks.answersAs")(function* (
251272
url: string,
252273
environmentId: EnvironmentId,
253274
) {
254-
const found = yield* describe(url).pipe(Effect.orElseSucceed(() => Option.none()));
275+
const found = yield* probe(url).pipe(Effect.option);
255276
return Option.filter(found, (peer) => peer.environmentId === environmentId);
256277
});
257278

@@ -404,7 +425,8 @@ const make = Effect.gen(function* () {
404425
/**
405426
* The addresses that answer as `environmentId`, in the order given, with
406427
* what the first one answered. Addresses this environment would not send
407-
* credentials to are skipped; when every one is, the failure says why.
428+
* credentials to are skipped; when none answers as it, the failure says why
429+
* for each.
408430
*/
409431
const answeringAs = Effect.fn("PeerLinks.answeringAs")(function* (
410432
urls: ReadonlyArray<string>,
@@ -423,28 +445,28 @@ const make = Effect.gen(function* () {
423445
message: `${origin} is this machine, not ${name}.`,
424446
});
425447
}
426-
return { origin, descriptor: yield* describe(origin) };
448+
const descriptor = yield* probe(origin);
449+
if (descriptor.environmentId !== environmentId) {
450+
return yield* new PeerLinkError({
451+
reason: "unreachable",
452+
message: `${origin} answered as another environment, ${descriptor.label}.`,
453+
});
454+
}
455+
return { origin, descriptor };
427456
}).pipe(Effect.result),
428457
{ concurrency: "unbounded" },
429458
);
430459
const matching = checked.flatMap((result) =>
431-
Result.isSuccess(result) &&
432-
Option.isSome(result.success.descriptor) &&
433-
result.success.descriptor.value.environmentId === environmentId
434-
? [{ origin: result.success.origin, descriptor: result.success.descriptor.value }]
435-
: [],
460+
Result.isSuccess(result) ? [result.success] : [],
436461
);
437462
const first = matching[0];
438463
if (first === undefined) {
439-
const refusals = checked.flatMap((result) =>
464+
const reasons = checked.flatMap((result) =>
440465
Result.isFailure(result) ? [result.failure.message] : [],
441466
);
442467
return yield* new PeerLinkError({
443468
reason: "unreachable",
444-
message:
445-
refusals.length === checked.length
446-
? `This environment could not reach ${name}: ${refusals.join(" ")}`
447-
: `This environment could not reach ${name} at ${urls.join(", ")}.`,
469+
message: `This environment could not reach ${name}: ${reasons.join(" ")}`,
448470
});
449471
}
450472
// Each address is kept once, even when two spellings share an origin.
@@ -456,14 +478,7 @@ const make = Effect.gen(function* () {
456478
const answeringAt = Effect.fn("PeerLinks.answeringAt")(function* (urls: ReadonlyArray<string>) {
457479
const origins = yield* Effect.forEach(urls, peerOrigin);
458480
const primary = origins[0]!;
459-
const descriptor = yield* describe(primary);
460-
if (Option.isNone(descriptor)) {
461-
return yield* new PeerLinkError({
462-
reason: "not_a_t3_environment",
463-
message: `Nothing at ${primary} answered as a T3 Code environment.`,
464-
});
465-
}
466-
return { primary, peer: descriptor.value, origins };
481+
return { primary, peer: yield* probe(primary), origins };
467482
});
468483

469484
const link: PeerLinks["Service"]["link"] = Effect.fn("PeerLinks.link")(function* (input) {

0 commit comments

Comments
 (0)