diff --git a/CHANGELOG.md b/CHANGELOG.md index 73a10fd..bfd0347 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,30 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## 0.3.0 - 2026-11-01 + +### Added + +- `WorkspaceSession.ObjectBatchMaterialization` is a new optional `ObjectBatchMaterializationService`. Its `Materialize` and `Dematerialize` take an array of paths and download or free their large objects in one operation, for providers that do this faster than one call per path. Paths are exact keys, and a duplicate counts once. An empty array, or paths already in the target state, give `Succeeded` with a `NoOp` effect. When paths fail, the result is `PartiallySucceeded` if others changed and `Failed` if none did. The failure lists the failed paths in `AffectedPaths` and one `: ` line per failed path in `Details` (for example a retained backup), and the outcome's `AffectedPaths` lists the changed paths. `ServiceAvailability.ObjectBatchMaterialization` reports whether the provider supplies the service, and `WorkspaceSession.withFallbackServices` fills a missing one with operations that succeed with a `NoOp` effect and a `service_unavailable` warning. The Git provider supplies it, with the failure codes `batch_materialization_incomplete` and `batch_dematerialization_incomplete` and the partial-success recoveries `retry_materialization` and `retry_dematerialization`. lakeFS does not, because it has no large-object representation. +- `OperationContext.ReportOutput` is a new opt-in channel for the raw output of an operation's subprocesses, for a host that shows it in a folded "Show logs" section. `OperationContext.createWithOutput` builds a context with it, and contexts from `create` or `detached` have none. The callback receives batches of `OperationOutput` entries of the kinds `Command`, `StdOut`, `StdErr` and `Notice`. `CommandId` groups the entries of one subprocess. `IsPartial` marks a snapshot of a line that git rewrites with carriage returns, and the next entry with the same `CommandId` and `Kind` replaces it. The Git provider reports a header and the stderr lines of the git and git-lfs processes of its synchronization, clone, publish and large-object operations, and stdout only for the large-object download and upload calls. It redacts every line and replaces the call's known credentials. The channel limits line length, batch size, batch rate and queue size. The rate applies within each subprocess, and a subprocess that ends delivers its pending entries at once. Progress is unchanged and still carries no raw lines. The lakeFS provider reports no output. + +### Changed + +- The Git provider's `Materialize` and `Dematerialize`, in both `ObjectMaterialization` and `ObjectBatchMaterialization`, fail with the code `local_changes` when a path has local changes such as an edited file, so a host can decide by the code instead of the message. A single-path failure used to have `lfs_operation_failed`. A batch returns `local_changes` when every failed path has local changes, as `Failed` if no path changed and as `PartiallySucceeded` otherwise. With any other failed path it keeps `batch_materialization_incomplete` or `batch_dematerialization_incomplete`. `AffectedPaths` and `Details` still list the failed paths, and the category and message are unchanged. +- `OperationContext` has a new `ReportOutput` field, so code that builds the record as a literal has to set it to `None`. Code that uses `OperationContext.create` or `detached` needs no change. `NodeProcess.ProcessRequest` has a new `ReportStdoutOutput` field, which `ProcessRequest.create` sets to `false`. +- `WorkspaceSession` and `ServiceAvailability` have a new `ObjectBatchMaterialization` field that code building these records has to set. `WorkspaceSession.createCoreOnly` sets it to `None`. +- The Git provider reports live progress of its long transfers through `OperationContext.ReportProgress`. `git fetch` and `git clone` run with `--progress`, and the Git LFS transfers of an update, a synchronization, a clone and `Materialize` run with `GIT_LFS_FORCE_PROGRESS=1`. Their meters arrive as events with the phase codes `fetch`, `clone`, `clone-lfs-pull`, `lfs-pull`, `lfs-materialize-transfer` and `lfs-materialize-checkout`, with `Completed` and `Total` taken from the meter. `Synchronize` also reports events without numbers before its fetch (`fetch`), its merge (`merge`) and its large-file download (`lfs-pull`). `Clone` reports events with a `DisplayMessage` and no numbers before `git clone` (`clone`) and before its large-file download (`clone-lfs-pull`). A batch `Materialize` or `Dematerialize` of more than one path counts the finished files under `lfs-materialize-files` or `lfs-dematerialize-files`, with `Total` set to the number of paths. A single-path call reports no count events. Failure messages of these calls leave out the meter lines. `NodeProcess.ProcessRequest` has a new `ObserveStdoutProgress` field, which `ProcessRequest.create` sets to `false`. +- The Git provider's `Materialize` and `Dematerialize` read the Git LFS listing once per call and check `git status` only for the requested path. A download used to list every Git LFS file of the repository four times and read the status of the whole working tree twice, which made single-file actions slow in large repositories. A file deleted while its download runs now fails with the local-changes message and stays deleted. + +### Fixed + +- The Git provider gives a failure the category `Network` when its text says "actively refused" (a refused connection on Windows), "no such host" or "forcibly closed" (a reset connection on Windows), or has a Git LFS "batch response:" line ending in ": EOF" (a server that closes the connection). It gives the category `Timeout` for "did not properly respond" (a Windows connection attempt that gets no answer). These failures used to have the category `ProviderError`, so a caller could not tell an unreachable remote from a rejected request. The texts of other platforms, such as "connection refused" and "i/o timeout", already had these categories. +- Canceling a large-object download during `Synchronize`, `Update` or `Clone` no longer leaves `.git/index.lock` behind. The Git provider ran `git lfs pull`, which a cancel could kill while it held the index lock. It now runs `git lfs fetch`, which a cancel stops, and then `git lfs checkout`, which runs to its end. A cancel during the checkout takes effect afterwards, and the call reports the work that finished. Every call that downloads large objects this way reports a step event with the code `lfs-pull-checkout` (`clone-lfs-pull-checkout` after a clone) before the checkout starts, and the checkout reports its progress under that code. The checkout also runs after a failed fetch, for example when the server lost one object, so the objects that arrived reach the working tree, and the result stays the fetch failure. When the checkout fails and an `index.lock` exists, or Git names the lock in its failure text, the partial result has the recovery `remove_index_lock` instead of `retry_materialization`. A failed fetch keeps `retry_materialization`, because the fetch takes no lock. The provider never deletes the lock. A batch `Materialize` or `Dematerialize` that hit an index lock on one path also reports `remove_index_lock`, whether or not other paths finished. +- A large-object checkout that git-lfs ends with success although it could not update the index (because of a held `index.lock`) is now a failure with the lock recovery. Before, git-lfs wrote the files, printed "Error updating the Git index:" and exited with 0, so the download reported success, the lock stayed and the files read as modified. The Git provider now reads that text from `git lfs checkout`. In `Update`, `Synchronize` and `Clone` the result is `PartiallySucceeded` with the code `hydration_failed`, and the recovery is `remove_index_lock` when the lock file exists. A batch `Materialize` looks for the lock file after such a checkout. If it exists, the recovery is `remove_index_lock`. If not, a partial success keeps `retry_materialization`, and a run in which no path changed is `Failed` without a recovery action. The unmark of a path in `StoragePolicy.SetPathPolicy`, the local materialization of a picked conflict object and the checkout of restored large files in `RestorePaths` also count this checkout as failed. The unmark fails with `index_locked` when the lock file exists, and a restore reports `PartiallySucceeded` with the recovery `remove_index_lock`. The failures of `Materialize`, the unmark, the pick and the restore set `StateChanged` to `true`, because git-lfs wrote the files. Every `git lfs checkout` of the provider runs to its end, including those of the unmark, the pick and the restore, so a cancel cannot leave `.git/index.lock` behind. +- The Git provider's `Materialize` and batch `Materialize` repair the index entries that a lock-blocked `git lfs checkout` leaves stale. After such a checkout the files hold their content, but the index keeps the stat data of the pointers, so `git status` lists them as modified. A download refused them with "has local changes", or found them materialized and left them modified. A path whose only change is that stale entry is now repaired without a transfer if the file is a regular file with the size and SHA-256 of its Git LFS object, the index entry equals the committed pointer, and the current attributes still route the path through the lfs filter (otherwise `git add` would stage the file as a plain blob). The provider runs `git add` on the repaired paths, which stages nothing because the clean filter reproduces the committed pointer for that content. The repair changes the index, so the batch `Materialize` lists a repaired path in `AffectedPaths` with the effect `Performed`, and the path's progress report says the file is materialized. A lock still held at that point is reported with the `remove_index_lock` recovery. A modified file with other content, or a file with a staged change, still fails with the local-changes message. +- `Redaction.redact` removes the whole userinfo of a URL whose user name contains an `@`, such as `https://me@mail.com:secret@host/repo.git`. It used to stop at the first `@` and leave the rest of the userinfo in the text. +- Git LFS transfers of a workspace whose remote URL has no `.git` suffix no longer fail on GitLab with "Unprocessable entity" (nfdi4plants/ARCitISA#1471). The provider passed the remote URL plus `/info/lfs` as `lfs.url`, which git-lfs uses literally. It now builds the endpoint the way git-lfs server discovery does: a remote that ends in `.git` gets `/info/lfs`, and any other gets `.git/info/lfs`. The check is case-sensitive like the one in git-lfs, so `proj.GIT` becomes `proj.GIT.git/info/lfs`. + ## 0.2.2 - 2026-10-26 ### Fixed diff --git a/docs/consuming.md b/docs/consuming.md index 4a7730b..1562854 100644 --- a/docs/consuming.md +++ b/docs/consuming.md @@ -179,7 +179,7 @@ let cloneWorkspace (factory: ProviderFactory) location targetPath (context: Oper } ``` -A clone canceled before it completes rolls back and fails as `Canceled`. A pre-existing empty target is cleaned by removing its entries, so entries another program adds to that folder during the clone are removed too. A clone that finished before cancellation took effect succeeds. A download failure that is not a cancellation returns `PartiallySucceeded` with `retry_materialization`, so the workspace exists and its large objects are not materialized. +A clone canceled before it completes rolls back and fails as `Canceled`. A pre-existing empty target is cleaned by removing its entries, so entries another program adds to that folder during the clone are removed too. A clone that finished before cancellation took effect succeeds. A download failure that is not a cancellation returns `PartiallySucceeded` with `retry_materialization`, so the workspace exists and its large objects are not materialized. The download is `git lfs fetch` followed by `git lfs checkout`. A cancel stops the fetch and rolls the clone back. A cancel that arrives during the checkout waits for the checkout to end, and the clone succeeds. A fetch that fails without a cancel still runs the checkout, so the files whose objects arrived are checked out, and the result is the failure of the fetch. When the checkout fails and a `.git/index.lock` is present, or when Git names the lock in its failure text, the recovery is `remove_index_lock` instead of `retry_materialization`. Remove the lock once no git process runs, then materialize again. A clone whose rollback cannot remove the target returns `Failed` with `StateChanged = true` and the recovery code `remove_clone_target`, with category `Canceled` when the user canceled. Ask the user to clear the target folder before retrying. @@ -406,7 +406,7 @@ ordering. ## Optional services -Every session has `Descriptor`, `Core` and `Close`. The seven services are `option`, and a +Every session has `Descriptor`, `Core` and `Close`. The eight services are `option`, and a provider leaves one absent when it has nothing to offer there. Feature discovery is an `Option.isSome` check, and there are two reasonable ways to write a host against that. @@ -445,7 +445,7 @@ let describe (session: WorkspaceSession) (context: OperationContext) = async { ``` `WorkspaceSession.availability` returns a `ServiceAvailability` record with one boolean -per service, which is easier to hand to a view model than seven options. +per service, which is easier to hand to a view model than eight options. ### Filled: every service present, no-ops where the provider has nothing @@ -476,7 +476,8 @@ The text diff fallback returns `NotDiffable ProviderUnsupported` from `Open`. It lakeFS has no text diff service, so it gets this fallback. A fallback write also succeeds and changes nothing. `Materialize`, `Dematerialize`, -`SetPathPolicy` and `SetSettings` return `Succeeded` with the same warning. Read the +`SetPathPolicy` and `SetSettings` return `Succeeded` with the same warning. The +`Materialize` and `Dematerialize` of the batch service do the same. Read the warning before you treat one of these as done. The storage settings reseed in [provider authoring](provider-authoring.md) shows why this matters. It tells a host to write its saved threshold through `SetSettings` and mark the migration complete only @@ -549,6 +550,12 @@ degrade quietly. Keep them absent when the interface changes shape per provider, a host must never offer an action the provider cannot carry out. Two hosts can make opposite choices against the same provider, which is the intent. +Use `ObjectBatchMaterialization` when an action covers many paths, for example a folder, +because one call is faster than one `ObjectMaterialization` call per path. When the +provider does not supply it, call `ObjectMaterialization.Materialize` or `Dematerialize` +for each path instead. A filled session always has the service, but its fallback changes +nothing, so read the `service_unavailable` warning before you treat the result as done. + ## Paged text diffs `TextDiff` is an optional service on `WorkspaceSession`. Read it from `session.TextDiff` @@ -1296,7 +1303,7 @@ last changed the file. Picking a candidate with no preview and no stored object resolves the item by deleting the file. A pick of a stored object whose bytes are not local succeeds with the warning `object_not_materialized`. A pick whose local materialization fails returns `PartiallySucceeded` -with `object_materialization_failed` and `retry_materialization`. Git's Materialize refuses a path +with `object_materialization_failed` and `retry_materialization`, or `remove_index_lock` when an index lock caused it. Git's Materialize refuses a path that has an uncommitted change, which every picked path has until Finalize, so the host materializes such paths after `Finalize`. @@ -1321,7 +1328,8 @@ let createContext (operationId: string) (onProgress: OperationProgress -> unit) `OperationContext.create` catches and drops exceptions from the progress callback, so a callback that reports to a closed window cannot fail the operation it watches. The guard -belongs to `create`. A context built as a record literal calls the callback unguarded. +belongs to `create` and `createWithOutput`. A context built as a record literal calls the +callbacks unguarded and has to set `ReportOutput`, which is `None` when the host asks for no output. The host calls `source.Cancel()` from wherever the user asks, such as a stop button. A canceled operation comes back as a `Canceled` failure that describes what the @@ -1343,14 +1351,144 @@ process leaves its `index.lock` behind, so `remove_index_lock` is the usual reco and a host needs a path for it. The recovery codes a Git update can report are listed in [provider authoring](provider-authoring.md). +The large-object download of an Update or a Synchronize (with `versioncontrolservice.lfs.materializelargeobjects` on) is `git lfs fetch` followed by `git lfs checkout`. A cancel kills only the fetch, and no checkout starts. The checkout is local and holds the index lock while it runs, so the provider never kills it. A cancel that arrives during the checkout takes effect when the checkout ends, and the call reports the work that finished, which is `Succeeded` when every file is checked out. A canceled fetch returns `PartiallySucceeded` with category `Canceled`, code `hydration_failed` and the recovery `retry_materialization`. A fetch that fails without a cancel, for example because the server lost one object, still runs the checkout, so the files whose objects arrived are checked out, and the result is the failure of the fetch. The provider never deletes a lock file. When the checkout fails and an `index.lock` exists, or when Git names the lock in its failure text, the partial result reports `remove_index_lock` instead. A failed fetch keeps `retry_materialization`, because the fetch takes no lock. With a held lock, git-lfs writes the files, prints `Error updating the Git index:` without Git's lock message and still exits with 0. The provider reads that text from the checkout and treats the run as a failed checkout. Every `git lfs checkout` of the provider runs to its end, because it holds the index lock. Besides the checkout of the download, these are the checkouts of a batch `Materialize`, of the unmark in `StoragePolicy.SetPathPolicy`, of the local materialization of a picked conflict object and of `RestorePaths`. A cancel never kills a running checkout. A batch `Materialize`, the unmark, the pick and `RestorePaths` look for the lock file through `git rev-parse --git-path index.lock` after the index error. When it exists, the unmark fails with `index_locked`, a batch `Materialize` gets the recovery `remove_index_lock` on its failure, and the pick and `RestorePaths` return `PartiallySucceeded` with that recovery. Without a lock file the failure is plain. The unmark fails with `object_materialization_failed` and the text of git-lfs. A batch `Materialize` that changed at least one path returns `PartiallySucceeded` with `retry_materialization`, and one that changed no path returns `Failed` with no recovery action. The pick and `RestorePaths` keep `retry_materialization`. Git-lfs wrote the files in each case, so these failures have `StateChanged` set to `true`. Remove the lock once no git process runs, then retry the download. The retry finds the files with their content but with index entries that still hold the stat data of the pointers, so `git status` lists them as modified. A single or batch `Materialize` repairs such an entry with `git add` when the file is a regular file with the size and the SHA-256 of its object and the entry has no staged change. The attributes must also still register the path with the lfs filter. The `git add` stages nothing, because the clean filter reproduces the committed pointer for that content (the file's content hashes to the pointer's object and the attributes route the path through the lfs filter). The repair changes the index, so the path counts as changed. A single `Materialize` returns a performed outcome, a batch `Materialize` lists the path in `AffectedPaths`, and the progress report of the path says the file is materialized. A held lock fails the repair with the lock failure, and any other modified file keeps the local-changes failure. + +The local-changes failure of `Materialize` and `Dematerialize` has the code `local_changes` and the category `ProviderError`. It covers a path with local changes, for example an edited file. The single-path `ObjectMaterialization` and `ObjectBatchMaterialization` both use it. A batch call returns `local_changes` when every failed path was refused for local changes. The result is `Failed` when no path changed and `PartiallySucceeded` otherwise, with the failed paths in `AffectedPaths` and one `: ` line per failed path in `Details`. A batch with any other failed path keeps `batch_materialization_incomplete` for `Materialize` and `batch_dematerialization_incomplete` for `Dematerialize`. A partial success keeps the recovery `retry_materialization` or `retry_dematerialization`. Decide by the code. The message names the path and can change. + The Git provider runs `git lfs ls-files -j` with no time limit, because that command prints nothing until it has listed every file. This applies to `ObjectMaterialization.ListObjects`, `Materialize` (including its download step) and `Dematerialize`. Each of them takes an `OperationContext`. Cancel the context to stop one that runs too long. The cancellation ends the git-lfs process and the operation returns a `Canceled` failure. +The `Materialize` and `Dematerialize` of `ObjectBatchMaterialization` behave the same way, and a canceled batch reports the paths that finished as changed. + `OperationProgress` carries a stable `PhaseCode` such as `transfer`, an optional item, completed and total counts, and a sanitized `DisplayMessage`. Counts are `float` because JavaScript has no native 64-bit integer, so a float is what carries byte totals above two GiB exactly on both runtimes. Show the message, and branch on the phase code. +### Progress of Git transfers + +The Git provider turns the progress meters of its long transfers into `OperationProgress` events. +A meter such as `Receiving objects: 12% (1/8)` becomes an event whose `Completed` is the percent +and whose `Total` is 100. The `DisplayMessage` holds the meter's label with its object count and +transferred size, for example `Downloading LFS objects (2/3), 1.2 MB`. A meter for a single object +has no `Completed` and `Total`, because one object has no useful percent. + +These calls report their meters, each under its own phase code: + +| Call | Phase code | +| --- | --- | +| `git fetch` of Refresh, Update, Synchronize, Publish and Bind | `fetch` | +| `git clone` | `clone` | +| `git lfs fetch` after a clone | `clone-lfs-pull` | +| `git lfs checkout` after that fetch | `clone-lfs-pull-checkout` | +| `git lfs fetch` that downloads the large objects of an Update or a Synchronize | `lfs-pull` | +| `git lfs checkout` after that fetch | `lfs-pull-checkout` | +| `git lfs fetch` of `Materialize` | `lfs-materialize-transfer` | +| `git lfs checkout` of `Materialize` | `lfs-materialize-checkout` | + +Git LFS prints its meters to a pipe only when `GIT_LFS_FORCE_PROGRESS=1` is set, and then it +writes them to stdout. The provider sets the variable for the Git LFS calls in the table and reads +their stdout for meters. It leaves the dry runs and the listings alone. The failure message of a call +that printed meters has none of the meter lines. + +A step of Synchronize, and of the Refresh and Update inside it, reports an event without numbers +when it starts, and so does a step of Clone. A host can show the step before the first meter +arrives. These events carry a `DisplayMessage`: + +| Phase code | `DisplayMessage` | Reported before | +| --- | --- | --- | +| `fetch` | Fetching online changes | the `git fetch` of the refresh | +| `merge` | Merging online changes | the `git merge` of the update | +| `lfs-pull` | Downloading large files | the `git lfs fetch` that follows an update | +| `lfs-pull-checkout` | Checking out large files | the `git lfs checkout` that follows that fetch | +| `clone` | Cloning the repository | the `git clone` | +| `clone-lfs-pull` | Downloading large files | the `git lfs fetch` that follows a clone with `MaterializeAllObjects` | + +The checkout after the fetch of a clone reports the same event under `clone-lfs-pull-checkout`. + +A batch call also reports how many of its files are done. `Materialize` of +`ObjectBatchMaterialization` uses the phase code `lfs-materialize-files`, and `Dematerialize` uses +`lfs-dematerialize-files`. `Item` is `None` and `Total` is the number of distinct requested paths. +`Completed` counts the paths that have an outcome, whatever the outcome is. A downloaded file counts +as soon as its checkout ends, before the check of its content. `Completed` only rises, and it reaches +`Total` when the call returns a result. These count events exist only for batch calls with more than +one path. A call with a single path keeps its earlier progress sequence and reports none. + +### Raw output of subprocesses + +A host that wants to show what git and git-lfs print, for example in a folded "Show logs" section, +builds its context with `OperationContext.createWithOutput`. The last argument receives batches of +`OperationOutput`: + +```fsharp +let createContextWithLogs + (operationId: string) + (onProgress: OperationProgress -> unit) + (onOutput: OperationOutput[] -> unit) + = + let source = OperationCancellation.Source() + + let context = + OperationContext.createWithOutput operationId source.Cancellation onProgress onOutput + + context, source +``` + +The channel is opt-in. `create` and `detached` leave `ReportOutput` at `None`, and the provider then +does no work for output. Progress stays what it was, and no raw line ever becomes a progress event. +The callback runs on the thread that runs the operation, so it should only queue the entries and +render them later. An exception from it is dropped. + +Each entry has a `Kind` and a `Text` without a line terminator. `CommandId` groups the entries of one +subprocess and is unique within the operation. A notice that concerns the whole operation has an empty +`CommandId`. + +| Kind | Content | +| --- | --- | +| `Command` | The header of a subprocess, such as `git lfs fetch origin HEAD`. The provider sends one before the subprocess starts. It leaves out the leading `-c key=value` pairs, which can hold credentials, and it shows at most twelve arguments and then `...`. | +| `StdErr` | A line from stderr. Every subprocess of the operation reports it, including probes whose failure the operation expects. Such a line does not mean that the operation failed. | +| `StdOut` | A line from stdout. Only calls whose stdout is diagnostic text report it. | +| `Notice` | A message from the library, for example that a long line was omitted or that lines were dropped. | + +Stdout is diagnostic text for the large-object download that Clone and the synchronizing operations +run (`git lfs fetch` and `git lfs checkout`), for the download of `Materialize` (the same two +commands) and for the `git lfs push` of a publish. The stdout of every other call is data, such as +`git lfs ls-files -j`, `git status -z`, object content or the output of `git cat-file`, and it never +reaches the channel. + +Git rewrites a progress meter in place with carriage returns, and the provider collapses these +rewrites. A line that is still being rewritten arrives as a snapshot with `IsPartial` set, at most +every 250 ms. A snapshot that this rate holds back arrives when the 250 ms end, even if no more text +comes. The next entry with the same `CommandId` and `Kind` replaces a partial entry in the +host's view, whether that next entry is partial or complete. When the line ends, or the subprocess +ends for any reason, the final text arrives with `IsPartial` unset. + +The text is a redacted diagnostic and the channel keeps no transcript. The provider strips terminal +escape sequences and control characters and skips blank lines. It replaces the credentials of the call +with `[REDACTED]`. These are the values of credential-bearing configuration arguments, the token +and the decoded `user:secret` parts of an Authorization header, the userinfo of URLs and the values +of credential-looking environment variables. The provider cannot recognize a secret it has no way to +know, for example one that a git hook prints. The order of stdout and stderr lines relative to each +other is not promised, and the provider keeps no history. The host decides how many lines to keep. + +The channel has these limits: + +| Limit | Behavior | +| --- | --- | +| 4096 UTF-16 units per line | A longer line is dropped and a notice says so. A partial entry that is open at that moment ends with its last text. | +| 20 entries per batch, 10 batches per second | Entries wait in a queue between batches. The rate holds within a subprocess. | +| 128 waiting entries | The oldest lines are dropped, the command headers stay, and a notice reports how many lines were left out. | +| End of a subprocess | Everything that waits is delivered at once, without waiting for the batch rate, before the operation completes. | + +The Git provider reports the subprocesses of Refresh, Update, Synchronize, Publish, Clone and Bind, the +large-object listing, download and free of `ObjectMaterialization` and `ObjectBatchMaterialization`, and +the LFS upload of a publish. It does not report the text diff workers, the byte-exact object reads, the +cleanup of the LFS cache (prune and dedup) or the few configuration probes that run without an operation +context. The lakeFS provider runs no subprocesses and reports no output. + +Show the output only in a folded or secondary view. Never use a raw line as the headline of an +operation. The headline comes from progress and from the result. + ## Building against the packages The packages are on nuget.org: diff --git a/docs/provider-authoring.md b/docs/provider-authoring.md index ef2f565..67c0de2 100644 --- a/docs/provider-authoring.md +++ b/docs/provider-authoring.md @@ -67,6 +67,7 @@ Optional services advertise real capability: | `TextDiff` | resumable pages for a working file against its version at HEAD | | `ConflictResolution` | provider-owned conflict sessions and stale-handle checks | | `ObjectMaterialization` | list, hydrate, and dematerialize large or lazy objects | +| `ObjectBatchMaterialization` | hydrate or dematerialize many objects in one operation | | `StoragePolicy` | literal-path policy and host-facing settings | | `Maintenance` | prune and deduplicate local storage | | `RepositoryBrowser` | a credential-free repository URL | @@ -198,4 +199,6 @@ The published records are intentionally small. Add new capability as a new optio `ServiceAvailability` is the exception to the rule about published records: a new optional service adds a required field to it, and that is a deliberate breaking change so a consumer's availability report can never be silently incomplete. +`OperationContext` is the second exception. It is an observation record that the host builds, and the next release adds the field `ReportOutput` to it. Code that builds the record as a literal has to add `ReportOutput = None`. Code that calls `OperationContext.create`, `createWithOutput` or `detached`, and a provider that only reads the context, compile as before. A provider that runs subprocesses reports their output only when `context.ReportOutput` is `Some`, and it redacts every line first, as the [consuming guide](consuming.md#raw-output-of-subprocesses) describes. + Run the shared conformance profiles before publishing an external provider. The harness contract and profile expectations are described in [conformance-profiles.md](conformance-profiles.md). diff --git a/src/VersionControlService.Abstractions/Extensions.fs b/src/VersionControlService.Abstractions/Extensions.fs index ff8387d..eb9fa13 100644 --- a/src/VersionControlService.Abstractions/Extensions.fs +++ b/src/VersionControlService.Abstractions/Extensions.fs @@ -302,6 +302,24 @@ type ObjectMaterializationService = { Dematerialize: RepositoryPath -> OperationContext -> Async> } +/// Optional batch variant of the object-materialization extension. A provider supplies it when it can +/// download or free many large objects in one operation, which is faster than one Materialize or +/// Dematerialize call per path. +/// +/// Paths are exact keys, as for the single calls, and a duplicate counts once. An empty array or paths that +/// are already in the target state give Succeeded with a NoOp effect. When some paths fail and others +/// changed, the result is PartiallySucceeded. When none changed, it is Failed. A failure lists the failed +/// paths in AffectedPaths and one ": " line per failed path in Details. The outcome's +/// AffectedPaths lists the changed paths. A canceled run reports the paths that finished as changed and +/// fails the others with a Canceled failure (PartiallySucceeded when some changed, Failed when none). +type ObjectBatchMaterializationService = { + /// Replaces the pointers of the given paths with their content. + Materialize: RepositoryPath[] -> OperationContext -> Async> + /// Replaces the content of the given paths with their pointers. Each path follows the rules of the + /// single Dematerialize call. + Dematerialize: RepositoryPath[] -> OperationContext -> Async> +} + type StoragePolicySettings = { /// Threshold in megabytes above which new objects use large-object storage, when supported. AutoPolicyThresholdMb: int option diff --git a/src/VersionControlService.Abstractions/Operations.fs b/src/VersionControlService.Abstractions/Operations.fs index ee0909a..a77b3fe 100644 --- a/src/VersionControlService.Abstractions/Operations.fs +++ b/src/VersionControlService.Abstractions/Operations.fs @@ -55,34 +55,76 @@ type OperationProgress = { DisplayMessage: string option } +/// The kind of an output entry. +[] +type OperationOutputKind = + /// The header of a subprocess, such as "git lfs pull origin main". It has no `-c` configuration pairs. + | Command + | StdOut + | StdErr + /// A message from the library, for example that a line was too long to keep. + | Notice + +/// One entry of the raw output channel: a redacted line from a subprocess that an operation ran. +/// The channel carries diagnostics and keeps no transcript. Progress stays in `OperationProgress`. +/// +/// A line that git rewrites in place with a carriage return, such as a progress meter, arrives as +/// snapshots with `IsPartial` set. The next entry with the same `CommandId` and `Kind` replaces a +/// partial entry in the host's view, whether that next entry is partial or complete. A complete +/// entry (`IsPartial` false) is never replaced. +type OperationOutput = { + /// Groups the entries of one subprocess. It is empty for a notice that concerns the whole operation. + CommandId: string + Kind: OperationOutputKind + /// Redacted text without a line terminator. + Text: string + IsPartial: bool +} + /// Context passed to every asynchronous provider operation. type OperationContext = { OperationId: string Cancellation: OperationCancellation ReportProgress: OperationProgress -> unit + /// Receives batches of redacted subprocess output. None means the host did not ask for output, + /// and a provider then does no work for it. Create a context with output through + /// `OperationContext.createWithOutput`. + ReportOutput: (OperationOutput[] -> unit) option } module OperationContext = + let private guard (callback: 'T -> unit) : 'T -> unit = + fun value -> + try + callback value + with _ -> + () + /// The context catches and drops any exception the progress callback throws, so a host /// that reports to something already gone (a closed window, say) cannot fail the operation. + /// The context has no output callback. let create (operationId: string) (cancellation: OperationCancellation) (reportProgress: OperationProgress -> unit) = { OperationId = operationId Cancellation = cancellation - ReportProgress = - fun progress -> - try - reportProgress progress - with _ -> - () + ReportProgress = guard reportProgress + ReportOutput = None } - /// Context without cancellation or progress observation. - let detached (operationId: string) = { - OperationId = operationId - Cancellation = OperationCancellation.none - ReportProgress = ignore - } + /// Like `create`, and the context also delivers raw subprocess output in batches to + /// `reportOutput`. An exception from that callback is dropped like one from the progress callback. + let createWithOutput + (operationId: string) + (cancellation: OperationCancellation) + (reportProgress: OperationProgress -> unit) + (reportOutput: OperationOutput[] -> unit) + = + { create operationId cancellation reportProgress with + ReportOutput = Some(guard reportOutput) } + + /// Context without cancellation, progress or output observation. + let detached (operationId: string) = + create operationId OperationCancellation.none ignore /// Stable failure category. Provider-specific detail lives in the extensible Code string. type FailureCategory = @@ -174,8 +216,9 @@ module Redaction = open System.Text.RegularExpressions let private replacements = [ - // URL credentials: https://user:secret@host or https://token@host - Regex(@"://[^/@\s]+@", RegexOptions.None), "://[REDACTED]@" + // URL credentials: https://user:secret@host or https://token@host. A user name can hold an "@", + // so the userinfo runs to the last "@" before the first "/". + Regex(@"://[^/\s]+@", RegexOptions.None), "://[REDACTED]@" // Authorization / token headers keep the field name, lose the value. Regex(@"(authorization\s*:)[^\r\n]+", RegexOptions.IgnoreCase), "$1 [REDACTED]" Regex(@"(private-token\s*:)[^\r\n]+", RegexOptions.IgnoreCase), "$1 [REDACTED]" diff --git a/src/VersionControlService.Abstractions/Providers.fs b/src/VersionControlService.Abstractions/Providers.fs index 3e9935d..f744ea1 100644 --- a/src/VersionControlService.Abstractions/Providers.fs +++ b/src/VersionControlService.Abstractions/Providers.fs @@ -18,6 +18,7 @@ type WorkspaceSession = { TextDiff: TextDiffService option ConflictResolution: ConflictResolutionService option ObjectMaterialization: ObjectMaterializationService option + ObjectBatchMaterialization: ObjectBatchMaterializationService option StoragePolicy: StoragePolicyService option Maintenance: StorageMaintenanceService option RepositoryBrowser: RepositoryBrowserService option @@ -31,6 +32,7 @@ type ServiceAvailability = { TextDiff: bool ConflictResolution: bool ObjectMaterialization: bool + ObjectBatchMaterialization: bool StoragePolicy: bool Maintenance: bool RepositoryBrowser: bool @@ -67,6 +69,7 @@ module WorkspaceSession = TextDiff = session.TextDiff.IsSome ConflictResolution = session.ConflictResolution.IsSome ObjectMaterialization = session.ObjectMaterialization.IsSome + ObjectBatchMaterialization = session.ObjectBatchMaterialization.IsSome StoragePolicy = session.StoragePolicy.IsSome Maintenance = session.Maintenance.IsSome RepositoryBrowser = session.RepositoryBrowser.IsSome @@ -99,6 +102,13 @@ module WorkspaceSession = Dematerialize = fun _ _ -> async { return noOp objectMaterializationReason () } } + let private objectBatchMaterializationReason = "The provider has no object batch materialization service." + + let private noOpObjectBatchMaterialization: ObjectBatchMaterializationService = { + Materialize = fun _ _ -> async { return noOp objectBatchMaterializationReason () } + Dematerialize = fun _ _ -> async { return noOp objectBatchMaterializationReason () } + } + let private storagePolicyReason = "The provider has no storage policy service." let private noOpStoragePolicy: StoragePolicyService = { @@ -148,6 +158,7 @@ module WorkspaceSession = TextDiff = None ConflictResolution = None ObjectMaterialization = None + ObjectBatchMaterialization = None StoragePolicy = None Maintenance = None RepositoryBrowser = None @@ -174,6 +185,8 @@ module WorkspaceSession = TextDiff = Some(Option.defaultValue noOpTextDiff session.TextDiff) ConflictResolution = Some(Option.defaultValue noOpConflictResolution session.ConflictResolution) ObjectMaterialization = Some(Option.defaultValue noOpObjectMaterialization session.ObjectMaterialization) + ObjectBatchMaterialization = + Some(Option.defaultValue noOpObjectBatchMaterialization session.ObjectBatchMaterialization) StoragePolicy = Some(Option.defaultValue noOpStoragePolicy session.StoragePolicy) Maintenance = Some(Option.defaultValue noOpStorageMaintenance session.Maintenance) RepositoryBrowser = Some(Option.defaultValue noOpRepositoryBrowser session.RepositoryBrowser) diff --git a/src/VersionControlService.Git/Git/GitEngineTypes.fs b/src/VersionControlService.Git/Git/GitEngineTypes.fs index a48fb8a..7ab4128 100644 --- a/src/VersionControlService.Git/Git/GitEngineTypes.fs +++ b/src/VersionControlService.Git/Git/GitEngineTypes.fs @@ -15,6 +15,15 @@ type GitLfsLsFileInfo = { [] let GitLfsSkipSmudgeEnvKey = "GIT_LFS_SKIP_SMUDGE" +/// Git LFS prints no meters to a pipe unless this variable asks for them. With it, every meter goes to stdout. +let GitLfsForceProgress = "GIT_LFS_FORCE_PROGRESS", "1" + +/// A copy of the environment with live Git LFS progress forced. The environment passed in stays as it is. +let withForcedLfsProgress (environment: obj) : obj = + let key, value = GitLfsForceProgress + + JS.Constructors.Object.assign (JsInterop.createObj [], environment, JsInterop.createObj [ key, box value ]) + type GitLfsCommand = | Pull | Fetch @@ -50,6 +59,8 @@ type GitFailureKind = | LfsBackupRetained | InvalidLfsThreshold | RemoteProjectAlreadyExists + /// A Git LFS download or free refused a path that has local changes. + | LocalChanges | Unknown [] diff --git a/src/VersionControlService.Git/Git/GitInternals.fs b/src/VersionControlService.Git/Git/GitInternals.fs index 5e3c8c6..04152c8 100644 --- a/src/VersionControlService.Git/Git/GitInternals.fs +++ b/src/VersionControlService.Git/Git/GitInternals.fs @@ -11,6 +11,8 @@ open VersionControlService.Git.GitAuthAdapter module NodeFileSystem = VersionControlService.Runtime.Node.FileSystem module NodeProcess = VersionControlService.Runtime.Node.Process +module NodeOutput = VersionControlService.Runtime.Node.OutputReporter +module NodeInterop = VersionControlService.Runtime.Node.Interop type GitProgressCallback = GitProgressDto -> unit @@ -113,23 +115,85 @@ let private hasStreamListener (_stream: obj) : bool = jsNative let private attachOutputHandler (_git: ISimpleGit) (_handler: string -> obj -> obj -> string[] -> unit) : ISimpleGit = jsNative -let internal withGitOutputProgress (progressCallback: GitProgressCallback option) (git: ISimpleGit) = - match progressCallback with - | None -> git - | Some _ -> +/// Attaches an output handler that reads the meter lines of both streams for the progress callback. When the +/// operation has an output channel, each command also reports a header and its stderr lines there. The +/// stdout of a simple-git command is data, so it never reaches the channel. `secretArguments` are +/// authentication arguments that the instance applies itself, in case the handler does not see them. +let internal withGitOutput + (progressCallback: GitProgressCallback option) + (outputTarget: NodeOutput.OutputTarget option) + (secretArguments: string[]) + (git: ISimpleGit) + = + match progressCallback, outputTarget with + | None, None -> git + | _ -> attachOutputHandler git - (fun (_command: string) (stdout: obj) (stderr: obj) (_args: string[]) -> - let observeStream (stream: obj) = + (fun (_command: string) (stdout: obj) (stderr: obj) (args: string[]) -> + let commandArguments = if isNull (box args) then [||] else args + + let commandOutput = + outputTarget + |> Option.map (fun target -> + NodeOutput.beginCommand + target.Channel + "git" + commandArguments + (Array.append secretArguments commandArguments) + [||] + false) + + // The command ends when both streams have ended. + let openStreams = ref 0 + + let observeStream (stream: obj) (observeLog: NodeOutput.CommandOutput -> string -> unit) = if hasStreamListener stream then - let observe, flush = createOutputObserver progressCallback - stream?on ("data", fun (chunk: obj) -> observe (string chunk)) |> ignore - stream?on ("end", fun (_: obj) -> flush ()) |> ignore + openStreams.Value <- openStreams.Value + 1 + let observeMeters, flushMeters = + if progressCallback.IsSome then + createOutputObserver progressCallback + else + ignore, ignore + + let decoder = NodeInterop.createUtf8StringDecoder () + let ended = ref false + + let observe (text: string) = + observeMeters text + commandOutput |> Option.iter (fun output -> observeLog output text) + + let finish () = + if not ended.Value then + ended.Value <- true + let tail = NodeInterop.finishUtf8Decoding decoder + + if not (String.IsNullOrEmpty tail) then + observe tail - observeStream stdout - observeStream stderr + flushMeters () + openStreams.Value <- openStreams.Value - 1 + + if openStreams.Value = 0 then + commandOutput |> Option.iter (fun output -> output.Finish()) + + stream?on ("data", fun (chunk: obj) -> observe (NodeInterop.decodeUtf8Chunk decoder chunk)) + |> ignore + + stream?on ("end", fun (_: obj) -> finish ()) |> ignore + stream?on ("close", fun (_: obj) -> finish ()) |> ignore + + observeStream stdout (fun output text -> output.ObserveStdout text) + observeStream stderr (fun output text -> output.ObserveStderr text) + + // A command whose streams cannot be observed would otherwise leave its header waiting. + if openStreams.Value = 0 then + commandOutput |> Option.iter (fun output -> output.Finish()) ) +let internal withGitOutputProgress (progressCallback: GitProgressCallback option) (git: ISimpleGit) = + withGitOutput progressCallback None [||] git + // `internal` stays inside the library assembly boundary. let internal unsafeOptions = SimpleGitUnsafeOptions( diff --git a/src/VersionControlService.Git/Git/GitLfsAdapter.fs b/src/VersionControlService.Git/Git/GitLfsAdapter.fs index 9e4a4bf..f0ac2ec 100644 --- a/src/VersionControlService.Git/Git/GitLfsAdapter.fs +++ b/src/VersionControlService.Git/Git/GitLfsAdapter.fs @@ -9,6 +9,7 @@ open VersionControlService.Runtime.Node.Interop open VersionControlService.Git.GitAuthAdapter module GitExecution = VersionControlService.Git.GitExecution +module NodeOutput = VersionControlService.Runtime.Node.OutputReporter [] let private repoValidationTimeoutMs = 5000 @@ -69,6 +70,8 @@ type GitSpawnRequest = { StandardInput: string option CancelCheck: (unit -> bool) option TimeoutMs: int option + /// Where the process reports its output lines. None when the operation's host did not ask for them. + Output: NodeOutput.OutputTarget option } /// Captured process result for spawned git commands, including raw stdout for binary-safe batch parsing. @@ -80,6 +83,32 @@ type GitSpawnResult = { TimedOut: bool } +/// Receives the decoded text of each stdout and stderr chunk of a spawned git process. An observer +/// that keeps a line buffer needs one buffer per stream, because a chunk of one stream can arrive +/// inside a split line of the other. +type OutputObservers = { + OnStdout: string -> unit + OnStderr: string -> unit +} + +module OutputObservers = + + let none: OutputObservers = { OnStdout = ignore; OnStderr = ignore } + + /// One callback for both streams, for observers that keep no line buffer. + let both (observe: string -> unit) : OutputObservers = { OnStdout = observe; OnStderr = observe } + + /// Reports the progress meter lines of both streams to `reportLine`, each stream with its own + /// line buffer. The returned function flushes the buffers after the process has ended. + let meters (reportLine: string -> unit) : OutputObservers * (unit -> unit) = + let observeStdout, flushStdout = VersionControlService.Runtime.Node.Process.createMeterObserver reportLine + let observeStderr, flushStderr = VersionControlService.Runtime.Node.Process.createMeterObserver reportLine + + { OnStdout = observeStdout; OnStderr = observeStderr }, + fun () -> + flushStdout () + flushStderr () + let private resolveGitEnvironment (environment: obj option) = environment |> Option.defaultWith createNonInteractiveEnv @@ -89,17 +118,31 @@ let private resolveGitEnvironment (environment: obj option) = let private runGitProcess (captureStdout: bool) (onStarted: unit -> unit) - (onOutput: string -> unit) + (output: OutputObservers) (request: GitSpawnRequest) : Promise = promise { let! result = Fable.Core.JS.Constructors.Promise.Create(fun resolve _ -> + let environment = resolveGitEnvironment request.Environment + + // The header is queued before the spawn. Nothing is computed when the host asked for no output. + let commandOutput = + request.Output + |> Option.map (fun target -> + NodeOutput.beginCommand + target.Channel + "git" + request.Arguments + request.Arguments + (NodeOutput.environmentEntries environment) + target.ReportStdout) + let spawnOptions = createObj [ "shell" ==> false "windowsHide" ==> true - "env" ==> resolveGitEnvironment request.Environment + "env" ==> environment "detached" ==> not (isWindows ()) match request.WorkingDirectory with @@ -138,6 +181,8 @@ let private runGitProcess if not finished then finished <- true clearTimers () + // The host has the output before the operation sees the result. + commandOutput |> Option.iter (fun output -> output.Finish()) let effectiveExitCode = if cancelRequested && exitCode = 0 then -1 else exitCode let stdoutBuffer = @@ -205,12 +250,24 @@ let private runGitProcess ) | _ -> () + // One decoder per stream keeps a multi-byte character that spans two chunks whole. + let stdoutDecoder = createUtf8StringDecoder () + let stderrDecoder = createUtf8StringDecoder () + + let observeStdout (text: string) = + output.OnStdout text + commandOutput |> Option.iter (fun command -> command.ObserveStdout text) + + let observeStderr (text: string) = + stderrChunks.Add text + output.OnStderr text + commandOutput |> Option.iter (fun command -> command.ObserveStderr text) + proc?stdout?on ( "data", fun d -> resetIdleTimer () - let text = d?toString ("utf8") |> unbox - onOutput text + observeStdout (decodeUtf8Chunk stdoutDecoder d) if captureStdout then stdoutChunks.Add d @@ -221,9 +278,7 @@ let private runGitProcess "data", fun d -> resetIdleTimer () - let text = d?toString ("utf8") |> unbox - stderrChunks.Add text - onOutput text + observeStderr (decodeUtf8Chunk stderrDecoder d) ) |> ignore @@ -262,6 +317,13 @@ let private runGitProcess proc?on ( "close", fun code -> + if not finished then + for decoder, observe in [ stdoutDecoder, observeStdout; stderrDecoder, observeStderr ] do + let tail = finishUtf8Decoding decoder + + if not (String.IsNullOrEmpty tail) then + observe tail + finish (if isNull code then -1 else int (unbox code)) ) |> ignore @@ -299,41 +361,50 @@ let private runGitProcess } /// Runs `git` without a shell and captures stdout/stderr for callers that need exact output or stdin support. -let runGitCaptured (request: GitSpawnRequest) : Promise = runGitProcess true ignore ignore request +let runGitCaptured (request: GitSpawnRequest) : Promise = runGitProcess true ignore OutputObservers.none request /// Runs `git` with a notification after the child process and its cancellation handlers are active. let runGitCapturedWithStarted (onStarted: unit -> unit) (request: GitSpawnRequest) : Promise = - runGitProcess true onStarted ignore request + runGitProcess true onStarted OutputObservers.none request /// Assembly-internal streaming variant used by explicit LFS transfers so /// provider progress originates from the real child process. let internal runGitCapturedWithOutput - (onOutput: string -> unit) + (output: OutputObservers) (request: GitSpawnRequest) : Promise = - runGitProcess true ignore onOutput request + runGitProcess true ignore output request /// Assembly-internal streaming variant used by maintenance operations so /// provider progress originates from the real child process. let internal runGitCapturedWithStartedAndOutput (onStarted: unit -> unit) - (onOutput: string -> unit) + (output: OutputObservers) (request: GitSpawnRequest) : Promise = - runGitProcess true onStarted onOutput request + runGitProcess true onStarted output request /// Runs `git` while draining and discarding stdout. /// This is used for commands such as `git lfs smudge`, whose stdout may contain a large file. -let runGitDiscardingStdout (request: GitSpawnRequest) : Promise = runGitProcess false ignore ignore request +let runGitDiscardingStdout (request: GitSpawnRequest) : Promise = runGitProcess false ignore OutputObservers.none request let runGitDiscardingStdoutWithStarted (onStarted: unit -> unit) (request: GitSpawnRequest) : Promise = - runGitProcess false onStarted ignore request + runGitProcess false onStarted OutputObservers.none request + +/// Drains and discards stdout like runGitDiscardingStdoutWithStarted, and still hands every chunk of both +/// streams to the observers, so the meters of a transfer reach the caller although its stdout is not kept. +let internal runGitDiscardingStdoutWithStartedAndOutput + (onStarted: unit -> unit) + (output: OutputObservers) + (request: GitSpawnRequest) + : Promise = + runGitProcess false onStarted output request /// Runs a small git command and returns stdout text, or None on command failure. /// Used for feature probes where failure should not surface as a user-facing Git error. @@ -346,6 +417,7 @@ let tryExecGitText (workingDirectory: string option) (timeoutMs: int) (args: str StandardInput = None CancelCheck = None TimeoutMs = Some timeoutMs + Output = None } if result.ExitCode = 0 && not result.TimedOut then @@ -390,6 +462,7 @@ let checkFilterAttributes StandardInput = Some(String.concat "\000" (relativePaths |> Seq.distinct |> Seq.toArray)) CancelCheck = None TimeoutMs = Some repoValidationTimeoutMs + Output = None } if result.ExitCode <> 0 || result.TimedOut then @@ -468,7 +541,7 @@ type NodeGitLfsAdapter() = runGitProcess true ignore - onProgress + (OutputObservers.both onProgress) { WorkingDirectory = workingDirectory Arguments = args |> List.toArray @@ -476,6 +549,7 @@ type NodeGitLfsAdapter() = StandardInput = None CancelCheck = Some cancelCheck TimeoutMs = timeoutMs + Output = None } return { diff --git a/src/VersionControlService.Git/Git/GitLfsService.fs b/src/VersionControlService.Git/Git/GitLfsService.fs index b06f69d..c443b25 100644 --- a/src/VersionControlService.Git/Git/GitLfsService.fs +++ b/src/VersionControlService.Git/Git/GitLfsService.fs @@ -17,6 +17,7 @@ module GitCredentialStrategy = VersionControlService.Git.GitCredentialStrategy module NodeFileSystem = VersionControlService.Runtime.Node.FileSystem module NodePath = VersionControlService.Runtime.Node.Path module NodeProcess = VersionControlService.Runtime.Node.Process +module NodeOutput = VersionControlService.Runtime.Node.OutputReporter /// Default timeout for interactive Git LFS commands launched by the service process. [] @@ -91,6 +92,27 @@ let tryFindLsFileInfoByRelativePath (filesByRelativePath: Dictionary) : string -> GitLfsLsFileInfo option = + let byComparisonKey = Dictionary() + + for entry in filesByRelativePath do + let comparisonKey = PathHelpers.normalizeForComparison entry.Key + + if not (byComparisonKey.ContainsKey comparisonKey) then + byComparisonKey[comparisonKey] <- entry.Value + + fun relativePath -> + let normalizedPath = PathHelpers.normalizeSeparators relativePath + + match filesByRelativePath.TryGetValue normalizedPath with + | true, info -> Some info + | false, _ -> + match byComparisonKey.TryGetValue(PathHelpers.normalizeForComparison normalizedPath) with + | true, info -> Some info + | false, _ -> None + let buildLsFilesJsonArgs () = [| "lfs"; "ls-files"; "-j" |] /// Chooses the most useful text from a Git LFS adapter result for user-facing errors. @@ -114,6 +136,24 @@ let isMissingOnRemote (output: string) = || output.IndexOf("remote missing object", StringComparison.OrdinalIgnoreCase) >= 0 || Regex.IsMatch(output, @"\[[0-9a-f]{64}\][^\r\n]*\[404\]")) +/// Object ids that fetch output reports as missing on the remote. A line counts when +/// isMissingOnRemote accepts it, and every 64-digit hex token on it is an id. +let missingOnRemoteObjectIds (output: string) : Set = + let isHexDigit (character: char) = + (character >= '0' && character <= '9') || (character >= 'a' && character <= 'f') + + if String.IsNullOrWhiteSpace output then + Set.empty + else + output.Split([| '\r'; '\n' |], StringSplitOptions.RemoveEmptyEntries) + |> Array.filter isMissingOnRemote + |> Array.collect (fun line -> + line + |> String.map (fun character -> if isHexDigit character then character else ' ') + |> fun hexOnly -> hexOnly.Split([| ' ' |], StringSplitOptions.RemoveEmptyEntries) + |> Array.filter (fun token -> token.Length = 64)) + |> Set.ofArray + let private redactDiagnosticText (text: string) = if String.IsNullOrWhiteSpace text then text @@ -171,6 +211,7 @@ let private requireGitLfsForLiteralPolicy (repoPath: string) : JS.Promise = promise { StandardInput = None CancelCheck = None TimeoutMs = Some DefaultTimeoutMs + Output = None } if result.ExitCode <> 0 || result.TimedOut then @@ -229,6 +271,7 @@ let tryHasStandaloneTransferAgent (repoPath: string) : JS.Promise = promis StandardInput = None CancelCheck = None TimeoutMs = Some 5000 + Output = None } return result.ExitCode = 0 && not result.TimedOut && not (String.IsNullOrWhiteSpace result.StdoutText) @@ -933,14 +976,14 @@ let readLsFilesByRelativePath try let! commandResult = runGitCapturedWithOutput - (fun _ -> + (OutputObservers.both (fun _ -> context.ReportProgress { PhaseCode = "lfs-list-transfer" Item = None Completed = Some 0.0 Total = None DisplayMessage = None - }) + })) { WorkingDirectory = Some normalizedRepoRoot Arguments = buildLsFilesJsonArgs () @@ -948,6 +991,8 @@ let readLsFilesByRelativePath StandardInput = None CancelCheck = Some context.Cancellation.IsCancellationRequested TimeoutMs = None + // The listing is JSON data, so only stderr reaches the output channel. + Output = NodeOutput.OutputTarget.ofContext context } if commandResult.ExitCode <> 0 || commandResult.TimedOut then @@ -1025,7 +1070,7 @@ let storageDedupArgs = [| "lfs"; "dedup" |] /// git-lfs has no working escape for these characters. /// The root-anchored pattern can also match a few files whose names differ only at special characters. -/// A download checks for such files with pathPatternMatchesOtherListedPath. +/// A download checks for such files with pathPatternMatchesIndexedPath. let lfsPathPattern (path: string) : string = let pattern = path @@ -1036,18 +1081,13 @@ let lfsPathPattern (path: string) : string = "/" + pattern -/// Tells whether a pattern from lfsPathPattern matches a repository path. A `?` matches one -/// character other than `/`, and every other character matches itself. The leading `/` anchors -/// the pattern at the root. The comparison ignores case, and a pattern that matches a directory -/// also matches the files below it. Both err toward reporting a match, which only costs the -/// caller the slower exact-object download. -let lfsPathPatternMatches (pattern: string) (path: string) : bool = - let body = - (if pattern.StartsWith("/", StringComparison.Ordinal) then pattern.Substring 1 else pattern) - .ToLowerInvariant() - - let candidate = (PathHelpers.normalizeSeparators path).ToLowerInvariant() +/// The pattern without its leading `/`, in lower case. +let private lfsPatternBody (pattern: string) : string = + (if pattern.StartsWith("/", StringComparison.Ordinal) then pattern.Substring 1 else pattern) + .ToLowerInvariant() +/// The matching of lfsPathPatternMatches on a pattern body and a path that are both in lower case. +let private lfsPathPatternMatchesLowered (body: string) (candidate: string) : bool = let rec matchesFrom index = if index = body.Length then true @@ -1063,28 +1103,72 @@ let lfsPathPatternMatches (pattern: string) (path: string) : bool = && matchesFrom 0 && (candidate.Length = body.Length || candidate.[body.Length] = '/') -/// Tells whether the path pattern of `relativePath` also matches another path in the LFS listing. -let pathPatternMatchesOtherListedPath - (filesByRelativePath: Dictionary) - (relativePath: string) - : bool = - let pattern = lfsPathPattern relativePath - let normalizedPath = PathHelpers.normalizeSeparators relativePath +/// Tells whether a pattern from lfsPathPattern matches a repository path. A `?` matches one +/// character other than `/`, and every other character matches itself. The leading `/` anchors +/// the pattern at the root. The comparison ignores case, and a pattern that matches a directory +/// also matches the files below it. Both err toward reporting a match, which only costs the +/// caller the slower exact-object download. +let lfsPathPatternMatches (pattern: string) (path: string) : bool = + lfsPathPatternMatchesLowered (lfsPatternBody pattern) ((PathHelpers.normalizeSeparators path).ToLowerInvariant()) + +/// Lower-case views of listed paths. They are built once, so that many paths can ask whether their +/// pattern matches a listed path without scanning the listing each time. +type ListedPathIndex = { + /// Every listed path, in listing order. + LowerPaths: string[] + LowerPathSet: HashSet + /// Every directory above a listed path. + LowerDirectories: HashSet +} - filesByRelativePath.Keys - |> Seq.exists (fun listedPath -> - not (String.Equals(listedPath, normalizedPath, StringComparison.Ordinal)) - && lfsPathPatternMatches pattern listedPath) +/// Indexes the listed paths that a pattern may match. A caller leaves out the paths it asks about, so that +/// a path never matches itself. +let createListedPathIndex (listedPaths: string seq) : ListedPathIndex = + let lowerPaths = + listedPaths + |> Seq.map (fun listedPath -> (PathHelpers.normalizeSeparators listedPath).ToLowerInvariant()) + |> Seq.toArray -let buildFetchRefetchArgs (dryRun: bool) (relativePath: string) = + let directories = HashSet() + + for lowerPath in lowerPaths do + let mutable separator = lowerPath.IndexOf '/' + + while separator >= 0 do + directories.Add(lowerPath.Substring(0, separator)) |> ignore + separator <- lowerPath.IndexOf('/', separator + 1) + + { + LowerPaths = lowerPaths + LowerPathSet = HashSet(lowerPaths) + LowerDirectories = directories + } + +/// Tells whether the path pattern of `relativePath` also matches a path of the index. Only a path with a +/// character that lfsPathPattern turns into a wildcard needs the scan. Any other pattern matches a +/// listed path that equals it, or lies below it as a directory, ignoring case. +let pathPatternMatchesIndexedPath (index: ListedPathIndex) (relativePath: string) : bool = + let body = lfsPatternBody (lfsPathPattern relativePath) + + if relativePath.IndexOfAny([| '*'; '?'; '['; ']'; '{'; '}'; ',' |]) >= 0 then + index.LowerPaths |> Array.exists (fun lowerPath -> lfsPathPatternMatchesLowered body lowerPath) + else + index.LowerPathSet.Contains body || index.LowerDirectories.Contains body + +/// The fixed arguments of a refetch. The comma-joined include patterns of lfsPathPattern follow them. +let buildFetchRefetchArgsForPaths (dryRun: bool) (relativePaths: string[]) = let dryRunArguments = if dryRun then [| "--dry-run" |] else [||] + let includePatterns = relativePaths |> Array.map lfsPathPattern |> String.concat "," Array.concat [| [| "lfs"; "fetch"; "--refetch" |] dryRunArguments - [| $"--include={lfsPathPattern relativePath}"; "origin"; "HEAD" |] + [| $"--include={includePatterns}"; "origin"; "HEAD" |] |] +let buildFetchRefetchArgs (dryRun: bool) (relativePath: string) = + buildFetchRefetchArgsForPaths dryRun [| relativePath |] + /// A configured lfs.fetchexclude wins over --include, so the fetch clears it. The override goes /// through git's GIT_CONFIG_COUNT variables (git 2.31 or newer), which git-lfs reads as config. let withFetchExcludeCleared (environment: obj) : obj = @@ -1111,6 +1195,16 @@ let dryRunCoversObject (output: string) (oid: string) : bool = output.Split '\n' |> Array.exists (fun line -> line.Trim().StartsWith(prefix, StringComparison.Ordinal)) +/// The text of a failed dry run without its listing lines. A listing line holds an object id and a +/// path, and either can contain a word that the failure classification reads as the cause. A text with +/// nothing but listing lines stays as it is, so the failure keeps a message. +let dropDryRunListingLines (text: string) : string = + let remaining = + text.Split([| '\r'; '\n' |], StringSplitOptions.RemoveEmptyEntries) + |> Array.filter (fun line -> not (Regex.IsMatch(line, @"^\s*fetch [0-9a-f]{64} => "))) + + if remaining.Length = 0 then text else String.concat "\n" remaining + let private buildSmudgePointerArgs (relativePath: string) = [| "-c" "lfs.fetchinclude=" @@ -1127,27 +1221,35 @@ let private buildPointerInput (listing: GitLfsLsFileInfo) = $"version {listing.version}\noid {listing.``oid_type``}:{listing.oid}\nsize {sizeText}\n" -let private buildDownloadObjectArgs (relativePath: string) = [| - "-c" - "lfs.fetchrecentalways=false" - "lfs" - "fetch" - $"--include={lfsPathPattern relativePath}" - "origin" - "HEAD" -|] +/// git-lfs reads one comma-separated list from --include and keeps only the last of repeated +/// flags. lfsPathPattern never leaves a comma in a pattern, so joining the patterns is safe. +let buildDownloadObjectArgs (relativePaths: string[]) = + let includePatterns = relativePaths |> Array.map lfsPathPattern |> String.concat "," + + [| + "-c" + "lfs.fetchrecentalways=false" + "lfs" + "fetch" + $"--include={includePatterns}" + "origin" + "HEAD" + |] let private extractSpawnFailureMessage (result: GitSpawnResult) = + // Forced progress puts meter lines into either stream, and they say nothing about the cause. let stderrText = result.StderrText |> Option.ofObj |> Option.defaultValue String.Empty + |> NodeProcess.dropProgressMeterLines |> _.Trim() let stdoutText = result.StdoutText |> Option.ofObj |> Option.defaultValue String.Empty + |> NodeProcess.dropProgressMeterLines |> _.Trim() if result.TimedOut then @@ -1162,26 +1264,138 @@ let private extractSpawnFailureMessage (result: GitSpawnResult) = else "Git command failed." -let buildCheckoutArgs (relativePath: string) = [| "lfs"; "checkout"; "--"; lfsPathPattern relativePath |] +let private indexUpdateFailureMarker = "Error updating the Git index" + +/// True when the text carries the index error of a `git lfs checkout`. The failure mapping of the batch +/// callers reads it to tell that git-lfs wrote its files before it failed. +let internal mentionsIndexUpdateFailure (text: string) : bool = + not (isNull text) && text.IndexOf(indexUpdateFailureMarker, StringComparison.Ordinal) >= 0 + +/// The error text of a `git lfs checkout` that wrote its files but could not update the Git index. +/// With a held index.lock, git-lfs 3.7.0 prints "Error updating the Git index:" to stderr and still exits +/// with 0. The files then read as modified and the lock stays, so the exit code alone reports success for +/// a failed run. The error stream is read before the output stream, and meter lines are dropped from both. +let lfsCheckoutIndexUpdateFailed (stdout: string) (stderr: string) : string option = + [| stderr; stdout |] + |> Array.tryPick (fun stream -> + let text = + stream + |> Option.ofObj + |> Option.defaultValue String.Empty + |> NodeProcess.dropProgressMeterLines + |> _.Trim() + + if mentionsIndexUpdateFailure text then Some text else None) + +/// The arguments that ask Git for the path of the index lock. Every lookup of a held lock uses them, +/// whichever runner executes them. +let internal heldIndexLockArguments = [| "rev-parse"; "--git-path"; "index.lock" |] + +/// The path of the index lock when its file exists. `gitPathOutput` is the stdout of +/// `heldIndexLockArguments` run in `repoPath`, and a relative answer is relative to it. +let internal heldIndexLockPath (repoPath: string) (gitPathOutput: string) : string option = + let rawPath = gitPathOutput |> Option.ofObj |> Option.defaultValue String.Empty |> _.Trim() + + if String.IsNullOrWhiteSpace rawPath then + None + else + let lockPath = NodePath.resolve [| repoPath; rawPath |] + + if NodeFileSystem.existsSync lockPath then Some lockPath else None -// Checkout has no timeout or cancellation because git-lfs holds the index lock while it refreshes the index. -// Stopping it midway leaves a stale lock and a checked-out file. -let checkoutPath (repoPath: string) (relativePath: string) : JS.Promise> = promise { +/// Looks for a held index lock through Git, so a linked worktree reports its own lock path. The lookup +/// has no cancellation, because it runs after a checkout that a cancel could not stop. A lookup that +/// fails finds nothing. +let internal tryFindHeldIndexLock (repoPath: string) : JS.Promise = promise { let! result = runGitCaptured { WorkingDirectory = Some repoPath - Arguments = buildCheckoutArgs relativePath + Arguments = heldIndexLockArguments Environment = None StandardInput = None CancelCheck = None - TimeoutMs = None + TimeoutMs = Some DefaultTimeoutMs + Output = None } return if result.ExitCode = 0 && not result.TimedOut then - Ok() + heldIndexLockPath repoPath result.StdoutText else - Error(exn (extractSpawnFailureMessage result)) + None +} + +/// The same lookup through the git runner of the caller, which also applies the context of the caller. +/// A lookup that fails finds nothing. +let internal tryFindHeldIndexLockWith + (runGit: string[] -> Async>) + (repoPath: string) + : Async = + async { + let! result = runGit heldIndexLockArguments + + match result with + | Ok output when output.ExitCode = 0 -> return heldIndexLockPath repoPath output.StdOut + | _ -> return None + } + +/// Git-lfs ends its index error without the lock message of Git, so the text alone does not name the +/// lock. With a held lock, the text gets that message in Git's words, which the failure mapping of the +/// callers reads to report the lock. +let internal withHeldIndexLockMessage (text: string) (lockPath: string option) : string = + match lockPath with + | Some path -> $"{text}\nfatal: Unable to create '{path}': File exists." + | None -> text + +/// The fixed arguments of `git lfs checkout`. The patterns of lfsPathPattern follow them. +let checkoutArgsPrefix = [| "lfs"; "checkout"; "--" |] + +let buildCheckoutArgs (relativePath: string) = + Array.append checkoutArgsPrefix [| lfsPathPattern relativePath |] + +/// Output observers that report the meters of both streams as progress under one phase code. The +/// returned function flushes their line buffers once the process has ended. +let internal createPhaseMeterOutput + (phaseCode: string) + (reportProgress: OperationProgress -> unit) + : OutputObservers * (unit -> unit) = + OutputObservers.meters (fun line -> + NodeProcess.tryParseProgressMeter line + |> Option.iter (NodeProcess.progressOfMeter phaseCode >> reportProgress)) + +// Checkout has no timeout or cancellation because git-lfs holds the index lock while it refreshes the index. +// Stopping it midway leaves a stale lock and a checked-out file. +let checkoutPatterns + (repoPath: string) + (patterns: string[]) + (reportProgress: OperationProgress -> unit) + (outputTarget: NodeOutput.OutputTarget option) + : JS.Promise> = promise { + let output, flushOutput = createPhaseMeterOutput "lfs-materialize-checkout" reportProgress + + let! result = + runGitCapturedWithOutput output { + WorkingDirectory = Some repoPath + Arguments = Array.append checkoutArgsPrefix patterns + Environment = Some(withForcedLfsProgress (createNonInteractiveEnv ())) + StandardInput = None + CancelCheck = None + TimeoutMs = None + // The stdout of `lfs checkout` is its transfer summary, so it is diagnostic text. + Output = NodeOutput.OutputTarget.withStdout outputTarget + } + + flushOutput () + + if result.ExitCode = 0 && not result.TimedOut then + match lfsCheckoutIndexUpdateFailed result.StdoutText result.StderrText with + | None -> return Ok() + | Some text when text.IndexOf("index.lock", StringComparison.Ordinal) >= 0 -> return Error(exn text) + | Some text -> + let! heldLock = tryFindHeldIndexLock repoPath + return Error(exn (withHeldIndexLockMessage text heldLock)) + else + return Error(exn (extractSpawnFailureMessage result)) } let private resolvePushRefSpec @@ -1426,7 +1640,7 @@ let private createMaintenanceOutputObserver (progressCallback: (GitProgressDto - }) | None -> () - NodeProcess.createMeterObserver reportLine + OutputObservers.meters reportLine /// Runs a maintenance command with authentication and streams its real process progress. /// `onStarted` fires only after the child process can observe cancellation. @@ -1451,6 +1665,7 @@ let internal runAuthenticatedMaintenance StandardInput = None CancelCheck = Some cancelCheck TimeoutMs = None + Output = None } flushOutput () @@ -1462,13 +1677,14 @@ let internal runAuthenticatedMaintenance Error(exn (extractSpawnFailureMessage result)) } -let fetchRefetchForPath +let fetchRefetchForPaths (repoPath: string) (commandAuth: GitCommandAuthentication) - (relativePath: string) + (relativePaths: string[]) (dryRun: bool) (cancelCheck: (unit -> bool) option) (onStarted: unit -> unit) + (outputTarget: NodeOutput.OutputTarget option) : JS.Promise> = promise { let! result = @@ -1479,11 +1695,13 @@ let fetchRefetchForPath Arguments = GitCredentialStrategy.buildLfsTransferArguments commandAuth.ConfigArgs - (buildFetchRefetchArgs dryRun relativePath) + (buildFetchRefetchArgsForPaths dryRun relativePaths) Environment = Some(withFetchExcludeCleared commandAuth.Environment) StandardInput = None CancelCheck = cancelCheck TimeoutMs = None + // The stdout of the dry run is a listing of objects, so only stderr is reported. + Output = outputTarget } return @@ -1501,43 +1719,60 @@ let fetchRefetchForPath else outputMessage - Error(exn failureMessage) + Error(exn (if dryRun then dropDryRunListingLines failureMessage else failureMessage)) } -/// Downloads the object of `listing` into the local cache. -/// By default one fetch of the path pattern downloads it. The pattern can also match files whose -/// names differ from the requested one only at special characters. For those, `exactObjectOnly` -/// switches to `git lfs smudge`, which downloads only the object named in the pointer on stdin. -let downloadObjectFromListing +/// Chooses how downloadObjects fetches objects into the local cache. +type ObjectDownload = + /// One fetch for the path patterns of these paths. + | FetchPaths of relativePaths: string[] + /// One `git lfs smudge` for the object named by the listing. A fetch of the path pattern also + /// downloads files whose names differ from the requested one only at special characters, + /// and the smudge takes just this object. + | SmudgeObject of relativePath: string * listing: GitLfsLsFileInfo + +/// Downloads objects into the local cache. +let downloadObjects (repoPath: string) (commandAuth: GitCommandAuthentication) - (relativePath: string) - (listing: GitLfsLsFileInfo) - (exactObjectOnly: bool) + (download: ObjectDownload) (cancelCheck: (unit -> bool) option) + (reportProgress: OperationProgress -> unit) (onStarted: unit -> unit) + (outputTarget: NodeOutput.OutputTarget option) : JS.Promise> = promise { let transferEnvironment = withFetchExcludeCleared commandAuth.Environment - let arguments, standardInput, environment = - if exactObjectOnly then + // Only the fetch reports meters. The smudge moves a single object, and its stdout holds the file content. + let arguments, standardInput, environment, (output, flushOutput), spawnOutput = + match download with + | SmudgeObject(relativePath, listing) -> buildSmudgePointerArgs relativePath, Some(buildPointerInput listing), - withLfsSmudgeEnabled transferEnvironment - else - buildDownloadObjectArgs relativePath, None, transferEnvironment + withLfsSmudgeEnabled transferEnvironment, + (OutputObservers.none, ignore), + outputTarget + | FetchPaths relativePaths -> + buildDownloadObjectArgs relativePaths, + None, + withForcedLfsProgress transferEnvironment, + createPhaseMeterOutput "lfs-materialize-transfer" reportProgress, + NodeOutput.OutputTarget.withStdout outputTarget let! result = - runGitDiscardingStdoutWithStarted onStarted { + runGitDiscardingStdoutWithStartedAndOutput onStarted output { WorkingDirectory = Some repoPath Arguments = GitCredentialStrategy.buildLfsTransferArguments commandAuth.ConfigArgs arguments Environment = Some environment StandardInput = standardInput CancelCheck = cancelCheck TimeoutMs = None + Output = spawnOutput } + flushOutput () + return if result.ExitCode = 0 && not result.TimedOut then Ok() @@ -1574,6 +1809,7 @@ let private filterResolvableRemoteTipIds StandardInput = Some(String.concat "\n" [| yield! distinctRemoteTipIds; yield "" |]) CancelCheck = None TimeoutMs = Some DefaultTimeoutMs + Output = None } if batchCheckResult.ExitCode <> 0 then @@ -1673,6 +1909,7 @@ let private tryGetOptimizedLfsObjectIds StandardInput = Some(buildRevListStandardInput refSpec remoteTipIds) CancelCheck = None TimeoutMs = Some DefaultTimeoutMs + Output = None } if revListResult.ExitCode <> 0 then @@ -1696,6 +1933,7 @@ let private tryGetOptimizedLfsObjectIds StandardInput = Some(String.concat "\n" [| yield! candidateBlobIds; yield "" |]) CancelCheck = None TimeoutMs = Some DefaultTimeoutMs + Output = None } if catFileResult.ExitCode <> 0 then @@ -1733,6 +1971,7 @@ let private getOutboundObjectIdsFromRemoteTips StandardInput = Some(buildRevListStandardInput refSpec remoteTipIds) CancelCheck = None TimeoutMs = Some DefaultTimeoutMs + Output = None } if revListResult.ExitCode = 0 then @@ -1856,6 +2095,7 @@ let uploadObjects (remoteName: string) (refSpec: string) (lfsObjectIds: string[]) + (outputTarget: NodeOutput.OutputTarget option) : JS.Promise> = promise { if lfsObjectIds.Length = 0 then @@ -1866,10 +2106,7 @@ let uploadObjects // stdout is a pipe, so request live progress explicitly. Git LFS otherwise // suppresses updates and its asynchronous final summary can race process exit. // Keep this override local to the upload without changing the caller's auth env. - let uploadEnvironment: obj = - Fable.Core.JsInterop.emitJsExpr - commandAuth.Environment - "({ ...$0, GIT_LFS_FORCE_PROGRESS: '1' })" + let uploadEnvironment = withForcedLfsProgress commandAuth.Environment let! exactUploadResult = runSpawnedGit { @@ -1882,6 +2119,8 @@ let uploadObjects StandardInput = Some(String.concat "\n" [| yield! lfsObjectIds; yield "" |]) CancelCheck = Some cancelCheck TimeoutMs = None + // The stdout of `lfs push` is its transfer summary, so it is diagnostic text. + Output = NodeOutput.OutputTarget.withStdout outputTarget } if exactUploadResult.ExitCode = 0 then @@ -1901,6 +2140,7 @@ let uploadObjects StandardInput = None CancelCheck = Some cancelCheck TimeoutMs = None + Output = NodeOutput.OutputTarget.withStdout outputTarget } return diff --git a/src/VersionControlService.Git/Git/GitService.fs b/src/VersionControlService.Git/Git/GitService.fs index d5cd28f..c9dad6e 100644 --- a/src/VersionControlService.Git/Git/GitService.fs +++ b/src/VersionControlService.Git/Git/GitService.fs @@ -18,6 +18,7 @@ open VersionControlService.Git.GitInternals module FileSystem = VersionControlService.Runtime.Node.FileSystem module NodeProcess = VersionControlService.Runtime.Node.Process +module NodeOutput = VersionControlService.Runtime.Node.OutputReporter module NodeCancellation = VersionControlService.Runtime.Node.Cancellation module GitCredentialStrategy = VersionControlService.Git.GitCredentialStrategy @@ -103,6 +104,14 @@ let classifyFailureKind (message: string) = && (lfsExecutableMissingTokens |> Array.exists line.Contains) ) + // A server that closes the connection mid-request gives "batch response: Post ...: EOF". + // A bare EOF elsewhere says nothing about the network. + let batchResponseEndsWithEof = + normalizedMessage.Split([| '\r'; '\n' |], StringSplitOptions.RemoveEmptyEntries) + |> Array.exists (fun line -> + line.Contains("batch response:") && line.TrimEnd().EndsWith(": eof", StringComparison.Ordinal) + ) + if containsAny lfsInstallRequiredTokens || (containsAny lfsFilterFailureTokens && gitLfsExecutableCouldNotStart) @@ -122,7 +131,7 @@ let classifyFailureKind (message: string) = // Process kills are classified structurally before any text reaches this function. elif containsAny [| "cancelled"; "canceled" |] then GitFailureKind.Canceled - elif containsAny [| "timed out"; "timeout"; "time out" |] then + elif containsAny [| "timed out"; "timeout"; "time out"; "did not properly respond" |] then GitFailureKind.Timeout elif containsAny [| "forbidden"; "403" |] then GitFailureKind.Forbidden @@ -144,8 +153,12 @@ let classifyFailureKind (message: string) = "failed to connect" "connection reset" "connection refused" + "actively refused" + "forcibly closed" + "no such host" "unable to access" |] + || batchResponseEndsWithEof then GitFailureKind.Network else @@ -555,6 +568,7 @@ let private resolveLfsBackupDirectory (arcPath: string) : JS.Promise Option.ofObj |> Option.defaultValue String.Empty |> _.Trim() @@ -643,17 +657,10 @@ let private removeTemporaryLfsBackup backupPath = if existsSync backupPath then unlinkSync backupPath -let private canceledLfsResult<'T> () : GitResult<'T> = - Error(createFailure GitFailureKind.Canceled "Git LFS operation canceled.") +let private canceledLfsFailure () : GitFailure = + createFailure GitFailureKind.Canceled "Git LFS operation canceled." -let private isPathCleanInStatus (status: StatusResult) (relativePath: string) = - valueOrEmptyArray status.files - |> Array.exists (fun fileStatus -> - String.Equals(fileStatus.path, relativePath, StringComparison.Ordinal) - || (fileStatus.``from`` - |> Option.exists (fun original -> String.Equals(original, relativePath, StringComparison.Ordinal))) - ) - |> not +let private canceledLfsResult<'T> () : GitResult<'T> = Error(canceledLfsFailure ()) let private ensureFileMatchesLfsOid (filePath: string) @@ -669,6 +676,7 @@ let private ensureFileMatchesLfsOid StandardInput = None CancelCheck = Some context.Cancellation.IsCancellationRequested TimeoutMs = None + Output = NodeOutput.OutputTarget.ofContext context } let generatedPointer = @@ -707,7 +715,8 @@ let private ensureFileMatchesLfsOid /// before the hash reveal a write that happened while it ran. let private moveVerifiedFileToLfsBackup (arcPath: string) - (safePath: string) + (gitPath: string) + (displayPath: string) (absolutePath: string) (listing: GitLfsLsFileInfo) (context: OperationContext) @@ -730,11 +739,12 @@ let private moveVerifiedFileToLfsBackup let! pointerResult = runGitCaptured { WorkingDirectory = Some arcPath - Arguments = [| "cat-file"; "blob"; "HEAD:" + safePath |] + Arguments = [| "cat-file"; "blob"; "HEAD:" + gitPath |] Environment = None StandardInput = None CancelCheck = Some context.Cancellation.IsCancellationRequested TimeoutMs = Some GitLfsService.DefaultTimeoutMs + Output = NodeOutput.OutputTarget.ofContext context } if context.Cancellation.IsCancellationRequested() then @@ -751,7 +761,7 @@ let private moveVerifiedFileToLfsBackup else diagnostic - return errorResult (exn $"Could not read the committed LFS pointer for '{safePath}': {detail}") + return errorResult (exn $"Could not read the committed LFS pointer for '{displayPath}': {detail}") else match! resolveLfsBackupDirectory arcPath with | Error failure -> return Error failure @@ -773,14 +783,14 @@ let private moveVerifiedFileToLfsBackup || backupStats.mtimeMs <> statsBeforeHash.mtimeMs then match restoreTemporaryLfsBackup backupPath absolutePath pointerResult.StdoutText false with - | LfsBackupRetained -> return Error(lfsBackupRetainedFailure safePath backupPath) + | LfsBackupRetained -> return Error(lfsBackupRetainedFailure displayPath backupPath) | LfsBackupRestored -> - return errorResult (exn $"'{safePath}' changed while it was being freed. Try again.") + return errorResult (exn $"'{displayPath}' changed while it was being freed. Try again.") else return Ok(backupPath, statsBeforeHash, pointerResult.StdoutText) with error -> match restoreTemporaryLfsBackup backupPath absolutePath pointerResult.StdoutText false with - | LfsBackupRetained -> return Error(lfsBackupRetainedFailure safePath backupPath) + | LfsBackupRetained -> return Error(lfsBackupRetainedFailure displayPath backupPath) | LfsBackupRestored -> return errorResult error } @@ -1085,7 +1095,7 @@ let private runGitCapturedWithOutput progressCallback request = |> report) | None -> () - let observeOutput, flushOutput = NodeProcess.createMeterObserver reportLine + let observeOutput, flushOutput = GitLfsAdapter.OutputObservers.meters reportLine promise { let! result = GitLfsAdapter.runGitCapturedWithOutput observeOutput request @@ -1103,6 +1113,7 @@ let private getConfiguredLfsThresholdMb (arcPath: string) : JS.Promise bool) : JS.Promise> = promise { @@ -1828,7 +1840,7 @@ let prepareExplicitLfsPush applyCommandAuthentication (fun currentOptions -> createGit currentOptions - |> withGitOutputProgress progressCallback) + |> withGitOutput progressCallback outputTarget commandAuth.ConfigArgs) options commandAuth @@ -1836,7 +1848,7 @@ let prepareExplicitLfsPush applyCommandAuthentication (fun currentOptions -> createGit currentOptions - |> withGitOutputProgress progressCallback) + |> withGitOutput progressCallback outputTarget fetchAuth.ConfigArgs) options fetchAuth @@ -1846,6 +1858,8 @@ let prepareExplicitLfsPush { request with CancelCheck = Some cancelCheck + // A request that names its own target keeps it. The plan probes get stderr only. + Output = request.Output |> Option.orElse outputTarget } reportPhase progressCallback "lfs" "Checking Git LFS objects" @@ -1882,6 +1896,7 @@ let prepareExplicitLfsPush remoteName branchName objectIds + outputTarget return match uploadResult with @@ -2101,538 +2116,1478 @@ let private discardPathspecsWithOriginals (arcPath: string) (status: StatusResul Array.append safePathSpecs originalPaths |> Array.distinct -let private requireLfsListingForPath - (arcPath: string) - (safePath: string) - (context: OperationContext) - : JS.Promise = promise { - if context.Cancellation.IsCancellationRequested() then - return abortGitPromise "Git LFS operation canceled." +let private createMissingLfsAttributesFailure safePath actionDescription = + exn + $"'{safePath}' is listed by Git LFS, but the current .gitattributes does not register it. Restore Git LFS tracking for this path before {actionDescription}." + +let private createLfsCheckoutFailure safePath trackedByAttributes = + if not trackedByAttributes then + createMissingLfsAttributesFailure safePath "downloading it" else - match! GitLfsService.tryFindListingForPath arcPath safePath context with - | Ok listing -> return listing - | Error message -> return abortGitPromise $"'{safePath}' {message}" -} + exn $"Could not download '{safePath}' into the working tree." -let private getCleanLfsListingForPath +let private lfsFailure (message: string) : GitFailure = toFailure (exn message) + +/// The refusal of a path with local changes. Hosts decide by its kind, because the message names the path +/// and the path can carry words that the text classifier reads as another kind. +let private localChangesFailure (message: string) : GitFailure = + { + lfsFailure message with + Kind = GitFailureKind.LocalChanges + } + +/// Reads the status records of the `paths` that have changes, with one `git status` per chunk +/// of literal pathspecs. The read has no timeout and ends when the context is canceled. +let private readDirtyFiles (arcPath: string) - (safePath: string) - (dirtyMessage: string) + (paths: string[]) (context: OperationContext) - : JS.Promise> = - if context.Cancellation.IsCancellationRequested() then - promise { return canceledLfsResult () } - else - withCancellableLocalGit - arcPath - context.Cancellation - (fun git -> promise { - let! status = git.status () + : JS.Promise> = + withCancellableLocalGit + arcPath + context.Cancellation + (fun git -> promise { + let fixedArguments = + [| "status"; "--porcelain=v2"; "-z"; "--untracked-files=all"; "--" |] + + let chunks = + GitPathTransport.chunkArguments fixedArguments (literalPathspecsFromStrings paths |> Array.distinct) + + let dirtyFiles = ResizeArray() + + for chunk in chunks do + let! output = git.raw (Array.append fixedArguments chunk) if context.Cancellation.IsCancellationRequested() then - return abortGitPromise "Git LFS operation canceled." - elif not (isPathCleanInStatus status safePath) then - return abortGitPromise dirtyMessage - else - return! requireLfsListingForPath arcPath safePath context - }) + abortGitPromise "Git LFS operation canceled." -let private getCleanLfsFileForAction + dirtyFiles.AddRange (parsePorcelainV2StatusDto arcPath output).Files + + return dirtyFiles.ToArray() + }) + +/// The path of every status record and the source path of a rename, the names that +/// isPathCleanInStatus compares. +let private dirtyPathsOf (files: GitFileStatusDto[]) : Set = + files + |> Seq.collect (fun file -> + match file.OriginalPath with + | Some original -> [ file.Path; original ] + | None -> [ file.Path ]) + |> Set.ofSeq + +/// Reads which of `paths` have changes, with one `git status` per chunk of literal pathspecs. +let private readDirtyPaths (arcPath: string) - (requestedPath: string) - (dirtyMessageForSafePath: string -> string) + (paths: string[]) (context: OperationContext) - : JS.Promise> = promise { - if context.Cancellation.IsCancellationRequested() then - return canceledLfsResult () - else - match tryResolveArcRelativePath arcPath requestedPath with - | Error validationError -> return errorResult validationError - | Ok(safePath, absolutePath) -> - match! - getCleanLfsListingForPath - arcPath - safePath - (dirtyMessageForSafePath safePath) - context - with - | Error failure -> return Error failure - | Ok listing -> return Ok(safePath, absolutePath, listing) + : JS.Promise>> = promise { + let! filesResult = readDirtyFiles arcPath paths context + return filesResult |> Result.map dirtyPathsOf } -let private createMissingLfsAttributesFailure safePath actionDescription = - exn - $"'{safePath}' is listed by Git LFS, but the current .gitattributes does not register it. Restore Git LFS tracking for this path before {actionDescription}." - -let private checkPathTrackedByAttributes arcPath safePath : JS.Promise> = promise { - match! GitLfsAdapter.checkFilterAttributes arcPath [| safePath |] with - | Error message -> - return - Error( - createFailure - (classifyFailureKind message) - $"Could not inspect Git LFS attributes for '{safePath}': {message}" - ) +/// Reads which of `paths` the current .gitattributes registers with the lfs filter. +/// The error is the text of the failed check. +let private readLfsTrackedPaths (arcPath: string) (paths: string[]) : JS.Promise, string>> = promise { + match! GitLfsAdapter.checkFilterAttributes arcPath paths with + | Error message -> return Error message | Ok attributes -> return attributes - |> Array.tryFind (fun (path, _) -> path = safePath) - |> Option.exists (fun (_, value) -> value = "lfs") + |> Array.filter (fun (_, value) -> value = "lfs") + |> Array.map fst + |> Set.ofArray |> Ok } -let private createLfsCheckoutFailure safePath trackedByAttributes = - if not trackedByAttributes then - createMissingLfsAttributesFailure safePath "downloading it" - else - exn $"Could not download '{safePath}' into the working tree." +/// Resolves the directory that holds the local Git LFS objects. +let private resolveLfsMediaDirectory (arcPath: string) : JS.Promise> = promise { + let runGit (arguments: string[]) : Async> = async { + let! result = + runGitCaptured { + WorkingDirectory = Some arcPath + Arguments = arguments + Environment = None + StandardInput = None + CancelCheck = None + TimeoutMs = Some GitLfsService.DefaultTimeoutMs + Output = None + } + |> Async.AwaitPromise -let private failLfsCheckout arcPath safePath : JS.Promise = promise { - match! checkPathTrackedByAttributes arcPath safePath with - | Error failure -> return abortGitPromise failure.Message - | Ok trackedByAttributes -> - return abortGitPromiseWith (createLfsCheckoutFailure safePath trackedByAttributes) + let output: NodeProcess.ProcessOutput = { + ExitCode = result.ExitCode + StdOut = result.StdoutText + StdErr = result.StderrText + } + + return Ok output + } + + let! mediaDirectory = GitLfsObjects.resolveLocalMediaDirectory runGit arcPath |> Async.StartAsPromise + + match mediaDirectory with + | Ok directory -> return Ok directory + | Error failure -> return errorResult (exn failure.Message) } -let private requireDownloadedLfsFile - arcPath - safePath - absolutePath - (expectedListing: GitLfsLsFileInfo) +let private tryReadFileSize (absolutePath: string) : JS.Promise = promise { + try + let! stats = statAsync absolutePath + return Some stats.size + with _ -> + return None +} + +/// Tells whether the file at the path still holds a Git LFS pointer. A pointer has the size of a small +/// object, so a size check alone cannot tell the two apart. +let internal isLfsPointerFile (absolutePath: string) : bool = + try + (readFileSync absolutePath Utf8).StartsWith("version https://git-lfs", StringComparison.Ordinal) + with _ -> + false + +/// What a download did to one path. +type LfsPathEffect = + | Changed + | AlreadyInState + +/// The result of a download for one requested path. `Path` is the path as the caller passed it. +type LfsPathOutcome = { + Path: string + Result: Result +} + +/// A requested path that still needs its content. `Key` is the spelling of the Git LFS listing, +/// which git uses for status and for the fetch and checkout patterns. `SafePath` is the validated spelling of the +/// request, which messages and progress reports use. +type private LfsPathCandidate = { + Requested: string + SafePath: string + Key: string + AbsolutePath: string + Listing: GitLfsLsFileInfo +} + +type private LfsPathResults = Collections.Generic.Dictionary> + +let private groupLfsCandidatesByPattern (candidates: LfsPathCandidate[]) = + let groups = Collections.Generic.Dictionary>() + + for candidate in candidates do + let pattern = GitLfsService.lfsPathPattern candidate.Key + + match groups.TryGetValue pattern with + | true, group -> group.Add candidate + | false, _ -> + let group = ResizeArray() + group.Add candidate + groups[pattern] <- group + + groups + +/// Reports how many of the paths of a batch are done, so a caller can show "n of m files". The count is +/// the settled paths plus `pending`, files that wait only for a later check. A request with a single +/// distinct path reports nothing, and a count equal to the last report is skipped, so Completed only rises. +let private createLfsCountReporter + (phaseCode: string) + (reportProgress: OperationProgress -> unit) + (results: LfsPathResults) + (order: ResizeArray) + : int -> unit = + let lastCompleted = ref -1 + + fun pending -> + let completed = results.Count + pending + + if order.Count > 1 && completed <> lastCompleted.Value then + lastCompleted.Value <- completed + + reportProgress { + PhaseCode = phaseCode + Item = None + Completed = Some(float completed) + Total = Some(float order.Count) + DisplayMessage = None + } + +/// Downloads the objects of the candidates into the local cache. A download that fails does not +/// stop the others, because git-lfs still fetches the rest of its objects. `missingOnRemote` collects +/// the candidates whose object the remote lacks and `downloadErrors` the error of every other failed +/// download. The result is an error only when the operation was canceled. +let private downloadLfsObjects + (arcPath: string) + (session: AuthenticatedGitSession) + (exactCandidates: LfsPathCandidate[]) + (fetchCandidates: LfsPathCandidate[]) + (missingOnRemote: Collections.Generic.HashSet) + (downloadErrors: Collections.Generic.Dictionary) + (reportProgress: OperationProgress -> unit) (context: OperationContext) - = - promise { - let! finalListing = requireLfsListingForPath arcPath safePath context + : JS.Promise> = promise { + let cancelCheck = Some context.Cancellation.IsCancellationRequested + let outputTarget = NodeOutput.OutputTarget.ofContext context + let mutable canceled = false + + let reportTransfer (item: string option) () = + reportProgress { + PhaseCode = "lfs-materialize-transfer" + Item = item + Completed = None + Total = None + DisplayMessage = None + } - if context.Cancellation.IsCancellationRequested() then - return abortGitPromise "Git LFS operation canceled." - elif not finalListing.checkout then - return! failLfsCheckout arcPath safePath - else - let! finalStats = statAsync absolutePath - let expectedSize = int64 expectedListing.size - let actualSize = int64 finalStats.size + let recordFailure (candidates: LfsPathCandidate[]) (error: exn) = + let missingObjectIds = GitLfsService.missingOnRemoteObjectIds error.Message + // A failure of one path that names the missing content without an object id still belongs to that path. + let onlyPathMissing = candidates.Length = 1 && GitLfsService.isMissingOnRemote error.Message - if actualSize <> expectedSize then - return! failLfsCheckout arcPath safePath + for candidate in candidates do + if onlyPathMissing || missingObjectIds.Contains candidate.Listing.oid then + missingOnRemote.Add candidate.Requested |> ignore else - let untimedStatusGit = createUntimedOptions arcPath None None |> createGit - let! finalStatus = untimedStatusGit.status () + downloadErrors[candidate.Requested] <- toFailure error - if context.Cancellation.IsCancellationRequested() then - return abortGitPromise "Git LFS operation canceled." - elif not (isPathCleanInStatus finalStatus safePath) then - return! failLfsCheckout arcPath safePath + // A fetch of the path pattern also downloads files whose names differ only at special + // characters. A candidate with such a file takes only its own object. The checkout later still runs + // with the pattern, so it replaces that file's pointer when the file's own object is already cached. + for candidate in exactCandidates do + if not canceled then + let! result = + GitLfsService.downloadObjects + arcPath + session.CommandAuth + (GitLfsService.SmudgeObject(candidate.Key, candidate.Listing)) + cancelCheck + reportProgress + (reportTransfer (Some candidate.SafePath)) + outputTarget + + match result with + | _ when context.Cancellation.IsCancellationRequested() -> canceled <- true + | Ok() -> () + | Error error -> recordFailure [| candidate |] error + + if fetchCandidates.Length > 0 then + let groups = groupLfsCandidatesByPattern fetchCandidates + + let fixedArguments = + Array.append session.CommandAuth.ConfigArgs (GitLfsService.buildDownloadObjectArgs [||]) + + let patternChunks = GitPathTransport.chunkArguments fixedArguments (Seq.toArray groups.Keys) + + for patterns in patternChunks do + if not canceled then + let chunkCandidates = + patterns |> Array.collect (fun pattern -> groups[pattern].ToArray()) + + let item = + if chunkCandidates.Length = 1 then + Some chunkCandidates[0].SafePath + else + None + + let! result = + GitLfsService.downloadObjects + arcPath + session.CommandAuth + (GitLfsService.FetchPaths(chunkCandidates |> Array.map (fun candidate -> candidate.Key))) + cancelCheck + reportProgress + (reportTransfer item) + outputTarget + + match result with + | _ when context.Cancellation.IsCancellationRequested() -> canceled <- true + | Ok() -> () + | Error error -> recordFailure chunkCandidates error + + if canceled then + return canceledLfsResult () + else + return Ok() +} + +/// Runs `git lfs checkout` for the candidates, one command per chunk of patterns. The result holds +/// the candidates of the chunks that succeeded. A chunk that fails settles its candidates with the +/// failure. A cancellation before the first chunk is an error, and a later one settles the candidates +/// of the chunks that did not run. +let private checkoutLfsCandidates + (arcPath: string) + (candidates: LfsPathCandidate[]) + (results: LfsPathResults) + (reportProgress: OperationProgress -> unit) + (reportCount: int -> unit) + (context: OperationContext) + : JS.Promise> = promise { + let groups = groupLfsCandidatesByPattern candidates + + let chunks = + GitPathTransport.chunkArguments GitLfsService.checkoutArgsPrefix (Seq.toArray groups.Keys) + + let checkedOut = ResizeArray() + let mutable chunkIndex = 0 + let mutable stopped = false + let mutable canceledBeforeChange = false + + for patterns in chunks do + let chunkCandidates = patterns |> Array.collect (fun pattern -> groups[pattern].ToArray()) + + if stopped then + for candidate in chunkCandidates do + results[candidate.Requested] <- Error(canceledLfsFailure ()) + elif context.Cancellation.IsCancellationRequested() then + stopped <- true + + if chunkIndex = 0 then + canceledBeforeChange <- true + else + for candidate in chunkCandidates do + results[candidate.Requested] <- Error(canceledLfsFailure ()) + else + let! checkoutResult = + GitLfsService.checkoutPatterns + arcPath + patterns + reportProgress + (NodeOutput.OutputTarget.ofContext context) + + match checkoutResult with + | Error error -> + for candidate in chunkCandidates do + results[candidate.Requested] <- Error(toFailure error) + | Ok() -> checkedOut.AddRange chunkCandidates + + // The verification settles the checked-out files later, and they count as done from here. + reportCount checkedOut.Count + + chunkIndex <- chunkIndex + 1 + + if canceledBeforeChange then + return canceledLfsResult () + else + return Ok(checkedOut.ToArray()) +} + +/// Confirms that each checked-out candidate holds its content and settles it. A file passes when its +/// size equals the listed size and its path-limited status is clean. The files have changed by now, +/// so the checks ignore cancellation. +let private verifyLfsCandidates + (arcPath: string) + (candidates: LfsPathCandidate[]) + (results: LfsPathResults) + (reportProgress: OperationProgress -> unit) + (context: OperationContext) + : JS.Promise = promise { + if candidates.Length > 0 then + let uncancelableContext = { context with Cancellation = OperationCancellation.none } + + let! dirtyResult = + readDirtyPaths arcPath (candidates |> Array.map (fun candidate -> candidate.Key)) uncancelableContext + + match dirtyResult with + | Error failure -> + for candidate in candidates do + results[candidate.Requested] <- Error failure + | Ok dirtyPaths -> + let failed = ResizeArray() + + for candidate in candidates do + let! size = tryReadFileSize candidate.AbsolutePath + + let pointerLeftInPlace = + candidate.Listing.size <= 1024.0 && isLfsPointerFile candidate.AbsolutePath + + if + size = Some candidate.Listing.size + && not pointerLeftInPlace + && not (dirtyPaths.Contains candidate.Key) + then + results[candidate.Requested] <- Ok Changed + + reportProgress { + PhaseCode = "lfs-materialize" + Item = Some candidate.SafePath + Completed = Some candidate.Listing.size + Total = Some candidate.Listing.size + DisplayMessage = Some "Git LFS file materialized" + } else - return () - } + failed.Add candidate + + if failed.Count > 0 then + let! trackedResult = + readLfsTrackedPaths arcPath (failed |> Seq.map (fun candidate -> candidate.Key) |> Seq.toArray) + + for candidate in failed do + match trackedResult with + | Error message -> + results[candidate.Requested] <- + Error( + lfsFailure + $"Could not inspect Git LFS attributes for '{candidate.SafePath}': {message}" + ) + | Ok trackedPaths -> + results[candidate.Requested] <- + Error( + toFailure ( + createLfsCheckoutFailure candidate.SafePath (trackedPaths.Contains candidate.Key) + ) + ) +} -let private downloadMissingLfsFile - arcPath - safePath - absolutePath - listing - credentials - connectionProfileId - context +/// Downloads and checks out the candidates. The error is a failure of the whole operation. A +/// failure of one candidate goes into `results`. +let private downloadLfsCandidates + (arcPath: string) + (listing: Collections.Generic.Dictionary) + (candidates: LfsPathCandidate[]) + (credentials: GitCredentialStrategy.GitCredentialStrategy) + (connectionProfileId: string option) + (reportProgress: OperationProgress -> unit) + (context: OperationContext) + (results: LfsPathResults) + (reportCount: int -> unit) : JS.Promise> = promise { + for candidate in candidates do + reportProgress { + PhaseCode = "lfs-materialize" + Item = Some candidate.SafePath + Completed = Some 0.0 + Total = Some candidate.Listing.size + DisplayMessage = Some "Preparing Git LFS materialization" + } + if context.Cancellation.IsCancellationRequested() then return canceledLfsResult () else match! createOriginLfsRemoteSession arcPath credentials connectionProfileId None with | Error failure -> return Error failure | Ok session -> - // A fetch of the path pattern also downloads files whose names differ only at special - // characters. When the listing has such a file, the download takes only this object, so - // it adds no object for that file. The checkout below still runs with the pattern, so it - // replaces that file's pointer when the file's own object is already in the local cache. - let! fullListingResult = GitLfsService.readLsFilesByRelativePath arcPath context - - match fullListingResult with - | Error _ when context.Cancellation.IsCancellationRequested() -> return canceledLfsResult () - | Error message -> return errorResult (exn $"Could not read Git LFS file metadata: {message}") - | Ok _ when context.Cancellation.IsCancellationRequested() -> return canceledLfsResult () - | Ok fullListing -> - let exactObjectOnly = GitLfsService.pathPatternMatchesOtherListedPath fullListing safePath + let candidateKeys = + Collections.Generic.HashSet(candidates |> Array.map (fun candidate -> candidate.Key)) - match! - GitLfsService.downloadObjectFromListing + let otherListedIndex = + GitLfsService.createListedPathIndex (listing.Keys |> Seq.filter (fun key -> not (candidateKeys.Contains key))) + + let exactCandidates, fetchCandidates = + candidates + |> Array.partition (fun candidate -> + GitLfsService.pathPatternMatchesIndexedPath otherListedIndex candidate.Key) + + let missingOnRemote = Collections.Generic.HashSet() + let downloadErrors = Collections.Generic.Dictionary() + + match! + downloadLfsObjects + arcPath + session + exactCandidates + fetchCandidates + missingOnRemote + downloadErrors + reportProgress + context + with + | Error failure -> return Error failure + | Ok() -> + match! resolveLfsMediaDirectory arcPath with + | Error failure -> return Error failure + | Ok mediaDirectory -> + let downloaded = ResizeArray() + + for candidate in candidates do + // git-lfs treats an empty object as present without a file in the object directory. + let isAvailable = + candidate.Listing.size = 0.0 + || GitLfsObjects.isObjectLocallyAvailable + mediaDirectory + candidate.Listing.oid + candidate.Listing.size + + if missingOnRemote.Contains candidate.Requested then + results[candidate.Requested] <- + Error( + lfsFailure + $"The remote does not have the content of '{candidate.SafePath}'. Upload it from the computer that saved it." + ) + elif isAvailable then + downloaded.Add candidate + else + match downloadErrors.TryGetValue candidate.Requested with + | true, failure -> results[candidate.Requested] <- Error failure + | false, _ -> + results[candidate.Requested] <- + Error(lfsFailure $"Git LFS did not download '{candidate.SafePath}'.") + + // A file that left the working tree during the download stays gone. + // The checkout would create it again from the object. + let present = ResizeArray() + + for candidate in downloaded do + if (tryLstatSync candidate.AbsolutePath).IsNone then + results[candidate.Requested] <- + Error( + localChangesFailure + $"'{candidate.SafePath}' has local changes. Save, discard, or commit them before downloading the Git LFS file." + ) + else + present.Add candidate + + if present.Count = 0 then + return Ok() + else + match! + checkoutLfsCandidates arcPath (present.ToArray()) results reportProgress reportCount context + with + | Error failure -> return Error failure + | Ok checkedOut -> + do! verifyLfsCandidates arcPath checkedOut results reportProgress context + return Ok() +} + +/// Tells whether the working tree holds the content of the listed object at the path. Only a regular +/// file counts, and the hash is read only when the size equals the size of the object. +let private holdsLfsObjectContent (absolutePath: string) (listing: GitLfsLsFileInfo) : JS.Promise = promise { + try + match tryLstatSync absolutePath with + | Some stats when stats.isFile () && stats.size = listing.size -> + let! hashed = hashFileSha256Async absolutePath |> Async.StartAsPromise + return String.Equals(hashed.Sha256, listing.oid, StringComparison.OrdinalIgnoreCase) + | _ -> return false + with _ -> + return false +} + +/// Refreshes the index entries of the paths with `git add`. The clean filter of a Git LFS path turns +/// the file into the committed pointer, so the call stages nothing and only records the stat data of +/// the file. One call serves each chunk of paths. +let private refreshLfsIndexEntries (arcPath: string) (keys: string[]) : JS.Promise> = + withUntimedLocalGit arcPath None (fun git -> promise { + let fixedArguments = [| "add"; "--" |] + + for chunk in GitPathTransport.chunkArguments fixedArguments (literalPathspecsFromStrings keys) do + let! _ = git.raw (Array.append fixedArguments chunk) + () + }) + +/// Repairs the dirty paths whose only change is an index entry with the stat data of the pointer, which +/// a `git lfs checkout` leaves when it cannot take the index lock. Such a path has a modified working +/// tree and no staged change, its file holds the content of its object, and the current attributes still +/// register it with the lfs filter. Without the filter, `git add` would stage the file as a plain blob. +/// The result names the repaired paths, and they are clean afterwards. A path that fails any of the +/// checks stays dirty. +let private repairStaleLfsIndexEntries + (arcPath: string) + (dirtyFiles: GitFileStatusDto[]) + (listings: GitLfsLsFileInfo[]) + (context: OperationContext) + : JS.Promise>> = promise { + let staleKeys = + dirtyFiles + |> Array.filter (fun file -> file.Index = " " && file.WorkingDir = "M" && file.OriginalPath.IsNone) + |> Array.map (fun file -> file.Path) + |> Set.ofArray + + let holdingContent = ResizeArray() + + for listing in listings do + if staleKeys.Contains listing.name && not (context.Cancellation.IsCancellationRequested()) then + let! holdsContent = holdsLfsObjectContent (resolve [| arcPath; listing.name |]) listing + + if holdsContent then + holdingContent.Add listing.name + + // One attribute check serves all paths. A failed check repairs nothing, and the paths keep their local-changes failure. + let! trackedPaths = + promise { + if holdingContent.Count = 0 then + return Set.empty + else + match! readLfsTrackedPaths arcPath (holdingContent.ToArray()) with + | Ok tracked -> return tracked + | Error _ -> return Set.empty + } + + let repairable = holdingContent.ToArray() |> Array.filter trackedPaths.Contains + + if context.Cancellation.IsCancellationRequested() then + return canceledLfsResult () + elif repairable.Length = 0 then + return Ok Set.empty + else + match! refreshLfsIndexEntries arcPath repairable with + | Error failure -> return Error failure + | Ok() -> return Ok(Set.ofArray repairable) +} + +/// Reads the Git LFS listing once. It settles the paths that need no action and fails the paths with +/// changes or without a listing entry. The rest are the candidates. A request that names an +/// already listed path again, for example in another case, is dropped from `order`, because a +/// duplicate counts once. With `reportRepaired`, a path whose only change is a stale index entry is +/// repaired. The repair changed the index, so the path settles as changed and `reportRepaired` reports it. +let private readLfsCandidates + (arcPath: string) + (resolvedPaths: (string * string)[]) + (dirtyMessage: string -> string) + (isAlreadyInState: GitLfsLsFileInfo -> bool) + (reportAlreadyInState: string -> GitLfsLsFileInfo -> unit) + (reportRepaired: (string -> GitLfsLsFileInfo -> unit) option) + (context: OperationContext) + (results: LfsPathResults) + (order: ResizeArray) + : JS.Promise * LfsPathCandidate[]>> = promise { + let isCanceled () = context.Cancellation.IsCancellationRequested() + let! listingResult = GitLfsService.readLsFilesByRelativePath arcPath context + + match listingResult with + | Error _ when isCanceled () -> return canceledLfsResult () + | Error message -> + // A request for one path keeps the message of the single-file action, which names the path. + let pathPrefix = + if resolvedPaths.Length = 1 then + $"'{snd resolvedPaths[0]}' " + else + String.Empty + + return errorResult (exn $"{pathPrefix}Could not read Git LFS file metadata: {message}") + | Ok _ when isCanceled () -> return canceledLfsResult () + | Ok listing -> + let lookup = GitLfsService.createListingLookup listing + let seenKeys = Collections.Generic.HashSet() + let uniqueEntries = ResizeArray() + + for requested, safePath in resolvedPaths do + let info = lookup safePath + + match info with + | Some listed when not (seenKeys.Add listed.name) -> order.Remove requested |> ignore + | _ -> uniqueEntries.Add((requested, safePath, info)) + + let entries = uniqueEntries.ToArray() + + // A path the listing lacks is still checked for changes, because a changed file reports + // that before it reports that Git LFS does not list it. + let statusPaths = + entries + |> Array.map (fun (_, safePath, info) -> + match info with + | Some listed -> listed.name + | None -> safePath) + |> Array.distinct + + match! readDirtyFiles arcPath statusPaths context with + | Error _ when isCanceled () -> return canceledLfsResult () + | Error failure -> return Error failure + | Ok _ when isCanceled () -> return canceledLfsResult () + | Ok dirtyFiles -> + let dirtyPaths = dirtyPathsOf dirtyFiles + + let! repairResult = + if reportRepaired.IsSome && dirtyFiles.Length > 0 then + repairStaleLfsIndexEntries arcPath - session.CommandAuth - safePath - listing - exactObjectOnly - (Some context.Cancellation.IsCancellationRequested) - (fun () -> - context.ReportProgress { - PhaseCode = "lfs-materialize-transfer" - Item = Some safePath - Completed = None - Total = None - DisplayMessage = None - }) - with - | Error _ when context.Cancellation.IsCancellationRequested() -> return canceledLfsResult () - | Error error when GitLfsService.isMissingOnRemote error.Message -> - return - errorResult ( - exn $"The remote does not have the content of '{safePath}'. Upload it from the computer that saved it." - ) - | Error error -> return errorResult error - | Ok() when context.Cancellation.IsCancellationRequested() -> return canceledLfsResult () - | Ok() -> - // The listing reader signals failure by throwing, so it runs inside runSimpleGit, - // which turns that into a GitResult. - let! fetchedListingResult = - runSimpleGit (fun _currentGit -> requireLfsListingForPath arcPath safePath context) session.Git - - match fetchedListingResult with - | Error _ when context.Cancellation.IsCancellationRequested() -> return canceledLfsResult () - | Error failure -> return Error failure - | Ok _ when context.Cancellation.IsCancellationRequested() -> return canceledLfsResult () - | Ok fetchedListing when not fetchedListing.downloaded -> - return errorResult (exn $"Git LFS did not download '{safePath}'.") - | Ok _ -> - let! checkoutResult = GitLfsService.checkoutPath arcPath safePath + dirtyFiles + (entries |> Array.choose (fun (_, _, info) -> info)) + context + else + promise { return Ok Set.empty } - match checkoutResult with - | Error error -> return errorResult error - | Ok() -> - return! - runSimpleGit - (fun _currentGit -> - requireDownloadedLfsFile - arcPath - safePath - absolutePath - listing - { context with Cancellation = OperationCancellation.none }) - session.Git + match repairResult with + | Error failure -> return Error failure + | Ok repairedPaths -> + let candidates = ResizeArray() + + for requested, safePath, info in entries do + let statusPath = + match info with + | Some listed -> listed.name + | None -> safePath + + if dirtyPaths.Contains statusPath && not (repairedPaths.Contains statusPath) then + results[requested] <- Error(localChangesFailure (dirtyMessage safePath)) + else + match info with + | None -> + results[requested] <- + Error( + lfsFailure $"'{safePath}' The file is not listed by Git LFS in the current checkout." + ) + | Some listed when repairedPaths.Contains listed.name -> + results[requested] <- Ok Changed + reportRepaired |> Option.iter (fun report -> report safePath listed) + | Some listed when isAlreadyInState listed -> + results[requested] <- Ok AlreadyInState + reportAlreadyInState safePath listed + | Some listed -> + candidates.Add { + Requested = requested + SafePath = safePath + Key = listed.name + AbsolutePath = resolve [| arcPath; listed.name |] + Listing = listed + } + + return Ok(listing, candidates.ToArray()) } -let freeLocalLfsCopy +/// Reads the Git LFS listing once, then downloads the paths that need it. +let private runLfsDownload (arcPath: string) - (requestedPath: string) + (resolvedPaths: (string * string)[]) (credentials: GitCredentialStrategy.GitCredentialStrategy) (connectionProfileId: string option) + (reportProgress: OperationProgress -> unit) (context: OperationContext) - : JS.Promise> = promise { - let! lfsFileResult = - getCleanLfsFileForAction + (results: LfsPathResults) + (order: ResizeArray) + : JS.Promise> = promise { + let reportCount = createLfsCountReporter "lfs-materialize-files" reportProgress results order + + match! + readLfsCandidates arcPath - requestedPath + resolvedPaths (fun safePath -> - $"'{safePath}' has local changes. Save, discard, or commit them before freeing the local LFS copy.") + $"'{safePath}' has local changes. Save, discard, or commit them before downloading the Git LFS file.") + (fun listed -> listed.checkout) + (fun safePath listed -> + reportProgress { + PhaseCode = "lfs-materialize" + Item = Some safePath + Completed = Some listed.size + Total = Some listed.size + DisplayMessage = Some "Git LFS file is already materialized" + }) + (Some(fun safePath listed -> + reportProgress { + PhaseCode = "lfs-materialize" + Item = Some safePath + Completed = Some listed.size + Total = Some listed.size + DisplayMessage = Some "Git LFS file materialized" + })) context + results + order + with + | Error failure -> return Error failure + | Ok(_, candidates) when candidates.Length = 0 -> + reportCount 0 + return Ok() + | Ok(listing, candidates) -> + // The listing has settled the paths that need no download and the paths that failed. + reportCount 0 + + let! downloaded = + downloadLfsCandidates + arcPath + listing + candidates + credentials + connectionProfileId + reportProgress + context + results + reportCount + + match downloaded with + | Ok() -> reportCount 0 + | Error _ -> () + + return downloaded +} + +/// Validates and deduplicates the requested paths for a download or a free, and runs `run` on the +/// valid ones. A path that fails validation settles at once. The result names each requested path +/// once, in request order, and `run` may drop a request from `order` when it duplicates another. +/// The error is a failure of the whole operation. +let private runLfsPaths + (arcPath: string) + (requestedPaths: string[]) + (context: OperationContext) + (run: (string * string)[] -> LfsPathResults -> ResizeArray -> JS.Promise>) + : JS.Promise> = promise { + if context.Cancellation.IsCancellationRequested() then + return canceledLfsResult () + else + try + let results = LfsPathResults() + let order = ResizeArray() + let resolvedPaths = ResizeArray() + let seenPaths = Collections.Generic.HashSet() + + for requested in requestedPaths do + match tryResolveArcRelativePath arcPath requested with + | Error validationError -> + if seenPaths.Add requested then + order.Add requested + results[requested] <- Error(toFailure validationError) + | Ok(safePath, _) -> + if seenPaths.Add safePath then + order.Add requested + resolvedPaths.Add((requested, safePath)) + + let! runResult = + if resolvedPaths.Count = 0 then + promise { return Ok() } + else + run (resolvedPaths.ToArray()) results order + + match runResult with + | Error failure -> return Error failure + | Ok() -> + return + order + |> Seq.map (fun requested -> ({ Path = requested; Result = results[requested] }: LfsPathOutcome)) + |> Seq.toArray + |> Ok + with error -> + return errorResult error +} - let! trackedResult = - match lfsFileResult with - | Ok(safePath, _, listing) when listing.checkout -> checkPathTrackedByAttributes arcPath safePath - | _ -> promise { return Ok true } - - match lfsFileResult, trackedResult with - | Error failure, _ -> return Error failure - | _, Error failure -> return Error failure - | Ok(safePath, _, listing), _ when not listing.checkout -> - context.ReportProgress { - PhaseCode = "lfs-dematerialize" - Item = Some safePath +/// Downloads the content of Git LFS files that sit in the working tree as pointers. One listing and +/// one remote session serve the whole request, and the objects come in one fetch per chunk of paths. +/// The result names each requested path once, in request order. A path whose request failed does not +/// stop the others. The error is a failure of the whole operation, such as a cancellation before any +/// file changed. +let downloadLfsFiles + (arcPath: string) + (requestedPaths: string[]) + (credentials: GitCredentialStrategy.GitCredentialStrategy) + (connectionProfileId: string option) + (reportProgress: OperationProgress -> unit) + (context: OperationContext) + : JS.Promise> = + runLfsPaths arcPath requestedPaths context (fun resolvedPaths results order -> + runLfsDownload + arcPath + resolvedPaths + credentials + connectionProfileId + reportProgress + context + results + order) + +/// The answer of the remote check for one path of a free. +type private LfsConfirmation = + | RemoteHasObject + | RemoteLacksCoverage + | ConfirmationFailed of exn + /// A failure that every other path meets again, such as an unreachable remote. + | ConfirmationRemoteWideFailed of exn + | ConfirmationCanceled + +let private lfsConfirmationFailureMessage (safePath: string) (error: exn) = + if GitLfsService.isMissingOnRemote error.Message then + $"The remote does not have '{safePath}' yet. Push it before freeing its local copy." + else + $"Could not confirm that the remote has '{safePath}': {error.Message}" + +/// Asks the remote about one path. The dry run must list the object, then a remote without +/// the batch API must complete a refetch. +let private confirmLfsPath + (arcPath: string) + (session: AuthenticatedGitSession) + (usesServer: bool) + (candidate: LfsPathCandidate) + (reportProgress: OperationProgress -> unit) + (context: OperationContext) + : JS.Promise = promise { + let cancelCheck = Some context.Cancellation.IsCancellationRequested + + let onTransferStarted () = + reportProgress { + PhaseCode = "lfs-dematerialize-transfer" + Item = Some candidate.SafePath Completed = Some 0.0 - Total = Some listing.size - DisplayMessage = Some "Git LFS file is already dematerialized" + Total = Some candidate.Listing.size + DisplayMessage = None } - return Ok false - | Ok(safePath, _, _), Ok false -> - return errorResult (createMissingLfsAttributesFailure safePath "freeing the local LFS copy") - | Ok(safePath, absolutePath, listing), Ok true -> - context.ReportProgress { - PhaseCode = "lfs-dematerialize" - Item = Some safePath - Completed = Some 0.0 - Total = Some listing.size - DisplayMessage = Some "Preparing Git LFS dematerialization" + let! confirmationResult = + promise { + let! dryRunResult = + GitLfsService.fetchRefetchForPaths + arcPath + session.CommandAuth + [| candidate.Key |] + true + cancelCheck + onTransferStarted + (NodeOutput.OutputTarget.ofContext context) + + match dryRunResult with + | Error error -> return Error error + | Ok output when not (GitLfsService.dryRunCoversObject output candidate.Listing.oid) -> return Ok None + | Ok _ when usesServer -> return Ok(Some String.Empty) + | Ok _ -> + let! refetchResult = + GitLfsService.fetchRefetchForPaths + arcPath + session.CommandAuth + [| candidate.Key |] + false + cancelCheck + onTransferStarted + (NodeOutput.OutputTarget.ofContext context) + + return Result.map Some refetchResult } + match confirmationResult with + | Error _ when context.Cancellation.IsCancellationRequested() -> return ConfirmationCanceled + | Error error -> return ConfirmationFailed error + | Ok _ when context.Cancellation.IsCancellationRequested() -> return ConfirmationCanceled + | Ok None -> return RemoteLacksCoverage + | Ok _ -> return RemoteHasObject +} + +/// Asks the remote about each path on its own, in order. +let private confirmLfsPathsOneByOne + (arcPath: string) + (session: AuthenticatedGitSession) + (usesServer: bool) + (paths: LfsPathCandidate[]) + (reportProgress: OperationProgress -> unit) + (context: OperationContext) + : JS.Promise = promise { + let answers = ResizeArray() + + for candidate in paths do if context.Cancellation.IsCancellationRequested() then - return canceledLfsResult () + answers.Add ConfirmationCanceled else - match! createOriginLfsRemoteSession arcPath credentials connectionProfileId None with - | Error failure -> return Error failure - | Ok session -> - let! endpoint = GitLfsService.tryGetLfsEndpoint arcPath - let! standaloneAgent = GitLfsService.tryHasStandaloneTransferAgent arcPath - let usesServer = GitLfsService.usesBatchApi endpoint && not standaloneAgent - - let onTransferStarted () = - context.ReportProgress { - PhaseCode = "lfs-dematerialize-transfer" - Item = Some safePath - Completed = Some 0.0 - Total = Some listing.size - DisplayMessage = None - } + let! answer = confirmLfsPath arcPath session usesServer candidate reportProgress context + answers.Add answer - let confirmationFailure (error: exn) = - let message = error.Message + return answers.ToArray() +} - if GitLfsService.isMissingOnRemote message then - exn $"The remote does not have '{safePath}' yet. Push it before freeing its local copy." +/// True when the failure classifies as a network, timeout, authentication or authorization problem. +/// The remote gives the same problem again for each path of a chunk, so asking path by path only waits longer. +/// The progress line names the branch, and the trailer and the error lines carry URLs with the repository +/// name. The decision reads neither those two lines nor any URL, so a name such as "fix-403-page" or +/// "gene-regulatory-network" cannot turn another failure into a remote-wide one. +let internal isRemoteWideFailure (error: exn) = + let isProgressOrTrailer (line: string) = + let text = line.Trim() + + let text = + if text.StartsWith("fetch: ", StringComparison.Ordinal) then + text.Substring 7 + else + text + + text.StartsWith("Fetching reference", StringComparison.Ordinal) + || text.StartsWith("error: failed to fetch some objects", StringComparison.Ordinal) + + let decisionText = + error.Message.Split([| '\r'; '\n' |], StringSplitOptions.RemoveEmptyEntries) + |> Array.filter (isProgressOrTrailer >> not) + |> Array.map (fun line -> Text.RegularExpressions.Regex.Replace(line, @"https?://[^\s""']+", "")) + |> String.concat "\n" + + match classifyFailureKind decisionText with + | GitFailureKind.Network + | GitFailureKind.Timeout + | GitFailureKind.Unauthorized + | GitFailureKind.Forbidden -> true + | _ -> false + +/// Asks the remote about the paths of one chunk with a single dry run. The chunk counts as +/// confirmed when the dry run succeeds and, without the batch API, so does the refetch. When either +/// fails, its output may name the objects that the remote lacks. Those paths settle with the message of +/// a single-file free, and the rest of the chunk asks again once. After a failure that names no object, a +/// network, timeout, authentication or authorization problem settles every path of the chunk at once, +/// each with the message of a single-file free. Any other failure, and a second failure that names +/// objects, sends each path to ask on its own, so every path keeps that message. +let rec private confirmLfsChunk + (arcPath: string) + (session: AuthenticatedGitSession) + (usesServer: bool) + (chunk: LfsPathCandidate[]) + (mayRetry: bool) + (reportProgress: OperationProgress -> unit) + (context: OperationContext) + : JS.Promise = promise { + let isCanceled () = context.Cancellation.IsCancellationRequested() + + if chunk.Length = 1 then + let! confirmation = confirmLfsPath arcPath session usesServer chunk[0] reportProgress context + return [| confirmation |] + else + let cancelCheck = Some context.Cancellation.IsCancellationRequested + let keys = chunk |> Array.map (fun candidate -> candidate.Key) + + let onTransferStarted () = + reportProgress { + PhaseCode = "lfs-dematerialize-transfer" + Item = None + Completed = Some 0.0 + Total = Some(chunk |> Array.sumBy (fun candidate -> candidate.Listing.size)) + DisplayMessage = None + } + + let canceledAnswers = chunk |> Array.map (fun _ -> ConfirmationCanceled) + + let answerAfterFailure (error: exn) = promise { + let missingObjectIds = GitLfsService.missingOnRemoteObjectIds error.Message + let lacksObject = chunk |> Array.map (fun candidate -> missingObjectIds.Contains candidate.Listing.oid) + + if mayRetry && Array.exists id lacksObject then + let remaining = + chunk |> Array.filter (fun candidate -> not (missingObjectIds.Contains candidate.Listing.oid)) + + let! remainingAnswers = + if remaining.Length = 0 then + promise { return [||] } else - exn $"Could not confirm that the remote has '{safePath}': {message}" + confirmLfsChunk arcPath session usesServer remaining false reportProgress context - let noCoverageMessage = - $"Could not check whether the remote has '{safePath}', so its local copy stays." + let answers = ResizeArray() + let mutable next = 0 - // The dry run must list this OID, then non-batch endpoints must complete a refetch. - let! confirmationResult = - promise { - let! dryRunResult = - GitLfsService.fetchRefetchForPath - arcPath - session.CommandAuth - safePath - true - (Some context.Cancellation.IsCancellationRequested) - onTransferStarted - - match dryRunResult with - | Error error -> return Error error - | Ok output when not (GitLfsService.dryRunCoversObject output listing.oid) -> - return Ok None - | Ok _ when usesServer -> return Ok(Some String.Empty) - | Ok _ -> - let! refetchResult = - GitLfsService.fetchRefetchForPath - arcPath - session.CommandAuth - safePath - false - (Some context.Cancellation.IsCancellationRequested) - onTransferStarted - - return Result.map Some refetchResult - } + for lacks in lacksObject do + if lacks then + answers.Add(ConfirmationFailed error) + else + answers.Add remainingAnswers[next] + next <- next + 1 - match confirmationResult with - | Error _ when context.Cancellation.IsCancellationRequested() -> return canceledLfsResult () - | Error error -> return errorResult (confirmationFailure error) - | Ok _ when context.Cancellation.IsCancellationRequested() -> return canceledLfsResult () - | Ok None -> return errorResult (exn noCoverageMessage) - | Ok _ -> - let git = session.Git - let! backupResult = moveVerifiedFileToLfsBackup arcPath safePath absolutePath listing context + return answers.ToArray() + // An object id can contain "401" or "403", so output that names missing objects is not classified. + elif missingObjectIds.IsEmpty && isRemoteWideFailure error then + return chunk |> Array.map (fun _ -> ConfirmationRemoteWideFailed error) + else + return! confirmLfsPathsOneByOne arcPath session usesServer chunk reportProgress context + } - match backupResult with - | Error failure -> return Error failure - | Ok(backupPath, statsBeforeHash, expectedPointer) -> - let mutable pointerCheckoutRan = false + let! dryRunResult = + GitLfsService.fetchRefetchForPaths + arcPath + session.CommandAuth + keys + true + cancelCheck + onTransferStarted + (NodeOutput.OutputTarget.ofContext context) + + match dryRunResult with + | Error _ when isCanceled () -> return canceledAnswers + | Error error -> return! answerAfterFailure error + | Ok output -> + let isCovered = + chunk + |> Array.map (fun candidate -> GitLfsService.dryRunCoversObject output candidate.Listing.oid) + + // The refetch only matters for an object that the dry run lists. + let! refetchResult = + if usesServer || not (Array.exists id isCovered) then + promise { return Ok String.Empty } + else + GitLfsService.fetchRefetchForPaths + arcPath + session.CommandAuth + keys + false + cancelCheck + onTransferStarted + (NodeOutput.OutputTarget.ofContext context) - try - freeLocalLfsCopyTestHook - |> Option.iter (fun hook -> hook "after-backup-move" absolutePath) - - if context.Cancellation.IsCancellationRequested() then - match - restoreTemporaryLfsBackup - backupPath - absolutePath - expectedPointer - pointerCheckoutRan - with - | LfsBackupRetained -> return Error(lfsBackupRetainedFailure safePath backupPath) - | LfsBackupRestored -> return canceledLfsResult () - else - let pointerGit = applyLfsSkipSmudge git + match refetchResult with + | Error _ when isCanceled () -> return canceledAnswers + | Error error -> return! answerAfterFailure error + | Ok _ when isCanceled () -> return canceledAnswers + | Ok _ -> + return + isCovered + |> Array.map (fun covered -> if covered then RemoteHasObject else RemoteLacksCoverage) +} - let pathExistsBeforeCheckout = - try - tryLstatSync absolutePath |> Option.isSome - with _ -> - true +/// Asks the remote about every candidate, one dry run per chunk of patterns. A candidate that the +/// remote lacks settles with its failure. When a chunk fails for a problem that every path meets again, +/// such as an unreachable remote, the remaining chunks settle with that failure and skip the remote. +/// The result holds the confirmed candidates in request order. The error is a cancellation. +let private confirmLfsCandidates + (arcPath: string) + (session: AuthenticatedGitSession) + (usesServer: bool) + (candidates: LfsPathCandidate[]) + (results: LfsPathResults) + (reportProgress: OperationProgress -> unit) + (context: OperationContext) + : JS.Promise> = promise { + let groups = groupLfsCandidatesByPattern candidates - if pathExistsBeforeCheckout then - return Error(lfsBackupRetainedFailure safePath backupPath) - else - pointerCheckoutRan <- true + let fixedArguments = + Array.append session.CommandAuth.ConfigArgs (GitLfsService.buildFetchRefetchArgsForPaths true [||]) - let! checkoutResult = - runSimpleGit - (fun currentGit -> - currentGit.raw [| - "checkout" - "HEAD" - "--" - literalPathspecFromString safePath - |]) - pointerGit + let patternChunks = GitPathTransport.chunkArguments fixedArguments (Seq.toArray groups.Keys) + let confirmed = ResizeArray() + let mutable canceled = false + let mutable remoteWideFailure: exn option = None - freeLocalLfsCopyTestHook - |> Option.iter (fun hook -> hook "after-pointer-checkout" absolutePath) + let settleFailed (candidate: LfsPathCandidate) (error: exn) = + results[candidate.Requested] <- Error(lfsFailure (lfsConfirmationFailureMessage candidate.SafePath error)) - match checkoutResult with - | Error failure -> - match - restoreTemporaryLfsBackup - backupPath - absolutePath - expectedPointer - pointerCheckoutRan - with - | LfsBackupRetained -> return Error(lfsBackupRetainedFailure safePath backupPath) - | LfsBackupRestored -> return Error failure - | Ok _ when context.Cancellation.IsCancellationRequested() -> - match - restoreTemporaryLfsBackup - backupPath - absolutePath - expectedPointer - pointerCheckoutRan - with - | LfsBackupRetained -> return Error(lfsBackupRetainedFailure safePath backupPath) - | LfsBackupRestored -> return canceledLfsResult () - | Ok _ -> - let untimedStatusGit = createUntimedOptions arcPath None None |> createGit - let! finalStatusResult = - runSimpleGit (fun currentGit -> currentGit.status ()) untimedStatusGit - - freeLocalLfsCopyTestHook - |> Option.iter (fun hook -> hook "after-final-status" absolutePath) - - match finalStatusResult with - | Error failure -> - match - restoreTemporaryLfsBackup - backupPath - absolutePath - expectedPointer - pointerCheckoutRan - with - | LfsBackupRetained -> return Error(lfsBackupRetainedFailure safePath backupPath) - | LfsBackupRestored -> return Error failure - | Ok finalStatus when not (isPathCleanInStatus finalStatus safePath) -> - match - restoreTemporaryLfsBackup - backupPath - absolutePath - expectedPointer - pointerCheckoutRan - with - | LfsBackupRetained -> return Error(lfsBackupRetainedFailure safePath backupPath) - | LfsBackupRestored -> - return - errorResult ( - exn - $"Could not replace '{safePath}' with an LFS pointer without changing Git status." - ) - | Ok _ -> - if not (isExpectedLfsPointerAtPath absolutePath expectedPointer pointerCheckoutRan) then - return Error(lfsBackupRetainedFailure safePath backupPath) - else - let backupStats = statSync backupPath - - if - backupStats.size <> statsBeforeHash.size - || backupStats.mtimeMs <> statsBeforeHash.mtimeMs - then - match - restoreTemporaryLfsBackup - backupPath - absolutePath - expectedPointer - pointerCheckoutRan - with - | LfsBackupRetained -> return Error(lfsBackupRetainedFailure safePath backupPath) - | LfsBackupRestored -> - return - errorResult ( - exn $"'{safePath}' changed while it was being freed. Try again." - ) - else - removeTemporaryLfsBackup backupPath - - context.ReportProgress { - PhaseCode = "lfs-dematerialize" - Item = Some safePath - Completed = Some listing.size - Total = Some listing.size - DisplayMessage = Some "Git LFS file dematerialized" - } - - return Ok true - with ex -> + for patterns in patternChunks do + if not canceled then + let chunk = patterns |> Array.collect (fun pattern -> groups[pattern].ToArray()) + + let! answers = + match remoteWideFailure with + | Some error -> promise { return chunk |> Array.map (fun _ -> ConfirmationRemoteWideFailed error) } + | None -> confirmLfsChunk arcPath session usesServer chunk true reportProgress context + + for index in 0 .. chunk.Length - 1 do + let candidate = chunk[index] + + match answers[index] with + | ConfirmationCanceled -> canceled <- true + | RemoteHasObject -> confirmed.Add candidate + | RemoteLacksCoverage -> + results[candidate.Requested] <- + Error( + lfsFailure + $"Could not check whether the remote has '{candidate.SafePath}', so its local copy stays." + ) + | ConfirmationFailed error -> settleFailed candidate error + | ConfirmationRemoteWideFailed error -> + remoteWideFailure <- Some error + settleFailed candidate error + + if canceled then + return canceledLfsResult () + else + let confirmedKeys = + Collections.Generic.HashSet(confirmed |> Seq.map (fun candidate -> candidate.Requested)) + + return Ok(candidates |> Array.filter (fun candidate -> confirmedKeys.Contains candidate.Requested)) +} + +/// Replaces one file with its pointer. The file moves into a backup first and returns from it when +/// anything goes wrong. A failure that leaves the backup behind has the kind LfsBackupRetained. +let private freeLfsCandidate + (arcPath: string) + (git: ISimpleGit) + (candidate: LfsPathCandidate) + (reportProgress: OperationProgress -> unit) + (context: OperationContext) + : JS.Promise> = promise { + let gitPath = candidate.Key + let displayPath = candidate.SafePath + let absolutePath = candidate.AbsolutePath + let listing = candidate.Listing + let! backupResult = moveVerifiedFileToLfsBackup arcPath gitPath displayPath absolutePath listing context + + match backupResult with + | Error failure -> return Error failure + | Ok(backupPath, statsBeforeHash, expectedPointer) -> + let mutable pointerCheckoutRan = false + + try + freeLocalLfsCopyTestHook + |> Option.iter (fun hook -> hook "after-backup-move" absolutePath) + + if context.Cancellation.IsCancellationRequested() then + match restoreTemporaryLfsBackup backupPath absolutePath expectedPointer pointerCheckoutRan with + | LfsBackupRetained -> return Error(lfsBackupRetainedFailure displayPath backupPath) + | LfsBackupRestored -> return canceledLfsResult () + else + let pointerGit = applyLfsSkipSmudge git + + let pathExistsBeforeCheckout = + try + tryLstatSync absolutePath |> Option.isSome + with _ -> + true + + if pathExistsBeforeCheckout then + return Error(lfsBackupRetainedFailure displayPath backupPath) + else + pointerCheckoutRan <- true + + let! checkoutResult = + runSimpleGit + (fun currentGit -> + currentGit.raw [| "checkout"; "HEAD"; "--"; literalPathspecFromString gitPath |]) + pointerGit + + freeLocalLfsCopyTestHook + |> Option.iter (fun hook -> hook "after-pointer-checkout" absolutePath) + + match checkoutResult with + | Error failure -> + match restoreTemporaryLfsBackup backupPath absolutePath expectedPointer pointerCheckoutRan with + | LfsBackupRetained -> return Error(lfsBackupRetainedFailure displayPath backupPath) + | LfsBackupRestored -> return Error failure + | Ok _ when context.Cancellation.IsCancellationRequested() -> + match restoreTemporaryLfsBackup backupPath absolutePath expectedPointer pointerCheckoutRan with + | LfsBackupRetained -> return Error(lfsBackupRetainedFailure displayPath backupPath) + | LfsBackupRestored -> return canceledLfsResult () + | Ok _ -> + // The file has changed, so the final status ignores cancellation. + let! finalStatusResult = + readDirtyPaths + arcPath + [| gitPath |] + { context with + Cancellation = OperationCancellation.none } + + freeLocalLfsCopyTestHook + |> Option.iter (fun hook -> hook "after-final-status" absolutePath) + + match finalStatusResult with + | Error failure -> + match + restoreTemporaryLfsBackup backupPath absolutePath expectedPointer pointerCheckoutRan + with + | LfsBackupRetained -> return Error(lfsBackupRetainedFailure displayPath backupPath) + | LfsBackupRestored -> return Error failure + | Ok dirtyPaths when dirtyPaths.Contains gitPath -> match - restoreTemporaryLfsBackup - backupPath - absolutePath - expectedPointer - pointerCheckoutRan + restoreTemporaryLfsBackup backupPath absolutePath expectedPointer pointerCheckoutRan with - | LfsBackupRetained -> return Error(lfsBackupRetainedFailure safePath backupPath) - | LfsBackupRestored -> return errorResult ex + | LfsBackupRetained -> return Error(lfsBackupRetainedFailure displayPath backupPath) + | LfsBackupRestored -> + return + errorResult ( + exn + $"Could not replace '{displayPath}' with an LFS pointer without changing Git status." + ) + | Ok _ -> + if not (isExpectedLfsPointerAtPath absolutePath expectedPointer pointerCheckoutRan) then + return Error(lfsBackupRetainedFailure displayPath backupPath) + else + let backupStats = statSync backupPath + + if + backupStats.size <> statsBeforeHash.size + || backupStats.mtimeMs <> statsBeforeHash.mtimeMs + then + match + restoreTemporaryLfsBackup + backupPath + absolutePath + expectedPointer + pointerCheckoutRan + with + | LfsBackupRetained -> return Error(lfsBackupRetainedFailure displayPath backupPath) + | LfsBackupRestored -> + return + errorResult (exn $"'{displayPath}' changed while it was being freed. Try again.") + else + removeTemporaryLfsBackup backupPath + + reportProgress { + PhaseCode = "lfs-dematerialize" + Item = Some candidate.SafePath + Completed = Some listing.size + Total = Some listing.size + DisplayMessage = Some "Git LFS file dematerialized" + } + + return Ok() + with ex -> + match restoreTemporaryLfsBackup backupPath absolutePath expectedPointer pointerCheckoutRan with + | LfsBackupRetained -> return Error(lfsBackupRetainedFailure displayPath backupPath) + | LfsBackupRestored -> return errorResult ex } -let downloadLfsFile +/// Frees the confirmed candidates one after the other. A cancellation stops the next paths, which +/// settle as canceled, and the paths already freed stay freed. A cancellation before the first path +/// is an error of the whole operation. +let private freeLfsCandidates (arcPath: string) - (requestedPath: string) + (session: AuthenticatedGitSession) + (confirmed: LfsPathCandidate[]) + (results: LfsPathResults) + (reportProgress: OperationProgress -> unit) + (reportCount: int -> unit) + (context: OperationContext) + : JS.Promise> = promise { + let mutable index = 0 + let mutable stopped = false + let mutable canceledBeforeChange = false + + for candidate in confirmed do + if stopped then + results[candidate.Requested] <- Error(canceledLfsFailure ()) + elif context.Cancellation.IsCancellationRequested() then + stopped <- true + + if index = 0 then + canceledBeforeChange <- true + else + results[candidate.Requested] <- Error(canceledLfsFailure ()) + else + let! freeResult = freeLfsCandidate arcPath session.Git candidate reportProgress context + + match freeResult with + | Ok() -> results[candidate.Requested] <- Ok Changed + | Error failure -> results[candidate.Requested] <- Error failure + + reportCount 0 + index <- index + 1 + + if canceledBeforeChange then + return canceledLfsResult () + else + return Ok() +} + +/// Reads the Git LFS listing once, then frees the paths that need it. +let private runLfsFree + (arcPath: string) + (resolvedPaths: (string * string)[]) (credentials: GitCredentialStrategy.GitCredentialStrategy) (connectionProfileId: string option) + (reportProgress: OperationProgress -> unit) (context: OperationContext) + (results: LfsPathResults) + (order: ResizeArray) : JS.Promise> = promise { - let! lfsFileResult = - getCleanLfsFileForAction + let reportCount = createLfsCountReporter "lfs-dematerialize-files" reportProgress results order + + match! + readLfsCandidates arcPath - requestedPath + resolvedPaths (fun safePath -> - $"'{safePath}' has local changes. Save, discard, or commit them before downloading the Git LFS file.") + $"'{safePath}' has local changes. Save, discard, or commit them before freeing the local LFS copy.") + (fun listed -> not listed.checkout) + (fun safePath listed -> + reportProgress { + PhaseCode = "lfs-dematerialize" + Item = Some safePath + Completed = Some 0.0 + Total = Some listed.size + DisplayMessage = Some "Git LFS file is already dematerialized" + }) + None context - - match lfsFileResult with + results + order + with | Error failure -> return Error failure - | Ok(safePath, _, listing) when listing.checkout -> - context.ReportProgress { - PhaseCode = "lfs-materialize" - Item = Some safePath - Completed = Some listing.size - Total = Some listing.size - DisplayMessage = Some "Git LFS file is already materialized" - } - + | Ok(_, candidates) when candidates.Length = 0 -> + reportCount 0 return Ok() - | Ok(safePath, absolutePath, listing) -> - context.ReportProgress { - PhaseCode = "lfs-materialize" - Item = Some safePath - Completed = Some 0.0 - Total = Some listing.size - DisplayMessage = Some "Preparing Git LFS materialization" - } + | Ok(_, candidates) -> + let! trackedResult = readLfsTrackedPaths arcPath (candidates |> Array.map (fun candidate -> candidate.Key)) + let tracked = ResizeArray() + + for candidate in candidates do + match trackedResult with + | Error message -> + results[candidate.Requested] <- + Error( + createFailure + (classifyFailureKind message) + $"Could not inspect Git LFS attributes for '{candidate.SafePath}': {message}" + ) + | Ok trackedPaths when trackedPaths.Contains candidate.Key -> tracked.Add candidate + | Ok _ -> + results[candidate.Requested] <- + Error( + toFailure (createMissingLfsAttributesFailure candidate.SafePath "freeing the local LFS copy") + ) - if context.Cancellation.IsCancellationRequested() then - return canceledLfsResult () + if tracked.Count = 0 then + reportCount 0 + return Ok() else - let! result = - downloadMissingLfsFile - arcPath - safePath - absolutePath - listing - credentials - connectionProfileId - context - - match result with - | Ok() -> - context.ReportProgress { - PhaseCode = "lfs-materialize" - Item = Some safePath - Completed = Some listing.size - Total = Some listing.size - DisplayMessage = Some "Git LFS file materialized" + for candidate in tracked do + reportProgress { + PhaseCode = "lfs-dematerialize" + Item = Some candidate.SafePath + Completed = Some 0.0 + Total = Some candidate.Listing.size + DisplayMessage = Some "Preparing Git LFS dematerialization" } - return Ok() - | Error failure -> return Error failure + if context.Cancellation.IsCancellationRequested() then + return canceledLfsResult () + else + match! createOriginLfsRemoteSession arcPath credentials connectionProfileId None with + | Error failure -> return Error failure + | Ok session -> + let! endpoint = GitLfsService.tryGetLfsEndpoint arcPath + let! standaloneAgent = GitLfsService.tryHasStandaloneTransferAgent arcPath + let usesServer = GitLfsService.usesBatchApi endpoint && not standaloneAgent + + match! + confirmLfsCandidates + arcPath + session + usesServer + (tracked.ToArray()) + results + reportProgress + context + with + | Error failure -> return Error failure + | Ok confirmed -> + // The confirmation has settled the paths that are already free and the ones that failed. + reportCount 0 + + if confirmed.Length = 0 then + return Ok() + else + return! + freeLfsCandidates arcPath session confirmed results reportProgress reportCount context +} + +/// Replaces the content of Git LFS files with their pointers, after the remote has confirmed that it +/// holds the objects. One listing and one remote session serve the whole request, with one remote check +/// per chunk of paths. The result names each requested path once, in request order. A path whose request +/// failed does not stop the others. The error is a failure of the whole operation, such as a cancellation +/// before any file changed. The objects in the local cache stay, and the caller removes those of the +/// freed paths. +let freeLfsFiles + (arcPath: string) + (requestedPaths: string[]) + (credentials: GitCredentialStrategy.GitCredentialStrategy) + (connectionProfileId: string option) + (reportProgress: OperationProgress -> unit) + (context: OperationContext) + : JS.Promise> = + runLfsPaths arcPath requestedPaths context (fun resolvedPaths results order -> + runLfsFree arcPath resolvedPaths credentials connectionProfileId reportProgress context results order) + +/// Frees one file. The result is false when the file already was a pointer. +let freeLocalLfsCopy + (arcPath: string) + (requestedPath: string) + (credentials: GitCredentialStrategy.GitCredentialStrategy) + (connectionProfileId: string option) + (context: OperationContext) + : JS.Promise> = promise { + match! freeLfsFiles arcPath [| requestedPath |] credentials connectionProfileId context.ReportProgress context with + | Error failure -> return Error failure + | Ok outcomes -> + match outcomes[0].Result with + | Ok Changed -> return Ok true + | Ok AlreadyInState -> return Ok false + | Error failure -> return Error failure +} + +let downloadLfsFile + (arcPath: string) + (requestedPath: string) + (credentials: GitCredentialStrategy.GitCredentialStrategy) + (connectionProfileId: string option) + (context: OperationContext) + : JS.Promise> = promise { + match! downloadLfsFiles arcPath [| requestedPath |] credentials connectionProfileId context.ReportProgress context with + | Error failure -> return Error failure + | Ok outcomes -> + match outcomes[0].Result with + | Ok _ -> return Ok() + | Error failure -> return Error failure } /// Discards validated pathspecs by restoring tracked paths from HEAD and cleaning selected untracked files. diff --git a/src/VersionControlService.Git/GitCredentialStrategy.fs b/src/VersionControlService.Git/GitCredentialStrategy.fs index 6d42070..79e3bed 100644 --- a/src/VersionControlService.Git/GitCredentialStrategy.fs +++ b/src/VersionControlService.Git/GitCredentialStrategy.fs @@ -132,6 +132,21 @@ let internal buildScopedAuthArguments (remoteUrl: string) (credential: GitCreden |] | _ -> [||] +/// Builds the Git LFS endpoint of a remote URL with the rule git-lfs applies in its +/// server discovery (docs/api/server-discovery.md). A remote that ends in ".git" gets +/// "/info/lfs" and any other remote gets ".git/info/lfs". git-lfs compares the suffix +/// case-sensitively (path.Ext(url) == ".git" in NewEndpointFromCloneURL), so "proj.GIT" becomes +/// "proj.GIT.git/info/lfs" here as well. git-lfs uses an explicit lfs.url literally, so the +/// suffix has to be added here. GitLab answers a batch request to an endpoint without ".git" +/// with "422 Unprocessable entity". +let private buildLfsEndpoint (remoteUrl: string) : string = + let trimmed = remoteUrl.TrimEnd('/') + + if trimmed.EndsWith(".git", StringComparison.Ordinal) then + trimmed + "/info/lfs" + else + trimmed + ".git/info/lfs" + /// Builds one command-scoped authentication value that can be reused for core /// Git and explicit Git LFS processes. The credential-bearing LFS endpoint is /// supplied only through `-c` arguments and is never persisted in repository @@ -160,7 +175,7 @@ let internal buildScopedCommandAuthentication let username = encodeUriComponent resolved.Username let secret = encodeUriComponent resolved.Secret let authenticatedRemote = $"https://{username}:{secret}@{remoteWithoutScheme}" - let authenticatedLfsUrl = authenticatedRemote.TrimEnd('/') + "/info/lfs" + let authenticatedLfsUrl = buildLfsEndpoint authenticatedRemote [| "-c" diff --git a/src/VersionControlService.Git/GitLfsExtensions.fs b/src/VersionControlService.Git/GitLfsExtensions.fs index ffc689a..5478eab 100644 --- a/src/VersionControlService.Git/GitLfsExtensions.fs +++ b/src/VersionControlService.Git/GitLfsExtensions.fs @@ -29,20 +29,30 @@ let private categoryOfKind (kind: GitFailureKind) = | GitFailureKind.LfsBackupRetained -> ProviderError | GitFailureKind.InvalidLfsThreshold -> Validation | GitFailureKind.RemoteProjectAlreadyExists -> ProviderError + | GitFailureKind.LocalChanges -> ProviderError | GitFailureKind.Unknown -> ProviderError let private toOperationFailure (failure: GitService.GitFailure) : OperationFailure = - match GitInternals.tryIndexLockFailure failure.Message with - | Some(path, ageSeconds) -> GitInternals.indexLockFailure path ageSeconds - | None when failure.Kind = GitFailureKind.InvalidLfsThreshold -> - OperationFailure.create Validation "invalid_lfs_threshold" failure.Message - | None when failure.Kind = GitFailureKind.LfsBackupRetained -> - { - OperationFailure.createRedacted ProviderError "lfs_backup_retained" failure.Message with - StateChanged = true - } - | None -> - OperationFailure.createRedacted (categoryOfKind failure.Kind) "lfs_operation_failed" failure.Message + let mapped = + match GitInternals.tryIndexLockFailure failure.Message with + | Some(path, ageSeconds) -> GitInternals.indexLockFailure path ageSeconds + | None when failure.Kind = GitFailureKind.InvalidLfsThreshold -> + OperationFailure.create Validation "invalid_lfs_threshold" failure.Message + | None when failure.Kind = GitFailureKind.LfsBackupRetained -> + { + OperationFailure.createRedacted ProviderError "lfs_backup_retained" failure.Message with + StateChanged = true + } + | None when failure.Kind = GitFailureKind.LocalChanges -> + OperationFailure.createRedacted (categoryOfKind failure.Kind) "local_changes" failure.Message + | None -> + OperationFailure.createRedacted (categoryOfKind failure.Kind) "lfs_operation_failed" failure.Message + + // A checkout that reports an index error has written its files already. + if GitLfsService.mentionsIndexUpdateFailure failure.Message then + { mapped with StateChanged = true } + else + mapped let private toOperationResult (failure: GitService.GitFailure) : OperationResult = if failure.Kind = GitFailureKind.Canceled then @@ -79,6 +89,13 @@ let private affectedPath (relativePath: string) (failure: OperationFailure) = { AffectedPaths = [| relativePath |] } +/// affectedPath for a failure that follows a checkout which wrote the file. +let private changedAffectedPath (relativePath: string) (failure: OperationFailure) = + { + affectedPath relativePath failure with + StateChanged = true + } + let private bumpRegularFileMtime (repoPath: string) (relativePath: string) : Result = try let absolutePath = NodePath.resolve [| repoPath; relativePath |] @@ -111,6 +128,27 @@ let private completeStoragePolicyChange (repoPath: string) (relativePath: string AffectedPaths = affectedPaths } +/// The index lock failure when the repository has a lock file, found through the caller's git runner. +/// The lookup runs without the cancellation of the context, because it follows a checkout that ran to +/// its end. A lookup that fails finds nothing. +let private tryHeldIndexLockFailure + (repoPath: string) + (runGit: string[] -> OperationContext -> Async>) + (context: OperationContext) + : Async = + async { + let lookupContext = { + context with + Cancellation = OperationCancellation.none + } + + let! lockPath = GitLfsService.tryFindHeldIndexLockWith (fun arguments -> runGit arguments lookupContext) repoPath + + return + lockPath + |> Option.map (fun path -> GitInternals.indexLockFailure path (GitInternals.tryFileAgeSeconds path)) + } + let private prepareUnmarkAfterPreflight (repoPath: string) (runGit: string[] -> OperationContext -> Async>) @@ -140,10 +178,12 @@ let private prepareUnmarkAfterPreflight |> affectedPath relativePath ) | Ok _ -> + // The checkout is local and holds the index lock, so a cancel must not kill it. let! checkoutResult = runGit [| "lfs"; "checkout"; "--"; GitLfsObjects.lfsCheckoutPattern relativePath |] - context + { context with + Cancellation = OperationCancellation.none } match checkoutResult with | Error failure -> @@ -156,20 +196,32 @@ let private prepareUnmarkAfterPreflight |> affectedPath relativePath ) | Ok output when output.ExitCode = 0 -> - let! restoredPointerResult = GitLfsObjects.readWorktreePointer repoPath relativePath + match GitLfsService.lfsCheckoutIndexUpdateFailed output.StdOut output.StdErr with + | Some text -> + let! lockFailure = tryHeldIndexLockFailure repoPath runGit context - match restoredPointerResult with - | Error failure -> return Error(affectedPath relativePath failure) - | Ok(Some _) -> return Error( - OperationFailure.create - ProviderError - "object_materialization_failed" - "Git LFS did not restore the file's content, so it stays in Git LFS." - |> affectedPath relativePath + lockFailure + |> Option.defaultWith (fun () -> + OperationFailure.createRedacted ProviderError "object_materialization_failed" text) + |> changedAffectedPath relativePath ) - | Ok None -> return Ok true + | None -> + let! restoredPointerResult = GitLfsObjects.readWorktreePointer repoPath relativePath + + match restoredPointerResult with + | Error failure -> return Error(affectedPath relativePath failure) + | Ok(Some _) -> + return + Error( + OperationFailure.create + ProviderError + "object_materialization_failed" + "Git LFS did not restore the file's content, so it stays in Git LFS." + |> affectedPath relativePath + ) + | Ok None -> return Ok true | Ok output -> let detail = if String.IsNullOrWhiteSpace output.StdErr then @@ -217,6 +269,91 @@ let private wrapUnitWithPreflight | Ok() -> return! wrapUnit context beginOperation operation } +/// Removes the cached objects of files that were just freed. An object stays when an unpushed commit +/// adds it, because git-lfs needs the local object to push that commit. The same holds for a custom +/// lfs.storage, which other clones can share and which prune refuses too. Every error is ignored, +/// because a cached object that stays only costs disk space. +let deleteCachedObjectsOfFreedPaths + (repoPath: string) + (runGit: string[] -> OperationContext -> Async>) + (context: OperationContext) + (relativePaths: string[]) + : Async = + async { + let detachedContext = { context with Cancellation = OperationCancellation.none } + + let hasNoOutput (result: Result) = + match result with + | Ok output -> output.ExitCode = 0 && String.IsNullOrWhiteSpace output.StdOut + | Error _ -> false + + try + let pointers = ResizeArray() + + for relativePath in relativePaths do + let! pointerResult = GitLfsObjects.readWorktreePointer repoPath relativePath + + match pointerResult with + | Ok(Some pointer) -> pointers.Add pointer + | Error _ + | Ok None -> () + + if pointers.Count > 0 then + let! mediaDirectoryResult = + GitLfsObjects.resolveLocalMediaDirectory (fun arguments -> runGit arguments detachedContext) repoPath + + match mediaDirectoryResult with + | Error _ -> () + | Ok mediaDirectory -> + let! storageResult = runGit [| "config"; "--get"; "lfs.storage" |] detachedContext + + match storageResult with + | Ok output when not (String.IsNullOrWhiteSpace(output.StdOut.Trim())) -> () + | _ -> + // One question answers it for every object when no commit is unpushed. + // The search covers HEAD too, so a commit on a detached HEAD keeps its objects. + let! unpushedCommitsResult = + runGit [| "rev-list"; "-1"; "HEAD"; "--branches"; "--not"; "--remotes=origin" |] detachedContext + + for pointer in pointers do + let! isUnreferenced = + async { + if hasNoOutput unpushedCommitsResult then + return true + else + let! unpushedResult = + runGit + [| + "-c" + "log.diffMerges=separate" + "log" + "-m" + "HEAD" + "--branches" + "--not" + "--remotes=origin" + "--format=%H" + "-1" + ("-Soid sha256:" + pointer.Oid) + |] + detachedContext + + return hasNoOutput unpushedResult + } + + if isUnreferenced then + // One object that cannot be removed does not keep the others. + try + let objectPath = GitLfsObjects.objectPath mediaDirectory pointer.Oid + + if NodeFileSystem.existsSync objectPath then + NodeFileSystem.unlinkSync objectPath + with _ -> + () + with _ -> + () + } + let createObjectMaterialization (repoPath: string) (runGit: string[] -> OperationContext -> Async>) @@ -334,62 +471,9 @@ let createObjectMaterialization match result with | Ok true -> - let detachedContext = { context with Cancellation = OperationCancellation.none } - - try - let! pointerResult = - GitLfsObjects.readWorktreePointer repoPath (RepositoryPath.value path) - |> Async.StartAsPromise - - match pointerResult with - | Ok(Some pointer) -> - let! mediaDirectoryResult = - GitLfsObjects.resolveLocalMediaDirectory - (fun arguments -> runGit arguments detachedContext) - repoPath - |> Async.StartAsPromise - - match mediaDirectoryResult with - | Ok mediaDirectory -> - let! storageResult = - runGit [| "config"; "--get"; "lfs.storage" |] detachedContext - |> Async.StartAsPromise - - match storageResult with - // Other clones can share a custom lfs.storage, so its objects stay. Prune refuses such storage too. - | Ok output when not (String.IsNullOrWhiteSpace(output.StdOut.Trim())) -> () - | _ -> - // git-lfs needs the local object to push an unpushed commit that adds it. - // The search covers HEAD too, so a commit on a detached HEAD keeps the object. - let! unpushedResult = - runGit - [| - "-c" - "log.diffMerges=separate" - "log" - "-m" - "HEAD" - "--branches" - "--not" - "--remotes=origin" - "--format=%H" - "-1" - ("-Soid sha256:" + pointer.Oid) - |] - detachedContext - |> Async.StartAsPromise - - match unpushedResult with - | Ok output when output.ExitCode = 0 && String.IsNullOrWhiteSpace output.StdOut -> - let objectPath = GitLfsObjects.objectPath mediaDirectory pointer.Oid - - if NodeFileSystem.existsSync objectPath then - NodeFileSystem.unlinkSync objectPath - | _ -> () - | Error _ -> () - | Error _ - | Ok None -> () - with _ -> () + do! + deleteCachedObjectsOfFreedPaths repoPath runGit context [| RepositoryPath.value path |] + |> Async.StartAsPromise return Ok() | Ok false -> return Ok() @@ -397,6 +481,215 @@ let createObjectMaterialization })) } +/// How a batch operation reports an incomplete run. +type internal BatchAction = { + /// Code of a failure when some paths fail. + IncompleteCode: string + /// Recovery of a partial success. + Recovery: RecoveryAction +} + +let internal batchMaterializeAction = { + IncompleteCode = "batch_materialization_incomplete" + Recovery = { + Code = "retry_materialization" + Instructions = Some "Materialize the path again to replace the pointer with the object's content." + } +} + +let private batchDematerializeAction = { + IncompleteCode = "batch_dematerialization_incomplete" + Recovery = { + Code = "retry_dematerialization" + Instructions = Some "Free the path again after the reported problem is fixed." + } +} + +let private batchNoOpReason = "Every path is already in the requested state." + +/// Collapses the outcomes of the paths into one result. The failure of a run with failed paths names +/// them in AffectedPaths and Details. It takes its category and retry flag from the first failure that +/// is not a cancellation, and has the category Canceled only when every failure is a cancellation. The +/// code is operation_canceled when every failure is a cancellation and local_changes when every failure is +/// the refusal of a path with local changes. Any other mix has the code of the action. +let internal toBatchResult (action: BatchAction) (outcomes: GitService.LfsPathOutcome[]) : OperationResult = + let changed = + outcomes + |> Array.choose (fun outcome -> + match outcome.Result with + | Ok GitService.Changed -> Some outcome.Path + | _ -> None) + + let failed = + outcomes + |> Array.choose (fun outcome -> + match outcome.Result with + | Error failure -> Some(outcome.Path, failure) + | Ok _ -> None) + + if failed.Length = 0 then + if changed.Length = 0 then + OperationResult.noOp (Some batchNoOpReason) () + else + Succeeded { + OperationOutcome.performed () with + AffectedPaths = changed + } + else + let failures = failed |> Array.map (fun (path, failure) -> path, toOperationFailure failure) + let allCanceled = failed |> Array.forall (fun (_, failure) -> failure.Kind = GitFailureKind.Canceled) + + let allLocalChanges = + failed |> Array.forall (fun (_, failure) -> failure.Kind = GitFailureKind.LocalChanges) + + // A cancellation says little about why other paths failed. The first failure that is not a + // cancellation therefore supplies the message and the category with its retry flag. + let basis = + match failed |> Array.tryFindIndex (fun (_, failure) -> failure.Kind <> GitFailureKind.Canceled) with + | Some index -> snd failures[index] + | None -> snd failures[0] + + let failure = { + basis with + Code = + if allCanceled then "operation_canceled" + elif allLocalChanges then "local_changes" + else action.IncompleteCode + Message = $"{failed.Length} of {outcomes.Length} paths failed: {basis.Message}" + StateChanged = changed.Length > 0 || (failures |> Array.exists (fun (_, item) -> item.StateChanged)) + AffectedPaths = failures |> Array.map fst + Details = failures |> Array.map (fun (path, item) -> $"{path}: {item.Message}") + } + + // A lock blocks every later path, so a lock recovery of any failed path replaces the retry + // and is also the recovery of a run in which every path failed. + let lockRecovery = + failures + |> Array.tryPick (fun (_, item) -> + item.RecoveryAction |> Option.filter (fun recovery -> recovery.Code = "remove_index_lock")) + + if changed.Length > 0 then + OperationResult.partiallySucceeded + { + OperationOutcome.performed () with + AffectedPaths = changed + } + failure + (lockRecovery |> Option.defaultValue action.Recovery) + else + Failed( + match lockRecovery with + | Some recovery -> + { failure with + RecoveryAction = Some recovery } + | None -> failure + ) + +/// Runs a batch operation under the session lock, after the preflight. An empty request needs neither. +let private runBatch + (preflight: OperationContext -> Async>) + (serialize: (unit -> Async>) -> Async>) + (phaseCode: string) + (action: BatchAction) + (operation: string[] -> OperationContext -> JS.Promise>) + (paths: RepositoryPath[]) + (context: OperationContext) + : Async> = + if paths.Length = 0 then + async { return OperationResult.noOp (Some batchNoOpReason) () } + else + serialize (fun () -> + async { + if context.Cancellation.IsCancellationRequested() then + return OperationResult.canceled "Git LFS operation canceled." + else + let! preflightResult = preflight context + + match preflightResult with + | Error failure when failure.Category = Canceled -> return OperationResult.canceled failure.Message + | Error failure -> return Failed failure + | Ok() -> + context.ReportProgress { + PhaseCode = phaseCode + Item = None + Completed = None + Total = None + DisplayMessage = None + } + + if context.Cancellation.IsCancellationRequested() then + return OperationResult.canceled "Git LFS operation canceled." + else + let! result = + Async.AwaitPromise(operation (paths |> Array.map RepositoryPath.value) context) + + match result with + | Error failure -> return toOperationResult failure + | Ok outcomes -> return toBatchResult action outcomes + }) + +/// The batch variant of createObjectMaterialization. Both operations read the Git LFS listing once, and the +/// download fetches the objects of many paths together. A path that fails does not stop the others. +let createObjectBatchMaterialization + (repoPath: string) + (runGit: string[] -> OperationContext -> Async>) + (credentials: GitCredentialStrategy.GitCredentialStrategy) + (connectionProfileId: string option) + (preflight: OperationContext -> Async>) + (serialize: (unit -> Async>) -> Async>) + : ObjectBatchMaterializationService = { + Materialize = + runBatch + preflight + serialize + "lfs-materialize" + batchMaterializeAction + (fun requestedPaths context -> + GitService.downloadLfsFiles + repoPath + requestedPaths + credentials + connectionProfileId + context.ReportProgress + context) + Dematerialize = + runBatch + preflight + serialize + "lfs-dematerialize" + batchDematerializeAction + (fun requestedPaths context -> + promise { + let! result = + GitService.freeLfsFiles + repoPath + requestedPaths + credentials + connectionProfileId + context.ReportProgress + context + + match result with + | Error failure -> return Error failure + | Ok outcomes -> + // The cleanup also covers a run that stopped on cancellation, because the files + // that were already freed stay freed. + let freedPaths = + outcomes + |> Array.choose (fun outcome -> + match outcome.Result with + | Ok GitService.Changed -> Some outcome.Path + | _ -> None) + + if freedPaths.Length > 0 then + do! + deleteCachedObjectsOfFreedPaths repoPath runGit context freedPaths + |> Async.StartAsPromise + + return Ok outcomes + }) +} + let createStoragePolicy (repoPath: string) (runGit: string[] -> OperationContext -> Async>) diff --git a/src/VersionControlService.Git/GitWorkspaceSession.fs b/src/VersionControlService.Git/GitWorkspaceSession.fs index c4ca59b..d393690 100644 --- a/src/VersionControlService.Git/GitWorkspaceSession.fs +++ b/src/VersionControlService.Git/GitWorkspaceSession.fs @@ -17,6 +17,7 @@ module GitLfsExtensions = VersionControlService.Git.GitLfsExtensions module GitProvisioningService = VersionControlService.Git.GitProvisioningService module GitTextDiffService = VersionControlService.Git.TextDiff.GitTextDiffService module NodeProcess = VersionControlService.Runtime.Node.Process +module NodeOutput = VersionControlService.Runtime.Node.OutputReporter module NodeFileSystem = VersionControlService.Runtime.Node.FileSystem module NodePath = VersionControlService.Runtime.Node.Path module NodeInterop = VersionControlService.Runtime.Node.Interop @@ -98,6 +99,7 @@ let private categoryOfKind (kind: GitFailureKind) = | GitFailureKind.LfsBackupRetained -> ProviderError | GitFailureKind.InvalidLfsThreshold -> Validation | GitFailureKind.RemoteProjectAlreadyExists -> ProviderError + | GitFailureKind.LocalChanges -> ProviderError | GitFailureKind.Unknown -> ProviderError let private codeOfKind (kind: GitFailureKind) = @@ -111,6 +113,7 @@ let private codeOfKind (kind: GitFailureKind) = | GitFailureKind.LfsBackupRetained -> "lfs_backup_retained" | GitFailureKind.InvalidLfsThreshold -> "invalid_lfs_threshold" | GitFailureKind.RemoteProjectAlreadyExists -> "remote_project_exists" + | GitFailureKind.LocalChanges -> "local_changes" | GitFailureKind.Unknown -> "git_failure" let private toOperationFailure (failure: GitService.GitFailure) : OperationFailure = @@ -163,7 +166,11 @@ let private mergeGitEnvironment (requestEnvironment: (string * string)[]) = |> Array.filter (fun (name, _) -> not (Set.contains name requestNames))) requestEnvironment -let private runGitEnv +/// Runs git with a progress phase code for its meter lines. Stderr meters are always read. Stdout is +/// read and reported to the output channel only when `observeStdout` is set, because the stdout of most calls is data. +let private runGitWithProgress + (phaseCode: string) + (observeStdout: bool) (hooks: GitSessionHooks) (repoPath: string) (arguments: string[]) @@ -177,7 +184,9 @@ let private runGitEnv WorkingDirectory = Some repoPath StdinData = stdinData Environment = mergeGitEnvironment environment - ProgressPhase = "git" + ProgressPhase = phaseCode + ObserveStdoutProgress = observeStdout + ReportStdoutOutput = observeStdout } let runner = hooks.RunProcess |> Option.defaultValue NodeProcess.run @@ -189,9 +198,35 @@ let private runGitEnv | Failed failure -> return Error failure } +let private runGitEnv hooks repoPath arguments stdinData environment context = + runGitWithProgress "git" false hooks repoPath arguments stdinData environment context + let private runGit hooks repoPath arguments stdinData context = runGitEnv hooks repoPath arguments stdinData [||] context +/// Runs a git call that transfers data. Its meters reach ReportProgress under `phaseCode`. The returned +/// output has no meter lines left, so a failure text built from it names the cause of the failure. +let private runGitTransfer + (phaseCode: string) + (observeStdout: bool) + (hooks: GitSessionHooks) + (repoPath: string) + (arguments: string[]) + (environment: (string * string)[]) + (context: OperationContext) + : Async> = + async { + let! result = runGitWithProgress phaseCode observeStdout hooks repoPath arguments None environment context + + return + result + |> Result.map (fun (output: NodeProcess.ProcessOutput) -> { + output with + StdOut = NodeProcess.dropProgressMeterLines output.StdOut + StdErr = NodeProcess.dropProgressMeterLines output.StdErr + }) + } + let private reportProgressReset (phaseCode: string) (context: OperationContext) = context.ReportProgress { PhaseCode = phaseCode @@ -201,6 +236,136 @@ let private reportProgressReset (phaseCode: string) (context: OperationContext) DisplayMessage = None } +/// Announces a step before it runs. Like a reset, the event has no numbers. It also names the step. +let private reportStepStart (phaseCode: string) (message: string) (context: OperationContext) = + context.ReportProgress { + PhaseCode = phaseCode + Item = None + Completed = None + Total = None + DisplayMessage = Some message + } + +let private outputFailureText (output: NodeProcess.ProcessOutput) = + if String.IsNullOrWhiteSpace output.StdErr then output.StdOut else output.StdErr + +/// How runLfsHydration ended. `Output` is the output of the step that ended the sequence, and for a fetch +/// that failed it is the fetch. `CheckoutFailed` is set when the checkout ran and failed. `Details` holds +/// the failure text of a checkout that failed after a failed fetch, for the Details of the failure. +type private LfsHydrationRun = { + Output: Result + CheckoutFailed: bool + Details: string[] +} + +/// Downloads the large objects of a checkout with `git lfs fetch` and then `git lfs checkout`, which is +/// what `git lfs pull` does in one process. A canceled pull kills git-lfs while it holds the index lock +/// and leaves `.git/index.lock` behind. The fetch takes no lock, so a cancel stops it cleanly. The +/// checkout is local and runs to its end, because stopping it midway is what leaves the lock. A cancel +/// that arrives during the checkout takes effect afterwards, and the work it finished counts. The +/// checkout runs after every fetch that ended without a cancel, whatever its exit code, because git-lfs +/// fetches the objects it can reach before it reports one that is missing, and those objects belong in the +/// working tree. The failure of such a fetch stays the result. The fetch reports under `phaseCode` and the +/// checkout under `phaseCode` plus "-checkout". +let private runLfsHydration + (phaseCode: string) + (hooks: GitSessionHooks) + (repoPath: string) + (authenticationArguments: string[]) + (fetchTarget: string[]) + (context: OperationContext) + : Async = + async { + // Git LFS writes its meters to stdout, and only when asked to. + let run code arguments runContext = + runGitTransfer + code + true + hooks + repoPath + (GitCredentialStrategy.buildLfsTransferArguments authenticationArguments arguments) + [| GitLfsForceProgress; "GIT_TERMINAL_PROMPT", "0" |] + runContext + + let! fetched = run phaseCode [| "lfs"; "fetch"; yield! fetchTarget |] context + + let endedWith output = { + Output = output + CheckoutFailed = false + Details = [||] + } + + match fetched with + | Ok fetchOutput when not (context.Cancellation.IsCancellationRequested()) -> + let checkoutPhaseCode = phaseCode + "-checkout" + reportStepStart checkoutPhaseCode "Checking out large files" context + + let! finishedCheckout = + run + checkoutPhaseCode + [| "lfs"; "checkout" |] + { context with + Cancellation = OperationCancellation.none } + + // A held index.lock makes git-lfs write the files, report the index error and exit with 0. + // That run counts as a failed checkout, so its output carries the error text and a nonzero exit. + let checkout = + match finishedCheckout with + | Ok output when output.ExitCode = 0 -> + match GitLfsService.lfsCheckoutIndexUpdateFailed output.StdOut output.StdErr with + | Some text -> + Ok { + output with + ExitCode = 1 + StdOut = String.Empty + StdErr = text + } + | None -> finishedCheckout + | _ -> finishedCheckout + + let checkoutFailure = + match checkout with + | Ok output when output.ExitCode = 0 -> None + | Ok output -> Some((outputFailureText output).Trim()) + | Error failure -> Some failure.Message + + if fetchOutput.ExitCode = 0 then + return { + endedWith checkout with + CheckoutFailed = checkoutFailure.IsSome + } + else + return { + endedWith fetched with + CheckoutFailed = checkoutFailure.IsSome + Details = + checkoutFailure + |> Option.map (fun text -> $"The checkout after the failed fetch also failed: {text}") + |> Option.toArray + } + | Ok output when output.ExitCode = 0 -> + return + endedWith ( + Error( + OperationFailure.create + Canceled + "operation_canceled" + "The large-object download was canceled before the checkout started." + ) + ) + | _ -> return endedWith fetched + } + +/// The failure of a hydration that ended with a nonzero exit, named after the operation whose Git +/// transfer had worked. Failure text of a checkout that followed a failed fetch goes to the Details. +let private hydrationOutputFailure (operation: string) (output: NodeProcess.ProcessOutput) (details: string[]) = + let failure = hydrationFailure operation (outputFailureText output) + + if details.Length = 0 then + failure + else + OperationFailure.withDetails details failure + let private runHookedBytesProcess (hooks: GitSessionHooks) (request: NodeProcess.ProcessRequest) @@ -218,35 +383,47 @@ let private runHookedBytesProcess /// The summary leaves out the leading `-c` pairs because they can hold credentials, and redacting a header would take Git's reason with it. let private commandSummary (arguments: string[]) = - let mutable firstRemainingArgument = 0 - - while firstRemainingArgument + 1 < arguments.Length && arguments[firstRemainingArgument] = "-c" do - firstRemainingArgument <- firstRemainingArgument + 2 - arguments - |> Array.skip firstRemainingArgument + |> NodeOutput.withoutLeadingConfig |> Array.truncate 3 |> String.concat " " +/// Turns a nonzero git exit into a failure. +let private checkGitExit + (arguments: string[]) + (result: Result) + : Result = + match result with + | Error failure -> Error failure + | Ok output when output.ExitCode <> 0 -> + match GitInternals.tryIndexLockFailure output.StdErr with + | Some(path, ageSeconds) -> Error(GitInternals.indexLockFailure path ageSeconds) + | None -> + Error( + OperationFailure.createRedacted + ProviderError + "git_failure" + $"git {commandSummary arguments} failed: {output.StdErr}" + ) + | Ok output -> Ok output + /// runGit that fails when git exits nonzero. let private runGitChecked hooks repoPath arguments stdinData context = async { let! result = runGit hooks repoPath arguments stdinData context + return checkGitExit arguments result + } - match result with - | Error failure -> return Error failure - | Ok output when output.ExitCode <> 0 -> - match GitInternals.tryIndexLockFailure output.StdErr with - | Some(path, ageSeconds) -> return Error(GitInternals.indexLockFailure path ageSeconds) - | None -> - return - Error( - OperationFailure.createRedacted - ProviderError - "git_failure" - $"git {commandSummary arguments} failed: {output.StdErr}" - ) - | Ok output -> return Ok output +/// Git prints no fetch meters to a pipe unless asked, and then writes them to stderr. +let private fetchArguments (authArguments: string[]) (remote: string) = + [| yield! authArguments; "fetch"; "--progress"; remote |] + +/// Fetches from the remote with meters under the phase "fetch" and fails when git exits nonzero. +let private runGitFetchChecked hooks repoPath authArguments remote context = + async { + let arguments = fetchArguments authArguments remote + let! result = runGitTransfer "fetch" false hooks repoPath arguments [||] context + return checkGitExit arguments result } let private barrier (hooks: GitSessionHooks) (repoPath: string) (point: string) (context: OperationContext) = @@ -1431,9 +1608,14 @@ let private toWorkspaceStatus /// Resolves a repository state path (MERGE_HEAD, ...) through Git itself so /// linked worktrees report the right location instead of `/.git/`. -let private resolveGitStatePath (state: SessionState) (name: string) (context: OperationContext) = +let private resolveGitStatePathAt + (hooks: GitSessionHooks) + (repoPath: string) + (name: string) + (context: OperationContext) + = async { - let! output = runGit state.Hooks state.RepoPath [| "rev-parse"; "--git-path"; name |] None context + let! output = runGit hooks repoPath [| "rev-parse"; "--git-path"; name |] None context match output with | Error failure -> return Error failure @@ -1447,7 +1629,7 @@ let private resolveGitStatePath (state: SessionState) (name: string) (context: O if rawPath.StartsWith "/" || (rawPath.Length >= 2 && rawPath[1] = ':') then rawPath else - NodePath.join [| state.RepoPath; rawPath |] + NodePath.join [| repoPath; rawPath |] return Ok(Some absolutePath) | Ok result -> @@ -1467,6 +1649,62 @@ let private resolveGitStatePath (state: SessionState) (name: string) (context: O ) } +let private resolveGitStatePath (state: SessionState) (name: string) (context: OperationContext) = + resolveGitStatePathAt state.Hooks state.RepoPath name context + +/// The path of the index lock when its file exists. The lookup runs on a copy of the context without its +/// cancellation, because it follows a checkout that ran to its end and the process runner starts nothing +/// on a canceled context. A lookup that fails finds nothing. +let private tryFindHeldIndexLock + (hooks: GitSessionHooks) + (repoPath: string) + (context: OperationContext) + : Async = + let lookupContext = { + context with + Cancellation = OperationCancellation.none + } + + GitLfsService.tryFindHeldIndexLockWith + (fun arguments -> runGit hooks repoPath arguments None lookupContext) + repoPath + +/// Recovery for a large-object download that failed or was canceled after the Git transfer itself +/// worked. It names the index.lock when Git reported one in the failure text, and when the checkout +/// step failed while a lock file exists. A lock next to a failed fetch proves nothing, because the +/// fetch takes no lock, so that failure gets the plain retry. The library never deletes a lock, because +/// nothing here shows who owns it. A lookup that fails falls back to the plain retry. +let private hydrationRecovery + (hooks: GitSessionHooks) + (repoPath: string) + (failure: OperationFailure) + (checkoutFailed: bool) + (context: OperationContext) + : Async = + async { + let removeLock = { + Code = "remove_index_lock" + Instructions = + Some + "An index.lock in the repository blocks the checkout of large files. Make sure no git process is running on the repository and remove the lock file if it is still there. Then retry the download." + } + + let namedByGit = + Array.append [| failure.Message |] failure.Details + |> Array.exists (fun text -> (GitInternals.tryIndexLockFailure text).IsSome) + + if namedByGit then + return removeLock + elif not checkoutFailed then + return materializationRecovery failure + else + let! heldLock = tryFindHeldIndexLock hooks repoPath context + + match heldLock with + | Some _ -> return removeLock + | None -> return materializationRecovery failure + } + let private preflightIndexLock (state: SessionState) (context: OperationContext) : Async> = async { let! lockPathResult = resolveGitStatePath state "index.lock" context @@ -2113,6 +2351,29 @@ let private isMaterializedLfsObject (state: SessionState) (pathValue: string) (s with _ -> false +/// The failure of a `git lfs checkout` that wrote its files but could not update the Git index. A held +/// index lock gives the lock failure with its recovery, and any other cause gives the checkout failure. +/// The files changed in both cases. +let private lfsCheckoutIndexFailure + (state: SessionState) + (text: string) + (context: OperationContext) + : Async = + async { + let! heldLock = tryFindHeldIndexLock state.Hooks state.RepoPath context + + let failure = + match heldLock with + | Some lockPath -> GitInternals.indexLockFailure lockPath (GitInternals.tryFileAgeSeconds lockPath) + | None -> + OperationFailure.createRedacted + ProviderError + "lfs_checkout_failed" + $"Git LFS checkout failed: {text}" + + return { failure with StateChanged = true } + } + let private materializeLocalLfsObject (state: SessionState) (pathValue: string) @@ -2131,6 +2392,7 @@ let private materializeLocalLfsObject | Ok mediaDirectory when not (GitLfsObjects.isObjectLocallyAvailable mediaDirectory objectId sizeBytes) -> return LocalLfsObjectUnavailable | Ok _ -> + // The checkout is local and holds the index lock, so a cancel must not kill it. let! checkoutResult = runGit state.Hooks @@ -2142,12 +2404,18 @@ let private materializeLocalLfsObject GitLfsObjects.lfsCheckoutPattern pathValue |] None - context + { context with + Cancellation = OperationCancellation.none } match checkoutResult with | Error failure -> return LocalLfsCheckoutFailed failure | Ok output when output.ExitCode = 0 -> - return LocalLfsCheckoutCompleted(isMaterializedLfsObject state pathValue sizeBytes) + match GitLfsService.lfsCheckoutIndexUpdateFailed output.StdOut output.StdErr with + | None -> return LocalLfsCheckoutCompleted(isMaterializedLfsObject state pathValue sizeBytes) + | Some text -> + // The checkout wrote the file, so the size check would pass. + let! failure = lfsCheckoutIndexFailure state text context + return LocalLfsCheckoutFailed failure | Ok output -> let detail = if String.IsNullOrWhiteSpace output.StdErr then @@ -2164,14 +2432,17 @@ let private materializeLocalLfsObject ) } +/// Checks out the local objects of the restored paths. It returns the failures as path, text and whether a +/// cancel caused them. It also returns the recovery of a checkout that hit a held index lock. let private materializeRestoredLocalLfsObjects (state: SessionState) (restoredPaths: string[]) (context: OperationContext) - : Async<(string * string * bool)[]> = + : Async<(string * string * bool)[] * RecoveryAction option> = async { let candidates = ResizeArray() let failures = ResizeArray() + let lockRecoveries = ResizeArray() for pathValue in restoredPaths do let! pointerResult = GitLfsObjects.readWorktreePointer state.RepoPath pathValue @@ -2209,19 +2480,32 @@ let private materializeRestoredLocalLfsObjects |> Seq.toArray for chunk in Array.chunkBySize 50 availableCandidates do + // The checkout is local and holds the index lock, so a cancel must not kill it. A + // cancel that arrived earlier stops the chunks that have not started. let! checkoutResult = - runGit - state.Hooks - state.RepoPath - [| - "lfs" - "checkout" - "--" - for pathValue, _ in chunk do - GitLfsObjects.lfsCheckoutPattern pathValue - |] - None - context + if context.Cancellation.IsCancellationRequested() then + async.Return( + Error( + OperationFailure.create + Canceled + "operation_canceled" + "The operation was canceled before the process started." + ) + ) + else + runGit + state.Hooks + state.RepoPath + [| + "lfs" + "checkout" + "--" + for pathValue, _ in chunk do + GitLfsObjects.lfsCheckoutPattern pathValue + |] + None + { context with + Cancellation = OperationCancellation.none } match checkoutResult with | Error failure -> @@ -2230,13 +2514,23 @@ let private materializeRestoredLocalLfsObjects for pathValue, _ in chunk do failures.Add(pathValue, failure.Message, canceled) | Ok output when output.ExitCode = 0 -> - for pathValue, pointer in chunk do - if not (isMaterializedLfsObject state pathValue pointer.SizeInBytes) then - failures.Add( - pathValue, - "Git LFS checkout did not write the expected object content.", - false - ) + match GitLfsService.lfsCheckoutIndexUpdateFailed output.StdOut output.StdErr with + | Some text -> + // The checkout wrote the files, so the content check below would pass. + let! indexFailure = lfsCheckoutIndexFailure state text context + + indexFailure.RecoveryAction |> Option.iter lockRecoveries.Add + + for pathValue, _ in chunk do + failures.Add(pathValue, indexFailure.Message, false) + | None -> + for pathValue, pointer in chunk do + if not (isMaterializedLfsObject state pathValue pointer.SizeInBytes) then + failures.Add( + pathValue, + "Git LFS checkout did not write the expected object content.", + false + ) | Ok output -> let detail = if String.IsNullOrWhiteSpace output.StdErr then @@ -2249,7 +2543,7 @@ let private materializeRestoredLocalLfsObjects for pathValue, _ in chunk do failures.Add(pathValue, detail, canceled) - return failures.ToArray() + return failures.ToArray(), Seq.tryHead lockRecoveries } let private restorePaths (state: SessionState) (request: RestoreRequest) (context: OperationContext) = @@ -2310,7 +2604,7 @@ let private restorePaths (state: SessionState) (request: RestoreRequest) (contex match result with | Error failure -> return Failed failure | Ok restoredPaths -> - let! materializationFailures = + let! materializationFailures, lockRecovery = materializeRestoredLocalLfsObjects state restoredPaths @@ -2341,7 +2635,7 @@ let private restorePaths (state: SessionState) (request: RestoreRequest) (contex OperationResult.partiallySucceeded (OperationOutcome.performed ()) failure - (localMaterializationRecovery ()) + (lockRecovery |> Option.defaultWith localMaterializationRecovery) } let private listRefs (state: SessionState) (context: OperationContext) = @@ -3376,13 +3670,9 @@ let private refresh (state: SessionState) (context: OperationContext) = | Error failure -> return Failed failure | Ok authArguments -> - let! fetchResult = - runGitChecked - state.Hooks - state.RepoPath - [| yield! authArguments; "fetch"; remote |] - None - context + reportStepStart "fetch" "Fetching online changes" context + + let! fetchResult = runGitFetchChecked state.Hooks state.RepoPath authArguments remote context match fetchResult with | Error failure -> return Failed { failure with Retryable = true } @@ -3517,13 +3807,14 @@ let private readMaterializeLargeObjects (state: SessionState) (context: Operatio | Error failure -> Error failure } -/// Downloads the large objects of the checkout from the upstream remote of `targetRef`. +/// Downloads the large objects of the checkout from the upstream remote of `targetRef`. A failure comes +/// with the recovery that fits it. let private downloadLargeObjects (state: SessionState) (targetRef: LogicalRef option) (operation: string) (context: OperationContext) - : Async> = + : Async> = async { let! remoteResult = match targetRef with @@ -3551,29 +3842,33 @@ let private downloadLargeObjects match authentication with | Error failure -> return Error failure | Ok authentication -> - return! - runGitEnv + reportStepStart "lfs-pull" "Downloading large files" context + + let! run = + runLfsHydration + "lfs-pull" state.Hooks state.RepoPath - (GitCredentialStrategy.buildLfsTransferArguments - authentication.ConfigArgs - [| - "lfs" - "pull" - remote - yield! hydrationRef |> Option.toArray - |]) - None - [| "GIT_TERMINAL_PROMPT", "0" |] + authentication.ConfigArgs + [| remote; yield! hydrationRef |> Option.toArray |] context + + return Ok run } + let failedWith (failure: OperationFailure) (checkoutFailed: bool) = async { + let! recovery = hydrationRecovery state.Hooks state.RepoPath failure checkoutFailed context + return Error(failure, recovery) + } + match hydration with - | Ok output when output.ExitCode = 0 -> return Ok() - | Ok output -> - let detail = if String.IsNullOrWhiteSpace output.StdErr then output.StdOut else output.StdErr - return Error(hydrationFailure operation detail) - | Error failure -> return Error { failure with Code = "hydration_failed" } + | Error failure -> return! failedWith { failure with Code = "hydration_failed" } false + | Ok run -> + match run.Output with + | Ok output when output.ExitCode = 0 -> return Ok() + | Ok output -> + return! failedWith (hydrationOutputFailure operation output run.Details) run.CheckoutFailed + | Error failure -> return! failedWith { failure with Code = "hydration_failed" } run.CheckoutFailed } /// Without anything to merge, an update still downloads the large objects of the checkout @@ -3598,7 +3893,7 @@ let private downloadLargeObjectsWithoutUpdate match downloaded with | Ok() -> return Succeeded outcome - | Error failure -> return OperationResult.partiallySucceeded outcome failure (materializationRecovery failure) + | Error(failure, recovery) -> return OperationResult.partiallySucceeded outcome failure recovery | _ -> return Succeeded outcome } @@ -3646,6 +3941,8 @@ let private updateFromState false ) else + reportStepStart "merge" "Merging online changes" context + let! result = runGitEnv state.Hooks @@ -3763,18 +4060,17 @@ let private updateFromState ResultingRevision = newState.WorkspaceRevision } - let partial failure = - OperationResult.partiallySucceeded - outcome - { - failure with - AffectedPaths = affectedPaths - } - (materializationRecovery failure) - match hydration with | Ok _ -> return Succeeded outcome - | Error failure -> return partial failure + | Error(failure, recovery) -> + return + OperationResult.partiallySucceeded + outcome + { + failure with + AffectedPaths = affectedPaths + } + recovery | Ok output, Ok start -> reportProgressReset "update-inspection" context let inspectionContext = startInspection () @@ -4203,6 +4499,7 @@ let private publish (state: SessionState) (expectedTarget: RevisionId option) (c fetchAuthentication authentication (Some reportLfsProgress) + (NodeOutput.OutputTarget.ofContext context) context.Cancellation.IsCancellationRequested |> Async.AwaitPromise @@ -4689,12 +4986,7 @@ let private publish (state: SessionState) (expectedTarget: RevisionId option) (c } | Ok authArguments -> let! fetchResult = - runGitChecked - state.Hooks - state.RepoPath - [| yield! authArguments; "fetch"; remoteName |] - None - context + runGitFetchChecked state.Hooks state.RepoPath authArguments remoteName context match fetchResult with | Error failure -> @@ -5418,7 +5710,14 @@ let private createConflictService (state: SessionState) : ConflictResolutionServ when context.Cancellation.IsCancellationRequested() -> return Ok([||], Some(canceledMaterializationFailure failure.Message)) | LocalLfsCheckoutFailed failure -> - return Ok([||], Some(materializationFailure failure.Message)) + return + Ok( + [||], + Some { + materializationFailure failure.Message with + RecoveryAction = failure.RecoveryAction + } + ) | _ -> return Ok(objectNotMaterialized (), None) } @@ -5457,7 +5756,8 @@ let private createConflictService (state: SessionState) : ConflictResolutionServ OperationResult.partiallySucceeded outcome failure - (localMaterializationRecovery ()) + (failure.RecoveryAction + |> Option.defaultWith localMaterializationRecovery) }) Finalize = fun request context -> @@ -5817,6 +6117,18 @@ let private createSessionWithTextDiff LfsMediaDirectory = None } + // A Save in the middle of a Free or Download could commit the file while it is missing + // or half written, so these bodies take the mutation lock like every other workspace change. + // The lock is not re-entrant, and nothing inside these bodies takes it again. + let serializeLargeObjectWork (body: unit -> Async>) = async { + do! state.Lock.Acquire() + + try + return! body () + finally + state.Lock.Release() + } + let core: CoreVersionControl = { GetStatus = fun context -> getWorkspaceStatus state context ListRefs = fun context -> listRefs state context @@ -5947,17 +6259,17 @@ let private createSessionWithTextDiff state.Credentials state.ConnectionProfileId (preflightIndexLock state) - // A Save in the middle of a Free or Download could commit the file while it is missing - // or half written, so these bodies take the mutation lock like every other workspace change. - // The lock is not re-entrant, and nothing inside these bodies takes it again. - (fun body -> async { - do! state.Lock.Acquire() - - try - return! body () - finally - state.Lock.Release() - }) + serializeLargeObjectWork + ) + ObjectBatchMaterialization = + Some( + GitLfsExtensions.createObjectBatchMaterialization + state.RepoPath + (fun arguments context -> runGit state.Hooks state.RepoPath arguments None context) + state.Credentials + state.ConnectionProfileId + (preflightIndexLock state) + serializeLargeObjectWork ) StoragePolicy = Some( @@ -6511,21 +6823,24 @@ let private createFactoryWithSessions | Error failure -> return Error failure | Ok () -> cloneStarted <- true + reportStepStart "clone" "Cloning the repository" context // Git keeps large objects as pointers until hydration so a download // failure can be reported as partial success. return! - runGitEnv + runGitTransfer + "clone" + false hooks "." [| yield! authentication.ConfigArgs "clone" + "--progress" "--" location.ProviderLocation request.TargetPath |] - None [| "GIT_TERMINAL_PROMPT", "0" "GIT_LFS_SKIP_SMUDGE", "1" @@ -6575,43 +6890,42 @@ let private createFactoryWithSessions // that hides the changed workspace. let! hydration = if context.Cancellation.IsCancellationRequested() then - async.Return( - Error( - OperationFailure.create - Canceled - "operation_canceled" - "The clone was canceled before large-object download started." - ) - ) + async.Return { + Output = + Error( + OperationFailure.create + Canceled + "operation_canceled" + "The clone was canceled before large-object download started." + ) + CheckoutFailed = false + Details = [||] + } else - reportProgressReset "clone-lfs-pull" context - runGitEnv + reportStepStart "clone-lfs-pull" "Downloading large files" context + + runLfsHydration + "clone-lfs-pull" hooks request.TargetPath - (GitCredentialStrategy.buildLfsTransferArguments - authentication.ConfigArgs - [| "lfs"; "pull"; "origin" |]) - None - [| "GIT_TERMINAL_PROMPT", "0" |] + authentication.ConfigArgs + [| "origin" |] context - match hydration with + match hydration.Output with | Ok hydrationOutput when hydrationOutput.ExitCode = 0 -> return OperationResult.succeeded binding | Ok hydrationOutput -> - let detail = - if String.IsNullOrWhiteSpace hydrationOutput.StdErr then - hydrationOutput.StdOut - else - hydrationOutput.StdErr + let failure = hydrationOutputFailure "clone" hydrationOutput hydration.Details - let failure = hydrationFailure "clone" detail + let! recovery = + hydrationRecovery hooks request.TargetPath failure hydration.CheckoutFailed context return OperationResult.partiallySucceeded (OperationOutcome.performed binding) failure - (materializationRecovery failure) + recovery | Error hydrationFailure -> if hydrationFailure.Category = Canceled then let! cleanupError = removeCloneResidue () @@ -6620,11 +6934,19 @@ let private createFactoryWithSessions return Failed(withResidue canceledFailure cleanupError) else + let! recovery = + hydrationRecovery + hooks + request.TargetPath + hydrationFailure + hydration.CheckoutFailed + context + return OperationResult.partiallySucceeded (OperationOutcome.performed binding) hydrationFailure - (materializationRecovery hydrationFailure) + recovery } Adopt = fun request context -> @@ -6763,7 +7085,14 @@ let private createFactoryWithSessions location.ConnectionProfileId let! _ = - runGit hooks request.WorkspaceRoot [| yield! authArguments; "fetch"; "origin" |] None context + runGitTransfer + "fetch" + false + hooks + request.WorkspaceRoot + (fetchArguments authArguments "origin") + [||] + context return OperationResult.succeeded (bindingFor request.WorkspaceRoot location) } diff --git a/src/VersionControlService.Git/VersionControlService.Git.fsproj b/src/VersionControlService.Git/VersionControlService.Git.fsproj index 5cb1bd4..2184421 100644 --- a/src/VersionControlService.Git/VersionControlService.Git.fsproj +++ b/src/VersionControlService.Git/VersionControlService.Git.fsproj @@ -29,10 +29,10 @@ + - diff --git a/src/VersionControlService.Runtime.Node/OutputReporter.fs b/src/VersionControlService.Runtime.Node/OutputReporter.fs new file mode 100644 index 0000000..4ba6ae6 --- /dev/null +++ b/src/VersionControlService.Runtime.Node/OutputReporter.fs @@ -0,0 +1,567 @@ +/// The raw output channel of an operation. A runner opens one command per subprocess, feeds it the decoded +/// text of each stream and finishes it when the process ends. The channel redacts every line, collapses +/// carriage-return rewrites, bounds line length and queue size, and hands the host batches. A runner +/// asks for the channel through the operation context, so nothing runs for a host that set no callback. +module VersionControlService.Runtime.Node.OutputReporter + +open System +open System.Text +open System.Text.RegularExpressions +open Fable.Core +open VersionControlService.Abstractions + +/// Longest line the channel keeps, in UTF-16 units. A longer line is dropped and a notice takes its place. +[] +let MaxLineLength = 4096 + +/// Most entries in one delivered batch. +[] +let MaxBatchEntries = 20 + +/// Most entries waiting for delivery. A full queue drops its oldest line. +[] +let MaxQueuedEntries = 128 + +/// The shortest time between two batches, which allows ten batches per second. +let BatchIntervalMilliseconds = 100.0 + +/// The shortest time between two snapshots of a line that is being rewritten. +let SnapshotIntervalMilliseconds = 250.0 + +/// Most arguments a command header shows after the leading configuration pairs. +[] +let MaxHeaderArguments = 12 + +/// Longest argument a command header shows. The cut keeps a header inside the line limit. +[] +let MaxHeaderArgumentLength = 200 + +/// A secret shorter than this is not replaced, because it would also hit unrelated text. +[] +let MinSecretLength = 4 + +/// Time source of a channel. Tests substitute a clock they control. +type OutputClock = { + Now: unit -> float + /// Runs the callback after the delay in milliseconds and returns a function that cancels it. + Schedule: float -> (unit -> unit) -> (unit -> unit) +} + +[] +let private dateNow () : float = jsNative + +let systemClock: OutputClock = { + Now = dateNow + Schedule = + fun delay callback -> + let handle = JS.setTimeout callback (int (Math.Ceiling delay)) + fun () -> JS.clearTimeout handle +} + +[ { try { return Buffer.from($0, 'base64').toString('utf8'); } catch (e) { return ''; } })()")>] +let private decodeBase64 (_value: string) : string = jsNative + +[ { try { return decodeURIComponent($0); } catch (e) { return $0; } })()")>] +let private decodeUriComponent (_value: string) : string = jsNative + +[] +let private encodeUriComponent (_value: string) : string = jsNative + +/// The string entries of an environment object, for the secret scan. +[ typeof entry[1] === 'string')")>] +let environmentEntries (_environment: obj) : (string * string)[] = jsNative + +let private escapeSequencePattern = + Regex(@"\u001b\[[0-?]*[ -/]*[@-~]|\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)|\u001b[@-Z\\-_]") + +// Tab stays. Line terminators never reach the pattern, because the framer splits on them. +let private controlCharacterPattern = Regex(@"[\u0000-\u0008\u000b-\u001f\u007f-\u009f]") + +// A user name can hold an "@" (an e-mail address), so the userinfo ends at the last "@" before the first "/". +let private urlUserInfoPattern = Regex(@"://(?[^/\s]+)@") + +let private headerValuePattern = + Regex( + @"(?:authorization\s*:\s*(?:(?bearer|basic|token)\s+)?|private-token\s*:\s*|x-access-token\s*:\s*)(?[^\s'""]+)", + RegexOptions.IgnoreCase + ) + +let private credentialNamePattern = + Regex(@"token|secret|passw|passphrase|credential|apikey|api_key|access_key", RegexOptions.IgnoreCase) + +let private addSecret (secrets: ResizeArray) (value: string) = + if not (isNull value) && value.Length >= MinSecretLength then + secrets.Add value + +// A value as written, decoded and encoded, because a URL carries the percent-encoded form of a secret. +let private addEncodedForms (secrets: ResizeArray) (value: string) = + if not (String.IsNullOrEmpty value) then + let decoded = decodeUriComponent value + addSecret secrets value + addSecret secrets decoded + addSecret secrets (encodeUriComponent decoded) + +let private addUserInfo (secrets: ResizeArray) (userInfo: string) = + addEncodedForms secrets userInfo + let colon = userInfo.IndexOf ':' + + if colon >= 0 then + addEncodedForms secrets (userInfo.Substring(0, colon)) + addEncodedForms secrets (userInfo.Substring(colon + 1)) + +// The payload of a Basic header is base64 text of "user:secret", and the parts are secrets of their own. +let private addHeaderValue (secrets: ResizeArray) (scheme: string) (value: string) = + addSecret secrets value + + if String.Equals(scheme, "basic", StringComparison.OrdinalIgnoreCase) then + let decoded = decodeBase64 value + let colon = decoded.IndexOf ':' + + if colon > 0 && decoded.IndexOf '�' < 0 then + addSecret secrets decoded + addSecret secrets (decoded.Substring(0, colon)) + addSecret secrets (decoded.Substring(colon + 1)) + +let private collectFromText (secrets: ResizeArray) (text: string) = + if not (String.IsNullOrEmpty text) then + for matched in urlUserInfoPattern.Matches text do + addUserInfo secrets matched.Groups["userinfo"].Value + + for matched in headerValuePattern.Matches text do + addHeaderValue secrets matched.Groups["scheme"].Value matched.Groups["value"].Value + +/// The secrets a command carries, longest first so that "user:secret" is replaced before "secret". They come +/// from the authentication in the arguments (config values, URL userinfo, Authorization headers and the +/// decoded Basic payload) and from credential-looking environment entries. A value shorter than four +/// characters is left out. +let collectSecrets (arguments: string[]) (environment: (string * string)[]) : string[] = + let secrets = ResizeArray() + let mutable index = 0 + + while index < arguments.Length do + if arguments[index] = "-c" && index + 1 < arguments.Length then + let setting = arguments[index + 1] + collectFromText secrets setting + let equals = setting.IndexOf '=' + + if equals > 0 && credentialNamePattern.IsMatch(setting.Substring(0, equals)) then + addSecret secrets (setting.Substring(equals + 1)) + + index <- index + 2 + else + collectFromText secrets arguments[index] + index <- index + 1 + + for name, value in environment do + collectFromText secrets value + + if credentialNamePattern.IsMatch name then + addSecret secrets value + + secrets + |> Seq.distinct + |> Seq.sortByDescending (fun secret -> secret.Length) + |> Seq.toArray + +/// Replaces each known secret and then applies the structural redaction. +let redactText (secrets: string[]) (text: string) : string = + let mutable result = text + + for secret in secrets do + if result.Contains secret then + result <- result.Replace(secret, "[REDACTED]") + + Redaction.redact result + +/// The arguments after the leading `-c key=value` pairs, which can hold credentials. +let withoutLeadingConfig (arguments: string[]) : string[] = + let mutable first = 0 + + while first + 1 < arguments.Length && arguments[first] = "-c" do + first <- first + 2 + + arguments |> Array.skip first + +/// The header line of a command: the program and its arguments without the leading configuration pairs. +/// It shows at most twelve arguments and then "...". The header redacts each argument with the secrets +/// before it cuts the argument to 200 characters, because a cut could leave a part of a long secret that +/// no longer matches. +let commandHeader (secrets: string[]) (command: string) (arguments: string[]) : string = + let shown = withoutLeadingConfig arguments + + let clip (argument: string) = + let redacted = redactText secrets argument + + if redacted.Length > MaxHeaderArgumentLength then + redacted.Substring(0, MaxHeaderArgumentLength) + "..." + else + redacted + + let words = + Array.append [| redactText secrets command |] (shown |> Array.truncate MaxHeaderArguments |> Array.map clip) + + let header = String.Join(" ", words) + + if shown.Length > MaxHeaderArguments then header + " ..." else header + +/// The batching queue of one operation. Entries wait here until the rate limit lets a batch go. A full +/// queue drops its oldest line and keeps the command headers, unless it holds nothing but headers. Flush +/// bypasses the rate limit, so the end of each subprocess delivers its pending entries at once. Within a +/// subprocess the limit holds. +[] +type OutputChannel(clock: OutputClock, deliver: OperationOutput[] -> unit) = + let queue = ResizeArray() + let mutable omitted = 0 + let mutable lastDelivery = -1.0e12 + let mutable cancelTimer: (unit -> unit) option = None + let mutable commandCount = 0 + + let hasPending () = queue.Count > 0 || omitted > 0 + + let takeBatch () = + let batch = ResizeArray() + + if omitted > 0 then + batch.Add { + CommandId = "" + Kind = OperationOutputKind.Notice + Text = if omitted = 1 then "1 output line was omitted." else $"{omitted} output lines were omitted." + IsPartial = false + } + + omitted <- 0 + + let count = min queue.Count (MaxBatchEntries - batch.Count) + batch.AddRange(queue.GetRange(0, count)) + queue.RemoveRange(0, count) + batch.ToArray() + + let deliverBatch () = + let batch = takeBatch () + lastDelivery <- clock.Now() + + if batch.Length > 0 then + try + deliver batch + with _ -> + () + + let rec pump () = + if hasPending () then + let elapsed = clock.Now() - lastDelivery + + if elapsed >= BatchIntervalMilliseconds then + deliverBatch () + + if hasPending () && cancelTimer.IsNone then + arm BatchIntervalMilliseconds + elif cancelTimer.IsNone then + arm (BatchIntervalMilliseconds - elapsed) + + and arm (delay: float) = + cancelTimer <- + Some( + clock.Schedule delay (fun () -> + cancelTimer <- None + pump ()) + ) + + member _.Clock = clock + + /// An identifier for the next command, unique within the channel. + member _.NextCommandId() = + commandCount <- commandCount + 1 + string commandCount + + /// Queues an entry. A partial entry that is still waiting for its replacement is replaced in place. + member _.Enqueue(entry: OperationOutput) = + let mutable index = queue.Count - 1 + + while index >= 0 + && not (queue[index].CommandId = entry.CommandId && queue[index].Kind = entry.Kind) do + index <- index - 1 + + if index >= 0 && queue[index].IsPartial then + queue[index] <- entry + else + if queue.Count >= MaxQueuedEntries then + // A header names the subprocess that the lines after it belong to, so a line goes first. + let victim = + queue + |> Seq.tryFindIndex (fun waiting -> waiting.Kind <> OperationOutputKind.Command) + |> Option.defaultValue 0 + + queue.RemoveAt victim + omitted <- omitted + 1 + + queue.Add entry + + pump () + + /// Delivers everything that waits, in batches of at most twenty, and ignores the rate limit. A runner + /// calls this when a process ends, so the host has the output before the operation completes. The + /// pending entries of a subprocess therefore arrive at once, whatever the rate was before. + member _.Flush() = + cancelTimer |> Option.iter (fun cancel -> cancel ()) + cancelTimer <- None + + while hasPending () do + deliverBatch () + +/// Turns the text of one stream into lines. It treats CRLF as one newline even across chunks, keeps only the +/// latest segment of a line that is rewritten with carriage returns, drops terminal escape sequences and +/// control characters, and replaces a line over the length limit with a notice. +type private LineFramer + ( + kind: OperationOutputKind, + commandId: string, + secrets: string[], + clock: OutputClock, + enqueue: OperationOutput -> unit + ) = + let current = StringBuilder() + // The last segment that a lone carriage return ended. A later segment of the same line replaces it. + let mutable held: string = null + let mutable afterCarriageReturn = false + let mutable overlong = false + // Text of the partial entry sent for the line in progress, null when none was sent. + let mutable lastPartial: string = null + let mutable partialAt = -1.0e12 + let mutable finished = false + let mutable cancelSnapshotTimer: (unit -> unit) option = None + + let stopSnapshotTimer () = + cancelSnapshotTimer |> Option.iter (fun cancel -> cancel ()) + cancelSnapshotTimer <- None + + let clean (raw: string) = + if isNull raw then + "" + else + raw + |> fun text -> escapeSequencePattern.Replace(text, "") + |> fun text -> controlCharacterPattern.Replace(text, "") + |> redactText secrets + |> fun text -> text.TrimEnd() + + let emit (text: string) (isPartial: bool) = + enqueue { + CommandId = commandId + Kind = kind + Text = text + IsPartial = isPartial + } + + let omitLongLine () = + enqueue { + CommandId = commandId + Kind = OperationOutputKind.Notice + Text = $"A line longer than {MaxLineLength} characters was omitted." + IsPartial = false + } + + overlong <- false + current.Clear() |> ignore + + // The host keeps a partial entry until a complete one with the same command and kind replaces it. + let closePartial () = + if not (isNull lastPartial) then + emit lastPartial false + lastPartial <- null + + // The latest segment is the line. A blank line is dropped, except that it closes a snapshot already sent. + let completeLine () = + stopSnapshotTimer () + let latest = clean (current.ToString()) + let text = if String.IsNullOrWhiteSpace latest then clean held else latest + + if not (String.IsNullOrWhiteSpace text) then + emit text false + elif not (isNull lastPartial) then + emit lastPartial false + + current.Clear() |> ignore + held <- null + lastPartial <- null + afterCarriageReturn <- false + + // The next character decides whether this was half of a CRLF or a rewrite. + let endSegment () = + if overlong then + omitLongLine () + // A line feed right after this segment must not complete the text of an earlier segment. + held <- null + elif current.Length > 0 then + held <- current.ToString() + current.Clear() |> ignore + + afterCarriageReturn <- true + + let endLine () = + if overlong then + stopSnapshotTimer () + closePartial () + omitLongLine () + held <- null + else + completeLine () + + afterCarriageReturn <- false + + // A snapshot that the interval holds back goes out when the interval ends, even if no more text comes. + let rec publishSnapshot () = + if not finished && not (isNull held) then + let now = clock.Now() + let waited = now - partialAt + + if waited >= SnapshotIntervalMilliseconds then + stopSnapshotTimer () + let text = clean held + + if not (String.IsNullOrWhiteSpace text) && text <> lastPartial then + emit text true + lastPartial <- text + partialAt <- now + elif cancelSnapshotTimer.IsNone then + cancelSnapshotTimer <- + Some( + clock.Schedule (SnapshotIntervalMilliseconds - waited) (fun () -> + cancelSnapshotTimer <- None + publishSnapshot ()) + ) + + member _.Push(text: string) = + if not finished then + for character in text do + if afterCarriageReturn && character = '\n' then + completeLine () + else + afterCarriageReturn <- false + + if character = '\r' then endSegment () + elif character = '\n' then endLine () + elif overlong then () + elif current.Length >= MaxLineLength then + overlong <- true + current.Clear() |> ignore + else + current.Append character |> ignore + + publishSnapshot () + + /// Sends the final state of the line in progress, which is the unterminated text at the end of a stream. + member _.Finish() = + if not finished then + finished <- true + stopSnapshotTimer () + + if overlong then + closePartial () + omitLongLine () + held <- null + else + completeLine () + +/// The output of one subprocess. The runner passes the decoded text of each stream to it and calls Finish +/// once the process has ended, whatever the reason. Finish flushes the channel, so the end of every +/// subprocess delivers its pending entries at once and the batch rate holds only within a subprocess. +[] +type CommandOutput(channel: OutputChannel, commandId: string, secrets: string[], reportStdout: bool) = + let stdoutFramer = + LineFramer(OperationOutputKind.StdOut, commandId, secrets, channel.Clock, channel.Enqueue) + + let stderrFramer = + LineFramer(OperationOutputKind.StdErr, commandId, secrets, channel.Clock, channel.Enqueue) + + let mutable finished = false + + member _.ObserveStdout(text: string) = + if reportStdout && not finished then + stdoutFramer.Push text + + member _.ObserveStderr(text: string) = + if not finished then + stderrFramer.Push text + + /// Sends the last state of both streams and everything that still waits in the channel. + member _.Finish() = + if not finished then + finished <- true + stdoutFramer.Finish() + stderrFramer.Finish() + channel.Flush() + +/// Where a spawned command reports its output. ReportStdout is set only by a call that declared its +/// stdout as diagnostic text. +type OutputTarget = { + Channel: OutputChannel + ReportStdout: bool +} + +type private ChannelRegistry = + abstract get: key: obj -> OutputChannel + abstract set: key: obj * channel: OutputChannel -> unit + +[] +let private createRegistry () : ChannelRegistry = jsNative + +// The context records are copied freely, and the callback function is what all copies share. +let private registry = createRegistry () + +/// A channel with the given clock and delivery function. Tests use it to control time. +let createChannel (clock: OutputClock) (deliver: OperationOutput[] -> unit) : OutputChannel = + OutputChannel(clock, deliver) + +/// The channel of the operation that owns the context, or None when its host set no output callback. +/// All copies of one context share one channel, so the batching limits hold per operation. +let tryOf (context: OperationContext) : OutputChannel option = + match context.ReportOutput with + | None -> None + | Some report -> + let key = box report + let existing = registry.get key + + if isNull existing then + let channel = OutputChannel(systemClock, report) + registry.set (key, channel) + Some channel + else + Some existing + +module OutputTarget = + + /// A target that reports stderr only, or None when the context has no output callback. + let ofContext (context: OperationContext) : OutputTarget option = + tryOf context + |> Option.map (fun channel -> + { + Channel = channel + ReportStdout = false + }) + + /// The same target for a call that declared its stdout as diagnostic text. + let withStdout (target: OutputTarget option) : OutputTarget option = + target |> Option.map (fun current -> { current with ReportStdout = true }) + +/// Starts a command: queues its header and returns the object that frames its streams. `headerArguments` +/// feed the header and `secretArguments` feed the secret scan. They differ when a tool applies part of its +/// configuration itself. The header leaves out the leading `-c` pairs. +let beginCommand + (channel: OutputChannel) + (command: string) + (headerArguments: string[]) + (secretArguments: string[]) + (environment: (string * string)[]) + (reportStdout: bool) + : CommandOutput = + let secrets = collectSecrets secretArguments environment + let commandId = channel.NextCommandId() + + channel.Enqueue { + CommandId = commandId + Kind = OperationOutputKind.Command + Text = commandHeader secrets command headerArguments + IsPartial = false + } + + CommandOutput(channel, commandId, secrets, reportStdout) diff --git a/src/VersionControlService.Runtime.Node/Process.fs b/src/VersionControlService.Runtime.Node/Process.fs index 8ba52cb..73320dc 100644 --- a/src/VersionControlService.Runtime.Node/Process.fs +++ b/src/VersionControlService.Runtime.Node/Process.fs @@ -19,6 +19,13 @@ type ProcessRequest = { Environment: (string * string)[] /// Stable progress phase code attached to parsed meter events. ProgressPhase: string + /// Also reads meter lines from stdout. Stderr is always read. Stdout is off by default because + /// plumbing output such as `status -z` is data. Only a few tools print meters there, such as + /// git-lfs with GIT_LFS_FORCE_PROGRESS. + ObserveStdoutProgress: bool + /// Also reports stdout to the context's output channel. Stderr always goes there when the context + /// has an output callback. Set it only for a call whose stdout is diagnostic text. + ReportStdoutOutput: bool } module ProcessRequest = @@ -30,6 +37,8 @@ module ProcessRequest = StdinData = None Environment = [||] ProgressPhase = "process" + ObserveStdoutProgress = false + ReportStdoutOutput = false } type ProcessOutput = { @@ -110,10 +119,11 @@ let progressMeterCompletedTotal (meter: ProgressMeter) = | Some(_, 1) -> None | _ -> Some(meter.Percent, 100.0) -let private reportProgressMeter (phaseCode: string) (context: OperationContext) (meter: ProgressMeter) = +/// The progress event of a parsed meter under the given phase code. The display text is redacted. +let progressOfMeter (phaseCode: string) (meter: ProgressMeter) : OperationProgress = let completedTotal = progressMeterCompletedTotal meter - context.ReportProgress { + { PhaseCode = phaseCode Item = None Completed = completedTotal |> Option.map fst @@ -121,6 +131,27 @@ let private reportProgressMeter (phaseCode: string) (context: OperationContext) DisplayMessage = Some(Redaction.redact (formatProgressMeter meter)) } +let private reportProgressMeter (phaseCode: string) (context: OperationContext) (meter: ProgressMeter) = + context.ReportProgress(progressOfMeter phaseCode meter) + +let private lineWithTerminatorPattern = Regex(@"[^\r\n]*(?:\r\n|\r|\n|$)") + +/// Removes every line that tryParseProgressMeter accepts, with its terminator, so each CR-separated +/// redraw of a meter goes. The other lines keep their text and terminators. A failure message built +/// from a transfer that printed meters uses this, because a meter line says nothing about the cause. +let dropProgressMeterLines (text: string) : string = + if String.IsNullOrEmpty text then + text + else + lineWithTerminatorPattern.Replace( + text, + MatchEvaluator(fun matched -> + if (tryParseProgressMeter matched.Value).IsSome then + String.Empty + else + matched.Value) + ) + let createMeterObserver (reportLine: string -> unit) = let pending = System.Text.StringBuilder() @@ -166,7 +197,9 @@ let killProcessTree (pid: int) : unit = /// Runs a child process under the operation context. On cancellation, it terminates /// the process tree and returns a canceled failure with StateChanged = false. -/// Parsed progress meter lines are redacted before progress reporting. +/// Parsed progress meter lines are redacted before progress reporting. When the context has an output +/// callback, the call also reports its header and output lines there, and the host has them before the +/// result is returned. let run (request: ProcessRequest) (context: OperationContext) : Async> = Async.FromContinuations(fun (resolve, _, _) -> if context.Cancellation.IsCancellationRequested() then @@ -189,11 +222,28 @@ let run (request: ProcessRequest) (context: OperationContext) : Async Option.map (fun channel -> + OutputReporter.beginCommand + channel + request.Command + request.Arguments + request.Arguments + request.Environment + request.ReportStdoutOutput) + + // Every path that ends the call finishes the output first, so the host has it before the result. + let finishOutput () = + commandOutput |> Option.iter (fun output -> output.Finish()) + let child: obj = try childProcessModule?spawn (request.Command, request.Arguments, options) with error -> finished <- true + finishOutput () resolve ( OperationResult.failed ( @@ -217,23 +267,35 @@ let run (request: ProcessRequest) (context: OperationContext) : Async Option.iter (reportProgressMeter request.ProgressPhase context) - let observeStderr, flushStderr = createMeterObserver reportLine + // One observer per stream, so a chunk of one stream never lands inside a split line of the other. + let observeStdoutMeters, flushStdout = createMeterObserver reportLine + let observeStderrMeters, flushStderr = createMeterObserver reportLine + + let observeStdout (text: string) = + if request.ObserveStdoutProgress then + observeStdoutMeters text + + commandOutput |> Option.iter (fun output -> output.ObserveStdout text) + + let observeStderr (text: string) = + observeStderrMeters text + commandOutput |> Option.iter (fun output -> output.ObserveStderr text) let observeStream (stream: obj) (decoder: obj) (buffer: System.Text.StringBuilder) - (observeProgress: (string -> unit) option) + (observe: string -> unit) = if not (isNull stream) then stream?on ("data", fun (data: obj) -> let text = Interop.decodeUtf8Chunk decoder data buffer.Append text |> ignore - observeProgress |> Option.iter (fun observe -> observe text)) + observe text) |> ignore - observeStream child?stdout stdoutDecoder stdout None - observeStream child?stderr stderrDecoder stderr (Some observeStderr) + observeStream child?stdout stdoutDecoder stdout observeStdout + observeStream child?stderr stderrDecoder stderr observeStderr child?on ("exit", fun (code: obj) -> exited <- true @@ -243,6 +305,7 @@ let run (request: ProcessRequest) (context: OperationContext) : Async if not finished then finished <- true + finishOutput () resolve ( OperationResult.failed ( @@ -259,6 +322,8 @@ let run (request: ProcessRequest) (context: OperationContext) : Async ignore tail - finishStream stdoutDecoder stdout |> ignore + let stdoutTail = finishStream stdoutDecoder stdout let stderrTail = finishStream stderrDecoder stderr + if not (String.IsNullOrEmpty stdoutTail) then + observeStdout stdoutTail + if not (String.IsNullOrEmpty stderrTail) then observeStderr stderrTail + flushStdout () flushStderr () + finishOutput () resolve ( OperationResult.succeeded { diff --git a/src/VersionControlService.Runtime.Node/VersionControlService.Runtime.Node.fsproj b/src/VersionControlService.Runtime.Node/VersionControlService.Runtime.Node.fsproj index a011f31..1e42a57 100644 --- a/src/VersionControlService.Runtime.Node/VersionControlService.Runtime.Node.fsproj +++ b/src/VersionControlService.Runtime.Node/VersionControlService.Runtime.Node.fsproj @@ -13,6 +13,7 @@ + diff --git a/tests/VersionControlService.Abstractions.Tests/ContractShapeTests.fs b/tests/VersionControlService.Abstractions.Tests/ContractShapeTests.fs index 46dbdc4..f953c8e 100644 --- a/tests/VersionControlService.Abstractions.Tests/ContractShapeTests.fs +++ b/tests/VersionControlService.Abstractions.Tests/ContractShapeTests.fs @@ -301,6 +301,8 @@ let private discoverFeatures (session: WorkspaceSession) = [ "conflicts" if session.ObjectMaterialization.IsSome then "materialization" + if session.ObjectBatchMaterialization.IsSome then + "batch-materialization" if session.StoragePolicy.IsSome then "storage-policy" if session.Maintenance.IsSome then diff --git a/tests/VersionControlService.Abstractions.Tests/FallbackServicesTests.fs b/tests/VersionControlService.Abstractions.Tests/FallbackServicesTests.fs index af1a0de..36e39ad 100644 --- a/tests/VersionControlService.Abstractions.Tests/FallbackServicesTests.fs +++ b/tests/VersionControlService.Abstractions.Tests/FallbackServicesTests.fs @@ -69,6 +69,11 @@ let private expectUnsupported reason (result: OperationResult<'T>) = let private require name (service: 'T option) : 'T = service |> Option.defaultWith (fun () -> failtest $"The {name} service is absent.") +let private batchMaterialization: ObjectBatchMaterializationService = { + Materialize = fun _ _ -> async { return OperationResult.succeeded () } + Dematerialize = fun _ _ -> async { return OperationResult.succeeded () } +} + [] let fallbackServicesTests = testList "FallbackServices" [ @@ -82,6 +87,7 @@ let fallbackServicesTests = Expect.isSome filled.TextDiff "Text diff is present." Expect.isSome filled.ConflictResolution "Conflict resolution is present." Expect.isSome filled.ObjectMaterialization "Object materialization is present." + Expect.isSome filled.ObjectBatchMaterialization "Object batch materialization is present." Expect.isSome filled.StoragePolicy "Storage policy is present." Expect.isSome filled.Maintenance "Storage maintenance is present." Expect.isSome filled.RepositoryBrowser "Repository browser is present." @@ -102,6 +108,7 @@ let fallbackServicesTests = TextDiff = false ConflictResolution = false ObjectMaterialization = false + ObjectBatchMaterialization = false StoragePolicy = false Maintenance = false RepositoryBrowser = false @@ -116,6 +123,7 @@ let fallbackServicesTests = TextDiff = true ConflictResolution = true ObjectMaterialization = true + ObjectBatchMaterialization = true StoragePolicy = true Maintenance = true RepositoryBrowser = true @@ -133,6 +141,18 @@ let fallbackServicesTests = |> WorkspaceSession.availability |> fun availability -> Expect.equal availability allAvailable "A filled session reports every service." + testCase "availability reports the batch materialization service only when the provider supplies it" + <| fun () -> + let coreOnly = WorkspaceSession.createCoreOnly descriptor (FakeProvider.createCore ()) + let withBatch = { coreOnly with ObjectBatchMaterialization = Some batchMaterialization } + + Expect.isFalse + (WorkspaceSession.availability coreOnly).ObjectBatchMaterialization + "A core-only session has no batch materialization." + Expect.isTrue + (WorkspaceSession.availability withBatch).ObjectBatchMaterialization + "A supplied batch materialization service is reported." + testCaseAsync "the paged text diff fallback opens without a provider and rejects later page reads" <| async { let session = WorkspaceSession.withFallbackServices (WorkspaceSession.createCoreOnly descriptor (FakeProvider.createCore ())) @@ -233,6 +253,18 @@ let fallbackServicesTests = expectNoOp policyReason setSettingsResult |> ignore } + testCaseAsync "the batch materialization fallback returns a warned no-op for both operations" + <| async { + let session = WorkspaceSession.withFallbackServices (WorkspaceSession.createCoreOnly descriptor (FakeProvider.createCore ())) + let batch = require "object batch materialization" session.ObjectBatchMaterialization + + let reason = "The provider has no object batch materialization service." + let! materializeResult = batch.Materialize [| path |] context + let! dematerializeResult = batch.Dematerialize [| path |] context + expectNoOp reason materializeResult |> ignore + expectNoOp reason dematerializeResult |> ignore + } + testCaseAsync "synchronization operations and conflict mutations fail as unsupported" <| async { let session = WorkspaceSession.withFallbackServices (WorkspaceSession.createCoreOnly descriptor (FakeProvider.createCore ())) @@ -314,6 +346,7 @@ let fallbackServicesTests = TextDiff = true ConflictResolution = true ObjectMaterialization = true + ObjectBatchMaterialization = true StoragePolicy = true Maintenance = true RepositoryBrowser = true @@ -357,6 +390,7 @@ let fallbackServicesTests = TextDiff = true ConflictResolution = true ObjectMaterialization = true + ObjectBatchMaterialization = true StoragePolicy = true Maintenance = true RepositoryBrowser = true diff --git a/tests/VersionControlService.Abstractions.Tests/OperationResultTests.fs b/tests/VersionControlService.Abstractions.Tests/OperationResultTests.fs index 45afae5..676915d 100644 --- a/tests/VersionControlService.Abstractions.Tests/OperationResultTests.fs +++ b/tests/VersionControlService.Abstractions.Tests/OperationResultTests.fs @@ -39,6 +39,38 @@ let operationResultTests = Expect.equal calls 1 "The callback ran once and its exception was dropped." + testCase "create gives a context without an output callback" + <| fun () -> + let created = OperationContext.create "output-none" OperationCancellation.none ignore + Expect.isNone created.ReportOutput "create sets no output callback." + + Expect.isNone (OperationContext.detached "output-none-detached").ReportOutput "detached sets none either." + + testCase "createWithOutput delivers batches and drops an exception from the callback" + <| fun () -> + let delivered = ResizeArray() + + let reporting = + OperationContext.createWithOutput "output-some" OperationCancellation.none ignore delivered.Add + + let entry = { + CommandId = "1" + Kind = OperationOutputKind.StdErr + Text = "fatal: example" + IsPartial = false + } + + reporting.ReportOutput |> Option.iter (fun report -> report [| entry |]) + Expect.equal (delivered |> Seq.toList) [ [| entry |] ] "The batch reached the callback." + + let throwing = + OperationContext.createWithOutput "output-throws" OperationCancellation.none ignore (fun _ -> + failwith "Object has been destroyed") + + match throwing.ReportOutput with + | Some report -> report [| entry |] + | None -> failtest "Expected an output callback." + testCase "noOp keeps its reason" <| fun () -> match OperationResult.noOp (Some "already up to date") "value" with @@ -166,4 +198,15 @@ let operationResultTests = Expect.isFalse (failure.Message.Contains "password1") "Message credentials removed." Expect.isTrue (failure.Message.Contains "[REDACTED]") "Redaction marker present." + + testCase "redaction removes the whole userinfo of a URL whose user name holds an at sign" + <| fun () -> + let redacted = + Redaction.redact + "fatal: unable to access 'https://me@mail.com:s3cr3tTokenValue@host.example/repo.git/@v2'" + + Expect.equal + redacted + "fatal: unable to access 'https://[REDACTED]@host.example/repo.git/@v2'" + "The userinfo ends at the last at sign before the first slash." ] diff --git a/tests/VersionControlService.FableConsumer.Tests/PortableConsumer.test.fs b/tests/VersionControlService.FableConsumer.Tests/PortableConsumer.test.fs index e2f7391..474b9fc 100644 --- a/tests/VersionControlService.FableConsumer.Tests/PortableConsumer.test.fs +++ b/tests/VersionControlService.FableConsumer.Tests/PortableConsumer.test.fs @@ -386,6 +386,7 @@ Vitest.describe ( TextDiff = false ConflictResolution = true ObjectMaterialization = true + ObjectBatchMaterialization = false StoragePolicy = false Maintenance = false RepositoryBrowser = false @@ -395,6 +396,7 @@ Vitest.describe ( TextDiff = true ConflictResolution = true ObjectMaterialization = true + ObjectBatchMaterialization = true StoragePolicy = true Maintenance = true RepositoryBrowser = true @@ -434,6 +436,38 @@ Vitest.describe ( } ) + Vitest.test ( + "batch materialization fallback returns a warned no-op", + fun () -> promise { + let factory = createFakeFactory () + let context = OperationContext.detached "portable-fallback-batch-materialization" + + let workflow = async { + let! session = openFakeSession factory context + let coreOnly = WorkspaceSession.createCoreOnly session.Descriptor session.Core + let filled = WorkspaceSession.withFallbackServices coreOnly + let batch = + filled.ObjectBatchMaterialization + |> Option.defaultWith (fun () -> failwith "Expected the fallback batch materialization service.") + let! materialized = batch.Materialize [| fakePath |] context + let! dematerialized = batch.Dematerialize [| fakePath |] context + return materialized, dematerialized + } + + let! materialized, dematerialized = Async.StartAsPromise workflow + + [ materialized; dematerialized ] + |> List.iter (fun result -> + match result with + | Succeeded outcome -> + Vitest.expect(outcome.Effect).toEqual (NoOp(Some "The provider has no object batch materialization service.")) + Vitest.expect(outcome.Warnings.Length).toBe (1) + Vitest.expect(outcome.Warnings[0].Code).toBe (FallbackServiceCodes.ServiceUnavailable) + | PartiallySucceeded _ + | Failed _ -> failwith "The batch materialization fallback did not return a successful no-op.") + } + ) + Vitest.test ( "synchronization fallback reports the service-unavailable failure", fun () -> promise { @@ -478,6 +512,7 @@ Vitest.describe ( TextDiff = true ConflictResolution = true ObjectMaterialization = true + ObjectBatchMaterialization = true StoragePolicy = true Maintenance = true RepositoryBrowser = true diff --git a/tests/VersionControlService.Tests/Contracts/ExtensionProviderSuites.fs b/tests/VersionControlService.Tests/Contracts/ExtensionProviderSuites.fs index 53ad9a1..4f6f695 100644 --- a/tests/VersionControlService.Tests/Contracts/ExtensionProviderSuites.fs +++ b/tests/VersionControlService.Tests/Contracts/ExtensionProviderSuites.fs @@ -40,6 +40,25 @@ let register (harness: ProviderTestHarness) : string * (unit -> int) = expectValue "list objects" listResult |> ignore } + if harness.ExpectedServices |> List.contains "batch-materialization" then + profileTest "batch materialization of no paths changes nothing" + <| fun () -> promise { + let! workspace = harness.CreateWorkspace() + + let batchMaterialization = + match workspace.Session.ObjectBatchMaterialization with + | Some service -> service + | None -> failwith "The harness advertises batch-materialization but the session lacks it." + + let! materializeResult = run (batchMaterialization.Materialize [||] (ctx "batch-materialize-none")) + expectNoOp "batch materialize of no paths" materializeResult |> ignore + + let! dematerializeResult = + run (batchMaterialization.Dematerialize [||] (ctx "batch-dematerialize-none")) + + expectNoOp "batch dematerialize of no paths" dematerializeResult |> ignore + } + if harness.ExpectedServices |> List.contains "storage-policy" then profileTest "storage policy settings round-trip" <| fun () -> promise { diff --git a/tests/VersionControlService.Tests/Contracts/ProviderHarness.fs b/tests/VersionControlService.Tests/Contracts/ProviderHarness.fs index d866c71..2fe872a 100644 --- a/tests/VersionControlService.Tests/Contracts/ProviderHarness.fs +++ b/tests/VersionControlService.Tests/Contracts/ProviderHarness.fs @@ -188,6 +188,8 @@ module SuiteHelpers = "conflicts" if session.ObjectMaterialization.IsSome then "materialization" + if session.ObjectBatchMaterialization.IsSome then + "batch-materialization" if session.StoragePolicy.IsSome then "storage-policy" if session.Maintenance.IsSome then diff --git a/tests/VersionControlService.Tests/GitCredentials.test.fs b/tests/VersionControlService.Tests/GitCredentials.test.fs index 9608ae0..a83e79b 100644 --- a/tests/VersionControlService.Tests/GitCredentials.test.fs +++ b/tests/VersionControlService.Tests/GitCredentials.test.fs @@ -10,6 +10,7 @@ open Vitest module GitWorkspaceSession = VersionControlService.Git.GitWorkspaceSession module GitCredentialStrategy = VersionControlService.Git.GitCredentialStrategy module NodeProcess = VersionControlService.Runtime.Node.Process +module NodeOutput = VersionControlService.Runtime.Node.OutputReporter let private fsPromisesDynamic: obj = importAll "fs/promises" let private osDynamic: obj = importAll "os" @@ -447,6 +448,125 @@ Vitest.describe ( return raise error } ) + + Vitest.test ( + "a single Materialize lists the Git LFS files once and reads the status of its own path", + TestOptions(timeout = 120000), + fun () -> promise { + let! lfsProbe = runGitIn "." [| "lfs"; "version" |] + + if String.IsNullOrWhiteSpace lfsProbe then + failwith "Expected Git LFS to be available." + else + let! root = createTempDirectoryAsync () + let workPath = join [| root; "work" |] + let remoteUrl = "https://127.0.0.1:1/origin.git" + let relativePath = "materialized.bin" + let observedCommands = ResizeArray() + let stopObserving = ref ignore + + try + let! _ = runGitIn root [| "init"; "-b"; "main"; workPath |] + let! _ = runGitIn workPath [| "config"; "user.name"; "VCS Cred Tests" |] + let! _ = runGitIn workPath [| "config"; "user.email"; "cred@example.org" |] + let! _ = runGitIn workPath [| "config"; "core.autocrlf"; "false" |] + let! _ = runGitIn workPath [| "lfs"; "install"; "--local" |] + let! _ = runGitIn workPath [| "lfs"; "track"; relativePath |] + do! writeUtf8FileAsync (join [| workPath; relativePath |]) "cached LFS content\n" + let! _ = runGitIn workPath [| "add"; "-A" |] + let! _ = runGitIn workPath [| "commit"; "-m"; "test: cached materialization" |] + let! _ = runGitIn workPath [| "remote"; "add"; "origin"; remoteUrl |] + let! pointer = runGitIn workPath [| "show"; $"HEAD:{relativePath}" |] + do! writeUtf8FileAsync (join [| workPath; relativePath |]) pointer + + let! _ = + runGitIn workPath [| + "-c" + "filter.lfs.smudge=" + "-c" + "filter.lfs.process=" + "-c" + "filter.lfs.required=false" + "checkout" + "HEAD" + "--" + relativePath + |] + + let strategy: GitCredentialStrategy.GitCredentialStrategy = { + ResolveCredential = + fun _host _profileId -> + async { + return + Some { + Username = "oauth2" + Secret = testSecret + } + } + } + + let binding: WorkspaceBinding = { + SchemaVersion = WorkspaceBinding.CurrentSchemaVersion + ProviderId = gitProviderId + WorkspaceRoot = workPath + ProviderStateRef = None + Location = { + ProviderId = gitProviderId + DisplayName = None + ProviderLocation = remoteUrl + ConnectionProfileId = Some "token-profile" + } + ConnectionProfileId = Some "token-profile" + } + + let session = + GitWorkspaceSession.createSessionWithCredentials + GitWorkspaceSession.GitSessionHooks.none + strategy + binding + + let materialization = + session.ObjectMaterialization + |> Option.defaultWith (fun () -> failwith "Expected Git object materialization.") + + stopObserving.Value <- observeGitSpawnArguments observedCommands + + let! materializeResult = + materialization.Materialize + (RepositoryPath.tryCreate relativePath |> Result.defaultWith failwith) + (ctx "listing-once-materialize") + |> Async.StartAsPromise + + stopObserving.Value () + stopObserving.Value <- ignore + expectValue "materialization with one listing" materializeResult |> ignore + + let listingCommands = + observedCommands + |> Seq.filter (fun arguments -> + arguments |> Array.contains "lfs" && arguments |> Array.contains "ls-files") + |> Seq.toArray + + Vitest.expect(listingCommands.Length).toBe 1 + + let statusCommands = + observedCommands + |> Seq.filter (fun arguments -> arguments |> Array.contains "status") + |> Seq.toArray + + Vitest.expect(statusCommands.Length > 0).toBe true + + for arguments in statusCommands do + let separator = arguments |> Array.findIndex (fun argument -> argument = "--") + Vitest.expect(arguments |> Array.skip (separator + 1)).toEqual [| $":(literal){relativePath}" |] + + do! removeDirectoryAsync root + with error -> + stopObserving.Value () + do! removeDirectoryAsync root + return raise error + } + ) ) Vitest.describe ( @@ -1076,3 +1196,342 @@ Vitest.describe ( fun () -> promise { Vitest.expect(GitCredentialStrategy.tryIdentityHost input).toEqual expected } ) ) + + +[] +let private nodeExecutablePath: string = jsNative + +[] +let private toBase64 (_value: string) : string = jsNative + +let private runWithOutput (request: NodeProcess.ProcessRequest) = promise { + let batches = ResizeArray() + + let context = + OperationContext.createWithOutput "git-credential-output" OperationCancellation.none ignore batches.Add + + let! _ = Async.StartAsPromise(NodeProcess.run request context) + return batches |> Seq.collect id |> Seq.toArray +} + +// A stand-in for `git clone ` that prints the URL to stderr, like git does in a failure message. +let private runCloneStandIn (url: string) = + runWithOutput ( + NodeProcess.ProcessRequest.create nodeExecutablePath [| + "-e" + "console.error(process.argv[process.argv.length - 1])" + "--" + "clone" + url + |] + ) + +Vitest.describe ( + "Git output channel redaction", + fun () -> + Vitest.test ( + "output text never holds a secret from config arguments, URL userinfo, Bearer or Basic headers", + TestOptions(timeout = 120000), + fun () -> promise { + let secret = "p@ss word-secret-123" + let encodedSecret = "p%40ss%20word-secret-123" + let basicPayload = toBase64 $"oauth2:{secret}" + let bearerToken = "bearer-token-value-77" + let plainPassword = "plain-password-value-55" + + let credentialArguments = [| + "-c" + $"http.https://{testHost}/.extraHeader=Authorization: Basic {basicPayload}" + "-c" + $"remote.origin.lfsurl=https://oauth2:{encodedSecret}@{testHost}/origin.git/info/lfs" + "-c" + $"fixture.bearer=Authorization: Bearer {bearerToken}" + "-c" + $"fixture.password={plainPassword}" + |] + + // Git prints a value it cannot read as a boolean, which puts each secret form into stderr + // in a sentence that the structural redaction does not recognize. + let secretForms = [| + basicPayload + $"oauth2:{secret}" + secret + encodedSecret + bearerToken + plainPassword + |] + + let reported = ResizeArray() + + for form in secretForms do + let request = + NodeProcess.ProcessRequest.create "git" [| + yield! credentialArguments + "-c" + $"fixture.echo={form}" + "config" + "--bool" + "fixture.echo" + |] + + let! entries = runWithOutput request + reported.AddRange entries + + let messages = + reported + |> Seq.filter (fun entry -> entry.Kind = OperationOutputKind.StdErr) + |> Seq.toArray + + Vitest.expect(messages.Length).toBe secretForms.Length + Vitest.expect(messages |> Array.forall (fun entry -> entry.Text.Contains "[REDACTED]")).toBe true + + for entry in reported do + for form in secretForms do + Vitest.expect(entry.Text.Contains form).toBe false + } + ) + + Vitest.test ( + "the command header leaves out the leading config pairs and cuts a long argument list", + TestOptions(timeout = 120000), + fun () -> promise { + let request = + NodeProcess.ProcessRequest.create "git" [| + "-c" + $"http.https://{testHost}/.extraHeader=Authorization: Basic {toBase64 testSecret}" + "-c" + "fixture.setting=1" + "config" + "--bool" + "fixture.missing" + |] + + let! entries = runWithOutput request + + Vitest.expect( + entries + |> Array.filter (fun entry -> entry.Kind = OperationOutputKind.Command) + |> Array.map (fun entry -> entry.Text) + ).toEqual [| "git config --bool fixture.missing" |] + + let manyArguments = [| for number in 1..14 -> $"argument{number}" |] + let header = NodeOutput.commandHeader [||] "git" manyArguments + + Vitest.expect(header).toBe ( + "git " + + (manyArguments |> Array.truncate NodeOutput.MaxHeaderArguments |> String.concat " ") + + " ..." + ) + } + ) + + Vitest.test ( + "the command header redacts a long token in a clone URL before it cuts the argument", + TestOptions(timeout = 120000), + fun () -> promise { + // The URL is well over 200 characters, the length at which the header cuts an argument. + let token = String.replicate 25 "aB3dEf9hIj" + let! entries = runCloneStandIn $"https://oauth2:{token}@{testHost}/origin.git" + + Vitest.expect(entries |> Array.exists (fun entry -> entry.Kind = OperationOutputKind.Command)).toBe true + + for entry in entries do + for start in 0 .. token.Length - 20 do + Vitest.expect(entry.Text.Contains(token.Substring(start, 20))).toBe false + } + ) + + Vitest.test ( + "a user name with an at sign does not leak the rest of the URL userinfo into the output", + TestOptions(timeout = 120000), + fun () -> promise { + let! entries = runCloneStandIn $"https://me@mail.com:s3cr3tTokenValue@{testHost}/origin.git" + + Vitest.expect( + entries + |> Array.exists (fun entry -> + entry.Kind = OperationOutputKind.Command && entry.Text.Contains $"[REDACTED]@{testHost}") + ) + .toBe true + + for entry in entries do + Vitest.expect(entry.Text.Contains "s3cr3tTokenValue").toBe false + Vitest.expect(entry.Text.Contains "mail.com").toBe false + } + ) + + Vitest.test ( + "a fetch with credentials reports no part of the credential in its output", + TestOptions(timeout = 120000), + fun () -> promise { + let secret = "p@ss word-secret-123" + let basicPayload = toBase64 $"oauth2:{secret}" + let! root = createTempDirectoryAsync () + let workPath = join [| root; "work" |] + + try + let! _ = runGitIn root [| "init"; "-b"; "main"; workPath |] + let! _ = runGitIn workPath [| "config"; "user.name"; "VCS Cred Tests" |] + let! _ = runGitIn workPath [| "config"; "user.email"; "cred@example.org" |] + do! writeUtf8FileAsync (join [| workPath; "base.txt" |]) "base\n" + let! _ = runGitIn workPath [| "add"; "-A" |] + let! _ = runGitIn workPath [| "commit"; "-m"; "init: base" |] + let! _ = runGitIn workPath [| "remote"; "add"; "origin"; testHttpsUrl |] + let! _ = runGitIn workPath [| "config"; "branch.main.remote"; "origin" |] + let! _ = runGitIn workPath [| "config"; "branch.main.merge"; "refs/heads/main" |] + let! _ = runGitIn workPath [| "update-ref"; "refs/remotes/origin/main"; "HEAD" |] + + // The stand-in for git echoes its arguments and the secret forms that the arguments hold, + // like a git that traces its configuration. The header value is not on a line of its own. + let echoScript = + "const args = process.argv.slice(1);" + + "for (const a of args) console.error(a);" + + "const header = args.find(a => a.includes('Basic '));" + + "const payload = header.split('Basic ')[1];" + + "console.error('payload=' + payload);" + + "console.error('decoded=' + Buffer.from(payload, 'base64').toString());" + + let hooks: GitWorkspaceSession.GitSessionHooks = { + RunBytesProcess = None + RunProcess = + Some(fun request processContext -> + if request.Arguments |> Array.contains "fetch" then + NodeProcess.run + { request with + Command = nodeExecutablePath + Arguments = [| "-e"; echoScript; "--"; yield! request.Arguments |] } + processContext + else + NodeProcess.run request processContext) + Barrier = None + } + + let strategy: GitCredentialStrategy.GitCredentialStrategy = { + ResolveCredential = + fun _host _profileId -> + async { + return + Some { + Username = "oauth2" + Secret = secret + } + } + } + + let binding: WorkspaceBinding = { + SchemaVersion = WorkspaceBinding.CurrentSchemaVersion + ProviderId = gitProviderId + WorkspaceRoot = workPath + ProviderStateRef = None + Location = { + ProviderId = gitProviderId + DisplayName = None + ProviderLocation = testHttpsUrl + ConnectionProfileId = Some "token-profile" + } + ConnectionProfileId = Some "token-profile" + } + + let session = GitWorkspaceSession.createSessionWithCredentials hooks strategy binding + let batches = ResizeArray() + + let context = + OperationContext.createWithOutput + "credential-fetch-output" + OperationCancellation.none + ignore + batches.Add + + let synchronization = + session.Synchronization + |> Option.defaultWith (fun () -> failwith "Expected the Git synchronization service.") + + let! _ = synchronization.Refresh context |> Async.StartAsPromise + let entries = batches |> Seq.collect id |> Seq.toArray + + Vitest.expect( + entries + |> Array.exists (fun entry -> + entry.Kind = OperationOutputKind.StdErr && entry.Text = "payload=[REDACTED]") + ) + .toBe true + + for entry in entries do + for form in [| basicPayload; $"oauth2:{secret}"; secret |] do + Vitest.expect(entry.Text.Contains form).toBe false + + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) +) + +let private lfsEndpointArguments (remoteUrl: string) : string[] = + let credential: GitCredentialStrategy.GitCredential option = + Some { + Username = "oauth2" + Secret = testSecret + } + + let authentication = GitCredentialStrategy.buildScopedCommandAuthentication "origin" remoteUrl credential + + authentication.ConfigArgs + |> Array.filter (fun argument -> + argument.StartsWith("lfs.url=", StringComparison.Ordinal) + || argument.StartsWith("remote.origin.lfsurl=", StringComparison.Ordinal)) + +let private expectLfsEndpoint (remoteUrl: string) (endpoint: string) = + Vitest.expect(lfsEndpointArguments remoteUrl).toEqual [| + $"remote.origin.lfsurl={endpoint}" + $"lfs.url={endpoint}" + |] + +Vitest.describe ( + "Git LFS endpoint of a credentialed remote", + fun () -> + Vitest.test ( + "adds .git to a remote URL without the suffix, as git-lfs server discovery does", + fun () -> + expectLfsEndpoint + $"https://{testHost}/group/proj" + $"https://oauth2:{testSecret}@{testHost}/group/proj.git/info/lfs" + ) + + Vitest.test ( + "keeps a remote URL that already ends in .git from getting the suffix twice", + fun () -> + expectLfsEndpoint + $"https://{testHost}/group/proj.git" + $"https://oauth2:{testSecret}@{testHost}/group/proj.git/info/lfs" + ) + + Vitest.test ( + "compares the .git suffix case-sensitively, as git-lfs does", + fun () -> + expectLfsEndpoint + $"https://{testHost}/group/proj.GIT" + $"https://oauth2:{testSecret}@{testHost}/group/proj.GIT.git/info/lfs" + ) + + Vitest.test ( + "trims a trailing slash before it appends the endpoint path", + fun () -> + expectLfsEndpoint + $"https://{testHost}/group/proj/" + $"https://oauth2:{testSecret}@{testHost}/group/proj.git/info/lfs" + + expectLfsEndpoint + $"https://{testHost}/group/proj.git/" + $"https://oauth2:{testSecret}@{testHost}/group/proj.git/info/lfs" + ) + + Vitest.test ( + "replaces the userinfo of the remote URL with the resolved credential in the endpoint", + fun () -> + expectLfsEndpoint + $"https://someone:old-secret@{testHost}/group/proj" + $"https://oauth2:{testSecret}@{testHost}/group/proj.git/info/lfs" + ) +) diff --git a/tests/VersionControlService.Tests/GitPartialSuccess.test.fs b/tests/VersionControlService.Tests/GitPartialSuccess.test.fs index f422c40..2a16c73 100644 --- a/tests/VersionControlService.Tests/GitPartialSuccess.test.fs +++ b/tests/VersionControlService.Tests/GitPartialSuccess.test.fs @@ -13,6 +13,9 @@ module GitExecution = VersionControlService.Git.GitExecution module GitLfsService = VersionControlService.Git.GitLfsService module GitLfsAdapter = VersionControlService.Git.GitLfsAdapter module GitInternals = VersionControlService.Git.GitInternals +module GitEngineTypes = VersionControlService.Git.GitEngineTypes +module GitCredentialStrategy = VersionControlService.Git.GitCredentialStrategy +module GitLfsExtensions = VersionControlService.Git.GitLfsExtensions module NodeProcess = VersionControlService.Runtime.Node.Process module NodeFileSystem = VersionControlService.Runtime.Node.FileSystem @@ -107,6 +110,53 @@ let private injectNextFileHandleSyncFailureAfterAttributesEdit """)>] let private observeGitSpawnArguments (_observed: ResizeArray) : unit -> unit = jsNative +// Records the arguments of every git spawn with the GIT_LFS_FORCE_PROGRESS value of its environment. +[ { + const childProcess = require('node:child_process'); + const moduleApi = require('node:module'); + const originalSpawn = childProcess.spawn; + childProcess.spawn = function(command, args, options) { + if (String(command).toLowerCase() === 'git') + $0.push([Array.from(args || []), String((options && options.env && options.env.GIT_LFS_FORCE_PROGRESS) || '')]); + return originalSpawn.call(childProcess, command, args, options); + }; + moduleApi.syncBuiltinESMExports(); + return () => { + childProcess.spawn = originalSpawn; + moduleApi.syncBuiltinESMExports(); + }; +})() +""")>] +let private observeGitSpawnForcedProgress (_observed: ResizeArray) : unit -> unit = jsNative + +// Replaces every `git lfs checkout` with a process that creates the lock file, prints the error text to +// stderr and exits with 0, which is what git-lfs 3.7.0 does when the index lock is held. An empty lock +// path creates no lock. +[ { + const childProcess = require('node:child_process'); + const moduleApi = require('node:module'); + const originalSpawn = childProcess.spawn; + const lockPath = $0; + const errorText = $1; + const createLock = lockPath ? 'require("node:fs").writeFileSync(' + JSON.stringify(lockPath) + ', "held by another process");' : ''; + const script = createLock + 'process.stderr.write(' + JSON.stringify(errorText) + ');'; + childProcess.spawn = function(command, args, options) { + const list = Array.from(args || []); + if (String(command).toLowerCase() === 'git' && list.includes('lfs') && list.includes('checkout')) + return originalSpawn.call(childProcess, process.execPath, ['-e', script], options); + return originalSpawn.call(childProcess, command, args, options); + }; + moduleApi.syncBuiltinESMExports(); + return () => { + childProcess.spawn = originalSpawn; + moduleApi.syncBuiltinESMExports(); + }; +})() +""")>] +let private fakeLfsCheckoutWithIndexError (_lockPath: string) (_errorText: string) : unit -> unit = jsNative + // The listener goes on the child before the caller adds its own close handler, so the append // finishes before the caller sees the hash result. [ Option.defaultWith (fun () -> failwith "Expected the object-materialization service.") + + for relativePath, _ in lfsDownloadFiles do + let! freed = + materialization.Dematerialize (repositoryPath relativePath) (ctx $"free-{relativePath}") + |> Async.StartAsPromise + + match freed with + | Succeeded _ -> () + | PartiallySucceeded(_, failure) + | Failed failure -> failwith $"Dematerialization failed for '{relativePath}' ({failure.Code})." + + // The remote check of a free on a local remote refetches the object into the cache. + let! objectPath = lfsObjectPathForHeadFile workPath relativePath + + if NodeFileSystem.existsSync objectPath then + NodeFileSystem.unlinkSync objectPath + + return root, workPath, barePath +} + +let private downloadLfsPaths (workPath: string) (paths: string[]) (reports: ResizeArray) = promise { + let! result = + GitService.downloadLfsFiles + workPath + paths + GitCredentialStrategy.anonymous + None + reports.Add + (ctx "download-lfs-paths") + + match result with + | Ok outcomes -> return outcomes + | Error failure -> return failwith $"The download failed as a whole: {failure.Message}" +} + +/// Writes the content of lfsDownloadFiles into the working tree and leaves the index alone. The index entries +/// keep the stat data of the pointers, which is what a `git lfs checkout` that could not take the index lock leaves. +let private writeContentBesideIndex (workPath: string) (relativePaths: string[]) = promise { + for relativePath in relativePaths do + let content = lfsDownloadFiles |> Array.find (fun (path, _) -> path = relativePath) |> snd + do! writeUtf8FileAsync (join [| workPath; relativePath |]) content +} + +/// The paths that `git status` lists, one per line. +let private statusLinesOf (workPath: string) = promise { + let! output = runGitOk workPath [| "status"; "--porcelain" |] + return output.Split('\n', StringSplitOptions.RemoveEmptyEntries) |> Array.map _.TrimEnd('\r') +} + +/// The paths with a staged change. +let private stagedPathsOf (workPath: string) = promise { + let! output = runGitOk workPath [| "diff"; "--cached"; "--name-only" |] + return output.Split('\n', StringSplitOptions.RemoveEmptyEntries) |> Array.map _.TrimEnd('\r') +} + +/// A work repository whose working tree holds the content of lfsDownloadFiles and whose origin has +/// their objects. With `unpushedLast`, the last file belongs to a commit that origin does not have. +let private createPushedLfsFixture (unpushedLast: bool) = promise { + let! root, workPath, _, _ = createPublishFixture GitWorkspaceSession.GitSessionHooks.none + let! _ = runGitOk workPath [| "lfs"; "track"; "*.bin" |] + + for folder in [| "data"; "other" |] do + NodeFileSystem.mkdirSync (join [| workPath; folder |]) (NodeFileSystem.MkdirOptions(recursive = true)) + + let pushedFiles = + if unpushedLast then + lfsDownloadFiles |> Array.take (lfsDownloadFiles.Length - 1) + else + lfsDownloadFiles + + for relativePath, content in pushedFiles do + do! writeUtf8FileAsync (join [| workPath; relativePath |]) content + + let! _ = runGitOk workPath [| "add"; "-A" |] + let! _ = runGitOk workPath [| "commit"; "-m"; "test: LFS files to free" |] + let! _ = runGitOk workPath [| "push"; "origin"; "main" |] + + if unpushedLast then + let relativePath, content = Array.last lfsDownloadFiles + do! writeUtf8FileAsync (join [| workPath; relativePath |]) content + let! _ = runGitOk workPath [| "add"; "-A" |] + let! _ = runGitOk workPath [| "commit"; "-m"; "test: LFS file that is not pushed" |] + () + + return root, workPath +} + +let private freeLfsPathsReporting (workPath: string) (paths: string[]) (reports: ResizeArray) = promise { + let! result = + GitService.freeLfsFiles + workPath + paths + GitCredentialStrategy.anonymous + None + reports.Add + (ctx "free-lfs-paths") + + match result with + | Ok outcomes -> return outcomes + | Error failure -> return failwith $"The free failed as a whole: {failure.Message}" +} + +let private freeLfsPaths (workPath: string) (paths: string[]) = + freeLfsPathsReporting workPath paths (ResizeArray()) + +/// The file counts a batch call reported, as Completed and Total pairs. +let private fileCountsOf (phaseCode: string) (reports: ResizeArray) = + reports + |> Seq.filter (fun report -> report.PhaseCode = phaseCode) + |> Seq.map (fun report -> report.Completed, report.Total) + |> Seq.toArray + +/// Removes the cached objects of freed paths, as the object-materialization service does after a free. +let private removeCachedObjectsOfFreedPaths (workPath: string) (paths: string[]) = promise { + let runGitForCleanup (arguments: string[]) (context: OperationContext) = async { + let request = { + NodeProcess.ProcessRequest.create "git" arguments with + WorkingDirectory = Some workPath + } + + let! result = NodeProcess.run request context + + match result with + | Succeeded outcome -> return Ok outcome.Value + | PartiallySucceeded(_, failure) + | Failed failure -> return Error failure + } + + do! + GitLfsExtensions.deleteCachedObjectsOfFreedPaths workPath runGitForCleanup (ctx "remove-cached-objects") paths + |> Async.StartAsPromise +} + +let private isLfsPointerText (text: string option) = + text + |> Option.exists (fun content -> content.StartsWith("version https://git-lfs", StringComparison.Ordinal)) + +/// A new session over a work repository whose origin is `barePath`. +let private openSession (workPath: string) (barePath: string) : WorkspaceSession = + let binding: WorkspaceBinding = { + SchemaVersion = WorkspaceBinding.CurrentSchemaVersion + ProviderId = gitProviderId + WorkspaceRoot = workPath + ProviderStateRef = None + Location = { + ProviderId = gitProviderId + DisplayName = None + ProviderLocation = barePath + ConnectionProfileId = None + } + ConnectionProfileId = None + } + + GitWorkspaceSession.createSession GitWorkspaceSession.GitSessionHooks.none binding + +/// The batch materialization service of a new session over a work repository whose origin is `barePath`. +let private openBatchMaterialization (workPath: string) (barePath: string) : ObjectBatchMaterializationService = + (openSession workPath barePath).ObjectBatchMaterialization + |> Option.defaultWith (fun () -> failwith "Expected the object batch materialization service.") + +/// The single-path materialization service of a new session over a work repository whose origin is `barePath`. +let private openMaterialization (workPath: string) (barePath: string) : ObjectMaterializationService = + (openSession workPath barePath).ObjectMaterialization + |> Option.defaultWith (fun () -> failwith "Expected the object-materialization service.") + +/// The batch materialization service of a session whose credential strategy hands out a token for the remote at `remoteUrl`. +let private openBatchMaterializationWithToken (workPath: string) (remoteUrl: string) : ObjectBatchMaterializationService = + let strategy: GitCredentialStrategy.GitCredentialStrategy = { + ResolveCredential = + fun _host _profileId -> async { return Some { Username = "oauth2"; Secret = "unreachable-token" } } + } + + let binding: WorkspaceBinding = { + SchemaVersion = WorkspaceBinding.CurrentSchemaVersion + ProviderId = gitProviderId + WorkspaceRoot = workPath + ProviderStateRef = None + Location = { + ProviderId = gitProviderId + DisplayName = None + ProviderLocation = remoteUrl + ConnectionProfileId = Some "token-profile" + } + ConnectionProfileId = Some "token-profile" + } + + GitWorkspaceSession.createSessionWithCredentials GitWorkspaceSession.GitSessionHooks.none strategy binding + |> fun session -> + session.ObjectBatchMaterialization + |> Option.defaultWith (fun () -> failwith "Expected the object batch materialization service.") + +[] +let private nowMilliseconds () : float = jsNative + +/// Files with long names in nested folders. Their paths together exceed one chunk of git arguments. +let private manyLfsFiles = + Array.init 120 (fun index -> + let number = (string index).PadLeft(4, '0') + let series = (string (index % 20)).PadLeft(2, '0') + let folder = $"long-term-observation-programme-with-a-descriptive-name/series-{series}-collected-at-the-northern-field-station" + + folder, $"{folder}/measurement-with-a-long-descriptive-file-name-{number}.bin", $"content {number}\n") + +/// Writes the files, then commits and pushes them. The files hold their content in the working tree afterwards. +let private commitAndPushLfsFiles (workPath: string) (files: (string * string * string)[]) = promise { + let! _ = runGitOk workPath [| "lfs"; "track"; "*.bin" |] + + for folder, relativePath, content in files do + NodeFileSystem.mkdirSync (join [| workPath; folder |]) (NodeFileSystem.MkdirOptions(recursive = true)) + do! writeUtf8FileAsync (join [| workPath; relativePath |]) content + + let! _ = runGitOk workPath [| "add"; "-A" |] + let! _ = runGitOk workPath [| "commit"; "-m"; "test: LFS files" |] + let! _ = runGitOk workPath [| "push"; "origin"; "main" |] + return () +} + +/// Turns the committed files below the top-level folders back into pointers and empties the local object cache. +let private resetToPointersWithoutCache (workPath: string) (topFolders: string[]) = promise { + let! objectsDirectory = runGitOk workPath [| "rev-parse"; "--git-path"; "lfs/objects" |] + let removeOptions = createObj [ "recursive" ==> true; "force" ==> true ] + + do! fsPromisesDynamic?rm (join [| workPath; objectsDirectory.Trim() |], removeOptions) |> unbox> + + for folder in topFolders do + do! fsPromisesDynamic?rm (join [| workPath; folder |], removeOptions) |> unbox> + + let! _ = + runGitOk workPath ( + Array.concat [| + [| + "-c" + "filter.lfs.smudge=" + "-c" + "filter.lfs.process=" + "-c" + "filter.lfs.required=false" + "checkout" + "HEAD" + "--" + |] + topFolders + |] + ) + + return () +} + let private createPathspecFixture () = promise { let! root = createTempDirectoryAsync () let workPath = join [| root; "work" |] @@ -382,10 +705,14 @@ let private commitPathspecFixtureFiles (workPath: string) (message: string) = pr return () } -let private isLfsPullRequest (request: NodeProcess.ProcessRequest) = +let private isLfsCommandRequest (command: string) (request: NodeProcess.ProcessRequest) = request.Arguments |> Array.windowed 2 - |> Array.exists (fun pair -> pair.[0] = "lfs" && pair.[1] = "pull") + |> Array.exists (fun pair -> pair.[0] = "lfs" && pair.[1] = command) + +let private isLfsFetchRequest = isLfsCommandRequest "fetch" +let private isLfsCheckoutRequest = isLfsCommandRequest "checkout" +let private isLfsPullRequest = isLfsCommandRequest "pull" let private isGitCloneRequest (request: NodeProcess.ProcessRequest) = request.Arguments |> Array.contains "clone" @@ -748,12 +1075,12 @@ Vitest.describe ( GitWorkspaceSession.GitSessionHooks.none with RunProcess = Some(fun request context -> - if isLfsPullRequest request then + if isLfsFetchRequest request then async.Return( OperationResult.succeeded { ExitCode = 2 StdOut = "" - StdErr = "injected lfs pull failure" + StdErr = "injected lfs fetch failure" } ) else @@ -831,7 +1158,7 @@ Vitest.describe ( GitWorkspaceSession.GitSessionHooks.none with RunProcess = Some(fun request context -> - if isLfsPullRequest request then + if isLfsFetchRequest request then NodeProcess.run blockedTransfer context else NodeProcess.run request context) @@ -978,7 +1305,7 @@ Vitest.describe ( ) Vitest.test ( - "cancellation between clone and LFS pull removes the created target", + "cancellation between clone and the large-object download removes the created target", TestOptions(timeout = 120000), fun () -> promise { let! lfsProbe = runGit "." [| "lfs"; "version" |] @@ -990,14 +1317,14 @@ Vitest.describe ( try let source = OperationCancellation.Source() - let mutable lfsPullSeen = false + let mutable lfsFetchSeen = false let hooks = { GitWorkspaceSession.GitSessionHooks.none with RunProcess = Some(fun request context -> - if isLfsPullRequest request then - lfsPullSeen <- true + if isLfsFetchRequest request then + lfsFetchSeen <- true NodeProcess.run request context elif isGitCloneRequest request then async { @@ -1038,7 +1365,7 @@ Vitest.describe ( | Succeeded _ | PartiallySucceeded _ -> failwith "Expected the clone to be canceled." - Vitest.expect(lfsPullSeen).toBe (false) + Vitest.expect(lfsFetchSeen).toBe (false) let! targetExists = pathExistsAsync targetPath Vitest.expect(targetExists).toBe (false) do! removeDirectoryAsync root @@ -1049,7 +1376,7 @@ Vitest.describe ( ) Vitest.test ( - "cancellation after LFS pull exits preserves clone success", + "cancellation during the clone's LFS checkout preserves clone success after fetch and checkout ran", TestOptions(timeout = 120000), fun () -> promise { let! lfsProbe = runGit "." [| "lfs"; "version" |] @@ -1061,20 +1388,25 @@ Vitest.describe ( try let source = OperationCancellation.Source() - let mutable lfsPullSeen = false + let lfsCommands = ResizeArray() let hooks = { GitWorkspaceSession.GitSessionHooks.none with RunProcess = Some(fun request context -> - if isLfsPullRequest request then + if isLfsCheckoutRequest request then async { - let! result = NodeProcess.run request context - lfsPullSeen <- true + lfsCommands.Add "checkout" + // The cancel arrives as the checkout starts. The checkout still runs to its end. source.Cancel() - return result + return! NodeProcess.run request context } else + if isLfsFetchRequest request then + lfsCommands.Add "fetch" + elif isLfsPullRequest request then + lfsCommands.Add "pull" + NodeProcess.run request context) } @@ -1106,9 +1438,11 @@ Vitest.describe ( failwith $"Expected clone success after late cancellation ({failure.Code})." | PartiallySucceeded _ -> failwith "Expected clone success after late cancellation." - Vitest.expect(lfsPullSeen).toBe (true) + Vitest.expect(lfsCommands.ToArray()).toEqual [| "fetch"; "checkout" |] let! targetExists = pathExistsAsync targetPath Vitest.expect(targetExists).toBe (true) + let! content = tryReadUtf8FileAsync (join [| targetPath; "large.bin" |]) + Vitest.expect(content).toEqual (Some "large binary payload\n") do! removeDirectoryAsync root with error -> do! removeDirectoryAsync root @@ -1221,6 +1555,61 @@ Vitest.describe ( .toBe false ) + Vitest.test ( + "a failed dry run keeps its listing lines out of the failure classification", + fun () -> + let oid = "403" + String.replicate 61 "a" + + let failureText = + $"Fetching reference refs/heads/main\nfetch {oid} => data/a.bin\nerror: failed to fetch some objects from 'https://example.org/origin.git/info/lfs'" + + let cleaned = GitLfsService.dropDryRunListingLines failureText + + Vitest.expect(GitService.classifyFailureKind failureText).toEqual (GitEngineTypes.GitFailureKind.Forbidden) + Vitest.expect(GitService.classifyFailureKind cleaned).toEqual (GitEngineTypes.GitFailureKind.Unknown) + + Vitest + .expect(cleaned) + .toEqual + "Fetching reference refs/heads/main\nerror: failed to fetch some objects from 'https://example.org/origin.git/info/lfs'" + ) + + Vitest.test ( + "a branch or endpoint name does not make a failed dry run remote-wide", + fun () -> + let serverError branch endpoint = + exn + $"Fetching reference refs/heads/{branch}\nbatch response: Fatal error: Server error {endpoint}/objects/batch from HTTP 502\nerror: failed to fetch some objects from '{endpoint}'" + + Vitest + .expect( + GitService.isRemoteWideFailure ( + serverError "fix-403-page" "https://example.org/origin.git/info/lfs" + ) + ) + .toBe + false + + Vitest + .expect( + GitService.isRemoteWideFailure ( + serverError "main" "https://example.org/gene-regulatory-network.git/info/lfs" + ) + ) + .toBe + false + + Vitest + .expect( + GitService.isRemoteWideFailure ( + exn + "Fetching reference refs/heads/main\nbatch response: Post \"https://example.org/info/lfs/objects/batch\": EOF\nerror: failed to fetch some objects from 'https://example.org/info/lfs'" + ) + ) + .toBe + true + ) + Vitest.test ( "Git LFS endpoint parsing prefers origin and trims auth annotations", fun () -> promise { @@ -1274,6 +1663,24 @@ Vitest.describe ( } ) + Vitest.test ( + "git output meters keep one line buffer per stream", + fun () -> + let lines = ResizeArray() + let observers, flush = GitLfsAdapter.OutputObservers.meters lines.Add + + // A stderr line arrives while a stdout meter is still split across chunks. + observers.OnStdout "Uploading LFS objects: 5" + observers.OnStderr "warning: slow link\n" + observers.OnStdout "0% (1/3), 1 B | 1 B/s\n" + flush () + + Vitest.expect(lines.ToArray()).toEqual [| + "warning: slow link" + "Uploading LFS objects: 50% (1/3), 1 B | 1 B/s" + |] + ) + Vitest.test ( "LFS push planning excludes each remote tip with a caret line in rev-list input", TestOptions(timeout = 120000), @@ -2321,6 +2728,1827 @@ Vitest.describe ( } ) + Vitest.test ( + "materialization of several files fetches them in one transfer and checks them out", + TestOptions(timeout = 120000), + fun () -> promise { + let! lfsProbe = runGit "." [| "lfs"; "version" |] + + match lfsProbe with + | Error _ -> Vitest.expect(true).toBe true + | Ok _ -> + let! root, workPath, _ = createFreedLfsFixture () + + try + let reports = ResizeArray() + let paths = lfsDownloadFiles |> Array.map fst + let! outcomes = downloadLfsPaths workPath paths reports + + Vitest.expect(outcomes |> Array.map (fun outcome -> outcome.Path)).toEqual paths + + Vitest + .expect(outcomes |> Array.forall (fun outcome -> outcome.Result = Ok GitService.Changed)) + .toBe true + + for relativePath, content in lfsDownloadFiles do + let! actual = tryReadUtf8FileAsync (join [| workPath; relativePath |]) + Vitest.expect(actual).toEqual (Some content) + + let! listingJson = runGitOk workPath [| "lfs"; "ls-files"; "-j" |] + let listing = GitLfsService.parseLsFiles listingJson + Vitest.expect(listing.Length).toBe lfsDownloadFiles.Length + Vitest.expect(listing |> Array.forall (fun file -> file.checkout)).toBe true + + // Three paths in two folders share one fetch, which names no single item. The start + // event has no message, and the meters of the fetch that follow it have one. + let transferReports = + reports + |> Seq.filter (fun report -> report.PhaseCode = "lfs-materialize-transfer") + |> Seq.toArray + + let transfers = transferReports |> Array.filter (fun report -> report.DisplayMessage.IsNone) + + Vitest.expect(transfers.Length).toBe 1 + Vitest.expect(transfers[0].Item.IsNone).toBe true + Vitest.expect(transferReports[0].DisplayMessage).toEqual None + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "materialization of several files forces Git LFS progress on its fetch and checkout", + TestOptions(timeout = 120000), + fun () -> promise { + let! lfsProbe = runGit "." [| "lfs"; "version" |] + + match lfsProbe with + | Error _ -> Vitest.expect(true).toBe true + | Ok _ -> + let! root, workPath, _ = createFreedLfsFixture () + + try + let spawned = ResizeArray() + let stopObserving = observeGitSpawnForcedProgress spawned + + try + let! _ = downloadLfsPaths workPath (lfsDownloadFiles |> Array.map fst) (ResizeArray()) + () + finally + stopObserving () + + let forcedValuesOf (subcommand: string) = + spawned + |> Seq.filter (fun (arguments, _) -> + arguments |> Array.contains "lfs" && arguments |> Array.contains subcommand) + |> Seq.map snd + |> Seq.toArray + + let fetchValues = forcedValuesOf "fetch" + let checkoutValues = forcedValuesOf "checkout" + Vitest.expect(fetchValues.Length).toBe 1 + Vitest.expect(checkoutValues.Length).toBe 1 + Vitest.expect(fetchValues[0]).toBe "1" + Vitest.expect(checkoutValues[0]).toBe "1" + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "materialization of several files reports how many files are done", + TestOptions(timeout = 120000), + fun () -> promise { + let! lfsProbe = runGit "." [| "lfs"; "version" |] + + match lfsProbe with + | Error _ -> Vitest.expect(true).toBe true + | Ok _ -> + let! root, workPath, _ = createFreedLfsFixture () + + try + let reports = ResizeArray() + let! _ = downloadLfsPaths workPath (lfsDownloadFiles |> Array.map fst) reports + + let counts = fileCountsOf "lfs-materialize-files" reports + let completed = counts |> Array.map (fun (completed, _) -> completed.Value) + + Vitest.expect(counts.Length > 1).toBe true + Vitest.expect(counts |> Array.forall (fun (_, total) -> total = Some 3.0)).toBe true + Vitest.expect(Array.last completed).toBe 3.0 + + for index = 1 to completed.Length - 1 do + Vitest.expect(completed[index] > completed[index - 1]).toBe true + + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "a download or a free of one path reports no file counts", + TestOptions(timeout = 120000), + fun () -> promise { + let! lfsProbe = runGit "." [| "lfs"; "version" |] + + match lfsProbe with + | Error _ -> Vitest.expect(true).toBe true + | Ok _ -> + let! root, workPath, _ = createFreedLfsFixture () + + try + let reports = ResizeArray() + let! _ = downloadLfsPaths workPath [| "data/a.bin" |] reports + let! _ = freeLfsPathsReporting workPath [| "data/a.bin" |] reports + + Vitest.expect(fileCountsOf "lfs-materialize-files" reports).toEqual [||] + Vitest.expect(fileCountsOf "lfs-dematerialize-files" reports).toEqual [||] + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "materialization of several files leaves a path with local changes alone and downloads the others", + TestOptions(timeout = 120000), + fun () -> promise { + let! lfsProbe = runGit "." [| "lfs"; "version" |] + + match lfsProbe with + | Error _ -> Vitest.expect(true).toBe true + | Ok _ -> + let! root, workPath, _ = createFreedLfsFixture () + + try + let dirtyPath = "data/b.bin" + let dirtyContent = "dirty pointer replacement\n" + do! writeUtf8FileAsync (join [| workPath; dirtyPath |]) dirtyContent + + let! outcomes = + downloadLfsPaths workPath (lfsDownloadFiles |> Array.map fst) (ResizeArray()) + + let resultOf path = + outcomes |> Array.find (fun outcome -> outcome.Path = path) |> _.Result + + Vitest.expect(resultOf "data/a.bin" = Ok GitService.Changed).toBe true + Vitest.expect(resultOf "other/c.bin" = Ok GitService.Changed).toBe true + + match resultOf dirtyPath with + | Error failure -> Vitest.expect(failure.Message.Contains $"'{dirtyPath}' has local changes").toBe true + | Ok _ -> failwith "A path with local changes must not be downloaded." + + let! dirtyAfter = tryReadUtf8FileAsync (join [| workPath; dirtyPath |]) + Vitest.expect(dirtyAfter).toEqual (Some dirtyContent) + + let! cleanAfter = tryReadUtf8FileAsync (join [| workPath; "data/a.bin" |]) + Vitest.expect(cleanAfter).toEqual (Some "content of a\n") + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "materialization of several files names the file whose content the remote lacks and downloads the others", + TestOptions(timeout = 120000), + fun () -> promise { + let! lfsProbe = runGit "." [| "lfs"; "version" |] + + match lfsProbe with + | Error _ -> Vitest.expect(true).toBe true + | Ok _ -> + let! root, workPath, barePath = createFreedLfsFixture () + + try + let missingPath = "other/c.bin" + let! missingObjectPath = lfsObjectPathForHeadFile workPath missingPath + let missingOid = missingObjectPath.Split [| '/'; '\\' |] |> Array.last + + let! remoteEntries = + fsPromisesDynamic?readdir (barePath, createObj [ "recursive" ==> true ]) + |> unbox> + + let remoteObjects = remoteEntries |> Array.filter (fun entry -> entry.EndsWith(missingOid)) + Vitest.expect(remoteObjects.Length).toBe 1 + + for entry in remoteObjects do + do! fsPromisesDynamic?rm (join [| barePath; entry |]) |> unbox> + + let! outcomes = + downloadLfsPaths + workPath + [| "data/a.bin"; missingPath; "data/b.bin" |] + (ResizeArray()) + + let resultOf path = + outcomes |> Array.find (fun outcome -> outcome.Path = path) |> _.Result + + Vitest.expect(resultOf "data/a.bin" = Ok GitService.Changed).toBe true + Vitest.expect(resultOf "data/b.bin" = Ok GitService.Changed).toBe true + + match resultOf missingPath with + | Error failure -> + Vitest.expect(failure.Message.Contains $"does not have the content of '{missingPath}'").toBe true + | Ok _ -> failwith "A file whose content the remote lacks must not be downloaded." + + let! missingAfter = tryReadUtf8FileAsync (join [| workPath; missingPath |]) + + Vitest + .expect( + missingAfter + |> Option.exists (fun text -> text.StartsWith("version https://git-lfs", StringComparison.Ordinal)) + ) + .toBe true + + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "materialization of several files reports a materialized file as already in state", + TestOptions(timeout = 120000), + fun () -> promise { + let! lfsProbe = runGit "." [| "lfs"; "version" |] + + match lfsProbe with + | Error _ -> Vitest.expect(true).toBe true + | Ok _ -> + let! root, workPath, _ = createFreedLfsFixture () + + try + let reports = ResizeArray() + let! first = downloadLfsPaths workPath [| "data/a.bin" |] reports + Vitest.expect(first |> Array.map (fun outcome -> outcome.Result) = [| Ok GitService.Changed |]).toBe true + + let! second = downloadLfsPaths workPath [| "data/a.bin"; "data/b.bin" |] reports + + Vitest + .expect( + second |> Array.map (fun outcome -> outcome.Result) = [| + Ok GitService.AlreadyInState + Ok GitService.Changed + |] + ) + .toBe true + + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "materialization of several files counts a repeated path once", + TestOptions(timeout = 120000), + fun () -> promise { + let! lfsProbe = runGit "." [| "lfs"; "version" |] + + match lfsProbe with + | Error _ -> Vitest.expect(true).toBe true + | Ok _ -> + let! root, workPath, _ = createFreedLfsFixture () + + try + let! outcomes = + downloadLfsPaths + workPath + [| "data/a.bin"; "data/b.bin"; "data/a.bin" |] + (ResizeArray()) + + Vitest.expect(outcomes |> Array.map (fun outcome -> outcome.Path)).toEqual [| + "data/a.bin" + "data/b.bin" + |] + + Vitest + .expect(outcomes |> Array.forall (fun outcome -> outcome.Result = Ok GitService.Changed)) + .toBe true + + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "dematerialization of several files leaves pointers and removes their cached objects", + TestOptions(timeout = 120000), + fun () -> promise { + let! lfsProbe = runGit "." [| "lfs"; "version" |] + + match lfsProbe with + | Error _ -> Vitest.expect(true).toBe true + | Ok _ -> + let! root, workPath = createPushedLfsFixture false + + try + let paths = lfsDownloadFiles |> Array.map fst + let! outcomes = freeLfsPaths workPath paths + + Vitest.expect(outcomes |> Array.map (fun outcome -> outcome.Path)).toEqual paths + + Vitest + .expect(outcomes |> Array.forall (fun outcome -> outcome.Result = Ok GitService.Changed)) + .toBe true + + do! removeCachedObjectsOfFreedPaths workPath paths + + for relativePath in paths do + let! worktreeText = tryReadUtf8FileAsync (join [| workPath; relativePath |]) + Vitest.expect(isLfsPointerText worktreeText).toBe true + + let! objectPath = lfsObjectPathForHeadFile workPath relativePath + let! objectExists = pathExistsAsync objectPath + Vitest.expect(objectExists).toBe false + + let! status = runGitOk workPath [| "status"; "--porcelain" |] + Vitest.expect(status.Trim()).toBe "" + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "dematerialization of several files reports how many files are done", + TestOptions(timeout = 120000), + fun () -> promise { + let! lfsProbe = runGit "." [| "lfs"; "version" |] + + match lfsProbe with + | Error _ -> Vitest.expect(true).toBe true + | Ok _ -> + let! root, workPath = createPushedLfsFixture false + + try + let reports = ResizeArray() + let! _ = freeLfsPathsReporting workPath (lfsDownloadFiles |> Array.map fst) reports + + let counts = fileCountsOf "lfs-dematerialize-files" reports + let completed = counts |> Array.map (fun (completed, _) -> completed.Value) + + Vitest.expect(counts.Length > 1).toBe true + Vitest.expect(counts |> Array.forall (fun (_, total) -> total = Some 3.0)).toBe true + Vitest.expect(Array.last completed).toBe 3.0 + + for index = 1 to completed.Length - 1 do + Vitest.expect(completed[index] > completed[index - 1]).toBe true + + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "dematerialization of several files leaves the dry run of its remote check without forced progress", + TestOptions(timeout = 120000), + fun () -> promise { + let! lfsProbe = runGit "." [| "lfs"; "version" |] + + match lfsProbe with + | Error _ -> Vitest.expect(true).toBe true + | Ok _ -> + let! root, workPath = createPushedLfsFixture false + + try + let spawned = ResizeArray() + let stopObserving = observeGitSpawnForcedProgress spawned + + try + let! _ = freeLfsPaths workPath (lfsDownloadFiles |> Array.map fst) + () + finally + stopObserving () + + let dryRunValues = + spawned + |> Seq.filter (fun (arguments, _) -> arguments |> Array.contains "--dry-run") + |> Seq.map snd + |> Seq.toArray + + Vitest.expect(dryRunValues.Length > 0).toBe true + Vitest.expect(dryRunValues |> Array.forall (fun value -> value <> "1")).toBe true + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "dematerialization of several files leaves a path with local changes alone and frees the others", + TestOptions(timeout = 120000), + fun () -> promise { + let! lfsProbe = runGit "." [| "lfs"; "version" |] + + match lfsProbe with + | Error _ -> Vitest.expect(true).toBe true + | Ok _ -> + let! root, workPath = createPushedLfsFixture false + + try + let dirtyPath = "data/b.bin" + let dirtyContent = "changed after the commit\n" + do! writeUtf8FileAsync (join [| workPath; dirtyPath |]) dirtyContent + + let! outcomes = freeLfsPaths workPath (lfsDownloadFiles |> Array.map fst) + + let resultOf path = + outcomes |> Array.find (fun outcome -> outcome.Path = path) |> _.Result + + Vitest.expect(resultOf "data/a.bin" = Ok GitService.Changed).toBe true + Vitest.expect(resultOf "other/c.bin" = Ok GitService.Changed).toBe true + + match resultOf dirtyPath with + | Error failure -> Vitest.expect(failure.Message.Contains $"'{dirtyPath}' has local changes").toBe true + | Ok _ -> failwith "A path with local changes must not be freed." + + let! dirtyAfter = tryReadUtf8FileAsync (join [| workPath; dirtyPath |]) + Vitest.expect(dirtyAfter).toEqual (Some dirtyContent) + + let! freedText = tryReadUtf8FileAsync (join [| workPath; "data/a.bin" |]) + Vitest.expect(isLfsPointerText freedText).toBe true + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "dematerialization of several files keeps a file whose commit is unpushed and frees the others", + TestOptions(timeout = 120000), + fun () -> promise { + let! lfsProbe = runGit "." [| "lfs"; "version" |] + + match lfsProbe with + | Error _ -> Vitest.expect(true).toBe true + | Ok _ -> + let! root, workPath = createPushedLfsFixture true + + try + let unpushedPath = "other/c.bin" + let! outcomes = freeLfsPaths workPath [| "data/a.bin"; unpushedPath; "data/b.bin" |] + + let resultOf path = + outcomes |> Array.find (fun outcome -> outcome.Path = path) |> _.Result + + Vitest.expect(resultOf "data/a.bin" = Ok GitService.Changed).toBe true + Vitest.expect(resultOf "data/b.bin" = Ok GitService.Changed).toBe true + + // A single free of this file fails the same way: the remote lacks its object. + match resultOf unpushedPath with + | Error failure -> + Vitest.expect(failure.Message.Contains $"The remote does not have '{unpushedPath}' yet").toBe true + | Ok _ -> failwith "A file whose commit is unpushed must not be freed." + + do! removeCachedObjectsOfFreedPaths workPath [| "data/a.bin"; "data/b.bin" |] + + let! unpushedText = tryReadUtf8FileAsync (join [| workPath; unpushedPath |]) + Vitest.expect(unpushedText).toEqual (Some "content of c\n") + + let! unpushedObjectPath = lfsObjectPathForHeadFile workPath unpushedPath + let! unpushedObjectExists = pathExistsAsync unpushedObjectPath + Vitest.expect(unpushedObjectExists).toBe true + + for relativePath in [| "data/a.bin"; "data/b.bin" |] do + let! worktreeText = tryReadUtf8FileAsync (join [| workPath; relativePath |]) + Vitest.expect(isLfsPointerText worktreeText).toBe true + + let! objectPath = lfsObjectPathForHeadFile workPath relativePath + let! objectExists = pathExistsAsync objectPath + Vitest.expect(objectExists).toBe false + + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "dematerialization of several files reports a pointer as already in state", + TestOptions(timeout = 120000), + fun () -> promise { + let! lfsProbe = runGit "." [| "lfs"; "version" |] + + match lfsProbe with + | Error _ -> Vitest.expect(true).toBe true + | Ok _ -> + let! root, workPath = createPushedLfsFixture false + + try + let! first = freeLfsPaths workPath [| "data/a.bin" |] + Vitest.expect(first |> Array.map (fun outcome -> outcome.Result) = [| Ok GitService.Changed |]).toBe true + + let! second = freeLfsPaths workPath [| "data/a.bin"; "data/b.bin" |] + + Vitest + .expect( + second |> Array.map (fun outcome -> outcome.Result) = [| + Ok GitService.AlreadyInState + Ok GitService.Changed + |] + ) + .toBe true + + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "batch materialization reports a path with local changes as a partial success", + TestOptions(timeout = 120000), + fun () -> promise { + let! lfsProbe = runGit "." [| "lfs"; "version" |] + + match lfsProbe with + | Error _ -> Vitest.expect(true).toBe true + | Ok _ -> + let! root, workPath, barePath = createFreedLfsFixture () + + try + let batch = openBatchMaterialization workPath barePath + let dirtyPath = "data/b.bin" + let dirtyContent = "changed after the commit\n" + do! writeUtf8FileAsync (join [| workPath; dirtyPath |]) dirtyContent + + let! result = + batch.Materialize + (lfsDownloadFiles |> Array.map (fst >> repositoryPath)) + (ctx "batch-materialize-partial") + |> Async.StartAsPromise + + match result with + | PartiallySucceeded(outcome, failure) -> + Vitest.expect(outcome.AffectedPaths).toEqual [| "data/a.bin"; "other/c.bin" |] + Vitest.expect(failure.AffectedPaths).toEqual [| dirtyPath |] + Vitest.expect(failure.Details.Length).toBe 1 + Vitest.expect(failure.Details[0].StartsWith($"{dirtyPath}: ")).toBe true + Vitest.expect(failure.StateChanged).toBe true + | Succeeded _ + | Failed _ -> failwith "Expected a partial success for a path with local changes." + + for relativePath, content in lfsDownloadFiles do + if relativePath <> dirtyPath then + let! actual = tryReadUtf8FileAsync (join [| workPath; relativePath |]) + Vitest.expect(actual).toEqual (Some content) + + let! dirtyAfter = tryReadUtf8FileAsync (join [| workPath; dirtyPath |]) + Vitest.expect(dirtyAfter).toEqual (Some dirtyContent) + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "batch materialization repairs index entries that a blocked checkout left stale without a transfer", + TestOptions(timeout = 120000), + fun () -> promise { + let! lfsProbe = runGit "." [| "lfs"; "version" |] + + match lfsProbe with + | Error _ -> Vitest.expect(true).toBe true + | Ok _ -> + let! root, workPath, barePath = createFreedLfsFixture () + + try + let stalePaths = [| "data/a.bin"; "data/b.bin" |] + do! writeContentBesideIndex workPath stalePaths + + let! statusBefore = statusLinesOf workPath + Vitest.expect(statusBefore).toEqual [| " M data/a.bin"; " M data/b.bin" |] + + let batch = openBatchMaterialization workPath barePath + let reports = ResizeArray() + + let! result = + batch.Materialize + (stalePaths |> Array.map repositoryPath) + (OperationContext.create "batch-materialize-stale-index" OperationCancellation.none reports.Add) + |> Async.StartAsPromise + + match result with + | Succeeded outcome -> + Vitest.expect(outcome.Effect = Performed).toBe true + Vitest.expect(outcome.AffectedPaths).toEqual stalePaths + | PartiallySucceeded _ + | Failed _ -> failwith "Expected the batch materialization to repair the stale index entries." + + Vitest + .expect(reports |> Seq.exists (fun report -> report.PhaseCode = "lfs-materialize-transfer")) + .toBe false + + for relativePath in stalePaths do + let size = float (lfsDownloadFiles |> Array.find (fun (path, _) -> path = relativePath) |> snd).Length + + Vitest + .expect( + reports + |> Seq.exists (fun report -> + report.PhaseCode = "lfs-materialize" + && report.Item = Some relativePath + && report.Completed = Some size + && report.Total = Some size) + ) + .toBe true + + let! statusAfter = statusLinesOf workPath + Vitest.expect(statusAfter).toEqual [||] + let! staged = stagedPathsOf workPath + Vitest.expect(staged).toEqual [||] + + for relativePath in stalePaths do + let! actual = tryReadUtf8FileAsync (join [| workPath; relativePath |]) + + Vitest + .expect(actual) + .toEqual (Some(lfsDownloadFiles |> Array.find (fun (path, _) -> path = relativePath) |> snd)) + + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "materialization of one path repairs an index entry that a blocked checkout left stale", + TestOptions(timeout = 120000), + fun () -> promise { + let! lfsProbe = runGit "." [| "lfs"; "version" |] + + match lfsProbe with + | Error _ -> Vitest.expect(true).toBe true + | Ok _ -> + let! root, workPath, barePath = createFreedLfsFixture () + + try + let materialization = + (openSession workPath barePath).ObjectMaterialization + |> Option.defaultWith (fun () -> failwith "Expected the object-materialization service.") + + do! writeContentBesideIndex workPath [| "data/a.bin" |] + + let! statusBefore = statusLinesOf workPath + Vitest.expect(statusBefore).toEqual [| " M data/a.bin" |] + + let! result = + materialization.Materialize (repositoryPath "data/a.bin") (ctx "materialize-stale-index") + |> Async.StartAsPromise + + match result with + | Succeeded outcome -> Vitest.expect(outcome.Effect = Performed).toBe true + | PartiallySucceeded(_, failure) + | Failed failure -> failwith $"Expected the stale index entry to be repaired ({failure.Code})." + + let! statusAfter = statusLinesOf workPath + Vitest.expect(statusAfter).toEqual [||] + let! staged = stagedPathsOf workPath + Vitest.expect(staged).toEqual [||] + + let! actual = tryReadUtf8FileAsync (join [| workPath; "data/a.bin" |]) + Vitest.expect(actual).toEqual (Some "content of a\n") + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "batch materialization still refuses a modified file that has the size of its object but other content", + TestOptions(timeout = 120000), + fun () -> promise { + let! lfsProbe = runGit "." [| "lfs"; "version" |] + + match lfsProbe with + | Error _ -> Vitest.expect(true).toBe true + | Ok _ -> + let! root, workPath, _ = createFreedLfsFixture () + + try + // The edit has the 13 bytes of "content of a\n", so only the hash tells it from the object. + let editedPath = "data/a.bin" + let editedContent = "content of X\n" + do! writeUtf8FileAsync (join [| workPath; editedPath |]) editedContent + do! writeContentBesideIndex workPath [| "data/b.bin" |] + + let! outcomes = downloadLfsPaths workPath [| editedPath; "data/b.bin" |] (ResizeArray()) + + match outcomes[0].Result with + | Error failure -> Vitest.expect(failure.Message.Contains $"'{editedPath}' has local changes").toBe true + | Ok _ -> failwith "A file with other content must not count as materialized." + + Vitest.expect(outcomes[1].Result = Ok GitService.Changed).toBe true + + let! statusAfter = statusLinesOf workPath + Vitest.expect(statusAfter).toEqual [| " M data/a.bin" |] + let! staged = stagedPathsOf workPath + Vitest.expect(staged).toEqual [||] + + let! editedAfter = tryReadUtf8FileAsync (join [| workPath; editedPath |]) + Vitest.expect(editedAfter).toEqual (Some editedContent) + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "batch materialization leaves a file alone whose index entry has a staged change", + TestOptions(timeout = 120000), + fun () -> promise { + let! lfsProbe = runGit "." [| "lfs"; "version" |] + + match lfsProbe with + | Error _ -> Vitest.expect(true).toBe true + | Ok _ -> + let! root, workPath, _ = createFreedLfsFixture () + + try + let path = "data/a.bin" + do! writeUtf8FileAsync (join [| workPath; path |]) "staged edit\n" + let! _ = runGitOk workPath [| "add"; "--"; path |] + // The working tree returns to the content of the object, so only the staged change differs from HEAD. + do! writeContentBesideIndex workPath [| path |] + let! stagedBlobBefore = runGitOk workPath [| "rev-parse"; $":{path}" |] + + let! outcomes = downloadLfsPaths workPath [| path |] (ResizeArray()) + + match outcomes[0].Result with + | Error failure -> Vitest.expect(failure.Message.Contains $"'{path}' has local changes").toBe true + | Ok _ -> failwith "A staged change must not be repaired away." + + let! stagedBlobAfter = runGitOk workPath [| "rev-parse"; $":{path}" |] + Vitest.expect(stagedBlobAfter).toBe stagedBlobBefore + let! staged = stagedPathsOf workPath + Vitest.expect(staged).toEqual [| path |] + + let! actual = tryReadUtf8FileAsync (join [| workPath; path |]) + Vitest.expect(actual).toEqual (Some "content of a\n") + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "batch materialization does not repair a stale entry whose path the attributes no longer register with the lfs filter", + TestOptions(timeout = 120000), + fun () -> promise { + let! lfsProbe = runGit "." [| "lfs"; "version" |] + + match lfsProbe with + | Error _ -> Vitest.expect(true).toBe true + | Ok _ -> + let! root, workPath, _ = createFreedLfsFixture () + + try + let path = "data/a.bin" + do! writeContentBesideIndex workPath [| path |] + // check-attr reads the working tree, so the uncommitted edit already removes the filter. + do! writeUtf8FileAsync (join [| workPath; ".gitattributes" |]) "\n" + + let! outcomes = downloadLfsPaths workPath [| path |] (ResizeArray()) + + match outcomes[0].Result with + | Error failure -> Vitest.expect(failure.Message.Contains $"'{path}' has local changes").toBe true + | Ok _ -> failwith "A path without the lfs filter must not be repaired." + + let! statusAfter = statusLinesOf workPath + Vitest.expect(statusAfter |> Array.contains $" M {path}").toBe true + let! staged = stagedPathsOf workPath + Vitest.expect(staged).toEqual [||] + + let! actual = tryReadUtf8FileAsync (join [| workPath; path |]) + Vitest.expect(actual).toEqual (Some "content of a\n") + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "batch materialization reports the lock text when a held index lock stops the repair of a stale entry", + TestOptions(timeout = 120000), + fun () -> promise { + let! lfsProbe = runGit "." [| "lfs"; "version" |] + + match lfsProbe with + | Error _ -> Vitest.expect(true).toBe true + | Ok _ -> + let! root, workPath, _ = createFreedLfsFixture () + + try + do! writeContentBesideIndex workPath [| "data/a.bin" |] + do! writeUtf8FileAsync (join [| workPath; ".git"; "index.lock" |]) "held by another process" + + let! result = + GitService.downloadLfsFiles + workPath + [| "data/a.bin" |] + GitCredentialStrategy.anonymous + None + ignore + (ctx "repair-stale-index-locked") + + match result with + | Error failure -> + Vitest.expect(GitInternals.tryIndexLockFailure failure.Message |> Option.isSome).toBe true + | Ok _ -> failwith "A held index lock must stop the repair." + + let! actual = tryReadUtf8FileAsync (join [| workPath; "data/a.bin" |]) + Vitest.expect(actual).toEqual (Some "content of a\n") + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "materialization of a file with local changes fails with the code local_changes", + TestOptions(timeout = 120000), + fun () -> promise { + let! lfsProbe = runGit "." [| "lfs"; "version" |] + + match lfsProbe with + | Error _ -> Vitest.expect(true).toBe true + | Ok _ -> + let! root, workPath, barePath = createFreedLfsFixture () + + try + let editedPath = "data/a.bin" + do! writeUtf8FileAsync (join [| workPath; editedPath |]) "content of X\n" + + let! result = + (openMaterialization workPath barePath).Materialize + (repositoryPath editedPath) + (ctx "materialize-local-changes") + |> Async.StartAsPromise + + match result with + | Failed failure -> + Vitest.expect(failure.Code).toBe "local_changes" + Vitest.expect(failure.Category).toEqual ProviderError + | Succeeded _ + | PartiallySucceeded _ -> failwith "A file with local changes must not be materialized." + + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "dematerialization of a file with local changes fails with the code local_changes", + TestOptions(timeout = 120000), + fun () -> promise { + let! lfsProbe = runGit "." [| "lfs"; "version" |] + + match lfsProbe with + | Error _ -> Vitest.expect(true).toBe true + | Ok _ -> + let! root, workPath = createPushedLfsFixture false + + try + let editedPath = "data/a.bin" + do! writeUtf8FileAsync (join [| workPath; editedPath |]) "content of X\n" + + let! result = + (openMaterialization workPath (join [| root; "origin.git" |])).Dematerialize + (repositoryPath editedPath) + (ctx "dematerialize-local-changes") + |> Async.StartAsPromise + + match result with + | Failed failure -> Vitest.expect(failure.Code).toBe "local_changes" + | Succeeded _ + | PartiallySucceeded _ -> failwith "A file with local changes must not be freed." + + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "batch materialization in which every path has local changes fails with the code local_changes", + TestOptions(timeout = 120000), + fun () -> promise { + let! lfsProbe = runGit "." [| "lfs"; "version" |] + + match lfsProbe with + | Error _ -> Vitest.expect(true).toBe true + | Ok _ -> + let! root, workPath, barePath = createFreedLfsFixture () + + try + let editedPaths = [| "data/a.bin"; "data/b.bin" |] + + for editedPath in editedPaths do + do! writeUtf8FileAsync (join [| workPath; editedPath |]) "content of X\n" + + let! result = + (openBatchMaterialization workPath barePath).Materialize + (editedPaths |> Array.map repositoryPath) + (ctx "batch-materialize-local-changes") + |> Async.StartAsPromise + + match result with + | Failed failure -> + Vitest.expect(failure.Code).toBe "local_changes" + Vitest.expect(failure.AffectedPaths).toEqual editedPaths + Vitest.expect(failure.Details.Length).toBe 2 + | Succeeded _ + | PartiallySucceeded _ -> failwith "Expected a failure when every path has local changes." + + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "batch materialization with one path with local changes and one other failure keeps the incomplete code", + TestOptions(timeout = 120000), + fun () -> promise { + let! lfsProbe = runGit "." [| "lfs"; "version" |] + + match lfsProbe with + | Error _ -> Vitest.expect(true).toBe true + | Ok _ -> + let! root, workPath, barePath = createFreedLfsFixture () + + try + let editedPath = "data/a.bin" + do! writeUtf8FileAsync (join [| workPath; editedPath |]) "content of X\n" + + // The listing of Git LFS lacks this path, which is a failure of another kind. + let unlistedPath = "data/unlisted.bin" + + let! result = + (openBatchMaterialization workPath barePath).Materialize + ([| editedPath; unlistedPath |] |> Array.map repositoryPath) + (ctx "batch-materialize-local-changes-and-unlisted") + |> Async.StartAsPromise + + match result with + | Failed failure -> + Vitest.expect(failure.Code).toBe "batch_materialization_incomplete" + Vitest.expect(failure.AffectedPaths).toEqual [| editedPath; unlistedPath |] + | Succeeded _ + | PartiallySucceeded _ -> failwith "Expected a failure when no path changed." + + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "a partial batch result in which every failed path has local changes has the code local_changes", + fun () -> promise { + let localChanges (path: string) = + ({ + Path = path + Result = + Error( + { + Kind = GitEngineTypes.GitFailureKind.LocalChanges + Message = $"'{path}' has local changes." + }: GitService.GitFailure + ) + }: GitService.LfsPathOutcome) + + let changed = + ({ Path = "c.bin"; Result = Ok GitService.Changed }: GitService.LfsPathOutcome) + + match + GitLfsExtensions.toBatchResult + GitLfsExtensions.batchMaterializeAction + [| localChanges "a.bin"; localChanges "b.bin"; changed |] + with + | PartiallySucceeded(outcome, failure) -> + Vitest.expect(failure.Code).toBe "local_changes" + Vitest.expect(failure.AffectedPaths).toEqual [| "a.bin"; "b.bin" |] + Vitest.expect(outcome.AffectedPaths).toEqual [| "c.bin" |] + | Succeeded _ + | Failed _ -> failwith "Expected a partial success for a run with one changed path." + } + ) + + Vitest.test ( + "batch materialization reports a checkout that ended with success but could not update the index as a lock failure", + TestOptions(timeout = 120000), + fun () -> promise { + let! lfsProbe = runGit "." [| "lfs"; "version" |] + + match lfsProbe with + | Error _ -> Vitest.expect(true).toBe true + | Ok _ -> + let! root, workPath, barePath = createFreedLfsFixture () + let lockPath = join [| workPath; ".git"; "index.lock" |] + let stopFaking: (unit -> unit) ref = ref ignore + + try + let batch = openBatchMaterialization workPath barePath + + // The preflight passes because the lock appears only with the checkout. The text is what + // git-lfs 3.7.0 prints, and it does not name the lock. + stopFaking.Value <- + fakeLfsCheckoutWithIndexError + lockPath + "Error updating the Git index:\n\n\nErrors logged to 'x.log'." + + let! result = + batch.Materialize + (lfsDownloadFiles |> Array.map (fst >> repositoryPath)) + (ctx "batch-materialize-index-error-exit-0") + |> Async.StartAsPromise + + stopFaking.Value () + stopFaking.Value <- ignore + + match result with + | Failed failure -> + Vitest.expect(failure.Code).toBe "batch_materialization_incomplete" + Vitest.expect(failure.RecoveryAction |> Option.map _.Code).toEqual (Some "remove_index_lock") + Vitest.expect(failure.StateChanged).toBe true + Vitest.expect(failure.AffectedPaths.Length).toBe lfsDownloadFiles.Length + | Succeeded _ + | PartiallySucceeded _ -> failwith "Expected a failure for a checkout that could not update the index." + + let! lockExists = pathExistsAsync lockPath + Vitest.expect(lockExists).toBe true + do! removeDirectoryAsync root + with error -> + stopFaking.Value () + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "batch materialization keeps the plain failure when a checkout that ended with success could not update the index and no lock exists", + TestOptions(timeout = 120000), + fun () -> promise { + let! lfsProbe = runGit "." [| "lfs"; "version" |] + + match lfsProbe with + | Error _ -> Vitest.expect(true).toBe true + | Ok _ -> + let! root, workPath, barePath = createFreedLfsFixture () + let stopFaking: (unit -> unit) ref = ref ignore + + try + let batch = openBatchMaterialization workPath barePath + + stopFaking.Value <- + fakeLfsCheckoutWithIndexError "" "Error updating the Git index:\n\n\nErrors logged to 'x.log'." + + let! result = + batch.Materialize + (lfsDownloadFiles |> Array.map (fst >> repositoryPath)) + (ctx "batch-materialize-index-error-no-lock") + |> Async.StartAsPromise + + stopFaking.Value () + stopFaking.Value <- ignore + + match result with + | Failed failure -> + Vitest.expect(failure.Code).toBe "batch_materialization_incomplete" + Vitest.expect(failure.RecoveryAction).toEqual None + Vitest.expect(failure.StateChanged).toBe true + Vitest.expect(failure.AffectedPaths.Length).toBe lfsDownloadFiles.Length + Vitest.expect(failure.Message.Contains "Error updating the Git index").toBe true + | Succeeded _ + | PartiallySucceeded _ -> failwith "Expected a failure for a checkout that could not update the index." + + do! removeDirectoryAsync root + with error -> + stopFaking.Value () + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "batch dematerialization frees several pushed files and keeps nothing in the cache", + TestOptions(timeout = 120000), + fun () -> promise { + let! lfsProbe = runGit "." [| "lfs"; "version" |] + + match lfsProbe with + | Error _ -> Vitest.expect(true).toBe true + | Ok _ -> + let! root, workPath = createPushedLfsFixture false + + try + let batch = openBatchMaterialization workPath (join [| root; "origin.git" |]) + let paths = [| "data/a.bin"; "other/c.bin" |] + + let! result = + batch.Dematerialize (paths |> Array.map repositoryPath) (ctx "batch-dematerialize") + |> Async.StartAsPromise + + match result with + | Succeeded outcome -> + Vitest.expect(outcome.Effect = Performed).toBe true + Vitest.expect(outcome.AffectedPaths).toEqual paths + | PartiallySucceeded _ + | Failed _ -> failwith "Expected the batch dematerialization to succeed." + + for relativePath in paths do + let! worktreeText = tryReadUtf8FileAsync (join [| workPath; relativePath |]) + Vitest.expect(isLfsPointerText worktreeText).toBe true + + let! objectPath = lfsObjectPathForHeadFile workPath relativePath + let! objectExists = pathExistsAsync objectPath + Vitest.expect(objectExists).toBe false + + let! untouchedText = tryReadUtf8FileAsync (join [| workPath; "data/b.bin" |]) + Vitest.expect(untouchedText).toEqual (Some "content of b\n") + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "batch materialization of files that are already materialized changes nothing", + TestOptions(timeout = 120000), + fun () -> promise { + let! lfsProbe = runGit "." [| "lfs"; "version" |] + + match lfsProbe with + | Error _ -> Vitest.expect(true).toBe true + | Ok _ -> + let! root, workPath = createPushedLfsFixture false + + try + let batch = openBatchMaterialization workPath (join [| root; "origin.git" |]) + + let! result = + batch.Materialize + ([| "data/a.bin"; "data/b.bin" |] |> Array.map repositoryPath) + (ctx "batch-materialize-noop") + |> Async.StartAsPromise + + match result with + | Succeeded outcome -> + Vitest.expect(outcome.Effect = Performed).toBe false + Vitest.expect(outcome.AffectedPaths.Length).toBe 0 + | PartiallySucceeded _ + | Failed _ -> failwith "Expected a no-op for files that are already materialized." + + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "batch materialization downloads more files than fit one chunk of git arguments", + TestOptions(timeout = 300000), + fun () -> promise { + let! lfsProbe = runGit "." [| "lfs"; "version" |] + + match lfsProbe with + | Error _ -> Vitest.expect(true).toBe true + | Ok _ -> + let! root, workPath, barePath, _ = createPublishFixture GitWorkspaceSession.GitSessionHooks.none + + try + do! commitAndPushLfsFiles workPath manyLfsFiles + do! resetToPointersWithoutCache workPath [| "long-term-observation-programme-with-a-descriptive-name" |] + + let batch = openBatchMaterialization workPath barePath + + let! result = + batch.Materialize + (manyLfsFiles |> Array.map (fun (_, relativePath, _) -> repositoryPath relativePath)) + (ctx "batch-materialize-many") + |> Async.StartAsPromise + + match result with + | Succeeded outcome -> Vitest.expect(outcome.AffectedPaths.Length).toBe manyLfsFiles.Length + | PartiallySucceeded _ + | Failed _ -> failwith "Expected the batch download of many files to succeed." + + for _, relativePath, content in manyLfsFiles do + let! actual = tryReadUtf8FileAsync (join [| workPath; relativePath |]) + Vitest.expect(actual).toEqual (Some content) + + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "batch dematerialization frees more files than fit one chunk of git arguments", + TestOptions(timeout = 600000), + fun () -> promise { + let! lfsProbe = runGit "." [| "lfs"; "version" |] + + match lfsProbe with + | Error _ -> Vitest.expect(true).toBe true + | Ok _ -> + let! root, workPath, barePath, _ = createPublishFixture GitWorkspaceSession.GitSessionHooks.none + + try + do! commitAndPushLfsFiles workPath manyLfsFiles + let batch = openBatchMaterialization workPath barePath + + let! result = + batch.Dematerialize + (manyLfsFiles |> Array.map (fun (_, relativePath, _) -> repositoryPath relativePath)) + (ctx "batch-dematerialize-many") + |> Async.StartAsPromise + + match result with + | Succeeded outcome -> Vitest.expect(outcome.AffectedPaths.Length).toBe manyLfsFiles.Length + | PartiallySucceeded(_, failure) + | Failed failure -> failwith $"Expected the batch free of many files to succeed: {failure.Message}" + + for _, relativePath, _ in manyLfsFiles do + let! worktreeText = tryReadUtf8FileAsync (join [| workPath; relativePath |]) + Vitest.expect(isLfsPointerText worktreeText).toBe true + + let! status = runGitOk workPath [| "status"; "--porcelain" |] + Vitest.expect(status.Trim()).toBe "" + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "batch materialization takes only the requested object when a listed sibling matches its path pattern", + TestOptions(timeout = 120000), + fun () -> promise { + let! lfsProbe = runGit "." [| "lfs"; "version" |] + + match lfsProbe with + | Error _ -> Vitest.expect(true).toBe true + | Ok _ -> + let! root, workPath, barePath, _ = createPublishFixture GitWorkspaceSession.GitSessionHooks.none + + try + let requestedPath = "runs/x,y.bin" + let plainPath = "runs/plain.bin" + let siblingPath = "runs/x_y.bin" + + do! + commitAndPushLfsFiles + workPath + [| + "runs", requestedPath, "requested object\n" + "runs", plainPath, "plain object\n" + "runs", siblingPath, "sibling object\n" + |] + + let! siblingObjectPath = lfsObjectPathForHeadFile workPath siblingPath + do! resetToPointersWithoutCache workPath [| "runs" |] + + let batch = openBatchMaterialization workPath barePath + + let! result = + batch.Materialize + ([| requestedPath; plainPath |] |> Array.map repositoryPath) + (ctx "batch-materialize-sibling") + |> Async.StartAsPromise + + match result with + | Succeeded outcome -> Vitest.expect(outcome.AffectedPaths).toEqual [| requestedPath; plainPath |] + | PartiallySucceeded(_, failure) + | Failed failure -> failwith $"Expected the batch download to succeed: {failure.Message}" + + let! requestedAfter = tryReadUtf8FileAsync (join [| workPath; requestedPath |]) + Vitest.expect(requestedAfter).toEqual (Some "requested object\n") + + let! plainAfter = tryReadUtf8FileAsync (join [| workPath; plainPath |]) + Vitest.expect(plainAfter).toEqual (Some "plain object\n") + + let! siblingAfter = tryReadUtf8FileAsync (join [| workPath; siblingPath |]) + Vitest.expect(isLfsPointerText siblingAfter).toBe true + + let! siblingObjectExists = pathExistsAsync siblingObjectPath + Vitest.expect(siblingObjectExists).toBe false + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "batch dematerialization keeps an unpushed file and its object and frees the pushed files", + TestOptions(timeout = 120000), + fun () -> promise { + let! lfsProbe = runGit "." [| "lfs"; "version" |] + + match lfsProbe with + | Error _ -> Vitest.expect(true).toBe true + | Ok _ -> + let! root, workPath = createPushedLfsFixture true + + try + let batch = openBatchMaterialization workPath (join [| root; "origin.git" |]) + let unpushedPath = "other/c.bin" + + let! result = + batch.Dematerialize + ([| "data/a.bin"; unpushedPath; "data/b.bin" |] |> Array.map repositoryPath) + (ctx "batch-dematerialize-unpushed") + |> Async.StartAsPromise + + match result with + | PartiallySucceeded(outcome, failure) -> + Vitest.expect(outcome.AffectedPaths).toEqual [| "data/a.bin"; "data/b.bin" |] + Vitest.expect(failure.AffectedPaths).toEqual [| unpushedPath |] + Vitest.expect(failure.Code).toBe "batch_dematerialization_incomplete" + Vitest.expect(failure.RecoveryAction |> Option.map _.Code).toEqual (Some "retry_dematerialization") + | Succeeded _ + | Failed _ -> failwith "Expected a partial success for a file whose commit is unpushed." + + let! unpushedText = tryReadUtf8FileAsync (join [| workPath; unpushedPath |]) + Vitest.expect(unpushedText).toEqual (Some "content of c\n") + + let! unpushedObjectPath = lfsObjectPathForHeadFile workPath unpushedPath + let! unpushedObjectExists = pathExistsAsync unpushedObjectPath + Vitest.expect(unpushedObjectExists).toBe true + + for relativePath in [| "data/a.bin"; "data/b.bin" |] do + let! worktreeText = tryReadUtf8FileAsync (join [| workPath; relativePath |]) + Vitest.expect(isLfsPointerText worktreeText).toBe true + + let! objectPath = lfsObjectPathForHeadFile workPath relativePath + let! objectExists = pathExistsAsync objectPath + Vitest.expect(objectExists).toBe false + + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "batch dematerialization asks the remote per chunk and asks again for the pushed files only", + TestOptions(timeout = 120000), + fun () -> promise { + let! lfsProbe = runGit "." [| "lfs"; "version" |] + + match lfsProbe with + | Error _ -> Vitest.expect(true).toBe true + | Ok _ -> + let! root, workPath = createPushedLfsFixture true + + let observedCommands = ResizeArray() + let stopObserving: (unit -> unit) ref = ref ignore + + try + let batch = openBatchMaterialization workPath (join [| root; "origin.git" |]) + let unpushedPath = "other/c.bin" + + stopObserving.Value <- observeGitSpawnArguments observedCommands + + let! result = + batch.Dematerialize + ([| "data/a.bin"; unpushedPath; "data/b.bin" |] |> Array.map repositoryPath) + (ctx "batch-dematerialize-spawns") + |> Async.StartAsPromise + + stopObserving.Value () + stopObserving.Value <- ignore + + match result with + | PartiallySucceeded(outcome, failure) -> + Vitest.expect(outcome.AffectedPaths).toEqual [| "data/a.bin"; "data/b.bin" |] + Vitest.expect(failure.AffectedPaths).toEqual [| unpushedPath |] + Vitest.expect(failure.Details.Length).toBe 1 + Vitest.expect(failure.Details[0].Contains "Push it before freeing its local copy").toBe true + | Succeeded _ + | Failed _ -> failwith "Expected a partial success for a file whose commit is unpushed." + + let fetches = + observedCommands + |> Seq.filter (fun arguments -> + arguments |> Array.contains "lfs" && arguments |> Array.contains "fetch") + |> Seq.toArray + + let includedPatternCount (arguments: string[]) = + let includeArgument = arguments |> Array.find (fun argument -> argument.StartsWith "--include=") + includeArgument.Substring("--include=".Length).Split(',').Length + + let isDryRun (arguments: string[]) = arguments |> Array.contains "--dry-run" + + let dryRunCounts = fetches |> Array.filter isDryRun |> Array.map includedPatternCount + let refetchCounts = fetches |> Array.filter (isDryRun >> not) |> Array.map includedPatternCount + + Vitest.expect(fetches.Length).toBe 4 + Vitest.expect(dryRunCounts).toEqual [| 3; 2 |] + Vitest.expect(refetchCounts).toEqual [| 3; 2 |] + + do! removeDirectoryAsync root + with error -> + stopObserving.Value () + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "batch dematerialization settles a chunk with one dry run when the remote cannot be reached", + TestOptions(timeout = 120000), + fun () -> promise { + let! lfsProbe = runGit "." [| "lfs"; "version" |] + + match lfsProbe with + | Error _ -> Vitest.expect(true).toBe true + | Ok _ -> + let! root, workPath = createPushedLfsFixture false + + let observedCommands = ResizeArray() + let stopObserving: (unit -> unit) ref = ref ignore + + try + // Nothing listens on port 1, so the dry run fails at once with a refused connection. + let remoteUrl = "https://127.0.0.1:1/origin.git" + let! _ = runGitOk workPath [| "remote"; "set-url"; "origin"; remoteUrl |] + + let batch = openBatchMaterializationWithToken workPath remoteUrl + let paths = lfsDownloadFiles |> Array.map fst + + stopObserving.Value <- observeGitSpawnArguments observedCommands + + let! result = + batch.Dematerialize (paths |> Array.map repositoryPath) (ctx "batch-dematerialize-unreachable") + |> Async.StartAsPromise + + stopObserving.Value () + stopObserving.Value <- ignore + + match result with + | Failed failure -> + Vitest.expect(failure.Category).toEqual Network + Vitest.expect(failure.AffectedPaths).toEqual paths + Vitest.expect(failure.Details.Length).toBe paths.Length + + for index in 0 .. paths.Length - 1 do + Vitest + .expect(failure.Details[index].Contains $"Could not confirm that the remote has '{paths[index]}'") + .toBe true + | Succeeded _ + | PartiallySucceeded _ -> failwith "Expected a failure for every path when the remote cannot be reached." + + let fetches = + observedCommands + |> Seq.filter (fun arguments -> + arguments |> Array.contains "lfs" && arguments |> Array.contains "fetch") + |> Seq.toArray + + Vitest.expect(fetches.Length).toBe 1 + Vitest.expect(fetches[0] |> Array.contains "--dry-run").toBe true + + for relativePath, content in lfsDownloadFiles do + let! worktreeText = tryReadUtf8FileAsync (join [| workPath; relativePath |]) + Vitest.expect(worktreeText).toEqual (Some content) + + let! objectPath = lfsObjectPathForHeadFile workPath relativePath + let! objectExists = pathExistsAsync objectPath + Vitest.expect(objectExists).toBe true + + do! removeDirectoryAsync root + with error -> + stopObserving.Value () + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "batch dematerialization skips the remote for later chunks once an unreachable remote failed a chunk", + TestOptions(timeout = 600000), + fun () -> promise { + let! lfsProbe = runGit "." [| "lfs"; "version" |] + + match lfsProbe with + | Error _ -> Vitest.expect(true).toBe true + | Ok _ -> + let! root, workPath, _, _ = createPublishFixture GitWorkspaceSession.GitSessionHooks.none + + let observedCommands = ResizeArray() + let stopObserving: (unit -> unit) ref = ref ignore + + try + do! commitAndPushLfsFiles workPath manyLfsFiles + + // The long paths need two chunks of patterns. Nothing listens on port 1. + let remoteUrl = "https://127.0.0.1:1/origin.git" + let! _ = runGitOk workPath [| "remote"; "set-url"; "origin"; remoteUrl |] + + let batch = openBatchMaterializationWithToken workPath remoteUrl + let paths = manyLfsFiles |> Array.map (fun (_, relativePath, _) -> relativePath) + + stopObserving.Value <- observeGitSpawnArguments observedCommands + + let! result = + batch.Dematerialize + (paths |> Array.map repositoryPath) + (ctx "batch-dematerialize-unreachable-chunks") + |> Async.StartAsPromise + + stopObserving.Value () + stopObserving.Value <- ignore + + match result with + | Failed failure -> + Vitest.expect(failure.Category).toEqual Network + Vitest.expect(failure.AffectedPaths).toEqual paths + Vitest.expect(failure.Details.Length).toBe paths.Length + + let lastPath = Array.last paths + + Vitest + .expect( + (Array.last failure.Details) + .Contains $"Could not confirm that the remote has '{lastPath}'" + ) + .toBe true + | Succeeded _ + | PartiallySucceeded _ -> failwith "Expected a failure for every path when the remote cannot be reached." + + let fetches = + observedCommands + |> Seq.filter (fun arguments -> + arguments |> Array.contains "lfs" && arguments |> Array.contains "fetch") + |> Seq.toArray + + Vitest.expect(fetches.Length).toBe 1 + Vitest.expect(fetches[0] |> Array.contains "--dry-run").toBe true + + for _, relativePath, content in manyLfsFiles do + let! worktreeText = tryReadUtf8FileAsync (join [| workPath; relativePath |]) + Vitest.expect(worktreeText).toEqual (Some content) + + for relativePath in [| paths[0]; Array.last paths |] do + let! objectPath = lfsObjectPathForHeadFile workPath relativePath + let! objectExists = pathExistsAsync objectPath + Vitest.expect(objectExists).toBe true + + do! removeDirectoryAsync root + with error -> + stopObserving.Value () + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "batch materialization counts a path once when the request spells it in two cases", + TestOptions(timeout = 120000), + fun () -> promise { + let! lfsProbe = runGit "." [| "lfs"; "version" |] + + match lfsProbe with + | Error _ -> Vitest.expect(true).toBe true + | Ok _ -> + let! root, workPath, barePath = createFreedLfsFixture () + + try + let batch = openBatchMaterialization workPath barePath + + let! result = + batch.Materialize + ([| "data/a.bin"; "DATA/A.BIN" |] |> Array.map repositoryPath) + (ctx "batch-materialize-cases") + |> Async.StartAsPromise + + match result with + | Succeeded outcome -> Vitest.expect(outcome.AffectedPaths).toEqual [| "data/a.bin" |] + | PartiallySucceeded(_, failure) + | Failed failure -> failwith $"Expected the download to succeed: {failure.Message}" + + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "batch materialization looks up paths and splits candidates quickly in a large listing", + fun () -> promise { + let listing = Collections.Generic.Dictionary() + + for listedIndex in 0..19999 do + let name = $"data/run-{listedIndex % 200}/sample-{listedIndex}.bin" + + listing[name] <- ({ + name = name + size = 1.0 + checkout = false + downloaded = false + ``oid_type`` = "sha256" + oid = "0000000000000000000000000000000000000000000000000000000000000000" + version = "https://git-lfs.github.com/spec/v1" + }: VersionControlService.Git.GitEngineTypes.GitLfsLsFileInfo) + + let candidates = + Array.init 1000 (fun number -> + if number % 100 = 0 then + $"data/run-{number % 200}/odd,{number}.bin" + else + $"other/set-{number}/file.bin") + + let startedAt = nowMilliseconds () + let index = GitLfsService.createListedPathIndex listing.Keys + + let overlapping = + candidates |> Array.filter (GitLfsService.pathPatternMatchesIndexedPath index) + + let lookup = GitLfsService.createListingLookup listing + + let found = + listing.Keys + |> Seq.truncate 1000 + |> Seq.filter (fun name -> (lookup (name.ToUpperInvariant())).IsSome) + |> Seq.length + + let elapsed = nowMilliseconds () - startedAt + + Vitest.expect(elapsed < 2000.0).toBe true + // None of the candidates shares a pattern with a listed path. + Vitest.expect(overlapping.Length).toBe 0 + Vitest.expect(found).toBe 1000 + Vitest.expect(GitLfsService.pathPatternMatchesIndexedPath index "data/run-1/sample,1.bin").toBe true + Vitest.expect(GitLfsService.pathPatternMatchesIndexedPath index "DATA/run-1").toBe true + Vitest.expect(GitLfsService.pathPatternMatchesIndexedPath index "data/run-1/sample-1.bina").toBe false + } + ) + + Vitest.test ( + "a pointer file is told apart from a small file with other content", + fun () -> promise { + let! root = createTempDirectoryAsync () + + try + let pointerPath = join [| root; "pointer.bin" |] + let contentPath = join [| root; "content.bin" |] + + do! + writeUtf8FileAsync + pointerPath + "version https://git-lfs.github.com/spec/v1\noid sha256:4d7a214614ab2935c943f9e0ff69d22eadbb8f32b1258daaa5e2ca24d17e2393\nsize 12\n" + + do! writeUtf8FileAsync contentPath "small file\n" + + Vitest.expect(GitService.isLfsPointerFile pointerPath).toBe true + Vitest.expect(GitService.isLfsPointerFile contentPath).toBe false + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "a batch result takes its category from the first failure that is not a cancellation", + fun () -> promise { + let failed (path: string) (kind: GitEngineTypes.GitFailureKind) (message: string) = + ({ + Path = path + Result = Error({ Kind = kind; Message = message }: GitService.GitFailure) + }: GitService.LfsPathOutcome) + + let changed = + ({ Path = "c.bin"; Result = Ok GitService.Changed }: GitService.LfsPathOutcome) + + let mixed = + GitLfsExtensions.toBatchResult + GitLfsExtensions.batchMaterializeAction + [| + failed "a.bin" GitEngineTypes.GitFailureKind.Canceled "canceled" + failed "b.bin" GitEngineTypes.GitFailureKind.Unknown "object store is unreadable" + changed + |] + + match mixed with + | PartiallySucceeded(_, failure) -> + Vitest.expect(failure.Category).toEqual ProviderError + Vitest.expect(failure.Code).toBe "batch_materialization_incomplete" + Vitest.expect(failure.Message).toBe "2 of 3 paths failed: object store is unreadable" + | Succeeded _ + | Failed _ -> failwith "Expected a partial success for a run with one changed path." + + let allCanceled = + GitLfsExtensions.toBatchResult + GitLfsExtensions.batchMaterializeAction + [| + failed "a.bin" GitEngineTypes.GitFailureKind.Canceled "canceled" + failed "b.bin" GitEngineTypes.GitFailureKind.Canceled "canceled" + |] + + match allCanceled with + | Failed failure -> + Vitest.expect(failure.Category).toEqual Canceled + Vitest.expect(failure.Code).toBe "operation_canceled" + | Succeeded _ + | PartiallySucceeded _ -> failwith "Expected a failure when every path was canceled." + } + ) + + Vitest.test ( + "a partial batch result recommends removing the index lock when a path hit one", + fun () -> promise { + let lockFailure = + ({ + Path = "a.bin" + Result = + Error( + { + Kind = GitEngineTypes.GitFailureKind.Unknown + Message = "fatal: Unable to create '/work/.git/index.lock': File exists." + }: GitService.GitFailure + ) + }: GitService.LfsPathOutcome) + + let changed = + ({ Path = "c.bin"; Result = Ok GitService.Changed }: GitService.LfsPathOutcome) + + match GitLfsExtensions.toBatchResult GitLfsExtensions.batchMaterializeAction [| lockFailure; changed |] with + | PartiallySucceeded(_, failure) -> + Vitest.expect(failure.RecoveryAction |> Option.map _.Code).toEqual (Some "remove_index_lock") + | Succeeded _ + | Failed _ -> failwith "Expected a partial success for a run with one changed path." + } + ) + + Vitest.test ( + "a batch result in which every path failed recommends removing the index lock when a path hit one", + fun () -> promise { + let failed (path: string) (message: string) = + ({ + Path = path + Result = Error({ Kind = GitEngineTypes.GitFailureKind.Unknown; Message = message }: GitService.GitFailure) + }: GitService.LfsPathOutcome) + + // The first failure is not the lock one, so it supplies the message and the lock only decides the recovery. + match + GitLfsExtensions.toBatchResult + GitLfsExtensions.batchMaterializeAction + [| + failed "a.bin" "object store is unreadable" + failed "b.bin" "fatal: Unable to create '/work/.git/index.lock': File exists." + |] + with + | Failed failure -> + Vitest.expect(failure.Code).toBe "batch_materialization_incomplete" + Vitest.expect(failure.Message).toBe "2 of 2 paths failed: object store is unreadable" + Vitest.expect(failure.RecoveryAction |> Option.map _.Code).toEqual (Some "remove_index_lock") + | Succeeded _ + | PartiallySucceeded _ -> failwith "Expected a failure when every path failed." + } + ) + Vitest.test ( "a workspace mutation waits until a running dematerialization finishes", TestOptions(timeout = 120000), diff --git a/tests/VersionControlService.Tests/GitProviderContract.test.fs b/tests/VersionControlService.Tests/GitProviderContract.test.fs index f4bdf31..e78b57d 100644 --- a/tests/VersionControlService.Tests/GitProviderContract.test.fs +++ b/tests/VersionControlService.Tests/GitProviderContract.test.fs @@ -400,6 +400,7 @@ let createGitHarness () : ProviderTestHarness = "synchronization" "conflicts" "materialization" + "batch-materialization" "storage-policy" "maintenance" "browser" @@ -609,6 +610,37 @@ Vitest.describe ( Vitest.expect(missingGitLfsCommand).toEqual (GitEngineTypes.GitFailureKind.LfsInstallRequired) ) + Vitest.test ( + "classifies connection failure texts as network or timeout", + fun () -> + let refused = + GitService.classifyFailureKind + "dial tcp 127.0.0.1:1: connectex: No connection could be made because the target machine actively refused it." + + let unknownHost = GitService.classifyFailureKind "dial tcp: lookup nohost.invalid: no such host" + + let unanswered = + GitService.classifyFailureKind + "connectex: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond." + + let reset = + GitService.classifyFailureKind + "read tcp 127.0.0.1:50000->127.0.0.1:1: wsarecv: An existing connection was forcibly closed by the remote host." + + let closedByServer = + GitService.classifyFailureKind + "Fetching reference refs/heads/main\nbatch response: Post \"http://127.0.0.1:1/origin.git/info/lfs/objects/batch\": EOF\nerror: failed to fetch some objects from 'http://127.0.0.1:1/origin.git/info/lfs'" + + let bareEof = GitService.classifyFailureKind "error: unexpected EOF while reading the file" + + Vitest.expect(refused).toEqual (GitEngineTypes.GitFailureKind.Network) + Vitest.expect(unknownHost).toEqual (GitEngineTypes.GitFailureKind.Network) + Vitest.expect(unanswered).toEqual (GitEngineTypes.GitFailureKind.Timeout) + Vitest.expect(reset).toEqual (GitEngineTypes.GitFailureKind.Network) + Vitest.expect(closedByServer).toEqual (GitEngineTypes.GitFailureKind.Network) + Vitest.expect(bareEof).toEqual (GitEngineTypes.GitFailureKind.Unknown) + ) + Vitest.test ( "preserves current and tracking flags across branch states", TestOptions(timeout = 120000), @@ -3769,7 +3801,7 @@ let private lfsMediaDirectoryFromEnvironment (lfsEnvironment: string) = let private lfsObjectPath (mediaDirectory: string) (oid: string) = join [| mediaDirectory; oid.Substring(0, 2); oid.Substring(2, 2); oid |] -let private createDownloadedLfsRestoreFixture () = promise { +let private createDownloadedLfsRestoreFixtureWithHooks (hooks: GitWorkspaceSession.GitSessionHooks) = promise { let! root = createTempDirectoryAsync () let barePath = join [| root; "origin.git" |] let sourcePath = join [| root; "source" |] @@ -3804,14 +3836,75 @@ let private createDownloadedLfsRestoreFixture () = promise { ConnectionProfileId = None } - return root, repoPath, GitWorkspaceSession.createSession GitWorkspaceSession.GitSessionHooks.none binding + return root, repoPath, GitWorkspaceSession.createSession hooks binding } +let private createDownloadedLfsRestoreFixture () = + createDownloadedLfsRestoreFixtureWithHooks GitWorkspaceSession.GitSessionHooks.none + let private repositoryPath (value: string) = match RepositoryPath.tryCreate value with | Ok path -> path | Error message -> failwith message +/// Restores a locally edited LFS file while every `git lfs checkout` ends with the text that git-lfs 3.7.0 +/// prints when the index lock is held, and exits with 0. With `createLock`, the checkout also creates the +/// lock file, which the text does not name. Returns the result of the restore and whether the lock exists. +let private restoreLfsFileWithIndexError (createLock: bool) (operationName: string) = promise { + let hooks: GitWorkspaceSession.GitSessionHooks = { + GitWorkspaceSession.GitSessionHooks.none with + RunProcess = + Some(fun request processContext -> + async { + if request.Arguments.Length >= 2 && request.Arguments[0] = "lfs" && request.Arguments[1] = "checkout" then + if createLock then + let workingDirectory = request.WorkingDirectory |> Option.defaultValue "." + + do! + writeUtf8FileAsync + (join [| workingDirectory; ".git"; "index.lock" |]) + "held by another process\n" + |> Async.AwaitPromise + + return + OperationResult.succeeded { + NodeProcess.ExitCode = 0 + StdOut = "" + StdErr = "Error updating the Git index:\n\n\nErrors logged to 'x.log'." + } + else + return! NodeProcess.run request processContext + }) + } + + let! root, repoPath, session = createDownloadedLfsRestoreFixtureWithHooks hooks + + try + do! writeUtf8FileAsync (join [| repoPath; "large.bin" |]) "local edit\n" + + let! statusResult = + session.Core.GetStatus(OperationContext.detached $"{operationName}-status") + |> Async.StartAsPromise + + let status = expectProviderValue "status before restoring the LFS file" statusResult + + let! restoreResult = + session.Core.RestorePaths + { + Paths = [| repositoryPath "large.bin" |] + ExpectedWorkspaceVersion = status.WorkspaceVersion + } + (OperationContext.detached operationName) + |> Async.StartAsPromise + + let lockExists = NodeFileSystem.existsSync (join [| repoPath; ".git"; "index.lock" |]) + do! removeDirectoryAsync root + return restoreResult, lockExists + with error -> + do! removeDirectoryAsync root + return raise error +} + Vitest.describe ( "Git clone target refs", fun () -> @@ -3997,7 +4090,7 @@ Vitest.describe ( GitWorkspaceSession.GitSessionHooks.none with RunProcess = Some(fun request context -> - if request.Arguments = [| "fetch"; "origin" |] then + if request.Arguments |> Array.contains "fetch" then async { fetchObserved <- true return @@ -4326,6 +4419,55 @@ Vitest.describe ( } ) + Vitest.test ( + "RestorePaths reports the lock recovery when the checkout ends with success but could not update the index and a lock exists", + TestOptions(timeout = 120000), + fun () -> promise { + let! lfsProbe = runGitResultIn "." [| "lfs"; "version" |] + + if lfsProbe.ExitCode <> 0 then + Vitest.expect(true).toBe true + else + let! result, lockExists = restoreLfsFileWithIndexError true "restore-lfs-index-error-lock" + + match result with + | PartiallySucceeded(_, failure) -> + Vitest.expect(failure.Code).toBe "object_materialization_failed" + Vitest.expect(failure.StateChanged).toBe true + Vitest.expect(failure.AffectedPaths).toEqual [| "large.bin" |] + Vitest.expect(failure.RecoveryAction |> Option.map _.Code).toEqual (Some "remove_index_lock") + | Failed failure -> failwith $"Expected a partial result, received {failure.Category}/{failure.Code}." + | Succeeded _ -> failwith "Expected the checkout that could not update the index to be reported." + + Vitest.expect(lockExists).toBe true + } + ) + + Vitest.test ( + "RestorePaths keeps the plain failure when the checkout ends with success but could not update the index and no lock exists", + TestOptions(timeout = 120000), + fun () -> promise { + let! lfsProbe = runGitResultIn "." [| "lfs"; "version" |] + + if lfsProbe.ExitCode <> 0 then + Vitest.expect(true).toBe true + else + let! result, lockExists = restoreLfsFileWithIndexError false "restore-lfs-index-error-no-lock" + + match result with + | PartiallySucceeded(_, failure) -> + Vitest.expect(failure.Code).toBe "object_materialization_failed" + Vitest.expect(failure.StateChanged).toBe true + Vitest.expect(failure.AffectedPaths).toEqual [| "large.bin" |] + Vitest.expect(failure.Message.Contains "Error updating the Git index").toBe true + Vitest.expect(failure.RecoveryAction |> Option.map _.Code).toEqual (Some "retry_materialization") + | Failed failure -> failwith $"Expected a partial result, received {failure.Category}/{failure.Code}." + | Succeeded _ -> failwith "Expected the checkout that could not update the index to be reported." + + Vitest.expect(lockExists).toBe false + } + ) + Vitest.test ( "RestorePaths leaves a pointer when its LFS object is absent locally", TestOptions(timeout = 120000), diff --git a/tests/VersionControlService.Tests/GitRevisionPolicy.test.fs b/tests/VersionControlService.Tests/GitRevisionPolicy.test.fs index b1807a5..4861ac6 100644 --- a/tests/VersionControlService.Tests/GitRevisionPolicy.test.fs +++ b/tests/VersionControlService.Tests/GitRevisionPolicy.test.fs @@ -230,6 +230,70 @@ let private lfsMediaDirectoryFromEnvironment (lfsEnvironment: string) = None) |> Option.defaultWith (fun () -> failwith "Expected Git LFS to report its local media directory.") +/// Unmarks `manual/.bin` while `git lfs checkout` writes the file, prints the text that git-lfs 3.7.0 +/// prints for a held index lock and exits with 0. With `createLock`, the checkout also creates the lock file, +/// which the text does not name. Returns the result of the unmark and whether the lock file exists. +let private unmarkWithIndexError (createLock: bool) (name: string) : JS.Promise * bool> = + withGitFixture RevisionPolicyStrategy.automatic (Some "\n") (fun fixture -> promise { + let path = $"manual/{name}.bin" + let absolutePath = join [| fixture.WorkPath; path |] + let lockPath = join [| fixture.WorkPath; ".git"; "index.lock" |] + do! writeUtf8FileAsync absolutePath "local object content\n" + + let! initial = createRevision fixture "test: commit path before the index error" [| path |] + expectSucceeded "initial plain revision" initial |> ignore + + let storagePolicy = + fixture.Session.StoragePolicy + |> Option.defaultWith (fun () -> failwith "Expected Git storage policy.") + + let! markResult = + storagePolicy.SetPathPolicy (repositoryPath path) true (context $"mark-{name}") + |> Async.StartAsPromise + + expectSucceeded "mark before the index error" markResult |> ignore + + let! lfsRevision = + createRevision fixture "test: commit path with LFS before the index error" [| path; ".gitattributes" |] + + expectSucceeded "LFS revision before the index error" lfsRevision |> ignore + let! pointer = runGitOk fixture.WorkPath [| "cat-file"; "-p"; $"HEAD:{path}" |] + do! writeUtf8FileAsync absolutePath pointer + + // The fake checkout restores the content, as git-lfs does before it reports the index error. + let hooks = { + GitWorkspaceSession.GitSessionHooks.none with + RunProcess = + Some(fun request processContext -> + async { + match request.Arguments with + | [| "lfs"; "checkout"; "--"; _ |] -> + do! writeUtf8FileAsync absolutePath "local object content\n" |> Async.AwaitPromise + + if createLock then + do! writeUtf8FileAsync lockPath "held by another process\n" |> Async.AwaitPromise + + return + OperationResult.succeeded { + ExitCode = 0 + StdOut = "" + StdErr = "Error updating the Git index:\n\n\nErrors logged to 'x.log'." + } + | _ -> return! NodeProcess.run request processContext + }) + } + + let hookedStoragePolicy = + (GitWorkspaceSession.createSession hooks fixture.Binding).StoragePolicy + |> Option.defaultWith (fun () -> failwith "Expected Git storage policy.") + + let! unmarkResult = + hookedStoragePolicy.SetPathPolicy (repositoryPath path) false (context name) + |> Async.StartAsPromise + + return unmarkResult, NodeFileSystem.existsSync lockPath + }) + Vitest.describe ( "Git revision policy", fun () -> @@ -907,6 +971,47 @@ Vitest.describe ( }) ) + Vitest.test ( + "unmarking reports the index lock when Git LFS ends the checkout with success but could not update the index", + TestOptions(timeout = 180000), + fun () -> promise { + let! result, lockExists = unmarkWithIndexError true "unmark-index-error" + let path = "manual/unmark-index-error.bin" + + match result with + | Failed failure -> + Vitest.expect(failure.Code).toBe "index_locked" + Vitest.expect(failure.RecoveryAction |> Option.map _.Code).toEqual (Some "remove_index_lock") + Vitest.expect(failure.StateChanged).toBe true + Vitest.expect(failure.AffectedPaths).toEqual [| path |] + | Succeeded _ + | PartiallySucceeded _ -> failwith "Expected unmarking to fail while the index lock is held." + + Vitest.expect(lockExists).toBe true + } + ) + + Vitest.test ( + "unmarking keeps the plain failure when Git LFS ends the checkout with success but could not update the index and no lock exists", + TestOptions(timeout = 180000), + fun () -> promise { + let! result, lockExists = unmarkWithIndexError false "unmark-index-error-no-lock" + let path = "manual/unmark-index-error-no-lock.bin" + + match result with + | Failed failure -> + Vitest.expect(failure.Code).toBe "object_materialization_failed" + Vitest.expect(failure.Message.Contains "Error updating the Git index").toBe true + Vitest.expect(failure.RecoveryAction).toEqual None + Vitest.expect(failure.StateChanged).toBe true + Vitest.expect(failure.AffectedPaths).toEqual [| path |] + | Succeeded _ + | PartiallySucceeded _ -> failwith "Expected unmarking to fail after the index error." + + Vitest.expect(lockExists).toBe false + } + ) + Vitest.test ( "unmarking a root file leaves a same-named subfolder pointer untouched", TestOptions(timeout = 180000), diff --git a/tests/VersionControlService.Tests/GitSynchronization.test.fs b/tests/VersionControlService.Tests/GitSynchronization.test.fs index aec96db..20b81f8 100644 --- a/tests/VersionControlService.Tests/GitSynchronization.test.fs +++ b/tests/VersionControlService.Tests/GitSynchronization.test.fs @@ -85,6 +85,9 @@ let private buffersEqual (_left: obj) (_right: obj) : bool = jsNative """)>] let private observeGitSpawnArguments (_observed: ResizeArray) : unit -> unit = jsNative +[] +let private nodeExecutablePath: string = jsNative + /// The git subcommand of a spawn, skipping global options such as `-c key=value`. let private gitSubcommand (arguments: string[]) = let rec find index = @@ -483,6 +486,69 @@ let private createLfsConflictFixtureWithOptions let private createLfsConflictFixture () = createLfsConflictFixtureWithOptions GitWorkspaceSession.GitSessionHooks.none "tracked.xlsx" None [||] +/// Picks the workspace candidate of an LFS conflict while every `git lfs checkout` ends with the text that +/// git-lfs 3.7.0 prints when the index lock is held, and exits with 0. With `createLock`, the checkout also +/// creates the lock file, which the text does not name. Returns the result of the pick and whether the lock exists. +let private pickLfsConflictWithIndexError (createLock: bool) (operationName: string) = promise { + let hooks: GitWorkspaceSession.GitSessionHooks = { + GitWorkspaceSession.GitSessionHooks.none with + RunProcess = + Some(fun request processContext -> + async { + if request.Arguments.Length >= 2 && request.Arguments[0] = "lfs" && request.Arguments[1] = "checkout" then + if createLock then + let workingDirectory = request.WorkingDirectory |> Option.defaultValue "." + + do! + writeUtf8FileAsync + (join [| workingDirectory; ".git"; "index.lock" |]) + "held by another process\n" + |> Async.AwaitPromise + + return + OperationResult.succeeded { + NodeProcess.ExitCode = 0 + StdOut = "" + StdErr = "Error updating the Git index:\n\n\nErrors logged to 'x.log'." + } + else + return! NodeProcess.run request processContext + }) + } + + let! root, workPath, path, _, _, _, session = createLfsConflictFixtureWithOptions hooks "tracked.xlsx" None [||] + + try + let conflicts = conflictService session + let! summaryResult = Async.StartAsPromise(conflicts.GetActiveSession(ctx $"{operationName}-session")) + + let summary = + match expectValue "LFS conflict session" summaryResult with + | Some value -> value + | None -> failwith "Expected an active LFS conflict session." + + let! status = sessionStatus session + + let! resolveResult = + Async.StartAsPromise( + conflicts.Resolve + { + Handle = summary.Handle + ExpectedWorkspaceVersion = status.WorkspaceVersion + Path = mkPath path + Resolution = PickCandidate "workspace" + } + (ctx $"{operationName}-pick") + ) + + let! lockExists = pathExistsAsync (join [| workPath; ".git"; "index.lock" |]) + do! removeDirectoryAsync root + return resolveResult, lockExists + with error -> + do! removeDirectoryAsync root + return raise error +} + let private createModifyDeleteConflictFixture (hooks: GitWorkspaceSession.GitSessionHooks) (path: string) @@ -2679,6 +2745,53 @@ Vitest.describe ( } ) + Vitest.test ( + "LFS pick reports the lock recovery when the checkout ends with success but could not update the index and a lock exists", + TestOptions(timeout = 120000), + fun () -> promise { + let! lfsProbe = runGitResultIn "." [| "lfs"; "version" |] + + if lfsProbe.ExitCode <> 0 then + Vitest.expect(true).toBe true + else + let! resolveResult, lockExists = pickLfsConflictWithIndexError true "lfs-pick-index-error-lock" + + match resolveResult with + | PartiallySucceeded(_, failure) -> + Vitest.expect(failure.Code).toBe "object_materialization_failed" + Vitest.expect(failure.StateChanged).toBe true + Vitest.expect(failure.RecoveryAction |> Option.map _.Code).toEqual (Some "remove_index_lock") + | Failed failure -> failwith $"Expected a partial result, received {failure.Category}/{failure.Code}." + | Succeeded _ -> failwith "Expected the checkout that could not update the index to be reported." + + Vitest.expect(lockExists).toBe true + } + ) + + Vitest.test ( + "LFS pick keeps the plain failure when the checkout ends with success but could not update the index and no lock exists", + TestOptions(timeout = 120000), + fun () -> promise { + let! lfsProbe = runGitResultIn "." [| "lfs"; "version" |] + + if lfsProbe.ExitCode <> 0 then + Vitest.expect(true).toBe true + else + let! resolveResult, lockExists = pickLfsConflictWithIndexError false "lfs-pick-index-error-no-lock" + + match resolveResult with + | PartiallySucceeded(_, failure) -> + Vitest.expect(failure.Code).toBe "object_materialization_failed" + Vitest.expect(failure.StateChanged).toBe true + Vitest.expect(failure.Message.Contains "Error updating the Git index").toBe true + Vitest.expect(failure.RecoveryAction |> Option.map _.Code).toEqual (Some "retry_materialization") + | Failed failure -> failwith $"Expected a partial result, received {failure.Category}/{failure.Code}." + | Succeeded _ -> failwith "Expected the checkout that could not update the index to be reported." + + Vitest.expect(lockExists).toBe false + } + ) + Vitest.test ( "rejects supplied content for an LFS conflict without changing the file or index", TestOptions(timeout = 120000), @@ -5694,16 +5807,21 @@ Vitest.describe ( let private unhydratedLfsContent = "large binary payload\n" -let private isLfsPullRequest (request: NodeProcess.ProcessRequest) = - request.Arguments |> Array.contains "lfs" && request.Arguments |> Array.contains "pull" +let private isLfsCommandRequest (command: string) (request: NodeProcess.ProcessRequest) = + request.Arguments + |> Array.windowed 2 + |> Array.exists (fun pair -> pair[0] = "lfs" && pair[1] = command) + +let private isLfsPullRequest = isLfsCommandRequest "pull" +let private isLfsFetchRequest = isLfsCommandRequest "fetch" +let private isLfsCheckoutRequest = isLfsCommandRequest "checkout" -/// An origin with one LFS file and a work clone that holds only its pointer, as after a -/// clone with the large-object setting off. The work clone is level with its upstream. -let private createUnhydratedLfsClone (hooks: GitWorkspaceSession.GitSessionHooks) = promise { +/// A temporary directory with a bare origin at origin.git that holds the LFS files. The objects of +/// the files in `lostFiles` are deleted from the origin afterwards, like objects that the server lost. +let private createLfsOrigin (files: (string * string) list) (lostFiles: string list) = promise { let! root = createTempDirectoryAsync () let barePath = join [| root; "origin.git" |] let sourcePath = join [| root; "source" |] - let workPath = join [| root; "work" |] let! _ = runGitIn root [| "init"; "--bare"; "-b"; "main"; barePath |] let! _ = runGitIn root [| "init"; "-b"; "main"; sourcePath |] let! _ = runGitIn sourcePath [| "config"; "user.name"; "VCS Sync Tests" |] @@ -5711,12 +5829,39 @@ let private createUnhydratedLfsClone (hooks: GitWorkspaceSession.GitSessionHooks let! _ = runGitIn sourcePath [| "config"; "core.autocrlf"; "false" |] let! _ = runGitIn sourcePath [| "lfs"; "install"; "--local" |] let! _ = runGitIn sourcePath [| "lfs"; "track"; "*.bin" |] - do! writeUtf8FileAsync (join [| sourcePath; "large.bin" |]) unhydratedLfsContent + + for name, content in files do + do! writeUtf8FileAsync (join [| sourcePath; name |]) content + let! _ = runGitIn sourcePath [| "add"; "-A" |] let! _ = runGitIn sourcePath [| "commit"; "-m"; "init: lfs base" |] let! _ = runGitIn sourcePath [| "remote"; "add"; "origin"; barePath |] let! _ = runGitIn sourcePath [| "push"; "-u"; "origin"; "main" |] + for name in lostFiles do + let! pointer = runGitIn sourcePath [| "show"; $"HEAD:{name}" |] + + let oid = + pointer.Replace("\r\n", "\n").Split('\n') + |> Array.find (fun line -> line.StartsWith "oid sha256:") + |> fun line -> line.Substring("oid sha256:".Length).Trim() + + do! removePathAsync (join [| barePath; "lfs"; "objects"; oid.Substring(0, 2); oid.Substring(2, 2); oid |]) + + return root +} + +/// An origin with LFS files and a work clone that holds only their pointers, as after a clone with the +/// large-object setting off. The work clone is level with its upstream. +let private createUnhydratedLfsCloneOf + (files: (string * string) list) + (lostFiles: string list) + (hooks: GitWorkspaceSession.GitSessionHooks) + = promise { + let! root = createLfsOrigin files lostFiles + let barePath = join [| root; "origin.git" |] + let workPath = join [| root; "work" |] + let cloneRequest = { NodeProcess.ProcessRequest.create "git" [| "clone"; "-c"; "core.autocrlf=false"; barePath; workPath |] with WorkingDirectory = Some root @@ -5733,6 +5878,10 @@ let private createUnhydratedLfsClone (hooks: GitWorkspaceSession.GitSessionHooks return root, workPath, GitWorkspaceSession.createSession hooks (syncBinding workPath barePath) } +/// An origin with one LFS file and a work clone that holds only its pointer. +let private createUnhydratedLfsClone (hooks: GitWorkspaceSession.GitSessionHooks) = + createUnhydratedLfsCloneOf [ "large.bin", unhydratedLfsContent ] [] hooks + let private setMaterializeLargeObjects (workPath: string) (enabled: bool) = runGitIn workPath @@ -5743,7 +5892,7 @@ let private setMaterializeLargeObjects (workPath: string) (enabled: bool) = (if enabled then "true" else "false") |] -let private synchronizeWithoutPublish (session: WorkspaceSession) (name: string) = promise { +let private synchronizeWithoutPublishIn (session: WorkspaceSession) (context: OperationContext) = promise { let! status = sessionStatus session return! @@ -5754,10 +5903,13 @@ let private synchronizeWithoutPublish (session: WorkspaceSession) (name: string) AcceptUpdateRisks = false PublishLocalRevisions = false } - (ctx name) + context |> Async.StartAsPromise } +let private synchronizeWithoutPublish (session: WorkspaceSession) (name: string) = + synchronizeWithoutPublishIn session (ctx name) + Vitest.describe ( "Git LFS transfer ordering", fun () -> @@ -5785,7 +5937,7 @@ Vitest.describe ( ) Vitest.test ( - "synchronization without anything to merge leaves pointers when the setting is off", + "hydration runs lfs fetch with the remote and ref and then lfs checkout, and never lfs pull", TestOptions(timeout = 120000), fun () -> promise { let observed = ResizeArray() @@ -5802,13 +5954,35 @@ Vitest.describe ( let! root, workPath, session = createUnhydratedLfsClone hooks try - let! _ = setMaterializeLargeObjects workPath false - let! result = synchronizeWithoutPublish session "lfs-up-to-date-setting-off" - expectSucceeded "synchronize with the setting off" result |> ignore + let! _ = setMaterializeLargeObjects workPath true + let! result = synchronizeWithoutPublish session "lfs-fetch-then-checkout" + expectSucceeded "synchronize with a two-step hydration" result |> ignore + let fetchIndex = observed |> Seq.findIndex isLfsFetchRequest + let checkoutIndex = observed |> Seq.findIndex isLfsCheckoutRequest + Vitest.expect(checkoutIndex > fetchIndex).toBe true Vitest.expect(observed |> Seq.exists isLfsPullRequest).toBe false + + let fetchRequest = observed[fetchIndex] + let checkoutRequest = observed[checkoutIndex] + + Vitest + .expect(fetchRequest.Arguments |> Array.windowed 4 |> Array.contains [| "lfs"; "fetch"; "origin"; "main" |]) + .toBe true + + Vitest.expect(Array.last checkoutRequest.Arguments).toBe "checkout" + + // Both calls carry the same authentication arguments, which come before the lfs command. + let authenticationOf (request: NodeProcess.ProcessRequest) = + request.Arguments |> Array.takeWhile (fun argument -> argument <> "lfs") + + Vitest.expect(authenticationOf checkoutRequest).toEqual (authenticationOf fetchRequest) + + for request in [| fetchRequest; checkoutRequest |] do + Vitest.expect(request.Environment |> Array.contains ("GIT_TERMINAL_PROMPT", "0")).toBe true + let! content = tryReadUtf8FileAsync (join [| workPath; "large.bin" |]) - Vitest.expect((content = Some unhydratedLfsContent)).toBe false + Vitest.expect(content).toEqual (Some unhydratedLfsContent) do! removeDirectoryAsync root with error -> do! removeDirectoryAsync root @@ -5817,24 +5991,30 @@ Vitest.describe ( ) Vitest.test ( - "update without anything to merge reports a failed download as partial success", + "canceling the download during the fetch reports a retryable cancel, leaves no index.lock and no checkout", TestOptions(timeout = 120000), fun () -> promise { + let observed = ResizeArray() + let source = OperationCancellation.Source() + + // The fetch is replaced by a program that prints one meter and then waits to be killed. + let blockedFetchScript = + "process.stdout.write('Downloading LFS objects: 50% (1/2), 1 B | 1 B/s\\r');setInterval(()=>{},1000);" + let hooks: GitWorkspaceSession.GitSessionHooks = { RunBytesProcess = None RunProcess = Some(fun request processContext -> - async { - if isLfsPullRequest request then - return - OperationResult.succeeded { - NodeProcess.ExitCode = 1 - StdOut = "" - StdErr = "HTTP 401 Unauthorized during LFS hydration" - } - else - return! NodeProcess.run request processContext - }) + observed.Add request + + if isLfsFetchRequest request then + NodeProcess.run + { request with + Command = nodeExecutablePath + Arguments = [| "-e"; blockedFetchScript |] } + processContext + else + NodeProcess.run request processContext) Barrier = None } @@ -5844,20 +6024,38 @@ Vitest.describe ( let! _ = setMaterializeLargeObjects workPath true let! status = sessionStatus session + let context = + OperationContext.create "lfs-cancel-during-fetch" source.Cancellation (fun progress -> + if progress.PhaseCode = "lfs-pull" && progress.Completed.IsSome then + source.Cancel()) + let! updateResult = - (syncService session).Update - { ExpectedWorkspaceVersion = status.WorkspaceVersion } - (ctx "lfs-up-to-date-update") + (syncService session).Update { ExpectedWorkspaceVersion = status.WorkspaceVersion } context |> Async.StartAsPromise match updateResult with | PartiallySucceeded(_, failure) -> - Vitest.expect(failure.Category).toEqual Authentication + Vitest.expect(failure.Category).toEqual Canceled Vitest.expect(failure.Code).toBe "hydration_failed" Vitest.expect(failure.RecoveryAction |> Option.map _.Code).toEqual (Some "retry_materialization") - | Failed failure -> failwith $"Expected partial download result, received {failure.Code}." - | Succeeded _ -> failwith "Expected the failed download to be reported." + | Failed failure -> failwith $"Expected a partial result, received {failure.Code}." + | Succeeded _ -> failwith "Expected the canceled download to be reported." + + Vitest.expect(observed |> Seq.exists isLfsCheckoutRequest).toBe false + let! lockExists = pathExistsAsync (join [| workPath; ".git"; "index.lock" |]) + Vitest.expect(lockExists).toBe false + + let materialization = + session.ObjectMaterialization + |> Option.defaultWith (fun () -> failwith "Expected Git object materialization.") + let! materializeResult = + materialization.Materialize (mkPath "large.bin") (ctx "lfs-materialize-after-cancel") + |> Async.StartAsPromise + + expectSucceeded "materialize after the canceled download" materializeResult |> ignore + let! content = tryReadUtf8FileAsync (join [| workPath; "large.bin" |]) + Vitest.expect(content).toEqual (Some unhydratedLfsContent) do! removeDirectoryAsync root with error -> do! removeDirectoryAsync root @@ -5866,22 +6064,68 @@ Vitest.describe ( ) Vitest.test ( - "update skips implicit smudge and reports failed explicit hydration as partial success", + "canceling the download during the checkout lets the checkout finish and reports the completed work", TestOptions(timeout = 120000), fun () -> promise { - let observed = ResizeArray() + let source = OperationCancellation.Source() + let mutable checkoutSawCancellation = true let hooks: GitWorkspaceSession.GitSessionHooks = { RunBytesProcess = None RunProcess = Some(fun request processContext -> async { - observed.Add request + if isLfsCheckoutRequest request then + // The cancel arrives as the checkout starts. The checkout must still run to its end. + source.Cancel() + checkoutSawCancellation <- processContext.Cancellation.IsCancellationRequested() + + return! NodeProcess.run request processContext + }) + Barrier = None + } + + let! root, workPath, session = createUnhydratedLfsClone hooks + + try + let! _ = setMaterializeLargeObjects workPath true + let! status = sessionStatus session + + let context = + OperationContext.create "lfs-cancel-during-checkout" source.Cancellation ignore + + let! updateResult = + (syncService session).Update { ExpectedWorkspaceVersion = status.WorkspaceVersion } context + |> Async.StartAsPromise + + expectSucceeded "update that is canceled during the checkout" updateResult |> ignore + Vitest.expect(source.IsCancellationRequested).toBe true + Vitest.expect(checkoutSawCancellation).toBe false + let! lockExists = pathExistsAsync (join [| workPath; ".git"; "index.lock" |]) + Vitest.expect(lockExists).toBe false + let! content = tryReadUtf8FileAsync (join [| workPath; "large.bin" |]) + Vitest.expect(content).toEqual (Some unhydratedLfsContent) + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "a failed fetch with an index.lock in the repository keeps the plain retry and leaves the lock in place", + TestOptions(timeout = 120000), + fun () -> promise { + let mutable lockPath = "" + + let hooks: GitWorkspaceSession.GitSessionHooks = { + RunBytesProcess = None + RunProcess = + Some(fun request processContext -> + async { + if isLfsFetchRequest request then + do! writeUtf8FileAsync lockPath "held by another process\n" |> Async.AwaitPromise - if - request.Arguments |> Array.contains "lfs" - && request.Arguments |> Array.contains "pull" - then return OperationResult.succeeded { NodeProcess.ExitCode = 1 @@ -5897,56 +6141,29 @@ Vitest.describe ( let! root, workPath, barePath, session = createSyncFixture hooks try - let! _ = - runGitIn - workPath - [| - "config" - "--local" - "versioncontrolservice.lfs.materializelargeobjects" - "true" - |] - + lockPath <- join [| workPath; ".git"; "index.lock" |] + let! _ = setMaterializeLargeObjects workPath true do! advanceTarget root barePath [ "target-lfs.bin", "target content\n" ] let! status = sessionStatus session let! updateResult = (syncService session).Update { ExpectedWorkspaceVersion = status.WorkspaceVersion } - (ctx "lfs-update-hydration") + (ctx "lfs-update-with-lock") |> Async.StartAsPromise match updateResult with - | PartiallySucceeded(outcome, failure) -> + | PartiallySucceeded(_, failure) -> Vitest.expect(failure.Category).toEqual Authentication Vitest.expect(failure.Code).toBe "hydration_failed" - Vitest.expect(failure.StateChanged).toBe true Vitest.expect(failure.AffectedPaths).toContain "target-lfs.bin" + // The fetch takes no lock, so a lock next to its failure proves nothing. Vitest.expect(failure.RecoveryAction |> Option.map _.Code).toEqual (Some "retry_materialization") - Vitest.expect(outcome.AffectedPaths).toContain "target-lfs.bin" - | Failed failure -> - failwith $"Expected partial hydration result, received {failure.Code}." - | Succeeded _ -> failwith "Expected explicit hydration failure after the successful Git update." - - let mergeRequest = - observed - |> Seq.find (fun request -> request.Arguments |> Array.contains "merge") - - Vitest - .expect(mergeRequest.Environment |> Array.contains ("GIT_LFS_SKIP_SMUDGE", "1")) - .toBe true - - let hydrationIndex = - observed - |> Seq.findIndex (fun request -> - request.Arguments |> Array.contains "lfs" - && request.Arguments |> Array.contains "pull") - - let mergeIndex = - observed - |> Seq.findIndex (fun request -> request.Arguments |> Array.contains "merge") + | Failed failure -> failwith $"Expected a partial result, received {failure.Code}." + | Succeeded _ -> failwith "Expected the failed download to be reported." - Vitest.expect(hydrationIndex > mergeIndex).toBe true + let! lockExists = pathExistsAsync lockPath + Vitest.expect(lockExists).toBe true do! removeDirectoryAsync root with error -> do! removeDirectoryAsync root @@ -5955,37 +6172,32 @@ Vitest.describe ( ) Vitest.test ( - "clone skips implicit smudge before explicit authenticated hydration", + "a checkout that fails while an index.lock exists recommends removing the lock and leaves it in place", TestOptions(timeout = 120000), fun () -> promise { - let observed = ResizeArray() - let cloneUrl = "https://git.local.test/origin.git" - let cloneSecret = "clone-token-123" - let mutable cloneSource = "" + let mutable lockPath = "" + let mutable checkoutRuns = 0 let hooks: GitWorkspaceSession.GitSessionHooks = { RunBytesProcess = None RunProcess = Some(fun request processContext -> async { - observed.Add request - - if request.Arguments |> Array.contains "clone" then - let cloneArguments = - request.Arguments - |> Array.map (fun argument -> - if argument = cloneUrl then cloneSource else argument) + if isLfsCheckoutRequest request then + checkoutRuns <- checkoutRuns + 1 + do! writeUtf8FileAsync lockPath "held by another process\n" |> Async.AwaitPromise - return! NodeProcess.run { request with Arguments = cloneArguments } processContext - elif - request.Arguments |> Array.contains "lfs" - && request.Arguments |> Array.contains "pull" - then + // The first checkout names the lock in Git's words. The second one fails + // without naming it, so only the lock file shows the cause. return OperationResult.succeeded { - NodeProcess.ExitCode = 1 + NodeProcess.ExitCode = 128 StdOut = "" - StdErr = "injected clone hydration failure" + StdErr = + if checkoutRuns = 1 then + $"fatal: Unable to create '{lockPath}': File exists." + else + "fatal: the checkout stopped" } else return! NodeProcess.run request processContext @@ -5993,63 +6205,417 @@ Vitest.describe ( Barrier = None } - let! root, _, barePath, _ = createSyncFixture hooks - let clonePath = join [| root; "hydrated-clone" |] - cloneSource <- barePath - let credential: GitCredentialStrategy.GitCredential = { - Username = "oauth2" - Secret = cloneSecret - } - - let credentials: GitCredentialStrategy.GitCredentialStrategy = { - ResolveCredential = - fun host _profileId -> - async { - if host = "git.local.test" then - return Some credential - else - return None - } - } + let! root, workPath, session = createUnhydratedLfsClone hooks try - let factory = GitWorkspaceSession.createFactoryWithCredentials hooks credentials + lockPath <- join [| workPath; ".git"; "index.lock" |] + let! _ = setMaterializeLargeObjects workPath true - let! cloneResult = - factory.Clone - { - Location = { - ProviderId = gitProviderId - DisplayName = None - ProviderLocation = cloneUrl - ConnectionProfileId = None - } - TargetPath = clonePath - TargetRef = None - MaterializeAllObjects = true - } - (ctx "lfs-clone-hydration") - |> Async.StartAsPromise + for attempt in 1..2 do + // The stand-in checkout leaves the lock behind, and the next update starts without it. + do! removePathAsync lockPath + let! status = sessionStatus session - match cloneResult with - | PartiallySucceeded(_, failure) -> - Vitest.expect(failure.Code).toBe "hydration_failed" - Vitest.expect(failure.RecoveryAction |> Option.map _.Code).toEqual (Some "retry_materialization") - | _ -> failwith "Expected clone hydration failure to preserve the successful clone as partial success." + let! updateResult = + (syncService session).Update + { ExpectedWorkspaceVersion = status.WorkspaceVersion } + (ctx $"lfs-checkout-with-lock-{attempt}") + |> Async.StartAsPromise - let cloneRequest = - observed - |> Seq.find (fun request -> request.Arguments |> Array.contains "clone") + match updateResult with + | PartiallySucceeded(_, failure) -> + Vitest.expect(failure.Code).toBe "hydration_failed" + Vitest.expect(failure.RecoveryAction |> Option.map _.Code).toEqual (Some "remove_index_lock") + | Failed failure -> failwith $"Expected a partial result, received {failure.Code}." + | Succeeded _ -> failwith "Expected the failed checkout to be reported." - Vitest - .expect(cloneRequest.Environment |> Array.contains ("GIT_LFS_SKIP_SMUDGE", "1")) - .toBe true + let! lockExists = pathExistsAsync lockPath + Vitest.expect(lockExists).toBe true - let hydrationRequest = - observed - |> Seq.find (fun request -> - request.Arguments |> Array.contains "lfs" - && request.Arguments |> Array.contains "pull") + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "a checkout that ends with success but could not update the index is a failed hydration with the lock recovery", + TestOptions(timeout = 120000), + fun () -> promise { + let mutable lockPath = "" + + let hooks: GitWorkspaceSession.GitSessionHooks = { + RunBytesProcess = None + RunProcess = + Some(fun request processContext -> + async { + if isLfsCheckoutRequest request then + do! writeUtf8FileAsync lockPath "held by another process\n" |> Async.AwaitPromise + + // git-lfs 3.7.0 prints this to stderr when the lock is held, and exits with 0. + // The text does not name the lock, so only the lock file shows the cause. + return + OperationResult.succeeded { + NodeProcess.ExitCode = 0 + StdOut = "" + StdErr = "Error updating the Git index:\n\n\nErrors logged to 'x.log'." + } + else + return! NodeProcess.run request processContext + }) + Barrier = None + } + + let! root, workPath, session = createUnhydratedLfsClone hooks + + try + lockPath <- join [| workPath; ".git"; "index.lock" |] + let! _ = setMaterializeLargeObjects workPath true + let! status = sessionStatus session + + let! updateResult = + (syncService session).Update + { ExpectedWorkspaceVersion = status.WorkspaceVersion } + (ctx "lfs-checkout-index-error-exit-0") + |> Async.StartAsPromise + + match updateResult with + | PartiallySucceeded(_, failure) -> + Vitest.expect(failure.Code).toBe "hydration_failed" + Vitest.expect(failure.Message.Contains "Error updating the Git index").toBe true + Vitest.expect(failure.RecoveryAction |> Option.map _.Code).toEqual (Some "remove_index_lock") + | Failed failure -> failwith $"Expected a partial result, received {failure.Code}." + | Succeeded _ -> failwith "Expected the checkout that could not update the index to be reported." + + let! lockExists = pathExistsAsync lockPath + Vitest.expect(lockExists).toBe true + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "a checkout that fails after a failed fetch keeps the fetch failure and adds its own text to the details", + TestOptions(timeout = 120000), + fun () -> promise { + let observed = ResizeArray() + + let hooks: GitWorkspaceSession.GitSessionHooks = { + RunBytesProcess = None + RunProcess = + Some(fun request processContext -> + async { + observed.Add request + + if isLfsFetchRequest request then + return + OperationResult.succeeded { + NodeProcess.ExitCode = 1 + StdOut = "" + StdErr = "HTTP 401 Unauthorized during LFS hydration" + } + elif isLfsCheckoutRequest request then + return + OperationResult.succeeded { + NodeProcess.ExitCode = 2 + StdOut = "" + StdErr = "the working tree refused the checkout" + } + else + return! NodeProcess.run request processContext + }) + Barrier = None + } + + let! root, workPath, session = createUnhydratedLfsClone hooks + + try + let! _ = setMaterializeLargeObjects workPath true + let! status = sessionStatus session + + let! updateResult = + (syncService session).Update + { ExpectedWorkspaceVersion = status.WorkspaceVersion } + (ctx "lfs-failed-fetch-failed-checkout") + |> Async.StartAsPromise + + match updateResult with + | PartiallySucceeded(_, failure) -> + Vitest.expect(failure.Category).toEqual Authentication + Vitest.expect(failure.Message.Contains "the working tree refused the checkout").toBe false + + Vitest.expect( + failure.Details |> Array.exists (fun line -> line.Contains "the working tree refused the checkout") + ) + .toBe true + | Failed failure -> failwith $"Expected a partial result, received {failure.Code}." + | Succeeded _ -> failwith "Expected the failed download to be reported." + + Vitest.expect(observed |> Seq.exists isLfsCheckoutRequest).toBe true + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "synchronization without anything to merge leaves pointers when the setting is off", + TestOptions(timeout = 120000), + fun () -> promise { + let observed = ResizeArray() + + let hooks: GitWorkspaceSession.GitSessionHooks = { + RunBytesProcess = None + RunProcess = + Some(fun request processContext -> + observed.Add request + NodeProcess.run request processContext) + Barrier = None + } + + let! root, workPath, session = createUnhydratedLfsClone hooks + + try + let! _ = setMaterializeLargeObjects workPath false + let! result = synchronizeWithoutPublish session "lfs-up-to-date-setting-off" + expectSucceeded "synchronize with the setting off" result |> ignore + + Vitest + .expect(observed |> Seq.exists (fun request -> isLfsFetchRequest request || isLfsCheckoutRequest request)) + .toBe false + let! content = tryReadUtf8FileAsync (join [| workPath; "large.bin" |]) + Vitest.expect((content = Some unhydratedLfsContent)).toBe false + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "update without anything to merge reports a failed download as partial success", + TestOptions(timeout = 120000), + fun () -> promise { + let hooks: GitWorkspaceSession.GitSessionHooks = { + RunBytesProcess = None + RunProcess = + Some(fun request processContext -> + async { + if isLfsFetchRequest request then + return + OperationResult.succeeded { + NodeProcess.ExitCode = 1 + StdOut = "" + StdErr = "HTTP 401 Unauthorized during LFS hydration" + } + else + return! NodeProcess.run request processContext + }) + Barrier = None + } + + let! root, workPath, session = createUnhydratedLfsClone hooks + + try + let! _ = setMaterializeLargeObjects workPath true + let! status = sessionStatus session + + let! updateResult = + (syncService session).Update + { ExpectedWorkspaceVersion = status.WorkspaceVersion } + (ctx "lfs-up-to-date-update") + |> Async.StartAsPromise + + match updateResult with + | PartiallySucceeded(_, failure) -> + Vitest.expect(failure.Category).toEqual Authentication + Vitest.expect(failure.Code).toBe "hydration_failed" + Vitest.expect(failure.RecoveryAction |> Option.map _.Code).toEqual (Some "retry_materialization") + | Failed failure -> failwith $"Expected partial download result, received {failure.Code}." + | Succeeded _ -> failwith "Expected the failed download to be reported." + + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "update skips implicit smudge and reports failed explicit hydration as partial success", + TestOptions(timeout = 120000), + fun () -> promise { + let observed = ResizeArray() + + let hooks: GitWorkspaceSession.GitSessionHooks = { + RunBytesProcess = None + RunProcess = + Some(fun request processContext -> + async { + observed.Add request + + if isLfsFetchRequest request then + return + OperationResult.succeeded { + NodeProcess.ExitCode = 1 + StdOut = "" + StdErr = "HTTP 401 Unauthorized during LFS hydration" + } + else + return! NodeProcess.run request processContext + }) + Barrier = None + } + + let! root, workPath, barePath, session = createSyncFixture hooks + + try + let! _ = + runGitIn + workPath + [| + "config" + "--local" + "versioncontrolservice.lfs.materializelargeobjects" + "true" + |] + + do! advanceTarget root barePath [ "target-lfs.bin", "target content\n" ] + let! status = sessionStatus session + + let! updateResult = + (syncService session).Update + { ExpectedWorkspaceVersion = status.WorkspaceVersion } + (ctx "lfs-update-hydration") + |> Async.StartAsPromise + + match updateResult with + | PartiallySucceeded(outcome, failure) -> + Vitest.expect(failure.Category).toEqual Authentication + Vitest.expect(failure.Code).toBe "hydration_failed" + Vitest.expect(failure.StateChanged).toBe true + Vitest.expect(failure.AffectedPaths).toContain "target-lfs.bin" + Vitest.expect(failure.RecoveryAction |> Option.map _.Code).toEqual (Some "retry_materialization") + Vitest.expect(outcome.AffectedPaths).toContain "target-lfs.bin" + | Failed failure -> + failwith $"Expected partial hydration result, received {failure.Code}." + | Succeeded _ -> failwith "Expected explicit hydration failure after the successful Git update." + + let mergeRequest = + observed + |> Seq.find (fun request -> request.Arguments |> Array.contains "merge") + + Vitest + .expect(mergeRequest.Environment |> Array.contains ("GIT_LFS_SKIP_SMUDGE", "1")) + .toBe true + + let hydrationIndex = observed |> Seq.findIndex isLfsFetchRequest + + let mergeIndex = + observed + |> Seq.findIndex (fun request -> request.Arguments |> Array.contains "merge") + + Vitest.expect(hydrationIndex > mergeIndex).toBe true + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "clone skips implicit smudge before explicit authenticated hydration", + TestOptions(timeout = 120000), + fun () -> promise { + let observed = ResizeArray() + let cloneUrl = "https://git.local.test/origin.git" + let cloneSecret = "clone-token-123" + let mutable cloneSource = "" + + let hooks: GitWorkspaceSession.GitSessionHooks = { + RunBytesProcess = None + RunProcess = + Some(fun request processContext -> + async { + observed.Add request + + if request.Arguments |> Array.contains "clone" then + let cloneArguments = + request.Arguments + |> Array.map (fun argument -> + if argument = cloneUrl then cloneSource else argument) + + return! NodeProcess.run { request with Arguments = cloneArguments } processContext + elif isLfsFetchRequest request then + return + OperationResult.succeeded { + NodeProcess.ExitCode = 1 + StdOut = "" + StdErr = "injected clone hydration failure" + } + else + return! NodeProcess.run request processContext + }) + Barrier = None + } + + let! root, _, barePath, _ = createSyncFixture hooks + let clonePath = join [| root; "hydrated-clone" |] + cloneSource <- barePath + let credential: GitCredentialStrategy.GitCredential = { + Username = "oauth2" + Secret = cloneSecret + } + + let credentials: GitCredentialStrategy.GitCredentialStrategy = { + ResolveCredential = + fun host _profileId -> + async { + if host = "git.local.test" then + return Some credential + else + return None + } + } + + try + let factory = GitWorkspaceSession.createFactoryWithCredentials hooks credentials + + let! cloneResult = + factory.Clone + { + Location = { + ProviderId = gitProviderId + DisplayName = None + ProviderLocation = cloneUrl + ConnectionProfileId = None + } + TargetPath = clonePath + TargetRef = None + MaterializeAllObjects = true + } + (ctx "lfs-clone-hydration") + |> Async.StartAsPromise + + match cloneResult with + | PartiallySucceeded(_, failure) -> + Vitest.expect(failure.Code).toBe "hydration_failed" + Vitest.expect(failure.RecoveryAction |> Option.map _.Code).toEqual (Some "retry_materialization") + | _ -> failwith "Expected clone hydration failure to preserve the successful clone as partial success." + + let cloneRequest = + observed + |> Seq.find (fun request -> request.Arguments |> Array.contains "clone") + + Vitest + .expect(cloneRequest.Environment |> Array.contains ("GIT_LFS_SKIP_SMUDGE", "1")) + .toBe true + + let hydrationRequest = observed |> Seq.find isLfsFetchRequest let expectedLfsUrl = $"lfs.url=https://{credential.Username}:{credential.Secret}@git.local.test/origin.git/info/lfs" @@ -6072,6 +6638,203 @@ Vitest.describe ( } ) + Vitest.test ( + "synchronize hydration checks out the files whose objects arrived when the server lost another one", + TestOptions(timeout = 120000), + fun () -> promise { + let! root, workPath, session = + createUnhydratedLfsCloneOf + [ "a.bin", "payload one\n"; "b.bin", "payload two\n" ] + [ "b.bin" ] + GitWorkspaceSession.GitSessionHooks.none + + try + let! _ = setMaterializeLargeObjects workPath true + let! result = synchronizeWithoutPublish session "lfs-hydration-lost-object" + + match result with + | PartiallySucceeded(_, failure) -> + Vitest.expect(failure.Code).toBe "hydration_failed" + Vitest.expect(failure.RecoveryAction |> Option.map _.Code).toEqual (Some "retry_materialization") + | Failed failure -> failwith $"Expected a partial result, received {failure.Code}." + | Succeeded _ -> failwith "Expected the lost object to be reported." + + let! available = tryReadUtf8FileAsync (join [| workPath; "a.bin" |]) + let! lost = tryReadUtf8FileAsync (join [| workPath; "b.bin" |]) + Vitest.expect(available).toEqual (Some "payload one\n") + Vitest.expect(lost.IsSome && lost.Value.StartsWith "version https://git-lfs.github.com/spec/v1").toBe true + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "clone hydration checks out the files whose objects arrived when the server lost another one", + TestOptions(timeout = 120000), + fun () -> promise { + let! root = createLfsOrigin [ "a.bin", "payload one\n"; "b.bin", "payload two\n" ] [ "b.bin" ] + let clonePath = join [| root; "hydrated-clone" |] + let factory = GitWorkspaceSession.createFactory GitWorkspaceSession.GitSessionHooks.none + + try + let! cloneResult = + factory.Clone + { + Location = { + ProviderId = gitProviderId + DisplayName = None + ProviderLocation = join [| root; "origin.git" |] + ConnectionProfileId = None + } + TargetPath = clonePath + TargetRef = None + MaterializeAllObjects = true + } + (ctx "lfs-clone-lost-object") + |> Async.StartAsPromise + + match cloneResult with + | PartiallySucceeded(_, failure) -> + Vitest.expect(failure.Code).toBe "hydration_failed" + Vitest.expect(failure.RecoveryAction |> Option.map _.Code).toEqual (Some "retry_materialization") + | Failed failure -> failwith $"Expected a partial result, received {failure.Code}." + | Succeeded _ -> failwith "Expected the lost object to be reported." + + let! available = tryReadUtf8FileAsync (join [| clonePath; "a.bin" |]) + let! lost = tryReadUtf8FileAsync (join [| clonePath; "b.bin" |]) + Vitest.expect(available).toEqual (Some "payload one\n") + Vitest.expect(lost.IsSome && lost.Value.StartsWith "version https://git-lfs.github.com/spec/v1").toBe true + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "a cancel right after the fetch of a synchronize skips the checkout and keeps the retry", + TestOptions(timeout = 120000), + fun () -> promise { + let observed = ResizeArray() + let source = OperationCancellation.Source() + + let hooks: GitWorkspaceSession.GitSessionHooks = { + RunBytesProcess = None + RunProcess = + Some(fun request processContext -> + async { + observed.Add request + + if isLfsFetchRequest request then + // The fetch ends well, and the cancel arrives before the checkout can start. + source.Cancel() + + return + OperationResult.succeeded { + NodeProcess.ExitCode = 0 + StdOut = "" + StdErr = "" + } + else + return! NodeProcess.run request processContext + }) + Barrier = None + } + + let! root, workPath, session = createUnhydratedLfsClone hooks + + try + let! _ = setMaterializeLargeObjects workPath true + + let! result = + synchronizeWithoutPublishIn + session + (OperationContext.create "lfs-cancel-after-fetch" source.Cancellation ignore) + + match result with + | PartiallySucceeded(_, failure) -> + Vitest.expect(failure.Category).toEqual Canceled + Vitest.expect(failure.Code).toBe "hydration_failed" + Vitest.expect(failure.RecoveryAction |> Option.map _.Code).toEqual (Some "retry_materialization") + | Failed failure -> failwith $"Expected a partial result, received {failure.Code}." + | Succeeded _ -> failwith "Expected the canceled download to be reported." + + Vitest.expect(observed |> Seq.exists isLfsCheckoutRequest).toBe false + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "a cancel right after the fetch of a clone skips the checkout and removes the clone", + TestOptions(timeout = 120000), + fun () -> promise { + let observed = ResizeArray() + let source = OperationCancellation.Source() + + let hooks: GitWorkspaceSession.GitSessionHooks = { + RunBytesProcess = None + RunProcess = + Some(fun request processContext -> + async { + observed.Add request + + if isLfsFetchRequest request then + source.Cancel() + + return + OperationResult.succeeded { + NodeProcess.ExitCode = 0 + StdOut = "" + StdErr = "" + } + else + return! NodeProcess.run request processContext + }) + Barrier = None + } + + let! root = createLfsOrigin [ "a.bin", "payload one\n" ] [] + let clonePath = join [| root; "canceled-clone" |] + + try + let factory = GitWorkspaceSession.createFactory hooks + + let! cloneResult = + factory.Clone + { + Location = { + ProviderId = gitProviderId + DisplayName = None + ProviderLocation = join [| root; "origin.git" |] + ConnectionProfileId = None + } + TargetPath = clonePath + TargetRef = None + MaterializeAllObjects = true + } + (OperationContext.create "lfs-clone-cancel-after-fetch" source.Cancellation ignore) + |> Async.StartAsPromise + + match cloneResult with + | Failed failure -> Vitest.expect(failure.Category).toEqual Canceled + | PartiallySucceeded(_, failure) -> failwith $"Expected a failure, received a partial {failure.Code}." + | Succeeded _ -> failwith "Expected the canceled clone to fail." + + Vitest.expect(observed |> Seq.exists isLfsCheckoutRequest).toBe false + let! cloneExists = pathExistsAsync clonePath + Vitest.expect(cloneExists).toBe false + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + Vitest.test ( "publish uploads selected-ref LFS objects before a hook-disabled ref push", TestOptions(timeout = 120000), @@ -6255,6 +7018,231 @@ Vitest.describe ( ) ) +Vitest.describe ( + "Git transfer progress", + fun () -> + Vitest.test ( + "hydration fetch and checkout read stdout meters under their own phase codes with Git LFS progress forced", + TestOptions(timeout = 120000), + fun () -> promise { + let observed = ResizeArray() + + let meterScript (label: string) = + "process.stdout.write('" + label + ": 50% (1/2), 1 B | 1 B/s\\r" + + label + ": 100% (2/2), 2 B | 1 B/s, done.\\n');" + + let hooks: GitWorkspaceSession.GitSessionHooks = { + RunBytesProcess = None + RunProcess = + Some(fun request processContext -> + observed.Add request + + // The request keeps its phase code and its stdout opt-in. Only the program changes. + if isLfsFetchRequest request then + NodeProcess.run + { request with + Command = nodeExecutablePath + Arguments = [| "-e"; meterScript "Downloading LFS objects" |] } + processContext + elif isLfsCheckoutRequest request then + NodeProcess.run + { request with + Command = nodeExecutablePath + Arguments = [| "-e"; meterScript "Checking out LFS objects" |] } + processContext + else + NodeProcess.run request processContext) + Barrier = None + } + + let! root, workPath, session = createUnhydratedLfsClone hooks + + try + let! _ = setMaterializeLargeObjects workPath true + let reports = ResizeArray() + + let! result = + synchronizeWithoutPublishIn + session + (OperationContext.create "lfs-hydration-meters" OperationCancellation.none reports.Add) + + expectSucceeded "synchronize with a metered hydration" result |> ignore + + for request in [| observed |> Seq.find isLfsFetchRequest; observed |> Seq.find isLfsCheckoutRequest |] do + Vitest.expect(request.Environment |> Array.contains ("GIT_LFS_FORCE_PROGRESS", "1")).toBe true + Vitest.expect(request.ObserveStdoutProgress).toBe true + + let metersOf (phaseCode: string) = + reports + |> Seq.filter (fun report -> report.PhaseCode = phaseCode && report.Completed.IsSome) + |> Seq.map (fun report -> report.Completed) + |> Seq.toArray + + Vitest.expect(metersOf "lfs-pull").toEqual [| Some 50.0; Some 100.0 |] + Vitest.expect(metersOf "lfs-pull-checkout").toEqual [| Some 50.0; Some 100.0 |] + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "fetch and clone ask git for progress", + TestOptions(timeout = 120000), + fun () -> promise { + let observed = ResizeArray() + + let hooks: GitWorkspaceSession.GitSessionHooks = { + RunBytesProcess = None + RunProcess = + Some(fun request processContext -> + observed.Add request + NodeProcess.run request processContext) + Barrier = None + } + + let! root, _, barePath, session = createSyncFixture hooks + + try + let! refreshResult = (syncService session).Refresh(ctx "progress-refresh") |> Async.StartAsPromise + expectValue "refresh" refreshResult |> ignore + + let fetchRequest = + observed |> Seq.find (fun request -> gitSubcommand request.Arguments = Some "fetch") + + Vitest.expect(fetchRequest.Arguments |> Array.contains "--progress").toBe true + + let factory = GitWorkspaceSession.createFactory hooks + let reports = ResizeArray() + + let! cloneResult = + factory.Clone + { + Location = { + ProviderId = gitProviderId + DisplayName = None + ProviderLocation = barePath + ConnectionProfileId = None + } + TargetPath = join [| root; "progress-clone" |] + TargetRef = None + MaterializeAllObjects = true + } + (OperationContext.create "progress-clone" OperationCancellation.none reports.Add) + |> Async.StartAsPromise + + expectValue "clone" cloneResult |> ignore + + let cloneRequest = + observed |> Seq.find (fun request -> gitSubcommand request.Arguments = Some "clone") + + Vitest.expect(cloneRequest.Arguments |> Array.contains "--progress").toBe true + + // The clone announces each step before it runs, with a message and without numbers. + let firstReportOf (phaseCode: string) = + reports |> Seq.findIndex (fun report -> report.PhaseCode = phaseCode) + + for phaseCode in [| "clone"; "clone-lfs-pull" |] do + let first = reports[firstReportOf phaseCode] + Vitest.expect(first.Completed).toEqual None + Vitest.expect(first.Total).toEqual None + Vitest.expect(first.DisplayMessage.IsSome).toBe true + + Vitest.expect(firstReportOf "clone" < firstReportOf "clone-lfs-pull").toBe true + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "a failing fetch whose stderr holds meter lines reports a failure message without them", + TestOptions(timeout = 120000), + fun () -> promise { + let hooks: GitWorkspaceSession.GitSessionHooks = { + RunBytesProcess = None + RunProcess = + Some(fun request processContext -> + if gitSubcommand request.Arguments = Some "fetch" then + async { + return + OperationResult.succeeded { + NodeProcess.ExitCode = 128 + StdOut = "" + StdErr = + "Receiving objects: 10% (1/10)\rReceiving objects: 100% (10/10), done.\n" + + "fatal: injected fetch failure\n" + } + } + else + NodeProcess.run request processContext) + Barrier = None + } + + let! root, _, _, session = createSyncFixture hooks + + try + let! refreshResult = (syncService session).Refresh(ctx "progress-failed-fetch") |> Async.StartAsPromise + let failure = expectProviderFailure "refresh" refreshResult + + Vitest.expect(failure.Message.Contains "fatal: injected fetch failure").toBe true + Vitest.expect(failure.Message.Contains "Receiving objects").toBe false + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "synchronize reports its step events in order for an update that downloads large objects", + TestOptions(timeout = 120000), + fun () -> promise { + let! root, workPath, barePath, session = createSyncFixture GitWorkspaceSession.GitSessionHooks.none + + try + let! _ = setMaterializeLargeObjects workPath true + do! advanceTarget root barePath [ "target.txt", "target content\n" ] + let reports = ResizeArray() + + let! result = + synchronizeWithoutPublishIn + session + (OperationContext.create "step-events" OperationCancellation.none reports.Add) + + match result with + | Failed failure -> failwith $"Synchronize failed ({failure.Code}): {failure.Message}" + | Succeeded _ + | PartiallySucceeded _ -> () + + let steps = + [| "fetch"; "refresh-state"; "merge"; "update-inspection"; "lfs-pull"; "lfs-pull-checkout" |] + + let reportedSteps = + reports + |> Seq.map (fun report -> report.PhaseCode) + |> Seq.filter (fun code -> Array.contains code steps) + |> Seq.distinct + |> Seq.toArray + + Vitest.expect(reportedSteps).toEqual steps + + for code in [| "fetch"; "merge"; "lfs-pull"; "lfs-pull-checkout" |] do + let first = reports |> Seq.find (fun report -> report.PhaseCode = code) + Vitest.expect(first.Completed).toEqual None + Vitest.expect(first.Total).toEqual None + Vitest.expect(first.DisplayMessage.IsSome).toBe true + + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) +) + Vitest.describe ( "Git synchronize composition", fun () -> @@ -7645,3 +8633,204 @@ Vitest.describe ( } ) ) + +let private outputContext (name: string) (batches: ResizeArray) = + OperationContext.createWithOutput name OperationCancellation.none ignore batches.Add + +let private outputEntries (batches: ResizeArray) = + batches |> Seq.collect id |> Seq.toArray + +Vitest.describe ( + "Git output channel", + fun () -> + Vitest.test ( + "synchronize reports the header and the stderr lines of its fetch", + TestOptions(timeout = 120000), + fun () -> promise { + let! root, _, barePath, session = createSyncFixture GitWorkspaceSession.GitSessionHooks.none + + try + do! advanceTarget root barePath [ "target.txt", "target content\n" ] + let batches = ResizeArray() + + let! result = synchronizeWithoutPublishIn session (outputContext "output-fetch" batches) + expectSucceeded "synchronize with output" result |> ignore + + let entries = outputEntries batches + + let fetchHeader = + entries + |> Array.tryFind (fun entry -> + entry.Kind = OperationOutputKind.Command && entry.Text = "git fetch --progress origin") + + Vitest.expect(fetchHeader.IsSome).toBe true + + // The ref update line is what git prints to stderr when the fetch brings something new. + let fetchLines = + entries + |> Array.filter (fun entry -> + entry.CommandId = fetchHeader.Value.CommandId + && entry.Kind = OperationOutputKind.StdErr) + + Vitest.expect(fetchLines |> Array.exists (fun entry -> entry.Text.Contains "origin/main")).toBe true + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "hydration reports the stdout of lfs fetch and lfs checkout", + TestOptions(timeout = 120000), + fun () -> promise { + let meterScript (label: string) = + "process.stdout.write('" + label + ": 50% (1/2), 1 B | 1 B/s\\r" + + label + ": 100% (2/2), 2 B | 1 B/s, done.\\n');" + + let hooks: GitWorkspaceSession.GitSessionHooks = { + RunBytesProcess = None + RunProcess = + Some(fun request processContext -> + if isLfsFetchRequest request then + NodeProcess.run + { request with + Command = nodeExecutablePath + Arguments = [| "-e"; meterScript "Downloading LFS objects" |] } + processContext + elif isLfsCheckoutRequest request then + NodeProcess.run + { request with + Command = nodeExecutablePath + Arguments = [| "-e"; meterScript "Checking out LFS objects" |] } + processContext + else + NodeProcess.run request processContext) + Barrier = None + } + + let! root, workPath, session = createUnhydratedLfsClone hooks + + try + let! _ = setMaterializeLargeObjects workPath true + let batches = ResizeArray() + + let! result = synchronizeWithoutPublishIn session (outputContext "output-hydration" batches) + expectSucceeded "synchronize with a metered hydration" result |> ignore + + let stdoutTexts = + outputEntries batches + |> Array.filter (fun entry -> entry.Kind = OperationOutputKind.StdOut && not entry.IsPartial) + |> Array.map (fun entry -> entry.Text) + + Vitest.expect(stdoutTexts).toEqual [| + "Downloading LFS objects: 100% (2/2), 2 B | 1 B/s, done." + "Checking out LFS objects: 100% (2/2), 2 B | 1 B/s, done." + |] + + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "the LFS listing reports its header and never its JSON stdout", + TestOptions(timeout = 120000), + fun () -> promise { + let! root, _, session = createUnhydratedLfsClone GitWorkspaceSession.GitSessionHooks.none + + try + let batches = ResizeArray() + + let materialization = + session.ObjectMaterialization + |> Option.defaultWith (fun () -> failwith "Expected Git object materialization.") + + let! listResult = + materialization.ListObjects(outputContext "output-listing" batches) + |> Async.StartAsPromise + + expectValue "listing" listResult |> ignore + let entries = outputEntries batches + + Vitest.expect( + entries + |> Array.exists (fun entry -> + entry.Kind = OperationOutputKind.Command && entry.Text = "git lfs ls-files -j") + ) + .toBe true + + Vitest.expect(entries |> Array.exists (fun entry -> entry.Kind = OperationOutputKind.StdOut)).toBe false + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) + + Vitest.test ( + "publish reports the header and the stdout of the explicit LFS upload", + TestOptions(timeout = 120000), + fun () -> promise { + let! root, workPath, _, session = createSyncFixture GitWorkspaceSession.GitSessionHooks.none + + try + do! + writeUtf8FileAsync + (join [| workPath; "publish-large.bin" |]) + (String.replicate (1024 * 1024) "p") + + let! saveStatus = sessionStatus session + + let! revisionResult = + session.Core.CreateRevision + { + Message = "test: publish explicit LFS object" + Paths = [| mkPath "publish-large.bin" |] + ExpectedWorkspaceVersion = saveStatus.WorkspaceVersion + } + (ctx "output-publish-revision") + |> Async.StartAsPromise + + expectValue "LFS revision" revisionResult |> ignore + let batches = ResizeArray() + let! publishStatus = sessionStatus session + + let! publishResult = + (syncService session).Publish + { + ExpectedWorkspaceVersion = publishStatus.WorkspaceVersion + ExpectedTargetRevision = None + } + (outputContext "output-publish" batches) + |> Async.StartAsPromise + + expectValue "publish" publishResult |> ignore + let entries = outputEntries batches + + let upload = + entries + |> Array.tryFind (fun entry -> + entry.Kind = OperationOutputKind.Command + && entry.Text = "git lfs push --object-id origin --stdin") + + Vitest.expect(upload.IsSome).toBe true + + Vitest.expect( + entries + |> Array.exists (fun entry -> + entry.CommandId = upload.Value.CommandId + && entry.Kind = OperationOutputKind.StdOut + && entry.Text.Contains "Uploading LFS objects") + ) + .toBe true + + do! removeDirectoryAsync root + with error -> + do! removeDirectoryAsync root + return raise error + } + ) +) diff --git a/tests/VersionControlService.Tests/LakeFsApi.test.fs b/tests/VersionControlService.Tests/LakeFsApi.test.fs index 5ce4941..840fcfa 100644 --- a/tests/VersionControlService.Tests/LakeFsApi.test.fs +++ b/tests/VersionControlService.Tests/LakeFsApi.test.fs @@ -698,3 +698,35 @@ Vitest.describe ( } ) ) + +Vitest.describe ( + "lakeFS output channel", + fun () -> + Vitest.test ( + "an operation whose context has an output callback reports no output", + TestOptions(timeout = 30000), + fun () -> promise { + let! server = + startFakeServer [ + "GET", "/api/v1/repositories/repo/branches/main", 200, """{"id":"main","commit_id":"c1"}""" + ] + + try + let batches = ResizeArray() + + let context = + OperationContext.createWithOutput "lakefs-output" OperationCancellation.none ignore batches.Add + + let! result = + Async.StartAsPromise(LakeFsApi.getBranch (connectionFor server) "repo" "main" context) + + match result with + | Ok branch -> Vitest.expect(branch.CommitId).toBe "c1" + | Error failure -> failwith $"Expected the branch lookup to succeed: {failure.Message}" + + Vitest.expect(batches.Count).toBe 0 + finally + server.Close() + } + ) +) diff --git a/tests/VersionControlService.Tests/NodeRuntime.test.fs b/tests/VersionControlService.Tests/NodeRuntime.test.fs index f876f09..1b14744 100644 --- a/tests/VersionControlService.Tests/NodeRuntime.test.fs +++ b/tests/VersionControlService.Tests/NodeRuntime.test.fs @@ -6,6 +6,7 @@ open VersionControlService.Abstractions open Vitest module NodeProcess = VersionControlService.Runtime.Node.Process +module NodeOutput = VersionControlService.Runtime.Node.OutputReporter module NodeInterop = VersionControlService.Runtime.Node.Interop module NodeBinaryIO = VersionControlService.Runtime.Node.BinaryIO module NodeFileSystem = VersionControlService.Runtime.Node.FileSystem @@ -236,6 +237,92 @@ Vitest.describe ( } ) + Vitest.test ( + "reports stdout meters under the request phase code when the request opts in", + TestOptions(timeout = 120000), + fun () -> promise { + let script = + "process.stdout.write('Downloading LFS objects: 50% (1/2), 1 B | 1 B/s\\r" + + "Downloading LFS objects: 100% (2/2), 2 B | 1 B/s, done.\\n');" + + let request = { + NodeProcess.ProcessRequest.create nodeExecutable [| "-e"; script |] with + ProgressPhase = "lfs-pull" + ObserveStdoutProgress = true + } + + let reports = ResizeArray() + let context = OperationContext.create "runtime-stdout-meters" OperationCancellation.none reports.Add + let! result = run (NodeProcess.run request context) + + match result with + | Succeeded outcome -> Vitest.expect(outcome.Value.ExitCode).toBe 0 + | PartiallySucceeded _ + | Failed _ -> failwith "Expected the process to succeed." + + Vitest.expect(reports |> Seq.map (fun report -> report.PhaseCode) |> Seq.toArray).toEqual [| + "lfs-pull" + "lfs-pull" + |] + + Vitest.expect(reports |> Seq.map (fun report -> report.Completed) |> Seq.toArray).toEqual [| + Some 50.0 + Some 100.0 + |] + } + ) + + Vitest.test ( + "does not parse stdout for meters unless the request opts in", + TestOptions(timeout = 120000), + fun () -> promise { + let script = + "process.stdout.write('Downloading LFS objects: 50% (1/2), 1 B | 1 B/s\\n');" + + let request = NodeProcess.ProcessRequest.create nodeExecutable [| "-e"; script |] + let reports = ResizeArray() + let context = OperationContext.create "runtime-stdout-plain" OperationCancellation.none reports.Add + let! result = run (NodeProcess.run request context) + + match result with + | Succeeded outcome -> Vitest.expect(outcome.Value.StdOut.Contains "Downloading LFS objects").toBe true + | PartiallySucceeded _ + | Failed _ -> failwith "Expected the process to succeed." + + Vitest.expect(reports.Count).toBe 0 + } + ) + + Vitest.test ( + "keeps a stdout meter whole when stderr output arrives in the middle of it", + TestOptions(timeout = 120000), + fun () -> promise { + // The pauses put each write into its own chunk, so the stderr line lands inside the stdout meter. + let script = + "process.stdout.write('Downloading LFS objects: 5');" + + "setTimeout(() => process.stderr.write('warning: slow link\\n'), 150);" + + "setTimeout(() => process.stdout.write('0% (1/3), 1 B | 1 B/s\\n'), 300);" + + let request = { + NodeProcess.ProcessRequest.create nodeExecutable [| "-e"; script |] with + ObserveStdoutProgress = true + } + + let reports = ResizeArray() + let context = OperationContext.create "runtime-split-meter" OperationCancellation.none reports.Add + let! result = run (NodeProcess.run request context) + + match result with + | Succeeded outcome -> Vitest.expect(outcome.Value.ExitCode).toBe 0 + | PartiallySucceeded _ + | Failed _ -> failwith "Expected the process to succeed." + + Vitest.expect(reports |> Seq.map (fun report -> report.DisplayMessage) |> Seq.toArray).toEqual [| + Some "Downloading LFS objects (1/3), 1 B" + |] + } + ) + Vitest.test ( "cancellation after child exit preserves success", TestOptions(timeout = 120000), @@ -683,3 +770,326 @@ Vitest.describe ( } ) ) + +/// A clock the test moves by hand. Timers run when the clock passes their time. +type private FakeTimer = { + At: float + Callback: unit -> unit + mutable Done: bool +} + +type private FakeClock() = + let mutable now = 0.0 + let timers = ResizeArray() + + member _.Clock: NodeOutput.OutputClock = { + Now = fun () -> now + Schedule = + fun delay callback -> + let timer = { + At = now + delay + Callback = callback + Done = false + } + + timers.Add timer + fun () -> timer.Done <- true + } + + member _.Advance(milliseconds: float) = + let target = now + milliseconds + let mutable running = true + + while running do + let due = + timers + |> Seq.filter (fun timer -> not timer.Done && timer.At <= target) + |> Seq.sortBy (fun timer -> timer.At) + |> Seq.tryHead + + match due with + | None -> running <- false + | Some timer -> + timer.Done <- true + now <- max now timer.At + timer.Callback() + + now <- target + +let private newOutputChannel (clock: FakeClock) = + let batches = ResizeArray() + NodeOutput.createChannel clock.Clock batches.Add, batches + +let private beginOutputCommand (channel: NodeOutput.OutputChannel) = + NodeOutput.beginCommand channel "git" [| "fetch" |] [| "fetch" |] [||] true + +let private allEntries (batches: ResizeArray) = batches |> Seq.collect id |> Seq.toArray + +let private stderrEntries (batches: ResizeArray) = + allEntries batches + |> Array.filter (fun entry -> entry.Kind = OperationOutputKind.StdErr) + +Vitest.describe ( + "Node runtime output channel", + fun () -> + Vitest.test ( + "a context has a channel only when its host set an output callback, and all copies share it", + fun () -> + Vitest.expect((NodeOutput.tryOf (OperationContext.detached "output-none")).IsNone).toBe true + + let context = + OperationContext.createWithOutput "output-shared" OperationCancellation.none ignore ignore + + let copy = { context with Cancellation = OperationCancellation.none } + let first = NodeOutput.tryOf context + let second = NodeOutput.tryOf copy + + Vitest.expect(first.IsSome && second.IsSome).toBe true + Vitest.expect(obj.ReferenceEquals(first.Value, second.Value)).toBe true + ) + + Vitest.test ( + "reads a CRLF split across two chunks as one newline", + fun () -> + let channel, batches = newOutputChannel (FakeClock()) + let command = beginOutputCommand channel + + command.ObserveStderr "abc\r" + command.ObserveStderr "\ndef\n" + channel.Flush() + + // A lone CR followed by text would have rewritten "abc". The CRLF completes it. + let lines = stderrEntries batches + Vitest.expect(lines |> Array.map (fun entry -> entry.Text)).toEqual [| "abc"; "def" |] + Vitest.expect(lines |> Array.exists (fun entry -> entry.IsPartial)).toBe false + ) + + Vitest.test ( + "collapses carriage return updates within 250 ms into one snapshot and the final state", + fun () -> + let clock = FakeClock() + let channel, batches = newOutputChannel clock + let command = beginOutputCommand channel + + command.ObserveStderr "Receiving objects: 10% (1/10)\r" + clock.Advance 100.0 + command.ObserveStderr "Receiving objects: 50% (5/10)\r" + clock.Advance 100.0 + command.ObserveStderr "Receiving objects: 100% (10/10), done.\n" + channel.Flush() + + let lines = stderrEntries batches + + Vitest.expect(lines |> Array.map (fun entry -> entry.Text)).toEqual [| + "Receiving objects: 10% (1/10)" + "Receiving objects: 100% (10/10), done." + |] + + Vitest.expect(lines |> Array.map (fun entry -> entry.IsPartial)).toEqual [| true; false |] + ) + + Vitest.test ( + "strips terminal escape sequences and control characters but keeps tabs", + fun () -> + let channel, batches = newOutputChannel (FakeClock()) + let command = beginOutputCommand channel + + command.ObserveStderr "\u001b[1;32mok\u001b[0m\tdone\u0001\u001b]0;title\u0007!\n" + channel.Flush() + + Vitest.expect(stderrEntries batches |> Array.map (fun entry -> entry.Text)).toEqual [| "ok\tdone!" |] + ) + + Vitest.test ( + "replaces a line over the length limit with a notice and keeps one at the limit", + fun () -> + let channel, batches = newOutputChannel (FakeClock()) + let command = beginOutputCommand channel + let atLimit = String.replicate NodeOutput.MaxLineLength "x" + + command.ObserveStderr(atLimit + "\n" + atLimit + "y\nafter\n") + channel.Flush() + + let entries = allEntries batches |> Array.filter (fun entry -> entry.Kind <> OperationOutputKind.Command) + + Vitest.expect(entries |> Array.map (fun entry -> entry.Kind = OperationOutputKind.Notice)).toEqual [| + false + true + false + |] + + Vitest.expect(entries[0].Text).toBe atLimit + Vitest.expect(entries[1].Text.Contains "longer than").toBe true + Vitest.expect(entries[2].Text).toBe "after" + ) + + Vitest.test ( + "drops the oldest entries when the queue is full and says how many", + fun () -> + let channel, batches = newOutputChannel (FakeClock()) + let command = beginOutputCommand channel + let lines = [ for number in 1..200 -> $"line {number}\n" ] |> String.concat "" + + // The clock stands still, so the header went out and nothing else did. + command.ObserveStderr lines + command.Finish() + + let entries = allEntries batches |> Array.filter (fun entry -> entry.Kind <> OperationOutputKind.Command) + let notice = entries[0] + let texts = entries |> Array.skip 1 |> Array.map (fun entry -> entry.Text) + + Vitest.expect(notice.Kind = OperationOutputKind.Notice).toBe true + Vitest.expect(notice.Text.Contains "72").toBe true + Vitest.expect(texts.Length).toBe NodeOutput.MaxQueuedEntries + Vitest.expect(texts[0]).toBe "line 73" + Vitest.expect(texts[texts.Length - 1]).toBe "line 200" + ) + + Vitest.test ( + "a full queue keeps its command headers, drops lines first and counts the lines", + fun () -> + let channel, batches = newOutputChannel (FakeClock()) + // The first header goes out at once and starts the rate limit, so the second one waits in the queue. + beginOutputCommand channel |> ignore + let command = beginOutputCommand channel + let lines = [ for number in 1..200 -> $"line {number}\n" ] |> String.concat "" + + command.ObserveStderr lines + command.Finish() + + let entries = allEntries batches + let notice = entries |> Array.find (fun entry -> entry.Kind = OperationOutputKind.Notice) + let texts = stderrEntries batches |> Array.map (fun entry -> entry.Text) + + let headers = entries |> Array.filter (fun entry -> entry.Kind = OperationOutputKind.Command) + + Vitest.expect(headers.Length).toBe 2 + Vitest.expect(notice.CommandId).toBe "" + Vitest.expect(notice.Text.Contains "73").toBe true + Vitest.expect(texts[0]).toBe "line 74" + Vitest.expect(texts[texts.Length - 1]).toBe "line 200" + ) + + Vitest.test ( + "publishes a snapshot that the 250 ms rule held back once the interval ends", + fun () -> + let clock = FakeClock() + let channel, batches = newOutputChannel clock + let command = beginOutputCommand channel + + command.ObserveStderr "Receiving objects: 10% (1/10)\r" + clock.Advance 100.0 + command.ObserveStderr "Receiving objects: 50% (5/10)\r" + clock.Advance 100.0 + + // No chunk arrives after the second one, and 200 ms since the first snapshot is too early. + Vitest.expect(stderrEntries batches |> Array.map (fun entry -> entry.Text)).toEqual [| + "Receiving objects: 10% (1/10)" + |] + + clock.Advance 50.0 + let lines = stderrEntries batches + + Vitest.expect(lines |> Array.map (fun entry -> entry.Text)).toEqual [| + "Receiving objects: 10% (1/10)" + "Receiving objects: 50% (5/10)" + |] + + Vitest.expect(lines |> Array.forall (fun entry -> entry.IsPartial)).toBe true + ) + + Vitest.test ( + "an overlong segment that ends with a carriage return leaves no earlier segment to complete", + fun () -> + let channel, batches = newOutputChannel (FakeClock()) + let command = beginOutputCommand channel + let tooLong = String.replicate (NodeOutput.MaxLineLength + 1) "x" + + command.ObserveStderr("Receiving objects: 10% (1/10)\r" + tooLong + "\r\n") + channel.Flush() + + let entries = allEntries batches |> Array.filter (fun entry -> entry.Kind <> OperationOutputKind.Command) + + Vitest.expect(entries |> Array.map (fun entry -> entry.Kind)).toEqual [| OperationOutputKind.Notice |] + ) + + Vitest.test ( + "an overlong line closes the partial entry that is still open", + fun () -> + let clock = FakeClock() + let channel, batches = newOutputChannel clock + let command = beginOutputCommand channel + let tooLong = String.replicate (NodeOutput.MaxLineLength + 1) "x" + + command.ObserveStderr "Receiving objects: 10% (1/10)\r" + clock.Advance 100.0 + command.ObserveStderr(tooLong + "\n") + channel.Flush() + + let lines = stderrEntries batches + + // The host replaces a partial entry only with an entry of the same command and kind. + Vitest.expect(lines |> Array.map (fun entry -> entry.Text, entry.IsPartial)).toEqual [| + "Receiving objects: 10% (1/10)", true + "Receiving objects: 10% (1/10)", false + |] + + Vitest.expect(allEntries batches |> Array.exists (fun entry -> entry.Kind = OperationOutputKind.Notice)).toBe true + ) + + Vitest.test ( + "delivers at most twenty entries per batch and ten batches per second", + fun () -> + let clock = FakeClock() + let channel, batches = newOutputChannel clock + let command = beginOutputCommand channel + let lines = [ for number in 1..60 -> $"line {number}\n" ] |> String.concat "" + + command.ObserveStderr lines + Vitest.expect(batches.Count).toBe 1 + clock.Advance 99.0 + Vitest.expect(batches.Count).toBe 1 + clock.Advance 1.0 + Vitest.expect(batches.Count).toBe 2 + clock.Advance 100.0 + Vitest.expect(batches.Count).toBe 3 + Vitest.expect(batches |> Seq.map (fun batch -> $"{batch.Length}") |> String.concat ",").toBe "1,20,20" + ) + + Vitest.test ( + "delivers the final output of a canceled process before the run completes", + TestOptions(timeout = 120000), + fun () -> promise { + // The text after the newline has no terminator, so only the final flush can deliver it. + let script = "process.stderr.write('line one\\ntail'); setInterval(() => {}, 1000);" + let request = NodeProcess.ProcessRequest.create nodeExecutable [| "-e"; script |] + let batches = ResizeArray() + let source = OperationCancellation.Source() + + let context = + OperationContext.createWithOutput "runtime-output-cancel" source.Cancellation ignore batches.Add + + let running = run (NodeProcess.run request context) + let attempts = ref 0 + + while not (allEntries batches |> Array.exists (fun entry -> entry.Text = "line one")) + && attempts.Value < 200 do + do! run (Async.Sleep 50) + attempts.Value <- attempts.Value + 1 + + source.Cancel() + let! result = running + + match result with + | Failed failure -> Vitest.expect(failure.Category).toEqual Canceled + | Succeeded _ + | PartiallySucceeded _ -> failwith "Expected the canceled process to fail." + + let tail = + stderrEntries batches + |> Array.tryFind (fun entry -> entry.Text = "tail") + + Vitest.expect(tail.IsSome && not tail.Value.IsPartial).toBe true + } + ) +)