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 kind: provider.kind,
162 ...(provider.resolveLink ? { resolveLink: provider.resolveLink } : {}),
163 listChangeRequests: (input) =>
164 provider.listChangeRequests({
165 ...input,
166 context: input.context ?? context,
167 }),
168 getChangeRequest: (input) =>
169 provider.getChangeRequest({
170 ...input,
171 context: input.context ?? context,
172 }),
173 createChangeRequest: (input) =>
174 provider.createChangeRequest({
175 ...input,
176 context: input.context ?? context,
177 }),
178 getRepositoryCloneUrls: (input) =>
179 provider.getRepositoryCloneUrls({
180 ...input,
181 context: input.context ?? context,
182 }),
183 createRepository: (input) => provider.createRepository(input),
184 getDefaultBranch: (input) =>
185 provider.getDefaultBranch({
186 ...input,
187 context: input.context ?? context,
188 }),
189 checkoutChangeRequest: (input) =>
190 provider.checkoutChangeRequest({
191 ...input,
192 context: input.context ?? context,
193 }),
194 });
195}
196
197/** @public Service construction is part of the canonical Effect module API. */
198export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWithProviders")(
199 function* (registrations: ReadonlyArray<SourceControlProviderRegistration>) {
200 const config = yield* ServerConfig.ServerConfig;
201 const { process } = yield* SourceControlHost.SourceControlHost;
202 const vcsRegistry = yield* VcsDriverRegistry.VcsDriverRegistry;
203 const providers = new Map<
204 SourceControlProviderKind,
205 SourceControlProvider.SourceControlProvider["Service"]
206 >(registrations.map((registration) => [registration.kind, registration.provider]));
207 const discoverySpecs = registrations.map((registration) => registration.discovery);
208
209 const get: SourceControlProviderRegistry["Service"]["get"] = (kind) =>
210 Effect.succeed(providers.get(kind) ?? unsupportedProvider(kind));
211
212 const detectProviderContext = Effect.fn("SourceControlProviderRegistry.detectProviderContext")(
213 function* (cwd: string) {
214 const handle = yield* vcsRegistry.resolve({ cwd }).pipe(
215 Effect.mapError(
216 (error) =>
217 new SourceControlProviderError({
218 provider: "unknown",
219 operation: "detectProvider",
220 cwd,
221 detail: "Failed to detect source control provider.",
222 cause: error,
223 }),
224 ),
225 );
226 const remotes = yield* handle.driver.listRemotes(cwd).pipe(
227 Effect.mapError(
228 (error) =>
229 new SourceControlProviderError({
230 provider: "unknown",
231 operation: "detectProvider",
232 cwd,
233 detail: "Failed to detect source control provider.",
234 cause: error,
235 }),
236 ),
237 );
238 const context = selectProviderContext(remotes.remotes);
239
240 return yield* refineUnknownRemoteProvider({
241 specs: discoverySpecs,
242 process,
243 cwd,
244 context,
245 });
246 },
247 );
248
249 const providerContextCache = yield* Cache.makeWith<
250 string,
251 SourceControlProvider.SourceControlProviderContext | null,
252 SourceControlProviderError
253 >(detectProviderContext, {
254 capacity: PROVIDER_DETECTION_CACHE_CAPACITY,
255 timeToLive: (exit) => (Exit.isSuccess(exit) ? PROVIDER_DETECTION_CACHE_TTL : Duration.zero),
256 });
257
258 const resolveHandle: SourceControlProviderRegistry["Service"]["resolveHandle"] = (input) =>
259 (input.context === undefined
260 ? Cache.get(providerContextCache, input.cwd)
261 : refineUnknownRemoteProvider({
262 specs: discoverySpecs,
263 process,
264 cwd: input.cwd,
265 context: input.context,
266 })
267 ).pipe(
268 Effect.map((context) => {
269 const kind = context?.provider.kind ?? "unknown";
270 const provider = providers.get(kind) ?? unsupportedProvider(kind);
271 return {
272 provider: bindProviderContext(provider, context),
273 context,
274 } satisfies SourceControlProviderHandle;
275 }),
276 );
277
278 return SourceControlProviderRegistry.of({
279 resolveLink: (input) => {
280 if (input.url.protocol !== "https:" || input.url.username || input.url.password) {
281 return undefined;
282 }
283 const kind = detectSourceControlProviderFromRemoteUrl(input.url.href)?.kind;
284 return kind ? providers.get(kind)?.resolveLink?.(input) : undefined;
285 },
286 get,
287 resolveHandle,
288 resolve: (input) => resolveHandle(input).pipe(Effect.map((handle) => handle.provider)),
289 discover: Effect.forEach(
290 discoverySpecs,
291 (spec) =>
292 probeSourceControlProvider({
293 spec,
294 process,
295 cwd: config.cwd,
296 }),
297 { concurrency: "unbounded" },
298 ),
299 });
300 },
301);
302
303export const make = Effect.gen(function* () {
304 const drivers = yield* Effect.forEach(BuiltInDrivers.BUILT_IN_SOURCE_CONTROL_DRIVERS, (driver) =>
305 driver.make.pipe(
306 Effect.map((instance): SourceControlProviderRegistration => ({
307 kind: driver.kind,
308 provider: instance.sourceControl,
309 discovery: instance.discovery,
310 })),
311 ),
312 );
313 return yield* makeWithProviders(drivers);
314});
315
316export const layer = Layer.effect(SourceControlProviderRegistry, make);