@devries-cameron20 / t3code Mirror · read-only / commits / a8e8e7ee11
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 23, 00:30 UTC

refactor(effect): trace shared and source-control operations (#21990)

Julius Marminge committed Oct 19, 2026 at 18:30 UTC a8e8e7ee1152c48aa89b2b37d3109777a541e687
20 files changed +1150 -1120
packages/shared/src/DrainableWorker.ts
+42 -39
@@ -15,50 +15,53 @@ export interface DrainableWorker<A> {
15 * closes instead of waiting on them. An item that fails or dies is logged and skipped; the worker
16 * keeps processing later items and `drain` still resolves.
17 */
18 -export const makeDrainableWorker = <A, E, R>(
18 +export const makeDrainableWorker = Effect.fn("DrainableWorker.makeDrainableWorker")(function* <
19 + A,
20 + E,
21 + R,
22 +>(
23 process: (item: A) => Effect.Effect<void, E, R>,
20 -): Effect.Effect<DrainableWorker<A>, never, Scope.Scope | R> =>
21 - Effect.gen(function* () {
22 - const outstanding = yield* TxRef.make(0);
23 - const queue = yield* Effect.acquireRelease(TxQueue.unbounded<A>(), (queue) =>
24 - // Uncount only the dropped items: an item still running uncounts itself,
25 - // even when a parallel scope closes it after this finalizer.
26 - TxQueue.clear(queue).pipe(
27 - Effect.flatMap((dropped) => TxRef.update(outstanding, (n) => n - dropped.length)),
28 - Effect.andThen(TxQueue.shutdown(queue)),
29 - Effect.tx,
30 - ),
31 - );
24 +): Effect.fn.Return<DrainableWorker<A>, never, Scope.Scope | R> {
25 + const outstanding = yield* TxRef.make(0);
26 + const queue = yield* Effect.acquireRelease(TxQueue.unbounded<A>(), (queue) =>
27 + // Uncount only the dropped items: an item still running uncounts itself,
28 + // even when a parallel scope closes it after this finalizer.
29 + TxQueue.clear(queue).pipe(
30 + Effect.flatMap((dropped) => TxRef.update(outstanding, (n) => n - dropped.length)),
31 + Effect.andThen(TxQueue.shutdown(queue)),
32 + Effect.tx,
33 + ),
34 + );
35
33 - yield* TxQueue.take(queue).pipe(
34 - Effect.flatMap((a) =>
35 - // `suspend` turns a `process` that throws while building its effect
36 - // into this item's defect instead of the loop's.
37 - Effect.suspend(() => process(a)).pipe(
38 - // Only the item's own failure, defect, or interruption lands here and
39 - // the loop continues; interrupting the worker fiber still stops it.
40 - Effect.catchCause((cause) =>
41 - Cause.hasInterruptsOnly(cause)
42 - ? Effect.void
43 - : Effect.logError("DrainableWorker item failed", cause),
44 - ),
45 - Effect.ensuring(TxRef.update(outstanding, (n) => n - 1)),
36 + yield* TxQueue.take(queue).pipe(
37 + Effect.flatMap((a) =>
38 + // `suspend` turns a `process` that throws while building its effect
39 + // into this item's defect instead of the loop's.
40 + Effect.suspend(() => process(a)).pipe(
41 + // Only the item's own failure, defect, or interruption lands here and
42 + // the loop continues; interrupting the worker fiber still stops it.
43 + Effect.catchCause((cause) =>
44 + Cause.hasInterruptsOnly(cause)
45 + ? Effect.void
46 + : Effect.logError("DrainableWorker item failed", cause),
47 ),
48 + Effect.ensuring(TxRef.update(outstanding, (n) => n - 1)),
49 ),
48 - Effect.forever,
49 - Effect.forkScoped,
50 - );
50 + ),
51 + Effect.forever,
52 + Effect.forkScoped,
53 + );
54 +
55 + const drain: DrainableWorker<A>["drain"] = TxRef.get(outstanding).pipe(
56 + Effect.flatMap((n) => (n > 0 ? Effect.txRetry : Effect.void)),
57 + Effect.tx,
58 + );
59
52 - const drain: DrainableWorker<A>["drain"] = TxRef.get(outstanding).pipe(
53 - Effect.flatMap((n) => (n > 0 ? Effect.txRetry : Effect.void)),
60 + const enqueue = (element: A): Effect.Effect<boolean, never, never> =>
61 + TxQueue.offer(queue, element).pipe(
62 + Effect.tap((offered) => (offered ? TxRef.update(outstanding, (n) => n + 1) : Effect.void)),
63 Effect.tx,
64 );
65
57 - const enqueue = (element: A): Effect.Effect<boolean, never, never> =>
58 - TxQueue.offer(queue, element).pipe(
59 - Effect.tap((offered) => (offered ? TxRef.update(outstanding, (n) => n + 1) : Effect.void)),
60 - Effect.tx,
61 - );
62 -
63 - return { enqueue, drain } satisfies DrainableWorker<A>;
64 - });
66 + return { enqueue, drain } satisfies DrainableWorker<A>;
67 +});
packages/shared/src/KeyedCoalescingWorker.ts
+82 -83
@@ -14,100 +14,99 @@ interface KeyedCoalescingWorkerState<K, V> {
14 readonly activeKeys: Set<K>;
15 }
16
17 -export const makeKeyedCoalescingWorker = <K, V, E, R>(options: {
17 +export const makeKeyedCoalescingWorker = Effect.fn(
18 + "KeyedCoalescingWorker.makeKeyedCoalescingWorker",
19 +)(function* <K, V, E, R>(options: {
20 readonly merge: (current: V, next: V) => V;
21 readonly process: (key: K, value: V) => Effect.Effect<void, E, R>;
20 -}): Effect.Effect<KeyedCoalescingWorker<K, V>, never, Scope.Scope | R> =>
21 - Effect.gen(function* () {
22 - const queue = yield* Effect.acquireRelease(TxQueue.unbounded<K>(), TxQueue.shutdown);
23 - const stateRef = yield* TxRef.make<KeyedCoalescingWorkerState<K, V>>({
24 - latestByKey: new Map(),
25 - queuedKeys: new Set(),
26 - activeKeys: new Set(),
27 - });
22 +}): Effect.fn.Return<KeyedCoalescingWorker<K, V>, never, Scope.Scope | R> {
23 + const queue = yield* Effect.acquireRelease(TxQueue.unbounded<K>(), TxQueue.shutdown);
24 + const stateRef = yield* TxRef.make<KeyedCoalescingWorkerState<K, V>>({
25 + latestByKey: new Map(),
26 + queuedKeys: new Set(),
27 + activeKeys: new Set(),
28 + });
29
29 - const completeKey = (key: K): Effect.Effect<void> =>
30 - TxRef.modify(stateRef, (state) => {
31 - const activeKeys = new Set(state.activeKeys);
32 - activeKeys.delete(key);
30 + const completeKey = (key: K): Effect.Effect<void> =>
31 + TxRef.modify(stateRef, (state) => {
32 + const activeKeys = new Set(state.activeKeys);
33 + activeKeys.delete(key);
34
34 - if (state.latestByKey.has(key) && !state.queuedKeys.has(key)) {
35 - const queuedKeys = new Set(state.queuedKeys);
36 - queuedKeys.add(key);
37 - return [true, { ...state, activeKeys, queuedKeys }] as const;
38 - }
35 + if (state.latestByKey.has(key) && !state.queuedKeys.has(key)) {
36 + const queuedKeys = new Set(state.queuedKeys);
37 + queuedKeys.add(key);
38 + return [true, { ...state, activeKeys, queuedKeys }] as const;
39 + }
40
40 - return [false, { ...state, activeKeys }] as const;
41 - }).pipe(
42 - Effect.flatMap((shouldRequeue) =>
43 - shouldRequeue ? TxQueue.offer(queue, key) : Effect.void,
44 - ),
45 - Effect.tx,
46 - Effect.asVoid,
47 - );
41 + return [false, { ...state, activeKeys }] as const;
42 + }).pipe(
43 + Effect.flatMap((shouldRequeue) => (shouldRequeue ? TxQueue.offer(queue, key) : Effect.void)),
44 + Effect.tx,
45 + Effect.asVoid,
46 + );
47
49 - yield* TxQueue.take(queue).pipe(
50 - Effect.flatMap((key) =>
51 - TxRef.modify(stateRef, (state) => {
52 - const queuedKeys = new Set(state.queuedKeys);
53 - queuedKeys.delete(key);
48 + yield* TxQueue.take(queue).pipe(
49 + Effect.flatMap((key) =>
50 + TxRef.modify(stateRef, (state) => {
51 + const queuedKeys = new Set(state.queuedKeys);
52 + queuedKeys.delete(key);
53
55 - const value = state.latestByKey.get(key);
56 - if (value === undefined) {
57 - return [null, { ...state, queuedKeys }] as const;
58 - }
54 + const value = state.latestByKey.get(key);
55 + if (value === undefined) {
56 + return [null, { ...state, queuedKeys }] as const;
57 + }
58
60 - const latestByKey = new Map(state.latestByKey);
61 - latestByKey.delete(key);
62 - const activeKeys = new Set(state.activeKeys);
63 - activeKeys.add(key);
59 + const latestByKey = new Map(state.latestByKey);
60 + latestByKey.delete(key);
61 + const activeKeys = new Set(state.activeKeys);
62 + activeKeys.add(key);
63
65 - return [
66 - { key, value } as const,
67 - { ...state, latestByKey, queuedKeys, activeKeys },
68 - ] as const;
69 - }).pipe(Effect.tx),
70 - ),
71 - Effect.flatMap((item) =>
72 - item === null
73 - ? Effect.void
74 - : options
75 - .process(item.key, item.value)
76 - .pipe(Effect.ignoreCause, Effect.ensuring(completeKey(item.key))),
77 - ),
78 - Effect.forever,
79 - Effect.forkScoped,
80 - );
64 + return [
65 + { key, value } as const,
66 + { ...state, latestByKey, queuedKeys, activeKeys },
67 + ] as const;
68 + }).pipe(Effect.tx),
69 + ),
70 + Effect.flatMap((item) =>
71 + item === null
72 + ? Effect.void
73 + : options
74 + .process(item.key, item.value)
75 + .pipe(Effect.ignoreCause, Effect.ensuring(completeKey(item.key))),
76 + ),
77 + Effect.forever,
78 + Effect.forkScoped,
79 + );
80
82 - const enqueue: KeyedCoalescingWorker<K, V>["enqueue"] = (key, value) =>
83 - TxRef.modify(stateRef, (state) => {
84 - const latestByKey = new Map(state.latestByKey);
85 - const existing = latestByKey.get(key);
86 - latestByKey.set(key, existing === undefined ? value : options.merge(existing, value));
81 + const enqueue: KeyedCoalescingWorker<K, V>["enqueue"] = (key, value) =>
82 + TxRef.modify(stateRef, (state) => {
83 + const latestByKey = new Map(state.latestByKey);
84 + const existing = latestByKey.get(key);
85 + latestByKey.set(key, existing === undefined ? value : options.merge(existing, value));
86
88 - if (state.queuedKeys.has(key) || state.activeKeys.has(key)) {
89 - return [false, { ...state, latestByKey }] as const;
90 - }
87 + if (state.queuedKeys.has(key) || state.activeKeys.has(key)) {
88 + return [false, { ...state, latestByKey }] as const;
89 + }
90
92 - const queuedKeys = new Set(state.queuedKeys);
93 - queuedKeys.add(key);
94 - return [true, { ...state, latestByKey, queuedKeys }] as const;
95 - }).pipe(
96 - Effect.flatMap((shouldOffer) => (shouldOffer ? TxQueue.offer(queue, key) : Effect.void)),
97 - Effect.tx,
98 - Effect.asVoid,
99 - );
91 + const queuedKeys = new Set(state.queuedKeys);
92 + queuedKeys.add(key);
93 + return [true, { ...state, latestByKey, queuedKeys }] as const;
94 + }).pipe(
95 + Effect.flatMap((shouldOffer) => (shouldOffer ? TxQueue.offer(queue, key) : Effect.void)),
96 + Effect.tx,
97 + Effect.asVoid,
98 + );
99
101 - const drainKey: KeyedCoalescingWorker<K, V>["drainKey"] = (key) =>
102 - TxRef.get(stateRef).pipe(
103 - Effect.tap((state) =>
104 - state.latestByKey.has(key) || state.queuedKeys.has(key) || state.activeKeys.has(key)
105 - ? Effect.txRetry
106 - : Effect.void,
107 - ),
108 - Effect.asVoid,
109 - Effect.tx,
110 - );
100 + const drainKey: KeyedCoalescingWorker<K, V>["drainKey"] = (key) =>
101 + TxRef.get(stateRef).pipe(
102 + Effect.tap((state) =>
103 + state.latestByKey.has(key) || state.queuedKeys.has(key) || state.activeKeys.has(key)
104 + ? Effect.txRetry
105 + : Effect.void,
106 + ),
107 + Effect.asVoid,
108 + Effect.tx,
109 + );
110
112 - return { enqueue, drainKey } satisfies KeyedCoalescingWorker<K, V>;
113 - });
111 + return { enqueue, drainKey } satisfies KeyedCoalescingWorker<K, V>;
112 +});
packages/shared/src/KeyedLock.ts
+35 -34
@@ -15,41 +15,42 @@ interface LockEntry {
15 /**
16 * Not reentrant: taking a key while already holding it deadlocks.
17 */
18 -export const make = <Key>(): Effect.Effect<KeyedLock<Key>> =>
19 - Effect.gen(function* () {
20 - const locks = yield* Ref.make<ReadonlyMap<Key, LockEntry>>(new Map());
18 +export const make = Effect.fn("KeyedLock.make")(function* <Key>(): Effect.fn.Return<
19 + KeyedLock<Key>
20 +> {
21 + const locks = yield* Ref.make<ReadonlyMap<Key, LockEntry>>(new Map());
22
22 - const acquire = (key: Key) =>
23 - Effect.flatMap(Semaphore.make(1), (candidate) =>
24 - Ref.modify(locks, (current) => {
25 - const existing = current.get(key);
26 - const semaphore = existing?.semaphore ?? candidate;
27 - const next = new Map(current);
28 - next.set(key, { semaphore, users: (existing?.users ?? 0) + 1 });
29 - return [semaphore, next] as const;
30 - }),
31 - );
32 -
33 - const release = (key: Key) =>
34 - Ref.update(locks, (current) => {
23 + const acquire = (key: Key) =>
24 + Effect.flatMap(Semaphore.make(1), (candidate) =>
25 + Ref.modify(locks, (current) => {
26 const existing = current.get(key);
36 - if (existing === undefined) return current;
27 + const semaphore = existing?.semaphore ?? candidate;
28 const next = new Map(current);
38 - if (existing.users === 1) {
39 - next.delete(key);
40 - } else {
41 - next.set(key, { ...existing, users: existing.users - 1 });
42 - }
43 - return next;
44 - });
29 + next.set(key, { semaphore, users: (existing?.users ?? 0) + 1 });
30 + return [semaphore, next] as const;
31 + }),
32 + );
33 +
34 + const release = (key: Key) =>
35 + Ref.update(locks, (current) => {
36 + const existing = current.get(key);
37 + if (existing === undefined) return current;
38 + const next = new Map(current);
39 + if (existing.users === 1) {
40 + next.delete(key);
41 + } else {
42 + next.set(key, { ...existing, users: existing.users - 1 });
43 + }
44 + return next;
45 + });
46
46 - return {
47 - withLock: (key, effect) =>
48 - Effect.acquireUseRelease(
49 - acquire(key),
50 - (semaphore) => semaphore.withPermit(effect),
51 - () => release(key),
52 - ),
53 - activeKeys: Effect.map(Ref.get(locks), (current) => Array.from(current.keys())),
54 - } satisfies KeyedLock<Key>;
55 - });
47 + return {
48 + withLock: (key, effect) =>
49 + Effect.acquireUseRelease(
50 + acquire(key),
51 + (semaphore) => semaphore.withPermit(effect),
52 + () => release(key),
53 + ),
54 + activeKeys: Effect.map(Ref.get(locks), (current) => Array.from(current.keys())),
55 + } satisfies KeyedLock<Key>;
56 +});
packages/shared/src/Net.ts
+24 -24
@@ -111,23 +111,24 @@ export const make = () => {
111 });
112 });
113
114 - const isPortAvailableOnLoopback = (port: number): Effect.Effect<boolean> =>
115 - Effect.gen(function* () {
116 - const hasListener = yield* Effect.zipWith(
117 - hasListenerOnHost(port, "127.0.0.1"),
118 - hasListenerOnHost(port, "::1"),
119 - (ipv4, ipv6) => ipv4 || ipv6,
120 - );
121 - if (hasListener) {
122 - return false;
123 - }
124 -
125 - return yield* Effect.zipWith(
126 - canListenOnHost(port, "127.0.0.1"),
127 - canListenOnHost(port, "::1"),
128 - (ipv4, ipv6) => ipv4 && ipv6,
129 - );
130 - });
114 + const isPortAvailableOnLoopback = Effect.fn("Net.isPortAvailableOnLoopback")(function* (
115 + port: number,
116 + ): Effect.fn.Return<boolean> {
117 + const hasListener = yield* Effect.zipWith(
118 + hasListenerOnHost(port, "127.0.0.1"),
119 + hasListenerOnHost(port, "::1"),
120 + (ipv4, ipv6) => ipv4 || ipv6,
121 + );
122 + if (hasListener) {
123 + return false;
124 + }
125 +
126 + return yield* Effect.zipWith(
127 + canListenOnHost(port, "127.0.0.1"),
128 + canListenOnHost(port, "::1"),
129 + (ipv4, ipv6) => ipv4 && ipv6,
130 + );
131 + });
132
133 const reserveLoopbackPort = (host = "127.0.0.1"): Effect.Effect<number, NetError> =>
134 Effect.callback<number, NetError>((resume) => {
@@ -166,13 +167,12 @@ export const make = () => {
167 isPortAvailableOnLoopback,
168 hasListenerOnHost,
169 reserveLoopbackPort,
169 - findAvailablePort: (preferred) =>
170 - Effect.gen(function* () {
171 - if (preferred > 0 && (yield* isPortAvailableOnLoopback(preferred))) {
172 - return preferred;
173 - }
174 - return yield* reserveLoopbackPort();
175 - }),
170 + findAvailablePort: Effect.fn("Net.findAvailablePort")(function* (preferred) {
171 + if (preferred > 0 && (yield* isPortAvailableOnLoopback(preferred))) {
172 + return preferred;
173 + }
174 + return yield* reserveLoopbackPort();
175 + }),
176 } satisfies NetServiceShape;
177 };
178
packages/shared/src/atomicWrite.test.ts
+5 -4
@@ -277,11 +277,12 @@ it.effect("surfaces an unreadable link instead of writing over it", () =>
277 pathOrDescriptor: "/home/settings.json",
278 });
279
280 - const result = yield* Effect.exit(
281 - writeFileStringAtomically({ filePath: "/home/settings.json", contents: "after" }),
282 - );
280 + const failure = yield* writeFileStringAtomically({
281 + filePath: "/home/settings.json",
282 + contents: "after",
283 + }).pipe(Effect.flip);
284
284 - assert.deepStrictEqual(result, Exit.fail(readLinkFailure));
285 + assert.deepStrictEqual(failure, readLinkFailure);
286 }).pipe(
287 Effect.provide(
288 Layer.mergeAll(
packages/shared/src/devHome.ts
+30 -32
@@ -33,46 +33,44 @@ const pointsAtLinkedWorktree = (gitFileContents: string, path: Path.Path): boole
33 return segments.length >= 3 && segments.at(-2) === "worktrees";
34 };
35
36 -export const resolveGitWorktreePath = (
36 +export const resolveGitWorktreePath = Effect.fn("devHome.resolveGitWorktreePath")(function* (
37 cwd: string,
38 -): Effect.Effect<string | undefined, never, FileSystem.FileSystem | Path.Path> =>
39 - Effect.gen(function* () {
40 - const fileSystem = yield* FileSystem.FileSystem;
41 - const path = yield* Path.Path;
38 +): Effect.fn.Return<string | undefined, never, FileSystem.FileSystem | Path.Path> {
39 + const fileSystem = yield* FileSystem.FileSystem;
40 + const path = yield* Path.Path;
41
43 - let directory = path.resolve(cwd);
44 - for (;;) {
45 - const gitPath = path.join(directory, ".git");
46 - const info = yield* fileSystem.stat(gitPath).pipe(Effect.option);
47 - if (Option.isSome(info)) {
48 - if (info.value.type !== "File") {
49 - return undefined;
50 - }
51 - const contents = yield* fileSystem
52 - .readFileString(gitPath)
53 - .pipe(Effect.orElseSucceed(() => ""));
54 - return pointsAtLinkedWorktree(contents, path) ? directory : undefined;
55 - }
56 - const parent = path.dirname(directory);
57 - if (parent === directory) {
42 + let directory = path.resolve(cwd);
43 + for (;;) {
44 + const gitPath = path.join(directory, ".git");
45 + const info = yield* fileSystem.stat(gitPath).pipe(Effect.option);
46 + if (Option.isSome(info)) {
47 + if (info.value.type !== "File") {
48 return undefined;
49 }
60 - directory = parent;
50 + const contents = yield* fileSystem
51 + .readFileString(gitPath)
52 + .pipe(Effect.orElseSucceed(() => ""));
53 + return pointsAtLinkedWorktree(contents, path) ? directory : undefined;
54 + }
55 + const parent = path.dirname(directory);
56 + if (parent === directory) {
57 + return undefined;
58 }
62 - });
59 + directory = parent;
60 + }
61 +});
62
63 /**
64 * Deliberately does not require the directory to exist yet: falling back
65 * because it is missing would send callers at the shared home.
66 */
68 -export const resolveWorktreeT3Home = (
67 +export const resolveWorktreeT3Home = Effect.fn("devHome.resolveWorktreeT3Home")(function* (
68 cwd: string,
70 -): Effect.Effect<string | undefined, never, FileSystem.FileSystem | Path.Path> =>
71 - Effect.gen(function* () {
72 - const worktreePath = yield* resolveGitWorktreePath(cwd);
73 - if (worktreePath === undefined) {
74 - return undefined;
75 - }
76 - const path = yield* Path.Path;
77 - return path.join(worktreePath, ".t3");
78 - });
69 +): Effect.fn.Return<string | undefined, never, FileSystem.FileSystem | Path.Path> {
70 + const worktreePath = yield* resolveGitWorktreePath(cwd);
71 + if (worktreePath === undefined) {
72 + return undefined;
73 + }
74 + const path = yield* Path.Path;
75 + return path.join(worktreePath, ".t3");
76 +});
packages/shared/src/shell.ts
+3 -2
@@ -511,8 +511,9 @@ const PathDirectoryListings = Context.Reference<
511 Cache.Cache<string, PathDirectoryListing, never, FileSystem.FileSystem> | undefined
512 >("@t3tools/shared/shell/PathDirectoryListings", { defaultValue: () => undefined });
513
514 -export const withPathDirectoryListings = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
515 - Effect.gen(function* () {
514 +export const withPathDirectoryListings =
515 + /* Directory reads are cached inside one shell operation; a span for each lookup adds noise. */
516 + Effect.fnUntraced(function* <A, E, R>(effect: Effect.Effect<A, E, R>) {
517 const listings = yield* Cache.make({
518 capacity: 1024,
519 lookup: listPathDirectory,
packages/shared/src/symlink.ts
+27 -26
@@ -17,31 +17,32 @@ const isNotASymlink = (error: PlatformError.PlatformError) =>
17 * on a cycle, an overly long chain, or an unreadable link rather than handing
18 * back a link that a rename would replace.
19 */
20 -export const resolveSymlinkTarget = (filePath: string) =>
21 - Effect.gen(function* () {
22 - const fs = yield* FileSystem.FileSystem;
23 - const path = yield* Path.Path;
24 - let current = path.resolve(filePath);
25 - for (let hop = 0; hop < MAX_SYMLINK_HOPS; hop++) {
26 - const link = yield* fs.readLink(current).pipe(
27 - Effect.map(Option.some),
28 - Effect.catchIf(isNotASymlink, () => Effect.succeedNone),
29 - );
30 - if (Option.isNone(link)) {
31 - return current;
32 - }
33 - // A relative target is relative to where the link really lives, which
34 - // differs from its lexical parent when that parent is itself a symlink.
35 - const linkDirectory = yield* fs
36 - .realPath(path.dirname(current))
37 - .pipe(Effect.catchIf(isNotFound, () => Effect.succeed(path.dirname(current))));
38 - current = path.resolve(linkDirectory, link.value);
20 +export const resolveSymlinkTarget = Effect.fn("symlink.resolveSymlinkTarget")(function* (
21 + filePath: string,
22 +) {
23 + const fs = yield* FileSystem.FileSystem;
24 + const path = yield* Path.Path;
25 + let current = path.resolve(filePath);
26 + for (let hop = 0; hop < MAX_SYMLINK_HOPS; hop++) {
27 + const link = yield* fs.readLink(current).pipe(
28 + Effect.map(Option.some),
29 + Effect.catchIf(isNotASymlink, () => Effect.succeedNone),
30 + );
31 + if (Option.isNone(link)) {
32 + return current;
33 }
40 - return yield* PlatformError.systemError({
41 - _tag: "Unknown",
42 - module: "FileSystem",
43 - method: "readLink",
44 - description: "Too many levels of symbolic links",
45 - pathOrDescriptor: filePath,
46 - });
34 + // A relative target is relative to where the link really lives, which
35 + // differs from its lexical parent when that parent is itself a symlink.
36 + const linkDirectory = yield* fs
37 + .realPath(path.dirname(current))
38 + .pipe(Effect.catchIf(isNotFound, () => Effect.succeed(path.dirname(current))));
39 + current = path.resolve(linkDirectory, link.value);
40 + }
41 + return yield* PlatformError.systemError({
42 + _tag: "Unknown",
43 + module: "FileSystem",
44 + method: "readLink",
45 + description: "Too many levels of symbolic links",
46 + pathOrDescriptor: filePath,
47 });
48 +});
packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.ts
+32 -22
@@ -176,17 +176,19 @@ export const make = Effect.gen(function* () {
176 );
177 };
178
179 - const diffScope = (input: { readonly cwd: string; readonly number: number }) =>
180 - Effect.gen(function* () {
181 - const location = yield* locationOf(input);
182 - if (location === null) return null;
183 - const iterations = yield* cli.listIterations({
184 - cwd: input.cwd,
185 - location,
186 - number: input.number,
187 - });
188 - return { location, iterations };
179 + const diffScope = Effect.fn("AzureDevOpsPullRequestProvider.diffScope")(function* (input: {
180 + readonly cwd: string;
181 + readonly number: number;
182 + }) {
183 + const location = yield* locationOf(input);
184 + if (location === null) return null;
185 + const iterations = yield* cli.listIterations({
186 + cwd: input.cwd,
187 + location,
188 + number: input.number,
189 });
190 + return { location, iterations };
191 + });
192
193 const EMPTY_ITEM: AzureDevOpsItemContent = { contents: "", isBinary: false };
194
@@ -305,8 +307,8 @@ export const make = Effect.gen(function* () {
307 })),
308 ),
309
308 - getChangeRequest: (input) =>
309 - Effect.gen(function* () {
310 + getChangeRequest: Effect.fn("AzureDevOpsPullRequestProvider.getChangeRequest")(
311 + function* (input) {
312 const pullRequest = yield* cli.getPullRequest({ cwd: input.cwd, number: input.number });
313 const location = pullRequest.location;
314 const iterations =
@@ -346,7 +348,9 @@ export const make = Effect.gen(function* () {
348 : { autoMergeMethod: pullRequest.autoMergeMethod }),
349 };
350 return detail;
349 - }).pipe(Effect.mapError(fail("getChangeRequest"))),
351 + },
352 + Effect.mapError(fail("getChangeRequest")),
353 + ),
354
355 getChangeRequestActivity: (input) =>
356 cli.getPullRequest({ cwd: input.cwd, number: input.number }).pipe(
@@ -380,8 +384,8 @@ export const make = Effect.gen(function* () {
384
385 // `input.commit` is deliberately dropped: Azure states no commit list on a pull request, so
386 // the Code tab has nothing to scope itself to and always asks for the whole change.
383 - getDiff: (input) =>
384 - Effect.gen(function* () {
387 + getDiff: Effect.fn("AzureDevOpsPullRequestProvider.getDiff")(
388 + function* (input) {
389 const scope = yield* diffScope(input);
390 if (scope === null) return EMPTY_DIFF_SLICE;
391 const cursor = parseAzureDevOpsDiffCursor(input.cursor);
@@ -479,10 +483,12 @@ export const make = Effect.gen(function* () {
483 : formatAzureDevOpsDiffCursor({ iterationId: iteration.id, fileIndex: index }),
484 };
485 return slice;
482 - }).pipe(Effect.mapError(fail("getDiff"))),
486 + },
487 + Effect.mapError(fail("getDiff")),
488 + ),
489
484 - getDiffFileContents: (input) =>
485 - Effect.gen(function* () {
490 + getDiffFileContents: Effect.fn("AzureDevOpsPullRequestProvider.getDiffFileContents")(
491 + function* (input) {
492 const scope = yield* diffScope(input);
493 const iteration = scope?.iterations.at(-1);
494 if (scope === null || iteration === undefined) return { oldContents: "", newContents: "" };
@@ -496,15 +502,17 @@ export const make = Effect.gen(function* () {
502 oldPath: input.oldPath,
503 },
504 });
499 - }).pipe(Effect.mapError(fail("getDiffFileContents"))),
505 + },
506 + Effect.mapError(fail("getDiffFileContents")),
507 + ),
508
509 /**
510 * A path the change does not carry is at the empty revision, which is where a file the pull
511 * request deletes sits. When the change was too long to follow to its end, those paths are left
512 * out instead: reporting them as deleted would clear a file nobody has read.
513 */
506 - getFileRevisions: (input) =>
507 - Effect.gen(function* () {
514 + getFileRevisions: Effect.fn("AzureDevOpsPullRequestProvider.getFileRevisions")(
515 + function* (input) {
516 const revisions = new Map<string, string>();
517 if (input.paths.length === 0) return { revisions };
518 const scope = yield* diffScope(input);
@@ -525,7 +533,9 @@ export const make = Effect.gen(function* () {
533 }
534 }
535 return { revisions };
528 - }).pipe(Effect.mapError(fail("getFileRevisions"))),
536 + },
537 + Effect.mapError(fail("getFileRevisions")),
538 + ),
539
540 runAction: (input) =>
541 cli
packages/source-control-bitbucket/src/server/BitbucketApi.ts
+82 -82
@@ -602,35 +602,33 @@ function originOf(value: string): string | null {
602 }
603 }
604
605 -function responseError(
605 +const responseError = Effect.fn("BitbucketApi.responseError")(function* (
606 operation: BitbucketApiOperation,
607 response: HttpClientResponse.HttpClientResponse,
608 -): Effect.Effect<never, BitbucketApiError> {
609 - return Effect.gen(function* () {
610 - const now = yield* Clock.currentTimeMillis;
611 - const retryAt = retryAtFromHeader(response.headers["retry-after"], now);
612 - const collected = yield* collectUint8StreamText({
613 - stream: response.stream,
614 - maxBytes: DEFAULT_MAX_RESPONSE_BYTES,
615 - }).pipe(
616 - Effect.mapError(
617 - (cause) =>
618 - new BitbucketResponseBodyReadError({
619 - operation,
620 - status: response.status,
621 - retryAt,
622 - cause,
623 - }),
624 - ),
625 - );
626 - return yield* new BitbucketResponseError({
627 - operation,
628 - status: response.status,
629 - responseBodyLength: collected.text.length,
630 - retryAt,
631 - });
608 +): Effect.fn.Return<never, BitbucketApiError> {
609 + const now = yield* Clock.currentTimeMillis;
610 + const retryAt = retryAtFromHeader(response.headers["retry-after"], now);
611 + const collected = yield* collectUint8StreamText({
612 + stream: response.stream,
613 + maxBytes: DEFAULT_MAX_RESPONSE_BYTES,
614 + }).pipe(
615 + Effect.mapError(
616 + (cause) =>
617 + new BitbucketResponseBodyReadError({
618 + operation,
619 + status: response.status,
620 + retryAt,
621 + cause,
622 + }),
623 + ),
624 + );
625 + return yield* new BitbucketResponseError({
626 + operation,
627 + status: response.status,
628 + responseBodyLength: collected.text.length,
629 + retryAt,
630 });
633 -}
631 +});
632
633 /** @public Service construction is part of the canonical Effect module API. */
634 export const make = Effect.gen(function* () {
@@ -1015,52 +1013,51 @@ export const make = Effect.gen(function* () {
1013 ),
1014 Effect.map(normalizeRepositoryCloneUrls),
1015 ),
1018 - createPullRequest: (input) =>
1019 - Effect.gen(function* () {
1020 - const repository = yield* resolveRepository(input);
1021 - const description = yield* fileSystem.readFileString(input.bodyFile).pipe(
1022 - Effect.mapError(
1023 - (cause) =>
1024 - new BitbucketPullRequestBodyReadError({
1025 - cwd: input.cwd,
1026 - bodyFile: input.bodyFile,
1027 - cause,
1028 - }),
1029 - ),
1030 - );
1031 - const sourceOwner = sourceWorkspace(input);
1032 - const body = {
1033 - title: input.title,
1034 - description,
1035 - source: {
1036 - branch: {
1037 - name: SourceControlProvider.sourceBranch(input),
1038 - },
1039 - ...(sourceOwner
1040 - ? {
1041 - repository: {
1042 - full_name: `${sourceOwner}/${input.source?.repository ?? repository.repoSlug}`,
1043 - },
1044 - }
1045 - : {}),
1016 + createPullRequest: Effect.fn("BitbucketApi.createPullRequest")(function* (input) {
1017 + const repository = yield* resolveRepository(input);
1018 + const description = yield* fileSystem.readFileString(input.bodyFile).pipe(
1019 + Effect.mapError(
1020 + (cause) =>
1021 + new BitbucketPullRequestBodyReadError({
1022 + cwd: input.cwd,
1023 + bodyFile: input.bodyFile,
1024 + cause,
1025 + }),
1026 + ),
1027 + );
1028 + const sourceOwner = sourceWorkspace(input);
1029 + const body = {
1030 + title: input.title,
1031 + description,
1032 + source: {
1033 + branch: {
1034 + name: SourceControlProvider.sourceBranch(input),
1035 },
1047 - destination: {
1048 - branch: {
1049 - name: input.target?.refName ?? input.baseBranch,
1050 - },
1036 + ...(sourceOwner
1037 + ? {
1038 + repository: {
1039 + full_name: `${sourceOwner}/${input.source?.repository ?? repository.repoSlug}`,
1040 + },
1041 + }
1042 + : {}),
1043 + },
1044 + destination: {
1045 + branch: {
1046 + name: input.target?.refName ?? input.baseBranch,
1047 },
1052 - };
1053 -
1054 - yield* executeJson(
1055 - "createPullRequest",
1056 - HttpClientRequest.post(
1057 - apiUrl(
1058 - `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/pullrequests`,
1059 - ),
1060 - ).pipe(HttpClientRequest.bodyJsonUnsafe(body)),
1061 - BitbucketPullRequestSchema,
1062 - );
1063 - }),
1048 + },
1049 + };
1050 +
1051 + yield* executeJson(
1052 + "createPullRequest",
1053 + HttpClientRequest.post(
1054 + apiUrl(
1055 + `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/pullrequests`,
1056 + ),
1057 + ).pipe(HttpClientRequest.bodyJsonUnsafe(body)),
1058 + BitbucketPullRequestSchema,
1059 + );
1060 + }),
1061 getDefaultBranch: (input) =>
1062 resolveRepository(input).pipe(
1063 Effect.flatMap((locator) =>
@@ -1078,8 +1075,8 @@ export const make = Effect.gen(function* () {
1075 ),
1076 Effect.map(defaultChangeRequestTargetBranch),
1077 ),
1081 - checkoutPullRequest: (input) =>
1082 - Effect.gen(function* () {
1078 + checkoutPullRequest: Effect.fn("BitbucketApi.checkoutPullRequest")(
1079 + function* (input) {
1080 const destinationRepository = yield* resolveRepository(input);
1081 const pullRequest = yield* getRawPullRequestFromRepository(
1082 destinationRepository,
@@ -1129,17 +1126,20 @@ export const make = Effect.gen(function* () {
1126 remoteBranch,
1127 });
1128 yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch }));
1132 - }).pipe(
1133 - Effect.mapError((cause) =>
1134 - isBitbucketApiError(cause)
1135 - ? cause
1136 - : new BitbucketCheckoutError({
1137 - cwd: input.cwd,
1138 - reference: input.reference,
1139 - cause,
1140 - }),
1129 + },
1130 + (effect, input) =>
1131 + effect.pipe(
1132 + Effect.mapError((cause) =>
1133 + isBitbucketApiError(cause)
1134 + ? cause
1135 + : new BitbucketCheckoutError({
1136 + cwd: input.cwd,
1137 + reference: input.reference,
1138 + cause,
1139 + }),
1140 + ),
1141 ),
1142 - ),
1142 + ),
1143 });
1144 });
1145
packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.ts
+30 -18
@@ -306,8 +306,8 @@ export const make = Effect.gen(function* () {
306 kind: SourceControlProviderKind.make("forgejo"),
307 repositoryNameFromRemoteUrl,
308 refineRepositoryIdentity,
309 - listChangeRequests: (input) =>
310 - Effect.gen(function* () {
309 + listChangeRequests: Effect.fn("ForgejoSourceControlProvider.listChangeRequests")(
310 + function* (input) {
311 const repo = yield* cli.resolveRepository(input);
312 const source = SourceControlProvider.sourceControlRefFromInput(input);
313 const branch = SourceControlProvider.sourceBranch(input);
@@ -334,14 +334,16 @@ export const make = Effect.gen(function* () {
334 if (items.length === 0) break;
335 }
336 return results.slice(0, limit);
337 - }).pipe(mapError("listChangeRequests", input.cwd)),
337 + },
338 + (effect, input) => effect.pipe(mapError("listChangeRequests", input.cwd)),
339 + ),
340 getChangeRequest: (input) =>
341 getPull(input).pipe(
342 Effect.map(toForgejoChangeRequest),
343 mapError("getChangeRequest", input.cwd),
344 ),
343 - createChangeRequest: (input) =>
344 - Effect.gen(function* () {
345 + createChangeRequest: Effect.fn("ForgejoSourceControlProvider.createChangeRequest")(
346 + function* (input) {
347 const repo = yield* cli.resolveRepository(input);
348 const source = SourceControlProvider.sourceControlRefFromInput(input);
349 const owner = source?.owner ?? source?.repository?.split("/")[0];
@@ -357,16 +359,20 @@ export const make = Effect.gen(function* () {
359 body: yield* fs.readFileString(input.bodyFile),
360 },
361 });
360 - }).pipe(mapError("createChangeRequest", input.cwd)),
361 - getRepositoryCloneUrls: (input) =>
362 - Effect.gen(function* () {
362 + },
363 + (effect, input) => effect.pipe(mapError("createChangeRequest", input.cwd)),
364 + ),
365 + getRepositoryCloneUrls: Effect.fn("ForgejoSourceControlProvider.getRepositoryCloneUrls")(
366 + function* (input) {
367 const repo = yield* cli.resolveRepository(input);
368 return cloneUrls(
369 yield* request({ ...input, path: repositoryPath(repo.repository) }, RepositorySchema),
370 );
367 - }).pipe(mapError("getRepositoryCloneUrls", input.cwd)),
368 - createRepository: (input) =>
369 - Effect.gen(function* () {
371 + },
372 + (effect, input) => effect.pipe(mapError("getRepositoryCloneUrls", input.cwd)),
373 + ),
374 + createRepository: Effect.fn("ForgejoSourceControlProvider.createRepository")(
375 + function* (input) {
376 const repo = yield* cli.resolveRepository(input);
377 const user = yield* request(
378 { ...input, path: "user" },
@@ -387,17 +393,21 @@ export const make = Effect.gen(function* () {
393 RepositorySchema,
394 ),
395 );
390 - }).pipe(mapError("createRepository", input.cwd)),
391 - getDefaultBranch: (input) =>
392 - Effect.gen(function* () {
396 + },
397 + (effect, input) => effect.pipe(mapError("createRepository", input.cwd)),
398 + ),
399 + getDefaultBranch: Effect.fn("ForgejoSourceControlProvider.getDefaultBranch")(
400 + function* (input) {
401 const repo = yield* cli.resolveRepository(input);
402 return (
403 (yield* request({ ...input, path: repositoryPath(repo.repository) }, RepositorySchema))
404 .default_branch ?? null
405 );
398 - }).pipe(mapError("getDefaultBranch", input.cwd)),
399 - checkoutChangeRequest: (input) =>
400 - Effect.gen(function* () {
406 + },
407 + (effect, input) => effect.pipe(mapError("getDefaultBranch", input.cwd)),
408 + ),
409 + checkoutChangeRequest: Effect.fn("ForgejoSourceControlProvider.checkoutChangeRequest")(
410 + function* (input) {
411 const repo = yield* cli.resolveRepository(input);
412 const pull = yield* getPull(input);
413 if (repo.command === "fj") {
@@ -468,6 +478,8 @@ export const make = Effect.gen(function* () {
478 args: ["reset", "--keep", pull.head.sha],
479 });
480 }
471 - }).pipe(mapError("checkoutChangeRequest", input.cwd)),
481 + },
482 + (effect, input) => effect.pipe(mapError("checkoutChangeRequest", input.cwd)),
483 + ),
484 });
485 });
packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts
+16 -25
@@ -230,31 +230,22 @@ export const make = Effect.gen(function* () {
230 Effect.flatMap((path) => read(operation, input, { path }, Json.GitCafePullDetail)),
231 );
232
233 - const readPages = <S extends Schema.Codec<Paged<unknown>, unknown, never, never>>(
234 - operation: string,
235 - input: Pick<ProviderRepositoryRef, "host">,
236 - path: string,
237 - schema: S,
238 - ) =>
239 - Effect.gen(function* () {
240 - const items: Array<S["Type"]["items"][number]> = [];
241 - let next: string | null = null;
242 - for (let page = 0; page < MAX_PAGES; page++) {
243 - const query = new URLSearchParams({ limit: String(PAGE_SIZE) });
244 - if (next !== null) query.set("after", next);
245 - const batch: S["Type"] = yield* read(
246 - operation,
247 - input,
248 - { path: `${path}?${query}` },
249 - schema,
250 - );
251 - items.push(...batch.items);
252 - const previous: string | null = next;
253 - next = batch.next;
254 - if (next === null || next === previous || batch.items.length === 0) break;
255 - }
256 - return { items, next };
257 - });
233 + const readPages = Effect.fn("GitCafePullRequestProvider.readPages")(function* <
234 + S extends Schema.Codec<Paged<unknown>, unknown, never, never>,
235 + >(operation: string, input: Pick<ProviderRepositoryRef, "host">, path: string, schema: S) {
236 + const items: Array<S["Type"]["items"][number]> = [];
237 + let next: string | null = null;
238 + for (let page = 0; page < MAX_PAGES; page++) {
239 + const query = new URLSearchParams({ limit: String(PAGE_SIZE) });
240 + if (next !== null) query.set("after", next);
241 + const batch: S["Type"] = yield* read(operation, input, { path: `${path}?${query}` }, schema);
242 + items.push(...batch.items);
243 + const previous: string | null = next;
244 + next = batch.next;
245 + if (next === null || next === previous || batch.items.length === 0) break;
246 + }
247 + return { items, next };
248 + });
249
250 const readComments = (operation: string, input: PullRef) =>
251 pullPath(operation, input).pipe(
packages/source-control-github/src/server/GitHubPullRequestApi.ts
+232 -224
@@ -1024,7 +1024,7 @@ export const make = Effect.gen(function* () {
1024 * `maxPages` have been read, or `until` is satisfied. `truncated` says pages remained when
1025 * reading stopped; a cursor GitHub hands back a second time stops the read as truncated too.
1026 */
1027 - const readPages = <Page, E, R>(
1027 + const readPages = Effect.fn("GitHubPullRequestApi.readPages")(function* <Page, E, R>(
1028 stream: Stream.Stream<Page, E | GraphQLClientError.GraphQLClientError, R>,
1029 options: {
1030 readonly cwd: string;
@@ -1033,33 +1033,32 @@ export const make = Effect.gen(function* () {
1033 readonly maxPages?: number;
1034 readonly until?: (pages: ReadonlyArray<NoInfer<Page>>) => boolean;
1035 },
1036 - ) =>
1037 - Effect.gen(function* () {
1038 - const pages: Page[] = [];
1039 - let repeated = false;
1040 - yield* stream.pipe(
1041 - // `pages` fails a cursor GitHub hands back unchanged, which would page forever.
1042 - Stream.catch((error) =>
1043 - isGraphQlClientError(error) && error.reason._tag === "PaginationError"
1044 - ? Stream.sync(() => {
1045 - repeated = true;
1046 - }).pipe(Stream.drain)
1047 - : Stream.fail(error),
1048 - ),
1049 - Stream.runForEachWhile((page) =>
1050 - Effect.sync(() => {
1051 - pages.push(page);
1052 - return (
1053 - options.hasNextPage(page) &&
1054 - pages.length < (options.maxPages ?? Infinity) &&
1055 - options.until?.(pages) !== true
1056 - );
1057 - }),
1058 - ),
1059 - );
1060 - const last = pages.at(-1);
1061 - return { pages, truncated: repeated || (last !== undefined && options.hasNextPage(last)) };
1062 - });
1036 + ) {
1037 + const pages: Page[] = [];
1038 + let repeated = false;
1039 + yield* stream.pipe(
1040 + // `pages` fails a cursor GitHub hands back unchanged, which would page forever.
1041 + Stream.catch((error) =>
1042 + isGraphQlClientError(error) && error.reason._tag === "PaginationError"
1043 + ? Stream.sync(() => {
1044 + repeated = true;
1045 + }).pipe(Stream.drain)
1046 + : Stream.fail(error),
1047 + ),
1048 + Stream.runForEachWhile((page) =>
1049 + Effect.sync(() => {
1050 + pages.push(page);
1051 + return (
1052 + options.hasNextPage(page) &&
1053 + pages.length < (options.maxPages ?? Infinity) &&
1054 + options.until?.(pages) !== true
1055 + );
1056 + }),
1057 + ),
1058 + );
1059 + const last = pages.at(-1);
1060 + return { pages, truncated: repeated || (last !== undefined && options.hasNextPage(last)) };
1061 + });
1062
1063 /**
1064 * The pull request's own node id, which is what a mutation against the pull request itself is
@@ -1207,84 +1206,81 @@ export const make = Effect.gen(function* () {
1206 };
1207
1208 const getPullRequestDiffFileContents: GitHubPullRequestApi["Service"]["getPullRequestDiffFileContents"] =
1210 - (input) =>
1211 - Effect.gen(function* () {
1212 - if (input.commit !== undefined && !isCommitSha(input.commit)) {
1213 - return yield* new GitHubDiffCommitError({ cwd: input.cwd });
1214 - }
1215 - const { owner, name } = parseRepositorySelector(input.repository);
1216 - const refsResponse = yield* api.rest({
1217 - host: input.host,
1218 - operation: "getPullRequestDiffFileContents",
1219 - path:
1220 - input.commit === undefined
1221 - ? `repos/${owner}/${name}/pulls/${input.number}`
1222 - : `repos/${owner}/${name}/commits/${input.commit}`,
1223 - timeout: DIFF_TIMEOUT,
1209 + Effect.fn("GitHubPullRequestApi.getPullRequestDiffFileContents")(function* (input) {
1210 + if (input.commit !== undefined && !isCommitSha(input.commit)) {
1211 + return yield* new GitHubDiffCommitError({ cwd: input.cwd });
1212 + }
1213 + const { owner, name } = parseRepositorySelector(input.repository);
1214 + const refsResponse = yield* api.rest({
1215 + host: input.host,
1216 + operation: "getPullRequestDiffFileContents",
1217 + path:
1218 + input.commit === undefined
1219 + ? `repos/${owner}/${name}/pulls/${input.number}`
1220 + : `repos/${owner}/${name}/commits/${input.commit}`,
1221 + timeout: DIFF_TIMEOUT,
1222 + });
1223 + const refs = decodeRevisionRefs(refsResponse.body);
1224 + const baseRef = Option.isSome(refs)
1225 + ? input.commit === undefined
1226 + ? refs.value.base?.sha
1227 + : (refs.value.parents?.[0]?.sha ?? "")
1228 + : undefined;
1229 + const headRef = Option.isSome(refs)
1230 + ? input.commit === undefined
1231 + ? refs.value.head?.sha
1232 + : refs.value.sha
1233 + : undefined;
1234 + const rootCommitNewFile =
1235 + input.commit !== undefined && input.changeType === "new" && baseRef === "";
1236 + if (
1237 + headRef === undefined ||
1238 + (!rootCommitNewFile && (baseRef === undefined || !isCommitSha(baseRef))) ||
1239 + !isCommitSha(headRef)
1240 + ) {
1241 + return yield* new GitHubDiffRevisionsUnavailableError({
1242 + cwd: input.cwd,
1243 + number: input.number,
1244 + ...(input.commit === undefined ? {} : { commit: input.commit }),
1245 });
1225 - const refs = decodeRevisionRefs(refsResponse.body);
1226 - const baseRef = Option.isSome(refs)
1227 - ? input.commit === undefined
1228 - ? refs.value.base?.sha
1229 - : (refs.value.parents?.[0]?.sha ?? "")
1230 - : undefined;
1231 - const headRef = Option.isSome(refs)
1232 - ? input.commit === undefined
1233 - ? refs.value.head?.sha
1234 - : refs.value.sha
1235 - : undefined;
1236 - const rootCommitNewFile =
1237 - input.commit !== undefined && input.changeType === "new" && baseRef === "";
1238 - if (
1239 - headRef === undefined ||
1240 - (!rootCommitNewFile && (baseRef === undefined || !isCommitSha(baseRef))) ||
1241 - !isCommitSha(headRef)
1242 - ) {
1243 - return yield* new GitHubDiffRevisionsUnavailableError({
1244 - cwd: input.cwd,
1245 - number: input.number,
1246 - ...(input.commit === undefined ? {} : { commit: input.commit }),
1247 - });
1248 - }
1246 + }
1247
1250 - const readFile = (revision: string, filePath: string) =>
1251 - api
1252 - .rest({
1253 - host: input.host,
1254 - operation: "getPullRequestDiffFileContents",
1255 - accept: "application/vnd.github.raw+json",
1256 - path: `repos/${owner}/${name}/contents/${filePath
1257 - .split("/")
1258 - .map(encodeURIComponent)
1259 - .join("/")}?ref=${encodeURIComponent(revision)}`,
1260 - maxResponseBytes: DIFF_FILE_MAX_OUTPUT_BYTES,
1261 - timeout: DIFF_TIMEOUT,
1262 - })
1263 - .pipe(
1264 - Effect.flatMap((response) =>
1265 - response.truncated || response.body.includes("\0") || response.invalidUtf8
1266 - ? Effect.fail(
1267 - new GitHubDiffFileContentsUnavailableError({
1268 - cwd: input.cwd,
1269 - path: filePath,
1270 - reason: response.truncated ? "oversized" : "binary",
1271 - }),
1272 - )
1273 - : Effect.succeed(response.body),
1274 - ),
1275 - );
1248 + const readFile = (revision: string, filePath: string) =>
1249 + api
1250 + .rest({
1251 + host: input.host,
1252 + operation: "getPullRequestDiffFileContents",
1253 + accept: "application/vnd.github.raw+json",
1254 + path: `repos/${owner}/${name}/contents/${filePath
1255 + .split("/")
1256 + .map(encodeURIComponent)
1257 + .join("/")}?ref=${encodeURIComponent(revision)}`,
1258 + maxResponseBytes: DIFF_FILE_MAX_OUTPUT_BYTES,
1259 + timeout: DIFF_TIMEOUT,
1260 + })
1261 + .pipe(
1262 + Effect.flatMap((response) =>
1263 + response.truncated || response.body.includes("\0") || response.invalidUtf8
1264 + ? Effect.fail(
1265 + new GitHubDiffFileContentsUnavailableError({
1266 + cwd: input.cwd,
1267 + path: filePath,
1268 + reason: response.truncated ? "oversized" : "binary",
1269 + }),
1270 + )
1271 + : Effect.succeed(response.body),
1272 + ),
1273 + );
1274
1277 - const [oldContents, newContents] = yield* Effect.all(
1278 - [
1279 - input.changeType === "new"
1280 - ? Effect.succeed("")
1281 - : readFile(baseRef ?? "", input.oldPath),
1282 - input.changeType === "deleted" ? Effect.succeed("") : readFile(headRef, input.newPath),
1283 - ],
1284 - { concurrency: 2 },
1285 - );
1286 - return { oldContents, newContents };
1287 - });
1275 + const [oldContents, newContents] = yield* Effect.all(
1276 + [
1277 + input.changeType === "new" ? Effect.succeed("") : readFile(baseRef ?? "", input.oldPath),
1278 + input.changeType === "deleted" ? Effect.succeed("") : readFile(headRef, input.newPath),
1279 + ],
1280 + { concurrency: 2 },
1281 + );
1282 + return { oldContents, newContents };
1283 + });
1284
1285 /** `isRequired` is asked for on github.com only: an older Enterprise server may not know it. */
1286 const asksRequired = (host: string) => host.toLowerCase() === "github.com";
@@ -1294,53 +1290,52 @@ export const make = Effect.gen(function* () {
1290 * its first hundred. Each page names the head it read, so a push mid-walk fails rather than
1291 * mixing two revisions' checks.
1292 */
1297 - const readAllCheckContexts = (
1293 + const readAllCheckContexts = Effect.fn("GitHubPullRequestApi.readAllCheckContexts")(function* (
1294 input: Parameters<GitHubPullRequestApi["Service"]["getPullRequestDetail"]>[0],
1295 allowReserve: boolean,
1300 - ) =>
1301 - Effect.gen(function* () {
1302 - const { owner, name } = parseRepositorySelector(input.repository);
1303 - const target = { ...input, operation: "getPullRequestDetail", allowReserve };
1304 - let headSha: string | null = null;
1305 - const { pages, truncated } = yield* readPages(
1306 - GraphQLClient.pages(client.PullRequestCheckContexts, {
1307 - variables: { owner, name, number: input.number, required: asksRequired(input.host) },
1308 - connection: (result) => {
1309 - const page = toPullRequestCheckContextsPage(result);
1310 - if (page === null) return null;
1311 - headSha ??= page.headSha;
1312 - return {
1313 - ...page,
1314 - // Past the first page a different head is a push mid-walk.
1315 - changed: page.headSha !== headSha,
1316 - pageInfo: { hasNextPage: page.nextCursor !== null, endCursor: page.nextCursor },
1317 - };
1318 - },
1319 - }).pipe(
1320 - Stream.mapEffect((page) =>
1321 - page.changed
1322 - ? Effect.fail(
1323 - readError(
1324 - input.cwd,
1325 - "getPullRequestDetail",
1326 - new Error("Pull request head changed while reading checks."),
1327 - ),
1328 - )
1329 - : Effect.succeed(page),
1330 - ),
1331 - ),
1332 - {
1333 - ...target,
1334 - maxPages: CHECK_CONTEXT_PAGES,
1335 - hasNextPage: (page) => page.nextCursor !== null,
1296 + ) {
1297 + const { owner, name } = parseRepositorySelector(input.repository);
1298 + const target = { ...input, operation: "getPullRequestDetail", allowReserve };
1299 + let headSha: string | null = null;
1300 + const { pages, truncated } = yield* readPages(
1301 + GraphQLClient.pages(client.PullRequestCheckContexts, {
1302 + variables: { owner, name, number: input.number, required: asksRequired(input.host) },
1303 + connection: (result) => {
1304 + const page = toPullRequestCheckContextsPage(result);
1305 + if (page === null) return null;
1306 + headSha ??= page.headSha;
1307 + return {
1308 + ...page,
1309 + // Past the first page a different head is a push mid-walk.
1310 + changed: page.headSha !== headSha,
1311 + pageInfo: { hasNextPage: page.nextCursor !== null, endCursor: page.nextCursor },
1312 + };
1313 },
1337 - ).pipe(graphql(target));
1338 - return {
1339 - headSha: pages[0]?.headSha ?? null,
1340 - contexts: pages.flatMap((page) => page.contexts),
1341 - truncated,
1342 - };
1343 - });
1314 + }).pipe(
1315 + Stream.mapEffect((page) =>
1316 + page.changed
1317 + ? Effect.fail(
1318 + readError(
1319 + input.cwd,
1320 + "getPullRequestDetail",
1321 + new Error("Pull request head changed while reading checks."),
1322 + ),
1323 + )
1324 + : Effect.succeed(page),
1325 + ),
1326 + ),
1327 + {
1328 + ...target,
1329 + maxPages: CHECK_CONTEXT_PAGES,
1330 + hasNextPage: (page) => page.nextCursor !== null,
1331 + },
1332 + ).pipe(graphql(target));
1333 + return {
1334 + headSha: pages[0]?.headSha ?? null,
1335 + contexts: pages.flatMap((page) => page.contexts),
1336 + truncated,
1337 + };
1338 + });
1339
1340 const getPullRequestDetail: GitHubPullRequestApi["Service"]["getPullRequestDetail"] = (input) => {
1341 const { owner, name } = parseRepositorySelector(input.repository);
@@ -1390,49 +1385,48 @@ export const make = Effect.gen(function* () {
1385 const workflowApprovalReadError = (cwd: string, cause: unknown) =>
1386 readError(cwd, "listWorkflowRunsRequiringApproval", cause);
1387
1393 - const listHeadsByBranch = (input: {
1388 + const listHeadsByBranch = Effect.fn("GitHubPullRequestApi.listHeadsByBranch")(function* (input: {
1389 readonly cwd: string;
1390 readonly repository: string;
1391 readonly host: string;
1392 readonly headBranch: string;
1398 - }) =>
1399 - Effect.gen(function* () {
1400 - const { owner, name } = parseRepositorySelector(input.repository);
1401 - const countHeads = (pages: ReadonlyArray<{ readonly heads: ReadonlyArray<unknown> }>) =>
1402 - pages.reduce((total, page) => total + page.heads.length, 0);
1403 - const target = {
1404 - ...input,
1405 - operation: "listWorkflowRunsRequiringApproval",
1406 - allowReserve: true,
1407 - };
1408 - const { pages, truncated } = yield* readPages(
1409 - GraphQLClient.pages(client.PullRequestHeads, {
1410 - variables: { owner, name, head: input.headBranch },
1411 - connection: (result) => {
1412 - const page = toPullRequestHeads(result);
1413 - return {
1414 - ...page,
1415 - pageInfo: { hasNextPage: page.nextCursor !== null, endCursor: page.nextCursor },
1416 - };
1417 - },
1418 - }),
1419 - {
1420 - ...target,
1421 - hasNextPage: (page) => page.nextCursor !== null,
1422 - until: (pages) => countHeads(pages) > workflowApprovalLimit,
1393 + }) {
1394 + const { owner, name } = parseRepositorySelector(input.repository);
1395 + const countHeads = (pages: ReadonlyArray<{ readonly heads: ReadonlyArray<unknown> }>) =>
1396 + pages.reduce((total, page) => total + page.heads.length, 0);
1397 + const target = {
1398 + ...input,
1399 + operation: "listWorkflowRunsRequiringApproval",
1400 + allowReserve: true,
1401 + };
1402 + const { pages, truncated } = yield* readPages(
1403 + GraphQLClient.pages(client.PullRequestHeads, {
1404 + variables: { owner, name, head: input.headBranch },
1405 + connection: (result) => {
1406 + const page = toPullRequestHeads(result);
1407 + return {
1408 + ...page,
1409 + pageInfo: { hasNextPage: page.nextCursor !== null, endCursor: page.nextCursor },
1410 + };
1411 },
1424 - ).pipe(graphql(target));
1425 - return { heads: pages.flatMap((page) => page.heads), truncated };
1426 - });
1412 + }),
1413 + {
1414 + ...target,
1415 + hasNextPage: (page) => page.nextCursor !== null,
1416 + until: (pages) => countHeads(pages) > workflowApprovalLimit,
1417 + },
1418 + ).pipe(graphql(target));
1419 + return { heads: pages.flatMap((page) => page.heads), truncated };
1420 + });
1421
1428 - const listActionRequiredRuns = (input: {
1429 - readonly cwd: string;
1430 - readonly repository: string;
1431 - readonly host: string;
1432 - readonly headSha: string;
1433 - readonly headBranch: string;
1434 - }) =>
1435 - Effect.gen(function* () {
1422 + const listActionRequiredRuns = Effect.fn("GitHubPullRequestApi.listActionRequiredRuns")(
1423 + function* (input: {
1424 + readonly cwd: string;
1425 + readonly repository: string;
1426 + readonly host: string;
1427 + readonly headSha: string;
1428 + readonly headBranch: string;
1429 + }) {
1430 const known = yield* KnownWorkflowRuns;
1431 if (known !== null && known.headSha === input.headSha) {
1432 return known.runs.flatMap((run) =>
@@ -1464,7 +1458,8 @@ export const make = Effect.gen(function* () {
1458 if (read.rawCount < 100) break;
1459 }
1460 return runs;
1467 - });
1461 + },
1462 + );
1463
1464 const listWorkflowRunsRequiringApproval: GitHubPullRequestApi["Service"]["listWorkflowRunsRequiringApproval"] =
1465 (input) =>
@@ -1590,8 +1585,10 @@ export const make = Effect.gen(function* () {
1585 RequestResolver.setDelay(SUMMARY_BATCH_WINDOW),
1586 RequestResolver.batchN(STAT_ALIASES_PER_REQUEST),
1587 );
1593 - const getPullRequestSummary: GitHubPullRequestApi["Service"]["getPullRequestSummary"] = (input) =>
1594 - Effect.gen(function* () {
1588 + const getPullRequestSummary: GitHubPullRequestApi["Service"]["getPullRequestSummary"] = Effect.fn(
1589 + "GitHubPullRequestApi.getPullRequestSummary",
1590 + )(
1591 + function* (input) {
1592 const lookup = pullRequestLookup(input);
1593 if (lookup === null) {
1594 return yield* new GitHubRepositorySelectorError({
@@ -1611,7 +1608,12 @@ export const make = Effect.gen(function* () {
1608 });
1609 }
1610 return toPullRequestSummary(pullRequest);
1614 - }).pipe((effect) => batchedRead({ ...input, operation: "getPullRequestSummary" }, effect));
1611 + },
1612 + (effect, input) =>
1613 + effect.pipe((effect) =>
1614 + batchedRead({ ...input, operation: "getPullRequestSummary" }, effect),
1615 + ),
1616 + );
1617
1618 // Every watched pull request on a host in one read per pass. A pull request the batch has no
1619 // answer for gets null, and its watch reads it in full; a failed request fails every entry.
@@ -1681,39 +1683,38 @@ export const make = Effect.gen(function* () {
1683 * Pages of up to a hundred until `rows` have arrived or GitHub has no more. Each page asks
1684 * for only the rows still missing, so the last one does not overshoot.
1685 */
1684 - const collect = (
1686 + const collect = Effect.fn("GitHubPullRequestApi.collect")(function* (
1687 rows: number,
1688 page: (
1689 after: string | null,
1690 rows: number,
1691 ) => Effect.Effect<GitHubPullRequestListPage, GitHubPullRequestApiError>,
1690 - ) =>
1691 - Effect.gen(function* () {
1692 - const countRows = (pages: ReadonlyArray<GitHubPullRequestListPage>) =>
1693 - pages.reduce((total, read) => total + read.rawCount, 0);
1694 - const pages: GitHubPullRequestListPage[] = [];
1695 - const seen = new Set<string>();
1696 - let after: string | null = null;
1697 - let truncated = false;
1698 - while (true) {
1699 - const read: GitHubPullRequestListPage = yield* page(after, rows - countRows(pages));
1700 - pages.push(read);
1701 - const next = read.endCursor;
1702 - if (next === null) break;
1703 - // `truncated` also covers a cursor GitHub repeated before `rows` arrived.
1704 - if (seen.has(next) || countRows(pages) >= rows) {
1705 - truncated = true;
1706 - break;
1707 - }
1708 - seen.add(next);
1709 - after = next;
1692 + ) {
1693 + const countRows = (pages: ReadonlyArray<GitHubPullRequestListPage>) =>
1694 + pages.reduce((total, read) => total + read.rawCount, 0);
1695 + const pages: GitHubPullRequestListPage[] = [];
1696 + const seen = new Set<string>();
1697 + let after: string | null = null;
1698 + let truncated = false;
1699 + while (true) {
1700 + const read: GitHubPullRequestListPage = yield* page(after, rows - countRows(pages));
1701 + pages.push(read);
1702 + const next = read.endCursor;
1703 + if (next === null) break;
1704 + // `truncated` also covers a cursor GitHub repeated before `rows` arrived.
1705 + if (seen.has(next) || countRows(pages) >= rows) {
1706 + truncated = true;
1707 + break;
1708 }
1711 - return {
1712 - items: pages.flatMap((read) => read.items),
1713 - rawCount: countRows(pages),
1714 - truncated,
1715 - };
1716 - });
1709 + seen.add(next);
1710 + after = next;
1711 + }
1712 + return {
1713 + items: pages.flatMap((read) => read.items),
1714 + rawCount: countRows(pages),
1715 + truncated,
1716 + };
1717 + });
1718 const stacks = input.host.toLowerCase() === "github.com";
1719 const read = (
1720 continues: boolean,
@@ -1859,8 +1860,8 @@ export const make = Effect.gen(function* () {
1860 );
1861 },
1862
1862 - listPullRequestStats: (input) =>
1863 - Effect.gen(function* () {
1863 + listPullRequestStats: Effect.fn("GitHubPullRequestApi.listPullRequestStats")(
1864 + function* (input) {
1865 const lookups = input.changeRequests.map((changeRequest) => ({
1866 changeRequest,
1867 lookup: pullRequestLookup(changeRequest),
@@ -1888,7 +1889,12 @@ export const make = Effect.gen(function* () {
1889 { concurrency: "unbounded" },
1890 );
1891 return stats.flat();
1891 - }).pipe((effect) => batchedRead({ ...input, operation: "listPullRequestStats" }, effect)),
1892 + },
1893 + (effect, input) =>
1894 + effect.pipe((effect) =>
1895 + batchedRead({ ...input, operation: "listPullRequestStats" }, effect),
1896 + ),
1897 + ),
1898
1899 getPullRequestSummary,
1900 getPullRequestWatchFingerprint,
@@ -1935,8 +1941,8 @@ export const make = Effect.gen(function* () {
1941 );
1942 },
1943
1938 - getPullRequestActivity: (input) =>
1939 - Effect.gen(function* () {
1944 + getPullRequestActivity: Effect.fn("GitHubPullRequestApi.getPullRequestActivity")(
1945 + function* (input) {
1946 const { owner, name } = parseRepositorySelector(input.repository);
1947 let author: PullRequestActor | null = null;
1948 let commits: ReadonlyArray<PullRequestCommit> = [];
@@ -1981,7 +1987,8 @@ export const make = Effect.gen(function* () {
1987 ),
1988 commits,
1989 } satisfies GitHubPullRequestActivity;
1984 - }),
1990 + },
1991 + ),
1992
1993 getPullRequestDiff: (input) => {
1994 const filesPage = (page: number) =>
@@ -2057,8 +2064,8 @@ export const make = Effect.gen(function* () {
2064 );
2065 },
2066
2060 - listReviewThreadComments: (input) =>
2061 - Effect.gen(function* () {
2067 + listReviewThreadComments: Effect.fn("GitHubPullRequestApi.listReviewThreadComments")(
2068 + function* (input) {
2069 const { owner, name } = parseRepositorySelector(input.repository);
2070 const target = { ...input, operation: "listReviewThreadComments" };
2071 const threadPage = (
@@ -2157,7 +2164,8 @@ export const make = Effect.gen(function* () {
2164 commits,
2165 viewer,
2166 };
2160 - }),
2167 + },
2168 + ),
2169
2170 listActorAvatars: (input) => {
2171 if (input.ids.length === 0) {
packages/source-control-github/src/server/GitHubRequestPolicy.ts
+77 -81
@@ -260,96 +260,92 @@ export const make = Effect.gen(function* () {
260 return { token: held.token, fingerprint: held.fingerprint };
261 });
262
263 - const request: GitHubRequestPolicy["Service"]["request"] = <A, E, R>(
263 + // The REST/GraphQL transport span owns request and quota metadata.
264 + const request: GitHubRequestPolicy["Service"]["request"] = Effect.fnUntraced(function* <A, E, R>(
265 input: GitHubRequest,
266 send: (headers: Readonly<Record<string, string>>) => Effect.Effect<GitHubAnswer<A>, E, R>,
266 - ) =>
267 - Effect.gen(function* () {
268 - const host = normalizeHost(input.host);
269 - const context = { host, operation: input.operation };
267 + ) {
268 + const host = normalizeHost(input.host);
269 + const context = { host, operation: input.operation };
270 + yield* Effect.annotateCurrentSpan({
271 + "github.host": host,
272 + "github.operation": input.operation,
273 + });
274 + const { token, fingerprint } = yield* credential(host);
275 + const scope = yield* SourceControlRateLimit.CredentialScope;
276 + // A refusal pauses the whole host, whichever quota it spent: the key PullRequestService
277 + // records its own backoff under.
278 + const key = { provider: SourceControlProviderKind.make("github"), host };
279 +
280 + // Settlement annotates the request span with status and rate-limit attributes.
281 + const settle = Effect.fnUntraced(function* (lease: number, answer: GitHubAnswer<A>) {
282 + yield* quota.observe(host, answer.headers);
283 yield* Effect.annotateCurrentSpan({
271 - "github.host": host,
272 - "github.operation": input.operation,
284 + ...(answer.status === undefined ? {} : { "http.response.status_code": answer.status }),
285 + ...rateLimitAttributes(answer.headers),
286 });
274 - const { token, fingerprint } = yield* credential(host);
275 - const scope = yield* SourceControlRateLimit.CredentialScope;
276 - // A refusal pauses the whole host, whichever quota it spent: the key PullRequestService
277 - // records its own backoff under.
278 - const key = { provider: SourceControlProviderKind.make("github"), host };
279 -
280 - const settle = (lease: number, answer: GitHubAnswer<A>) =>
281 - Effect.gen(function* () {
282 - yield* quota.observe(host, answer.headers);
287 + switch (answer._tag) {
288 + case "Ok":
289 + yield* limits.recordSuccess({ ...key, lease });
290 + return answer.value;
291 + case "RateLimited": {
292 + const retryAt = retryAtFrom(answer.headers, yield* Clock.currentTimeMillis);
293 + yield* limits.recordRateLimit({ ...key, lease, retryAt });
294 yield* Effect.annotateCurrentSpan({
284 - ...(answer.status === undefined ? {} : { "http.response.status_code": answer.status }),
285 - ...rateLimitAttributes(answer.headers),
295 + "github.rate_limited": true,
296 + ...(retryAt === undefined ? {} : { "github.retry_at": retryAt }),
297 });
287 - switch (answer._tag) {
288 - case "Ok":
289 - yield* limits.recordSuccess({ ...key, lease });
290 - return answer.value;
291 - case "RateLimited": {
292 - const retryAt = retryAtFrom(answer.headers, yield* Clock.currentTimeMillis);
293 - yield* limits.recordRateLimit({ ...key, lease, retryAt });
294 - yield* Effect.annotateCurrentSpan({
295 - "github.rate_limited": true,
296 - ...(retryAt === undefined ? {} : { "github.retry_at": retryAt }),
297 - });
298 - return yield* new GitHubApiRateLimitError({
299 - ...context,
300 - ...(retryAt === undefined ? {} : { retryAt }),
301 - });
302 - }
303 - case "Unauthorized":
304 - // The source may hold a newer token than the one that was refused.
305 - yield* credentials.invalidate(host);
306 - return yield* new GitHubApiAuthenticationError(context);
307 - case "NotFound":
308 - return yield* new GitHubApiNotFoundError(context);
309 - case "Failed":
310 - return yield* new GitHubApiResponseError({
311 - ...context,
312 - status: answer.status ?? 200,
313 - ...(answer.messages === undefined ? {} : { githubErrors: answer.messages }),
314 - });
315 - }
316 - });
298 + return yield* new GitHubApiRateLimitError({
299 + ...context,
300 + ...(retryAt === undefined ? {} : { retryAt }),
301 + });
302 + }
303 + case "Unauthorized":
304 + // The source may hold a newer token than the one that was refused.
305 + yield* credentials.invalidate(host);
306 + return yield* new GitHubApiAuthenticationError(context);
307 + case "NotFound":
308 + return yield* new GitHubApiNotFoundError(context);
309 + case "Failed":
310 + return yield* new GitHubApiResponseError({
311 + ...context,
312 + status: answer.status ?? 200,
313 + ...(answer.messages === undefined ? {} : { githubErrors: answer.messages }),
314 + });
315 + }
316 + });
317
318 - const run = Effect.gen(function* () {
319 - const lease = yield* quota
320 - .admit(host, input.resource, { allowReserve: input.allowReserve })
321 - .pipe(
322 - Effect.andThen(
323 - limits.check(key, input.allowReserve ? { allowPaused: true } : undefined),
324 - ),
325 - Effect.tapError((paused) =>
326 - Effect.annotateCurrentSpan({
327 - "github.paused": true,
328 - "github.retry_at": paused.retryAt,
329 - }),
330 - ),
331 - );
332 - // One deadline covers the headers and the body: a host that answers headers and then
333 - // stalls must not hold a shared slot for undici's own five-minute body timeout.
334 - const answer = yield* send({
335 - ...REQUEST_HEADERS,
336 - authorization: `Bearer ${Redacted.value(token)}`,
337 - }).pipe(
338 - Effect.timeoutOrElse({
339 - duration: input.timeout ?? DEFAULT_TIMEOUT,
340 - orElse: () =>
341 - Effect.fail(
342 - new GitHubApiRequestError({ ...context, cause: new Cause.TimeoutError() }),
343 - ),
344 - }),
318 + const run = Effect.gen(function* () {
319 + const lease = yield* quota
320 + .admit(host, input.resource, { allowReserve: input.allowReserve })
321 + .pipe(
322 + Effect.andThen(limits.check(key, input.allowReserve ? { allowPaused: true } : undefined)),
323 + Effect.tapError((paused) =>
324 + Effect.annotateCurrentSpan({
325 + "github.paused": true,
326 + "github.retry_at": paused.retryAt,
327 + }),
328 + ),
329 );
346 - return yield* settle(lease, answer);
347 - });
348 - // The rate-limit scope follows the credential, so a pause on one account never blocks another.
349 - return yield* slots
350 - .withPermit(run)
351 - .pipe(Effect.provideService(SourceControlRateLimit.CredentialScope, scope || fingerprint));
330 + // One deadline covers the headers and the body: a host that answers headers and then
331 + // stalls must not hold a shared slot for undici's own five-minute body timeout.
332 + const answer = yield* send({
333 + ...REQUEST_HEADERS,
334 + authorization: `Bearer ${Redacted.value(token)}`,
335 + }).pipe(
336 + Effect.timeoutOrElse({
337 + duration: input.timeout ?? DEFAULT_TIMEOUT,
338 + orElse: () =>
339 + Effect.fail(new GitHubApiRequestError({ ...context, cause: new Cause.TimeoutError() })),
340 + }),
341 + );
342 + return yield* settle(lease, answer);
343 });
344 + // The rate-limit scope follows the credential, so a pause on one account never blocks another.
345 + return yield* slots
346 + .withPermit(run)
347 + .pipe(Effect.provideService(SourceControlRateLimit.CredentialScope, scope || fingerprint));
348 + });
349
350 return GitHubRequestPolicy.of({ request, credential });
351 });
packages/source-control-github/src/server/GitHubSourceControlProvider.ts
+32 -21
@@ -927,8 +927,8 @@ export const make = Effect.gen(function* () {
927 providerError("getChangeRequest", input.cwd, { reference: input.reference }),
928 ),
929 ),
930 - createChangeRequest: (input) =>
931 - Effect.gen(function* () {
930 + createChangeRequest: Effect.fn("GitHubSourceControlProvider.createChangeRequest")(
931 + function* (input) {
932 const locator = yield* resolveRepository(input);
933 const body = yield* fileSystem
934 .readFileString(input.bodyFile)
@@ -953,13 +953,16 @@ export const make = Effect.gen(function* () {
953 maintainer_can_modify: true,
954 },
955 });
956 - }).pipe(
957 - Effect.mapError(
958 - providerError("createChangeRequest", input.cwd, { reference: input.headSelector }),
956 + },
957 + (effect, input) =>
958 + effect.pipe(
959 + Effect.mapError(
960 + providerError("createChangeRequest", input.cwd, { reference: input.headSelector }),
961 + ),
962 ),
960 - ),
961 - getRepositoryCloneUrls: (input) =>
962 - Effect.gen(function* () {
963 + ),
964 + getRepositoryCloneUrls: Effect.fn("GitHubSourceControlProvider.getRepositoryCloneUrls")(
965 + function* (input) {
966 const fallbackHost = (yield* resolveRepository(input).pipe(
967 Effect.map((locator) => locator.host),
968 Effect.orElseSucceed(() => environment.GH_HOST ?? "github.com"),
@@ -972,13 +975,16 @@ export const make = Effect.gen(function* () {
975 : null);
976 if (locator === null) return yield* failure("Repositories are named owner/name.");
977 return repositoryCloneUrls(yield* readRepository(locator));
975 - }).pipe(
976 - Effect.mapError(
977 - providerError("getRepositoryCloneUrls", input.cwd, { repository: input.repository }),
978 + },
979 + (effect, input) =>
980 + effect.pipe(
981 + Effect.mapError(
982 + providerError("getRepositoryCloneUrls", input.cwd, { repository: input.repository }),
983 + ),
984 ),
979 - ),
980 - createRepository: (input) =>
981 - Effect.gen(function* () {
985 + ),
986 + createRepository: Effect.fn("GitHubSourceControlProvider.createRepository")(
987 + function* (input) {
988 const locator = parseGitHubRepositorySelector(
989 input.repository,
990 (environment.GH_HOST ?? "github.com").toLowerCase(),
@@ -1006,13 +1012,16 @@ export const make = Effect.gen(function* () {
1012 return yield* failure("GitHub returned an invalid repository.", decoded.failure);
1013 }
1014 return repositoryCloneUrls(decoded.success);
1009 - }).pipe(
1010 - Effect.mapError(
1011 - providerError("createRepository", input.cwd, { repository: input.repository }),
1015 + },
1016 + (effect, input) =>
1017 + effect.pipe(
1018 + Effect.mapError(
1019 + providerError("createRepository", input.cwd, { repository: input.repository }),
1020 + ),
1021 ),
1013 - ),
1014 - getDefaultBranch: (input) =>
1015 - Effect.gen(function* () {
1022 + ),
1023 + getDefaultBranch: Effect.fn("GitHubSourceControlProvider.getDefaultBranch")(
1024 + function* (input) {
1025 const locator = yield* resolveRepository({
1026 cwd: input.cwd,
1027 host: contextHost(input.context),
@@ -1021,7 +1030,9 @@ export const make = Effect.gen(function* () {
1030 const repository = yield* readRepository(locator);
1031 const branch = repository.default_branch?.trim() ?? "";
1032 return branch.length > 0 ? branch : null;
1024 - }).pipe(Effect.mapError(providerError("getDefaultBranch", input.cwd))),
1033 + },
1034 + (effect, input) => effect.pipe(Effect.mapError(providerError("getDefaultBranch", input.cwd))),
1035 + ),
1036 checkoutChangeRequest: (input) =>
1037 checkoutPullRequest(input).pipe(
1038 Effect.mapError(
packages/source-control-github/src/server/gitHubChangeRequestTemplate.ts
+9 -9
@@ -92,13 +92,13 @@ type DirectoryTemplateResult =
92 | { readonly _tag: "Ambiguous" }
93 | { readonly _tag: "Template"; readonly template: string };
94
95 -function readTemplateDirectory(input: {
96 - readonly cwd: string;
97 - readonly executeGit: ExecuteGit;
98 - readonly entries: ReadonlyArray<TemplateTreeEntry>;
99 - readonly directory: string;
100 -}): Effect.Effect<DirectoryTemplateResult, GitCommandError> {
101 - return Effect.gen(function* () {
95 +const readTemplateDirectory = Effect.fn("gitHubChangeRequestTemplate.readTemplateDirectory")(
96 + function* (input: {
97 + readonly cwd: string;
98 + readonly executeGit: ExecuteGit;
99 + readonly entries: ReadonlyArray<TemplateTreeEntry>;
100 + readonly directory: string;
101 + }): Effect.fn.Return<DirectoryTemplateResult, GitCommandError> {
102 const prefix = `${input.directory}/`;
103 const candidates = input.entries.filter((entry) => {
104 if (!entry.path.startsWith(prefix)) {
@@ -122,8 +122,8 @@ function readTemplateDirectory(input: {
122 return templates[0]
123 ? ({ _tag: "Template", template: templates[0] } as const)
124 : ({ _tag: "None" } as const);
125 - });
126 -}
125 + },
126 +);
127
128 export const detect = Effect.fn("gitHubChangeRequestTemplate.detect")(function* (
129 cwd: string,
packages/source-control-github/src/server/gitHubConditionalChecks.ts
+49 -47
@@ -85,54 +85,56 @@ export const makeChecksRevalidator = Effect.gen(function* () {
85 operation: "revalidateChecks",
86 status,
87 });
88 - const get = (endpoint: string, head = false) =>
89 - Effect.gen(function* () {
90 - const previous = entry.validators.get(endpoint);
91 - const response = yield* api
92 - .rest({
93 - host: input.host,
94 - operation: "revalidateChecks",
95 - path: endpoint,
96 - ...(previous?.etag ? { ifNoneMatch: previous.etag } : {}),
97 - })
98 - .pipe(
99 - Effect.catchTags({
100 - GitHubApiNotFoundError: () =>
101 - Effect.sync(() => {
102 - entry.supported = false;
103 - return null;
104 - }),
105 - GitHubApiResponseError: (error) =>
106 - Effect.sync(() => {
107 - entry.supported = !UNSUPPORTED_STATUSES.has(error.status);
108 - return null;
109 - }),
110 - }),
111 - );
112 - if (response === null) {
113 - entry.value = null;
114 - return null;
115 - }
116 - if (response.status === 304 && previous) return previous.next;
117 - if (response.status !== 200 || response.truncated) {
118 - return yield* fail(response.status);
119 - }
88 + const get = Effect.fn("gitHubConditionalChecks.get")(function* (
89 + endpoint: string,
90 + head = false,
91 + ) {
92 + const previous = entry.validators.get(endpoint);
93 + const response = yield* api
94 + .rest({
95 + host: input.host,
96 + operation: "revalidateChecks",
97 + path: endpoint,
98 + ...(previous?.etag ? { ifNoneMatch: previous.etag } : {}),
99 + })
100 + .pipe(
101 + Effect.catchTags({
102 + GitHubApiNotFoundError: () =>
103 + Effect.sync(() => {
104 + entry.supported = false;
105 + return null;
106 + }),
107 + GitHubApiResponseError: (error) =>
108 + Effect.sync(() => {
109 + entry.supported = !UNSUPPORTED_STATUSES.has(error.status);
110 + return null;
111 + }),
112 + }),
113 + );
114 + if (response === null) {
115 entry.value = null;
121 - if (head) {
122 - const decoded = yield* decodeHead(response.body).pipe(
123 - Effect.mapError(() => fail(response.status)),
124 - );
125 - if (entry.head?.head.sha !== decoded.head.sha) entry.validators.clear();
126 - entry.head = decoded;
127 - }
128 - const validator = {
129 - etag: response.headers["etag"]?.trim(),
130 - next: /rel="next"/.test(response.headers["link"] ?? ""),
131 - body: response.body,
132 - };
133 - entry.validators.set(endpoint, validator);
134 - return validator.next;
135 - });
116 + return null;
117 + }
118 + if (response.status === 304 && previous) return previous.next;
119 + if (response.status !== 200 || response.truncated) {
120 + return yield* fail(response.status);
121 + }
122 + entry.value = null;
123 + if (head) {
124 + const decoded = yield* decodeHead(response.body).pipe(
125 + Effect.mapError(() => fail(response.status)),
126 + );
127 + if (entry.head?.head.sha !== decoded.head.sha) entry.validators.clear();
128 + entry.head = decoded;
129 + }
130 + const validator = {
131 + etag: response.headers["etag"]?.trim(),
132 + next: /rel="next"/.test(response.headers["link"] ?? ""),
133 + body: response.body,
134 + };
135 + entry.validators.set(endpoint, validator);
136 + return validator.next;
137 + });
138 const root = `repos/${input.repository}`;
139 if ((yield* get(`${root}/pulls/${input.number}`, true)) === null) return yield* read;
140 const head = entry.head;
packages/source-control-github/src/server/gitHubGraphQlClient.ts
+95 -98
@@ -64,41 +64,40 @@ export class GitHubGraphQlAuth extends GraphQLMiddleware.Service<
64 Effect.gen(function* () {
65 const policy = yield* GitHubRequestPolicy.GitHubRequestPolicy;
66 return GitHubGraphQlAuth.of({
67 - execute: ({ request, next }) =>
68 - Effect.gen(function* () {
69 - const target = yield* GitHubGraphQlTarget;
70 - const host = GitHubRequestPolicy.normalizeHost(target.host);
71 - yield* Effect.annotateCurrentSpan({
72 - "github.kind": "graphql",
73 - "github.graphql.query_hash": queryHash(request.query),
74 - });
75 - return yield* policy.request(
76 - {
77 - host,
78 - operation: target.operation,
79 - resource: "graphql",
80 - allowReserve: target.allowReserve ?? (yield* SourceControlRateLimit.Interactive),
81 - },
82 - (headers) =>
83 - next({ ...request, headers: Headers.setAll(request.headers, headers) }).pipe(
84 - Effect.map((answer) => {
85 - const status = answer.status;
86 - const responseHeaders = answer.headers ?? Headers.empty;
87 - const rateLimited = GitHubRequestPolicy.isRateLimited({
88 - status: status ?? 200,
89 - headers: responseHeaders,
90 - ...(answer.errors === undefined ? {} : { graphqlErrors: answer.errors }),
91 - });
92 - return rateLimited
93 - ? { _tag: "RateLimited" as const, status, headers: responseHeaders }
94 - : { _tag: "Ok" as const, value: answer, status, headers: responseHeaders };
95 - }),
96 - Effect.catchIf(GraphQLClientError.isGraphQLClientError, (error) =>
97 - refused(error, { host, operation: target.operation }),
98 - ),
67 + execute: Effect.fn("GitHubGraphQlAuth.execute")(function* ({ request, next }) {
68 + const target = yield* GitHubGraphQlTarget;
69 + const host = GitHubRequestPolicy.normalizeHost(target.host);
70 + yield* Effect.annotateCurrentSpan({
71 + "github.kind": "graphql",
72 + "github.graphql.query_hash": queryHash(request.query),
73 + });
74 + return yield* policy.request(
75 + {
76 + host,
77 + operation: target.operation,
78 + resource: "graphql",
79 + allowReserve: target.allowReserve ?? (yield* SourceControlRateLimit.Interactive),
80 + },
81 + (headers) =>
82 + next({ ...request, headers: Headers.setAll(request.headers, headers) }).pipe(
83 + Effect.map((answer) => {
84 + const status = answer.status;
85 + const responseHeaders = answer.headers ?? Headers.empty;
86 + const rateLimited = GitHubRequestPolicy.isRateLimited({
87 + status: status ?? 200,
88 + headers: responseHeaders,
89 + ...(answer.errors === undefined ? {} : { graphqlErrors: answer.errors }),
90 + });
91 + return rateLimited
92 + ? { _tag: "RateLimited" as const, status, headers: responseHeaders }
93 + : { _tag: "Ok" as const, value: answer, status, headers: responseHeaders };
94 + }),
95 + Effect.catchIf(GraphQLClientError.isGraphQLClientError, (error) =>
96 + refused(error, { host, operation: target.operation }),
97 ),
100 - );
101 - }).pipe(Effect.withSpan("GitHubGraphQlAuth.execute")),
98 + ),
99 + );
100 + }),
101 subscribe: () => Stream.die(new Error("GitHub GraphQL has no subscriptions.")),
102 });
103 }),
@@ -110,80 +109,78 @@ export class GitHubGraphQlAuth extends GraphQLMiddleware.Service<
109 * failure that never reached GitHub is a request error; one that is not about the transport
110 * (an answer that does not decode) is the client's own.
111 */
113 -const refused = (
112 +const refused = Effect.fn("gitHubGraphQlClient.refused")(function* (
113 error: GraphQLClientError.GraphQLClientError,
114 context: { readonly host: string; readonly operation: string },
116 -) =>
117 - Effect.gen(function* () {
118 - const reason = error.reason;
119 - if (reason._tag !== "TransportError" && reason._tag !== "ResponseError") {
120 - return yield* Effect.fail(error);
121 - }
122 - const status = reason.status;
123 - if (reason._tag === "TransportError" && status === undefined) {
124 - return yield* new GitHubRequestPolicy.GitHubApiRequestError({ ...context, cause: error });
125 - }
126 - const headers = reason.headers ?? Headers.empty;
127 - // A secondary limit is a 403 that only its body names, which the transport read.
128 - const body =
129 - reason._tag === "TransportError" &&
130 - HttpClientError.isHttpClientError(reason.cause) &&
131 - reason.cause.response !== undefined
132 - ? yield* reason.cause.response.text.pipe(Effect.orElseSucceed(() => ""))
133 - : "";
134 - const tag = GitHubRequestPolicy.isRateLimited({
135 - status: status ?? 200,
136 - headers,
137 - body,
138 - ...(reason._tag === "ResponseError" ? { graphqlErrors: reason.errors } : {}),
139 - })
140 - ? "RateLimited"
141 - : status === 401
142 - ? "Unauthorized"
143 - : status === 404
144 - ? "NotFound"
145 - : "Failed";
146 - return { _tag: tag, status: status ?? 200, headers } as const;
147 - });
115 +) {
116 + const reason = error.reason;
117 + if (reason._tag !== "TransportError" && reason._tag !== "ResponseError") {
118 + return yield* Effect.fail(error);
119 + }
120 + const status = reason.status;
121 + if (reason._tag === "TransportError" && status === undefined) {
122 + return yield* new GitHubRequestPolicy.GitHubApiRequestError({ ...context, cause: error });
123 + }
124 + const headers = reason.headers ?? Headers.empty;
125 + // A secondary limit is a 403 that only its body names, which the transport read.
126 + const body =
127 + reason._tag === "TransportError" &&
128 + HttpClientError.isHttpClientError(reason.cause) &&
129 + reason.cause.response !== undefined
130 + ? yield* reason.cause.response.text.pipe(Effect.orElseSucceed(() => ""))
131 + : "";
132 + const tag = GitHubRequestPolicy.isRateLimited({
133 + status: status ?? 200,
134 + headers,
135 + body,
136 + ...(reason._tag === "ResponseError" ? { graphqlErrors: reason.errors } : {}),
137 + })
138 + ? "RateLimited"
139 + : status === 401
140 + ? "Unauthorized"
141 + : status === 404
142 + ? "NotFound"
143 + : "Failed";
144 + return { _tag: tag, status: status ?? 200, headers } as const;
145 +});
146
147 /**
148 * Reads each answer whole, up to the call's byte cap, before the protocol parses it. A body cut
149 * at the cap hides any `errors` past the cut and cannot be decoded, so it fails, which the
150 * middleware reports as a `GitHubApiResponseError` with the answer's status.
151 */
154 -const capResponse = (
152 +const capResponse = Effect.fn("gitHubGraphQlClient.capResponse")(function* (
153 effect: Effect.Effect<HttpClientResponse.HttpClientResponse, HttpClientError.HttpClientError>,
156 -) =>
157 - Effect.gen(function* () {
158 - const response = yield* effect;
159 - const target = yield* Effect.serviceOption(GitHubGraphQlTarget);
160 - const maxBytes = Option.match(target, {
161 - onNone: () => DEFAULT_MAX_RESPONSE_BYTES,
162 - onSome: (target) => target.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES,
163 - });
164 - const collected = yield* collectUint8StreamText({ stream: response.stream, maxBytes }).pipe(
165 - Effect.catchIf(
166 - (error) => error.reason._tag === "EmptyBodyError",
167 - () => Effect.succeed({ text: "", truncated: false }),
168 - ),
169 - );
170 - if (collected.truncated) {
171 - return yield* new HttpClientError.HttpClientError({
172 - reason: new HttpClientError.DecodeError({
173 - request: response.request,
174 - response,
175 - description: `The answer is longer than ${maxBytes} bytes.`,
176 - }),
177 - });
178 - }
179 - return HttpClientResponse.fromWeb(
180 - response.request,
181 - new Response(collected.text === "" ? null : collected.text, {
182 - status: response.status,
183 - headers: response.headers,
184 - }),
185 - );
154 +) {
155 + const response = yield* effect;
156 + const target = yield* Effect.serviceOption(GitHubGraphQlTarget);
157 + const maxBytes = Option.match(target, {
158 + onNone: () => DEFAULT_MAX_RESPONSE_BYTES,
159 + onSome: (target) => target.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES,
160 });
161 + const collected = yield* collectUint8StreamText({ stream: response.stream, maxBytes }).pipe(
162 + Effect.catchIf(
163 + (error) => error.reason._tag === "EmptyBodyError",
164 + () => Effect.succeed({ text: "", truncated: false }),
165 + ),
166 + );
167 + if (collected.truncated) {
168 + return yield* new HttpClientError.HttpClientError({
169 + reason: new HttpClientError.DecodeError({
170 + request: response.request,
171 + response,
172 + description: `The answer is longer than ${maxBytes} bytes.`,
173 + }),
174 + });
175 + }
176 + return HttpClientResponse.fromWeb(
177 + response.request,
178 + new Response(collected.text === "" ? null : collected.text, {
179 + status: response.status,
180 + headers: response.headers,
181 + }),
182 + );
183 +});
184
185 /**
186 * The HTTP transport, sending each request to its target host's endpoint. Resolvers batch by this
packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts
+129 -129
@@ -1080,40 +1080,39 @@ export const make = Effect.gen(function* () {
1080
1081 getFileRevisions: fileRevisions,
1082
1083 - setReaction: (input) =>
1084 - Effect.gen(function* () {
1085 - const subject = awardSubjectPath(input);
1086 - if (input.reacted) {
1087 - yield* api({
1088 - cwd: input.cwd,
1089 - path: `${subject}?${query([["name", gitLabAwardName(input.content)]])}`,
1090 - method: "POST",
1091 - });
1092 - return;
1093 - }
1094 - // GitLab deletes an award by its id and takes no emoji name there, so the reader's own
1095 - // award of that name is looked up first.
1096 - const viewer = yield* viewerUsername({ cwd: input.cwd });
1097 - const listed = yield* api({ cwd: input.cwd, path: subject });
1098 - const own = decodeOwnAwardIdJson(listed.stdout.trim(), {
1099 - content: input.content,
1100 - viewer,
1101 - });
1102 - if (!Result.isSuccess(own)) {
1103 - return yield* new GitLabMergeRequestReadError({
1104 - command: "glab",
1105 - cwd: input.cwd,
1106 - operation: "setReaction",
1107 - cause: own.failure,
1108 - });
1109 - }
1110 - if (own.success === null) return;
1083 + setReaction: Effect.fn("GitLabPullRequestCli.setReaction")(function* (input) {
1084 + const subject = awardSubjectPath(input);
1085 + if (input.reacted) {
1086 yield* api({
1087 cwd: input.cwd,
1113 - path: `${subject}/${own.success}`,
1114 - method: "DELETE",
1088 + path: `${subject}?${query([["name", gitLabAwardName(input.content)]])}`,
1089 + method: "POST",
1090 });
1116 - }),
1091 + return;
1092 + }
1093 + // GitLab deletes an award by its id and takes no emoji name there, so the reader's own
1094 + // award of that name is looked up first.
1095 + const viewer = yield* viewerUsername({ cwd: input.cwd });
1096 + const listed = yield* api({ cwd: input.cwd, path: subject });
1097 + const own = decodeOwnAwardIdJson(listed.stdout.trim(), {
1098 + content: input.content,
1099 + viewer,
1100 + });
1101 + if (!Result.isSuccess(own)) {
1102 + return yield* new GitLabMergeRequestReadError({
1103 + command: "glab",
1104 + cwd: input.cwd,
1105 + operation: "setReaction",
1106 + cause: own.failure,
1107 + });
1108 + }
1109 + if (own.success === null) return;
1110 + yield* api({
1111 + cwd: input.cwd,
1112 + path: `${subject}/${own.success}`,
1113 + method: "DELETE",
1114 + });
1115 + }),
1116
1117 listCommits: (input) =>
1118 api({
@@ -1159,56 +1158,57 @@ export const make = Effect.gen(function* () {
1158 : diffPage({ ...target, page });
1159 },
1160
1162 - getMergeRequestDiffFileContents: (input) =>
1163 - Effect.gen(function* () {
1164 - if (input.commit !== undefined && !isCommitSha(input.commit)) {
1165 - return yield* new GitLabDiffCommitError({ command: "glab", cwd: input.cwd });
1166 - }
1167 - const refs = yield* input.commit === undefined
1168 - ? getDiffRefs(input)
1169 - : getCommitDiffRefs({
1170 - cwd: input.cwd,
1171 - repository: input.repository,
1172 - commit: input.commit,
1173 - allowRoot: input.changeType === "new",
1174 - });
1175 -
1176 - const readFile = (revision: string, filePath: string) =>
1177 - api({
1161 + getMergeRequestDiffFileContents: Effect.fn(
1162 + "GitLabPullRequestCli.getMergeRequestDiffFileContents",
1163 + )(function* (input) {
1164 + if (input.commit !== undefined && !isCommitSha(input.commit)) {
1165 + return yield* new GitLabDiffCommitError({ command: "glab", cwd: input.cwd });
1166 + }
1167 + const refs = yield* input.commit === undefined
1168 + ? getDiffRefs(input)
1169 + : getCommitDiffRefs({
1170 cwd: input.cwd,
1179 - path: `projects/${projectPath(input.repository)}/repository/files/${encodeURIComponent(
1180 - filePath,
1181 - )}/raw?ref=${encodeURIComponent(revision)}`,
1182 - maxOutputBytes: DIFF_FILE_MAX_OUTPUT_BYTES,
1183 - timeoutMs: DIFF_TIMEOUT_MS,
1184 - }).pipe(
1185 - Effect.flatMap((result) =>
1186 - result.stdoutTruncated ||
1187 - result.stdout.includes("\0") ||
1188 - result.stdoutInvalidUtf8 === true
1189 - ? Effect.fail(
1190 - new GitLabDiffFileContentsUnavailableError({
1191 - command: "glab",
1192 - cwd: input.cwd,
1193 - path: filePath,
1194 - reason: result.stdoutTruncated ? "oversized" : "binary",
1195 - }),
1196 - )
1197 - : Effect.succeed(result.stdout),
1198 - ),
1199 - );
1171 + repository: input.repository,
1172 + commit: input.commit,
1173 + allowRoot: input.changeType === "new",
1174 + });
1175
1201 - const [oldContents, newContents] = yield* Effect.all(
1202 - [
1203 - input.changeType === "new" ? Effect.succeed("") : readFile(refs.baseSha, input.oldPath),
1204 - input.changeType === "deleted"
1205 - ? Effect.succeed("")
1206 - : readFile(refs.headSha, input.newPath),
1207 - ],
1208 - { concurrency: 2 },
1176 + const readFile = (revision: string, filePath: string) =>
1177 + api({
1178 + cwd: input.cwd,
1179 + path: `projects/${projectPath(input.repository)}/repository/files/${encodeURIComponent(
1180 + filePath,
1181 + )}/raw?ref=${encodeURIComponent(revision)}`,
1182 + maxOutputBytes: DIFF_FILE_MAX_OUTPUT_BYTES,
1183 + timeoutMs: DIFF_TIMEOUT_MS,
1184 + }).pipe(
1185 + Effect.flatMap((result) =>
1186 + result.stdoutTruncated ||
1187 + result.stdout.includes("\0") ||
1188 + result.stdoutInvalidUtf8 === true
1189 + ? Effect.fail(
1190 + new GitLabDiffFileContentsUnavailableError({
1191 + command: "glab",
1192 + cwd: input.cwd,
1193 + path: filePath,
1194 + reason: result.stdoutTruncated ? "oversized" : "binary",
1195 + }),
1196 + )
1197 + : Effect.succeed(result.stdout),
1198 + ),
1199 );
1210 - return { oldContents, newContents };
1211 - }),
1200 +
1201 + const [oldContents, newContents] = yield* Effect.all(
1202 + [
1203 + input.changeType === "new" ? Effect.succeed("") : readFile(refs.baseSha, input.oldPath),
1204 + input.changeType === "deleted"
1205 + ? Effect.succeed("")
1206 + : readFile(refs.headSha, input.newPath),
1207 + ],
1208 + { concurrency: 2 },
1209 + );
1210 + return { oldContents, newContents };
1211 + }),
1212
1213 getProjectMergeCapabilities: (input) =>
1214 api({
@@ -1271,8 +1271,8 @@ export const make = Effect.gen(function* () {
1271 Effect.asVoid,
1272 ),
1273
1274 - runMergeRequestAction: (input) =>
1275 - Effect.gen(function* () {
1274 + runMergeRequestAction: Effect.fn("GitLabPullRequestCli.runMergeRequestAction")(
1275 + function* (input) {
1276 // `glab mr merge` arms auto-merge and never disarms it, so the one direction the CLI has
1277 // no flag for is asked of GitLab directly through the same `api` passthrough the rest of
1278 // this module writes with.
@@ -1298,7 +1298,8 @@ export const make = Effect.gen(function* () {
1298 flags.push("--sha", refs.headSha);
1299 }
1300 yield* executeMr(subcommand!, ...flags);
1301 - }),
1301 + },
1302 + ),
1303
1304 updateMergeRequest: (input) =>
1305 api({
@@ -1336,55 +1337,54 @@ export const make = Effect.gen(function* () {
1337
1338 listDiscussions: (input) => discussionsPage({ ...input, page: 1, collected: [] }),
1339
1339 - submitReview: (input) =>
1340 - Effect.gen(function* () {
1341 - const project = projectPath(input.repository);
1342 - const mergeRequest = `projects/${project}/merge_requests/${input.number}`;
1343 - // GitLab has no pending review to attach comments to, so a review is replayed as the
1344 - // requests it is made of: the line comments, then the summary, then the verdict. A
1345 - // failure part-way therefore leaves what was already posted in place, which is why
1346 - // the verdict goes last — a half-sent review is never an approval.
1347 - if (input.comments.length > 0) {
1348 - const refs = yield* getDiffRefs(input);
1349 - yield* Effect.forEach(
1350 - input.comments,
1351 - (comment) =>
1352 - api({
1353 - cwd: input.cwd,
1354 - path: `${mergeRequest}/discussions`,
1355 - method: "POST",
1356 - stdin: JSON.stringify({
1357 - body: comment.body,
1358 - position: {
1359 - base_sha: refs.baseSha,
1360 - head_sha: refs.headSha,
1361 - start_sha: refs.startSha,
1362 - position_type: "text",
1363 - // Both paths are sent because GitLab resolves a position against both
1364 - // sides of the diff. They differ only for a renamed file, which is why the
1365 - // draft carries the name the file had before the change.
1366 - old_path: comment.oldPath ?? comment.path,
1367 - new_path: comment.path,
1368 - ...gitLabReviewPositionLines(comment.position),
1369 - },
1370 - }),
1340 + submitReview: Effect.fn("GitLabPullRequestCli.submitReview")(function* (input) {
1341 + const project = projectPath(input.repository);
1342 + const mergeRequest = `projects/${project}/merge_requests/${input.number}`;
1343 + // GitLab has no pending review to attach comments to, so a review is replayed as the
1344 + // requests it is made of: the line comments, then the summary, then the verdict. A
1345 + // failure part-way therefore leaves what was already posted in place, which is why
1346 + // the verdict goes last — a half-sent review is never an approval.
1347 + if (input.comments.length > 0) {
1348 + const refs = yield* getDiffRefs(input);
1349 + yield* Effect.forEach(
1350 + input.comments,
1351 + (comment) =>
1352 + api({
1353 + cwd: input.cwd,
1354 + path: `${mergeRequest}/discussions`,
1355 + method: "POST",
1356 + stdin: JSON.stringify({
1357 + body: comment.body,
1358 + position: {
1359 + base_sha: refs.baseSha,
1360 + head_sha: refs.headSha,
1361 + start_sha: refs.startSha,
1362 + position_type: "text",
1363 + // Both paths are sent because GitLab resolves a position against both
1364 + // sides of the diff. They differ only for a renamed file, which is why the
1365 + // draft carries the name the file had before the change.
1366 + old_path: comment.oldPath ?? comment.path,
1367 + new_path: comment.path,
1368 + ...gitLabReviewPositionLines(comment.position),
1369 + },
1370 }),
1372 - { discard: true },
1373 - );
1374 - }
1375 - if (input.body.trim().length > 0) {
1376 - yield* api({
1377 - cwd: input.cwd,
1378 - path: `${mergeRequest}/notes`,
1379 - method: "POST",
1380 - // @effect-diagnostics-next-line preferSchemaOverJson:off
1381 - stdin: JSON.stringify({ body: input.body }),
1382 - });
1383 - }
1384 - if (input.verdict === "approve") {
1385 - yield* api({ cwd: input.cwd, path: `${mergeRequest}/approve`, method: "POST" });
1386 - }
1387 - }),
1371 + }),
1372 + { discard: true },
1373 + );
1374 + }
1375 + if (input.body.trim().length > 0) {
1376 + yield* api({
1377 + cwd: input.cwd,
1378 + path: `${mergeRequest}/notes`,
1379 + method: "POST",
1380 + // @effect-diagnostics-next-line preferSchemaOverJson:off
1381 + stdin: JSON.stringify({ body: input.body }),
1382 + });
1383 + }
1384 + if (input.verdict === "approve") {
1385 + yield* api({ cwd: input.cwd, path: `${mergeRequest}/approve`, method: "POST" });
1386 + }
1387 + }),
1388
1389 replyToDiscussion: (input) =>
1390 api({
packages/tailscale/src/tailscale.ts
+119 -120
@@ -210,63 +210,65 @@ export const parseTailscaleStatus = (
210 }),
211 );
212
213 -const readTailscaleOutput = (subcommand: "status" | "debug", args: readonly string[]) =>
214 - Effect.gen(function* () {
215 - const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
216 - const hostPlatform = yield* HostProcess.Platform;
217 - const executable = tailscaleCommandForPlatform(hostPlatform);
218 - const commandContext = {
219 - executable,
220 - subcommand,
221 - argumentCount: args.length,
222 - };
223 - return yield* Effect.gen(function* () {
224 - const child = yield* spawner.spawn(ChildProcess.make(executable, [...args])).pipe(
225 - Effect.mapError((cause) => new TailscaleCommandSpawnError({ ...commandContext, cause })),
226 - // Spawning can also fail as a defect rather than a typed error - a
227 - // non-directory entry on PATH makes node throw ENOTDIR synchronously.
228 - // `mapError` never sees that, so it would escape as an uncaught error.
229 - Effect.catchDefect((cause) =>
230 - Effect.fail(new TailscaleCommandSpawnError({ ...commandContext, cause })),
231 - ),
232 - );
233 - const [stdout, stderr, exitCode] = yield* Effect.all(
234 - [
235 - collectStdout(child.stdout),
236 - collectStderr(child.stderr),
237 - child.exitCode.pipe(Effect.map(Number)),
238 - ],
239 - { concurrency: "unbounded" },
240 - ).pipe(
241 - Effect.mapError((cause) => new TailscaleCommandOutputError({ ...commandContext, cause })),
242 - );
243 - if (exitCode !== 0) {
244 - return yield* new TailscaleCommandExitError({
245 - ...commandContext,
246 - exitCode,
247 - stdoutLength: stdout.length,
248 - stderrLength: stderr.length,
249 - ...(stderrDiagnosticOf(stderr) !== undefined
250 - ? { stderrDiagnostic: stderrDiagnosticOf(stderr) }
251 - : {}),
252 - });
253 - }
254 - return stdout;
255 - }).pipe(
256 - Effect.scoped,
257 - Effect.timeout(TAILSCALE_STATUS_TIMEOUT),
258 - Effect.catchTags({
259 - TimeoutError: (cause) =>
260 - Effect.fail(
261 - new TailscaleCommandTimeoutError({
262 - ...commandContext,
263 - timeoutMs: Duration.toMillis(TAILSCALE_STATUS_TIMEOUT),
264 - cause,
265 - }),
266 - ),
267 - }),
213 +const readTailscaleOutput = Effect.fn("tailscale.readTailscaleOutput")(function* (
214 + subcommand: "status" | "debug",
215 + args: readonly string[],
216 +) {
217 + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
218 + const hostPlatform = yield* HostProcess.Platform;
219 + const executable = tailscaleCommandForPlatform(hostPlatform);
220 + const commandContext = {
221 + executable,
222 + subcommand,
223 + argumentCount: args.length,
224 + };
225 + return yield* Effect.gen(function* () {
226 + const child = yield* spawner.spawn(ChildProcess.make(executable, [...args])).pipe(
227 + Effect.mapError((cause) => new TailscaleCommandSpawnError({ ...commandContext, cause })),
228 + // Spawning can also fail as a defect rather than a typed error - a
229 + // non-directory entry on PATH makes node throw ENOTDIR synchronously.
230 + // `mapError` never sees that, so it would escape as an uncaught error.
231 + Effect.catchDefect((cause) =>
232 + Effect.fail(new TailscaleCommandSpawnError({ ...commandContext, cause })),
233 + ),
234 + );
235 + const [stdout, stderr, exitCode] = yield* Effect.all(
236 + [
237 + collectStdout(child.stdout),
238 + collectStderr(child.stderr),
239 + child.exitCode.pipe(Effect.map(Number)),
240 + ],
241 + { concurrency: "unbounded" },
242 + ).pipe(
243 + Effect.mapError((cause) => new TailscaleCommandOutputError({ ...commandContext, cause })),
244 );
269 - });
245 + if (exitCode !== 0) {
246 + return yield* new TailscaleCommandExitError({
247 + ...commandContext,
248 + exitCode,
249 + stdoutLength: stdout.length,
250 + stderrLength: stderr.length,
251 + ...(stderrDiagnosticOf(stderr) !== undefined
252 + ? { stderrDiagnostic: stderrDiagnosticOf(stderr) }
253 + : {}),
254 + });
255 + }
256 + return stdout;
257 + }).pipe(
258 + Effect.scoped,
259 + Effect.timeout(TAILSCALE_STATUS_TIMEOUT),
260 + Effect.catchTags({
261 + TimeoutError: (cause) =>
262 + Effect.fail(
263 + new TailscaleCommandTimeoutError({
264 + ...commandContext,
265 + timeoutMs: Duration.toMillis(TAILSCALE_STATUS_TIMEOUT),
266 + cause,
267 + }),
268 + ),
269 + }),
270 + );
271 +});
272
273 export const readTailscaleStatus = readTailscaleOutput("status", ["status", "--json"]).pipe(
274 Effect.flatMap(parseTailscaleStatus),
@@ -308,58 +310,57 @@ export function buildTailscaleHttpsBaseUrl(input: {
310 return url.toString();
311 }
312
311 -const runTailscaleCommand = (
313 +const runTailscaleCommand = Effect.fn("tailscale.runTailscaleCommand")(function* (
314 args: readonly string[],
315 timeoutInput: Duration.Input,
314 -): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> =>
315 - Effect.gen(function* () {
316 - const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
317 - const hostPlatform = yield* HostProcess.Platform;
318 - const executable = tailscaleCommandForPlatform(hostPlatform);
319 - const commandContext = {
320 - executable,
321 - subcommand: "serve" as const,
322 - argumentCount: args.length,
323 - };
324 - const timeout = Duration.fromInputUnsafe(timeoutInput);
325 - return yield* Effect.gen(function* () {
326 - const child = yield* spawner.spawn(ChildProcess.make(executable, args)).pipe(
327 - Effect.mapError((cause) => new TailscaleCommandSpawnError({ ...commandContext, cause })),
328 - Effect.catchDefect((cause) =>
329 - Effect.fail(new TailscaleCommandSpawnError({ ...commandContext, cause })),
330 - ),
331 - );
332 - const [stderr, exitCode] = yield* Effect.all(
333 - [collectStderr(child.stderr), child.exitCode.pipe(Effect.map(Number))],
334 - { concurrency: "unbounded" },
335 - ).pipe(
336 - Effect.mapError((cause) => new TailscaleCommandOutputError({ ...commandContext, cause })),
337 - );
338 - if (exitCode !== 0) {
339 - return yield* new TailscaleCommandExitError({
340 - ...commandContext,
341 - exitCode,
342 - stderrLength: stderr.length,
343 - ...(stderrDiagnosticOf(stderr) !== undefined
344 - ? { stderrDiagnostic: stderrDiagnosticOf(stderr) }
345 - : {}),
346 - });
347 - }
348 - }).pipe(
349 - Effect.scoped,
350 - Effect.timeout(timeout),
351 - Effect.catchTags({
352 - TimeoutError: (cause) =>
353 - Effect.fail(
354 - new TailscaleCommandTimeoutError({
355 - ...commandContext,
356 - timeoutMs: Duration.toMillis(timeout),
357 - cause,
358 - }),
359 - ),
360 - }),
316 +): Effect.fn.Return<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> {
317 + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
318 + const hostPlatform = yield* HostProcess.Platform;
319 + const executable = tailscaleCommandForPlatform(hostPlatform);
320 + const commandContext = {
321 + executable,
322 + subcommand: "serve" as const,
323 + argumentCount: args.length,
324 + };
325 + const timeout = Duration.fromInputUnsafe(timeoutInput);
326 + return yield* Effect.gen(function* () {
327 + const child = yield* spawner.spawn(ChildProcess.make(executable, args)).pipe(
328 + Effect.mapError((cause) => new TailscaleCommandSpawnError({ ...commandContext, cause })),
329 + Effect.catchDefect((cause) =>
330 + Effect.fail(new TailscaleCommandSpawnError({ ...commandContext, cause })),
331 + ),
332 );
362 - });
333 + const [stderr, exitCode] = yield* Effect.all(
334 + [collectStderr(child.stderr), child.exitCode.pipe(Effect.map(Number))],
335 + { concurrency: "unbounded" },
336 + ).pipe(
337 + Effect.mapError((cause) => new TailscaleCommandOutputError({ ...commandContext, cause })),
338 + );
339 + if (exitCode !== 0) {
340 + return yield* new TailscaleCommandExitError({
341 + ...commandContext,
342 + exitCode,
343 + stderrLength: stderr.length,
344 + ...(stderrDiagnosticOf(stderr) !== undefined
345 + ? { stderrDiagnostic: stderrDiagnosticOf(stderr) }
346 + : {}),
347 + });
348 + }
349 + }).pipe(
350 + Effect.scoped,
351 + Effect.timeout(timeout),
352 + Effect.catchTags({
353 + TimeoutError: (cause) =>
354 + Effect.fail(
355 + new TailscaleCommandTimeoutError({
356 + ...commandContext,
357 + timeoutMs: Duration.toMillis(timeout),
358 + cause,
359 + }),
360 + ),
361 + }),
362 + );
363 +});
364
365 export const ensureTailscaleServe = (input: {
366 readonly localPort: number;
@@ -372,24 +373,20 @@ export const ensureTailscaleServe = (input: {
373 return runTailscaleCommand(args, TAILSCALE_SERVE_TIMEOUT);
374 };
375
375 -export const disableTailscaleServe = (
376 +export const disableTailscaleServe = Effect.fn("tailscale.disableTailscaleServe")(function* (
377 input: {
378 readonly servePort?: number;
379 } = {},
379 -): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> =>
380 - Effect.gen(function* () {
381 - const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
382 - return yield* runTailscaleCommand(
383 - ["serve", `--https=${servePort}`, "off"],
384 - TAILSCALE_SERVE_TIMEOUT,
385 - );
386 - });
380 +): Effect.fn.Return<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> {
381 + const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
382 + return yield* runTailscaleCommand(
383 + ["serve", `--https=${servePort}`, "off"],
384 + TAILSCALE_SERVE_TIMEOUT,
385 + );
386 +});
387
388 -export const probeTailscaleHttpsEndpoint = (input: {
389 - readonly baseUrl: string;
390 - readonly timeout?: Duration.Input;
391 -}): Effect.Effect<boolean, never, HttpClient.HttpClient> =>
392 - Effect.gen(function* () {
388 +export const probeTailscaleHttpsEndpoint = Effect.fn("tailscale.probeTailscaleHttpsEndpoint")(
389 + function* (input: { readonly baseUrl: string; readonly timeout?: Duration.Input }) {
390 const client = yield* HttpClient.HttpClient;
391 const response = yield* Effect.gen(function* () {
392 const url = new URL("/.well-known/t3/environment", input.baseUrl);
@@ -401,4 +398,6 @@ export const probeTailscaleHttpsEndpoint = (input: {
398 onNone: () => false,
399 onSome: (httpResponse) => httpResponse.status >= 200 && httpResponse.status < 300,
400 });
404 - }).pipe(Effect.orElseSucceed(() => false));
401 + },
402 + Effect.orElseSucceed(() => false),
403 +);