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

IssueTrackerConnections.ts

328 lines13.0 KB

1/**
2 * Standalone issue trackers as Settings manages them: one credential per tracker account in the
3 * secret store, and the per-project binding that puts an account's scope beside the project's
4 * git-host issues. A tracker's first account predates accounts and has no id; each added one
5 * gets its own. Disconnecting an account clears the bindings that pointed at it.
6 */
7import * as Context from "effect/Context";
8import * as Effect from "effect/Effect";
9import * as Layer from "effect/Layer";
10import * as Option from "effect/Option";
11import * as Semaphore from "effect/Semaphore";
12import * as DateTime from "effect/DateTime";
13import * as SecureRandom from "effect/crypto/SecureRandom";
14import {
15 IssueTrackerAccountId,
16 IssueTrackerConnectionError,
17 IssueTrackerKind,
18 type IssueTrackerBindProjectInput,
19 type IssueTrackerConnectInput,
20 type IssueTrackerConnection,
21 type IssueTrackerConnectionList,
22} from "@t3tools/contracts";
23import type { StandaloneIssueTrackerApi } from "@t3tools/source-control-core/server/IssueTracker";
24​
25import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
26import * as IssueTrackerBindings from "../persistence/IssueTrackerBindings.ts";
27import * as IssueService from "./IssueService.ts";
28import { issueTrackerSecretName } from "./IssueTrackerHostLive.ts";
29import * as IssueTrackerRegistry from "./IssueTrackerRegistry.ts";
30​
31const encoder = new TextEncoder();
32​
33export class IssueTrackerConnections extends Context.Service<
34 IssueTrackerConnections,
35 {
36 /** Every standalone tracker account, each probed against its stored credential, and the bindings. */
37 readonly list: Effect.Effect<IssueTrackerConnectionList, IssueTrackerConnectionError>;
38 /**
39 * Vets the credential with the tracker and stores it only when the tracker accepts it. A null
40 * token removes the stored one and unbinds every project that pointed at the account.
41 */
42 readonly connect: (
43 input: IssueTrackerConnectInput,
44 ) => Effect.Effect<IssueTrackerConnection, IssueTrackerConnectionError>;
45 /** Binds a project to one of an account's scopes, or unbinds it with a null binding. */
46 readonly bindProject: (
47 input: IssueTrackerBindProjectInput,
48 ) => Effect.Effect<void, IssueTrackerConnectionError>;
49 }
50>()("t3/issue/IssueTrackerConnections") {}
51​
52const make = Effect.gen(function* () {
53 const registry = yield* IssueTrackerRegistry.IssueTrackerRegistry;
54 const secrets = yield* ServerSecretStore.ServerSecretStore;
55 const bindings = yield* IssueTrackerBindings.IssueTrackerBindingsRepository;
56 // Account checks, credential writes, and removals run one at a time, so a removal cannot land
57 // between a check and the write that relied on it.
58 const accountLock = yield* Semaphore.make(1);
59 const random = yield* SecureRandom.SecureRandom;
60​
61 const requireTracker = (
62 tracker: IssueTrackerKind,
63 ): Effect.Effect<StandaloneIssueTrackerApi, IssueTrackerConnectionError> => {
64 const found = registry.standalone.find((api) => api.kind === tracker);
65 return found === undefined
66 ? Effect.fail(
67 new IssueTrackerConnectionError({
68 tracker,
69 reason: "unknown-tracker",
70 detail: "This server has no such issue tracker.",
71 }),
72 )
73 : Effect.succeed(found);
74 };
75​
76 /** The kind an error about no tracker in particular is filed under. */
77 const anyTracker = registry.standalone[0]?.kind ?? IssueTrackerKind.make("none");
78​
79 const secretFailure = (tracker: IssueTrackerKind, detail: string) => (cause: unknown) =>
80 new IssueTrackerConnectionError({ tracker, reason: "failed", detail, cause });
81​
82 const accountFields = (accountId: IssueTrackerAccountId | null) =>
83 accountId === null ? {} : { accountId };
84​
85 const disconnected = (
86 api: StandaloneIssueTrackerApi,
87 accountId: IssueTrackerAccountId | null,
88 ): IssueTrackerConnection => ({
89 ...api.standalone,
90 ...accountFields(accountId),
91 connected: false,
92 account: null,
93 detail: null,
94 scopes: [],
95 });
96​
97 const requireAccount = Effect.fn("IssueTrackerConnections.requireAccount")(function* (
98 tracker: IssueTrackerKind,
99 accountId: IssueTrackerAccountId | undefined,
100 ) {
101 if (accountId === undefined) return null;
102 const saved = yield* bindings.listAccounts.pipe(
103 Effect.mapError(secretFailure(tracker, "The saved accounts could not be read.")),
104 );
105 if (saved.some((account) => account.tracker === tracker && account.accountId === accountId))
106 return accountId;
107 return yield* new IssueTrackerConnectionError({
108 tracker,
109 reason: "failed",
110 detail: "This account is not saved on the server.",
111 });
112 });
113​
114 /** The tracker's view of a stored credential; a refusal is status, not a failure. */
115 const status = (
116 api: StandaloneIssueTrackerApi,
117 accountId: IssueTrackerAccountId | null,
118 token: string,
119 ) =>
120 api.probeCredential(token).pipe(
121 Effect.map((probe): IssueTrackerConnection => ({
122 ...api.standalone,
123 ...accountFields(accountId),
124 connected: true,
125 account: probe.account,
126 detail: null,
127 ...(probe.workspace === undefined ? {} : { workspace: probe.workspace }),
128 scopes: probe.scopes,
129 })),
130 Effect.catch((error) =>
131 Effect.succeed<IssueTrackerConnection>({
132 ...api.standalone,
133 ...accountFields(accountId),
134 connected: true,
135 account: null,
136 detail: IssueService.trackerDetail(error),
137 scopes: [],
138 }),
139 ),
140 );
141​
142 const current = (api: StandaloneIssueTrackerApi, accountId: IssueTrackerAccountId | null) =>
143 secrets.get(issueTrackerSecretName(api.kind, accountId)).pipe(
144 Effect.mapError(secretFailure(api.kind, "The stored credential could not be read.")),
145 Effect.flatMap((stored) =>
146 Option.isNone(stored)
147 ? Effect.succeed(disconnected(api, accountId))
148 : status(api, accountId, new TextDecoder().decode(stored.value)),
149 ),
150 );
151​
152 const list: IssueTrackerConnections["Service"]["list"] = Effect.all({
153 trackers: Effect.forEach(registry.standalone, (api) => current(api, null), { concurrency: 4 }),
154 accounts: bindings.listAccounts.pipe(
155 Effect.mapError(secretFailure(anyTracker, "The saved accounts could not be read.")),
156 Effect.flatMap((accounts) =>
157 Effect.forEach(
158 accounts.flatMap((account) => {
159 const api = registry.standalone.find((tracker) => tracker.kind === account.tracker);
160 return api === undefined ? [] : [{ api, accountId: account.accountId }];
161 }),
162 ({ api, accountId }) => current(api, accountId),
163 { concurrency: 4 },
164 ),
165 ),
166 ),
167 bindings: bindings.list().pipe(
168 // No single tracker is at fault; the first registered one carries the report.
169 Effect.mapError(secretFailure(anyTracker, "The project bindings could not be read.")),
170 ),
171 }).pipe(
172 Effect.map(({ trackers, accounts, bindings: bound }) => {
173 const all = [...bound];
174 return {
175 trackers,
176 accounts,
177 bindings: Object.fromEntries(all.filter(([, binding]) => binding.accountId === undefined)),
178 accountBindings: Object.fromEntries(
179 all.filter(([, binding]) => binding.accountId !== undefined),
180 ),
181 };
182 }),
183 );
184​
185 const disconnect = Effect.fn("IssueTrackerConnections.disconnect")(function* (
186 api: StandaloneIssueTrackerApi,
187 accountId: IssueTrackerAccountId | null,
188 ) {
189 yield* secrets
190 .remove(issueTrackerSecretName(api.kind, accountId))
191 .pipe(Effect.mapError(secretFailure(api.kind, "The credential could not be removed.")));
192 // Bindings to an account nobody is signed into would only produce errors in every listing.
193 yield* bindings
194 .removeAccount({ tracker: api.kind, accountId })
195 .pipe(Effect.mapError(secretFailure(api.kind, "The project bindings could not be cleared.")));
196 return disconnected(api, accountId);
197 });
198​
199 /** Whether another of the tracker's accounts already holds this exact credential. */
200 const heldElsewhere = Effect.fn("IssueTrackerConnections.heldElsewhere")(function* (
201 api: StandaloneIssueTrackerApi,
202 accountId: IssueTrackerAccountId | null,
203 token: string,
204 ) {
205 const saved = yield* bindings.listAccounts.pipe(
206 Effect.mapError(secretFailure(api.kind, "The saved accounts could not be read.")),
207 );
208 const others = [
209 null,
210 ...saved
211 .filter((account) => account.tracker === api.kind)
212 .map((account) => account.accountId),
213 ].filter((other) => other !== accountId);
214 for (const other of others) {
215 const stored = yield* secrets
216 .get(issueTrackerSecretName(api.kind, other))
217 .pipe(Effect.mapError(secretFailure(api.kind, "The stored credential could not be read.")));
218 if (Option.isSome(stored) && new TextDecoder().decode(stored.value) === token) return true;
219 }
220 return false;
221 });
222​
223 const connect: IssueTrackerConnections["Service"]["connect"] = Effect.fn(
224 "IssueTrackerConnections.connect",
225 )(function* (input) {
226 const api = yield* requireTracker(input.tracker);
227 const addAccount = input.addAccount === true;
228 const token = input.token;
229 if (token === null) {
230 if (addAccount) {
231 return yield* new IssueTrackerConnectionError({
232 tracker: input.tracker,
233 reason: "failed",
234 detail: "A new account needs a credential.",
235 });
236 }
237 return yield* accountLock.withPermits(1)(
238 Effect.flatMap(requireAccount(api.kind, input.accountId), (existing) =>
239 disconnect(api, existing),
240 ),
241 );
242 }
243 // The tracker is asked before the lock, so a slow probe never holds up other settings.
244 const probed = yield* api.probeCredential(token).pipe(
245 Effect.mapError(
246 (error) =>
247 new IssueTrackerConnectionError({
248 tracker: input.tracker,
249 reason: error.reason === "unauthenticated" ? "rejected" : "failed",
250 detail: IssueService.trackerDetail(error),
251 cause: error,
252 }),
253 ),
254 );
255 const accountId = yield* accountLock.withPermits(1)(
256 Effect.gen(function* () {
257 const accountId = addAccount
258 ? IssueTrackerAccountId.make(
259 yield* random
260 .uuidV4()
261 .pipe(
262 Effect.mapError(secretFailure(api.kind, "The account could not be created.")),
263 ),
264 )
265 : yield* requireAccount(api.kind, input.accountId);
266 if (yield* heldElsewhere(api, accountId, token)) {
267 return yield* new IssueTrackerConnectionError({
268 tracker: input.tracker,
269 reason: "failed",
270 detail: "This credential is already connected as another account.",
271 });
272 }
273 yield* secrets
274 .set(issueTrackerSecretName(api.kind, accountId), encoder.encode(token))
275 .pipe(Effect.mapError(secretFailure(api.kind, "The credential could not be stored.")));
276 if (addAccount && accountId !== null) {
277 const createdAt = DateTime.formatIso(yield* DateTime.now);
278 yield* bindings.addAccount({ tracker: api.kind, accountId, createdAt }).pipe(
279 Effect.tapError(() =>
280 Effect.ignore(secrets.remove(issueTrackerSecretName(api.kind, accountId))),
281 ),
282 Effect.mapError(secretFailure(api.kind, "The account could not be saved.")),
283 );
284 }
285 return accountId;
286 }),
287 );
288 return {
289 ...api.standalone,
290 ...accountFields(accountId),
291 connected: true,
292 account: probed.account,
293 detail: null,
294 ...(probed.workspace === undefined ? {} : { workspace: probed.workspace }),
295 scopes: probed.scopes,
296 };
297 });
298​
299 const bindProject: IssueTrackerConnections["Service"]["bindProject"] = Effect.fn(
300 "IssueTrackerConnections.bindProject",
301 )(function* (input) {
302 if (input.binding === null) {
303 // Older clients cannot see a project bound with an added account and offer it as unbound;
304 // an unbind that does not name the binding's account leaves it alone.
305 const current = (yield* bindings
306 .list(input.projectId)
307 .pipe(
308 Effect.mapError(secretFailure(anyTracker, "The project bindings could not be read.")),
309 )).get(input.projectId);
310 if (current !== undefined && current.accountId !== input.accountId) return;
311 } else {
312 yield* requireAccount(
313 (yield* requireTracker(input.binding.tracker)).kind,
314 input.binding.accountId,
315 );
316 }
317 // Unbinding names no tracker; the first registered one carries any report.
318 const tracker = input.binding?.tracker ?? anyTracker;
319 const updatedAt = DateTime.formatIso(yield* DateTime.now);
320 yield* bindings
321 .set({ projectId: input.projectId, binding: input.binding, updatedAt })
322 .pipe(Effect.mapError(secretFailure(tracker, "The project binding could not be saved.")));
323 }, accountLock.withPermits(1));
324​
325 return IssueTrackerConnections.of({ list, connect, bindProject });
326});
327​
328export const layer = Layer.effect(IssueTrackerConnections, make);