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