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

PeerLinks.testkit.ts

194 lines7.7 KB

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