TypeScript
refactor(effect): trace shared and source-control operations (#21990)
Julius Marmingea8e8e7ee1152
diff --git a/packages/shared/src/DrainableWorker.ts b/packages/shared/src/DrainableWorker.tsindex 4515e5ca626..6f994068a5d 100644--- a/packages/shared/src/DrainableWorker.ts+++ b/packages/shared/src/DrainableWorker.ts@@ -15,50 +15,53 @@ export interface DrainableWorker<A> {* closes instead of waiting on them. An item that fails or dies is logged and skipped; the worker* keeps processing later items and `drain` still resolves.*/-export const makeDrainableWorker = <A, E, R>(+export const makeDrainableWorker = Effect.fn("DrainableWorker.makeDrainableWorker")(function* <+ A,+ E,+ R,+>(process: (item: A) => Effect.Effect<void, E, R>,-): Effect.Effect<DrainableWorker<A>, never, Scope.Scope | R> =>- Effect.gen(function* () {- const outstanding = yield* TxRef.make(0);- const queue = yield* Effect.acquireRelease(TxQueue.unbounded<A>(), (queue) =>- // Uncount only the dropped items: an item still running uncounts itself,- // even when a parallel scope closes it after this finalizer.- TxQueue.clear(queue).pipe(- Effect.flatMap((dropped) => TxRef.update(outstanding, (n) => n - dropped.length)),- Effect.andThen(TxQueue.shutdown(queue)),- Effect.tx,- ),- );+): Effect.fn.Return<DrainableWorker<A>, never, Scope.Scope | R> {+ const outstanding = yield* TxRef.make(0);+ const queue = yield* Effect.acquireRelease(TxQueue.unbounded<A>(), (queue) =>+ // Uncount only the dropped items: an item still running uncounts itself,+ // even when a parallel scope closes it after this finalizer.+ TxQueue.clear(queue).pipe(+ Effect.flatMap((dropped) => TxRef.update(outstanding, (n) => n - dropped.length)),+ Effect.andThen(TxQueue.shutdown(queue)),+ Effect.tx,+ ),+ );- yield* TxQueue.take(queue).pipe(- Effect.flatMap((a) =>- // `suspend` turns a `process` that throws while building its effect- // into this item's defect instead of the loop's.- Effect.suspend(() => process(a)).pipe(- // Only the item's own failure, defect, or interruption lands here and- // the loop continues; interrupting the worker fiber still stops it.- Effect.catchCause((cause) =>- Cause.hasInterruptsOnly(cause)- ? Effect.void- : Effect.logError("DrainableWorker item failed", cause),- ),- Effect.ensuring(TxRef.update(outstanding, (n) => n - 1)),+ yield* TxQueue.take(queue).pipe(+ Effect.flatMap((a) =>+ // `suspend` turns a `process` that throws while building its effect+ // into this item's defect instead of the loop's.+ Effect.suspend(() => process(a)).pipe(+ // Only the item's own failure, defect, or interruption lands here and+ // the loop continues; interrupting the worker fiber still stops it.+ Effect.catchCause((cause) =>+ Cause.hasInterruptsOnly(cause)+ ? Effect.void+ : Effect.logError("DrainableWorker item failed", cause),),+ Effect.ensuring(TxRef.update(outstanding, (n) => n - 1)),),- Effect.forever,- Effect.forkScoped,- );+ ),+ Effect.forever,+ Effect.forkScoped,+ );++ const drain: DrainableWorker<A>["drain"] = TxRef.get(outstanding).pipe(+ Effect.flatMap((n) => (n > 0 ? Effect.txRetry : Effect.void)),+ Effect.tx,+ );- const drain: DrainableWorker<A>["drain"] = TxRef.get(outstanding).pipe(- Effect.flatMap((n) => (n > 0 ? Effect.txRetry : Effect.void)),+ const enqueue = (element: A): Effect.Effect<boolean, never, never> =>+ TxQueue.offer(queue, element).pipe(+ Effect.tap((offered) => (offered ? TxRef.update(outstanding, (n) => n + 1) : Effect.void)),Effect.tx,);- const enqueue = (element: A): Effect.Effect<boolean, never, never> =>- TxQueue.offer(queue, element).pipe(- Effect.tap((offered) => (offered ? TxRef.update(outstanding, (n) => n + 1) : Effect.void)),- Effect.tx,- );-- return { enqueue, drain } satisfies DrainableWorker<A>;- });+ return { enqueue, drain } satisfies DrainableWorker<A>;+});diff --git a/packages/shared/src/KeyedCoalescingWorker.ts b/packages/shared/src/KeyedCoalescingWorker.tsindex 733a3b3c537..e36859367a9 100644--- a/packages/shared/src/KeyedCoalescingWorker.ts+++ b/packages/shared/src/KeyedCoalescingWorker.ts@@ -14,100 +14,99 @@ interface KeyedCoalescingWorkerState<K, V> {readonly activeKeys: Set<K>;}-export const makeKeyedCoalescingWorker = <K, V, E, R>(options: {+export const makeKeyedCoalescingWorker = Effect.fn(+ "KeyedCoalescingWorker.makeKeyedCoalescingWorker",+)(function* <K, V, E, R>(options: {readonly merge: (current: V, next: V) => V;readonly process: (key: K, value: V) => Effect.Effect<void, E, R>;-}): Effect.Effect<KeyedCoalescingWorker<K, V>, never, Scope.Scope | R> =>- Effect.gen(function* () {- const queue = yield* Effect.acquireRelease(TxQueue.unbounded<K>(), TxQueue.shutdown);- const stateRef = yield* TxRef.make<KeyedCoalescingWorkerState<K, V>>({- latestByKey: new Map(),- queuedKeys: new Set(),- activeKeys: new Set(),- });+}): Effect.fn.Return<KeyedCoalescingWorker<K, V>, never, Scope.Scope | R> {+ const queue = yield* Effect.acquireRelease(TxQueue.unbounded<K>(), TxQueue.shutdown);+ const stateRef = yield* TxRef.make<KeyedCoalescingWorkerState<K, V>>({+ latestByKey: new Map(),+ queuedKeys: new Set(),+ activeKeys: new Set(),+ });- const completeKey = (key: K): Effect.Effect<void> =>- TxRef.modify(stateRef, (state) => {- const activeKeys = new Set(state.activeKeys);- activeKeys.delete(key);+ const completeKey = (key: K): Effect.Effect<void> =>+ TxRef.modify(stateRef, (state) => {+ const activeKeys = new Set(state.activeKeys);+ activeKeys.delete(key);- if (state.latestByKey.has(key) && !state.queuedKeys.has(key)) {- const queuedKeys = new Set(state.queuedKeys);- queuedKeys.add(key);- return [true, { ...state, activeKeys, queuedKeys }] as const;- }+ if (state.latestByKey.has(key) && !state.queuedKeys.has(key)) {+ const queuedKeys = new Set(state.queuedKeys);+ queuedKeys.add(key);+ return [true, { ...state, activeKeys, queuedKeys }] as const;+ }- return [false, { ...state, activeKeys }] as const;- }).pipe(- Effect.flatMap((shouldRequeue) =>- shouldRequeue ? TxQueue.offer(queue, key) : Effect.void,- ),- Effect.tx,- Effect.asVoid,- );+ return [false, { ...state, activeKeys }] as const;+ }).pipe(+ Effect.flatMap((shouldRequeue) => (shouldRequeue ? TxQueue.offer(queue, key) : Effect.void)),+ Effect.tx,+ Effect.asVoid,+ );- yield* TxQueue.take(queue).pipe(- Effect.flatMap((key) =>- TxRef.modify(stateRef, (state) => {- const queuedKeys = new Set(state.queuedKeys);- queuedKeys.delete(key);+ yield* TxQueue.take(queue).pipe(+ Effect.flatMap((key) =>+ TxRef.modify(stateRef, (state) => {+ const queuedKeys = new Set(state.queuedKeys);+ queuedKeys.delete(key);- const value = state.latestByKey.get(key);- if (value === undefined) {- return [null, { ...state, queuedKeys }] as const;- }+ const value = state.latestByKey.get(key);+ if (value === undefined) {+ return [null, { ...state, queuedKeys }] as const;+ }- const latestByKey = new Map(state.latestByKey);- latestByKey.delete(key);- const activeKeys = new Set(state.activeKeys);- activeKeys.add(key);+ const latestByKey = new Map(state.latestByKey);+ latestByKey.delete(key);+ const activeKeys = new Set(state.activeKeys);+ activeKeys.add(key);- return [- { key, value } as const,- { ...state, latestByKey, queuedKeys, activeKeys },- ] as const;- }).pipe(Effect.tx),- ),- Effect.flatMap((item) =>- item === null- ? Effect.void- : options- .process(item.key, item.value)- .pipe(Effect.ignoreCause, Effect.ensuring(completeKey(item.key))),- ),- Effect.forever,- Effect.forkScoped,- );+ return [+ { key, value } as const,+ { ...state, latestByKey, queuedKeys, activeKeys },+ ] as const;+ }).pipe(Effect.tx),+ ),+ Effect.flatMap((item) =>+ item === null+ ? Effect.void+ : options+ .process(item.key, item.value)+ .pipe(Effect.ignoreCause, Effect.ensuring(completeKey(item.key))),+ ),+ Effect.forever,+ Effect.forkScoped,+ );- const enqueue: KeyedCoalescingWorker<K, V>["enqueue"] = (key, value) =>- TxRef.modify(stateRef, (state) => {- const latestByKey = new Map(state.latestByKey);- const existing = latestByKey.get(key);- latestByKey.set(key, existing === undefined ? value : options.merge(existing, value));+ const enqueue: KeyedCoalescingWorker<K, V>["enqueue"] = (key, value) =>+ TxRef.modify(stateRef, (state) => {+ const latestByKey = new Map(state.latestByKey);+ const existing = latestByKey.get(key);+ latestByKey.set(key, existing === undefined ? value : options.merge(existing, value));- if (state.queuedKeys.has(key) || state.activeKeys.has(key)) {- return [false, { ...state, latestByKey }] as const;- }+ if (state.queuedKeys.has(key) || state.activeKeys.has(key)) {+ return [false, { ...state, latestByKey }] as const;+ }- const queuedKeys = new Set(state.queuedKeys);- queuedKeys.add(key);- return [true, { ...state, latestByKey, queuedKeys }] as const;- }).pipe(- Effect.flatMap((shouldOffer) => (shouldOffer ? TxQueue.offer(queue, key) : Effect.void)),- Effect.tx,- Effect.asVoid,- );+ const queuedKeys = new Set(state.queuedKeys);+ queuedKeys.add(key);+ return [true, { ...state, latestByKey, queuedKeys }] as const;+ }).pipe(+ Effect.flatMap((shouldOffer) => (shouldOffer ? TxQueue.offer(queue, key) : Effect.void)),+ Effect.tx,+ Effect.asVoid,+ );- const drainKey: KeyedCoalescingWorker<K, V>["drainKey"] = (key) =>- TxRef.get(stateRef).pipe(- Effect.tap((state) =>- state.latestByKey.has(key) || state.queuedKeys.has(key) || state.activeKeys.has(key)- ? Effect.txRetry- : Effect.void,- ),- Effect.asVoid,- Effect.tx,- );+ const drainKey: KeyedCoalescingWorker<K, V>["drainKey"] = (key) =>+ TxRef.get(stateRef).pipe(+ Effect.tap((state) =>+ state.latestByKey.has(key) || state.queuedKeys.has(key) || state.activeKeys.has(key)+ ? Effect.txRetry+ : Effect.void,+ ),+ Effect.asVoid,+ Effect.tx,+ );- return { enqueue, drainKey } satisfies KeyedCoalescingWorker<K, V>;- });+ return { enqueue, drainKey } satisfies KeyedCoalescingWorker<K, V>;+});diff --git a/packages/shared/src/KeyedLock.ts b/packages/shared/src/KeyedLock.tsindex 0411d7ef7e7..27ddcd79210 100644--- a/packages/shared/src/KeyedLock.ts+++ b/packages/shared/src/KeyedLock.ts@@ -15,41 +15,42 @@ interface LockEntry {/*** Not reentrant: taking a key while already holding it deadlocks.*/-export const make = <Key>(): Effect.Effect<KeyedLock<Key>> =>- Effect.gen(function* () {- const locks = yield* Ref.make<ReadonlyMap<Key, LockEntry>>(new Map());+export const make = Effect.fn("KeyedLock.make")(function* <Key>(): Effect.fn.Return<+ KeyedLock<Key>+> {+ const locks = yield* Ref.make<ReadonlyMap<Key, LockEntry>>(new Map());- const acquire = (key: Key) =>- Effect.flatMap(Semaphore.make(1), (candidate) =>- Ref.modify(locks, (current) => {- const existing = current.get(key);- const semaphore = existing?.semaphore ?? candidate;- const next = new Map(current);- next.set(key, { semaphore, users: (existing?.users ?? 0) + 1 });- return [semaphore, next] as const;- }),- );-- const release = (key: Key) =>- Ref.update(locks, (current) => {+ const acquire = (key: Key) =>+ Effect.flatMap(Semaphore.make(1), (candidate) =>+ Ref.modify(locks, (current) => {const existing = current.get(key);- if (existing === undefined) return current;+ const semaphore = existing?.semaphore ?? candidate;const next = new Map(current);- if (existing.users === 1) {- next.delete(key);- } else {- next.set(key, { ...existing, users: existing.users - 1 });- }- return next;- });+ next.set(key, { semaphore, users: (existing?.users ?? 0) + 1 });+ return [semaphore, next] as const;+ }),+ );++ const release = (key: Key) =>+ Ref.update(locks, (current) => {+ const existing = current.get(key);+ if (existing === undefined) return current;+ const next = new Map(current);+ if (existing.users === 1) {+ next.delete(key);+ } else {+ next.set(key, { ...existing, users: existing.users - 1 });+ }+ return next;+ });- return {- withLock: (key, effect) =>- Effect.acquireUseRelease(- acquire(key),- (semaphore) => semaphore.withPermit(effect),- () => release(key),- ),- activeKeys: Effect.map(Ref.get(locks), (current) => Array.from(current.keys())),- } satisfies KeyedLock<Key>;- });+ return {+ withLock: (key, effect) =>+ Effect.acquireUseRelease(+ acquire(key),+ (semaphore) => semaphore.withPermit(effect),+ () => release(key),+ ),+ activeKeys: Effect.map(Ref.get(locks), (current) => Array.from(current.keys())),+ } satisfies KeyedLock<Key>;+});diff --git a/packages/shared/src/Net.ts b/packages/shared/src/Net.tsindex 7acb024d859..de56d07fadb 100644--- a/packages/shared/src/Net.ts+++ b/packages/shared/src/Net.ts@@ -111,23 +111,24 @@ export const make = () => {});});- const isPortAvailableOnLoopback = (port: number): Effect.Effect<boolean> =>- Effect.gen(function* () {- const hasListener = yield* Effect.zipWith(- hasListenerOnHost(port, "127.0.0.1"),- hasListenerOnHost(port, "::1"),- (ipv4, ipv6) => ipv4 || ipv6,- );- if (hasListener) {- return false;- }-- return yield* Effect.zipWith(- canListenOnHost(port, "127.0.0.1"),- canListenOnHost(port, "::1"),- (ipv4, ipv6) => ipv4 && ipv6,- );- });+ const isPortAvailableOnLoopback = Effect.fn("Net.isPortAvailableOnLoopback")(function* (+ port: number,+ ): Effect.fn.Return<boolean> {+ const hasListener = yield* Effect.zipWith(+ hasListenerOnHost(port, "127.0.0.1"),+ hasListenerOnHost(port, "::1"),+ (ipv4, ipv6) => ipv4 || ipv6,+ );+ if (hasListener) {+ return false;+ }++ return yield* Effect.zipWith(+ canListenOnHost(port, "127.0.0.1"),+ canListenOnHost(port, "::1"),+ (ipv4, ipv6) => ipv4 && ipv6,+ );+ });const reserveLoopbackPort = (host = "127.0.0.1"): Effect.Effect<number, NetError> =>Effect.callback<number, NetError>((resume) => {@@ -166,13 +167,12 @@ export const make = () => {isPortAvailableOnLoopback,hasListenerOnHost,reserveLoopbackPort,- findAvailablePort: (preferred) =>- Effect.gen(function* () {- if (preferred > 0 && (yield* isPortAvailableOnLoopback(preferred))) {- return preferred;- }- return yield* reserveLoopbackPort();- }),+ findAvailablePort: Effect.fn("Net.findAvailablePort")(function* (preferred) {+ if (preferred > 0 && (yield* isPortAvailableOnLoopback(preferred))) {+ return preferred;+ }+ return yield* reserveLoopbackPort();+ }),} satisfies NetServiceShape;};diff --git a/packages/shared/src/atomicWrite.test.ts b/packages/shared/src/atomicWrite.test.tsindex 83d85b050d8..5249966d154 100644--- a/packages/shared/src/atomicWrite.test.ts+++ b/packages/shared/src/atomicWrite.test.ts@@ -277,11 +277,12 @@ it.effect("surfaces an unreadable link instead of writing over it", () =>pathOrDescriptor: "/home/settings.json",});- const result = yield* Effect.exit(- writeFileStringAtomically({ filePath: "/home/settings.json", contents: "after" }),- );+ const failure = yield* writeFileStringAtomically({+ filePath: "/home/settings.json",+ contents: "after",+ }).pipe(Effect.flip);- assert.deepStrictEqual(result, Exit.fail(readLinkFailure));+ assert.deepStrictEqual(failure, readLinkFailure);}).pipe(Effect.provide(Layer.mergeAll(diff --git a/packages/shared/src/devHome.ts b/packages/shared/src/devHome.tsindex e35e63681b0..1bf729a3a42 100644--- a/packages/shared/src/devHome.ts+++ b/packages/shared/src/devHome.ts@@ -33,46 +33,44 @@ const pointsAtLinkedWorktree = (gitFileContents: string, path: Path.Path): boolereturn segments.length >= 3 && segments.at(-2) === "worktrees";};-export const resolveGitWorktreePath = (+export const resolveGitWorktreePath = Effect.fn("devHome.resolveGitWorktreePath")(function* (cwd: string,-): Effect.Effect<string | undefined, never, FileSystem.FileSystem | Path.Path> =>- Effect.gen(function* () {- const fileSystem = yield* FileSystem.FileSystem;- const path = yield* Path.Path;+): Effect.fn.Return<string | undefined, never, FileSystem.FileSystem | Path.Path> {+ const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;- let directory = path.resolve(cwd);- for (;;) {- const gitPath = path.join(directory, ".git");- const info = yield* fileSystem.stat(gitPath).pipe(Effect.option);- if (Option.isSome(info)) {- if (info.value.type !== "File") {- return undefined;- }- const contents = yield* fileSystem- .readFileString(gitPath)- .pipe(Effect.orElseSucceed(() => ""));- return pointsAtLinkedWorktree(contents, path) ? directory : undefined;- }- const parent = path.dirname(directory);- if (parent === directory) {+ let directory = path.resolve(cwd);+ for (;;) {+ const gitPath = path.join(directory, ".git");+ const info = yield* fileSystem.stat(gitPath).pipe(Effect.option);+ if (Option.isSome(info)) {+ if (info.value.type !== "File") {return undefined;}- directory = parent;+ const contents = yield* fileSystem+ .readFileString(gitPath)+ .pipe(Effect.orElseSucceed(() => ""));+ return pointsAtLinkedWorktree(contents, path) ? directory : undefined;+ }+ const parent = path.dirname(directory);+ if (parent === directory) {+ return undefined;}- });+ directory = parent;+ }+});/*** Deliberately does not require the directory to exist yet: falling back* because it is missing would send callers at the shared home.*/-export const resolveWorktreeT3Home = (+export const resolveWorktreeT3Home = Effect.fn("devHome.resolveWorktreeT3Home")(function* (cwd: string,-): Effect.Effect<string | undefined, never, FileSystem.FileSystem | Path.Path> =>- Effect.gen(function* () {- const worktreePath = yield* resolveGitWorktreePath(cwd);- if (worktreePath === undefined) {- return undefined;- }- const path = yield* Path.Path;- return path.join(worktreePath, ".t3");- });+): Effect.fn.Return<string | undefined, never, FileSystem.FileSystem | Path.Path> {+ const worktreePath = yield* resolveGitWorktreePath(cwd);+ if (worktreePath === undefined) {+ return undefined;+ }+ const path = yield* Path.Path;+ return path.join(worktreePath, ".t3");+});diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.tsindex 983ba0598eb..48155c4337a 100644--- a/packages/shared/src/shell.ts+++ b/packages/shared/src/shell.ts@@ -511,8 +511,9 @@ const PathDirectoryListings = Context.Reference<Cache.Cache<string, PathDirectoryListing, never, FileSystem.FileSystem> | undefined>("@t3tools/shared/shell/PathDirectoryListings", { defaultValue: () => undefined });-export const withPathDirectoryListings = <A, E, R>(effect: Effect.Effect<A, E, R>) =>- Effect.gen(function* () {+export const withPathDirectoryListings =+ /* Directory reads are cached inside one shell operation; a span for each lookup adds noise. */+ Effect.fnUntraced(function* <A, E, R>(effect: Effect.Effect<A, E, R>) {const listings = yield* Cache.make({capacity: 1024,lookup: listPathDirectory,diff --git a/packages/shared/src/symlink.ts b/packages/shared/src/symlink.tsindex bc947b0596a..7dfc7606e78 100644--- a/packages/shared/src/symlink.ts+++ b/packages/shared/src/symlink.ts@@ -17,31 +17,32 @@ const isNotASymlink = (error: PlatformError.PlatformError) =>* on a cycle, an overly long chain, or an unreadable link rather than handing* back a link that a rename would replace.*/-export const resolveSymlinkTarget = (filePath: string) =>- Effect.gen(function* () {- const fs = yield* FileSystem.FileSystem;- const path = yield* Path.Path;- let current = path.resolve(filePath);- for (let hop = 0; hop < MAX_SYMLINK_HOPS; hop++) {- const link = yield* fs.readLink(current).pipe(- Effect.map(Option.some),- Effect.catchIf(isNotASymlink, () => Effect.succeedNone),- );- if (Option.isNone(link)) {- return current;- }- // A relative target is relative to where the link really lives, which- // differs from its lexical parent when that parent is itself a symlink.- const linkDirectory = yield* fs- .realPath(path.dirname(current))- .pipe(Effect.catchIf(isNotFound, () => Effect.succeed(path.dirname(current))));- current = path.resolve(linkDirectory, link.value);+export const resolveSymlinkTarget = Effect.fn("symlink.resolveSymlinkTarget")(function* (+ filePath: string,+) {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ let current = path.resolve(filePath);+ for (let hop = 0; hop < MAX_SYMLINK_HOPS; hop++) {+ const link = yield* fs.readLink(current).pipe(+ Effect.map(Option.some),+ Effect.catchIf(isNotASymlink, () => Effect.succeedNone),+ );+ if (Option.isNone(link)) {+ return current;}- return yield* PlatformError.systemError({- _tag: "Unknown",- module: "FileSystem",- method: "readLink",- description: "Too many levels of symbolic links",- pathOrDescriptor: filePath,- });+ // A relative target is relative to where the link really lives, which+ // differs from its lexical parent when that parent is itself a symlink.+ const linkDirectory = yield* fs+ .realPath(path.dirname(current))+ .pipe(Effect.catchIf(isNotFound, () => Effect.succeed(path.dirname(current))));+ current = path.resolve(linkDirectory, link.value);+ }+ return yield* PlatformError.systemError({+ _tag: "Unknown",+ module: "FileSystem",+ method: "readLink",+ description: "Too many levels of symbolic links",+ pathOrDescriptor: filePath,});+});diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.tsindex 4a060b23a42..d083384697a 100644--- a/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.ts+++ b/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.ts@@ -176,17 +176,19 @@ export const make = Effect.gen(function* () {);};- const diffScope = (input: { readonly cwd: string; readonly number: number }) =>- Effect.gen(function* () {- const location = yield* locationOf(input);- if (location === null) return null;- const iterations = yield* cli.listIterations({- cwd: input.cwd,- location,- number: input.number,- });- return { location, iterations };+ const diffScope = Effect.fn("AzureDevOpsPullRequestProvider.diffScope")(function* (input: {+ readonly cwd: string;+ readonly number: number;+ }) {+ const location = yield* locationOf(input);+ if (location === null) return null;+ const iterations = yield* cli.listIterations({+ cwd: input.cwd,+ location,+ number: input.number,});+ return { location, iterations };+ });const EMPTY_ITEM: AzureDevOpsItemContent = { contents: "", isBinary: false };@@ -305,8 +307,8 @@ export const make = Effect.gen(function* () {})),),- getChangeRequest: (input) =>- Effect.gen(function* () {+ getChangeRequest: Effect.fn("AzureDevOpsPullRequestProvider.getChangeRequest")(+ function* (input) {const pullRequest = yield* cli.getPullRequest({ cwd: input.cwd, number: input.number });const location = pullRequest.location;const iterations =@@ -346,7 +348,9 @@ export const make = Effect.gen(function* () {: { autoMergeMethod: pullRequest.autoMergeMethod }),};return detail;- }).pipe(Effect.mapError(fail("getChangeRequest"))),+ },+ Effect.mapError(fail("getChangeRequest")),+ ),getChangeRequestActivity: (input) =>cli.getPullRequest({ cwd: input.cwd, number: input.number }).pipe(@@ -380,8 +384,8 @@ export const make = Effect.gen(function* () {// `input.commit` is deliberately dropped: Azure states no commit list on a pull request, so// the Code tab has nothing to scope itself to and always asks for the whole change.- getDiff: (input) =>- Effect.gen(function* () {+ getDiff: Effect.fn("AzureDevOpsPullRequestProvider.getDiff")(+ function* (input) {const scope = yield* diffScope(input);if (scope === null) return EMPTY_DIFF_SLICE;const cursor = parseAzureDevOpsDiffCursor(input.cursor);@@ -479,10 +483,12 @@ export const make = Effect.gen(function* () {: formatAzureDevOpsDiffCursor({ iterationId: iteration.id, fileIndex: index }),};return slice;- }).pipe(Effect.mapError(fail("getDiff"))),+ },+ Effect.mapError(fail("getDiff")),+ ),- getDiffFileContents: (input) =>- Effect.gen(function* () {+ getDiffFileContents: Effect.fn("AzureDevOpsPullRequestProvider.getDiffFileContents")(+ function* (input) {const scope = yield* diffScope(input);const iteration = scope?.iterations.at(-1);if (scope === null || iteration === undefined) return { oldContents: "", newContents: "" };@@ -496,15 +502,17 @@ export const make = Effect.gen(function* () {oldPath: input.oldPath,},});- }).pipe(Effect.mapError(fail("getDiffFileContents"))),+ },+ Effect.mapError(fail("getDiffFileContents")),+ ),/*** A path the change does not carry is at the empty revision, which is where a file the pull* request deletes sits. When the change was too long to follow to its end, those paths are left* out instead: reporting them as deleted would clear a file nobody has read.*/- getFileRevisions: (input) =>- Effect.gen(function* () {+ getFileRevisions: Effect.fn("AzureDevOpsPullRequestProvider.getFileRevisions")(+ function* (input) {const revisions = new Map<string, string>();if (input.paths.length === 0) return { revisions };const scope = yield* diffScope(input);@@ -525,7 +533,9 @@ export const make = Effect.gen(function* () {}}return { revisions };- }).pipe(Effect.mapError(fail("getFileRevisions"))),+ },+ Effect.mapError(fail("getFileRevisions")),+ ),runAction: (input) =>clidiff --git a/packages/source-control-bitbucket/src/server/BitbucketApi.ts b/packages/source-control-bitbucket/src/server/BitbucketApi.tsindex e3f64c731f7..eaa607e3ef1 100644--- a/packages/source-control-bitbucket/src/server/BitbucketApi.ts+++ b/packages/source-control-bitbucket/src/server/BitbucketApi.ts@@ -602,35 +602,33 @@ function originOf(value: string): string | null {}}-function responseError(+const responseError = Effect.fn("BitbucketApi.responseError")(function* (operation: BitbucketApiOperation,response: HttpClientResponse.HttpClientResponse,-): Effect.Effect<never, BitbucketApiError> {- return Effect.gen(function* () {- const now = yield* Clock.currentTimeMillis;- const retryAt = retryAtFromHeader(response.headers["retry-after"], now);- const collected = yield* collectUint8StreamText({- stream: response.stream,- maxBytes: DEFAULT_MAX_RESPONSE_BYTES,- }).pipe(- Effect.mapError(- (cause) =>- new BitbucketResponseBodyReadError({- operation,- status: response.status,- retryAt,- cause,- }),- ),- );- return yield* new BitbucketResponseError({- operation,- status: response.status,- responseBodyLength: collected.text.length,- retryAt,- });+): Effect.fn.Return<never, BitbucketApiError> {+ const now = yield* Clock.currentTimeMillis;+ const retryAt = retryAtFromHeader(response.headers["retry-after"], now);+ const collected = yield* collectUint8StreamText({+ stream: response.stream,+ maxBytes: DEFAULT_MAX_RESPONSE_BYTES,+ }).pipe(+ Effect.mapError(+ (cause) =>+ new BitbucketResponseBodyReadError({+ operation,+ status: response.status,+ retryAt,+ cause,+ }),+ ),+ );+ return yield* new BitbucketResponseError({+ operation,+ status: response.status,+ responseBodyLength: collected.text.length,+ retryAt,});-}+});/** @public Service construction is part of the canonical Effect module API. */export const make = Effect.gen(function* () {@@ -1015,52 +1013,51 @@ export const make = Effect.gen(function* () {),Effect.map(normalizeRepositoryCloneUrls),),- createPullRequest: (input) =>- Effect.gen(function* () {- const repository = yield* resolveRepository(input);- const description = yield* fileSystem.readFileString(input.bodyFile).pipe(- Effect.mapError(- (cause) =>- new BitbucketPullRequestBodyReadError({- cwd: input.cwd,- bodyFile: input.bodyFile,- cause,- }),- ),- );- const sourceOwner = sourceWorkspace(input);- const body = {- title: input.title,- description,- source: {- branch: {- name: SourceControlProvider.sourceBranch(input),- },- ...(sourceOwner- ? {- repository: {- full_name: `${sourceOwner}/${input.source?.repository ?? repository.repoSlug}`,- },- }- : {}),+ createPullRequest: Effect.fn("BitbucketApi.createPullRequest")(function* (input) {+ const repository = yield* resolveRepository(input);+ const description = yield* fileSystem.readFileString(input.bodyFile).pipe(+ Effect.mapError(+ (cause) =>+ new BitbucketPullRequestBodyReadError({+ cwd: input.cwd,+ bodyFile: input.bodyFile,+ cause,+ }),+ ),+ );+ const sourceOwner = sourceWorkspace(input);+ const body = {+ title: input.title,+ description,+ source: {+ branch: {+ name: SourceControlProvider.sourceBranch(input),},- destination: {- branch: {- name: input.target?.refName ?? input.baseBranch,- },+ ...(sourceOwner+ ? {+ repository: {+ full_name: `${sourceOwner}/${input.source?.repository ?? repository.repoSlug}`,+ },+ }+ : {}),+ },+ destination: {+ branch: {+ name: input.target?.refName ?? input.baseBranch,},- };-- yield* executeJson(- "createPullRequest",- HttpClientRequest.post(- apiUrl(- `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/pullrequests`,- ),- ).pipe(HttpClientRequest.bodyJsonUnsafe(body)),- BitbucketPullRequestSchema,- );- }),+ },+ };++ yield* executeJson(+ "createPullRequest",+ HttpClientRequest.post(+ apiUrl(+ `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/pullrequests`,+ ),+ ).pipe(HttpClientRequest.bodyJsonUnsafe(body)),+ BitbucketPullRequestSchema,+ );+ }),getDefaultBranch: (input) =>resolveRepository(input).pipe(Effect.flatMap((locator) =>@@ -1078,8 +1075,8 @@ export const make = Effect.gen(function* () {),Effect.map(defaultChangeRequestTargetBranch),),- checkoutPullRequest: (input) =>- Effect.gen(function* () {+ checkoutPullRequest: Effect.fn("BitbucketApi.checkoutPullRequest")(+ function* (input) {const destinationRepository = yield* resolveRepository(input);const pullRequest = yield* getRawPullRequestFromRepository(destinationRepository,@@ -1129,17 +1126,20 @@ export const make = Effect.gen(function* () {remoteBranch,});yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch }));- }).pipe(- Effect.mapError((cause) =>- isBitbucketApiError(cause)- ? cause- : new BitbucketCheckoutError({- cwd: input.cwd,- reference: input.reference,- cause,- }),+ },+ (effect, input) =>+ effect.pipe(+ Effect.mapError((cause) =>+ isBitbucketApiError(cause)+ ? cause+ : new BitbucketCheckoutError({+ cwd: input.cwd,+ reference: input.reference,+ cause,+ }),+ ),),- ),+ ),});});diff --git a/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.ts b/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.tsindex 957694c60ed..ba8465e9cc7 100644--- a/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.ts+++ b/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.ts@@ -306,8 +306,8 @@ export const make = Effect.gen(function* () {kind: SourceControlProviderKind.make("forgejo"),repositoryNameFromRemoteUrl,refineRepositoryIdentity,- listChangeRequests: (input) =>- Effect.gen(function* () {+ listChangeRequests: Effect.fn("ForgejoSourceControlProvider.listChangeRequests")(+ function* (input) {const repo = yield* cli.resolveRepository(input);const source = SourceControlProvider.sourceControlRefFromInput(input);const branch = SourceControlProvider.sourceBranch(input);@@ -334,14 +334,16 @@ export const make = Effect.gen(function* () {if (items.length === 0) break;}return results.slice(0, limit);- }).pipe(mapError("listChangeRequests", input.cwd)),+ },+ (effect, input) => effect.pipe(mapError("listChangeRequests", input.cwd)),+ ),getChangeRequest: (input) =>getPull(input).pipe(Effect.map(toForgejoChangeRequest),mapError("getChangeRequest", input.cwd),),- createChangeRequest: (input) =>- Effect.gen(function* () {+ createChangeRequest: Effect.fn("ForgejoSourceControlProvider.createChangeRequest")(+ function* (input) {const repo = yield* cli.resolveRepository(input);const source = SourceControlProvider.sourceControlRefFromInput(input);const owner = source?.owner ?? source?.repository?.split("/")[0];@@ -357,16 +359,20 @@ export const make = Effect.gen(function* () {body: yield* fs.readFileString(input.bodyFile),},});- }).pipe(mapError("createChangeRequest", input.cwd)),- getRepositoryCloneUrls: (input) =>- Effect.gen(function* () {+ },+ (effect, input) => effect.pipe(mapError("createChangeRequest", input.cwd)),+ ),+ getRepositoryCloneUrls: Effect.fn("ForgejoSourceControlProvider.getRepositoryCloneUrls")(+ function* (input) {const repo = yield* cli.resolveRepository(input);return cloneUrls(yield* request({ ...input, path: repositoryPath(repo.repository) }, RepositorySchema),);- }).pipe(mapError("getRepositoryCloneUrls", input.cwd)),- createRepository: (input) =>- Effect.gen(function* () {+ },+ (effect, input) => effect.pipe(mapError("getRepositoryCloneUrls", input.cwd)),+ ),+ createRepository: Effect.fn("ForgejoSourceControlProvider.createRepository")(+ function* (input) {const repo = yield* cli.resolveRepository(input);const user = yield* request({ ...input, path: "user" },@@ -387,17 +393,21 @@ export const make = Effect.gen(function* () {RepositorySchema,),);- }).pipe(mapError("createRepository", input.cwd)),- getDefaultBranch: (input) =>- Effect.gen(function* () {+ },+ (effect, input) => effect.pipe(mapError("createRepository", input.cwd)),+ ),+ getDefaultBranch: Effect.fn("ForgejoSourceControlProvider.getDefaultBranch")(+ function* (input) {const repo = yield* cli.resolveRepository(input);return ((yield* request({ ...input, path: repositoryPath(repo.repository) }, RepositorySchema)).default_branch ?? null);- }).pipe(mapError("getDefaultBranch", input.cwd)),- checkoutChangeRequest: (input) =>- Effect.gen(function* () {+ },+ (effect, input) => effect.pipe(mapError("getDefaultBranch", input.cwd)),+ ),+ checkoutChangeRequest: Effect.fn("ForgejoSourceControlProvider.checkoutChangeRequest")(+ function* (input) {const repo = yield* cli.resolveRepository(input);const pull = yield* getPull(input);if (repo.command === "fj") {@@ -468,6 +478,8 @@ export const make = Effect.gen(function* () {args: ["reset", "--keep", pull.head.sha],});}- }).pipe(mapError("checkoutChangeRequest", input.cwd)),+ },+ (effect, input) => effect.pipe(mapError("checkoutChangeRequest", input.cwd)),+ ),});});diff --git a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.tsindex efcc1b9e2d9..41683de1767 100644--- a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts+++ b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts@@ -230,31 +230,22 @@ export const make = Effect.gen(function* () {Effect.flatMap((path) => read(operation, input, { path }, Json.GitCafePullDetail)),);- const readPages = <S extends Schema.Codec<Paged<unknown>, unknown, never, never>>(- operation: string,- input: Pick<ProviderRepositoryRef, "host">,- path: string,- schema: S,- ) =>- Effect.gen(function* () {- const items: Array<S["Type"]["items"][number]> = [];- let next: string | null = null;- for (let page = 0; page < MAX_PAGES; page++) {- const query = new URLSearchParams({ limit: String(PAGE_SIZE) });- if (next !== null) query.set("after", next);- const batch: S["Type"] = yield* read(- operation,- input,- { path: `${path}?${query}` },- schema,- );- items.push(...batch.items);- const previous: string | null = next;- next = batch.next;- if (next === null || next === previous || batch.items.length === 0) break;- }- return { items, next };- });+ const readPages = Effect.fn("GitCafePullRequestProvider.readPages")(function* <+ S extends Schema.Codec<Paged<unknown>, unknown, never, never>,+ >(operation: string, input: Pick<ProviderRepositoryRef, "host">, path: string, schema: S) {+ const items: Array<S["Type"]["items"][number]> = [];+ let next: string | null = null;+ for (let page = 0; page < MAX_PAGES; page++) {+ const query = new URLSearchParams({ limit: String(PAGE_SIZE) });+ if (next !== null) query.set("after", next);+ const batch: S["Type"] = yield* read(operation, input, { path: `${path}?${query}` }, schema);+ items.push(...batch.items);+ const previous: string | null = next;+ next = batch.next;+ if (next === null || next === previous || batch.items.length === 0) break;+ }+ return { items, next };+ });const readComments = (operation: string, input: PullRef) =>pullPath(operation, input).pipe(diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.tsindex 0e73babffc0..4eb3aec349c 100644--- a/packages/source-control-github/src/server/GitHubPullRequestApi.ts+++ b/packages/source-control-github/src/server/GitHubPullRequestApi.ts@@ -1024,7 +1024,7 @@ export const make = Effect.gen(function* () {* `maxPages` have been read, or `until` is satisfied. `truncated` says pages remained when* reading stopped; a cursor GitHub hands back a second time stops the read as truncated too.*/- const readPages = <Page, E, R>(+ const readPages = Effect.fn("GitHubPullRequestApi.readPages")(function* <Page, E, R>(stream: Stream.Stream<Page, E | GraphQLClientError.GraphQLClientError, R>,options: {readonly cwd: string;@@ -1033,33 +1033,32 @@ export const make = Effect.gen(function* () {readonly maxPages?: number;readonly until?: (pages: ReadonlyArray<NoInfer<Page>>) => boolean;},- ) =>- Effect.gen(function* () {- const pages: Page[] = [];- let repeated = false;- yield* stream.pipe(- // `pages` fails a cursor GitHub hands back unchanged, which would page forever.- Stream.catch((error) =>- isGraphQlClientError(error) && error.reason._tag === "PaginationError"- ? Stream.sync(() => {- repeated = true;- }).pipe(Stream.drain)- : Stream.fail(error),- ),- Stream.runForEachWhile((page) =>- Effect.sync(() => {- pages.push(page);- return (- options.hasNextPage(page) &&- pages.length < (options.maxPages ?? Infinity) &&- options.until?.(pages) !== true- );- }),- ),- );- const last = pages.at(-1);- return { pages, truncated: repeated || (last !== undefined && options.hasNextPage(last)) };- });+ ) {+ const pages: Page[] = [];+ let repeated = false;+ yield* stream.pipe(+ // `pages` fails a cursor GitHub hands back unchanged, which would page forever.+ Stream.catch((error) =>+ isGraphQlClientError(error) && error.reason._tag === "PaginationError"+ ? Stream.sync(() => {+ repeated = true;+ }).pipe(Stream.drain)+ : Stream.fail(error),+ ),+ Stream.runForEachWhile((page) =>+ Effect.sync(() => {+ pages.push(page);+ return (+ options.hasNextPage(page) &&+ pages.length < (options.maxPages ?? Infinity) &&+ options.until?.(pages) !== true+ );+ }),+ ),+ );+ const last = pages.at(-1);+ return { pages, truncated: repeated || (last !== undefined && options.hasNextPage(last)) };+ });/*** 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* () {};const getPullRequestDiffFileContents: GitHubPullRequestApi["Service"]["getPullRequestDiffFileContents"] =- (input) =>- Effect.gen(function* () {- if (input.commit !== undefined && !isCommitSha(input.commit)) {- return yield* new GitHubDiffCommitError({ cwd: input.cwd });- }- const { owner, name } = parseRepositorySelector(input.repository);- const refsResponse = yield* api.rest({- host: input.host,- operation: "getPullRequestDiffFileContents",- path:- input.commit === undefined- ? `repos/${owner}/${name}/pulls/${input.number}`- : `repos/${owner}/${name}/commits/${input.commit}`,- timeout: DIFF_TIMEOUT,+ Effect.fn("GitHubPullRequestApi.getPullRequestDiffFileContents")(function* (input) {+ if (input.commit !== undefined && !isCommitSha(input.commit)) {+ return yield* new GitHubDiffCommitError({ cwd: input.cwd });+ }+ const { owner, name } = parseRepositorySelector(input.repository);+ const refsResponse = yield* api.rest({+ host: input.host,+ operation: "getPullRequestDiffFileContents",+ path:+ input.commit === undefined+ ? `repos/${owner}/${name}/pulls/${input.number}`+ : `repos/${owner}/${name}/commits/${input.commit}`,+ timeout: DIFF_TIMEOUT,+ });+ const refs = decodeRevisionRefs(refsResponse.body);+ const baseRef = Option.isSome(refs)+ ? input.commit === undefined+ ? refs.value.base?.sha+ : (refs.value.parents?.[0]?.sha ?? "")+ : undefined;+ const headRef = Option.isSome(refs)+ ? input.commit === undefined+ ? refs.value.head?.sha+ : refs.value.sha+ : undefined;+ const rootCommitNewFile =+ input.commit !== undefined && input.changeType === "new" && baseRef === "";+ if (+ headRef === undefined ||+ (!rootCommitNewFile && (baseRef === undefined || !isCommitSha(baseRef))) ||+ !isCommitSha(headRef)+ ) {+ return yield* new GitHubDiffRevisionsUnavailableError({+ cwd: input.cwd,+ number: input.number,+ ...(input.commit === undefined ? {} : { commit: input.commit }),});- const refs = decodeRevisionRefs(refsResponse.body);- const baseRef = Option.isSome(refs)- ? input.commit === undefined- ? refs.value.base?.sha- : (refs.value.parents?.[0]?.sha ?? "")- : undefined;- const headRef = Option.isSome(refs)- ? input.commit === undefined- ? refs.value.head?.sha- : refs.value.sha- : undefined;- const rootCommitNewFile =- input.commit !== undefined && input.changeType === "new" && baseRef === "";- if (- headRef === undefined ||- (!rootCommitNewFile && (baseRef === undefined || !isCommitSha(baseRef))) ||- !isCommitSha(headRef)- ) {- return yield* new GitHubDiffRevisionsUnavailableError({- cwd: input.cwd,- number: input.number,- ...(input.commit === undefined ? {} : { commit: input.commit }),- });- }+ }- const readFile = (revision: string, filePath: string) =>- api- .rest({- host: input.host,- operation: "getPullRequestDiffFileContents",- accept: "application/vnd.github.raw+json",- path: `repos/${owner}/${name}/contents/${filePath- .split("/")- .map(encodeURIComponent)- .join("/")}?ref=${encodeURIComponent(revision)}`,- maxResponseBytes: DIFF_FILE_MAX_OUTPUT_BYTES,- timeout: DIFF_TIMEOUT,- })- .pipe(- Effect.flatMap((response) =>- response.truncated || response.body.includes("\0") || response.invalidUtf8- ? Effect.fail(- new GitHubDiffFileContentsUnavailableError({- cwd: input.cwd,- path: filePath,- reason: response.truncated ? "oversized" : "binary",- }),- )- : Effect.succeed(response.body),- ),- );+ const readFile = (revision: string, filePath: string) =>+ api+ .rest({+ host: input.host,+ operation: "getPullRequestDiffFileContents",+ accept: "application/vnd.github.raw+json",+ path: `repos/${owner}/${name}/contents/${filePath+ .split("/")+ .map(encodeURIComponent)+ .join("/")}?ref=${encodeURIComponent(revision)}`,+ maxResponseBytes: DIFF_FILE_MAX_OUTPUT_BYTES,+ timeout: DIFF_TIMEOUT,+ })+ .pipe(+ Effect.flatMap((response) =>+ response.truncated || response.body.includes("\0") || response.invalidUtf8+ ? Effect.fail(+ new GitHubDiffFileContentsUnavailableError({+ cwd: input.cwd,+ path: filePath,+ reason: response.truncated ? "oversized" : "binary",+ }),+ )+ : Effect.succeed(response.body),+ ),+ );- const [oldContents, newContents] = yield* Effect.all(- [- input.changeType === "new"- ? Effect.succeed("")- : readFile(baseRef ?? "", input.oldPath),- input.changeType === "deleted" ? Effect.succeed("") : readFile(headRef, input.newPath),- ],- { concurrency: 2 },- );- return { oldContents, newContents };- });+ const [oldContents, newContents] = yield* Effect.all(+ [+ input.changeType === "new" ? Effect.succeed("") : readFile(baseRef ?? "", input.oldPath),+ input.changeType === "deleted" ? Effect.succeed("") : readFile(headRef, input.newPath),+ ],+ { concurrency: 2 },+ );+ return { oldContents, newContents };+ });/** `isRequired` is asked for on github.com only: an older Enterprise server may not know it. */const asksRequired = (host: string) => host.toLowerCase() === "github.com";@@ -1294,53 +1290,52 @@ export const make = Effect.gen(function* () {* its first hundred. Each page names the head it read, so a push mid-walk fails rather than* mixing two revisions' checks.*/- const readAllCheckContexts = (+ const readAllCheckContexts = Effect.fn("GitHubPullRequestApi.readAllCheckContexts")(function* (input: Parameters<GitHubPullRequestApi["Service"]["getPullRequestDetail"]>[0],allowReserve: boolean,- ) =>- Effect.gen(function* () {- const { owner, name } = parseRepositorySelector(input.repository);- const target = { ...input, operation: "getPullRequestDetail", allowReserve };- let headSha: string | null = null;- const { pages, truncated } = yield* readPages(- GraphQLClient.pages(client.PullRequestCheckContexts, {- variables: { owner, name, number: input.number, required: asksRequired(input.host) },- connection: (result) => {- const page = toPullRequestCheckContextsPage(result);- if (page === null) return null;- headSha ??= page.headSha;- return {- ...page,- // Past the first page a different head is a push mid-walk.- changed: page.headSha !== headSha,- pageInfo: { hasNextPage: page.nextCursor !== null, endCursor: page.nextCursor },- };- },- }).pipe(- Stream.mapEffect((page) =>- page.changed- ? Effect.fail(- readError(- input.cwd,- "getPullRequestDetail",- new Error("Pull request head changed while reading checks."),- ),- )- : Effect.succeed(page),- ),- ),- {- ...target,- maxPages: CHECK_CONTEXT_PAGES,- hasNextPage: (page) => page.nextCursor !== null,+ ) {+ const { owner, name } = parseRepositorySelector(input.repository);+ const target = { ...input, operation: "getPullRequestDetail", allowReserve };+ let headSha: string | null = null;+ const { pages, truncated } = yield* readPages(+ GraphQLClient.pages(client.PullRequestCheckContexts, {+ variables: { owner, name, number: input.number, required: asksRequired(input.host) },+ connection: (result) => {+ const page = toPullRequestCheckContextsPage(result);+ if (page === null) return null;+ headSha ??= page.headSha;+ return {+ ...page,+ // Past the first page a different head is a push mid-walk.+ changed: page.headSha !== headSha,+ pageInfo: { hasNextPage: page.nextCursor !== null, endCursor: page.nextCursor },+ };},- ).pipe(graphql(target));- return {- headSha: pages[0]?.headSha ?? null,- contexts: pages.flatMap((page) => page.contexts),- truncated,- };- });+ }).pipe(+ Stream.mapEffect((page) =>+ page.changed+ ? Effect.fail(+ readError(+ input.cwd,+ "getPullRequestDetail",+ new Error("Pull request head changed while reading checks."),+ ),+ )+ : Effect.succeed(page),+ ),+ ),+ {+ ...target,+ maxPages: CHECK_CONTEXT_PAGES,+ hasNextPage: (page) => page.nextCursor !== null,+ },+ ).pipe(graphql(target));+ return {+ headSha: pages[0]?.headSha ?? null,+ contexts: pages.flatMap((page) => page.contexts),+ truncated,+ };+ });const getPullRequestDetail: GitHubPullRequestApi["Service"]["getPullRequestDetail"] = (input) => {const { owner, name } = parseRepositorySelector(input.repository);@@ -1390,49 +1385,48 @@ export const make = Effect.gen(function* () {const workflowApprovalReadError = (cwd: string, cause: unknown) =>readError(cwd, "listWorkflowRunsRequiringApproval", cause);- const listHeadsByBranch = (input: {+ const listHeadsByBranch = Effect.fn("GitHubPullRequestApi.listHeadsByBranch")(function* (input: {readonly cwd: string;readonly repository: string;readonly host: string;readonly headBranch: string;- }) =>- Effect.gen(function* () {- const { owner, name } = parseRepositorySelector(input.repository);- const countHeads = (pages: ReadonlyArray<{ readonly heads: ReadonlyArray<unknown> }>) =>- pages.reduce((total, page) => total + page.heads.length, 0);- const target = {- ...input,- operation: "listWorkflowRunsRequiringApproval",- allowReserve: true,- };- const { pages, truncated } = yield* readPages(- GraphQLClient.pages(client.PullRequestHeads, {- variables: { owner, name, head: input.headBranch },- connection: (result) => {- const page = toPullRequestHeads(result);- return {- ...page,- pageInfo: { hasNextPage: page.nextCursor !== null, endCursor: page.nextCursor },- };- },- }),- {- ...target,- hasNextPage: (page) => page.nextCursor !== null,- until: (pages) => countHeads(pages) > workflowApprovalLimit,+ }) {+ const { owner, name } = parseRepositorySelector(input.repository);+ const countHeads = (pages: ReadonlyArray<{ readonly heads: ReadonlyArray<unknown> }>) =>+ pages.reduce((total, page) => total + page.heads.length, 0);+ const target = {+ ...input,+ operation: "listWorkflowRunsRequiringApproval",+ allowReserve: true,+ };+ const { pages, truncated } = yield* readPages(+ GraphQLClient.pages(client.PullRequestHeads, {+ variables: { owner, name, head: input.headBranch },+ connection: (result) => {+ const page = toPullRequestHeads(result);+ return {+ ...page,+ pageInfo: { hasNextPage: page.nextCursor !== null, endCursor: page.nextCursor },+ };},- ).pipe(graphql(target));- return { heads: pages.flatMap((page) => page.heads), truncated };- });+ }),+ {+ ...target,+ hasNextPage: (page) => page.nextCursor !== null,+ until: (pages) => countHeads(pages) > workflowApprovalLimit,+ },+ ).pipe(graphql(target));+ return { heads: pages.flatMap((page) => page.heads), truncated };+ });- const listActionRequiredRuns = (input: {- readonly cwd: string;- readonly repository: string;- readonly host: string;- readonly headSha: string;- readonly headBranch: string;- }) =>- Effect.gen(function* () {+ const listActionRequiredRuns = Effect.fn("GitHubPullRequestApi.listActionRequiredRuns")(+ function* (input: {+ readonly cwd: string;+ readonly repository: string;+ readonly host: string;+ readonly headSha: string;+ readonly headBranch: string;+ }) {const known = yield* KnownWorkflowRuns;if (known !== null && known.headSha === input.headSha) {return known.runs.flatMap((run) =>@@ -1464,7 +1458,8 @@ export const make = Effect.gen(function* () {if (read.rawCount < 100) break;}return runs;- });+ },+ );const listWorkflowRunsRequiringApproval: GitHubPullRequestApi["Service"]["listWorkflowRunsRequiringApproval"] =(input) =>@@ -1590,8 +1585,10 @@ export const make = Effect.gen(function* () {RequestResolver.setDelay(SUMMARY_BATCH_WINDOW),RequestResolver.batchN(STAT_ALIASES_PER_REQUEST),);- const getPullRequestSummary: GitHubPullRequestApi["Service"]["getPullRequestSummary"] = (input) =>- Effect.gen(function* () {+ const getPullRequestSummary: GitHubPullRequestApi["Service"]["getPullRequestSummary"] = Effect.fn(+ "GitHubPullRequestApi.getPullRequestSummary",+ )(+ function* (input) {const lookup = pullRequestLookup(input);if (lookup === null) {return yield* new GitHubRepositorySelectorError({@@ -1611,7 +1608,12 @@ export const make = Effect.gen(function* () {});}return toPullRequestSummary(pullRequest);- }).pipe((effect) => batchedRead({ ...input, operation: "getPullRequestSummary" }, effect));+ },+ (effect, input) =>+ effect.pipe((effect) =>+ batchedRead({ ...input, operation: "getPullRequestSummary" }, effect),+ ),+ );// Every watched pull request on a host in one read per pass. A pull request the batch has no// 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* () {* Pages of up to a hundred until `rows` have arrived or GitHub has no more. Each page asks* for only the rows still missing, so the last one does not overshoot.*/- const collect = (+ const collect = Effect.fn("GitHubPullRequestApi.collect")(function* (rows: number,page: (after: string | null,rows: number,) => Effect.Effect<GitHubPullRequestListPage, GitHubPullRequestApiError>,- ) =>- Effect.gen(function* () {- const countRows = (pages: ReadonlyArray<GitHubPullRequestListPage>) =>- pages.reduce((total, read) => total + read.rawCount, 0);- const pages: GitHubPullRequestListPage[] = [];- const seen = new Set<string>();- let after: string | null = null;- let truncated = false;- while (true) {- const read: GitHubPullRequestListPage = yield* page(after, rows - countRows(pages));- pages.push(read);- const next = read.endCursor;- if (next === null) break;- // `truncated` also covers a cursor GitHub repeated before `rows` arrived.- if (seen.has(next) || countRows(pages) >= rows) {- truncated = true;- break;- }- seen.add(next);- after = next;+ ) {+ const countRows = (pages: ReadonlyArray<GitHubPullRequestListPage>) =>+ pages.reduce((total, read) => total + read.rawCount, 0);+ const pages: GitHubPullRequestListPage[] = [];+ const seen = new Set<string>();+ let after: string | null = null;+ let truncated = false;+ while (true) {+ const read: GitHubPullRequestListPage = yield* page(after, rows - countRows(pages));+ pages.push(read);+ const next = read.endCursor;+ if (next === null) break;+ // `truncated` also covers a cursor GitHub repeated before `rows` arrived.+ if (seen.has(next) || countRows(pages) >= rows) {+ truncated = true;+ break;}- return {- items: pages.flatMap((read) => read.items),- rawCount: countRows(pages),- truncated,- };- });+ seen.add(next);+ after = next;+ }+ return {+ items: pages.flatMap((read) => read.items),+ rawCount: countRows(pages),+ truncated,+ };+ });const stacks = input.host.toLowerCase() === "github.com";const read = (continues: boolean,@@ -1859,8 +1860,8 @@ export const make = Effect.gen(function* () {);},- listPullRequestStats: (input) =>- Effect.gen(function* () {+ listPullRequestStats: Effect.fn("GitHubPullRequestApi.listPullRequestStats")(+ function* (input) {const lookups = input.changeRequests.map((changeRequest) => ({changeRequest,lookup: pullRequestLookup(changeRequest),@@ -1888,7 +1889,12 @@ export const make = Effect.gen(function* () {{ concurrency: "unbounded" },);return stats.flat();- }).pipe((effect) => batchedRead({ ...input, operation: "listPullRequestStats" }, effect)),+ },+ (effect, input) =>+ effect.pipe((effect) =>+ batchedRead({ ...input, operation: "listPullRequestStats" }, effect),+ ),+ ),getPullRequestSummary,getPullRequestWatchFingerprint,@@ -1935,8 +1941,8 @@ export const make = Effect.gen(function* () {);},- getPullRequestActivity: (input) =>- Effect.gen(function* () {+ getPullRequestActivity: Effect.fn("GitHubPullRequestApi.getPullRequestActivity")(+ function* (input) {const { owner, name } = parseRepositorySelector(input.repository);let author: PullRequestActor | null = null;let commits: ReadonlyArray<PullRequestCommit> = [];@@ -1981,7 +1987,8 @@ export const make = Effect.gen(function* () {),commits,} satisfies GitHubPullRequestActivity;- }),+ },+ ),getPullRequestDiff: (input) => {const filesPage = (page: number) =>@@ -2057,8 +2064,8 @@ export const make = Effect.gen(function* () {);},- listReviewThreadComments: (input) =>- Effect.gen(function* () {+ listReviewThreadComments: Effect.fn("GitHubPullRequestApi.listReviewThreadComments")(+ function* (input) {const { owner, name } = parseRepositorySelector(input.repository);const target = { ...input, operation: "listReviewThreadComments" };const threadPage = (@@ -2157,7 +2164,8 @@ export const make = Effect.gen(function* () {commits,viewer,};- }),+ },+ ),listActorAvatars: (input) => {if (input.ids.length === 0) {diff --git a/packages/source-control-github/src/server/GitHubRequestPolicy.ts b/packages/source-control-github/src/server/GitHubRequestPolicy.tsindex 831ba010b9c..a34467aaa4b 100644--- a/packages/source-control-github/src/server/GitHubRequestPolicy.ts+++ b/packages/source-control-github/src/server/GitHubRequestPolicy.ts@@ -260,96 +260,92 @@ export const make = Effect.gen(function* () {return { token: held.token, fingerprint: held.fingerprint };});- const request: GitHubRequestPolicy["Service"]["request"] = <A, E, R>(+ // The REST/GraphQL transport span owns request and quota metadata.+ const request: GitHubRequestPolicy["Service"]["request"] = Effect.fnUntraced(function* <A, E, R>(input: GitHubRequest,send: (headers: Readonly<Record<string, string>>) => Effect.Effect<GitHubAnswer<A>, E, R>,- ) =>- Effect.gen(function* () {- const host = normalizeHost(input.host);- const context = { host, operation: input.operation };+ ) {+ const host = normalizeHost(input.host);+ const context = { host, operation: input.operation };+ yield* Effect.annotateCurrentSpan({+ "github.host": host,+ "github.operation": input.operation,+ });+ const { token, fingerprint } = yield* credential(host);+ const scope = yield* SourceControlRateLimit.CredentialScope;+ // A refusal pauses the whole host, whichever quota it spent: the key PullRequestService+ // records its own backoff under.+ const key = { provider: SourceControlProviderKind.make("github"), host };++ // Settlement annotates the request span with status and rate-limit attributes.+ const settle = Effect.fnUntraced(function* (lease: number, answer: GitHubAnswer<A>) {+ yield* quota.observe(host, answer.headers);yield* Effect.annotateCurrentSpan({- "github.host": host,- "github.operation": input.operation,+ ...(answer.status === undefined ? {} : { "http.response.status_code": answer.status }),+ ...rateLimitAttributes(answer.headers),});- const { token, fingerprint } = yield* credential(host);- const scope = yield* SourceControlRateLimit.CredentialScope;- // A refusal pauses the whole host, whichever quota it spent: the key PullRequestService- // records its own backoff under.- const key = { provider: SourceControlProviderKind.make("github"), host };-- const settle = (lease: number, answer: GitHubAnswer<A>) =>- Effect.gen(function* () {- yield* quota.observe(host, answer.headers);+ switch (answer._tag) {+ case "Ok":+ yield* limits.recordSuccess({ ...key, lease });+ return answer.value;+ case "RateLimited": {+ const retryAt = retryAtFrom(answer.headers, yield* Clock.currentTimeMillis);+ yield* limits.recordRateLimit({ ...key, lease, retryAt });yield* Effect.annotateCurrentSpan({- ...(answer.status === undefined ? {} : { "http.response.status_code": answer.status }),- ...rateLimitAttributes(answer.headers),+ "github.rate_limited": true,+ ...(retryAt === undefined ? {} : { "github.retry_at": retryAt }),});- switch (answer._tag) {- case "Ok":- yield* limits.recordSuccess({ ...key, lease });- return answer.value;- case "RateLimited": {- const retryAt = retryAtFrom(answer.headers, yield* Clock.currentTimeMillis);- yield* limits.recordRateLimit({ ...key, lease, retryAt });- yield* Effect.annotateCurrentSpan({- "github.rate_limited": true,- ...(retryAt === undefined ? {} : { "github.retry_at": retryAt }),- });- return yield* new GitHubApiRateLimitError({- ...context,- ...(retryAt === undefined ? {} : { retryAt }),- });- }- case "Unauthorized":- // The source may hold a newer token than the one that was refused.- yield* credentials.invalidate(host);- return yield* new GitHubApiAuthenticationError(context);- case "NotFound":- return yield* new GitHubApiNotFoundError(context);- case "Failed":- return yield* new GitHubApiResponseError({- ...context,- status: answer.status ?? 200,- ...(answer.messages === undefined ? {} : { githubErrors: answer.messages }),- });- }- });+ return yield* new GitHubApiRateLimitError({+ ...context,+ ...(retryAt === undefined ? {} : { retryAt }),+ });+ }+ case "Unauthorized":+ // The source may hold a newer token than the one that was refused.+ yield* credentials.invalidate(host);+ return yield* new GitHubApiAuthenticationError(context);+ case "NotFound":+ return yield* new GitHubApiNotFoundError(context);+ case "Failed":+ return yield* new GitHubApiResponseError({+ ...context,+ status: answer.status ?? 200,+ ...(answer.messages === undefined ? {} : { githubErrors: answer.messages }),+ });+ }+ });- const run = Effect.gen(function* () {- const lease = yield* quota- .admit(host, input.resource, { allowReserve: input.allowReserve })- .pipe(- Effect.andThen(- limits.check(key, input.allowReserve ? { allowPaused: true } : undefined),- ),- Effect.tapError((paused) =>- Effect.annotateCurrentSpan({- "github.paused": true,- "github.retry_at": paused.retryAt,- }),- ),- );- // One deadline covers the headers and the body: a host that answers headers and then- // stalls must not hold a shared slot for undici's own five-minute body timeout.- const answer = yield* send({- ...REQUEST_HEADERS,- authorization: `Bearer ${Redacted.value(token)}`,- }).pipe(- Effect.timeoutOrElse({- duration: input.timeout ?? DEFAULT_TIMEOUT,- orElse: () =>- Effect.fail(- new GitHubApiRequestError({ ...context, cause: new Cause.TimeoutError() }),- ),- }),+ const run = Effect.gen(function* () {+ const lease = yield* quota+ .admit(host, input.resource, { allowReserve: input.allowReserve })+ .pipe(+ Effect.andThen(limits.check(key, input.allowReserve ? { allowPaused: true } : undefined)),+ Effect.tapError((paused) =>+ Effect.annotateCurrentSpan({+ "github.paused": true,+ "github.retry_at": paused.retryAt,+ }),+ ),);- return yield* settle(lease, answer);- });- // The rate-limit scope follows the credential, so a pause on one account never blocks another.- return yield* slots- .withPermit(run)- .pipe(Effect.provideService(SourceControlRateLimit.CredentialScope, scope || fingerprint));+ // One deadline covers the headers and the body: a host that answers headers and then+ // stalls must not hold a shared slot for undici's own five-minute body timeout.+ const answer = yield* send({+ ...REQUEST_HEADERS,+ authorization: `Bearer ${Redacted.value(token)}`,+ }).pipe(+ Effect.timeoutOrElse({+ duration: input.timeout ?? DEFAULT_TIMEOUT,+ orElse: () =>+ Effect.fail(new GitHubApiRequestError({ ...context, cause: new Cause.TimeoutError() })),+ }),+ );+ return yield* settle(lease, answer);});+ // The rate-limit scope follows the credential, so a pause on one account never blocks another.+ return yield* slots+ .withPermit(run)+ .pipe(Effect.provideService(SourceControlRateLimit.CredentialScope, scope || fingerprint));+ });return GitHubRequestPolicy.of({ request, credential });});diff --git a/packages/source-control-github/src/server/GitHubSourceControlProvider.ts b/packages/source-control-github/src/server/GitHubSourceControlProvider.tsindex 8c8aa06cd9a..b4c2b5107fe 100644--- a/packages/source-control-github/src/server/GitHubSourceControlProvider.ts+++ b/packages/source-control-github/src/server/GitHubSourceControlProvider.ts@@ -927,8 +927,8 @@ export const make = Effect.gen(function* () {providerError("getChangeRequest", input.cwd, { reference: input.reference }),),),- createChangeRequest: (input) =>- Effect.gen(function* () {+ createChangeRequest: Effect.fn("GitHubSourceControlProvider.createChangeRequest")(+ function* (input) {const locator = yield* resolveRepository(input);const body = yield* fileSystem.readFileString(input.bodyFile)@@ -953,13 +953,16 @@ export const make = Effect.gen(function* () {maintainer_can_modify: true,},});- }).pipe(- Effect.mapError(- providerError("createChangeRequest", input.cwd, { reference: input.headSelector }),+ },+ (effect, input) =>+ effect.pipe(+ Effect.mapError(+ providerError("createChangeRequest", input.cwd, { reference: input.headSelector }),+ ),),- ),- getRepositoryCloneUrls: (input) =>- Effect.gen(function* () {+ ),+ getRepositoryCloneUrls: Effect.fn("GitHubSourceControlProvider.getRepositoryCloneUrls")(+ function* (input) {const fallbackHost = (yield* resolveRepository(input).pipe(Effect.map((locator) => locator.host),Effect.orElseSucceed(() => environment.GH_HOST ?? "github.com"),@@ -972,13 +975,16 @@ export const make = Effect.gen(function* () {: null);if (locator === null) return yield* failure("Repositories are named owner/name.");return repositoryCloneUrls(yield* readRepository(locator));- }).pipe(- Effect.mapError(- providerError("getRepositoryCloneUrls", input.cwd, { repository: input.repository }),+ },+ (effect, input) =>+ effect.pipe(+ Effect.mapError(+ providerError("getRepositoryCloneUrls", input.cwd, { repository: input.repository }),+ ),),- ),- createRepository: (input) =>- Effect.gen(function* () {+ ),+ createRepository: Effect.fn("GitHubSourceControlProvider.createRepository")(+ function* (input) {const locator = parseGitHubRepositorySelector(input.repository,(environment.GH_HOST ?? "github.com").toLowerCase(),@@ -1006,13 +1012,16 @@ export const make = Effect.gen(function* () {return yield* failure("GitHub returned an invalid repository.", decoded.failure);}return repositoryCloneUrls(decoded.success);- }).pipe(- Effect.mapError(- providerError("createRepository", input.cwd, { repository: input.repository }),+ },+ (effect, input) =>+ effect.pipe(+ Effect.mapError(+ providerError("createRepository", input.cwd, { repository: input.repository }),+ ),),- ),- getDefaultBranch: (input) =>- Effect.gen(function* () {+ ),+ getDefaultBranch: Effect.fn("GitHubSourceControlProvider.getDefaultBranch")(+ function* (input) {const locator = yield* resolveRepository({cwd: input.cwd,host: contextHost(input.context),@@ -1021,7 +1030,9 @@ export const make = Effect.gen(function* () {const repository = yield* readRepository(locator);const branch = repository.default_branch?.trim() ?? "";return branch.length > 0 ? branch : null;- }).pipe(Effect.mapError(providerError("getDefaultBranch", input.cwd))),+ },+ (effect, input) => effect.pipe(Effect.mapError(providerError("getDefaultBranch", input.cwd))),+ ),checkoutChangeRequest: (input) =>checkoutPullRequest(input).pipe(Effect.mapError(diff --git a/packages/source-control-github/src/server/gitHubChangeRequestTemplate.ts b/packages/source-control-github/src/server/gitHubChangeRequestTemplate.tsindex 284f3860582..5b81c198da5 100644--- a/packages/source-control-github/src/server/gitHubChangeRequestTemplate.ts+++ b/packages/source-control-github/src/server/gitHubChangeRequestTemplate.ts@@ -92,13 +92,13 @@ type DirectoryTemplateResult =| { readonly _tag: "Ambiguous" }| { readonly _tag: "Template"; readonly template: string };-function readTemplateDirectory(input: {- readonly cwd: string;- readonly executeGit: ExecuteGit;- readonly entries: ReadonlyArray<TemplateTreeEntry>;- readonly directory: string;-}): Effect.Effect<DirectoryTemplateResult, GitCommandError> {- return Effect.gen(function* () {+const readTemplateDirectory = Effect.fn("gitHubChangeRequestTemplate.readTemplateDirectory")(+ function* (input: {+ readonly cwd: string;+ readonly executeGit: ExecuteGit;+ readonly entries: ReadonlyArray<TemplateTreeEntry>;+ readonly directory: string;+ }): Effect.fn.Return<DirectoryTemplateResult, GitCommandError> {const prefix = `${input.directory}/`;const candidates = input.entries.filter((entry) => {if (!entry.path.startsWith(prefix)) {@@ -122,8 +122,8 @@ function readTemplateDirectory(input: {return templates[0]? ({ _tag: "Template", template: templates[0] } as const): ({ _tag: "None" } as const);- });-}+ },+);export const detect = Effect.fn("gitHubChangeRequestTemplate.detect")(function* (cwd: string,diff --git a/packages/source-control-github/src/server/gitHubConditionalChecks.ts b/packages/source-control-github/src/server/gitHubConditionalChecks.tsindex ebef5ba5f7b..46b4feea696 100644--- a/packages/source-control-github/src/server/gitHubConditionalChecks.ts+++ b/packages/source-control-github/src/server/gitHubConditionalChecks.ts@@ -85,54 +85,56 @@ export const makeChecksRevalidator = Effect.gen(function* () {operation: "revalidateChecks",status,});- const get = (endpoint: string, head = false) =>- Effect.gen(function* () {- const previous = entry.validators.get(endpoint);- const response = yield* api- .rest({- host: input.host,- operation: "revalidateChecks",- path: endpoint,- ...(previous?.etag ? { ifNoneMatch: previous.etag } : {}),- })- .pipe(- Effect.catchTags({- GitHubApiNotFoundError: () =>- Effect.sync(() => {- entry.supported = false;- return null;- }),- GitHubApiResponseError: (error) =>- Effect.sync(() => {- entry.supported = !UNSUPPORTED_STATUSES.has(error.status);- return null;- }),- }),- );- if (response === null) {- entry.value = null;- return null;- }- if (response.status === 304 && previous) return previous.next;- if (response.status !== 200 || response.truncated) {- return yield* fail(response.status);- }+ const get = Effect.fn("gitHubConditionalChecks.get")(function* (+ endpoint: string,+ head = false,+ ) {+ const previous = entry.validators.get(endpoint);+ const response = yield* api+ .rest({+ host: input.host,+ operation: "revalidateChecks",+ path: endpoint,+ ...(previous?.etag ? { ifNoneMatch: previous.etag } : {}),+ })+ .pipe(+ Effect.catchTags({+ GitHubApiNotFoundError: () =>+ Effect.sync(() => {+ entry.supported = false;+ return null;+ }),+ GitHubApiResponseError: (error) =>+ Effect.sync(() => {+ entry.supported = !UNSUPPORTED_STATUSES.has(error.status);+ return null;+ }),+ }),+ );+ if (response === null) {entry.value = null;- if (head) {- const decoded = yield* decodeHead(response.body).pipe(- Effect.mapError(() => fail(response.status)),- );- if (entry.head?.head.sha !== decoded.head.sha) entry.validators.clear();- entry.head = decoded;- }- const validator = {- etag: response.headers["etag"]?.trim(),- next: /rel="next"/.test(response.headers["link"] ?? ""),- body: response.body,- };- entry.validators.set(endpoint, validator);- return validator.next;- });+ return null;+ }+ if (response.status === 304 && previous) return previous.next;+ if (response.status !== 200 || response.truncated) {+ return yield* fail(response.status);+ }+ entry.value = null;+ if (head) {+ const decoded = yield* decodeHead(response.body).pipe(+ Effect.mapError(() => fail(response.status)),+ );+ if (entry.head?.head.sha !== decoded.head.sha) entry.validators.clear();+ entry.head = decoded;+ }+ const validator = {+ etag: response.headers["etag"]?.trim(),+ next: /rel="next"/.test(response.headers["link"] ?? ""),+ body: response.body,+ };+ entry.validators.set(endpoint, validator);+ return validator.next;+ });const root = `repos/${input.repository}`;if ((yield* get(`${root}/pulls/${input.number}`, true)) === null) return yield* read;const head = entry.head;diff --git a/packages/source-control-github/src/server/gitHubGraphQlClient.ts b/packages/source-control-github/src/server/gitHubGraphQlClient.tsindex f1f6ee8944e..427369ea510 100644--- a/packages/source-control-github/src/server/gitHubGraphQlClient.ts+++ b/packages/source-control-github/src/server/gitHubGraphQlClient.ts@@ -64,41 +64,40 @@ export class GitHubGraphQlAuth extends GraphQLMiddleware.Service<Effect.gen(function* () {const policy = yield* GitHubRequestPolicy.GitHubRequestPolicy;return GitHubGraphQlAuth.of({- execute: ({ request, next }) =>- Effect.gen(function* () {- const target = yield* GitHubGraphQlTarget;- const host = GitHubRequestPolicy.normalizeHost(target.host);- yield* Effect.annotateCurrentSpan({- "github.kind": "graphql",- "github.graphql.query_hash": queryHash(request.query),- });- return yield* policy.request(- {- host,- operation: target.operation,- resource: "graphql",- allowReserve: target.allowReserve ?? (yield* SourceControlRateLimit.Interactive),- },- (headers) =>- next({ ...request, headers: Headers.setAll(request.headers, headers) }).pipe(- Effect.map((answer) => {- const status = answer.status;- const responseHeaders = answer.headers ?? Headers.empty;- const rateLimited = GitHubRequestPolicy.isRateLimited({- status: status ?? 200,- headers: responseHeaders,- ...(answer.errors === undefined ? {} : { graphqlErrors: answer.errors }),- });- return rateLimited- ? { _tag: "RateLimited" as const, status, headers: responseHeaders }- : { _tag: "Ok" as const, value: answer, status, headers: responseHeaders };- }),- Effect.catchIf(GraphQLClientError.isGraphQLClientError, (error) =>- refused(error, { host, operation: target.operation }),- ),+ execute: Effect.fn("GitHubGraphQlAuth.execute")(function* ({ request, next }) {+ const target = yield* GitHubGraphQlTarget;+ const host = GitHubRequestPolicy.normalizeHost(target.host);+ yield* Effect.annotateCurrentSpan({+ "github.kind": "graphql",+ "github.graphql.query_hash": queryHash(request.query),+ });+ return yield* policy.request(+ {+ host,+ operation: target.operation,+ resource: "graphql",+ allowReserve: target.allowReserve ?? (yield* SourceControlRateLimit.Interactive),+ },+ (headers) =>+ next({ ...request, headers: Headers.setAll(request.headers, headers) }).pipe(+ Effect.map((answer) => {+ const status = answer.status;+ const responseHeaders = answer.headers ?? Headers.empty;+ const rateLimited = GitHubRequestPolicy.isRateLimited({+ status: status ?? 200,+ headers: responseHeaders,+ ...(answer.errors === undefined ? {} : { graphqlErrors: answer.errors }),+ });+ return rateLimited+ ? { _tag: "RateLimited" as const, status, headers: responseHeaders }+ : { _tag: "Ok" as const, value: answer, status, headers: responseHeaders };+ }),+ Effect.catchIf(GraphQLClientError.isGraphQLClientError, (error) =>+ refused(error, { host, operation: target.operation }),),- );- }).pipe(Effect.withSpan("GitHubGraphQlAuth.execute")),+ ),+ );+ }),subscribe: () => Stream.die(new Error("GitHub GraphQL has no subscriptions.")),});}),@@ -110,80 +109,78 @@ export class GitHubGraphQlAuth extends GraphQLMiddleware.Service<* failure that never reached GitHub is a request error; one that is not about the transport* (an answer that does not decode) is the client's own.*/-const refused = (+const refused = Effect.fn("gitHubGraphQlClient.refused")(function* (error: GraphQLClientError.GraphQLClientError,context: { readonly host: string; readonly operation: string },-) =>- Effect.gen(function* () {- const reason = error.reason;- if (reason._tag !== "TransportError" && reason._tag !== "ResponseError") {- return yield* Effect.fail(error);- }- const status = reason.status;- if (reason._tag === "TransportError" && status === undefined) {- return yield* new GitHubRequestPolicy.GitHubApiRequestError({ ...context, cause: error });- }- const headers = reason.headers ?? Headers.empty;- // A secondary limit is a 403 that only its body names, which the transport read.- const body =- reason._tag === "TransportError" &&- HttpClientError.isHttpClientError(reason.cause) &&- reason.cause.response !== undefined- ? yield* reason.cause.response.text.pipe(Effect.orElseSucceed(() => ""))- : "";- const tag = GitHubRequestPolicy.isRateLimited({- status: status ?? 200,- headers,- body,- ...(reason._tag === "ResponseError" ? { graphqlErrors: reason.errors } : {}),- })- ? "RateLimited"- : status === 401- ? "Unauthorized"- : status === 404- ? "NotFound"- : "Failed";- return { _tag: tag, status: status ?? 200, headers } as const;- });+) {+ const reason = error.reason;+ if (reason._tag !== "TransportError" && reason._tag !== "ResponseError") {+ return yield* Effect.fail(error);+ }+ const status = reason.status;+ if (reason._tag === "TransportError" && status === undefined) {+ return yield* new GitHubRequestPolicy.GitHubApiRequestError({ ...context, cause: error });+ }+ const headers = reason.headers ?? Headers.empty;+ // A secondary limit is a 403 that only its body names, which the transport read.+ const body =+ reason._tag === "TransportError" &&+ HttpClientError.isHttpClientError(reason.cause) &&+ reason.cause.response !== undefined+ ? yield* reason.cause.response.text.pipe(Effect.orElseSucceed(() => ""))+ : "";+ const tag = GitHubRequestPolicy.isRateLimited({+ status: status ?? 200,+ headers,+ body,+ ...(reason._tag === "ResponseError" ? { graphqlErrors: reason.errors } : {}),+ })+ ? "RateLimited"+ : status === 401+ ? "Unauthorized"+ : status === 404+ ? "NotFound"+ : "Failed";+ return { _tag: tag, status: status ?? 200, headers } as const;+});/*** Reads each answer whole, up to the call's byte cap, before the protocol parses it. A body cut* at the cap hides any `errors` past the cut and cannot be decoded, so it fails, which the* middleware reports as a `GitHubApiResponseError` with the answer's status.*/-const capResponse = (+const capResponse = Effect.fn("gitHubGraphQlClient.capResponse")(function* (effect: Effect.Effect<HttpClientResponse.HttpClientResponse, HttpClientError.HttpClientError>,-) =>- Effect.gen(function* () {- const response = yield* effect;- const target = yield* Effect.serviceOption(GitHubGraphQlTarget);- const maxBytes = Option.match(target, {- onNone: () => DEFAULT_MAX_RESPONSE_BYTES,- onSome: (target) => target.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES,- });- const collected = yield* collectUint8StreamText({ stream: response.stream, maxBytes }).pipe(- Effect.catchIf(- (error) => error.reason._tag === "EmptyBodyError",- () => Effect.succeed({ text: "", truncated: false }),- ),- );- if (collected.truncated) {- return yield* new HttpClientError.HttpClientError({- reason: new HttpClientError.DecodeError({- request: response.request,- response,- description: `The answer is longer than ${maxBytes} bytes.`,- }),- });- }- return HttpClientResponse.fromWeb(- response.request,- new Response(collected.text === "" ? null : collected.text, {- status: response.status,- headers: response.headers,- }),- );+) {+ const response = yield* effect;+ const target = yield* Effect.serviceOption(GitHubGraphQlTarget);+ const maxBytes = Option.match(target, {+ onNone: () => DEFAULT_MAX_RESPONSE_BYTES,+ onSome: (target) => target.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES,});+ const collected = yield* collectUint8StreamText({ stream: response.stream, maxBytes }).pipe(+ Effect.catchIf(+ (error) => error.reason._tag === "EmptyBodyError",+ () => Effect.succeed({ text: "", truncated: false }),+ ),+ );+ if (collected.truncated) {+ return yield* new HttpClientError.HttpClientError({+ reason: new HttpClientError.DecodeError({+ request: response.request,+ response,+ description: `The answer is longer than ${maxBytes} bytes.`,+ }),+ });+ }+ return HttpClientResponse.fromWeb(+ response.request,+ new Response(collected.text === "" ? null : collected.text, {+ status: response.status,+ headers: response.headers,+ }),+ );+});/*** The HTTP transport, sending each request to its target host's endpoint. Resolvers batch by thisdiff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.tsindex 2a2418c6bf4..a49d175edac 100644--- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts@@ -1080,40 +1080,39 @@ export const make = Effect.gen(function* () {getFileRevisions: fileRevisions,- setReaction: (input) =>- Effect.gen(function* () {- const subject = awardSubjectPath(input);- if (input.reacted) {- yield* api({- cwd: input.cwd,- path: `${subject}?${query([["name", gitLabAwardName(input.content)]])}`,- method: "POST",- });- return;- }- // GitLab deletes an award by its id and takes no emoji name there, so the reader's own- // award of that name is looked up first.- const viewer = yield* viewerUsername({ cwd: input.cwd });- const listed = yield* api({ cwd: input.cwd, path: subject });- const own = decodeOwnAwardIdJson(listed.stdout.trim(), {- content: input.content,- viewer,- });- if (!Result.isSuccess(own)) {- return yield* new GitLabMergeRequestReadError({- command: "glab",- cwd: input.cwd,- operation: "setReaction",- cause: own.failure,- });- }- if (own.success === null) return;+ setReaction: Effect.fn("GitLabPullRequestCli.setReaction")(function* (input) {+ const subject = awardSubjectPath(input);+ if (input.reacted) {yield* api({cwd: input.cwd,- path: `${subject}/${own.success}`,- method: "DELETE",+ path: `${subject}?${query([["name", gitLabAwardName(input.content)]])}`,+ method: "POST",});- }),+ return;+ }+ // GitLab deletes an award by its id and takes no emoji name there, so the reader's own+ // award of that name is looked up first.+ const viewer = yield* viewerUsername({ cwd: input.cwd });+ const listed = yield* api({ cwd: input.cwd, path: subject });+ const own = decodeOwnAwardIdJson(listed.stdout.trim(), {+ content: input.content,+ viewer,+ });+ if (!Result.isSuccess(own)) {+ return yield* new GitLabMergeRequestReadError({+ command: "glab",+ cwd: input.cwd,+ operation: "setReaction",+ cause: own.failure,+ });+ }+ if (own.success === null) return;+ yield* api({+ cwd: input.cwd,+ path: `${subject}/${own.success}`,+ method: "DELETE",+ });+ }),listCommits: (input) =>api({@@ -1159,56 +1158,57 @@ export const make = Effect.gen(function* () {: diffPage({ ...target, page });},- getMergeRequestDiffFileContents: (input) =>- Effect.gen(function* () {- if (input.commit !== undefined && !isCommitSha(input.commit)) {- return yield* new GitLabDiffCommitError({ command: "glab", cwd: input.cwd });- }- const refs = yield* input.commit === undefined- ? getDiffRefs(input)- : getCommitDiffRefs({- cwd: input.cwd,- repository: input.repository,- commit: input.commit,- allowRoot: input.changeType === "new",- });-- const readFile = (revision: string, filePath: string) =>- api({+ getMergeRequestDiffFileContents: Effect.fn(+ "GitLabPullRequestCli.getMergeRequestDiffFileContents",+ )(function* (input) {+ if (input.commit !== undefined && !isCommitSha(input.commit)) {+ return yield* new GitLabDiffCommitError({ command: "glab", cwd: input.cwd });+ }+ const refs = yield* input.commit === undefined+ ? getDiffRefs(input)+ : getCommitDiffRefs({cwd: input.cwd,- path: `projects/${projectPath(input.repository)}/repository/files/${encodeURIComponent(- filePath,- )}/raw?ref=${encodeURIComponent(revision)}`,- maxOutputBytes: DIFF_FILE_MAX_OUTPUT_BYTES,- timeoutMs: DIFF_TIMEOUT_MS,- }).pipe(- Effect.flatMap((result) =>- result.stdoutTruncated ||- result.stdout.includes("\0") ||- result.stdoutInvalidUtf8 === true- ? Effect.fail(- new GitLabDiffFileContentsUnavailableError({- command: "glab",- cwd: input.cwd,- path: filePath,- reason: result.stdoutTruncated ? "oversized" : "binary",- }),- )- : Effect.succeed(result.stdout),- ),- );+ repository: input.repository,+ commit: input.commit,+ allowRoot: input.changeType === "new",+ });- const [oldContents, newContents] = yield* Effect.all(- [- input.changeType === "new" ? Effect.succeed("") : readFile(refs.baseSha, input.oldPath),- input.changeType === "deleted"- ? Effect.succeed("")- : readFile(refs.headSha, input.newPath),- ],- { concurrency: 2 },+ const readFile = (revision: string, filePath: string) =>+ api({+ cwd: input.cwd,+ path: `projects/${projectPath(input.repository)}/repository/files/${encodeURIComponent(+ filePath,+ )}/raw?ref=${encodeURIComponent(revision)}`,+ maxOutputBytes: DIFF_FILE_MAX_OUTPUT_BYTES,+ timeoutMs: DIFF_TIMEOUT_MS,+ }).pipe(+ Effect.flatMap((result) =>+ result.stdoutTruncated ||+ result.stdout.includes("\0") ||+ result.stdoutInvalidUtf8 === true+ ? Effect.fail(+ new GitLabDiffFileContentsUnavailableError({+ command: "glab",+ cwd: input.cwd,+ path: filePath,+ reason: result.stdoutTruncated ? "oversized" : "binary",+ }),+ )+ : Effect.succeed(result.stdout),+ ),);- return { oldContents, newContents };- }),++ const [oldContents, newContents] = yield* Effect.all(+ [+ input.changeType === "new" ? Effect.succeed("") : readFile(refs.baseSha, input.oldPath),+ input.changeType === "deleted"+ ? Effect.succeed("")+ : readFile(refs.headSha, input.newPath),+ ],+ { concurrency: 2 },+ );+ return { oldContents, newContents };+ }),getProjectMergeCapabilities: (input) =>api({@@ -1271,8 +1271,8 @@ export const make = Effect.gen(function* () {Effect.asVoid,),- runMergeRequestAction: (input) =>- Effect.gen(function* () {+ runMergeRequestAction: Effect.fn("GitLabPullRequestCli.runMergeRequestAction")(+ function* (input) {// `glab mr merge` arms auto-merge and never disarms it, so the one direction the CLI has// no flag for is asked of GitLab directly through the same `api` passthrough the rest of// this module writes with.@@ -1298,7 +1298,8 @@ export const make = Effect.gen(function* () {flags.push("--sha", refs.headSha);}yield* executeMr(subcommand!, ...flags);- }),+ },+ ),updateMergeRequest: (input) =>api({@@ -1336,55 +1337,54 @@ export const make = Effect.gen(function* () {listDiscussions: (input) => discussionsPage({ ...input, page: 1, collected: [] }),- submitReview: (input) =>- Effect.gen(function* () {- const project = projectPath(input.repository);- const mergeRequest = `projects/${project}/merge_requests/${input.number}`;- // GitLab has no pending review to attach comments to, so a review is replayed as the- // requests it is made of: the line comments, then the summary, then the verdict. A- // failure part-way therefore leaves what was already posted in place, which is why- // the verdict goes last — a half-sent review is never an approval.- if (input.comments.length > 0) {- const refs = yield* getDiffRefs(input);- yield* Effect.forEach(- input.comments,- (comment) =>- api({- cwd: input.cwd,- path: `${mergeRequest}/discussions`,- method: "POST",- stdin: JSON.stringify({- body: comment.body,- position: {- base_sha: refs.baseSha,- head_sha: refs.headSha,- start_sha: refs.startSha,- position_type: "text",- // Both paths are sent because GitLab resolves a position against both- // sides of the diff. They differ only for a renamed file, which is why the- // draft carries the name the file had before the change.- old_path: comment.oldPath ?? comment.path,- new_path: comment.path,- ...gitLabReviewPositionLines(comment.position),- },- }),+ submitReview: Effect.fn("GitLabPullRequestCli.submitReview")(function* (input) {+ const project = projectPath(input.repository);+ const mergeRequest = `projects/${project}/merge_requests/${input.number}`;+ // GitLab has no pending review to attach comments to, so a review is replayed as the+ // requests it is made of: the line comments, then the summary, then the verdict. A+ // failure part-way therefore leaves what was already posted in place, which is why+ // the verdict goes last — a half-sent review is never an approval.+ if (input.comments.length > 0) {+ const refs = yield* getDiffRefs(input);+ yield* Effect.forEach(+ input.comments,+ (comment) =>+ api({+ cwd: input.cwd,+ path: `${mergeRequest}/discussions`,+ method: "POST",+ stdin: JSON.stringify({+ body: comment.body,+ position: {+ base_sha: refs.baseSha,+ head_sha: refs.headSha,+ start_sha: refs.startSha,+ position_type: "text",+ // Both paths are sent because GitLab resolves a position against both+ // sides of the diff. They differ only for a renamed file, which is why the+ // draft carries the name the file had before the change.+ old_path: comment.oldPath ?? comment.path,+ new_path: comment.path,+ ...gitLabReviewPositionLines(comment.position),+ },}),- { discard: true },- );- }- if (input.body.trim().length > 0) {- yield* api({- cwd: input.cwd,- path: `${mergeRequest}/notes`,- method: "POST",- // @effect-diagnostics-next-line preferSchemaOverJson:off- stdin: JSON.stringify({ body: input.body }),- });- }- if (input.verdict === "approve") {- yield* api({ cwd: input.cwd, path: `${mergeRequest}/approve`, method: "POST" });- }- }),+ }),+ { discard: true },+ );+ }+ if (input.body.trim().length > 0) {+ yield* api({+ cwd: input.cwd,+ path: `${mergeRequest}/notes`,+ method: "POST",+ // @effect-diagnostics-next-line preferSchemaOverJson:off+ stdin: JSON.stringify({ body: input.body }),+ });+ }+ if (input.verdict === "approve") {+ yield* api({ cwd: input.cwd, path: `${mergeRequest}/approve`, method: "POST" });+ }+ }),replyToDiscussion: (input) =>api({diff --git a/packages/tailscale/src/tailscale.ts b/packages/tailscale/src/tailscale.tsindex 4da4b8f5b77..4e8606e252a 100644--- a/packages/tailscale/src/tailscale.ts+++ b/packages/tailscale/src/tailscale.ts@@ -210,63 +210,65 @@ export const parseTailscaleStatus = (}),);-const readTailscaleOutput = (subcommand: "status" | "debug", args: readonly string[]) =>- Effect.gen(function* () {- const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;- const hostPlatform = yield* HostProcess.Platform;- const executable = tailscaleCommandForPlatform(hostPlatform);- const commandContext = {- executable,- subcommand,- argumentCount: args.length,- };- return yield* Effect.gen(function* () {- const child = yield* spawner.spawn(ChildProcess.make(executable, [...args])).pipe(- Effect.mapError((cause) => new TailscaleCommandSpawnError({ ...commandContext, cause })),- // Spawning can also fail as a defect rather than a typed error - a- // non-directory entry on PATH makes node throw ENOTDIR synchronously.- // `mapError` never sees that, so it would escape as an uncaught error.- Effect.catchDefect((cause) =>- Effect.fail(new TailscaleCommandSpawnError({ ...commandContext, cause })),- ),- );- const [stdout, stderr, exitCode] = yield* Effect.all(- [- collectStdout(child.stdout),- collectStderr(child.stderr),- child.exitCode.pipe(Effect.map(Number)),- ],- { concurrency: "unbounded" },- ).pipe(- Effect.mapError((cause) => new TailscaleCommandOutputError({ ...commandContext, cause })),- );- if (exitCode !== 0) {- return yield* new TailscaleCommandExitError({- ...commandContext,- exitCode,- stdoutLength: stdout.length,- stderrLength: stderr.length,- ...(stderrDiagnosticOf(stderr) !== undefined- ? { stderrDiagnostic: stderrDiagnosticOf(stderr) }- : {}),- });- }- return stdout;- }).pipe(- Effect.scoped,- Effect.timeout(TAILSCALE_STATUS_TIMEOUT),- Effect.catchTags({- TimeoutError: (cause) =>- Effect.fail(- new TailscaleCommandTimeoutError({- ...commandContext,- timeoutMs: Duration.toMillis(TAILSCALE_STATUS_TIMEOUT),- cause,- }),- ),- }),+const readTailscaleOutput = Effect.fn("tailscale.readTailscaleOutput")(function* (+ subcommand: "status" | "debug",+ args: readonly string[],+) {+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;+ const hostPlatform = yield* HostProcess.Platform;+ const executable = tailscaleCommandForPlatform(hostPlatform);+ const commandContext = {+ executable,+ subcommand,+ argumentCount: args.length,+ };+ return yield* Effect.gen(function* () {+ const child = yield* spawner.spawn(ChildProcess.make(executable, [...args])).pipe(+ Effect.mapError((cause) => new TailscaleCommandSpawnError({ ...commandContext, cause })),+ // Spawning can also fail as a defect rather than a typed error - a+ // non-directory entry on PATH makes node throw ENOTDIR synchronously.+ // `mapError` never sees that, so it would escape as an uncaught error.+ Effect.catchDefect((cause) =>+ Effect.fail(new TailscaleCommandSpawnError({ ...commandContext, cause })),+ ),+ );+ const [stdout, stderr, exitCode] = yield* Effect.all(+ [+ collectStdout(child.stdout),+ collectStderr(child.stderr),+ child.exitCode.pipe(Effect.map(Number)),+ ],+ { concurrency: "unbounded" },+ ).pipe(+ Effect.mapError((cause) => new TailscaleCommandOutputError({ ...commandContext, cause })),);- });+ if (exitCode !== 0) {+ return yield* new TailscaleCommandExitError({+ ...commandContext,+ exitCode,+ stdoutLength: stdout.length,+ stderrLength: stderr.length,+ ...(stderrDiagnosticOf(stderr) !== undefined+ ? { stderrDiagnostic: stderrDiagnosticOf(stderr) }+ : {}),+ });+ }+ return stdout;+ }).pipe(+ Effect.scoped,+ Effect.timeout(TAILSCALE_STATUS_TIMEOUT),+ Effect.catchTags({+ TimeoutError: (cause) =>+ Effect.fail(+ new TailscaleCommandTimeoutError({+ ...commandContext,+ timeoutMs: Duration.toMillis(TAILSCALE_STATUS_TIMEOUT),+ cause,+ }),+ ),+ }),+ );+});export const readTailscaleStatus = readTailscaleOutput("status", ["status", "--json"]).pipe(Effect.flatMap(parseTailscaleStatus),@@ -308,58 +310,57 @@ export function buildTailscaleHttpsBaseUrl(input: {return url.toString();}-const runTailscaleCommand = (+const runTailscaleCommand = Effect.fn("tailscale.runTailscaleCommand")(function* (args: readonly string[],timeoutInput: Duration.Input,-): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> =>- Effect.gen(function* () {- const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;- const hostPlatform = yield* HostProcess.Platform;- const executable = tailscaleCommandForPlatform(hostPlatform);- const commandContext = {- executable,- subcommand: "serve" as const,- argumentCount: args.length,- };- const timeout = Duration.fromInputUnsafe(timeoutInput);- return yield* Effect.gen(function* () {- const child = yield* spawner.spawn(ChildProcess.make(executable, args)).pipe(- Effect.mapError((cause) => new TailscaleCommandSpawnError({ ...commandContext, cause })),- Effect.catchDefect((cause) =>- Effect.fail(new TailscaleCommandSpawnError({ ...commandContext, cause })),- ),- );- const [stderr, exitCode] = yield* Effect.all(- [collectStderr(child.stderr), child.exitCode.pipe(Effect.map(Number))],- { concurrency: "unbounded" },- ).pipe(- Effect.mapError((cause) => new TailscaleCommandOutputError({ ...commandContext, cause })),- );- if (exitCode !== 0) {- return yield* new TailscaleCommandExitError({- ...commandContext,- exitCode,- stderrLength: stderr.length,- ...(stderrDiagnosticOf(stderr) !== undefined- ? { stderrDiagnostic: stderrDiagnosticOf(stderr) }- : {}),- });- }- }).pipe(- Effect.scoped,- Effect.timeout(timeout),- Effect.catchTags({- TimeoutError: (cause) =>- Effect.fail(- new TailscaleCommandTimeoutError({- ...commandContext,- timeoutMs: Duration.toMillis(timeout),- cause,- }),- ),- }),+): Effect.fn.Return<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> {+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;+ const hostPlatform = yield* HostProcess.Platform;+ const executable = tailscaleCommandForPlatform(hostPlatform);+ const commandContext = {+ executable,+ subcommand: "serve" as const,+ argumentCount: args.length,+ };+ const timeout = Duration.fromInputUnsafe(timeoutInput);+ return yield* Effect.gen(function* () {+ const child = yield* spawner.spawn(ChildProcess.make(executable, args)).pipe(+ Effect.mapError((cause) => new TailscaleCommandSpawnError({ ...commandContext, cause })),+ Effect.catchDefect((cause) =>+ Effect.fail(new TailscaleCommandSpawnError({ ...commandContext, cause })),+ ),);- });+ const [stderr, exitCode] = yield* Effect.all(+ [collectStderr(child.stderr), child.exitCode.pipe(Effect.map(Number))],+ { concurrency: "unbounded" },+ ).pipe(+ Effect.mapError((cause) => new TailscaleCommandOutputError({ ...commandContext, cause })),+ );+ if (exitCode !== 0) {+ return yield* new TailscaleCommandExitError({+ ...commandContext,+ exitCode,+ stderrLength: stderr.length,+ ...(stderrDiagnosticOf(stderr) !== undefined+ ? { stderrDiagnostic: stderrDiagnosticOf(stderr) }+ : {}),+ });+ }+ }).pipe(+ Effect.scoped,+ Effect.timeout(timeout),+ Effect.catchTags({+ TimeoutError: (cause) =>+ Effect.fail(+ new TailscaleCommandTimeoutError({+ ...commandContext,+ timeoutMs: Duration.toMillis(timeout),+ cause,+ }),+ ),+ }),+ );+});export const ensureTailscaleServe = (input: {readonly localPort: number;@@ -372,24 +373,20 @@ export const ensureTailscaleServe = (input: {return runTailscaleCommand(args, TAILSCALE_SERVE_TIMEOUT);};-export const disableTailscaleServe = (+export const disableTailscaleServe = Effect.fn("tailscale.disableTailscaleServe")(function* (input: {readonly servePort?: number;} = {},-): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> =>- Effect.gen(function* () {- const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;- return yield* runTailscaleCommand(- ["serve", `--https=${servePort}`, "off"],- TAILSCALE_SERVE_TIMEOUT,- );- });+): Effect.fn.Return<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> {+ const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;+ return yield* runTailscaleCommand(+ ["serve", `--https=${servePort}`, "off"],+ TAILSCALE_SERVE_TIMEOUT,+ );+});-export const probeTailscaleHttpsEndpoint = (input: {- readonly baseUrl: string;- readonly timeout?: Duration.Input;-}): Effect.Effect<boolean, never, HttpClient.HttpClient> =>- Effect.gen(function* () {+export const probeTailscaleHttpsEndpoint = Effect.fn("tailscale.probeTailscaleHttpsEndpoint")(+ function* (input: { readonly baseUrl: string; readonly timeout?: Duration.Input }) {const client = yield* HttpClient.HttpClient;const response = yield* Effect.gen(function* () {const url = new URL("/.well-known/t3/environment", input.baseUrl);@@ -401,4 +398,6 @@ export const probeTailscaleHttpsEndpoint = (input: {onNone: () => false,onSome: (httpResponse) => httpResponse.status >= 200 && httpResponse.status < 300,});- }).pipe(Effect.orElseSucceed(() => false));+ },+ Effect.orElseSucceed(() => false),+);