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

SourceControlProviderRegistry.ts

321 lines11.5 KB

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 Exit from "effect/Exit";
7import * as Layer from "effect/Layer";
8import {
9 SourceControlProviderError,
10 type SourceControlProviderDiscoveryItem,
11} from "@t3tools/contracts";
12import type {} from "@t3tools/contracts";
13import { detectSourceControlProviderFromRemoteUrl } from "@t3tools/shared/sourceControl";
14​
15import * as BuiltInDrivers from "./builtInDrivers.ts";
16import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
17import {
18 probeSourceControlProvider,
19 refineUnknownRemoteProvider,
20 type SourceControlProviderDiscoverySpec,
21} from "@t3tools/source-control-core/server/discovery";
22import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
23​
24import * as ServerConfig from "../config.ts";
25import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
26​
27const PROVIDER_DETECTION_CACHE_CAPACITY = 2_048;
28const PROVIDER_DETECTION_CACHE_TTL = Duration.seconds(5);
29​
30export interface SourceControlProviderRegistration {
31 readonly kind: SourceControlProviderKind;
32 readonly provider: SourceControlProvider.SourceControlProvider["Service"];
33 readonly discovery: SourceControlProviderDiscoverySpec;
35​
36export interface SourceControlProviderHandle {
37 readonly provider: SourceControlProvider.SourceControlProvider["Service"];
38 readonly context: SourceControlProvider.SourceControlProviderContext | null;
40​
41export class SourceControlProviderRegistry extends Context.Service<
42 SourceControlProviderRegistry,
43 {
44 readonly resolveLink: SourceControlProvider.ResolveSourceControlLink;
45 readonly get: (
46 kind: SourceControlProviderKind,
47 ) => Effect.Effect<
48 SourceControlProvider.SourceControlProvider["Service"],
49 SourceControlProviderError
50 >;
51 readonly resolveHandle: (input: {
52 readonly cwd: string;
53 readonly context?: SourceControlProvider.SourceControlProviderContext;
54 }) => Effect.Effect<SourceControlProviderHandle, SourceControlProviderError>;
55 readonly resolve: (input: {
56 readonly cwd: string;
57 }) => Effect.Effect<
58 SourceControlProvider.SourceControlProvider["Service"],
59 SourceControlProviderError
60 >;
61 readonly discover: Effect.Effect<ReadonlyArray<SourceControlProviderDiscoveryItem>>;
62 }
63>()("t3/sourceControl/SourceControlProviderRegistry") {}
64​
65function unsupportedProvider(
66 kind: SourceControlProviderKind,
67): SourceControlProvider.SourceControlProvider["Service"] {
68 return SourceControlProvider.SourceControlProvider.of({
69 kind,
70 // A remote on a host no provider recognizes (or no remote at all) has no change
71 // requests T3 could know about. Answering with none keeps the status poller from
72 // failing, and warning, on every refresh of such a repository.
73 listChangeRequests: (input) =>
74 kind === "unknown"
75 ? Effect.succeed([])
76 : new SourceControlProviderError({
77 provider: kind,
78 operation: "listChangeRequests",
79 cwd: input.cwd,
80 detail: `No ${kind} source control provider is registered.`,
81 }),
82 getChangeRequest: (input) =>
83 new SourceControlProviderError({
84 provider: kind,
85 operation: "getChangeRequest",
86 cwd: input.cwd,
87 reference: SourceControlProvider.transportSafeSourceControlErrorValue(input.reference),
88 detail: `No ${kind} source control provider is registered.`,
89 }),
90 createChangeRequest: (input) =>
91 new SourceControlProviderError({
92 provider: kind,
93 operation: "createChangeRequest",
94 cwd: input.cwd,
95 reference: SourceControlProvider.transportSafeSourceControlErrorValue(input.headSelector),
96 detail: `No ${kind} source control provider is registered.`,
97 }),
98 getRepositoryCloneUrls: (input) =>
99 new SourceControlProviderError({
100 provider: kind,
101 operation: "getRepositoryCloneUrls",
102 cwd: input.cwd,
103 repository: SourceControlProvider.transportSafeSourceControlErrorValue(input.repository),
104 detail: `No ${kind} source control provider is registered.`,
105 }),
106 createRepository: (input) =>
107 new SourceControlProviderError({
108 provider: kind,
109 operation: "createRepository",
110 cwd: input.cwd,
111 repository: SourceControlProvider.transportSafeSourceControlErrorValue(input.repository),
112 detail: `No ${kind} source control provider is registered.`,
113 }),
114 getDefaultBranch: (input) =>
115 new SourceControlProviderError({
116 provider: kind,
117 operation: "getDefaultBranch",
118 cwd: input.cwd,
119 detail: `No ${kind} source control provider is registered.`,
120 }),
121 checkoutChangeRequest: (input) =>
122 new SourceControlProviderError({
123 provider: kind,
124 operation: "checkoutChangeRequest",
125 cwd: input.cwd,
126 reference: SourceControlProvider.transportSafeSourceControlErrorValue(input.reference),
127 detail: `No ${kind} source control provider is registered.`,
128 }),
129 });
131​
132function selectProviderContext(
133 remotes: ReadonlyArray<{
134 readonly name: string;
135 readonly url: string;
136 }>,
137): SourceControlProvider.SourceControlProviderContext | null {
138 const candidates: Array<SourceControlProvider.SourceControlProviderContext> = [];
139 for (const remote of remotes) {
140 const provider = detectSourceControlProviderFromRemoteUrl(remote.url);
141 if (provider) {
142 candidates.push({
143 provider,
144 remoteName: remote.name,
145 remoteUrl: remote.url,
146 });
147 }
148 }
149​
150 return (
151 candidates.find((candidate) => candidate.remoteName === "origin") ??
152 candidates.find((candidate) => candidate.provider.kind !== "unknown") ??
153 candidates[0] ??
154 null
155 );
157​
158function bindProviderContext(
159 provider: SourceControlProvider.SourceControlProvider["Service"],
160 context: SourceControlProvider.SourceControlProviderContext | null,
161): SourceControlProvider.SourceControlProvider["Service"] {
162 if (context === null) {
163 return provider;
164 }
165​
166 return SourceControlProvider.SourceControlProvider.of({
167 ...provider,
168 listChangeRequests: (input) =>
169 provider.listChangeRequests({
170 ...input,
171 context: input.context ?? context,
172 }),
173 getChangeRequest: (input) =>
174 provider.getChangeRequest({
175 ...input,
176 context: input.context ?? context,
177 }),
178 createChangeRequest: (input) =>
179 provider.createChangeRequest({
180 ...input,
181 context: input.context ?? context,
182 }),
183 getRepositoryCloneUrls: (input) =>
184 provider.getRepositoryCloneUrls({
185 ...input,
186 context: input.context ?? context,
187 }),
188 createRepository: (input) => provider.createRepository(input),
189 getDefaultBranch: (input) =>
190 provider.getDefaultBranch({
191 ...input,
192 context: input.context ?? context,
193 }),
194 checkoutChangeRequest: (input) =>
195 provider.checkoutChangeRequest({
196 ...input,
197 context: input.context ?? context,
198 }),
199 });
201​
202/** @public Service construction is part of the canonical Effect module API. */
203export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWithProviders")(
204 function* (registrations: ReadonlyArray<SourceControlProviderRegistration>) {
205 const config = yield* ServerConfig.ServerConfig;
206 const { process } = yield* SourceControlHost.SourceControlHost;
207 const vcsRegistry = yield* VcsDriverRegistry.VcsDriverRegistry;
208 const providers = new Map<
209 SourceControlProviderKind,
210 SourceControlProvider.SourceControlProvider["Service"]
211 >(registrations.map((registration) => [registration.kind, registration.provider]));
212 const discoverySpecs = registrations.map((registration) => registration.discovery);
213​
214 const get: SourceControlProviderRegistry["Service"]["get"] = (kind) =>
215 Effect.succeed(providers.get(kind) ?? unsupportedProvider(kind));
216​
217 const detectProviderContext = Effect.fn("SourceControlProviderRegistry.detectProviderContext")(
218 function* (cwd: string) {
219 const handle = yield* vcsRegistry.resolve({ cwd }).pipe(
220 Effect.mapError(
221 (error) =>
222 new SourceControlProviderError({
223 provider: SourceControlProviderKind.make("unknown"),
224 operation: "detectProvider",
225 cwd,
226 detail: "Failed to detect source control provider.",
227 cause: error,
228 }),
229 ),
230 );
231 const remotes = yield* handle.driver.listRemotes(cwd).pipe(
232 Effect.mapError(
233 (error) =>
234 new SourceControlProviderError({
235 provider: SourceControlProviderKind.make("unknown"),
236 operation: "detectProvider",
237 cwd,
238 detail: "Failed to detect source control provider.",
239 cause: error,
240 }),
241 ),
242 );
243 const context = selectProviderContext(remotes.remotes);
244​
245 return yield* refineUnknownRemoteProvider({
246 specs: discoverySpecs,
247 process,
248 cwd,
249 context,
250 });
251 },
252 );
253​
254 const providerContextCache = yield* Cache.makeWith<
255 string,
256 SourceControlProvider.SourceControlProviderContext | null,
257 SourceControlProviderError
258 >(detectProviderContext, {
259 capacity: PROVIDER_DETECTION_CACHE_CAPACITY,
260 timeToLive: (exit) => (Exit.isSuccess(exit) ? PROVIDER_DETECTION_CACHE_TTL : Duration.zero),
261 });
262​
263 const resolveHandle: SourceControlProviderRegistry["Service"]["resolveHandle"] = (input) =>
264 (input.context === undefined
265 ? Cache.get(providerContextCache, input.cwd)
266 : refineUnknownRemoteProvider({
267 specs: discoverySpecs,
268 process,
269 cwd: input.cwd,
270 context: input.context,
271 })
272 ).pipe(
273 Effect.map((context) => {
274 const kind = context?.provider.kind ?? SourceControlProviderKind.make("unknown");
275 const provider = providers.get(kind) ?? unsupportedProvider(kind);
276 return {
277 provider: bindProviderContext(provider, context),
278 context,
279 } satisfies SourceControlProviderHandle;
280 }),
281 );
282​
283 return SourceControlProviderRegistry.of({
284 resolveLink: (input) => {
285 if (input.url.protocol !== "https:" || input.url.username || input.url.password) {
286 return undefined;
287 }
288 const kind = detectSourceControlProviderFromRemoteUrl(input.url.href)?.kind;
289 return kind ? providers.get(kind)?.resolveLink?.(input) : undefined;
290 },
291 get,
292 resolveHandle,
293 resolve: (input) => resolveHandle(input).pipe(Effect.map((handle) => handle.provider)),
294 discover: Effect.forEach(
295 discoverySpecs,
296 (spec) =>
297 probeSourceControlProvider({
298 spec,
299 process,
300 cwd: config.cwd,
301 }),
302 { concurrency: "unbounded" },
303 ),
304 });
305 },
306);
307​
308export const make = Effect.gen(function* () {
309 const drivers = yield* Effect.forEach(BuiltInDrivers.BUILT_IN_SOURCE_CONTROL_DRIVERS, (driver) =>
310 driver.make.pipe(
311 Effect.map((instance): SourceControlProviderRegistration => ({
312 kind: driver.kind,
313 provider: instance.sourceControl,
314 discovery: instance.discovery,
315 })),
316 ),
317 );
318 return yield* makeWithProviders(drivers);
319});
320​
321export const layer = Layer.effect(SourceControlProviderRegistry, make);