Open History to see the last commit
1import { SourceControlProviderKind } from "@t3tools/contracts";
2import * as Cache from "effect/Cache";
3import * as Context from "effect/Context";
4import * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
6import * as Equal from "effect/Equal";
7import * as Exit from "effect/Exit";
8import * as Hash from "effect/Hash";
9import * as Layer from "effect/Layer";
10import * as Stream from "effect/Stream";
11import {
12 SourceControlProviderError,
13 type SourceControlProviderDiscoveryItem,
14} from "@t3tools/contracts";
15import type {} from "@t3tools/contracts";
16import { detectSourceControlProviderFromRemoteUrl } from "@t3tools/shared/sourceControl";
17
18import * as BuiltInDrivers from "./builtInDrivers.ts";
19import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
20import {
21 probeSourceControlProvider,
22 refineUnknownRemoteProvider,
23 type SourceControlProviderDiscoverySpec,
24 type UnknownRemoteVerdict,
25} from "@t3tools/source-control-core/server/discovery";
26import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
27
28import * as ServerConfig from "../config.ts";
29import * as ServerSettings from "../serverSettings.ts";
30import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
31
32const PROVIDER_DETECTION_CACHE_CAPACITY = 2_048;
33const PROVIDER_DETECTION_CACHE_TTL = Duration.seconds(5);
34const UNKNOWN_REMOTE_CACHE_CAPACITY = 512;
35// Outlasts the one-minute pull request sweep. A login made since is noticed after this.
36const UNKNOWN_REMOTE_CACHE_TTL = Duration.minutes(5);
37
38export interface SourceControlProviderRegistration {
39 readonly kind: SourceControlProviderKind;
40 readonly provider: SourceControlProvider.SourceControlProvider["Service"];
41 readonly discovery: SourceControlProviderDiscoverySpec;
42}
43
44export interface SourceControlProviderHandle {
45 readonly provider: SourceControlProvider.SourceControlProvider["Service"];
46 readonly context: SourceControlProvider.SourceControlProviderContext | null;
47}
48
49export class SourceControlProviderRegistry extends Context.Service<
50 SourceControlProviderRegistry,
51 {
52 readonly resolveLink: SourceControlProvider.ResolveSourceControlLink;
53 readonly get: (
54 kind: SourceControlProviderKind,
55 ) => Effect.Effect<
56 SourceControlProvider.SourceControlProvider["Service"],
57 SourceControlProviderError
58 >;
59 readonly resolveHandle: (input: {
60 readonly cwd: string;
61 readonly context?: SourceControlProvider.SourceControlProviderContext;
62 }) => Effect.Effect<SourceControlProviderHandle, SourceControlProviderError>;
63 readonly resolve: (input: {
64 readonly cwd: string;
65 }) => Effect.Effect<
66 SourceControlProvider.SourceControlProvider["Service"],
67 SourceControlProviderError
68 >;
69 readonly discover: Effect.Effect<ReadonlyArray<SourceControlProviderDiscoveryItem>>;
70 }
71>()("t3/sourceControl/SourceControlProviderRegistry") {}
72
73function unsupportedProvider(
74 kind: SourceControlProviderKind,
75): SourceControlProvider.SourceControlProvider["Service"] {
76 return SourceControlProvider.SourceControlProvider.of({
77 kind,
78 listChangeRequests: (input) =>
79 new SourceControlProviderError({
80 provider: kind,
81 operation: "listChangeRequests",
82 cwd: input.cwd,
83 detail: `No ${kind} source control provider is registered.`,
84 }),
85 getChangeRequest: (input) =>
86 new SourceControlProviderError({
87 provider: kind,
88 operation: "getChangeRequest",
89 cwd: input.cwd,
90 reference: SourceControlProvider.transportSafeSourceControlErrorValue(input.reference),
91 detail: `No ${kind} source control provider is registered.`,
92 }),
93 createChangeRequest: (input) =>
94 new SourceControlProviderError({
95 provider: kind,
96 operation: "createChangeRequest",
97 cwd: input.cwd,
98 reference: SourceControlProvider.transportSafeSourceControlErrorValue(input.headSelector),
99 detail: `No ${kind} source control provider is registered.`,
100 }),
101 getRepositoryCloneUrls: (input) =>
102 new SourceControlProviderError({
103 provider: kind,
104 operation: "getRepositoryCloneUrls",
105 cwd: input.cwd,
106 repository: SourceControlProvider.transportSafeSourceControlErrorValue(input.repository),
107 detail: `No ${kind} source control provider is registered.`,
108 }),
109 createRepository: (input) =>
110 new SourceControlProviderError({
111 provider: kind,
112 operation: "createRepository",
113 cwd: input.cwd,
114 repository: SourceControlProvider.transportSafeSourceControlErrorValue(input.repository),
115 detail: `No ${kind} source control provider is registered.`,
116 }),
117 getDefaultBranch: (input) =>
118 new SourceControlProviderError({
119 provider: kind,
120 operation: "getDefaultBranch",
121 cwd: input.cwd,
122 detail: `No ${kind} source control provider is registered.`,
123 }),
124 checkoutChangeRequest: (input) =>
125 new SourceControlProviderError({
126 provider: kind,
127 operation: "checkoutChangeRequest",
128 cwd: input.cwd,
129 reference: SourceControlProvider.transportSafeSourceControlErrorValue(input.reference),
130 detail: `No ${kind} source control provider is registered.`,
131 }),
132 });
133}
134
135function selectProviderContext(
136 remotes: ReadonlyArray<{
137 readonly name: string;
138 readonly url: string;
139 }>,
140): SourceControlProvider.SourceControlProviderContext | null {
141 const candidates: Array<SourceControlProvider.SourceControlProviderContext> = [];
142 for (const remote of remotes) {
143 const provider = detectSourceControlProviderFromRemoteUrl(remote.url);
144 if (provider) {
145 candidates.push({
146 provider,
147 remoteName: remote.name,
148 remoteUrl: remote.url,
149 });
150 }
151 }
152
153 return (
154 candidates.find((candidate) => candidate.remoteName === "origin") ??
155 candidates.find((candidate) => candidate.provider.kind !== "unknown") ??
156 candidates[0] ??
157 null
158 );
159}
160
161/**
162 * One lookup per server: remotes that differ only in `owner/repo` share a verdict, and callers
163 * that arrive while it runs wait on it. `cwd` is left out because it only matters when a probe
164 * fails there, and a failed probe is not kept. Equality ignores `lookup`, so this is not a
165 * `Data.Class`.
166 */
167class UnknownRemoteLookup {
168 readonly key: string;
169 readonly lookup: Effect.Effect<UnknownRemoteVerdict>;
170
171 constructor(
172 context: SourceControlProvider.SourceControlProviderContext,
173 lookup: Effect.Effect<UnknownRemoteVerdict>,
174 ) {
175 this.lookup = lookup;
176 this.key = [
177 context.provider.name,
178 context.provider.baseUrl,
179 // Strip a trailing `owner/repo`, never the host after `//`, so one-segment remotes stay apart.
180 context.remoteUrl.trim().replace(/(?<!\/\/[^/]*)[^/:]+\/[^/:]+\/?$/u, ""),
181 context.requestedHost ?? "",
182 ].join("\n");
183 }
184
185 [Equal.symbol](that: unknown): boolean {
186 return that instanceof UnknownRemoteLookup && that.key === this.key;
187 }
188 [Hash.symbol](): number {
189 return Hash.string(this.key);
190 }
191}
192
193function bindProviderContext(
194 provider: SourceControlProvider.SourceControlProvider["Service"],
195 context: SourceControlProvider.SourceControlProviderContext | null,
196): SourceControlProvider.SourceControlProvider["Service"] {
197 if (context === null) {
198 return provider;
199 }
200
201 return SourceControlProvider.SourceControlProvider.of({
202 ...provider,
203 listChangeRequests: (input) =>
204 provider.listChangeRequests({
205 ...input,
206 context: input.context ?? context,
207 }),
208 getChangeRequest: (input) =>
209 provider.getChangeRequest({
210 ...input,
211 context: input.context ?? context,
212 }),
213 createChangeRequest: (input) =>
214 provider.createChangeRequest({
215 ...input,
216 context: input.context ?? context,
217 }),
218 getRepositoryCloneUrls: (input) =>
219 provider.getRepositoryCloneUrls({
220 ...input,
221 context: input.context ?? context,
222 }),
223 createRepository: (input) => provider.createRepository(input),
224 getDefaultBranch: (input) =>
225 provider.getDefaultBranch({
226 ...input,
227 context: input.context ?? context,
228 }),
229 checkoutChangeRequest: (input) =>
230 provider.checkoutChangeRequest({
231 ...input,
232 context: input.context ?? context,
233 }),
234 });
235}
236
237/** @public Service construction is part of the canonical Effect module API. */
238export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWithProviders")(
239 function* (registrations: ReadonlyArray<SourceControlProviderRegistration>) {
240 const config = yield* ServerConfig.ServerConfig;
241 const serverSettings = yield* ServerSettings.ServerSettingsService;
242 const { process } = yield* SourceControlHost.SourceControlHost;
243 const vcsRegistry = yield* VcsDriverRegistry.VcsDriverRegistry;
244 const providers = new Map<
245 SourceControlProviderKind,
246 SourceControlProvider.SourceControlProvider["Service"]
247 >(registrations.map((registration) => [registration.kind, registration.provider]));
248 const discoverySpecs = registrations.map((registration) => registration.discovery);
249
250 const get: SourceControlProviderRegistry["Service"]["get"] = (kind) =>
251 Effect.succeed(providers.get(kind) ?? unsupportedProvider(kind));
252
253 // "No integration holds this host" is the common verdict and the one worth keeping. A verdict
254 // reached while some probe failed is handed to the callers waiting on it, then dropped.
255 const unknownRemoteCache = yield* Cache.makeWith(
256 (request: UnknownRemoteLookup) => request.lookup,
257 {
258 capacity: UNKNOWN_REMOTE_CACHE_CAPACITY,
259 timeToLive: (exit) =>
260 Exit.isSuccess(exit) && exit.value.settled ? UNKNOWN_REMOTE_CACHE_TTL : Duration.zero,
261 },
262 );
263 // A token saved or a host toggled in Settings must show on the next read, not after the TTL.
264 const settingsChanges = yield* serverSettings.subscribeChanges;
265 yield* Stream.runForEach(settingsChanges, () => Cache.invalidateAll(unknownRemoteCache)).pipe(
266 Effect.forkScoped,
267 );
268
269 const refineContext = (
270 cwd: string,
271 context: SourceControlProvider.SourceControlProviderContext | null,
272 ): Effect.Effect<SourceControlProvider.SourceControlProviderContext | null> =>
273 context === null || context.provider.kind !== "unknown"
274 ? Effect.succeed(context)
275 : Cache.get(
276 unknownRemoteCache,
277 new UnknownRemoteLookup(
278 context,
279 refineUnknownRemoteProvider({ specs: discoverySpecs, process, cwd, context }),
280 ),
281 ).pipe(Effect.map(({ provider }) => (provider ? { ...context, provider } : context)));
282
283 const detectProviderContext = Effect.fn("SourceControlProviderRegistry.detectProviderContext")(
284 function* (cwd: string) {
285 const handle = yield* vcsRegistry.resolve({ cwd }).pipe(
286 Effect.mapError(
287 (error) =>
288 new SourceControlProviderError({
289 provider: SourceControlProviderKind.make("unknown"),
290 operation: "detectProvider",
291 cwd,
292 detail: "Failed to detect source control provider.",
293 cause: error,
294 }),
295 ),
296 );
297 const remotes = yield* handle.driver.listRemotes(cwd).pipe(
298 Effect.mapError(
299 (error) =>
300 new SourceControlProviderError({
301 provider: SourceControlProviderKind.make("unknown"),
302 operation: "detectProvider",
303 cwd,
304 detail: "Failed to detect source control provider.",
305 cause: error,
306 }),
307 ),
308 );
309 return yield* refineContext(cwd, selectProviderContext(remotes.remotes));
310 },
311 );
312
313 const providerContextCache = yield* Cache.makeWith<
314 string,
315 SourceControlProvider.SourceControlProviderContext | null,
316 SourceControlProviderError
317 >(detectProviderContext, {
318 capacity: PROVIDER_DETECTION_CACHE_CAPACITY,
319 timeToLive: (exit) => (Exit.isSuccess(exit) ? PROVIDER_DETECTION_CACHE_TTL : Duration.zero),
320 });
321
322 const resolveHandle: SourceControlProviderRegistry["Service"]["resolveHandle"] = (input) =>
323 (input.context === undefined
324 ? Cache.get(providerContextCache, input.cwd)
325 : refineContext(input.cwd, input.context)
326 ).pipe(
327 Effect.map((context) => {
328 const kind = context?.provider.kind ?? SourceControlProviderKind.make("unknown");
329 const provider = providers.get(kind) ?? unsupportedProvider(kind);
330 return {
331 provider: bindProviderContext(provider, context),
332 context,
333 } satisfies SourceControlProviderHandle;
334 }),
335 );
336
337 return SourceControlProviderRegistry.of({
338 resolveLink: (input) => {
339 if (input.url.protocol !== "https:" || input.url.username || input.url.password) {
340 return undefined;
341 }
342 const kind = detectSourceControlProviderFromRemoteUrl(input.url.href)?.kind;
343 return kind ? providers.get(kind)?.resolveLink?.(input) : undefined;
344 },
345 get,
346 resolveHandle,
347 resolve: (input) => resolveHandle(input).pipe(Effect.map((handle) => handle.provider)),
348 discover: Effect.forEach(
349 discoverySpecs,
350 (spec) =>
351 probeSourceControlProvider({
352 spec,
353 process,
354 cwd: config.cwd,
355 }),
356 { concurrency: "unbounded" },
357 ),
358 });
359 },
360);
361
362export const make = Effect.gen(function* () {
363 const drivers = yield* Effect.forEach(BuiltInDrivers.BUILT_IN_SOURCE_CONTROL_DRIVERS, (driver) =>
364 driver.make.pipe(
365 Effect.map((instance): SourceControlProviderRegistration => ({
366 kind: driver.kind,
367 provider: instance.sourceControl,
368 discovery: instance.discovery,
369 })),
370 ),
371 );
372 return yield* makeWithProviders(drivers);
373});
374
375export const layer = Layer.effect(SourceControlProviderRegistry, make);