From 76767308600d5b4c5aac15ef51e439a9d60f1bdb Mon Sep 17 00:00:00 2001
From: Pascal Bleser
Date: Thu, 15 Oct 2026 14:34:42 +0200
Subject: [PATCH 1/9] feat: 1419: configure the revision cleanup of the
storage-users drivers
Wire reva's revision cleanup options into the 'decomposed', 'decomposeds3'
and 'posix' drivers, in the storage provider and in the data provider.
The options are a single 'revisions_cleanup' section of the storage-users
configuration, next to 'filemetadata_cache' and 'id_cache', as only one
driver is used at a time. Its environment variables:
- STORAGE_USERS_REVISIONS_CLEANUP_STRATEGY: which old revisions to
delete whenever a file gets a new revision, e.g. 'auto', '30d' or
'7d, auto, 90d'
- STORAGE_USERS_REVISIONS_CLEANUP_ASYNC: run the cleanup in background
workers
- STORAGE_USERS_REVISIONS_CLEANUP_ASYNC_WORKERS: number of background
workers
- STORAGE_USERS_REVISIONS_CLEANUP_ASYNC_QUEUE_SIZE: number of files that
can wait
- STORAGE_USERS_REVISIONS_CLEANUP_ASYNC_QUEUE_FULL: 'drop' or 'block'
- STORAGE_USERS_REVISIONS_CLEANUP_ASYNC_QUEUE_FULL_TIMEOUT: how long
'block' waits for room at most, 0 for as long as it takes
The strategy defaults to 'disabled', which keeps all revisions as before.
The other defaults are reva's: background workers, with the number of
workers and the queue size determined automatically, dropping the
cleanup of a file when the queue is full (it is cleaned up with its
next revision), and a timeout of 5s for 'block'.
Other commands that create a driver, 'posixfs scan' and 'uploads
sessions', clean up revisions without background workers: they could
exit before the workers are done, and stop the cleanup of a file
midway.
Assisted-by: Claude Code:claude-opus-5-5
---
opencloud/pkg/command/posixfs.go | 3 ++
services/storage-users/pkg/command/uploads.go | 3 ++
services/storage-users/pkg/config/config.go | 11 ++++
.../pkg/config/defaults/defaultconfig.go | 6 +++
.../storage-users/pkg/revaconfig/drivers.go | 35 ++++++++++++
.../pkg/revaconfig/drivers_test.go | 53 +++++++++++++++++++
6 files changed, 111 insertions(+)
diff --git a/opencloud/pkg/command/posixfs.go b/opencloud/pkg/command/posixfs.go
index 743f54f03d..3f81ed9669 100644
--- a/opencloud/pkg/command/posixfs.go
+++ b/opencloud/pkg/command/posixfs.go
@@ -121,6 +121,9 @@ the command is aborted with an error before performing any scanning.`,
// We want to initialize the driver but disable scanfs on boot, so we can trigger it manually afterwards
drivers := revaconfig.StorageProviderDrivers(cfg)
drivers["posix"] = revaconfig.Posix(cfg, false, false)
+ // Clean up revisions without background workers: the command could exit before
+ // they are done, and stop the cleanup of a file midway.
+ drivers["posix"].(map[string]any)["revisions_cleanup_async"] = false
var fsStream events.Stream
var err error
diff --git a/services/storage-users/pkg/command/uploads.go b/services/storage-users/pkg/command/uploads.go
index d84ee3d7a3..de2d07b5a1 100644
--- a/services/storage-users/pkg/command/uploads.go
+++ b/services/storage-users/pkg/command/uploads.go
@@ -117,6 +117,9 @@ func ListUploadSessions(cfg *config.Config) *cobra.Command {
fmt.Fprintf(os.Stderr, "No configuration found for filesystem driver '%s'\n", cfg.Driver)
os.Exit(1)
}
+ // Clean up revisions without background workers: the command could exit before
+ // they are done, and stop the cleanup of a file midway.
+ driverConf["revisions_cleanup_async"] = false
fs, err := f(driverConf, fsStream, nil)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to initialize filesystem driver '%s'\n", cfg.Driver)
diff --git a/services/storage-users/pkg/config/config.go b/services/storage-users/pkg/config/config.go
index 19506427b8..2e5012545e 100644
--- a/services/storage-users/pkg/config/config.go
+++ b/services/storage-users/pkg/config/config.go
@@ -30,6 +30,7 @@ type Config struct {
Events Events `yaml:"events"`
FilemetadataCache FilemetadataCache `yaml:"filemetadata_cache"`
IDCache IDCache `yaml:"id_cache"`
+ RevisionsCleanup RevisionsCleanup `yaml:"revisions_cleanup"`
MountID string `yaml:"mount_id" env:"STORAGE_USERS_MOUNT_ID" desc:"Mount ID of this storage." introductionVersion:"1.0.0"`
ReadOnly bool `yaml:"readonly" env:"STORAGE_USERS_READ_ONLY" desc:"Set this storage to be read-only." introductionVersion:"1.0.0"`
UploadExpiration int64 `yaml:"upload_expiration" env:"STORAGE_USERS_UPLOAD_EXPIRATION" desc:"Duration in seconds after which uploads will expire. Note that when setting this to a low number, uploads could be cancelled before they are finished and return a 403 to the user." introductionVersion:"1.0.0"`
@@ -226,6 +227,16 @@ type Events struct {
// TODO use TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OC_EVENTS_TLS_ROOT_CA_CERTIFICATE;STORAGE_USERS_EVENTS_TLS_ROOT_CA_CERTIFICATE" desc:"The root CA certificate used to validate the server's TLS certificate. If provided STORAGE_USERS_EVENTS_TLS_INSECURE will be seen as false." introductionVersion:"1.0.0"`
}
+// RevisionsCleanup configures the deletion of old revisions, for the 'decomposed', 'decomposeds3' and 'posix' storage drivers
+type RevisionsCleanup struct {
+ Strategy string `yaml:"strategy" env:"STORAGE_USERS_REVISIONS_CLEANUP_STRATEGY" desc:"Which old revisions (versions) of a file to delete whenever the file gets a new revision. 'disabled' keeps all revisions. A strategy is a comma-separated list of up to three parts: a number of revisions, which counts from the newest one (e.g. '10'), a duration with one of the units 'w', 'd', 'h', 'm' or 's' (e.g. '30d'; with the uppercase units 'D' and 'W', days and weeks count from midnight, e.g. '1D'), and 'auto', which thins out revisions the older they get. 'X' deletes everything beyond X, e.g. '10', '30d', or '0' to delete all revisions. 'X, auto' keeps everything within X and thins out the older revisions, e.g. '14d, auto'. 'auto, X' deletes everything beyond X and thins out the rest, e.g. 'auto, 90d'. 'X1, X2' keeps everything within X1 and deletes everything beyond X2, e.g. '5, 30d'. 'X1, auto, X2' also thins out in between, e.g. '7d, auto, 90d'. The age of a revision is the time its content was written, i.e. the modification time the file had before it was changed, not the time of that change. Only files that get a new revision are cleaned up, including revisions created from changes on disk with posix. An invalid value makes the storage driver fail at startup." introductionVersion:"%%NEXT%%"`
+ Async bool `yaml:"async" env:"STORAGE_USERS_REVISIONS_CLEANUP_ASYNC" desc:"Run the revision cleanup in background workers, so that it does not slow down the upload, restore or change that created the new revision. When set to false, the cleanup runs right away." introductionVersion:"%%NEXT%%"`
+ AsyncWorkers int `yaml:"async_workers" env:"STORAGE_USERS_REVISIONS_CLEANUP_ASYNC_WORKERS" desc:"Number of background workers for the revision cleanup. A value of 0 determines it automatically: half the available CPUs, respecting container CPU limits, but at least 2." introductionVersion:"%%NEXT%%"`
+ AsyncQueueSize int `yaml:"async_queue_size" env:"STORAGE_USERS_REVISIONS_CLEANUP_ASYNC_QUEUE_SIZE" desc:"Number of files that can wait for a background revision cleanup. A value of 0 determines it automatically: 64 per worker." introductionVersion:"%%NEXT%%"`
+ AsyncQueueFull string `yaml:"async_queue_full" env:"STORAGE_USERS_REVISIONS_CLEANUP_ASYNC_QUEUE_FULL" desc:"What happens when a file gets a new revision while the revision cleanup queue is full. 'drop' skips the cleanup of that file, which is cleaned up with its next revision. 'block' waits for room, up to STORAGE_USERS_REVISIONS_CLEANUP_ASYNC_QUEUE_FULL_TIMEOUT." introductionVersion:"%%NEXT%%"`
+ AsyncQueueFullTimeout time.Duration `yaml:"async_queue_full_timeout" env:"STORAGE_USERS_REVISIONS_CLEANUP_ASYNC_QUEUE_FULL_TIMEOUT" desc:"How long 'block' (see STORAGE_USERS_REVISIONS_CLEANUP_ASYNC_QUEUE_FULL) waits for room in the revision cleanup queue at most, after which the cleanup of that file is skipped as with 'drop'. A value of 0 waits as long as it takes, so that no cleanup is ever skipped, but then writes can slow down without bound under heavy load. See the Environment Variable Types description for more details." introductionVersion:"%%NEXT%%"`
+}
+
// FilemetadataCache holds cache config
type FilemetadataCache struct {
Store string `yaml:"store" env:"OC_CACHE_STORE;STORAGE_USERS_FILEMETADATA_CACHE_STORE" desc:"The type of the cache store. Supported values are: 'memory', 'nats-js-kv', 'noop'. See the text description for details." introductionVersion:"1.0.0"`
diff --git a/services/storage-users/pkg/config/defaults/defaultconfig.go b/services/storage-users/pkg/config/defaults/defaultconfig.go
index 504798445f..a8a277466f 100644
--- a/services/storage-users/pkg/config/defaults/defaultconfig.go
+++ b/services/storage-users/pkg/config/defaults/defaultconfig.go
@@ -173,6 +173,12 @@ func DefaultConfig() *config.Config {
Nodes: []string{"127.0.0.1:9233"},
Database: "ids-storage-users",
},
+ RevisionsCleanup: config.RevisionsCleanup{
+ Strategy: "disabled",
+ Async: true,
+ AsyncQueueFull: "drop",
+ AsyncQueueFullTimeout: 5 * time.Second,
+ },
Tasks: config.Tasks{
PurgeTrashBin: config.PurgeTrashBin{
ProjectDeleteBefore: 30 * 24 * time.Hour,
diff --git a/services/storage-users/pkg/revaconfig/drivers.go b/services/storage-users/pkg/revaconfig/drivers.go
index 24c4f1ef46..bf52e50c98 100644
--- a/services/storage-users/pkg/revaconfig/drivers.go
+++ b/services/storage-users/pkg/revaconfig/drivers.go
@@ -104,6 +104,13 @@ func Posix(cfg *config.Config, enableFSScan, enableFSWatch bool) map[string]any
"metadata_prefix": cfg.Drivers.Posix.MetadataPrefix,
"multi_tenant_enabled": cfg.Commons.MultiTenantEnabled,
"propagator": cfg.Drivers.Posix.Propagator,
+
+ "revisions_cleanup_strategy": cfg.RevisionsCleanup.Strategy,
+ "revisions_cleanup_async": cfg.RevisionsCleanup.Async,
+ "revisions_cleanup_async_workers": cfg.RevisionsCleanup.AsyncWorkers,
+ "revisions_cleanup_async_queue_size": cfg.RevisionsCleanup.AsyncQueueSize,
+ "revisions_cleanup_async_queue_full": cfg.RevisionsCleanup.AsyncQueueFull,
+ "revisions_cleanup_async_queue_full_timeout": cfg.RevisionsCleanup.AsyncQueueFullTimeout,
"async_propagator_options": map[string]any{
"propagation_delay": cfg.Drivers.Posix.AsyncPropagatorOptions.PropagationDelay,
},
@@ -209,6 +216,13 @@ func Decomposed(cfg *config.Config) map[string]any {
"max_quota": cfg.Drivers.Decomposed.MaxQuota,
"disable_versioning": cfg.Drivers.Decomposed.DisableVersioning,
"multi_tenant_enabled": cfg.Commons.MultiTenantEnabled,
+
+ "revisions_cleanup_strategy": cfg.RevisionsCleanup.Strategy,
+ "revisions_cleanup_async": cfg.RevisionsCleanup.Async,
+ "revisions_cleanup_async_workers": cfg.RevisionsCleanup.AsyncWorkers,
+ "revisions_cleanup_async_queue_size": cfg.RevisionsCleanup.AsyncQueueSize,
+ "revisions_cleanup_async_queue_full": cfg.RevisionsCleanup.AsyncQueueFull,
+ "revisions_cleanup_async_queue_full_timeout": cfg.RevisionsCleanup.AsyncQueueFullTimeout,
"filemetadatacache": map[string]any{
"cache_store": cfg.FilemetadataCache.Store,
"cache_nodes": cfg.FilemetadataCache.Nodes,
@@ -269,6 +283,13 @@ func DecomposedNoEvents(cfg *config.Config) map[string]any {
"max_quota": cfg.Drivers.Decomposed.MaxQuota,
"disable_versioning": cfg.Drivers.Decomposed.DisableVersioning,
"multi_tenant_enabled": cfg.Commons.MultiTenantEnabled,
+
+ "revisions_cleanup_strategy": cfg.RevisionsCleanup.Strategy,
+ "revisions_cleanup_async": cfg.RevisionsCleanup.Async,
+ "revisions_cleanup_async_workers": cfg.RevisionsCleanup.AsyncWorkers,
+ "revisions_cleanup_async_queue_size": cfg.RevisionsCleanup.AsyncQueueSize,
+ "revisions_cleanup_async_queue_full": cfg.RevisionsCleanup.AsyncQueueFull,
+ "revisions_cleanup_async_queue_full_timeout": cfg.RevisionsCleanup.AsyncQueueFullTimeout,
"filemetadatacache": map[string]any{
"cache_store": cfg.FilemetadataCache.Store,
"cache_nodes": cfg.FilemetadataCache.Nodes,
@@ -334,6 +355,13 @@ func DecomposedS3(cfg *config.Config) map[string]any {
"disable_versioning": cfg.Drivers.DecomposedS3.DisableVersioning,
"multi_tenant_enabled": cfg.Commons.MultiTenantEnabled,
"asyncfileuploads": cfg.Drivers.DecomposedS3.AsyncUploads,
+
+ "revisions_cleanup_strategy": cfg.RevisionsCleanup.Strategy,
+ "revisions_cleanup_async": cfg.RevisionsCleanup.Async,
+ "revisions_cleanup_async_workers": cfg.RevisionsCleanup.AsyncWorkers,
+ "revisions_cleanup_async_queue_size": cfg.RevisionsCleanup.AsyncQueueSize,
+ "revisions_cleanup_async_queue_full": cfg.RevisionsCleanup.AsyncQueueFull,
+ "revisions_cleanup_async_queue_full_timeout": cfg.RevisionsCleanup.AsyncQueueFullTimeout,
"filemetadatacache": map[string]any{
"cache_store": cfg.FilemetadataCache.Store,
"cache_nodes": cfg.FilemetadataCache.Nodes,
@@ -398,6 +426,13 @@ func DecomposedS3NoEvents(cfg *config.Config) map[string]any {
"disable_versioning": cfg.Drivers.DecomposedS3.DisableVersioning,
"multi_tenant_enabled": cfg.Commons.MultiTenantEnabled,
"lock_cycle_duration_factor": cfg.Drivers.DecomposedS3.LockCycleDurationFactor,
+
+ "revisions_cleanup_strategy": cfg.RevisionsCleanup.Strategy,
+ "revisions_cleanup_async": cfg.RevisionsCleanup.Async,
+ "revisions_cleanup_async_workers": cfg.RevisionsCleanup.AsyncWorkers,
+ "revisions_cleanup_async_queue_size": cfg.RevisionsCleanup.AsyncQueueSize,
+ "revisions_cleanup_async_queue_full": cfg.RevisionsCleanup.AsyncQueueFull,
+ "revisions_cleanup_async_queue_full_timeout": cfg.RevisionsCleanup.AsyncQueueFullTimeout,
"filemetadatacache": map[string]any{
"cache_store": cfg.FilemetadataCache.Store,
"cache_nodes": cfg.FilemetadataCache.Nodes,
diff --git a/services/storage-users/pkg/revaconfig/drivers_test.go b/services/storage-users/pkg/revaconfig/drivers_test.go
index 04daf08188..4877762e80 100644
--- a/services/storage-users/pkg/revaconfig/drivers_test.go
+++ b/services/storage-users/pkg/revaconfig/drivers_test.go
@@ -1,8 +1,11 @@
package revaconfig
import (
+ "errors"
"testing"
+ "time"
+ "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/options"
"github.com/test-go/testify/require"
"github.com/opencloud-eu/opencloud/pkg/config/envdecode"
@@ -60,3 +63,53 @@ func TestLegacyDriverAliases(t *testing.T) {
})
}
}
+
+func TestRevisionsCleanupReachesAllDrivers(t *testing.T) {
+ drivers := func(t *testing.T) map[string]map[string]any {
+ cfg := defaults.FullDefaultConfig()
+ cfg.Commons = &shared.Commons{GRPCClientTLS: &shared.GRPCClientTLS{}}
+ if err := envdecode.Decode(cfg); !errors.Is(err, envdecode.ErrNoTargetFieldsAreSet) {
+ require.NoError(t, err)
+ }
+ return map[string]map[string]any{
+ "posix": Posix(cfg, false, false),
+ "decomposed": Decomposed(cfg),
+ "decomposed no events": DecomposedNoEvents(cfg),
+ "decomposeds3": DecomposedS3(cfg),
+ "decomposeds3 no events": DecomposedS3NoEvents(cfg),
+ }
+ }
+
+ t.Run("defaults keep all revisions", func(t *testing.T) {
+ for name, driver := range drivers(t) {
+ o, err := options.New(driver)
+ require.NoError(t, err, name)
+ require.Equal(t, "disabled", o.RevisionsCleanupStrategy, name)
+ require.True(t, o.RevisionsCleanupAsync, name)
+ require.Equal(t, 0, o.RevisionsCleanupAsyncWorkers, name)
+ require.Equal(t, 0, o.RevisionsCleanupAsyncQueueSize, name)
+ require.Equal(t, "drop", o.RevisionsCleanupAsyncQueueFull, name)
+ require.Equal(t, 5*time.Second, o.RevisionsCleanupAsyncQueueFullTimeout, name)
+ }
+ })
+
+ t.Run("environment variables", func(t *testing.T) {
+ t.Setenv("STORAGE_USERS_REVISIONS_CLEANUP_STRATEGY", "7d, auto, 90d")
+ t.Setenv("STORAGE_USERS_REVISIONS_CLEANUP_ASYNC", "false")
+ t.Setenv("STORAGE_USERS_REVISIONS_CLEANUP_ASYNC_WORKERS", "3")
+ t.Setenv("STORAGE_USERS_REVISIONS_CLEANUP_ASYNC_QUEUE_SIZE", "42")
+ t.Setenv("STORAGE_USERS_REVISIONS_CLEANUP_ASYNC_QUEUE_FULL", "block")
+ t.Setenv("STORAGE_USERS_REVISIONS_CLEANUP_ASYNC_QUEUE_FULL_TIMEOUT", "1m")
+ for name, driver := range drivers(t) {
+ // decoded by reva, so that a key it does not know would show up as a default value
+ o, err := options.New(driver)
+ require.NoError(t, err, name)
+ require.Equal(t, "7d, auto, 90d", o.RevisionsCleanupStrategy, name)
+ require.False(t, o.RevisionsCleanupAsync, name)
+ require.Equal(t, 3, o.RevisionsCleanupAsyncWorkers, name)
+ require.Equal(t, 42, o.RevisionsCleanupAsyncQueueSize, name)
+ require.Equal(t, "block", o.RevisionsCleanupAsyncQueueFull, name)
+ require.Equal(t, time.Minute, o.RevisionsCleanupAsyncQueueFullTimeout, name)
+ }
+ })
+}
From 26a7b4f9037d77d4d7f46cb5c001804efe1e48fe Mon Sep 17 00:00:00 2001
From: Pascal Bleser
Date: Thu, 15 Oct 2026 15:27:17 +0200
Subject: [PATCH 2/9] feat: 1419: add a command to clean up old revisions on
demand
'opencloud storage-users revisions cleanup' deletes old revisions,
according to a cleanup strategy, of:
- the files of spaces (--space, repeatable),
- or of a file or folder within a space (--space with --path),
- or of all spaces (--all),
- or of a file or folder given by its path on disk (--fs-path, posix
only).
The id of a file or folder is rejected as the id of a space, as the
command would otherwise clean up its whole space. So is an id without a
space id, e.g. 'storage$'.
The storage-users service only cleans up the revisions of a file when it
gets a new one. The command also covers the files that are not changed
anymore, and applies a different strategy once.
The strategy and the settings of the background workers default to the
configured ones (STORAGE_USERS_REVISIONS_CLEANUP_*), and can be
overridden with --strategy, --async, --workers and --queue-size. Only
--queue-full defaults to 'block' without a timeout, whatever is
configured: the command finds files faster than the workers clean them
up, so dropping the files that find the queue full, or giving up after
the timeout meant for uploads, would skip most of them.
--queue-full-timeout sets one for the run.
The command uses the storage driver directly, in its own process, like
'uploads sessions': posix neither scans nor watches the file system, and
no driver joins the postprocessing consumer group of the service.
For posix, the driver needs NATS for its event stream. The command waits
for it 10 seconds at most, instead of the 15 minutes the stream retries
for, and ctrl-c also stops that wait: with the single binary, NATS only
runs within the server (opencloud-eu/opencloud#3805). The driver gets
the logger of the command: posix passes it on to the NATS connections
of its id cache, whose handlers would panic on a lost connection
without one. Ctrl-C also stops waiting for the driver, e.g. for the id
cache, which retries for up to 15 minutes as well.
Unless it is a dry run, which changes nothing on disk, the command
warns when the storage belongs to another user than the one it runs as,
e.g. root: the lock files it creates belong to that user, and the
server may not be able to lock these files anymore.
Output: a line for every file whose revisions were deleted, that failed
or that was skipped, with its path within its space, and a summary;
--verbose adds every file and every revision with the decision and its
reason; --json prints the same as JSON objects, one per line, with a
final summary object. --dry-run deletes nothing.
--timeout stops the cleanup gracefully, as does ctrl-c, and a second
ctrl-c ends the command right away, which can leave the blob of a
deleted revision behind; the help says so. Whether the timeout or ctrl-c
stopped the cleanup is told by the contexts of the command, not by the
error: the storage can return context errors of its own. --shuffle walks
the spaces and folders in a random order, so that repeated runs that
are stopped by the timeout, e.g. from a cron job, eventually reach all
files. The help explains that a file waiting for a lock can't be
interrupted, and that a dry run changes nothing on disk, but decides on
a snapshot, as it doesn't keep the files locked while it decides.
The common flags have short forms: -a (--all), -p (--fs-path),
-s (--strategy), -n (--dry-run), -v (--verbose), -j (--json) and
-t (--timeout).
Exit codes:
- 0 when done,
- 1 if the cleanup or any file failed, or if it was interrupted,
- 2 if the timeout stopped the cleanup before all files were cleaned
up.
The storage-users README documents the command, along with the cleanup
strategies and how they relate to the configured cleanup.
Assisted-by: Claude Code:claude-opus-5-5
---
services/storage-users/README.md | 131 +++-
.../storage-users/pkg/command/revisions.go | 692 ++++++++++++++++++
.../pkg/command/revisions_test.go | 417 +++++++++++
services/storage-users/pkg/command/root.go | 1 +
4 files changed, 1240 insertions(+), 1 deletion(-)
create mode 100644 services/storage-users/pkg/command/revisions.go
create mode 100644 services/storage-users/pkg/command/revisions_test.go
diff --git a/services/storage-users/README.md b/services/storage-users/README.md
index a7194a707c..470eb0fcd6 100644
--- a/services/storage-users/README.md
+++ b/services/storage-users/README.md
@@ -266,7 +266,7 @@ opencloud storage-users blobstore get --space-id=b19ec764-5398-458a-8ff1-1925bd9
### Manage Trash-Bin Items
-This command set provides commands to get an overview of trash-bin items, restore items and purge old items of `personal` spaces and `project` spaces (spaces that have been created manually). `trash-bin` commands require a `spaceID` as parameter.
+This command set provides commands to get an overview of trash-bin items, restore items and purge old items of `personal` spaces and `project` spaces (spaces that have been created manually). `trash-bin` commands require a `spaceID` as parameter.
```bash
opencloud storage-users trash-bin
@@ -333,6 +333,135 @@ When the CLI tool restores the item with the `replace` option, the existing item
opencloud storage-users trash-bin restore [command options] ['spaceID' required] ['itemID' required]
```
+### Clean Up Old Revisions
+
+Every change to a file keeps its previous content as a revision (version). With `STORAGE_USERS_REVISIONS_CLEANUP_STRATEGY`, the `storage-users` service deletes old revisions according to a cleanup strategy, whenever a file gets a new revision.
+
+The `decomposed`, `decomposeds3` and `posix` storage drivers are supported, with `posix` also for the revisions created from changes on disk.
+
+The default strategy `disabled` keeps all revisions and, as one would expect, does not perform any cleanup process for revisions at all.
+
+The service only cleans up a file when it gets a new revision, so files that are never changed again keep their revisions.
+
+The `revisions cleanup` command cleans up the revisions of whole spaces, folders or files on demand, to cover those files as well, or to apply a different strategy once, e.g. after changing the strategy or to free storage.
+
+```bash
+opencloud storage-users revisions cleanup [flags]
+```
+
+The command uses the storage directly, with the configuration of the `storage-users` service, and can run while the service is running. It needs access to the storage and, for the `posix` driver, to NATS. With the single binary, NATS runs within the server: without a running server, the command gives up after 10 seconds. It needs no service account.
+
+Run the command as the user that OpenCloud runs as, e.g. with `sudo -u opencloud` on a server where OpenCloud runs as the user `opencloud`, or with `docker exec` in its container. The lock files the command creates belong to the user that runs it, with permissions only for that user, so OpenCloud may not be able to lock these files anymore if it was run as another user, e.g. as `root`. Unless it is a dry run, which changes nothing on disk, the command warns when the storage belongs to another user.
+
+#### Strategies
+
+A strategy is a comma-separated list of up to three parts.
+
+Each `X` is either
+* a number, which is a number of revisions, always counting from the newest one,
+* or a duration with one of the units `w` (weeks), `d` (days), `h` (hours), `m` (minutes) or `s` (seconds).
+
+Durations in days or weeks can use an uppercase unit, `D` or `W`, to count from midnight (server time) instead of from now: `1d` means the last 24 hours, `1D` since yesterday 00:00.
+
+| Strategy | Meaning | Examples |
+|---|---|---|
+| `auto` | Thin out revisions the older they get: one per 10 seconds in the last minute, one per minute in the last hour, one per hour in the last 24 hours, one per day in the last 30 days, one per week beyond | `auto` |
+| `X` | Delete everything beyond `X` | `10`, `30d`, `0` deletes all revisions |
+| `X, auto` | Keep everything within `X`, thin out the older revisions | `14d, auto` |
+| `auto, X` | Delete everything beyond `X`, thin out the rest | `auto, 90d`, `auto, 50` |
+| `X1, X2` | Keep everything within `X1`, delete everything beyond `X2`; one must be a number, the other a duration | `5, 30d`, `7d, 10` |
+| `X1, auto, X2` | Keep everything within `X1`, delete everything beyond `X2`, thin out in between | `7d, auto, 90d`, `1D, auto, 30d` |
+| `disabled` | Never delete revisions | `disabled` |
+
+Note that the age of a revision is the time its content was written, i.e. the modification time the file had before it was changed, which is also the date the version list shows for it. It is not the time the file was changed, which turned that content into a revision. A document that was unchanged for two months gets a revision that is two months old when it is changed, and e.g. `30d` deletes that revision right away. Combine a duration with a number of revisions, e.g. `5, 30d`, to always keep the newest ones.
+
+#### Selecting the Files
+
+Exactly one of these selects the files to clean up:
+
+* `--space `: all files of a space. It can be given several times. The space IDs are accepted as the APIs show them, e.g. `$`. The ID of a file or folder within the space (`$!`) is rejected: give the space with `--space` and the file or folder with `--path`.
+* `--space --path `: only a file or a folder (recursively) within one space, e.g. `--path /Documents`.
+* `--all` (`-a`): all files of all spaces, including disabled spaces, which are skipped.
+* `--fs-path ` (`-p`): a file or a folder (recursively) by its path on disk. Only supported by the `posix` driver.
+
+#### Options
+
+The strategy and the settings of the background workers default to the configured ones and can be overridden for a run. Only `--queue-full` defaults to `block` without a timeout, whatever is configured: the command finds files faster than the workers clean them up, so dropping the files that find the queue full would skip most of them.
+
+| Flag | Default | Meaning |
+|---|---|---|
+| `--strategy`, `-s` | `STORAGE_USERS_REVISIONS_CLEANUP_STRATEGY` | The strategy, see above. The command fails if there is none. |
+| `--async` | `STORAGE_USERS_REVISIONS_CLEANUP_ASYNC` | Clean up files in background workers while looking for more. |
+| `--workers` | `STORAGE_USERS_REVISIONS_CLEANUP_ASYNC_WORKERS` | The number of background workers, `0` for half the available CPUs, at least 2. |
+| `--queue-size` | `STORAGE_USERS_REVISIONS_CLEANUP_ASYNC_QUEUE_SIZE` | The number of files that can wait for a worker, `0` for 64 per worker. |
+| `--queue-full` | `block` | `block` waits for room in a full queue, `drop` skips the file. |
+| `--queue-full-timeout` | `0` | With `block`, skip a file after waiting this long for room, e.g. `10s`. `0` waits as long as it takes. |
+| `--dry-run`, `-n` | off | Delete nothing, only print what would be deleted. |
+| `--verbose`, `-v` | off | Print every file and every revision, with what was decided about it and why. |
+| `--json`, `-j` | off | Print JSON objects, one per line, instead of text. |
+| `--timeout`, `-t` | none | Stop the cleanup gracefully after this time, e.g. `30m` or `2h`. |
+| `--shuffle` | off | Clean up the spaces, and the files within each folder, in a random order. |
+
+By default, the command prints a line for every file whose revisions it deleted, that it could not clean up or that it skipped, with the space ID and the path of the file within the space, and a summary:
+
+```plaintext
+25b69780-5f39-43be-a7ac-a9b9e9fe4230 /Documents/report.odt: deleted 3 of 12 revisions (4.2 MiB)
+25b69780-5f39-43be-a7ac-a9b9e9fe4230 /Photos/holiday.jpg: skipped: an upload to the file is still being processed
+1520 files in 3 spaces: deleted 3 revisions (4.2 MiB) of 1 file, 1 skipped, 0 failed
+```
+
+With `--verbose`, every revision is listed with the decision (`deleted`, `kept` or `protected`), its time, its size and the reason:
+
+```plaintext
+25b69780-5f39-43be-a7ac-a9b9e9fe4230 /dir1/file1 (node 43ca5408-c77b-4d9a-8a3b-d4470b1253b8): would delete 1 of 3 revisions (1.2 KiB)
+ protected 2026-10-15T13:24:35+02:00 1.2 KiB protected by "1": one of the 1 newest
+ kept 2026-10-13T15:24:35+02:00 1.2 KiB kept by "30d": not older than 2026-09-15T15:24:35+02:00
+ deleted 2026-03-29T15:24:35+02:00 1.2 KiB deleted by "30d": older than 2026-09-15T15:24:35+02:00
+```
+
+With `--json`, every file is an object of the `type` `file`, with the revisions in `details` when `--verbose` is set, and the last line is an object of the `type` `summary`. The sizes are in bytes. The same run as above:
+
+```json
+{"type":"file","space_id":"25b69780-5f39-43be-a7ac-a9b9e9fe4230","node_id":"8a1c0e2f-6b4d-4f7a-9c3e-2d5b7f1a0c94","path":"/Documents/report.odt","dry_run":false,"revisions":12,"deleted":3,"deleted_bytes":4404019,"failed":0}
+{"type":"file","space_id":"25b69780-5f39-43be-a7ac-a9b9e9fe4230","node_id":"f3e9d2c1-0a7b-4c8e-b6d5-9e4f1a2b3c7d","path":"/Photos/holiday.jpg","dry_run":false,"skipped":"an upload to the file is still being processed","revisions":0,"deleted":0,"deleted_bytes":0,"failed":0}
+{"type":"summary","dry_run":false,"spaces":3,"files":1520,"cleaned":1,"deleted":3,"deleted_bytes":4404019,"skipped":1,"failed":0}
+```
+
+With `--verbose` as well, a file object lists its revisions in `details`, here from the dry run above:
+
+```json
+{"type":"file","space_id":"25b69780-5f39-43be-a7ac-a9b9e9fe4230","node_id":"43ca5408-c77b-4d9a-8a3b-d4470b1253b8","path":"/dir1/file1","dry_run":true,"revisions":3,"deleted":1,"deleted_bytes":1234,"failed":0,"details":[{"key":"43ca5408-c77b-4d9a-8a3b-d4470b1253b8.REV.2026-10-15T11:24:35.118424081Z","time":"2026-10-15T11:24:35.118424081Z","size":1234,"decision":"protected","reason":"protected by \"1\": one of the 1 newest"},{"key":"43ca5408-c77b-4d9a-8a3b-d4470b1253b8.REV.2026-10-13T13:24:35.118424081Z","time":"2026-10-13T13:24:35.118424081Z","size":1234,"decision":"kept","reason":"kept by \"30d\": not older than 2026-09-15T15:24:35+02:00"},{"key":"43ca5408-c77b-4d9a-8a3b-d4470b1253b8.REV.2026-03-29T13:24:35.118424081Z","time":"2026-03-29T13:24:35.118424081Z","size":1234,"decision":"deleted","reason":"deleted by \"30d\": older than 2026-09-15T15:24:35+02:00"}]}
+```
+
+A file that failed has an `error`, and so has a revision in `details` that could not be deleted. When `--timeout` stopped the cleanup, the summary has a `stopped` field with the reason.
+
+Things to keep in mind:
+
+* **A dry run changes nothing on disk.** It doesn't keep the files locked while it decides, so its decisions are a snapshot: a real run may decide differently for files that change in the meantime.
+* **`--timeout` stops the cleanup gracefully:** the files being cleaned up are finished, the files still waiting for a worker are skipped. It can't interrupt a file that waits for a lock held by another process, though, so the command can run longer than the timeout. Ctrl-C (or `SIGTERM`) stops the cleanup the same way, but counts as a failure, see the exit codes below. A second Ctrl-C ends the command right away, e.g. when it waits for a lock. Use it only when the first one doesn't help: a revision is deleted in two steps, first its entry, then its content (the blob), and if the command ends between them, the blob stays on the storage, unused.
+* **Every run starts over from the beginning.** For regular runs with a timeout, e.g. by a cron job, add `--shuffle`, so that every run starts in a different place and the runs eventually reach all files, also in spaces too large for a single run.
+
+The exit code is `0` when the cleanup is done, `1` if the cleanup or any file failed, or if Ctrl-C (or `SIGTERM`) interrupted it, and `2` if `--timeout` stopped the cleanup before all files were cleaned up, and nothing failed.
+
+#### Command Examples
+
+```bash
+# show what a strategy would delete in all spaces, with the reason for every revision
+opencloud storage-users revisions cleanup --all --strategy "auto, 90d" --dry-run --verbose
+
+# keep only the 10 newest revisions of the files in a folder of a space
+opencloud storage-users revisions cleanup --space 25b69780-5f39-43be-a7ac-a9b9e9fe4230 --path /Documents --strategy 10
+
+# clean up a folder by its path on disk, with the posix driver
+opencloud storage-users revisions cleanup --fs-path /var/lib/opencloud/storage/users/projects/25b69780-5f39-43be-a7ac-a9b9e9fe4230/Documents
+
+# a nightly cron job: the configured strategy, at most one hour, in a random order
+opencloud storage-users revisions cleanup --all --timeout 1h --shuffle
+
+# the same with the short flags
+opencloud storage-users revisions cleanup -a -t 1h --shuffle
+```
+
## Caching
The `storage-users` service caches stat, metadata and uuids of files and folders via the configured store in `STORAGE_USERS_FILEMETADATA_CACHE_STORE` and `STORAGE_USERS_ID_CACHE_STORE`. Possible stores are:
diff --git a/services/storage-users/pkg/command/revisions.go b/services/storage-users/pkg/command/revisions.go
new file mode 100644
index 0000000000..def373cb41
--- /dev/null
+++ b/services/storage-users/pkg/command/revisions.go
@@ -0,0 +1,692 @@
+package command
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "os/signal"
+ "os/user"
+ "strconv"
+ "strings"
+ "syscall"
+ "time"
+
+ "github.com/rs/zerolog"
+ "github.com/spf13/cobra"
+
+ "github.com/opencloud-eu/opencloud/pkg/config/configlog"
+ opencloudstorage "github.com/opencloud-eu/opencloud/pkg/storage"
+ "github.com/opencloud-eu/opencloud/services/storage-users/pkg/config"
+ "github.com/opencloud-eu/opencloud/services/storage-users/pkg/config/parser"
+ "github.com/opencloud-eu/opencloud/services/storage-users/pkg/event"
+ "github.com/opencloud-eu/opencloud/services/storage-users/pkg/revaconfig"
+ "github.com/opencloud-eu/reva/v3/pkg/events"
+ "github.com/opencloud-eu/reva/v3/pkg/storage"
+ "github.com/opencloud-eu/reva/v3/pkg/storage/fs/registry"
+ "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup"
+ "github.com/opencloud-eu/reva/v3/pkg/storagespace"
+)
+
+// The exit codes of the revisions cleanup command
+const (
+ exitFailed = 1 // the cleanup or some of its files failed, or it was interrupted
+ exitStopped = 2 // stopped by --timeout before all files were cleaned up
+)
+
+// Revisions wraps the commands for the revisions (versions) of files.
+func Revisions(cfg *config.Config) *cobra.Command {
+ revisionsCmd := &cobra.Command{
+ Use: "revisions",
+ Short: "manage the revisions (versions) of files",
+ }
+ revisionsCmd.AddCommand(RevisionsCleanup(cfg))
+ return revisionsCmd
+}
+
+// RevisionsCleanup deletes old revisions of the files of whole spaces, folders or files.
+func RevisionsCleanup(cfg *config.Config) *cobra.Command {
+ cmd, _ := revisionsCleanupCommand(cfg)
+ return cmd
+}
+
+// revisionsCleanupCommand returns the revisions cleanup command, and the values of its flags.
+func revisionsCleanupCommand(cfg *config.Config) (*cobra.Command, *revisionsCleanupFlags) {
+ f := &revisionsCleanupFlags{}
+ cmd := &cobra.Command{
+ Use: "cleanup",
+ Short: "Delete old revisions according to a cleanup strategy",
+ Long: `Delete old revisions (versions) of files according to a cleanup strategy.
+
+The storage-users service cleans up the revisions of a file whenever it gets a new one,
+with the strategy configured in STORAGE_USERS_REVISIONS_CLEANUP_STRATEGY. This command
+cleans up the revisions of files that are not changed anymore, or applies a different
+strategy once, e.g. after the strategy was changed or to free storage.
+
+Exactly one of these selects the files to clean up:
+ --space all files of a space, repeatable; with --path, only that file or
+ folder within the space
+ --all all files of all spaces
+ --fs-path a file or folder by its path on disk ('posix' driver only)
+
+The strategy and the settings of the background workers default to the configured
+ones (STORAGE_USERS_REVISIONS_CLEANUP_*) and can be overridden for this run. See the
+description of STORAGE_USERS_REVISIONS_CLEANUP_STRATEGY for the strategies, e.g. '30d',
+'10' or '7d, auto, 90d'. Only --queue-full defaults to 'block' without a timeout,
+whatever is configured: the command finds files faster than the workers clean them up,
+so dropping the files that find the queue full would skip most of them.
+
+The command uses the storage directly, with the configuration of the storage-users
+service, and can run while the service is running. It needs access to the storage and,
+for the 'posix' driver, to NATS. With the single binary, NATS runs within the server:
+without a running server, the command gives up after 10 seconds. Run it as the user
+that OpenCloud runs as, e.g. with 'sudo -u': the lock files it creates belong to the
+user that runs it, and OpenCloud may not be able to open them otherwise. Unless it is a
+dry run, the command warns when the storage belongs to another user.
+
+By default, it prints a line for every file it deleted revisions of, could not clean
+up or skipped, and a summary. --verbose prints every file with every revision, what
+was decided about it and why. --json prints the same as JSON objects, one per line.
+
+--dry-run deletes nothing and prints what would be deleted. It changes nothing on
+disk, and doesn't keep the files locked while it decides: its decisions are a
+snapshot, and a real run may decide differently for files that change meanwhile.
+
+--timeout stops the cleanup gracefully: the files being cleaned up are finished, the
+files still waiting are skipped. It can't interrupt a file that waits for the lock of
+another process, though, so the command can run longer than the timeout. As every run
+starts over from the beginning, combine --timeout with --shuffle for regular runs, e.g.
+by a cron job, so that every run starts in a different place.
+
+Ctrl-C stops the cleanup like --timeout. A second ctrl-c ends the command right away,
+e.g. when it waits for a lock: that can leave the content of a deleted revision on the
+storage, unused, so use it only when the first one doesn't help.
+
+Exit codes: 0 when done, 1 if the cleanup or any file failed, or if it was interrupted
+(ctrl-c, SIGTERM), 2 if --timeout stopped the cleanup before all files were cleaned up
+(and nothing failed).`,
+ Example: ` opencloud storage-users revisions cleanup --all --strategy "auto, 90d" --dry-run
+ opencloud storage-users revisions cleanup --space --path /Documents --strategy 10
+ opencloud storage-users revisions cleanup --all --timeout 1h --shuffle`,
+ PreRunE: func(_ *cobra.Command, _ []string) error {
+ return configlog.ReturnFatal(parser.ParseConfig(cfg))
+ },
+ RunE: func(cmd *cobra.Command, _ []string) error {
+ code, err := runRevisionsCleanup(cmd, cfg, f)
+ if err != nil {
+ return err
+ }
+ if code != 0 {
+ os.Exit(code)
+ }
+ return nil
+ },
+ }
+ flags := cmd.Flags()
+ flags.StringSliceVar(&f.spaces, "space", nil, "the id of a space to clean up, repeatable")
+ flags.StringVar(&f.o.request.Path, "path", "", "a file or folder within the space given by --space, to clean up only that")
+ flags.StringVarP(&f.o.request.FSPath, "fs-path", "p", "", "a file or folder to clean up, by its path on disk ('posix' driver only)")
+ flags.BoolVarP(&f.o.request.All, "all", "a", false, "clean up all spaces")
+ flags.StringVarP(&f.strategy, "strategy", "s", "", "the cleanup strategy, defaults to STORAGE_USERS_REVISIONS_CLEANUP_STRATEGY")
+ flags.BoolVarP(&f.o.request.DryRun, "dry-run", "n", false, "delete nothing, only print what would be deleted")
+ flags.BoolVarP(&f.o.verbose, "verbose", "v", false, "print every file and every revision, with the decision and its reason")
+ flags.BoolVarP(&f.o.json, "json", "j", false, "print JSON objects, one per line, instead of text")
+ flags.DurationVarP(&f.o.timeout, "timeout", "t", 0, "stop the cleanup gracefully after this time, e.g. 30m or 2h; 0 never stops it")
+ flags.BoolVar(&f.o.request.Shuffle, "shuffle", false, "clean up the spaces and the files within each folder in a random order")
+ flags.BoolVar(&f.async, "async", false, "clean up files in background workers, while looking for more, defaults to STORAGE_USERS_REVISIONS_CLEANUP_ASYNC")
+ flags.IntVar(&f.workers, "workers", 0, "the number of background workers, 0 for automatic, defaults to STORAGE_USERS_REVISIONS_CLEANUP_ASYNC_WORKERS")
+ flags.IntVar(&f.queueSize, "queue-size", 0, "the number of files that can wait for a worker, 0 for automatic, defaults to STORAGE_USERS_REVISIONS_CLEANUP_ASYNC_QUEUE_SIZE")
+ flags.StringVar(&f.queueFull, "queue-full", string(revisioncleanup.QueueFullBlock), "'block' (wait for room) or 'drop' (skip) files when the queue is full")
+ flags.DurationVar(&f.queueFullTimeout, "queue-full-timeout", 0, "with --queue-full block, skip a file after waiting this long for room, e.g. 10s; 0 waits as long as it takes")
+ return cmd, f
+}
+
+// revisionsCleanupFlags holds the values of the flags of the revisions cleanup command: in o
+// the ones that are used as they are, the others are turned into options by options.
+type revisionsCleanupFlags struct {
+ o revisionsCleanupOptions
+ spaces []string
+ strategy string
+ async bool
+ workers int
+ queueSize int
+ queueFull string
+ // the settings of a full queue, which, unlike the others, don't default to the configured
+ // ones, see the help of the command
+ queueFullTimeout time.Duration
+}
+
+// revisionsCleanupOptions are the settings of a run of the revisions cleanup command
+type revisionsCleanupOptions struct {
+ request revisioncleanup.Request
+ timeout time.Duration
+ verbose bool
+ json bool
+}
+
+// options builds the options of a run from the flags, with the configured strategy and async
+// settings unless the flags override them; changed tells whether a flag was given.
+func (f *revisionsCleanupFlags) options(cfg *config.Config, changed func(name string) bool) (revisionsCleanupOptions, error) {
+ o := f.o
+ r := &o.request
+
+ for _, space := range f.spaces {
+ // accept the ids as the APIs show them, e.g. $
+ id, err := storagespace.ParseID(space)
+ if err != nil {
+ return o, fmt.Errorf("invalid space id %q: %w", space, err)
+ }
+ if id.GetSpaceId() == "" {
+ return o, fmt.Errorf("invalid space id %q: it has no space id", space)
+ }
+ // a resource id of a file or folder within the space would clean up the whole space
+ if node := id.GetOpaqueId(); node != "" && node != id.GetSpaceId() {
+ return o, fmt.Errorf("invalid space id %q: it is the id of a file or folder within space %q, give the space with --space and the file or folder with --path", space, id.GetSpaceId())
+ }
+ r.SpaceIDs = append(r.SpaceIDs, id.GetSpaceId())
+ }
+ if r.Path != "" && len(r.SpaceIDs) == 0 {
+ return o, errors.New("--path requires --space")
+ }
+ err := r.Validate()
+ if err != nil {
+ return o, err
+ }
+ if r.FSPath != "" && cfg.Driver != "posix" {
+ return o, fmt.Errorf("--fs-path is only supported by the 'posix' driver, not by %q", cfg.Driver)
+ }
+
+ r.Strategy = cfg.RevisionsCleanup.Strategy
+ if changed("strategy") {
+ r.Strategy = f.strategy
+ }
+ // check the strategy before the storage is opened
+ switch cleaner, err := revisioncleanup.New(r.Strategy); {
+ case err != nil:
+ return o, fmt.Errorf("invalid strategy %q: %w", r.Strategy, err)
+ case !cleaner.Enabled():
+ return o, errors.New("no strategy: the revisions cleanup is disabled, give one with --strategy or configure STORAGE_USERS_REVISIONS_CLEANUP_STRATEGY")
+ }
+
+ async := revisioncleanup.AsyncOptions{
+ Enabled: cfg.RevisionsCleanup.Async,
+ Workers: cfg.RevisionsCleanup.AsyncWorkers,
+ QueueSize: cfg.RevisionsCleanup.AsyncQueueSize,
+ // not the configured ones, see revisionsCleanupFlags.queueFullTimeout
+ QueueFull: revisioncleanup.QueueFullPolicy(f.queueFull),
+ QueueFullTimeout: f.queueFullTimeout,
+ }
+ if changed("async") {
+ async.Enabled = f.async
+ }
+ if changed("workers") {
+ async.Workers = f.workers
+ }
+ if changed("queue-size") {
+ async.QueueSize = f.queueSize
+ }
+ r.Async = &async
+
+ if o.timeout < 0 {
+ return o, fmt.Errorf("invalid timeout %s", o.timeout)
+ }
+ return o, nil
+}
+
+// runRevisionsCleanup runs the revisions cleanup command and returns its exit code.
+func runRevisionsCleanup(cmd *cobra.Command, cfg *config.Config, f *revisionsCleanupFlags) (int, error) {
+ o, err := f.options(cfg, cmd.Flags().Changed)
+ if err != nil {
+ return 0, err
+ }
+
+ // stop gracefully on ctrl-c as well, also while waiting for NATS
+ ctx, stop := signal.NotifyContext(cmd.Context(), os.Interrupt, syscall.SIGTERM)
+ defer stop()
+ go func() {
+ <-ctx.Done()
+ // Make sure that a second ctrl-c ends the process right away, e.g. when a file
+ // waits for the lock of another process: this context and the one of the root
+ // command keep listening to the signals otherwise. That can leave the blob of a
+ // deleted revision behind, which the help says.
+ signal.Reset()
+ }()
+
+ // warnings, e.g. about revisions dated in the future or a lost connection to NATS;
+ // errors of the cleanup are reported
+ logger := zerolog.New(zerolog.ConsoleWriter{Out: cmd.ErrOrStderr(), TimeFormat: time.RFC3339, NoColor: true}).
+ With().Timestamp().Logger().Level(zerolog.WarnLevel)
+ ctx = logger.WithContext(ctx)
+
+ // a dry run changes nothing on disk, so it may run as any user
+ if !o.request.DryRun {
+ warnAboutStorageOwner(cfg, &logger)
+ }
+ onDemand, err := revisionsCleanupDriver(ctx, cfg, &logger)
+ if err != nil {
+ return 0, err
+ }
+
+ return cleanupRevisions(ctx, onDemand, o, cmd.OutOrStdout())
+}
+
+// cleanupRevisions runs the cleanup with the given options, prints its results to w and
+// returns the exit code of the command.
+func cleanupRevisions(ctx context.Context, onDemand revisioncleanup.OnDemand, o revisionsCleanupOptions, w io.Writer) (int, error) {
+ interrupted := ctx
+ if o.timeout > 0 {
+ var cancel context.CancelFunc
+ ctx, cancel = context.WithTimeout(ctx, o.timeout)
+ defer cancel()
+ }
+
+ out := newRevisionsCleanupOutput(w, o)
+ err := onDemand.CleanupRevisionsUnchecked(ctx, o.request, out.report)
+ // Tell the timeout and an interruption by the contexts, not by the error: the storage
+ // can return context errors of its own, e.g. when NATS doesn't answer in time.
+ switch {
+ case err != nil && interrupted.Err() != nil:
+ out.summary("interrupted")
+ return exitFailed, nil
+ case err != nil && ctx.Err() != nil:
+ out.summary(fmt.Sprintf("stopped after the timeout of %s", o.timeout))
+ if out.failed() {
+ return exitFailed, nil
+ }
+ return exitStopped, nil
+ case err != nil:
+ out.summary("")
+ return 0, err
+ }
+ out.summary("")
+ if out.err != nil {
+ return 0, fmt.Errorf("could not write the output: %w", out.err)
+ }
+ if out.failed() {
+ return exitFailed, nil
+ }
+ return 0, nil
+}
+
+// revisionsCleanupDriverConfig returns the name and the configuration of the storage
+// driver to create, without the parts of the storage-users service that would
+// interfere with the running service.
+func revisionsCleanupDriverConfig(cfg *config.Config) (string, map[string]any, error) {
+ // The deprecated driver names "ocis" and "s3ng" are aliases of "decomposed" and
+ // "decomposeds3" since https://github.com/opencloud-eu/opencloud/pull/3859: there
+ // are no driver entries of their own anymore, and StorageProviderDrivers sets the
+ // legacy metadata prefix on the entry of the driver they resolve to. Resolve the
+ // alias like the other storage-users commands (uploads, blobstore) do. When the
+ // aliases are removed, so is storage.EffectiveDriver, and this resolution with it.
+ driver := opencloudstorage.EffectiveDriver(cfg.Driver)
+ drivers := revaconfig.StorageProviderDrivers(cfg)
+ if driver == "posix" {
+ // neither scan nor watch the file system, that is the service's job: e.g. a second
+ // inotifywait would stop the one of the service
+ drivers["posix"] = revaconfig.Posix(cfg, false, false)
+ }
+ driverConfig, ok := drivers[driver].(map[string]any)
+ if !ok {
+ return "", nil, fmt.Errorf("unknown storage driver %q", cfg.Driver)
+ }
+ // Without async uploads, the driver doesn't join the postprocessing consumer group of the
+ // service: the events delivered to this short-lived process would be lost.
+ driverConfig["asyncfileuploads"] = false
+ return driver, driverConfig, nil
+}
+
+// revisionsCleanupDriver creates the storage driver, see revisionsCleanupDriverConfig.
+func revisionsCleanupDriver(ctx context.Context, cfg *config.Config, log *zerolog.Logger) (revisioncleanup.OnDemand, error) {
+ driver, driverConfig, err := revisionsCleanupDriverConfig(cfg)
+ if err != nil {
+ return nil, err
+ }
+ newFS, ok := registry.NewFuncs[driver]
+ if !ok {
+ return nil, fmt.Errorf("unknown storage driver %q", cfg.Driver)
+ }
+ var stream events.Stream
+ if driver == "posix" {
+ // posix refuses to start without an event stream
+ stream, err = newEventStream(ctx, cfg, eventStreamTimeout, event.NewStream)
+ if err != nil {
+ return nil, fmt.Errorf("could not create the event stream for the posix driver: %w", err)
+ }
+ }
+
+ // The driver can't be interrupted: e.g. the id cache of the 'posix' driver waits for
+ // NATS for up to 15 minutes. It keeps trying in the background until the command exits.
+ fs, err := interruptible(ctx, func() (storage.FS, error) { return newFS(driverConfig, stream, log) })
+ switch {
+ case err != nil && ctx.Err() != nil:
+ return nil, fmt.Errorf("interrupted while initializing the storage driver %q: %w", cfg.Driver, err)
+ case err != nil:
+ return nil, fmt.Errorf("could not initialize the storage driver %q: %w", cfg.Driver, err)
+ }
+ onDemand, ok := fs.(revisioncleanup.OnDemand)
+ if !ok {
+ return nil, fmt.Errorf("the %q driver can't clean up revisions", cfg.Driver)
+ }
+ return onDemand, nil
+}
+
+// eventStreamTimeout is how long the command waits for NATS. The event stream retries
+// for up to 15 minutes, which suits the service, but not a command: with the single
+// binary, NATS only runs within the server, see
+// https://github.com/opencloud-eu/opencloud/issues/3805
+const eventStreamTimeout = 10 * time.Second
+
+// newEventStream creates the event stream with newStream, but gives up after timeout, or
+// when ctx is done (e.g. on ctrl-c), as newStream itself waits for NATS for up to 15
+// minutes and can't be interrupted. newStream then keeps trying in the background until
+// the command exits.
+func newEventStream[S any](ctx context.Context, cfg *config.Config, timeout time.Duration, newStream func(*config.Config) (S, error)) (S, error) {
+ connect, cancel := context.WithTimeout(ctx, timeout)
+ defer cancel()
+ stream, err := interruptible(connect, func() (S, error) { return newStream(cfg) })
+ switch {
+ case err != nil && ctx.Err() != nil:
+ return stream, fmt.Errorf("interrupted while connecting to NATS at %s: %w", cfg.Events.Addr, ctx.Err())
+ case err != nil && connect.Err() != nil:
+ return stream, fmt.Errorf("could not connect to NATS at %s within %s: the command needs NATS, i.e. a running OpenCloud server or a separate NATS", cfg.Events.Addr, timeout)
+ }
+ return stream, err
+}
+
+// interruptible returns what f returns, or the error of ctx when ctx is done first. f
+// then keeps running in the background until the command exits.
+func interruptible[T any](ctx context.Context, f func() (T, error)) (T, error) {
+ type result struct {
+ value T
+ err error
+ }
+ done := make(chan result, 1)
+ go func() {
+ value, err := f()
+ done <- result{value, err}
+ }()
+
+ select {
+ case r := <-done:
+ return r.value, r.err
+ case <-ctx.Done():
+ var none T
+ return none, ctx.Err()
+ }
+}
+
+// userName returns the name of the user with the id uid, or uid if it has no name.
+func userName(uid string) string {
+ u, err := user.LookupId(uid)
+ if err != nil {
+ return uid
+ }
+ return u.Username
+}
+
+// warnAboutStorageOwner logs the warning of storageOwnerWarning for the storage of the driver
+// that the command creates, if there is one.
+func warnAboutStorageOwner(cfg *config.Config, log *zerolog.Logger) {
+ _, driverConfig, err := revisionsCleanupDriverConfig(cfg)
+ if err != nil {
+ // revisionsCleanupDriver reports it
+ return
+ }
+ root, _ := driverConfig["root"].(string)
+ if warning := storageOwnerWarning(root, os.Geteuid()); warning != "" {
+ log.Warn().Msg(warning)
+ }
+}
+
+// storageOwnerWarning returns a warning when the storage at root doesn't belong to the
+// user euid, as the files that the command creates belong to that user, with permissions
+// only for that user: the lock files of the files it cleans up. The
+// server may then not be able to lock these files anymore.
+func storageOwnerWarning(root string, euid int) string {
+ info, err := os.Stat(root)
+ if err != nil {
+ // the driver reports it
+ return ""
+ }
+ st, ok := info.Sys().(*syscall.Stat_t)
+ if !ok || int(st.Uid) == euid {
+ return ""
+ }
+ owner := userName(strconv.FormatUint(uint64(st.Uid), 10))
+ runAs := userName(strconv.Itoa(euid))
+ return fmt.Sprintf("the storage %s belongs to the user %s, but the command runs as %s: the lock files it creates belong to %s, and OpenCloud may not be able to lock these files anymore; run the command as %s, e.g. with 'sudo -u %s'", root, owner, runAs, runAs, owner, owner)
+}
+
+// revisionsCleanupOutput prints the results of a revisions cleanup as they come in, and
+// sums them up.
+type revisionsCleanupOutput struct {
+ w io.Writer
+ o revisionsCleanupOptions
+ enc *json.Encoder
+ spaces map[string]struct{}
+ files int
+ cleaned int // files with deleted revisions
+ deleted int
+ bytes uint64
+ skipped int
+ errors int // files that failed, as a whole or for some of their revisions
+ err error // the first error writing the output
+}
+
+func newRevisionsCleanupOutput(w io.Writer, o revisionsCleanupOptions) *revisionsCleanupOutput {
+ out := &revisionsCleanupOutput{w: w, o: o, spaces: map[string]struct{}{}}
+ if o.json {
+ out.enc = json.NewEncoder(w)
+ }
+ return out
+}
+
+// revisionJSON is a revision in the JSON output
+type revisionJSON struct {
+ Key string `json:"key"`
+ Time time.Time `json:"time"`
+ Size uint64 `json:"size"`
+ Decision string `json:"decision"`
+ Reason string `json:"reason,omitempty"`
+ Error string `json:"error,omitempty"`
+}
+
+// fileJSON is a file in the JSON output
+type fileJSON struct {
+ Type string `json:"type"`
+ SpaceID string `json:"space_id"`
+ NodeID string `json:"node_id"`
+ Path string `json:"path,omitempty"`
+ DryRun bool `json:"dry_run"`
+ Skipped string `json:"skipped,omitempty"`
+ Error string `json:"error,omitempty"`
+ Revisions int `json:"revisions"`
+ Deleted int `json:"deleted"`
+ DeletedBytes uint64 `json:"deleted_bytes"`
+ Failed int `json:"failed"`
+ Details []revisionJSON `json:"details,omitempty"`
+}
+
+// summaryJSON is the summary in the JSON output
+type summaryJSON struct {
+ Type string `json:"type"`
+ DryRun bool `json:"dry_run"`
+ Spaces int `json:"spaces"`
+ Files int `json:"files"`
+ Cleaned int `json:"cleaned"`
+ Deleted int `json:"deleted"`
+ DeletedBytes uint64 `json:"deleted_bytes"`
+ Skipped int `json:"skipped"`
+ Failed int `json:"failed"`
+ Stopped string `json:"stopped,omitempty"`
+}
+
+// report prints the Result of a file, it is called one result at a time.
+func (out *revisionsCleanupOutput) report(r revisioncleanup.Result) {
+ deleted, bytes := r.DeletedCount()
+ failedRevisions := 0
+ for _, rev := range r.Revisions {
+ if rev.Err != nil {
+ failedRevisions++
+ }
+ }
+ failed := r.Err != nil || failedRevisions > 0
+
+ out.spaces[r.SpaceID] = struct{}{}
+ out.files++
+ out.deleted += deleted
+ out.bytes += bytes
+ switch {
+ case failed:
+ out.errors++
+ case r.Skipped != "":
+ out.skipped++
+ }
+ if deleted > 0 {
+ out.cleaned++
+ }
+
+ // without --verbose, only what needs attention or changed something
+ if !out.o.verbose && deleted == 0 && !failed && r.Skipped == "" {
+ return
+ }
+ if out.enc != nil {
+ out.printJSON(r, deleted, bytes, failedRevisions)
+ return
+ }
+ out.printText(r, deleted, bytes, failedRevisions)
+}
+
+func (out *revisionsCleanupOutput) printJSON(r revisioncleanup.Result, deleted int, bytes uint64, failedRevisions int) {
+ f := fileJSON{
+ Type: "file",
+ SpaceID: r.SpaceID,
+ NodeID: r.NodeID,
+ Path: r.Path,
+ DryRun: r.DryRun,
+ Skipped: r.Skipped,
+ Revisions: len(r.Revisions),
+ Deleted: deleted,
+ DeletedBytes: bytes,
+ Failed: failedRevisions,
+ }
+ if r.Err != nil {
+ f.Error = r.Err.Error()
+ }
+ if out.o.verbose {
+ for _, rev := range r.Revisions {
+ d := revisionJSON{Key: rev.Key, Time: rev.Time, Size: rev.Size, Decision: string(rev.Decision), Reason: rev.Reason}
+ if rev.Err != nil {
+ d.Error = rev.Err.Error()
+ }
+ f.Details = append(f.Details, d)
+ }
+ }
+ out.write(out.enc.Encode(f))
+}
+
+func (out *revisionsCleanupOutput) printText(r revisioncleanup.Result, deleted int, bytes uint64, failedRevisions int) {
+ file := r.Path
+ if file == "" || out.o.verbose {
+ file = strings.TrimSpace(file + " (node " + r.NodeID + ")")
+ }
+ line := fmt.Sprintf("%s %s: ", r.SpaceID, file)
+ switch {
+ case r.Err != nil:
+ line += "failed: " + r.Err.Error()
+ case r.Skipped != "":
+ line += "skipped: " + r.Skipped
+ default:
+ verb := "deleted"
+ if r.DryRun {
+ verb = "would delete"
+ }
+ line += fmt.Sprintf("%s %d of %s (%s)", verb, deleted, plural(len(r.Revisions), "revision"), formatBytes(bytes))
+ if failedRevisions > 0 {
+ line += fmt.Sprintf(", %d could not be deleted", failedRevisions)
+ }
+ }
+ _, err := fmt.Fprintln(out.w, line)
+ out.write(err)
+
+ if !out.o.verbose {
+ for _, rev := range r.Revisions {
+ if rev.Err != nil {
+ fmt.Fprintf(out.w, " %s: %s\n", rev.Key, rev.Err)
+ }
+ }
+ return
+ }
+ for _, rev := range r.Revisions {
+ // in the server's time zone, like the times in the reasons
+ fmt.Fprintf(out.w, " %-9s %s %9s %s\n", rev.Decision, rev.Time.Local().Format(time.RFC3339), formatBytes(rev.Size), rev.Reason)
+ if rev.Err != nil {
+ fmt.Fprintf(out.w, " %-9s could not be deleted: %s\n", "", rev.Err)
+ }
+ }
+}
+
+// summary prints the totals, stopped tells why the cleanup stopped early, if it did.
+func (out *revisionsCleanupOutput) summary(stopped string) {
+ if out.enc != nil {
+ out.write(out.enc.Encode(summaryJSON{
+ Type: "summary",
+ DryRun: out.o.request.DryRun,
+ Spaces: len(out.spaces),
+ Files: out.files,
+ Cleaned: out.cleaned,
+ Deleted: out.deleted,
+ DeletedBytes: out.bytes,
+ Skipped: out.skipped,
+ Failed: out.errors,
+ Stopped: stopped,
+ }))
+ return
+ }
+ verb := "deleted"
+ if out.o.request.DryRun {
+ verb = "would delete"
+ }
+ fmt.Fprintf(out.w, "%s in %s: %s %s (%s) of %s, %d skipped, %d failed\n",
+ plural(out.files, "file"), plural(len(out.spaces), "space"), verb, plural(out.deleted, "revision"),
+ formatBytes(out.bytes), plural(out.cleaned, "file"), out.skipped, out.errors)
+ if stopped != "" {
+ fmt.Fprintf(out.w, "The cleanup was %s, before all files were cleaned up.\n", stopped)
+ }
+}
+
+// write records the first error writing the output.
+func (out *revisionsCleanupOutput) write(err error) {
+ if out.err == nil {
+ out.err = err
+ }
+}
+
+// failed tells whether the cleanup of any file failed.
+func (out *revisionsCleanupOutput) failed() bool {
+ return out.errors > 0
+}
+
+// plural returns the count with the noun, e.g. "1 file" or "2 files".
+func plural(n int, noun string) string {
+ if n == 1 {
+ return "1 " + noun
+ }
+ return fmt.Sprintf("%d %ss", n, noun)
+}
+
+// formatBytes formats a size in bytes with a binary unit, e.g. 1.5 MiB.
+func formatBytes(b uint64) string {
+ const unit = 1024
+ if b < unit {
+ return fmt.Sprintf("%d B", b)
+ }
+ div, exp := uint64(unit), 0
+ for n := b / unit; n >= unit; n /= unit {
+ div *= unit
+ exp++
+ }
+ return fmt.Sprintf("%.1f %ciB", float64(b)/float64(div), "KMGTPE"[exp])
+}
diff --git a/services/storage-users/pkg/command/revisions_test.go b/services/storage-users/pkg/command/revisions_test.go
new file mode 100644
index 0000000000..f2202dac73
--- /dev/null
+++ b/services/storage-users/pkg/command/revisions_test.go
@@ -0,0 +1,417 @@
+package command
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup"
+ "github.com/test-go/testify/require"
+
+ "github.com/opencloud-eu/opencloud/pkg/shared"
+ opencloudstorage "github.com/opencloud-eu/opencloud/pkg/storage"
+ "github.com/opencloud-eu/opencloud/services/storage-users/pkg/config"
+ "github.com/opencloud-eu/opencloud/services/storage-users/pkg/config/defaults"
+)
+
+// revisionsCleanupOptionsFor parses the flags of the revisions cleanup command
+func revisionsCleanupOptionsFor(t *testing.T, cfg *config.Config, args ...string) (revisionsCleanupOptions, error) {
+ t.Helper()
+ cmd, f := revisionsCleanupCommand(cfg)
+ require.NoError(t, cmd.ParseFlags(args))
+ return f.options(cfg, cmd.Flags().Changed)
+}
+
+func revisionsCleanupConfig() *config.Config {
+ return &config.Config{
+ Driver: "decomposed",
+ RevisionsCleanup: config.RevisionsCleanup{
+ Strategy: "auto, 90d",
+ Async: true,
+ AsyncWorkers: 4,
+ AsyncQueueSize: 100,
+ AsyncQueueFull: "drop",
+ AsyncQueueFullTimeout: 5 * time.Second,
+ },
+ }
+}
+
+func TestRevisionsCleanupOptions(t *testing.T) {
+ t.Run("the configuration is the default", func(t *testing.T) {
+ o, err := revisionsCleanupOptionsFor(t, revisionsCleanupConfig(), "--all")
+ require.NoError(t, err)
+ require.True(t, o.request.All)
+ require.Equal(t, "auto, 90d", o.request.Strategy)
+ // except for a full queue: the command waits for room as long as it takes
+ require.Equal(t, &revisioncleanup.AsyncOptions{Enabled: true, Workers: 4, QueueSize: 100, QueueFull: revisioncleanup.QueueFullBlock}, o.request.Async)
+ require.False(t, o.request.DryRun)
+ require.False(t, o.request.Shuffle)
+ require.Zero(t, o.timeout)
+ })
+
+ t.Run("flags override the configuration", func(t *testing.T) {
+ o, err := revisionsCleanupOptionsFor(t, revisionsCleanupConfig(),
+ "--space", "storage$space1!space1", "--space", "space2", "--strategy", "10",
+ "--async=false", "--workers", "0", "--queue-size", "7", "--queue-full", "drop", "--queue-full-timeout", "30s",
+ "--dry-run", "--shuffle", "--timeout", "1h", "--verbose", "--json")
+ require.NoError(t, err)
+ require.Equal(t, []string{"space1", "space2"}, o.request.SpaceIDs, "the space ids as the APIs show them are accepted")
+ require.Equal(t, "10", o.request.Strategy)
+ require.Equal(t, &revisioncleanup.AsyncOptions{Enabled: false, Workers: 0, QueueSize: 7, QueueFull: revisioncleanup.QueueFullDrop, QueueFullTimeout: 30 * time.Second}, o.request.Async)
+ require.True(t, o.request.DryRun)
+ require.True(t, o.request.Shuffle)
+ require.Equal(t, time.Hour, o.timeout)
+ require.True(t, o.verbose)
+ require.True(t, o.json)
+ })
+
+ t.Run("short flags", func(t *testing.T) {
+ o, err := revisionsCleanupOptionsFor(t, revisionsCleanupConfig(), "-anvj", "-s", "10", "-t", "30m")
+ require.NoError(t, err)
+ require.True(t, o.request.All)
+ require.True(t, o.request.DryRun)
+ require.True(t, o.verbose)
+ require.True(t, o.json)
+ require.Equal(t, "10", o.request.Strategy)
+ require.Equal(t, 30*time.Minute, o.timeout)
+
+ cfg := revisionsCleanupConfig()
+ cfg.Driver = "posix"
+ o, err = revisionsCleanupOptionsFor(t, cfg, "-p", "/var/lib/opencloud/users/einstein")
+ require.NoError(t, err)
+ require.Equal(t, "/var/lib/opencloud/users/einstein", o.request.FSPath)
+ })
+
+ t.Run("a path within a space", func(t *testing.T) {
+ o, err := revisionsCleanupOptionsFor(t, revisionsCleanupConfig(), "--space", "space1", "--path", "/Documents")
+ require.NoError(t, err)
+ require.Equal(t, "/Documents", o.request.Path)
+ })
+
+ t.Run("a path on disk with posix", func(t *testing.T) {
+ cfg := revisionsCleanupConfig()
+ cfg.Driver = "posix"
+ o, err := revisionsCleanupOptionsFor(t, cfg, "--fs-path", "/var/lib/opencloud/users/einstein")
+ require.NoError(t, err)
+ require.Equal(t, "/var/lib/opencloud/users/einstein", o.request.FSPath)
+ })
+
+ for _, tc := range []struct {
+ name string
+ strategy string
+ args []string
+ err string
+ }{
+ {name: "nothing to clean up", err: "no space"},
+ {name: "the id of a file as a space", args: []string{"--space", "storage$space1!node1"}, err: "it is the id of a file or folder within space \"space1\""},
+ {name: "a storage id without a space id", args: []string{"--space", "storage$"}, err: "it has no space id"},
+ {name: "a file id without a space id", args: []string{"--space", "storage$!node1"}, err: "it has no space id"},
+ {name: "a path without a space", args: []string{"--path", "/Documents"}, err: "--path requires --space"},
+ {name: "all and a space", args: []string{"--all", "--space", "space1"}, err: "not both"},
+ {name: "a path in two spaces", args: []string{"--space", "space1", "--space", "space2", "--path", "/Documents"}, err: "exactly one space"},
+ {name: "a path on disk and a space", args: []string{"--fs-path", "/data", "--space", "space1"}, err: "can't be combined"},
+ {name: "a path on disk without posix", args: []string{"--fs-path", "/data"}, err: "only supported by the 'posix' driver"},
+ {name: "the cleanup is disabled", strategy: "disabled", args: []string{"--all"}, err: "--strategy"},
+ {name: "an invalid strategy", args: []string{"--all", "--strategy", "whenever"}, err: "invalid strategy"},
+ {name: "a negative timeout", args: []string{"--all", "--timeout", "-1s"}, err: "invalid timeout"},
+ } {
+ t.Run("rejects "+tc.name, func(t *testing.T) {
+ cfg := revisionsCleanupConfig()
+ if tc.strategy != "" {
+ cfg.RevisionsCleanup.Strategy = tc.strategy
+ }
+ _, err := revisionsCleanupOptionsFor(t, cfg, tc.args...)
+ require.Error(t, err)
+ require.Contains(t, err.Error(), tc.err)
+ })
+ }
+}
+
+// fakeOnDemand reports the given results, and then waits for the end of ctx if wait is set
+type fakeOnDemand struct {
+ results []revisioncleanup.Result
+ wait bool
+ err error
+ request revisioncleanup.Request
+}
+
+func (f *fakeOnDemand) CleanupRevisionsUnchecked(ctx context.Context, req revisioncleanup.Request, report func(revisioncleanup.Result)) error {
+ f.request = req
+ for _, r := range f.results {
+ r.DryRun = req.DryRun
+ report(r)
+ }
+ if f.wait {
+ <-ctx.Done()
+ return ctx.Err()
+ }
+ return f.err
+}
+
+var (
+ revisionsCleanupTime = time.Date(2026, 10, 14, 10, 0, 0, 0, time.UTC)
+ // a file with a deleted and a kept revision
+ cleanedFile = revisioncleanup.Result{SpaceID: "space1", NodeID: "node1", Path: "/Documents/report.odt", Revisions: []revisioncleanup.RevisionResult{
+ {Key: "node1.REV.1", Time: revisionsCleanupTime, Size: 1536, Decision: revisioncleanup.Kept, Reason: "kept by \"auto\""},
+ {Key: "node1.REV.2", Time: revisionsCleanupTime.Add(-100 * 24 * time.Hour), Size: 2048, Decision: revisioncleanup.Deleted, Reason: "deleted by \"90d\""},
+ }}
+ // a file with nothing to delete
+ untouchedFile = revisioncleanup.Result{SpaceID: "space1", NodeID: "node2", Path: "/notes.txt", Revisions: []revisioncleanup.RevisionResult{
+ {Key: "node2.REV.1", Time: revisionsCleanupTime, Size: 10, Decision: revisioncleanup.Kept, Reason: "kept by \"auto\""},
+ }}
+ skippedFile = revisioncleanup.Result{SpaceID: "space2", NodeID: "node3", Path: "/upload.bin", Skipped: "an upload to the file is still being processed"}
+ failedFile = revisioncleanup.Result{SpaceID: "space2", NodeID: "node4", Path: "/broken.txt", Err: errors.New("could not list revisions")}
+)
+
+func runFakeRevisionsCleanup(t *testing.T, f *fakeOnDemand, o revisionsCleanupOptions) (int, string, error) {
+ t.Helper()
+ if o.request.Async == nil {
+ o.request = revisioncleanup.Request{All: true, Strategy: "auto, 90d", DryRun: o.request.DryRun}
+ }
+ var out bytes.Buffer
+ code, err := cleanupRevisions(context.Background(), f, o, &out)
+ return code, out.String(), err
+}
+
+func TestRevisionsCleanupOutput(t *testing.T) {
+ t.Run("only the files that changed or need attention, and a summary", func(t *testing.T) {
+ code, out, err := runFakeRevisionsCleanup(t, &fakeOnDemand{results: []revisioncleanup.Result{cleanedFile, untouchedFile, skippedFile}}, revisionsCleanupOptions{})
+ require.NoError(t, err)
+ require.Equal(t, 0, code)
+ require.Equal(t, `space1 /Documents/report.odt: deleted 1 of 2 revisions (2.0 KiB)
+space2 /upload.bin: skipped: an upload to the file is still being processed
+3 files in 2 spaces: deleted 1 revision (2.0 KiB) of 1 file, 1 skipped, 0 failed
+`, out)
+ })
+
+ t.Run("a dry run", func(t *testing.T) {
+ o := revisionsCleanupOptions{request: revisioncleanup.Request{DryRun: true}}
+ code, out, err := runFakeRevisionsCleanup(t, &fakeOnDemand{results: []revisioncleanup.Result{cleanedFile}}, o)
+ require.NoError(t, err)
+ require.Equal(t, 0, code)
+ require.Contains(t, out, "space1 /Documents/report.odt: would delete 1 of 2 revisions")
+ require.Contains(t, out, "would delete 1 revision (2.0 KiB) of 1 file")
+ })
+
+ t.Run("every file and revision with --verbose", func(t *testing.T) {
+ code, out, err := runFakeRevisionsCleanup(t, &fakeOnDemand{results: []revisioncleanup.Result{cleanedFile, untouchedFile}}, revisionsCleanupOptions{verbose: true})
+ require.NoError(t, err)
+ require.Equal(t, 0, code)
+ // the times are in the local time zone, like the ones in the reasons
+ local := func(t time.Time) string { return t.Local().Format(time.RFC3339) }
+ require.Equal(t, `space1 /Documents/report.odt (node node1): deleted 1 of 2 revisions (2.0 KiB)
+ kept `+local(revisionsCleanupTime)+` 1.5 KiB kept by "auto"
+ deleted `+local(revisionsCleanupTime.Add(-100*24*time.Hour))+` 2.0 KiB deleted by "90d"
+space1 /notes.txt (node node2): deleted 0 of 1 revision (0 B)
+ kept `+local(revisionsCleanupTime)+` 10 B kept by "auto"
+2 files in 1 space: deleted 1 revision (2.0 KiB) of 1 file, 0 skipped, 0 failed
+`, out)
+ })
+
+ t.Run("JSON lines", func(t *testing.T) {
+ code, out, err := runFakeRevisionsCleanup(t, &fakeOnDemand{results: []revisioncleanup.Result{cleanedFile, untouchedFile, failedFile}}, revisionsCleanupOptions{json: true})
+ require.NoError(t, err)
+ require.Equal(t, exitFailed, code)
+ lines := strings.Split(strings.TrimSpace(out), "\n")
+ require.Len(t, lines, 3, "the untouched file is left out without --verbose")
+
+ var file fileJSON
+ require.NoError(t, json.Unmarshal([]byte(lines[0]), &file))
+ require.Equal(t, fileJSON{Type: "file", SpaceID: "space1", NodeID: "node1", Path: "/Documents/report.odt", Revisions: 2, Deleted: 1, DeletedBytes: 2048}, file)
+ require.NoError(t, json.Unmarshal([]byte(lines[1]), &file))
+ require.Equal(t, "could not list revisions", file.Error)
+
+ var summary summaryJSON
+ require.NoError(t, json.Unmarshal([]byte(lines[2]), &summary))
+ require.Equal(t, summaryJSON{Type: "summary", Spaces: 2, Files: 3, Cleaned: 1, Deleted: 1, DeletedBytes: 2048, Failed: 1}, summary)
+ })
+
+ t.Run("JSON lines with the revisions with --verbose", func(t *testing.T) {
+ _, out, err := runFakeRevisionsCleanup(t, &fakeOnDemand{results: []revisioncleanup.Result{cleanedFile}}, revisionsCleanupOptions{json: true, verbose: true})
+ require.NoError(t, err)
+ var file fileJSON
+ require.NoError(t, json.Unmarshal([]byte(strings.Split(out, "\n")[0]), &file))
+ require.Len(t, file.Details, 2)
+ require.Equal(t, revisionJSON{Key: "node1.REV.2", Time: revisionsCleanupTime.Add(-100 * 24 * time.Hour), Size: 2048, Decision: "deleted", Reason: "deleted by \"90d\""}, file.Details[1])
+ })
+}
+
+func TestRevisionsCleanupExitCodes(t *testing.T) {
+ t.Run("a failed file", func(t *testing.T) {
+ code, out, err := runFakeRevisionsCleanup(t, &fakeOnDemand{results: []revisioncleanup.Result{cleanedFile, failedFile}}, revisionsCleanupOptions{})
+ require.NoError(t, err)
+ require.Equal(t, exitFailed, code)
+ require.Contains(t, out, "space2 /broken.txt: failed: could not list revisions")
+ })
+
+ t.Run("a revision that could not be deleted", func(t *testing.T) {
+ file := cleanedFile
+ file.Revisions = append([]revisioncleanup.RevisionResult{}, cleanedFile.Revisions...)
+ file.Revisions[1].Err = errors.New("permission denied")
+ code, out, err := runFakeRevisionsCleanup(t, &fakeOnDemand{results: []revisioncleanup.Result{file}}, revisionsCleanupOptions{})
+ require.NoError(t, err)
+ require.Equal(t, exitFailed, code)
+ require.Contains(t, out, "deleted 0 of 2 revisions (0 B), 1 could not be deleted\n node1.REV.2: permission denied\n")
+ })
+
+ t.Run("the cleanup could not run", func(t *testing.T) {
+ code, _, err := runFakeRevisionsCleanup(t, &fakeOnDemand{err: errors.New("could not find space space1")}, revisionsCleanupOptions{})
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "could not find space")
+ require.Equal(t, 0, code, "the error itself makes the command fail")
+ })
+
+ t.Run("stopped by the timeout", func(t *testing.T) {
+ code, out, err := runFakeRevisionsCleanup(t, &fakeOnDemand{results: []revisioncleanup.Result{cleanedFile}, wait: true}, revisionsCleanupOptions{timeout: 10 * time.Millisecond})
+ require.NoError(t, err)
+ require.Equal(t, exitStopped, code)
+ require.Contains(t, out, "The cleanup was stopped after the timeout of 10ms, before all files were cleaned up.")
+ })
+
+ t.Run("a context error of the storage is an error, not the timeout", func(t *testing.T) {
+ // e.g. NATS that doesn't answer in time
+ storageErr := fmt.Errorf("could not get the id: %w", context.DeadlineExceeded)
+ code, out, err := runFakeRevisionsCleanup(t, &fakeOnDemand{err: storageErr}, revisionsCleanupOptions{timeout: time.Hour})
+ require.True(t, errors.Is(err, storageErr), "expected the error of the storage, got %v", err)
+ require.Equal(t, 0, code, "the error itself makes the command fail")
+ require.NotContains(t, out, "timeout")
+ })
+
+ t.Run("interrupted while a timeout is set", func(t *testing.T) {
+ ctx, cancel := context.WithCancel(context.Background())
+ time.AfterFunc(10*time.Millisecond, cancel)
+ var out bytes.Buffer
+ o := revisionsCleanupOptions{timeout: time.Hour, request: revisioncleanup.Request{All: true, Strategy: "auto"}}
+ code, err := cleanupRevisions(ctx, &fakeOnDemand{wait: true}, o, &out)
+ require.NoError(t, err)
+ require.Equal(t, exitFailed, code)
+ require.Contains(t, out.String(), "interrupted")
+ })
+
+ t.Run("stopped by the timeout, with a failed file", func(t *testing.T) {
+ code, _, err := runFakeRevisionsCleanup(t, &fakeOnDemand{results: []revisioncleanup.Result{failedFile}, wait: true}, revisionsCleanupOptions{timeout: 10 * time.Millisecond})
+ require.NoError(t, err)
+ require.Equal(t, exitFailed, code)
+ })
+}
+
+func TestFormatBytes(t *testing.T) {
+ for in, want := range map[uint64]string{0: "0 B", 1023: "1023 B", 1024: "1.0 KiB", 1536: "1.5 KiB", 5 << 20: "5.0 MiB", 3 << 40: "3.0 TiB"} {
+ require.Equal(t, want, formatBytes(in))
+ }
+}
+
+func TestNewEventStream(t *testing.T) {
+ cfg := &config.Config{}
+ cfg.Events.Addr = "127.0.0.1:9233"
+
+ // blocked stands for a NATS that doesn't answer: newStream returns only when the test ends
+ blocked := func(t *testing.T) func(*config.Config) (string, error) {
+ release := make(chan struct{})
+ t.Cleanup(func() { close(release) })
+ return func(*config.Config) (string, error) {
+ <-release
+ return "", errors.New("released")
+ }
+ }
+
+ t.Run("returns the stream once connected", func(t *testing.T) {
+ stream, err := newEventStream(context.Background(), cfg, time.Second, func(*config.Config) (string, error) {
+ return "stream", nil
+ })
+ require.NoError(t, err)
+ require.Equal(t, "stream", stream)
+ })
+
+ t.Run("returns the error of the stream", func(t *testing.T) {
+ _, err := newEventStream(context.Background(), cfg, time.Second, func(*config.Config) (string, error) {
+ return "", errors.New("bad credentials")
+ })
+ require.EqualError(t, err, "bad credentials")
+ })
+
+ t.Run("gives up after the timeout, and says what it needs", func(t *testing.T) {
+ start := time.Now()
+ _, err := newEventStream(context.Background(), cfg, 50*time.Millisecond, blocked(t))
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "could not connect to NATS at 127.0.0.1:9233 within 50ms")
+ require.Contains(t, err.Error(), "a running OpenCloud server or a separate NATS")
+ require.True(t, time.Since(start) < 5*time.Second, "it should give up long before 5s")
+ })
+
+ t.Run("stops when interrupted", func(t *testing.T) {
+ ctx, cancel := context.WithCancel(context.Background())
+ time.AfterFunc(50*time.Millisecond, cancel)
+ _, err := newEventStream(ctx, cfg, time.Minute, blocked(t))
+ require.True(t, errors.Is(err, context.Canceled), "expected context.Canceled, got %v", err)
+ require.Contains(t, err.Error(), "interrupted while connecting to NATS")
+ })
+}
+
+func TestStorageOwnerWarning(t *testing.T) {
+ root := t.TempDir()
+
+ t.Run("none for the owner of the storage", func(t *testing.T) {
+ require.Empty(t, storageOwnerWarning(root, os.Geteuid()))
+ })
+
+ t.Run("another user", func(t *testing.T) {
+ warning := storageOwnerWarning(root, os.Geteuid()+1)
+ require.Contains(t, warning, "the storage "+root+" belongs to the user ")
+ require.Contains(t, warning, "sudo -u")
+ })
+
+ t.Run("none without a storage", func(t *testing.T) {
+ require.Empty(t, storageOwnerWarning(filepath.Join(root, "missing"), os.Geteuid()+1))
+ })
+}
+
+// TestRevisionsCleanupDriverConfig doesn't create the drivers: the metadata prefix is
+// process wide, and the legacy prefix of the aliases would clash with the prefix that
+// TestDeleteStaleNodesHonoursMetadataPrefix fixes for the whole package.
+func TestRevisionsCleanupDriverConfig(t *testing.T) {
+ newConfig := func(driver string) *config.Config {
+ cfg := defaults.FullDefaultConfig()
+ cfg.Commons = &shared.Commons{GRPCClientTLS: &shared.GRPCClientTLS{}}
+ cfg.Driver = driver
+ return cfg
+ }
+
+ for _, tc := range []struct{ driver, effective, prefix string }{
+ // the configured prefix, empty by default: then reva uses its own default
+ {"decomposed", "decomposed", ""},
+ {"decomposeds3", "decomposeds3", ""},
+ // the deprecated driver names are aliases, see revisionsCleanupDriverConfig
+ {"ocis", "decomposed", opencloudstorage.LegacyMetadataPrefix()},
+ {"s3ng", "decomposeds3", opencloudstorage.LegacyMetadataPrefix()},
+ } {
+ t.Run(tc.driver, func(t *testing.T) {
+ driver, driverConfig, err := revisionsCleanupDriverConfig(newConfig(tc.driver))
+ require.NoError(t, err)
+ require.Equal(t, tc.effective, driver)
+ require.Equal(t, tc.prefix, driverConfig["metadata_prefix"])
+ require.Equal(t, false, driverConfig["asyncfileuploads"])
+ })
+ }
+
+ t.Run("posix neither scans nor watches", func(t *testing.T) {
+ driver, driverConfig, err := revisionsCleanupDriverConfig(newConfig("posix"))
+ require.NoError(t, err)
+ require.Equal(t, "posix", driver)
+ require.Equal(t, false, driverConfig["scan_fs"])
+ require.Equal(t, false, driverConfig["watch_fs"])
+ require.Equal(t, false, driverConfig["asyncfileuploads"])
+ })
+
+ t.Run("unknown driver", func(t *testing.T) {
+ _, _, err := revisionsCleanupDriverConfig(newConfig("nonexistent"))
+ require.EqualError(t, err, `unknown storage driver "nonexistent"`)
+ })
+}
diff --git a/services/storage-users/pkg/command/root.go b/services/storage-users/pkg/command/root.go
index db14b09efb..0b357698db 100644
--- a/services/storage-users/pkg/command/root.go
+++ b/services/storage-users/pkg/command/root.go
@@ -19,6 +19,7 @@ func GetCommands(cfg *config.Config) []*cobra.Command {
Uploads(cfg),
TrashBin(cfg),
Blobstore(cfg),
+ Revisions(cfg),
// infos about this service
Health(cfg),
From 9c99eeae362d05b53deaf32cd4e152abb70101ea Mon Sep 17 00:00:00 2001
From: Pascal Bleser
Date: Thu, 15 Oct 2026 16:42:54 +0200
Subject: [PATCH 3/9] test: 1419: acceptance tests for the revision cleanup
A new cliCommands feature, cleanupFileVersions.feature, tests the
"storage-users revisions cleanup" command against a running server,
checking the remaining versions through the WebDAV versions API:
- keeping the newest version of every file in all spaces
- a dry run, which deletes nothing
- only a folder within the personal space (--space with --path)
- only a project space (--space)
- the JSON output (--json)
- no strategy while the configured one is disabled: exit code 1
- a timeout: exit code 2, nothing deleted
- a strategy without spaces after its commas ("auto,1"), as the CLI
wrapper splits commands on spaces
- a folder by its path on disk (--fs-path), posix only
- the configured strategy (STORAGE_USERS_REVISIONS_CLEANUP_STRATEGY),
which cleans up a file whenever it gets a new version: without
background workers, and with them, the default
- the configured strategy for uploads with TUS, as the web UI and the
clients upload
- the age of a version, which is the time its content was written:
uploads with an older modification time (X-OC-Mtime) make versions
that "30d" deletes right away, while "1,30d" keeps the newest one
- restoring a version with the strategy "0": the content from before
the restore is kept, so that the restore can be undone
A second feature, collaborativePosix/cleanupFileVersions.feature, tests
the versions that changes on the POSIX filesystem create, with
STORAGE_USERS_POSIX_ENABLE_FS_REVISIONS: the configured strategy cleans
up a file whenever a change on disk creates a version, with and without
background workers, and the command deletes such versions. The
collaborativePosix suite doesn't run in the CI for now
(https://github.com/opencloud-eu/opencloud/issues/2036), so these
scenarios are ready for when it does again; they pass locally. The
suite gets the FilesVersionsContext, whose steps its existing version
scenarios already use.
New steps: in CliContext, running the command for all spaces, a space,
a path within a space, a path on the POSIX filesystem, or with flags
only; checking the exact exit code; and checking the objects of a JSON
output, which "the command output should contain" can't match as it
contains quotes. In FilesVersionsContext, a number of versions that is
checked until it matches, for the cleanup that runs in the background
after postprocessing. In WebDav, the Given form of an upload with
content and a modification time.
Assisted-by: Claude Code:claude-opus-5-5
---
tests/acceptance/bootstrap/CliContext.php | 159 ++++++++++++
.../bootstrap/FilesVersionsContext.php | 30 +++
tests/acceptance/bootstrap/WebDav.php | 30 +++
tests/acceptance/config/behat.yml | 1 +
.../cliCommands/cleanupFileVersions.feature | 243 ++++++++++++++++++
.../cleanupFileVersions.feature | 55 ++++
6 files changed, 518 insertions(+)
create mode 100644 tests/acceptance/features/cliCommands/cleanupFileVersions.feature
create mode 100644 tests/acceptance/features/collaborativePosix/cleanupFileVersions.feature
diff --git a/tests/acceptance/bootstrap/CliContext.php b/tests/acceptance/bootstrap/CliContext.php
index 2ac6e976ca..50fe1f831a 100644
--- a/tests/acceptance/bootstrap/CliContext.php
+++ b/tests/acceptance/bootstrap/CliContext.php
@@ -336,6 +336,165 @@ class CliContext implements Context {
$this->featureContext->setResponse(CliHelper::runCommand($body));
}
+ /**
+ * runs the revisions cleanup command with the files to clean up and further flags
+ *
+ * @param string $scope the flags that select the files, e.g. "--all"
+ * @param string $flags e.g. "--strategy 1 --dry-run"
+ *
+ * @return void
+ */
+ private function cleanUpFileVersions(string $scope, string $flags): void {
+ $command = \trim("storage-users revisions cleanup $scope $flags");
+ $body = [
+ "command" => $command
+ ];
+ $this->featureContext->setResponse(CliHelper::runCommand($body));
+ }
+
+ /**
+ *
+ * @param string $flags
+ *
+ * @return void
+ */
+ #[When('the administrator cleans up the file versions using the CLI with flags :flags')]
+ public function theAdministratorCleansUpTheFileVersionsUsingTheCliWithFlags(string $flags): void {
+ $this->cleanUpFileVersions("", $flags);
+ }
+
+ /**
+ *
+ * @param string $flags
+ *
+ * @return void
+ */
+ #[When('the administrator cleans up the file versions of all spaces using the CLI with flags :flags')]
+ public function theAdministratorCleansUpTheFileVersionsOfAllSpacesUsingTheCliWithFlags(string $flags): void {
+ $this->cleanUpFileVersions("--all", $flags);
+ }
+
+ /**
+ *
+ * @param string $space
+ * @param string $user
+ * @param string $flags
+ *
+ * @return void
+ */
+ #[When('the administrator cleans up the file versions of space :space of user :user using the CLI with flags :flags')]
+ public function theAdministratorCleansUpTheFileVersionsOfSpaceUsingTheCliWithFlags(
+ string $space,
+ string $user,
+ string $flags
+ ): void {
+ $spaceId = $this->spacesContext->getSpaceIdByName($user, $space);
+ $this->cleanUpFileVersions("--space $spaceId", $flags);
+ }
+
+ /**
+ *
+ * @param string $path
+ * @param string $space
+ * @param string $user
+ * @param string $flags
+ *
+ * @return void
+ */
+ #[When('the administrator cleans up the file versions of :path in space :space of user :user using the CLI with flags :flags')]
+ public function theAdministratorCleansUpTheFileVersionsOfPathInSpaceUsingTheCliWithFlags(
+ string $path,
+ string $space,
+ string $user,
+ string $flags
+ ): void {
+ $spaceId = $this->spacesContext->getSpaceIdByName($user, $space);
+ $this->cleanUpFileVersions("--space $spaceId --path $path", $flags);
+ }
+
+ /**
+ *
+ * @param string $path
+ * @param string $user
+ * @param string $flags
+ *
+ * @return void
+ */
+ #[When('the administrator cleans up the file versions of :path of user :user by its path on the POSIX filesystem using the CLI with flags :flags')]
+ public function theAdministratorCleansUpTheFileVersionsByPathOnPosixUsingTheCliWithFlags(
+ string $path,
+ string $user,
+ string $flags
+ ): void {
+ $userUuid = $this->featureContext->getAttributeOfCreatedUser($user, 'id');
+ $fsPath = $this->getUsersStoragePath() . "/$userUuid/" . \ltrim($path, '/');
+ $this->cleanUpFileVersions("--fs-path $fsPath", $flags);
+ }
+
+ /**
+ *
+ * @param int $exitCode
+ *
+ * @return void
+ */
+ #[Then('the command should exit with code :exitCode')]
+ public function theCommandShouldExitWithCode(int $exitCode): void {
+ $response = $this->featureContext->getResponse();
+ $this->featureContext->theHTTPStatusCodeShouldBe(200, '', $response);
+
+ $jsonResponse = $this->featureContext->getJsonDecodedResponse($response);
+ Assert::assertSame(
+ $exitCode,
+ $jsonResponse["exitCode"],
+ "Expected exit code $exitCode, but got " . $jsonResponse["exitCode"]
+ . ". Message: " . $jsonResponse["message"]
+ );
+ }
+
+ /**
+ * checks the output of a command that prints JSON objects, one per line, e.g. with --json,
+ * for an object with a "type" and the given values
+ *
+ * @param string $type
+ * @param TableNode $table with the columns "key" and "value"
+ *
+ * @return void
+ */
+ #[Then('the JSON output of the command should contain an object of type :type with:')]
+ public function theJsonOutputOfTheCommandShouldContainAnObjectOfTypeWith(string $type, TableNode $table): void {
+ $response = $this->featureContext->getResponse();
+ $message = $this->featureContext->getJsonDecodedResponse($response)["message"];
+ $expected = [];
+ foreach ($table->getHash() as $row) {
+ $expected[$row['key']] = $this->featureContext->substituteInLineCodes($row['value']);
+ }
+
+ // other lines, e.g. log messages, are not JSON objects
+ foreach (\preg_split('/\r?\n/', $message) as $line) {
+ $object = \json_decode(\trim($line), true);
+ if (!\is_array($object) || ($object["type"] ?? null) !== $type) {
+ continue;
+ }
+ $matches = true;
+ foreach ($expected as $key => $value) {
+ $actual = $object[$key] ?? null;
+ if (\is_bool($actual)) {
+ $actual = $actual ? "true" : "false";
+ }
+ if ((string)$actual !== $value) {
+ $matches = false;
+ break;
+ }
+ }
+ if ($matches) {
+ return;
+ }
+ }
+ Assert::fail(
+ "No JSON object of type '$type' with " . \json_encode($expected) . " in the output:\n$message"
+ );
+ }
+
/**
*
* @return void
diff --git a/tests/acceptance/bootstrap/FilesVersionsContext.php b/tests/acceptance/bootstrap/FilesVersionsContext.php
index 29d24b31d9..943923d1c1 100644
--- a/tests/acceptance/bootstrap/FilesVersionsContext.php
+++ b/tests/acceptance/bootstrap/FilesVersionsContext.php
@@ -84,6 +84,36 @@ class FilesVersionsContext implements Context {
$this->featureContext->setResponse($this->getFileVersions($user, $file));
}
+ /**
+ * for changes that happen in the background, e.g. the revision cleanup after postprocessing
+ *
+ * @param string $file
+ * @param string $user
+ * @param int $number
+ *
+ * @return void
+ * @throws Exception
+ */
+ #[Then('the number of versions of file :file for user :user should eventually be :number')]
+ public function theNumberOfVersionsOfFileForUserShouldEventuallyBe(string $file, string $user, int $number): void {
+ $actualNumber = null;
+ for ($attempt = 0; $attempt < 20; $attempt++) {
+ $response = $this->getFileVersions($user, $file);
+ $this->featureContext->theHTTPStatusCodeShouldBe(207, '', $response);
+ $responseXmlObject = HttpRequestHelper::getResponseXml($response, __METHOD__);
+ $actualNumber = \count($responseXmlObject->xpath("//d:getlastmodified"));
+ if ($actualNumber === $number) {
+ return;
+ }
+ \usleep(500000);
+ }
+ Assert::assertEquals(
+ $number,
+ $actualNumber,
+ "Expected number of versions of file '$file' was '$number', but got '$actualNumber' after 10 seconds"
+ );
+ }
+
/**
*
* @param string $file
diff --git a/tests/acceptance/bootstrap/WebDav.php b/tests/acceptance/bootstrap/WebDav.php
index d3e043f6bf..f645e890b2 100644
--- a/tests/acceptance/bootstrap/WebDav.php
+++ b/tests/acceptance/bootstrap/WebDav.php
@@ -2371,6 +2371,36 @@ trait WebDav {
$this->setResponse($response);
}
+ /**
+ *
+ * @param string $user
+ * @param string|null $content
+ * @param string $mtime e.g. "-60 days", anything DateTime accepts
+ * @param string $destination
+ *
+ * @return void
+ * @throws Exception
+ */
+ #[Given('user :user has uploaded a file with content :content and mtime :mtime to :destination')]
+ public function userHasUploadedAFileWithContentAndMtimeTo(
+ string $user,
+ ?string $content,
+ string $mtime,
+ string $destination
+ ): void {
+ $user = $this->getActualUsername($user);
+ $mtime = new DateTime($mtime);
+ $mtime = $mtime->format('U');
+ $response = $this->makeDavRequest(
+ $user,
+ "PUT",
+ $destination,
+ ["X-OC-Mtime" => $mtime],
+ $content
+ );
+ $this->theHTTPStatusCodeShouldBe(["201", "204"], "", $response);
+ }
+
/**
* @param string $user
* @param string $checksum
diff --git a/tests/acceptance/config/behat.yml b/tests/acceptance/config/behat.yml
index b2e7841c63..1cd13bfa88 100644
--- a/tests/acceptance/config/behat.yml
+++ b/tests/acceptance/config/behat.yml
@@ -493,6 +493,7 @@ default:
- OcConfigContext:
- SharingNgContext:
- PublicWebDavContext:
+ - FilesVersionsContext:
coreApiMain:
paths:
diff --git a/tests/acceptance/features/cliCommands/cleanupFileVersions.feature b/tests/acceptance/features/cliCommands/cleanupFileVersions.feature
new file mode 100644
index 0000000000..e6802fdf6b
--- /dev/null
+++ b/tests/acceptance/features/cliCommands/cleanupFileVersions.feature
@@ -0,0 +1,243 @@
+@env-config
+Feature: clean up old file versions according to a cleanup strategy
+ As an administrator
+ I want to delete old file versions according to a cleanup strategy
+ So that files that are not changed anymore don't keep all their old versions
+
+ # The strategies are written without spaces, as the CLI wrapper splits commands on spaces;
+ # "2,auto,10" is the same as "2, auto, 10".
+
+ Background:
+ Given user "Alice" has been created with default attributes
+
+
+ Scenario: keep only the newest version of every file in all spaces
+ Given user "Alice" has uploaded file with content "version 1" to "textfile.txt"
+ And user "Alice" has uploaded file with content "version 2" to "textfile.txt"
+ And user "Alice" has uploaded file with content "version 3" to "textfile.txt"
+ And user "Alice" has uploaded file with content "version 4" to "textfile.txt"
+ And user "Alice" has uploaded file with content "version 1" to "anotherFile.txt"
+ And user "Alice" has uploaded file with content "version 2" to "anotherFile.txt"
+ When the administrator cleans up the file versions of all spaces using the CLI with flags "--strategy 1"
+ Then the command should be successful
+ And the command output should contain "/textfile.txt: deleted 2 of 3 revisions"
+ And the command output should not contain "/anotherFile.txt"
+ And the command output should contain "deleted 2 revisions"
+ When user "Alice" gets the number of versions of file "textfile.txt"
+ Then the HTTP status code should be "207"
+ And the number of versions should be "1"
+ When user "Alice" gets the number of versions of file "anotherFile.txt"
+ Then the HTTP status code should be "207"
+ And the number of versions should be "1"
+ And the content of file "textfile.txt" for user "Alice" should be "version 4"
+
+
+ Scenario: a dry run only prints what would be deleted
+ Given user "Alice" has uploaded file with content "version 1" to "textfile.txt"
+ And user "Alice" has uploaded file with content "version 2" to "textfile.txt"
+ And user "Alice" has uploaded file with content "version 3" to "textfile.txt"
+ When the administrator cleans up the file versions of all spaces using the CLI with flags "-s 0 --dry-run"
+ Then the command should be successful
+ And the command output should contain "/textfile.txt: would delete 2 of 2 revisions"
+ When user "Alice" gets the number of versions of file "textfile.txt"
+ Then the HTTP status code should be "207"
+ And the number of versions should be "2"
+
+
+ Scenario: clean up only a folder within the personal space
+ Given user "Alice" has created folder "folder"
+ And user "Alice" has uploaded file with content "version 1" to "folder/inFolder.txt"
+ And user "Alice" has uploaded file with content "version 2" to "folder/inFolder.txt"
+ And user "Alice" has uploaded file with content "version 3" to "folder/inFolder.txt"
+ And user "Alice" has uploaded file with content "version 1" to "outside.txt"
+ And user "Alice" has uploaded file with content "version 2" to "outside.txt"
+ And user "Alice" has uploaded file with content "version 3" to "outside.txt"
+ When the administrator cleans up the file versions of "/folder" in space "Personal" of user "Alice" using the CLI with flags "-s 0"
+ Then the command should be successful
+ And the command output should contain "/folder/inFolder.txt: deleted 2 of 2 revisions"
+ When user "Alice" gets the number of versions of file "folder/inFolder.txt"
+ Then the HTTP status code should be "207"
+ And the number of versions should be "0"
+ When user "Alice" gets the number of versions of file "outside.txt"
+ Then the HTTP status code should be "207"
+ And the number of versions should be "2"
+
+
+ Scenario: clean up only a project space
+ Given the administrator has assigned the role "Space Admin" to user "Alice" using the Graph API
+ And using spaces DAV path
+ And user "Alice" has created a space "projectSpace" with the default quota using the Graph API
+ And user "Alice" has uploaded file with content "version 1" to "personal.txt"
+ And user "Alice" has uploaded file with content "version 2" to "personal.txt"
+ And user "Alice" has uploaded file with content "version 3" to "personal.txt"
+ And user "Alice" has uploaded a file inside space "projectSpace" with content "version 1" to "project.txt"
+ And user "Alice" has uploaded a file inside space "projectSpace" with content "version 2" to "project.txt"
+ And user "Alice" has uploaded a file inside space "projectSpace" with content "version 3" to "project.txt"
+ And we save it into "PROJECT_FILEID"
+ When the administrator cleans up the file versions of space "projectSpace" of user "Alice" using the CLI with flags "-s 0"
+ Then the command should be successful
+ And the command output should contain "/project.txt: deleted 2 of 2 revisions"
+ When user "Alice" gets the number of versions of file "project.txt" using file-id "<>"
+ Then the HTTP status code should be "207"
+ And the number of versions should be "0"
+ When user "Alice" gets the number of versions of file "personal.txt"
+ Then the HTTP status code should be "207"
+ And the number of versions should be "2"
+
+
+ Scenario: print the results as JSON
+ Given user "Alice" has uploaded file with content "version 1" to "textfile.txt"
+ And user "Alice" has uploaded file with content "version 2" to "textfile.txt"
+ And user "Alice" has uploaded file with content "version 3" to "textfile.txt"
+ When the administrator cleans up the file versions of all spaces using the CLI with flags "-s 0 --json"
+ Then the command should be successful
+ And the JSON output of the command should contain an object of type "file" with:
+ | key | value |
+ | path | /textfile.txt |
+ | dry_run | false |
+ | revisions | 2 |
+ | deleted | 2 |
+ | failed | 0 |
+ And the JSON output of the command should contain an object of type "summary" with:
+ | key | value |
+ | deleted | 2 |
+ | failed | 0 |
+
+
+ Scenario: a cleanup without a strategy fails when the configured one is disabled
+ Given user "Alice" has uploaded file with content "version 1" to "textfile.txt"
+ And user "Alice" has uploaded file with content "version 2" to "textfile.txt"
+ When the administrator cleans up the file versions using the CLI with flags "--all"
+ Then the command should exit with code "1"
+ And the command output should contain "no strategy"
+ When user "Alice" gets the number of versions of file "textfile.txt"
+ Then the HTTP status code should be "207"
+ And the number of versions should be "1"
+
+
+ Scenario: a cleanup stopped by its timeout exits with code 2
+ Given user "Alice" has uploaded file with content "version 1" to "textfile.txt"
+ And user "Alice" has uploaded file with content "version 2" to "textfile.txt"
+ When the administrator cleans up the file versions of all spaces using the CLI with flags "-s 0 --timeout 1ns"
+ Then the command should exit with code "2"
+ And the command output should contain "stopped after the timeout of 1ns"
+ When user "Alice" gets the number of versions of file "textfile.txt"
+ Then the HTTP status code should be "207"
+ And the number of versions should be "1"
+
+
+ Scenario: a strategy without spaces after its commas
+ Given user "Alice" has uploaded file with content "version 1" to "textfile.txt"
+ And user "Alice" has uploaded file with content "version 2" to "textfile.txt"
+ And user "Alice" has uploaded file with content "version 3" to "textfile.txt"
+ And user "Alice" has uploaded file with content "version 4" to "textfile.txt"
+ When the administrator cleans up the file versions of all spaces using the CLI with flags "-s auto,1"
+ Then the command should be successful
+ And the command output should contain "/textfile.txt: deleted 2 of 3 revisions"
+ When user "Alice" gets the number of versions of file "textfile.txt"
+ Then the HTTP status code should be "207"
+ And the number of versions should be "1"
+
+ @skipOnOpencloud-decomposed-Storage @skipOnOpencloud-decomposeds3-Storage
+ Scenario: clean up a folder given by its path on the POSIX filesystem
+ Given user "Alice" has created folder "folder"
+ And user "Alice" has uploaded file with content "version 1" to "folder/inFolder.txt"
+ And user "Alice" has uploaded file with content "version 2" to "folder/inFolder.txt"
+ And user "Alice" has uploaded file with content "version 3" to "folder/inFolder.txt"
+ And user "Alice" has uploaded file with content "version 1" to "outside.txt"
+ And user "Alice" has uploaded file with content "version 2" to "outside.txt"
+ And user "Alice" has uploaded file with content "version 3" to "outside.txt"
+ When the administrator cleans up the file versions of "folder" of user "Alice" by its path on the POSIX filesystem using the CLI with flags "-s 0"
+ Then the command should be successful
+ And the command output should contain "/folder/inFolder.txt: deleted 2 of 2 revisions"
+ When user "Alice" gets the number of versions of file "folder/inFolder.txt"
+ Then the HTTP status code should be "207"
+ And the number of versions should be "0"
+ When user "Alice" gets the number of versions of file "outside.txt"
+ Then the HTTP status code should be "207"
+ And the number of versions should be "2"
+
+
+ Scenario: the configured strategy cleans up a file whenever it gets a new version
+ Given the following configs have been set:
+ | config | value |
+ | STORAGE_USERS_REVISIONS_CLEANUP_STRATEGY | 2 |
+ | STORAGE_USERS_REVISIONS_CLEANUP_ASYNC | false |
+ And user "Alice" has uploaded file with content "version 1" to "textfile.txt"
+ And user "Alice" has uploaded file with content "version 2" to "textfile.txt"
+ And user "Alice" has uploaded file with content "version 3" to "textfile.txt"
+ And user "Alice" has uploaded file with content "version 4" to "textfile.txt"
+ And user "Alice" has uploaded file with content "version 5" to "textfile.txt"
+ Then the number of versions of file "textfile.txt" for user "Alice" should eventually be "2"
+ And the content of file "textfile.txt" for user "Alice" should be "version 5"
+
+
+ Scenario: the configured strategy cleans up in the background by default
+ Given the following configs have been set:
+ | config | value |
+ | STORAGE_USERS_REVISIONS_CLEANUP_STRATEGY | 2 |
+ And user "Alice" has uploaded file with content "version 1" to "textfile.txt"
+ And user "Alice" has uploaded file with content "version 2" to "textfile.txt"
+ And user "Alice" has uploaded file with content "version 3" to "textfile.txt"
+ And user "Alice" has uploaded file with content "version 4" to "textfile.txt"
+ And user "Alice" has uploaded file with content "version 5" to "textfile.txt"
+ Then the number of versions of file "textfile.txt" for user "Alice" should eventually be "2"
+ And the content of file "textfile.txt" for user "Alice" should be "version 5"
+
+
+ Scenario: the configured strategy cleans up a file uploaded with TUS
+ Given the following configs have been set:
+ | config | value |
+ | STORAGE_USERS_REVISIONS_CLEANUP_STRATEGY | 2 |
+ And user "Alice" has uploaded a file with content "version 1" to "textfile.txt" via TUS inside of the space "Personal"
+ And user "Alice" has uploaded a file with content "version 2" to "textfile.txt" via TUS inside of the space "Personal"
+ And user "Alice" has uploaded a file with content "version 3" to "textfile.txt" via TUS inside of the space "Personal"
+ And user "Alice" has uploaded a file with content "version 4" to "textfile.txt" via TUS inside of the space "Personal"
+ And user "Alice" has uploaded a file with content "version 5" to "textfile.txt" via TUS inside of the space "Personal"
+ Then the number of versions of file "textfile.txt" for user "Alice" should eventually be "2"
+ And the content of file "textfile.txt" for user "Alice" should be "version 5"
+
+ # The age of a version is the time its content was written, i.e. the modification time the
+ # file had before it was changed, not the time of that change: "version 1" is 60 days old
+ # as soon as it becomes a version.
+ Scenario Outline: the configured strategy measures the age of a version by the time its content was written
+ Given the following configs have been set:
+ | config | value |
+ | STORAGE_USERS_REVISIONS_CLEANUP_STRATEGY | |
+ | STORAGE_USERS_REVISIONS_CLEANUP_ASYNC | false |
+ And user "Alice" has uploaded a file with content "version 1" and mtime "-60 days" to "textfile.txt"
+ And user "Alice" has uploaded a file with content "version 2" and mtime "-50 days" to "textfile.txt"
+ And user "Alice" has uploaded file with content "version 3" to "textfile.txt"
+ When user "Alice" gets the number of versions of file "textfile.txt"
+ Then the HTTP status code should be "207"
+ And the number of versions should be ""
+ And the content of file "textfile.txt" for user "Alice" should be "version 3"
+ Examples:
+ | strategy | versions |
+ | 30d | 0 |
+ | 1,30d | 1 |
+ | 90d | 2 |
+
+ # A restore makes the content from before the restore a version, which the cleanup keeps
+ # whatever the strategy, so that the restore can be undone. The restored version itself
+ # becomes the current content and is no longer a version.
+ Scenario: restoring a version keeps the content from before the restore, so that the restore can be undone
+ Given user "Alice" has uploaded file with content "version 1" to "textfile.txt"
+ And user "Alice" has uploaded file with content "version 2" to "textfile.txt"
+ And user "Alice" has uploaded file with content "version 3" to "textfile.txt"
+ And the following configs have been set:
+ | config | value |
+ | STORAGE_USERS_REVISIONS_CLEANUP_STRATEGY | 0 |
+ | STORAGE_USERS_REVISIONS_CLEANUP_ASYNC | false |
+ When user "Alice" restores version index "1" of file "textfile.txt" using the WebDAV API
+ Then the HTTP status code should be "204"
+ And the content of file "textfile.txt" for user "Alice" should be "version 2"
+ When user "Alice" gets the number of versions of file "textfile.txt"
+ Then the HTTP status code should be "207"
+ And the number of versions should be "1"
+ When user "Alice" restores version index "1" of file "textfile.txt" using the WebDAV API
+ Then the HTTP status code should be "204"
+ And the content of file "textfile.txt" for user "Alice" should be "version 3"
+ When user "Alice" gets the number of versions of file "textfile.txt"
+ Then the HTTP status code should be "207"
+ And the number of versions should be "1"
diff --git a/tests/acceptance/features/collaborativePosix/cleanupFileVersions.feature b/tests/acceptance/features/collaborativePosix/cleanupFileVersions.feature
new file mode 100644
index 0000000000..aee5abd9b8
--- /dev/null
+++ b/tests/acceptance/features/collaborativePosix/cleanupFileVersions.feature
@@ -0,0 +1,55 @@
+@env-config @skipOnOpencloud-decomposed-Storage @skipOnOpencloud-decomposeds3-Storage
+Feature: clean up old file versions that changes on the POSIX filesystem created
+ As an administrator
+ I want versions created by changes on the POSIX filesystem to be cleaned up like any other version
+ So that files that are changed directly on disk don't keep all their old versions
+
+ # With STORAGE_USERS_POSIX_ENABLE_FS_REVISIONS, a change on disk turns the previous content into a
+ # version. That needs a copy of the previous content, which posix only keeps of content it wrote
+ # or picked up while the setting was on, so it is set before the files are uploaded.
+
+ Background:
+ Given the following configs have been set:
+ | config | value |
+ | STORAGE_USERS_POSIX_WATCH_FS | true |
+ | STORAGE_USERS_POSIX_ENABLE_FS_REVISIONS | true |
+ And user "Alice" has been created with default attributes
+
+ # The strategy is only set after the uploads, so that the file has 3 versions when it is changed
+ # on disk: only the cleanup that the change on disk triggers can bring it down to 1.
+ Scenario Outline: the configured strategy cleans up a file whenever a change on disk creates a version
+ Given user "Alice" has uploaded file with content "version 1" to "textfile.txt"
+ And user "Alice" has uploaded file with content "version 2" to "textfile.txt"
+ And user "Alice" has uploaded file with content "version 3" to "textfile.txt"
+ And user "Alice" has uploaded file with content "version 4" to "textfile.txt"
+ And the following configs have been set:
+ | config | value |
+ | STORAGE_USERS_REVISIONS_CLEANUP_STRATEGY | 1 |
+ | STORAGE_USERS_REVISIONS_CLEANUP_ASYNC | |
+ When the administrator puts the content " changed on disk" into the file "textfile.txt" in the POSIX storage folder of user "Alice"
+ Then the command should be successful
+ And as "Alice" the final content of file "textfile.txt" should be "version 4 changed on disk"
+ And the number of versions of file "textfile.txt" for user "Alice" should eventually be "1"
+ And the content of version index "1" of file "textfile.txt" for user "Alice" should be "version 4"
+ Examples:
+ | async |
+ | true |
+ | false |
+
+
+ Scenario: the cleanup command deletes versions that changes on disk created
+ Given user "Alice" has uploaded file with content "version 1" to "textfile.txt"
+ When the administrator puts the content ", changed on disk" into the file "textfile.txt" in the POSIX storage folder of user "Alice"
+ Then the command should be successful
+ And as "Alice" the final content of file "textfile.txt" should be "version 1, changed on disk"
+ When the administrator puts the content ", changed again" into the file "textfile.txt" in the POSIX storage folder of user "Alice"
+ Then the command should be successful
+ And as "Alice" the final content of file "textfile.txt" should be "version 1, changed on disk, changed again"
+ And the number of versions of file "textfile.txt" for user "Alice" should eventually be "2"
+ When the administrator cleans up the file versions of all spaces using the CLI with flags "-s 0"
+ Then the command should be successful
+ And the command output should contain "/textfile.txt: deleted 2 of 2 revisions"
+ When user "Alice" gets the number of versions of file "textfile.txt"
+ Then the HTTP status code should be "207"
+ And the number of versions should be "0"
+ And the content of file "textfile.txt" for user "Alice" should be "version 1, changed on disk, changed again"
From 1b0a81f39d99d354f3f896dc409dc7724627764b Mon Sep 17 00:00:00 2001
From: Pascal Bleser
Date: Wed, 18 Nov 2026 21:19:21 +0100
Subject: [PATCH 4/9] feat: 1419: refuse to clean up revisions with a file
metadata cache local to each process
The revisions cleanup command runs in a process of its own. With a file
metadata cache that each process keeps in its own memory ('memory', the
default, or 'ocmem'), the server doesn't learn about the revisions the
command deletes: a list of versions that is already open, e.g. in the
Versions panel, keeps showing them, and downloading or restoring one of
them fails. A new list is right, as the server lists them from disk.
The command now refuses to run with such a cache. The error says how to
share the cache (STORAGE_USERS_FILEMETADATA_CACHE_STORE=nats-js-kv, not
OC_CACHE_STORE, which sets the cache store of all services) and that
--allow-local-cache runs it anyway. A dry run deletes nothing and runs
with any cache.
The acceptance tests pass --allow-local-cache: their server runs with the
default cache, and they check the versions through the API, which lists
them from disk.
Assisted-by: Claude Code:claude-opus-5-5
---
services/storage-users/README.md | 3 ++
.../storage-users/pkg/command/revisions.go | 35 +++++++++++++++++++
.../pkg/command/revisions_test.go | 28 ++++++++++++++-
tests/acceptance/bootstrap/CliContext.php | 5 ++-
4 files changed, 69 insertions(+), 2 deletions(-)
diff --git a/services/storage-users/README.md b/services/storage-users/README.md
index 470eb0fcd6..2bc79a164b 100644
--- a/services/storage-users/README.md
+++ b/services/storage-users/README.md
@@ -351,6 +351,8 @@ opencloud storage-users revisions cleanup [flags]
The command uses the storage directly, with the configuration of the `storage-users` service, and can run while the service is running. It needs access to the storage and, for the `posix` driver, to NATS. With the single binary, NATS runs within the server: without a running server, the command gives up after 10 seconds. It needs no service account.
+The server must see the revisions the command deletes, so its file metadata cache must be shared between processes, e.g. with `STORAGE_USERS_FILEMETADATA_CACHE_STORE=nats-js-kv` (see [Caching](#caching); `OC_CACHE_STORE` would set the cache store of all services). With a cache that each process keeps in its own memory, `memory` (the default) or `ocmem`, the server would keep listing the deleted revisions until their cache entries expire or it restarts, and restoring or downloading one of them would fail. The command therefore refuses to run with such a cache, unless `--allow-local-cache` is given. A dry run deletes nothing and runs with any cache.
+
Run the command as the user that OpenCloud runs as, e.g. with `sudo -u opencloud` on a server where OpenCloud runs as the user `opencloud`, or with `docker exec` in its container. The lock files the command creates belong to the user that runs it, with permissions only for that user, so OpenCloud may not be able to lock these files anymore if it was run as another user, e.g. as `root`. Unless it is a dry run, which changes nothing on disk, the command warns when the storage belongs to another user.
#### Strategies
@@ -401,6 +403,7 @@ The strategy and the settings of the background workers default to the configure
| `--json`, `-j` | off | Print JSON objects, one per line, instead of text. |
| `--timeout`, `-t` | none | Stop the cleanup gracefully after this time, e.g. `30m` or `2h`. |
| `--shuffle` | off | Clean up the spaces, and the files within each folder, in a random order. |
+| `--allow-local-cache` | off | Run even though the file metadata cache is kept in the memory of each process, see above. |
By default, the command prints a line for every file whose revisions it deleted, that it could not clean up or that it skipped, with the space ID and the path of the file within the space, and a summary:
diff --git a/services/storage-users/pkg/command/revisions.go b/services/storage-users/pkg/command/revisions.go
index def373cb41..a970f090b9 100644
--- a/services/storage-users/pkg/command/revisions.go
+++ b/services/storage-users/pkg/command/revisions.go
@@ -9,6 +9,7 @@ import (
"os"
"os/signal"
"os/user"
+ "slices"
"strconv"
"strings"
"syscall"
@@ -28,6 +29,7 @@ import (
"github.com/opencloud-eu/reva/v3/pkg/storage/fs/registry"
"github.com/opencloud-eu/reva/v3/pkg/storage/pkg/decomposedfs/revisioncleanup"
"github.com/opencloud-eu/reva/v3/pkg/storagespace"
+ "github.com/opencloud-eu/reva/v3/pkg/store"
)
// The exit codes of the revisions cleanup command
@@ -90,6 +92,13 @@ By default, it prints a line for every file it deleted revisions of, could not c
up or skipped, and a summary. --verbose prints every file with every revision, what
was decided about it and why. --json prints the same as JSON objects, one per line.
+The server must see the revisions the command deletes: its file metadata cache must be
+shared between processes, e.g. with STORAGE_USERS_FILEMETADATA_CACHE_STORE=nats-js-kv.
+With a cache kept in the memory of each process ('memory', the default, or 'ocmem'), the
+server would keep listing the deleted revisions until their cache entries expire or it
+restarts, so the command refuses to run, unless --allow-local-cache is given. A dry run
+runs with any cache.
+
--dry-run deletes nothing and prints what would be deleted. It changes nothing on
disk, and doesn't keep the files locked while it decides: its decisions are a
snapshot, and a real run may decide differently for files that change meanwhile.
@@ -140,6 +149,7 @@ Exit codes: 0 when done, 1 if the cleanup or any file failed, or if it was inter
flags.IntVar(&f.queueSize, "queue-size", 0, "the number of files that can wait for a worker, 0 for automatic, defaults to STORAGE_USERS_REVISIONS_CLEANUP_ASYNC_QUEUE_SIZE")
flags.StringVar(&f.queueFull, "queue-full", string(revisioncleanup.QueueFullBlock), "'block' (wait for room) or 'drop' (skip) files when the queue is full")
flags.DurationVar(&f.queueFullTimeout, "queue-full-timeout", 0, "with --queue-full block, skip a file after waiting this long for room, e.g. 10s; 0 waits as long as it takes")
+ flags.BoolVar(&f.allowLocalCache, "allow-local-cache", false, "run even though the file metadata cache is kept in the memory of each process, so that the server keeps listing the deleted revisions for a while")
return cmd, f
}
@@ -156,6 +166,8 @@ type revisionsCleanupFlags struct {
// the settings of a full queue, which, unlike the others, don't default to the configured
// ones, see the help of the command
queueFullTimeout time.Duration
+ // run even with a file metadata cache local to each process, see checkFileMetadataCache
+ allowLocalCache bool
}
// revisionsCleanupOptions are the settings of a run of the revisions cleanup command
@@ -197,6 +209,12 @@ func (f *revisionsCleanupFlags) options(cfg *config.Config, changed func(name st
if r.FSPath != "" && cfg.Driver != "posix" {
return o, fmt.Errorf("--fs-path is only supported by the 'posix' driver, not by %q", cfg.Driver)
}
+ // a dry run deletes nothing, so the server's cache can't go stale
+ if !r.DryRun && !f.allowLocalCache {
+ if err := checkFileMetadataCache(cfg.FilemetadataCache.Store); err != nil {
+ return o, err
+ }
+ }
r.Strategy = cfg.RevisionsCleanup.Strategy
if changed("strategy") {
@@ -235,6 +253,23 @@ func (f *revisionsCleanupFlags) options(cfg *config.Config, changed func(name st
return o, nil
}
+// localCacheStores are the cache stores that keep the cache in the memory of each process.
+var localCacheStores = []string{store.TypeMemory, store.TypeOCMem}
+
+// checkFileMetadataCache returns an error if the file metadata cache of the storage is kept in the
+// memory of each process. The command runs in a process of its own: the server wouldn't see
+// the revisions it deletes and keep listing them, until their cache entries expire or the
+// server restarts. Restoring or downloading them fails then, as they are gone from disk.
+func checkFileMetadataCache(storeType string) error {
+ if !slices.Contains(localCacheStores, storeType) {
+ return nil
+ }
+ return fmt.Errorf("the file metadata cache of the storage-users service is kept in the memory of each process (store %q): "+
+ "the server would keep listing the revisions this command deletes, until their cache entries expire or it restarts. "+
+ "Share the cache by setting STORAGE_USERS_FILEMETADATA_CACHE_STORE to 'nats-js-kv' "+
+ "(OC_CACHE_STORE would set the cache store of all services), or run the command anyway with --allow-local-cache", storeType)
+}
+
// runRevisionsCleanup runs the revisions cleanup command and returns its exit code.
func runRevisionsCleanup(cmd *cobra.Command, cfg *config.Config, f *revisionsCleanupFlags) (int, error) {
o, err := f.options(cfg, cmd.Flags().Changed)
diff --git a/services/storage-users/pkg/command/revisions_test.go b/services/storage-users/pkg/command/revisions_test.go
index f2202dac73..353e53ec62 100644
--- a/services/storage-users/pkg/command/revisions_test.go
+++ b/services/storage-users/pkg/command/revisions_test.go
@@ -31,7 +31,8 @@ func revisionsCleanupOptionsFor(t *testing.T, cfg *config.Config, args ...string
func revisionsCleanupConfig() *config.Config {
return &config.Config{
- Driver: "decomposed",
+ Driver: "decomposed",
+ FilemetadataCache: config.FilemetadataCache{Store: "nats-js-kv"},
RevisionsCleanup: config.RevisionsCleanup{
Strategy: "auto, 90d",
Async: true,
@@ -89,6 +90,31 @@ func TestRevisionsCleanupOptions(t *testing.T) {
require.Equal(t, "/var/lib/opencloud/users/einstein", o.request.FSPath)
})
+ t.Run("a file metadata cache local to each process", func(t *testing.T) {
+ for _, storeType := range []string{"memory", "ocmem"} {
+ cfg := revisionsCleanupConfig()
+ cfg.FilemetadataCache.Store = storeType
+
+ _, err := revisionsCleanupOptionsFor(t, cfg, "--all")
+ require.Error(t, err, storeType)
+ require.Contains(t, err.Error(), "'nats-js-kv'", "the error names the fix")
+ require.Contains(t, err.Error(), "--allow-local-cache", "the error names the override")
+
+ _, err = revisionsCleanupOptionsFor(t, cfg, "--all", "--allow-local-cache")
+ require.NoError(t, err, "with the override, %s", storeType)
+
+ _, err = revisionsCleanupOptionsFor(t, cfg, "--all", "--dry-run")
+ require.NoError(t, err, "a dry run deletes nothing, %s", storeType)
+ }
+
+ for _, storeType := range []string{"nats-js-kv", "redis-sentinel", "noop"} {
+ cfg := revisionsCleanupConfig()
+ cfg.FilemetadataCache.Store = storeType
+ _, err := revisionsCleanupOptionsFor(t, cfg, "--all")
+ require.NoError(t, err, storeType)
+ }
+ })
+
t.Run("a path within a space", func(t *testing.T) {
o, err := revisionsCleanupOptionsFor(t, revisionsCleanupConfig(), "--space", "space1", "--path", "/Documents")
require.NoError(t, err)
diff --git a/tests/acceptance/bootstrap/CliContext.php b/tests/acceptance/bootstrap/CliContext.php
index 50fe1f831a..c3fb3ed307 100644
--- a/tests/acceptance/bootstrap/CliContext.php
+++ b/tests/acceptance/bootstrap/CliContext.php
@@ -345,7 +345,10 @@ class CliContext implements Context {
* @return void
*/
private function cleanUpFileVersions(string $scope, string $flags): void {
- $command = \trim("storage-users revisions cleanup $scope $flags");
+ // The test server keeps its file metadata cache in memory, the default, which the command
+ // refuses unless it is allowed: the scenarios check the versions through the API, which
+ // lists them from disk, so the cache of the server going stale doesn't matter here.
+ $command = \trim("storage-users revisions cleanup --allow-local-cache $scope $flags");
$body = [
"command" => $command
];
From cae8a78da91534dccd4f27f1fcb138c3841132f6 Mon Sep 17 00:00:00 2001
From: Pascal Bleser
Date: Wed, 18 Nov 2026 21:19:21 +0100
Subject: [PATCH 5/9] docs: 1419: a restore keeps the revision of the replaced
content
The revision cleanup doesn't apply the strategy to the revision a
restore created of the content it replaced, not even an age limit,
as long as the file has the restored content. Say so next to the
strategies, as it is an exception admins wouldn't expect.
Assisted-by: Claude Code:claude-opus-5-5
---
services/storage-users/README.md | 2 ++
1 file changed, 2 insertions(+)
diff --git a/services/storage-users/README.md b/services/storage-users/README.md
index 2bc79a164b..3a6c710a09 100644
--- a/services/storage-users/README.md
+++ b/services/storage-users/README.md
@@ -375,6 +375,8 @@ Durations in days or weeks can use an uppercase unit, `D` or `W`, to count from
| `X1, auto, X2` | Keep everything within `X1`, delete everything beyond `X2`, thin out in between | `7d, auto, 90d`, `1D, auto, 30d` |
| `disabled` | Never delete revisions | `disabled` |
+A restore keeps the revision of the content it replaced as long as the file has the restored content: the strategy doesn't apply to that one revision, not even an age limit like `30d`, until the file is changed again, by an upload, another restore or, with `posix`, a change on disk.
+
Note that the age of a revision is the time its content was written, i.e. the modification time the file had before it was changed, which is also the date the version list shows for it. It is not the time the file was changed, which turned that content into a revision. A document that was unchanged for two months gets a revision that is two months old when it is changed, and e.g. `30d` deletes that revision right away. Combine a duration with a number of revisions, e.g. `5, 30d`, to always keep the newest ones.
#### Selecting the Files
From 498e5030e7defb6f98c0c990e1b9b6a5d0580c04 Mon Sep 17 00:00:00 2001
From: Pascal Bleser
Date: Wed, 18 Nov 2026 21:46:59 +0100
Subject: [PATCH 6/9] feat: 1419: let a dry run of the revisions cleanup keep a
cache of its own
A dry run reads the metadata of every file it looks at. With a file
metadata cache shared with the server, e.g. 'nats-js-kv', it filled
that cache with entries for all of them, for a run that changes
nothing.
A dry run now always keeps its file metadata cache in its own memory,
whatever is configured. It doesn't need the shared cache: it deletes
nothing the server would have to see, and a cache of its own starts
empty, so it reads the metadata from disk. A real run still uses the
configured cache, which must be shared.
Assisted-by: Claude Code:claude-opus-5-5
---
services/storage-users/README.md | 2 +-
.../storage-users/pkg/command/revisions.go | 38 ++++++++++++++++---
.../pkg/command/revisions_test.go | 21 ++++++++--
3 files changed, 51 insertions(+), 10 deletions(-)
diff --git a/services/storage-users/README.md b/services/storage-users/README.md
index 3a6c710a09..d8d8b02b5f 100644
--- a/services/storage-users/README.md
+++ b/services/storage-users/README.md
@@ -351,7 +351,7 @@ opencloud storage-users revisions cleanup [flags]
The command uses the storage directly, with the configuration of the `storage-users` service, and can run while the service is running. It needs access to the storage and, for the `posix` driver, to NATS. With the single binary, NATS runs within the server: without a running server, the command gives up after 10 seconds. It needs no service account.
-The server must see the revisions the command deletes, so its file metadata cache must be shared between processes, e.g. with `STORAGE_USERS_FILEMETADATA_CACHE_STORE=nats-js-kv` (see [Caching](#caching); `OC_CACHE_STORE` would set the cache store of all services). With a cache that each process keeps in its own memory, `memory` (the default) or `ocmem`, the server would keep listing the deleted revisions until their cache entries expire or it restarts, and restoring or downloading one of them would fail. The command therefore refuses to run with such a cache, unless `--allow-local-cache` is given. A dry run deletes nothing and runs with any cache.
+The server must see the revisions the command deletes, so its file metadata cache must be shared between processes, e.g. with `STORAGE_USERS_FILEMETADATA_CACHE_STORE=nats-js-kv` (see [Caching](#caching); `OC_CACHE_STORE` would set the cache store of all services). With a cache that each process keeps in its own memory, `memory` (the default) or `ocmem`, the server would keep listing the deleted revisions until their cache entries expire or it restarts, and restoring or downloading one of them would fail. The command therefore refuses to run with such a cache, unless `--allow-local-cache` is given. A dry run deletes nothing the server would have to see: it always keeps a cache of its own in its memory, whatever is configured, so that it doesn't fill the shared cache with the metadata of every file it looks at.
Run the command as the user that OpenCloud runs as, e.g. with `sudo -u opencloud` on a server where OpenCloud runs as the user `opencloud`, or with `docker exec` in its container. The lock files the command creates belong to the user that runs it, with permissions only for that user, so OpenCloud may not be able to lock these files anymore if it was run as another user, e.g. as `root`. Unless it is a dry run, which changes nothing on disk, the command warns when the storage belongs to another user.
diff --git a/services/storage-users/pkg/command/revisions.go b/services/storage-users/pkg/command/revisions.go
index a970f090b9..f7034033db 100644
--- a/services/storage-users/pkg/command/revisions.go
+++ b/services/storage-users/pkg/command/revisions.go
@@ -97,7 +97,8 @@ shared between processes, e.g. with STORAGE_USERS_FILEMETADATA_CACHE_STORE=nats-
With a cache kept in the memory of each process ('memory', the default, or 'ocmem'), the
server would keep listing the deleted revisions until their cache entries expire or it
restarts, so the command refuses to run, unless --allow-local-cache is given. A dry run
-runs with any cache.
+always keeps a cache of its own in its memory: it deletes nothing the server would have to
+see, and leaves the shared cache alone.
--dry-run deletes nothing and prints what would be deleted. It changes nothing on
disk, and doesn't keep the files locked while it decides: its decisions are a
@@ -299,7 +300,7 @@ func runRevisionsCleanup(cmd *cobra.Command, cfg *config.Config, f *revisionsCle
if !o.request.DryRun {
warnAboutStorageOwner(cfg, &logger)
}
- onDemand, err := revisionsCleanupDriver(ctx, cfg, &logger)
+ onDemand, err := revisionsCleanupDriver(ctx, cfg, o.request.DryRun, &logger)
if err != nil {
return 0, err
}
@@ -348,7 +349,10 @@ func cleanupRevisions(ctx context.Context, onDemand revisioncleanup.OnDemand, o
// revisionsCleanupDriverConfig returns the name and the configuration of the storage
// driver to create, without the parts of the storage-users service that would
// interfere with the running service.
-func revisionsCleanupDriverConfig(cfg *config.Config) (string, map[string]any, error) {
+//
+// A dry run gets a file metadata cache of its own, in its memory, whatever is configured, see
+// dryRunFileMetadataCache.
+func revisionsCleanupDriverConfig(cfg *config.Config, dryRun bool) (string, map[string]any, error) {
// The deprecated driver names "ocis" and "s3ng" are aliases of "decomposed" and
// "decomposeds3" since https://github.com/opencloud-eu/opencloud/pull/3859: there
// are no driver entries of their own anymore, and StorageProviderDrivers sets the
@@ -369,12 +373,34 @@ func revisionsCleanupDriverConfig(cfg *config.Config) (string, map[string]any, e
// Without async uploads, the driver doesn't join the postprocessing consumer group of the
// service: the events delivered to this short-lived process would be lost.
driverConfig["asyncfileuploads"] = false
+ if dryRun {
+ if err := dryRunFileMetadataCache(driverConfig); err != nil {
+ return "", nil, err
+ }
+ }
return driver, driverConfig, nil
}
+// dryRunFileMetadataCache makes the driver keep its file metadata cache in the memory of the
+// process. A dry run reads the metadata of every file it looks at: with a cache shared with the
+// server, e.g. 'nats-js-kv', it would fill that cache with entries for all of them, for a run that
+// changes nothing. It doesn't need the shared cache either, as it deletes nothing that the server
+// would have to see, and a cache of its own starts empty, so that it reads the metadata from disk.
+// That a command walking a whole space should not fill the shared cache is one of the open points
+// of https://github.com/opencloud-eu/opencloud/issues/4064, which proposes 'nats-js-kv' as the
+// default.
+func dryRunFileMetadataCache(driverConfig map[string]any) error {
+ cache, ok := driverConfig["filemetadatacache"].(map[string]any)
+ if !ok {
+ return errors.New("the storage driver has no file metadata cache configuration")
+ }
+ cache["cache_store"] = store.TypeMemory
+ return nil
+}
+
// revisionsCleanupDriver creates the storage driver, see revisionsCleanupDriverConfig.
-func revisionsCleanupDriver(ctx context.Context, cfg *config.Config, log *zerolog.Logger) (revisioncleanup.OnDemand, error) {
- driver, driverConfig, err := revisionsCleanupDriverConfig(cfg)
+func revisionsCleanupDriver(ctx context.Context, cfg *config.Config, dryRun bool, log *zerolog.Logger) (revisioncleanup.OnDemand, error) {
+ driver, driverConfig, err := revisionsCleanupDriverConfig(cfg, dryRun)
if err != nil {
return nil, err
}
@@ -464,7 +490,7 @@ func userName(uid string) string {
// warnAboutStorageOwner logs the warning of storageOwnerWarning for the storage of the driver
// that the command creates, if there is one.
func warnAboutStorageOwner(cfg *config.Config, log *zerolog.Logger) {
- _, driverConfig, err := revisionsCleanupDriverConfig(cfg)
+ _, driverConfig, err := revisionsCleanupDriverConfig(cfg, false)
if err != nil {
// revisionsCleanupDriver reports it
return
diff --git a/services/storage-users/pkg/command/revisions_test.go b/services/storage-users/pkg/command/revisions_test.go
index 353e53ec62..c6263ac1a1 100644
--- a/services/storage-users/pkg/command/revisions_test.go
+++ b/services/storage-users/pkg/command/revisions_test.go
@@ -419,7 +419,7 @@ func TestRevisionsCleanupDriverConfig(t *testing.T) {
{"s3ng", "decomposeds3", opencloudstorage.LegacyMetadataPrefix()},
} {
t.Run(tc.driver, func(t *testing.T) {
- driver, driverConfig, err := revisionsCleanupDriverConfig(newConfig(tc.driver))
+ driver, driverConfig, err := revisionsCleanupDriverConfig(newConfig(tc.driver), false)
require.NoError(t, err)
require.Equal(t, tc.effective, driver)
require.Equal(t, tc.prefix, driverConfig["metadata_prefix"])
@@ -428,7 +428,7 @@ func TestRevisionsCleanupDriverConfig(t *testing.T) {
}
t.Run("posix neither scans nor watches", func(t *testing.T) {
- driver, driverConfig, err := revisionsCleanupDriverConfig(newConfig("posix"))
+ driver, driverConfig, err := revisionsCleanupDriverConfig(newConfig("posix"), false)
require.NoError(t, err)
require.Equal(t, "posix", driver)
require.Equal(t, false, driverConfig["scan_fs"])
@@ -436,8 +436,23 @@ func TestRevisionsCleanupDriverConfig(t *testing.T) {
require.Equal(t, false, driverConfig["asyncfileuploads"])
})
+ t.Run("a dry run keeps a file metadata cache of its own", func(t *testing.T) {
+ for _, driver := range []string{"decomposed", "decomposeds3", "posix"} {
+ cfg := newConfig(driver)
+ cfg.FilemetadataCache.Store = "nats-js-kv"
+
+ _, driverConfig, err := revisionsCleanupDriverConfig(cfg, true)
+ require.NoError(t, err, driver)
+ require.Equal(t, "memory", driverConfig["filemetadatacache"].(map[string]any)["cache_store"], driver)
+
+ _, driverConfig, err = revisionsCleanupDriverConfig(cfg, false)
+ require.NoError(t, err, driver)
+ require.Equal(t, "nats-js-kv", driverConfig["filemetadatacache"].(map[string]any)["cache_store"], "a real run uses the configured cache, %s", driver)
+ }
+ })
+
t.Run("unknown driver", func(t *testing.T) {
- _, _, err := revisionsCleanupDriverConfig(newConfig("nonexistent"))
+ _, _, err := revisionsCleanupDriverConfig(newConfig("nonexistent"), false)
require.EqualError(t, err, `unknown storage driver "nonexistent"`)
})
}
From a9b16e67458ac08391408a7c052da63b81d5d9bb Mon Sep 17 00:00:00 2001
From: Pascal Bleser
Date: Wed, 18 Nov 2026 22:27:54 +0100
Subject: [PATCH 7/9] fix: 1419: describe what a file metadata cache local to
each process does
The revisions cleanup command, its help and the README said that, with
a cache local to each process, the server would keep listing the
revisions the command deleted until their cache entries expire or it
restarts. It doesn't: the server lists the revisions of a file from
disk. What it doesn't learn about is that they were deleted, so a list
of versions that is already open, e.g. in the Versions panel, keeps
showing them, and downloading or restoring one of them fails.
The command still refuses to run with such a cache, unless
--allow-local-cache is given: a shared cache is the right setup for a
command that changes the storage next to the server.
Assisted-by: Claude Code:claude-opus-5-5
---
services/storage-users/README.md | 2 +-
.../storage-users/pkg/command/revisions.go | 26 +++++++++++--------
2 files changed, 16 insertions(+), 12 deletions(-)
diff --git a/services/storage-users/README.md b/services/storage-users/README.md
index d8d8b02b5f..3b20097953 100644
--- a/services/storage-users/README.md
+++ b/services/storage-users/README.md
@@ -351,7 +351,7 @@ opencloud storage-users revisions cleanup [flags]
The command uses the storage directly, with the configuration of the `storage-users` service, and can run while the service is running. It needs access to the storage and, for the `posix` driver, to NATS. With the single binary, NATS runs within the server: without a running server, the command gives up after 10 seconds. It needs no service account.
-The server must see the revisions the command deletes, so its file metadata cache must be shared between processes, e.g. with `STORAGE_USERS_FILEMETADATA_CACHE_STORE=nats-js-kv` (see [Caching](#caching); `OC_CACHE_STORE` would set the cache store of all services). With a cache that each process keeps in its own memory, `memory` (the default) or `ocmem`, the server would keep listing the deleted revisions until their cache entries expire or it restarts, and restoring or downloading one of them would fail. The command therefore refuses to run with such a cache, unless `--allow-local-cache` is given. A dry run deletes nothing the server would have to see: it always keeps a cache of its own in its memory, whatever is configured, so that it doesn't fill the shared cache with the metadata of every file it looks at.
+The server must learn about the revisions the command deletes, so its file metadata cache must be shared between processes, e.g. with `STORAGE_USERS_FILEMETADATA_CACHE_STORE=nats-js-kv` (see [Caching](#caching); `OC_CACHE_STORE` would set the cache store of all services). With a cache that each process keeps in its own memory, `memory` (the default) or `ocmem`, the server doesn't learn about them. It lists the versions of a file from disk all the same, so a new list is right, but a list that is already open, for example in the Versions panel, keeps showing the deleted versions, and downloading or restoring one of them fails. The command therefore refuses to run with such a cache, unless `--allow-local-cache` is given. A dry run deletes nothing the server would have to learn about: it always keeps a cache of its own in its memory, whatever is configured, so that it doesn't fill the shared cache with the metadata of every file it looks at.
Run the command as the user that OpenCloud runs as, e.g. with `sudo -u opencloud` on a server where OpenCloud runs as the user `opencloud`, or with `docker exec` in its container. The lock files the command creates belong to the user that runs it, with permissions only for that user, so OpenCloud may not be able to lock these files anymore if it was run as another user, e.g. as `root`. Unless it is a dry run, which changes nothing on disk, the command warns when the storage belongs to another user.
diff --git a/services/storage-users/pkg/command/revisions.go b/services/storage-users/pkg/command/revisions.go
index f7034033db..4bb6a42acc 100644
--- a/services/storage-users/pkg/command/revisions.go
+++ b/services/storage-users/pkg/command/revisions.go
@@ -92,13 +92,14 @@ By default, it prints a line for every file it deleted revisions of, could not c
up or skipped, and a summary. --verbose prints every file with every revision, what
was decided about it and why. --json prints the same as JSON objects, one per line.
-The server must see the revisions the command deletes: its file metadata cache must be
-shared between processes, e.g. with STORAGE_USERS_FILEMETADATA_CACHE_STORE=nats-js-kv.
+The server must learn about the revisions the command deletes: its file metadata cache must
+be shared between processes, e.g. with STORAGE_USERS_FILEMETADATA_CACHE_STORE=nats-js-kv.
With a cache kept in the memory of each process ('memory', the default, or 'ocmem'), the
-server would keep listing the deleted revisions until their cache entries expire or it
-restarts, so the command refuses to run, unless --allow-local-cache is given. A dry run
-always keeps a cache of its own in its memory: it deletes nothing the server would have to
-see, and leaves the shared cache alone.
+server lists the versions of a file from disk all the same, but a list of versions that is
+already open keeps showing the deleted ones, and downloading or restoring one of them fails.
+The command therefore refuses to run with such a cache, unless --allow-local-cache is given.
+A dry run always keeps a cache of its own in its memory: it deletes nothing the server would
+have to learn about, and leaves the shared cache alone.
--dry-run deletes nothing and prints what would be deleted. It changes nothing on
disk, and doesn't keep the files locked while it decides: its decisions are a
@@ -150,7 +151,7 @@ Exit codes: 0 when done, 1 if the cleanup or any file failed, or if it was inter
flags.IntVar(&f.queueSize, "queue-size", 0, "the number of files that can wait for a worker, 0 for automatic, defaults to STORAGE_USERS_REVISIONS_CLEANUP_ASYNC_QUEUE_SIZE")
flags.StringVar(&f.queueFull, "queue-full", string(revisioncleanup.QueueFullBlock), "'block' (wait for room) or 'drop' (skip) files when the queue is full")
flags.DurationVar(&f.queueFullTimeout, "queue-full-timeout", 0, "with --queue-full block, skip a file after waiting this long for room, e.g. 10s; 0 waits as long as it takes")
- flags.BoolVar(&f.allowLocalCache, "allow-local-cache", false, "run even though the file metadata cache is kept in the memory of each process, so that the server keeps listing the deleted revisions for a while")
+ flags.BoolVar(&f.allowLocalCache, "allow-local-cache", false, "run even though the file metadata cache is kept in the memory of each process, so that the server doesn't learn about the deleted revisions")
return cmd, f
}
@@ -258,15 +259,18 @@ func (f *revisionsCleanupFlags) options(cfg *config.Config, changed func(name st
var localCacheStores = []string{store.TypeMemory, store.TypeOCMem}
// checkFileMetadataCache returns an error if the file metadata cache of the storage is kept in the
-// memory of each process. The command runs in a process of its own: the server wouldn't see
-// the revisions it deletes and keep listing them, until their cache entries expire or the
-// server restarts. Restoring or downloading them fails then, as they are gone from disk.
+// memory of each process. The command runs in a process of its own, so the server doesn't learn
+// about the revisions it deletes. The server lists the revisions of a file from disk, so a new
+// list is right, but a list that is already open, e.g. in the Versions panel, keeps showing the
+// deleted ones, and downloading or restoring one of them fails with "not found", as they are gone
+// from disk.
func checkFileMetadataCache(storeType string) error {
if !slices.Contains(localCacheStores, storeType) {
return nil
}
return fmt.Errorf("the file metadata cache of the storage-users service is kept in the memory of each process (store %q): "+
- "the server would keep listing the revisions this command deletes, until their cache entries expire or it restarts. "+
+ "the server doesn't learn about the revisions this command deletes, so a list of versions that is already open keeps showing them, "+
+ "and downloading or restoring one of them fails. "+
"Share the cache by setting STORAGE_USERS_FILEMETADATA_CACHE_STORE to 'nats-js-kv' "+
"(OC_CACHE_STORE would set the cache store of all services), or run the command anyway with --allow-local-cache", storeType)
}
From 5e8a88a05f71bdfd34a0a4a0854f190cf952606c Mon Sep 17 00:00:00 2001
From: Pascal Bleser
Date: Thu, 19 Nov 2026 00:02:20 +0100
Subject: [PATCH 8/9] feat: 1419: clean up revisions by the time they were
created
Follows opencloud-eu/reva#895, which makes the revision cleanup go by
the time a revision was created, recorded by the server, instead of the
modification time of its content, which clients choose with X-OC-Mtime.
"auto" keeps the oldest revision of each slot (#3735).
- The storage-users README explains the new age of a revision.
- The acceptance scenario outline that checked the age as the time the
content was written is replaced by two scenarios: versions whose
content is dated 60 and 50 days ago are kept by "30d", and a version
with content dated 10 years ahead doesn't push out the newest one
under "1".
Assisted-by: Claude Code:claude-opus-5-5
---
services/storage-users/README.md | 4 +-
services/storage-users/pkg/config/config.go | 2 +-
.../cliCommands/cleanupFileVersions.feature | 38 ++++++++++++-------
3 files changed, 28 insertions(+), 16 deletions(-)
diff --git a/services/storage-users/README.md b/services/storage-users/README.md
index 3b20097953..fb583dad21 100644
--- a/services/storage-users/README.md
+++ b/services/storage-users/README.md
@@ -377,7 +377,7 @@ Durations in days or weeks can use an uppercase unit, `D` or `W`, to count from
A restore keeps the revision of the content it replaced as long as the file has the restored content: the strategy doesn't apply to that one revision, not even an age limit like `30d`, until the file is changed again, by an upload, another restore or, with `posix`, a change on disk.
-Note that the age of a revision is the time its content was written, i.e. the modification time the file had before it was changed, which is also the date the version list shows for it. It is not the time the file was changed, which turned that content into a revision. A document that was unchanged for two months gets a revision that is two months old when it is changed, and e.g. `30d` deletes that revision right away. Combine a duration with a number of revisions, e.g. `5, 30d`, to always keep the newest ones.
+Note that the age of a revision is the time it was created, i.e. when the file was changed and its previous content became the revision, by the clock of the server. The revisions are also ordered by it, e.g. for a number of revisions to keep. It is not the modification time of the content of the revision, which is the date the version list shows for it, as clients can set that to any time. A document that was unchanged for two months gets a revision that is a few seconds old when it is changed, and e.g. `30d` keeps that revision for 30 days. `auto` keeps the oldest revision of each time slot, which holds the content the file had when the slot began. Revisions created before OpenCloud recorded the time of their creation get an estimate: the time they were replaced, as far as it can be told from the dates of the newer revisions and of the file.
#### Selecting the Files
@@ -415,7 +415,7 @@ By default, the command prints a line for every file whose revisions it deleted,
1520 files in 3 spaces: deleted 3 revisions (4.2 MiB) of 1 file, 1 skipped, 0 failed
```
-With `--verbose`, every revision is listed with the decision (`deleted`, `kept` or `protected`), its time, its size and the reason:
+With `--verbose`, every revision is listed with the decision (`deleted`, `kept` or `protected`), its time, its size and the reason. The time is when the revision was created, see above, which can differ from the date the version list shows for it:
```plaintext
25b69780-5f39-43be-a7ac-a9b9e9fe4230 /dir1/file1 (node 43ca5408-c77b-4d9a-8a3b-d4470b1253b8): would delete 1 of 3 revisions (1.2 KiB)
diff --git a/services/storage-users/pkg/config/config.go b/services/storage-users/pkg/config/config.go
index 2e5012545e..bfeefbaa09 100644
--- a/services/storage-users/pkg/config/config.go
+++ b/services/storage-users/pkg/config/config.go
@@ -229,7 +229,7 @@ type Events struct {
// RevisionsCleanup configures the deletion of old revisions, for the 'decomposed', 'decomposeds3' and 'posix' storage drivers
type RevisionsCleanup struct {
- Strategy string `yaml:"strategy" env:"STORAGE_USERS_REVISIONS_CLEANUP_STRATEGY" desc:"Which old revisions (versions) of a file to delete whenever the file gets a new revision. 'disabled' keeps all revisions. A strategy is a comma-separated list of up to three parts: a number of revisions, which counts from the newest one (e.g. '10'), a duration with one of the units 'w', 'd', 'h', 'm' or 's' (e.g. '30d'; with the uppercase units 'D' and 'W', days and weeks count from midnight, e.g. '1D'), and 'auto', which thins out revisions the older they get. 'X' deletes everything beyond X, e.g. '10', '30d', or '0' to delete all revisions. 'X, auto' keeps everything within X and thins out the older revisions, e.g. '14d, auto'. 'auto, X' deletes everything beyond X and thins out the rest, e.g. 'auto, 90d'. 'X1, X2' keeps everything within X1 and deletes everything beyond X2, e.g. '5, 30d'. 'X1, auto, X2' also thins out in between, e.g. '7d, auto, 90d'. The age of a revision is the time its content was written, i.e. the modification time the file had before it was changed, not the time of that change. Only files that get a new revision are cleaned up, including revisions created from changes on disk with posix. An invalid value makes the storage driver fail at startup." introductionVersion:"%%NEXT%%"`
+ Strategy string `yaml:"strategy" env:"STORAGE_USERS_REVISIONS_CLEANUP_STRATEGY" desc:"Which old revisions (versions) of a file to delete whenever the file gets a new revision. 'disabled' keeps all revisions. A strategy is a comma-separated list of up to three parts: a number of revisions, which counts from the newest one (e.g. '10'), a duration with one of the units 'w', 'd', 'h', 'm' or 's' (e.g. '30d'; with the uppercase units 'D' and 'W', days and weeks count from midnight, e.g. '1D'), and 'auto', which thins out revisions the older they get. 'X' deletes everything beyond X, e.g. '10', '30d', or '0' to delete all revisions. 'X, auto' keeps everything within X and thins out the older revisions, e.g. '14d, auto'. 'auto, X' deletes everything beyond X and thins out the rest, e.g. 'auto, 90d'. 'X1, X2' keeps everything within X1 and deletes everything beyond X2, e.g. '5, 30d'. 'X1, auto, X2' also thins out in between, e.g. '7d, auto, 90d'. The age of a revision is the time it was created, i.e. when the file was changed and its previous content became the revision, not the modification time of that content, which the version list shows. Only files that get a new revision are cleaned up, including revisions created from changes on disk with posix. An invalid value makes the storage driver fail at startup." introductionVersion:"%%NEXT%%"`
Async bool `yaml:"async" env:"STORAGE_USERS_REVISIONS_CLEANUP_ASYNC" desc:"Run the revision cleanup in background workers, so that it does not slow down the upload, restore or change that created the new revision. When set to false, the cleanup runs right away." introductionVersion:"%%NEXT%%"`
AsyncWorkers int `yaml:"async_workers" env:"STORAGE_USERS_REVISIONS_CLEANUP_ASYNC_WORKERS" desc:"Number of background workers for the revision cleanup. A value of 0 determines it automatically: half the available CPUs, respecting container CPU limits, but at least 2." introductionVersion:"%%NEXT%%"`
AsyncQueueSize int `yaml:"async_queue_size" env:"STORAGE_USERS_REVISIONS_CLEANUP_ASYNC_QUEUE_SIZE" desc:"Number of files that can wait for a background revision cleanup. A value of 0 determines it automatically: 64 per worker." introductionVersion:"%%NEXT%%"`
diff --git a/tests/acceptance/features/cliCommands/cleanupFileVersions.feature b/tests/acceptance/features/cliCommands/cleanupFileVersions.feature
index e6802fdf6b..6c8a60da33 100644
--- a/tests/acceptance/features/cliCommands/cleanupFileVersions.feature
+++ b/tests/acceptance/features/cliCommands/cleanupFileVersions.feature
@@ -197,26 +197,38 @@ Feature: clean up old file versions according to a cleanup strategy
Then the number of versions of file "textfile.txt" for user "Alice" should eventually be "2"
And the content of file "textfile.txt" for user "Alice" should be "version 5"
- # The age of a version is the time its content was written, i.e. the modification time the
- # file had before it was changed, not the time of that change: "version 1" is 60 days old
- # as soon as it becomes a version.
- Scenario Outline: the configured strategy measures the age of a version by the time its content was written
+ # The age of a version is the time it was created, i.e. when its content was replaced, not
+ # the modification time of its content, which the client chooses: "version 1" and "version 2"
+ # are only seconds old as versions, although their content is dated 60 and 50 days ago.
+ Scenario: the configured strategy measures the age of a version by the time it was created
Given the following configs have been set:
- | config | value |
- | STORAGE_USERS_REVISIONS_CLEANUP_STRATEGY | |
- | STORAGE_USERS_REVISIONS_CLEANUP_ASYNC | false |
+ | config | value |
+ | STORAGE_USERS_REVISIONS_CLEANUP_STRATEGY | 30d |
+ | STORAGE_USERS_REVISIONS_CLEANUP_ASYNC | false |
And user "Alice" has uploaded a file with content "version 1" and mtime "-60 days" to "textfile.txt"
And user "Alice" has uploaded a file with content "version 2" and mtime "-50 days" to "textfile.txt"
And user "Alice" has uploaded file with content "version 3" to "textfile.txt"
When user "Alice" gets the number of versions of file "textfile.txt"
Then the HTTP status code should be "207"
- And the number of versions should be ""
+ And the number of versions should be "2"
+ And the content of file "textfile.txt" for user "Alice" should be "version 3"
+
+ # The versions are ordered by the time they were created as well: a version whose content
+ # is dated years ahead doesn't count as the newest one, so "1" keeps the version created
+ # last, "version 2", and not "version 1".
+ Scenario: a version with content dated in the future doesn't take the place of the newest one
+ Given the following configs have been set:
+ | config | value |
+ | STORAGE_USERS_REVISIONS_CLEANUP_STRATEGY | 1 |
+ | STORAGE_USERS_REVISIONS_CLEANUP_ASYNC | false |
+ And user "Alice" has uploaded a file with content "version 1" and mtime "+10 years" to "textfile.txt"
+ And user "Alice" has uploaded file with content "version 2" to "textfile.txt"
+ And user "Alice" has uploaded file with content "version 3" to "textfile.txt"
+ When user "Alice" gets the number of versions of file "textfile.txt"
+ Then the HTTP status code should be "207"
+ And the number of versions should be "1"
+ And the content of version index "1" of file "textfile.txt" for user "Alice" should be "version 2"
And the content of file "textfile.txt" for user "Alice" should be "version 3"
- Examples:
- | strategy | versions |
- | 30d | 0 |
- | 1,30d | 1 |
- | 90d | 2 |
# A restore makes the content from before the restore a version, which the cleanup keeps
# whatever the strategy, so that the restore can be undone. The restored version itself
From 9095f76f5230333099da7baccba7d5a7b20509fd Mon Sep 17 00:00:00 2001
From: Sara Ahmadi
Date: Tue, 24 Nov 2026 13:14:50 +0100
Subject: [PATCH 9/9] feat(audit): log the space name when a space is deleted
Assisted-by: Claude Code:claude-opus-5-5
---
services/audit/pkg/service/service_test.go | 34 +++++++++++++++++++++-
services/audit/pkg/types/conversion.go | 2 +-
services/audit/pkg/types/messages.go | 4 +--
3 files changed, 36 insertions(+), 4 deletions(-)
diff --git a/services/audit/pkg/service/service_test.go b/services/audit/pkg/service/service_test.go
index 81a17695b4..fc119991ee 100644
--- a/services/audit/pkg/service/service_test.go
+++ b/services/audit/pkg/service/service_test.go
@@ -547,6 +547,7 @@ var testCases = []struct {
Event: events.SpaceDeleted{
Executant: userID("uid-123"),
ID: &provider.StorageSpaceId{OpaqueId: "storage-1$space-123"},
+ SpaceName: "test-space",
},
},
CheckAuditEvent: func(t *testing.T, b []byte) {
@@ -554,10 +555,41 @@ var testCases = []struct {
require.NoError(t, json.Unmarshal(b, &ev))
// AuditEvent fields
- checkBaseAuditEvent(t, ev.AuditEvent, "", "0001-01-01T00:00:00Z", "user 'uid-123' deleted the space 'space-123' (storage: 'storage-1')", "space_deleted")
+ checkBaseAuditEvent(t, ev.AuditEvent, "", "0001-01-01T00:00:00Z", "user 'uid-123' deleted the space 'space-123' with name 'test-space' (storage: 'storage-1')", "space_deleted")
// AuditEventSpaces fields
checkSpacesAuditEvent(t, ev.AuditEventSpaces, "storage-1$space-123")
},
+ }, {
+ Alias: "Space deleted - unicode name",
+ SystemEvent: events.Event{
+ Event: events.SpaceDeleted{
+ Executant: userID("uid-123"),
+ ID: &provider.StorageSpaceId{OpaqueId: "storage-1$space-123"},
+ SpaceName: "Prüfung 📁 空间",
+ },
+ },
+ CheckAuditEvent: func(t *testing.T, b []byte) {
+ ev := types.AuditEventSpaceDeleted{}
+ require.NoError(t, json.Unmarshal(b, &ev))
+
+ checkBaseAuditEvent(t, ev.AuditEvent, "", "0001-01-01T00:00:00Z", "user 'uid-123' deleted the space 'space-123' with name 'Prüfung 📁 空间' (storage: 'storage-1')", "space_deleted")
+ checkSpacesAuditEvent(t, ev.AuditEventSpaces, "storage-1$space-123")
+ },
+ }, {
+ Alias: "Space deleted - empty name",
+ SystemEvent: events.Event{
+ Event: events.SpaceDeleted{
+ Executant: userID("uid-123"),
+ ID: &provider.StorageSpaceId{OpaqueId: "storage-1$space-123"},
+ },
+ },
+ CheckAuditEvent: func(t *testing.T, b []byte) {
+ ev := types.AuditEventSpaceDeleted{}
+ require.NoError(t, json.Unmarshal(b, &ev))
+
+ checkBaseAuditEvent(t, ev.AuditEvent, "", "0001-01-01T00:00:00Z", "user 'uid-123' deleted the space 'space-123' with name '' (storage: 'storage-1')", "space_deleted")
+ checkSpacesAuditEvent(t, ev.AuditEventSpaces, "storage-1$space-123")
+ },
},
{
Alias: "ScienceMesh - InviteTokenGenerated",
diff --git a/services/audit/pkg/types/conversion.go b/services/audit/pkg/types/conversion.go
index 94bbd3c1e3..8be38a9458 100644
--- a/services/audit/pkg/types/conversion.go
+++ b/services/audit/pkg/types/conversion.go
@@ -378,7 +378,7 @@ func SpaceEnabled(ev events.SpaceEnabled) AuditEventSpaceEnabled {
// SpaceDeleted converts a SpaceDeleted event to an AuditEventSpaceDeleted
func SpaceDeleted(ev events.SpaceDeleted) AuditEventSpaceDeleted {
sid := ev.ID.GetOpaqueId()
- base := BasicAuditEvent("", formatTime(utils.TimeToTS(ev.Timestamp)), MessageSpaceDeleted(ev.Executant.GetOpaqueId(), sid), ActionSpaceDeleted)
+ base := BasicAuditEvent("", formatTime(utils.TimeToTS(ev.Timestamp)), MessageSpaceDeleted(ev.Executant.GetOpaqueId(), sid, ev.SpaceName), ActionSpaceDeleted)
return AuditEventSpaceDeleted{
AuditEventSpaces: SpacesAuditEvent(base, sid),
}
diff --git a/services/audit/pkg/types/messages.go b/services/audit/pkg/types/messages.go
index 38dbfd259f..64698bb7d8 100644
--- a/services/audit/pkg/types/messages.go
+++ b/services/audit/pkg/types/messages.go
@@ -166,9 +166,9 @@ func MessageSpaceEnabled(executant, spaceID string) string {
}
// MessageSpaceDeleted returns the human-readable string that describes the action
-func MessageSpaceDeleted(executant, spaceID string) string {
+func MessageSpaceDeleted(executant, spaceID, name string) string {
storagID, spaceID := storagespace.SplitStorageID(spaceID)
- return fmt.Sprintf("user '%s' deleted the space '%s' (storage: '%s')", executant, spaceID, storagID)
+ return fmt.Sprintf("user '%s' deleted the space '%s' with name '%s' (storage: '%s')", executant, spaceID, name, storagID)
}
// MessageSpaceShared returns the human-readable string that describes the action