@devries-cameron20 / composio Mirror · read-only
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 04:45 UTC

next
ts 158 lines 6 KB
Raw
1 import { Auth, make, type ComposioClientShape } from '@composio/client/effect';
2 import { Effect, Layer, Result } from 'effect';
3 import { HttpClient, HttpClientRequest, HttpClientResponse } from 'effect/http';
4 import { ComposioClientSingleton } from 'src/services/composio-clients';
5 import { schemaLoaders } from '@composio/client/effect/schemas';
6
7 /** One request as it reached the stub transport. */
8 export interface StubRequest {
9 readonly method: string;
10 /** Path and query, without the origin. */
11 readonly path: string;
12 /** The JSON body, or `undefined` when the request carried none. */
13 readonly body: unknown;
14 }
15
16 /**
17 * The org and project a stubbed request carried in its scope headers (`x-org-id`,
18 * `x-project-id`), as the client sends them for a client built with `scope`; both are absent
19 * for a client built without one.
20 */
21 export interface StubRequestScope {
22 readonly orgId?: string;
23 readonly projectId?: string;
24 }
25
26 /** The scope a client is built with: an org and a project together, as `getFor` takes them. */
27 type StubClientScope = { readonly orgId: string; readonly projectId: string };
28
29 /**
30 * A transport that records each request, and the scope headers it carried, and answers it
31 * with `respond`. `scopes[i]` is the scope of `requests[i]`.
32 */
33 const recordingTransport = (respond: (request: StubRequest) => Response) => {
34 const requests: Array<StubRequest> = [];
35 const scopes: Array<StubRequestScope> = [];
36 const httpClient = HttpClient.make(request =>
37 Effect.promise(async () => {
38 const web = Result.getOrThrow(HttpClientRequest.toWebResult(request));
39 const url = new URL(web.url);
40 const text = await web.text();
41 const recorded: StubRequest = {
42 method: web.method,
43 path: `${url.pathname}${url.search}`,
44 body: text === '' ? undefined : (JSON.parse(text) as unknown),
45 };
46 const orgId = web.headers.get('x-org-id');
47 const projectId = web.headers.get('x-project-id');
48 requests.push(recorded);
49 scopes.push({
50 ...(orgId === null ? {} : { orgId }),
51 ...(projectId === null ? {} : { projectId }),
52 });
53 return HttpClientResponse.fromWeb(request, respond(recorded));
54 })
55 );
56 return { httpClient, requests, scopes };
57 };
58
59 const makeStubClient = (httpClient: HttpClient.HttpClient, scope?: StubClientScope) =>
60 make(
61 {
62 auth: Auth.project('test'),
63 scope:
64 scope === undefined
65 ? undefined
66 : { organizationId: scope.orgId, projectId: scope.projectId },
67 baseURL: 'https://stub.invalid',
68 maxRetries: 0,
69 schemas: schemaLoaders,
70 },
71 httpClient
72 );
73
74 /**
75 * The Effect client the CLI builds in production, over a transport that
76 * records each request and answers it with `respond`. Retries, status errors,
77 * and the validation a call asks for are the client's own.
78 *
79 * A retried call sleeps on Effect's clock, so a test whose answer is retryable
80 * runs on the live clock (`it.live`, or `layer(..., { excludeTestServices: true })`)
81 * and answers with a `retry-after-ms: 0` header.
82 */
83 export const stubComposioClient = (
84 respond: (request: StubRequest) => Response
85 ): { readonly client: ComposioClientShape; readonly requests: ReadonlyArray<StubRequest> } => {
86 const { httpClient, requests } = recordingTransport(respond);
87 return { client: makeStubClient(httpClient), requests };
88 };
89
90 /**
91 * A layer over a test layer's `ComposioClientSingleton` that swaps the named
92 * resources of every client it hands out for those of a client built by
93 * {@link stubComposioClient}, with the org and project the client was asked
94 * for. Calls to those resources go through the real client to `respond`;
95 * every other resource keeps the test layer's answers. `scopes[i]` holds the
96 * scope headers `requests[i]` carried, so a test can tell which project a
97 * request named.
98 *
99 * The test layer's answers do not model request options (`signal`,
100 * `maxRetries`, or any header beyond `decode`), and its connected-account
101 * shadows serve fixtures without cursor traversal, so pagination, retries, and abort are
102 * exercised through {@link stubComposioClient}, the real `make` over a
103 * recording transport.
104 */
105 export const stubClientResources = (
106 resources: ReadonlyArray<keyof ComposioClientShape>,
107 respond: (request: StubRequest) => Response
108 ) => {
109 const transport = recordingTransport(respond);
110 const overlayFor = (scope?: StubClientScope) => {
111 const client = makeStubClient(transport.httpClient, scope);
112 return Object.fromEntries(resources.map(resource => [resource, client[resource]]));
113 };
114 const unscoped = overlayFor();
115 const stubbed =
116 (overlay: ReturnType<typeof overlayFor>) =>
117 (client: ComposioClientShape): ComposioClientShape => ({ ...client, ...overlay });
118 const layer = Layer.effect(
119 ComposioClientSingleton,
120 Effect.gen(function* () {
121 const base = yield* ComposioClientSingleton;
122 return ComposioClientSingleton.of({
123 ...base,
124 get: () => Effect.map(base.get(), stubbed(unscoped)),
125 getFor: params =>
126 Effect.map(
127 base.getFor(params),
128 stubbed(
129 params.orgId === undefined || params.projectId === undefined
130 ? unscoped
131 : overlayFor({ orgId: params.orgId, projectId: params.projectId })
132 )
133 ),
134 });
135 })
136 );
137 return { requests: transport.requests, scopes: transport.scopes, layer };
138 };
139
140 /** A request the stub answers specially: its method and a prefix of its path. */
141 export interface StubRoute {
142 readonly method: string;
143 readonly path: string;
144 readonly respond: () => Response;
145 }
146
147 /**
148 * A `respond` that answers a request with the first route whose method and
149 * path prefix match it, and every other request with `otherwise`.
150 */
151 export const routeRequests =
152 (routes: ReadonlyArray<StubRoute>, otherwise: () => Response) =>
153 (request: StubRequest): Response => {
154 const route = routes.find(
155 ({ method, path }) => request.method === method && request.path.startsWith(path)
156 );
157 return (route?.respond ?? otherwise)();
158 };