From ea161d48b07b2a1f41dd28e05f7c12dfab305c60 Mon Sep 17 00:00:00 2001 From: fangfang qi Date: Fri, 4 Dec 2026 15:17:10 +0800 Subject: [PATCH 1/3] fix(fs): migrate ti companion integration to LayerFS v36 --- AGENTS.md | 31 +- README.md | 31 +- docs/release-notes/v0.2.12.md | 19 + docs/releasing.md | 2 +- e2e/cli_test.go | 107 ++--- e2e/installer_test.go | 6 +- e2e/live_layer_test.go | 335 ++------------- e2e/live_test.go | 77 +--- e2e/testdata/fake-drive9.go | 35 +- internal/api/fs/layer.go | 490 +--------------------- internal/api/fs/layer_test.go | 198 --------- internal/authz/authz.go | 6 +- internal/cli/commands.go | 313 ++++---------- internal/fs/data.go | 6 +- internal/fs/drive9_companion.go | 151 ++----- internal/fs/drive9_companion_test.go | 86 ++-- internal/fs/drive9_copy.go | 4 +- internal/fs/drive9_fake_companion_test.go | 23 +- internal/fs/drive9_mount_audit.go | 36 +- internal/fs/drive9_mount_audit_test.go | 38 ++ internal/fs/layer.go | 473 ++------------------- internal/fs/mount.go | 58 +-- internal/fs/mount_durability.go | 4 +- internal/fs/mount_durability_test.go | 43 -- internal/fs/mountlocator/locator.go | 9 +- internal/fs/mountroot.go | 11 + internal/output/command_contract_test.go | 8 +- internal/update/update.go | 10 +- internal/update/update_test.go | 25 +- scripts/install.ps1 | 8 +- scripts/install.sh | 10 +- 31 files changed, 513 insertions(+), 2140 deletions(-) create mode 100644 docs/release-notes/v0.2.12.md delete mode 100644 internal/api/fs/layer_test.go diff --git a/AGENTS.md b/AGENTS.md index 838f04aa..879dc174 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -79,7 +79,7 @@ Implemented: `docs/spec/done/0018-fs-token-auth-and-config-free-access.md` - Server-backed Filesystem token lifecycle management from `docs/spec/done/0030-file-system-token-lifecycle-management.md` -- Filesystem layer fork, ancestry, deletion, and historical mount workflows +- Historical filesystem layer workflows from `docs/spec/done/0032-filesystem-layer-fork-workflows.md` - install and update distribution from `docs/spec/done/0012-install-and-update-distribution.md` @@ -136,12 +136,9 @@ Implemented: - `ti fs create-layer` - `ti fs list-layers` - `ti fs fork-layer` -- `ti fs list-layer-chain` - `ti fs describe-layer` -- `ti fs diff-layer` -- `ti fs create-layer-checkpoint` - `ti fs delete-layer` -- `ti fs rollback-layer` +- `ti fs merge-layer` - `ti fs commit-layer` - `ti fs mount-file-system` - `ti fs drain-file-system` @@ -293,8 +290,8 @@ For ti fs data-plane and mount runtime, the live suite creates uniquely named remote paths, exercises real file create/read/list/copy/move/delete flows, range reads, append, resume, recursive local/remote copy, stdin/stdout copy, tags/descriptions, chmod, symlink, hardlink, pack/unpack, real public layer -create/list/describe/diff/checkpoint/rollback/commit flows, layer-aware -copy/find where Drive9 exposes it, vault create/read/replace/delete, delegated +create/list/describe/fork/delete/merge flows, layer-aware +copy where Drive9 exposes it, vault create/read/replace/delete, delegated vault grant reads, vault mount read on macOS/Linux hosts when available, journal create/append/read/search/verify, public Git clone/hydrate/worktree flows, mount and drain through the companion runtime, and explicit WebDAV @@ -629,20 +626,15 @@ Implemented command behavior: - `ti fs create-symlink --target README.md --link-path /workspace/README.link` - `ti fs create-hardlink --source-path /workspace/README.md --link-path /workspace/README.hard` - `ti fs search-file-content --path /workspace --pattern "hello"` -- `ti fs search-file-content --path /workspace --pattern "hello" --layer-id layer-1` - `ti fs find-files --path /workspace --file-name-pattern "*.md"` -- `ti fs find-files --path /workspace --file-name-pattern "*.md" --layer-id layer-1` -- `ti fs create-layer --layer-id layer-1 --base-root-path /workspace --layer-name task --durability-mode restore-safe --tag task=auth` +- `ti fs create-layer --base-root-path /workspace --layer-name task --ttl 1h --tag task=auth` - `ti fs list-layers` - `ti fs list-layers --output text` -- `ti fs fork-layer --parent-layer-ref layer-1 --layer-name child --checkpoint-id cp-1` -- `ti fs list-layer-chain --layer-ref child --output text` +- `ti fs fork-layer --parent-layer-ref layer-1 --layer-name child --ttl 30m` - `ti fs describe-layer --layer-id layer-1` -- `ti fs diff-layer --layer-id layer-1` - `ti fs copy-file --from-local ./README.md --to-remote /workspace/layered.md --layer-id layer-1` -- `ti fs create-layer-checkpoint --layer-id layer-1 --checkpoint-id cp-1 --label before-commit` - `ti fs delete-layer --layer-ref child` -- `ti fs rollback-layer --layer-id layer-1` +- `ti fs merge-layer --layer-id layer-1` - `ti fs commit-layer --layer-id layer-1` - `ti fs pack-file-system --local-root ~/.ti/local/fs/demo --remote-root /workspace --mount-profile portable` - `ti fs pack-file-system --mount-path ./workspace` @@ -656,7 +648,6 @@ Implemented command behavior: - `ti fs mount-file-system --file-system-id --mount-path ./workspace --driver fuse --cache-dir ~/.ti/cache/workspace --write-back-cache=false` - `ti fs mount-file-system --file-system-id --mount-path ./workspace --driver fuse --durability close-sync` - `ti fs mount-file-system --file-system-id --mount-path ./workspace --remote-path /workspace --driver fuse --layer-ref layer-1` -- `ti fs mount-file-system --file-system-id --mount-path ./workspace-v1 --remote-path /workspace --driver fuse --layer-ref layer-1 --checkpoint-id cp-1` - `ti fs drain-file-system --mount-path ./workspace` - `ti fs drain-file-system --mount-path ./workspace --timeout 30s` - `ti fs unmount-file-system --mount-path ./workspace` @@ -735,12 +726,9 @@ Registered command surface: - `ti fs create-layer` - `ti fs list-layers` - `ti fs fork-layer` -- `ti fs list-layer-chain` - `ti fs describe-layer` -- `ti fs diff-layer` -- `ti fs create-layer-checkpoint` - `ti fs delete-layer` -- `ti fs rollback-layer` +- `ti fs merge-layer` - `ti fs commit-layer` - `ti fs pack-file-system` - `ti fs unpack-file-system` @@ -1207,8 +1195,7 @@ ordinary mount keeps its documented behavior instead of following the engine's combination. FUSE mounts forward the tier, including `--driver auto` mounts on platforms whose automatic choice is FUSE; WebDAV mounts forward none and reject every explicit tier except `auto` with `fs.webdav_durability_unsupported`; -checkpoint mounts are read-only, force `auto`, and reject any other explicit -tier. Report the effective tier as `durability` in the mount result and do not +report the effective tier as `durability` in the mount result and do not reintroduce the removed `write_back_cache` boolean. Do not implement or expose ti commands for Drive9 internal APIs that are not diff --git a/README.md b/README.md index 823f54d8..70cf6c45 100644 --- a/README.md +++ b/README.md @@ -215,28 +215,22 @@ Use `ti update` or reinstall ti if the local capability check reports an incompa Mount readiness means the mounted path is readable: `ti fs mount-file-system` and `ti fs-vault mount-vault` keep polling the mount path until directory listing succeeds, bounded by `--ready-timeout` (default `30s`). If the mount path never becomes readable in time, the command fails with `fs.mount_ready_timeout`, the background mount is left running, and the mount locator is preserved so the matching unmount command can stop it. -When a mount unpacks a local overlay (auto-unpack with a non-`none` mount profile whose effective pack paths are non-empty — `portable` supplies `/` by default, and the companion's mount accepts no extra pack paths of its own — while `--no-auto-unpack` is not set, or an explicit `--unpack-archive-path`), it runs the same overlay symlink audit as `ti fs unpack-file-system`: ti resolves the local overlay before the companion runs, snapshots it, audits it after the mount becomes readable, and also when readiness times out, removes links that escape the overlay, stops the mount, and reports the error. The audited root is the companion's own default overlay root, so existing overlays keep their location; an explicit `--local-root` is passed through and audited as given. If the audit rejects the overlay or an unpack-capable mount never becomes ready, ti stops the mount instead of leaving it running (an exception to the usual timeout behavior, because unpack may still be completing). If the mount cannot be stopped, the error says so and the mount locator is kept so `ti fs unmount-file-system` can retry; before the locator exists there is nothing to keep, so the error instead names the companion's own `ti-drive9 umount` with the resource-scoped HOME. A mount that would unpack into an overlay ti cannot resolve is refused with `fs.mount_unpack_requires_profile`. A mount that unpacks nothing at the companion, including one that only names `--local-root`, is not audited; ordinary mounts keep their previous behavior. The predicate counts the effective pack paths rather than the companion's unpack decision, so a `coding-agent` mount with `--pack-path` still runs the audit even though that profile carries no unpack paths of its own. Links that land outside an audited run window are treated as pre-existing local state. The extra `--pack-path` values are recorded in the mount locator (together with the mount's local root) and replayed as repeated `drive9 umount --pack-path` when the mount is unmounted, because the companion's `mount` has no flag for them and `umount --pack-path` is what feeds the automatic pack; without the replay the mount succeeds while the archive silently omits those local overlay paths. They are overlay paths: a value that is absent from `/overlay` at unmount is skipped with a check in the unmount output rather than failing the pack after the mount is already detached, and a WebDAV mount (which has no local overlay) refuses `--pack-path` at mount time. `--pack-archive-path` adds an archive instead of choosing the only one: without `--no-auto-pack` the companion packs both the profile's default archive and the named one; an explicit archive keeps the replay even together with `--no-auto-pack`, because the pack still runs; `--no-auto-pack` alone suppresses the replay along with the automatic pack. `--pack-path` is refused at mount time for a WebDAV mount and for a value the pack cannot accept (`\` or a `.`/`..` segment, and a relative value may not contain an empty segment; a blank value is dropped, and an absolute value may repeat slashes). Restoring the archive is still the mount profile's decision: only a profile that carries automatic unpack paths, such as `portable`, unpacks it at the next mount, a `coding-agent` mount never does, and `ti fs unpack-file-system` (or an explicit `--unpack-archive-path`) is how to restore it deliberately. +When a mount unpacks a local overlay (auto-unpack with a non-`none` mount profile whose effective pack paths are non-empty — `portable` supplies `/` by default, and the companion's mount accepts no extra pack paths of its own — while `--no-auto-unpack` is not set, or an explicit `--unpack-archive-path`), it runs the same overlay symlink audit as `ti fs unpack-file-system`: ti resolves the local overlay before the companion runs, snapshots it, audits it after the mount becomes readable, and also when readiness times out, removes links that escape the overlay, stops the mount, and reports the error. The audited root is the companion's own default overlay root, so existing overlays keep their location; an explicit `--local-root` is passed through and audited as given. If the audit rejects the overlay or an unpack-capable mount never becomes ready, ti stops the mount instead of leaving it running (an exception to the usual timeout behavior, because unpack may still be completing). If the mount cannot be stopped, the error says so and the mount locator is kept so `ti fs unmount-file-system` can retry; before the locator exists there is nothing to keep, so the error instead names the companion's own `ti-drive9 umount` with the resource-scoped HOME. A mount that would unpack into an overlay ti cannot resolve is refused with `fs.mount_unpack_requires_profile`. A mount that unpacks nothing at the companion, including one that only names `--local-root`, is not audited; ordinary mounts keep their previous behavior. The predicate counts the effective pack paths rather than the companion's unpack decision, so a `coding-agent` mount with `--pack-path` still runs the audit even though that profile carries no unpack paths of its own. Links that land outside an audited run window are treated as pre-existing local state. The extra `--pack-path` values are recorded in the mount locator (together with the mount's local root) and replayed as repeated `drive9 umount --pack-path` when the mount is unmounted, because the companion's `mount` has no flag for them and `umount --pack-path` is what feeds the automatic pack; without the replay the mount succeeds while the archive silently omits those local overlay paths. They are overlay paths: a value that is absent from `/overlay` (under the layer-specific root for a layer mount) at unmount is skipped with a check in the unmount output rather than failing the pack after the mount is already detached, and a WebDAV mount (which has no local overlay) refuses `--pack-path` at mount time. `--pack-archive-path` adds an archive instead of choosing the only one: without `--no-auto-pack` the companion packs both the profile's default archive and the named one; an explicit archive keeps the replay even together with `--no-auto-pack`, because the pack still runs; `--no-auto-pack` alone suppresses the replay along with the automatic pack. `--pack-path` is refused at mount time for a WebDAV mount and for a value the pack cannot accept (`\` or a `.`/`..` segment, and a relative value may not contain an empty segment; a blank value is dropped, and an absolute value may repeat slashes). Restoring the archive is still the mount profile's decision: only a profile that carries automatic unpack paths, such as `portable`, unpacks it at the next mount, a `coding-agent` mount never does, and `ti fs unpack-file-system` (or an explicit `--unpack-archive-path`) is how to restore it deliberately. `ti fs-vault run-with-secret` reads the named secret through the companion and runs the command from ti itself. The child receives only the secret fields plus an environment with ti credentials removed: the filesystem bearer token, the vault token, the organization API key pair, and the filesystem AI provider key are never inherited. Field names are exported with the same environment-key conversion as `ti fs-vault read-secret --format env` (ASCII letters upper-cased, digits and `_` kept, a leading digit prefixed with `_`, and every byte outside `A-Z`, `a-z`, `0-9`, and `_` replaced with `_`), so accented characters produce one underscore per UTF-8 byte; two fields that convert to the same key fail with a usage error instead of overwriting each other. A field that converts to a process-configuration variable is rejected with `vault.env_key_forbidden` instead of injected, because whoever can write a secret's fields could otherwise choose what the child loads or runs; the error lists every rejected field and what it would have configured: `PATH`, `PATHEXT`, `COMSPEC`, `SHELL`, shell startup and evaluation names such as `ENV`, `BASH_ENV`, `SHELLOPTS`, `PS4`, and `IFS`, dynamic-loader names such as `LD_PRELOAD`, `LD_LIBRARY_PATH`, `DYLD_INSERT_LIBRARIES`, and `GCONV_PATH`, language-runtime names such as `PYTHONPATH`, `PERL5OPT`, `NODE_OPTIONS`, `RUBYOPT`, `JAVA_TOOL_OPTIONS`, and `LUA_INIT`, and helper-selection names such as `SSH_AUTH_SOCK`, `GIT_SSH_COMMAND`, `GIT_CONFIG_GLOBAL`, and `PAGER`. The check matches exact names after conversion, except that a few families whose suffix the field name chooses are matched by prefix (`DYLD_*`, `LD_32_*`, `LD_64_*`, `GIT_CONFIG_KEY_`, `GIT_CONFIG_VALUE_`), and that trailing all-digit version segments are stripped before the lookup, so versioned spellings such as `LUA_INIT_5_4`, `LUA_PATH_5_4`, `LUA_CPATH_5_4`, and `LD_PRELOAD_32` hit the same entries as their base names (Lua reads the versioned name first, and the Solaris loader reads the 32/64-bit one). Names that merely resemble a rejected one, such as `SSH_PRIVATE_KEY`, `GIT_TOKEN`, `LD_PRELOAD_BACKUP`, or `DB_URL_2`, remain injectable. `ti fs-vault read-secret --format env` still converts those names, because it only prints values and never spawns a child. On Windows, an inherited variable that differs from an injected field only by letter case is replaced, because the platform resolves environment names case-insensitively. -Filesystem layers can fork copy-on-write child timelines without copying a workspace. Layer and checkpoint mounts require FUSE; checkpoint mounts are always read-only. Drive9 does not support combining recursive copy with a layer, so seed a directory tree through a writable layer mount, drain it, and then create the checkpoint: +Create a layer to try changes in an isolated working directory. Seed it with a recursive copy, then fork its current contents for an independent experiment. -```shell +~~~shell export TI_FS_FILE_SYSTEM_ID="" -ti fs create-directory --path /research/q3-market -ti fs create-layer --base-root-path /research/q3-market --layer-name research-base -SEED_MOUNT="$(mktemp -d)" -ti fs mount-file-system --mount-path "$SEED_MOUNT" --remote-path /research/q3-market --driver fuse --layer-ref research-base -tar -C . -cf - . | tar -C "$SEED_MOUNT" -xf - -ti fs drain-file-system --mount-path "$SEED_MOUNT" -ti fs unmount-file-system --mount-path "$SEED_MOUNT" -rmdir "$SEED_MOUNT" -ti fs create-layer-checkpoint --layer-id research-base --checkpoint-id seed -ti fs fork-layer --parent-layer-ref research-base --layer-name experiment-a --checkpoint-id seed -ti fs list-layer-chain --layer-ref experiment-a --output text -``` +ti fs create-directory --path /research +ti fs create-layer --base-root-path /research --layer-name research-base --ttl 1h +ti fs copy-file --from-local ./seed --to-remote /research/seed --recursive --layer-id research-base +ti fs fork-layer --parent-layer-ref research-base --layer-name experiment-a --ttl 30m +ti fs describe-layer --layer-ref experiment-a +~~~ -Use `ti fs delete-layer --layer-ref experiment-a` to abandon a rejected leaf. Deleting a layer with live descendants fails unless `--cascade` is supplied explicitly. Layer names are not durable unique identifiers because abandoned layers remain visible; automation should capture returned layer IDs and use run-unique checkpoint IDs. +Use `ti fs merge-layer --layer-ref experiment-a` to publish the selected layer or `ti fs delete-layer --layer-ref experiment-a` to discard it. Scripts can use the server-generated `layer_id` returned by create or fork. Layer mounts require FUSE. Their local overlays are scoped by the SHA-256 of that ID under `/views//overlay`. `ti fs list-regions` lists the Filesystem regions published by TiDB Cloud Filesystem, with their cloud provider, display name, state, and regional service address. It uses TiDB Cloud credentials, always asks the API, and refreshes the recorded `service_address` of locally stored File System credentials. The catalog request is Digest-authenticated with the organization API key pair, so `ti` follows a redirect only when it keeps the same scheme and host and otherwise fails with `api.fs_regions_redirect_refused`; the catalog endpoint itself must be `https` (plain `http` is accepted only for a loopback test server) and must not embed credentials, a query, or a fragment: @@ -406,12 +400,9 @@ ti fs find-files ti fs create-layer ti fs list-layers ti fs fork-layer -ti fs list-layer-chain ti fs describe-layer -ti fs diff-layer -ti fs create-layer-checkpoint ti fs delete-layer -ti fs rollback-layer +ti fs merge-layer ti fs commit-layer ti fs pack-file-system ti fs unpack-file-system diff --git a/docs/release-notes/v0.2.12.md b/docs/release-notes/v0.2.12.md new file mode 100644 index 00000000..6b05dde3 --- /dev/null +++ b/docs/release-notes/v0.2.12.md @@ -0,0 +1,19 @@ +# TiDB Cloud CLI v0.2.12 + +The installer and updater accept the Drive9 LayerFS v36 command surface. Both still fetch the latest companion and verify its checksum. The macOS arm64 build tested for this change was bbb61cbc3ccda6748475a650035a9653922ad0ff. + +## Filesystem layers + +Create and fork return a generated layer ID and accept a lifetime and tags. Inspect a layer by ID, name, or tag with `ti fs describe-layer --layer-ref`. Publish it with `merge-layer`, also available as `commit-layer`. Delete it with `delete-layer`. The optional `--force` allows deletion while exclusively mounted. + +Checkpoint creation, historical mounts, ancestry listing, diff and rollback commands have been removed. Fork operates on the current parent layer. Layer-scoped search and find flags have been removed. Recursive copy supports layers. FUSE mounts audit unpacked files and check pack paths in the selected layer’s own overlay. + +## Upgrade + +Drain and unmount active mounts before replacing ti and its companion. The v0.2.11 updater still requires the previous companion command surface. Once v0.2.12 is published, use its installer to upgrade an existing installation or install a new one. + +~~~sh +curl -fsSL https://github.com/tidbcloud/ti-cli/releases/download/v0.2.12/install.sh | sh -s -- --version v0.2.12 --yes +~~~ + +On Windows, run the v0.2.12 PowerShell installer with `-Version v0.2.12 -Yes`. Pass the original install directory when upgrading a custom installation. diff --git a/docs/releasing.md b/docs/releasing.md index fa85b6ec..d752a98d 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -23,7 +23,7 @@ Do not claim that a ti rollback also rolls back Drive9. Windows users must rerun ## Prepare the release PR 1. Check the latest published ti release and changes since that tag. Use the next patch version for a companion refresh with no ti interface change. Include only merged changes in the release notes. -2. Check the Drive9 `version` file and checksum manifest at each source above. Confirm that they agree and contain all five ti targets: Darwin and Linux on amd64/arm64, and Windows on amd64. Download and verify the companion on the validation host, then inspect `ti-drive9 version`, `ti-drive9 fs layer help`, and `ti-drive9 mount --help`, and require `ti-drive9 exec --help` to exit zero. Do not parse Runtime help prose as an API. The required capabilities include layer `fork`, `chain`, `delete`, mount `--layer`, `--checkpoint`, and the Runtime command from Drive9 #1022. Record the exact Drive9 version, full Git hash, and each artifact checksum in the release evidence. Publish the Drive9 artifact before the ti release. +2. Check the Drive9 `version` file and checksum manifest at each source above. Confirm that they agree and contain all five ti targets: Darwin and Linux on amd64/arm64, and Windows on amd64. Download and verify the companion on the validation host, then inspect `ti-drive9 version`, `ti-drive9 fs layer help`, and `ti-drive9 mount --help`, and require `ti-drive9 exec --help` to exit zero. Do not parse Runtime help prose as an API. The required capabilities include layer `create`, `fork`, `merge`, `rm`, mount `--layer`, and the Runtime command from Drive9 #1022. Record the exact Drive9 version, full Git hash, and each artifact checksum in the release evidence. Publish the Drive9 artifact before the ti release. 3. Add `docs/release-notes/.md`, following recent notes. For a companion refresh, identify the tested Drive9 build, link the relevant upstream fixes, explain the mutable download source, and include upgrade and reinstall commands. Pass the ti version explicitly to the installer: downloading an installer from a tagged URL alone still defaults to installing the latest ti release. 4. Validate the candidate with the repository commands: diff --git a/e2e/cli_test.go b/e2e/cli_test.go index aa6a0f52..a9813b51 100644 --- a/e2e/cli_test.go +++ b/e2e/cli_test.go @@ -1015,15 +1015,15 @@ func TestFSRemoteInventoryAndIDCredentialSelectionAcrossCommandFamilies(t *testi git.wantExitCode(0) mount := runTIWithInput(t, bin, "", baseEnv, "--profile", "stage", "fs", "mount-file-system", "--file-system-id", "tenant-aws-us-west-2", "--mount-path", filepath.Join(home, "mount")) mount.wantExitCode(0) - profileFork := runTIWithInput(t, bin, "", baseEnv, "--profile", "stage", "--region", "aws-us-west-2", "fs", "fork-layer", "--file-system-id", "tenant-aws-us-west-2", "--parent-layer-ref", "parent-id", "--layer-id", "profile-child") + profileFork := runTIWithInput(t, bin, "", baseEnv, "--profile", "stage", "--region", "aws-us-west-2", "fs", "fork-layer", "--file-system-id", "tenant-aws-us-west-2", "--parent-layer-ref", "parent-id", "--layer-name", "profile-child") profileFork.wantExitCode(0) profileFork.wantStdoutContains(`"layer_id": "child-id"`) - profileChain := runTIWithInput(t, bin, "", baseEnv, "--profile", "stage", "--region", "aws-us-west-2", "fs", "list-layer-chain", "--file-system-id", "tenant-aws-us-west-2", "--layer-ref", "profile-child") - profileChain.wantExitCode(0) - profileChain.wantStdoutContains(`"chain"`) + profileInspect := runTIWithInput(t, bin, "", baseEnv, "--profile", "stage", "--region", "aws-us-west-2", "fs", "describe-layer", "--file-system-id", "tenant-aws-us-west-2", "--layer-ref", "profile-child") + profileInspect.wantExitCode(0) + profileInspect.wantStdoutContains(`"fence"`) profileDeleteLayer := runTIWithInput(t, bin, "", baseEnv, "--profile", "stage", "--region", "aws-us-west-2", "fs", "delete-layer", "--file-system-id", "tenant-aws-us-west-2", "--layer-ref", "profile-child") profileDeleteLayer.wantExitCode(0) - profileDeleteLayer.wantStdoutContains(`"status": "abandoned"`) + profileDeleteLayer.wantStdoutContains(`"status": "deleted"`) calls := readFakeDrive9Calls(t, recordPath) for _, call := range calls { @@ -1034,8 +1034,8 @@ func TestFSRemoteInventoryAndIDCredentialSelectionAcrossCommandFamilies(t *testi assertFakeDrive9Call(t, calls, []string{"fs", "ls"}, drive9TestToken("tenant-aws-us-west-2"), home, "stage", "tenant-aws-us-west-2", westControl.URL(), "aws-us-west-2") assertFakeDrive9Call(t, calls, []string{"vault", "ls"}, drive9TestToken("tenant-aws-us-east-1"), home, "stage", "tenant-aws-us-east-1", eastControl.URL(), "aws-us-east-1") assertFakeDrive9Call(t, calls, []string{"fs", "layer", "fork"}, drive9TestToken("tenant-aws-us-west-2"), home, "stage", "tenant-aws-us-west-2", westControl.URL(), "aws-us-west-2") - assertFakeDrive9Call(t, calls, []string{"fs", "layer", "chain"}, drive9TestToken("tenant-aws-us-west-2"), home, "stage", "tenant-aws-us-west-2", westControl.URL(), "aws-us-west-2") - assertFakeDrive9Call(t, calls, []string{"fs", "layer", "delete"}, drive9TestToken("tenant-aws-us-west-2"), home, "stage", "tenant-aws-us-west-2", westControl.URL(), "aws-us-west-2") + assertFakeDrive9Call(t, calls, []string{"fs", "layer", "inspect"}, drive9TestToken("tenant-aws-us-west-2"), home, "stage", "tenant-aws-us-west-2", westControl.URL(), "aws-us-west-2") + assertFakeDrive9Call(t, calls, []string{"fs", "layer", "rm"}, drive9TestToken("tenant-aws-us-west-2"), home, "stage", "tenant-aws-us-west-2", westControl.URL(), "aws-us-west-2") if !eastControl.hasRequest(http.MethodPost, "/v1/admin/tenants") || !eastControl.hasRequest(http.MethodGet, "/v1/admin/tenants", "display_name=agent", "label=environment%3D%3Dproduction") || !westControl.hasRequest(http.MethodGet, "/v1/admin/tenants/tenant-aws-us-west-2") { @@ -1674,64 +1674,47 @@ func TestFSLayerForkWorkflowCommands(t *testing.T) { } seedFSCredential(t, home, "default", "tenant-layer", "aws-us-east-1", "https://fs-east.test", drive9TestToken("tenant-layer")) - fork := runTIWithInput(t, bin, "", env, "fs", "fork-layer", "--parent-layer-ref", "research-base", "--layer-id", "child-id", "--layer-name", "child", "--checkpoint-id", "seed", "--actor-id", "agent") + run := func(args ...string) commandResult { + return runTIWithInput(t, bin, "", env, append([]string{"fs"}, args...)...) + } + create := run("create-layer", "--base-root-path", "/workspace", "--layer-name", "child", "--ttl", "5m", "--tag", "k=v") + create.wantExitCode(0) + fork := run("fork-layer", "--parent-layer-ref", "research-base", "--layer-name", "child", "--tag", "k=v", "--ttl", "1h", "--actor-id", "agent") fork.wantExitCode(0) - fork.wantStdoutContains(`"parent_layer_id": "parent-id"`) - fork.wantStdoutNotContains("drive9_") - - chain := runTIWithInput(t, bin, "", env, "fs", "list-layer-chain", "--layer-ref", "child-id", "--output", "text") - chain.wantExitCode(0) - chain.wantStdoutContains("LAYER_ID") - chain.wantStdoutContains("root-id") - chain.wantStdoutContains("child-id") - - queried := runTIWithInput(t, bin, "", env, "fs", "list-layer-chain", "--layer-ref", "child-id", "--query", "chain[].layer_id") - queried.wantExitCode(0) - queried.wantStdoutContains("root-id") - - dryRunDelete := runTIWithInput(t, bin, "", env, "fs", "delete-layer", "--layer-ref", "child-id", "--cascade", "--dry-run") - dryRunDelete.wantExitCode(0) - dryRunDelete.wantStdoutContains(`"operation": "delete_layer"`) - dryRunDelete.wantStdoutContains(`"companion_capability"`) - dryRunDelete.wantStdoutNotContains(drive9TestToken("tenant-layer")) - - deleted := runTIWithInput(t, bin, "", env, "fs", "delete-layer", "--layer-ref", "child-id", "--cascade", "--output", "text") - deleted.wantExitCode(0) - deleted.wantStdoutContains("status=abandoned") - - recursive := runTIWithInput(t, bin, "", env, "fs", "copy-file", "--from-local", ".", "--to-remote", "/workspace", "--recursive", "--layer-id", "child-id") - recursive.wantExitCode(2) - recursive.wantStderrContains("--recursive cannot be combined with --layer-id") - - checkpointWithoutLayer := runTIWithInput(t, bin, "", env, "fs", "mount-file-system", "--mount-path", filepath.Join(home, "missing-layer"), "--driver", "fuse", "--checkpoint-id", "seed") - checkpointWithoutLayer.wantExitCode(2) - checkpointWithoutLayer.wantStderrContains("--checkpoint-id requires --layer-ref") - - webdavLayer := runTIWithInput(t, bin, "", env, "fs", "mount-file-system", "--mount-path", filepath.Join(home, "webdav"), "--driver", "webdav", "--layer-ref", "child-id") - webdavLayer.wantExitCode(2) - webdavLayer.wantStderrContains("layer and checkpoint mounts require FUSE") - - mountPath := filepath.Join(home, "checkpoint") - mounted := runTIWithInput(t, bin, "", env, "fs", "mount-file-system", "--mount-path", mountPath, "--remote-path", "/workspace", "--driver", "fuse", "--layer-ref", "child-id", "--checkpoint-id", "seed") + fork.wantStdoutContains("parent-id") + list := run("list-layers", "--output", "text") + list.wantExitCode(0) + list.wantStdoutContains("FENCE") + for _, name := range []string{"merge-layer", "commit-layer"} { + flag := "--layer-ref" + if name == "commit-layer" { + flag = "--layer-id" + } + dry := run(name, flag, "child", "--dry-run") + dry.wantExitCode(0) + dry.wantStdoutContains("merge_layer") + r := run(name, flag, "child") + r.wantExitCode(0) + r.wantStdoutContains(`"applied_paths": 2`) + } + run("delete-layer", "--layer-ref", "child", "--force").wantExitCode(0) + removed := [][]string{{"fork-layer", "--checkpoint-id", "v1"}, {"mount-file-system", "--checkpoint-id", "cp"}, {"find-files", "--layer-id", "child"}, {"search-file-content", "--layer-id", "child"}, {"create-layer", "--layer-id", "forced"}, {"delete-layer", "--cascade"}} + for _, args := range removed { + res := run(args...) + res.wantExitCode(2) + res.wantStderrContains("unknown flag") + } + mountPath := filepath.Join(home, "mounted") + mounted := run("mount-file-system", "--mount-path", mountPath, "--remote-path", "/workspace", "--driver", "fuse", "--layer-ref", "child", "--read-only") mounted.wantExitCode(0) - mounted.wantStdoutContains(`"read_only": true`) - mounted.wantStdoutContains(`"durability": "auto"`) - mounted.wantStdoutContains(`"checkpoint_id": "seed"`) - - explicitWritable := runTIWithInput(t, bin, "", env, "fs", "mount-file-system", "--mount-path", filepath.Join(home, "writable-checkpoint"), "--driver", "fuse", "--layer-ref", "child-id", "--checkpoint-id", "seed", "--read-only=false") - explicitWritable.wantExitCode(2) - explicitWritable.wantStderrContains("checkpoint mounts are read-only") - explicitWriteBack := runTIWithInput(t, bin, "", env, "fs", "mount-file-system", "--mount-path", filepath.Join(home, "write-back-checkpoint"), "--driver", "fuse", "--layer-ref", "child-id", "--checkpoint-id", "seed", "--write-back-cache=true") - explicitWriteBack.wantExitCode(2) - explicitWriteBack.wantStderrContains("checkpoint mounts are read-only") - unmounted := runTIWithInput(t, bin, "", env, "fs", "unmount-file-system", "--mount-path", mountPath) - unmounted.wantExitCode(0) - + mounted.wantStdoutContains(`"layer_id": "layer_01jz0123456789abcdefghjkmn"`) + run("unmount-file-system", "--mount-path", mountPath).wantExitCode(0) calls := readFakeDrive9Calls(t, recordPath) - assertFakeDrive9Args(t, calls, []string{"fs", "layer", "fork", "--json", "--id", "child-id", "--name", "child", "--checkpoint", "seed", "--actor", "agent", "research-base"}) - assertFakeDrive9Args(t, calls, []string{"fs", "layer", "chain", "--json", "child-id"}) - assertFakeDrive9Args(t, calls, []string{"fs", "layer", "delete", "--cascade", "child-id"}) - assertFakeDrive9Args(t, calls, []string{"mount", "--mode", "fuse", "--read-only", "--layer", "child-id", "--checkpoint", "seed", "--cache-size", "128", "--read-cache-max-file-mb", "4", "--read-cache-ttl", "30s", ":/workspace", mountPath}) + assertFakeDrive9Args(t, calls, []string{"fs", "layer", "create", "--json", "--name", "child", "--ttl", "5m", "--tag", "k=v", ":/workspace"}) + assertFakeDrive9Args(t, calls, []string{"fs", "layer", "fork", "--json", "--name", "child", "--ttl", "1h", "--tag", "k=v", "--actor", "agent", "research-base"}) + assertFakeDrive9Args(t, calls, []string{"fs", "layer", "merge", "--json", "child"}) + assertFakeDrive9Args(t, calls, []string{"fs", "layer", "rm", "--json", "--force", "child"}) + } func TestFSImportFileSystemToken(t *testing.T) { diff --git a/e2e/installer_test.go b/e2e/installer_test.go index c2dbf818..ee7bc6d7 100644 --- a/e2e/installer_test.go +++ b/e2e/installer_test.go @@ -239,11 +239,11 @@ func compatibleDrive9ShellFixture(callLog string) string { return fmt.Sprintf(`#!/bin/sh printf '%%s\n' "$*" >> %q if [ "$1 $2 $3" = "fs layer help" ]; then - printf 'usage: drive9 fs layer \n' + printf 'usage: drive9 fs layer \n' exit 0 fi if [ "$1 $2" = "mount --help" ]; then - printf ' -layer string\n -checkpoint string\n' + printf ' -layer value\n' exit 0 fi if [ "$1 $2" = "exec --help" ]; then @@ -336,7 +336,7 @@ func TestInstallersValidateCompanionCommandSurfaceBeforeInstallation(t *testing. if powerShellValidation < 0 || powerShellInstall < 0 || powerShellValidation >= powerShellInstall { t.Fatal("install.ps1 must validate the staged companion before installing it") } - for _, required := range []string{"fork", "chain", "delete", "layer", "checkpoint", "exec"} { + for _, required := range []string{"create", "fork", "merge", "rm", "layer", "exec"} { if !strings.Contains(shell, required) || !strings.Contains(powerShell, required) { t.Fatalf("installers do not validate required companion surface %q", required) } diff --git a/e2e/live_layer_test.go b/e2e/live_layer_test.go index 59c7328d..25cad0a2 100644 --- a/e2e/live_layer_test.go +++ b/e2e/live_layer_test.go @@ -36,8 +36,7 @@ func TestLiveFSLayerForkWorkflow(t *testing.T) { } suffix := fmt.Sprintf("%d-%d", os.Getpid(), time.Now().UnixNano()) remoteRoot := "/ti-e2e-layer-fork-" + suffix - rootLayerID := "ti-e2e-root-" + suffix - rootCheckpointID := "ti-e2e-seed-" + suffix + var layers []string runFS := func(command string, args ...string) commandResult { cliArgs := []string{"--profile", profileName, "fs", command, "--file-system-id", fileSystemID} @@ -51,7 +50,6 @@ func TestLiveFSLayerForkWorkflow(t *testing.T) { } mounted := map[string]bool{} - rootCreated := false defer func() { for mountPath, active := range mounted { if !active { @@ -62,14 +60,13 @@ func TestLiveFSLayerForkWorkflow(t *testing.T) { t.Logf("cleanup layer mount failed for %s: exit=%d stderr=%s", mountPath, cleanup.exitCode, strings.TrimSpace(cleanup.stderr)) } } - if rootCreated { - cleanupLayer := runFS("delete-layer", "--layer-ref", rootLayerID, "--cascade") - if cleanupLayer.exitCode != 0 && cleanupLayer.exitCode != 5 { - t.Logf("cleanup root layer failed for %s: exit=%d stderr=%s", rootLayerID, cleanupLayer.exitCode, strings.TrimSpace(cleanupLayer.stderr)) - rollbackLayer := runFS("rollback-layer", "--layer-id", rootLayerID) - if rollbackLayer.exitCode != 0 && rollbackLayer.exitCode != 5 { - t.Logf("cleanup root layer rollback failed for %s: exit=%d stderr=%s", rootLayerID, rollbackLayer.exitCode, strings.TrimSpace(rollbackLayer.stderr)) - } + for i := len(layers) - 1; i >= 0; i-- { + if layers[i] == "" { + continue + } + res := runFS("delete-layer", "--layer-ref", layers[i]) + if res.exitCode != 0 && !isLiveFSNotFound(res.stderr) { + t.Errorf("cleanup layer %s: %s", layers[i], res.stderr) } } cleanupRoot := runFS("delete-file", "--path", remoteRoot, "--recursive") @@ -91,7 +88,7 @@ func TestLiveFSLayerForkWorkflow(t *testing.T) { result.wantExitCode(0) result.wantStdoutContains(`"status": "drained"`) } - mountLayer := func(layerRef, checkpointID, mountPath string) { + mountLayer := func(layerRef, mountPath string) { t.Helper() args := []string{ "--mount-path", mountPath, @@ -100,55 +97,12 @@ func TestLiveFSLayerForkWorkflow(t *testing.T) { "--layer-ref", layerRef, "--ready-timeout", "60s", } - if checkpointID != "" { - args = append(args, "--checkpoint-id", checkpointID) - } result := runFS("mount-file-system", args...) result.wantExitCode(0) result.wantStdoutContains(`"status": "mounted"`) result.wantStdoutContains(`"layer_ref": "` + layerRef + `"`) - if checkpointID != "" { - result.wantStdoutContains(`"checkpoint_id": "` + checkpointID + `"`) - result.wantStdoutContains(`"read_only": true`) - } mounted[mountPath] = true } - checkpoint := func(layerID, checkpointID, label string) { - t.Helper() - result := runFS( - "create-layer-checkpoint", - "--layer-id", layerID, - "--checkpoint-id", checkpointID, - "--label", label, - ) - result.wantExitCode(0) - result.wantStdoutContains(checkpointID) - } - fork := func(parentID, childID, checkpointID, name string) apifs.FSLayer { - t.Helper() - args := []string{ - "--parent-layer-ref", parentID, - "--layer-id", childID, - "--layer-name", name, - "--actor-id", "ti-live-e2e", - } - if checkpointID != "" { - args = append(args, "--checkpoint-id", checkpointID) - } - result := runFS("fork-layer", args...) - result.wantExitCode(0) - var layer apifs.FSLayer - if err := json.Unmarshal([]byte(result.stdout), &layer); err != nil { - t.Fatalf("decode forked layer %s: %v\n%s", childID, err, result.stdout) - } - if layer.LayerID != childID || layer.ParentLayerID != parentID { - t.Fatalf("forked layer identity mismatch: %+v", layer) - } - if checkpointID != "" && layer.OriginCheckpointID != checkpointID { - t.Fatalf("forked layer checkpoint = %q, want %q: %+v", layer.OriginCheckpointID, checkpointID, layer) - } - return layer - } assertBaseAbsent := func(remotePath string) { t.Helper() result := runFS("read-file", "--path", remotePath) @@ -177,252 +131,39 @@ func TestLiveFSLayerForkWorkflow(t *testing.T) { createRoot := runFS("create-directory", "--path", remoteRoot, "--mode", "0755") createRoot.wantExitCode(0) - createLayer := runFS( - "create-layer", - "--layer-id", rootLayerID, - "--base-root-path", remoteRoot, - "--layer-name", "research-base-"+suffix, - "--actor-id", "ti-live-e2e-seed", - "--tag", "test=ti-e2e", - "--tag", "run="+suffix, - ) - createLayer.wantExitCode(0) - rootCreated = true - - seedSource := filepath.Join(t.TempDir(), "seed") - if err := os.MkdirAll(filepath.Join(seedSource, "reports"), 0o755); err != nil { - t.Fatalf("create local seed reports: %v", err) + parent := liveLayerID(t, runFS("create-layer", "--base-root-path", remoteRoot, "--layer-name", "parent-"+suffix, "--ttl", "1h")) + layers = append(layers, parent) + seedMount := t.TempDir() + mountLayer(parent, seedMount) + if err := os.WriteFile(filepath.Join(seedMount, "seed.txt"), []byte(suffix), 0600); err != nil { + t.Fatal(err) } - if err := os.MkdirAll(filepath.Join(seedSource, "data"), 0o755); err != nil { - t.Fatalf("create local seed data: %v", err) - } - seedReport := "seed report " + suffix + "\n" - seedData := "seed data " + suffix + "\n" - if err := os.WriteFile(filepath.Join(seedSource, "reports", "report.md"), []byte(seedReport), 0o644); err != nil { - t.Fatalf("write local seed report: %v", err) - } - if err := os.WriteFile(filepath.Join(seedSource, "data", "input.txt"), []byte(seedData), 0o644); err != nil { - t.Fatalf("write local seed data: %v", err) - } - seedMount := filepath.Join(t.TempDir(), "seed-mount") - if err := os.MkdirAll(seedMount, 0o755); err != nil { - t.Fatalf("create seed mount path: %v", err) - } - mountLayer(rootLayerID, "", seedMount) - copyLiveDirectoryTree(t, seedSource, seedMount) drain(seedMount) unmount(seedMount) - assertBaseAbsent(remoteRoot + "/reports/report.md") - assertBaseAbsent(remoteRoot + "/data/input.txt") - seedFind := runFS("find-files", "--path", remoteRoot, "--file-name-pattern", "report.md", "--layer-id", rootLayerID) - seedFind.wantExitCode(0) - seedFind.wantStdoutContains(remoteRoot + "/reports/report.md") - checkpoint(rootLayerID, rootCheckpointID, "workspace-seed") - - briefID := "ti-e2e-brief-" + suffix - longformID := "ti-e2e-longform-" + suffix - analystID := "ti-e2e-analyst-" + suffix - fork(rootLayerID, briefID, rootCheckpointID, "style-brief-"+suffix) - fork(rootLayerID, longformID, rootCheckpointID, "style-longform-"+suffix) - fork(rootLayerID, analystID, rootCheckpointID, "style-analyst-"+suffix) - - for _, childID := range []string{briefID, longformID, analystID} { - chainResult := runFS("list-layer-chain", "--layer-ref", childID) - chainResult.wantExitCode(0) - var chain struct { - Chain []apifs.FSLayerChainFrame `json:"chain"` - } - if err := json.Unmarshal([]byte(chainResult.stdout), &chain); err != nil { - t.Fatalf("decode layer chain for %s: %v\n%s", childID, err, chainResult.stdout) - } - if len(chain.Chain) != 2 || chain.Chain[0].LayerID != rootLayerID || chain.Chain[1].LayerID != childID || chain.Chain[1].OriginCheckpointID != rootCheckpointID { - t.Fatalf("unexpected pinned chain for %s: %+v", childID, chain.Chain) - } - } - - parentLatePath := remoteRoot + "/parent-late.txt" - parentLateFile := filepath.Join(t.TempDir(), "parent-late.txt") - if err := os.WriteFile(parentLateFile, []byte("late parent write\n"), 0o644); err != nil { - t.Fatalf("write parent-late source: %v", err) - } - parentLate := runFS("copy-file", "--from-local", parentLateFile, "--to-remote", parentLatePath, "--layer-id", rootLayerID) - parentLate.wantExitCode(0) - for _, childID := range []string{briefID, longformID, analystID} { - findLate := runFS("find-files", "--path", remoteRoot, "--file-name-pattern", "parent-late.txt", "--layer-id", childID) - findLate.wantExitCode(0) - findLate.wantStdoutNotContains(parentLatePath) - } - - briefMount := filepath.Join(t.TempDir(), "brief") - longformMount := filepath.Join(t.TempDir(), "longform") - analystMount := filepath.Join(t.TempDir(), "analyst") - for _, mountPath := range []string{briefMount, longformMount, analystMount} { - if err := os.MkdirAll(mountPath, 0o755); err != nil { - t.Fatalf("create child mount path: %v", err) - } - } - mountLayer(briefID, "", briefMount) - mountLayer(longformID, "", longformMount) - mountLayer(analystID, "", analystMount) - for _, mountPath := range []string{briefMount, longformMount, analystMount} { - waitLiveLocalFile(t, filepath.Join(mountPath, "reports", "report.md"), seedReport, 30*time.Second) - } - briefContent := "brief report " + suffix + "\n" - longformContent := "longform report " + suffix + "\n" - analystV1 := "analyst v1 TAM " + suffix + "\n" - if err := os.WriteFile(filepath.Join(briefMount, "reports", "brief.md"), []byte(briefContent), 0o644); err != nil { - t.Fatalf("write brief report: %v", err) - } - if err := os.WriteFile(filepath.Join(longformMount, "reports", "longform.md"), []byte(longformContent), 0o644); err != nil { - t.Fatalf("write longform report: %v", err) - } - if err := os.WriteFile(filepath.Join(analystMount, "reports", "report.md"), []byte(analystV1), 0o644); err != nil { - t.Fatalf("write analyst report: %v", err) - } - for _, mountPath := range []string{briefMount, longformMount, analystMount} { - drain(mountPath) - } - if data, err := os.ReadFile(filepath.Join(analystMount, "reports", "report.md")); err != nil || string(data) != analystV1 { - t.Fatalf("analyst mount report mismatch: %q, %v", data, err) - } - if _, err := os.Stat(filepath.Join(analystMount, "reports", "brief.md")); !os.IsNotExist(err) { - t.Fatalf("brief child write leaked into analyst child: %v", err) - } - waitLiveFSResult(t, bin, []string{"--profile", profileName, "fs", "search-file-content", "--file-system-id", fileSystemID, "--path", remoteRoot, "--pattern", "TAM", "--layer-id", analystID}, "report.md", 2*time.Minute, "search analyst layer") - analystDiff := runFS("diff-layer", "--layer-id", analystID) - analystDiff.wantExitCode(0) - analystDiff.wantStdoutContains(remoteRoot + "/reports/report.md") - - unmount(briefMount) - unmount(longformMount) - for _, childID := range []string{briefID, longformID} { - deleted := runFS("delete-layer", "--layer-ref", childID) - deleted.wantExitCode(0) - described := runFS("describe-layer", "--layer-id", childID) - described.wantExitCode(0) - described.wantStdoutContains(`"state": "abandoned"`) - } - listAbandoned := runFS("list-layers") - listAbandoned.wantExitCode(0) - listAbandoned.wantStdoutContains(briefID) - listAbandoned.wantStdoutContains(longformID) - - cpV1 := "ti-e2e-v1-" + suffix - cpV5 := "ti-e2e-v5-" + suffix - cpV7 := "ti-e2e-v7-" + suffix - drain(analystMount) - checkpoint(analystID, cpV1, "first-draft") - analystV5 := "analyst v5 narrative " + suffix + "\n" - if err := os.WriteFile(filepath.Join(analystMount, "reports", "report.md"), []byte(analystV5), 0o644); err != nil { - t.Fatalf("write analyst v5: %v", err) - } - drain(analystMount) - checkpoint(analystID, cpV5, "narrative-ok") - analystV7 := "analyst v7 latest " + suffix + "\n" - if err := os.WriteFile(filepath.Join(analystMount, "reports", "report.md"), []byte(analystV7), 0o644); err != nil { - t.Fatalf("write analyst v7: %v", err) - } - drain(analystMount) - checkpoint(analystID, cpV7, "latest-tip") - - v5Mount := filepath.Join(t.TempDir(), "v5") - if err := os.MkdirAll(v5Mount, 0o755); err != nil { - t.Fatalf("create v5 mount path: %v", err) - } - mountLayer(analystID, cpV5, v5Mount) - waitLiveLocalFile(t, filepath.Join(v5Mount, "reports", "report.md"), analystV5, 30*time.Second) - waitLiveLocalFile(t, filepath.Join(analystMount, "reports", "report.md"), analystV7, 30*time.Second) - if err := os.WriteFile(filepath.Join(v5Mount, "reports", "report.md"), []byte("must fail\n"), 0o644); err == nil { - t.Fatal("historical checkpoint mount accepted a write") - } - - fromV5ID := "ti-e2e-from-v5-" + suffix - fork(analystID, fromV5ID, cpV5, "from-v5-"+suffix) - fromV5Chain := runFS("list-layer-chain", "--layer-ref", fromV5ID) - fromV5Chain.wantExitCode(0) - fromV5Chain.wantStdoutContains(`"origin_checkpoint_id": "` + cpV5 + `"`) - fromV5Mount := filepath.Join(t.TempDir(), "from-v5") - if err := os.MkdirAll(fromV5Mount, 0o755); err != nil { - t.Fatalf("create from-v5 mount path: %v", err) - } - mountLayer(fromV5ID, "", fromV5Mount) - waitLiveLocalFile(t, filepath.Join(fromV5Mount, "reports", "report.md"), analystV5, 30*time.Second) - selectedContent := "selected rewrite from v5 " + suffix + "\n" - if err := os.WriteFile(filepath.Join(fromV5Mount, "reports", "report.md"), []byte(selectedContent), 0o644); err != nil { - t.Fatalf("write selected from-v5 report: %v", err) - } - drain(fromV5Mount) - checkpoint(fromV5ID, "ti-e2e-v5b1-"+suffix, "rewrite-from-v5") - - deleteParent := runFS("delete-layer", "--layer-ref", analystID) - if deleteParent.exitCode == 0 { - deleteParent.fail("deleting a parent with live descendant %s unexpectedly succeeded", fromV5ID) - } - if !strings.Contains(strings.ToLower(deleteParent.stderr), "descendant") { - deleteParent.fail("deleting a parent with live descendant %s failed for an unrelated reason", fromV5ID) - } - - cascadeParentID := "ti-e2e-cascade-parent-" + suffix - cascadeChildID := "ti-e2e-cascade-child-" + suffix - fork(rootLayerID, cascadeParentID, rootCheckpointID, "cascade-parent-"+suffix) - fork(cascadeParentID, cascadeChildID, "", "cascade-child-"+suffix) - cascadeDelete := runFS("delete-layer", "--layer-ref", cascadeParentID, "--cascade") - cascadeDelete.wantExitCode(0) - for _, layerID := range []string{cascadeParentID, cascadeChildID} { - described := runFS("describe-layer", "--layer-id", layerID) - described.wantExitCode(0) - described.wantStdoutContains(`"state": "abandoned"`) - } - - unmount(v5Mount) - unmount(analystMount) - rollbackParent := runFS("rollback-layer", "--layer-id", analystID) - rollbackParent.wantExitCode(0) - waitLiveLocalFile(t, filepath.Join(fromV5Mount, "reports", "report.md"), selectedContent, 30*time.Second) - continuedContent := "continued after parent rollback " + suffix + "\n" - if err := os.WriteFile(filepath.Join(fromV5Mount, "reports", "continued.md"), []byte(continuedContent), 0o644); err != nil { - t.Fatalf("write child after parent rollback: %v", err) - } - drain(fromV5Mount) - waitLiveLocalFile(t, filepath.Join(fromV5Mount, "reports", "continued.md"), continuedContent, 30*time.Second) - unmount(fromV5Mount) - - commitSelected := runFS("commit-layer", "--layer-id", fromV5ID) - commitSelected.wantExitCode(0) - waitBaseRead(remoteRoot+"/reports/report.md", selectedContent) - waitBaseRead(remoteRoot+"/reports/continued.md", continuedContent) - waitBaseRead(remoteRoot+"/data/input.txt", seedData) - assertBaseAbsent(remoteRoot + "/reports/brief.md") - assertBaseAbsent(remoteRoot + "/reports/longform.md") - assertBaseAbsent(parentLatePath) + assertBaseAbsent(remoteRoot + "/seed.txt") + child := liveLayerID(t, runFS("fork-layer", "--parent-layer-ref", parent, "--layer-name", "child-"+suffix, "--ttl", "1h")) + layers = append(layers, child) + childMount := t.TempDir() + mountLayer(child, childMount) + waitLiveLocalFile(t, filepath.Join(childMount, "seed.txt"), suffix, 30*time.Second) + if err := os.WriteFile(filepath.Join(childMount, "trial.txt"), []byte("discard"), 0600); err != nil { + t.Fatal(err) + } + drain(childMount) + unmount(childMount) + runFS("delete-layer", "--layer-ref", child).wantExitCode(0) + layers[1] = "" + runFS("merge-layer", "--layer-ref", parent).wantExitCode(0) + layers[0] = "" + waitBaseRead(remoteRoot+"/seed.txt", suffix) + assertBaseAbsent(remoteRoot + "/trial.txt") } - -func copyLiveDirectoryTree(t *testing.T, sourceRoot, destinationRoot string) { +func liveLayerID(t *testing.T, res commandResult) string { t.Helper() - if err := filepath.Walk(sourceRoot, func(path string, info os.FileInfo, walkErr error) error { - if walkErr != nil { - return walkErr - } - relative, err := filepath.Rel(sourceRoot, path) - if err != nil { - return err - } - if relative == "." { - return nil - } - destination := filepath.Join(destinationRoot, relative) - if info.IsDir() { - return os.MkdirAll(destination, info.Mode().Perm()) - } - if !info.Mode().IsRegular() { - return fmt.Errorf("unsupported seed entry %s (%s)", path, info.Mode()) - } - data, err := os.ReadFile(path) - if err != nil { - return err - } - return os.WriteFile(destination, data, info.Mode().Perm()) - }); err != nil { - t.Fatalf("copy seed tree through layer mount: %v", err) + res.wantExitCode(0) + var layer apifs.FSLayer + if err := json.Unmarshal([]byte(res.stdout), &layer); err != nil || layer.LayerID == "" { + t.Fatalf("expected layer ID: %s (%v)", res.stdout, err) } + return layer.LayerID } diff --git a/e2e/live_test.go b/e2e/live_test.go index a5ba7167..0484cb9a 100644 --- a/e2e/live_test.go +++ b/e2e/live_test.go @@ -310,10 +310,10 @@ func TestLiveFSCommandSurface(t *testing.T) { {"fs", "read-file", "help"}, {"fs", "chmod-file", "help"}, {"fs", "create-symlink", "help"}, {"fs", "create-hardlink", "help"}, {"fs", "create-layer", "help"}, {"fs", "list-layers", "help"}, - {"fs", "fork-layer", "help"}, {"fs", "list-layer-chain", "help"}, - {"fs", "describe-layer", "help"}, {"fs", "diff-layer", "help"}, - {"fs", "create-layer-checkpoint", "help"}, {"fs", "delete-layer", "help"}, {"fs", "rollback-layer", "help"}, - {"fs", "commit-layer", "help"}, {"fs", "pack-file-system", "help"}, + {"fs", "fork-layer", "help"}, + {"fs", "describe-layer", "help"}, + {"fs", "delete-layer", "help"}, + {"fs", "merge-layer", "help"}, {"fs", "pack-file-system", "help"}, {"fs", "unpack-file-system", "help"}, {"fs", "drain-file-system", "help"}, {"fs", "cp", "help"}, {"fs", "cat", "help"}, {"fs", "ls", "help"}, {"fs", "stat", "help"}, {"fs", "mv", "help"}, {"fs", "rm", "help"}, @@ -330,9 +330,9 @@ func TestLiveFSCommandSurface(t *testing.T) { {"fs", "delete-file-system", "--file-system-id", selected.FSTenantID, "--confirm-file-system-name", selectedDisplayName}, {"fs", "update-file-system-extract-configuration", "--file-system-id", selected.FSTenantID, "--media-type", "image", "--enabled", "false"}, {"fs", "update-file-system-embedding-configuration", "--file-system-id", selected.FSTenantID, "--enabled", "false"}, - {"fs", "create-layer", "--layer-id", "layer-1", "--base-root-path", "/workspace", "--layer-name", "dev"}, - {"fs", "create-layer-checkpoint", "--layer-id", "layer-1", "--checkpoint-id", "cp-1"}, - {"fs", "rollback-layer", "--layer-id", "layer-1"}, {"fs", "commit-layer", "--layer-id", "layer-1"}, + {"fs", "create-layer", "--base-root-path", "/workspace", "--layer-name", "dev"}, + {"fs", "fork-layer", "--parent-layer-ref", "test-parent", "--ttl", "1h"}, + {"fs", "delete-layer", "--layer-ref", "layer-1"}, {"fs", "commit-layer", "--layer-id", "layer-1"}, {"fs", "pack-file-system", "--local-root", "/tmp/ti-e2e-pack", "--remote-root", "/workspace", "--mount-profile", "portable"}, {"fs", "unpack-file-system", "--local-root", "/tmp/ti-e2e-pack", "--remote-root", "/workspace", "--mount-profile", "portable"}, {"fs", "mount-file-system", "--mount-path", "/tmp/ti-e2e-mount", "--driver", "webdav"}, @@ -971,16 +971,15 @@ func TestLiveFSDataPlaneLifecycle(t *testing.T) { readResumeUpload.fail("upload resume should preserve uploaded contents") } - layerID := "ti-e2e-layer-" + suffix - checkpointID := layerID + "-cp" + var layerID string layerClosed := false defer func() { - if layerClosed { + if layerID == "" || layerClosed { return } - rollback := runTI(t, bin, "--profile", profileName, "fs", "rollback-layer", "--layer-id", layerID) + rollback := runTI(t, bin, "--profile", profileName, "fs", "delete-layer", "--layer-ref", layerID) if rollback.exitCode != 0 && rollback.exitCode != 5 { - t.Logf("cleanup rollback failed for layer %s: exit=%d stdout=%s stderr=%s", layerID, rollback.exitCode, rollback.stdout, rollback.stderr) + t.Logf("cleanup deletion failed for layer %s: exit=%d stdout=%s stderr=%s", layerID, rollback.exitCode, rollback.stdout, rollback.stderr) } }() createLayer := runTI( @@ -988,16 +987,14 @@ func TestLiveFSDataPlaneLifecycle(t *testing.T) { bin, "--profile", profileName, "fs", "create-layer", - "--layer-id", layerID, "--base-root-path", rootPath, "--layer-name", "live-e2e-"+suffix, - "--durability-mode", "restore-safe", + "--ttl", "1h", "--actor-id", "ti-live-e2e", "--tag", "test=ti-e2e", "--tag", "suffix="+suffix, ) - createLayer.wantExitCode(0) - createLayer.wantStdoutContains(layerID) + layerID = liveLayerID(t, createLayer) listLayers := runTI(t, bin, "--profile", profileName, "fs", "list-layers", "--query", fmt.Sprintf("layers[?layer_id=='%s'].layer_id | [0]", layerID)) listLayers.wantExitCode(0) @@ -1017,48 +1014,12 @@ func TestLiveFSDataPlaneLifecycle(t *testing.T) { copyToLayer.wantExitCode(0) copyToLayer.wantStdoutContains(`"status"`) - diffLayer := runTI(t, bin, "--profile", profileName, "fs", "diff-layer", "--layer-id", layerID, "--output", "text") - diffLayer.wantExitCode(0) - diffLayer.wantStdoutContains(layerCopyPath) - - createCheckpoint := runTI(t, bin, "--profile", profileName, "fs", "create-layer-checkpoint", "--layer-id", layerID, "--checkpoint-id", checkpointID, "--label", "live-e2e") - createCheckpoint.wantExitCode(0) - createCheckpoint.wantStdoutContains(checkpointID) - - childID := layerID + "-child" - childDeleted := false - defer func() { - if childDeleted { - return - } - cleanup := runTI(t, bin, "--profile", profileName, "fs", "delete-layer", "--layer-ref", childID, "--cascade") - if cleanup.exitCode != 0 && cleanup.exitCode != 5 { - t.Logf("cleanup delete failed for child layer %s: exit=%d stdout=%s stderr=%s", childID, cleanup.exitCode, cleanup.stdout, cleanup.stderr) - } - }() - forkChild := runTI(t, bin, "--profile", profileName, "fs", "fork-layer", "--parent-layer-ref", layerID, "--layer-id", childID, "--layer-name", "live-e2e-child-"+suffix, "--checkpoint-id", checkpointID, "--actor-id", "ti-live-e2e-child") - forkChild.wantExitCode(0) - forkChild.wantStdoutContains(childID) - forkChild.wantStdoutContains(layerID) - - chain := runTI(t, bin, "--profile", profileName, "fs", "list-layer-chain", "--layer-ref", childID) - chain.wantExitCode(0) - chain.wantStdoutContains(`"layer_id": "` + layerID + `"`) - chain.wantStdoutContains(`"layer_id": "` + childID + `"`) - chainText := runTI(t, bin, "--profile", profileName, "fs", "list-layer-chain", "--layer-ref", childID, "--output", "text") - chainText.wantExitCode(0) - chainText.wantStdoutContains("PARENT_LAYER_ID") - - deleteChild := runTI(t, bin, "--profile", profileName, "fs", "delete-layer", "--layer-ref", childID) - deleteChild.wantExitCode(0) - deleteChild.wantStdoutContains(`"status": "abandoned"`) - childDeleted = true - describeDeletedChild := runTI(t, bin, "--profile", profileName, "fs", "describe-layer", "--layer-id", childID) - describeDeletedChild.wantExitCode(0) - describeDeletedChild.wantStdoutContains(`"state": "abandoned"`) - - waitLiveFSResult(t, bin, []string{"--profile", profileName, "fs", "find-files", "--path", rootPath, "--file-name-pattern", "copy-layer.txt", "--layer-id", layerID, "--limit", "5"}, layerCopyPath, 2*time.Minute, "find file inside layer") - + child := runTI(t, bin, "--profile", profileName, "fs", "fork-layer", "--parent-layer-ref", layerID, "--layer-name", "child-"+suffix, "--ttl", "1h") + childID := liveLayerID(t, child) + child.wantStdoutContains(layerID) + deletedChild := runTI(t, bin, "--profile", profileName, "fs", "delete-layer", "--layer-ref", childID) + deletedChild.wantExitCode(0) + deletedChild.wantStdoutContains("deleted") commitLayer := runTI(t, bin, "--profile", profileName, "fs", "commit-layer", "--layer-id", layerID) commitLayer.wantExitCode(0) commitLayer.wantStdoutContains(`"status"`) diff --git a/e2e/testdata/fake-drive9.go b/e2e/testdata/fake-drive9.go index f437f404..62f22ce6 100644 --- a/e2e/testdata/fake-drive9.go +++ b/e2e/testdata/fake-drive9.go @@ -104,27 +104,30 @@ func main() { return } if hasPrefix(args, "fs", "layer", "help") { - fmt.Println("usage: drive9 fs layer ") + fmt.Println("usage: drive9 fs layer ") return } if hasPrefix(args, "mount", "--help") { - fmt.Println("-layer string") - fmt.Println("-checkpoint string") + fmt.Println("-layer value") return } - if hasPrefix(args, "fs", "layer", "fork") { - _ = json.NewEncoder(os.Stdout).Encode(map[string]any{ - "layer_id": "child-id", "name": "child", "state": "active", "base_root_path": "/workspace", - "parent_layer_id": "parent-id", "origin_seq": 7, "origin_checkpoint_id": flagValue(args, "--checkpoint"), "root_layer_id": "root-id", "depth": 1, - }) - return - } - if hasPrefix(args, "fs", "layer", "chain") { - fmt.Println(`{"chain":[{"layer_id":"root-id","name":"root","state":"active","depth":0,"limit_seq":7,"base_root_path":"/workspace"},{"layer_id":"child-id","name":"child","state":"active","parent_layer_id":"root-id","origin_seq":7,"origin_checkpoint_id":"seed","depth":1,"limit_seq":7,"base_root_path":"/workspace"}]}`) - return - } - if hasPrefix(args, "fs", "layer", "delete") { - fmt.Println("ok") + if hasPrefix(args, "fs", "layer") { + layer := map[string]any{"layer_id": "child-id", "name": "child", "parent_layer_id": "parent-id", "base_root_path": "/workspace", "fence": 2, "snap_gen": 7} + switch args[2] { + case "inspect": + layer["layer_id"] = "layer_01jz0123456789abcdefghjkmn" + _ = json.NewEncoder(os.Stdout).Encode(layer) + case "create", "fork": + _ = json.NewEncoder(os.Stdout).Encode(layer) + case "ls": + _ = json.NewEncoder(os.Stdout).Encode(map[string]any{"layers": []any{layer}}) + case "merge": + _ = json.NewEncoder(os.Stdout).Encode(map[string]any{"layer_id": "child-id", "status": "merged", "applied_paths": 2}) + case "rm": + _ = json.NewEncoder(os.Stdout).Encode(map[string]any{"layer_id": "child-id", "status": "deleted"}) + default: + os.Exit(2) + } return } if hasPrefix(args, "create") { diff --git a/internal/api/fs/layer.go b/internal/api/fs/layer.go index fce150c9..e599313e 100644 --- a/internal/api/fs/layer.go +++ b/internal/api/fs/layer.go @@ -1,478 +1,22 @@ package fs -import ( - "context" - "encoding/json" - "errors" - "fmt" - "io" - "net/http" - "net/url" - "strconv" - "strings" - "time" - - "github.com/tidbcloud/ti-cli/internal/api" - "github.com/tidbcloud/ti-cli/internal/apperr" -) - -var ErrLayerCommitConflict = errors.New("fs layer commit conflict") - -type LayerCommitConflictError struct { - Commit FSLayerCommit -} - -func (e *LayerCommitConflictError) Error() string { - if e == nil { - return "" - } - return "fs layer commit conflict" -} - -func (e *LayerCommitConflictError) Is(target error) bool { - return target == ErrLayerCommitConflict -} - -type FSLayerCreateRequest struct { - LayerID string `json:"layer_id,omitempty"` - BaseRootPath string `json:"base_root_path"` - Name string `json:"name,omitempty"` - Tags map[string]string `json:"tags,omitempty"` - DurabilityMode string `json:"durability_mode,omitempty"` - ActorID string `json:"actor_id,omitempty"` -} +import "time" type FSLayer struct { - LayerID string `json:"layer_id"` - BaseRootPath string `json:"base_root_path"` - Name string `json:"name"` - Tags map[string]string `json:"tags,omitempty"` - State string `json:"state"` - DurabilityMode string `json:"durability_mode"` - ActorID string `json:"actor_id"` - DurableSeq int64 `json:"durable_seq"` - ParentLayerID string `json:"parent_layer_id,omitempty"` - OriginSeq int64 `json:"origin_seq,omitempty"` - OriginCheckpointID string `json:"origin_checkpoint_id,omitempty"` - RootLayerID string `json:"root_layer_id,omitempty"` - Depth int `json:"depth,omitempty"` - Origin string `json:"origin,omitempty"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - SealedAt *time.Time `json:"sealed_at,omitempty"` -} - -type FSLayerChainFrame struct { - LayerID string `json:"layer_id"` - Name string `json:"name"` - State string `json:"state"` - ParentLayerID string `json:"parent_layer_id,omitempty"` - OriginSeq int64 `json:"origin_seq,omitempty"` - OriginCheckpointID string `json:"origin_checkpoint_id,omitempty"` - Depth int `json:"depth,omitempty"` - RootLayerID string `json:"root_layer_id,omitempty"` - BaseRootPath string `json:"base_root_path,omitempty"` - CreatedAt time.Time `json:"created_at"` - LimitSeq int64 `json:"limit_seq"` -} - -type FSLayerEntry struct { - LayerID string `json:"layer_id"` - Path string `json:"path"` - ParentPath string `json:"parent_path"` - Name string `json:"name"` - Op string `json:"op"` - Kind string `json:"kind"` - BaseInodeID string `json:"base_inode_id"` - BaseRevision int64 `json:"base_revision"` - StorageType string `json:"storage_type"` - StorageRef string `json:"storage_ref"` - StorageRefHash string `json:"storage_ref_hash"` - StorageEncryptionMode string `json:"storage_encryption_mode"` - StorageEncryptionKeyID string `json:"storage_encryption_key_id"` - ChecksumSHA256 string `json:"checksum_sha256"` - SizeBytes int64 `json:"size_bytes"` - Mode uint32 `json:"mode"` - Content []byte `json:"content,omitempty"` - ContentText string `json:"content_text,omitempty"` - EntrySeq int64 `json:"entry_seq"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` -} - -type FSLayerEntryRequest struct { - Path string `json:"path"` - Op string `json:"op,omitempty"` - Kind string `json:"kind,omitempty"` - BaseInodeID string `json:"base_inode_id,omitempty"` - BaseRevision int64 `json:"base_revision,omitempty"` - StorageType string `json:"storage_type,omitempty"` - StorageRef string `json:"storage_ref,omitempty"` - StorageRefHash string `json:"storage_ref_hash,omitempty"` - StorageEncryptionMode string `json:"storage_encryption_mode,omitempty"` - StorageEncryptionKeyID string `json:"storage_encryption_key_id,omitempty"` - Content []byte `json:"content,omitempty"` - ContentType string `json:"content_type,omitempty"` - ContentText string `json:"content_text,omitempty"` - ChecksumSHA256 string `json:"checksum_sha256,omitempty"` - SizeBytes int64 `json:"size_bytes,omitempty"` - Mode uint32 `json:"mode,omitempty"` -} - -type FSLayerCommit struct { - Status string `json:"status"` - LayerID string `json:"layer_id"` - Applied int `json:"applied,omitempty"` - Conflicts []FSLayerCommitConflict `json:"conflicts,omitempty"` -} - -type FSLayerCommitConflict struct { - Path string `json:"path"` - Reason string `json:"reason"` - BaseRevision int64 `json:"base_revision,omitempty"` - WantRevision int64 `json:"want_revision,omitempty"` -} - -type FSLayerCheckpointRequest struct { - CheckpointID string `json:"checkpoint_id,omitempty"` - Label string `json:"label,omitempty"` -} - -type FSLayerCheckpoint struct { - CheckpointID string `json:"checkpoint_id"` - LayerID string `json:"layer_id"` - DurableSeq int64 `json:"durable_seq"` - Label string `json:"label"` - CreatedAt time.Time `json:"created_at"` -} - -type FSLayerEvent struct { - EventID string `json:"event_id"` - LayerID string `json:"layer_id"` - Seq int64 `json:"seq"` - ActorID string `json:"actor_id"` - Op string `json:"op"` - Path string `json:"path"` - CreatedAt time.Time `json:"created_at"` -} - -func (c *Client) CreateFSLayer(ctx context.Context, request FSLayerCreateRequest) (FSLayer, error) { - var response FSLayer - if err := c.doLayerJSON(ctx, http.MethodPost, "/v1/layers", request, &response); err != nil { - return FSLayer{}, err - } - return response, nil -} - -func (c *Client) ListFSLayers(ctx context.Context) ([]FSLayer, error) { - var response struct { - Layers []FSLayer `json:"layers"` - } - if err := c.doLayerJSON(ctx, http.MethodGet, "/v1/layers", nil, &response); err != nil { - return nil, err - } - if response.Layers == nil { - response.Layers = []FSLayer{} - } - return response.Layers, nil -} - -func (c *Client) GetFSLayer(ctx context.Context, layerID string) (FSLayer, error) { - if err := requireLayerID(layerID); err != nil { - return FSLayer{}, err - } - var response FSLayer - if err := c.doLayerJSON(ctx, http.MethodGet, "/v1/layers/"+url.PathEscape(layerID), nil, &response); err != nil { - return FSLayer{}, err - } - return response, nil -} - -func (c *Client) DiffFSLayer(ctx context.Context, layerID string) ([]FSLayerEntry, error) { - return c.fetchFSLayerDiff(ctx, layerID, nil, false) -} - -func (c *Client) DiffFSLayerAtSeq(ctx context.Context, layerID string, maxSeq int64) ([]FSLayerEntry, error) { - if maxSeq < 0 { - return nil, apperr.New("fs.invalid_layer_sequence", "usage", 2, "--max-seq must be non-negative") - } - return c.fetchFSLayerDiff(ctx, layerID, &maxSeq, false) -} - -func (c *Client) ReplayFSLayer(ctx context.Context, layerID string) ([]FSLayerEntry, error) { - return c.fetchFSLayerDiff(ctx, layerID, nil, true) -} - -func (c *Client) ReplayFSLayerAtSeq(ctx context.Context, layerID string, maxSeq int64) ([]FSLayerEntry, error) { - if maxSeq < 0 { - return nil, apperr.New("fs.invalid_layer_sequence", "usage", 2, "--max-seq must be non-negative") - } - return c.fetchFSLayerDiff(ctx, layerID, &maxSeq, true) -} - -func (c *Client) fetchFSLayerDiff(ctx context.Context, layerID string, maxSeq *int64, replay bool) ([]FSLayerEntry, error) { - if err := requireLayerID(layerID); err != nil { - return nil, err - } - values := url.Values{} - if maxSeq != nil { - values.Set("max_seq", strconv.FormatInt(*maxSeq, 10)) - } - if replay { - values.Set("replay", "1") - } - requestPath := "/v1/layers/" + url.PathEscape(layerID) + "/diff" - if encoded := values.Encode(); encoded != "" { - requestPath += "?" + encoded - } - var response struct { - Entries []FSLayerEntry `json:"entries"` - } - if err := c.doLayerJSON(ctx, http.MethodGet, requestPath, nil, &response); err != nil { - return nil, err - } - if response.Entries == nil { - response.Entries = []FSLayerEntry{} - } - return response.Entries, nil -} - -func (c *Client) UpsertFSLayerEntry(ctx context.Context, layerID string, request FSLayerEntryRequest) (FSLayerEntry, error) { - if err := requireLayerID(layerID); err != nil { - return FSLayerEntry{}, err - } - var response FSLayerEntry - if err := c.doLayerJSON(ctx, http.MethodPost, "/v1/layers/"+url.PathEscape(layerID)+"/entries", request, &response); err != nil { - return FSLayerEntry{}, err - } - return response, nil -} - -func (c *Client) UploadFSLayerFile(ctx context.Context, layerID, remotePath string, body io.Reader, size int64, baseRevision int64, mode uint32, hasMode bool) (FSLayerEntry, error) { - if err := requireLayerID(layerID); err != nil { - return FSLayerEntry{}, err - } - if strings.TrimSpace(remotePath) == "" { - return FSLayerEntry{}, apperr.New("fs.missing_layer_path", "usage", 2, "layer file path is required") - } - if size < 0 { - return FSLayerEntry{}, apperr.New("fs.invalid_layer_file_size", "usage", 2, "layer file size must be non-negative") - } - values := url.Values{} - values.Set("path", remotePath) - values.Set("size", strconv.FormatInt(size, 10)) - if baseRevision > 0 { - values.Set("base_revision", strconv.FormatInt(baseRevision, 10)) - } - if hasMode { - values.Set("mode", fmt.Sprintf("%o", mode&0o777)) - } - req, err := c.api.NewRequest(ctx, http.MethodPost, "/v1/layers/"+url.PathEscape(layerID)+"/objects?"+values.Encode(), nil) - if err != nil { - return FSLayerEntry{}, err - } - req.Body = io.NopCloser(body) - req.ContentLength = size - req.Header.Set("Content-Type", "application/octet-stream") - res, err := c.api.DoRaw(req) - if err != nil { - return FSLayerEntry{}, err - } - defer res.Body.Close() - var response FSLayerEntry - if err := json.NewDecoder(res.Body).Decode(&response); err != nil { - return FSLayerEntry{}, apperr.Wrap("api.decode_response", "api", 1, "decode fs layer object entry", err) - } - return response, nil -} - -func (c *Client) ReadFSLayerFile(ctx context.Context, layerID, remotePath string, maxSeq *int64) ([]byte, error) { - if err := requireLayerID(layerID); err != nil { - return nil, err - } - if strings.TrimSpace(remotePath) == "" { - return nil, apperr.New("fs.missing_layer_path", "usage", 2, "layer file path is required") - } - values := url.Values{} - values.Set("path", remotePath) - if maxSeq != nil { - if *maxSeq < 0 { - return nil, apperr.New("fs.invalid_layer_sequence", "usage", 2, "--max-seq must be non-negative") - } - values.Set("max_seq", strconv.FormatInt(*maxSeq, 10)) - } - req, err := c.api.NewRequest(ctx, http.MethodGet, "/v1/layers/"+url.PathEscape(layerID)+"/objects?"+values.Encode(), nil) - if err != nil { - return nil, err - } - res, err := c.api.DoRaw(req) - if err != nil { - return nil, err - } - defer res.Body.Close() - data, err := io.ReadAll(res.Body) - if err != nil { - return nil, apperr.Wrap("api.read_response", "runtime", 1, "read fs layer file response body", err) - } - return data, nil -} - -func (c *Client) GetFSLayerEntry(ctx context.Context, layerID, remotePath string) (FSLayerEntry, error) { - return c.getFSLayerEntry(ctx, layerID, remotePath, nil) -} - -func (c *Client) GetFSLayerEntryAtSeq(ctx context.Context, layerID, remotePath string, maxSeq int64) (FSLayerEntry, error) { - if maxSeq < 0 { - return FSLayerEntry{}, apperr.New("fs.invalid_layer_sequence", "usage", 2, "--max-seq must be non-negative") - } - return c.getFSLayerEntry(ctx, layerID, remotePath, &maxSeq) -} - -func (c *Client) getFSLayerEntry(ctx context.Context, layerID, remotePath string, maxSeq *int64) (FSLayerEntry, error) { - if err := requireLayerID(layerID); err != nil { - return FSLayerEntry{}, err - } - if strings.TrimSpace(remotePath) == "" { - return FSLayerEntry{}, apperr.New("fs.missing_layer_path", "usage", 2, "layer entry path is required") - } - values := url.Values{} - values.Set("path", remotePath) - if maxSeq != nil { - values.Set("max_seq", strconv.FormatInt(*maxSeq, 10)) - } - var response FSLayerEntry - if err := c.doLayerJSON(ctx, http.MethodGet, "/v1/layers/"+url.PathEscape(layerID)+"/entries?"+values.Encode(), nil, &response); err != nil { - return FSLayerEntry{}, err - } - return response, nil -} - -func (c *Client) CheckpointFSLayer(ctx context.Context, layerID string, request FSLayerCheckpointRequest) (FSLayerCheckpoint, error) { - if err := requireLayerID(layerID); err != nil { - return FSLayerCheckpoint{}, err - } - var response FSLayerCheckpoint - if err := c.doLayerJSON(ctx, http.MethodPost, "/v1/layers/"+url.PathEscape(layerID)+"/checkpoints", request, &response); err != nil { - return FSLayerCheckpoint{}, err - } - return response, nil -} - -func (c *Client) GetFSLayerCheckpoint(ctx context.Context, checkpointID string) (FSLayerCheckpoint, error) { - if strings.TrimSpace(checkpointID) == "" { - return FSLayerCheckpoint{}, apperr.New("fs.missing_layer_checkpoint_id", "usage", 2, "--checkpoint-id is required") - } - var response FSLayerCheckpoint - if err := c.doLayerJSON(ctx, http.MethodGet, "/v1/layer-checkpoints/"+url.PathEscape(checkpointID), nil, &response); err != nil { - return FSLayerCheckpoint{}, err - } - return response, nil -} - -func (c *Client) ListFSLayerEvents(ctx context.Context, layerID string, since int64) ([]FSLayerEvent, error) { - if err := requireLayerID(layerID); err != nil { - return nil, err - } - if since < 0 { - return nil, apperr.New("fs.invalid_layer_sequence", "usage", 2, "--since must be non-negative") - } - requestPath := "/v1/layers/" + url.PathEscape(layerID) + "/events" - if since > 0 { - values := url.Values{} - values.Set("since", strconv.FormatInt(since, 10)) - requestPath += "?" + values.Encode() - } - var response struct { - Events []FSLayerEvent `json:"events"` - } - if err := c.doLayerJSON(ctx, http.MethodGet, requestPath, nil, &response); err != nil { - return nil, err - } - if response.Events == nil { - response.Events = []FSLayerEvent{} - } - return response.Events, nil -} - -func (c *Client) RollbackFSLayer(ctx context.Context, layerID string) error { - return c.postFSLayerAction(ctx, layerID, "rollback") -} - -func (c *Client) CommitFSLayer(ctx context.Context, layerID string) (FSLayerCommit, error) { - if err := requireLayerID(layerID); err != nil { - return FSLayerCommit{}, err - } - req, err := c.api.NewRequest(ctx, http.MethodPost, "/v1/layers/"+url.PathEscape(layerID)+"/commit", map[string]any{}) - if err != nil { - return FSLayerCommit{}, err - } - res, err := c.api.DoRaw(req) - if err != nil { - var apiErr *api.Error - if errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusConflict { - var response FSLayerCommit - if decodeErr := json.Unmarshal([]byte(apiErr.Body), &response); decodeErr == nil && (response.Status != "" || len(response.Conflicts) > 0) { - return response, &LayerCommitConflictError{Commit: response} - } - } - return FSLayerCommit{}, err - } - defer res.Body.Close() - var response FSLayerCommit - if err := json.NewDecoder(res.Body).Decode(&response); err != nil { - return FSLayerCommit{}, apperr.Wrap("api.decode_response", "api", 1, "decode fs layer commit", err) - } - return response, nil -} - -func (c *Client) postFSLayerAction(ctx context.Context, layerID, action string) error { - if err := requireLayerID(layerID); err != nil { - return err - } - req, err := c.api.NewRequest(ctx, http.MethodPost, "/v1/layers/"+url.PathEscape(layerID)+"/"+url.PathEscape(action), map[string]any{}) - if err != nil { - return err - } - return c.api.DoJSON(req, nil) -} - -func (c *Client) GrepWithLayer(ctx context.Context, remotePath, pattern string, limit int32, layerID string) ([]SearchResult, error) { - values := url.Values{} - values.Set("grep", pattern) - if limit > 0 { - values.Set("limit", strconv.FormatInt(int64(limit), 10)) - } - if strings.TrimSpace(layerID) != "" { - values.Set("layer", strings.TrimSpace(layerID)) - } - req, err := c.api.NewRequest(ctx, http.MethodGet, fsPathWithRawQuery(remotePath, values.Encode()), nil) - if err != nil { - return nil, err - } - var response []SearchResult - if err := c.api.DoJSON(req, &response); err != nil { - return nil, err - } - if response == nil { - response = []SearchResult{} - } - return response, nil -} - -func (c *Client) doLayerJSON(ctx context.Context, method, requestPath string, body any, out any) error { - req, err := c.api.NewRequest(ctx, method, requestPath, body) - if err != nil { - return err - } - if err := c.api.DoJSON(req, out); err != nil { - return err - } - return nil -} - -func requireLayerID(layerID string) error { - if strings.TrimSpace(layerID) == "" { - return apperr.New("fs.missing_layer_id", "usage", 2, "--layer-id is required") - } - return nil + LayerID string `json:"layer_id"` + Name string `json:"name"` + BaseRootPath string `json:"base_root_path"` + ParentLayerID string `json:"parent_layer_id"` + ActorID string `json:"actor_id"` + State string `json:"state"` + SnapGen int64 `json:"snap_gen"` + Fence int64 `json:"fence"` + ExclusiveMountID string `json:"exclusive_mount_id"` + MountLeaseUntil *time.Time `json:"mount_lease_until"` + MountLeaseTTLMS int64 `json:"mount_lease_ttl_ms"` + MountExpired bool `json:"mount_expired"` + Tags map[string]string `json:"tags,omitempty"` + ExpiresAt *time.Time `json:"expires_at"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` } diff --git a/internal/api/fs/layer_test.go b/internal/api/fs/layer_test.go deleted file mode 100644 index f48100eb..00000000 --- a/internal/api/fs/layer_test.go +++ /dev/null @@ -1,198 +0,0 @@ -package fs - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "io" - "net/http" - "net/http/httptest" - "strings" - "testing" -) - -func TestFSLayerClientMethods(t *testing.T) { - var sawUpload bool - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch { - case r.Method == http.MethodPost && r.URL.Path == "/v1/layers": - var req FSLayerCreateRequest - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { - t.Fatalf("decode create layer request: %v", err) - } - if req.BaseRootPath != "/repo" || req.Name != "task" || req.Tags["task"] != "auth" { - t.Fatalf("unexpected create layer request: %#v", req) - } - _ = json.NewEncoder(w).Encode(FSLayer{LayerID: "layer-1", BaseRootPath: req.BaseRootPath, Name: req.Name, State: "active"}) - case r.Method == http.MethodGet && r.URL.Path == "/v1/layers": - _ = json.NewEncoder(w).Encode(map[string]any{"layers": []FSLayer{{LayerID: "layer-1", State: "active"}}}) - case r.Method == http.MethodGet && r.URL.Path == "/v1/layers/layer-1": - _ = json.NewEncoder(w).Encode(FSLayer{LayerID: "layer-1", State: "active"}) - case r.Method == http.MethodGet && r.URL.Path == "/v1/layers/layer-1/diff": - if r.URL.Query().Get("max_seq") == "7" && r.URL.Query().Get("replay") != "1" { - _ = json.NewEncoder(w).Encode(map[string]any{"entries": []FSLayerEntry{{LayerID: "layer-1", Path: "/repo/a.txt", EntrySeq: 7}}}) - return - } - if r.URL.Query().Get("replay") == "1" { - _ = json.NewEncoder(w).Encode(map[string]any{"entries": []FSLayerEntry{{LayerID: "layer-1", Path: "/repo/replay.txt", EntrySeq: 3}}}) - return - } - _ = json.NewEncoder(w).Encode(map[string]any{"entries": []FSLayerEntry{{LayerID: "layer-1", Path: "/repo/a.txt", EntrySeq: 1}}}) - case r.Method == http.MethodPost && r.URL.Path == "/v1/layers/layer-1/entries": - var req FSLayerEntryRequest - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { - t.Fatalf("decode layer entry request: %v", err) - } - if req.Path != "/repo/a.txt" || req.Op != "upsert" || string(req.Content) != "hello" { - t.Fatalf("unexpected layer entry request: %#v", req) - } - _ = json.NewEncoder(w).Encode(FSLayerEntry{LayerID: "layer-1", Path: req.Path, Op: req.Op, EntrySeq: 2}) - case r.Method == http.MethodPost && r.URL.Path == "/v1/layers/layer-1/objects": - sawUpload = true - if r.URL.Query().Get("path") != "/repo/upload.txt" || r.URL.Query().Get("mode") != "640" || r.URL.Query().Get("base_revision") != "2" { - t.Fatalf("unexpected upload query: %s", r.URL.RawQuery) - } - body, err := io.ReadAll(r.Body) - if err != nil { - t.Fatalf("read upload body: %v", err) - } - if string(body) != "upload bytes" { - t.Fatalf("unexpected upload body %q", body) - } - _ = json.NewEncoder(w).Encode(FSLayerEntry{LayerID: "layer-1", Path: "/repo/upload.txt", EntrySeq: 4, SizeBytes: int64(len(body))}) - case r.Method == http.MethodGet && r.URL.Path == "/v1/layers/layer-1/objects": - if r.URL.Query().Get("path") != "/repo/upload.txt" || r.URL.Query().Get("max_seq") != "4" { - t.Fatalf("unexpected read layer object query: %s", r.URL.RawQuery) - } - _, _ = w.Write([]byte("upload bytes")) - case r.Method == http.MethodGet && r.URL.Path == "/v1/layers/layer-1/entries": - if r.URL.Query().Get("path") != "/repo/a.txt" { - t.Fatalf("unexpected get entry query: %s", r.URL.RawQuery) - } - _ = json.NewEncoder(w).Encode(FSLayerEntry{LayerID: "layer-1", Path: "/repo/a.txt", EntrySeq: 2}) - case r.Method == http.MethodPost && r.URL.Path == "/v1/layers/layer-1/checkpoints": - _ = json.NewEncoder(w).Encode(FSLayerCheckpoint{CheckpointID: "cp-1", LayerID: "layer-1", DurableSeq: 4}) - case r.Method == http.MethodGet && r.URL.Path == "/v1/layer-checkpoints/cp-1": - _ = json.NewEncoder(w).Encode(FSLayerCheckpoint{CheckpointID: "cp-1", LayerID: "layer-1", DurableSeq: 4}) - case r.Method == http.MethodGet && r.URL.Path == "/v1/layers/layer-1/events": - if r.URL.Query().Get("since") != "3" { - t.Fatalf("unexpected events query: %s", r.URL.RawQuery) - } - _ = json.NewEncoder(w).Encode(map[string]any{"events": []FSLayerEvent{{LayerID: "layer-1", Seq: 4, Op: "upsert", Path: "/repo/a.txt"}}}) - case r.Method == http.MethodPost && r.URL.Path == "/v1/layers/layer-1/rollback": - w.WriteHeader(http.StatusNoContent) - case r.Method == http.MethodPost && r.URL.Path == "/v1/layers/layer-1/commit": - _ = json.NewEncoder(w).Encode(FSLayerCommit{Status: "committed", LayerID: "layer-1", Applied: 1}) - default: - t.Fatalf("unexpected request %s %s", r.Method, r.URL.RequestURI()) - } - })) - defer server.Close() - - client := testClient(t, server.URL) - layer, err := client.CreateFSLayer(context.Background(), FSLayerCreateRequest{BaseRootPath: "/repo", Name: "task", Tags: map[string]string{"task": "auth"}}) - if err != nil || layer.LayerID != "layer-1" { - t.Fatalf("CreateFSLayer = %#v, %v", layer, err) - } - layers, err := client.ListFSLayers(context.Background()) - if err != nil || len(layers) != 1 { - t.Fatalf("ListFSLayers = %#v, %v", layers, err) - } - if _, err := client.GetFSLayer(context.Background(), "layer-1"); err != nil { - t.Fatalf("GetFSLayer: %v", err) - } - if entries, err := client.DiffFSLayerAtSeq(context.Background(), "layer-1", 7); err != nil || entries[0].EntrySeq != 7 { - t.Fatalf("DiffFSLayerAtSeq = %#v, %v", entries, err) - } - if entries, err := client.ReplayFSLayer(context.Background(), "layer-1"); err != nil || entries[0].Path != "/repo/replay.txt" { - t.Fatalf("ReplayFSLayer = %#v, %v", entries, err) - } - if _, err := client.UpsertFSLayerEntry(context.Background(), "layer-1", FSLayerEntryRequest{Path: "/repo/a.txt", Op: "upsert", Content: []byte("hello")}); err != nil { - t.Fatalf("UpsertFSLayerEntry: %v", err) - } - if _, err := client.UploadFSLayerFile(context.Background(), "layer-1", "/repo/upload.txt", strings.NewReader("upload bytes"), int64(len("upload bytes")), 2, 0o640, true); err != nil { - t.Fatalf("UploadFSLayerFile: %v", err) - } - if !sawUpload { - t.Fatal("expected upload request") - } - maxSeq := int64(4) - data, err := client.ReadFSLayerFile(context.Background(), "layer-1", "/repo/upload.txt", &maxSeq) - if err != nil || string(data) != "upload bytes" { - t.Fatalf("ReadFSLayerFile = %q, %v", data, err) - } - if _, err := client.GetFSLayerEntry(context.Background(), "layer-1", "/repo/a.txt"); err != nil { - t.Fatalf("GetFSLayerEntry: %v", err) - } - if _, err := client.CheckpointFSLayer(context.Background(), "layer-1", FSLayerCheckpointRequest{CheckpointID: "cp-1"}); err != nil { - t.Fatalf("CheckpointFSLayer: %v", err) - } - if _, err := client.GetFSLayerCheckpoint(context.Background(), "cp-1"); err != nil { - t.Fatalf("GetFSLayerCheckpoint: %v", err) - } - if events, err := client.ListFSLayerEvents(context.Background(), "layer-1", 3); err != nil || len(events) != 1 { - t.Fatalf("ListFSLayerEvents = %#v, %v", events, err) - } - if err := client.RollbackFSLayer(context.Background(), "layer-1"); err != nil { - t.Fatalf("RollbackFSLayer: %v", err) - } - if commit, err := client.CommitFSLayer(context.Background(), "layer-1"); err != nil || commit.Status != "committed" { - t.Fatalf("CommitFSLayer = %#v, %v", commit, err) - } -} - -func TestCommitFSLayerReturnsConflictBody(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodPost || r.URL.Path != "/v1/layers/layer-1/commit" { - http.NotFound(w, r) - return - } - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusConflict) - _ = json.NewEncoder(w).Encode(FSLayerCommit{ - Status: "conflicted", - LayerID: "layer-1", - Conflicts: []FSLayerCommitConflict{{ - Path: "/repo/a.txt", - Reason: "base revision changed", - BaseRevision: 3, - WantRevision: 2, - }}, - }) - })) - defer server.Close() - - commit, err := testClient(t, server.URL).CommitFSLayer(context.Background(), "layer-1") - if !errors.Is(err, ErrLayerCommitConflict) { - t.Fatalf("CommitFSLayer err=%v, want ErrLayerCommitConflict", err) - } - if commit.Status != "conflicted" || len(commit.Conflicts) != 1 { - t.Fatalf("commit=%+v, want conflict body", commit) - } - if commit.Conflicts[0].Path != "/repo/a.txt" || commit.Conflicts[0].WantRevision != 2 { - t.Fatalf("conflict=%+v, want decoded conflict details", commit.Conflicts[0]) - } -} - -func TestGrepWithLayerPassesLayerQuery(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodGet || r.URL.Path != "/v1/fs/repo" { - t.Fatalf("unexpected request %s %s", r.Method, r.URL.RequestURI()) - } - if r.URL.Query().Get("grep") != "needle" || r.URL.Query().Get("layer") != "layer-1" { - t.Fatalf("unexpected grep query: %s", r.URL.RawQuery) - } - _, _ = io.Copy(io.Discard, bytes.NewReader(nil)) - _ = json.NewEncoder(w).Encode([]SearchResult{{Path: "/repo/a.txt"}}) - })) - defer server.Close() - - results, err := testClient(t, server.URL).GrepWithLayer(context.Background(), "/repo", "needle", 20, "layer-1") - if err != nil { - t.Fatalf("GrepWithLayer: %v", err) - } - if len(results) != 1 || results[0].Path != "/repo/a.txt" { - t.Fatalf("results=%#v", results) - } -} diff --git a/internal/authz/authz.go b/internal/authz/authz.go index d802d21c..089dd5b8 100644 --- a/internal/authz/authz.go +++ b/internal/authz/authz.go @@ -90,9 +90,9 @@ var commandPermissions = map[string]Permission{ "ti fs create-layer": FSFileWrite, "ti fs list-layers": FSFileRead, "ti fs describe-layer": FSFileRead, - "ti fs diff-layer": FSFileRead, - "ti fs create-layer-checkpoint": FSFileWrite, - "ti fs rollback-layer": FSFileWrite, + "ti fs fork-layer": FSFileWrite, + "ti fs delete-layer": FSFileWrite, + "ti fs merge-layer": FSFileWrite, "ti fs commit-layer": FSFileWrite, "ti fs pack-file-system": FSFileWrite, "ti fs unpack-file-system": FSFileRead, diff --git a/internal/cli/commands.go b/internal/cli/commands.go index f6bdd2ea..6ddae0c6 100644 --- a/internal/cli/commands.go +++ b/internal/cli/commands.go @@ -4,6 +4,7 @@ import ( "fmt" "io" "net/http" + "net/url" "os" "runtime" "strings" @@ -998,13 +999,9 @@ func newFSCommand(info version.Info) *cobra.Command { newFSCreateLayerCommand(info), newFSListLayersCommand(info), newFSForkLayerCommand(info), - newFSListLayerChainCommand(info), newFSDescribeLayerCommand(info), - newFSDiffLayerCommand(info), - newFSCreateLayerCheckpointCommand(info), newFSDeleteLayerCommand(info), - newFSRollbackLayerCommand(info), - newFSCommitLayerCommand(info), + newFSMergeLayerCommand(info), newFSPackFileSystemCommand(info), newFSUnpackFileSystemCommand(info), newFSMountFileSystemCommand(info), @@ -1809,9 +1806,9 @@ func newFSCopyFileCommand(info version.Info) *cobra.Command { cmd.Flags().Bool("overwrite", false, "Replace an existing destination: an upload or a download overwrites it, and a server-side copy replaces it by moving a completed copy onto it.") cmd.Flags().Bool("create-parents", false, "Create missing local parent directories when copying from a TiDB Cloud file system.") cmd.Flags().Bool("append", false, "Append a local file content to a file in the TiDB Cloud file system.") - cmd.Flags().Bool("recursive", false, "Copy directory structure recursively; cannot be combined with --layer-id. Seed a layer through a writable FUSE mount instead.") + cmd.Flags().Bool("recursive", false, "Copy a directory tree recursively.") cmd.Flags().Bool("resume", false, "Resume an active copy operation.") - cmd.Flags().String("layer-id", "", "Write one copied file into a file system layer instead of the base file system; cannot be combined with --recursive.") + cmd.Flags().String("layer-id", "", "Copy within the selected layer, including recursive copies. Incompatible with --append and --description.") cmd.Flags().StringArray("tag", nil, "Create tag(s) key=value for --to-remote operation; repeatable.") cmd.Flags().String("description", "", "The file description for --to-remote operation.") return cmd @@ -2134,23 +2131,18 @@ func newFSSearchFileContentCommand(info version.Info) *cobra.Command { if err != nil { return nil, err } - layerID, err := ctx.StringFlag("layer-id") - if err != nil { - return nil, err - } return service.SearchFileContent(ctx.cmd.Context(), tifs.SearchFileContentOptions{ Profile: profile, Path: path, Pattern: pattern, Limit: limit, - LayerID: layerID, }) }, }, info) cmd.Flags().String("path", "/", "File path prefix to be searched.") cmd.Flags().String("pattern", "", "Content search matching pattern.") cmd.Flags().Int32("limit", 0, "Maximum number of search results; 0 uses the service default.") - cmd.Flags().String("layer-id", "", "Search within a file system layer.") + markUsageRequired(cmd, "pattern") return cmd } @@ -2178,7 +2170,7 @@ func newFSFindFilesCommand(info version.Info) *cobra.Command { cmd.Flags().String("file-name-pattern", "", "File name pattern filter, such as *.md.") cmd.Flags().String("resource-type", "", "Resource type filter: file or directory.") cmd.Flags().String("tag", "", "Tag filter.") - cmd.Flags().String("layer-id", "", "Search files and directories within a specific file system layer.") + cmd.Flags().String("newer", "", "Only return files newer than the filter.") cmd.Flags().String("older", "", "Only return files older than the filter.") cmd.Flags().Int64("min-size-bytes", 0, "Minimum file size in bytes.") @@ -2217,22 +2209,25 @@ func newFSCreateLayerCommand(info version.Info) *cobra.Command { if err != nil { return dryrun.Result{}, err } + ttl, err := tifs.LayerTTLSeconds(opts.TTL) + if err != nil { + return dryrun.Result{}, err + } body := map[string]any{ - "layer_id": opts.LayerID, - "base_root_path": opts.BaseRootPath, - "name": opts.LayerName, - "tags": tags, - "durability_mode": opts.DurabilityMode, - "actor_id": opts.ActorID, + "base_root_path": opts.BaseRootPath, + "name": opts.LayerName, + "tags": tags, + "ttl_seconds": ttl, + "actor_id": opts.ActorID, } return service.DryRunLayerMutation(ctx.cmd.Context(), ctx.CommandPath(), "create_layer", "POST", "/v1/layers", body, profile, authz.FSFileWrite) }, }, info) - cmd.Flags().String("layer-id", "", "The layer ID. Normally it is generated by the service automatically.") + cmd.Flags().String("base-root-path", "", "Base root path in the TiDB Cloud file system.") cmd.Flags().String("layer-name", "", "The name of the layer.") cmd.Flags().StringArray("tag", nil, "Tag(s) for the layer, key=value; repeatable.") - cmd.Flags().String("durability-mode", "", "Layer durability mode, must be restore-safe.") + cmd.Flags().String("ttl", "", "Layer lifetime in seconds or as a duration (e.g. 1h).") cmd.Flags().String("actor-id", "", "Actor ID identifying the layer owner (for example, the agent name).") markUsageRequired(cmd, "base-root-path") return cmd @@ -2283,49 +2278,51 @@ func newFSForkLayerCommand(info version.Info) *cobra.Command { if err := tifs.ValidateLayerReference(opts.ParentLayerRef, "--parent-layer-ref"); err != nil { return dryrun.Result{}, err } - if opts.CheckpointID != "" { - if err := tifs.ValidateLayerReference(opts.CheckpointID, "--checkpoint-id"); err != nil { - return dryrun.Result{}, err - } + tags, err := tifs.ParseLayerTagsForDryRun(opts.Tags) + if err != nil { + return dryrun.Result{}, err } - return service.DryRunLayerMutation(ctx.cmd.Context(), ctx.CommandPath(), "fork_layer", "POST", "/v1/layers/"+opts.ParentLayerRef+"/fork", map[string]any{ - "layer_id": opts.LayerID, - "name": opts.LayerName, - "checkpoint_id": opts.CheckpointID, - "actor_id": opts.ActorID, + ttl, err := tifs.LayerTTLSeconds(opts.TTL) + if err != nil { + return dryrun.Result{}, err + } + return service.DryRunLayerMutation(ctx.cmd.Context(), ctx.CommandPath(), "fork_layer", "POST", "/v1/layers/"+url.PathEscape(strings.TrimSpace(opts.ParentLayerRef))+"/fork", map[string]any{ + "tags": tags, + "name": opts.LayerName, + "ttl_seconds": ttl, + "actor_id": opts.ActorID, }, profile, authz.FSFileWrite, tifs.LayerCapabilityFork) }, }, info) cmd.Flags().String("parent-layer-ref", "", "The parent layer ID, unique name, or supported tag reference.") - cmd.Flags().String("layer-id", "", "The child layer ID. Normally it is generated by the service automatically.") + cmd.Flags().String("layer-name", "", "The name of the child layer.") - cmd.Flags().String("checkpoint-id", "", "Pin the child to this checkpoint of the parent layer.") + cmd.Flags().String("ttl", "", "Child layer lifetime in seconds or as a duration (e.g. 1h).") + cmd.Flags().StringArray("tag", nil, "Layer tag key=value (repeatable).") cmd.Flags().String("actor-id", "", "Actor ID identifying the child layer owner.") markUsageRequired(cmd, "parent-layer-ref") return cmd } -func newFSListLayerChainCommand(info version.Info) *cobra.Command { - cmd := newControlPlaneCommand(controlPlaneCommandSpec{ - Use: "list-layer-chain", - Short: "List a file system layer ancestry chain. (preview)", - Mutation: readOnlyCommand, - Permission: authz.FSFileRead, - Run: func(ctx commandContext) (any, error) { - service, profile, err := fsServiceAndProfile(ctx) - if err != nil { - return nil, err - } - layerRef, err := ctx.StringFlag("layer-ref") - if err != nil { - return nil, err - } - return service.ListLayerChain(ctx.cmd.Context(), tifs.ListLayerChainOptions{Profile: profile, LayerRef: layerRef}) - }, - }, info) - cmd.Flags().String("layer-ref", "", "The layer ID, unique name, or supported tag reference.") - markUsageRequired(cmd, "layer-ref") - return cmd +func layerRefFlag(ctx commandContext) (string, error) { + ref, err := ctx.StringFlag("layer-ref") + if err != nil { + return "", err + } + if ref == "" { + ref, err = ctx.StringFlag("layer-id") + if err != nil { + return "", err + } + } + return ref, tifs.ValidateLayerReference(ref, "--layer-ref") +} + +func registerLayerRefFlags(cmd *cobra.Command) { + cmd.Flags().String("layer-ref", "", "Layer ID, unique name, or tag reference.") + cmd.Flags().String("layer-id", "", "Alias for --layer-ref.") + cmd.MarkFlagsMutuallyExclusive("layer-id", "layer-ref") + cmd.MarkFlagsOneRequired("layer-id", "layer-ref") } func newFSDescribeLayerCommand(info version.Info) *cobra.Command { @@ -2339,85 +2336,21 @@ func newFSDescribeLayerCommand(info version.Info) *cobra.Command { if err != nil { return nil, err } - layerID, err := ctx.StringFlag("layer-id") + layerID, err := layerRefFlag(ctx) if err != nil { return nil, err } return service.DescribeLayer(ctx.cmd.Context(), tifs.DescribeLayerOptions{Profile: profile, LayerID: layerID}) }, }, info) - cmd.Flags().String("layer-id", "", "The ID of the specified file system layer.") - markUsageRequired(cmd, "layer-id") - return cmd -} - -func newFSDiffLayerCommand(info version.Info) *cobra.Command { - cmd := newControlPlaneCommand(controlPlaneCommandSpec{ - Use: "diff-layer", - Short: "Show changed entries in a file system layer. (preview)", - Mutation: readOnlyCommand, - Permission: authz.FSFileRead, - Run: func(ctx commandContext) (any, error) { - service, profile, err := fsServiceAndProfile(ctx) - if err != nil { - return nil, err - } - opts, err := fsLayerEntriesOptions(ctx, profile) - if err != nil { - return nil, err - } - return service.DiffLayer(ctx.cmd.Context(), opts) - }, - }, info) - cmd.Flags().String("layer-id", "", "The ID of the layer.") - cmd.Flags().Int64("max-seq", 0, "The highest layer sequence to include; 0 includes all layers.") - markUsageRequired(cmd, "layer-id") - return cmd -} - -func newFSCreateLayerCheckpointCommand(info version.Info) *cobra.Command { - cmd := newControlPlaneCommand(controlPlaneCommandSpec{ - Use: "create-layer-checkpoint", - Short: "Create a layer checkpoint. (preview)", - Mutation: mutatingCommand, - Permission: authz.FSFileWrite, - Run: func(ctx commandContext) (any, error) { - service, profile, err := fsServiceAndProfile(ctx) - if err != nil { - return nil, err - } - opts, err := fsCreateLayerCheckpointOptions(ctx, profile) - if err != nil { - return nil, err - } - return service.CreateLayerCheckpoint(ctx.cmd.Context(), opts) - }, - DryRun: func(ctx commandContext) (dryrun.Result, error) { - service, profile, err := fsServiceAndProfile(ctx) - if err != nil { - return dryrun.Result{}, err - } - opts, err := fsCreateLayerCheckpointOptions(ctx, profile) - if err != nil { - return dryrun.Result{}, err - } - return service.DryRunLayerMutation(ctx.cmd.Context(), ctx.CommandPath(), "create_layer_checkpoint", "POST", "/v1/layers/"+opts.LayerID+"/checkpoints", map[string]any{ - "checkpoint_id": opts.CheckpointID, - "label": opts.Label, - }, profile, authz.FSFileWrite) - }, - }, info) - cmd.Flags().String("layer-id", "", "The layer ID identifying the layer.") - cmd.Flags().String("checkpoint-id", "", "Checkpoint ID. Normally it is generated by the service automatically.") - cmd.Flags().String("label", "", "The checkpoint label.") - markUsageRequired(cmd, "layer-id") + registerLayerRefFlags(cmd) return cmd } func newFSDeleteLayerCommand(info version.Info) *cobra.Command { cmd := newControlPlaneCommand(controlPlaneCommandSpec{ Use: "delete-layer", - Short: "Abandon a file system layer. (preview)", + Short: "Delete a file system layer. (preview)", Mutation: mutatingCommand, Permission: authz.FSFileWrite, Run: func(ctx commandContext) (any, error) { @@ -2443,53 +2376,24 @@ func newFSDeleteLayerCommand(info version.Info) *cobra.Command { if err := tifs.ValidateLayerReference(opts.LayerRef, "--layer-ref"); err != nil { return dryrun.Result{}, err } - return service.DryRunLayerMutation(ctx.cmd.Context(), ctx.CommandPath(), "delete_layer", "DELETE", fmt.Sprintf("/v1/layers/%s?cascade=%t", opts.LayerRef, opts.Cascade), nil, profile, authz.FSFileWrite, tifs.LayerCapabilityDelete) + path := "/v1/layers/" + url.PathEscape(strings.TrimSpace(opts.LayerRef)) + if opts.Force { + path += "?force=true" + } + return service.DryRunLayerMutation(ctx.cmd.Context(), ctx.CommandPath(), "delete_layer", "DELETE", path, nil, profile, authz.FSFileWrite, tifs.LayerCapabilityDelete) }, }, info) cmd.Flags().String("layer-ref", "", "The layer ID, unique name, or supported tag reference.") - cmd.Flags().Bool("cascade", false, "Abandon live descendants before abandoning this layer.") + cmd.Flags().Bool("force", false, "Delete even when the layer is exclusively mounted.") markUsageRequired(cmd, "layer-ref") return cmd } -func newFSRollbackLayerCommand(info version.Info) *cobra.Command { - cmd := newControlPlaneCommand(controlPlaneCommandSpec{ - Use: "rollback-layer", - Short: "Rollback a file system layer. (preview)", - Mutation: mutatingCommand, - Permission: authz.FSFileWrite, - Run: func(ctx commandContext) (any, error) { - service, profile, err := fsServiceAndProfile(ctx) - if err != nil { - return nil, err - } - layerID, err := ctx.StringFlag("layer-id") - if err != nil { - return nil, err - } - return service.RollbackLayer(ctx.cmd.Context(), tifs.LayerActionOptions{Profile: profile, LayerID: layerID}) - }, - DryRun: func(ctx commandContext) (dryrun.Result, error) { - service, profile, err := fsServiceAndProfile(ctx) - if err != nil { - return dryrun.Result{}, err - } - layerID, err := ctx.StringFlag("layer-id") - if err != nil { - return dryrun.Result{}, err - } - return service.DryRunLayerMutation(ctx.cmd.Context(), ctx.CommandPath(), "rollback_layer", "POST", "/v1/layers/"+layerID+"/rollback", nil, profile, authz.FSFileWrite) - }, - }, info) - cmd.Flags().String("layer-id", "", "The ID of the layer.") - markUsageRequired(cmd, "layer-id") - return cmd -} - -func newFSCommitLayerCommand(info version.Info) *cobra.Command { +func newFSMergeLayerCommand(info version.Info) *cobra.Command { cmd := newControlPlaneCommand(controlPlaneCommandSpec{ - Use: "commit-layer", - Short: "Commit a layer into the base file system. (preview)", + Use: "merge-layer", + Aliases: []string{"commit-layer"}, + Short: "Merge a layer into the base file system. (preview)", Mutation: mutatingCommand, Permission: authz.FSFileWrite, Run: func(ctx commandContext) (any, error) { @@ -2497,26 +2401,25 @@ func newFSCommitLayerCommand(info version.Info) *cobra.Command { if err != nil { return nil, err } - layerID, err := ctx.StringFlag("layer-id") + layerID, err := layerRefFlag(ctx) if err != nil { return nil, err } - return service.CommitLayer(ctx.cmd.Context(), tifs.LayerActionOptions{Profile: profile, LayerID: layerID}) + return service.MergeLayer(ctx.cmd.Context(), tifs.LayerActionOptions{Profile: profile, LayerID: layerID}) }, DryRun: func(ctx commandContext) (dryrun.Result, error) { service, profile, err := fsServiceAndProfile(ctx) if err != nil { return dryrun.Result{}, err } - layerID, err := ctx.StringFlag("layer-id") + layerID, err := layerRefFlag(ctx) if err != nil { return dryrun.Result{}, err } - return service.DryRunLayerMutation(ctx.cmd.Context(), ctx.CommandPath(), "commit_layer", "POST", "/v1/layers/"+layerID+"/commit", map[string]any{}, profile, authz.FSFileWrite) + return service.DryRunLayerMutation(ctx.cmd.Context(), ctx.CommandPath(), "merge_layer", "POST", "/v1/layers/"+url.PathEscape(strings.TrimSpace(layerID))+"/merge", map[string]any{}, profile, authz.FSFileWrite, tifs.LayerCapabilityMerge) }, }, info) - cmd.Flags().String("layer-id", "", "ti fs layer id") - markUsageRequired(cmd, "layer-id") + registerLayerRefFlags(cmd) return cmd } @@ -2637,14 +2540,13 @@ func newFSMountFileSystemCommand(info version.Info) *cobra.Command { cmd.Flags().Int64("read-cache-max-file-mb", 4, "Maximum file size admitted to the FUSE read cache in MiB. 0 uses the default.") cmd.Flags().Duration("read-cache-ttl", 30*time.Second, "FUSE read cache Time-to-Live.") cmd.Flags().String("durability", tifs.DefaultMountDurability, "Write durability: auto, interactive, fsync, close-sync, or write-sync. FUSE only; WebDAV mounts reject every tier except auto.") - cmd.Flags().Bool("write-back-cache", true, "Legacy alias: true selects --durability=interactive and false selects --durability=auto. Unavailable for checkpoint mounts.") + cmd.Flags().Bool("write-back-cache", true, "Legacy alias: true selects --durability=interactive and false selects --durability=auto.") cmd.Flags().String("mount-profile", "", "Mount profile: coding-agent, portable, or none. Default: none.") cmd.Flags().String("local-root", "", "Local overlay root. Default: ~/.ti/local/fs/.") cmd.Flags().StringArray("pack-path", nil, "Local overlay path to include in the automatic pack written at unmount; the path must exist in the local overlay, and WebDAV mounts cannot use it. Repeatable.") cmd.Flags().String("unpack-archive-path", "", "Restore the pack archive before mounting.") cmd.Flags().Bool("no-auto-unpack", false, "Skip default auto-unpack for portable mount profile before mounting.") cmd.Flags().String("layer-ref", "", "Mount through this writable layer ID, unique name, or supported tag reference; requires FUSE.") - cmd.Flags().String("checkpoint-id", "", "Mount this checkpoint of --layer-ref read-only; requires FUSE.") markUsageRequired(cmd, "mount-path") return cmd } @@ -2946,10 +2848,6 @@ func fsFindFilesOptions(ctx commandContext, profile *config.Profile) (tifs.FindF if err != nil { return tifs.FindFilesOptions{}, err } - layerID, err := ctx.StringFlag("layer-id") - if err != nil { - return tifs.FindFilesOptions{}, err - } newer, err := ctx.StringFlag("newer") if err != nil { return tifs.FindFilesOptions{}, err @@ -2976,7 +2874,6 @@ func fsFindFilesOptions(ctx commandContext, profile *config.Profile) (tifs.FindF FileNamePattern: fileNamePattern, ResourceType: resourceType, Tag: tag, - LayerID: layerID, Newer: newer, Older: older, MinSizeBytes: minSizeBytes, @@ -2986,10 +2883,6 @@ func fsFindFilesOptions(ctx commandContext, profile *config.Profile) (tifs.FindF } func fsCreateLayerOptions(ctx commandContext, profile *config.Profile) (tifs.CreateLayerOptions, error) { - layerID, err := ctx.StringFlag("layer-id") - if err != nil { - return tifs.CreateLayerOptions{}, err - } baseRootPath, err := ctx.StringFlag("base-root-path") if err != nil { return tifs.CreateLayerOptions{}, err @@ -3002,7 +2895,7 @@ func fsCreateLayerOptions(ctx commandContext, profile *config.Profile) (tifs.Cre if err != nil { return tifs.CreateLayerOptions{}, err } - durabilityMode, err := ctx.StringFlag("durability-mode") + ttl, err := ctx.StringFlag("ttl") if err != nil { return tifs.CreateLayerOptions{}, err } @@ -3011,50 +2904,12 @@ func fsCreateLayerOptions(ctx commandContext, profile *config.Profile) (tifs.Cre return tifs.CreateLayerOptions{}, err } return tifs.CreateLayerOptions{ - Profile: profile, - LayerID: layerID, - BaseRootPath: baseRootPath, - LayerName: layerName, - Tags: tags, - DurabilityMode: durabilityMode, - ActorID: actorID, - }, nil -} - -func fsLayerEntriesOptions(ctx commandContext, profile *config.Profile) (tifs.LayerEntriesOptions, error) { - layerID, err := ctx.StringFlag("layer-id") - if err != nil { - return tifs.LayerEntriesOptions{}, err - } - maxSeq, err := ctx.Int64Flag("max-seq") - if err != nil { - return tifs.LayerEntriesOptions{}, err - } - return tifs.LayerEntriesOptions{ - Profile: profile, - LayerID: layerID, - MaxSeq: maxSeq, - }, nil -} - -func fsCreateLayerCheckpointOptions(ctx commandContext, profile *config.Profile) (tifs.CreateLayerCheckpointOptions, error) { - layerID, err := ctx.StringFlag("layer-id") - if err != nil { - return tifs.CreateLayerCheckpointOptions{}, err - } - checkpointID, err := ctx.StringFlag("checkpoint-id") - if err != nil { - return tifs.CreateLayerCheckpointOptions{}, err - } - label, err := ctx.StringFlag("label") - if err != nil { - return tifs.CreateLayerCheckpointOptions{}, err - } - return tifs.CreateLayerCheckpointOptions{ Profile: profile, - LayerID: layerID, - CheckpointID: checkpointID, - Label: label, + BaseRootPath: baseRootPath, + LayerName: layerName, + Tags: tags, + TTL: ttl, + ActorID: actorID, }, nil } @@ -3063,7 +2918,7 @@ func fsForkLayerOptions(ctx commandContext, profile *config.Profile) (tifs.ForkL if err != nil { return tifs.ForkLayerOptions{}, err } - layerID, err := ctx.StringFlag("layer-id") + tags, err := ctx.StringArrayFlag("tag") if err != nil { return tifs.ForkLayerOptions{}, err } @@ -3071,7 +2926,7 @@ func fsForkLayerOptions(ctx commandContext, profile *config.Profile) (tifs.ForkL if err != nil { return tifs.ForkLayerOptions{}, err } - checkpointID, err := ctx.StringFlag("checkpoint-id") + ttl, err := ctx.StringFlag("ttl") if err != nil { return tifs.ForkLayerOptions{}, err } @@ -3079,7 +2934,7 @@ func fsForkLayerOptions(ctx commandContext, profile *config.Profile) (tifs.ForkL if err != nil { return tifs.ForkLayerOptions{}, err } - return tifs.ForkLayerOptions{Profile: profile, ParentLayerRef: parentLayerRef, LayerID: layerID, LayerName: layerName, CheckpointID: checkpointID, ActorID: actorID}, nil + return tifs.ForkLayerOptions{Profile: profile, ParentLayerRef: parentLayerRef, Tags: tags, LayerName: layerName, TTL: ttl, ActorID: actorID}, nil } func fsDeleteLayerOptions(ctx commandContext, profile *config.Profile) (tifs.DeleteLayerOptions, error) { @@ -3087,11 +2942,11 @@ func fsDeleteLayerOptions(ctx commandContext, profile *config.Profile) (tifs.Del if err != nil { return tifs.DeleteLayerOptions{}, err } - cascade, err := ctx.BoolFlag("cascade") + force, err := ctx.BoolFlag("force") if err != nil { return tifs.DeleteLayerOptions{}, err } - return tifs.DeleteLayerOptions{Profile: profile, LayerRef: layerRef, Cascade: cascade}, nil + return tifs.DeleteLayerOptions{Profile: profile, LayerRef: layerRef, Force: force}, nil } func fsMountOptions(ctx commandContext, profile *config.Profile) (tifs.MountFileSystemOptions, error) { @@ -3167,10 +3022,6 @@ func fsMountOptions(ctx commandContext, profile *config.Profile) (tifs.MountFile if err != nil { return tifs.MountFileSystemOptions{}, err } - checkpointID, err := ctx.StringFlag("checkpoint-id") - if err != nil { - return tifs.MountFileSystemOptions{}, err - } return tifs.MountFileSystemOptions{ Profile: profile, FileSystemName: fileSystemID, @@ -3178,7 +3029,6 @@ func fsMountOptions(ctx commandContext, profile *config.Profile) (tifs.MountFile RemotePath: remotePath, Driver: driver, ReadOnly: readOnly, - ReadOnlySet: ctx.FlagChanged("read-only"), ReadyTimeout: readyTimeout, CacheDir: cacheDir, ReadCacheMB: readCacheMB, @@ -3194,7 +3044,6 @@ func fsMountOptions(ctx commandContext, profile *config.Profile) (tifs.MountFile UnpackArchivePath: unpackArchivePath, NoAutoUnpack: noAutoUnpack, LayerRef: layerRef, - CheckpointID: checkpointID, }, nil } diff --git a/internal/fs/data.go b/internal/fs/data.go index ba722d38..94468a83 100644 --- a/internal/fs/data.go +++ b/internal/fs/data.go @@ -99,7 +99,6 @@ type SearchFileContentOptions struct { Path string Pattern string Limit int32 - LayerID string } type FindFilesOptions struct { @@ -108,7 +107,6 @@ type FindFilesOptions struct { FileNamePattern string ResourceType string Tag string - LayerID string Newer string Older string MinSizeBytes int64 @@ -640,9 +638,7 @@ func validateCopyMetadataFlags(opts CopyFileOptions) error { if strings.TrimSpace(opts.FromRemote) != "" { return apperr.New("fs.invalid_copy_flags", "usage", 2, "--tag and --description are only supported for local or stdin uploads") } - if opts.LayerID != "" { - return apperr.New("fs.invalid_copy_flags", "usage", 2, "--tag and --description cannot be combined with --layer-id") - } + return nil } diff --git a/internal/fs/drive9_companion.go b/internal/fs/drive9_companion.go index 9d2460e8..70d0b3bc 100644 --- a/internal/fs/drive9_companion.go +++ b/internal/fs/drive9_companion.go @@ -53,11 +53,10 @@ type drive9CommandResult struct { } const ( - drive9CapabilityLayerFork = "layer-fork" - drive9CapabilityLayerChain = "layer-chain" - drive9CapabilityLayerDelete = "layer-delete" - drive9CapabilityLayerMount = "layer-mount" - drive9CapabilityCheckpointMount = "checkpoint-mount" + drive9CapabilityLayerFork = "layer-fork" + drive9CapabilityLayerMerge = "layer-merge" + drive9CapabilityLayerDelete = "layer-delete" + drive9CapabilityLayerMount = "layer-mount" ) func (s Service) drive9Runner() fswrap.Runner { @@ -87,9 +86,9 @@ func (s Service) requireDrive9Capabilities(ctx context.Context, profile *config. needMountHelp := false for _, capability := range capabilities { switch capability { - case drive9CapabilityLayerFork, drive9CapabilityLayerChain, drive9CapabilityLayerDelete: + case drive9CapabilityLayerFork, drive9CapabilityLayerMerge, drive9CapabilityLayerDelete: needLayerHelp = true - case drive9CapabilityLayerMount, drive9CapabilityCheckpointMount: + case drive9CapabilityLayerMount: needMountHelp = true default: return apperr.New("fs.companion_capability_unknown", "runtime", 1, fmt.Sprintf("unknown ti fs companion capability %q", capability)) @@ -118,14 +117,12 @@ func (s Service) requireDrive9Capabilities(ctx context.Context, profile *config. switch capability { case drive9CapabilityLayerFork: available = layerHelpHasCommand(layerHelp, "fork") - case drive9CapabilityLayerChain: - available = layerHelpHasCommand(layerHelp, "chain") + case drive9CapabilityLayerMerge: + available = layerHelpHasCommand(layerHelp, "merge") case drive9CapabilityLayerDelete: - available = layerHelpHasCommand(layerHelp, "delete") + available = layerHelpHasCommand(layerHelp, "rm") case drive9CapabilityLayerMount: - available = strings.Contains(mountHelp, "-layer string") || strings.Contains(mountHelp, "--layer string") - case drive9CapabilityCheckpointMount: - available = strings.Contains(mountHelp, "-checkpoint string") || strings.Contains(mountHelp, "--checkpoint string") + available = layerHelpHasCommand(mountHelp, "-layer") || layerHelpHasCommand(mountHelp, "--layer") } if !available { return incompatibleDrive9Error(nil) @@ -586,9 +583,6 @@ func (s Service) drive9SearchFileContent(ctx context.Context, opts SearchFileCon return SearchFilesResult{}, apperr.New("fs.missing_pattern", "usage", 2, "--pattern is required") } args := []string{"fs", "grep"} - if strings.TrimSpace(opts.LayerID) != "" { - args = append(args, "--layer", strings.TrimSpace(opts.LayerID)) - } args = append(args, opts.Pattern, drive9Remote(remotePath)) result, err := s.drive9Run(ctx, opts.Profile, args, true) if err != nil { @@ -612,9 +606,6 @@ func (s Service) drive9FindFiles(ctx context.Context, opts FindFilesOptions) (Se if opts.Tag != "" { args = append(args, "-tag", opts.Tag) } - if opts.LayerID != "" { - args = append(args, "--layer", opts.LayerID) - } if opts.Newer != "" { args = append(args, "-newer", opts.Newer) } @@ -640,9 +631,8 @@ func (s Service) drive9CreateLayer(ctx context.Context, opts CreateLayerOptions) return LayerResult{}, err } args := []string{"fs", "layer", "create", "--json"} - appendFlagValue(&args, "--id", opts.LayerID) appendFlagValue(&args, "--name", opts.LayerName) - appendFlagValue(&args, "--durability", opts.DurabilityMode) + appendFlagValue(&args, "--ttl", opts.TTL) appendFlagValue(&args, "--actor", opts.ActorID) for _, tag := range opts.Tags { appendFlagValue(&args, "--tag", tag) @@ -660,7 +650,7 @@ func (s Service) drive9CreateLayer(ctx context.Context, opts CreateLayerOptions) } func (s Service) drive9ListLayers(ctx context.Context, opts ListLayersOptions) (LayerListResult, error) { - result, err := s.drive9RunTransientRetry(ctx, opts.Profile, []string{"fs", "layer", "list", "--json"}, true) + result, err := s.drive9RunTransientRetry(ctx, opts.Profile, []string{"fs", "layer", "ls", "--json"}, true) if err != nil { return LayerListResult{}, err } @@ -676,9 +666,11 @@ func (s Service) drive9ForkLayer(ctx context.Context, opts ForkLayerOptions) (La return LayerResult{}, err } args := []string{"fs", "layer", "fork", "--json"} - appendFlagValue(&args, "--id", opts.LayerID) appendFlagValue(&args, "--name", opts.LayerName) - appendFlagValue(&args, "--checkpoint", opts.CheckpointID) + appendFlagValue(&args, "--ttl", opts.TTL) + for _, tag := range opts.Tags { + appendFlagValue(&args, "--tag", tag) + } appendFlagValue(&args, "--actor", opts.ActorID) args = append(args, strings.TrimSpace(opts.ParentLayerRef)) result, err := s.drive9Run(ctx, opts.Profile, args, true) @@ -692,38 +684,28 @@ func (s Service) drive9ForkLayer(ctx context.Context, opts ForkLayerOptions) (La return LayerResult{FSLayer: layer}, nil } -func (s Service) drive9ListLayerChain(ctx context.Context, opts ListLayerChainOptions) (LayerChainResult, error) { - if err := s.requireDrive9Capabilities(ctx, opts.Profile, drive9CapabilityLayerChain); err != nil { - return LayerChainResult{}, err - } - result, err := s.drive9RunTransientRetry(ctx, opts.Profile, []string{"fs", "layer", "chain", "--json", strings.TrimSpace(opts.LayerRef)}, true) - if err != nil { - return LayerChainResult{}, err - } - var out LayerChainResult - if err := json.Unmarshal(result.Stdout, &out); err != nil { - return LayerChainResult{}, apperr.Wrap("fs.companion_decode", "runtime", 1, "decode ti fs layer chain response", err) - } - return out, nil -} - func (s Service) drive9DeleteLayer(ctx context.Context, opts DeleteLayerOptions) (DeleteLayerResult, error) { if err := s.requireDrive9Capabilities(ctx, opts.Profile, drive9CapabilityLayerDelete); err != nil { return DeleteLayerResult{}, err } - args := []string{"fs", "layer", "delete"} - if opts.Cascade { - args = append(args, "--cascade") + args := []string{"fs", "layer", "rm", "--json"} + if opts.Force { + args = append(args, "--force") } args = append(args, strings.TrimSpace(opts.LayerRef)) - if _, err := s.drive9Run(ctx, opts.Profile, args, true); err != nil { + result, err := s.drive9Run(ctx, opts.Profile, args, true) + if err != nil { return DeleteLayerResult{}, err } - return DeleteLayerResult{Operation: "delete_layer", LayerRef: strings.TrimSpace(opts.LayerRef), Status: "abandoned", Cascade: opts.Cascade}, nil + var out DeleteLayerResult + if err := json.Unmarshal(result.Stdout, &out); err != nil { + return out, apperr.Wrap("fs.companion_decode", "runtime", 1, "decode ti fs layer deletion", err) + } + return out, nil } func (s Service) drive9DescribeLayer(ctx context.Context, opts DescribeLayerOptions) (LayerResult, error) { - result, err := s.drive9RunTransientRetry(ctx, opts.Profile, []string{"fs", "layer", "status", "--json", strings.TrimSpace(opts.LayerID)}, true) + result, err := s.drive9RunTransientRetry(ctx, opts.Profile, []string{"fs", "layer", "inspect", "--json", strings.TrimSpace(opts.LayerID)}, true) if err != nil { return LayerResult{}, err } @@ -734,62 +716,21 @@ func (s Service) drive9DescribeLayer(ctx context.Context, opts DescribeLayerOpti return LayerResult{FSLayer: layer}, nil } -func (s Service) drive9DiffLayer(ctx context.Context, opts LayerEntriesOptions) (LayerEntriesResult, error) { - layerID := strings.TrimSpace(opts.LayerID) - result, err := s.drive9RunTransientRetry(ctx, opts.Profile, []string{"fs", "layer", "diff", "--json", layerID}, true) +func (s Service) MergeLayer(ctx context.Context, opts LayerActionOptions) (LayerMergeResult, error) { + if err := s.requireDrive9Capabilities(ctx, opts.Profile, drive9CapabilityLayerMerge); err != nil { + return LayerMergeResult{}, err + } + result, err := s.drive9Run(ctx, opts.Profile, []string{"fs", "layer", "merge", "--json", opts.LayerID}, true) if err != nil { - return LayerEntriesResult{}, err + return LayerMergeResult{}, err } - var out LayerEntriesResult + var out LayerMergeResult if err := json.Unmarshal(result.Stdout, &out); err != nil { - return LayerEntriesResult{}, apperr.Wrap("fs.companion_decode", "runtime", 1, "decode ti fs layer diff response", err) - } - out.LayerID = layerID - if opts.MaxSeq > 0 { - filtered := out.Entries[:0] - for _, entry := range out.Entries { - if entry.EntrySeq <= opts.MaxSeq { - filtered = append(filtered, entry) - } - } - out.Entries = filtered + return out, apperr.Wrap("fs.companion_decode", "runtime", 1, "decode ti fs layer merge", err) } return out, nil } -func (s Service) drive9CreateLayerCheckpoint(ctx context.Context, opts CreateLayerCheckpointOptions) (LayerCheckpointResult, error) { - args := []string{"fs", "layer", "checkpoint", "--json"} - appendFlagValue(&args, "--id", opts.CheckpointID) - appendFlagValue(&args, "--label", opts.Label) - args = append(args, strings.TrimSpace(opts.LayerID)) - result, err := s.drive9RunTransientRetry(ctx, opts.Profile, args, true) - if err != nil { - return LayerCheckpointResult{}, err - } - var checkpoint apifs.FSLayerCheckpoint - if err := json.Unmarshal(result.Stdout, &checkpoint); err != nil { - return LayerCheckpointResult{}, apperr.Wrap("fs.companion_decode", "runtime", 1, "decode ti fs layer checkpoint response", err) - } - return LayerCheckpointResult{FSLayerCheckpoint: checkpoint}, nil -} - -func (s Service) drive9RollbackLayer(ctx context.Context, opts LayerActionOptions) (LayerActionResult, error) { - layerID := strings.TrimSpace(opts.LayerID) - if _, err := s.drive9Run(ctx, opts.Profile, []string{"fs", "layer", "rollback", layerID}, true); err != nil { - return LayerActionResult{}, err - } - return LayerActionResult{Operation: "rollback_layer", LayerID: layerID, Status: "rolled_back"}, nil -} - -func (s Service) drive9CommitLayer(ctx context.Context, opts LayerActionOptions) (LayerCommitResult, error) { - layerID := strings.TrimSpace(opts.LayerID) - result, err := s.drive9Run(ctx, opts.Profile, []string{"fs", "layer", "commit", layerID}, true) - if err != nil { - return LayerCommitResult{}, err - } - return LayerCommitResult{FSLayerCommit: parseDrive9LayerCommit(layerID, result.Stdout)}, nil -} - func (s Service) drive9GitCloneWorkspace(ctx context.Context, opts GitWorkspaceCloneOptions) (GitWorkspaceCloneResult, error) { args := []string{"git", "clone", "--fast"} if opts.Blobless { @@ -1456,10 +1397,11 @@ func replayablePackPaths(locator mountlocator.Locator) ([]string, []MountRuntime Message: "the mount did not record the local overlay root it packs from, so ti cannot verify the recorded --pack-path values and does not replay them", }} } + localRoot := layerLocalRoot(locator.LocalRoot, locator.LayerID) kept := make([]string, 0, len(locator.PackPaths)) var checks []MountRuntimeCheck for _, packPath := range locator.PackPaths { - overlayPath := mountPackOverlayPath(locator.LocalRoot, mountPackArchivePath(locator.RemotePath, packPath)) + overlayPath := mountPackOverlayPath(localRoot, mountPackArchivePath(locator.RemotePath, packPath)) // The companion normalizes the archive path to NFC and this check compares // raw bytes, so a name in another normalization form is either skipped // here or replayed and then not found by the pack after the detach. ti @@ -1495,13 +1437,13 @@ func (s Service) writeDrive9MountLocator(profile *config.Profile, mountPath, kin } locator = locator.WithTokenCorrelation(profile.FSTenantID, profile.FSTokenID, fsTokenFingerprint(profile.FSAPIKey)).WithServiceAddress(profile.FSServiceAddress).WithDriver(driver) if opts != nil { - locator = locator.WithLayerView(opts.RemotePath, opts.LayerRef, opts.CheckpointID, opts.ReadOnly) + locator = locator.WithLayerView(opts.RemotePath, opts.LayerRef, opts.LayerID, opts.ReadOnly) // The companion's `mount` has no pack-path flag, so the values have to // survive until unmount: `drive9 umount --pack-path` is what makes the // automatic pack include them. Only a FUSE mount has a local overlay to // pack, and only a recorded local root lets unmount verify a path before // detaching the mount. - if driver == "fuse" && len(opts.PackPaths) > 0 { + if driver == "fuse" && (len(opts.PackPaths) > 0 || opts.LayerID != "") { locator.PackPaths = opts.PackPaths locator.LocalRoot = localRoot } @@ -1737,21 +1679,6 @@ func parseDrive9Paths(raw []byte, limit int32) []SearchResult { return results } -func parseDrive9LayerCommit(layerID string, raw []byte) apifs.FSLayerCommit { - commit := apifs.FSLayerCommit{LayerID: layerID, Status: "committed"} - parts := strings.Fields(string(bytes.TrimSpace(raw))) - for _, part := range parts { - if strings.HasPrefix(part, "applied=") { - applied, _ := strconv.Atoi(strings.TrimPrefix(part, "applied=")) - commit.Applied = applied - } - if strings.HasPrefix(part, "layer=") && commit.LayerID == "" { - commit.LayerID = strings.TrimPrefix(part, "layer=") - } - } - return commit -} - func journalAppendStdin(opts JournalAppendOptions) ([]byte, error) { if len(opts.EntryJSON) > 0 { if opts.JSONArray { diff --git a/internal/fs/drive9_companion_test.go b/internal/fs/drive9_companion_test.go index 05049238..1407db76 100644 --- a/internal/fs/drive9_companion_test.go +++ b/internal/fs/drive9_companion_test.go @@ -372,49 +372,36 @@ func TestDrive9CopyDoesNotRetryNonReplayableStreamsOrAppend(t *testing.T) { } } -func TestDrive9LayerForkChainAndDeleteTranslateToCompanion(t *testing.T) { +func TestDrive9LayerForkAndDeleteTranslateToCompanion(t *testing.T) { companion, recordPath := buildFakeDrive9(t) t.Setenv("TI_FAKE_DRIVE9_RECORD", recordPath) service := testCompanionService(t.TempDir(), companion) profile := dataProfile() forked, err := service.ForkLayer(context.Background(), ForkLayerOptions{ - Profile: profile, ParentLayerRef: "research-base", LayerID: "child-id", LayerName: "style-analyst", CheckpointID: "seed", ActorID: "hermes", + Profile: profile, ParentLayerRef: "research-base", TTL: "1h", LayerName: "style-analyst", Tags: []string{"env=dev"}, ActorID: "hermes", }) if err != nil { t.Fatalf("ForkLayer failed: %v", err) } - if forked.LayerID != "child-id" || forked.ParentLayerID != "parent-id" || forked.OriginCheckpointID != "seed" || forked.Depth != 1 { + if forked.LayerID != "child-id" || forked.ParentLayerID != "parent-id" || forked.SnapGen != 12 || forked.Fence != 2 { t.Fatalf("unexpected fork response: %#v", forked) } forkCall := requireFakeDrive9Call(t, recordPath, "fs", "layer", "fork") - wantFork := []string{"fs", "layer", "fork", "--json", "--id", "child-id", "--name", "style-analyst", "--checkpoint", "seed", "--actor", "hermes", "research-base"} + wantFork := []string{"fs", "layer", "fork", "--json", "--name", "style-analyst", "--ttl", "1h", "--tag", "env=dev", "--actor", "hermes", "research-base"} if fmt.Sprint(forkCall.Args) != fmt.Sprint(wantFork) { t.Fatalf("fork args = %#v, want %#v", forkCall.Args, wantFork) } - chain, err := service.ListLayerChain(context.Background(), ListLayerChainOptions{Profile: profile, LayerRef: "style-analyst"}) - if err != nil { - t.Fatalf("ListLayerChain failed: %v", err) - } - if len(chain.Chain) != 2 || chain.Chain[0].LayerID != "root-id" || chain.Chain[1].LimitSeq != 12 { - t.Fatalf("unexpected chain response: %#v", chain) - } - chainCall := requireFakeDrive9Call(t, recordPath, "fs", "layer", "chain") - wantChain := []string{"fs", "layer", "chain", "--json", "style-analyst"} - if fmt.Sprint(chainCall.Args) != fmt.Sprint(wantChain) { - t.Fatalf("chain args = %#v, want %#v", chainCall.Args, wantChain) - } - - deleted, err := service.DeleteLayer(context.Background(), DeleteLayerOptions{Profile: profile, LayerRef: "style-brief", Cascade: true}) + deleted, err := service.DeleteLayer(context.Background(), DeleteLayerOptions{Profile: profile, LayerRef: "style-brief", Force: true}) if err != nil { t.Fatalf("DeleteLayer failed: %v", err) } - if deleted.Status != "abandoned" || !deleted.Cascade || deleted.LayerRef != "style-brief" { + if deleted.Status != "deleted" || deleted.LayerID != "style-brief" { t.Fatalf("unexpected delete response: %#v", deleted) } - deleteCall := requireFakeDrive9Call(t, recordPath, "fs", "layer", "delete") - wantDelete := []string{"fs", "layer", "delete", "--cascade", "style-brief"} + deleteCall := requireFakeDrive9Call(t, recordPath, "fs", "layer", "rm") + wantDelete := []string{"fs", "layer", "rm", "--json", "--force", "style-brief"} if fmt.Sprint(deleteCall.Args) != fmt.Sprint(wantDelete) { t.Fatalf("delete args = %#v, want %#v", deleteCall.Args, wantDelete) } @@ -443,11 +430,11 @@ func TestDrive9LayerTipForkAndLeafDeleteOmitOptionalFlags(t *testing.T) { if err != nil { t.Fatalf("DeleteLayer failed: %v", err) } - if deleted.Cascade { - t.Fatalf("leaf delete unexpectedly enabled cascade: %#v", deleted) + if deleted.Status != "deleted" { + t.Fatalf("unexpected deletion receipt: %#v", deleted) } - deleteCall := requireFakeDrive9Call(t, recordPath, "fs", "layer", "delete") - wantDelete := []string{"fs", "layer", "delete", "leaf-id"} + deleteCall := requireFakeDrive9Call(t, recordPath, "fs", "layer", "rm") + wantDelete := []string{"fs", "layer", "rm", "--json", "leaf-id"} if fmt.Sprint(deleteCall.Args) != fmt.Sprint(wantDelete) { t.Fatalf("leaf delete args = %#v, want %#v", deleteCall.Args, wantDelete) } @@ -462,16 +449,16 @@ func TestDrive9LayerWorkflowRejectsIncompatibleCompanion(t *testing.T) { } } -func TestDrive9DeleteLayerPreservesDescendantConflict(t *testing.T) { +func TestDrive9DeleteLayerPreservesMountConflict(t *testing.T) { companion, _ := buildFakeDrive9(t) - t.Setenv("TI_FAKE_DRIVE9_DELETE_DESCENDANT", "1") + t.Setenv("TI_FAKE_DRIVE9_DELETE_MOUNTED", "1") _, err := testCompanionService(t.TempDir(), companion).DeleteLayer(context.Background(), DeleteLayerOptions{Profile: dataProfile(), LayerRef: "parent"}) - if err == nil || !strings.Contains(apperr.MessageFor(err), "live descendants") { + if err == nil || !strings.Contains(apperr.MessageFor(err), "exclusively mounted") { t.Fatalf("delete descendant conflict was not preserved: %v", err) } } -func TestDrive9LayerCheckpointMountIsReadOnlyAndRecorded(t *testing.T) { +func TestDrive9LayerMountUsesCanonicalIDAndRecordsReadOnly(t *testing.T) { home := t.TempDir() companion, recordPath := buildFakeDrive9(t) t.Setenv("TI_FAKE_DRIVE9_RECORD", recordPath) @@ -479,16 +466,16 @@ func TestDrive9LayerCheckpointMountIsReadOnlyAndRecorded(t *testing.T) { checkpointService := testCompanionService(home, companion) checkpointService.mountPointActive = trueMountEvidence result, err := checkpointService.MountFileSystem(context.Background(), MountFileSystemOptions{ - Profile: dataProfile(), MountPath: mountPath, RemotePath: "/research/q3-market", Driver: "fuse", LayerRef: "style-analyst", CheckpointID: "v5", + Profile: dataProfile(), MountPath: mountPath, RemotePath: "/research/q3-market", Driver: "fuse", LayerRef: "style-analyst", ReadOnly: true, }) if err != nil { t.Fatalf("MountFileSystem failed: %v", err) } - if !result.ReadOnly || result.LayerRef != "style-analyst" || result.CheckpointID != "v5" || result.Driver != "fuse" { + if !result.ReadOnly || result.LayerRef != "style-analyst" || result.LayerID != "layer_01jz0123456789abcdefghjkmn" || result.Driver != "fuse" { t.Fatalf("unexpected layer mount result: %#v", result) } mountCall := requireFakeDrive9CallWithoutArg(t, recordPath, "--help", "mount") - want := []string{"mount", "--mode", "fuse", "--read-only", "--layer", "style-analyst", "--checkpoint", "v5", ":/research/q3-market", mountPath} + want := []string{"mount", "--mode", "fuse", "--read-only", "--layer", "layer_01jz0123456789abcdefghjkmn", "--durability", "interactive", ":/research/q3-market", mountPath} if fmt.Sprint(mountCall.Args) != fmt.Sprint(want) { t.Fatalf("mount args = %#v, want %#v", mountCall.Args, want) } @@ -496,7 +483,7 @@ func TestDrive9LayerCheckpointMountIsReadOnlyAndRecorded(t *testing.T) { if err != nil { t.Fatalf("read mount locator: %v", err) } - if locator.LayerRef != "style-analyst" || locator.CheckpointID != "v5" || !locator.ReadOnly || locator.RemotePath != "/research/q3-market" { + if locator.LayerRef != "style-analyst" || locator.LayerID != "layer_01jz0123456789abcdefghjkmn" || !locator.ReadOnly || locator.RemotePath != "/research/q3-market" { t.Fatalf("unexpected layer mount locator: %#v", locator) } } @@ -504,18 +491,9 @@ func TestDrive9LayerCheckpointMountIsReadOnlyAndRecorded(t *testing.T) { func TestLayerMountValidationRejectsUnsupportedInputs(t *testing.T) { profile := dataProfile() service := Service{} - if _, err := service.MountFileSystem(context.Background(), MountFileSystemOptions{Profile: profile, MountPath: "/tmp/x", Driver: "fuse", CheckpointID: "v5"}); apperr.CodeFor(err) != "fs.checkpoint_requires_layer" { - t.Fatalf("checkpoint-only error = %v", err) - } if _, err := service.MountFileSystem(context.Background(), MountFileSystemOptions{Profile: profile, MountPath: "/tmp/x", Driver: "webdav", LayerRef: "layer"}); apperr.CodeFor(err) != "fs.layer_mount_requires_fuse" { t.Fatalf("webdav layer error = %v", err) } - if _, err := service.MountFileSystem(context.Background(), MountFileSystemOptions{Profile: profile, MountPath: "/tmp/x", Driver: "fuse", LayerRef: "layer", CheckpointID: "v5", ReadOnlySet: true}); apperr.CodeFor(err) != "fs.checkpoint_mount_read_only" { - t.Fatalf("explicit writable checkpoint error = %v", err) - } - if _, err := service.MountFileSystem(context.Background(), MountFileSystemOptions{Profile: profile, MountPath: "/tmp/x", Driver: "fuse", LayerRef: "layer", CheckpointID: "v5", WriteBackCache: true, WriteBackCacheSet: true}); apperr.CodeFor(err) != "fs.checkpoint_mount_read_only" { - t.Fatalf("checkpoint write-back error = %v", err) - } } func TestLayerReferenceValidation(t *testing.T) { @@ -540,17 +518,21 @@ func TestLayerReferenceValidation(t *testing.T) { } } -func TestDrive9RecursiveLayerCopyIsRejectedLocally(t *testing.T) { - companion, recordPath := buildFakeDrive9(t) - t.Setenv("TI_FAKE_DRIVE9_RECORD", recordPath) - _, err := testCompanionService(t.TempDir(), companion).CopyFile(context.Background(), CopyFileOptions{ - Profile: dataProfile(), FromLocal: ".", ToRemote: "/research/q3-market", Recursive: true, LayerID: "research-base", - }) - if apperr.CodeFor(err) != "fs.recursive_layer_copy_unsupported" { - t.Fatalf("error = %v, want fs.recursive_layer_copy_unsupported", err) +func TestDrive9LayerCopyFlags(t *testing.T) { + opts := CopyFileOptions{FromLocal: ".", ToRemote: "/data", Recursive: true, LayerID: "trial"} + args, _, _, err := drive9CopyArgs(opts) + if err != nil || fmt.Sprint(args) != "[fs cp --recursive --layer trial . :/data]" { + t.Fatalf("args=%v err=%v", args, err) } - if _, statErr := os.Stat(recordPath); !os.IsNotExist(statErr) { - t.Fatalf("rejected copy invoked companion: %v", statErr) + opts.Recursive = false + opts.Append = true + if _, _, _, err := drive9CopyArgs(opts); apperr.CodeFor(err) != "fs.invalid_copy_flags" { + t.Fatalf("append: %v", err) + } + opts.Append = false + opts.Description = "label" + if _, _, _, err := drive9CopyArgs(opts); apperr.CodeFor(err) != "fs.invalid_copy_flags" { + t.Fatalf("description: %v", err) } } diff --git a/internal/fs/drive9_copy.go b/internal/fs/drive9_copy.go index 67f646fe..b11fdec8 100644 --- a/internal/fs/drive9_copy.go +++ b/internal/fs/drive9_copy.go @@ -608,8 +608,8 @@ func drive9CopyArgs(opts CopyFileOptions) ([]string, string, string, error) { // is used by the server-side --overwrite replace, which copies to a sibling // temporary path first; every other caller passes "". func drive9CopyArgsForTarget(opts CopyFileOptions, targetOverride string) ([]string, string, string, error) { - if opts.Recursive && strings.TrimSpace(opts.LayerID) != "" { - return nil, "", "", apperr.New("fs.recursive_layer_copy_unsupported", "usage", 2, "--recursive cannot be combined with --layer-id; mount the layer with --driver fuse and copy the directory through the mounted path") + if strings.TrimSpace(opts.LayerID) != "" && (opts.Append || opts.Description != "") { + return nil, "", "", apperr.New("fs.invalid_copy_flags", "usage", 2, "--layer-id cannot be combined with --append or --description") } args := []string{"fs", "cp"} if opts.Resume { diff --git a/internal/fs/drive9_fake_companion_test.go b/internal/fs/drive9_fake_companion_test.go index 7dead2aa..bda918de 100644 --- a/internal/fs/drive9_fake_companion_test.go +++ b/internal/fs/drive9_fake_companion_test.go @@ -62,31 +62,28 @@ func main() { if os.Getenv("TI_FAKE_DRIVE9_OLD_LAYER") == "1" { fmt.Println("usage: drive9 fs layer ") } else { - fmt.Println("usage: drive9 fs layer ") + fmt.Println("usage: drive9 fs layer ") } case len(args) >= 2 && args[0] == "mount" && args[1] == "--help": if os.Getenv("TI_FAKE_DRIVE9_OLD_LAYER") == "1" { fmt.Println("usage: drive9 mount [flags] [:/remote] ") } else { - fmt.Println("-layer string") - fmt.Println("-checkpoint string") + fmt.Println("-layer value") } case len(args) >= 3 && args[0] == "fs" && args[1] == "layer" && args[2] == "fork": _ = json.NewEncoder(os.Stdout).Encode(map[string]any{ "layer_id": "child-id", "name": "style-analyst", "state": "active", "base_root_path": "/research/q3-market", - "parent_layer_id": "parent-id", "origin_seq": 12, "origin_checkpoint_id": "seed", "root_layer_id": "root-id", "depth": 1, + "parent_layer_id": "parent-id", "snap_gen": 12, "fence": 2, }) - case len(args) >= 3 && args[0] == "fs" && args[1] == "layer" && args[2] == "chain": - _ = json.NewEncoder(os.Stdout).Encode(map[string]any{"chain": []map[string]any{ - {"layer_id": "root-id", "name": "research-base", "state": "active", "depth": 0, "limit_seq": 12, "base_root_path": "/research/q3-market"}, - {"layer_id": "child-id", "name": "style-analyst", "state": "active", "depth": 1, "parent_layer_id": "root-id", "origin_seq": 12, "limit_seq": 12, "origin_checkpoint_id": "seed", "base_root_path": "/research/q3-market"}, - }}) - case len(args) >= 3 && args[0] == "fs" && args[1] == "layer" && args[2] == "delete": - if os.Getenv("TI_FAKE_DRIVE9_DELETE_DESCENDANT") == "1" { - fmt.Fprintln(os.Stderr, "fs layer delete: layer has live descendants") + + case len(args) >= 3 && args[0] == "fs" && args[1] == "layer" && args[2] == "inspect": + _ = json.NewEncoder(os.Stdout).Encode(map[string]string{"layer_id": "layer_01jz0123456789abcdefghjkmn"}) + case len(args) >= 3 && args[0] == "fs" && args[1] == "layer" && args[2] == "rm": + if os.Getenv("TI_FAKE_DRIVE9_DELETE_MOUNTED") == "1" { + fmt.Fprintln(os.Stderr, "layer is exclusively mounted") os.Exit(1) } - fmt.Fprintln(os.Stdout, "ok") + _ = json.NewEncoder(os.Stdout).Encode(map[string]string{"layer_id": args[len(args)-1], "status": "deleted"}) case args[0] == "create": if path := os.Getenv("TI_FAKE_DRIVE9_BREAK_CREDENTIAL_ROOT"); path != "" { _ = os.RemoveAll(path) diff --git a/internal/fs/drive9_mount_audit.go b/internal/fs/drive9_mount_audit.go index 0bdc3cf5..3176c7df 100644 --- a/internal/fs/drive9_mount_audit.go +++ b/internal/fs/drive9_mount_audit.go @@ -33,6 +33,12 @@ func (s Service) unpackAuditLocalRoot(opts UnpackFileSystemOptions) (string, err if err != nil { return "", err } + if locator, _, err := mountlocator.Read(homeDir, mountPath); err == nil && locator.LayerID != "" { + if filepath.IsAbs(locator.LocalRoot) { + return layerLocalRoot(locator.LocalRoot, locator.LayerID), nil + } + return "", apperr.New("fs.unpack_unknown_local_root", "runtime", 1, "this layer mount has no recorded overlay root; pass its effective --local-root") + } if state, _, readErr := mountstate.Read(homeDir, mountPath); readErr == nil { if localRoot := strings.TrimSpace(state.LocalRoot); localRoot != "" && filepath.IsAbs(localRoot) { return filepath.Clean(localRoot), nil @@ -52,8 +58,8 @@ func (s Service) drive9MountFileSystem(ctx context.Context, opts MountFileSystem // Security (information protection): mount-time auto/explicit unpack writes a // local overlay through the companion, so audit it exactly like // unpack-file-system does. An unpack target ti cannot resolve is refused - // rather than silently skipped, and the resolved root is passed to the - // companion so both sides write the same overlay. + // rather than silently skipped, and layer mounts pin the canonical ID for both the + // companion and the local audit. auditRoot, unpackPossible, err := s.mountOverlayAudit(opts, remotePath) if err != nil { return MountResult{}, err @@ -71,6 +77,20 @@ func (s Service) drive9MountFileSystem(ctx context.Context, opts MountFileSystem "resolve the local overlay root that --pack-path is packed from", err) } } + if opts.LayerRef != "" { + if err := s.requireDrive9Capabilities(ctx, opts.Profile, drive9CapabilityLayerMount); err != nil { + return MountResult{}, err + } + layer, err := s.DescribeLayer(ctx, DescribeLayerOptions{Profile: opts.Profile, LayerID: opts.LayerRef}) + if err != nil { + return MountResult{}, err + } + if !canonicalLayerID.MatchString(layer.LayerID) { + return MountResult{}, apperr.New("fs.companion_decode", "runtime", 1, "layer inspection returned an invalid layer ID") + } + opts.LayerID = layer.LayerID + auditRoot = layerLocalRoot(auditRoot, opts.LayerID) + } var overlayBefore map[string]overlayEntryInfo if unpackPossible { var snapshotProblems []string @@ -90,15 +110,7 @@ func (s Service) drive9MountFileSystem(ctx context.Context, opts MountFileSystem args = append(args, "--read-only") } if opts.LayerRef != "" { - capabilities := []string{drive9CapabilityLayerMount} - if opts.CheckpointID != "" { - capabilities = append(capabilities, drive9CapabilityCheckpointMount) - } - if err := s.requireDrive9Capabilities(ctx, opts.Profile, capabilities...); err != nil { - return MountResult{}, err - } - appendFlagValue(&args, "--layer", opts.LayerRef) - appendFlagValue(&args, "--checkpoint", opts.CheckpointID) + appendFlagValue(&args, "--layer", opts.LayerID) } fuseRequested := strings.TrimSpace(opts.Driver) == "fuse" if fuseRequested { @@ -192,7 +204,7 @@ func (s Service) drive9MountFileSystem(ctx context.Context, opts MountFileSystem if driver == "webdav" { durability = MountDurabilityAuto } - return MountResult{Status: "mounted", Profile: profileName(opts.Profile), FileSystemName: opts.Profile.FSResourceName, MountPath: opts.MountPath, RemotePath: remotePath, Driver: driver, Endpoint: &endpoint, MountProfile: opts.MountProfile, LocalRoot: auditRoot, PackPaths: opts.PackPaths, Durability: durability, LayerRef: opts.LayerRef, CheckpointID: opts.CheckpointID, ReadOnly: opts.ReadOnly}, nil + return MountResult{Status: "mounted", Profile: profileName(opts.Profile), FileSystemName: opts.Profile.FSResourceName, MountPath: opts.MountPath, RemotePath: remotePath, Driver: driver, Endpoint: &endpoint, MountProfile: opts.MountProfile, LocalRoot: auditRoot, PackPaths: opts.PackPaths, Durability: durability, LayerRef: opts.LayerRef, LayerID: opts.LayerID, ReadOnly: opts.ReadOnly}, nil } // stopMountAfterUnsafeAudit tears down a mount whose overlay failed the audit. It diff --git a/internal/fs/drive9_mount_audit_test.go b/internal/fs/drive9_mount_audit_test.go index 543db732..721c46f9 100644 --- a/internal/fs/drive9_mount_audit_test.go +++ b/internal/fs/drive9_mount_audit_test.go @@ -766,3 +766,41 @@ func TestDrive9FailedUnmountPreservesMountLocator(t *testing.T) { t.Fatalf("failed unmount removed mount locator: %v", err) } } + +func TestLayerMountScopesUnpackAndPackPaths(t *testing.T) { + home, base, mount := t.TempDir(), t.TempDir(), t.TempDir() + const id = "layer_01jz0123456789abcdefghjkmn" + scoped := filepath.Join(base, "views", "d2b7ded3898e7d4333a48e1aa6ba0722ee05cf6ee6efdda53a4d644fb9b04976") + for _, path := range []string{filepath.Join(base, "overlay", "main"), filepath.Join(scoped, "overlay", "trial")} { + if err := os.MkdirAll(path, 0700); err != nil { + t.Fatal(err) + } + } + companion, _ := buildFakeDrive9(t) + service := testCompanionService(home, companion) + service.mountPointActive = trueMountEvidence + result, err := service.MountFileSystem(context.Background(), MountFileSystemOptions{ + Profile: dataProfile(), Driver: "fuse", MountPath: mount, LayerRef: "named-trial", LocalRoot: base, MountProfile: "portable", PackPaths: []string{"trial", "main"}, + }) + if err != nil { + t.Fatal(err) + } + if result.LocalRoot != scoped { + t.Fatalf("audit root = %q, want %q", result.LocalRoot, scoped) + } + locator, _, err := mountlocator.Read(home, mount) + if err != nil { + t.Fatal(err) + } + if locator.LayerID != id || locator.LocalRoot != base { + t.Fatalf("unexpected locator root or layer ID: %v", locator) + } + paths, checks := replayablePackPaths(locator) + if len(paths) != 1 || paths[0] != "trial" || len(checks) != 1 { + t.Fatalf("pack paths=%v, checks=%v", paths, checks) + } + unpackRoot, err := service.unpackAuditLocalRoot(UnpackFileSystemOptions{MountPath: mount}) + if err != nil || unpackRoot != scoped { + t.Fatalf("unpack root=%q err=%v", unpackRoot, err) + } +} diff --git a/internal/fs/layer.go b/internal/fs/layer.go index 71344bbb..62e62fd8 100644 --- a/internal/fs/layer.go +++ b/internal/fs/layer.go @@ -1,13 +1,13 @@ package fs import ( - "bytes" "context" "fmt" - "os" "sort" + "strconv" "strings" "text/tabwriter" + "time" "unicode" apifs "github.com/tidbcloud/ti-cli/internal/api/fs" @@ -19,18 +19,18 @@ import ( ) const ( + LayerCapabilityMerge = drive9CapabilityLayerMerge LayerCapabilityFork = drive9CapabilityLayerFork LayerCapabilityDelete = drive9CapabilityLayerDelete ) type CreateLayerOptions struct { - Profile *config.Profile - LayerID string - BaseRootPath string - LayerName string - Tags []string - DurabilityMode string - ActorID string + Profile *config.Profile + BaseRootPath string + LayerName string + Tags []string + TTL string + ActorID string } type DescribeLayerOptions struct { @@ -45,91 +45,16 @@ type ListLayersOptions struct { type ForkLayerOptions struct { Profile *config.Profile ParentLayerRef string - LayerID string LayerName string - CheckpointID string + Tags []string + TTL string ActorID string } -type ListLayerChainOptions struct { - Profile *config.Profile - LayerRef string -} - type DeleteLayerOptions struct { Profile *config.Profile LayerRef string - Cascade bool -} - -type LayerEntriesOptions struct { - Profile *config.Profile - LayerID string - MaxSeq int64 -} - -type CreateLayerEntryOptions struct { - Profile *config.Profile - LayerID string - Path string - Operation string - ResourceKind string - BaseInodeID string - BaseRevision int64 - StorageType string - StorageRef string - StorageRefHash string - StorageEncryptionMode string - StorageEncryptionKeyID string - Content string - ContentSet bool - ContentType string - ContentText string - ChecksumSHA256 string - SizeBytes int64 - Mode string -} - -type UploadLayerFileOptions struct { - Profile *config.Profile - LayerID string - FromLocal string - ToLayerPath string - BaseRevision int64 - Mode string - ModeSet bool -} - -type ReadLayerFileOptions struct { - Profile *config.Profile - LayerID string - Path string - MaxSeq int64 -} - -type DescribeLayerEntryOptions struct { - Profile *config.Profile - LayerID string - Path string - MaxSeq int64 -} - -type CreateLayerCheckpointOptions struct { - Profile *config.Profile - LayerID string - CheckpointID string - Label string -} - -type DescribeLayerCheckpointOptions struct { - Profile *config.Profile - CheckpointID string -} - -type ListLayerEventsOptions struct { - Profile *config.Profile - LayerID string - Since int64 + Force bool } type LayerActionOptions struct { @@ -145,43 +70,15 @@ type LayerListResult struct { Layers []apifs.FSLayer `json:"layers"` } -type LayerChainResult struct { - Chain []apifs.FSLayerChainFrame `json:"chain"` -} - type DeleteLayerResult struct { - Operation string `json:"operation"` - LayerRef string `json:"layer_ref"` - Status string `json:"status"` - Cascade bool `json:"cascade"` -} - -type LayerEntriesResult struct { - LayerID string `json:"layer_id"` - Entries []apifs.FSLayerEntry `json:"entries"` -} - -type LayerEntryResult struct { - apifs.FSLayerEntry -} - -type LayerCheckpointResult struct { - apifs.FSLayerCheckpoint -} - -type LayerEventsResult struct { - LayerID string `json:"layer_id"` - Events []apifs.FSLayerEvent `json:"events"` + LayerID string `json:"layer_id"` + Status string `json:"status"` } -type LayerActionResult struct { - Operation string `json:"operation"` - LayerID string `json:"layer_id"` - Status string `json:"status"` -} - -type LayerCommitResult struct { - apifs.FSLayerCommit +type LayerMergeResult struct { + LayerID string `json:"layer_id"` + Status string `json:"status"` + AppliedPaths int `json:"applied_paths"` } func (s Service) CreateLayer(ctx context.Context, opts CreateLayerOptions) (LayerResult, error) { @@ -196,21 +93,9 @@ func (s Service) ForkLayer(ctx context.Context, opts ForkLayerOptions) (LayerRes if err := validateLayerReference(opts.ParentLayerRef, "--parent-layer-ref"); err != nil { return LayerResult{}, err } - if strings.TrimSpace(opts.CheckpointID) != "" { - if err := validateLayerReference(opts.CheckpointID, "--checkpoint-id"); err != nil { - return LayerResult{}, err - } - } return s.drive9ForkLayer(ctx, opts) } -func (s Service) ListLayerChain(ctx context.Context, opts ListLayerChainOptions) (LayerChainResult, error) { - if err := validateLayerReference(opts.LayerRef, "--layer-ref"); err != nil { - return LayerChainResult{}, err - } - return s.drive9ListLayerChain(ctx, opts) -} - func (s Service) DeleteLayer(ctx context.Context, opts DeleteLayerOptions) (DeleteLayerResult, error) { if err := validateLayerReference(opts.LayerRef, "--layer-ref"); err != nil { return DeleteLayerResult{}, err @@ -222,130 +107,6 @@ func (s Service) DescribeLayer(ctx context.Context, opts DescribeLayerOptions) ( return s.drive9DescribeLayer(ctx, opts) } -func (s Service) DiffLayer(ctx context.Context, opts LayerEntriesOptions) (LayerEntriesResult, error) { - return s.drive9DiffLayer(ctx, opts) -} - -func (s Service) ReplayLayer(ctx context.Context, opts LayerEntriesOptions) (LayerEntriesResult, error) { - client, err := s.dataClient(opts.Profile, authz.FSFileRead, "replay ti fs layer") - if err != nil { - return LayerEntriesResult{}, err - } - layerID := strings.TrimSpace(opts.LayerID) - var entries []apifs.FSLayerEntry - if opts.MaxSeq > 0 { - entries, err = client.ReplayFSLayerAtSeq(ctx, layerID, opts.MaxSeq) - } else { - entries, err = client.ReplayFSLayer(ctx, layerID) - } - if err != nil { - return LayerEntriesResult{}, err - } - return LayerEntriesResult{LayerID: layerID, Entries: entries}, nil -} - -func (s Service) CreateLayerEntry(ctx context.Context, opts CreateLayerEntryOptions) (LayerEntryResult, error) { - client, err := s.dataClient(opts.Profile, authz.FSFileWrite, "write ti fs layer entry") - if err != nil { - return LayerEntryResult{}, err - } - request, err := layerEntryRequest(opts) - if err != nil { - return LayerEntryResult{}, err - } - entry, err := client.UpsertFSLayerEntry(ctx, strings.TrimSpace(opts.LayerID), request) - if err != nil { - return LayerEntryResult{}, err - } - return LayerEntryResult{FSLayerEntry: entry}, nil -} - -func (s Service) UploadLayerFile(ctx context.Context, opts UploadLayerFileOptions) (LayerEntryResult, error) { - client, err := s.dataClient(opts.Profile, authz.FSFileWrite, "upload ti fs layer file") - if err != nil { - return LayerEntryResult{}, err - } - entry, err := uploadLocalFileToLayer(ctx, client, opts) - if err != nil { - return LayerEntryResult{}, err - } - return LayerEntryResult{FSLayerEntry: entry}, nil -} - -func (s Service) ReadLayerFile(ctx context.Context, opts ReadLayerFileOptions) ([]byte, error) { - client, err := s.dataClient(opts.Profile, authz.FSFileRead, "read ti fs layer file") - if err != nil { - return nil, err - } - remotePath, err := normalizeRemotePath(opts.Path) - if err != nil { - return nil, err - } - var maxSeq *int64 - if opts.MaxSeq > 0 { - maxSeq = &opts.MaxSeq - } - return client.ReadFSLayerFile(ctx, strings.TrimSpace(opts.LayerID), remotePath, maxSeq) -} - -func (s Service) DescribeLayerEntry(ctx context.Context, opts DescribeLayerEntryOptions) (LayerEntryResult, error) { - client, err := s.dataClient(opts.Profile, authz.FSFileRead, "describe ti fs layer entry") - if err != nil { - return LayerEntryResult{}, err - } - remotePath, err := normalizeRemotePath(opts.Path) - if err != nil { - return LayerEntryResult{}, err - } - var entry apifs.FSLayerEntry - if opts.MaxSeq > 0 { - entry, err = client.GetFSLayerEntryAtSeq(ctx, strings.TrimSpace(opts.LayerID), remotePath, opts.MaxSeq) - } else { - entry, err = client.GetFSLayerEntry(ctx, strings.TrimSpace(opts.LayerID), remotePath) - } - if err != nil { - return LayerEntryResult{}, err - } - return LayerEntryResult{FSLayerEntry: entry}, nil -} - -func (s Service) CreateLayerCheckpoint(ctx context.Context, opts CreateLayerCheckpointOptions) (LayerCheckpointResult, error) { - return s.drive9CreateLayerCheckpoint(ctx, opts) -} - -func (s Service) DescribeLayerCheckpoint(ctx context.Context, opts DescribeLayerCheckpointOptions) (LayerCheckpointResult, error) { - client, err := s.dataClient(opts.Profile, authz.FSFileRead, "describe ti fs layer checkpoint") - if err != nil { - return LayerCheckpointResult{}, err - } - checkpoint, err := client.GetFSLayerCheckpoint(ctx, strings.TrimSpace(opts.CheckpointID)) - if err != nil { - return LayerCheckpointResult{}, err - } - return LayerCheckpointResult{FSLayerCheckpoint: checkpoint}, nil -} - -func (s Service) ListLayerEvents(ctx context.Context, opts ListLayerEventsOptions) (LayerEventsResult, error) { - client, err := s.dataClient(opts.Profile, authz.FSFileRead, "list ti fs layer events") - if err != nil { - return LayerEventsResult{}, err - } - layerID := strings.TrimSpace(opts.LayerID) - events, err := client.ListFSLayerEvents(ctx, layerID, opts.Since) - if err != nil { - return LayerEventsResult{}, err - } - return LayerEventsResult{LayerID: layerID, Events: events}, nil -} - -func (s Service) RollbackLayer(ctx context.Context, opts LayerActionOptions) (LayerActionResult, error) { - return s.drive9RollbackLayer(ctx, opts) -} - -func (s Service) CommitLayer(ctx context.Context, opts LayerActionOptions) (LayerCommitResult, error) { - return s.drive9CommitLayer(ctx, opts) -} - func (s Service) DryRunLayerMutation(ctx context.Context, commandPath, operation, method, requestPath string, body any, profile *config.Profile, permission authz.Permission, capabilities ...string) (dryrun.Result, error) { if profile == nil { return dryrun.Result{}, apperr.New("fs.missing_profile", "config", 2, "active profile is required") @@ -402,84 +163,6 @@ func validateLayerReference(value, flagName string) error { return nil } -func layerEntryRequest(opts CreateLayerEntryOptions) (apifs.FSLayerEntryRequest, error) { - remotePath, err := normalizeRemotePath(opts.Path) - if err != nil { - return apifs.FSLayerEntryRequest{}, err - } - mode, err := parseMode(opts.Mode) - if err != nil { - return apifs.FSLayerEntryRequest{}, err - } - request := apifs.FSLayerEntryRequest{ - Path: remotePath, - Op: strings.TrimSpace(opts.Operation), - Kind: strings.TrimSpace(opts.ResourceKind), - BaseInodeID: strings.TrimSpace(opts.BaseInodeID), - BaseRevision: opts.BaseRevision, - StorageType: strings.TrimSpace(opts.StorageType), - StorageRef: strings.TrimSpace(opts.StorageRef), - StorageRefHash: strings.TrimSpace(opts.StorageRefHash), - StorageEncryptionMode: strings.TrimSpace(opts.StorageEncryptionMode), - StorageEncryptionKeyID: strings.TrimSpace(opts.StorageEncryptionKeyID), - ContentType: strings.TrimSpace(opts.ContentType), - ContentText: opts.ContentText, - ChecksumSHA256: strings.TrimSpace(opts.ChecksumSHA256), - SizeBytes: opts.SizeBytes, - Mode: uint32(mode), - } - if request.Op == "" { - request.Op = "upsert" - } - if request.Kind == "" { - request.Kind = "file" - } - if opts.ContentSet { - request.Content = []byte(opts.Content) - } - return request, nil -} - -func uploadLocalFileToLayer(ctx context.Context, client *apifs.Client, opts UploadLayerFileOptions) (apifs.FSLayerEntry, error) { - file, size, err := openLocalRegularFile(opts.FromLocal) - if err != nil { - return apifs.FSLayerEntry{}, err - } - defer file.Close() - remotePath, err := normalizeRemotePath(opts.ToLayerPath) - if err != nil { - return apifs.FSLayerEntry{}, err - } - mode, hasMode, err := layerUploadMode(opts.Mode, opts.ModeSet, file) - if err != nil { - return apifs.FSLayerEntry{}, err - } - return client.UploadFSLayerFile(ctx, strings.TrimSpace(opts.LayerID), remotePath, file, size, opts.BaseRevision, mode, hasMode) -} - -func uploadBytesToLayer(ctx context.Context, client *apifs.Client, layerID, remotePath string, data []byte, mode uint32, hasMode bool) (apifs.FSLayerEntry, error) { - remotePath, err := normalizeRemotePath(remotePath) - if err != nil { - return apifs.FSLayerEntry{}, err - } - return client.UploadFSLayerFile(ctx, strings.TrimSpace(layerID), remotePath, bytes.NewReader(data), int64(len(data)), 0, mode, hasMode) -} - -func layerUploadMode(modeValue string, modeSet bool, file *os.File) (uint32, bool, error) { - if modeSet { - mode, err := parseMode(modeValue) - if err != nil { - return 0, false, err - } - return uint32(mode), true, nil - } - info, err := file.Stat() - if err != nil { - return 0, false, apperr.Wrap("fs.stat_local_file", "runtime", 1, fmt.Sprintf("stat local file %q", file.Name()), err) - } - return uint32(info.Mode().Perm()), true, nil -} - func parseLayerTags(values []string) (map[string]string, error) { if len(values) == 0 { return nil, nil @@ -531,30 +214,12 @@ func (r LayerResult) Human() string { if r.Name != "" { lines = append(lines, "Name: "+r.Name) } - if r.DurabilityMode != "" { - lines = append(lines, "Durability: "+r.DurabilityMode) - } if r.ActorID != "" { lines = append(lines, "Actor: "+r.ActorID) } + lines = append(lines, fmt.Sprintf("Snapshot generation: %d", r.SnapGen), fmt.Sprintf("Fence: %d", r.Fence)) if r.ParentLayerID != "" { - lines = append(lines, - "Parent layer ID: "+r.ParentLayerID, - fmt.Sprintf("Origin seq: %d", r.OriginSeq), - fmt.Sprintf("Depth: %d", r.Depth), - ) - } - if r.OriginCheckpointID != "" { - lines = append(lines, "Origin checkpoint ID: "+r.OriginCheckpointID) - } - if r.RootLayerID != "" { - lines = append(lines, "Root layer ID: "+r.RootLayerID) - } - if r.Origin != "" { - lines = append(lines, "Origin: "+r.Origin) - } - if r.DurableSeq != 0 { - lines = append(lines, fmt.Sprintf("Durable seq: %d", r.DurableSeq)) + lines = append(lines, "Parent layer ID: "+r.ParentLayerID) } if tags := formatLayerTags(r.Tags); tags != "" { lines = append(lines, "Tags: "+tags) @@ -562,100 +227,40 @@ func (r LayerResult) Human() string { return strings.Join(lines, "\n") } -func (r LayerChainResult) Human() string { - var out strings.Builder - writer := tabwriter.NewWriter(&out, 0, 0, 2, ' ', 0) - _, _ = fmt.Fprintln(writer, "LAYER_ID\tNAME\tSTATE\tDEPTH\tPARENT_LAYER_ID\tORIGIN_SEQ\tLIMIT_SEQ\tORIGIN_CHECKPOINT_ID\tBASE_ROOT") - for _, frame := range r.Chain { - _, _ = fmt.Fprintf(writer, "%s\t%s\t%s\t%d\t%s\t%d\t%d\t%s\t%s\n", frame.LayerID, frame.Name, frame.State, frame.Depth, frame.ParentLayerID, frame.OriginSeq, frame.LimitSeq, frame.OriginCheckpointID, frame.BaseRootPath) - } - _ = writer.Flush() - return strings.TrimRight(out.String(), "\n") -} - func (r DeleteLayerResult) Human() string { - return fmt.Sprintf("%s layer=%s status=%s cascade=%t", r.Operation, r.LayerRef, r.Status, r.Cascade) + return fmt.Sprintf("%s layer=%s", r.Status, r.LayerID) } func (r LayerListResult) Human() string { var out strings.Builder writer := tabwriter.NewWriter(&out, 0, 0, 2, ' ', 0) - _, _ = fmt.Fprintln(writer, "LAYER_ID\tSTATE\tDURABILITY\tBASE_ROOT\tNAME\tTAGS") + _, _ = fmt.Fprintln(writer, "LAYER_ID\tSTATE\tFENCE\tBASE_ROOT\tNAME\tTAGS") for _, layer := range r.Layers { - _, _ = fmt.Fprintf(writer, "%s\t%s\t%s\t%s\t%s\t%s\n", layer.LayerID, layer.State, layer.DurabilityMode, layer.BaseRootPath, layer.Name, formatLayerTags(layer.Tags)) + _, _ = fmt.Fprintf(writer, "%s\t%s\t%d\t%s\t%s\t%s\n", layer.LayerID, layer.State, layer.Fence, layer.BaseRootPath, layer.Name, formatLayerTags(layer.Tags)) } _ = writer.Flush() return strings.TrimRight(out.String(), "\n") } -func (r LayerEntriesResult) Human() string { - var out strings.Builder - writer := tabwriter.NewWriter(&out, 0, 0, 2, ' ', 0) - _, _ = fmt.Fprintln(writer, "SEQ\tOP\tKIND\tMODE\tSIZE\tPATH") - for _, entry := range r.Entries { - _, _ = fmt.Fprintf(writer, "%d\t%s\t%s\t%04o\t%d\t%s\n", entry.EntrySeq, entry.Op, entry.Kind, entry.Mode, entry.SizeBytes, entry.Path) - } - _ = writer.Flush() - return strings.TrimRight(out.String(), "\n") +func (r LayerMergeResult) Human() string { + return fmt.Sprintf("%s layer=%s applied_paths=%d", r.Status, r.LayerID, r.AppliedPaths) } -func (r LayerEntryResult) Human() string { - lines := []string{ - "Layer ID: " + r.LayerID, - "Path: " + r.Path, - "Operation: " + r.Op, - "Kind: " + r.Kind, - } - if r.EntrySeq != 0 { - lines = append(lines, fmt.Sprintf("Entry seq: %d", r.EntrySeq)) +// LayerTTLSeconds converts the companion TTL flag into the wire value for dry-run output. +func LayerTTLSeconds(raw string) (int64, error) { + s := strings.TrimSpace(raw) + if s == "" { + return 0, nil } - if r.SizeBytes != 0 { - lines = append(lines, fmt.Sprintf("Size: %d", r.SizeBytes)) - } - if r.Mode != 0 { - lines = append(lines, fmt.Sprintf("Mode: %04o", r.Mode)) - } - return strings.Join(lines, "\n") -} - -func (r LayerCheckpointResult) Human() string { - lines := []string{ - "Checkpoint ID: " + r.CheckpointID, - "Layer ID: " + r.LayerID, - fmt.Sprintf("Durable seq: %d", r.DurableSeq), - } - if r.Label != "" { - lines = append(lines, "Label: "+r.Label) - } - return strings.Join(lines, "\n") -} - -func (r LayerEventsResult) Human() string { - var out strings.Builder - writer := tabwriter.NewWriter(&out, 0, 0, 2, ' ', 0) - _, _ = fmt.Fprintln(writer, "SEQ\tEVENT_ID\tACTOR\tOP\tPATH") - for _, event := range r.Events { - _, _ = fmt.Fprintf(writer, "%d\t%s\t%s\t%s\t%s\n", event.Seq, event.EventID, event.ActorID, event.Op, event.Path) - } - _ = writer.Flush() - return strings.TrimRight(out.String(), "\n") -} - -func (r LayerActionResult) Human() string { - return fmt.Sprintf("%s layer=%s status=%s", r.Operation, r.LayerID, r.Status) -} - -func (r LayerCommitResult) Human() string { - if len(r.Conflicts) == 0 { - return fmt.Sprintf("%s layer=%s applied=%d", r.Status, r.LayerID, r.Applied) + if secs, err := strconv.ParseInt(s, 10, 64); err == nil { + if secs < 0 { + return 0, apperr.New("fs.invalid_layer_ttl", "usage", 2, fmt.Sprintf("invalid --ttl %q (must be >= 0)", raw)) + } + return secs, nil } - var out strings.Builder - _, _ = fmt.Fprintf(&out, "%s layer=%s applied=%d conflicts=%d\n", r.Status, r.LayerID, r.Applied, len(r.Conflicts)) - writer := tabwriter.NewWriter(&out, 0, 0, 2, ' ', 0) - _, _ = fmt.Fprintln(writer, "PATH\tREASON\tBASE_REVISION\tWANT_REVISION") - for _, conflict := range r.Conflicts { - _, _ = fmt.Fprintf(writer, "%s\t%s\t%d\t%d\n", conflict.Path, conflict.Reason, conflict.BaseRevision, conflict.WantRevision) + dur, err := time.ParseDuration(s) + if err != nil || dur <= 0 || dur%time.Second != 0 { + return 0, apperr.New("fs.invalid_layer_ttl", "usage", 2, fmt.Sprintf("invalid --ttl %q (expected whole seconds or duration such as 1h)", raw)) } - _ = writer.Flush() - return strings.TrimRight(out.String(), "\n") + return int64(dur / time.Second), nil } diff --git a/internal/fs/mount.go b/internal/fs/mount.go index bef0475e..a059e724 100644 --- a/internal/fs/mount.go +++ b/internal/fs/mount.go @@ -37,7 +37,6 @@ type MountFileSystemOptions struct { RemotePath string Driver string ReadOnly bool - ReadOnlySet bool ReadyTimeout time.Duration CacheDir string ReadCacheMB int64 @@ -60,8 +59,8 @@ type MountFileSystemOptions struct { PackPaths []string UnpackArchivePath string NoAutoUnpack bool + LayerID string LayerRef string - CheckpointID string } type UnmountFileSystemOptions struct { @@ -99,9 +98,10 @@ type MountResult struct { MountProfile string `json:"mount_profile,omitempty"` LocalRoot string `json:"local_root,omitempty"` PackPaths []string `json:"pack_paths,omitempty"` + LayerID string `json:"layer_id,omitempty"` LayerRef string `json:"layer_ref,omitempty"` - CheckpointID string `json:"checkpoint_id,omitempty"` - ReadOnly bool `json:"read_only,omitempty"` + + ReadOnly bool `json:"read_only,omitempty"` } type MountRemoteSnapshot struct { @@ -195,11 +195,7 @@ func (s Service) DryRunMountFileSystem(ctx context.Context, commandPath string, return dryrun.Result{}, err } if opts.LayerRef != "" { - capabilities := []string{drive9CapabilityLayerMount} - if opts.CheckpointID != "" { - capabilities = append(capabilities, drive9CapabilityCheckpointMount) - } - if err := s.requireDrive9Capabilities(ctx, opts.Profile, capabilities...); err != nil { + if err := s.requireDrive9Capabilities(ctx, opts.Profile, drive9CapabilityLayerMount); err != nil { return dryrun.Result{}, err } } @@ -221,9 +217,6 @@ func (s Service) DryRunMountFileSystem(ctx context.Context, commandPath string, if opts.LayerRef != "" { checks = append(checks, dryrun.Check{Name: "layer_view", Status: "passed", Message: opts.LayerRef}) } - if opts.CheckpointID != "" { - checks = append(checks, dryrun.Check{Name: "checkpoint_view", Status: "passed", Message: opts.CheckpointID + " (read-only)"}) - } description := "normal execution starts the ti-drive9 companion mount and returns once the requested path is readable" return dryrun.New( commandPath, @@ -233,11 +226,10 @@ func (s Service) DryRunMountFileSystem(ctx context.Context, commandPath string, Method: "GET", Path: "/v1/status", Body: map[string]any{ - "driver": opts.Driver, - "durability": opts.Durability, - "layer_ref": opts.LayerRef, - "checkpoint_id": opts.CheckpointID, - "read_only": opts.ReadOnly, + "driver": opts.Driver, + "durability": opts.Durability, + "layer_ref": opts.LayerRef, + "read_only": opts.ReadOnly, }, }, checks..., @@ -246,41 +238,18 @@ func (s Service) DryRunMountFileSystem(ctx context.Context, commandPath string, func normalizeLayerMountOptions(opts MountFileSystemOptions) (MountFileSystemOptions, error) { opts.LayerRef = strings.TrimSpace(opts.LayerRef) - opts.CheckpointID = strings.TrimSpace(opts.CheckpointID) - if opts.CheckpointID != "" && opts.LayerRef == "" { - return MountFileSystemOptions{}, apperr.New("fs.checkpoint_requires_layer", "usage", 2, "--checkpoint-id requires --layer-ref") - } if opts.LayerRef == "" { return opts, nil } if err := validateLayerReference(opts.LayerRef, "--layer-ref"); err != nil { return MountFileSystemOptions{}, err } - if opts.CheckpointID != "" { - if err := validateLayerReference(opts.CheckpointID, "--checkpoint-id"); err != nil { - return MountFileSystemOptions{}, err - } - if opts.ReadOnlySet && !opts.ReadOnly { - return MountFileSystemOptions{}, apperr.New("fs.checkpoint_mount_read_only", "usage", 2, "checkpoint mounts are read-only; remove --read-only=false") - } - if opts.WriteBackCacheSet && opts.WriteBackCache { - return MountFileSystemOptions{}, apperr.New("fs.checkpoint_mount_read_only", "usage", 2, "checkpoint mounts are read-only; remove --write-back-cache=true") - } - if opts.DurabilityExplicit && opts.Durability != MountDurabilityAuto { - return MountFileSystemOptions{}, apperr.New("fs.checkpoint_mount_read_only", "usage", 2, fmt.Sprintf("checkpoint mounts are read-only; remove --durability=%s", opts.Durability)) - } - opts.ReadOnly = true - opts.WriteBackCache = false - // A checkpoint view never writes, so ti forwards no tier and reports - // the engine's own default instead of the interactive mount default. - opts.Durability = MountDurabilityAuto - } driverName := strings.TrimSpace(opts.Driver) if driverName == "" { driverName = "auto" } if driverName == "webdav" { - return MountFileSystemOptions{}, apperr.New("fs.layer_mount_requires_fuse", "usage", 2, "layer and checkpoint mounts require FUSE; install or enable FUSE and use --driver fuse") + return MountFileSystemOptions{}, apperr.New("fs.layer_mount_requires_fuse", "usage", 2, "layer mounts require FUSE; install or enable FUSE and use --driver fuse") } if driverName == "auto" { driver, err := mountdriver.Resolve("auto") @@ -288,10 +257,10 @@ func normalizeLayerMountOptions(opts MountFileSystemOptions) (MountFileSystemOpt return MountFileSystemOptions{}, apperr.New("fs.invalid_mount_driver", "usage", 2, err.Error()) } if driver.Name() != "fuse" { - return MountFileSystemOptions{}, apperr.New("fs.layer_mount_requires_fuse", "usage", 2, "automatic mount selection would use WebDAV, but layer and checkpoint mounts require FUSE; install or enable FUSE and use --driver fuse") + return MountFileSystemOptions{}, apperr.New("fs.layer_mount_requires_fuse", "usage", 2, "automatic mount selection would use WebDAV, but layer mounts require FUSE; install or enable FUSE and use --driver fuse") } if err := driver.CheckPrerequisites(); err != nil { - return MountFileSystemOptions{}, apperr.New("fs.layer_mount_requires_fuse", "usage", 2, "layer and checkpoint mounts require FUSE: "+err.Error()) + return MountFileSystemOptions{}, apperr.New("fs.layer_mount_requires_fuse", "usage", 2, "layer mounts require FUSE: "+err.Error()) } opts.Driver = "fuse" return opts, nil @@ -804,9 +773,6 @@ func (r MountResult) Human() string { if r.LayerRef != "" { lines = append(lines, "Layer: "+r.LayerRef) } - if r.CheckpointID != "" { - lines = append(lines, "Checkpoint: "+r.CheckpointID) - } if r.ReadOnly { lines = append(lines, "Read only: true") } diff --git a/internal/fs/mount_durability.go b/internal/fs/mount_durability.go index 0bc7f3e5..c2d65736 100644 --- a/internal/fs/mount_durability.go +++ b/internal/fs/mount_durability.go @@ -152,7 +152,7 @@ func companionMountMode(driver string) string { // mountDurabilityForwarded reports whether ti pins the tier on the companion // argv. It pins FUSE mounts, including automatic ones that resolve to FUSE, so // an ordinary mount keeps the documented interactive default instead of the -// engine's auto default. Checkpoint mounts are read-only and forward nothing. +// engine's auto default. func mountDurabilityForwarded(opts MountFileSystemOptions) bool { - return opts.CheckpointID == "" && companionMountMode(opts.Driver) == "fuse" + return companionMountMode(opts.Driver) == "fuse" } diff --git a/internal/fs/mount_durability_test.go b/internal/fs/mount_durability_test.go index 1fe6644a..d4b1fc37 100644 --- a/internal/fs/mount_durability_test.go +++ b/internal/fs/mount_durability_test.go @@ -165,49 +165,6 @@ func TestNormalizeMountDurabilityWebDAV(t *testing.T) { } } -// TestNormalizeMountDurabilityCheckpoint keeps read-only checkpoint mounts on -// the engine default and refuses a tier that cannot take effect there. -func TestNormalizeMountDurabilityCheckpoint(t *testing.T) { - base := MountFileSystemOptions{Driver: "fuse", LayerRef: "layer", CheckpointID: "cp-1"} - got, err := normalizeMountOptions(base) - if err != nil { - t.Fatalf("default checkpoint mount failed: %v", err) - } - if !got.ReadOnly { - t.Fatal("checkpoint mount must be read-only") - } - if got.Durability != MountDurabilityAuto { - t.Fatalf("checkpoint durability = %q, want %s", got.Durability, MountDurabilityAuto) - } - if mountDurabilityForwarded(got) { - t.Fatal("checkpoint mount must not forward --durability") - } - - explicitAuto := base - explicitAuto.Durability = MountDurabilityAuto - explicitAuto.DurabilitySet = true - if _, err := normalizeMountOptions(explicitAuto); err != nil { - t.Fatalf("explicit auto checkpoint mount failed: %v", err) - } - explicitLegacyOff := base - explicitLegacyOff.WriteBackCache = false - explicitLegacyOff.WriteBackCacheSet = true - if _, err := normalizeMountOptions(explicitLegacyOff); err != nil { - t.Fatalf("explicit write-back-cache=false checkpoint mount failed: %v", err) - } - - for _, tier := range []string{MountDurabilityInteractive, MountDurabilityFsync, MountDurabilityCloseSync, MountDurabilityWriteSync} { - explicit := base - explicit.Durability = tier - explicit.DurabilitySet = true - if _, err := normalizeMountOptions(explicit); apperr.CodeFor(err) != "fs.checkpoint_mount_read_only" { - t.Fatalf("checkpoint %s error = %v, want fs.checkpoint_mount_read_only", tier, err) - } - } -} - -// TestCompanionMountModeMatchesCompanionAutoResolution pins the local mirror of -// the companion's --mode auto rule, which decides whether a tier is forwarded. func TestCompanionMountModeMatchesCompanionAutoResolution(t *testing.T) { wantAuto := "fuse" if runtime.GOOS == "darwin" || runtime.GOOS == "windows" { diff --git a/internal/fs/mountlocator/locator.go b/internal/fs/mountlocator/locator.go index 95a74ad7..76989a25 100644 --- a/internal/fs/mountlocator/locator.go +++ b/internal/fs/mountlocator/locator.go @@ -35,21 +35,20 @@ type Locator struct { TokenFingerprint string `json:"token_fingerprint,omitempty"` RemotePath string `json:"remote_path,omitempty"` LayerRef string `json:"layer_ref,omitempty"` - CheckpointID string `json:"checkpoint_id,omitempty"` + LayerID string `json:"layer_id,omitempty"` ReadOnly bool `json:"read_only,omitempty"` // LocalRoot and PackPaths let unmount hand the extra `--pack-path` values // to the companion, which is the only channel into the automatic pack (the - // companion's mount has no pack-path flag). LocalRoot is the mount's local - // overlay root, recorded so unmount can check that each path exists before + // companion's mount has no pack-path flag). LocalRoot is the base before layer scoping, recorded so unmount can check that each path exists before // the mount is detached. Older locators omit both; omitted means "none". LocalRoot string `json:"local_root,omitempty"` PackPaths []string `json:"pack_paths,omitempty"` } -func (l Locator) WithLayerView(remotePath, layerRef, checkpointID string, readOnly bool) Locator { +func (l Locator) WithLayerView(remotePath, layerRef, layerID string, readOnly bool) Locator { l.RemotePath = strings.TrimSpace(remotePath) l.LayerRef = strings.TrimSpace(layerRef) - l.CheckpointID = strings.TrimSpace(checkpointID) + l.LayerID = strings.TrimSpace(layerID) l.ReadOnly = readOnly return l } diff --git a/internal/fs/mountroot.go b/internal/fs/mountroot.go index 36e66fbb..00c8615f 100644 --- a/internal/fs/mountroot.go +++ b/internal/fs/mountroot.go @@ -5,6 +5,7 @@ import ( "encoding/hex" "os" "path/filepath" + "regexp" "runtime" "strings" @@ -118,3 +119,13 @@ func companionMountRootLabel(remoteRoot string) string { } return label } + +var canonicalLayerID = regexp.MustCompile(`^layer_[0-9a-hjkmnp-tv-z]{26}$`) + +func layerLocalRoot(base, layerID string) string { + if base == "" || layerID == "" { + return base + } + digest := sha256.Sum256([]byte(layerID)) + return filepath.Join(base, "views", hex.EncodeToString(digest[:])) +} diff --git a/internal/output/command_contract_test.go b/internal/output/command_contract_test.go index 4ec209ef..807b33f9 100644 --- a/internal/output/command_contract_test.go +++ b/internal/output/command_contract_test.go @@ -43,12 +43,8 @@ func TestRegisteredCommandResultsSupportTextOutput(t *testing.T) { "fs search files": fs.SearchFilesResult{}, "fs layer": fs.LayerResult{}, "fs list layers": fs.LayerListResult{}, - "fs layer entries": fs.LayerEntriesResult{}, - "fs layer entry": fs.LayerEntryResult{}, - "fs layer checkpoint": fs.LayerCheckpointResult{}, - "fs layer events": fs.LayerEventsResult{}, - "fs layer action": fs.LayerActionResult{}, - "fs layer commit": fs.LayerCommitResult{}, + "fs layer merge": fs.LayerMergeResult{}, + "fs layer delete": fs.DeleteLayerResult{}, "fs pack": fs.PackFileSystemResult{}, "fs unpack": fs.UnpackFileSystemResult{}, "fs mount": fs.MountResult{}, diff --git a/internal/update/update.go b/internal/update/update.go index 8f9eeb29..78a3de06 100644 --- a/internal/update/update.go +++ b/internal/update/update.go @@ -793,7 +793,7 @@ func validateDrive9Companion(ctx context.Context, path string) error { if err != nil { return incompatibleDrive9CompanionError("read filesystem layer command surface", layerHelp, err) } - for _, command := range []string{"fork", "chain", "delete"} { + for _, command := range []string{"create", "fork", "merge", "rm"} { if !drive9HelpHasToken(layerHelp, command) { return incompatibleDrive9CompanionError("missing `drive9 fs layer "+command+"`", layerHelp, nil) } @@ -803,10 +803,8 @@ func validateDrive9Companion(ctx context.Context, path string) error { if err != nil { return incompatibleDrive9CompanionError("read filesystem mount command surface", mountHelp, err) } - for _, flag := range []string{"layer", "checkpoint"} { - if !drive9HelpHasFlag(mountHelp, flag) { - return incompatibleDrive9CompanionError("missing `drive9 mount --"+flag+"`", mountHelp, nil) - } + if !drive9HelpHasFlag(mountHelp, "layer") { + return incompatibleDrive9CompanionError("missing `drive9 mount --layer`", mountHelp, nil) } if _, err := drive9HelpOutput(ctx, path, "exec", "--help"); err != nil { @@ -834,7 +832,7 @@ func drive9HelpHasToken(help, token string) bool { func drive9HelpHasFlag(help, flag string) bool { for _, field := range strings.Fields(help) { - if strings.TrimLeft(field, "-") == flag { + if field == "-"+flag || field == "--"+flag { return true } } diff --git a/internal/update/update_test.go b/internal/update/update_test.go index f09dada7..89dce6e0 100644 --- a/internal/update/update_test.go +++ b/internal/update/update_test.go @@ -241,6 +241,21 @@ func TestApplyRejectsIncompatibleCompanionBeforeReplacingFiles(t *testing.T) { } } +func TestValidateDrive9CompanionRejectsV35(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("shell companion fixture is Unix-only") + } + path := filepath.Join(t.TempDir(), "drive9") + stale := strings.Replace(compatibleDrive9CompanionScript, "create|ls|inspect|fork|merge|rm", "create|list|status|fork|chain|delete", 1) + if err := os.WriteFile(path, []byte(stale), 0755); err != nil { + t.Fatal(err) + } + err := validateDrive9Companion(context.Background(), path) + if apperr.CodeFor(err) != "update.companion_incompatible" || !strings.Contains(apperr.MessageFor(err), "fs layer merge") { + t.Fatalf("expected missing merge: %v", err) + } +} + func TestValidateDrive9CompanionRejectsLegacySurfaceWithoutRuntimeExec(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("shell companion fixture is Unix-only") @@ -248,12 +263,11 @@ func TestValidateDrive9CompanionRejectsLegacySurfaceWithoutRuntimeExec(t *testin path := filepath.Join(t.TempDir(), "drive9") legacy := `#!/bin/sh if [ "$1 $2 $3" = "fs layer help" ]; then - echo 'usage: drive9 fs layer ' + echo 'usage: drive9 fs layer ' exit 0 fi if [ "$1 $2" = "mount --help" ]; then - echo ' -layer string' - echo ' -checkpoint string' + echo ' -layer value' exit 0 fi echo 'drive9: unknown command exec' >&2 @@ -270,12 +284,11 @@ exit 2 const compatibleDrive9CompanionScript = `#!/bin/sh if [ "$1 $2 $3" = "fs layer help" ]; then - echo 'usage: drive9 fs layer ' + echo 'usage: drive9 fs layer ' exit 0 fi if [ "$1 $2" = "mount --help" ]; then - echo ' -layer string' - echo ' -checkpoint string' + echo ' -layer value' exit 0 fi if [ "$1 $2" = "exec --help" ]; then diff --git a/scripts/install.ps1 b/scripts/install.ps1 index 0fb20430..feff713a 100644 --- a/scripts/install.ps1 +++ b/scripts/install.ps1 @@ -27,7 +27,7 @@ function Assert-CompanionCommandSurface($CompanionPath) { if ($LASTEXITCODE -ne 0) { Fail "downloaded ti-drive9 companion cannot report its filesystem layer commands" } - foreach ($command in @("fork", "chain", "delete")) { + foreach ($command in @("create", "fork", "merge", "rm")) { if ($layerHelp -notmatch "(?m)(^|[\s<|])$command([\s>|]|$)") { Fail "downloaded ti-drive9 companion is incompatible: missing drive9 fs layer $command" } @@ -37,10 +37,8 @@ function Assert-CompanionCommandSurface($CompanionPath) { if ($LASTEXITCODE -ne 0) { Fail "downloaded ti-drive9 companion cannot report its mount options" } - foreach ($flag in @("layer", "checkpoint")) { - if ($mountHelp -notmatch "(?m)(^|\s)--?$flag(\s|$)") { - Fail "downloaded ti-drive9 companion is incompatible: missing drive9 mount --$flag" - } + if ($mountHelp -notmatch "(?m)(^|\s)--?layer(\s|$)") { + Fail "downloaded ti-drive9 companion is incompatible: missing drive9 mount --layer" } $null = (& $CompanionPath exec --help 2>&1 | Out-String) diff --git a/scripts/install.sh b/scripts/install.sh index ca8f2310..6aafde3c 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -105,7 +105,7 @@ validate_companion() { if ! layer_help="$("$companion_path" fs layer help 2>&1)"; then error "downloaded ti-drive9 companion cannot report its filesystem layer commands" fi - for command in fork chain delete; do + for command in create fork merge rm; do if ! printf '%s\n' "$layer_help" | grep -Eq "(^|[[:space:]<|])${command}([[:space:]>|]|$)"; then error "downloaded ti-drive9 companion is incompatible: missing drive9 fs layer ${command}" fi @@ -114,11 +114,9 @@ validate_companion() { if ! mount_help="$("$companion_path" mount --help 2>&1)"; then error "downloaded ti-drive9 companion cannot report its mount options" fi - for flag in layer checkpoint; do - if ! printf '%s\n' "$mount_help" | grep -Eq "(^|[[:space:]])--?${flag}([[:space:]]|$)"; then - error "downloaded ti-drive9 companion is incompatible: missing drive9 mount --${flag}" - fi - done + if ! printf '%s\n' "$mount_help" | grep -Eq '(^|[[:space:]])--?layer([[:space:]]|$)'; then + error "downloaded ti-drive9 companion is incompatible: missing drive9 mount --layer" + fi if ! "$companion_path" exec --help >/dev/null 2>&1; then error "downloaded ti-drive9 companion is incompatible: missing drive9 Runtime exec command; retry after the matching companion release is published" From 29c9627d233ff39fd167a8f1ef65807c7e5c9187 Mon Sep 17 00:00:00 2001 From: fangfang qi Date: Fri, 4 Dec 2026 15:17:16 +0800 Subject: [PATCH 2/3] test(fs): update layer smoke checks and allow companion startup time --- e2e/live_test.go | 4 ++-- internal/fs/tenant_control_test.go | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/e2e/live_test.go b/e2e/live_test.go index 0484cb9a..88a1aa82 100644 --- a/e2e/live_test.go +++ b/e2e/live_test.go @@ -349,7 +349,7 @@ func TestLiveFSCommandSurface(t *testing.T) { forkDryRun := runTI(t, bin, "--profile", profileName, "fs", "fork-layer", "--parent-layer-ref", "layer-1", "--layer-name", "child", "--dry-run", "--query", "checks[].name") forkDryRun.wantExitCode(0) forkDryRun.wantStdoutContains("companion_capability") - deleteLayerDryRun := runTI(t, bin, "--profile", profileName, "fs", "delete-layer", "--layer-ref", "layer-1", "--cascade", "--dry-run", "--query", "checks[].name") + deleteLayerDryRun := runTI(t, bin, "--profile", profileName, "fs", "delete-layer", "--layer-ref", "layer-1", "--force", "--dry-run", "--query", "checks[].name") deleteLayerDryRun.wantExitCode(0) deleteLayerDryRun.wantStdoutContains("companion_capability") unmountDryRun := runTI(t, bin, "--profile", profileName, "fs", "unmount-file-system", "--mount-path", "/tmp/ti-e2e-mount", "--ignore-absent", "--dry-run", "--query", "checks[].name") @@ -380,7 +380,7 @@ func TestLiveFSCommandSurface(t *testing.T) { {"fs", "describe-file-system-embedding-configuration", "--file-system-id", selected.FSTenantID}, {"fs", "read-file"}, {"fs", "list-files"}, {"fs", "describe-file"}, {"fs", "search-file-content"}, {"fs", "find-files"}, {"fs", "list-layers"}, - {"fs", "describe-layer"}, {"fs", "diff-layer"}, {"fs", "list-layer-chain", "--layer-ref", "layer-1"}, + {"fs", "describe-layer", "--layer-ref", "layer-1"}, }) } diff --git a/internal/fs/tenant_control_test.go b/internal/fs/tenant_control_test.go index 716007fc..c3de914a 100644 --- a/internal/fs/tenant_control_test.go +++ b/internal/fs/tenant_control_test.go @@ -102,7 +102,8 @@ func TestTenantControlCreateWaitUsesOnlyCompanionReadiness(t *testing.T) { service := directTenantService(home, server.URL) service.CompanionPath = companion - service.FSReadyWaitTimeout = time.Second + // This success case launches a freshly built companion twice. Allow for first-launch overhead. + service.FSReadyWaitTimeout = 10 * time.Second service.FSReadyWaitPollInterval = time.Millisecond result, err := service.CreateFileSystem(context.Background(), CreateFileSystemOptions{Profile: testProfile(), WaitUntilReady: true}) if err != nil { From 3a1899b64483251839ea01951a10e23d1cc41d93 Mon Sep 17 00:00:00 2001 From: fangfang qi Date: Fri, 4 Dec 2026 15:17:25 +0800 Subject: [PATCH 3/3] Validate the complete LayerFS v36 surface and mount audit --- AGENTS.md | 3 +- README.md | 2 +- docs/release-notes/v0.2.12.md | 7 ++ docs/releasing.md | 2 +- docs/spec/done/0032-ext01-layerfs-v36.md | 16 ++++ e2e/cli_test.go | 16 +++- e2e/installer_test.go | 6 +- e2e/live_layer_test.go | 17 ++++ internal/cli/commands.go | 19 ++-- internal/drive9cap/surface.go | 30 ++++++ internal/fs/drive9_companion.go | 113 +++++++++-------------- internal/fs/drive9_companion_test.go | 28 +++++- internal/fs/drive9_mount_audit.go | 13 ++- internal/fs/drive9_mount_audit_test.go | 12 +++ internal/fs/layer.go | 37 +++++--- internal/fs/mount.go | 2 +- internal/fs/mount_durability.go | 2 +- internal/fs/mount_durability_test.go | 1 + internal/fs/mountroot.go | 2 + internal/update/update.go | 33 +------ internal/update/update_test.go | 4 +- scripts/install.ps1 | 2 +- scripts/install.sh | 2 +- 23 files changed, 223 insertions(+), 146 deletions(-) create mode 100644 docs/spec/done/0032-ext01-layerfs-v36.md create mode 100644 internal/drive9cap/surface.go diff --git a/AGENTS.md b/AGENTS.md index 879dc174..d4561cff 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -80,7 +80,8 @@ Implemented: - Server-backed Filesystem token lifecycle management from `docs/spec/done/0030-file-system-token-lifecycle-management.md` - Historical filesystem layer workflows - from `docs/spec/done/0032-filesystem-layer-fork-workflows.md` + from `docs/spec/done/0032-filesystem-layer-fork-workflows.md`, updated by + `docs/spec/done/0032-ext01-layerfs-v36.md` - install and update distribution from `docs/spec/done/0012-install-and-update-distribution.md` - English PingCAP Preview documentation from diff --git a/README.md b/README.md index 70cf6c45..3f18f8b1 100644 --- a/README.md +++ b/README.md @@ -219,7 +219,7 @@ When a mount unpacks a local overlay (auto-unpack with a non-`none` mount profil `ti fs-vault run-with-secret` reads the named secret through the companion and runs the command from ti itself. The child receives only the secret fields plus an environment with ti credentials removed: the filesystem bearer token, the vault token, the organization API key pair, and the filesystem AI provider key are never inherited. Field names are exported with the same environment-key conversion as `ti fs-vault read-secret --format env` (ASCII letters upper-cased, digits and `_` kept, a leading digit prefixed with `_`, and every byte outside `A-Z`, `a-z`, `0-9`, and `_` replaced with `_`), so accented characters produce one underscore per UTF-8 byte; two fields that convert to the same key fail with a usage error instead of overwriting each other. A field that converts to a process-configuration variable is rejected with `vault.env_key_forbidden` instead of injected, because whoever can write a secret's fields could otherwise choose what the child loads or runs; the error lists every rejected field and what it would have configured: `PATH`, `PATHEXT`, `COMSPEC`, `SHELL`, shell startup and evaluation names such as `ENV`, `BASH_ENV`, `SHELLOPTS`, `PS4`, and `IFS`, dynamic-loader names such as `LD_PRELOAD`, `LD_LIBRARY_PATH`, `DYLD_INSERT_LIBRARIES`, and `GCONV_PATH`, language-runtime names such as `PYTHONPATH`, `PERL5OPT`, `NODE_OPTIONS`, `RUBYOPT`, `JAVA_TOOL_OPTIONS`, and `LUA_INIT`, and helper-selection names such as `SSH_AUTH_SOCK`, `GIT_SSH_COMMAND`, `GIT_CONFIG_GLOBAL`, and `PAGER`. The check matches exact names after conversion, except that a few families whose suffix the field name chooses are matched by prefix (`DYLD_*`, `LD_32_*`, `LD_64_*`, `GIT_CONFIG_KEY_`, `GIT_CONFIG_VALUE_`), and that trailing all-digit version segments are stripped before the lookup, so versioned spellings such as `LUA_INIT_5_4`, `LUA_PATH_5_4`, `LUA_CPATH_5_4`, and `LD_PRELOAD_32` hit the same entries as their base names (Lua reads the versioned name first, and the Solaris loader reads the 32/64-bit one). Names that merely resemble a rejected one, such as `SSH_PRIVATE_KEY`, `GIT_TOKEN`, `LD_PRELOAD_BACKUP`, or `DB_URL_2`, remain injectable. `ti fs-vault read-secret --format env` still converts those names, because it only prints values and never spawns a child. On Windows, an inherited variable that differs from an injected field only by letter case is replaced, because the platform resolves environment names case-insensitively. -Create a layer to try changes in an isolated working directory. Seed it with a recursive copy, then fork its current contents for an independent experiment. +Create a layer to try changes in an isolated working directory. Seed it with a recursive copy, then fork its current contents for an independent experiment. Create and fork accept TTLs in whole seconds or a duration such as `5m`. Each `--tag key=value` must have a unique key. An unpack-capable layer mount stops if its local overlay directory cannot be audited. ~~~shell export TI_FS_FILE_SYSTEM_ID="" diff --git a/docs/release-notes/v0.2.12.md b/docs/release-notes/v0.2.12.md index 6b05dde3..18176833 100644 --- a/docs/release-notes/v0.2.12.md +++ b/docs/release-notes/v0.2.12.md @@ -8,6 +8,13 @@ Create and fork return a generated layer ID and accept a lifetime and tags. Insp Checkpoint creation, historical mounts, ancestry listing, diff and rollback commands have been removed. Fork operates on the current parent layer. Layer-scoped search and find flags have been removed. Recursive copy supports layers. FUSE mounts audit unpacked files and check pack paths in the selected layer’s own overlay. +### Output changes + +- The text table from `list-layers` replaces `DURABILITY` with `FENCE`. +- `delete-layer` reports the companion status `deleted` where ti previously returned `abandoned`. +- `commit-layer` and `merge-layer` return `layer_id`, `status` and `applied_paths` on success. A merge conflict exits with an error. The v36 companion does not provide the former per-path conflict array. +- The installer checks all six layer commands. Read-only mounts omit the write durability option. + ## Upgrade Drain and unmount active mounts before replacing ti and its companion. The v0.2.11 updater still requires the previous companion command surface. Once v0.2.12 is published, use its installer to upgrade an existing installation or install a new one. diff --git a/docs/releasing.md b/docs/releasing.md index d752a98d..9df0f9d6 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -23,7 +23,7 @@ Do not claim that a ti rollback also rolls back Drive9. Windows users must rerun ## Prepare the release PR 1. Check the latest published ti release and changes since that tag. Use the next patch version for a companion refresh with no ti interface change. Include only merged changes in the release notes. -2. Check the Drive9 `version` file and checksum manifest at each source above. Confirm that they agree and contain all five ti targets: Darwin and Linux on amd64/arm64, and Windows on amd64. Download and verify the companion on the validation host, then inspect `ti-drive9 version`, `ti-drive9 fs layer help`, and `ti-drive9 mount --help`, and require `ti-drive9 exec --help` to exit zero. Do not parse Runtime help prose as an API. The required capabilities include layer `create`, `fork`, `merge`, `rm`, mount `--layer`, and the Runtime command from Drive9 #1022. Record the exact Drive9 version, full Git hash, and each artifact checksum in the release evidence. Publish the Drive9 artifact before the ti release. +2. Check the Drive9 `version` file and checksum manifest at each source above. Confirm that they agree and contain all five ti targets: Darwin and Linux on amd64/arm64, and Windows on amd64. Download and verify the companion on the validation host, then inspect `ti-drive9 version`, `ti-drive9 fs layer help`, and `ti-drive9 mount --help`, and require `ti-drive9 exec --help` to exit zero. Do not parse Runtime help prose as an API. The required capabilities include layer `create`, `ls`, `inspect`, `fork`, `merge`, `rm`, mount `--layer`, and the Runtime command from Drive9 #1022. Record the exact Drive9 version, full Git hash, and each artifact checksum in the release evidence. Publish the Drive9 artifact before the ti release. 3. Add `docs/release-notes/.md`, following recent notes. For a companion refresh, identify the tested Drive9 build, link the relevant upstream fixes, explain the mutable download source, and include upgrade and reinstall commands. Pass the ti version explicitly to the installer: downloading an installer from a tagged URL alone still defaults to installing the latest ti release. 4. Validate the candidate with the repository commands: diff --git a/docs/spec/done/0032-ext01-layerfs-v36.md b/docs/spec/done/0032-ext01-layerfs-v36.md new file mode 100644 index 00000000..f39db9cc --- /dev/null +++ b/docs/spec/done/0032-ext01-layerfs-v36.md @@ -0,0 +1,16 @@ +# Layer commands in ti v0.2.12 + +This revision supersedes the v35 command and output contracts in 0032 for filesystem layers. The installer and updater continue to fetch the latest companion. Each must verify its checksum and the v36 command surface before replacing the installed binary. + +| ti fs command | Companion operation | Contract | +| --- | --- | --- | +| create-layer | fs layer create | The service assigns the ID. A base root, optional name, actor, TTL and tags describe the new layer. | +| list-layers | fs layer ls | The text table includes FENCE. | +| describe-layer | fs layer inspect | Accepts either --layer-id or --layer-ref. | +| fork-layer | fs layer fork | Forks the current contents of the specified parent. | +| merge-layer, commit-layer | fs layer merge | Returns layer_id, status and applied_paths on success. A conflict exits with an error. | +| delete-layer | fs layer rm | Returns the companion's deletion status. --force permits deletion of an exclusively mounted layer. | + +Create and fork accept nonnegative integer seconds or a positive whole-second duration. Tag keys are unique and both keys and values are trimmed. Real execution and dry-run use the same validation. + +Checkpoint creation, historical checkpoint mounts, rollback, directory diff and ancestry listing are retired. The checkpoint, durability, caller-assigned ID and cascade options from v35 are retired. A layer mount resolves the ref with inspect before constructing the local overlay path. An unpack-capable layer mount must stop if ti cannot audit its layer overlay. diff --git a/e2e/cli_test.go b/e2e/cli_test.go index a9813b51..26594a26 100644 --- a/e2e/cli_test.go +++ b/e2e/cli_test.go @@ -1677,7 +1677,7 @@ func TestFSLayerForkWorkflowCommands(t *testing.T) { run := func(args ...string) commandResult { return runTIWithInput(t, bin, "", env, append([]string{"fs"}, args...)...) } - create := run("create-layer", "--base-root-path", "/workspace", "--layer-name", "child", "--ttl", "5m", "--tag", "k=v") + create := run("create-layer", "--base-root-path", "/workspace", "--layer-name", "child", "--ttl", "5m", "--tag", " k = v ") create.wantExitCode(0) fork := run("fork-layer", "--parent-layer-ref", "research-base", "--layer-name", "child", "--tag", "k=v", "--ttl", "1h", "--actor-id", "agent") fork.wantExitCode(0) @@ -1698,7 +1698,15 @@ func TestFSLayerForkWorkflowCommands(t *testing.T) { r.wantStdoutContains(`"applied_paths": 2`) } run("delete-layer", "--layer-ref", "child", "--force").wantExitCode(0) - removed := [][]string{{"fork-layer", "--checkpoint-id", "v1"}, {"mount-file-system", "--checkpoint-id", "cp"}, {"find-files", "--layer-id", "child"}, {"search-file-content", "--layer-id", "child"}, {"create-layer", "--layer-id", "forced"}, {"delete-layer", "--cascade"}} + for _, operation := range [][]string{{"create-layer", "--base-root-path", "/workspace"}, {"fork-layer", "--parent-layer-ref", "base"}} { + for _, bad := range [][]string{{"--ttl", "1.5s"}, {"--ttl", "-5"}, {"--ttl", "bogus"}, {"--tag", "missing-equals"}, {"--tag", "k=v", "--tag", " k =other"}} { + for _, dry := range [][]string{nil, {"--dry-run"}} { + args := append(append([]string{}, operation...), bad...) + run(append(args, dry...)...).wantExitCode(2) + } + } + } + removed := [][]string{{"fork-layer", "--checkpoint-id", "v1"}, {"mount-file-system", "--checkpoint-id", "cp"}, {"find-files", "--layer-id", "child"}, {"search-file-content", "--layer-id", "child"}, {"create-layer", "--layer-id", "forced"}, {"delete-layer", "--cascade"}, {"create-layer", "--durability-mode", "durable"}, {"fork-layer", "--layer-id", "child"}} for _, args := range removed { res := run(args...) res.wantExitCode(2) @@ -1710,8 +1718,8 @@ func TestFSLayerForkWorkflowCommands(t *testing.T) { mounted.wantStdoutContains(`"layer_id": "layer_01jz0123456789abcdefghjkmn"`) run("unmount-file-system", "--mount-path", mountPath).wantExitCode(0) calls := readFakeDrive9Calls(t, recordPath) - assertFakeDrive9Args(t, calls, []string{"fs", "layer", "create", "--json", "--name", "child", "--ttl", "5m", "--tag", "k=v", ":/workspace"}) - assertFakeDrive9Args(t, calls, []string{"fs", "layer", "fork", "--json", "--name", "child", "--ttl", "1h", "--tag", "k=v", "--actor", "agent", "research-base"}) + assertFakeDrive9Args(t, calls, []string{"fs", "layer", "create", "--json", "--name", "child", "--ttl", "300", "--tag", "k=v", ":/workspace"}) + assertFakeDrive9Args(t, calls, []string{"fs", "layer", "fork", "--json", "--name", "child", "--ttl", "3600", "--tag", "k=v", "--actor", "agent", "research-base"}) assertFakeDrive9Args(t, calls, []string{"fs", "layer", "merge", "--json", "child"}) assertFakeDrive9Args(t, calls, []string{"fs", "layer", "rm", "--json", "--force", "child"}) diff --git a/e2e/installer_test.go b/e2e/installer_test.go index ee7bc6d7..a1fb3ad7 100644 --- a/e2e/installer_test.go +++ b/e2e/installer_test.go @@ -3,6 +3,7 @@ package e2e import ( "crypto/sha256" "fmt" + "github.com/tidbcloud/ti-cli/internal/drive9cap" "os" "os/exec" "path/filepath" @@ -336,7 +337,10 @@ func TestInstallersValidateCompanionCommandSurfaceBeforeInstallation(t *testing. if powerShellValidation < 0 || powerShellInstall < 0 || powerShellValidation >= powerShellInstall { t.Fatal("install.ps1 must validate the staged companion before installing it") } - for _, required := range []string{"create", "fork", "merge", "rm", "layer", "exec"} { + if !strings.Contains(shell, "for command in "+drive9cap.LayerCommands+";") || !strings.Contains(powerShell, `@("`+strings.Join(strings.Fields(drive9cap.LayerCommands), `", "`)+`")`) { + t.Fatal("installer layer commands differ from runtime") + } + for _, required := range []string{"layer", "exec"} { if !strings.Contains(shell, required) || !strings.Contains(powerShell, required) { t.Fatalf("installers do not validate required companion surface %q", required) } diff --git a/e2e/live_layer_test.go b/e2e/live_layer_test.go index 25cad0a2..d3f46f19 100644 --- a/e2e/live_layer_test.go +++ b/e2e/live_layer_test.go @@ -1,6 +1,7 @@ package e2e import ( + "crypto/sha256" "encoding/json" "fmt" "os" @@ -90,7 +91,9 @@ func TestLiveFSLayerForkWorkflow(t *testing.T) { } mountLayer := func(layerRef, mountPath string) { t.Helper() + base := t.TempDir() args := []string{ + "--local-root", base, "--mount-profile", "portable", "--mount-path", mountPath, "--remote-path", remoteRoot, "--driver", "fuse", @@ -102,6 +105,10 @@ func TestLiveFSLayerForkWorkflow(t *testing.T) { result.wantStdoutContains(`"status": "mounted"`) result.wantStdoutContains(`"layer_ref": "` + layerRef + `"`) mounted[mountPath] = true + overlay := filepath.Join(base, "views", fmt.Sprintf("%x", sha256.Sum256([]byte(layerRef))), "overlay") + if info, err := os.Stat(overlay); err != nil || !info.IsDir() { + t.Fatalf("mounted layer has no overlay directory at %s: %v", overlay, err) + } } assertBaseAbsent := func(remotePath string) { t.Helper() @@ -143,8 +150,18 @@ func TestLiveFSLayerForkWorkflow(t *testing.T) { assertBaseAbsent(remoteRoot + "/seed.txt") child := liveLayerID(t, runFS("fork-layer", "--parent-layer-ref", parent, "--layer-name", "child-"+suffix, "--ttl", "1h")) layers = append(layers, child) + tree := t.TempDir() + if err := os.Mkdir(filepath.Join(tree, "nested"), 0700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(tree, "nested", "row"), []byte(suffix), 0600); err != nil { + t.Fatal(err) + } + runFS("copy-file", "--from-local", tree, "--to-remote", remoteRoot+"/copied", "--recursive", "--layer-id", child).wantExitCode(0) childMount := t.TempDir() mountLayer(child, childMount) + waitLiveLocalFile(t, filepath.Join(childMount, "copied", "nested", "row"), suffix, 30*time.Second) + assertBaseAbsent(remoteRoot + "/copied/nested/row") waitLiveLocalFile(t, filepath.Join(childMount, "seed.txt"), suffix, 30*time.Second) if err := os.WriteFile(filepath.Join(childMount, "trial.txt"), []byte("discard"), 0600); err != nil { t.Fatal(err) diff --git a/internal/cli/commands.go b/internal/cli/commands.go index 6ddae0c6..c314b751 100644 --- a/internal/cli/commands.go +++ b/internal/cli/commands.go @@ -2205,11 +2205,7 @@ func newFSCreateLayerCommand(info version.Info) *cobra.Command { if err != nil { return dryrun.Result{}, err } - tags, err := tifs.ParseLayerTagsForDryRun(opts.Tags) - if err != nil { - return dryrun.Result{}, err - } - ttl, err := tifs.LayerTTLSeconds(opts.TTL) + tags, ttl, err := tifs.LayerMetadata(opts.Tags, opts.TTL) if err != nil { return dryrun.Result{}, err } @@ -2278,11 +2274,7 @@ func newFSForkLayerCommand(info version.Info) *cobra.Command { if err := tifs.ValidateLayerReference(opts.ParentLayerRef, "--parent-layer-ref"); err != nil { return dryrun.Result{}, err } - tags, err := tifs.ParseLayerTagsForDryRun(opts.Tags) - if err != nil { - return dryrun.Result{}, err - } - ttl, err := tifs.LayerTTLSeconds(opts.TTL) + tags, ttl, err := tifs.LayerMetadata(opts.Tags, opts.TTL) if err != nil { return dryrun.Result{}, err } @@ -2291,7 +2283,7 @@ func newFSForkLayerCommand(info version.Info) *cobra.Command { "name": opts.LayerName, "ttl_seconds": ttl, "actor_id": opts.ActorID, - }, profile, authz.FSFileWrite, tifs.LayerCapabilityFork) + }, profile, authz.FSFileWrite) }, }, info) cmd.Flags().String("parent-layer-ref", "", "The parent layer ID, unique name, or supported tag reference.") @@ -2319,6 +2311,7 @@ func layerRefFlag(ctx commandContext) (string, error) { } func registerLayerRefFlags(cmd *cobra.Command) { + cmd.Long = strings.TrimSpace(cmd.Short + " Specify either --layer-ref or --layer-id.") cmd.Flags().String("layer-ref", "", "Layer ID, unique name, or tag reference.") cmd.Flags().String("layer-id", "", "Alias for --layer-ref.") cmd.MarkFlagsMutuallyExclusive("layer-id", "layer-ref") @@ -2380,7 +2373,7 @@ func newFSDeleteLayerCommand(info version.Info) *cobra.Command { if opts.Force { path += "?force=true" } - return service.DryRunLayerMutation(ctx.cmd.Context(), ctx.CommandPath(), "delete_layer", "DELETE", path, nil, profile, authz.FSFileWrite, tifs.LayerCapabilityDelete) + return service.DryRunLayerMutation(ctx.cmd.Context(), ctx.CommandPath(), "delete_layer", "DELETE", path, nil, profile, authz.FSFileWrite) }, }, info) cmd.Flags().String("layer-ref", "", "The layer ID, unique name, or supported tag reference.") @@ -2416,7 +2409,7 @@ func newFSMergeLayerCommand(info version.Info) *cobra.Command { if err != nil { return dryrun.Result{}, err } - return service.DryRunLayerMutation(ctx.cmd.Context(), ctx.CommandPath(), "merge_layer", "POST", "/v1/layers/"+url.PathEscape(strings.TrimSpace(layerID))+"/merge", map[string]any{}, profile, authz.FSFileWrite, tifs.LayerCapabilityMerge) + return service.DryRunLayerMutation(ctx.cmd.Context(), ctx.CommandPath(), "merge_layer", "POST", "/v1/layers/"+url.PathEscape(strings.TrimSpace(layerID))+"/merge", map[string]any{}, profile, authz.FSFileWrite) }, }, info) registerLayerRefFlags(cmd) diff --git a/internal/drive9cap/surface.go b/internal/drive9cap/surface.go new file mode 100644 index 00000000..6c3d75f7 --- /dev/null +++ b/internal/drive9cap/surface.go @@ -0,0 +1,30 @@ +// Package drive9cap describes the companion interface used by ti. +package drive9cap + +import ( + "slices" + "strings" + "unicode" +) + +// The standalone installers carry this list inline; installer tests check parity. +const LayerCommands = "create ls inspect fork merge rm" + +func HasToken(help, token string) bool { + return slices.Contains(strings.FieldsFunc(help, func(r rune) bool { + return unicode.IsSpace(r) || strings.ContainsRune("<>|", r) + }), token) +} + +func MissingLayerCommand(help string) string { + for _, command := range strings.Fields(LayerCommands) { + if !HasToken(help, command) { + return command + } + } + return "" +} + +func SupportsLayerMount(help string) bool { + return HasToken(help, "-layer") || HasToken(help, "--layer") +} diff --git a/internal/fs/drive9_companion.go b/internal/fs/drive9_companion.go index 70d0b3bc..b86efe1a 100644 --- a/internal/fs/drive9_companion.go +++ b/internal/fs/drive9_companion.go @@ -7,9 +7,11 @@ import ( "errors" "fmt" "io" + "maps" "os" "path/filepath" "regexp" + "slices" "sort" "strconv" "strings" @@ -20,6 +22,7 @@ import ( "github.com/tidbcloud/ti-cli/internal/apperr" "github.com/tidbcloud/ti-cli/internal/config" "github.com/tidbcloud/ti-cli/internal/config/region" + "github.com/tidbcloud/ti-cli/internal/drive9cap" "github.com/tidbcloud/ti-cli/internal/fs/fscred" "github.com/tidbcloud/ti-cli/internal/fs/mountlocator" "github.com/tidbcloud/ti-cli/internal/fswrap" @@ -52,13 +55,6 @@ type drive9CommandResult struct { Stdout string `json:"stdout,omitempty"` } -const ( - drive9CapabilityLayerFork = "layer-fork" - drive9CapabilityLayerMerge = "layer-merge" - drive9CapabilityLayerDelete = "layer-delete" - drive9CapabilityLayerMount = "layer-mount" -) - func (s Service) drive9Runner() fswrap.Runner { return fswrap.Runner{ HomeDir: s.HomeDir, @@ -81,72 +77,31 @@ func (s Service) drive9Run(ctx context.Context, profile *config.Profile, args [] }) } -func (s Service) requireDrive9Capabilities(ctx context.Context, profile *config.Profile, capabilities ...string) error { - needLayerHelp := false - needMountHelp := false - for _, capability := range capabilities { - switch capability { - case drive9CapabilityLayerFork, drive9CapabilityLayerMerge, drive9CapabilityLayerDelete: - needLayerHelp = true - case drive9CapabilityLayerMount: - needMountHelp = true - default: - return apperr.New("fs.companion_capability_unknown", "runtime", 1, fmt.Sprintf("unknown ti fs companion capability %q", capability)) - } +func (s Service) requireDrive9Layer(ctx context.Context, profile *config.Profile, mountLayer bool) error { + result, err := s.drive9Runner().Run(ctx, fswrap.RunOptions{Profile: profile, Args: []string{"fs", "layer", "help"}, CaptureStdout: true}) + if err != nil { + return incompatibleDrive9Error(err) } - - layerHelp := "" - if needLayerHelp { - result, err := s.drive9Runner().Run(ctx, fswrap.RunOptions{Profile: profile, Args: []string{"fs", "layer", "help"}, CaptureStdout: true}) - if err != nil { - return incompatibleDrive9Error(err) - } - layerHelp = string(result.Stdout) + "\n" + string(result.Stderr) + if missing := drive9cap.MissingLayerCommand(string(result.Stdout) + "\n" + string(result.Stderr)); missing != "" { + return incompatibleDrive9Error(fmt.Errorf("missing drive9 fs layer %s", missing)) } - mountHelp := "" - if needMountHelp { - result, err := s.drive9Runner().Run(ctx, fswrap.RunOptions{Profile: profile, Args: []string{"mount", "--help"}, CaptureStdout: true}) + if mountLayer { + mount, err := s.drive9Runner().Run(ctx, fswrap.RunOptions{Profile: profile, Args: []string{"mount", "--help"}, CaptureStdout: true}) if err != nil { return incompatibleDrive9Error(err) } - mountHelp = string(result.Stdout) + "\n" + string(result.Stderr) - } - - for _, capability := range capabilities { - available := false - switch capability { - case drive9CapabilityLayerFork: - available = layerHelpHasCommand(layerHelp, "fork") - case drive9CapabilityLayerMerge: - available = layerHelpHasCommand(layerHelp, "merge") - case drive9CapabilityLayerDelete: - available = layerHelpHasCommand(layerHelp, "rm") - case drive9CapabilityLayerMount: - available = layerHelpHasCommand(mountHelp, "-layer") || layerHelpHasCommand(mountHelp, "--layer") - } - if !available { - return incompatibleDrive9Error(nil) + if !drive9cap.SupportsLayerMount(string(mount.Stdout) + "\n" + string(mount.Stderr)) { + return incompatibleDrive9Error(fmt.Errorf("missing drive9 mount --layer")) } } return nil } -func layerHelpHasCommand(help, command string) bool { - for _, line := range strings.FieldsFunc(help, func(r rune) bool { - return r == '<' || r == '>' || r == '|' || r == ' ' || r == '\t' || r == '\r' || r == '\n' - }) { - if line == command { - return true - } - } - return false -} - func incompatibleDrive9Error(cause error) error { if isFSPlacementError(cause) { return cause } - message := "the installed ti-drive9 companion does not support filesystem layer fork workflows; update or reinstall ti after a compatible companion release is available" + message := "the installed ti-drive9 companion does not support the required filesystem layer commands or mount options; update or reinstall ti after a compatible companion release is available" if cause != nil { return apperr.Wrap("fs.companion_incompatible", "runtime", 1, message, cause) } @@ -626,16 +581,25 @@ func (s Service) drive9FindFiles(ctx context.Context, opts FindFilesOptions) (Se } func (s Service) drive9CreateLayer(ctx context.Context, opts CreateLayerOptions) (LayerResult, error) { + tags, ttl, err := LayerMetadata(opts.Tags, opts.TTL) + if err != nil { + return LayerResult{}, err + } baseRoot, err := normalizeRemotePath(opts.BaseRootPath) if err != nil { return LayerResult{}, err } + if err := s.requireDrive9Layer(ctx, opts.Profile, false); err != nil { + return LayerResult{}, err + } args := []string{"fs", "layer", "create", "--json"} appendFlagValue(&args, "--name", opts.LayerName) - appendFlagValue(&args, "--ttl", opts.TTL) + if strings.TrimSpace(opts.TTL) != "" { + args = append(args, "--ttl", strconv.FormatInt(ttl, 10)) + } appendFlagValue(&args, "--actor", opts.ActorID) - for _, tag := range opts.Tags { - appendFlagValue(&args, "--tag", tag) + for _, key := range slices.Sorted(maps.Keys(tags)) { + args = append(args, "--tag", key+"="+tags[key]) } args = append(args, drive9Remote(baseRoot)) result, err := s.drive9Run(ctx, opts.Profile, args, true) @@ -650,6 +614,9 @@ func (s Service) drive9CreateLayer(ctx context.Context, opts CreateLayerOptions) } func (s Service) drive9ListLayers(ctx context.Context, opts ListLayersOptions) (LayerListResult, error) { + if err := s.requireDrive9Layer(ctx, opts.Profile, false); err != nil { + return LayerListResult{}, err + } result, err := s.drive9RunTransientRetry(ctx, opts.Profile, []string{"fs", "layer", "ls", "--json"}, true) if err != nil { return LayerListResult{}, err @@ -662,14 +629,20 @@ func (s Service) drive9ListLayers(ctx context.Context, opts ListLayersOptions) ( } func (s Service) drive9ForkLayer(ctx context.Context, opts ForkLayerOptions) (LayerResult, error) { - if err := s.requireDrive9Capabilities(ctx, opts.Profile, drive9CapabilityLayerFork); err != nil { + tags, ttl, err := LayerMetadata(opts.Tags, opts.TTL) + if err != nil { + return LayerResult{}, err + } + if err := s.requireDrive9Layer(ctx, opts.Profile, false); err != nil { return LayerResult{}, err } args := []string{"fs", "layer", "fork", "--json"} appendFlagValue(&args, "--name", opts.LayerName) - appendFlagValue(&args, "--ttl", opts.TTL) - for _, tag := range opts.Tags { - appendFlagValue(&args, "--tag", tag) + if strings.TrimSpace(opts.TTL) != "" { + args = append(args, "--ttl", strconv.FormatInt(ttl, 10)) + } + for _, key := range slices.Sorted(maps.Keys(tags)) { + args = append(args, "--tag", key+"="+tags[key]) } appendFlagValue(&args, "--actor", opts.ActorID) args = append(args, strings.TrimSpace(opts.ParentLayerRef)) @@ -685,7 +658,7 @@ func (s Service) drive9ForkLayer(ctx context.Context, opts ForkLayerOptions) (La } func (s Service) drive9DeleteLayer(ctx context.Context, opts DeleteLayerOptions) (DeleteLayerResult, error) { - if err := s.requireDrive9Capabilities(ctx, opts.Profile, drive9CapabilityLayerDelete); err != nil { + if err := s.requireDrive9Layer(ctx, opts.Profile, false); err != nil { return DeleteLayerResult{}, err } args := []string{"fs", "layer", "rm", "--json"} @@ -717,7 +690,11 @@ func (s Service) drive9DescribeLayer(ctx context.Context, opts DescribeLayerOpti } func (s Service) MergeLayer(ctx context.Context, opts LayerActionOptions) (LayerMergeResult, error) { - if err := s.requireDrive9Capabilities(ctx, opts.Profile, drive9CapabilityLayerMerge); err != nil { + opts.LayerID = strings.TrimSpace(opts.LayerID) + if err := validateLayerReference(opts.LayerID, "--layer-ref"); err != nil { + return LayerMergeResult{}, err + } + if err := s.requireDrive9Layer(ctx, opts.Profile, false); err != nil { return LayerMergeResult{}, err } result, err := s.drive9Run(ctx, opts.Profile, []string{"fs", "layer", "merge", "--json", opts.LayerID}, true) diff --git a/internal/fs/drive9_companion_test.go b/internal/fs/drive9_companion_test.go index 1407db76..197047ad 100644 --- a/internal/fs/drive9_companion_test.go +++ b/internal/fs/drive9_companion_test.go @@ -388,7 +388,7 @@ func TestDrive9LayerForkAndDeleteTranslateToCompanion(t *testing.T) { t.Fatalf("unexpected fork response: %#v", forked) } forkCall := requireFakeDrive9Call(t, recordPath, "fs", "layer", "fork") - wantFork := []string{"fs", "layer", "fork", "--json", "--name", "style-analyst", "--ttl", "1h", "--tag", "env=dev", "--actor", "hermes", "research-base"} + wantFork := []string{"fs", "layer", "fork", "--json", "--name", "style-analyst", "--ttl", "3600", "--tag", "env=dev", "--actor", "hermes", "research-base"} if fmt.Sprint(forkCall.Args) != fmt.Sprint(wantFork) { t.Fatalf("fork args = %#v, want %#v", forkCall.Args, wantFork) } @@ -443,9 +443,26 @@ func TestDrive9LayerTipForkAndLeafDeleteOmitOptionalFlags(t *testing.T) { func TestDrive9LayerWorkflowRejectsIncompatibleCompanion(t *testing.T) { companion, _ := buildFakeDrive9(t) t.Setenv("TI_FAKE_DRIVE9_OLD_LAYER", "1") - _, err := testCompanionService(t.TempDir(), companion).ForkLayer(context.Background(), ForkLayerOptions{Profile: dataProfile(), ParentLayerRef: "parent"}) - if apperr.CodeFor(err) != "fs.companion_incompatible" { - t.Fatalf("error = %v, want fs.companion_incompatible", err) + svc := testCompanionService(t.TempDir(), companion) + ctx, p := context.Background(), dataProfile() + for _, call := range []func() error{ + func() error { + _, err := svc.CreateLayer(ctx, CreateLayerOptions{Profile: p, BaseRootPath: "/"}) + return err + }, + func() error { _, err := svc.ListLayers(ctx, ListLayersOptions{Profile: p}); return err }, + func() error { + _, err := svc.DescribeLayer(ctx, DescribeLayerOptions{Profile: p, LayerID: "child"}) + return err + }, + func() error { + _, err := svc.ForkLayer(ctx, ForkLayerOptions{Profile: p, ParentLayerRef: "parent"}) + return err + }, + } { + if err := call(); apperr.CodeFor(err) != "fs.companion_incompatible" { + t.Fatalf("expected companion incompatibility, got %v", err) + } } } @@ -475,7 +492,7 @@ func TestDrive9LayerMountUsesCanonicalIDAndRecordsReadOnly(t *testing.T) { t.Fatalf("unexpected layer mount result: %#v", result) } mountCall := requireFakeDrive9CallWithoutArg(t, recordPath, "--help", "mount") - want := []string{"mount", "--mode", "fuse", "--read-only", "--layer", "layer_01jz0123456789abcdefghjkmn", "--durability", "interactive", ":/research/q3-market", mountPath} + want := []string{"mount", "--mode", "fuse", "--read-only", "--layer", "layer_01jz0123456789abcdefghjkmn", ":/research/q3-market", mountPath} if fmt.Sprint(mountCall.Args) != fmt.Sprint(want) { t.Fatalf("mount args = %#v, want %#v", mountCall.Args, want) } @@ -503,6 +520,7 @@ func TestLayerReferenceValidation(t *testing.T) { code string }{ {name: "empty", value: " ", code: "fs.missing_layer_reference"}, + {name: "leading dash", value: "--force", code: "fs.invalid_layer_reference"}, {name: "slash", value: "parent/child", code: "fs.invalid_layer_reference"}, {name: "backslash", value: `parent\child`, code: "fs.invalid_layer_reference"}, {name: "control", value: "parent\nchild", code: "fs.invalid_layer_reference"}, diff --git a/internal/fs/drive9_mount_audit.go b/internal/fs/drive9_mount_audit.go index 3176c7df..fa30ef89 100644 --- a/internal/fs/drive9_mount_audit.go +++ b/internal/fs/drive9_mount_audit.go @@ -3,6 +3,7 @@ package fs import ( "context" "fmt" + "os" "path/filepath" "strconv" "strings" @@ -78,10 +79,10 @@ func (s Service) drive9MountFileSystem(ctx context.Context, opts MountFileSystem } } if opts.LayerRef != "" { - if err := s.requireDrive9Capabilities(ctx, opts.Profile, drive9CapabilityLayerMount); err != nil { + if err := s.requireDrive9Layer(ctx, opts.Profile, true); err != nil { return MountResult{}, err } - layer, err := s.DescribeLayer(ctx, DescribeLayerOptions{Profile: opts.Profile, LayerID: opts.LayerRef}) + layer, err := s.drive9DescribeLayer(ctx, DescribeLayerOptions{Profile: opts.Profile, LayerID: opts.LayerRef}) if err != nil { return MountResult{}, err } @@ -179,6 +180,14 @@ func (s Service) drive9MountFileSystem(ctx context.Context, opts MountFileSystem // so a slow archive cannot slip past it. readyErr := s.waitForMountReady(ctx, opts.MountPath, opts.ReadyTimeout, fmt.Sprintf("; to stop it run: ti fs unmount-file-system --mount-path %q", opts.MountPath)) if unpackPossible { + if opts.LayerID != "" { + overlay := filepath.Join(auditRoot, "overlay") + info, err := os.Lstat(overlay) + if err != nil || !info.IsDir() { + auditErr := apperr.New("fs.unpack_audit_incomplete", "runtime", 1, fmt.Sprintf("cannot audit the layer overlay directory %q", overlay)) + return MountResult{}, s.stopMountAfterUnsafeAudit(ctx, opts, auditErr) + } + } if auditErr := auditUnpackedOverlaySymlinks(auditRoot, overlayBefore); auditErr != nil { return MountResult{}, s.stopMountAfterUnsafeAudit(ctx, opts, auditErr) } diff --git a/internal/fs/drive9_mount_audit_test.go b/internal/fs/drive9_mount_audit_test.go index 721c46f9..51e3ed20 100644 --- a/internal/fs/drive9_mount_audit_test.go +++ b/internal/fs/drive9_mount_audit_test.go @@ -804,3 +804,15 @@ func TestLayerMountScopesUnpackAndPackPaths(t *testing.T) { t.Fatalf("unpack root=%q err=%v", unpackRoot, err) } } + +func TestLayerMountRequiresObservableOverlay(t *testing.T) { + companion, _ := buildFakeDrive9(t) + service := testCompanionService(t.TempDir(), companion) + service.mountPointActive = trueMountEvidence + _, err := service.MountFileSystem(context.Background(), MountFileSystemOptions{ + Profile: dataProfile(), Driver: "fuse", MountPath: t.TempDir(), LayerRef: "named-trial", LocalRoot: t.TempDir(), MountProfile: "portable", + }) + if apperr.CodeFor(err) != "fs.unpack_audit_incomplete" { + t.Fatalf("missing layer overlay: %v", err) + } +} diff --git a/internal/fs/layer.go b/internal/fs/layer.go index 62e62fd8..fcf05e4f 100644 --- a/internal/fs/layer.go +++ b/internal/fs/layer.go @@ -18,12 +18,6 @@ import ( "github.com/tidbcloud/ti-cli/internal/fs/fscred" ) -const ( - LayerCapabilityMerge = drive9CapabilityLayerMerge - LayerCapabilityFork = drive9CapabilityLayerFork - LayerCapabilityDelete = drive9CapabilityLayerDelete -) - type CreateLayerOptions struct { Profile *config.Profile BaseRootPath string @@ -104,10 +98,16 @@ func (s Service) DeleteLayer(ctx context.Context, opts DeleteLayerOptions) (Dele } func (s Service) DescribeLayer(ctx context.Context, opts DescribeLayerOptions) (LayerResult, error) { + if err := validateLayerReference(opts.LayerID, "--layer-ref"); err != nil { + return LayerResult{}, err + } + if err := s.requireDrive9Layer(ctx, opts.Profile, false); err != nil { + return LayerResult{}, err + } return s.drive9DescribeLayer(ctx, opts) } -func (s Service) DryRunLayerMutation(ctx context.Context, commandPath, operation, method, requestPath string, body any, profile *config.Profile, permission authz.Permission, capabilities ...string) (dryrun.Result, error) { +func (s Service) DryRunLayerMutation(ctx context.Context, commandPath, operation, method, requestPath string, body any, profile *config.Profile, permission authz.Permission) (dryrun.Result, error) { if profile == nil { return dryrun.Result{}, apperr.New("fs.missing_profile", "config", 2, "active profile is required") } @@ -125,12 +125,10 @@ func (s Service) DryRunLayerMutation(ctx context.Context, commandPath, operation } else { return dryrun.Result{}, apperr.New("auth.missing_fs_api_key", "authentication", 3, fmt.Sprintf("authentication required: missing fs_api_key for profile %q. Create or configure a ti fs resource first.", profileName(profile))) } - if len(capabilities) > 0 { - if err := s.requireDrive9Capabilities(ctx, profile, capabilities...); err != nil { - return dryrun.Result{}, err - } - checks = append(checks, dryrun.Check{Name: "companion_capability", Status: "passed", Message: strings.Join(capabilities, ", ")}) + if err := s.requireDrive9Layer(ctx, profile, false); err != nil { + return dryrun.Result{}, err } + checks = append(checks, dryrun.Check{Name: "companion_capability", Status: "passed", Message: "filesystem layer commands"}) return dryrun.New( commandPath, operation, @@ -152,6 +150,9 @@ func validateLayerReference(value, flagName string) error { if value == "" { return apperr.New("fs.missing_layer_reference", "usage", 2, flagName+" is required") } + if strings.HasPrefix(value, "-") { + return apperr.New("fs.invalid_layer_reference", "usage", 2, flagName+" must not start with a dash") + } if strings.ContainsAny(value, "/\\") { return apperr.New("fs.invalid_layer_reference", "usage", 2, fmt.Sprintf("%s must not contain path separators", flagName)) } @@ -185,8 +186,14 @@ func parseLayerTags(values []string) (map[string]string, error) { return out, nil } -func ParseLayerTagsForDryRun(values []string) (map[string]string, error) { - return parseLayerTags(values) +// LayerMetadata validates create and fork metadata for execution and dry runs. +func LayerMetadata(values []string, rawTTL string) (map[string]string, int64, error) { + tags, err := parseLayerTags(values) + if err != nil { + return nil, 0, err + } + ttl, err := LayerTTLSeconds(rawTTL) + return tags, ttl, err } func formatLayerTags(tags map[string]string) string { @@ -246,7 +253,7 @@ func (r LayerMergeResult) Human() string { return fmt.Sprintf("%s layer=%s applied_paths=%d", r.Status, r.LayerID, r.AppliedPaths) } -// LayerTTLSeconds converts the companion TTL flag into the wire value for dry-run output. +// LayerTTLSeconds converts a layer TTL to whole seconds. func LayerTTLSeconds(raw string) (int64, error) { s := strings.TrimSpace(raw) if s == "" { diff --git a/internal/fs/mount.go b/internal/fs/mount.go index a059e724..2bb8a2d1 100644 --- a/internal/fs/mount.go +++ b/internal/fs/mount.go @@ -195,7 +195,7 @@ func (s Service) DryRunMountFileSystem(ctx context.Context, commandPath string, return dryrun.Result{}, err } if opts.LayerRef != "" { - if err := s.requireDrive9Capabilities(ctx, opts.Profile, drive9CapabilityLayerMount); err != nil { + if err := s.requireDrive9Layer(ctx, opts.Profile, true); err != nil { return dryrun.Result{}, err } } diff --git a/internal/fs/mount_durability.go b/internal/fs/mount_durability.go index c2d65736..5c67dcf3 100644 --- a/internal/fs/mount_durability.go +++ b/internal/fs/mount_durability.go @@ -154,5 +154,5 @@ func companionMountMode(driver string) string { // an ordinary mount keeps the documented interactive default instead of the // engine's auto default. func mountDurabilityForwarded(opts MountFileSystemOptions) bool { - return companionMountMode(opts.Driver) == "fuse" + return !opts.ReadOnly && companionMountMode(opts.Driver) == "fuse" } diff --git a/internal/fs/mount_durability_test.go b/internal/fs/mount_durability_test.go index d4b1fc37..28d2cf71 100644 --- a/internal/fs/mount_durability_test.go +++ b/internal/fs/mount_durability_test.go @@ -165,6 +165,7 @@ func TestNormalizeMountDurabilityWebDAV(t *testing.T) { } } +// TestCompanionMountModeMatchesCompanionAutoResolution keeps auto mode in sync with the companion. func TestCompanionMountModeMatchesCompanionAutoResolution(t *testing.T) { wantAuto := "fuse" if runtime.GOOS == "darwin" || runtime.GOOS == "windows" { diff --git a/internal/fs/mountroot.go b/internal/fs/mountroot.go index 00c8615f..39188cc3 100644 --- a/internal/fs/mountroot.go +++ b/internal/fs/mountroot.go @@ -120,6 +120,8 @@ func companionMountRootLabel(remoteRoot string) string { return label } +// Drive9 bbb61cbc3ccda6748475a650035a9653922ad0ff defines the canonical ID +// in pkg/viewprotocol and its disk layout in pkg/mountstate/layer_local_root.go. var canonicalLayerID = regexp.MustCompile(`^layer_[0-9a-hjkmnp-tv-z]{26}$`) func layerLocalRoot(base, layerID string) string { diff --git a/internal/update/update.go b/internal/update/update.go index 78a3de06..c2bc35d6 100644 --- a/internal/update/update.go +++ b/internal/update/update.go @@ -25,6 +25,7 @@ import ( apitransport "github.com/tidbcloud/ti-cli/internal/api/transport" "github.com/tidbcloud/ti-cli/internal/apperr" "github.com/tidbcloud/ti-cli/internal/credentialenv" + "github.com/tidbcloud/ti-cli/internal/drive9cap" "github.com/tidbcloud/ti-cli/internal/version" ) @@ -793,17 +794,15 @@ func validateDrive9Companion(ctx context.Context, path string) error { if err != nil { return incompatibleDrive9CompanionError("read filesystem layer command surface", layerHelp, err) } - for _, command := range []string{"create", "fork", "merge", "rm"} { - if !drive9HelpHasToken(layerHelp, command) { - return incompatibleDrive9CompanionError("missing `drive9 fs layer "+command+"`", layerHelp, nil) - } + if command := drive9cap.MissingLayerCommand(layerHelp); command != "" { + return incompatibleDrive9CompanionError("missing `drive9 fs layer "+command+"`", layerHelp, nil) } mountHelp, err := drive9HelpOutput(ctx, path, "mount", "--help") if err != nil { return incompatibleDrive9CompanionError("read filesystem mount command surface", mountHelp, err) } - if !drive9HelpHasFlag(mountHelp, "layer") { + if !drive9cap.SupportsLayerMount(mountHelp) { return incompatibleDrive9CompanionError("missing `drive9 mount --layer`", mountHelp, nil) } @@ -824,30 +823,6 @@ func drive9HelpOutput(ctx context.Context, path string, args ...string) (string, return strings.TrimSpace(string(output)), err } -func drive9HelpHasToken(help, token string) bool { - return slicesContains(strings.FieldsFunc(help, func(r rune) bool { - return r == '<' || r == '>' || r == '|' || r == ' ' || r == '\t' || r == '\r' || r == '\n' - }), token) -} - -func drive9HelpHasFlag(help, flag string) bool { - for _, field := range strings.Fields(help) { - if field == "-"+flag || field == "--"+flag { - return true - } - } - return false -} - -func slicesContains(values []string, want string) bool { - for _, value := range values { - if value == want { - return true - } - } - return false -} - func incompatibleDrive9CompanionError(detail, output string, cause error) error { message := "downloaded ti-drive9 companion is incompatible with this ti release: " + detail + "; retry after the matching companion release is published" if output != "" { diff --git a/internal/update/update_test.go b/internal/update/update_test.go index 89dce6e0..ef047132 100644 --- a/internal/update/update_test.go +++ b/internal/update/update_test.go @@ -251,8 +251,8 @@ func TestValidateDrive9CompanionRejectsV35(t *testing.T) { t.Fatal(err) } err := validateDrive9Companion(context.Background(), path) - if apperr.CodeFor(err) != "update.companion_incompatible" || !strings.Contains(apperr.MessageFor(err), "fs layer merge") { - t.Fatalf("expected missing merge: %v", err) + if apperr.CodeFor(err) != "update.companion_incompatible" || !strings.Contains(apperr.MessageFor(err), "fs layer ls") { + t.Fatalf("expected missing ls: %v", err) } } diff --git a/scripts/install.ps1 b/scripts/install.ps1 index feff713a..bf2ad4fd 100644 --- a/scripts/install.ps1 +++ b/scripts/install.ps1 @@ -27,7 +27,7 @@ function Assert-CompanionCommandSurface($CompanionPath) { if ($LASTEXITCODE -ne 0) { Fail "downloaded ti-drive9 companion cannot report its filesystem layer commands" } - foreach ($command in @("create", "fork", "merge", "rm")) { + foreach ($command in @("create", "ls", "inspect", "fork", "merge", "rm")) { if ($layerHelp -notmatch "(?m)(^|[\s<|])$command([\s>|]|$)") { Fail "downloaded ti-drive9 companion is incompatible: missing drive9 fs layer $command" } diff --git a/scripts/install.sh b/scripts/install.sh index 6aafde3c..75e19e87 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -105,7 +105,7 @@ validate_companion() { if ! layer_help="$("$companion_path" fs layer help 2>&1)"; then error "downloaded ti-drive9 companion cannot report its filesystem layer commands" fi - for command in create fork merge rm; do + for command in create ls inspect fork merge rm; do if ! printf '%s\n' "$layer_help" | grep -Eq "(^|[[:space:]<|])${command}([[:space:]>|]|$)"; then error "downloaded ti-drive9 companion is incompatible: missing drive9 fs layer ${command}" fi