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

PeerLinks.testkit.ts

180 lines7.0 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import {
3 EnvironmentHttpApi,
4 EnvironmentId,
5 type AuthMcpClientAccess,
6 type ExecutionEnvironmentDescriptor,
7} from "@t3tools/contracts";
8import * as Context from "effect/Context";
9import * as Effect from "effect/Effect";
10import * as Layer from "effect/Layer";
11import * as Ref from "effect/Ref";
12import * as FetchHttpClient from "effect/http/FetchHttpClient";
13import * as HttpRouter from "effect/http/HttpRouter";
14import * as HttpServer from "effect/http/HttpServer";
15import * as HttpServerRequest from "effect/http/HttpServerRequest";
16import * as HttpApi from "effect/http-api/HttpApi";
17import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
18​
19import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
20import * as AuthHttp from "../auth/http.ts";
21import * as McpOAuth from "../auth/McpOAuth.ts";
22import * as McpOAuthHttp from "../auth/mcpOAuthHttp.ts";
23import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
24import * as ServerConfig from "../config.ts";
25import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
26import * as ServerHttp from "../http.ts";
27import * as McpHttpServer from "../mcp/McpHttpServer.ts";
28import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts";
29import * as Sqlite from "../persistence/Sqlite.ts";
30import * as PeerLinks from "./PeerLinks.ts";
31import * as PeerMcpClient from "./PeerMcpClient.ts";
32​
33class PeerTestApi extends HttpApi.make("environment")
34 .add(EnvironmentHttpApi.groups.metadata)
35 .add(EnvironmentHttpApi.groups.mcpOAuth) {}
36​
37export const descriptorOf = (
38 environmentId: string,
39 label: string,
40 capabilities: Partial<ExecutionEnvironmentDescriptor["capabilities"]> = {},
41): ExecutionEnvironmentDescriptor => ({
42 environmentId: EnvironmentId.make(environmentId),
43 label,
44 platform: { os: "linux", arch: "x64" },
45 serverVersion: "0.0.0-test",
46 capabilities: {
47 repositoryIdentity: true,
48 mcpModeLimitHeader: true,
49 linkFence: true,
50 ...capabilities,
51 },
52});
53​
54/**
55 * The environment a link points at, as it runs: its descriptor, MCP OAuth,
56 * and `/mcp` with `tools` behind the real client authenticator, on a real
57 * socket. The descriptor can be swapped, as when its address comes to answer
58 * as another environment, and every bearer it receives is recorded.
59 */
60export const servePeer = <E, R>(
61 initial: ExecutionEnvironmentDescriptor,
62 tools: Layer.Layer<never, E, R>,
63) =>
64 Effect.gen(function* () {
65 const descriptor = yield* Ref.make(initial);
66 const bearers = yield* Ref.make<ReadonlyArray<string>>([]);
67 const probes = yield* Ref.make(0);
68 const layerEnvironment = Layer.succeed(ServerEnvironment.ServerEnvironment, {
69 getEnvironmentId: Ref.get(descriptor).pipe(Effect.map((current) => current.environmentId)),
70 getDescriptor: Ref.get(descriptor),
71 });
72 const authContext = yield* EnvironmentAuth.layer.pipe(
73 Layer.provide(Sqlite.layerMemory),
74 Layer.provideMerge(ServerSecretStore.layer),
75 Layer.provideMerge(ServerEnvironment.layerIdentity),
76 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-peer-link-peer-" })),
77 Layer.provideMerge(NodeServices.layer),
78 Layer.fresh,
79 Layer.build,
80 );
81 const layerRecordBearers = HttpRouter.middleware(
82 (httpEffect) =>
83 Effect.gen(function* () {
84 const request = yield* HttpServerRequest.HttpServerRequest;
85 if (request.url.startsWith("/.well-known/t3/environment")) {
86 yield* Ref.update(probes, (count) => count + 1);
87 }
88 const authorization = request.headers.authorization;
89 if (authorization !== undefined) {
90 yield* Ref.update(bearers, (seen) => [...seen, authorization]);
91 }
92 return yield* httpEffect;
93 }),
94 { global: true },
95 );
96 const layerRoutes = Layer.mergeAll(
97 HttpApiBuilder.layer(PeerTestApi).pipe(
98 Layer.provide(McpOAuthHttp.layer.pipe(Layer.provide(McpOAuth.layer))),
99 Layer.provide(ServerHttp.layerServerEnvironmentHttpApi),
100 Layer.provide(AuthHttp.layerAuthenticatedAuth),
101 ),
102 tools.pipe(
103 Layer.provideMerge(McpHttpServer.layerMcpTransport),
104 Layer.provide(
105 Layer.mock(McpSessionRegistry.McpSessionRegistry)({
106 // @effect-diagnostics-next-line effectSucceedWithVoid:off - This optional result requires undefined, not the wider void type.
107 resolve: () => Effect.succeed(undefined),
108 }),
109 ),
110 Layer.provide(McpOAuth.layerMcpClientAuthenticator),
111 ),
112 ).pipe(
113 Layer.provide(layerRecordBearers),
114 Layer.provide(layerEnvironment),
115 Layer.provide(Layer.succeedContext(authContext)),
116 );
117 // Fresh, so the peer never shares a toolkit or MCP server with the
118 // environment that links to it in the same test.
119 yield* HttpRouter.serve(layerRoutes, { disableListenLog: true, disableLogger: true }).pipe(
120 Layer.fresh,
121 Layer.build,
122 );
123 const address = (yield* HttpServer.HttpServer).address;
124 if (address._tag === "UnixPathAddress") return yield* Effect.die("expected a TCP address");
125 const url = `http://127.0.0.1:${address.port}`;
126 const auth = Context.get(authContext, EnvironmentAuth.EnvironmentAuth);
127 return {
128 url,
129 auth,
130 descriptor,
131 bearers,
132 /** How often its descriptor was asked for, as a probe of whether it answers. */
133 probes,
134 /** The sessions linking created there, which its Connections lists. */
135 linkedSessions: auth
136 .listSessions()
137 .pipe(
138 Effect.map((sessions) =>
139 sessions.filter((session) => session.client.label?.startsWith("T3 Code · ")),
140 ),
141 ),
142 };
143 });
144​
145export type ServedPeer = Effect.Success<ReturnType<typeof servePeer>>;
146​
147/**
148 * The environment that links: its own database and secret store, reaching
149 * peers over plain HTTP. Provide it to anything built on its links.
150 */
151export const layerLinkingEnvironment = (descriptor: ExecutionEnvironmentDescriptor) =>
152 PeerMcpClient.layer.pipe(
153 Layer.provideMerge(PeerLinks.layer),
154 Layer.provideMerge(Sqlite.layerMemory),
155 Layer.provide(Layer.mergeAll(ServerSecretStore.layer, FetchHttpClient.layer)),
156 // Services that act for this environment, such as delegation, name it too.
157 Layer.provideMerge(
158 Layer.succeed(ServerEnvironment.ServerEnvironment, {
159 getEnvironmentId: Effect.succeed(descriptor.environmentId),
160 getDescriptor: Effect.succeed(descriptor),
161 }),
162 ),
163 Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-peer-link-here-" })),
164 Layer.provideMerge(NodeServices.layer),
165 Layer.fresh,
166 );
167​
168/** Links `links` to `peer` with a fresh pairing code from it. */
169export const linkTo = (
170 links: PeerLinks.PeerLinks["Service"],
171 peer: ServedPeer,
172 access: AuthMcpClientAccess = "auto",
173) =>
174 peer.auth
175 .issuePairingCredential()
176 .pipe(
177 Effect.flatMap((pairing) =>
178 links.link({ url: peer.url, pairingCode: pairing.credential, access }),
179 ),
180 );