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

The best way to control Claude Code, Codex and more from any computer or phone

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

Synced Nov 21, 04:45 UTC

main
ts 180 lines 7.12 KB
Raw
1 /**
2 * Standalone issue trackers as Settings manages them: one credential per tracker kind in the
3 * secret store, and the per-project binding that puts a tracker's scope beside the project's
4 * git-host issues. Disconnecting clears the bindings that pointed at the tracker.
5 */
6 import * as Context from "effect/Context";
7 import * as Effect from "effect/Effect";
8 import * as Layer from "effect/Layer";
9 import * as Option from "effect/Option";
10 import * as DateTime from "effect/DateTime";
11 import {
12 IssueTrackerConnectionError,
13 IssueTrackerKind,
14 type IssueTrackerBindProjectInput,
15 type IssueTrackerConnectInput,
16 type IssueTrackerConnection,
17 type IssueTrackerConnectionList,
18 } from "@t3tools/contracts";
19 import type { StandaloneIssueTrackerApi } from "@t3tools/source-control-core/server/IssueTracker";
20
21 import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
22 import * as IssueTrackerBindings from "../persistence/IssueTrackerBindings.ts";
23 import * as IssueService from "./IssueService.ts";
24 import { issueTrackerSecretName } from "./IssueTrackerHostLive.ts";
25 import * as IssueTrackerRegistry from "./IssueTrackerRegistry.ts";
26
27 const encoder = new TextEncoder();
28
29 export class IssueTrackerConnections extends Context.Service<
30 IssueTrackerConnections,
31 {
32 /** Every standalone tracker, each probed against its stored credential, and the bindings. */
33 readonly list: Effect.Effect<IssueTrackerConnectionList, IssueTrackerConnectionError>;
34 /**
35 * Vets the credential with the tracker and stores it only when the tracker accepts it. A null
36 * token removes the stored one and unbinds every project that pointed at the tracker.
37 */
38 readonly connect: (
39 input: IssueTrackerConnectInput,
40 ) => Effect.Effect<IssueTrackerConnection, IssueTrackerConnectionError>;
41 /** Binds a project to one of a tracker's scopes, or unbinds it with a null binding. */
42 readonly bindProject: (
43 input: IssueTrackerBindProjectInput,
44 ) => Effect.Effect<void, IssueTrackerConnectionError>;
45 }
46 >()("t3/issue/IssueTrackerConnections") {}
47
48 const make = Effect.gen(function* () {
49 const registry = yield* IssueTrackerRegistry.IssueTrackerRegistry;
50 const secrets = yield* ServerSecretStore.ServerSecretStore;
51 const bindings = yield* IssueTrackerBindings.IssueTrackerBindingsRepository;
52
53 const requireTracker = (
54 tracker: IssueTrackerKind,
55 ): Effect.Effect<StandaloneIssueTrackerApi, IssueTrackerConnectionError> => {
56 const found = registry.standalone.find((api) => api.kind === tracker);
57 return found === undefined
58 ? Effect.fail(
59 new IssueTrackerConnectionError({
60 tracker,
61 reason: "unknown-tracker",
62 detail: "This server has no such issue tracker.",
63 }),
64 )
65 : Effect.succeed(found);
66 };
67
68 /** The kind an error about no tracker in particular is filed under. */
69 const anyTracker = registry.standalone[0]?.kind ?? IssueTrackerKind.make("none");
70
71 const secretFailure = (tracker: IssueTrackerKind, detail: string) => (cause: unknown) =>
72 new IssueTrackerConnectionError({ tracker, reason: "failed", detail, cause });
73
74 const disconnected = (api: StandaloneIssueTrackerApi): IssueTrackerConnection => ({
75 ...api.standalone,
76 connected: false,
77 account: null,
78 detail: null,
79 scopes: [],
80 });
81
82 /** The tracker's view of a stored credential; a refusal is status, not a failure. */
83 const status = (api: StandaloneIssueTrackerApi, token: string) =>
84 api.probeCredential(token).pipe(
85 Effect.map((probe): IssueTrackerConnection => ({
86 ...api.standalone,
87 connected: true,
88 account: probe.account,
89 detail: null,
90 ...(probe.workspace === undefined ? {} : { workspace: probe.workspace }),
91 scopes: probe.scopes,
92 })),
93 Effect.catch((error) =>
94 Effect.succeed<IssueTrackerConnection>({
95 ...api.standalone,
96 connected: true,
97 account: null,
98 detail: IssueService.trackerDetail(error),
99 scopes: [],
100 }),
101 ),
102 );
103
104 const current = (api: StandaloneIssueTrackerApi) =>
105 secrets.get(issueTrackerSecretName(api.kind)).pipe(
106 Effect.mapError(secretFailure(api.kind, "The stored credential could not be read.")),
107 Effect.flatMap((stored) =>
108 Option.isNone(stored)
109 ? Effect.succeed(disconnected(api))
110 : status(api, new TextDecoder().decode(stored.value)),
111 ),
112 );
113
114 const list: IssueTrackerConnections["Service"]["list"] = Effect.all({
115 trackers: Effect.forEach(registry.standalone, current, { concurrency: 4 }),
116 bindings: bindings.list.pipe(
117 Effect.map((bound) => Object.fromEntries(bound)),
118 // No single tracker is at fault; the first registered one carries the report.
119 Effect.mapError(secretFailure(anyTracker, "The project bindings could not be read.")),
120 ),
121 });
122
123 const disconnect = Effect.fn("IssueTrackerConnections.disconnect")(function* (
124 api: StandaloneIssueTrackerApi,
125 ) {
126 yield* secrets
127 .remove(issueTrackerSecretName(api.kind))
128 .pipe(Effect.mapError(secretFailure(api.kind, "The credential could not be removed.")));
129 // Bindings to a tracker nobody is signed into would only produce errors in every listing.
130 yield* bindings
131 .removeTracker(api.kind)
132 .pipe(Effect.mapError(secretFailure(api.kind, "The project bindings could not be cleared.")));
133 return disconnected(api);
134 });
135
136 const connect: IssueTrackerConnections["Service"]["connect"] = Effect.fn(
137 "IssueTrackerConnections.connect",
138 )(function* (input) {
139 const api = yield* requireTracker(input.tracker);
140 if (input.token === null) return yield* disconnect(api);
141 const probe = yield* api.probeCredential(input.token).pipe(
142 Effect.mapError(
143 (error) =>
144 new IssueTrackerConnectionError({
145 tracker: input.tracker,
146 reason: error.reason === "unauthenticated" ? "rejected" : "failed",
147 detail: IssueService.trackerDetail(error),
148 cause: error,
149 }),
150 ),
151 );
152 yield* secrets
153 .set(issueTrackerSecretName(api.kind), encoder.encode(input.token))
154 .pipe(Effect.mapError(secretFailure(api.kind, "The credential could not be stored.")));
155 return {
156 ...api.standalone,
157 connected: true,
158 account: probe.account,
159 detail: null,
160 ...(probe.workspace === undefined ? {} : { workspace: probe.workspace }),
161 scopes: probe.scopes,
162 };
163 });
164
165 const bindProject: IssueTrackerConnections["Service"]["bindProject"] = Effect.fn(
166 "IssueTrackerConnections.bindProject",
167 )(function* (input) {
168 // Unbinding names no tracker; the first registered one carries any report.
169 const tracker =
170 input.binding === null ? anyTracker : (yield* requireTracker(input.binding.tracker)).kind;
171 const updatedAt = DateTime.formatIso(yield* DateTime.now);
172 yield* bindings
173 .set({ projectId: input.projectId, binding: input.binding, updatedAt })
174 .pipe(Effect.mapError(secretFailure(tracker, "The project binding could not be saved.")));
175 });
176
177 return IssueTrackerConnections.of({ list, connect, bindProject });
178 });
179
180 export const layer = Layer.effect(IssueTrackerConnections, make);