Compare commits

..
Author SHA1 Message Date
Chris Lu 25cfeb3a2a feat(s3api): full-chunk gzip pass-through skips volume-side decompress
Building on the io.Pipe streaming chunk copy: when a copy operation
covers an entire source chunk (the common case for Harbor's
part-size = chunk-size assemble pattern), ask the source volume for
compressed bytes via Accept-Encoding: gzip and forward them to the
destination as-is.

This trades a Range fetch (where the volume decompresses the chunk
internally to satisfy the byte range) for a full-chunk fetch that
returns whatever wire bytes the chunk is stored as. For gzipped
chunks the source volume avoids the decompression entirely; we never
allocate a chunk-sized decompress buffer.

Implementation: build the source GET directly instead of going
through ReadUrlAsStream, because that helper auto-decompresses gzip
responses (which would defeat the point). Trust the response's
Content-Encoding header over caller hints — for partial ranges the
volume always returns raw bytes regardless of how the chunk is
stored, so labeling those as gzip would corrupt subsequent reads.

End-to-end repro impact (512 MiB src, 6 parallel UploadPartCopy):
  + #9420/#9421/#9422       : 2236 MiB
  + io.Pipe streaming       : 1521 MiB
  + this commit             : 1149 MiB  (round 2 RSS, perfectly flat)

Round 3 now completes (was hitting volume-full before, since
chunks took up uncompressed space on disk; we now store the gzipped
chunks the volume gives us, which fit in the test's 8 GiB volume
budget).

Heap inuse_space (after force GC):
  before all: ~1.5 GiB
  this PR:    266 MiB

Volume-side bytes.Buffer.ReadFrom inuse:
  before:     611 MiB
  streaming:  571 MiB
  this PR:    297 MiB (now in destination-volume parseUpload's
                       size-hint decompression — separate
                       optimization opportunity for a hint header)
2026-05-10 13:54:16 -07:00
Chris Lu 843e4b7cdb review: cancel source GET when destination POST fails
Address coderabbit review (line 165 / second pass on PR 9424): when
the POST leg fails or returns an error status, closing pipeReader
only fails the producer's *writes*. ReadUrlAsStream's own read loop
runs under the parent ctx, so it keeps draining the source body in
the background until EOF — wasting source-volume bandwidth and CPU
on a copy that's already failed.

Wrap streamCopyChunkRange in a child context cancelled on return.
ReadUrlAsStream checks ctx.Done() per 256 KiB tick, so the in-flight
read aborts on the next iteration once the function returns. The POST
also moves to streamCtx so the in-flight request can be cancelled the
same way if the producer fails first.

Defer-cancel runs after both legs return, so the success path still
sends EOF cleanly through pipeWriter.Close before cancellation.
2026-05-10 13:53:18 -07:00
Chris Lu f70f338e7f review: surface shouldRetry, add int32 guard, drop redundant drains
Address review on PR 9424:

* coderabbit (HIGH, line 122): ReadUrlAsStream can set shouldRetry=true
  with readErr=nil. Before this fix, that fell through to mw.Close()
  and the destination POST succeeded against a possibly-truncated
  multipart body. Mirror downloadChunkData's explicit check and
  surface shouldRetry as a producer error so the dst POST aborts.
* gemini (line 98): chunk size is int64 but ReadUrlAsStream takes int.
  Reject sizes above MaxInt32 up front so the int(size) cast can't
  truncate negative on 32-bit platforms — same guard downloadChunkData
  uses.
* gemini (line 151): util_http.CloseResponse already drains the body
  (io.Copy(io.Discard, ...) inside the helper) before closing, so the
  manual io.Copy drains we added are redundant. Drop them.
2026-05-10 13:30:22 -07:00
Chris Lu 6f2bf40d5a feat(s3api): stream chunk copy via io.Pipe to cut peak working set
Final piece for #6541. The buffered chunk-copy path holds two
chunk-sized buffers per copy in flight (download buffer + multipart-
encoded upload buffer). Under concurrent UploadPartCopy that put a
floor on RSS at concurrency × 2 × chunk_size — about 768 MiB for the
6-way / 64 MiB Harbor-style assemble repro, even after the previous
pool/retention fixes.

Replace the buffered path with an io.Pipe between the source GET and
the destination POST: ReadUrlAsStream pumps data into the pipe via a
multipart.Writer, the http.Client reads from the pipe end and POSTs
the body. In-flight per copy is now ~32 KiB (pipe hand-off + http
buffers), regardless of chunk size.

The streaming path is gated by canStreamCopyChunk: only used when no
in-transit transformation is needed (no per-chunk CipherKey, no SSE).
SSE-C / SSE-KMS / SSE-S3 paths still go through the buffered path,
which already handles re-encryption correctly.

Benchmarks (Apple M4, httptest source/dest, B/op = bytes per copy):

  Buffered  1 MiB:   6.0 MB B/op,  443 MB/s
  Streamed  1 MiB:   374 KB B/op,  727 MB/s
  Buffered  8 MiB:    56 MB B/op,  559 MB/s
  Streamed  8 MiB:   379 KB B/op, 1138 MB/s
  Buffered 64 MiB:   455 MB B/op,  718 MB/s
  Streamed 64 MiB:   304 KB B/op, 1387 MB/s

End-to-end repro (512 MiB src, 6 parallel UploadPartCopy):
  pre-#9420 RSS round 2: 3134 MiB
  + #9420/#9421/#9422  : 2236 MiB
  + this PR            : 1521 MiB
  heap inuse_space     :  350 MiB (was 1422 / 1187 MiB)
  HeapSys (MemStats)   : 1.74 GiB (was 2.49 GiB)
2026-05-10 12:40:49 -07:00
Chris Lu 26c257bf40 fix: cap pool retention so chunk-copy buffers don't hoard memory
Two pool-retention sites kept the runaway-RSS pattern in #6541 visible
even after #9420 and #9421:

* weed/util/buffer_pool: SyncPoolPutBuffer dropped a buffer back into
  sync.Pool regardless of how big it had grown. After a 64 MiB chunk
  upload through volume.PostHandler -> needle.ParseUpload, the pool
  hoarded a 64 MiB byte array per cached entry for the rest of the
  process's lifetime. Cap retention at 4 MiB; oversized buffers are
  dropped so GC can reclaim the backing array.

* weed/s3api/...copy.go: uploadChunkData left UploadOption.BytesBuffer
  unset, so operation.upload_content fell back to the package-global
  valyala/bytebufferpool. That pool also retains high-water buffers
  forever, and concurrent UploadPartCopy filled it with one chunk-sized
  buffer per concurrent upload. Provide a fresh per-call bytes.Buffer
  pre-sized to chunk + multipart framing; it's GC'd as soon as the
  upload returns.

Tests:
- weed/util/buffer_pool/sync_pool_test.go: pin the cap (oversized
  buffers don't round-trip), the inverse (right-sized buffers do), and
  nil-safety.
- weed/s3api/...copy_chunk_upload_test.go: extract newChunkUploadOption
  and pin that BytesBuffer is always non-nil and pre-sized, and that
  each call gets a distinct buffer.
2026-05-10 11:58:38 -07:00
Chris Lu ca12934834 docs(s3/lifecycle): reflect shipped reader, obsolete Phase 6 (#9419)
* test(s3/lifecycle/engine): pin delay-group dedup across buckets

Compile a 100-bucket × 5-rule snapshot where the five Days values
include duplicates (1, 1, 7, 7, 30) and assert:

- snap.actions has 500 entries — every (bucket, rule) compiles to its
  own ActionKey, no collapse.
- snap.originalDelayGroups has exactly 3 entries — the routing index
  is keyed by Delay, so same-day rules across all buckets share a
  group. This is the property that lets the dispatcher index by
  delay group rather than per-rule.
- Per-group key count = (rules with that day) × buckets, so every
  action is reachable from its group entry.

* docs(s3/lifecycle): reflect shipped reader, obsolete Phase 6

The reader didn't end up building per-filer-shard cursors,
RetainedLogRangePerShard / EarliestRetainedPositionPerShard probes,
tail_drained_streams GC, or CollectLogFileRefs heap-merge. The
filer's SubscribeMetadata already aggregates persisted + in-memory
logs across peer filers, so a single global cursor on a single
subscription is sufficient.

Mark the per-shard architecture and lost-log GC pseudocode as
implementation-note + obsoleted, rewrite Phase 6 to call out what
was descoped and why, point readers at the narrow ResumeFromDiskError
auto-degrade follow-up that is the only residual gap, and update
Layer 4 to note no multi-filer test harness is needed.

* docs(s3/lifecycle): drop stale per-shard cursor wording in Phase 3

The "one sweep per delay group" bullet still described
last_processed_original / last_processed_predicate as per-shard maps,
contradicting the implementation note added a few lines above. The
shipped reader stores one global (ts_ns, offset) position per delay
group; rewrite the bullet to match.
2026-05-10 10:40:33 -07:00
Chris Lu 82648cca53 test(s3/lifecycle/engine): pin delay-group dedup across buckets (#9418)
Compile a 100-bucket × 5-rule snapshot where the five Days values
include duplicates (1, 1, 7, 7, 30) and assert:

- snap.actions has 500 entries — every (bucket, rule) compiles to its
  own ActionKey, no collapse.
- snap.originalDelayGroups has exactly 3 entries — the routing index
  is keyed by Delay, so same-day rules across all buckets share a
  group. This is the property that lets the dispatcher index by
  delay group rather than per-rule.
- Per-group key count = (rules with that day) × buckets, so every
  action is reachable from its group entry.
2026-05-10 10:36:54 -07:00
Chris Lu 1b1d4aa814 refactor(s3/lifecycle): extract entryUsesMetadataOnlyDelete predicate (#9417)
* test(s3/lifecycle): integration coverage for versioning + filters

First integration-test bundle building on the existing single-test
backdating harness. Each scenario follows the same shape: create
bucket, set lifecycle, PUT object, backdate mtime via filer
UpdateEntry, run the shell command for one shard sweep, assert
S3-side state.

Five new tests:

- TestLifecycleVersionedBucketCreatesDeleteMarker: Expiration on a
  versioned bucket must produce a delete marker (latest after worker
  runs is a marker) AND keep the original version directly addressable
  by versionId. ListObjectVersions confirms IsLatest=true on the
  marker.

- TestLifecycleNoncurrentVersionExpiration: NoncurrentVersionExpiration
  fires only on demoted versions. PUT v1, PUT v2 (so v1 → noncurrent),
  backdate v1, run worker. v1 must be gone, v2 still current.

- TestLifecycleExpiredDeleteMarkerCleanup: combined rule (noncurrent +
  expired-delete-marker) cleans up a sole-survivor marker. PUT v1,
  DELETE (creates marker), backdate both, run worker. Every version
  AND marker must be gone for the key.

- TestLifecycleDisabledRuleSkipsObject: rule with Status=Disabled
  must not produce dispatches even on a backdated match. Negative
  test for the engine's enabled-status gate.

- TestLifecycleTagFilter: rule with And{Prefix, Tag} only matches
  objects carrying the tag. Two backdated objects (one tagged, one
  not) — only the tagged one is removed.

Helpers extracted to keep each test focused: putVersioningEnabled,
putNoncurrentExpirationLifecycle, putExpiredDeleteMarkerLifecycle,
backdateVersionedMtime (ages a specific .versions/v_<id> entry),
runLifecycleShard (one-shot shell invocation with FATAL guard).

* test(s3/lifecycle): tighten noncurrent expiration diagnostics

Local run showed TestLifecycleNoncurrentVersionExpiration failing
with a bare 404 on HEAD(latest), not enough to tell whether v2 was
deleted, the bare-key pointer was removed, or a delete marker was
synthesized. Strengthen the test to:

- HEAD by versionId=v2 first, so we pin "v2 file still on disk"
  separately from "the latest pointer resolves to v2"
- on HEAD(latest) failure, log ListObjectVersions output (versions +
  markers, with IsLatest) so the next failure shows which side the
  bug is on rather than just NotFound

* test(s3/lifecycle): integration coverage for AbortIncompleteMultipartUpload

Exercises the lifecycleAbortMPU handler path that the prefix-based
expiration tests can't reach — routing keys off of .uploads/<id>/
directory events, not regular object events, and the dispatcher uses
a different RPC path (rm on the .uploads/<id>/ folder).

Setup: AbortIncompleteMultipartUpload rule with DaysAfterInitiation=1,
CreateMultipartUpload, UploadPart (so the directory carries the
right shape), backdate the .uploads/<uploadID>/ directory entry 30
days, run the worker. The upload must drop out of
ListMultipartUploads.

Helpers added: putAbortMPULifecycle, backdateUploadDir.

* test(s3/lifecycle): integration coverage for NewerNoncurrentVersions

NewerNoncurrentVersions=N keeps the N most recent noncurrent versions
and expires the rest. Distinct from per-version NoncurrentDays —
depends on per-version rank, not just per-version age — and routes
through routePointerTransition's "needs full expansion" path.

Setup: PUT v1, v2, v3, v4 on a versioned bucket (v4 current; v1-v3
noncurrent), backdate v1+v2+v3 so all satisfy the NoncurrentDays>=1
floor, run the worker. Expect v1+v2 expired (older noncurrent),
v3 (newest noncurrent within keep=1) and v4 (current) preserved.

Helper added: putNewerNoncurrentLifecycle.

* test(s3/lifecycle): integration coverage for suspended-versioning Expiration

Suspended versioning takes a distinct code path in lifecycleDispatch:
the VersioningSuspended branch first deletes the null version (via
deleteSpecificObjectVersion(versionId="null")) and then writes a
fresh delete marker on top. Other branches (Enabled → only writes a
marker; Off → straight rm) miss this two-step.

Setup: enable versioning, PUT v1 (real versionId), suspend
versioning, PUT again (creates the null version, demotes v1 to
noncurrent), set the Expiration rule, backdate the null at the
bare path. Expect: latest is now a fresh delete marker, the
"null" version is gone from ListObjectVersions, and v1 (noncurrent
under Enabled) still addressable directly — suspended Expiration
must only touch the null, not other versions.

Helper added: putVersioningSuspended.

* test(s3/lifecycle): integration coverage for multi-bucket sweep

A single shell-driven shard sweep must process every bucket carrying
lifecycle config, not just the first one alphabetically. Pinned
because the scheduler iterates the buckets directory and a regression
that returns early after the first match would silently disable
lifecycle for every later bucket.

Two buckets, each with their own prefix-expiration rule and a
backdated object. Both must be expired after the same sweep.

* test(s3/lifecycle): integration coverage for ObjectSizeGreaterThan filter

ObjectSizeGreaterThan is a strict > gate (filterAllows uses
ev.Size <= rule.FilterSizeGreaterThan to reject). Pinned at the
boundary: an object whose size equals the threshold must remain;
only an object strictly larger expires. Catches a > vs >= flip.

Two backdated objects on the same prefix, sizes 100 and 150 with
threshold=100 — boundary survives, larger expires.

* test(s3/lifecycle): scrub bucket lifecycle config + versions on cleanup

Tests share one weed mini server. Two pollution modes were producing
order-dependent failures:

- A later test's shard sweep would still load the prior test's
  lifecycle config (the worker reads every bucket's XML from filer
  state, and DeleteBucket alone doesn't drop lifecycle config
  cleanly on this codebase).
- Versioned-bucket tests left versions + delete markers behind that
  ListObjectsV2 can't see, so the existing best-effort empty-then-
  delete didn't actually empty those buckets.
- The AbortMPU test intentionally leaves an in-flight upload; without
  an explicit AbortMultipartUpload the bucket DELETE hits NotEmpty.

Cleanup now runs DeleteBucketLifecycle, ListObjectVersions →
DeleteObject(versionId), ListObjectsV2 → DeleteObject (catches what
ListObjectVersions missed), ListMultipartUploads → AbortMultipartUpload,
then DeleteBucket. Best-effort throughout so a half-torn-down bucket
doesn't fail the cleanup chain.

* test(s3/lifecycle): backdate both versions for NoncurrentDays clock

Per codex review: NoncurrentDays is clocked from the SUCCESSOR
version's mtime (when the displaced version became noncurrent), not
from the displaced version's own mtime. Backdating only v1 left the
clock (v2's mtime) at "now" and the rule never fired — the test was
wrong, not the production path.

Backdate v1=31d and v2=30d so v1 sits past the 1-day threshold
relative to v2, the noncurrent rule fires, and v2 stays current.

* test(s3/lifecycle): assert specific NotFound on multi-bucket deletion

Per codex review: TestLifecycleMultipleBucketsInOneSweep treated any
HeadObject error as "deleted", which lets a transport failure or
dead endpoint mask a real bug. Recognize NoSuchKey/NotFound/HTTP-404
specifically via a small isS3NotFound helper so the assertion
actually proves deletion happened, not just that the call broke.

* test(s3/lifecycle): gofmt size-filter test

* test(s3/lifecycle): integration coverage for Object Lock skip

Object Lock retention must override the lifecycle rule. The handler's
enforceObjectLockProtections check (s3api_internal_lifecycle.go:47)
returns an error when retention is active; the dispatcher then
classifies the outcome as SKIPPED_OBJECT_LOCK and the object stays.
No existing integration test reaches that outcome.

Setup: bucket created with ObjectLockEnabledForBucket=true, expiration
rule on prefix "lock/", two backdated objects under the same prefix —
one with GOVERNANCE retention until 1h from now, one without. After
the worker runs, the unlocked object expires (positive control); the
locked one survives.

Custom cleanup uses BypassGovernanceRetention so the test can drop
the locked version when the test finishes — otherwise the retention
window keeps the bucket from being deleted.

* test(s3/lifecycle): integration coverage for config update between sweeps

An operator changes the lifecycle rule between two shell-driven
sweeps. The second sweep must respect the NEW rule, not a cached
copy of the old one. Each runLifecycleShard invocation spawns a
fresh weed shell subprocess, so cached engine state from a previous
sweep doesn't persist — but a regression that caches rules across
PutBucketLifecycleConfiguration calls within the S3 server itself
would still surface here.

Sweep 1: rule prefix="first/", PUT + backdate firstKey, run worker
→ firstKey expires.

Update rule to prefix="second/", PUT + backdate secondKey AND a
new key under the OLD prefix ("first/post-update.txt"). Sweep 2
must expire only the second-prefix object; the post-update old-
prefix one must survive — config replacement, not merge.

* test(s3/lifecycle): integration coverage for ExpirationDate (past)

Rules with Expiration{Date: <past>} route through ScanAtDate in the
engine (decideMode's ActionKindExpirationDate case) — a separate
compile + dispatch branch from the EventDriven delay-group path the
Days-based tests exercise.

Past date + in-prefix object → must expire. Out-of-prefix object →
must remain. Object also backdated as defense-in-depth so the
assertion doesn't depend on whether the dispatcher consults
MinTriggerAge for date kinds.

* test(s3/lifecycle): integration coverage for bootstrap walk on existing objects

Production scenario: operator enables lifecycle on a bucket that
already holds objects from before the policy. The worker must
discover them via the bootstrap walk (BucketBootstrapper) — there
were no meta-log events to observe because the objects predate the
rule. Without the bootstrap path, only NEW writes would ever match.

Setup: PUT 5 objects (no lifecycle config yet) + 1 out-of-prefix
survivor, backdate all, THEN set the Expiration rule, run the
worker. Every in-prefix pre-existing object must be expired; the
out-of-prefix one must remain.

* test(s3/lifecycle): integration coverage for DeleteBucketLifecycle stops dispatching

Operator UX: after DeleteBucketLifecycle, the worker must observe the
removal on the next sweep and stop expiring objects under the now-gone
rule. A regression that caches old configs across
PutBucketLifecycleConfiguration → DeleteBucketLifecycle would keep
silently dropping objects.

Setup: positive control (rule active, backdated obj expires) →
DeleteBucketLifecycle → PUT + backdate a fresh object → second
sweep. The fresh object must remain.

* test(s3/lifecycle): integration coverage for empty bucket sweep no-op

A bucket carrying lifecycle config but no objects must produce a
successful sweep — no hangs, no errors, no dispatches. Pinned
because the bootstrap walker iterates bucket directories, and an
empty directory is a corner of that traversal that's easy to break
(slice-bounds bug on the first listing returning zero entries).

Asserts: worker logs "loaded lifecycle for" and "shards 0-15
complete", no FATAL output, bucket still exists after the sweep.

* test(s3/lifecycle): fix Object Lock backdate path + skip unwired ScanAtDate

ObjectLock: enabling Object Lock on a bucket implicitly enables
versioning, so PUT objects land at .versions/v_<id>, not at the bare
key. The test was calling backdateMtime (bare path) and failing in
the helper with "filer: no entry is found". Switch to
backdateVersionedMtime with the versionId returned by PutObject.

ExpirationDate: ScanAtDate dispatch path isn't wired to the run-shard
shell command yet — the bootstrap walker explicitly skips actions in
ModeScanAtDate (walker.go:141 says "SCAN_AT_DATE runs its own date-
triggered bootstrap" but no such bootstrap exists in the scheduler or
shell). Skip with a t.Skip + explanation so the test activates the
moment the date-triggered path lands.

* fix(s3/lifecycle): wire ExpirationDate dispatch through bootstrap walker

The walker explicitly skipped ModeScanAtDate actions on the comment
"SCAN_AT_DATE runs its own date-triggered bootstrap" — but no such
bootstrap exists in the scheduler or shell layer. The result: rules
with Expiration{Date: ...} compiled correctly, populated the
snapshot's dateActions map, and were never dispatched.
ExpirationDate is silently a no-op in production.

EvaluateAction already handles ActionKindExpirationDate correctly
(rejects when now.Before(rule.ExpirationDate), otherwise emits
ActionDeleteObject). The walker just needed to fall through instead
of skipping. Pre-date walks become no-ops via EvaluateAction's date
check; post-date walks expire eligible objects.

Un-skip TestLifecycleExpirationDateInThePast — it now exercises the
fixed path end-to-end.

* test(s3/lifecycle): integration coverage for multiple rules per bucket

A single bucket carries two independent Expiration rules with disjoint
prefix filters and different Days thresholds. Each rule must fire
only on its prefix; objects outside both prefixes must survive.

Pinned because Compile builds one CompiledAction per rule per kind
all sharing the same bucket index — a bug that lets one rule's
prefix or threshold leak into another (e.g. last-write-wins on a
shared map) would silently expire wrong objects.

Setup: rule A with prefix=logs/ Days=1, rule B with prefix=tmp/
Days=7. Three backdated objects: logs/access.log, tmp/scratch.bin,
data/keep.bin. After the worker runs, logs/ + tmp/ are gone;
data/ — outside both rule prefixes — survives.

* fix(s3/lifecycle): mark ScanAtDate actions active in Compile

Two layers were silently filtering ScanAtDate actions out of routing:
the walker's mode skip (fixed in e785f59d6) and Compile only marking
ModeEventDriven actions active. MatchPath / MatchOriginalWrite both
require IsActive() to emit a key, so a ScanAtDate action that's never
marked active never reaches a dispatch path even after the walker
falls through.

ScanAtDate's only dispatch path is the bootstrap walk's MatchPath
call — there's no bootstrap-completion rendezvous to wait on. Make
the active flag include ModeScanAtDate alongside the
EventDriven+BootstrapComplete combination.

ExpirationDate-based rules now actually fire end-to-end. The
TestLifecycleExpirationDateInThePast integration test exercises this.

* fix(s3/lifecycle): route date kinds via ComputeDueAt

ExpirationDate has MinTriggerAge=0, so router computed
dueTime = info.ModTime + 0 = info.ModTime. For a backdated entry
that mtime is BEFORE rule.ExpirationDate, so EvaluateAction's
now.Before(rule.ExpirationDate) check returned ActionNone and the
date rule never fired through the event-driven path.

ComputeDueAt already knows the per-kind shape — rule.ExpirationDate
for date kinds, ModTime+Days for the rest — so use it as the
single source of truth for dueTime in Route's main loop.

* test(s3/lifecycle): pin bootstrap walker date dispatch

The original TestWalk_DateActionsSkipped pinned the pre-e785f59d6
behavior that the regular walker skipped ExpirationDate. That
walker was rewired to fire date rules whose date has passed (the
SCAN_AT_DATE bootstrap was never wired); update the test to match.

Split into two: post-date entries dispatch, pre-date entries don't.

* test(s3/lifecycle): drop unused putExpiredDeleteMarkerLifecycle

The helper was never called — TestLifecycleExpiredDeleteMarkerCleanup
constructs a combined noncurrent + expired-marker rule inline, which
the helper doesn't cover. The blank-assignment workaround was just
hiding dead code; remove both.

* test(s3/lifecycle): tighten HeadObject termination check to typed not-found

Generic err != nil also passes on transport/auth/timeouts, letting
the test go green without proving the lifecycle action actually
fired. Switch the three Eventuallyf HeadObject predicates to
isS3NotFound, matching the pattern already in the multi-bucket and
expiration-date tests.

* test(s3/lifecycle): guard ListObjectVersions diagnostic against nil

When ListObjectVersions errors, listOut is nil and the diagnostic
log path panics on listOut.Versions before the real assertion fires.
Branch on (listErr != nil || listOut == nil) so the failure log is
robust whatever ListObjectVersions returned.

* refactor(s3/lifecycle): extract entryUsesMetadataOnlyDelete predicate

The metadata-only delete decision (entry.Attributes.TtlSec > 0) was
inlined in lifecycleDispatch with no direct test. Lift it into a
named predicate with the rationale comment moved onto the function
and pin the four edge cases: nil entry, nil attributes, TtlSec=0,
TtlSec>0, plus a defensive check that TtlSec<0 doesn't flip the
path on.
2026-05-10 09:39:05 -07:00
Chris Lu c7b01c72b2 test(s3/lifecycle): integration coverage for versioning + filters (#9415)
* test(s3/lifecycle): integration coverage for versioning + filters

First integration-test bundle building on the existing single-test
backdating harness. Each scenario follows the same shape: create
bucket, set lifecycle, PUT object, backdate mtime via filer
UpdateEntry, run the shell command for one shard sweep, assert
S3-side state.

Five new tests:

- TestLifecycleVersionedBucketCreatesDeleteMarker: Expiration on a
  versioned bucket must produce a delete marker (latest after worker
  runs is a marker) AND keep the original version directly addressable
  by versionId. ListObjectVersions confirms IsLatest=true on the
  marker.

- TestLifecycleNoncurrentVersionExpiration: NoncurrentVersionExpiration
  fires only on demoted versions. PUT v1, PUT v2 (so v1 → noncurrent),
  backdate v1, run worker. v1 must be gone, v2 still current.

- TestLifecycleExpiredDeleteMarkerCleanup: combined rule (noncurrent +
  expired-delete-marker) cleans up a sole-survivor marker. PUT v1,
  DELETE (creates marker), backdate both, run worker. Every version
  AND marker must be gone for the key.

- TestLifecycleDisabledRuleSkipsObject: rule with Status=Disabled
  must not produce dispatches even on a backdated match. Negative
  test for the engine's enabled-status gate.

- TestLifecycleTagFilter: rule with And{Prefix, Tag} only matches
  objects carrying the tag. Two backdated objects (one tagged, one
  not) — only the tagged one is removed.

Helpers extracted to keep each test focused: putVersioningEnabled,
putNoncurrentExpirationLifecycle, putExpiredDeleteMarkerLifecycle,
backdateVersionedMtime (ages a specific .versions/v_<id> entry),
runLifecycleShard (one-shot shell invocation with FATAL guard).

* test(s3/lifecycle): tighten noncurrent expiration diagnostics

Local run showed TestLifecycleNoncurrentVersionExpiration failing
with a bare 404 on HEAD(latest), not enough to tell whether v2 was
deleted, the bare-key pointer was removed, or a delete marker was
synthesized. Strengthen the test to:

- HEAD by versionId=v2 first, so we pin "v2 file still on disk"
  separately from "the latest pointer resolves to v2"
- on HEAD(latest) failure, log ListObjectVersions output (versions +
  markers, with IsLatest) so the next failure shows which side the
  bug is on rather than just NotFound

* test(s3/lifecycle): integration coverage for AbortIncompleteMultipartUpload

Exercises the lifecycleAbortMPU handler path that the prefix-based
expiration tests can't reach — routing keys off of .uploads/<id>/
directory events, not regular object events, and the dispatcher uses
a different RPC path (rm on the .uploads/<id>/ folder).

Setup: AbortIncompleteMultipartUpload rule with DaysAfterInitiation=1,
CreateMultipartUpload, UploadPart (so the directory carries the
right shape), backdate the .uploads/<uploadID>/ directory entry 30
days, run the worker. The upload must drop out of
ListMultipartUploads.

Helpers added: putAbortMPULifecycle, backdateUploadDir.

* test(s3/lifecycle): integration coverage for NewerNoncurrentVersions

NewerNoncurrentVersions=N keeps the N most recent noncurrent versions
and expires the rest. Distinct from per-version NoncurrentDays —
depends on per-version rank, not just per-version age — and routes
through routePointerTransition's "needs full expansion" path.

Setup: PUT v1, v2, v3, v4 on a versioned bucket (v4 current; v1-v3
noncurrent), backdate v1+v2+v3 so all satisfy the NoncurrentDays>=1
floor, run the worker. Expect v1+v2 expired (older noncurrent),
v3 (newest noncurrent within keep=1) and v4 (current) preserved.

Helper added: putNewerNoncurrentLifecycle.

* test(s3/lifecycle): integration coverage for suspended-versioning Expiration

Suspended versioning takes a distinct code path in lifecycleDispatch:
the VersioningSuspended branch first deletes the null version (via
deleteSpecificObjectVersion(versionId="null")) and then writes a
fresh delete marker on top. Other branches (Enabled → only writes a
marker; Off → straight rm) miss this two-step.

Setup: enable versioning, PUT v1 (real versionId), suspend
versioning, PUT again (creates the null version, demotes v1 to
noncurrent), set the Expiration rule, backdate the null at the
bare path. Expect: latest is now a fresh delete marker, the
"null" version is gone from ListObjectVersions, and v1 (noncurrent
under Enabled) still addressable directly — suspended Expiration
must only touch the null, not other versions.

Helper added: putVersioningSuspended.

* test(s3/lifecycle): integration coverage for multi-bucket sweep

A single shell-driven shard sweep must process every bucket carrying
lifecycle config, not just the first one alphabetically. Pinned
because the scheduler iterates the buckets directory and a regression
that returns early after the first match would silently disable
lifecycle for every later bucket.

Two buckets, each with their own prefix-expiration rule and a
backdated object. Both must be expired after the same sweep.

* test(s3/lifecycle): integration coverage for ObjectSizeGreaterThan filter

ObjectSizeGreaterThan is a strict > gate (filterAllows uses
ev.Size <= rule.FilterSizeGreaterThan to reject). Pinned at the
boundary: an object whose size equals the threshold must remain;
only an object strictly larger expires. Catches a > vs >= flip.

Two backdated objects on the same prefix, sizes 100 and 150 with
threshold=100 — boundary survives, larger expires.

* test(s3/lifecycle): scrub bucket lifecycle config + versions on cleanup

Tests share one weed mini server. Two pollution modes were producing
order-dependent failures:

- A later test's shard sweep would still load the prior test's
  lifecycle config (the worker reads every bucket's XML from filer
  state, and DeleteBucket alone doesn't drop lifecycle config
  cleanly on this codebase).
- Versioned-bucket tests left versions + delete markers behind that
  ListObjectsV2 can't see, so the existing best-effort empty-then-
  delete didn't actually empty those buckets.
- The AbortMPU test intentionally leaves an in-flight upload; without
  an explicit AbortMultipartUpload the bucket DELETE hits NotEmpty.

Cleanup now runs DeleteBucketLifecycle, ListObjectVersions →
DeleteObject(versionId), ListObjectsV2 → DeleteObject (catches what
ListObjectVersions missed), ListMultipartUploads → AbortMultipartUpload,
then DeleteBucket. Best-effort throughout so a half-torn-down bucket
doesn't fail the cleanup chain.

* test(s3/lifecycle): backdate both versions for NoncurrentDays clock

Per codex review: NoncurrentDays is clocked from the SUCCESSOR
version's mtime (when the displaced version became noncurrent), not
from the displaced version's own mtime. Backdating only v1 left the
clock (v2's mtime) at "now" and the rule never fired — the test was
wrong, not the production path.

Backdate v1=31d and v2=30d so v1 sits past the 1-day threshold
relative to v2, the noncurrent rule fires, and v2 stays current.

* test(s3/lifecycle): assert specific NotFound on multi-bucket deletion

Per codex review: TestLifecycleMultipleBucketsInOneSweep treated any
HeadObject error as "deleted", which lets a transport failure or
dead endpoint mask a real bug. Recognize NoSuchKey/NotFound/HTTP-404
specifically via a small isS3NotFound helper so the assertion
actually proves deletion happened, not just that the call broke.

* test(s3/lifecycle): gofmt size-filter test

* test(s3/lifecycle): integration coverage for Object Lock skip

Object Lock retention must override the lifecycle rule. The handler's
enforceObjectLockProtections check (s3api_internal_lifecycle.go:47)
returns an error when retention is active; the dispatcher then
classifies the outcome as SKIPPED_OBJECT_LOCK and the object stays.
No existing integration test reaches that outcome.

Setup: bucket created with ObjectLockEnabledForBucket=true, expiration
rule on prefix "lock/", two backdated objects under the same prefix —
one with GOVERNANCE retention until 1h from now, one without. After
the worker runs, the unlocked object expires (positive control); the
locked one survives.

Custom cleanup uses BypassGovernanceRetention so the test can drop
the locked version when the test finishes — otherwise the retention
window keeps the bucket from being deleted.

* test(s3/lifecycle): integration coverage for config update between sweeps

An operator changes the lifecycle rule between two shell-driven
sweeps. The second sweep must respect the NEW rule, not a cached
copy of the old one. Each runLifecycleShard invocation spawns a
fresh weed shell subprocess, so cached engine state from a previous
sweep doesn't persist — but a regression that caches rules across
PutBucketLifecycleConfiguration calls within the S3 server itself
would still surface here.

Sweep 1: rule prefix="first/", PUT + backdate firstKey, run worker
→ firstKey expires.

Update rule to prefix="second/", PUT + backdate secondKey AND a
new key under the OLD prefix ("first/post-update.txt"). Sweep 2
must expire only the second-prefix object; the post-update old-
prefix one must survive — config replacement, not merge.

* test(s3/lifecycle): integration coverage for ExpirationDate (past)

Rules with Expiration{Date: <past>} route through ScanAtDate in the
engine (decideMode's ActionKindExpirationDate case) — a separate
compile + dispatch branch from the EventDriven delay-group path the
Days-based tests exercise.

Past date + in-prefix object → must expire. Out-of-prefix object →
must remain. Object also backdated as defense-in-depth so the
assertion doesn't depend on whether the dispatcher consults
MinTriggerAge for date kinds.

* test(s3/lifecycle): integration coverage for bootstrap walk on existing objects

Production scenario: operator enables lifecycle on a bucket that
already holds objects from before the policy. The worker must
discover them via the bootstrap walk (BucketBootstrapper) — there
were no meta-log events to observe because the objects predate the
rule. Without the bootstrap path, only NEW writes would ever match.

Setup: PUT 5 objects (no lifecycle config yet) + 1 out-of-prefix
survivor, backdate all, THEN set the Expiration rule, run the
worker. Every in-prefix pre-existing object must be expired; the
out-of-prefix one must remain.

* test(s3/lifecycle): integration coverage for DeleteBucketLifecycle stops dispatching

Operator UX: after DeleteBucketLifecycle, the worker must observe the
removal on the next sweep and stop expiring objects under the now-gone
rule. A regression that caches old configs across
PutBucketLifecycleConfiguration → DeleteBucketLifecycle would keep
silently dropping objects.

Setup: positive control (rule active, backdated obj expires) →
DeleteBucketLifecycle → PUT + backdate a fresh object → second
sweep. The fresh object must remain.

* test(s3/lifecycle): integration coverage for empty bucket sweep no-op

A bucket carrying lifecycle config but no objects must produce a
successful sweep — no hangs, no errors, no dispatches. Pinned
because the bootstrap walker iterates bucket directories, and an
empty directory is a corner of that traversal that's easy to break
(slice-bounds bug on the first listing returning zero entries).

Asserts: worker logs "loaded lifecycle for" and "shards 0-15
complete", no FATAL output, bucket still exists after the sweep.

* test(s3/lifecycle): fix Object Lock backdate path + skip unwired ScanAtDate

ObjectLock: enabling Object Lock on a bucket implicitly enables
versioning, so PUT objects land at .versions/v_<id>, not at the bare
key. The test was calling backdateMtime (bare path) and failing in
the helper with "filer: no entry is found". Switch to
backdateVersionedMtime with the versionId returned by PutObject.

ExpirationDate: ScanAtDate dispatch path isn't wired to the run-shard
shell command yet — the bootstrap walker explicitly skips actions in
ModeScanAtDate (walker.go:141 says "SCAN_AT_DATE runs its own date-
triggered bootstrap" but no such bootstrap exists in the scheduler or
shell). Skip with a t.Skip + explanation so the test activates the
moment the date-triggered path lands.

* fix(s3/lifecycle): wire ExpirationDate dispatch through bootstrap walker

The walker explicitly skipped ModeScanAtDate actions on the comment
"SCAN_AT_DATE runs its own date-triggered bootstrap" — but no such
bootstrap exists in the scheduler or shell layer. The result: rules
with Expiration{Date: ...} compiled correctly, populated the
snapshot's dateActions map, and were never dispatched.
ExpirationDate is silently a no-op in production.

EvaluateAction already handles ActionKindExpirationDate correctly
(rejects when now.Before(rule.ExpirationDate), otherwise emits
ActionDeleteObject). The walker just needed to fall through instead
of skipping. Pre-date walks become no-ops via EvaluateAction's date
check; post-date walks expire eligible objects.

Un-skip TestLifecycleExpirationDateInThePast — it now exercises the
fixed path end-to-end.

* test(s3/lifecycle): integration coverage for multiple rules per bucket

A single bucket carries two independent Expiration rules with disjoint
prefix filters and different Days thresholds. Each rule must fire
only on its prefix; objects outside both prefixes must survive.

Pinned because Compile builds one CompiledAction per rule per kind
all sharing the same bucket index — a bug that lets one rule's
prefix or threshold leak into another (e.g. last-write-wins on a
shared map) would silently expire wrong objects.

Setup: rule A with prefix=logs/ Days=1, rule B with prefix=tmp/
Days=7. Three backdated objects: logs/access.log, tmp/scratch.bin,
data/keep.bin. After the worker runs, logs/ + tmp/ are gone;
data/ — outside both rule prefixes — survives.

* fix(s3/lifecycle): mark ScanAtDate actions active in Compile

Two layers were silently filtering ScanAtDate actions out of routing:
the walker's mode skip (fixed in e785f59d6) and Compile only marking
ModeEventDriven actions active. MatchPath / MatchOriginalWrite both
require IsActive() to emit a key, so a ScanAtDate action that's never
marked active never reaches a dispatch path even after the walker
falls through.

ScanAtDate's only dispatch path is the bootstrap walk's MatchPath
call — there's no bootstrap-completion rendezvous to wait on. Make
the active flag include ModeScanAtDate alongside the
EventDriven+BootstrapComplete combination.

ExpirationDate-based rules now actually fire end-to-end. The
TestLifecycleExpirationDateInThePast integration test exercises this.

* fix(s3/lifecycle): route date kinds via ComputeDueAt

ExpirationDate has MinTriggerAge=0, so router computed
dueTime = info.ModTime + 0 = info.ModTime. For a backdated entry
that mtime is BEFORE rule.ExpirationDate, so EvaluateAction's
now.Before(rule.ExpirationDate) check returned ActionNone and the
date rule never fired through the event-driven path.

ComputeDueAt already knows the per-kind shape — rule.ExpirationDate
for date kinds, ModTime+Days for the rest — so use it as the
single source of truth for dueTime in Route's main loop.

* test(s3/lifecycle): pin bootstrap walker date dispatch

The original TestWalk_DateActionsSkipped pinned the pre-e785f59d6
behavior that the regular walker skipped ExpirationDate. That
walker was rewired to fire date rules whose date has passed (the
SCAN_AT_DATE bootstrap was never wired); update the test to match.

Split into two: post-date entries dispatch, pre-date entries don't.

* test(s3/lifecycle): drop unused putExpiredDeleteMarkerLifecycle

The helper was never called — TestLifecycleExpiredDeleteMarkerCleanup
constructs a combined noncurrent + expired-marker rule inline, which
the helper doesn't cover. The blank-assignment workaround was just
hiding dead code; remove both.

* test(s3/lifecycle): tighten HeadObject termination check to typed not-found

Generic err != nil also passes on transport/auth/timeouts, letting
the test go green without proving the lifecycle action actually
fired. Switch the three Eventuallyf HeadObject predicates to
isS3NotFound, matching the pattern already in the multi-bucket and
expiration-date tests.

* test(s3/lifecycle): guard ListObjectVersions diagnostic against nil

When ListObjectVersions errors, listOut is nil and the diagnostic
log path panics on listOut.Versions before the real assertion fires.
Branch on (listErr != nil || listOut == nil) so the failure log is
robust whatever ListObjectVersions returned.
2026-05-10 09:30:50 -07:00
Chris Lu 2840980c7d test(s3/lifecycle): final unit-test cleanup before integration suite (#9414)
* test(s3/lifecycle): final unit-test cleanup before integration suite

Closes the residual coverage gaps in the lifecycle packages so the
next track (Layer 3 integration tests) starts from a clean baseline.
Big coverage lifts: lifecycletest 88.7→100.0, engine 81.7→95.1,
s3lifecycle 87.8→95.0, dispatcher 60.3→67.6, router 86.1→88.8,
bootstrap 90.7→92.6. Remaining sub-100% surfaces (reader.Run,
Pipeline.Run, scheduler.Run, multi-step bootstrap orchestration)
need a live filer and belong with the integration suite.

router/helpers_test.go (formerly #9409, now stale on master because
9410-9413 absorbed adjacent surface): direct tests for the pure
helpers Route exercises indirectly — successorModTimeFromContainer
(missing/empty/non-numeric/non-positive/positive round-trip),
logicalKeyFromVersionPath (extracts logical, rejects non-.versions
parent / root-level / no-slashes / bare container), isVersionsContainerKey
(table over container forms), isVersionFolderPath (table over child
forms), isDeleteMarkerEntry (only literal "true" matches),
extractTags (nil/empty, AmzObjectTagging-prefixed only, no-tag
returns nil), hasActiveEventDrivenAction (matches only active+
event-driven, scan-only rejected, unknown skipped). Plus engine
Snapshot accessors: BucketVersioned (compiled flag, unknown bucket
false), BucketActionKeys (full list, unknown nil), Action (unknown
nil), AllActions (every kind), SnapshotID (strictly monotonic).

s3lifecycle/final_cleanup_test.go: ActionKind.String default branch
(unspecified + future-unknown render "unspecified" rather than
empty); HashExtended direct from the lifecycle package (covers it
in this package's coverage report, not just the s3api one) including
nil/empty produces no bytes and identical content hashes the same.

bootstrap/has_prefix_test.go: thin wrapper around strings.HasPrefix
exported by the package; trivial but at 0% pre-fix.

lifecycletest/eventbuilder_old_entry_test.go: pins the OldEntry
fall-through path on Delete events for WithModTime / WithTtlSec /
WithVersionID / WithExtended / WithChunks (existing tests cover
Create events that hit NewEntry only). Adds WithBootstrapVersion
across all three event shapes. Defensive: every With* option is a
no-op on a degenerate event with neither entry populated.

* test(s3/lifecycle): address coderabbit nitpicks on final cleanup

- eventbuilder empty-event test now exercises WithBootstrapVersion
  too, with an honest claim about its scope: it targets the event
  itself (not an entry), so it sets BootstrapVersion regardless of
  whether NewEntry/OldEntry are populated. Renamed the test from
  AllAreNoOpsOnEmptyEvent to NoPanicOnEmptyEvent since the original
  name overstated the contract.
- HashExtended stability check uses a 3-key map with different
  literal orders so the helper's sort path actually does work; a
  single-key check can't catch an iteration-order regression.
- HasPrefix test refactored to table-driven so adding a new edge
  case is one row instead of two assertion lines.
2026-05-09 22:32:49 -07:00
Chris Lu b740e22e63 test(s3/lifecycle): bundle dispatcher + engine edge-case coverage (#9413)
* test(s3/lifecycle): bundle dispatcher + engine edge-case coverage

Two-package bundle covering uncovered branches in production code that
the existing happy-path tests don't reach. Dispatcher 58.1% → 60.2%
and engine 81.0% → 81.7% (engine lift modest because most branches
were already hit; the nil-rule defensive case is otherwise unreachable
from a Compile flow).

dispatcher (4 tests):
- FilerPersister.Load with nil Store errors with a "nil Store"
  message rather than panicking at the Read call.
- FilerPersister.Save with nil Store same.
- FilerPersister.Load with a non-NotFound transport error wraps the
  shard ID into the message AND keeps the underlying error
  recoverable via errors.Is.
- FilerPersister.Load with successful empty []byte returns an empty
  map, not a JSON-decode error — pinning that an existing-but-empty
  cursor file is treated as "no entries".
- Tick initializes the retries map on first call without panic so a
  freshly-constructed Dispatcher works.
- Tick with already-canceled ctx re-queues the popped Match, returns
  zero, and never invokes the LifecycleDelete client — the Match
  must not be lost across worker restart.

engine (4 tests):
- rulePredicateSensitive(nil) returns false rather than panicking on
  the FilterTags dereference. The non-nil paths run through Compile,
  but a defensive nil-rule arrival isn't reachable that way.
- rule with no FilterTags / empty FilterTags map returns false (the
  check is len(FilterTags) > 0, so empty must classify as
  non-sensitive — pinning catches a flipped >= comparison).
- rule with a populated FilterTags returns true.

* fix(s3/lifecycle): Tick must requeue every drained Match on shutdown

Per codex review on #9413: Tick called Schedule.Drain to pop ALL due
matches at once, then iterated. If ctx canceled mid-loop, only the
current Match was re-added — everything past that index was silently
lost across the worker restart. With N due matches, up to N-1 were
dropped.

Fix: on cancellation, re-add due[i:] (current + remaining) before
returning. Matches already dispatched (due[:i]) stay processed; the
schedule is left exactly as it would be if Drain had returned only
the dispatched prefix.

Strengthen the existing test to enqueue three due matches and assert
sched.Len()==3 after a pre-canceled Tick. Pre-fix the test would have
seen Len()==1 because only the first popped Match was re-added.
2026-05-09 22:02:17 -07:00
Chris Lu ad77362be3 test(s3/lifecycle): bundle reader + scheduler helper coverage (#9412)
* test(s3/lifecycle): bundle reader + scheduler helper coverage

Bundles direct tests for previously-uncovered helpers in two
packages. Bumps reader 73.2% → 79.2% and scheduler 71.6% → 73.6%.

Reader Event predicates (4):
- IsCreate: NewEntry-only event classifies as create
- IsDelete: OldEntry-only event classifies as delete
- both entries (update): neither IsCreate nor IsDelete (strict
  exclusivity so router routes updates through their own path)
- no entries (degenerate): neither (so a metadata-only filer event
  with no payload doesn't trigger spurious dispatches)

Reader LogStartup (4): exercises both shape branches (single-shard
ShardID vs ShardPredicate), the explicit-StartTsNs override path, and
the Cursor.MinTsNs fallback when StartTsNs=0. Side-effect-only
function; tests pin compile-time shape and visit each code path.

Scheduler pipelineFanout.InjectEvent (5):
- nil event silently absorbed (no follow-up panic in receiving
  pipeline)
- unknown shard returns nil (forward-compat for future shard-mapping
  gaps)
- known shard succeeds
- ctx cancellation propagates when underlying pipeline's buffer fills
- routes to the correct pipeline among multiple, with cross-pipeline
  isolation proven via per-pipeline buffer state

* test(s3/lifecycle): rename canceled to canceledCtx in fanout test

Per gemini review on #9412: a bare 'canceled' identifier reads like
a bool. Rename to canceledCtx so the type is obvious at the call site.
2026-05-09 22:02:09 -07:00
Chris Lu 7996dc1d67 test(s3/lifecycle): bundle dispatcher pipeline helper coverage (#9411)
* test(s3/lifecycle): bundle dispatcher pipeline helper coverage

Five untested helpers in dispatcher/pipeline.go and one accessor in
dispatcher.go that previously sat at 0% coverage. Bumps the dispatcher
package from 58.8% → 64.7%.

observeScheduleDepth: gauge tracks Schedule.Len; pinned for empty,
populated, and post-Drain states with a unique shard label so the
test doesn't bleed into other parallel tests sharing the global
counter.

ensureEventsChan: positive EventBuffer sizes the channel; zero and
negative fall back to defaultEventBuffer so a misconfigured operator
doesn't end up with a zero-cap channel that blocks every InjectEvent;
sync.Once contract holds under 32-goroutine concurrent invocation.

InjectEvent: delivers the same pointer to p.events (no defensive
copy); a canceled ctx propagates context.Canceled rather than
silently dropping the event; allocates the channel via
ensureEventsChan so a caller can inject before Run starts.

isCtxShutdown: nil → false; context.Canceled / DeadlineExceeded →
true; gRPC-wrapped Canceled / DeadlineExceeded codes → true (so
shutdown isn't misclassified as transport failure when filer/S3
RPCs unwrap as status); other errors (Unavailable, Internal, plain)
→ false.

cursorFileName: shard 0 / 1 / 9 / 10 / 15 all pad to two digits so
on-disk filenames stay sorted by shard ID — pinned so a refactor that
drops %02d doesn't break existing cursor files.

* test(s3/lifecycle): drop ScheduleDepthGauge label series at test end

Per gemini review on #9411: even with a unique shard label, the gauge
series persists in the global Prometheus registry across test runs in
the same process. Add a defer to DeleteLabelValues so the registry
stays clean.
2026-05-09 22:02:01 -07:00
Chris Lu ca95d33092 test(s3/lifecycle): bundle dispatcher + engine accessor coverage (#9410)
* test(s3/lifecycle): bundle dispatcher + engine accessor coverage

Two-package bundle covering pure helpers and snapshot read-side
accessors that the router and dispatcher reach for at runtime. None
were directly tested; regressions previously surfaced only as
downstream Tick / Match / Compile failures.

dispatcher (10 tests):
- keyOf: derives every retryKey field from the Match; equal Match
  values produce equal keys (so the second dispatch hits the first's
  retry counter); distinct VersionIDs and ActionKinds produce
  distinct keys (so a noisy version can't starve a healthy one,
  and two kinds on the same object don't share a budget).
- budget(): configured value when set; defaultRetryBudget when zero
  or negative — pins the >0 guard against a flipped comparison.
- backoff(): same pattern as budget for RetryBackoff.

engine snapshot accessors (8 tests):
- OriginalDelayGroups exposes the compiled per-delay groups; rules
  with multiple kinds at different cadences land in distinct entries;
  scan-only actions don't leak into delay groups so the dispatcher
  doesn't try to drive them event-driven.
- PredicateActions populated for tag-sensitive rules, empty for non-
  tag-sensitive ones (so MatchPredicateChange doesn't route
  irrelevant kinds).
- DateActions surfaces ExpirationDate verbatim for date kinds; empty
  for non-date rules.
- MarkActive on an unknown key is a no-op (durable bootstrap-complete
  write races a recompile that drops the rule; panic here would crash
  the worker).
- MarkActive flips a fresh-no-prior-state action from inactive to
  active.
- BucketActionKeys covers every kind RuleActionKinds reports.

* test(s3/lifecycle): strengthen snapshot accessor content assertions

Per gemini review on #9410: assertions previously only checked counts
and non-empty status. Verify the specific ActionKeys land where
expected so an indexing regression that produces the right number of
items with wrong kinds gets caught.

OriginalDelayGroups: each delay group's slice asserts.Contains the
specific (bucket, rule_hash, kind) ActionKey instead of just
NotEmpty.

PredicateActions: assert.Contains the expected key instead of just
NotEmpty.

BucketActionKeys: every key.Bucket must equal the test bucket (catches
cross-bucket leak), and ElementsMatch pins kinds against
RuleActionKinds.
2026-05-09 22:01:54 -07:00
Chris Lu 0955d1aa08 test(s3/lifecycle): direct prefixMatches + filterAllows coverage (#9408)
Both helpers were exercised indirectly through MatchOriginalWrite /
MatchPath; pinning them directly catches a regression at the helper
level so a Match-test failure isn't the first signal of a broken
filter.

prefixMatches: empty prefix fast path; exact-prefix match; non-match
rejection; path shorter than prefix.

filterAllows: no-filter accepts any event; FilterSizeGreaterThan is
strictly > (boundary value rejected); FilterSizeLessThan is strictly
<; zero-size thresholds mean "not set" (must let any size through —
a regression treating 0 as a real threshold would reject everything);
required tag present accepts; missing key, empty tags map, wrong
value, and missing-among-multiple all reject; size + tag filters are
AND'd so either failing rejects.
2026-05-09 20:47:35 -07:00
Chris Lu edbe7ab140 test(s3/lifecycle): meta-log Event builder + monotonic clock fixture (#9406)
* test(s3/lifecycle): meta-log Event builder + monotonic clock fixture

Several test files build *reader.Event ad-hoc; consolidate the common
shape into the lifecycletest package as task #12 spec calls out
("fixture meta-log generator"). New tests using the builder don't
have to thread Mtime / ShardID / leaf-name semantics by hand, and
existing helpers can migrate over time without churning this PR.

NewCreate / NewDelete / NewUpdate cover the three event shapes;
WithSize / WithModTime / WithTtlSec / WithVersionID / WithExtended /
WithChunks / WithBootstrapVersion / WithShardID compose deterministic
overrides. ShardID defaults to s3lifecycle.ShardID(bucket, key) so
events route through the same shard the production reader would.

MetaLogClock issues monotonic timestamps with a configurable step
(default 1s); concurrent-safe so fan-out fixtures don't have to lock
externally.

15 unit tests pin every option, the IsCreate/IsDelete/IsUpdate
discriminators, leaf-name extraction for nested keys, ShardID
derivation, option-ordering semantics, the concurrent clock contract
under -race, and a Peek-doesn't-advance check.

* test(s3/lifecycle): address review comments on event builder

- leafOf strips trailing slashes before splitting so directory-key
  fixtures (e.g. "folder/") get the slashless leaf "folder" — pre-fix
  it returned "" which would break router tests for directory markers.
- NewUpdate now seeds OldEntry.Attributes.Mtime with the event ts
  (matching NewDelete), so a downstream router that compares mtimes
  doesn't see a synthetic 1970 epoch on the pre-update state.
- New WithOldSize / WithOldChunks / WithOldModTime options let Update
  events configure pre-update state independently. The unprefixed
  variants still target NewEntry on Update events; the With Old*
  options are no-ops on Create (no OldEntry to mutate) and never bleed
  into NewEntry.

5 new tests pin: directory-key + multi-slash leaf extraction; OldEntry
mtime default on Update; the WithOld* targeting + Create-event
no-bleed contract.
2026-05-09 20:47:27 -07:00
Chris Lu 9d20e71883 test(s3/lifecycle): cover worker handler lookupBucketsPath (#9407)
Three branches: gRPC error from GetFilerConfiguration must propagate
(else Execute would proceed to dial S3 with an empty buckets path
and never dispatch); a non-empty DirBuckets is honored verbatim so
operators with a non-default layout aren't force-routed to /buckets;
an empty DirBuckets falls back to the documented "/buckets" default
rather than returning empty (which would route to root). stubFilerConfigClient
embeds filer_pb.SeaweedFilerClient so methods other than the one
under test panic if called — keeps the surface narrow.
2026-05-09 20:41:09 -07:00
Chris Lu 1aa55f5bf9 test(s3/lifecycle): direct decideMode + RuleMode.String coverage (#9405)
Compile tests cover decideMode indirectly; these direct tests pin
every branch so a regression in the classifier itself can't slip
behind a more elaborate Compile failure.

Pinned: nil rule and Disabled status both → Disabled; ExpirationDate
→ ScanAtDate without consulting retention; metaLogRetention=0 means
unbounded so any horizon → EventDriven; horizon within retention →
EventDriven; horizon exceeding retention → ScanOnly; bootstrapLookback
adds to horizon (not retention) so a near-threshold case is still
gated; zero horizon (rule field unset) skips the gate. RuleMode.String
must render the documented names for every variant; an unknown value
collapses to "unspecified" rather than empty or panic.
2026-05-09 20:35:34 -07:00
Chris Lu 619cb39827 test(s3/lifecycle): pin Schedule edge cases beyond happy path (Phase 15 slice) (#9403)
* test(s3/lifecycle): pin Schedule edge cases beyond happy path

Pre-existing schedule_test covered the happy path (ordered Drain,
empty schedule, duplicates, boundary-inclusive). Five new tests pin
edge cases the dispatcher relies on:

- Drain at a time before any DueTime returns nil and leaves the heap
  intact, so the dispatcher can't accidentally consume future-due
  matches.
- NextDue after partial Drain points to the next earliest, catching
  a Drain that forgets the heap invariant.
- Add after Drain bubbles a fresh earlier DueTime to the front, so
  late-arriving high-priority matches don't sit behind older ones.
- Drain returns Matches in ascending DueTime order regardless of
  insert order — explicit pinning of the documented contract.
- Concurrent Add+Drain across 64 goroutines under -race.

* test(s3/lifecycle): actually exercise Drain in AddAfterDrain test

Per coderabbit review on #9403: the test name promised "after Drain"
but the previous body only Add'd both items without ever calling
Drain in between. Insert a real Drain (popping "drain_me") before
the second Add, so the heap-invariant-across-Drain-then-Add path is
actually pinned. Bumps the after-Drain Match's DueTime out of the
way so the Drain in step 3 returns it deterministically.
2026-05-09 20:35:22 -07:00
Chris Lu 435ef7f94f test(s3/lifecycle): pin toProtoActionKind + toProtoIdentity converters (#9404)
test(s3/lifecycle): pin toProtoActionKind + toProtoIdentity

The two converters are the worker-side wire to LifecycleDelete; a
miss in toProtoActionKind sends ACTION_KIND_UNSPECIFIED that the
server rejects FATAL, and a wrong toProtoIdentity flips the CAS
witness so every dispatch comes back NOOP_RESOLVED with STALE_IDENTITY
even though the entry hasn't changed.

10 tests pin: every listed s3lifecycle.ActionKind maps to its proto
counterpart (table-driven, one subtest per kind); ActionKindUnspecified
and a future unknown kind both collapse to ACTION_KIND_UNSPECIFIED
(forward compat); nil EntryIdentity stays nil (preserves the no-CAS
sentinel); a populated identity copies every field; a zero-valued
identity still produces a non-nil output so the server treats it as
a real CAS witness rather than no-CAS.
2026-05-09 20:35:04 -07:00
Chris Lu 1350e681c9 test(s3/lifecycle): pin Pipeline.Run dependency + shard validation (Phase 15 slice) (#9402)
* test(s3/lifecycle): pin Pipeline.Run dependency + shard validation

Pre-existing TestPipelineRunRequiresDependencies only checked that an
empty Pipeline errors; it didn't pin which specific dependency must be
present. A refactor that makes one nilable accidentally would slip
through.

8 new tests pin every validation branch in Pipeline.Run: missing
Engine / Persister / Client / FilerClient each error with "missing
required dependency"; missing BucketsPath errors with its own
distinct message so operators can spot the missing wiring; ShardID =
-1 / ShardCount errors with a range message (covers the half-open
[0, ShardCount) boundary so a < to <= refactor can't introduce a
one-past-the-end shard); and a multi-shard config with one
out-of-range entry refuses the whole run rather than silently
disabling the rest.

* test(s3/lifecycle): refactor Pipeline.Run validation tests as table-driven

Per gemini review on #9402: collapse the eight per-branch tests into
TestPipelineRunValidation with a slice of (name, mutate, wantErr)
cases. Same coverage, ~30 fewer lines, idiomatic Go pattern that
makes adding a new validation case trivial.
2026-05-09 20:34:51 -07:00
Chris Lu cb6e498e0b test(s3/lifecycle): pin Descriptor structural invariants (#9401)
* test(s3/lifecycle): pin Descriptor structural invariants

Pre-existing handler tests covered Capability and Detect; Descriptor
was previously untested. A drift between the form fields it advertises
and the defaults config.go reads silently breaks the admin UI in two
ways: the form renders blank (admin can't tune) or the worker clamps
to a hardcoded fallback ignoring the admin's edits. The new tests
catch both directions.

Pinned: jobType / DisplayName / Description / DescriptorVersion;
AdminConfigForm exposes a workers field whose default matches
defaultWorkers; WorkerConfigForm has a default and a field for every
cadence knob ParseConfig reads (dispatch_tick / checkpoint_tick /
refresh_interval / bootstrap_interval / max_runtime); AdminRuntime-
Defaults hits a daily cadence with bounded detection timeout and
single job per detection.

* test(s3/lifecycle): tighten Descriptor invariant assertions

Per gemini review on #9401: pin DetectionTimeoutSeconds to its exact
value (60) instead of ">0" so an accidental tweak is caught, and
assert WorkerConfigForm fields are INT64 (matching ParseConfig's
readInt64) so a STRING-type drift can't silently make the worker
ignore admin edits.
2026-05-09 20:34:17 -07:00
Chris Lu 6f9668c20b test(s3/lifecycle): pin lifecycleDispatch validation early-returns (#9400)
Three pure-validation paths in lifecycleDispatch return BLOCKED before
any filer call; without coverage a refactor could let them fall
through to a real delete. ABORT_MPU at dispatch time is a defensive
catch (the route bypass should never happen, but if it does the
fallthrough must not become a default-case rm). Unknown ActionKind
gets the same treatment for forward-compatibility with new proto
values. Empty version_id on noncurrent / EXPIRED_DELETE_MARKER kinds
must be rejected before deleteSpecificObjectVersion is called, so a
malformed event can't silently delete the latest pointer.
2026-05-09 20:11:08 -07:00
Chris Lu af2a359e45 feat(s3/lifecycle): metadata_only_total Prometheus counter (#9399)
Operator-visible signal for the metadata-only delete path landed in
PR 9390. Increment seaweedfs_s3_lifecycle_metadata_only_total{bucket,
rule_hash} after each successful unversioned or noncurrent / expired-
marker delete that took the skip-chunk path. Suspended-versioning
null delete is intentionally not counted: that path's nil err can
mean "deleted" or "NotFound", so a count there would over-report.
rule_hash is hex-encoded for label safety; nil bytes collapse to
"". DeleteBucketMetrics tears the new series down alongside the
existing lifecycle counters when a bucket is removed.
2026-05-09 20:02:26 -07:00
Chris Lu c0cf1417f1 test(s3/lifecycle): cover worker handler Execute validation paths (#9398)
7 tests pin the Execute early-return surface that runs without a
filer or S3 dial: nil request / nil Job / nil sender all error;
foreign JobType errors with the offending name in the message; no
S3 endpoints in cluster context errors (Execute is stricter than
Detect — the admin shouldn't have routed the job there); missing
filer_grpc_address parameter errors (proposal must have been tampered
with or dropped); empty JobType is accepted as broadcast routing and
flows through to the next validation step. The dial path itself is
intentionally not covered here — those tests would need an in-process
gRPC server and belong with the integration suite.
2026-05-09 19:51:31 -07:00
Chris Lu 284d37c3b6 test(s3/lifecycle): cover InMemoryPersister deep-copy contract (#9397)
* test(s3/lifecycle): cover InMemoryPersister deep-copy contract

8 tests pin the persister contract other lifecycle tests rely on for
cursor checkpointing: Load on an unknown shard returns an empty map
(not an error); Save then Load roundtrips; Save copies the input so
caller-side mutation doesn't bleed into stored state; Load returns a
copy so caller-side mutation of the snapshot doesn't bleed back; Save
replaces (not merges) prior state so stale resume points don't survive
restart; different shards stay isolated; saving an empty map clears
state; concurrent Save+Load is race-free under -race. A regression on
any of these silently corrupts downstream tests.

* test(s3/lifecycle): assert.NotContains for InMemoryPersister key absence

assert.Empty on a map[K]V index returns true when the value is the
zero value, which would mask a key that leaked through with int64(0).
Use assert.NotContains so the assertion fails on key presence
regardless of the stored value.
2026-05-09 19:47:16 -07:00
Chris Lu 62e04623ce test(s3/lifecycle): cover worker handler Detect + helpers (#9396)
* test(s3/lifecycle): cover worker handler Detect + helpers

13 tests pin the worker-handler surface that runs without a live filer
or S3 server. Pure helpers: clusterS3Endpoints (nil context, empty
list, filter empty entries while preserving order, all-valid
passthrough); readString (missing key, nil ConfigValue, wrong kind
falls back, string returned). Capability advertises jobType with
single-job concurrency caps. Detect: nil request / nil sender / wrong
JobType all error; no S3 endpoints emits a 'skipped' activity and
completes with success; no filer addresses behaves the same; the
happy path proposes one job parameterized with the first filer
address; empty JobType is accepted (broadcast detect); a
SendProposals failure propagates without firing complete.

* test(s3/lifecycle): cover SendComplete error propagation in worker Detect

The recordingSender already supported forcing an err on SendComplete
via errOn, but no case exercised it. A SendComplete failure must
propagate so the admin learns the completion signal never landed;
proposals went out before the failure so they remain recorded.
2026-05-09 19:46:57 -07:00
Chris Lu 551e700e64 test(s3/lifecycle): cover scheduler configload surface (#9395)
* test(s3/lifecycle): cover scheduler configload surface

LoadCompileInputs is the bridge between the filer's bucket directory
and the engine snapshot the scheduler compiles every refresh; a missed
or misclassified bucket silently disables lifecycle for that prefix
until the next refresh. Tests pin: empty bucket dir, files at the
bucket level skipped, buckets without the lifecycle XML extended key
skipped, empty-bytes XML skipped, valid XML becomes a CompileInput,
versioning attr propagates to CompileInput.Versioned, malformed XML
surfaces as a ParseError without aborting the walk, and pagination
across the 1024 page boundary preserves bucket order.

Also covers the IsBucketVersioned (case + whitespace tolerance,
rejection of garbage values) and AllActivePriorStates (one entry per
(bucket, ruleHash, actionKind), bucket-keyed isolation) helpers.

* test(s3/lifecycle): tighten configload pagination boundary check

Switch the bucket-count check to require.Len so a regression that
returns the wrong number of buckets fails fast before the boundary
asserts panic on out-of-range index. Add explicit assertions on the
last entry of page 1 (b01023) and the first entry of page 2 (b01024)
so a pagination-loop bug that drops or duplicates the seam is caught
directly rather than only via the count check.
2026-05-09 19:46:40 -07:00
Chris Lu 6021a88606 test(s3/lifecycle): cover CompareVersionIds tiebreak surface (#9394)
* test(s3/lifecycle): cover CompareVersionIds tiebreak surface

13 tests pin every documented branch of the version-id comparator and
its helpers (isNewFormatVersionId, getVersionTimestamp): equality and
short-circuit paths, null sorting last, both-new-format with smaller-
=-newer ordering, both-old-format with larger-=-newer ordering, mixed-
format compared by parsed timestamp, mixed-format with synthesized
equal timestamps, length / null / non-hex rejection, the strictly-
greater-than threshold boundary at 0x4000000000000000, and the
inverted-value invariant the comparator relies on. Getting any axis
wrong silently inverts retention rankings, which would resurrect
deleted versions or evict live ones.

* test(s3/lifecycle): use plain assert.Equal in mixed-format compare test

The previous local require := assert.New(t) shadowed testify's require
package while actually returning an assert.Assertions (continue-on-fail
semantics, not fail-fast). Use plain assert.Equal(t, ...) calls so the
behavior matches the variable's name and the rest of the file.
2026-05-09 19:03:31 -07:00
Chris Lu 7781eef429 test(s3/lifecycle): cover dispatcher filerSiblingLister surface (Phase 14 slice) (#9392)
* test(s3/lifecycle): cover dispatcher's filerSiblingLister surface

Tests pin the four routing-critical filer interactions on the
filerSiblingLister: Survivors (count cap, LoneEntry semantics,
null-version detection across regular files and directory-key
markers, error propagation in both list and lookup paths),
ListVersions (NotFound collapse, dir/missing-id filtering,
1024-page boundary, error propagation), LookupNullVersion (regular
file, explicit-null flag, directory-key marker accept, plain-dir
reject, NotFound collapse, error propagation), and LookupVersion
(empty version-id no-op, v_ prefix, NotFound collapse, error
propagation).

The fake SeaweedFilerClient mirrors the real filer's NotFound
shape — gRPC succeeds at stream creation and the first Recv()
surfaces filer_pb.ErrNotFound — which is what the lister's
errors.Is check depends on. NewFullPath strips a trailing slash
before splitting so directory-key markers are stored under their
slashless Name.

* test(s3/lifecycle): gofmt sibling_lister_test.go

Trailing comment alignment.
2026-05-09 18:55:50 -07:00
Chris Lu 8cf42a5abb test(s3/lifecycle): assert per-goroutine errors in fake-server concurrent test (#9393)
test(s3/lifecycle): assert per-goroutine errors in concurrent fake test

The previous TestFake_ConcurrentCallsSerializeWithoutDeadlock dropped
the err return from each LifecycleDelete call, so a regression in the
concurrent path could pass the length-only assertion. Capture each
err on a buffered channel and require.NoError after wg.Wait().
2026-05-09 18:54:15 -07:00
Chris Lu ddfb219ec3 test(s3/lifecycle): fake LifecycleDelete server (Phase 12 slice) (#9391)
* test(s3/lifecycle): fake LifecycleDelete server for component tests

A reusable double for SeaweedS3LifecycleInternalServer with per-key
FIFO outcome queues, a fallback Default, and recorded request capture.
Tests of the worker pipeline that need to hit the proto boundary can
queue up DONE/NOOP/RETRY/FATAL/SKIPPED_OBJECT_LOCK responses per
(bucket, objectPath, versionId) and assert dispatch order against
Recorded(). SetError flips the server into transport-failure mode
without polluting the request log.

* test(s3/lifecycle): use struct map key for FakeLifecycleServer queues

Bucket / object path / version-id are user-supplied strings that can
contain "/" or "@", which would collide if the queue map were keyed by
"<bucket>/<object>@<version>". Switch to a struct key so the
components stay separate.

* test(s3/lifecycle): deep-copy recorded LifecycleDelete requests

Tests that mutate a Recorded() entry — or a request pointer they
already passed in — were able to corrupt the fake's bookkeeping
because the slice carried shared pointers. Clone with proto.Clone at
both record and read time so the fake holds an independent snapshot
of every arriving request and hands callers an independent snapshot
back. Tightened TestFake_VersionIDPartOfKey error checks while there.
2026-05-09 18:38:52 -07:00
Chris Lu bb0c7c779f feat(s3/lifecycle): metadata-only delete when entry TtlSec > 0 (Phase 2b) (#9390)
* refactor(s3): thread metadataOnly into delete helpers

Add a metadataOnly bool to deleteUnversionedObjectWithClient and
deleteSpecificObjectVersion. When true the helper sends IsDeleteData=
false to the filer's DeleteEntry RPC so per-chunk DeleteFile RPCs are
skipped — the volume server reclaims chunks on its own at TTL drop.
Non-lifecycle callers (DELETE handlers, batch delete) pass false to
preserve today's eager-chunk-delete behavior; only the lifecycle
handler in the next commit will pass true.

* feat(s3/lifecycle): metadata-only delete when entry TtlSec > 0

Per-write TTL stamping (PR 9377) sets Attributes.TtlSec on every
lifecycle-fitting entry. When the live entry the LifecycleDelete
handler fetched carries TtlSec > 0 the volume server is guaranteed
to reclaim chunks at TTL drop, so the filer can skip per-chunk
DeleteFile RPCs and just remove the entry record. lifecycleDispatch
now computes metadataOnly from the live entry and threads it through
the unversioned, suspended-null, and noncurrent/expired-marker delete
paths. createDeleteMarker is unaffected — it creates a marker, never
deletes chunks.
2026-05-09 18:38:38 -07:00
Chris Lu 255e9cd0f7 test(s3/lifecycle): cover reader cursor + Run validation contracts (#9389)
* test(s3/lifecycle): cover reader cursor + Run validation contracts

Layer 2 tests pinning four reader-package contracts the dispatcher
pipeline depends on: MinTsNs anchors at frozen positions, Snapshot
returns a deep copy in both directions, Restore replaces (not merges),
and Run validates ShardID/Events/BucketsPath before subscribing.

* test(s3/lifecycle): tighten cursor composition assertions

Snapshot deep-copy: also assert cursor doesn't see keys added to the
returned map. Restore replace: freeze before second Restore and assert
IsFrozen returns false after, pinning the contract that Restore wipes
frozen state alongside the value map. Run validation: bound the call
with a 5s context timeout so a regression that lets Run reach the nil
client surfaces as a failure instead of a hang.
2026-05-09 14:32:11 -07:00
Chris Lu aa280443e7 test(s3/lifecycle): Layer 2 multi-shard composition for the dispatcher (#9387)
* test(s3/lifecycle): Layer 2 multi-shard composition for the dispatcher

The existing dispatcher unit tests cover individual outcomes
(DONE / RETRY_LATER / BLOCKED / etc.) on a single shard, and
pipeline_test.go has only one end-to-end happy-path assertion.
Multi-shard composition — the contract Pipeline.Run wires up at
runtime — was untested at the component level.

Add four Layer 2 tests in dispatcher/multi_shard_test.go:

  Two events for two shards land in different schedules, dispatch
  independently, and each cursor advances only for its own event
  (no cross-contamination on the action-key map).

  A poison event on shard 0 returns BLOCKED and freezes shard 0's
  cursor; shard 1's normal event continues to dispatch and its
  cursor advances. Per-shard isolation contract.

  Save/Load round-trips a per-shard cursor snapshot through the
  Persister: a fresh dispatcher restores the same TsNs map. Pins
  the contract Pipeline.Run drives on the checkpoint ticker.

  RETRY_LATER respects RetryBackoff against the wall clock — a
  Tick within the backoff window doesn't re-dispatch; a Tick past
  the new DueTime does. Guards against premature retries from
  refresh ticks landing inside the backoff.

Pipeline.Run itself can't run here (it builds a real reader.Reader),
so the tests share the same fakeClient pattern dispatcher_test.go
uses and drive Tick directly.

* test(s3/lifecycle): drop unused snapshot helper and addAndTick parameter
2026-05-09 14:12:21 -07:00
Chris Lu 1854101125 feat(s3/lifecycle): bootstrap re-walk cadence + operator hooks (Phase 8) (#9386)
* feat(s3/lifecycle): bootstrap re-walk cadence + operator hooks (Phase 8)

scan_only actions only fire from the bootstrap walk: the engine
classifies a rule as scan_only when its retention horizon exceeds the
meta-log retention, so event-driven routing can't be trusted. Today
each bucket walks once per process, so a long-running worker never
revisits — scan_only retention only catches up when the worker
restarts.

Replace BucketBootstrapper.known (set) with BucketBootstrapper.lastWalk
(name -> completion time). KickOffNew now re-walks a bucket whose
last walk completed more than BootstrapInterval ago. Zero interval
preserves the legacy walk-once-per-process behavior so existing
deployments don't change cadence by default. walkBucket re-stamps
on success and clears the stamp on failure (via MarkDirty), so the
next KickOffNew picks failed walks back up.

Add MarkDirty / MarkAllDirty operator hooks for forced re-walks, and
a Now func() for testable time travel.

weed shell run-shard grows --bootstrap-interval (cadence knob) and
--force-bootstrap (drop in-memory state at startup so every bucket
walks again immediately, useful when a config change should take
effect without a restart).

Tests: cadence respected (skip inside interval, re-walk past it);
zero interval keeps once-per-process; MarkDirty forces re-walk
under a 24h interval; MarkAllDirty resets every record. The
fakeClock helper guards the test clock with a mutex so race-detector
runs are clean.

* fix(s3/lifecycle): split walk state, thread BootstrapInterval through worker, drop dead flag

Three issues with the Phase 8 cadence work as it landed:

1. lastWalk did double duty as both completed-walk timestamp and
   in-flight debounce. A walk that took longer than BootstrapInterval
   would have a fresh KickOffNew start a duplicate goroutine on the
   next refresh tick because the stamp from KickOffNew looked stale
   against the interval. Split into lastCompleted (set on success)
   and inFlight (set on dispatch, cleared after the walk goroutine
   returns success or failure). KickOffNew skips inFlight buckets
   regardless of cadence.

2. The cadence knob existed on `weed shell` but not on the production
   path: scheduler.Scheduler constructed BucketBootstrapper without
   BootstrapInterval, and weed/worker/tasks/s3_lifecycle/Config had
   no field for it. Add Scheduler.BootstrapInterval, parse
   `bootstrap_interval_minutes` in ParseConfig (zero = legacy walk-
   once-per-process; negative clamps to zero), and forward it from
   the handler. Tests cover default, override, clamp, and explicit-zero.

3. --force-bootstrap was a no-op: BucketBootstrapper is freshly
   allocated at command start, so MarkAllDirty on empty state does
   nothing, and the flag couldn't influence an already-running
   process anyway. Remove it; a real runtime trigger (SIGHUP, control
   RPC) is a separate change.

In-flight regression: a blockingInjector pins the first walk in
progress while the test advances the clock past the interval. The
second KickOffNew is a no-op (inFlight check). After release, the
post-completion KickOffNew within the interval is also a no-op.

* test(s3/lifecycle): wait for lastCompleted stamp before advancing fake clock

The cadence test polled listedN to know "the walk happened" — but
that fires once both list passes are issued, while the success-stamp
lands later, after walkBucketDir returns. A clock.Advance(30m)
between those two events would record the stamp at clock+30m
instead of T0; the next assertion would then see now.Sub(last) < 1h
and skip the expected re-walk. Tight in practice but exposed under
-race / load.

Add a waitForCompleted helper that polls b.lastCompleted directly,
and use it before each clock advance in both the cadence and zero-
interval tests.

* fix(s3/lifecycle): expose bootstrap interval in worker UI; honor MarkDirty during walks

Two follow-ups on Phase 8.

The worker config descriptor had no bootstrap_interval_minutes field,
so the production operator UI couldn't enable the cadence — only the
internal ParseConfig + Scheduler wiring knew about it. Add the field
to the cadence section (MinValue=0 since 0 is the legacy default) and
include the default in DefaultValues so existing deployments see the
knob with the right preset.

MarkDirty / MarkAllDirty silently lost their effect when a walk was
in flight: the methods cleared lastCompleted, but the walk's success
path then wrote a fresh timestamp, hiding the operator's invalidation.
Track a pendingDirty set; the walk goroutine consumes the flag on
exit and skips the success stamp, so the next KickOffNew picks the
bucket up immediately.

Regression: pin a walk in progress with a blockingInjector, MarkDirty
the bucket, release the walk, and assert lastCompleted stayed empty
plus the next KickOffNew triggers a new walk inside the
BootstrapInterval window.

* refactor(s3/lifecycle): drop unused MarkDirty / MarkAllDirty + pendingDirty

These methods were the operator-hook half of Phase 8, but the only
caller (--force-bootstrap on the shell command) was removed when it
turned out to be a no-op against a freshly-allocated bootstrapper.
Nothing in production calls them anymore.

Strip the dead surface: MarkDirty, MarkAllDirty, the pendingDirty
set, the dirty-suppression branch in walkBucket, and the three tests
that only exercised those methods. BootstrapInterval-driven
re-bootstrap is the live mechanism. A real runtime trigger (SIGHUP,
control RPC) is a separate change with a real call site.
2026-05-09 13:42:31 -07:00
Chris Lu edfa1ce210 feat(s3/lifecycle): pointer-transition routing for live PUTs (Phase 5b/4) (#9385)
* feat(s3/lifecycle): pointer-transition routing for live PUTs (Phase 5b/4)

Bootstrap covers existing versions, but a live PUT that creates a new
.versions/<v-new> file and updates the parent's ExtLatestVersionIdKey
didn't fire NoncurrentDays / NewerNoncurrent on the displaced prior
version until the next bootstrap. Close that runtime gap.

The meta-log already emits an Update event for the .versions/
directory itself when the latest pointer changes; the router was
dropping it because buildObjectInfo returns nil for directories. New
branch in Route detects that shape (versioned bucket, NewEntry +
OldEntry both directories with the .versions/ suffix, ExtLatestVersionIdKey
changed, ID different from the new ID) and emits a Match against the
LOGICAL key with VersionID=oldID. Match.Identity comes from a single
LookupVersion RPC for the displaced version file; SuccessorModTime is
the directory update's mtime, which is the moment the displaced
version became noncurrent.

SiblingLister grows LookupVersion(bucket, key, versionID) for that
single-RPC fetch. filerSiblingLister implements it; routing path
treats NotFound as "displaced version was hard-deleted in the
meantime, suppress" rather than an error.

The router gates the lookup on at least one active event-driven
NoncurrentDays / NewerNoncurrent rule for the bucket, so most buckets
pay nothing per directory update.

Tests: pointer-flip fires NoncurrentDays with displaced version_id;
unchanged pointer skips; empty old pointer skips (first-PUT scenario);
displaced-version NotFound suppresses; no-rule skips lookup;
NewerNoncurrentVersions retains rank-0; unversioned bucket skips.

* fix(s3/lifecycle): SuccessorModTime cache + NewerNoncurrent expansion

Two correctness gaps in pointer-transition routing.

The .versions/ directory's own Attributes.Mtime is preserved across
pointer updates by updateLatestVersionInDirectory: it's a stale clock
relative to the freshly-written latest version. Using it as the
displaced version's SuccessorModTime made NoncurrentDays compute
due = staleMtime + days, which fires immediately on a fresh PUT
into an old .versions/ container. Read ExtLatestVersionMtimeKey
written by setCachedListMetadata; suppress (return no matches) when
the cache is missing rather than fall back to dir mtime.

Single-oldID lookup is only enough for pure
NoncurrentVersionExpirationDays. Any rule with NewerNoncurrentVersions
> 0 cares about the noncurrent ranks, and a pointer flip shifts every
prior noncurrent's index by one — the version that just crossed the
keep-count threshold needs to be evaluated too. When any matching
rule needs ranks, list the full .versions/ container, sort newest-
first with mtime + version-id tiebreak, and route every noncurrent
with its real index. Identity-CAS dedups against earlier schedules.

SiblingLister grows ListVersions(bucket, key); filerSiblingLister's
implementation paginates the container fully.

Two regression tests: stale dir mtime + correct cached mtime
schedules ~30 days out (not immediate); NewerNoncurrentVersions=2
with 4 versions fires on the rank-2 entry that just crossed the
threshold while rank-0/1 are retained.

* fix(s3/lifecycle): bound pointer-transition expansion to threshold crossings

routePointerTransitionExpand emitted a Match for every eligible
noncurrent on every PUT. Schedule.Add doesn't dedup, so identity-CAS
at dispatch only saved the wasted RPC, not the heap slot. A hot key
with many already-eligible versions and a count rule would push
O(versions) entries per flip, repeatedly, until dispatch caught up.

Bound the emission to versions that newly entered eligibility on
this specific flip: rank 0 (the displaced version, for the
NoncurrentDays clock) plus rank == rule.NewerNoncurrentVersions
for each active count-gated rule (the version that just crossed
from kept to expired). Bootstrap still owns full backfill for
versions that were already over-threshold.

Adds a regression with 6 versions and NewerNoncurrentVersions=2:
asserts only the rank-2 entry that just crossed fires, not the
already-over-threshold rank-3/rank-4 entries.

* fix(s3/lifecycle): suppress pointer-transition expansion when newID missing

routePointerTransitionExpand defaulted latestPos to 0 if newID wasn't
found in the listing. That made the actual newest sibling latest
against the pointer's intent, then misranked every other version. A
race between the pointer write and the version write could land us
there.

Default latestPos to -1, set it only on a real match, and suppress
the expansion when the search misses. Bootstrap repairs state on
the next walk.

The NewerNoncurrentVersions retention test was setting only
lookupEntry, so Route never reached the expansion path it claimed to
exercise. Repoint to listVersions and assert ListVersions was
consulted while LookupVersion was not. Adds a regression covering
the missing-newID suppression directly.

* fix(s3/lifecycle): include bare null version in pointer-transition routing

Bootstrap models the bare-key object as a "null" sibling alongside
.versions/ children, but the live pointer-transition path didn't.
Two cases lost:

1. oldID == "" was treated as "nothing displaced". A pre-versioning
   bare object becomes noncurrent when the first versioned PUT lands
   and the pointer flips to a real id, but live routing skipped it
   and waited for the next bootstrap.

2. The expansion path's ListVersions returned only .versions/
   children. With a bare null in the picture, the noncurrent ranks
   were wrong, so NewerNoncurrentVersions could keep the wrong
   versions and delete the right ones (or vice versa).

SiblingLister grows LookupNullVersion(bucket, key) returning the
bare entry plus an explicit-null flag (matches the bootstrap shape).
filerSiblingLister implements it via util.NewFullPath +
filer_pb.LookupEntry.

routePointerTransitionDisplaced: oldID == "" now consults
LookupNullVersion. When the bare entry exists, route it as
VersionID="null" against the LOGICAL key.

routePointerTransitionExpand: collect .versions/ children plus the
null entry into one sibling slice before sorting and ranking. The
threshold-crossing logic now sees the same N-version set that
bootstrap would compute.

Three new tests: oldID == "" with no null is a no-op (one null
lookup, no version lookup); oldID == "" with a bare null schedules
NoncurrentDays as VersionID="null"; expansion with a bare null
between .versions/ siblings places null at its mtime-correct rank
and only that rank-N entry fires.

* fix(s3/lifecycle): atomic listPageSize so test cleanup doesn't race

KickOffNew dispatches walks via `go b.walkBucket(...)`. A test that
finishes before its goroutines drain leaves them running into the
next test's t.Cleanup, which mutates listPageSize. -race spots the
read/write collision intermittently. Convert listPageSize to
atomic.Uint32; tests use Load/Store. No production semantics change.

* fix(s3/lifecycle): null becomes latest when suspended PUT clears pointer

The router treated newID == "" as if the cached
ExtLatestVersionMtimeKey were still authoritative — but that cache
holds the displaced version's mtime, written by setCachedListMetadata
when the prior version became latest. Using it as SuccessorModTime
made NoncurrentDays=30 immediately fire on a 100-day-old displaced
version even though it became noncurrent today.

When newID == "" the bare null is the new latest. Look it up,
substitute its mtime as the successor clock, and substitute "null"
as the latestPos target for the expansion path's id match. Both
displaced and expand paths now derive the right clock.

updateIsLatestFlagsForSuspendedVersioning was the upstream cause of
the staleness — it cleared ExtLatestVersionIdKey and FileNameKey but
left the cached size/mtime/etag/owner/delete-marker behind. Call
clearCachedVersionMetadata so the .versions/ container is consistent
with "null is latest". The router-side guard is still needed for
older deployments that ran the buggy code, but new writes won't
exercise the workaround.

Two regressions: 100-day-old displaced under NoncurrentDays=30 with
a today-null PUT schedules ~30d out (not immediate); same shape with
NewerNoncurrentVersions=2 ranks the null at latest and only the
rank-2 entry fires.
2026-05-09 12:21:35 -07:00
Chris Lu 2f7ac1d664 feat(s3/lifecycle): NoncurrentVersionExpiration via bootstrap (Phase 5b/3) (#9383)
* feat(s3/lifecycle): NoncurrentVersionExpiration via bootstrap (Phase 5b/3)

Bootstrap now expands every <key>.versions/ directory into one event
per version with sibling state pre-computed. The router fires
NoncurrentDays / NewerNoncurrent off these events using
SuccessorModTime as the noncurrent clock; previously these rules
never ran on a versioned bucket because buildObjectInfo couldn't
classify version-folder events without the latest pointer.

Mechanics

walkBucketDir treats a directory ending in .versions and carrying
ExtLatestVersionIdKey as a SeaweedFS .versions container — emit it
once and skip the recursion. Coincidentally-named directories without
the latest pointer recurse normally.

BucketBootstrapper.expandVersionsDir lists the children, sorts
newest-first by mtime, resolves the latest position from the pointer,
and injects a synthesized reader.Event per version with
BootstrapVersion populated. NoncurrentIndex is 0-based among
noncurrents in newest-first order; SuccessorModTime is the immediate
newer sibling's mtime (zero for the latest). Pointer naming a missing
or absent version falls back to the newest-by-mtime sibling so a
race window can't flag every entry as noncurrent.

routeBootstrapVersion uses BootstrapVersion to build ObjectInfo
directly (bypassing the version-folder skip in buildObjectInfo) and
runs the standard match loop. ABORT_MPU is excluded by kind-shape
gate. The schedule clock uses SuccessorModTime for noncurrents and
ModTime for the latest, so the dispatcher fires when the rule's days
threshold is met. Match.ObjectKey is the LOGICAL key,
Match.VersionID is the marker's stored version_id — the dispatcher
reaches deleteSpecificObjectVersion or createDeleteMarker correctly.

Layer 2 tests cover both sides. Router: latest fires ExpirationDays;
noncurrent fires NoncurrentDays; NewerNoncurrentVersions retains the
N newest noncurrents; ABORT_MPU never matches. Bootstrap: .versions
dir emitted once and not recursed; missing latest pointer falls back
to newest; backdated PUT (latest pointer is older by mtime) keeps
the right noncurrent index; delete-marker flag propagates.

* fix(s3/lifecycle): no VersionID for latest expirations, child-based dir disambig

Two correctness gaps in Phase 5b/3.

Bootstrap was pinning the version_id on every Match. For
EXPIRATION_DAYS / EXPIRATION_DATE on the latest version this is
unsafe: between schedule and dispatch a fresh PUT can land, the
dispatcher would still identity-match against the original version's
bytes (it still exists at that path) and the resulting delete marker
would hide the new latest. Drop VersionID for those kinds; an empty
VersionID makes the dispatcher fetch the current latest, where
identity-CAS resolves to STALE_IDENTITY and bootstrap re-schedules
with the new latest's identity. NoncurrentDays / NewerNoncurrent /
EXPIRED_DELETE_MARKER still pin the version_id since those are
version-targeted.

isVersionsDir gating on ExtLatestVersionIdKey lost a race window:
createDeleteMarker writes the version file before updating the
parent's Extended pointer, so a walk between those two steps would
see a .versions/ dir without the pointer, recurse into it, and emit
raw version files that the router drops. Match the suffix only and
let expandVersionsDir disambiguate by child inspection: if any child
carries ExtVersionIdKey it's a real .versions container and we expand;
otherwise it's a coincidentally-named user folder and we recurse via
the bucket-walk's own callback so nested entries still flow through.

Tests: latest-expiration assertion flipped to expect empty VersionID;
new tests cover the coincidentally-named-folder recursion and the
race-window expansion (children present, pointer absent).

* fix(s3/lifecycle): filter directory + missing-version-id children at listing

expandVersionsDir's listing callback collected every child with
attributes; subdirectories or entries without ExtVersionIdKey would
make it past the empty-id skip in the inner loop but still inflate
NumVersions and skew NoncurrentIndex (the rank derives from the
filtered slice's position, which was wrong when the unfiltered slice
was sorted). Drop directories at listing time and partition the
file children into a versions slice that's the actual rank source.

Test cleanups: out-of-order-mtime test now sets v1 older than v2 so
latestPos > 0 actually exercises the rank-skip branch in
expandVersionsDir; bootstrapVersionEntry preserves nanosecond
precision via MtimeNs to match markerLoneEntry's pattern; drop a
leftover unused idx variable.

* fix(s3/lifecycle): null version + canonical version-id tiebreak

Two correctness gaps in Phase 5b/3 bootstrap.

Null versions live at the bare logical path, not under .versions/.
Bootstrap previously expanded only .versions/<key>/ children, so:
  - pre-versioning objects with newer .versions/ history never had
    their null version expired by NoncurrentDays
  - suspended-bucket writes (which clear the .versions/ latest pointer
    so null becomes current) had every .versions/ child wrongly
    classified as latest by the buildObjectInfo fallback

expandVersionsDir now looks up the bare key via NewFullPath +
LookupEntry, accepts a regular file or an explicit S3 directory-key
marker (Mime set), and folds it into the sibling set with
VersionID="null". Latest resolution: pointer present + names a real
id wins; pointer absent + null exists makes null latest; otherwise
falls back to newest sibling. The walker's regular emission for the
bare entry would otherwise duplicate, so walkBucketDir now does a
two-pass walk per directory level — .versions/ first, then everything
else with a per-walk skipBare set keyed by bucket-relative path that
expandVersionsDir populates when it claims a bare null sibling.

Sort tiebreak: PUTs only set second-level Mtime, so two versions
written in the same second tied. The unstable secondary order let
old-format version filenames sort oldest-first and corrupt
NoncurrentIndex under NewerNoncurrentVersions retention. Add
CompareVersionIds to s3lifecycle/version_time.go (mirrors the
canonical comparator in s3api/s3api_version_id.go to avoid the
import cycle) and use it as a secondary key after mtime equality.

Tests: pre-versioning null-as-noncurrent, suspended null-as-current,
directory-key marker as null version, end-to-end claim through
walkBucketDir's two-pass ordering, and same-second tiebreak via
canonical version-id ordering. fakeFilerClient grows a
LookupDirectoryEntry implementation backed by the same in-memory tree.

* fix(s3/lifecycle): only treat explicit-null bare entries as current

The pointer-missing branch in expandVersionsDir made null latest as
soon as a bare object was found. That's correct for suspended-bucket
writes (s3api_object_handlers_put.go writes the bare entry with
ExtVersionIdKey="null") but wrong for the pre-versioning race window:
a brand-new version under .versions/<file> exists before the parent's
ExtLatestVersionIdKey update lands, and a pre-versioning bare object
has no version-id marker. Marking that older bare object latest hides
the real new version and skips noncurrent expiration of the null
until the next process restart/bootstrap.

Distinguish the two: lookupNullVersion now returns whether the bare
entry's Extended map carries ExtVersionIdKey="null" (the suspended
write marker). expandVersionsDir's pointer-missing branch only
promotes null to latest when explicit; otherwise it falls back to
newest-sibling, which is safe for the race window since the new
version's mtime is fresher than the bare object's.

The existing suspended-null test now uses a new helper that adds the
explicit marker. New regression test covers the race window: bare
entry without the marker + a fresh .versions/<v1> file + missing
parent pointer must keep v1 as latest and the null as noncurrent.

* fix(s3/lifecycle): only the newest item can be the explicit-null latest

The pointer-missing branch in expandVersionsDir scanned every item for
an explicit null and promoted it to latest. After a suspended->enabled
transition that's the wrong call: createVersion writes the version
file before updating ExtLatestVersionIdKey, so a bootstrap that lands
in the race window sees an older bare null with ExtVersionIdKey="null"
plus a newer .versions/<v-new> child and no parent pointer. Promoting
the null misclassifies v-new as noncurrent and skips both the new
version's current-version expiration and the null's noncurrent
scheduling until the next bootstrap.

Constrain the explicit-null branch to items[0]: if the suspended-null
write is genuinely current it'll be the newest by mtime AND tagged.
Anything else falls through to the newest-sibling default.

Adds a regression test for the suspended->re-enabled race.

* fix(s3/lifecycle): paginate bootstrap directory listings

SeaweedList(..., limit=0) is a single-page request: the filer caps
limit=0 at DirListingLimit (1000 by default) and returns whatever fits
in one round trip. expandVersionsDir and walkBucketDir both relied on
that, so any directory bigger than the cap silently truncated. For
noncurrent retention this is correctness, not just scale — a hot key
with more versions than the cap had its rank/sort math computed off
the first page only, NumVersions, NoncurrentIndex, SuccessorModTime,
and the latest-fallback all wrong, with the older versions never
scheduled until a future bootstrap.

Add a listAll helper that drives pagination via StartFromFileName +
inclusive=false, looping until a page returns fewer entries than the
configured page size. Use it in both call sites. Page size is a var
(listPageSize, default 1024) so tests can shrink it without
generating thousands of entries.

The fake filer client now mirrors the real semantics: sort children
by name, honor StartFromFileName/InclusiveStartFrom, cap at Limit.
New regression tests force a small page size and assert the full
result set is processed and the call count matches what pagination
should drive.

* perf(s3/lifecycle): stream bucket walk in two passes instead of buffering

walkBucketDir was paginating into a children slice and then iterating
twice (pass 1: .versions/, pass 2: everything else). For flat buckets
with millions of entries the buffer is a real memory spike. Drop the
materialization: each pass now drives its own listAll over the same
directory and acts on entries as they stream in. The skipBare ordering
contract is preserved — pass 2 still runs after pass 1 finishes — and
the per-pass paging keeps memory bounded by listPageSize.

Tradeoff: each directory level is listed twice. For workloads where
that matters more than the memory headroom, we can revisit; the
correctness/scale dial here is what the noncurrent rules need.

Updated three tests for the new call count: each walk now records 2
listings per directory (pass 1 + pass 2). The KickOffNew dedup tests
expect 2 calls per bucket; the pagination test expects 6 instead of 3.
2026-05-09 10:48:32 -07:00
Chris Lu 1c917ffacb fix(volume): sticky EIO quarantine; track streamed reads (#9384)
Two follow-ups on PR #9382:

1. Quarantine wasn't sticky. Once CollectHeartbeat crossed the streak
   threshold and hid the replica, a subsequent successful read called
   checkReadWriteError(nil), wiping the streak; the next heartbeat
   then re-announced the suspect replica as read-only and master could
   send reads back to a disk that already failed IoErrorTolerance.
   Added an ioErrorQuarantined sticky flag set on the first heartbeat
   that observes the threshold and cleared only by MarkVolumeWritable
   (resetIoErrorState). clearIoError continues to reset just the
   streak so successful ops don't accumulate phantom errors.

2. Streamed reads bypassed the EIO counter. readNeedleDataInto and
   ReadNeedleBlob — the hot paths for large/range GETs — returned
   ReadNeedleData / needle.ReadNeedleBlob errors without threading
   them through checkReadWriteError, so a disk failing only on those
   paths would never trip IoErrorTolerance. Both now route the
   backend error through the tracker, and a fully clean
   readNeedleDataInto call clears the streak.

Tests cover the sticky flag (TestQuarantineIsSticky) and the streamed
read path (TestReadNeedleBlobTracksEIO via a fake EIO backend).
2026-05-09 09:55:02 -07:00
Chris Lu 7c60407897 fix(volume): don't nuke local data on transient IO error (#9378) (#9382)
* fix(volume): don't nuke local data on transient IO error (#9378)

A single syscall.EIO from any read/write/delete set v.lastIoError, and
the next CollectHeartbeat then called Volume.Destroy on the replica —
removing the .dat/.idx/.vif/.sdx/.ldb/.rdb files. A brief NFS / fabric
/ controller blip hitting several replicas at once could cascade into
removal of the last healthy copy, with no recovery for non-tiered
volumes.

Now require IoErrorTolerance (3) consecutive EIOs before acting, and on
that threshold mark the volume read-only and stop announcing it to the
master so re-replication kicks in from healthy peers — never delete
the data files. The on-disk copy stays for operator inspection /
recovery.

* review: fix race, accounting, recovery, non-EIO streak break

Addressing PR #9382 review:

- Data race on lastIoError: guard lastIoError + lastIoErrorCount with a
  RWMutex and expose them through note/clear/get helpers so the
  heartbeat reader sees a consistent snapshot. Verified with -race.
- Collection-size accounting: when a volume is quarantined for sustained
  EIO, skip the entire per-volume bookkeeping (`continue`) instead of
  flipping shouldDeleteVolume — the old branch subtracted a size that
  was never added, dragging the collection gauge to zero / negative.
- Recoverability: MarkVolumeWritable now also calls clearIoError so an
  operator can rejoin a quarantined replica. The next failed op
  re-arms the streak if the disk is still bad.
- Non-EIO streak break: a non-EIO error (e.g. ENOSPC) now resets the
  consecutive-EIO counter, so a sequence EIO,EIO,ENOSPC,EIO is treated
  as a streak of one — the counter only tracks consecutive EIOs.

Reads already call checkReadWriteError (volume_read.go), so successful
reads also clear the streak — no change needed there.
2026-05-09 09:20:31 -07:00
Chris Lu c6ad6dcf74 feat(s3/lifecycle): sole-survivor delete-marker routing (Phase 5b/2) (#9381)
* feat(s3/lifecycle): sole-survivor delete-marker routing (Phase 5b/2)

Production stores delete markers under <object>.versions/<version-file>;
buildObjectInfo skips every version-folder event because it can't tell
current from noncurrent without sibling state. EXP_DM is the one rule
that can be routed from the file path alone: if the marker is the only
entry under .versions/<key>/ then it's necessarily the latest.

Add SiblingLister; gate the listing on (versioned, version-folder path,
delete-marker entry, EXP_DM rule active for the bucket, lister supplied)
so non-marker version writes pay nothing. The Match carries the LOGICAL
key in ObjectKey and the marker's version_id in VersionID so the
dispatcher can reach deleteSpecificObjectVersion(bucket, logical, vid);
without a version_id the dispatcher would BLOCK and freeze the cursor.

Server-side dispatch re-checks sole-survivor before deleting: another
PUT can land between schedule and dispatch, and identity-CAS only covers
the marker entry, not the directory shape. Lists .versions/<key>/ with
limit 2 and returns NOOP_RESOLVED if count != 1 or the surviving entry
is not the same version.

Fix isDeleteMarkerEntry to compare string(v) == "true" — production
writes []byte("true"), not {1}; every other reader of ExtDeleteMarkerKey
in this repo uses the string predicate.

filerSiblingLister.Count caps at limit 2 — callers only distinguish
"sole survivor" (1) from "more than one" (>=2).

Follows #9373.

* fix(s3/lifecycle): gate sibling listing on active event-driven EXP_DM

hasActionKind tested key presence only; an EXP_DM rule whose action was
inactive (BootstrapComplete=false) or scan-only would still trigger the
sibling-listing RPC even though no match could fire. Replace with a
helper that mirrors the per-key filter Route already applies before
emitting matches: kind matches, snap.Action returns non-nil, IsActive,
and Mode == ModeEventDriven.

Add a regression test that builds a versioned snapshot with the rule
but no PriorStates (action stays inactive) and asserts the lister is
never consulted.

* chore(s3/lifecycle): trim verbose comments

* fix(s3/lifecycle): null version, hard-delete trigger, latest pointer

Three correctness gaps in EXP_DM routing.

1. Null version. SiblingLister.Count saw only .versions/<key>/, but a
   pre-versioning bare-key object survives outside that folder when
   versioning is enabled later. Marker + null would look like count==1
   and EXP_DM would re-expose the old object. Replace Count with
   Survivors which also reports HasNullVersion; route- and dispatch-time
   suppress when set.

2. Hard-delete trigger. The router skipped events with NewEntry==nil so
   a noncurrent hard-delete that left the marker as sole survivor never
   fired EXP_DM. Allow version-folder hard-deletes through; the lister's
   LoneEntry carries the surviving marker's version_id and identity.

3. Latest pointer. checkSoleSurvivorMarker only checked count and
   filename. The worker can race createDeleteMarker between the file
   write and the .versions/ directory metadata update. Require
   ExtLatestVersionIdKey == versionId; missing pointer returns
   retry-later instead of deleting.

Adds a null-version exists check on the dispatch path too.

* fix(s3/lifecycle): normalize null-version lookup errors and detect dir markers

Two correctness bugs in the null-version check.

Route-side: filerSiblingLister called client.LookupDirectoryEntry
directly. SeaweedList wraps not-found via filer_pb.LookupEntry, which
normalizes the gRPC string-mapped not-found into ErrNotFound. The raw
client returns it as a generic error instead, so every absent
null-version (the common case) bubbled up as an error and the router
suppressed every otherwise-valid match. Use filer_pb.LookupEntry.

Both sides: explicit S3 directory-key markers (object names ending in /)
are stored as directory entries with Attributes.Mime set;
processExplicitDirectory in the listing path treats them as null
versions. The previous check was !IsDirectory only, which let the
marker delete proceed and re-expose the directory key. Add
IsDirectoryKeyObject() to both predicates. Also use
util.NewFullPath(...).DirAndName() for the parent/name split so a
trailing-slash key resolves to the same underlying entry path as the
listing code.

* fix(s3/lifecycle): EXP_DM ctx propagation, nil-entry guard, fast-path skip

Three small follow-ups on the EXP_DM dispatch path.

checkSoleSurvivorMarker now takes ctx instead of context.Background()
so worker shutdown / deadlines cancel the SeaweedList RPC instead of
stalling.

If SeaweedList fires the lone callback with entry==nil, firstName
stays empty and the marker-replaced check would short-circuit; that's
the one shape that bypasses the dispatch guard, so retry-later instead.

routeSoleSurvivorMarker now skips the Survivors RPC on regular
non-marker version creates — those always have Count >= 2, so the
listing was wasted load on every versioned write under an EXP_DM rule.
Hard-delete events (NewEntry==nil) and marker creates still flow
through. Added a regression test asserting the regular-create case
doesn't consult the lister.

Documented that logicalKeyFromVersionPath rejects bucket-root markers
intentionally.
2026-05-08 23:24:08 -07:00
Chris Lu 196c41d21a test(s3/lifecycle): cover scheduler/bootstrap walker + MPU detection (#9380)
Locks down isMPUInitDir, walkBucketDir (regular/nested/MPU/error/cancel
paths), and BucketBootstrapper.KickOffNew (per-bucket fanout and
in-process dedup) against a fake SeaweedFilerClient.
2026-05-08 22:14:45 -07:00
74 changed files with 11556 additions and 250 deletions

No files matched your search

+34 -25
View File
@@ -110,7 +110,9 @@ This is more state than the previous "single subscription, single cursor" claim
**Cursor-skip semantics.** `last_processed[filer_id]` points at the *last resolved event* for that shard. Resume must skip events with position `<= cursor[filer_id]` (using the `(ts, offset)` order per shard) — strict `<=`, not `<`, otherwise the last processed event is replayed on every resume. Equivalently: deliver events with `(event.ts, event.offset) > cursor[filer_id]`. Phase 3 introduces a new API variant that takes per-shard `MessagePosition`s and applies this comparator — see "API change" below. The existing `pb.ReadLogFileRefs` filter `logEntry.TsNs <= startTsNs` (`weed/pb/filer_pb_direct_read.go:333`) is the wrong shape because it can't disambiguate equal-ts events.
**Required API addition** (Phase 3 dependency): `pb.ReadLogFileRefsWithPosition` extending the current `ReadLogFileRefs`:
> **Implementation note:** the API addition described below was not built. The shipped reader uses `SubscribeMetadata` with a single global cursor (the filer's server-side `MetaAggregator` already does the merge). The pseudocode is preserved as design context for a future per-shard architecture.
**~~Required API addition~~ (Phase 3 dependency, not built)**: `pb.ReadLogFileRefsWithPosition` extending the current `ReadLogFileRefs`:
- Take a per-shard `start_positions: map<filer_id, MessagePosition>` instead of a single `startTsNs`.
- Per-event callback signature `eachLogEntry(event, filer_id, position) → CallbackResult`.
@@ -565,6 +567,8 @@ Policy changes during a bucket bootstrap: the bootstrap is bound to a specific `
### Reader — single subscription, client-side merge
> **Implementation note (post-Phase 3):** the production reader uses `client.SubscribeMetadata(...)` directly with a single global cursor. The filer's `SubscribeMetadata` server (`weed/server/filer_grpc_server_sub_meta.go`) already aggregates across peer filers — it reads disk-persisted logs from every filer via `sendLogFileRefs` then drains `MetaAggregator.MetaLogBuffer` for the in-memory tail — so the worker doesn't have to assemble its own multi-filer merge. The per-filer-shard cursor model below was designed before this was wired and was not built; the proto fields (`last_processed_original` map keyed by `filer_id`, `tail_drained_streams`) remain as forward-compat stubs. The pseudocode below describes the alternative the design considered, kept here for context. See "Multi-filer durability" and the obsoleted Phase 6 section.
The reader is one cluster-singleton task subscribed to one filer at a time. `Filer.CollectLogFileRefs(start_position, stop_ts)` returns chunk refs from log files in directory order. The worker passes those refs to `pb.ReadLogFileRefsWithPosition` (the new API — see Task #19), which heap-merges per-filer chunks by event ts client-side and applies the per-shard `(ts, offset)` skip filter. Chunk *bodies* are read in parallel from volume servers via the returned fileIds.
Cursors are per-filer-shard. `last_processed_original[D.seconds]` is `map<filer_id, MessagePosition>`; `MessagePosition = {ts_ns, offset}` disambiguates equal-ts events within a per-filer chunk. Resume skips events with `(event.ts, event.offset) <= cursor[filer_id]` — strict `<=` so the last resolved event isn't replayed.
@@ -1394,6 +1398,8 @@ Why a separate lane matters here:
### Multi-filer durability
> **Implementation note (post-Phase 3):** the worker did not end up building its own multi-filer merge. `SubscribeMetadata` on the filer server (`weed/server/filer_grpc_server_sub_meta.go:154`) routes through `MetaAggregator` when peer filers exist: it reads from every filer's disk-persisted logs first (via `sendLogFileRefs`/`Filer.CollectLogFileRefs`), then drains the aggregator's in-memory tail. Workers get an aggregated, durable stream from a single subscription. The per-filer-shard cursor architecture below describes what would be needed if the worker had to assemble the merge itself; we kept it here as design context and as a reference for the proto stubs (`LOST_LOG`, `tail_drained_streams`) that remain forward-compatible if the architecture ever changes. The genuine residual gap — auto-degrading the worker on `ResumeFromDiskError` — is tracked separately as a narrow follow-up rather than a Phase.
`MetaAggregator` is **in-memory only** — `weed/filer/meta_aggregator.go:39`: *"MetaAggregator only aggregates data 'on the fly'. The logs are not re-persisted to disk. The old data comes from what each LocalMetadata persisted on disk."*
So the aggregator can't be the worker's source of truth: a worker restart, a crash, or a peer outage all lose unpersisted aggregated events. The persistent source is per-filer logs at `/topics/.system/log/<date>/<hour-min>.<filerId>` — written by each filer for its own events, durable, and queryable via `Filer.CollectLogFileRefs` and `Filer.ReadPersistedLogBuffer`.
@@ -1904,11 +1910,13 @@ Phasing changed: **the back-stamp cannot be removed until the worker can take ov
## Phase 3 — Shared cluster reader + delay-group sweeps (non-versioned)
- Implement `s3.lifecycle.read` task: cluster singleton, subscribed to one filer at a time. `Filer.CollectLogFileRefs` returns chunk refs in directory order; the worker uses `pb.ReadLogFileRefsWithPosition` (Task #19) to heap-merge per-filer chunks by event ts client-side, with per-shard `MessagePosition` skip filtering. Worker reads chunk bodies in parallel from volume servers. Cursors are per-filer-shard: `last_processed_original: map<delay_seconds, map<filer_id, MessagePosition>>` and `last_processed_predicate: map<filer_id, MessagePosition>` — `LogEntry.Offset` is per-buffer (per filerId), not globally unique, so per-shard cursors are required. Resume skips events with `(ts, offset) <= cursor[filer_id]` (strict `<=`). Listing uses the low-water-mark across per-filer cursors. New shards seeded lazily via `seedNewlyDiscoveredShardsLazily` using `EarliestRetainedPositionPerShard` (Task #19), and seeding clears any matching `tail_drained_streams` marker. Tail-drain GC at task entry uses `RetainedLogRangePerShard` (Task #19) to remove cursor entries where `cursor >= range.latest`, record the matching `tail_drained_streams` key, and downgrade to `scan_only` with `LOST_LOG` if logs vanished before a stream caught up. Failover to another filer endpoint on connection error; per-filer cursor map is portable. Periodic checkpointing (default every 1000 events or 5s) bounds crash redo.
- **Tail-drain tests required in this phase**: (a) cursor at exactly `range.latest` for a shard → tail-drained, entry GC'd, matching `tail_drained_streams` key updated, low-water-mark recovers; (b) cursor before `range.latest` → not GC'd, entry preserved; (c) shard removed from cluster but logs still retained → not GC'd until each stream cursor catches up to `range.latest`; (d) verify low-water-mark advances after GC (otherwise the tail-drain wasn't effective); (e) **lost-log**: shard's logs pruned with a stream cursor still behind `range.latest` and no matching `tail_drained_streams[...]` marker → cursor NOT GC'd, all reader-driven rules promoted to `mode = scan_only` with `degraded_reason = LOST_LOG`, `lifecycle_lost_log_total{filer_id}` increments, warning log emitted; verify `s3.lifecycle.reseed -ack-lost-log --reason <text>` is the only path that clears the lost-log cursor entries and degraded flag together; (f) cross-stream guard: a tail-drained 30-day original stream does not permit GC of the same filer's 60-day original stream or predicate stream; (g) rejoin guard: when a previously tail-drained shard reappears and is lazily seeded, the matching `tail_drained_streams` marker is cleared.
> **Implementation note:** the shipped reader uses `client.SubscribeMetadata(...)` with a single global `(ts_ns, offset)` cursor (`weed/s3api/s3lifecycle/reader/reader.go`). The filer's `SubscribeMetadata` server already aggregates persisted + in-memory logs across peer filers, so the per-filer-shard cursor map and the `RetainedLogRangePerShard` / `EarliestRetainedPositionPerShard` filer RPCs (Task #19) were not built. The tail-drain matrix and lost-log tests below were written against that unbuilt architecture and are obsoleted; the only residual gap — auto-degrading on `ResumeFromDiskError` — is tracked as a separate narrow follow-up. The retention mode-gate, engine routing, predicate-change pass, SKIPPED_OBJECT_LOCK, TRANSPORT_ERROR, and cursor-trail tests remain valid and were exercised against the production reader/router/engine stack.
- Implement `s3.lifecycle.read` task: cluster singleton, subscribed to one filer at a time. ~~`Filer.CollectLogFileRefs` returns chunk refs in directory order; the worker uses `pb.ReadLogFileRefsWithPosition` (Task #19) to heap-merge per-filer chunks by event ts client-side, with per-shard `MessagePosition` skip filtering.~~ The shipped task uses a direct `SubscribeMetadata` subscription; the filer server-side does the multi-filer merge. Cursor is one global `(ts_ns, offset)` position resumed via `SinceNs`. Failover to another filer endpoint on connection error; cursor is portable (one ts). Periodic checkpointing bounds crash redo.
- ~~**Tail-drain tests required in this phase**~~ — obsoleted by the single-cursor architecture; see Phase 6 for context.
- **Retention mode-gate tests** (per `eventLogHorizon` table, kinds beyond age-based): inject a rule of each reader-driven kind and toggle `metaLogRetention` above and below `eventLogHorizon(rule) + bootstrapLookbackMin`; verify the rule is `event_driven` above and `scan_only` with `degraded_reason = RETENTION_BELOW_HORIZON` below. Cover `EXPIRATION_DAYS`, `NONCURRENT_DAYS`, `ABORT_MPU`, `NEWER_NONCURRENT`, `EXPIRED_DELETE_MARKER`. Verify `EXPIRATION_DATE` bypasses the gate regardless of retention.
- Engine drives event routing: `engine.MatchOriginalWrite(event, delay=D)` and `engine.MatchPredicateChange(event)`.
- **One sweep per delay group** (e.g. `1d`, `30d`, `60d`, `90d`); each sweep advances `reader_state.last_processed_original[D.seconds]` (a `map<filer_id, MessagePosition>` — per-shard cursors, not a single position). Single predicate-change sweep clamped to `min(now - smallDelay, now - flushSafetyLag)` advances `reader_state.last_processed_predicate` (also per-shard).
- **One sweep per delay group** (e.g. `1d`, `30d`, `60d`, `90d`); each sweep advances `reader_state.last_processed_original[D.seconds]` (a single global `(ts_ns, offset)` `MessagePosition`). Single predicate-change sweep clamped to `min(now - smallDelay, now - flushSafetyLag)` advances `reader_state.last_processed_predicate` (also a single global position).
- One filer fetch per event (`fetchLiveEntryOnce`), reused across all candidate rules.
- Per-event resolution-or-stop: `Resolved` outcomes advance the cursor; `TRANSPORT_ERROR` halts the batch and the cursor stays.
- Engine refreshes when the reader observes a lifecycle-xattr `UpdateEntry` event.
@@ -1941,20 +1949,26 @@ Phasing changed: **the back-stamp cannot be removed until the worker can take ov
- `AbortIncompleteMultipartUpload` driven by events under `.uploads/`.
- Tests covering: new version PUT, delete marker creation, non-current expiration, expired-delete-marker, MPU abort.
## Phase 6 — Multi-filer durable replay (mostly done in Phase 3)
## Phase 6 — Multi-filer durable replay (obsoleted)
The shared-reader design (Phase 3) already reads from the shared filer namespace, so multi-filer correctness is largely subsumed. This phase fills in:
**Status: not built. Architecture moved on; the production reader uses the filer's existing aggregation surface.**
- Per-shard cursors keyed by `filerId` are already in the reader-state proto (Phase 3).
- Filer-set discovery: list `/topics/.system/log/<date>/` and observe filerId suffixes (Phase 3).
- Tail-drain GC implementation using `RetainedLogRangePerShard` (Task #19): cursor entries where `cursor >= range.latest` are removed at task entry AND the stream-specific key is recorded in `reader_state.tail_drained_streams`. Phase 3 tests verify single-shard tail-drain; Phase 6 adds multi-filer convergence tests:
- Two filers actively writing, racing writes against the same key — events from both shards merged correctly, per-shard cursors advance independently.
- Filer A departs (stops writing); its logs are still retained → cursor for A continues to advance until A's `range.latest`; not GC'd before then.
- Filer A reaches `range.latest` for one stream (e.g. original delay 30d), then its logs are pruned: probe returns no range, but the matching `tail_drained_streams[(ORIGINAL,30d,A)]` entry is set → that stream cursor is GC'd as safe; no degradation.
- Filer A later reappears and writes retained logs for that same stream: lazy seeding creates a new cursor and clears `tail_drained_streams[(ORIGINAL,30d,A)]`, so the old safe-drain marker cannot mask a future lost-log event.
- **Lost-log: Filer A's logs are pruned BEFORE another stream cursor reaches `range.latest`** (probe returns no range AND the matching `tail_drained_streams[...]` entry is unset): the reader does NOT GC that cursor; instead, all reader-driven rules are promoted to `mode = scan_only` with `degraded_reason = LOST_LOG`; `lifecycle_lost_log_total{filer_id="A"}` increments; warning logged. Verify cursor stays put until `s3.lifecycle.reseed -ack-lost-log --reason <text>` clears the lost-log cursor entries and degraded flag.
- Worker restart mid-merge → resumes per-filer cursors correctly; both shards continue from their persisted positions; `tail_drained_streams` survives restart.
- Failover to a different primary filer mid-batch — cursor portable, no events skipped or replayed.
What the original Phase 6 set out to add — per-filer-shard cursor maps, `EarliestRetainedPositionPerShard` and `RetainedLogRangePerShard` filer RPCs, `tail_drained_streams` GC, `CollectLogFileRefs` heap-merge, lost-log degraded promotion — was designed under the assumption that the lifecycle worker would have to assemble its own multi-filer view because `MetaAggregator` is in-memory only.
`SubscribeMetadata` already does that work server-side: when the filer has peer filers it reads disk-persisted logs from every filer first (via `sendLogFileRefs` → `Filer.CollectLogFileRefs`) and only then drains the in-memory aggregator. A single subscription returns a durable, multi-filer-merged stream. The Phase 3 shipped reader (`weed/s3api/s3lifecycle/reader/reader.go`) consumes that stream with one global `(ts_ns, offset)` cursor and never needed the per-shard cursor map.
What the design's per-shard architecture would have bought us, and why each piece is no longer required:
| Phase 6 mechanism | Why it's no longer required |
|---|---|
| Per-filer-shard cursor map | Single global cursor suffices because the filer presents one merged stream. Resume-replay overhead is bounded by `LogFlushInterval` (~1m) and the dispatcher's tick interval (~200ms), so the worst-case redundant work per batch is one minute of events that the cursor compare immediately skips. |
| `RetainedLogRangePerShard` / `EarliestRetainedPositionPerShard` filer RPCs | No per-shard cursor → no need for per-shard probe. `SubscribeMetadata` already returns `ResumeFromDiskError` when the cursor predates retained logs. |
| Tail-drain GC + `tail_drained_streams` | No per-shard cursor → no entries to GC. Departed filers' events are absorbed into the aggregated stream and the global cursor advances past them. |
| Lazy seeding `seedNewlyDiscoveredShardsLazily` | No per-shard cursor → no shards to seed. New filers' events appear automatically through the aggregator. |
Forward-compat stubs that stay in the proto: `LifecycleState.DegradedReason.LOST_LOG`, `ReaderState.tail_drained_streams`, `last_processed_original` keyed by `filer_id`. They cost nothing and keep the on-disk state file readable if a future deployment ever needs a per-shard architecture.
The single residual gap — and the only piece worth building — is auto-degrading the reader when `SubscribeMetadata` returns `ResumeFromDiskError`. Tracked as a separate narrow follow-up (catch the error in `reader.Run`, mark reader-driven actions `scan_only` with `degraded_reason = LOST_LOG`, increment the counter, advance the cursor to retained-earliest, expose `s3.lifecycle.reseed -ack-lost-log` to flip back to event_driven once safety scans cover the gap). It is a ~50-line change, not a Phase.
## Phase 7 — Observability
@@ -1979,7 +1993,7 @@ The shared-reader design (Phase 3) already reads from the shared filer namespace
- Date-rule deletions (`SCAN_AT_DATE` mode: a single scheduled bucket-level bootstrap at `rule.date` deletes all matches inline).
- Periodic safety scans (re-run bootstrap on the per-kind cadence) catch drift over time.
Not-yet-due age-based discovery via meta-log events arrives in Phase 3 (the reader). Versioned buckets remain unhandled until Phase 5; the worker skips them with a logged warning until then. The existing back-stamp keeps simple `Expiration.Days` working in parallel.
- Phase 3 brings steady-state event-driven expiration. The reader is a cluster singleton subscribed to one filer; the worker heap-merges per-filer log chunks client-side via `pb.ReadLogFileRefsWithPosition` (Task #19) with per-shard `MessagePosition` cursors. Multi-filer clusters work the same as single-filer clusters from this point forward.
- Phase 3 brings steady-state event-driven expiration. The reader is a cluster singleton subscribed to one filer via `SubscribeMetadata`, which the filer's `MetaAggregator` already merges across peer filers. Single global `(ts_ns, offset)` cursor; multi-filer clusters work the same as single-filer clusters from this point forward.
- Phase 4 makes `PUT` constant-time. Required dependency: Phase 2 + Phase 3 shipped and stable.
- Phases 5–8 complete the surface.
@@ -2073,16 +2087,11 @@ test-fast: build-weed-10sec
Run: `make -C test/s3/lifecycle test-with-server`. Phase mapping: end-to-end tests land in the same phase as the capability they cover.
## Layer 4 — Multi-filer convergence (Phase 6 only)
## Layer 4 — Multi-filer convergence (obsoleted)
Location: `test/plugin_workers/lifecycle/multi_filer_test.go` (component) plus a multi-filer scenario in `test/s3/lifecycle/` if needed.
**Not built.** Phase 6 was obsoleted by `SubscribeMetadata`'s server-side aggregation (see the Phase 6 section). With a single global cursor on a server-merged stream, there are no per-filer-shard convergence properties for the worker to test — any merge correctness lives inside the filer's `MetaAggregator`, which has its own coverage in `weed/filer/`.
Patterns to copy: `test/multi_master/`, `test/metadata_subscribe/` — both spin up multi-node clusters in-process.
Cases:
- Racing writes to the same key on different filers, **including events with identical `event.ts`** — reader merges per-filer logs by `(event.ts, filer_id, event.offset)` (deterministic ordering across shards because `event.offset` is per-buffer/per-filer and not globally unique). Test asserts the same merge order across runs and that equal-ts events from different filers don't swap relative position.
- Worker restart mid-merge → resumes per-filer watermarks correctly.
- Filer leaves cluster → topology refresh skips it; remaining filers' logs continue.
If `ResumeFromDiskError` auto-degrade lands as a follow-up (task #21), its tests live with the reader package, not in a separate multi-filer harness.
## CI gating
@@ -0,0 +1,79 @@
// Bootstrap-walk integration scenario: lifecycle config added AFTER the
// objects exist must still expire them on the first sweep.
package lifecycle
import (
"context"
"fmt"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/stretchr/testify/require"
)
// TestLifecycleBootstrapWalkOnExistingObjects: PUT a batch of objects
// FIRST, backdate them, THEN configure the lifecycle rule, THEN run
// the worker. The worker must discover the pre-existing objects via
// the bootstrap walk (BucketBootstrapper) — there were no meta-log
// events the reader could have observed because the objects predate
// the rule.
//
// Production scenario: an operator enables lifecycle on a bucket that
// already holds a million objects from before the policy. Without a
// bootstrap walk, only NEW writes would ever match; the existing
// content would never expire.
func TestLifecycleBootstrapWalkOnExistingObjects(t *testing.T) {
c := s3Client(t)
fc, fcClose := filerClient(t)
defer fcClose()
bucket := uniqueBucket("bootstrap")
mustCreateBucket(t, c, bucket)
// 5 objects so the test exercises the walker iterating multiple
// entries in the same bucket directory. PUT FIRST, before any
// lifecycle config is set, so the meta-log doesn't carry events
// that match any rule.
const total = 5
keys := make([]string, total)
for i := 0; i < total; i++ {
keys[i] = fmt.Sprintf("preexisting/obj-%02d.txt", i)
putObject(t, c, bucket, keys[i], "content")
backdateMtime(t, fc, bucket, keys[i], 30)
}
// One out-of-prefix object that must NOT be expired. Same
// pre-existing PUT timing.
const survivor = "other/keep.txt"
putObject(t, c, bucket, survivor, "keep")
backdateMtime(t, fc, bucket, survivor, 30)
// NOW set the rule. Up to this point the worker (if it were
// running event-driven only) would have nothing matching to do.
putExpirationLifecycle(t, c, bucket, "preexisting/", 1)
out := runLifecycleShard(t)
t.Logf("shell output:\n%s", out)
// Every pre-existing in-prefix object must be expired by the
// bootstrap walk's discovery + dispatch.
for _, k := range keys {
k := k
require.Eventuallyf(t, func() bool {
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(k),
})
return isS3NotFound(err)
}, 30*time.Second, 500*time.Millisecond,
"pre-existing %s/%s must be discovered + expired by bootstrap walk", bucket, k)
}
// Out-of-prefix object stays — pin that the bootstrap walk
// doesn't ignore the rule's prefix filter.
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(survivor),
})
require.NoError(t, err, "out-of-prefix object must survive the bootstrap walk")
}
@@ -0,0 +1,79 @@
// Lifecycle config update across sweeps.
package lifecycle
import (
"context"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/stretchr/testify/require"
)
// TestLifecycleConfigUpdateBetweenSweeps: an operator changes the
// lifecycle rule between two shell-driven sweeps. The second sweep
// must respect the NEW rule, not a cached version of the old one.
//
// Each `runLifecycleShard` invocation spawns a fresh `weed shell`
// subprocess, so cached engine state from a previous sweep doesn't
// persist across runs. This test pins that the freshly-loaded config
// actually changes routing — under the new prefix only matching
// objects expire, even if there are still backdated objects sitting
// under the old prefix.
func TestLifecycleConfigUpdateBetweenSweeps(t *testing.T) {
c := s3Client(t)
fc, fcClose := filerClient(t)
defer fcClose()
bucket := uniqueBucket("config-update")
mustCreateBucket(t, c, bucket)
// Sweep 1: rule expires anything under "first/".
putExpirationLifecycle(t, c, bucket, "first/", 1)
const firstKey = "first/initial.txt"
putObject(t, c, bucket, firstKey, "first")
backdateMtime(t, fc, bucket, firstKey, 30)
out := runLifecycleShard(t)
t.Logf("sweep 1 output:\n%s", out)
require.Eventuallyf(t, func() bool {
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(firstKey),
})
return isS3NotFound(err)
}, 30*time.Second, 500*time.Millisecond, "sweep 1 must expire %s", firstKey)
// Update the rule to a different prefix. The old "first/" prefix
// is no longer covered by any rule; objects under it must NOT be
// expired by sweep 2 even when backdated.
putExpirationLifecycle(t, c, bucket, "second/", 1)
const secondKey = "second/new.txt"
const oldPrefixKey = "first/post-update.txt"
putObject(t, c, bucket, secondKey, "second")
putObject(t, c, bucket, oldPrefixKey, "stale rule")
backdateMtime(t, fc, bucket, secondKey, 30)
backdateMtime(t, fc, bucket, oldPrefixKey, 30)
out = runLifecycleShard(t)
t.Logf("sweep 2 output:\n%s", out)
// Sweep 2 expires the new-prefix object.
require.Eventuallyf(t, func() bool {
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(secondKey),
})
return isS3NotFound(err)
}, 30*time.Second, 500*time.Millisecond, "sweep 2 must expire %s under the new rule", secondKey)
// Sweep 2 must NOT expire the old-prefix object — the rule was
// replaced, not merged. A regression that caches old rules across
// PutBucketLifecycleConfiguration calls would fail here.
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(oldPrefixKey),
})
require.NoError(t, err, "old-prefix object must survive after rule update — config replacement, not merge")
}
@@ -0,0 +1,67 @@
// Operator-removes-lifecycle-config integration scenario.
package lifecycle
import (
"context"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/stretchr/testify/require"
)
// TestLifecycleDeleteBucketLifecycleStopsDispatching: when an operator
// runs DeleteBucketLifecycle, subsequent sweeps must NOT continue
// expiring objects under the now-removed rule. The worker reads each
// bucket's XML config from filer state on every run; if it cached the
// previous config across PutBucketLifecycleConfiguration → DeleteBucket
// Lifecycle the bucket would keep losing objects.
//
// Setup: positive control (rule active, backdated obj expires), then
// DeleteBucketLifecycle, then PUT + backdate a fresh object, run the
// worker again. The fresh object must remain — no rule, no dispatch.
func TestLifecycleDeleteBucketLifecycleStopsDispatching(t *testing.T) {
c := s3Client(t)
fc, fcClose := filerClient(t)
defer fcClose()
bucket := uniqueBucket("delete-config")
mustCreateBucket(t, c, bucket)
putExpirationLifecycle(t, c, bucket, "x/", 1)
const firstKey = "x/initial.txt"
putObject(t, c, bucket, firstKey, "first")
backdateMtime(t, fc, bucket, firstKey, 30)
out := runLifecycleShard(t)
t.Logf("sweep 1 output (rule active):\n%s", out)
require.Eventuallyf(t, func() bool {
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(firstKey),
})
return isS3NotFound(err)
}, 30*time.Second, 500*time.Millisecond, "positive control: %s should expire while rule is active", firstKey)
// Now remove the rule. The worker must observe the removal on the
// next sweep.
_, err := c.DeleteBucketLifecycle(context.Background(), &s3.DeleteBucketLifecycleInput{
Bucket: aws.String(bucket),
})
require.NoError(t, err)
const survivorKey = "x/post-delete.txt"
putObject(t, c, bucket, survivorKey, "should-stay")
backdateMtime(t, fc, bucket, survivorKey, 30)
out = runLifecycleShard(t)
t.Logf("sweep 2 output (rule deleted):\n%s", out)
// Wait the same window; survivor MUST still exist after the worker
// has had every opportunity to (incorrectly) act on it.
time.Sleep(2 * time.Second)
_, err = c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(survivorKey),
})
require.NoError(t, err, "after DeleteBucketLifecycle, sweeps must not expire %s", survivorKey)
}
@@ -0,0 +1,46 @@
// Empty bucket sweep — no-op safety integration scenario.
package lifecycle
import (
"context"
"strings"
"testing"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/stretchr/testify/require"
)
// TestLifecycleEmptyBucketSweepIsNoOp: a bucket carrying lifecycle
// config but no objects must produce a successful sweep — no hangs,
// no errors, no dispatches. Pinned because the bootstrap walker
// iterates bucket directories, and an empty directory is a corner of
// that traversal that's easy to break (e.g. a slice-bounds bug on
// the first listing returning zero entries).
func TestLifecycleEmptyBucketSweepIsNoOp(t *testing.T) {
c := s3Client(t)
_, fcClose := filerClient(t)
defer fcClose()
bucket := uniqueBucket("empty")
mustCreateBucket(t, c, bucket)
putExpirationLifecycle(t, c, bucket, "anywhere/", 1)
// No PUTs. The bucket is empty.
out := runLifecycleShard(t)
t.Logf("sweep output:\n%s", out)
// Sanity: the worker must report it loaded the bucket's config and
// completed without errors. The runLifecycleShard helper already
// fails on FATAL; pin the success markers here too so a regression
// that produces a half-shaped output (no completion) is caught.
require.Contains(t, out, "loaded lifecycle for", "worker must report config load")
require.Contains(t, out, "shards 0-15 complete", "worker must complete all shards")
require.False(t, strings.Contains(out, "FATAL"), "worker must not produce FATAL output")
// Bucket still exists after the sweep — the worker doesn't drop
// empty buckets as a side effect.
_, err := c.HeadBucket(context.Background(), &s3.HeadBucketInput{Bucket: aws.String(bucket)})
require.NoError(t, err, "empty bucket must still exist after sweep")
}
@@ -0,0 +1,75 @@
// ExpirationDate (date-based, not Days) integration scenario.
package lifecycle
import (
"context"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
"github.com/stretchr/testify/require"
)
// TestLifecycleExpirationDateInThePast: an Expiration{Date: <past>} rule
// routes through the engine's ScanAtDate mode rather than the
// EventDriven delay-group path. The worker's dispatcher must still fire
// when the date has already passed at the time the worker runs. Pinning
// this path because most tests use Days-based rules; ScanAtDate is a
// separate compile + dispatch branch (engine.decideMode case
// ActionKindExpirationDate) that wouldn't be exercised otherwise.
func TestLifecycleExpirationDateInThePast(t *testing.T) {
c := s3Client(t)
fc, fcClose := filerClient(t)
defer fcClose()
bucket := uniqueBucket("expdate")
mustCreateBucket(t, c, bucket)
// Date in the past: AWS rejects ExpirationDate in the future from
// being processed early but a past date is the natural integration
// test — every object hit by the rule is immediately eligible.
pastDate := time.Now().Add(-7 * 24 * time.Hour).UTC().Truncate(24 * time.Hour)
_, err := c.PutBucketLifecycleConfiguration(context.Background(), &s3.PutBucketLifecycleConfigurationInput{
Bucket: aws.String(bucket),
LifecycleConfiguration: &types.BucketLifecycleConfiguration{
Rules: []types.LifecycleRule{{
ID: aws.String("expire-by-date"),
Status: types.ExpirationStatusEnabled,
Filter: &types.LifecycleRuleFilter{Prefix: aws.String("d/")},
Expiration: &types.LifecycleExpiration{
Date: aws.Time(pastDate),
},
}},
},
})
require.NoError(t, err)
const oldKey = "d/in-prefix.txt"
const otherKey = "other/skip.txt"
putObject(t, c, bucket, oldKey, "old")
putObject(t, c, bucket, otherKey, "other")
// Backdate oldKey too — defense-in-depth so the test doesn't
// depend on whether the worker also considers MinTriggerAge for
// date kinds; a fresh object with a past date should still expire,
// but aging it locks the assertion either way.
backdateMtime(t, fc, bucket, oldKey, 30)
out := runLifecycleShard(t)
t.Logf("shell output:\n%s", out)
require.Eventuallyf(t, func() bool {
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(oldKey),
})
return isS3NotFound(err)
}, 30*time.Second, 500*time.Millisecond, "%s/%s must be expired by past-date rule", bucket, oldKey)
// Out-of-prefix object stays — the rule's Filter.Prefix gates this.
_, err = c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(otherKey),
})
require.NoError(t, err, "object outside the rule's prefix must remain")
}
+136
View File
@@ -0,0 +1,136 @@
// AbortIncompleteMultipartUpload integration scenario.
package lifecycle
import (
"context"
"strings"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/stretchr/testify/require"
)
// putAbortMPULifecycle wires AbortIncompleteMultipartUpload on a prefix.
// AWS rejects DaysAfterInitiation < 1, so the test backdates the upload
// directory to age it past the threshold.
func putAbortMPULifecycle(t *testing.T, c *s3.Client, bucket, prefix string, days int32) {
t.Helper()
_, err := c.PutBucketLifecycleConfiguration(context.Background(), &s3.PutBucketLifecycleConfigurationInput{
Bucket: aws.String(bucket),
LifecycleConfiguration: &types.BucketLifecycleConfiguration{
Rules: []types.LifecycleRule{
{
ID: aws.String("abort-stale-mpu"),
Status: types.ExpirationStatusEnabled,
Filter: &types.LifecycleRuleFilter{Prefix: aws.String(prefix)},
AbortIncompleteMultipartUpload: &types.AbortIncompleteMultipartUpload{
DaysAfterInitiation: aws.Int32(days),
},
},
},
},
})
require.NoError(t, err)
}
// backdateUploadDir ages the .uploads/<uploadID>/ directory entry, which is
// what the lifecycle worker keys ABORT_MPU off of (the upload's init-time
// directory carries the destination key in Extended).
func backdateUploadDir(t *testing.T, fc filer_pb.SeaweedFilerClient, bucket, uploadID string, daysOld int) {
t.Helper()
dir := bucketsPath + "/" + bucket + "/.uploads"
resp, err := fc.LookupDirectoryEntry(context.Background(), &filer_pb.LookupDirectoryEntryRequest{
Directory: dir, Name: uploadID,
})
require.NoError(t, err, "lookup .uploads/%s", uploadID)
require.NotNil(t, resp.Entry)
require.NotNil(t, resp.Entry.Attributes)
require.True(t, resp.Entry.IsDirectory, ".uploads/%s should be a directory", uploadID)
resp.Entry.Attributes.Mtime = time.Now().Add(-time.Duration(daysOld) * 24 * time.Hour).Unix()
resp.Entry.Attributes.MtimeNs = 0
_, err = fc.UpdateEntry(context.Background(), &filer_pb.UpdateEntryRequest{
Directory: dir, Entry: resp.Entry,
})
require.NoError(t, err)
}
// TestLifecycleAbortIncompleteMultipartUpload: an MPU left incomplete past
// the AbortIncompleteMultipartUpload.DaysAfterInitiation threshold must be
// aborted by the lifecycle worker. Exercises the lifecycleAbortMPU handler
// path which is otherwise unreachable from the prefix-based expiration
// tests (the routing keys off of `.uploads/<id>/` directory events, not
// regular object events).
func TestLifecycleAbortIncompleteMultipartUpload(t *testing.T) {
c := s3Client(t)
fc, fcClose := filerClient(t)
defer fcClose()
bucket := uniqueBucket("abort-mpu")
mustCreateBucket(t, c, bucket)
putAbortMPULifecycle(t, c, bucket, "uploads/", 1)
// Initiate an MPU, upload a single part, then leave it. CompleteMultipart
// would consume the upload; AbortMultipart would explicitly abort. We do
// neither so the lifecycle worker is the path that ends it.
const key = "uploads/big.bin"
createOut, err := c.CreateMultipartUpload(context.Background(), &s3.CreateMultipartUploadInput{
Bucket: aws.String(bucket), Key: aws.String(key),
})
require.NoError(t, err)
uploadID := aws.ToString(createOut.UploadId)
require.NotEmpty(t, uploadID)
// Upload one part so the directory carries the right shape.
_, err = c.UploadPart(context.Background(), &s3.UploadPartInput{
Bucket: aws.String(bucket),
Key: aws.String(key),
UploadId: aws.String(uploadID),
PartNumber: aws.Int32(1),
Body: strings.NewReader("part 1 contents"),
})
require.NoError(t, err)
// Sanity: ListMultipartUploads sees our pending upload before the
// worker runs.
listOut, err := c.ListMultipartUploads(context.Background(), &s3.ListMultipartUploadsInput{
Bucket: aws.String(bucket),
})
require.NoError(t, err)
var foundBefore bool
for _, u := range listOut.Uploads {
if aws.ToString(u.UploadId) == uploadID {
foundBefore = true
break
}
}
require.True(t, foundBefore, "upload %s should be visible before the worker runs", uploadID)
// Backdate the upload directory entry so the rule's DaysAfterInitiation
// threshold is satisfied. The router walks .uploads/ and emits an
// MPU-init event for each entry.
backdateUploadDir(t, fc, bucket, uploadID, 30)
out := runLifecycleShard(t)
t.Logf("shell output:\n%s", out)
// The upload must no longer appear in ListMultipartUploads.
require.Eventuallyf(t, func() bool {
listOut, err := c.ListMultipartUploads(context.Background(), &s3.ListMultipartUploadsInput{
Bucket: aws.String(bucket),
})
if err != nil {
return false
}
for _, u := range listOut.Uploads {
if aws.ToString(u.UploadId) == uploadID {
return false
}
}
return true
}, 30*time.Second, 500*time.Millisecond, "upload %s must be aborted by the lifecycle worker", uploadID)
}
@@ -0,0 +1,90 @@
// Multiple-bucket integration scenario.
package lifecycle
import (
"context"
"errors"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
smithyhttp "github.com/aws/smithy-go/transport/http"
"github.com/stretchr/testify/require"
)
// isS3NotFound recognizes a NotFound (NoSuchKey/404) response from the
// AWS SDK. Treating any HeadObject error as "deleted" lets a transport
// failure or dead endpoint mask a real bug, so callers that need to
// prove deletion specifically should use this.
func isS3NotFound(err error) bool {
if err == nil {
return false
}
var nsk *types.NoSuchKey
if errors.As(err, &nsk) {
return true
}
var notFound *types.NotFound
if errors.As(err, &notFound) {
return true
}
var apiErr *smithyhttp.ResponseError
if errors.As(err, &apiErr) {
return apiErr.HTTPStatusCode() == 404
}
return false
}
// TestLifecycleMultipleBucketsInOneSweep: a single shell-driven shard
// sweep must process every bucket carrying lifecycle config, not just
// the first one alphabetically. Pinned because the scheduler iterates
// the buckets directory and a regression that returns early after the
// first match would silently disable lifecycle for every later bucket.
//
// Two buckets, each with its own 1-day prefix-expiration rule and one
// backdated object. After the worker runs, both objects must be gone.
func TestLifecycleMultipleBucketsInOneSweep(t *testing.T) {
c := s3Client(t)
fc, fcClose := filerClient(t)
defer fcClose()
bucketA := uniqueBucket("multi-a")
bucketB := uniqueBucket("multi-b")
mustCreateBucket(t, c, bucketA)
mustCreateBucket(t, c, bucketB)
putExpirationLifecycle(t, c, bucketA, "exp/", 1)
putExpirationLifecycle(t, c, bucketB, "exp/", 1)
const keyA = "exp/a.txt"
const keyB = "exp/b.txt"
putObject(t, c, bucketA, keyA, "a")
putObject(t, c, bucketB, keyB, "b")
backdateMtime(t, fc, bucketA, keyA, 30)
backdateMtime(t, fc, bucketB, keyB, 30)
out := runLifecycleShard(t)
t.Logf("shell output:\n%s", out)
// Both buckets must have their objects expired in this single sweep.
for _, c2 := range []struct {
bucket, key string
}{
{bucketA, keyA},
{bucketB, keyB},
} {
c2 := c2
require.Eventuallyf(t, func() bool {
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(c2.bucket), Key: aws.String(c2.key),
})
// Pin: only count 404 / NoSuchKey as deletion. Any other
// error (transport failure, dead endpoint, auth) would
// otherwise mask a real bug as a "passed" test.
return isS3NotFound(err)
}, 30*time.Second, 500*time.Millisecond,
"%s/%s must be expired by the multi-bucket sweep", c2.bucket, c2.key)
}
}
@@ -0,0 +1,94 @@
// Multiple-rules-per-bucket integration scenario.
package lifecycle
import (
"context"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
"github.com/stretchr/testify/require"
)
// TestLifecycleMultipleRulesInOneBucket: a single bucket carries two
// independent Expiration rules with disjoint prefix filters and
// different Days thresholds. Each rule must fire only on its prefix
// and ignore the other; objects outside both prefixes must survive.
//
// Pinned because compile.Compile builds one CompiledAction per rule
// per kind, all sharing the same bucket index. A bug that lets one
// rule's prefix or threshold leak into the other (e.g. last-write-
// wins on a shared map) would silently expire wrong objects.
func TestLifecycleMultipleRulesInOneBucket(t *testing.T) {
c := s3Client(t)
fc, fcClose := filerClient(t)
defer fcClose()
bucket := uniqueBucket("multi-rule")
mustCreateBucket(t, c, bucket)
_, err := c.PutBucketLifecycleConfiguration(context.Background(), &s3.PutBucketLifecycleConfigurationInput{
Bucket: aws.String(bucket),
LifecycleConfiguration: &types.BucketLifecycleConfiguration{
Rules: []types.LifecycleRule{
{
ID: aws.String("logs-1d"),
Status: types.ExpirationStatusEnabled,
Filter: &types.LifecycleRuleFilter{Prefix: aws.String("logs/")},
Expiration: &types.LifecycleExpiration{Days: aws.Int32(1)},
},
{
ID: aws.String("tmp-7d"),
Status: types.ExpirationStatusEnabled,
Filter: &types.LifecycleRuleFilter{Prefix: aws.String("tmp/")},
Expiration: &types.LifecycleExpiration{Days: aws.Int32(7)},
},
},
},
})
require.NoError(t, err)
const logsKey = "logs/access.log"
const tmpKey = "tmp/scratch.bin"
const otherKey = "data/keep.bin"
putObject(t, c, bucket, logsKey, "log entry")
putObject(t, c, bucket, tmpKey, "scratch")
putObject(t, c, bucket, otherKey, "important")
// Backdate logs/ past the 1d rule, tmp/ past the 7d rule, data/
// past both thresholds — but data/ matches no rule, so it must
// survive regardless of age.
backdateMtime(t, fc, bucket, logsKey, 30)
backdateMtime(t, fc, bucket, tmpKey, 30)
backdateMtime(t, fc, bucket, otherKey, 30)
out := runLifecycleShard(t)
t.Logf("shell output:\n%s", out)
// logs/ rule fires.
require.Eventuallyf(t, func() bool {
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(logsKey),
})
return isS3NotFound(err)
}, 30*time.Second, 500*time.Millisecond, "logs/ rule must expire %s", logsKey)
// tmp/ rule fires.
require.Eventuallyf(t, func() bool {
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(tmpKey),
})
return isS3NotFound(err)
}, 30*time.Second, 500*time.Millisecond, "tmp/ rule must expire %s", tmpKey)
// data/ matches NEITHER rule and must survive — pinning that the
// per-rule prefix gate is independent and additive, not a global
// "any rule's prefix" check.
_, err = c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(otherKey),
})
require.NoError(t, err, "object outside both rule prefixes must survive")
}
@@ -0,0 +1,110 @@
// NewerNoncurrentVersions integration scenario.
package lifecycle
import (
"context"
"strings"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
"github.com/stretchr/testify/require"
)
// putNewerNoncurrentLifecycle keeps the N most recent noncurrent versions
// and expires the rest. NoncurrentDays is required by the AWS XML schema
// alongside NewerNoncurrentVersions; keeping it at 1 means the rule fires
// as soon as a version moves past the keep-count and is older than 1 day.
func putNewerNoncurrentLifecycle(t *testing.T, c *s3.Client, bucket, prefix string, keep int32) {
t.Helper()
_, err := c.PutBucketLifecycleConfiguration(context.Background(), &s3.PutBucketLifecycleConfigurationInput{
Bucket: aws.String(bucket),
LifecycleConfiguration: &types.BucketLifecycleConfiguration{
Rules: []types.LifecycleRule{
{
ID: aws.String("keep-newest-noncurrent"),
Status: types.ExpirationStatusEnabled,
Filter: &types.LifecycleRuleFilter{Prefix: aws.String(prefix)},
NoncurrentVersionExpiration: &types.NoncurrentVersionExpiration{
NewerNoncurrentVersions: aws.Int32(keep),
NoncurrentDays: aws.Int32(1),
},
},
},
},
})
require.NoError(t, err)
}
// TestLifecycleNewerNoncurrentVersions: NewerNoncurrentVersions=1 keeps
// only the most recent noncurrent version; older noncurrent versions
// must be deleted. PUT v1, v2, v3, v4 (v4 current; v1-v3 noncurrent),
// backdate v1, v2, v3, run the worker, expect v3 (newest noncurrent)
// and v4 (current) to remain, v1 and v2 to be removed.
//
// This routes through routePointerTransition's "needs full expansion"
// path — distinct from the per-version NoncurrentDays path because
// the rule depends on per-version rank, not just per-version age.
func TestLifecycleNewerNoncurrentVersions(t *testing.T) {
c := s3Client(t)
fc, fcClose := filerClient(t)
defer fcClose()
bucket := uniqueBucket("newer-nc")
mustCreateBucket(t, c, bucket)
putVersioningEnabled(t, c, bucket)
putNewerNoncurrentLifecycle(t, c, bucket, "n/", 1)
const key = "n/obj.txt"
puts := make([]string, 4) // versionIds in PUT order
for i := range puts {
out, err := c.PutObject(context.Background(), &s3.PutObjectInput{
Bucket: aws.String(bucket), Key: aws.String(key),
Body: strings.NewReader(time.Now().Format(time.RFC3339Nano) + "-" + string(rune('a'+i))),
})
require.NoError(t, err)
puts[i] = aws.ToString(out.VersionId)
require.NotEmpty(t, puts[i])
}
v1, v2, v3, v4 := puts[0], puts[1], puts[2], puts[3]
require.NotEqual(t, v1, v2)
require.NotEqual(t, v3, v4)
// Backdate every noncurrent (v1, v2, v3) so all three satisfy the
// NoncurrentDays>=1 floor; the keep-newest-1 logic then chooses
// which to drop.
for _, vid := range []string{v1, v2, v3} {
backdateVersionedMtime(t, fc, bucket, key, vid, 30)
}
out := runLifecycleShard(t)
t.Logf("shell output:\n%s", out)
// v1 and v2 (older noncurrent) must be expired.
for _, vid := range []string{v1, v2} {
vid := vid
require.Eventuallyf(t, func() bool {
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(key), VersionId: aws.String(vid),
})
return err != nil
}, 30*time.Second, 500*time.Millisecond, "older noncurrent version %s must be expired", vid)
}
// v3 (newest noncurrent within the keep=1 window) must remain.
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(key), VersionId: aws.String(v3),
})
require.NoError(t, err, "v3 (newest noncurrent within keep=1) must survive")
// v4 (current) must remain — current versions are immune to
// NoncurrentVersionExpiration regardless of how the keep-count
// arithmetic plays out.
currentHead, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(key),
})
require.NoError(t, err, "current version v4 must remain")
require.Equal(t, v4, aws.ToString(currentHead.VersionId))
}
@@ -0,0 +1,119 @@
// Object Lock + lifecycle integration scenario.
package lifecycle
import (
"context"
"strings"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
"github.com/stretchr/testify/require"
)
// TestLifecycleSkipsObjectLockedObjects: an object under Object Lock
// retention must NOT be expired by the lifecycle worker. The handler's
// enforceObjectLockProtections check (s3api_internal_lifecycle.go:47)
// returns an error which the dispatcher classifies as
// SKIPPED_OBJECT_LOCK. Pinning the integration end-to-end so a
// regression in either the lock state lookup or the dispatcher's
// outcome handling is caught.
//
// Companion positive control: a second object in the same bucket
// without retention is expired by the same sweep — proves the rule
// is firing AND that the lock check is selective, not a blanket skip.
func TestLifecycleSkipsObjectLockedObjects(t *testing.T) {
c := s3Client(t)
fc, fcClose := filerClient(t)
defer fcClose()
bucket := uniqueBucket("objlock")
// Object Lock requires the bucket to be created with the flag set;
// it can't be enabled retroactively on an existing bucket. Use the
// raw API rather than mustCreateBucket here so we can pass the
// ObjectLockEnabledForBucket option.
_, err := c.CreateBucket(context.Background(), &s3.CreateBucketInput{
Bucket: aws.String(bucket),
ObjectLockEnabledForBucket: aws.Bool(true),
})
require.NoError(t, err)
t.Cleanup(func() {
// Best-effort cleanup mirrors mustCreateBucket; locked objects
// may resist deletion but the test process continues regardless.
c.DeleteBucketLifecycle(context.Background(), &s3.DeleteBucketLifecycleInput{Bucket: aws.String(bucket)})
listOut, _ := c.ListObjectVersions(context.Background(), &s3.ListObjectVersionsInput{Bucket: aws.String(bucket)})
if listOut != nil {
for _, v := range listOut.Versions {
// Bypass governance retention to free the bucket for delete.
c.DeleteObject(context.Background(), &s3.DeleteObjectInput{
Bucket: aws.String(bucket),
Key: v.Key,
VersionId: v.VersionId,
BypassGovernanceRetention: aws.Bool(true),
})
}
for _, m := range listOut.DeleteMarkers {
c.DeleteObject(context.Background(), &s3.DeleteObjectInput{
Bucket: aws.String(bucket), Key: m.Key, VersionId: m.VersionId,
})
}
}
c.DeleteBucket(context.Background(), &s3.DeleteBucketInput{Bucket: aws.String(bucket)})
})
putExpirationLifecycle(t, c, bucket, "lock/", 1)
const lockedKey = "lock/protected.txt"
const freeKey = "lock/free.txt"
// Locked object: PUT with GOVERNANCE retention until 1h from now.
lockedPut, err := c.PutObject(context.Background(), &s3.PutObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(lockedKey),
Body: strings.NewReader("locked"),
ObjectLockMode: types.ObjectLockModeGovernance,
ObjectLockRetainUntilDate: aws.Time(time.Now().Add(time.Hour)),
})
require.NoError(t, err, "PUT with retention must succeed on a lock-enabled bucket")
require.NotEmpty(t, aws.ToString(lockedPut.VersionId))
// Free object: PUT without retention. Object Lock requires
// versioning, so the bucket is implicitly versioned and every PUT
// produces a versionId. Capture both for the version-aware
// backdate path.
freePut, err := c.PutObject(context.Background(), &s3.PutObjectInput{
Bucket: aws.String(bucket), Key: aws.String(freeKey), Body: strings.NewReader("free"),
})
require.NoError(t, err)
freeVersionID := aws.ToString(freePut.VersionId)
require.NotEmpty(t, freeVersionID)
// Backdate both so they would otherwise both expire under the
// 1-day rule. The lock check is what distinguishes them.
// Versioning-enabled buckets store entries under .versions/v_<id>,
// not at the bare key path, so use backdateVersionedMtime.
backdateVersionedMtime(t, fc, bucket, lockedKey, aws.ToString(lockedPut.VersionId), 30)
backdateVersionedMtime(t, fc, bucket, freeKey, freeVersionID, 30)
out := runLifecycleShard(t)
t.Logf("shell output:\n%s", out)
// Free object expires (positive control).
require.Eventuallyf(t, func() bool {
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(freeKey),
})
return isS3NotFound(err)
}, 30*time.Second, 500*time.Millisecond, "unlocked object must expire (control)")
// Locked object survives — Object Lock retention overrides the
// lifecycle rule. HEAD without versionId returns the still-current
// object data, not a 404.
_, err = c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(lockedKey),
})
require.NoError(t, err, "object under GOVERNANCE retention must survive the sweep")
}
@@ -0,0 +1,71 @@
// Size-filter integration scenario.
package lifecycle
import (
"context"
"strings"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
"github.com/stretchr/testify/require"
)
// TestLifecycleSizeFilterGreaterThan: ObjectSizeGreaterThan is a strict >
// gate (filterAllows in match.go uses ev.Size <= rule.FilterSizeGreaterThan
// to reject). Two backdated objects on the same prefix — only the one
// strictly larger than the threshold is expired.
func TestLifecycleSizeFilterGreaterThan(t *testing.T) {
c := s3Client(t)
fc, fcClose := filerClient(t)
defer fcClose()
bucket := uniqueBucket("size-filter")
mustCreateBucket(t, c, bucket)
const threshold = 100
_, err := c.PutBucketLifecycleConfiguration(context.Background(), &s3.PutBucketLifecycleConfigurationInput{
Bucket: aws.String(bucket),
LifecycleConfiguration: &types.BucketLifecycleConfiguration{
Rules: []types.LifecycleRule{{
ID: aws.String("size-gt"),
Status: types.ExpirationStatusEnabled,
Filter: &types.LifecycleRuleFilter{
And: &types.LifecycleRuleAndOperator{
Prefix: aws.String("sz/"),
ObjectSizeGreaterThan: aws.Int64(threshold),
},
},
Expiration: &types.LifecycleExpiration{Days: aws.Int32(1)},
}},
},
})
require.NoError(t, err)
const smallKey = "sz/small.txt" // size <= threshold → must remain
const largeKey = "sz/large.txt" // size > threshold → must expire
putObject(t, c, bucket, smallKey, strings.Repeat("a", threshold)) // exactly at boundary; gate is strictly >, so rejects
putObject(t, c, bucket, largeKey, strings.Repeat("a", threshold+50))
backdateMtime(t, fc, bucket, smallKey, 30)
backdateMtime(t, fc, bucket, largeKey, 30)
out := runLifecycleShard(t)
t.Logf("shell output:\n%s", out)
// Larger-than-threshold object expired.
require.Eventuallyf(t, func() bool {
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(largeKey),
})
return err != nil
}, 30*time.Second, 500*time.Millisecond, "object larger than threshold must expire")
// Boundary object (size == threshold) survives — strictly-greater gate.
_, err = c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(smallKey),
})
require.NoError(t, err, "object at exact threshold must remain (gate is strictly >)")
}
@@ -0,0 +1,117 @@
// Suspended-versioning Expiration integration scenario.
package lifecycle
import (
"context"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
"github.com/stretchr/testify/require"
)
// putVersioningSuspended flips Status=Suspended. PUTs after this point
// overwrite the null version in place rather than creating new versionIds.
func putVersioningSuspended(t *testing.T, c *s3.Client, bucket string) {
t.Helper()
_, err := c.PutBucketVersioning(context.Background(), &s3.PutBucketVersioningInput{
Bucket: aws.String(bucket),
VersioningConfiguration: &types.VersioningConfiguration{Status: types.BucketVersioningStatusSuspended},
})
require.NoError(t, err)
}
// TestLifecycleSuspendedVersioningExpiration: on a suspended-versioning
// bucket, Expiration takes a different code path than the Enabled and
// Off cases. lifecycleDispatch's VersioningSuspended branch first
// deletes the null version (via deleteSpecificObjectVersion(versionId="null"))
// and then writes a fresh delete marker on top.
//
// Setup: enable then suspend versioning so any noncurrent versions can
// exist alongside the null one; PUT once-with-versioning + once-after-
// suspend (so we have a noncurrent version + a null version), backdate
// the null, run the worker. The null must be deleted and replaced by a
// delete marker; the prior noncurrent version stays addressable.
func TestLifecycleSuspendedVersioningExpiration(t *testing.T) {
c := s3Client(t)
fc, fcClose := filerClient(t)
defer fcClose()
bucket := uniqueBucket("suspended")
mustCreateBucket(t, c, bucket)
putVersioningEnabled(t, c, bucket)
const key = "s/obj.txt"
// First PUT under Enabled: produces a real versionId.
putObject(t, c, bucket, key, "v1")
headEnabled, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(key),
})
require.NoError(t, err)
v1 := aws.ToString(headEnabled.VersionId)
require.NotEmpty(t, v1)
require.NotEqual(t, "null", v1)
// Suspend versioning, then PUT again. The new write becomes the
// "null" version that overwrites the bare-key entry; v1 demotes to
// a noncurrent version.
putVersioningSuspended(t, c, bucket)
putObject(t, c, bucket, key, "null-version")
// Set the Expiration rule AFTER the writes so the rule
// configuration race against PUTs is deterministic. Days=1 for
// AWS-spec compliance; backdating the null entry makes the worker
// fire immediately.
putExpirationLifecycle(t, c, bucket, "s/", 1)
// Backdate the bare-key entry (the null version): on suspended
// buckets the null lives at the bare path, NOT under .versions/.
backdateMtime(t, fc, bucket, key, 30)
out := runLifecycleShard(t)
t.Logf("shell output:\n%s", out)
// HEAD without versionId hits the latest, which after the worker
// runs should be a delete marker (404 NoSuchKey).
require.Eventuallyf(t, func() bool {
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(key),
})
return err != nil
}, 30*time.Second, 500*time.Millisecond, "delete marker must dominate latest after suspended-versioning expiration")
// The noncurrent v1 (created under Enabled) must remain — Expiration
// in the suspended branch only touches the null version, not other
// versions in the .versions/ folder.
directHead, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(key), VersionId: aws.String(v1),
})
require.NoError(t, err, "noncurrent v1 must survive — suspended Expiration only touches the null")
require.NotNil(t, directHead)
// ListObjectVersions must show: v1 still present, a fresh delete
// marker as latest, and no more "null" version.
listOut, err := c.ListObjectVersions(context.Background(), &s3.ListObjectVersionsInput{
Bucket: aws.String(bucket), Prefix: aws.String(key),
})
require.NoError(t, err)
var sawV1, sawMarker bool
for _, v := range listOut.Versions {
if aws.ToString(v.Key) == key {
vid := aws.ToString(v.VersionId)
if vid == v1 {
sawV1 = true
}
require.NotEqual(t, "null", vid, "null version must have been removed")
}
}
for _, m := range listOut.DeleteMarkers {
if aws.ToString(m.Key) == key && aws.ToBool(m.IsLatest) {
sawMarker = true
}
}
require.True(t, sawV1, "v1 must still appear in ListObjectVersions")
require.True(t, sawMarker, "fresh delete marker must dominate latest")
}
+40 -3
View File
@@ -90,13 +90,50 @@ func mustCreateBucket(t *testing.T, c *s3.Client, name string) {
_, err := c.CreateBucket(context.Background(), &s3.CreateBucketInput{Bucket: aws.String(name)})
require.NoError(t, err)
t.Cleanup(func() {
// Best effort: empty + delete.
listOut, _ := c.ListObjectsV2(context.Background(), &s3.ListObjectsV2Input{Bucket: aws.String(name)})
// Drop the lifecycle configuration first so any subsequent
// shell-driven shard sweep stops loading rules for this bucket
// — without this, a later test's run-shard would pick up the
// dead bucket's config and produce phantom dispatches.
c.DeleteBucketLifecycle(context.Background(), &s3.DeleteBucketLifecycleInput{Bucket: aws.String(name)})
// Empty every version + delete marker (versioning-aware buckets
// hold state that ListObjectsV2 doesn't surface). Best-effort:
// errors are tolerated because the bucket might already be
// half-torn-down.
listOut, _ := c.ListObjectVersions(context.Background(), &s3.ListObjectVersionsInput{Bucket: aws.String(name)})
if listOut != nil {
for _, o := range listOut.Contents {
for _, v := range listOut.Versions {
c.DeleteObject(context.Background(), &s3.DeleteObjectInput{
Bucket: aws.String(name), Key: v.Key, VersionId: v.VersionId,
})
}
for _, m := range listOut.DeleteMarkers {
c.DeleteObject(context.Background(), &s3.DeleteObjectInput{
Bucket: aws.String(name), Key: m.Key, VersionId: m.VersionId,
})
}
}
// Catch any non-versioned objects ListObjectVersions missed.
objs, _ := c.ListObjectsV2(context.Background(), &s3.ListObjectsV2Input{Bucket: aws.String(name)})
if objs != nil {
for _, o := range objs.Contents {
c.DeleteObject(context.Background(), &s3.DeleteObjectInput{Bucket: aws.String(name), Key: o.Key})
}
}
// Abort any in-flight multipart uploads — the AbortMPU lifecycle
// test leaves these intentionally; without an explicit Abort the
// bucket DELETE refuses with NotEmpty.
mpus, _ := c.ListMultipartUploads(context.Background(), &s3.ListMultipartUploadsInput{Bucket: aws.String(name)})
if mpus != nil {
for _, u := range mpus.Uploads {
c.AbortMultipartUpload(context.Background(), &s3.AbortMultipartUploadInput{
Bucket: aws.String(name), Key: u.Key, UploadId: u.UploadId,
})
}
}
c.DeleteBucket(context.Background(), &s3.DeleteBucketInput{Bucket: aws.String(name)})
})
}
@@ -0,0 +1,441 @@
// Versioning + delete-marker + noncurrent integration scenarios for the
// event-driven lifecycle worker. Same backdating trick as the base test:
// AWS rejects Days < 1, so the test ages the object via the filer's
// UpdateEntry RPC and runs the shell command once with -runtime 10s.
package lifecycle
import (
"context"
"fmt"
"strings"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/stretchr/testify/require"
)
// putVersioningEnabled flips Status=Enabled on the bucket so subsequent
// PUTs produce versioned siblings rather than overwriting.
func putVersioningEnabled(t *testing.T, c *s3.Client, bucket string) {
t.Helper()
_, err := c.PutBucketVersioning(context.Background(), &s3.PutBucketVersioningInput{
Bucket: aws.String(bucket),
VersioningConfiguration: &types.VersioningConfiguration{Status: types.BucketVersioningStatusEnabled},
})
require.NoError(t, err)
}
// putNoncurrentExpirationLifecycle sets a NoncurrentVersionExpiration rule
// targeting a prefix. Days=1 because AWS rejects 0; the test backdates
// the noncurrent version.
func putNoncurrentExpirationLifecycle(t *testing.T, c *s3.Client, bucket, prefix string, days int32) {
t.Helper()
_, err := c.PutBucketLifecycleConfiguration(context.Background(), &s3.PutBucketLifecycleConfigurationInput{
Bucket: aws.String(bucket),
LifecycleConfiguration: &types.BucketLifecycleConfiguration{
Rules: []types.LifecycleRule{
{
ID: aws.String("expire-noncurrent"),
Status: types.ExpirationStatusEnabled,
Filter: &types.LifecycleRuleFilter{Prefix: aws.String(prefix)},
NoncurrentVersionExpiration: &types.NoncurrentVersionExpiration{
NoncurrentDays: aws.Int32(days),
},
},
},
},
})
require.NoError(t, err)
}
// backdateVersionedMtime ages a specific .versions/v_<id> entry. The
// version files live under <buckets>/<bucket>/<key>.versions/v_<versionId>.
func backdateVersionedMtime(t *testing.T, fc filer_pb.SeaweedFilerClient, bucket, key, versionID string, daysOld int) {
t.Helper()
dir := bucketsPath + "/" + bucket + "/" + key + ".versions"
name := "v_" + versionID
resp, err := fc.LookupDirectoryEntry(context.Background(), &filer_pb.LookupDirectoryEntryRequest{
Directory: dir, Name: name,
})
require.NoError(t, err, "lookup version %s/%s", dir, name)
require.NotNil(t, resp.Entry)
require.NotNil(t, resp.Entry.Attributes)
resp.Entry.Attributes.Mtime = time.Now().Add(-time.Duration(daysOld) * 24 * time.Hour).Unix()
resp.Entry.Attributes.MtimeNs = 0
_, err = fc.UpdateEntry(context.Background(), &filer_pb.UpdateEntryRequest{
Directory: dir, Entry: resp.Entry,
})
require.NoError(t, err)
}
func runLifecycleShard(t *testing.T) string {
t.Helper()
out := runShellCommand(t, fmt.Sprintf(
"s3.lifecycle.run-shard -shards 0-15 -s3 %s -events 0 -dispatch 200ms -checkpoint 5s -runtime 10s",
envOr("S3_GRPC_ENDPOINT", defaultS3GrpcEndpoint),
))
require.NotContains(t, out, "FATAL", "shell output:\n%s", out)
return out
}
// TestLifecycleVersionedBucketCreatesDeleteMarker: an Expiration rule on a
// versioned bucket must produce a delete marker (latest version after
// expiration) rather than removing the version itself. Pre-fix this would
// have unconditionally deleted the live version.
func TestLifecycleVersionedBucketCreatesDeleteMarker(t *testing.T) {
c := s3Client(t)
fc, fcClose := filerClient(t)
defer fcClose()
bucket := uniqueBucket("vexp")
mustCreateBucket(t, c, bucket)
putVersioningEnabled(t, c, bucket)
putExpirationLifecycle(t, c, bucket, "expire/", 1)
const key = "expire/old.txt"
putObject(t, c, bucket, key, "v1")
// Look up the version we just created so we can backdate it. The bare
// filer entry under <bucket>/<key> is the latest-version pointer in
// SeaweedFS's versioned layout.
headOut, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(key),
})
require.NoError(t, err)
require.NotNil(t, headOut.VersionId)
versionID := aws.ToString(headOut.VersionId)
require.NotEmpty(t, versionID)
backdateVersionedMtime(t, fc, bucket, key, versionID, 30)
out := runLifecycleShard(t)
t.Logf("shell output:\n%s", out)
// HEAD without versionId returns the latest version. After the worker
// runs, the latest must be a delete marker (NoSuchKey on plain HEAD).
require.Eventuallyf(t, func() bool {
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(key),
})
return isS3NotFound(err)
}, 30*time.Second, 500*time.Millisecond, "expected delete marker to become latest for %s/%s", bucket, key)
// The original version must still be addressable directly — Expiration
// on a versioned bucket creates a marker, it doesn't drop the version.
directHead, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(key), VersionId: aws.String(versionID),
})
require.NoError(t, err, "original version must still exist")
require.NotNil(t, directHead)
// ListObjectVersions should now show a delete marker dominating the
// version. The IsLatest=true marker proves the worker created a fresh
// marker rather than aging the existing version.
listOut, err := c.ListObjectVersions(context.Background(), &s3.ListObjectVersionsInput{
Bucket: aws.String(bucket), Prefix: aws.String(key),
})
require.NoError(t, err)
var sawMarker bool
for _, m := range listOut.DeleteMarkers {
if aws.ToString(m.Key) == key && aws.ToBool(m.IsLatest) {
sawMarker = true
break
}
}
require.True(t, sawMarker, "ListObjectVersions must show a delete marker as latest for %s", key)
}
// TestLifecycleNoncurrentVersionExpiration: NoncurrentVersionExpiration
// only fires on noncurrent versions. PUT v1, PUT v2 (so v1 → noncurrent),
// backdate v1, run worker. v1 must be removed; v2 stays current.
func TestLifecycleNoncurrentVersionExpiration(t *testing.T) {
c := s3Client(t)
fc, fcClose := filerClient(t)
defer fcClose()
bucket := uniqueBucket("noncurrent")
mustCreateBucket(t, c, bucket)
putVersioningEnabled(t, c, bucket)
putNoncurrentExpirationLifecycle(t, c, bucket, "v/", 1)
const key = "v/obj.txt"
// First PUT.
put1, err := c.PutObject(context.Background(), &s3.PutObjectInput{
Bucket: aws.String(bucket), Key: aws.String(key), Body: strings.NewReader("v1"),
})
require.NoError(t, err)
v1 := aws.ToString(put1.VersionId)
// Second PUT promotes v1 to noncurrent.
put2, err := c.PutObject(context.Background(), &s3.PutObjectInput{
Bucket: aws.String(bucket), Key: aws.String(key), Body: strings.NewReader("v2"),
})
require.NoError(t, err)
v2 := aws.ToString(put2.VersionId)
require.NotEqual(t, v1, v2)
// NoncurrentDays is clocked from the SUCCESSOR's mtime — i.e. when
// the version became noncurrent — not from the displaced version's
// own mtime. Backdating only v1 leaves the noncurrent clock (v2's
// mtime) at "now" and the rule never fires. Age both with v1 older
// than v2 so the ordering is realistic.
backdateVersionedMtime(t, fc, bucket, key, v1, 31)
backdateVersionedMtime(t, fc, bucket, key, v2, 30)
out := runLifecycleShard(t)
t.Logf("shell output:\n%s", out)
// v1 must be gone.
require.Eventuallyf(t, func() bool {
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(key), VersionId: aws.String(v1),
})
return isS3NotFound(err)
}, 30*time.Second, 500*time.Millisecond, "noncurrent v1 must be expired")
// v2 must still be addressable BY VERSION ID — pinning that the
// noncurrent dispatch didn't accidentally remove the current
// version's file.
directHead, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(key), VersionId: aws.String(v2),
})
require.NoError(t, err, "current version v2 (versionId=%s) must still be addressable directly", v2)
// And HEAD without versionId (i.e., the latest) must hit v2 — pinning
// that the bare-key pointer wasn't removed and a delete marker
// wasn't fabricated as a side effect of the noncurrent delete. On
// failure we dump ListObjectVersions so the failure log shows
// exactly what's there (versions vs delete markers vs bare).
currentHead, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(key),
})
if err != nil {
listOut, listErr := c.ListObjectVersions(context.Background(), &s3.ListObjectVersionsInput{
Bucket: aws.String(bucket), Prefix: aws.String(key),
})
if listErr != nil || listOut == nil {
t.Logf("HeadObject(latest) failed: %v\nListObjectVersions err=%v", err, listErr)
} else {
t.Logf("HeadObject(latest) failed: %v\nListObjectVersions err=%v versions=%d markers=%d", err, listErr, len(listOut.Versions), len(listOut.DeleteMarkers))
for _, v := range listOut.Versions {
t.Logf(" version key=%s id=%s isLatest=%v", aws.ToString(v.Key), aws.ToString(v.VersionId), aws.ToBool(v.IsLatest))
}
for _, m := range listOut.DeleteMarkers {
t.Logf(" marker key=%s id=%s isLatest=%v", aws.ToString(m.Key), aws.ToString(m.VersionId), aws.ToBool(m.IsLatest))
}
}
require.NoError(t, err, "HEAD(latest) on %s/%s must succeed; v2 (%s) must remain current", bucket, key, v2)
}
require.Equal(t, v2, aws.ToString(currentHead.VersionId), "latest pointer must still resolve to v2")
_ = directHead
}
// TestLifecycleExpiredDeleteMarkerCleanup: a sole-survivor delete marker
// must be removed by an ExpiredObjectDeleteMarker=true rule. Setup: PUT v1,
// DELETE (creates a marker that becomes latest, with v1 as noncurrent),
// expire v1 via NoncurrentVersionExpiration so the marker is alone, then
// the marker rule fires.
//
// We exercise this in two passes: pass 1 (Noncurrent rule on a sibling
// prefix) cleans v1; pass 2 (ExpiredObjectDeleteMarker rule, also on the
// same prefix) removes the now-orphaned marker. Since the lifecycle XML
// only carries one set of rules per bucket, we wire both.
func TestLifecycleExpiredDeleteMarkerCleanup(t *testing.T) {
c := s3Client(t)
fc, fcClose := filerClient(t)
defer fcClose()
bucket := uniqueBucket("marker")
mustCreateBucket(t, c, bucket)
putVersioningEnabled(t, c, bucket)
// Combined rule: noncurrent expiration + delete-marker cleanup, both
// on the same prefix.
_, err := c.PutBucketLifecycleConfiguration(context.Background(), &s3.PutBucketLifecycleConfigurationInput{
Bucket: aws.String(bucket),
LifecycleConfiguration: &types.BucketLifecycleConfiguration{
Rules: []types.LifecycleRule{
{
ID: aws.String("expire-noncurrent"),
Status: types.ExpirationStatusEnabled,
Filter: &types.LifecycleRuleFilter{Prefix: aws.String("m/")},
NoncurrentVersionExpiration: &types.NoncurrentVersionExpiration{
NoncurrentDays: aws.Int32(1),
},
},
{
ID: aws.String("expire-marker"),
Status: types.ExpirationStatusEnabled,
Filter: &types.LifecycleRuleFilter{Prefix: aws.String("m/")},
Expiration: &types.LifecycleExpiration{
ExpiredObjectDeleteMarker: aws.Bool(true),
},
},
},
},
})
require.NoError(t, err)
const key = "m/obj.txt"
put1, err := c.PutObject(context.Background(), &s3.PutObjectInput{
Bucket: aws.String(bucket), Key: aws.String(key), Body: strings.NewReader("v1"),
})
require.NoError(t, err)
v1 := aws.ToString(put1.VersionId)
// Plain DELETE with versioning on creates a marker; the marker becomes
// latest, v1 demotes to noncurrent.
_, err = c.DeleteObject(context.Background(), &s3.DeleteObjectInput{
Bucket: aws.String(bucket), Key: aws.String(key),
})
require.NoError(t, err)
// Backdate v1 so the noncurrent rule expires it.
backdateVersionedMtime(t, fc, bucket, key, v1, 30)
// Backdate the delete marker too. ListObjectVersions tells us the
// marker's versionId.
listOut, err := c.ListObjectVersions(context.Background(), &s3.ListObjectVersionsInput{
Bucket: aws.String(bucket), Prefix: aws.String(key),
})
require.NoError(t, err)
var markerID string
for _, m := range listOut.DeleteMarkers {
if aws.ToString(m.Key) == key {
markerID = aws.ToString(m.VersionId)
break
}
}
require.NotEmpty(t, markerID, "expected to find the delete marker we just created")
backdateVersionedMtime(t, fc, bucket, key, markerID, 30)
out := runLifecycleShard(t)
t.Logf("shell output:\n%s", out)
// Both v1 and the marker must be gone — the .versions/<key>/ folder
// should hold nothing for this key.
require.Eventuallyf(t, func() bool {
listOut, err := c.ListObjectVersions(context.Background(), &s3.ListObjectVersionsInput{
Bucket: aws.String(bucket), Prefix: aws.String(key),
})
if err != nil {
return false
}
for _, v := range listOut.Versions {
if aws.ToString(v.Key) == key {
return false
}
}
for _, m := range listOut.DeleteMarkers {
if aws.ToString(m.Key) == key {
return false
}
}
return true
}, 30*time.Second, 500*time.Millisecond, "every version and marker for %s must be gone", key)
}
// TestLifecycleDisabledRuleSkipsObject: a rule with Status=Disabled must
// not produce dispatches, even on a backdated object that would otherwise
// match. Negative test for the engine's enabled-status gate.
func TestLifecycleDisabledRuleSkipsObject(t *testing.T) {
c := s3Client(t)
fc, fcClose := filerClient(t)
defer fcClose()
bucket := uniqueBucket("disabled")
mustCreateBucket(t, c, bucket)
_, err := c.PutBucketLifecycleConfiguration(context.Background(), &s3.PutBucketLifecycleConfigurationInput{
Bucket: aws.String(bucket),
LifecycleConfiguration: &types.BucketLifecycleConfiguration{
Rules: []types.LifecycleRule{{
ID: aws.String("disabled-rule"),
Status: types.ExpirationStatusDisabled,
Filter: &types.LifecycleRuleFilter{Prefix: aws.String("d/")},
Expiration: &types.LifecycleExpiration{Days: aws.Int32(1)},
}},
},
})
require.NoError(t, err)
const key = "d/obj.txt"
putObject(t, c, bucket, key, "still-here")
backdateMtime(t, fc, bucket, key, 30)
out := runLifecycleShard(t)
t.Logf("shell output:\n%s", out)
// Wait the same window; the object MUST still exist after.
time.Sleep(2 * time.Second) // give the worker a chance to (incorrectly) act
_, err = c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(key),
})
require.NoError(t, err, "Disabled rule must not delete the object")
}
// TestLifecycleTagFilter: a rule with a tag filter must only match objects
// carrying that tag. Two backdated objects, one tagged, one not — only the
// tagged one is removed.
func TestLifecycleTagFilter(t *testing.T) {
c := s3Client(t)
fc, fcClose := filerClient(t)
defer fcClose()
bucket := uniqueBucket("tagfilter")
mustCreateBucket(t, c, bucket)
_, err := c.PutBucketLifecycleConfiguration(context.Background(), &s3.PutBucketLifecycleConfigurationInput{
Bucket: aws.String(bucket),
LifecycleConfiguration: &types.BucketLifecycleConfiguration{
Rules: []types.LifecycleRule{{
ID: aws.String("tag-only"),
Status: types.ExpirationStatusEnabled,
Filter: &types.LifecycleRuleFilter{
And: &types.LifecycleRuleAndOperator{
Prefix: aws.String("t/"),
Tags: []types.Tag{
{Key: aws.String("env"), Value: aws.String("temp")},
},
},
},
Expiration: &types.LifecycleExpiration{Days: aws.Int32(1)},
}},
},
})
require.NoError(t, err)
const taggedKey = "t/tagged.txt"
const untaggedKey = "t/untagged.txt"
putObject(t, c, bucket, taggedKey, "tagged")
putObject(t, c, bucket, untaggedKey, "untagged")
// Stamp the tag on one of them.
_, err = c.PutObjectTagging(context.Background(), &s3.PutObjectTaggingInput{
Bucket: aws.String(bucket), Key: aws.String(taggedKey),
Tagging: &types.Tagging{TagSet: []types.Tag{
{Key: aws.String("env"), Value: aws.String("temp")},
}},
})
require.NoError(t, err)
backdateMtime(t, fc, bucket, taggedKey, 30)
backdateMtime(t, fc, bucket, untaggedKey, 30)
out := runLifecycleShard(t)
t.Logf("shell output:\n%s", out)
require.Eventuallyf(t, func() bool {
_, err := c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(taggedKey),
})
return isS3NotFound(err)
}, 30*time.Second, 500*time.Millisecond, "tagged object must be expired")
_, err = c.HeadObject(context.Background(), &s3.HeadObjectInput{
Bucket: aws.String(bucket), Key: aws.String(untaggedKey),
})
require.NoError(t, err, "untagged object must remain")
}
+125 -3
View File
@@ -3,6 +3,7 @@ package s3api
import (
"bytes"
"context"
"encoding/hex"
"errors"
"path"
"strings"
@@ -12,6 +13,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/pb/s3_lifecycle_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
stats_collect "github.com/seaweedfs/seaweedfs/weed/stats"
)
// LifecycleDelete executes one (rule, action) verdict: re-fetch, identity
@@ -54,6 +56,7 @@ func (s3a *S3ApiServer) LifecycleDelete(ctx context.Context, req *s3_lifecycle_p
}
func (s3a *S3ApiServer) lifecycleDispatch(ctx context.Context, req *s3_lifecycle_pb.LifecycleDeleteRequest, entry *filer_pb.Entry) (*s3_lifecycle_pb.LifecycleDeleteResponse, error) {
metadataOnly := entryUsesMetadataOnlyDelete(entry)
switch req.ActionKind {
case s3_lifecycle_pb.ActionKind_EXPIRATION_DAYS, s3_lifecycle_pb.ActionKind_EXPIRATION_DATE:
// Current-version expiration: Enabled -> delete marker; Suspended
@@ -74,7 +77,7 @@ func (s3a *S3ApiServer) lifecycleDispatch(ctx context.Context, req *s3_lifecycle
return done(), nil
case s3_constants.VersioningSuspended:
// Best-effort null delete; NotFound is benign.
if err := s3a.deleteSpecificObjectVersion(req.Bucket, req.ObjectPath, "null"); err != nil {
if err := s3a.deleteSpecificObjectVersion(req.Bucket, req.ObjectPath, "null", metadataOnly); err != nil {
if !errors.Is(err, filer_pb.ErrNotFound) && !errors.Is(err, ErrVersionNotFound) {
return retryLater("TRANSPORT_ERROR: deleteNullVersion: " + err.Error()), nil
}
@@ -85,7 +88,7 @@ func (s3a *S3ApiServer) lifecycleDispatch(ctx context.Context, req *s3_lifecycle
return done(), nil
default:
err := s3a.WithFilerClient(false, func(c filer_pb.SeaweedFilerClient) error {
return s3a.deleteUnversionedObjectWithClient(c, req.Bucket, req.ObjectPath)
return s3a.deleteUnversionedObjectWithClient(c, req.Bucket, req.ObjectPath, metadataOnly)
})
if err != nil {
if errors.Is(err, filer_pb.ErrNotFound) || errors.Is(err, ErrObjectNotFound) {
@@ -93,6 +96,7 @@ func (s3a *S3ApiServer) lifecycleDispatch(ctx context.Context, req *s3_lifecycle
}
return retryLater("TRANSPORT_ERROR: deleteUnversioned: " + err.Error()), nil
}
recordMetadataOnlyIf(metadataOnly, req)
return done(), nil
}
@@ -120,12 +124,22 @@ func (s3a *S3ApiServer) lifecycleDispatch(ctx context.Context, req *s3_lifecycle
return noopResolved("VERSION_IS_LATEST"), nil
}
}
if err := s3a.deleteSpecificObjectVersion(req.Bucket, req.ObjectPath, req.VersionId); err != nil {
// Re-check sole-survivor: a fresh PUT can land between schedule
// and dispatch. Identity-CAS upstream covers the marker bytes;
// this covers the directory shape.
if req.ActionKind == s3_lifecycle_pb.ActionKind_EXPIRED_DELETE_MARKER {
outcome, err := s3a.checkSoleSurvivorMarker(ctx, req.Bucket, req.ObjectPath, req.VersionId)
if outcome != nil || err != nil {
return outcome, err
}
}
if err := s3a.deleteSpecificObjectVersion(req.Bucket, req.ObjectPath, req.VersionId, metadataOnly); err != nil {
if errors.Is(err, filer_pb.ErrNotFound) || errors.Is(err, ErrVersionNotFound) || errors.Is(err, ErrObjectNotFound) {
return noopResolved("NOT_FOUND_AT_DELETE"), nil
}
return retryLater("TRANSPORT_ERROR: deleteSpecificVersion: " + err.Error()), nil
}
recordMetadataOnlyIf(metadataOnly, req)
return done(), nil
case s3_lifecycle_pb.ActionKind_ABORT_MPU:
@@ -175,6 +189,92 @@ func (s3a *S3ApiServer) lifecycleAbortMPU(ctx context.Context, req *s3_lifecycle
return done(), nil
}
// checkSoleSurvivorMarker returns nil to proceed with the delete, or a
// terminal response when state has drifted: count != 1, the surviving
// entry is a different version, the .versions/ directory's latest
// pointer doesn't name versionId, or a bare null-version exists outside
// .versions/. Pointer missing while a marker is present is treated as
// retry-later — the create races with the directory metadata update.
func (s3a *S3ApiServer) checkSoleSurvivorMarker(ctx context.Context, bucket, object, versionId string) (*s3_lifecycle_pb.LifecycleDeleteResponse, error) {
bucketDir := s3a.bucketDir(bucket)
versionsDir := bucketDir + "/" + object + s3_constants.VersionsFolder
count := 0
var firstName string
err := s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
return filer_pb.SeaweedList(ctx, client, versionsDir, "", func(entry *filer_pb.Entry, _ bool) error {
count++
if count == 1 && entry != nil {
firstName = entry.Name
}
return nil
}, "", false, 2)
})
if err != nil {
if errors.Is(err, filer_pb.ErrNotFound) {
return noopResolved("NOT_FOUND"), nil
}
return retryLater("TRANSPORT_ERROR: sole-survivor list: " + err.Error()), nil
}
if count == 0 {
return noopResolved("NOT_FOUND"), nil
}
if count > 1 {
return noopResolved("NOT_SOLE_SURVIVOR"), nil
}
// SeaweedList delivered a single callback but with a nil entry; we
// can't compare names so retry rather than silently bypass the
// marker-replaced check.
if firstName == "" {
return retryLater("PENDING_SURVIVOR_ENTRY"), nil
}
if versionId != "" && firstName != s3a.getVersionFileName(versionId) {
return noopResolved("MARKER_REPLACED"), nil
}
// Latest-pointer check: createDeleteMarker writes the marker file
// and then updates the parent directory's Extended map. Reading
// before the second step lands would see count==1 but no pointer;
// retry-later rather than mistakenly delete.
parent, name := path.Split(versionsDir)
parent = strings.TrimRight(parent, "/")
if parent == "" {
parent = "/"
}
versionsEntry, err := s3a.getEntry(parent, name)
if err != nil {
if errors.Is(err, filer_pb.ErrNotFound) {
return noopResolved("NOT_FOUND"), nil
}
return retryLater("TRANSPORT_ERROR: latest-pointer lookup: " + err.Error()), nil
}
if versionsEntry == nil {
return noopResolved("NOT_FOUND"), nil
}
latest, hasPointer := versionsEntry.Extended[s3_constants.ExtLatestVersionIdKey]
if !hasPointer || len(latest) == 0 {
return retryLater("PENDING_LATEST_POINTER"), nil
}
if string(latest) != versionId {
return noopResolved("MARKER_NOT_LATEST"), nil
}
// Null-version check: pre-versioning objects survive as the bare
// <bucket>/<key>. Both regular files and explicit S3 directory-key
// markers (object names ending in /) qualify; the listing path
// (s3api_object_versioning.go processExplicitDirectory) treats both
// as the null version. getEntry uses NewFullPath so a trailing slash
// in object splits the same as a regular key.
bareEntry, err := s3a.getEntry(bucketDir, object)
if err != nil {
if errors.Is(err, filer_pb.ErrNotFound) {
return nil, nil
}
return retryLater("TRANSPORT_ERROR: null-version lookup: " + err.Error()), nil
}
if bareEntry != nil && (!bareEntry.IsDirectory || bareEntry.IsDirectoryKeyObject()) {
return noopResolved("NULL_VERSION_PRESENT"), nil
}
return nil, nil
}
// isCurrentLatestVersion reports whether versionId is the version the
// .versions/ directory currently points to. SeaweedFS records the latest
// version on the parent directory's Extended map; without consulting it,
@@ -242,6 +342,28 @@ func identityMatches(live, want *s3_lifecycle_pb.EntryIdentity) bool {
return bytes.Equal(live.ExtendedHash, want.ExtendedHash)
}
// entryUsesMetadataOnlyDelete reports whether the lifecycle delete path
// can skip per-chunk DeleteFile RPCs and rely on the volume's TTL to
// reclaim chunks. Per-write TTL stamping (PR 9377) sets Attributes.TtlSec
// on every entry whose lifecycle rule fits within volume TTL — observing
// a non-zero TtlSec on the live entry is the authoritative signal.
// Defensive nil-checks because the caller may be racing a concurrent
// rewrite that nil-ed Attributes briefly during meta-log replay.
func entryUsesMetadataOnlyDelete(entry *filer_pb.Entry) bool {
return entry != nil && entry.Attributes != nil && entry.Attributes.TtlSec > 0
}
// recordMetadataOnlyIf bumps the metadata-only counter when on=true.
// Skipped when off so callers don't need a guard at every call site.
// rule_hash is hex-encoded so operators can group by rule when
// debugging; nil rule_hash collapses to the empty string.
func recordMetadataOnlyIf(on bool, req *s3_lifecycle_pb.LifecycleDeleteRequest) {
if !on || req == nil {
return
}
stats_collect.S3LifecycleMetadataOnlyCounter.WithLabelValues(req.Bucket, hex.EncodeToString(req.RuleHash)).Inc()
}
func done() *s3_lifecycle_pb.LifecycleDeleteResponse {
return &s3_lifecycle_pb.LifecycleDeleteResponse{Outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_DONE}
}
+182
View File
@@ -4,9 +4,11 @@ import (
"bytes"
"testing"
"github.com/prometheus/client_golang/prometheus/testutil"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/s3_lifecycle_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
stats_collect "github.com/seaweedfs/seaweedfs/weed/stats"
)
func TestComputeEntryIdentity_BasicFields(t *testing.T) {
@@ -147,3 +149,183 @@ func TestLifecycleAbortMPU_RejectsTraversalUploadIDs(t *testing.T) {
})
}
}
func TestLifecycleDispatch_AbortMPUAfterFetchIsBlocked(t *testing.T) {
// LifecycleDelete routes ABORT_MPU to lifecycleAbortMPU before
// getObjectEntry; reaching lifecycleDispatch with ABORT_MPU means
// some caller bypassed that route. Defensive BLOCKED so a
// regression there can't accidentally rm a real object via the
// expiration paths.
s := &S3ApiServer{}
resp, err := s.lifecycleDispatch(nil, &s3_lifecycle_pb.LifecycleDeleteRequest{
Bucket: "bk",
ObjectPath: "k",
ActionKind: s3_lifecycle_pb.ActionKind_ABORT_MPU,
}, &filer_pb.Entry{Attributes: &filer_pb.FuseAttributes{}})
if err != nil {
t.Fatalf("unexpected gRPC error: %v", err)
}
if resp.Outcome != s3_lifecycle_pb.LifecycleDeleteOutcome_BLOCKED {
t.Fatalf("ABORT_MPU at dispatch should be BLOCKED, got %v reason=%q", resp.Outcome, resp.Reason)
}
if !contains(resp.Reason, "ABORT_MPU dispatched after fetch") {
t.Fatalf("reason should name the route bypass, got %q", resp.Reason)
}
}
func TestLifecycleDispatch_UnknownActionKindIsBlocked(t *testing.T) {
// An ActionKind value the proto doesn't define yet must produce a
// FATAL outcome rather than fall through to a default delete path.
s := &S3ApiServer{}
const bogus = s3_lifecycle_pb.ActionKind(999)
resp, err := s.lifecycleDispatch(nil, &s3_lifecycle_pb.LifecycleDeleteRequest{
Bucket: "bk",
ObjectPath: "k",
ActionKind: bogus,
}, &filer_pb.Entry{Attributes: &filer_pb.FuseAttributes{}})
if err != nil {
t.Fatalf("unexpected gRPC error: %v", err)
}
if resp.Outcome != s3_lifecycle_pb.LifecycleDeleteOutcome_BLOCKED {
t.Fatalf("unknown action kind should be BLOCKED, got %v reason=%q", resp.Outcome, resp.Reason)
}
if !contains(resp.Reason, "unknown action_kind") {
t.Fatalf("reason should name the unknown kind, got %q", resp.Reason)
}
}
func TestLifecycleDispatch_NoncurrentRequiresVersionID(t *testing.T) {
// Noncurrent / EXPIRED_DELETE_MARKER target a specific version; an
// empty version_id is a writer-side bug and must be rejected before
// any filer call. This pinning keeps the early-return in place so
// a refactor doesn't accidentally let the empty-version_id path
// reach deleteSpecificObjectVersion.
s := &S3ApiServer{}
for _, kind := range []s3_lifecycle_pb.ActionKind{
s3_lifecycle_pb.ActionKind_NONCURRENT_DAYS,
s3_lifecycle_pb.ActionKind_NEWER_NONCURRENT,
s3_lifecycle_pb.ActionKind_EXPIRED_DELETE_MARKER,
} {
t.Run(kind.String(), func(t *testing.T) {
resp, err := s.lifecycleDispatch(nil, &s3_lifecycle_pb.LifecycleDeleteRequest{
Bucket: "bk",
ObjectPath: "k",
ActionKind: kind,
// VersionId intentionally empty
}, &filer_pb.Entry{Attributes: &filer_pb.FuseAttributes{}})
if err != nil {
t.Fatalf("unexpected gRPC error: %v", err)
}
if resp.Outcome != s3_lifecycle_pb.LifecycleDeleteOutcome_BLOCKED {
t.Fatalf("kind %v with empty version_id should be BLOCKED, got %v reason=%q",
kind, resp.Outcome, resp.Reason)
}
if !contains(resp.Reason, "version_id required") {
t.Fatalf("reason should name the missing version_id, got %q", resp.Reason)
}
})
}
}
// contains is a tiny helper so the tests above don't pull in strings
// just for a substring check.
func contains(haystack, needle string) bool {
if len(needle) == 0 {
return true
}
for i := 0; i+len(needle) <= len(haystack); i++ {
if haystack[i:i+len(needle)] == needle {
return true
}
}
return false
}
func TestEntryUsesMetadataOnlyDelete(t *testing.T) {
cases := []struct {
name string
entry *filer_pb.Entry
want bool
}{
{
name: "nil entry",
entry: nil,
want: false,
},
{
name: "nil attributes",
entry: &filer_pb.Entry{},
want: false,
},
{
name: "TtlSec=0 (no per-write stamp)",
entry: &filer_pb.Entry{Attributes: &filer_pb.FuseAttributes{TtlSec: 0}},
want: false,
},
{
name: "TtlSec>0 (PR 9377 stamped a fast-path TTL)",
entry: &filer_pb.Entry{Attributes: &filer_pb.FuseAttributes{TtlSec: 86400}},
want: true,
},
{
name: "TtlSec<0 should not happen but must not flip the path on",
entry: &filer_pb.Entry{Attributes: &filer_pb.FuseAttributes{TtlSec: -1}},
want: false,
},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if got := entryUsesMetadataOnlyDelete(c.entry); got != c.want {
t.Fatalf("want %v, got %v", c.want, got)
}
})
}
}
func TestRecordMetadataOnlyIf_OnlyFiresWhenOn(t *testing.T) {
// Counter must increment exactly once per (bucket, hex(rule_hash))
// when on=true, and not at all when on=false. Other lifecycle paths
// in the same suite share the global counter — use distinct bucket
// names per test so series don't bleed.
c := stats_collect.S3LifecycleMetadataOnlyCounter
bucket := "bk-counter-on"
hash := []byte{0xde, 0xad, 0xbe, 0xef, 0x01, 0x02, 0x03, 0x04}
hexHash := "deadbeef01020304"
before := testutil.ToFloat64(c.WithLabelValues(bucket, hexHash))
recordMetadataOnlyIf(true, &s3_lifecycle_pb.LifecycleDeleteRequest{
Bucket: bucket,
RuleHash: hash,
})
if got := testutil.ToFloat64(c.WithLabelValues(bucket, hexHash)); got != before+1 {
t.Fatalf("on=true should bump by 1; before=%v after=%v", before, got)
}
beforeOff := testutil.ToFloat64(c.WithLabelValues("bk-counter-off", hexHash))
recordMetadataOnlyIf(false, &s3_lifecycle_pb.LifecycleDeleteRequest{
Bucket: "bk-counter-off",
RuleHash: hash,
})
if got := testutil.ToFloat64(c.WithLabelValues("bk-counter-off", hexHash)); got != beforeOff {
t.Fatalf("on=false should not bump; before=%v after=%v", beforeOff, got)
}
}
func TestRecordMetadataOnlyIf_NilRequestSafe(t *testing.T) {
// A nil req is a defensive no-op; never panic on the prometheus
// label call which would otherwise dereference req.Bucket.
recordMetadataOnlyIf(true, nil)
}
func TestRecordMetadataOnlyIf_EmptyRuleHashCollapsesToEmptyLabel(t *testing.T) {
// Bootstrap or test paths may not stamp a rule hash; the label
// must end up as an empty string rather than panicking on
// hex.EncodeToString(nil).
c := stats_collect.S3LifecycleMetadataOnlyCounter
bucket := "bk-counter-emptyhash"
before := testutil.ToFloat64(c.WithLabelValues(bucket, ""))
recordMetadataOnlyIf(true, &s3_lifecycle_pb.LifecycleDeleteRequest{Bucket: bucket})
if got := testutil.ToFloat64(c.WithLabelValues(bucket, "")); got != before+1 {
t.Fatalf("nil rule_hash should produce empty-label series; before=%v after=%v", before, got)
}
}
+61 -11
View File
@@ -1053,7 +1053,20 @@ func (s3a *S3ApiServer) copySingleChunk(chunk *filer_pb.FileChunk, dstPath strin
return nil, err
}
// Download and upload the chunk
// Stream the chunk through io.Pipe when no in-transit transformation is
// required; this holds only ~32 KiB per copy in flight, vs. the
// chunk-sized buffers the buffered path needs. isFullChunk=true asks
// the source volume for compressed bytes, so a gzipped chunk is
// forwarded to the destination without anyone having to decompress.
if canStreamCopyChunk(chunk) {
if err := s3a.streamCopyChunkRange(context.Background(), srcUrl, fileId, 0, int64(chunk.Size), true /*isFullChunk*/, assignResult); err != nil {
return nil, fmt.Errorf("stream chunk: %w", err)
}
return dstChunk, nil
}
// SSE / per-chunk-cipher: bytes need to be transformed in transit, so
// download into a buffer first.
chunkData, err := s3a.downloadChunkData(srcUrl, fileId, 0, int64(chunk.Size), chunk.CipherKey)
if err != nil {
return nil, fmt.Errorf("download chunk data: %w", err)
@@ -1088,6 +1101,25 @@ func (s3a *S3ApiServer) copySingleChunkForRange(originalChunk, rangeChunk *filer
overlapStart := max(rangeStart, chunkStart)
offsetInChunk := overlapStart - chunkStart
// Stream the byte range through io.Pipe when there's no in-transit
// transformation required (see canStreamCopyChunk for the eligibility
// rules); this is the dominant path for Harbor-style multipart
// assemble loads, which use UploadPartCopy with a CopySourceRange.
//
// When the requested range happens to cover the entire source chunk
// exactly, switch to the full-chunk fetch mode: that asks the source
// volume for compressed bytes (Accept-Encoding: gzip) and forwards
// them as-is, avoiding the volume-side decompression that a Range
// fetch on a gzipped chunk would otherwise pay. Harbor's typical
// part-size = chunk-size assemble pattern hits this branch.
if canStreamCopyChunk(originalChunk) {
isFullChunk := offsetInChunk == 0 && rangeChunk.Size == originalChunk.Size
if err := s3a.streamCopyChunkRange(context.Background(), srcUrl, fileId, offsetInChunk, int64(rangeChunk.Size), isFullChunk, assignResult); err != nil {
return nil, fmt.Errorf("stream chunk range: %w", err)
}
return dstChunk, nil
}
// Download and upload the chunk portion
chunkData, err := s3a.downloadChunkData(srcUrl, fileId, offsetInChunk, int64(rangeChunk.Size), originalChunk.CipherKey)
if err != nil {
@@ -1379,16 +1411,7 @@ func (s3a *S3ApiServer) prepareChunkCopy(sourceFileId, dstPath string, expectedD
// uploadChunkData uploads chunk data to the destination using common upload logic
// isCompressed indicates if the data is already compressed and should not be compressed again
func (s3a *S3ApiServer) uploadChunkData(chunkData []byte, assignResult *filer_pb.AssignVolumeResponse, isCompressed bool) error {
dstUrl := fmt.Sprintf("http://%s/%s", assignResult.Location.Url, assignResult.FileId)
uploadOption := &operation.UploadOption{
UploadUrl: dstUrl,
Cipher: false, // Data is already encrypted if source had CipherKey; don't re-encrypt
IsInputCompressed: isCompressed,
MimeType: "",
PairMap: nil,
Jwt: security.EncodedJwt(assignResult.Auth),
}
uploadOption := newChunkUploadOption(chunkData, assignResult, isCompressed)
uploader, err := operation.NewUploader()
if err != nil {
return fmt.Errorf("create uploader: %w", err)
@@ -1401,6 +1424,33 @@ func (s3a *S3ApiServer) uploadChunkData(chunkData []byte, assignResult *filer_pb
return nil
}
// multipartFramingOverhead reserves space for the multipart wrapper
// upload_content writes around chunkData (boundary + Content-Disposition +
// optional Content-Type/Content-Encoding/Content-MD5 headers + trailing
// boundary). Real-world overhead is a few hundred bytes; rounding to 1 KiB
// avoids a single grow on the buffer we hand to the multipart writer.
const multipartFramingOverhead = 1024
// newChunkUploadOption builds the operation.UploadOption used by every
// chunk-copy upload. It always sets BytesBuffer to a fresh, per-call buffer
// so upload_content does not fall back to the package-global
// valyala/bytebufferpool — that pool retains every high-water buffer for the
// process's lifetime, and under concurrent UploadPartCopy load it hoarded
// one chunk-sized buffer per concurrent upload (see #6541). The per-call
// buffer is GC'd as soon as the upload returns.
func newChunkUploadOption(chunkData []byte, assignResult *filer_pb.AssignVolumeResponse, isCompressed bool) *operation.UploadOption {
dstUrl := fmt.Sprintf("http://%s/%s", assignResult.Location.Url, assignResult.FileId)
return &operation.UploadOption{
UploadUrl: dstUrl,
Cipher: false, // Data is already encrypted if source had CipherKey; don't re-encrypt
IsInputCompressed: isCompressed,
MimeType: "",
PairMap: nil,
Jwt: security.EncodedJwt(assignResult.Auth),
BytesBuffer: bytes.NewBuffer(make([]byte, 0, len(chunkData)+multipartFramingOverhead)),
}
}
// downloadChunkData downloads chunk data from the source URL
func (s3a *S3ApiServer) downloadChunkData(srcUrl, fileId string, offset, size int64, cipherKey []byte) ([]byte, error) {
jwt := filer.JwtForVolumeServer(fileId)
@@ -0,0 +1,186 @@
package s3api
import (
"context"
"crypto/sha256"
"fmt"
"io"
"mime/multipart"
"net"
"net/http"
"net/http/httptest"
"strconv"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
)
// benchEnv stands up a fake source volume (returns N bytes on GET) and a
// fake destination volume (parses an incoming multipart POST and discards
// the body, asserting the data arrived intact via SHA-256). It returns the
// URLs and an AssignVolumeResponse pointing at the destination.
type benchEnv struct {
srcSrv *httptest.Server
dstSrv *httptest.Server
payload []byte
dstHash [32]byte
assign *filer_pb.AssignVolumeResponse
}
func newBenchEnv(b *testing.B, payloadSize int) *benchEnv {
b.Helper()
payload := make([]byte, payloadSize)
for i := range payload {
payload[i] = byte(i*31 + 7) // arbitrary repeatable pattern
}
wantHash := sha256.Sum256(payload)
srcSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Honor Range header if present (UploadPartCopy passes one).
start, end := int64(0), int64(len(payload)-1)
if rng := r.Header.Get("Range"); rng != "" {
var s, e int64
if _, err := fmt.Sscanf(rng, "bytes=%d-%d", &s, &e); err == nil {
start, end = s, e
}
}
w.Header().Set("Content-Length", strconv.FormatInt(end-start+1, 10))
w.WriteHeader(http.StatusOK)
_, _ = w.Write(payload[start : end+1])
}))
dstSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mr, err := r.MultipartReader()
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
part, err := mr.NextPart()
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
h := sha256.New()
if _, err := io.Copy(h, part); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
var got [32]byte
copy(got[:], h.Sum(nil))
if got != wantHash {
http.Error(w, "hash mismatch", http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusCreated)
_, _ = io.WriteString(w, `{"size":`+strconv.Itoa(payloadSize)+`}`)
}))
dstURL, _ := neturl(dstSrv.URL)
assign := &filer_pb.AssignVolumeResponse{
FileId: "1,benchmark",
Location: &filer_pb.Location{
Url: dstURL,
PublicUrl: dstURL,
},
Auth: "",
}
return &benchEnv{
srcSrv: srcSrv,
dstSrv: dstSrv,
payload: payload,
dstHash: wantHash,
assign: assign,
}
}
func (e *benchEnv) close() {
e.srcSrv.Close()
e.dstSrv.Close()
}
// neturl extracts host:port from "http://host:port".
func neturl(rawURL string) (string, error) {
const prefix = "http://"
if len(rawURL) < len(prefix) || rawURL[:len(prefix)] != prefix {
return "", fmt.Errorf("unexpected URL: %q", rawURL)
}
host := rawURL[len(prefix):]
if _, _, err := net.SplitHostPort(host); err != nil {
return "", err
}
return host, nil
}
// BenchmarkCopyChunk_Buffered measures the cost of the existing buffered
// chunk-copy path (downloadChunkData + uploadChunkData). The path
// allocates one chunk-sized []byte and one multipart-encoded buffer per
// call.
func BenchmarkCopyChunk_Buffered(b *testing.B) {
for _, size := range []int{1 << 20, 8 << 20, 64 << 20} {
b.Run(humanByteName(size), func(b *testing.B) {
util_http.InitGlobalHttpClient()
env := newBenchEnv(b, size)
defer env.close()
s3a := &S3ApiServer{}
b.ResetTimer()
b.SetBytes(int64(size))
b.ReportAllocs()
for i := 0; i < b.N; i++ {
data, err := s3a.downloadChunkData(env.srcSrv.URL, env.assign.FileId, 0, int64(size), nil)
if err != nil {
b.Fatalf("download: %v", err)
}
if err := s3a.uploadChunkData(data, env.assign, false); err != nil {
b.Fatalf("upload: %v", err)
}
}
})
}
}
// BenchmarkCopyChunk_Streamed measures the cost of the io.Pipe streaming
// chunk-copy path. The path holds only the pipe's hand-off buffer (~32
// KiB) plus http transport buffers per call, regardless of chunk size.
func BenchmarkCopyChunk_Streamed(b *testing.B) {
for _, size := range []int{1 << 20, 8 << 20, 64 << 20} {
b.Run(humanByteName(size), func(b *testing.B) {
util_http.InitGlobalHttpClient()
env := newBenchEnv(b, size)
defer env.close()
s3a := &S3ApiServer{}
b.ResetTimer()
b.SetBytes(int64(size))
b.ReportAllocs()
for i := 0; i < b.N; i++ {
if err := s3a.streamCopyChunkRange(context.Background(),
env.srcSrv.URL, env.assign.FileId, 0, int64(size),
true /*isFullChunk*/, env.assign); err != nil {
b.Fatalf("stream: %v", err)
}
}
})
}
}
func humanByteName(n int) string {
switch {
case n >= 1<<30:
return strconv.Itoa(n>>30) + "GiB"
case n >= 1<<20:
return strconv.Itoa(n>>20) + "MiB"
case n >= 1<<10:
return strconv.Itoa(n>>10) + "KiB"
default:
return strconv.Itoa(n) + "B"
}
}
// Compile-time sanity: ensure the multipart library version we depend on
// is the one whose framing we mirror in streamCopyChunkRange.
var _ = multipart.NewWriter
@@ -0,0 +1,77 @@
package s3api
import (
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
)
// TestNewChunkUploadOption_AvoidsBytePool is a regression guard for the
// s3-side retention amplifier in https://github.com/seaweedfs/seaweedfs/issues/6541.
//
// operation.upload_content falls back to the package-global
// valyala/bytebufferpool (which retains high-water buffers for the
// process's lifetime) whenever UploadOption.BytesBuffer is nil. Concurrent
// UploadPartCopy calls then hoard one chunk-sized buffer per concurrent
// upload in that pool, and RSS never recedes. The chunk-copy path must
// therefore always provide its own buffer; this test pins that contract.
func TestNewChunkUploadOption_AvoidsBytePool(t *testing.T) {
cases := []struct {
name string
chunkLen int
}{
{"empty chunk", 0},
{"small chunk", 1024},
{"typical 8 MiB chunk", 8 * 1024 * 1024},
{"large 64 MiB chunk", 64 * 1024 * 1024},
}
assign := &filer_pb.AssignVolumeResponse{
FileId: "1,foo",
Location: &filer_pb.Location{
Url: "127.0.0.1:8080",
PublicUrl: "127.0.0.1:8080",
},
Auth: "",
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
data := make([]byte, c.chunkLen)
opt := newChunkUploadOption(data, assign, false)
if opt.BytesBuffer == nil {
t.Fatalf("BytesBuffer must be non-nil so chunk uploads bypass " +
"the package-global bytebufferpool (regression: #6541)")
}
if got, want := opt.BytesBuffer.Cap(), c.chunkLen+multipartFramingOverhead; got < want {
t.Errorf("BytesBuffer cap=%d, want >=%d (one alloc-and-grow "+
"per upload defeats the purpose of pre-sizing)", got, want)
}
if opt.BytesBuffer.Len() != 0 {
t.Errorf("BytesBuffer not empty: len=%d", opt.BytesBuffer.Len())
}
if opt.Cipher {
t.Errorf("Cipher must be false: chunk-copy data is already " +
"encrypted if the source had a CipherKey")
}
})
}
}
// TestNewChunkUploadOption_PerCallIsolation verifies each call returns a
// distinct buffer. Sharing one buffer across concurrent uploads would
// corrupt the multipart bodies under concurrent UploadPartCopy.
func TestNewChunkUploadOption_PerCallIsolation(t *testing.T) {
assign := &filer_pb.AssignVolumeResponse{
FileId: "1,foo",
Location: &filer_pb.Location{Url: "127.0.0.1:8080"},
}
o1 := newChunkUploadOption(nil, assign, false)
o2 := newChunkUploadOption(nil, assign, false)
if o1.BytesBuffer == o2.BytesBuffer {
t.Fatalf("newChunkUploadOption must hand each caller a distinct buffer; " +
"sharing one across concurrent uploads would corrupt the multipart bodies")
}
}
@@ -0,0 +1,214 @@
package s3api
import (
"context"
"fmt"
"io"
"math"
"mime"
"mime/multipart"
"net/http"
"net/textproto"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/security"
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
)
// canStreamCopyChunk reports whether the chunk-copy fast path can use the
// io.Pipe streaming variant. The streaming path bypasses both the s3-side
// download buffer and the s3-side multipart-encode buffer, holding only the
// io.Pipe internal buffer (~32 KiB) per copy in flight. It does not work
// when bytes need to be transformed in transit:
//
// - SSE-C / SSE-KMS / SSE-S3: bytes need to be re-encrypted with a
// different key on the destination, so they have to land in memory.
// - Per-chunk CipherKey (per-chunk encryption from the source): the
// source bytes need to be decrypted before being re-uploaded.
//
// In both cases the caller falls back to the buffered copySingleChunk path,
// which already handles those transformations correctly. The streaming
// path is still safe for IsCompressed chunks — gzip is end-to-end and we
// just forward the wire bytes (with the destination Content-Encoding
// header set to whatever the source actually returned).
func canStreamCopyChunk(chunk *filer_pb.FileChunk) bool {
if len(chunk.CipherKey) > 0 {
return false
}
if chunk.GetSseType() != filer_pb.SSEType_NONE {
return false
}
return true
}
// streamCopyChunkRange copies size bytes starting at offset from srcUrl to
// the destination volume identified by assignResult, using io.Pipe to avoid
// buffering the chunk in memory. The destination volume server expects the
// same multipart wire format that operation.upload_content writes — see
// upload_content.go for the canonical version; we mirror its part headers
// here so the volume's needle.parseUpload accepts the request.
//
// isFullChunk is the load-bearing distinction:
//
// - false (partial range): a Range header is sent to the source volume,
// which serves the requested byte range. For compressed chunks the
// volume internally decompresses to satisfy the range, then returns
// raw bytes (no Content-Encoding); we forward those raw bytes.
// - true (full chunk): we ask the source volume to send compressed
// bytes via Accept-Encoding: gzip, bypass Go's auto-decompression on
// resp.Body, and forward whatever wire bytes arrived to the
// destination. When the chunk is stored gzipped that means we never
// decompress on either the source-volume or s3-server side; the
// destination receives gzipped bytes and stores them as-is.
//
// For the Harbor-style assemble repro (where each UploadPartCopy range
// matches a source chunk boundary), the full-chunk path eliminates the
// "bytes.growSlice from util.DecompressData" cost that dominates the
// volume-side heap profile after the s3-side fixes.
//
// The destination's Content-Encoding header is set from the source's
// response Content-Encoding only — never from a caller-supplied hint.
// Trusting a hint that disagrees with the wire bytes (e.g. caller says
// "compressed" but the volume returned raw bytes for a partial range)
// would label raw bytes as gzip and corrupt reads on the destination.
func (s3a *S3ApiServer) streamCopyChunkRange(
ctx context.Context,
srcUrl, srcFileId string,
offset, size int64,
isFullChunk bool,
assignResult *filer_pb.AssignVolumeResponse,
) error {
// Range header takes int64, but mirror the int32 bound from
// downloadChunkData so the two paths reject the same inputs.
if size > int64(math.MaxInt32) {
return fmt.Errorf("chunk size %d exceeds maximum int32 size", size)
}
// Child context so a terminal error here unblocks both legs
// immediately. Without this, a failed POST closes pipeReader
// (which only fails the producer's writes), but the source GET's
// read loop would keep draining srcResp.Body in the background
// until EOF — wasting source-volume bandwidth and CPU on a copy
// that's already failed. Cancelling streamCtx tears down both the
// source GET and the destination POST when this function returns.
streamCtx, cancel := context.WithCancel(ctx)
defer cancel()
dstUrl := fmt.Sprintf("http://%s/%s", assignResult.Location.Url, assignResult.FileId)
dstJwt := security.EncodedJwt(assignResult.Auth)
srcJwt := filer.JwtForVolumeServer(srcFileId)
// Source GET: built directly (not through ReadUrlAsStream) because that
// helper auto-decompresses gzipped responses, which would defeat the
// whole-chunk pass-through optimization. We want the wire bytes.
srcReq, err := http.NewRequestWithContext(streamCtx, http.MethodGet, srcUrl, nil)
if err != nil {
return fmt.Errorf("create source GET: %w", err)
}
if srcJwt != "" {
srcReq.Header.Set("Authorization", "BEARER "+srcJwt)
}
if isFullChunk {
// Manually setting Accept-Encoding tells Go's http.Transport that
// the user wants raw bytes back — Go's automatic decompression is
// only applied when it adds the header itself. The server may or
// may not actually gzip; the response Content-Encoding header is
// authoritative.
srcReq.Header.Set("Accept-Encoding", "gzip")
} else {
srcReq.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", offset, offset+size-1))
}
srcResp, err := util_http.GetGlobalHttpClient().Do(srcReq)
if err != nil {
return fmt.Errorf("source GET: %w", err)
}
// CloseResponse drains and closes resp.Body for keepalive.
defer util_http.CloseResponse(srcResp)
if srcResp.StatusCode >= 400 {
return fmt.Errorf("source GET %s: %s", srcUrl, srcResp.Status)
}
// What's actually on the wire — trust this over caller hints. For range
// fetches the volume always returns raw bytes (no Content-Encoding); for
// full-chunk fetches it depends on whether the chunk is stored gzipped.
bodyIsGzipped := srcResp.Header.Get("Content-Encoding") == "gzip"
// io.Pipe gives us a synchronous handoff: the producer goroutine builds
// the multipart body, the consumer (HTTP transport) reads it. Writes
// block until reads consume them, so the in-flight footprint is the
// pipe's hand-off buffer — not the chunk size.
pipeReader, pipeWriter := io.Pipe()
mw := multipart.NewWriter(pipeWriter)
contentType := mw.FormDataContentType()
go func() {
// CloseWithError on the writer end propagates the failure to the
// HTTP transport reading from pipeReader, which then aborts the
// POST. Plain Close (with err==nil) sends EOF normally.
var producerErr error
defer func() {
pipeWriter.CloseWithError(producerErr)
}()
h := make(textproto.MIMEHeader)
h.Set("Content-Disposition", mime.FormatMediaType("form-data",
map[string]string{"name": "file", "filename": ""}))
h.Set("Idempotency-Key", dstUrl)
if bodyIsGzipped {
h.Set("Content-Encoding", "gzip")
}
fw, err := mw.CreatePart(h)
if err != nil {
producerErr = fmt.Errorf("multipart create part: %w", err)
return
}
if _, err := io.Copy(fw, srcResp.Body); err != nil {
if shouldLogStreamError(err) {
glog.V(2).Infof("stream copy %s offset=%d size=%d: %v",
srcUrl, offset, size, err)
}
producerErr = fmt.Errorf("stream copy: %w", err)
return
}
if err := mw.Close(); err != nil {
producerErr = fmt.Errorf("multipart close: %w", err)
return
}
}()
req, err := http.NewRequestWithContext(streamCtx, http.MethodPost, dstUrl, pipeReader)
if err != nil {
pipeReader.CloseWithError(err)
return fmt.Errorf("create POST request: %w", err)
}
req.Header.Set("Content-Type", contentType)
if dstJwt != "" {
req.Header.Set("Authorization", "BEARER "+string(dstJwt))
}
resp, err := util_http.GetGlobalHttpClient().Do(req)
if err != nil {
// Closing the reader unblocks the producer if it was still mid-write;
// the deferred cancel above also stops any in-flight source read.
pipeReader.CloseWithError(err)
return fmt.Errorf("POST: %w", err)
}
defer util_http.CloseResponse(resp)
if resp.StatusCode >= 400 {
return fmt.Errorf("POST %s: %s", dstUrl, resp.Status)
}
return nil
}
func shouldLogStreamError(err error) bool {
// io.ErrClosedPipe shows up when the HTTP transport closed pipeReader
// after the POST failed; the underlying error is reported via the POST
// path, no need to log twice.
return err != nil && err != io.ErrClosedPipe
}
+11 -6
View File
@@ -125,7 +125,7 @@ func (s3a *S3ApiServer) deleteVersionedObject(r *http.Request, bucket, object, v
glog.V(2).Infof("deleteVersionedObject: object lock check failed for %s/%s version %s: %v", bucket, object, versionId, err)
return result, s3err.ErrAccessDenied
}
if err := s3a.deleteSpecificObjectVersion(bucket, object, versionId); err != nil {
if err := s3a.deleteSpecificObjectVersion(bucket, object, versionId, false); err != nil {
glog.Errorf("deleteVersionedObject: failed to delete specific version %s for %s/%s: %v", versionId, bucket, object, err)
return result, s3err.ErrInternalError
}
@@ -148,7 +148,7 @@ func (s3a *S3ApiServer) deleteVersionedObject(r *http.Request, bucket, object, v
glog.V(2).Infof("deleteVersionedObject: object lock check failed for %s/%s null version: %v", bucket, object, err)
return result, s3err.ErrAccessDenied
}
if err := s3a.deleteSpecificObjectVersion(bucket, object, "null"); err != nil {
if err := s3a.deleteSpecificObjectVersion(bucket, object, "null", false); err != nil {
glog.Errorf("deleteVersionedObject: failed to delete null version for %s/%s: %v", bucket, object, err)
return result, s3err.ErrInternalError
}
@@ -166,10 +166,15 @@ func (s3a *S3ApiServer) deleteVersionedObject(r *http.Request, bucket, object, v
return result, s3err.ErrInternalError
}
func (s3a *S3ApiServer) deleteUnversionedObjectWithClient(client filer_pb.SeaweedFilerClient, bucket, object string) error {
// deleteUnversionedObjectWithClient removes the bare object entry. When
// metadataOnly is true the filer skips per-chunk DeleteFile RPCs and
// relies on the volume's natural TTL to reclaim chunks; pass true only
// when the entry's Attributes.TtlSec > 0 so the volume is guaranteed to
// drop the chunks on its own.
func (s3a *S3ApiServer) deleteUnversionedObjectWithClient(client filer_pb.SeaweedFilerClient, bucket, object string, metadataOnly bool) error {
target := util.NewFullPath(s3a.bucketDir(bucket), object)
dir, name := target.DirAndName()
return deleteObjectEntry(client, dir, name, true, false)
return deleteObjectEntry(client, dir, name, !metadataOnly, false)
}
func (s3a *S3ApiServer) DeleteObjectHandler(w http.ResponseWriter, r *http.Request) {
@@ -228,7 +233,7 @@ func (s3a *S3ApiServer) DeleteObjectHandler(w http.ResponseWriter, r *http.Reque
}
if err := s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
return s3a.deleteUnversionedObjectWithClient(client, bucket, object)
return s3a.deleteUnversionedObjectWithClient(client, bucket, object, false)
}); err != nil {
glog.Errorf("DeleteObjectHandler: failed to delete %s/%s: %v", bucket, object, err)
return s3err.ErrInternalError
@@ -370,7 +375,7 @@ func (s3a *S3ApiServer) DeleteMultipleObjectsHandler(w http.ResponseWriter, r *h
return s3err.ErrAccessDenied
}
if err := s3a.deleteUnversionedObjectWithClient(client, bucket, object.Key); err != nil {
if err := s3a.deleteUnversionedObjectWithClient(client, bucket, object.Key, false); err != nil {
glog.Errorf("DeleteMultipleObjectsHandler: failed to delete %s/%s: %v", bucket, object.Key, err)
return s3err.ErrInternalError
}
@@ -0,0 +1,66 @@
package s3api
import (
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestDeleteUnversionedObjectWithClient_MetadataOnlySkipsChunkDelete(t *testing.T) {
// metadataOnly=true must reach the filer as IsDeleteData=false so the
// volume server reclaims chunks via TTL instead of the filer enqueueing
// per-chunk DeleteFile RPCs.
s3a := &S3ApiServer{option: &S3ApiServerOption{BucketsPath: "/buckets"}}
client := &deleteObjectEntryTestClient{}
err := s3a.deleteUnversionedObjectWithClient(client, "b", "k", true)
require.NoError(t, err)
require.NotNil(t, client.deleteReq)
assert.Equal(t, "/buckets/b", client.deleteReq.Directory)
assert.Equal(t, "k", client.deleteReq.Name)
assert.False(t, client.deleteReq.IsDeleteData, "metadataOnly must clear IsDeleteData")
}
func TestDeleteUnversionedObjectWithClient_FullDeletePreservesIsDeleteData(t *testing.T) {
// Default behavior (metadataOnly=false): filer should still enqueue
// chunk deletions as before.
s3a := &S3ApiServer{option: &S3ApiServerOption{BucketsPath: "/buckets"}}
client := &deleteObjectEntryTestClient{}
err := s3a.deleteUnversionedObjectWithClient(client, "b", "k", false)
require.NoError(t, err)
require.NotNil(t, client.deleteReq)
assert.True(t, client.deleteReq.IsDeleteData, "default delete must keep IsDeleteData true")
}
func TestDeleteUnversionedObjectWithClient_FullPathFromBucketsRoot(t *testing.T) {
// Sanity: BucketsPath joins to <bucketsPath>/<bucket>/<object> in the
// DeleteEntryRequest so the filer can locate the entry. Object keys
// with multiple path segments should split into Directory + Name
// correctly.
s3a := &S3ApiServer{option: &S3ApiServerOption{BucketsPath: "/buckets"}}
client := &deleteObjectEntryTestClient{}
err := s3a.deleteUnversionedObjectWithClient(client, "mybucket", "a/b/c.txt", false)
require.NoError(t, err)
require.NotNil(t, client.deleteReq)
assert.Equal(t, "/buckets/mybucket/a/b", client.deleteReq.Directory)
assert.Equal(t, "c.txt", client.deleteReq.Name)
}
func TestDeleteUnversionedObjectWithClient_PropagatesEntryAttributesIrrelevant(t *testing.T) {
// The metadataOnly decision is the caller's responsibility (the
// lifecycle handler). This function is dumb plumbing — it must not
// inspect the entry itself, only translate the bool to IsDeleteData.
s3a := &S3ApiServer{option: &S3ApiServerOption{BucketsPath: "/buckets"}}
client := &deleteObjectEntryTestClient{
// A response with no error is fine; attributes on a delete are unused.
deleteResp: &filer_pb.DeleteEntryResponse{},
}
require.NoError(t, s3a.deleteUnversionedObjectWithClient(client, "b", "k", true))
require.NotNil(t, client.deleteReq)
assert.False(t, client.deleteReq.IsDeleteData)
}
+6 -1
View File
@@ -1341,9 +1341,14 @@ func (s3a *S3ApiServer) updateIsLatestFlagsForSuspendedVersioning(bucket, object
// Clear the latest version metadata from .versions directory since "null" is now latest
versionsEntry, err := s3a.getEntry(bucketDir, versionsObjectPath)
if err == nil && versionsEntry.Extended != nil {
// Remove latest version metadata so all versions show IsLatest=false
// Remove latest version metadata so all versions show IsLatest=false.
// Also wipe cached list-metadata (size/mtime/etag/owner/delete-marker):
// they were stamped from the prior latest, and stale cached mtime
// would let lifecycle compute SuccessorModTime off the displaced
// version's age rather than today's null PUT.
delete(versionsEntry.Extended, s3_constants.ExtLatestVersionIdKey)
delete(versionsEntry.Extended, s3_constants.ExtLatestVersionFileNameKey)
clearCachedVersionMetadata(versionsEntry.Extended)
// Update the .versions directory entry
err = s3a.mkFile(bucketDir, versionsObjectPath, versionsEntry.Chunks, func(updatedEntry *filer_pb.Entry) {
+7 -4
View File
@@ -964,8 +964,11 @@ func (s3a *S3ApiServer) getSpecificObjectVersion(bucket, object, versionId strin
return entry, nil
}
// deleteSpecificObjectVersion deletes a specific version of an object
func (s3a *S3ApiServer) deleteSpecificObjectVersion(bucket, object, versionId string) error {
// deleteSpecificObjectVersion deletes a specific version of an object.
// metadataOnly=true skips per-chunk DeleteFile RPCs at the filer; only
// pass true when the live entry's Attributes.TtlSec > 0 so the volume
// reclaims chunks on its own.
func (s3a *S3ApiServer) deleteSpecificObjectVersion(bucket, object, versionId string, metadataOnly bool) error {
// Normalize object path to ensure consistency with toFilerPath behavior
normalizedObject := s3_constants.NormalizeObjectKey(object)
@@ -986,7 +989,7 @@ func (s3a *S3ApiServer) deleteSpecificObjectVersion(bucket, object, versionId st
}
// Delete the regular file
deleteErr := s3a.rmObject(bucketDir, normalizedObject, true, false)
deleteErr := s3a.rmObject(bucketDir, normalizedObject, !metadataOnly, false)
if deleteErr != nil {
// Check if file was already deleted by another process
if _, checkErr := s3a.getEntry(bucketDir, normalizedObject); checkErr != nil {
@@ -1013,7 +1016,7 @@ func (s3a *S3ApiServer) deleteSpecificObjectVersion(bucket, object, versionId st
// Attempt to delete the version file
// Note: We don't check if the file exists first to avoid race conditions
// The deletion operation should be idempotent
deleteErr := s3a.rm(versionsDir, versionFile, true, false)
deleteErr := s3a.rm(versionsDir, versionFile, !metadataOnly, false)
if deleteErr != nil {
// Check if file was already deleted by another process (race condition handling)
if _, checkErr := s3a.getEntry(versionsDir, versionFile); checkErr != nil {
@@ -0,0 +1,33 @@
package bootstrap
import (
"testing"
"github.com/stretchr/testify/assert"
)
// HasPrefix is a thin wrapper around strings.HasPrefix exported by the
// bootstrap package so call sites can avoid pulling strings just to do
// a prefix check. Trivial but at 0% coverage — pin it.
func TestHasPrefix(t *testing.T) {
cases := []struct {
name string
path string
prefix string
want bool
}{
{"matching prefix", "logs/2026/01/01", "logs/", true},
{"exact match", "logs/", "logs/", true},
{"non-matching prefix", "metrics/x", "logs/", false},
{"shorter than prefix", "logs", "logs/", false},
{"empty prefix matches all", "anything", "", true},
{"both empty", "", "", true},
{"empty input non-empty prefix", "", "x", false},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
assert.Equal(t, c.want, HasPrefix(c.path, c.prefix))
})
}
}
+10 -4
View File
@@ -135,10 +135,16 @@ func walkEntry(ctx context.Context, snap *engine.Snapshot, bucket string, entry
if action == nil {
continue
}
// SCAN_AT_DATE runs its own date-triggered bootstrap. DISABLED can
// be flipped at runtime independent of XML Status, so skip it even
// though EvaluateAction would also reject.
if action.Mode == engine.ModeScanAtDate || action.Mode == engine.ModeDisabled {
// DISABLED can be flipped at runtime independent of XML Status,
// so skip it even though EvaluateAction would also reject.
// SCAN_AT_DATE actions are processed here too — the date check
// in EvaluateAction (now.Before(rule.ExpirationDate)) gates the
// dispatch, so pre-date walks are no-ops and post-date walks
// expire eligible objects. The earlier "scan-at-date runs its
// own bootstrap" plan was never wired; until that lands, the
// regular bootstrap walk is the only path that fires
// ExpirationDate rules.
if action.Mode == engine.ModeDisabled {
continue
}
// (kind, info) shape gate: ABORT_MPU only on MPU init records,
@@ -164,9 +164,10 @@ func TestWalk_NotYetDueSkipped(t *testing.T) {
}
}
func TestWalk_DateActionsSkipped(t *testing.T) {
// Date kind is handled by its own SCAN_AT_DATE bootstrap, not by the
// regular bootstrap walker.
func TestWalk_DateActionFiresAfterDate(t *testing.T) {
// The dedicated SCAN_AT_DATE bootstrap was never wired; until it
// lands, the regular bootstrap walker is the only path that fires
// ExpirationDate rules. Entries past the rule's date must dispatch.
date := mustTime(t, "2025-06-15T00:00:00Z")
rule := &s3lifecycle.Rule{
ID: "d",
@@ -181,8 +182,30 @@ func TestWalk_DateActionsSkipped(t *testing.T) {
}), rec, WalkOptions{Now: date.AddDate(0, 1, 0)}); err != nil {
t.Fatalf("Walk: %v", err)
}
if len(rec.calls) != 1 || rec.calls[0].path != "x/a" {
t.Fatalf("date kind past the rule date must dispatch, got %v", rec.calls)
}
}
func TestWalk_DateActionSkippedBeforeDate(t *testing.T) {
// Pre-date walks are no-ops: EvaluateAction returns ActionNone when
// now is before rule.ExpirationDate.
date := mustTime(t, "2025-06-15T00:00:00Z")
rule := &s3lifecycle.Rule{
ID: "d",
Status: s3lifecycle.StatusEnabled,
ExpirationDate: date,
}
snap := compileEvDriven(t, "bk", rule)
rec := &recorder{}
if _, err := Walk(context.Background(), snap, "bk", EntryCallback([]*Entry{
{Path: "x/a", IsLatest: true, ModTime: mustTime(t, "2024-01-01T00:00:00Z")},
}), rec, WalkOptions{Now: date.AddDate(0, -1, 0)}); err != nil {
t.Fatalf("Walk: %v", err)
}
if len(rec.calls) != 0 {
t.Fatalf("date kind should not dispatch from walker, got %v", rec.calls)
t.Fatalf("pre-date walk must not dispatch, got %v", rec.calls)
}
}
@@ -98,10 +98,16 @@ func (d *Dispatcher) Tick(ctx context.Context, now time.Time) int {
d.retries = map[retryKey]int{}
}
due := d.Schedule.Drain(now)
for _, m := range due {
for i, m := range due {
if err := ctx.Err(); err != nil {
// Re-queue and return; the caller is shutting down.
d.Schedule.Add(m)
// Caller is shutting down. Re-queue every remaining drained
// Match (current and any not yet visited) so they're not
// lost across the worker restart — the schedule already
// popped them all out, so the dispatcher owns putting them
// back.
for _, rem := range due[i:] {
d.Schedule.Add(rem)
}
return 0
}
d.dispatchOne(ctx, m, now)
@@ -0,0 +1,109 @@
package dispatcher
import (
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/router"
"github.com/stretchr/testify/assert"
)
// Direct coverage for dispatcher pure helpers (keyOf, budget, backoff)
// and the retryKey identity that drives the retry-budget map. The
// existing dispatcher tests exercise these only through Tick; pinning
// each one separately makes a regression in the helper itself fail at
// the helper level.
func TestKeyOf_DerivesIdentityFromMatch(t *testing.T) {
hash := [8]byte{0xde, 0xad, 0xbe, 0xef, 1, 2, 3, 4}
m := router.Match{
Key: s3lifecycle.ActionKey{
Bucket: "bk",
RuleHash: hash,
ActionKind: s3lifecycle.ActionKindExpirationDays,
},
ObjectKey: "obj.txt",
VersionID: "v_abc",
}
got := keyOf(m)
assert.Equal(t, "bk", got.bucket)
assert.Equal(t, hash, got.ruleHash)
assert.Equal(t, s3lifecycle.ActionKindExpirationDays, got.kind)
assert.Equal(t, "obj.txt", got.objectKey)
assert.Equal(t, "v_abc", got.versionID)
}
func TestKeyOf_EqualMatchesProduceEqualKeys(t *testing.T) {
// retryKey is used as a map key in the retry budget; equality must
// hold between two Match values with identical fields so the second
// dispatch finds the first's retry counter.
hash := [8]byte{0xde, 0xad, 0xbe, 0xef}
m1 := router.Match{
Key: s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: s3lifecycle.ActionKindExpirationDays},
ObjectKey: "obj",
VersionID: "v_x",
}
m2 := m1
assert.Equal(t, keyOf(m1), keyOf(m2))
}
func TestKeyOf_DistinctVersionIDsProduceDistinctKeys(t *testing.T) {
// Two versions of the same logical object must NOT share a retry
// budget; otherwise a noisy version could starve a healthy one.
base := router.Match{
Key: s3lifecycle.ActionKey{Bucket: "bk", ActionKind: s3lifecycle.ActionKindNoncurrentDays},
ObjectKey: "obj",
VersionID: "v_a",
}
other := base
other.VersionID = "v_b"
assert.NotEqual(t, keyOf(base), keyOf(other))
}
func TestKeyOf_DistinctActionKindsProduceDistinctKeys(t *testing.T) {
// The same (bucket, object, version) hit by two different action
// kinds must each have their own retry budget.
base := router.Match{
Key: s3lifecycle.ActionKey{Bucket: "bk", ActionKind: s3lifecycle.ActionKindExpirationDays},
ObjectKey: "obj",
}
other := base
other.Key.ActionKind = s3lifecycle.ActionKindNoncurrentDays
assert.NotEqual(t, keyOf(base), keyOf(other))
}
func TestDispatcherBudget_ReturnsConfiguredValueWhenSet(t *testing.T) {
d := &Dispatcher{RetryBudget: 9}
assert.Equal(t, 9, d.budget())
}
func TestDispatcherBudget_FallsBackToDefaultWhenZero(t *testing.T) {
// Operators leaving the budget at zero opt into the documented
// default. A regression that returns 0 would NOOP every retry.
d := &Dispatcher{}
assert.Equal(t, defaultRetryBudget, d.budget())
}
func TestDispatcherBudget_NegativeFallsBackToDefault(t *testing.T) {
// budget() guards on > 0, so a negative value falls back rather
// than producing nonsense. Pin the contract so a refactor that
// flips the comparison is caught.
d := &Dispatcher{RetryBudget: -1}
assert.Equal(t, defaultRetryBudget, d.budget())
}
func TestDispatcherBackoff_ReturnsConfiguredValueWhenSet(t *testing.T) {
d := &Dispatcher{RetryBackoff: 5 * time.Second}
assert.Equal(t, 5*time.Second, d.backoff())
}
func TestDispatcherBackoff_FallsBackToDefaultWhenZero(t *testing.T) {
d := &Dispatcher{}
assert.Equal(t, defaultRetryBackoff, d.backoff())
}
func TestDispatcherBackoff_NegativeFallsBackToDefault(t *testing.T) {
d := &Dispatcher{RetryBackoff: -time.Second}
assert.Equal(t, defaultRetryBackoff, d.backoff())
}
@@ -0,0 +1,134 @@
package dispatcher
import (
"context"
"errors"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/s3_lifecycle_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/router"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// errFilerStore satisfies FilerStore with a forced Read error so the
// Load path's "non-NotFound transport error" branch is reachable.
// Save mirrors the pattern; tests for the nil-Store branch don't need
// a stub at all.
type errFilerStore struct {
readErr error
saveErr error
readData []byte
}
func (e *errFilerStore) Read(_ context.Context, _, _ string) ([]byte, error) {
if e.readErr != nil {
return nil, e.readErr
}
return e.readData, nil
}
func (e *errFilerStore) Save(_ context.Context, _, _ string, _ []byte) error {
return e.saveErr
}
// ---------- FilerPersister edges ----------
func TestFilerPersisterLoad_NilStoreErrors(t *testing.T) {
// The persister's Store dependency is required; loading with a nil
// Store must error rather than panic on the Read call.
p := &FilerPersister{}
_, err := p.Load(context.Background(), 0)
require.Error(t, err)
assert.Contains(t, err.Error(), "nil Store")
}
func TestFilerPersisterSave_NilStoreErrors(t *testing.T) {
p := &FilerPersister{}
err := p.Save(context.Background(), 0, map[s3lifecycle.ActionKey]int64{})
require.Error(t, err)
assert.Contains(t, err.Error(), "nil Store")
}
func TestFilerPersisterLoad_NonNotFoundErrorIsWrapped(t *testing.T) {
// A transport-level error (anything that isn't ErrNotFound) wraps
// with the shard ID context so operators can attribute it. Pin
// both that the error surfaces and that the original is recoverable
// via errors.Is so a caller can distinguish.
want := errors.New("filer-side bang")
p := &FilerPersister{Store: &errFilerStore{readErr: want}}
_, err := p.Load(context.Background(), 3)
require.Error(t, err)
assert.ErrorIs(t, err, want)
assert.Contains(t, err.Error(), "shard=3")
}
func TestFilerPersisterLoad_EmptyContentReturnsEmptyMap(t *testing.T) {
// Read returning a successful empty []byte means "file exists but
// is zero length"; the persister must treat this as "no entries"
// rather than try to JSON-decode an empty slice and return an
// error.
p := &FilerPersister{Store: &errFilerStore{readData: []byte{}}}
got, err := p.Load(context.Background(), 0)
require.NoError(t, err)
assert.NotNil(t, got)
assert.Empty(t, got)
}
// ---------- Tick edges ----------
func TestTick_InitializesRetriesMapOnFirstCall(t *testing.T) {
// retries is a lazy map; a Dispatcher constructed without it must
// not panic on the first Tick. Pin that handleRetryLater can write
// into the map afterwards (proven by the dispatcher returning an
// integer rather than crashing).
d, sched := newDispatcher(&fakeClient{
respond: func(int) (*s3_lifecycle_pb.LifecycleDeleteResponse, error) {
return &s3_lifecycle_pb.LifecycleDeleteResponse{Outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_DONE}, nil
},
})
require.Nil(t, d.retries, "preconditions: retries map starts nil")
t0 := time.Now()
sched.Add(router.Match{
Key: s3lifecycle.ActionKey{Bucket: "bk", ActionKind: s3lifecycle.ActionKindExpirationDays},
ObjectKey: "k",
DueTime: t0,
})
processed := d.Tick(context.Background(), t0.Add(time.Hour))
assert.Equal(t, 1, processed)
assert.NotNil(t, d.retries, "Tick must initialize the retries map")
}
func TestTick_CtxShutdownMidLoopRequeuesAndReturnsZero(t *testing.T) {
// If ctx is canceled before Tick starts dispatching, the entire
// drained batch must be re-queued. Drain pops ALL due matches at
// once, so a naive "re-add the current Match only" would silently
// lose every Match past the cancellation point. Three matches
// here exercises that the loop re-queues the current AND every
// remaining drained entry.
calls := 0
client := &fakeClient{
respond: func(int) (*s3_lifecycle_pb.LifecycleDeleteResponse, error) {
calls++
return &s3_lifecycle_pb.LifecycleDeleteResponse{Outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_DONE}, nil
},
}
d, sched := newDispatcher(client)
t0 := time.Now()
for _, k := range []string{"k1", "k2", "k3"} {
sched.Add(router.Match{
Key: s3lifecycle.ActionKey{Bucket: "bk", ActionKind: s3lifecycle.ActionKindExpirationDays},
ObjectKey: k,
DueTime: t0,
})
}
ctx, cancel := context.WithCancel(context.Background())
cancel() // shutdown before Tick even starts dispatching
processed := d.Tick(ctx, t0.Add(time.Hour))
assert.Equal(t, 0, processed, "shutdown must report zero processed")
assert.Equal(t, 0, calls, "shutdown must skip every dispatch call")
assert.Equal(t, 3, sched.Len(), "every drained Match must be re-queued — none lost")
}
@@ -0,0 +1,275 @@
package dispatcher
import (
"context"
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/s3_lifecycle_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/reader"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/router"
)
// Layer 2 component tests for the dispatcher pipeline mechanics:
// the per-shard composition that Pipeline.Run wires up at runtime
// (cursors, schedules, dispatchers, persister), exercised directly so
// the tests stay independent of a live filer connection. Pipeline.Run
// itself can't run here because it builds a real reader.Reader; these
// tests instead drive Tick directly while sharing the same fakeClient
// that dispatcher_test.go uses.
// shardKit bundles the per-shard state Pipeline.Run constructs in
// production: a Cursor, a Schedule, and a Dispatcher hooked to both.
type shardKit struct {
id int
cursor *reader.Cursor
dispatch *Dispatcher
}
func newShardKit(t *testing.T, id int, client LifecycleClient) *shardKit {
t.Helper()
c := reader.NewCursor()
return &shardKit{
id: id,
cursor: c,
dispatch: &Dispatcher{
ShardID: id,
Client: client,
Cursor: c,
Schedule: router.NewSchedule(),
RetryBudget: 3,
RetryBackoff: time.Millisecond,
},
}
}
// recordingClient lets Layer 2 tests assert exactly which RPCs the
// dispatcher made. Goroutine-safe because Tick is called from test
// goroutines but inspections happen from the test goroutine.
type recordingClient struct {
mu sync.Mutex
requests []*s3_lifecycle_pb.LifecycleDeleteRequest
respond func(req *s3_lifecycle_pb.LifecycleDeleteRequest) (*s3_lifecycle_pb.LifecycleDeleteResponse, error)
}
func (r *recordingClient) LifecycleDelete(ctx context.Context, req *s3_lifecycle_pb.LifecycleDeleteRequest) (*s3_lifecycle_pb.LifecycleDeleteResponse, error) {
r.mu.Lock()
r.requests = append(r.requests, req)
r.mu.Unlock()
return r.respond(req)
}
func TestPipelineMultiShardFanOutKeepsCursorsIsolated(t *testing.T) {
// Two events for two different shards land in different schedules
// and dispatch independently. Each shard's cursor advances only
// for the event(s) targeting that shard.
client := &recordingClient{
respond: func(*s3_lifecycle_pb.LifecycleDeleteRequest) (*s3_lifecycle_pb.LifecycleDeleteResponse, error) {
return &s3_lifecycle_pb.LifecycleDeleteResponse{Outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_DONE}, nil
},
}
shards := map[int]*shardKit{
0: newShardKit(t, 0, client),
1: newShardKit(t, 1, client),
}
t0 := time.Now()
mA := router.Match{
Key: s3lifecycle.ActionKey{Bucket: "bk", ActionKind: s3lifecycle.ActionKindExpirationDays},
EventTs: t0,
DueTime: t0,
Bucket: "bk",
ObjectKey: "alpha",
}
// Use a different action kind on shard 1 so the cursor key differs
// from shard 0 — shared keys would write to the same cursor entry.
mB := router.Match{
Key: s3lifecycle.ActionKey{Bucket: "bk", ActionKind: s3lifecycle.ActionKindNoncurrentDays},
EventTs: t0.Add(time.Second),
DueTime: t0.Add(time.Second),
Bucket: "bk",
ObjectKey: "beta",
}
shards[0].dispatch.Schedule.Add(mA)
shards[1].dispatch.Schedule.Add(mB)
// Tick shard 0 first; shard 1's schedule must still hold its match.
if got := shards[0].dispatch.Tick(context.Background(), t0.Add(time.Hour)); got != 1 {
t.Fatalf("shard 0 Tick processed=%d, want 1", got)
}
if got := shards[1].dispatch.Schedule.Len(); got != 1 {
t.Fatalf("shard 1 schedule must not be drained by shard 0 Tick: len=%d", got)
}
// Now tick shard 1.
if got := shards[1].dispatch.Tick(context.Background(), t0.Add(time.Hour)); got != 1 {
t.Fatalf("shard 1 Tick processed=%d, want 1", got)
}
if shards[0].cursor.Get(mA.Key) != mA.EventTs.UnixNano() {
t.Fatalf("shard 0 cursor not advanced: got %d", shards[0].cursor.Get(mA.Key))
}
if shards[1].cursor.Get(mB.Key) != mB.EventTs.UnixNano() {
t.Fatalf("shard 1 cursor not advanced: got %d", shards[1].cursor.Get(mB.Key))
}
// Cursors must NOT cross-contaminate.
if shards[0].cursor.Get(mB.Key) != 0 {
t.Fatalf("shard 0 cursor saw shard 1's key: got %d", shards[0].cursor.Get(mB.Key))
}
}
func TestPipelineCursorFreezeOnOneShardDoesntBlockOthers(t *testing.T) {
// Shard 0 dispatches a poison event that returns BLOCKED — its
// cursor freezes at the event TsNs. Shard 1's progress must be
// independent: it dispatches successfully and advances.
client := &recordingClient{
respond: func(req *s3_lifecycle_pb.LifecycleDeleteRequest) (*s3_lifecycle_pb.LifecycleDeleteResponse, error) {
if req.Bucket == "bk" && req.ObjectPath == "poison" {
return &s3_lifecycle_pb.LifecycleDeleteResponse{Outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_BLOCKED}, nil
}
return &s3_lifecycle_pb.LifecycleDeleteResponse{Outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_DONE}, nil
},
}
shards := map[int]*shardKit{
0: newShardKit(t, 0, client),
1: newShardKit(t, 1, client),
}
t0 := time.Now()
poison := router.Match{
Key: s3lifecycle.ActionKey{Bucket: "bk", ActionKind: s3lifecycle.ActionKindExpirationDays},
EventTs: t0,
DueTime: t0,
Bucket: "bk",
ObjectKey: "poison",
}
good := router.Match{
Key: s3lifecycle.ActionKey{Bucket: "bk", ActionKind: s3lifecycle.ActionKindNoncurrentDays},
EventTs: t0.Add(time.Second),
DueTime: t0.Add(time.Second),
Bucket: "bk",
ObjectKey: "good",
}
shards[0].dispatch.Schedule.Add(poison)
shards[1].dispatch.Schedule.Add(good)
shards[0].dispatch.Tick(context.Background(), t0.Add(time.Hour))
shards[1].dispatch.Tick(context.Background(), t0.Add(time.Hour))
if !shards[0].cursor.IsFrozen(poison.Key) {
t.Fatalf("shard 0 cursor must freeze on BLOCKED outcome")
}
if shards[1].cursor.IsFrozen(good.Key) {
t.Fatalf("shard 1 cursor must not freeze when shard 0 fails")
}
if shards[1].cursor.Get(good.Key) != good.EventTs.UnixNano() {
t.Fatalf("shard 1 cursor must advance independently: got %d", shards[1].cursor.Get(good.Key))
}
}
func TestPipelinePersisterCheckpointRoundTripsEveryShard(t *testing.T) {
// A cursor checkpoint persists the per-shard map; a fresh dispatcher
// can Restore from that map and resume at the same TsNs. Pipeline.Run
// drives this on a ticker; tests exercise the contract directly.
client := &recordingClient{
respond: func(*s3_lifecycle_pb.LifecycleDeleteRequest) (*s3_lifecycle_pb.LifecycleDeleteResponse, error) {
return &s3_lifecycle_pb.LifecycleDeleteResponse{Outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_DONE}, nil
},
}
shards := map[int]*shardKit{
0: newShardKit(t, 0, client),
1: newShardKit(t, 1, client),
}
t0 := time.Now()
addAndTick := func(s *shardKit, obj string, kind s3lifecycle.ActionKind, ts time.Time) {
s.dispatch.Schedule.Add(router.Match{
Key: s3lifecycle.ActionKey{Bucket: "bk", ActionKind: kind},
EventTs: ts,
DueTime: ts,
Bucket: "bk",
ObjectKey: obj,
})
s.dispatch.Tick(context.Background(), t0.Add(time.Hour))
}
addAndTick(shards[0], "alpha", s3lifecycle.ActionKindExpirationDays, t0)
addAndTick(shards[1], "beta", s3lifecycle.ActionKindNoncurrentDays, t0.Add(time.Second))
pers := reader.NewInMemoryPersister()
for id, s := range shards {
if err := pers.Save(context.Background(), id, s.cursor.Snapshot()); err != nil {
t.Fatalf("save shard %d: %v", id, err)
}
}
// Restore into fresh cursors, verify every shard's TsNs round-trips.
for id, s := range shards {
state, err := pers.Load(context.Background(), id)
if err != nil {
t.Fatalf("load shard %d: %v", id, err)
}
c := reader.NewCursor()
c.Restore(state)
want := s.cursor.Snapshot()
got := c.Snapshot()
if len(got) != len(want) {
t.Fatalf("shard %d snapshot len: got %d, want %d", id, len(got), len(want))
}
for k, v := range want {
if got[k] != v {
t.Fatalf("shard %d cursor key %v: got %d, want %d", id, k, got[k], v)
}
}
}
}
func TestPipelineRetryLaterRespectsDispatchTickCadence(t *testing.T) {
// RETRY_LATER schedules the match for a later DueTime. A Tick at
// the present moment must NOT re-dispatch it; only a Tick past
// the new DueTime triggers a second RPC. This pins the cadence
// contract against premature retries from later refresh ticks.
calls := 0
client := &recordingClient{
respond: func(*s3_lifecycle_pb.LifecycleDeleteRequest) (*s3_lifecycle_pb.LifecycleDeleteResponse, error) {
calls++
if calls == 1 {
return &s3_lifecycle_pb.LifecycleDeleteResponse{Outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_RETRY_LATER}, nil
}
return &s3_lifecycle_pb.LifecycleDeleteResponse{Outcome: s3_lifecycle_pb.LifecycleDeleteOutcome_DONE}, nil
},
}
s := newShardKit(t, 0, client)
s.dispatch.RetryBackoff = time.Hour // long backoff so the second Tick at t0+1m doesn't fire
t0 := time.Now()
m := router.Match{
Key: s3lifecycle.ActionKey{Bucket: "bk", ActionKind: s3lifecycle.ActionKindExpirationDays},
EventTs: t0,
DueTime: t0,
Bucket: "bk",
ObjectKey: "obj",
}
s.dispatch.Schedule.Add(m)
if got := s.dispatch.Tick(context.Background(), t0); got != 1 {
t.Fatalf("first Tick processed=%d, want 1 (RETRY_LATER counts as processed)", got)
}
// Within the backoff window: nothing fires.
if got := s.dispatch.Tick(context.Background(), t0.Add(time.Minute)); got != 0 {
t.Fatalf("Tick within backoff must skip: processed=%d", got)
}
if calls != 1 {
t.Fatalf("RPC must not retry within backoff: calls=%d", calls)
}
// Past backoff: re-dispatches.
if got := s.dispatch.Tick(context.Background(), t0.Add(2*time.Hour)); got != 1 {
t.Fatalf("Tick past backoff must re-dispatch: processed=%d", got)
}
if calls != 2 {
t.Fatalf("expected exactly 2 calls (initial + one retry), got %d", calls)
}
}
@@ -205,6 +205,8 @@ func (p *Pipeline) Run(ctx context.Context) error {
cancel() // wake the dispatcher goroutine to drain & exit
}()
lister := &filerSiblingLister{client: p.FilerClient, bucketsPath: p.BucketsPath}
// Router/dispatcher goroutine: pulls events, routes them to per-shard
// schedules, ticks every shard's dispatcher on the same cadence, and
// checkpoints every shard's cursor on the checkpoint cadence. One
@@ -257,7 +259,7 @@ func (p *Pipeline) Run(ctx context.Context) error {
// against the prior (empty) snapshot would silently drop
// every match. Engine.Snapshot is an atomic Load.
snap := p.Engine.Snapshot()
for _, m := range router.Route(snap, ev, time.Now()) {
for _, m := range router.Route(runCtx, snap, ev, time.Now(), lister) {
st.dispatch.Schedule.Add(m)
}
case <-dt.C:
@@ -0,0 +1,189 @@
package dispatcher
import (
"context"
"errors"
"strconv"
"sync"
"testing"
"time"
"github.com/prometheus/client_golang/prometheus/testutil"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/reader"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/router"
stats_collect "github.com/seaweedfs/seaweedfs/weed/stats"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// Direct tests for dispatcher / pipeline pure helpers and their side
// effects on the Prometheus surface. The Tick + Run integration tests
// drive these only as one slice of a larger flow; pinning each helper
// individually makes a regression in the helper itself fail at the
// helper level.
// ---------- observeScheduleDepth ----------
func TestObserveScheduleDepth_ReportsScheduleLen(t *testing.T) {
// observeScheduleDepth sets the gauge to the current Schedule.Len.
// The dispatcher calls it on every Tick so operators can see how
// far behind schedule the worker is. Use a distinct shard label so
// other tests sharing the global gauge don't bleed in.
const shard = 137
d := &Dispatcher{ShardID: shard, Schedule: router.NewSchedule()}
g := stats_collect.S3LifecycleScheduleDepthGauge.WithLabelValues(strconv.Itoa(shard))
// Drop the label series at end of test so the global registry
// doesn't accumulate stale entries across test runs in the same
// process.
defer stats_collect.S3LifecycleScheduleDepthGauge.DeleteLabelValues(strconv.Itoa(shard))
// Empty schedule -> 0.
d.observeScheduleDepth()
assert.Equal(t, float64(0), testutil.ToFloat64(g))
// Adding two matches lifts the gauge to 2 on the next observe.
t0 := time.Now()
d.Schedule.Add(router.Match{DueTime: t0})
d.Schedule.Add(router.Match{DueTime: t0.Add(time.Second)})
d.observeScheduleDepth()
assert.Equal(t, float64(2), testutil.ToFloat64(g))
// Draining drops it back to 0; Tick would re-call but observe is a
// pure setter so we drive it manually here.
_ = d.Schedule.Drain(t0.Add(2 * time.Second))
d.observeScheduleDepth()
assert.Equal(t, float64(0), testutil.ToFloat64(g))
}
// ---------- ensureEventsChan ----------
func TestEnsureEventsChan_HonorsEventBuffer(t *testing.T) {
p := &Pipeline{EventBuffer: 7}
p.ensureEventsChan()
require.NotNil(t, p.events)
assert.Equal(t, 7, cap(p.events), "EventBuffer must size the channel")
require.NotNil(t, p.eventsReady)
}
func TestEnsureEventsChan_FallsBackToDefault(t *testing.T) {
// EventBuffer=0 means "use the default"; non-positive must not
// produce a zero-sized channel that would block every InjectEvent.
p := &Pipeline{}
p.ensureEventsChan()
assert.Equal(t, defaultEventBuffer, cap(p.events))
}
func TestEnsureEventsChan_NegativeFallsBackToDefault(t *testing.T) {
p := &Pipeline{EventBuffer: -1}
p.ensureEventsChan()
assert.Equal(t, defaultEventBuffer, cap(p.events))
}
func TestEnsureEventsChan_IdempotentAcrossConcurrentCallers(t *testing.T) {
// sync.Once must guarantee a single channel allocation under
// concurrent calls; otherwise a races would create two channels
// and lose events on the discarded one.
p := &Pipeline{EventBuffer: 4}
const N = 32
var wg sync.WaitGroup
wg.Add(N)
for i := 0; i < N; i++ {
go func() {
defer wg.Done()
p.ensureEventsChan()
}()
}
wg.Wait()
require.NotNil(t, p.events)
assert.Equal(t, 4, cap(p.events))
}
// ---------- InjectEvent ----------
func TestInjectEvent_DeliversToEventsChannel(t *testing.T) {
p := &Pipeline{EventBuffer: 1}
ev := &reader.Event{Bucket: "bk", Key: "k"}
require.NoError(t, p.InjectEvent(context.Background(), ev))
select {
case got := <-p.events:
assert.Same(t, ev, got, "InjectEvent must deliver the same pointer")
default:
t.Fatal("event was not enqueued")
}
}
func TestInjectEvent_ReturnsCtxErrWhenCanceled(t *testing.T) {
// A canceled context must propagate the cancellation; otherwise
// the bootstrap walker could keep injecting after the worker is
// shutting down. ensureEventsChan clamps EventBuffer<=0 to the
// default, so to force the select to actually block we pre-fill
// the buffer (size 1) and then send into the canceled context.
p := &Pipeline{EventBuffer: 1}
require.NoError(t, p.InjectEvent(context.Background(), &reader.Event{}))
ctx, cancel := context.WithCancel(context.Background())
cancel()
err := p.InjectEvent(ctx, &reader.Event{})
require.Error(t, err)
assert.ErrorIs(t, err, context.Canceled)
}
func TestInjectEvent_EnsureEventsChanCalledIfFirstCall(t *testing.T) {
// InjectEvent must call ensureEventsChan internally so a caller can
// inject before Run starts (e.g. bootstrap walks that fire before
// the reader is up). Pin that the channel exists post-call.
p := &Pipeline{}
require.Nil(t, p.events, "preconditions: events not yet allocated")
require.NoError(t, p.InjectEvent(context.Background(), &reader.Event{}))
require.NotNil(t, p.events, "InjectEvent must allocate the channel via ensureEventsChan")
}
// ---------- isCtxShutdown ----------
func TestIsCtxShutdown_NilIsNotShutdown(t *testing.T) {
assert.False(t, isCtxShutdown(nil))
}
func TestIsCtxShutdown_ContextCanceledIsShutdown(t *testing.T) {
assert.True(t, isCtxShutdown(context.Canceled))
assert.True(t, isCtxShutdown(context.DeadlineExceeded))
}
func TestIsCtxShutdown_GRPCCanceledStatusIsShutdown(t *testing.T) {
// Filer / S3 RPCs can come back wrapped as gRPC status codes; the
// helper must recognize Canceled / DeadlineExceeded by code so a
// shutdown doesn't get misclassified as a transport failure.
assert.True(t, isCtxShutdown(status.Error(codes.Canceled, "client closed")))
assert.True(t, isCtxShutdown(status.Error(codes.DeadlineExceeded, "stream timeout")))
}
func TestIsCtxShutdown_OtherErrorsAreNotShutdown(t *testing.T) {
// A garden-variety transport error must NOT classify as shutdown;
// otherwise the worker would silently swallow real failures.
assert.False(t, isCtxShutdown(errors.New("connection refused")))
assert.False(t, isCtxShutdown(status.Error(codes.Unavailable, "filer down")))
assert.False(t, isCtxShutdown(status.Error(codes.Internal, "boom")))
}
// ---------- cursorFileName ----------
func TestCursorFileName_PadsShardIDToTwoDigits(t *testing.T) {
// The persister stores per-shard cursor files at predictable paths
// so a manual operator inspection finds them sorted by shard. Pin
// the zero-padded form so a refactor that drops %02d doesn't break
// existing on-disk filenames.
cases := map[int]string{
0: "shard-00.json",
1: "shard-01.json",
9: "shard-09.json",
10: "shard-10.json",
15: "shard-15.json",
}
for shard, want := range cases {
t.Run(want, func(t *testing.T) {
assert.Equal(t, want, cursorFileName(shard))
})
}
}
@@ -2,6 +2,7 @@ package dispatcher
import (
"context"
"strings"
"testing"
"time"
@@ -48,7 +49,7 @@ func TestPipelineIntegrationInMemory(t *testing.T) {
},
}
matches := router.Route(snap, ev, now)
matches := router.Route(context.Background(), snap, ev, now, nil)
if len(matches) != 1 {
t.Fatalf("expected 1 match, got %v", matches)
}
@@ -82,3 +83,59 @@ func TestPipelineRunRequiresDependencies(t *testing.T) {
t.Fatal("expected error for empty Pipeline")
}
}
// stubFilerClient satisfies filer_pb.SeaweedFilerClient just enough to
// pass the nil-check in Pipeline.Run; methods would panic if called,
// but the validation tests below all return before any RPC.
type stubFilerClient struct {
filer_pb.SeaweedFilerClient
}
// fullPipeline assembles a Pipeline whose dependencies all pass the
// nil-check, so individual tests can knock out one piece at a time
// to exercise specific validation branches.
func fullPipeline() *Pipeline {
return &Pipeline{
Engine: engine.New(),
Persister: reader.NewInMemoryPersister(),
Client: &fakeClient{},
FilerClient: &stubFilerClient{},
BucketsPath: "/buckets",
ShardID: 0,
}
}
func TestPipelineRunValidation(t *testing.T) {
// Each case mutates one piece of a fullPipeline() and asserts the
// expected error fragment. Per-dependency cases pin that the nil
// check exercises every required field individually; the Buckets-
// Path case asserts the distinct error message; the shard cases
// pin the half-open [0, ShardCount) range and that any one bad
// entry refuses the whole multi-shard run.
cases := []struct {
name string
mutate func(*Pipeline)
wantErr string
}{
{"missing Engine", func(p *Pipeline) { p.Engine = nil }, "missing required dependency"},
{"missing Persister", func(p *Pipeline) { p.Persister = nil }, "missing required dependency"},
{"missing Client", func(p *Pipeline) { p.Client = nil }, "missing required dependency"},
{"missing FilerClient", func(p *Pipeline) { p.FilerClient = nil }, "missing required dependency"},
{"missing BucketsPath", func(p *Pipeline) { p.BucketsPath = "" }, "BucketsPath required"},
{"negative ShardID", func(p *Pipeline) { p.ShardID = -1 }, "out of"},
{"ShardID at boundary", func(p *Pipeline) { p.ShardID = s3lifecycle.ShardCount }, "out of"},
{"multi-shard out of range", func(p *Pipeline) {
p.Shards = []int{0, 1, s3lifecycle.ShardCount + 1}
}, "out of"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
p := fullPipeline()
tc.mutate(p)
err := p.Run(context.Background())
if err == nil || !strings.Contains(err.Error(), tc.wantErr) {
t.Fatalf("expected error containing %q, got %v", tc.wantErr, err)
}
})
}
}
@@ -0,0 +1,162 @@
package dispatcher
import (
"context"
"errors"
"strings"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/router"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// filerSiblingLister inspects the .versions/<key>/ folder and the bare
// null-version. Listing caps at 2 — callers only distinguish 1 vs >=2.
type filerSiblingLister struct {
client filer_pb.SeaweedFilerClient
bucketsPath string
}
func (l *filerSiblingLister) Survivors(ctx context.Context, bucket, objectKey string) (router.Survivors, error) {
bucketPath := strings.TrimSuffix(l.bucketsPath, "/") + "/" + bucket
versionsDir := bucketPath + "/" + objectKey + s3_constants.VersionsFolder
var s router.Survivors
err := filer_pb.SeaweedList(ctx, l.client, versionsDir, "", func(entry *filer_pb.Entry, _ bool) error {
s.Count++
if s.Count == 1 && entry != nil {
s.LoneEntry = entry
} else if s.Count > 1 {
s.LoneEntry = nil
}
return nil
}, "", false, 2)
if err != nil && !errors.Is(err, filer_pb.ErrNotFound) {
return router.Survivors{}, err
}
// NewFullPath strips a trailing slash from objectKey so directory-key
// objects (foo/) split the same as regular keys. LookupEntry
// normalizes the gRPC string-mapped not-found into ErrNotFound; a
// raw client.LookupDirectoryEntry would return that as a generic
// error and suppress every otherwise-valid match.
parent, name := util.NewFullPath(bucketPath, objectKey).DirAndName()
resp, err := filer_pb.LookupEntry(ctx, l.client, &filer_pb.LookupDirectoryEntryRequest{
Directory: parent,
Name: name,
})
if err != nil {
if errors.Is(err, filer_pb.ErrNotFound) {
return s, nil
}
return router.Survivors{}, err
}
// Bare regular file or an explicit S3 directory-marker (an empty
// directory entry with Mime set) both count as the null version.
if resp.Entry != nil && (!resp.Entry.IsDirectory || resp.Entry.IsDirectoryKeyObject()) {
s.HasNullVersion = true
}
return s, nil
}
// ListVersions paginates every file under .versions/<key>/. Used by
// the pointer-transition expansion path when a NewerNoncurrentVersions
// rule needs accurate per-version ranking. Subdirectories and entries
// without ExtVersionIdKey are filtered out. NotFound returns
// (nil, nil) so a hard-deleted .versions/ container collapses cleanly.
func (l *filerSiblingLister) ListVersions(ctx context.Context, bucket, objectKey string) ([]*filer_pb.Entry, error) {
bucketPath := strings.TrimSuffix(l.bucketsPath, "/") + "/" + bucket
dir := bucketPath + "/" + objectKey + s3_constants.VersionsFolder
const pageSize uint32 = 1024
startFrom := ""
var versions []*filer_pb.Entry
for {
var pageCount uint32
var lastName string
err := filer_pb.SeaweedList(ctx, l.client, dir, "", func(e *filer_pb.Entry, _ bool) error {
pageCount++
if e == nil {
return nil
}
lastName = e.Name
if e.Attributes == nil || e.IsDirectory {
return nil
}
if id, ok := e.Extended[s3_constants.ExtVersionIdKey]; !ok || len(id) == 0 {
return nil
}
versions = append(versions, e)
return nil
}, startFrom, false, pageSize)
if err != nil {
if errors.Is(err, filer_pb.ErrNotFound) {
return nil, nil
}
return nil, err
}
if pageCount < pageSize {
return versions, nil
}
startFrom = lastName
}
}
// LookupNullVersion returns the bare-key entry that represents the
// null version of objectKey, if any. Both regular files and explicit
// S3 directory-key markers (an empty directory entry with Mime set)
// qualify. explicit reports whether the entry's Extended map carries
// ExtVersionIdKey="null" — the marker the suspended-versioning write
// path applies. NotFound returns (nil, false, nil).
func (l *filerSiblingLister) LookupNullVersion(ctx context.Context, bucket, objectKey string) (*filer_pb.Entry, bool, error) {
bucketPath := strings.TrimSuffix(l.bucketsPath, "/") + "/" + bucket
parent, name := util.NewFullPath(bucketPath, objectKey).DirAndName()
resp, err := filer_pb.LookupEntry(ctx, l.client, &filer_pb.LookupDirectoryEntryRequest{
Directory: parent,
Name: name,
})
if err != nil {
if errors.Is(err, filer_pb.ErrNotFound) {
return nil, false, nil
}
return nil, false, err
}
if resp == nil || resp.Entry == nil {
return nil, false, nil
}
e := resp.Entry
if e.IsDirectory && !e.IsDirectoryKeyObject() {
return nil, false, nil
}
explicit := false
if id, ok := e.Extended[s3_constants.ExtVersionIdKey]; ok && string(id) == "null" {
explicit = true
}
return e, explicit, nil
}
// LookupVersion fetches <bucketsPath>/<bucket>/<objectKey>.versions/v_<id>
// for the pointer-transition router branch. NotFound returns (nil, nil)
// — the displaced version may have been hard-deleted between the
// pointer update and the lookup.
func (l *filerSiblingLister) LookupVersion(ctx context.Context, bucket, objectKey, versionID string) (*filer_pb.Entry, error) {
if versionID == "" {
return nil, nil
}
bucketPath := strings.TrimSuffix(l.bucketsPath, "/") + "/" + bucket
dir := bucketPath + "/" + objectKey + s3_constants.VersionsFolder
resp, err := filer_pb.LookupEntry(ctx, l.client, &filer_pb.LookupDirectoryEntryRequest{
Directory: dir,
Name: "v_" + versionID,
})
if err != nil {
if errors.Is(err, filer_pb.ErrNotFound) {
return nil, nil
}
return nil, err
}
if resp == nil {
return nil, nil
}
return resp.Entry, nil
}
@@ -0,0 +1,502 @@
package dispatcher
import (
"context"
"errors"
"fmt"
"io"
"sort"
"sync"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
)
// Tests for filerSiblingLister cover the four routing-critical surfaces
// the dispatcher pipeline depends on: Survivors (count cap + null
// detection), ListVersions (pagination + filter), LookupNullVersion
// (regular vs directory-key marker, explicit-null flag), and
// LookupVersion (v_ prefix + NotFound collapse).
type fsListStream struct {
responses []*filer_pb.ListEntriesResponse
index int
// recvErr is returned from the FIRST Recv() call before any
// responses are delivered; lets tests inject the gRPC NotFound the
// real filer surfaces when the parent directory doesn't exist.
recvErr error
ctx context.Context
}
func (s *fsListStream) Recv() (*filer_pb.ListEntriesResponse, error) {
if s.ctx != nil {
if err := s.ctx.Err(); err != nil {
return nil, err
}
}
if s.recvErr != nil {
err := s.recvErr
s.recvErr = nil
return nil, err
}
if s.index >= len(s.responses) {
return nil, io.EOF
}
resp := s.responses[s.index]
s.index++
return resp, nil
}
func (s *fsListStream) Header() (metadata.MD, error) { return metadata.MD{}, nil }
func (s *fsListStream) Trailer() metadata.MD { return metadata.MD{} }
func (s *fsListStream) CloseSend() error { return nil }
func (s *fsListStream) Context() context.Context {
if s.ctx != nil {
return s.ctx
}
return context.Background()
}
func (s *fsListStream) SendMsg(any) error { return nil }
func (s *fsListStream) RecvMsg(any) error { return nil }
// fsFakeFiler implements just the SeaweedFilerClient methods that
// filerSiblingLister calls (ListEntries + LookupDirectoryEntry). Other
// methods on the embedded interface remain nil; calling them panics,
// which the tests rely on to catch regressions that try to reach beyond
// the documented surface.
type fsFakeFiler struct {
filer_pb.SeaweedFilerClient
mu sync.Mutex
// tree maps a directory path to its immediate children. A directory
// is "missing" when its key is absent from tree (we return ErrNotFound
// from ListEntries / LookupDirectoryEntry to mimic the real filer).
tree map[string][]*filer_pb.Entry
// listErr / lookupErr force the next call to fail with this error.
// Reset to nil after use so tests can mix success + failure runs.
listErr error
lookupErr error
// missing controls per-directory NotFound for ListEntries: when a path
// is in this set, ListEntries returns filer_pb.ErrNotFound regardless
// of whether tree has an entry for it. Lets us test the .versions/
// not-yet-created vs. empty cases independently.
missing map[string]struct{}
}
func newFakeFiler() *fsFakeFiler {
return &fsFakeFiler{
tree: map[string][]*filer_pb.Entry{},
missing: map[string]struct{}{},
}
}
func (c *fsFakeFiler) ListEntries(ctx context.Context, in *filer_pb.ListEntriesRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[filer_pb.ListEntriesResponse], error) {
c.mu.Lock()
defer c.mu.Unlock()
if c.listErr != nil {
err := c.listErr
c.listErr = nil
return nil, err
}
// Real-filer behavior on a missing parent: stream creation succeeds,
// the first Recv() surfaces ErrNotFound. SeaweedList passes that
// through unwrapped, which is what filerSiblingLister's
// errors.Is(err, filer_pb.ErrNotFound) check depends on.
if _, missing := c.missing[in.Directory]; missing {
return &fsListStream{recvErr: filer_pb.ErrNotFound, ctx: ctx}, nil
}
src := c.tree[in.Directory]
filtered := make([]*filer_pb.Entry, 0, len(src))
for _, e := range src {
if e == nil {
continue
}
if in.StartFromFileName != "" {
if in.InclusiveStartFrom {
if e.Name < in.StartFromFileName {
continue
}
} else if e.Name <= in.StartFromFileName {
continue
}
}
filtered = append(filtered, e)
}
sort.SliceStable(filtered, func(i, j int) bool { return filtered[i].Name < filtered[j].Name })
if in.Limit > 0 && uint32(len(filtered)) > in.Limit {
filtered = filtered[:in.Limit]
}
resps := make([]*filer_pb.ListEntriesResponse, 0, len(filtered))
for _, e := range filtered {
resps = append(resps, &filer_pb.ListEntriesResponse{Entry: e})
}
return &fsListStream{responses: resps, ctx: ctx}, nil
}
func (c *fsFakeFiler) LookupDirectoryEntry(ctx context.Context, in *filer_pb.LookupDirectoryEntryRequest, opts ...grpc.CallOption) (*filer_pb.LookupDirectoryEntryResponse, error) {
c.mu.Lock()
defer c.mu.Unlock()
if c.lookupErr != nil {
err := c.lookupErr
c.lookupErr = nil
return nil, err
}
for _, e := range c.tree[in.Directory] {
if e != nil && e.Name == in.Name {
return &filer_pb.LookupDirectoryEntryResponse{Entry: e}, nil
}
}
return nil, filer_pb.ErrNotFound
}
func (c *fsFakeFiler) put(dir string, entries ...*filer_pb.Entry) {
c.mu.Lock()
defer c.mu.Unlock()
c.tree[dir] = append(c.tree[dir], entries...)
}
func (c *fsFakeFiler) markMissing(dir string) {
c.mu.Lock()
defer c.mu.Unlock()
c.missing[dir] = struct{}{}
}
func newLister(c *fsFakeFiler) *filerSiblingLister {
return &filerSiblingLister{client: c, bucketsPath: "/buckets"}
}
func versionEntry(name, versionID string) *filer_pb.Entry {
return &filer_pb.Entry{
Name: name,
Attributes: &filer_pb.FuseAttributes{},
Extended: map[string][]byte{
s3_constants.ExtVersionIdKey: []byte(versionID),
},
}
}
func TestSurvivors_NoVersionsNoNullReturnsZero(t *testing.T) {
f := newFakeFiler()
// .versions/ doesn't exist (NotFound) and the bare key doesn't exist either.
f.markMissing("/buckets/b/k" + s3_constants.VersionsFolder)
l := newLister(f)
s, err := l.Survivors(context.Background(), "b", "k")
require.NoError(t, err)
assert.Equal(t, 0, s.Count)
assert.False(t, s.HasNullVersion)
assert.Nil(t, s.LoneEntry)
}
func TestSurvivors_OneVersionPopulatesLoneEntry(t *testing.T) {
// Count == 1 means LoneEntry must be set; the dispatcher's
// sole-survivor path uses it to compare against the marker version.
f := newFakeFiler()
dir := "/buckets/b/k" + s3_constants.VersionsFolder
f.put(dir, versionEntry("v_aaa", "aaa"))
f.markMissing("/buckets/b") // bare key absent
l := newLister(f)
s, err := l.Survivors(context.Background(), "b", "k")
require.NoError(t, err)
assert.Equal(t, 1, s.Count)
require.NotNil(t, s.LoneEntry)
assert.Equal(t, "v_aaa", s.LoneEntry.Name)
assert.False(t, s.HasNullVersion)
}
func TestSurvivors_MoreThanOneClearsLoneEntry(t *testing.T) {
// Listing caps at 2; once Count > 1, LoneEntry must be reset to nil
// so the caller doesn't mistakenly treat the second-arrival entry as
// the sole survivor.
f := newFakeFiler()
dir := "/buckets/b/k" + s3_constants.VersionsFolder
f.put(dir, versionEntry("v_aaa", "aaa"), versionEntry("v_bbb", "bbb"))
f.markMissing("/buckets/b")
l := newLister(f)
s, err := l.Survivors(context.Background(), "b", "k")
require.NoError(t, err)
assert.Equal(t, 2, s.Count)
assert.Nil(t, s.LoneEntry, "Count > 1 must clear LoneEntry")
}
func TestSurvivors_NullVersionDetectedFromBareRegularFile(t *testing.T) {
// The bare <bucket>/<key> path resolves to a regular file when the
// object pre-dates versioning; that file is the null version.
f := newFakeFiler()
f.markMissing("/buckets/b/k" + s3_constants.VersionsFolder)
f.put("/buckets/b", &filer_pb.Entry{Name: "k", IsDirectory: false, Attributes: &filer_pb.FuseAttributes{}})
l := newLister(f)
s, err := l.Survivors(context.Background(), "b", "k")
require.NoError(t, err)
assert.True(t, s.HasNullVersion)
}
func TestSurvivors_DirectoryKeyMarkerCountsAsNull(t *testing.T) {
// An explicit S3 directory-key marker (IsDirectory=true with
// Attributes.Mime set) is also the null version. The listing path
// downstream treats both the regular-file and the directory-marker
// shape as null; Survivors must agree. The lister's NewFullPath
// trims the trailing slash from objectKey before splitting, so the
// stored entry Name has no trailing slash.
f := newFakeFiler()
f.markMissing("/buckets/b/dir" + s3_constants.VersionsFolder)
f.put("/buckets/b", &filer_pb.Entry{
Name: "dir",
IsDirectory: true,
Attributes: &filer_pb.FuseAttributes{Mime: "application/x-directory"},
})
l := newLister(f)
s, err := l.Survivors(context.Background(), "b", "dir/")
require.NoError(t, err)
assert.True(t, s.HasNullVersion, "directory-key marker must count as null version")
}
func TestSurvivors_PlainDirectoryDoesNotCount(t *testing.T) {
// A plain directory (no Mime, just IsDirectory=true) is implicit-only
// and must NOT register as a null version — otherwise normal prefix
// directories would shadow real null-version detection.
f := newFakeFiler()
f.markMissing("/buckets/b/dir" + s3_constants.VersionsFolder)
f.put("/buckets/b", &filer_pb.Entry{
Name: "dir",
IsDirectory: true,
Attributes: &filer_pb.FuseAttributes{}, // no Mime
})
l := newLister(f)
s, err := l.Survivors(context.Background(), "b", "dir/")
require.NoError(t, err)
assert.False(t, s.HasNullVersion, "plain directory must not count as null version")
}
func TestSurvivors_VersionsListingErrorPropagates(t *testing.T) {
// A non-NotFound error from the .versions/ listing must surface; the
// dispatcher promotes this to a retry instead of a NOOP.
f := newFakeFiler()
f.listErr = errors.New("transport boom")
l := newLister(f)
_, err := l.Survivors(context.Background(), "b", "k")
assert.Error(t, err)
assert.Contains(t, err.Error(), "transport boom")
}
func TestSurvivors_NullLookupErrorPropagates(t *testing.T) {
// A non-NotFound error from the bare-key lookup must surface; we
// can't conclude "no null" from a transport failure.
f := newFakeFiler()
f.markMissing("/buckets/b/k" + s3_constants.VersionsFolder)
f.lookupErr = errors.New("lookup boom")
l := newLister(f)
_, err := l.Survivors(context.Background(), "b", "k")
assert.Error(t, err)
assert.Contains(t, err.Error(), "lookup boom")
}
func TestListVersions_NotFoundReturnsNil(t *testing.T) {
// A hard-deleted .versions/ container collapses to (nil, nil) so
// callers can treat it as "no versions" without special-casing.
f := newFakeFiler()
f.markMissing("/buckets/b/k" + s3_constants.VersionsFolder)
l := newLister(f)
versions, err := l.ListVersions(context.Background(), "b", "k")
require.NoError(t, err)
assert.Nil(t, versions)
}
func TestListVersions_FiltersOutDirectoriesAndMissingVersionId(t *testing.T) {
// Subdirectories and entries without ExtVersionIdKey aren't real
// versions; the bootstrap walker writes them sometimes so the
// listing must filter rather than treat them as data.
f := newFakeFiler()
dir := "/buckets/b/k" + s3_constants.VersionsFolder
f.put(dir,
versionEntry("v_aaa", "aaa"),
&filer_pb.Entry{Name: "subdir", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
&filer_pb.Entry{Name: "v_no_attrs"}, // nil Attributes
&filer_pb.Entry{Name: "v_no_ext", Attributes: &filer_pb.FuseAttributes{}}, // missing Extended
&filer_pb.Entry{Name: "v_empty_ext", Attributes: &filer_pb.FuseAttributes{}, Extended: map[string][]byte{s3_constants.ExtVersionIdKey: nil}}, // empty value
versionEntry("v_zzz", "zzz"),
)
l := newLister(f)
versions, err := l.ListVersions(context.Background(), "b", "k")
require.NoError(t, err)
require.Len(t, versions, 2)
assert.Equal(t, "v_aaa", versions[0].Name)
assert.Equal(t, "v_zzz", versions[1].Name)
}
func TestListVersions_PaginatesAcrossPages(t *testing.T) {
// pageSize is 1024 inside the lister; populate just over the boundary
// to force a second listing call. The fake's StartFromFileName
// handling mirrors the real filer.
f := newFakeFiler()
dir := "/buckets/b/k" + s3_constants.VersionsFolder
const total = 1030
entries := make([]*filer_pb.Entry, 0, total)
for i := 0; i < total; i++ {
entries = append(entries, versionEntry(fmt.Sprintf("v_%05d", i), fmt.Sprintf("id_%05d", i)))
}
f.put(dir, entries...)
l := newLister(f)
versions, err := l.ListVersions(context.Background(), "b", "k")
require.NoError(t, err)
require.Len(t, versions, total)
// Order is preserved across pages.
assert.Equal(t, "v_00000", versions[0].Name)
assert.Equal(t, fmt.Sprintf("v_%05d", total-1), versions[total-1].Name)
}
func TestListVersions_ErrorPropagates(t *testing.T) {
f := newFakeFiler()
f.listErr = errors.New("list boom")
l := newLister(f)
versions, err := l.ListVersions(context.Background(), "b", "k")
assert.Nil(t, versions)
assert.Error(t, err)
assert.Contains(t, err.Error(), "list boom")
}
func TestLookupNullVersion_RegularFileExplicitFalse(t *testing.T) {
// A bare regular file with no ExtVersionIdKey is the null version
// but not "explicit" — the suspended-versioning write path flags
// explicit nulls with ExtVersionIdKey="null".
f := newFakeFiler()
f.put("/buckets/b", &filer_pb.Entry{Name: "k", IsDirectory: false, Attributes: &filer_pb.FuseAttributes{}})
l := newLister(f)
entry, explicit, err := l.LookupNullVersion(context.Background(), "b", "k")
require.NoError(t, err)
require.NotNil(t, entry)
assert.Equal(t, "k", entry.Name)
assert.False(t, explicit)
}
func TestLookupNullVersion_ExplicitNullFlag(t *testing.T) {
// ExtVersionIdKey="null" is the marker the suspended-versioning
// write path sets; the lister surfaces it via the explicit return.
f := newFakeFiler()
f.put("/buckets/b", &filer_pb.Entry{
Name: "k",
Attributes: &filer_pb.FuseAttributes{},
Extended: map[string][]byte{s3_constants.ExtVersionIdKey: []byte("null")},
})
l := newLister(f)
entry, explicit, err := l.LookupNullVersion(context.Background(), "b", "k")
require.NoError(t, err)
require.NotNil(t, entry)
assert.True(t, explicit)
}
func TestLookupNullVersion_DirectoryKeyMarkerQualifies(t *testing.T) {
// NewFullPath strips a trailing slash before splitting; the entry
// Name as stored has no slash.
f := newFakeFiler()
f.put("/buckets/b", &filer_pb.Entry{
Name: "dir",
IsDirectory: true,
Attributes: &filer_pb.FuseAttributes{Mime: "application/x-directory"},
})
l := newLister(f)
entry, _, err := l.LookupNullVersion(context.Background(), "b", "dir/")
require.NoError(t, err)
require.NotNil(t, entry)
}
func TestLookupNullVersion_PlainDirectoryRejected(t *testing.T) {
// A plain directory must not be returned — otherwise the dispatcher
// would treat any prefix directory as a null version.
f := newFakeFiler()
f.put("/buckets/b", &filer_pb.Entry{
Name: "dir",
IsDirectory: true,
Attributes: &filer_pb.FuseAttributes{},
})
l := newLister(f)
entry, explicit, err := l.LookupNullVersion(context.Background(), "b", "dir/")
require.NoError(t, err)
assert.Nil(t, entry)
assert.False(t, explicit)
}
func TestLookupNullVersion_NotFoundCollapses(t *testing.T) {
f := newFakeFiler()
l := newLister(f) // empty tree -> NotFound on lookup
entry, explicit, err := l.LookupNullVersion(context.Background(), "b", "k")
require.NoError(t, err)
assert.Nil(t, entry)
assert.False(t, explicit)
}
func TestLookupNullVersion_TransportErrorPropagates(t *testing.T) {
f := newFakeFiler()
f.lookupErr = errors.New("lookup boom")
l := newLister(f)
_, _, err := l.LookupNullVersion(context.Background(), "b", "k")
assert.Error(t, err)
assert.Contains(t, err.Error(), "lookup boom")
}
func TestLookupVersion_EmptyVersionIdReturnsNil(t *testing.T) {
// An empty versionID is a no-op — neither error nor result.
f := newFakeFiler()
l := newLister(f)
entry, err := l.LookupVersion(context.Background(), "b", "k", "")
require.NoError(t, err)
assert.Nil(t, entry)
}
func TestLookupVersion_AppliesVPrefix(t *testing.T) {
// File name on disk is "v_<id>"; the caller passes only the id.
f := newFakeFiler()
dir := "/buckets/b/k" + s3_constants.VersionsFolder
f.put(dir, versionEntry("v_abc123", "abc123"))
l := newLister(f)
entry, err := l.LookupVersion(context.Background(), "b", "k", "abc123")
require.NoError(t, err)
require.NotNil(t, entry)
assert.Equal(t, "v_abc123", entry.Name)
}
func TestLookupVersion_NotFoundCollapses(t *testing.T) {
// Hard-delete between pointer update and lookup is the documented
// race; collapse to (nil, nil) so the dispatcher continues without
// retry-storming.
f := newFakeFiler()
l := newLister(f)
entry, err := l.LookupVersion(context.Background(), "b", "k", "abc")
require.NoError(t, err)
assert.Nil(t, entry)
}
func TestLookupVersion_TransportErrorPropagates(t *testing.T) {
f := newFakeFiler()
f.lookupErr = errors.New("lookup boom")
l := newLister(f)
_, err := l.LookupVersion(context.Background(), "b", "k", "abc")
assert.Error(t, err)
assert.Contains(t, err.Error(), "lookup boom")
}
@@ -0,0 +1,85 @@
package dispatcher
import (
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/s3_lifecycle_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/router"
"github.com/stretchr/testify/assert"
)
// toProtoActionKind / toProtoIdentity are the worker-side CAS-witness
// converters; getting them wrong silently breaks the LifecycleDelete
// flow because the server's identity check always fails. These tests
// pin the full mapping so a new ActionKind added in s3lifecycle but
// forgotten here can't slip through as ACTION_KIND_UNSPECIFIED.
func TestToProtoActionKind_AllKnownKindsMap(t *testing.T) {
cases := []struct {
in s3lifecycle.ActionKind
want s3_lifecycle_pb.ActionKind
}{
{s3lifecycle.ActionKindExpirationDays, s3_lifecycle_pb.ActionKind_EXPIRATION_DAYS},
{s3lifecycle.ActionKindExpirationDate, s3_lifecycle_pb.ActionKind_EXPIRATION_DATE},
{s3lifecycle.ActionKindNoncurrentDays, s3_lifecycle_pb.ActionKind_NONCURRENT_DAYS},
{s3lifecycle.ActionKindNewerNoncurrent, s3_lifecycle_pb.ActionKind_NEWER_NONCURRENT},
{s3lifecycle.ActionKindAbortMPU, s3_lifecycle_pb.ActionKind_ABORT_MPU},
{s3lifecycle.ActionKindExpiredDeleteMarker, s3_lifecycle_pb.ActionKind_EXPIRED_DELETE_MARKER},
}
for _, c := range cases {
t.Run(c.in.String(), func(t *testing.T) {
assert.Equal(t, c.want, toProtoActionKind(c.in))
})
}
}
func TestToProtoActionKind_UnspecifiedAndUnknownFallToUnspecified(t *testing.T) {
// Both the in-package zero value and a future kind not listed in
// the switch must collapse to ACTION_KIND_UNSPECIFIED so the server
// can reject with FATAL rather than silently dispatch a wrong kind.
assert.Equal(t, s3_lifecycle_pb.ActionKind_ACTION_KIND_UNSPECIFIED,
toProtoActionKind(s3lifecycle.ActionKindUnspecified))
assert.Equal(t, s3_lifecycle_pb.ActionKind_ACTION_KIND_UNSPECIFIED,
toProtoActionKind(s3lifecycle.ActionKind(999)))
}
func TestToProtoIdentity_NilReturnsNil(t *testing.T) {
// LifecycleDelete treats a nil ExpectedIdentity as "no CAS"; the
// converter must preserve that signal rather than emit an empty
// non-nil identity that would force a re-fetch + comparison.
assert.Nil(t, toProtoIdentity(nil))
}
func TestToProtoIdentity_AllFieldsCopied(t *testing.T) {
in := &router.EntryIdentity{
MtimeNs: 1700000000_000_000_123,
Size: 4096,
HeadFid: "1,abc",
ExtendedHash: []byte{0xde, 0xad, 0xbe, 0xef},
}
out := toProtoIdentity(in)
if out == nil {
t.Fatal("non-nil input must produce non-nil output")
}
assert.Equal(t, in.MtimeNs, out.MtimeNs)
assert.Equal(t, in.Size, out.Size)
assert.Equal(t, in.HeadFid, out.HeadFid)
assert.Equal(t, in.ExtendedHash, out.ExtendedHash)
}
func TestToProtoIdentity_EmptyFieldsSurvive(t *testing.T) {
// A bootstrap-fresh entry can land at the dispatcher with zero
// MtimeNs / Size / no HeadFid — the converter must still produce a
// non-nil identity so the server treats it as a real CAS witness
// rather than the no-CAS sentinel.
in := &router.EntryIdentity{}
out := toProtoIdentity(in)
if out == nil {
t.Fatal("zero-valued identity must still produce non-nil")
}
assert.Zero(t, out.MtimeNs)
assert.Zero(t, out.Size)
assert.Empty(t, out.HeadFid)
assert.Empty(t, out.ExtendedHash)
}
+8 -1
View File
@@ -64,7 +64,14 @@ func (e *Engine) Compile(inputs []CompileInput, opts CompileOptions) *Snapshot {
if !hasPrior || mode == ModeUnspecified {
mode = decideMode(rule, kind, opts.MetaLogRetention, opts.BootstrapLookbackMin)
}
active := prior.BootstrapComplete && mode == ModeEventDriven
// Active gates routing: MatchPath / MatchOriginalWrite skip
// !IsActive actions. ScanAtDate's only dispatch path is the
// bootstrap walk's MatchPath call, so the action must be
// considered active there or its rule is silently a no-op.
// Bootstrap-completion state is per-action and event-driven-
// shaped; date-based actions don't need a bootstrap rendezvous.
active := mode == ModeScanAtDate ||
(prior.BootstrapComplete && mode == ModeEventDriven)
ca := &CompiledAction{
Rule: rule,
@@ -0,0 +1,45 @@
package engine
import (
"testing"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
"github.com/stretchr/testify/assert"
)
// rulePredicateSensitive's non-nil branches are exercised by the
// existing Compile tests; this test pins the defensive nil-rule
// branch directly. Compile shouldn't ever pass a nil rule, but a
// future caller that does shouldn't panic.
func TestRulePredicateSensitive_NilRuleReturnsFalse(t *testing.T) {
assert.False(t, rulePredicateSensitive(nil))
}
func TestRulePredicateSensitive_NoFilterTagsReturnsFalse(t *testing.T) {
// A rule without FilterTags is not predicate-sensitive; the
// router's MatchPredicateChange path skips actions whose rule
// returns false here.
rule := &s3lifecycle.Rule{ID: "r", Status: s3lifecycle.StatusEnabled, ExpirationDays: 7}
assert.False(t, rulePredicateSensitive(rule))
}
func TestRulePredicateSensitive_EmptyFilterTagsReturnsFalse(t *testing.T) {
// An empty (non-nil) FilterTags map must classify as non-sensitive
// — the function checks len, so empty == 0 == false.
rule := &s3lifecycle.Rule{
ID: "r",
Status: s3lifecycle.StatusEnabled,
FilterTags: map[string]string{},
}
assert.False(t, rulePredicateSensitive(rule))
}
func TestRulePredicateSensitive_PopulatedFilterTagsReturnsTrue(t *testing.T) {
rule := &s3lifecycle.Rule{
ID: "r",
Status: s3lifecycle.StatusEnabled,
FilterTags: map[string]string{"env": "prod"},
}
assert.True(t, rulePredicateSensitive(rule))
}
@@ -1,6 +1,7 @@
package engine
import (
"strconv"
"testing"
"time"
@@ -322,3 +323,60 @@ func TestEngine_SnapshotAtomicSwap(t *testing.T) {
t.Fatalf("Engine.Snapshot should return the latest")
}
}
// TestCompile_DelayGroupsDedupeAcrossBuckets pins the scaling property
// the dispatcher relies on: originalDelayGroups is keyed by Delay, so N
// rules sharing the same Days threshold across M buckets collapse into
// one delay group with N*M action keys — not N*M groups. The dispatch
// path can then index by delay group rather than per-rule.
func TestCompile_DelayGroupsDedupeAcrossBuckets(t *testing.T) {
const buckets = 100
const rulesPerBucket = 5
// Five rules per bucket, but only three distinct day values, so two
// pairs of rules per bucket share a delay group.
dayValues := []int{1, 1, 7, 7, 30}
distinctDays := map[int]bool{}
for _, d := range dayValues {
distinctDays[d] = true
}
inputs := make([]CompileInput, buckets)
prior := map[s3lifecycle.ActionKey]PriorState{}
for b := 0; b < buckets; b++ {
bucket := "b" + strconv.Itoa(b)
rules := make([]*s3lifecycle.Rule, rulesPerBucket)
for r, days := range dayValues {
rule := ruleExpDays("r"+strconv.Itoa(r), "p"+strconv.Itoa(r)+"/", days)
rules[r] = rule
prior[s3lifecycle.ActionKey{
Bucket: bucket,
RuleHash: s3lifecycle.RuleHash(rule),
ActionKind: s3lifecycle.ActionKindExpirationDays,
}] = PriorState{BootstrapComplete: true}
}
inputs[b] = CompileInput{Bucket: bucket, Rules: rules}
}
e := New()
snap := e.Compile(inputs, CompileOptions{PriorStates: prior})
if got := len(snap.actions); got != buckets*rulesPerBucket {
t.Fatalf("want %d actions (no collapse), got %d", buckets*rulesPerBucket, got)
}
if got := len(snap.originalDelayGroups); got != len(distinctDays) {
t.Fatalf("want %d delay groups (one per distinct Days), got %d",
len(distinctDays), got)
}
// Per-group key count: each distinct day appears in `count` rules per
// bucket, so the group holds count*buckets keys.
wantPerGroup := map[time.Duration]int{}
for _, d := range dayValues {
wantPerGroup[s3lifecycle.DaysToDuration(d)] += buckets
}
for delay, want := range wantPerGroup {
if got := len(snap.originalDelayGroups[delay]); got != want {
t.Fatalf("delay %v: want %d action keys, got %d", delay, want, got)
}
}
}
@@ -0,0 +1,321 @@
package engine
import (
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// prefixMatches and filterAllows are pure helpers exercised indirectly
// through MatchOriginalWrite / MatchPath; pinning them directly catches
// a regression at the helper level so a Match-test failure isn't the
// first signal of a broken filter.
func TestPrefixMatches_EmptyPrefixAllowsEverything(t *testing.T) {
// An empty prefix on a rule means "match every key in the bucket"
// — the no-op fast path that skips the HasPrefix call.
assert.True(t, prefixMatches("", "logs/2026/01/01"))
assert.True(t, prefixMatches("", ""))
assert.True(t, prefixMatches("", "/"))
}
func TestPrefixMatches_HonorsExactPrefix(t *testing.T) {
assert.True(t, prefixMatches("logs/", "logs/2026/01/01"))
assert.True(t, prefixMatches("logs/", "logs/"))
}
func TestPrefixMatches_RejectsNonMatchingPath(t *testing.T) {
assert.False(t, prefixMatches("logs/", "metrics/2026/01/01"))
assert.False(t, prefixMatches("logs/", "log/2026/01/01")) // no trailing slash
}
func TestPrefixMatches_PathShorterThanPrefixIsReject(t *testing.T) {
// Path shorter than the rule prefix can't satisfy HasPrefix; the
// helper must say no rather than treat it as a partial match.
assert.False(t, prefixMatches("logs/2026/", "logs/"))
}
func TestFilterAllows_NoFiltersAcceptsAnything(t *testing.T) {
// A rule without any filter knobs allows every event regardless of
// size or tag map. Pins the documented "no filter" fast path.
rule := &s3lifecycle.Rule{}
assert.True(t, filterAllows(rule, &Event{Size: 0}))
assert.True(t, filterAllows(rule, &Event{Size: 1024}))
assert.True(t, filterAllows(rule, &Event{Tags: map[string]string{"a": "b"}}))
}
func TestFilterAllows_SizeGreaterThanGate(t *testing.T) {
// FilterSizeGreaterThan is "strictly greater"; events at or below
// the threshold are rejected.
rule := &s3lifecycle.Rule{FilterSizeGreaterThan: 1024}
assert.False(t, filterAllows(rule, &Event{Size: 1024}), "boundary value rejected (gate is >, not >=)")
assert.False(t, filterAllows(rule, &Event{Size: 100}))
assert.True(t, filterAllows(rule, &Event{Size: 1025}))
}
func TestFilterAllows_SizeLessThanGate(t *testing.T) {
// FilterSizeLessThan is "strictly less"; events at or above the
// threshold are rejected.
rule := &s3lifecycle.Rule{FilterSizeLessThan: 1024}
assert.False(t, filterAllows(rule, &Event{Size: 1024}), "boundary value rejected (gate is <, not <=)")
assert.False(t, filterAllows(rule, &Event{Size: 4096}))
assert.True(t, filterAllows(rule, &Event{Size: 1023}))
}
func TestFilterAllows_ZeroSizeFilterIsDisabled(t *testing.T) {
// FilterSizeGreaterThan/LessThan = 0 means "not set"; the filter
// must let any size through. A regression treating 0 as a real
// threshold would reject every event at or above 0 (i.e., all of
// them).
greater := &s3lifecycle.Rule{FilterSizeGreaterThan: 0}
less := &s3lifecycle.Rule{FilterSizeLessThan: 0}
for _, size := range []int64{0, 1, 1024, 1 << 30} {
assert.True(t, filterAllows(greater, &Event{Size: size}), "Gt 0 must allow size %d", size)
assert.True(t, filterAllows(less, &Event{Size: size}), "Lt 0 must allow size %d", size)
}
}
func TestFilterAllows_RequiredTagPresent(t *testing.T) {
// A FilterTags entry is "must equal"; the event's Tags map must
// have the same key with the same value.
rule := &s3lifecycle.Rule{FilterTags: map[string]string{"env": "prod"}}
assert.True(t, filterAllows(rule, &Event{Tags: map[string]string{"env": "prod"}}))
assert.True(t, filterAllows(rule, &Event{Tags: map[string]string{"env": "prod", "team": "a"}}))
}
func TestFilterAllows_RequiredTagMissingOrWrong(t *testing.T) {
rule := &s3lifecycle.Rule{FilterTags: map[string]string{"env": "prod"}}
assert.False(t, filterAllows(rule, &Event{}), "nil tags map rejected")
assert.False(t, filterAllows(rule, &Event{Tags: map[string]string{}}), "empty tags rejected")
assert.False(t, filterAllows(rule, &Event{Tags: map[string]string{"team": "a"}}), "different key rejected")
assert.False(t, filterAllows(rule, &Event{Tags: map[string]string{"env": "stage"}}), "wrong value rejected")
}
func TestFilterAllows_AllRequiredTagsMustMatch(t *testing.T) {
// Multiple FilterTags are AND'd; missing any one rejects.
rule := &s3lifecycle.Rule{FilterTags: map[string]string{"env": "prod", "team": "data"}}
assert.True(t, filterAllows(rule, &Event{Tags: map[string]string{"env": "prod", "team": "data"}}))
assert.False(t, filterAllows(rule, &Event{Tags: map[string]string{"env": "prod"}}), "missing one tag rejected")
assert.False(t, filterAllows(rule, &Event{Tags: map[string]string{"team": "data"}}), "missing other tag rejected")
assert.False(t, filterAllows(rule, &Event{Tags: map[string]string{"env": "prod", "team": "ops"}}), "wrong value on second tag rejected")
}
func TestFilterAllows_SizeAndTagAreANDed(t *testing.T) {
// A rule with both size and tag filters requires BOTH to pass;
// either one failing rejects the event.
rule := &s3lifecycle.Rule{
FilterSizeGreaterThan: 100,
FilterTags: map[string]string{"env": "prod"},
}
// Both pass.
assert.True(t, filterAllows(rule, &Event{Size: 200, Tags: map[string]string{"env": "prod"}}))
// Size fails.
assert.False(t, filterAllows(rule, &Event{Size: 50, Tags: map[string]string{"env": "prod"}}))
// Tag fails.
assert.False(t, filterAllows(rule, &Event{Size: 200, Tags: map[string]string{"env": "stage"}}))
}
// ---------- MatchOriginalWrite / MatchPredicateChange / MatchPath edge cases ----------
// helperSnapshot constructs a Snapshot via the engine's Compile path so
// the action map and bucket index are populated correctly. Tests below
// poke at the public Match functions rather than the internal maps.
func helperSnapshot(t *testing.T) (*Snapshot, *s3lifecycle.Rule, s3lifecycle.ActionKey) {
t.Helper()
rule := &s3lifecycle.Rule{
ID: "r",
Status: s3lifecycle.StatusEnabled,
Prefix: "logs/",
ExpirationDays: 7,
}
hash := s3lifecycle.RuleHash(rule)
prior := map[s3lifecycle.ActionKey]PriorState{}
for _, k := range s3lifecycle.RuleActionKinds(rule) {
prior[s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: k}] = PriorState{
BootstrapComplete: true,
Mode: ModeEventDriven,
}
}
snap := New().Compile(
[]CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
CompileOptions{PriorStates: prior},
)
key := s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: s3lifecycle.ActionKindExpirationDays}
return snap, rule, key
}
func TestMatchOriginalWrite_NilEventReturnsNil(t *testing.T) {
// A nil event is treated as "no match"; the routing path should
// not panic on a defensive caller.
snap, _, _ := helperSnapshot(t)
assert.Nil(t, snap.MatchOriginalWrite(nil, 7*24*time.Hour))
}
func TestMatchOriginalWrite_WrongShapeReturnsNil(t *testing.T) {
// Only EventShapeOriginalWrite goes through this path; a
// PredicateChange event must not produce delay-group matches.
snap, _, _ := helperSnapshot(t)
got := snap.MatchOriginalWrite(&Event{Shape: EventShapePredicateChange, Bucket: "bk"}, 7*24*time.Hour)
assert.Nil(t, got)
}
func TestMatchOriginalWrite_DelayMismatchReturnsNil(t *testing.T) {
// The action is in the 7-day delay group; asking for a different
// delay must produce no matches.
snap, _, _ := helperSnapshot(t)
got := snap.MatchOriginalWrite(&Event{Shape: EventShapeOriginalWrite, Bucket: "bk", Path: "logs/x"}, 30*24*time.Hour)
assert.Empty(t, got)
}
func TestMatchPredicateChange_NilEventReturnsNil(t *testing.T) {
snap, _, _ := helperSnapshot(t)
assert.Nil(t, snap.MatchPredicateChange(nil))
}
func TestMatchPredicateChange_WrongShapeReturnsNil(t *testing.T) {
// EventShapeOriginalWrite events go through MatchOriginalWrite; a
// caller passing one to MatchPredicateChange gets nothing back.
snap, _, _ := helperSnapshot(t)
got := snap.MatchPredicateChange(&Event{Shape: EventShapeOriginalWrite, Bucket: "bk"})
assert.Nil(t, got)
}
func TestMatchPredicateChange_NoTagSensitiveActionsReturnsNil(t *testing.T) {
// The default helperSnapshot rule has no FilterTags, so it's not
// tag-sensitive — predicate changes must yield no matches.
snap, _, _ := helperSnapshot(t)
got := snap.MatchPredicateChange(&Event{Shape: EventShapePredicateChange, Bucket: "bk", Path: "logs/x"})
assert.Nil(t, got, "non-tag-sensitive snapshot returns nil from predicate change")
}
func TestMatchPath_UnknownBucketReturnsNil(t *testing.T) {
snap, _, _ := helperSnapshot(t)
got := snap.MatchPath("other-bucket", "logs/x", nil)
assert.Nil(t, got)
}
func TestMatchPath_NilEventStillAppliesPrefix(t *testing.T) {
// MatchPath with ev=nil applies prefix matching only; tags/size
// don't gate. Pinned because the bootstrap walker calls it that
// way.
snap, _, key := helperSnapshot(t)
matches := snap.MatchPath("bk", "logs/2026/01/01", nil)
assert.Contains(t, matches, key)
assert.Empty(t, snap.MatchPath("bk", "metrics/x", nil), "prefix mismatch must reject even with nil event")
}
func TestMatchPath_FilterRespectedWhenEventProvided(t *testing.T) {
// When the caller supplies an Event, both prefix and filter gates
// fire. A size-filter rule rejects an event below the threshold.
rule := &s3lifecycle.Rule{
ID: "r",
Status: s3lifecycle.StatusEnabled,
ExpirationDays: 7,
FilterSizeGreaterThan: 1000,
}
hash := s3lifecycle.RuleHash(rule)
prior := map[s3lifecycle.ActionKey]PriorState{}
for _, k := range s3lifecycle.RuleActionKinds(rule) {
prior[s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: k}] = PriorState{
BootstrapComplete: true,
Mode: ModeEventDriven,
}
}
snap := New().Compile(
[]CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
CompileOptions{PriorStates: prior},
)
belowThreshold := &Event{Size: 500}
aboveThreshold := &Event{Size: 2000}
assert.Empty(t, snap.MatchPath("bk", "x", belowThreshold), "size below threshold must reject")
assert.NotEmpty(t, snap.MatchPath("bk", "x", aboveThreshold), "size above threshold must allow")
}
// ---------- filterMatching direct coverage ----------
func TestFilterMatching_BucketScoping(t *testing.T) {
// Two buckets sharing identical rules: filterMatching must reject
// keys whose action.Bucket doesn't match ev.Bucket so a match in
// "alpha" doesn't bleed into "beta".
rule := &s3lifecycle.Rule{ID: "r", Status: s3lifecycle.StatusEnabled, ExpirationDays: 7}
hash := s3lifecycle.RuleHash(rule)
prior := map[s3lifecycle.ActionKey]PriorState{}
for _, b := range []string{"alpha", "beta"} {
for _, k := range s3lifecycle.RuleActionKinds(rule) {
prior[s3lifecycle.ActionKey{Bucket: b, RuleHash: hash, ActionKind: k}] = PriorState{
BootstrapComplete: true,
Mode: ModeEventDriven,
}
}
}
snap := New().Compile(
[]CompileInput{
{Bucket: "alpha", Rules: []*s3lifecycle.Rule{rule}},
{Bucket: "beta", Rules: []*s3lifecycle.Rule{rule}},
},
CompileOptions{PriorStates: prior},
)
got := snap.MatchOriginalWrite(&Event{
Shape: EventShapeOriginalWrite, Bucket: "alpha", Path: "x", Size: 1,
}, 7*24*time.Hour)
require.NotEmpty(t, got)
for _, k := range got {
assert.Equal(t, "alpha", k.Bucket, "match leaked across bucket")
}
}
func TestFilterMatching_AbortMPURequiresMPUInit(t *testing.T) {
// AbortMPU actions only fire on MPU-init events; a normal write to
// the same prefix must not trigger them.
rule := &s3lifecycle.Rule{
ID: "r",
Status: s3lifecycle.StatusEnabled,
AbortMPUDaysAfterInitiation: 7,
}
hash := s3lifecycle.RuleHash(rule)
abortKey := s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: s3lifecycle.ActionKindAbortMPU}
prior := map[s3lifecycle.ActionKey]PriorState{
abortKey: {BootstrapComplete: true, Mode: ModeEventDriven},
}
snap := New().Compile(
[]CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
CompileOptions{PriorStates: prior},
)
regular := &Event{Shape: EventShapeOriginalWrite, Bucket: "bk", Path: "x", IsMPUInit: false}
mpu := &Event{Shape: EventShapeOriginalWrite, Bucket: "bk", Path: "x", IsMPUInit: true}
assert.Empty(t, snap.MatchOriginalWrite(regular, 7*24*time.Hour), "regular write must not trigger AbortMPU")
assert.Contains(t, snap.MatchOriginalWrite(mpu, 7*24*time.Hour), abortKey, "MPU init must trigger AbortMPU")
}
func TestFilterMatching_ExpiredDeleteMarkerRequiresMarkerLatest(t *testing.T) {
// EXPIRED_DELETE_MARKER actions only fire when the event is both a
// delete marker AND the current latest version. A non-delete event
// or a noncurrent delete marker must not trigger.
rule := &s3lifecycle.Rule{
ID: "r",
Status: s3lifecycle.StatusEnabled,
ExpiredObjectDeleteMarker: true,
}
hash := s3lifecycle.RuleHash(rule)
markerKey := s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: s3lifecycle.ActionKindExpiredDeleteMarker}
prior := map[s3lifecycle.ActionKey]PriorState{
markerKey: {BootstrapComplete: true, Mode: ModeEventDriven},
}
snap := New().Compile(
[]CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
CompileOptions{PriorStates: prior},
)
// ExpiredDeleteMarker has MinTriggerAge=0; the action lives in the
// zero-duration delay group, so the dispatcher polls it on every
// tick.
delay := time.Duration(0)
notMarker := &Event{Shape: EventShapeOriginalWrite, Bucket: "bk", Path: "x", IsDeleteMarker: false, IsLatest: true}
notLatest := &Event{Shape: EventShapeOriginalWrite, Bucket: "bk", Path: "x", IsDeleteMarker: true, IsLatest: false}
bothTrue := &Event{Shape: EventShapeOriginalWrite, Bucket: "bk", Path: "x", IsDeleteMarker: true, IsLatest: true}
assert.Empty(t, snap.MatchOriginalWrite(notMarker, delay), "non-marker must not trigger")
assert.Empty(t, snap.MatchOriginalWrite(notLatest, delay), "noncurrent marker must not trigger")
assert.Contains(t, snap.MatchOriginalWrite(bothTrue, delay), markerKey, "marker that is also latest must trigger")
}
+126
View File
@@ -0,0 +1,126 @@
package engine
import (
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
"github.com/stretchr/testify/assert"
)
// decideMode is the per-action mode classifier the scheduler uses when
// no durable Mode exists yet. Compile tests cover most paths
// indirectly; these direct tests pin every branch so a regression in
// decideMode itself can't slip through behind a more elaborate Compile
// test failure.
func TestDecideMode_NilRuleIsDisabled(t *testing.T) {
got := decideMode(nil, s3lifecycle.ActionKindExpirationDays, 0, 0)
assert.Equal(t, ModeDisabled, got)
}
func TestDecideMode_DisabledStatusIsDisabled(t *testing.T) {
rule := &s3lifecycle.Rule{Status: s3lifecycle.StatusDisabled, ExpirationDays: 30}
got := decideMode(rule, s3lifecycle.ActionKindExpirationDays, 0, 0)
assert.Equal(t, ModeDisabled, got)
}
func TestDecideMode_ExpirationDateIsScanAtDate(t *testing.T) {
// ExpirationDate is a one-shot wall-clock trigger; no event log
// involvement, so retention gates don't apply.
rule := &s3lifecycle.Rule{
Status: s3lifecycle.StatusEnabled,
ExpirationDate: time.Now().Add(24 * time.Hour),
}
got := decideMode(rule, s3lifecycle.ActionKindExpirationDate, 0, 0)
assert.Equal(t, ModeScanAtDate, got)
}
func TestDecideMode_UnboundedRetentionIsEventDriven(t *testing.T) {
// metaLogRetention=0 means unbounded; the retention gate doesn't
// trip, so any horizon falls back to event-driven.
rule := &s3lifecycle.Rule{
Status: s3lifecycle.StatusEnabled,
ExpirationDays: 365,
}
got := decideMode(rule, s3lifecycle.ActionKindExpirationDays, 0, time.Hour)
assert.Equal(t, ModeEventDriven, got)
}
func TestDecideMode_HorizonWithinRetentionIsEventDriven(t *testing.T) {
// retention=30d, horizon=7d, lookback=1m → 7d+1m < 30d → no gate.
rule := &s3lifecycle.Rule{
Status: s3lifecycle.StatusEnabled,
ExpirationDays: 7,
}
got := decideMode(rule, s3lifecycle.ActionKindExpirationDays, 30*24*time.Hour, time.Minute)
assert.Equal(t, ModeEventDriven, got)
}
func TestDecideMode_HorizonExceedsRetentionIsScanOnly(t *testing.T) {
// retention=7d, horizon=30d → can't drive from event log alone, so
// the action is promoted to scan_only and only fires from the
// bootstrap walk.
rule := &s3lifecycle.Rule{
Status: s3lifecycle.StatusEnabled,
ExpirationDays: 30,
}
got := decideMode(rule, s3lifecycle.ActionKindExpirationDays, 7*24*time.Hour, time.Minute)
assert.Equal(t, ModeScanOnly, got)
}
func TestDecideMode_LookbackPushesAcrossThreshold(t *testing.T) {
// retention=7d, horizon=7d - the bare horizon fits, but adding the
// bootstrapLookbackMin must push it past retention so the gate
// trips. Pins that lookback is added to horizon (not retention).
rule := &s3lifecycle.Rule{
Status: s3lifecycle.StatusEnabled,
ExpirationDays: 7,
}
retention := 7 * 24 * time.Hour
// horizon already ~= retention; even a tiny lookback should trip.
got := decideMode(rule, s3lifecycle.ActionKindExpirationDays, retention, 5*time.Minute)
assert.Equal(t, ModeScanOnly, got)
}
func TestDecideMode_ZeroHorizonNeverGates(t *testing.T) {
// EventLogHorizon returns 0 for kinds whose rule fields aren't set
// (e.g. an EXPIRATION_DAYS kind on a rule with ExpirationDays=0).
// A zero horizon must skip the gate so the action falls through to
// event-driven rather than incorrectly promote to scan_only.
rule := &s3lifecycle.Rule{
Status: s3lifecycle.StatusEnabled,
// ExpirationDays unset -> EventLogHorizon returns 0
}
got := decideMode(rule, s3lifecycle.ActionKindExpirationDays, time.Hour, time.Minute)
assert.Equal(t, ModeEventDriven, got)
}
func TestRuleMode_StringRendersDocumentedNames(t *testing.T) {
// Operators read these via metrics labels and admin UI; pin the
// exact strings so a rename can't break dashboards.
cases := []struct {
mode RuleMode
want string
}{
{ModeUnspecified, "unspecified"},
{ModeEventDriven, "event_driven"},
{ModeScanAtDate, "scan_at_date"},
{ModeScanOnly, "scan_only"},
{ModeDisabled, "disabled"},
{ModePendingBootstrap, "pending_bootstrap"},
}
for _, c := range cases {
t.Run(c.want, func(t *testing.T) {
assert.Equal(t, c.want, c.mode.String())
})
}
}
func TestRuleMode_StringFallsToUnspecifiedForUnknown(t *testing.T) {
// A bogus enum value (e.g., a future RuleMode added without a
// String() update) must render as "unspecified" rather than empty
// or panic.
bogus := RuleMode(999)
assert.Equal(t, "unspecified", bogus.String())
}
@@ -0,0 +1,201 @@
package engine
import (
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// Direct tests for Snapshot.OriginalDelayGroups / PredicateActions /
// DateActions accessors and MarkActive/IsActive transitions. The Compile
// tests exercise the construction path; these tests pin the read-side
// surface the router and dispatcher reach for at runtime.
func TestSnapshot_OriginalDelayGroupsExposesCompiledGroups(t *testing.T) {
// Two action kinds with different delays must land in distinct
// delay groups so the dispatcher polls each at the right cadence.
rule := &s3lifecycle.Rule{
ID: "r",
Status: s3lifecycle.StatusEnabled,
ExpirationDays: 7,
AbortMPUDaysAfterInitiation: 3,
}
hash := s3lifecycle.RuleHash(rule)
prior := map[s3lifecycle.ActionKey]PriorState{}
for _, k := range s3lifecycle.RuleActionKinds(rule) {
prior[s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: k}] = PriorState{
BootstrapComplete: true,
Mode: ModeEventDriven,
}
}
snap := New().Compile(
[]CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
CompileOptions{PriorStates: prior},
)
groups := snap.OriginalDelayGroups()
require.NotNil(t, groups)
// 7d expiration delay group must contain the specific expiration key.
expirationDelay := s3lifecycle.MinTriggerAge(rule, s3lifecycle.ActionKindExpirationDays)
expirationKey := s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: s3lifecycle.ActionKindExpirationDays}
assert.Contains(t, groups[expirationDelay], expirationKey, "expiration delay group must carry its specific key")
// 3d abort-mpu delay group is distinct and contains the abort key.
abortDelay := s3lifecycle.MinTriggerAge(rule, s3lifecycle.ActionKindAbortMPU)
assert.NotEqual(t, expirationDelay, abortDelay)
abortKey := s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: s3lifecycle.ActionKindAbortMPU}
assert.Contains(t, groups[abortDelay], abortKey, "abort-mpu delay group must carry its specific key")
}
func TestSnapshot_OriginalDelayGroupsScanOnlyExcluded(t *testing.T) {
// Scan-only actions don't go through originalDelayGroups (they
// fire from the bootstrap walk only), so the dispatcher's
// MatchOriginalWrite path won't see them.
rule := &s3lifecycle.Rule{ID: "r", Status: s3lifecycle.StatusEnabled, ExpirationDays: 7}
hash := s3lifecycle.RuleHash(rule)
scanOnlyKey := s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: s3lifecycle.ActionKindExpirationDays}
prior := map[s3lifecycle.ActionKey]PriorState{
scanOnlyKey: {BootstrapComplete: true, Mode: ModeScanOnly},
}
snap := New().Compile(
[]CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
CompileOptions{PriorStates: prior},
)
groups := snap.OriginalDelayGroups()
for delay, keys := range groups {
for _, k := range keys {
assert.NotEqual(t, scanOnlyKey, k, "scan-only action leaked into delay group %v", delay)
}
}
}
func TestSnapshot_PredicateActionsContainsTagSensitive(t *testing.T) {
// A tag-sensitive rule's actions must surface in PredicateActions
// so MatchPredicateChange routes them.
rule := &s3lifecycle.Rule{
ID: "r",
Status: s3lifecycle.StatusEnabled,
ExpirationDays: 7,
FilterTags: map[string]string{"env": "prod"},
}
hash := s3lifecycle.RuleHash(rule)
prior := map[s3lifecycle.ActionKey]PriorState{}
for _, k := range s3lifecycle.RuleActionKinds(rule) {
prior[s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: k}] = PriorState{
BootstrapComplete: true,
Mode: ModeEventDriven,
}
}
snap := New().Compile(
[]CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
CompileOptions{PriorStates: prior},
)
predicates := snap.PredicateActions()
require.NotEmpty(t, predicates, "tag-sensitive rule must populate predicateActions")
// Verify the specific key landed (not just non-empty) so a routing
// regression that emits a wrong ActionKey is caught.
expectedKey := s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: s3lifecycle.ActionKindExpirationDays}
assert.Contains(t, predicates, expectedKey, "predicateActions must carry the rule's specific ActionKey")
}
func TestSnapshot_PredicateActionsEmptyForNonTagSensitiveRule(t *testing.T) {
// A rule without FilterTags is not predicate-sensitive; the
// predicate-action list must stay empty so MatchPredicateChange
// never routes irrelevant kinds.
rule := &s3lifecycle.Rule{ID: "r", Status: s3lifecycle.StatusEnabled, ExpirationDays: 7}
snap := New().Compile(
[]CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
CompileOptions{},
)
assert.Empty(t, snap.PredicateActions())
}
func TestSnapshot_DateActionsContainsExpirationDate(t *testing.T) {
// EXPIRATION_DATE rules go into dateActions (not delay groups);
// the scan-at-date scheduler reads from this map.
when := time.Now().Add(24 * time.Hour)
rule := &s3lifecycle.Rule{
ID: "r",
Status: s3lifecycle.StatusEnabled,
ExpirationDate: when,
}
snap := New().Compile(
[]CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
CompileOptions{},
)
dateActions := snap.DateActions()
require.NotEmpty(t, dateActions)
for _, dt := range dateActions {
assert.Equal(t, when, dt, "DateActions must surface the rule's ExpirationDate verbatim")
}
}
func TestSnapshot_DateActionsEmptyForNonDateRule(t *testing.T) {
rule := &s3lifecycle.Rule{ID: "r", Status: s3lifecycle.StatusEnabled, ExpirationDays: 7}
snap := New().Compile(
[]CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
CompileOptions{},
)
assert.Empty(t, snap.DateActions())
}
func TestSnapshot_MarkActiveUnknownKeyIsNoOp(t *testing.T) {
// MarkActive must silently skip keys that aren't in the snapshot;
// the durable bootstrap-complete write can race with a recompile
// that drops the rule, and a panic here would crash the worker.
snap := New().Compile(nil, CompileOptions{})
snap.MarkActive(s3lifecycle.ActionKey{Bucket: "ghost", ActionKind: s3lifecycle.ActionKindExpirationDays})
}
func TestSnapshot_MarkActiveFlipsCompiledActionToActive(t *testing.T) {
// Bootstrap-pending actions land inactive; MarkActive transitions
// them to active so the routing filter starts emitting matches.
rule := &s3lifecycle.Rule{ID: "r", Status: s3lifecycle.StatusEnabled, ExpirationDays: 7}
hash := s3lifecycle.RuleHash(rule)
key := s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: s3lifecycle.ActionKindExpirationDays}
// No prior state -> the action lands inactive (BootstrapComplete=false).
snap := New().Compile(
[]CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
CompileOptions{},
)
a := snap.Action(key)
require.NotNil(t, a)
assert.False(t, a.IsActive(), "fresh action without prior state must be inactive")
snap.MarkActive(key)
assert.True(t, a.IsActive(), "MarkActive must transition the action to active")
}
func TestSnapshot_BucketIndexedActionKeysCoverAllKinds(t *testing.T) {
// Cross-check that BucketActionKeys lists every kind compiled from
// the rule, regardless of mode. The router iterates these for
// MatchPath, so a missed kind silently disables prefix-only routing
// for that action.
rule := &s3lifecycle.Rule{
ID: "r",
Status: s3lifecycle.StatusEnabled,
ExpirationDays: 7,
AbortMPUDaysAfterInitiation: 3,
ExpiredObjectDeleteMarker: true,
}
snap := New().Compile(
[]CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
CompileOptions{},
)
keys := snap.BucketActionKeys("bk")
wantKinds := s3lifecycle.RuleActionKinds(rule)
require.Len(t, keys, len(wantKinds))
// Verify the contents, not just the count: every key must carry
// the right bucket scope, and the kinds must match RuleActionKinds
// element-for-element (in any order). Catches an indexing
// regression that produces N keys but with wrong kinds.
gotKinds := make([]s3lifecycle.ActionKind, 0, len(keys))
for _, k := range keys {
assert.Equal(t, "bk", k.Bucket, "key leaked across bucket")
gotKinds = append(gotKinds, k.ActionKind)
}
assert.ElementsMatch(t, wantKinds, gotKinds, "kinds must match RuleActionKinds")
}
@@ -0,0 +1,48 @@
package s3lifecycle
import (
"testing"
"github.com/stretchr/testify/assert"
)
// Final unit-test cleanup ahead of the integration suite. Pins the
// remaining 0%-and-default-branch helpers in the s3lifecycle package
// and the lifecycletest builder so a regression doesn't slip in
// during the integration work that follows.
func TestActionKind_StringUnspecifiedDefault(t *testing.T) {
// String's default branch (covers ActionKindUnspecified and any
// future enum value not listed) must render "unspecified" rather
// than empty or panic. Operators read this via the metrics labels
// (see S3LifecycleDispatchCounter "kind").
assert.Equal(t, "unspecified", ActionKindUnspecified.String())
assert.Equal(t, "unspecified", ActionKind(99).String())
}
func TestHashExtended_DirectFromLifecyclePackage(t *testing.T) {
// HashExtended is exercised from the s3api package's identity
// tests; pin it here so the s3lifecycle package's own coverage
// reflects the call. A nil/empty map produces no bytes, so the
// CAS witness collapses to "no Extended" rather than a synthetic
// hash that would mismatch on the server.
assert.Empty(t, HashExtended(nil))
assert.Empty(t, HashExtended(map[string][]byte{}))
got := HashExtended(map[string][]byte{"a": []byte("1")})
assert.NotEmpty(t, got)
// Same content, different literal/insertion order across multiple
// keys: hash must be stable. A single-key check can't catch an
// iteration-order regression — multiple keys force the helper's
// sort path to actually do work.
first := HashExtended(map[string][]byte{
"a": []byte("1"),
"b": []byte("2"),
"c": []byte("3"),
})
second := HashExtended(map[string][]byte{
"c": []byte("3"),
"a": []byte("1"),
"b": []byte("2"),
})
assert.Equal(t, first, second, "hash must be insensitive to map iteration order")
}
@@ -0,0 +1,286 @@
package lifecycletest
import (
"sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/reader"
)
// EventOption mutates a reader.Event during construction. Options compose
// in order — later options override earlier ones if they touch the same
// field, which lets a default+override pattern work without surprises.
type EventOption func(*reader.Event)
// WithSize sets the Size on whichever entry the event populates (NewEntry
// for Create / Update, OldEntry for Delete). Constructors that build
// both entries apply the size to NewEntry.
func WithSize(bytes int64) EventOption {
return func(e *reader.Event) {
if e.NewEntry != nil && e.NewEntry.Attributes != nil {
e.NewEntry.Attributes.FileSize = uint64(bytes)
} else if e.OldEntry != nil && e.OldEntry.Attributes != nil {
e.OldEntry.Attributes.FileSize = uint64(bytes)
}
}
}
// WithModTime sets Mtime/MtimeNs on the populated entry.
func WithModTime(t time.Time) EventOption {
return func(e *reader.Event) {
secs, nanos := t.Unix(), int32(t.Nanosecond())
if e.NewEntry != nil && e.NewEntry.Attributes != nil {
e.NewEntry.Attributes.Mtime = secs
e.NewEntry.Attributes.MtimeNs = nanos
} else if e.OldEntry != nil && e.OldEntry.Attributes != nil {
e.OldEntry.Attributes.Mtime = secs
e.OldEntry.Attributes.MtimeNs = nanos
}
}
}
// WithTtlSec sets the TTL on the populated entry. Used by tests that
// exercise the lifecycle metadata-only delete path (TtlSec > 0 means
// the volume reclaims chunks naturally).
func WithTtlSec(ttl int32) EventOption {
return func(e *reader.Event) {
if e.NewEntry != nil && e.NewEntry.Attributes != nil {
e.NewEntry.Attributes.TtlSec = ttl
} else if e.OldEntry != nil && e.OldEntry.Attributes != nil {
e.OldEntry.Attributes.TtlSec = ttl
}
}
}
// WithVersionID stamps Seaweed-X-Amz-Version-Id on the populated entry's
// Extended map. Used by versioning-aware router and dispatcher tests.
func WithVersionID(versionID string) EventOption {
return func(e *reader.Event) {
var entry *filer_pb.Entry
if e.NewEntry != nil {
entry = e.NewEntry
} else if e.OldEntry != nil {
entry = e.OldEntry
}
if entry == nil {
return
}
if entry.Extended == nil {
entry.Extended = map[string][]byte{}
}
entry.Extended[s3_constants.ExtVersionIdKey] = []byte(versionID)
}
}
// WithExtended sets an arbitrary Extended key/value on the populated entry.
func WithExtended(key string, value []byte) EventOption {
return func(e *reader.Event) {
var entry *filer_pb.Entry
if e.NewEntry != nil {
entry = e.NewEntry
} else if e.OldEntry != nil {
entry = e.OldEntry
}
if entry == nil {
return
}
if entry.Extended == nil {
entry.Extended = map[string][]byte{}
}
entry.Extended[key] = value
}
}
// WithChunks attaches FileChunks to the populated entry. Identity-CAS in
// LifecycleDelete uses the head chunk's FID, so tests that exercise CAS
// drift need at least one chunk. For Update events the chunks land on
// NewEntry; use WithOldChunks to target the pre-update state.
func WithChunks(chunks ...*filer_pb.FileChunk) EventOption {
return func(e *reader.Event) {
if e.NewEntry != nil {
e.NewEntry.Chunks = append(e.NewEntry.Chunks, chunks...)
} else if e.OldEntry != nil {
e.OldEntry.Chunks = append(e.OldEntry.Chunks, chunks...)
}
}
}
// WithOldSize sets FileSize on OldEntry specifically. Use on Update
// events to configure the pre-update size (the WithSize default lands
// on NewEntry when both are populated).
func WithOldSize(bytes int64) EventOption {
return func(e *reader.Event) {
if e.OldEntry != nil && e.OldEntry.Attributes != nil {
e.OldEntry.Attributes.FileSize = uint64(bytes)
}
}
}
// WithOldChunks attaches FileChunks to OldEntry specifically. Use on
// Update events to configure the pre-update chunk list (WithChunks
// targets NewEntry when both are populated).
func WithOldChunks(chunks ...*filer_pb.FileChunk) EventOption {
return func(e *reader.Event) {
if e.OldEntry != nil {
e.OldEntry.Chunks = append(e.OldEntry.Chunks, chunks...)
}
}
}
// WithOldModTime sets Mtime/MtimeNs on OldEntry specifically. Update
// events whose pre-update mtime should differ from the event timestamp
// use this to override the default.
func WithOldModTime(t time.Time) EventOption {
return func(e *reader.Event) {
if e.OldEntry != nil && e.OldEntry.Attributes != nil {
e.OldEntry.Attributes.Mtime = t.Unix()
e.OldEntry.Attributes.MtimeNs = int32(t.Nanosecond())
}
}
}
// WithBootstrapVersion attaches a BootstrapVersion to the event.
// Bootstrap-walk events use this to carry per-version state the live
// meta-log doesn't see.
func WithBootstrapVersion(bv *reader.BootstrapVersion) EventOption {
return func(e *reader.Event) { e.BootstrapVersion = bv }
}
// WithShardID overrides the computed ShardID. Most tests should leave
// it as the s3lifecycle.ShardID default to mirror production routing.
func WithShardID(shard int) EventOption {
return func(e *reader.Event) { e.ShardID = shard }
}
// NewCreate builds a Create event (NewEntry populated, OldEntry nil) at
// the given timestamp. Bucket and key are required; everything else is
// derived (Mtime defaults to ts, FileSize defaults to 0). Apply options
// to override.
func NewCreate(bucket, key string, ts time.Time, opts ...EventOption) *reader.Event {
e := &reader.Event{
TsNs: ts.UnixNano(),
Bucket: bucket,
Key: key,
ShardID: s3lifecycle.ShardID(bucket, key),
NewEntry: &filer_pb.Entry{
Name: leafOf(key),
Attributes: &filer_pb.FuseAttributes{
Mtime: ts.Unix(),
MtimeNs: int32(ts.Nanosecond()),
},
},
}
for _, o := range opts {
o(e)
}
return e
}
// NewDelete builds a Delete event (OldEntry populated, NewEntry nil).
// Tests usually pass the entry the prior Create produced as a snapshot
// of pre-delete state; this helper builds a minimal stand-in.
func NewDelete(bucket, key string, ts time.Time, opts ...EventOption) *reader.Event {
e := &reader.Event{
TsNs: ts.UnixNano(),
Bucket: bucket,
Key: key,
ShardID: s3lifecycle.ShardID(bucket, key),
OldEntry: &filer_pb.Entry{
Name: leafOf(key),
Attributes: &filer_pb.FuseAttributes{
Mtime: ts.Unix(),
MtimeNs: int32(ts.Nanosecond()),
},
},
}
for _, o := range opts {
o(e)
}
return e
}
// NewUpdate builds an Update event (both OldEntry and NewEntry populated).
// Same defaults as NewCreate; options apply to NewEntry per the rules in
// each option's doc.
func NewUpdate(bucket, key string, ts time.Time, opts ...EventOption) *reader.Event {
e := &reader.Event{
TsNs: ts.UnixNano(),
Bucket: bucket,
Key: key,
ShardID: s3lifecycle.ShardID(bucket, key),
OldEntry: &filer_pb.Entry{
Name: leafOf(key),
Attributes: &filer_pb.FuseAttributes{
Mtime: ts.Unix(),
MtimeNs: int32(ts.Nanosecond()),
},
},
NewEntry: &filer_pb.Entry{
Name: leafOf(key),
Attributes: &filer_pb.FuseAttributes{
Mtime: ts.Unix(),
MtimeNs: int32(ts.Nanosecond()),
},
},
}
for _, o := range opts {
o(e)
}
return e
}
// MetaLogClock produces monotonically increasing timestamps for fixture
// generation. Each call to Next advances by Step (default 1s) so tests
// don't have to thread a counter through every helper invocation. Safe
// for concurrent use.
type MetaLogClock struct {
mu sync.Mutex
now time.Time
step time.Duration
}
// NewMetaLogClock returns a clock that ticks forward Step on every Next
// call. Step defaults to 1s when zero.
func NewMetaLogClock(start time.Time, step time.Duration) *MetaLogClock {
if step <= 0 {
step = time.Second
}
return &MetaLogClock{now: start, step: step}
}
// Next returns the current timestamp and advances by Step.
func (c *MetaLogClock) Next() time.Time {
c.mu.Lock()
defer c.mu.Unlock()
t := c.now
c.now = c.now.Add(c.step)
return t
}
// Peek returns what Next() would return without advancing.
func (c *MetaLogClock) Peek() time.Time {
c.mu.Lock()
defer c.mu.Unlock()
return c.now
}
// leafOf returns the basename of a slash-separated key. Filer entries
// store only the leaf name; tests that mirror production layout need
// the same shape. Trailing slashes are stripped first so directory-key
// fixtures (e.g. "folder/") get the slashless leaf "folder" — the
// production directory-marker write path stores the name without the
// trailing slash.
func leafOf(key string) string {
for len(key) > 0 && key[len(key)-1] == '/' {
key = key[:len(key)-1]
}
for i := len(key) - 1; i >= 0; i-- {
if key[i] == '/' {
return key[i+1:]
}
}
return key
}
@@ -0,0 +1,102 @@
package lifecycletest
import (
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/reader"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// Coverage gap-fillers for the With* options' OldEntry-only branches
// (NewEntry==nil, OldEntry populated — i.e. Delete events). The
// existing eventbuilder_test.go covers Create events; these tests
// exercise the alternate fall-through path on each option.
func TestEventOption_WithModTime_AppliesToOldEntryOnDelete(t *testing.T) {
t0 := time.Unix(1700000000, 0)
override := time.Unix(1699000000, 250)
e := NewDelete("bk", "k", t0, WithModTime(override))
require.Nil(t, e.NewEntry)
require.NotNil(t, e.OldEntry)
assert.Equal(t, override.Unix(), e.OldEntry.Attributes.Mtime)
assert.Equal(t, int32(250), e.OldEntry.Attributes.MtimeNs)
}
func TestEventOption_WithTtlSec_AppliesToOldEntryOnDelete(t *testing.T) {
e := NewDelete("bk", "k", time.Unix(0, 0), WithTtlSec(7200))
require.NotNil(t, e.OldEntry)
assert.Equal(t, int32(7200), e.OldEntry.Attributes.TtlSec)
}
func TestEventOption_WithVersionID_AppliesToOldEntryOnDelete(t *testing.T) {
// VersionID-on-delete: the bootstrapper synthesizes deletes for
// noncurrent-version sweeps and needs the version-id stamp.
e := NewDelete("bk", "k", time.Unix(0, 0), WithVersionID("v_old"))
require.NotNil(t, e.OldEntry)
require.NotNil(t, e.OldEntry.Extended)
assert.Equal(t, []byte("v_old"), e.OldEntry.Extended[s3_constants.ExtVersionIdKey])
}
func TestEventOption_WithExtended_AppliesToOldEntryOnDelete(t *testing.T) {
e := NewDelete("bk", "k", time.Unix(0, 0), WithExtended("Custom-Tag", []byte("v")))
require.NotNil(t, e.OldEntry)
require.NotNil(t, e.OldEntry.Extended)
assert.Equal(t, []byte("v"), e.OldEntry.Extended["Custom-Tag"])
}
func TestEventOption_WithChunks_AppliesToOldEntryOnDelete(t *testing.T) {
c := &filer_pb.FileChunk{FileId: "1,old"}
e := NewDelete("bk", "k", time.Unix(0, 0), WithChunks(c))
require.NotNil(t, e.OldEntry)
require.Len(t, e.OldEntry.Chunks, 1)
assert.Equal(t, "1,old", e.OldEntry.Chunks[0].FileId)
}
func TestEventOption_WithBootstrapVersion(t *testing.T) {
// WithBootstrapVersion attaches a BootstrapVersion to the event;
// the bootstrap walker uses this for per-version state the live
// meta-log doesn't carry. Pin both create and delete shapes.
bv := &reader.BootstrapVersion{
LogicalKey: "obj.txt",
VersionID: "v_aaa",
IsLatest: true,
IsDeleteMarker: false,
NumVersions: 3,
NoncurrentIndex: 2,
}
create := NewCreate("bk", "obj.txt", time.Unix(0, 0), WithBootstrapVersion(bv))
require.Same(t, bv, create.BootstrapVersion)
del := NewDelete("bk", "obj.txt", time.Unix(0, 0), WithBootstrapVersion(bv))
require.Same(t, bv, del.BootstrapVersion)
update := NewUpdate("bk", "obj.txt", time.Unix(0, 0), WithBootstrapVersion(bv))
require.Same(t, bv, update.BootstrapVersion)
}
func TestEventOption_NoPanicOnEmptyEvent(t *testing.T) {
// Defense: an event with neither NewEntry nor OldEntry must not
// panic on any With* option, even though no constructor produces
// this shape today. Entry-targeting options fall through silently
// (NewEntry/OldEntry stay nil); WithBootstrapVersion targets the
// event itself, not an entry, so it does set BootstrapVersion —
// included here for panic safety.
e := &reader.Event{}
WithModTime(time.Unix(1, 0))(e)
WithTtlSec(60)(e)
WithVersionID("v")(e)
WithExtended("k", []byte("v"))(e)
WithChunks(&filer_pb.FileChunk{FileId: "x"})(e)
WithSize(1024)(e)
bv := &reader.BootstrapVersion{VersionID: "v"}
WithBootstrapVersion(bv)(e)
assert.Nil(t, e.NewEntry, "entry-targeting options must not allocate NewEntry")
assert.Nil(t, e.OldEntry, "entry-targeting options must not allocate OldEntry")
assert.Same(t, bv, e.BootstrapVersion, "WithBootstrapVersion sets the field regardless of entry state")
}
@@ -0,0 +1,240 @@
package lifecycletest
import (
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestNewCreate_PopulatesNewEntryOnly(t *testing.T) {
t0 := time.Unix(1700000000, 123)
e := NewCreate("bk", "obj.txt", t0)
require.NotNil(t, e.NewEntry)
assert.Nil(t, e.OldEntry)
assert.True(t, e.IsCreate())
assert.Equal(t, t0.UnixNano(), e.TsNs)
assert.Equal(t, "bk", e.Bucket)
assert.Equal(t, "obj.txt", e.Key)
assert.Equal(t, "obj.txt", e.NewEntry.Name)
// Mtime defaults to the event timestamp; tests that don't care can
// rely on this rather than threading time through every call.
assert.Equal(t, t0.Unix(), e.NewEntry.Attributes.Mtime)
assert.Equal(t, int32(t0.Nanosecond()), e.NewEntry.Attributes.MtimeNs)
}
func TestNewDelete_PopulatesOldEntryOnly(t *testing.T) {
t0 := time.Unix(1700000000, 0)
e := NewDelete("bk", "obj.txt", t0)
require.NotNil(t, e.OldEntry)
assert.Nil(t, e.NewEntry)
assert.True(t, e.IsDelete())
assert.Equal(t, "obj.txt", e.OldEntry.Name)
}
func TestNewUpdate_PopulatesBothEntries(t *testing.T) {
t0 := time.Unix(1700000000, 0)
e := NewUpdate("bk", "obj.txt", t0)
require.NotNil(t, e.OldEntry)
require.NotNil(t, e.NewEntry)
assert.False(t, e.IsCreate())
assert.False(t, e.IsDelete())
// OldEntry's Mtime defaults to the event ts so its mirror of pre-
// update state reflects the same wall-clock origin as NewEntry —
// a downstream router that compares mtimes won't see a synthetic
// 1970 epoch.
assert.Equal(t, t0.Unix(), e.OldEntry.Attributes.Mtime)
assert.Equal(t, t0.Unix(), e.NewEntry.Attributes.Mtime)
}
func TestNewCreate_NestedKeyUsesLeafName(t *testing.T) {
// Filer entries store only the leaf name; mirroring that in the
// fixture keeps router/dispatcher tests realistic.
e := NewCreate("bk", "a/b/c.txt", time.Unix(0, 0))
assert.Equal(t, "c.txt", e.NewEntry.Name)
}
func TestNewCreate_DirectoryKeyUsesSlashlessLeaf(t *testing.T) {
// Directory-marker objects (S3 keys ending in "/") store the leaf
// name without the trailing slash on the filer side. A pre-fix
// regression returned "" here.
e := NewCreate("bk", "folder/", time.Unix(0, 0))
assert.Equal(t, "folder", e.NewEntry.Name)
// Nested directory key strips both the trailing slash AND the
// parent prefix.
e2 := NewCreate("bk", "a/b/folder/", time.Unix(0, 0))
assert.Equal(t, "folder", e2.NewEntry.Name)
// Multiple trailing slashes collapse.
e3 := NewCreate("bk", "folder///", time.Unix(0, 0))
assert.Equal(t, "folder", e3.NewEntry.Name)
}
func TestNewCreate_ShardIDDerivedFromKey(t *testing.T) {
// ShardID matches s3lifecycle.ShardID(bucket, key) so the event
// routes through the same shard the production reader would
// classify it under.
e := NewCreate("bk", "obj.txt", time.Unix(0, 0))
assert.Equal(t, s3lifecycle.ShardID("bk", "obj.txt"), e.ShardID)
}
func TestEventOption_WithSize(t *testing.T) {
e := NewCreate("bk", "k", time.Unix(0, 0), WithSize(4096))
assert.Equal(t, uint64(4096), e.NewEntry.Attributes.FileSize)
}
func TestEventOption_WithSizeAppliesToOldEntryOnDelete(t *testing.T) {
// Delete events have OldEntry only; WithSize must apply there.
e := NewDelete("bk", "k", time.Unix(0, 0), WithSize(8192))
assert.Equal(t, uint64(8192), e.OldEntry.Attributes.FileSize)
}
func TestEventOption_WithModTimeOverridesDefault(t *testing.T) {
// Default Mtime is event ts; explicit WithModTime overrides.
t0 := time.Unix(1700000000, 0)
override := time.Unix(1700000123, 456)
e := NewCreate("bk", "k", t0, WithModTime(override))
assert.Equal(t, override.Unix(), e.NewEntry.Attributes.Mtime)
assert.Equal(t, int32(override.Nanosecond()), e.NewEntry.Attributes.MtimeNs)
}
func TestEventOption_WithTtlSec(t *testing.T) {
// WithTtlSec drives the lifecycle metadata-only delete path; the
// gate fires when the live entry's TtlSec > 0.
e := NewCreate("bk", "k", time.Unix(0, 0), WithTtlSec(300))
assert.Equal(t, int32(300), e.NewEntry.Attributes.TtlSec)
}
func TestEventOption_WithVersionID(t *testing.T) {
e := NewCreate("bk", "k", time.Unix(0, 0), WithVersionID("v_abc"))
assert.Equal(t, []byte("v_abc"), e.NewEntry.Extended[s3_constants.ExtVersionIdKey])
}
func TestEventOption_WithExtendedKeyValue(t *testing.T) {
e := NewCreate("bk", "k", time.Unix(0, 0), WithExtended("Custom-Tag", []byte("v1")))
assert.Equal(t, []byte("v1"), e.NewEntry.Extended["Custom-Tag"])
}
func TestEventOption_WithChunks(t *testing.T) {
c1 := &filer_pb.FileChunk{FileId: "1,abc"}
c2 := &filer_pb.FileChunk{FileId: "1,def"}
e := NewCreate("bk", "k", time.Unix(0, 0), WithChunks(c1, c2))
require.Len(t, e.NewEntry.Chunks, 2)
assert.Equal(t, "1,abc", e.NewEntry.Chunks[0].FileId)
assert.Equal(t, "1,def", e.NewEntry.Chunks[1].FileId)
}
func TestEventOption_WithShardIDOverrides(t *testing.T) {
e := NewCreate("bk", "obj.txt", time.Unix(0, 0), WithShardID(7))
assert.Equal(t, 7, e.ShardID)
}
func TestEventOption_WithOldSizeTargetsOldEntryOnUpdate(t *testing.T) {
// On Update events, WithSize lands on NewEntry; WithOldSize lets
// the caller configure pre-update state independently. Both options
// in a single call should produce distinct sizes on the two entries.
t0 := time.Unix(1700000000, 0)
e := NewUpdate("bk", "k", t0, WithSize(200), WithOldSize(100))
assert.Equal(t, uint64(200), e.NewEntry.Attributes.FileSize, "WithSize lands on NewEntry")
assert.Equal(t, uint64(100), e.OldEntry.Attributes.FileSize, "WithOldSize lands on OldEntry")
}
func TestEventOption_WithOldChunksTargetsOldEntryOnUpdate(t *testing.T) {
newChunk := &filer_pb.FileChunk{FileId: "1,new"}
oldChunk := &filer_pb.FileChunk{FileId: "1,old"}
t0 := time.Unix(1700000000, 0)
e := NewUpdate("bk", "k", t0, WithChunks(newChunk), WithOldChunks(oldChunk))
require.Len(t, e.NewEntry.Chunks, 1)
require.Len(t, e.OldEntry.Chunks, 1)
assert.Equal(t, "1,new", e.NewEntry.Chunks[0].FileId)
assert.Equal(t, "1,old", e.OldEntry.Chunks[0].FileId)
}
func TestEventOption_WithOldModTimeTargetsOldEntryOnUpdate(t *testing.T) {
// Pre-update mtime can lag the event timestamp; WithOldModTime lets
// a router test pin the noncurrent-clock origin.
t0 := time.Unix(1700000000, 0)
older := time.Unix(1699000000, 500)
e := NewUpdate("bk", "k", t0, WithOldModTime(older))
assert.Equal(t, older.Unix(), e.OldEntry.Attributes.Mtime)
assert.Equal(t, int32(500), e.OldEntry.Attributes.MtimeNs)
// NewEntry's mtime stays at the default ts.
assert.Equal(t, t0.Unix(), e.NewEntry.Attributes.Mtime)
}
func TestEventOption_WithOldOptionsAreNoOpsOnCreate(t *testing.T) {
// Create events have no OldEntry; the WithOld* options must not
// panic and must not leak fields into NewEntry.
t0 := time.Unix(1700000000, 0)
e := NewCreate("bk", "k", t0,
WithOldSize(999),
WithOldChunks(&filer_pb.FileChunk{FileId: "phantom"}),
WithOldModTime(time.Unix(1, 0)),
)
assert.Nil(t, e.OldEntry)
assert.Equal(t, uint64(0), e.NewEntry.Attributes.FileSize, "WithOldSize must not bleed to NewEntry")
assert.Empty(t, e.NewEntry.Chunks, "WithOldChunks must not bleed to NewEntry")
assert.Equal(t, t0.Unix(), e.NewEntry.Attributes.Mtime, "WithOldModTime must not bleed to NewEntry")
}
func TestEventOption_LaterOverridesEarlier(t *testing.T) {
// Apply order matters: later options win on the same field. Pins
// the documented ordering so tests can compose default+override
// patterns without surprises.
e := NewCreate("bk", "k", time.Unix(0, 0),
WithSize(100),
WithSize(200),
)
assert.Equal(t, uint64(200), e.NewEntry.Attributes.FileSize)
}
func TestMetaLogClock_DefaultStepIsOneSecond(t *testing.T) {
c := NewMetaLogClock(time.Unix(1000, 0), 0)
t1 := c.Next()
t2 := c.Next()
assert.Equal(t, time.Second, t2.Sub(t1))
}
func TestMetaLogClock_CustomStep(t *testing.T) {
c := NewMetaLogClock(time.Unix(1000, 0), 250*time.Millisecond)
t1 := c.Next()
t2 := c.Next()
assert.Equal(t, 250*time.Millisecond, t2.Sub(t1))
}
func TestMetaLogClock_PeekDoesNotAdvance(t *testing.T) {
c := NewMetaLogClock(time.Unix(1000, 0), time.Second)
first := c.Peek()
again := c.Peek()
assert.True(t, first.Equal(again), "Peek must not advance the clock")
advanced := c.Next()
assert.True(t, first.Equal(advanced), "Next returns what Peek returned")
}
func TestMetaLogClock_ConcurrentNextNoRace(t *testing.T) {
// Tests that produce events from many goroutines (e.g. fan-out
// fixtures) need the clock to serialize without deadlock or
// duplicate timestamps. -race catches a regression that drops
// the lock.
c := NewMetaLogClock(time.Unix(0, 0), time.Microsecond)
const N = 64
seen := sync.Map{}
var wg sync.WaitGroup
wg.Add(N)
for i := 0; i < N; i++ {
go func() {
defer wg.Done()
seen.Store(c.Next(), struct{}{})
}()
}
wg.Wait()
count := 0
seen.Range(func(_, _ any) bool { count++; return true })
assert.Equal(t, N, count, "every Next must produce a unique timestamp")
}
@@ -0,0 +1,159 @@
// Package lifecycletest provides reusable test doubles for the lifecycle
// worker pipeline. The pieces here let component-level tests stand up the
// gRPC boundary the worker dials at runtime without pulling in a real
// S3ApiServer or filer.
package lifecycletest
import (
"context"
"sync"
"github.com/seaweedfs/seaweedfs/weed/pb/s3_lifecycle_pb"
"google.golang.org/protobuf/proto"
)
// Outcome is what the fake returns for a single LifecycleDelete call.
// Code is required; Reason is echoed verbatim into LifecycleDeleteResponse.
type Outcome struct {
Code s3_lifecycle_pb.LifecycleDeleteOutcome
Reason string
}
// Done, NoopResolved, RetryLater, Blocked, SkippedObjectLock are
// constructors for the common outcomes; tests can also build Outcome
// values directly when they need a specific Reason.
func Done() Outcome {
return Outcome{Code: s3_lifecycle_pb.LifecycleDeleteOutcome_DONE}
}
func NoopResolved(reason string) Outcome {
return Outcome{Code: s3_lifecycle_pb.LifecycleDeleteOutcome_NOOP_RESOLVED, Reason: reason}
}
func RetryLater(reason string) Outcome {
return Outcome{Code: s3_lifecycle_pb.LifecycleDeleteOutcome_RETRY_LATER, Reason: reason}
}
func Blocked(reason string) Outcome {
return Outcome{Code: s3_lifecycle_pb.LifecycleDeleteOutcome_BLOCKED, Reason: reason}
}
func SkippedObjectLock(reason string) Outcome {
return Outcome{Code: s3_lifecycle_pb.LifecycleDeleteOutcome_SKIPPED_OBJECT_LOCK, Reason: reason}
}
// FakeLifecycleServer implements s3_lifecycle_pb.SeaweedS3LifecycleInternalServer.
// It returns per-key queued outcomes (FIFO) and falls back to Default when a
// key has no queued entry. Every received request is recorded; tests assert
// against Recorded() in arrival order.
//
// A non-nil Err short-circuits everything — LifecycleDelete returns (nil, Err)
// immediately, before the per-key lookup or the request recording. Use it to
// simulate transport failures.
//
// All methods are safe for concurrent use. Outcomes/Default may be set at
// construction or via Queue/SetDefault between calls; mid-call mutation is
// supported but ordering across that boundary is undefined.
type FakeLifecycleServer struct {
s3_lifecycle_pb.UnimplementedSeaweedS3LifecycleInternalServer
mu sync.Mutex
queues map[requestKey][]Outcome
def Outcome
err error
received []*s3_lifecycle_pb.LifecycleDeleteRequest
}
// requestKey is the map key for queues. A struct rather than a delimited
// string so bucket/object/versionId values containing "/" or "@" can't
// collide.
type requestKey struct {
bucket, objectPath, versionId string
}
// NewFakeLifecycleServer returns a server whose Default outcome is DONE.
// Most tests want a different default; call SetDefault to change it.
func NewFakeLifecycleServer() *FakeLifecycleServer {
return &FakeLifecycleServer{
queues: map[requestKey][]Outcome{},
def: Done(),
}
}
// Queue appends an outcome to the FIFO for (bucket, objectPath, versionId).
// Subsequent calls matching the same key return outcomes in the order they
// were queued; once the queue is drained, Default applies.
func (f *FakeLifecycleServer) Queue(bucket, objectPath, versionId string, outcome Outcome) {
f.mu.Lock()
defer f.mu.Unlock()
k := key(bucket, objectPath, versionId)
f.queues[k] = append(f.queues[k], outcome)
}
// SetDefault sets the outcome returned when no per-key queue entry remains.
func (f *FakeLifecycleServer) SetDefault(o Outcome) {
f.mu.Lock()
defer f.mu.Unlock()
f.def = o
}
// SetError makes LifecycleDelete return (nil, err) on every call until
// SetError(nil) clears it. The request is not recorded while Err is set —
// transport-error tests should rely on the worker's own bookkeeping.
func (f *FakeLifecycleServer) SetError(err error) {
f.mu.Lock()
defer f.mu.Unlock()
f.err = err
}
// Recorded returns a deep-copied snapshot of every request the server has
// received (excluding calls that returned a transport error). Both the
// slice and each element are independent of the fake's internal state, so
// callers can mutate freely without affecting later Recorded() snapshots.
func (f *FakeLifecycleServer) Recorded() []*s3_lifecycle_pb.LifecycleDeleteRequest {
f.mu.Lock()
defer f.mu.Unlock()
out := make([]*s3_lifecycle_pb.LifecycleDeleteRequest, len(f.received))
for i, r := range f.received {
out[i] = cloneRequest(r)
}
return out
}
// LifecycleDelete is the gRPC handler. It honors Err first, then dequeues
// the per-key outcome, falling back to Default.
func (f *FakeLifecycleServer) LifecycleDelete(ctx context.Context, req *s3_lifecycle_pb.LifecycleDeleteRequest) (*s3_lifecycle_pb.LifecycleDeleteResponse, error) {
f.mu.Lock()
if f.err != nil {
err := f.err
f.mu.Unlock()
return nil, err
}
// Record a deep copy so a caller mutating a Recorded() entry can't
// reach back into the fake's bookkeeping (and so subsequent calls'
// view of "what arrived" stays stable across assertions).
f.received = append(f.received, cloneRequest(req))
if req == nil {
out := f.def
f.mu.Unlock()
return &s3_lifecycle_pb.LifecycleDeleteResponse{Outcome: out.Code, Reason: out.Reason}, nil
}
k := key(req.Bucket, req.ObjectPath, req.VersionId)
q := f.queues[k]
var out Outcome
if len(q) > 0 {
out = q[0]
f.queues[k] = q[1:]
} else {
out = f.def
}
f.mu.Unlock()
return &s3_lifecycle_pb.LifecycleDeleteResponse{Outcome: out.Code, Reason: out.Reason}, nil
}
func key(bucket, objectPath, versionId string) requestKey {
return requestKey{bucket: bucket, objectPath: objectPath, versionId: versionId}
}
func cloneRequest(req *s3_lifecycle_pb.LifecycleDeleteRequest) *s3_lifecycle_pb.LifecycleDeleteRequest {
if req == nil {
return nil
}
return proto.Clone(req).(*s3_lifecycle_pb.LifecycleDeleteRequest)
}
@@ -0,0 +1,217 @@
package lifecycletest
import (
"context"
"errors"
"sync"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/s3_lifecycle_pb"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestFake_DefaultIsDoneOutOfTheBox(t *testing.T) {
// A test that doesn't queue anything should still get a non-error
// response so it can exercise the worker's happy path.
f := NewFakeLifecycleServer()
resp, err := f.LifecycleDelete(context.Background(), &s3_lifecycle_pb.LifecycleDeleteRequest{
Bucket: "b",
ObjectPath: "k",
})
require.NoError(t, err)
require.NotNil(t, resp)
assert.Equal(t, s3_lifecycle_pb.LifecycleDeleteOutcome_DONE, resp.Outcome)
assert.Equal(t, "", resp.Reason)
}
func TestFake_QueuedOutcomesPopFIFO(t *testing.T) {
// Per-key queue is FIFO and one-shot per entry; after the queue
// drains, Default kicks in.
f := NewFakeLifecycleServer()
f.SetDefault(NoopResolved("nothing more queued"))
f.Queue("b", "k", "", RetryLater("first"))
f.Queue("b", "k", "", Blocked("second"))
got := []s3_lifecycle_pb.LifecycleDeleteOutcome{}
reasons := []string{}
for i := 0; i < 3; i++ {
resp, err := f.LifecycleDelete(context.Background(), &s3_lifecycle_pb.LifecycleDeleteRequest{
Bucket: "b", ObjectPath: "k",
})
require.NoError(t, err)
got = append(got, resp.Outcome)
reasons = append(reasons, resp.Reason)
}
assert.Equal(t, []s3_lifecycle_pb.LifecycleDeleteOutcome{
s3_lifecycle_pb.LifecycleDeleteOutcome_RETRY_LATER,
s3_lifecycle_pb.LifecycleDeleteOutcome_BLOCKED,
s3_lifecycle_pb.LifecycleDeleteOutcome_NOOP_RESOLVED,
}, got)
assert.Equal(t, []string{"first", "second", "nothing more queued"}, reasons)
}
func TestFake_QueuesIsolatedByKey(t *testing.T) {
// Queues are partitioned by (bucket, objectPath, versionId); a queued
// outcome for one key must not bleed into another's lookup.
f := NewFakeLifecycleServer()
f.Queue("b", "a", "", Blocked("a-only"))
f.Queue("b", "b", "", RetryLater("b-only"))
respA, err := f.LifecycleDelete(context.Background(), &s3_lifecycle_pb.LifecycleDeleteRequest{Bucket: "b", ObjectPath: "a"})
require.NoError(t, err)
assert.Equal(t, s3_lifecycle_pb.LifecycleDeleteOutcome_BLOCKED, respA.Outcome)
respB, err := f.LifecycleDelete(context.Background(), &s3_lifecycle_pb.LifecycleDeleteRequest{Bucket: "b", ObjectPath: "b"})
require.NoError(t, err)
assert.Equal(t, s3_lifecycle_pb.LifecycleDeleteOutcome_RETRY_LATER, respB.Outcome)
}
func TestFake_VersionIDPartOfKey(t *testing.T) {
// Two requests for the same bucket/objectPath but different
// versionIds must address different queues.
f := NewFakeLifecycleServer()
f.Queue("b", "k", "v1", SkippedObjectLock("v1-locked"))
f.Queue("b", "k", "v2", Done())
respV1, err := f.LifecycleDelete(context.Background(), &s3_lifecycle_pb.LifecycleDeleteRequest{Bucket: "b", ObjectPath: "k", VersionId: "v1"})
require.NoError(t, err)
respV2, err := f.LifecycleDelete(context.Background(), &s3_lifecycle_pb.LifecycleDeleteRequest{Bucket: "b", ObjectPath: "k", VersionId: "v2"})
require.NoError(t, err)
assert.Equal(t, s3_lifecycle_pb.LifecycleDeleteOutcome_SKIPPED_OBJECT_LOCK, respV1.Outcome)
assert.Equal(t, s3_lifecycle_pb.LifecycleDeleteOutcome_DONE, respV2.Outcome)
}
func TestFake_KeyComponentsWithDelimitersDoNotCollide(t *testing.T) {
// String-concatenation keys would have made these two requests
// indistinguishable. The struct key keeps them separate.
f := NewFakeLifecycleServer()
f.Queue("b/k", "", "", Blocked("variant-a"))
f.Queue("b", "k", "", Done())
respA, err := f.LifecycleDelete(context.Background(), &s3_lifecycle_pb.LifecycleDeleteRequest{Bucket: "b/k", ObjectPath: ""})
require.NoError(t, err)
respB, err := f.LifecycleDelete(context.Background(), &s3_lifecycle_pb.LifecycleDeleteRequest{Bucket: "b", ObjectPath: "k"})
require.NoError(t, err)
assert.Equal(t, s3_lifecycle_pb.LifecycleDeleteOutcome_BLOCKED, respA.Outcome)
assert.Equal(t, s3_lifecycle_pb.LifecycleDeleteOutcome_DONE, respB.Outcome)
}
func TestFake_ErrShortCircuitsBeforeRecording(t *testing.T) {
// Err makes LifecycleDelete return (nil, err) without recording the
// request — transport-error tests rely on the worker's own
// bookkeeping, not the fake's.
f := NewFakeLifecycleServer()
transportErr := errors.New("connection refused")
f.SetError(transportErr)
resp, err := f.LifecycleDelete(context.Background(), &s3_lifecycle_pb.LifecycleDeleteRequest{Bucket: "b", ObjectPath: "k"})
assert.Nil(t, resp)
assert.ErrorIs(t, err, transportErr)
assert.Empty(t, f.Recorded(), "transport-error calls must not be recorded")
// Clearing the error returns the server to normal behavior.
f.SetError(nil)
resp2, err2 := f.LifecycleDelete(context.Background(), &s3_lifecycle_pb.LifecycleDeleteRequest{Bucket: "b", ObjectPath: "k"})
require.NoError(t, err2)
require.NotNil(t, resp2)
assert.Len(t, f.Recorded(), 1)
}
func TestFake_RecordsRequestsInOrder(t *testing.T) {
// Recorded() preserves arrival order so tests can assert that
// dispatch happened in the expected sequence.
f := NewFakeLifecycleServer()
for _, key := range []string{"k1", "k2", "k3"} {
_, err := f.LifecycleDelete(context.Background(), &s3_lifecycle_pb.LifecycleDeleteRequest{
Bucket: "b", ObjectPath: key,
})
require.NoError(t, err)
}
rec := f.Recorded()
require.Len(t, rec, 3)
assert.Equal(t, "k1", rec[0].ObjectPath)
assert.Equal(t, "k2", rec[1].ObjectPath)
assert.Equal(t, "k3", rec[2].ObjectPath)
}
func TestFake_RecordedIsSnapshot(t *testing.T) {
// Mutating the slice the caller got back must not bleed into the
// fake's internal state — otherwise a flaky test could corrupt
// bookkeeping for later assertions.
f := NewFakeLifecycleServer()
_, err := f.LifecycleDelete(context.Background(), &s3_lifecycle_pb.LifecycleDeleteRequest{Bucket: "b", ObjectPath: "k"})
require.NoError(t, err)
snap := f.Recorded()
require.Len(t, snap, 1)
snap[0] = nil
again := f.Recorded()
require.Len(t, again, 1)
assert.NotNil(t, again[0], "internal record must survive caller-side mutation of the snapshot")
}
func TestFake_RecordedRequestsAreDeepCopies(t *testing.T) {
// A caller mutating fields on a Recorded() entry must not bleed
// into a later Recorded() snapshot. We also confirm the original
// request the caller passed in stays decoupled from internal state
// — proto.Clone runs at record time, so the caller's pointer is
// no longer the one the fake holds.
f := NewFakeLifecycleServer()
orig := &s3_lifecycle_pb.LifecycleDeleteRequest{Bucket: "b", ObjectPath: "k", VersionId: "v"}
_, err := f.LifecycleDelete(context.Background(), orig)
require.NoError(t, err)
snap := f.Recorded()
require.Len(t, snap, 1)
snap[0].Bucket = "mutated-by-caller"
snap[0].ObjectPath = "also-mutated"
again := f.Recorded()
require.Len(t, again, 1)
assert.Equal(t, "b", again[0].Bucket, "field mutations on a snapshot must not bleed back")
assert.Equal(t, "k", again[0].ObjectPath)
assert.Equal(t, "v", again[0].VersionId)
// The caller's own pointer is independent of the fake's record.
orig.Bucket = "caller-mutates-original"
yetAgain := f.Recorded()
assert.Equal(t, "b", yetAgain[0].Bucket, "caller mutating the input pointer must not bleed in either")
}
func TestFake_NilRequestUsesDefault(t *testing.T) {
// gRPC won't deliver a nil request in practice, but defensive code
// in the fake should still produce a deterministic response so a
// regressing client doesn't panic the test process.
f := NewFakeLifecycleServer()
f.SetDefault(Blocked("no request"))
resp, err := f.LifecycleDelete(context.Background(), nil)
require.NoError(t, err)
require.NotNil(t, resp)
assert.Equal(t, s3_lifecycle_pb.LifecycleDeleteOutcome_BLOCKED, resp.Outcome)
}
func TestFake_ConcurrentCallsSerializeWithoutDeadlock(t *testing.T) {
// The dispatcher fans dispatch across many goroutines; the fake
// must not livelock or drop records under concurrent load. Capture
// each goroutine's err so a regression in concurrent paths surfaces
// instead of being masked by length-only assertions.
f := NewFakeLifecycleServer()
const N = 64
var wg sync.WaitGroup
errCh := make(chan error, N)
wg.Add(N)
for i := 0; i < N; i++ {
go func() {
defer wg.Done()
_, err := f.LifecycleDelete(context.Background(), &s3_lifecycle_pb.LifecycleDeleteRequest{Bucket: "b", ObjectPath: "k"})
errCh <- err
}()
}
wg.Wait()
close(errCh)
for err := range errCh {
require.NoError(t, err)
}
assert.Len(t, f.Recorded(), N)
}
@@ -0,0 +1,162 @@
package reader
import (
"context"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// Layer 2 contracts the dispatcher pipeline relies on. These augment
// reader_test.go (extract + dispatch) and cursor_test.go (Advance +
// Freeze) by pinning the cursor composition surface that
// dispatcher.Pipeline depends on for resume-point selection,
// checkpoint persistence, and Run-time input validation.
func TestCursorMinTsNsWithFrozenKeysIncluded(t *testing.T) {
// MinTsNs is the resume point Reader.Run feeds to SubscribeMetadata
// when StartTsNs is zero. A freeze pins a key at its current TsNs;
// the min must still see that pinned position so the subscription
// doesn't rewind past it. Mixing frozen + non-frozen keys exercises
// the path where the smallest position belongs to a frozen key.
c := NewCursor()
frozenKey := key("a", s3lifecycle.ActionKindExpirationDays)
movingKey := key("b", s3lifecycle.ActionKindNoncurrentDays)
otherKey := key("c", s3lifecycle.ActionKindAbortMPU)
c.Advance(frozenKey, 100)
c.Advance(movingKey, 500)
c.Advance(otherKey, 300)
c.Freeze(frozenKey, 100)
// Frozen key holds at 100; Advance must not move it.
c.Advance(frozenKey, 9_999)
require.Equal(t, int64(100), c.Get(frozenKey))
// MinTsNs reflects the frozen key because it is still the smallest.
assert.Equal(t, int64(100), c.MinTsNs())
// Non-frozen keys keep advancing; min stays anchored to the freeze.
c.Advance(movingKey, 700)
c.Advance(otherKey, 600)
assert.Equal(t, int64(100), c.MinTsNs())
}
func TestCursorSnapshotIsDeepCopy(t *testing.T) {
// Snapshot is persisted via the persister; callers must be able to
// hold the returned map without observing live cursor mutations,
// and the cursor must not observe caller-side edits to the map.
c := NewCursor()
a := key("a", s3lifecycle.ActionKindExpirationDays)
b := key("b", s3lifecycle.ActionKindNoncurrentDays)
c.Advance(a, 100)
c.Advance(b, 200)
snap := c.Snapshot()
require.Equal(t, int64(100), snap[a])
require.Equal(t, int64(200), snap[b])
// Mutating the returned map must not bleed into the cursor.
snap[a] = 9_999
delete(snap, b)
snap[key("z", s3lifecycle.ActionKindAbortMPU)] = 42
assert.Equal(t, int64(100), c.Get(a), "cursor must be insulated from snapshot writes")
assert.Equal(t, int64(200), c.Get(b), "cursor must retain key the caller deleted from snapshot")
assert.Equal(t, int64(0), c.Get(key("z", s3lifecycle.ActionKindAbortMPU)), "cursor must not see keys added to snapshot")
// Mutating the cursor after Snapshot must not bleed into the map
// the caller is still holding (e.g., between Snapshot and Save).
snap2 := c.Snapshot()
c.Advance(a, 1_000)
c.Advance(key("d", s3lifecycle.ActionKindAbortMPU), 50)
assert.Equal(t, int64(100), snap2[a], "snapshot must not see post-snapshot Advance")
_, hasNew := snap2[key("d", s3lifecycle.ActionKindAbortMPU)]
assert.False(t, hasNew, "snapshot must not see post-snapshot key insertions")
}
func TestCursorRestoreReplacesNotMerges(t *testing.T) {
// On startup the persister loads the last checkpoint and Restores
// the cursor. A subsequent Restore (e.g., after a re-bootstrap)
// must fully replace the in-memory map: keys present before but
// absent in the new map must vanish, otherwise stale resume
// points would survive across restores.
c := NewCursor()
a := key("a", s3lifecycle.ActionKindExpirationDays)
b := key("b", s3lifecycle.ActionKindNoncurrentDays)
cc := key("c", s3lifecycle.ActionKindAbortMPU)
c.Restore(map[s3lifecycle.ActionKey]int64{a: 100, b: 200, cc: 300})
require.Equal(t, int64(100), c.Get(a))
require.Equal(t, int64(200), c.Get(b))
require.Equal(t, int64(300), c.Get(cc))
// Freeze a key before second Restore; Restore must clear frozen state
// alongside the value map so a stale freeze doesn't survive a reload.
c.Freeze(a, 100)
require.True(t, c.IsFrozen(a))
// Second Restore drops keys b and c entirely; a is replaced.
c.Restore(map[s3lifecycle.ActionKey]int64{a: 50})
assert.Equal(t, int64(50), c.Get(a))
assert.False(t, c.IsFrozen(a), "Restore must clear frozen state")
assert.Equal(t, int64(0), c.Get(b), "key absent from second Restore must be removed")
assert.Equal(t, int64(0), c.Get(cc), "key absent from second Restore must be removed")
// MinTsNs reflects only the surviving key.
assert.Equal(t, int64(50), c.MinTsNs())
// Restoring an empty map clears all state.
c.Restore(map[s3lifecycle.ActionKey]int64{})
assert.Equal(t, int64(0), c.Get(a))
assert.Equal(t, int64(0), c.MinTsNs())
}
func TestReaderRunValidatesInputsBeforeSubscribing(t *testing.T) {
// Run guards: out-of-range ShardID (no predicate), nil Events
// channel, empty BucketsPath. Each error path must fire before any
// client call, so a nil client suffices to drive the assertions.
out := make(chan *Event, 1)
cases := []struct {
name string
reader *Reader
wantSub string
}{
{
name: "shard id below zero",
reader: &Reader{ShardID: -1, BucketsPath: "/buckets", Events: out},
wantSub: "shard_id",
},
{
name: "shard id at or above ShardCount",
reader: &Reader{ShardID: s3lifecycle.ShardCount, BucketsPath: "/buckets", Events: out},
wantSub: "shard_id",
},
{
name: "nil events channel",
reader: &Reader{ShardID: 0, BucketsPath: "/buckets", Events: nil},
wantSub: "nil Events",
},
{
name: "empty buckets path",
reader: &Reader{ShardID: 0, BucketsPath: "", Events: out},
wantSub: "empty BucketsPath",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
// Bound the call so a regression that lets Run reach the
// nil client's blocking subscribe surfaces as a test failure
// instead of hanging the suite.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
err := tc.reader.Run(ctx, nil, "test", 0)
require.Error(t, err)
assert.Contains(t, err.Error(), tc.wantSub)
})
}
}
@@ -0,0 +1,47 @@
package reader
import (
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/stretchr/testify/assert"
)
// IsCreate / IsDelete are the small but routing-critical predicates
// the dispatcher uses to decide which match path applies. Both were
// previously exercised only through end-to-end Tick/Match tests; pin
// them directly here.
func TestEventIsCreate_PopulatedNewEntryNoOldEntry(t *testing.T) {
e := &Event{NewEntry: &filer_pb.Entry{Name: "k"}}
assert.True(t, e.IsCreate())
assert.False(t, e.IsDelete())
}
func TestEventIsDelete_PopulatedOldEntryNoNewEntry(t *testing.T) {
e := &Event{OldEntry: &filer_pb.Entry{Name: "k"}}
assert.True(t, e.IsDelete())
assert.False(t, e.IsCreate())
}
func TestEventBothEntries_NeitherCreateNorDelete(t *testing.T) {
// An update event carries both old and new; the predicates are
// strict (one or the other, not both) so the router can route
// updates through the dedicated path rather than treating them
// as creates or deletes.
e := &Event{
OldEntry: &filer_pb.Entry{Name: "k"},
NewEntry: &filer_pb.Entry{Name: "k"},
}
assert.False(t, e.IsCreate(), "update event must not classify as create")
assert.False(t, e.IsDelete(), "update event must not classify as delete")
}
func TestEventNoEntries_NeitherCreateNorDelete(t *testing.T) {
// A degenerate event with neither side populated must not classify
// as either; otherwise a metadata-only filer event with no bucket
// payload could trigger spurious dispatches.
e := &Event{}
assert.False(t, e.IsCreate())
assert.False(t, e.IsDelete())
}
@@ -0,0 +1,44 @@
package reader
import (
"testing"
)
// LogStartup writes a single glog line summarising the reader's
// resume position; the only behavioral output is a side effect on the
// log sink, but exercising both branches still pins compile-time
// shape (e.g. that ShardPredicate-set readers don't trip on a missing
// ShardID and vice versa) and lets coverage actually visit the code.
func TestLogStartup_ShardIDOnly(t *testing.T) {
// Single-shard configuration: ShardID is set, ShardPredicate is nil,
// no Cursor, no StartTsNs. The function must run without panic.
r := &Reader{ShardID: 7, EventBudget: 100}
r.LogStartup()
}
func TestLogStartup_ShardPredicate(t *testing.T) {
// ShardPredicate-set readers take a different log branch; pinning
// the call here catches a regression that returns or panics.
r := &Reader{
ShardPredicate: func(int) bool { return true },
EventBudget: 100,
}
r.LogStartup()
}
func TestLogStartup_StartTsNsOverridesCursor(t *testing.T) {
// Explicit StartTsNs takes precedence over Cursor.MinTsNs; this
// branch is otherwise only hit when a worker is replaying a
// specific position. Run it through to make sure the override is
// honored without consulting the Cursor.
r := &Reader{ShardID: 0, StartTsNs: 1700000000_000_000_000, Cursor: NewCursor()}
r.LogStartup()
}
func TestLogStartup_CursorMinFallback(t *testing.T) {
// StartTsNs=0 with a non-nil Cursor falls back to Cursor.MinTsNs.
c := NewCursor()
r := &Reader{ShardID: 0, Cursor: c}
r.LogStartup()
}
@@ -0,0 +1,161 @@
package reader
import (
"context"
"sync"
"testing"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// InMemoryPersister is the in-memory test double other lifecycle tests
// rely on for cursor checkpointing. The deep-copy contract documented
// on the Persister interface is what insulates each test's state from
// the others — these tests pin every direction of that contract so a
// regression here can't silently corrupt downstream tests.
func TestInMemoryPersister_LoadOnUnknownShardReturnsEmptyMap(t *testing.T) {
// Contract: Load returns an empty map (not an error) when no prior
// state exists. The dispatcher startup path relies on this so a
// fresh worker doesn't have to special-case the "no checkpoint yet"
// branch.
p := NewInMemoryPersister()
got, err := p.Load(context.Background(), 0)
require.NoError(t, err)
assert.NotNil(t, got)
assert.Empty(t, got)
}
func TestInMemoryPersister_SaveLoadRoundTrip(t *testing.T) {
p := NewInMemoryPersister()
want := map[s3lifecycle.ActionKey]int64{
key("a", s3lifecycle.ActionKindExpirationDays): 100,
key("b", s3lifecycle.ActionKindNoncurrentDays): 200,
}
require.NoError(t, p.Save(context.Background(), 7, want))
got, err := p.Load(context.Background(), 7)
require.NoError(t, err)
assert.Equal(t, want, got)
}
func TestInMemoryPersister_SaveCopiesInput(t *testing.T) {
// Caller mutating the map after Save must not bleed into stored
// state — the next Load must return what was saved.
p := NewInMemoryPersister()
in := map[s3lifecycle.ActionKey]int64{
key("a", s3lifecycle.ActionKindExpirationDays): 100,
}
require.NoError(t, p.Save(context.Background(), 0, in))
in[key("a", s3lifecycle.ActionKindExpirationDays)] = 9_999
in[key("z", s3lifecycle.ActionKindAbortMPU)] = 42
delete(in, key("a", s3lifecycle.ActionKindExpirationDays))
got, err := p.Load(context.Background(), 0)
require.NoError(t, err)
assert.Equal(t, int64(100), got[key("a", s3lifecycle.ActionKindExpirationDays)],
"caller-side mutation must not bleed into stored state")
assert.NotContains(t, got, key("z", s3lifecycle.ActionKindAbortMPU),
"caller-side insertion must not bleed into stored state")
}
func TestInMemoryPersister_LoadReturnsACopy(t *testing.T) {
// Caller mutating the returned map must not bleed back; otherwise
// a test reusing the persister across cases could see drift.
p := NewInMemoryPersister()
want := map[s3lifecycle.ActionKey]int64{
key("a", s3lifecycle.ActionKindExpirationDays): 100,
}
require.NoError(t, p.Save(context.Background(), 0, want))
first, err := p.Load(context.Background(), 0)
require.NoError(t, err)
first[key("a", s3lifecycle.ActionKindExpirationDays)] = 9_999
first[key("z", s3lifecycle.ActionKindAbortMPU)] = 42
second, err := p.Load(context.Background(), 0)
require.NoError(t, err)
assert.Equal(t, int64(100), second[key("a", s3lifecycle.ActionKindExpirationDays)],
"caller-side mutation of the first snapshot must not bleed back")
assert.NotContains(t, second, key("z", s3lifecycle.ActionKindAbortMPU),
"caller-side insertion into the first snapshot must not bleed back")
}
func TestInMemoryPersister_SaveReplacesNotMerges(t *testing.T) {
// Documented contract: Save replaces prior state atomically. A
// merge would silently keep stale resume points across restarts.
p := NewInMemoryPersister()
require.NoError(t, p.Save(context.Background(), 0, map[s3lifecycle.ActionKey]int64{
key("a", s3lifecycle.ActionKindExpirationDays): 100,
key("b", s3lifecycle.ActionKindNoncurrentDays): 200,
}))
require.NoError(t, p.Save(context.Background(), 0, map[s3lifecycle.ActionKey]int64{
key("c", s3lifecycle.ActionKindAbortMPU): 300,
}))
got, err := p.Load(context.Background(), 0)
require.NoError(t, err)
assert.Equal(t, map[s3lifecycle.ActionKey]int64{
key("c", s3lifecycle.ActionKindAbortMPU): 300,
}, got, "second Save must replace prior state, not merge")
}
func TestInMemoryPersister_DifferentShardsIsolated(t *testing.T) {
// State for shardID=1 must not leak into Load(shardID=2).
p := NewInMemoryPersister()
require.NoError(t, p.Save(context.Background(), 1, map[s3lifecycle.ActionKey]int64{
key("a", s3lifecycle.ActionKindExpirationDays): 100,
}))
require.NoError(t, p.Save(context.Background(), 2, map[s3lifecycle.ActionKey]int64{
key("b", s3lifecycle.ActionKindNoncurrentDays): 200,
}))
got1, err := p.Load(context.Background(), 1)
require.NoError(t, err)
got2, err := p.Load(context.Background(), 2)
require.NoError(t, err)
assert.Equal(t, int64(100), got1[key("a", s3lifecycle.ActionKindExpirationDays)])
assert.NotContains(t, got1, key("b", s3lifecycle.ActionKindNoncurrentDays))
assert.Equal(t, int64(200), got2[key("b", s3lifecycle.ActionKindNoncurrentDays)])
assert.NotContains(t, got2, key("a", s3lifecycle.ActionKindExpirationDays))
}
func TestInMemoryPersister_SaveEmptyMapClearsState(t *testing.T) {
// An empty map is valid input; Save must accept it and a subsequent
// Load must return an empty map (not the prior contents).
p := NewInMemoryPersister()
require.NoError(t, p.Save(context.Background(), 0, map[s3lifecycle.ActionKey]int64{
key("a", s3lifecycle.ActionKindExpirationDays): 100,
}))
require.NoError(t, p.Save(context.Background(), 0, map[s3lifecycle.ActionKey]int64{}))
got, err := p.Load(context.Background(), 0)
require.NoError(t, err)
assert.Empty(t, got)
}
func TestInMemoryPersister_ConcurrentSaveLoadDoesNotRace(t *testing.T) {
// The dispatcher fans cursor reads/writes across many goroutines;
// the persister must hold under load without livelocking or
// data-racing (-race detector enforces that).
p := NewInMemoryPersister()
var wg sync.WaitGroup
const N = 64
wg.Add(N * 2)
for i := 0; i < N; i++ {
i := i
go func() {
defer wg.Done()
_ = p.Save(context.Background(), i%4, map[s3lifecycle.ActionKey]int64{
key("k", s3lifecycle.ActionKindExpirationDays): int64(i),
})
}()
go func() {
defer wg.Done()
_, _ = p.Load(context.Background(), i%4)
}()
}
wg.Wait()
}
+30 -7
View File
@@ -6,6 +6,7 @@ import (
"fmt"
"io"
"strings"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
@@ -13,14 +14,36 @@ import (
)
// Event is one in-shard meta-log event delivered to the router.
//
// BootstrapVersion is set only by the bucket bootstrapper when it
// expands a .versions/ directory; the meta-log path leaves it nil.
// Carries pre-computed sibling state so the router can fire
// NoncurrentDays / NewerNoncurrent without listing again.
type Event struct {
TsNs int64
Bucket string
Key string
ShardID int
OldEntry *filer_pb.Entry
NewEntry *filer_pb.Entry
NewParent string
TsNs int64
Bucket string
Key string
ShardID int
OldEntry *filer_pb.Entry
NewEntry *filer_pb.Entry
NewParent string
BootstrapVersion *BootstrapVersion
}
// BootstrapVersion is the per-version state computed once per
// .versions/<key>/ directory at bootstrap time. Key fields shape
// EvaluateAction: IsLatest gates current vs. noncurrent rules,
// NoncurrentIndex gates NewerNoncurrentVersions retention,
// SuccessorModTime sets the noncurrent clock (when this version was
// replaced).
type BootstrapVersion struct {
LogicalKey string
VersionID string
IsLatest bool
IsDeleteMarker bool
NumVersions int
NoncurrentIndex int // 0 = newest noncurrent
SuccessorModTime time.Time
}
// IsDelete reports whether this event removes an entry.
@@ -0,0 +1,335 @@
package router
import (
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/engine"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// Direct coverage for the pure helpers in router.go that the larger
// Route* tests exercise indirectly. Pinning each one separately catches
// regressions before they manifest as a broader Route failure that's
// harder to diagnose.
// ---------- successorModTimeFromContainer ----------
func TestSuccessorModTimeFromContainer_MissingExtReturnsZero(t *testing.T) {
assert.True(t, successorModTimeFromContainer(&filer_pb.Entry{}).IsZero())
assert.True(t, successorModTimeFromContainer(&filer_pb.Entry{
Extended: map[string][]byte{},
}).IsZero())
}
func TestSuccessorModTimeFromContainer_EmptyValueReturnsZero(t *testing.T) {
got := successorModTimeFromContainer(&filer_pb.Entry{
Extended: map[string][]byte{s3_constants.ExtLatestVersionMtimeKey: nil},
})
assert.True(t, got.IsZero())
}
func TestSuccessorModTimeFromContainer_NonNumericReturnsZero(t *testing.T) {
// A malformed value is the writer's bug; the helper must not
// propagate a parse error or surface a nonsense time.
got := successorModTimeFromContainer(&filer_pb.Entry{
Extended: map[string][]byte{s3_constants.ExtLatestVersionMtimeKey: []byte("not-a-number")},
})
assert.True(t, got.IsZero())
}
func TestSuccessorModTimeFromContainer_NonPositiveReturnsZero(t *testing.T) {
// The container ext stores Unix seconds; <=0 means "not set" so
// the helper falls back to zero rather than emitting 1970-01-01.
for _, raw := range []string{"0", "-1", "-1000"} {
t.Run(raw, func(t *testing.T) {
got := successorModTimeFromContainer(&filer_pb.Entry{
Extended: map[string][]byte{s3_constants.ExtLatestVersionMtimeKey: []byte(raw)},
})
assert.True(t, got.IsZero(), "value %q must produce zero time", raw)
})
}
}
func TestSuccessorModTimeFromContainer_PositiveSecondsRoundTrip(t *testing.T) {
got := successorModTimeFromContainer(&filer_pb.Entry{
Extended: map[string][]byte{s3_constants.ExtLatestVersionMtimeKey: []byte("1700000000")},
})
assert.Equal(t, time.Unix(1700000000, 0).UTC(), got.UTC())
}
// ---------- logicalKeyFromVersionPath ----------
func TestLogicalKeyFromVersionPath_ExtractsLogicalKey(t *testing.T) {
logical, ok := logicalKeyFromVersionPath("a/b/c.versions/v_abc")
require.True(t, ok)
assert.Equal(t, "a/b/c", logical)
}
func TestLogicalKeyFromVersionPath_RejectsPathWithoutVersionsParent(t *testing.T) {
// The parent of the version file must end with .versions; otherwise
// it's not a version path.
_, ok := logicalKeyFromVersionPath("a/b/c/v_abc")
assert.False(t, ok)
}
func TestLogicalKeyFromVersionPath_RejectsRootLevelPath(t *testing.T) {
// LastIndex returning 0 means the only "/" is at index 0, which
// would yield an empty parent — not a real version path.
_, ok := logicalKeyFromVersionPath("/v_abc")
assert.False(t, ok)
}
func TestLogicalKeyFromVersionPath_RejectsNoSlashes(t *testing.T) {
_, ok := logicalKeyFromVersionPath("v_abc")
assert.False(t, ok)
_, ok = logicalKeyFromVersionPath("")
assert.False(t, ok)
}
func TestLogicalKeyFromVersionPath_RejectsBareVersionsContainer(t *testing.T) {
// A path that's only the .versions container has no version-file
// child to extract a logical key from.
_, ok := logicalKeyFromVersionPath(s3_constants.VersionsFolder + "/v_x")
assert.False(t, ok, "logical key cannot be empty after trim")
}
// ---------- isVersionsContainerKey ----------
func TestIsVersionsContainerKey(t *testing.T) {
cases := []struct {
key string
want bool
}{
{"obj" + s3_constants.VersionsFolder, true},
{"a/b/obj" + s3_constants.VersionsFolder, true},
// Bucket-root .versions is rejected explicitly: it has no
// logical object key, so the router can't process it.
{s3_constants.VersionsFolder, false},
{"obj.versions/v_x", false}, // the version file inside, not the container
{"obj", false},
{"", false},
}
for _, c := range cases {
t.Run(c.key, func(t *testing.T) {
assert.Equal(t, c.want, isVersionsContainerKey(c.key))
})
}
}
// ---------- isVersionFolderPath ----------
func TestIsVersionFolderPath(t *testing.T) {
// Reports whether a key sits inside a .versions/ folder, looking at
// the parent segment specifically. The router uses this to skip
// version-file events that need sibling state to classify.
cases := []struct {
key string
want bool
}{
{"obj.versions/v_aaa", true},
{"a/b/obj.versions/v_aaa", true},
{"obj/v_aaa", false}, // parent isn't .versions
{"obj.versions", false}, // the container itself, not a child
// "obj.versions/" reads as the trailing-slash form of the path
// "obj.versions" → leaf is "obj.versions" which ends with the
// suffix → true. The router never sees this shape from the
// reader (events carry concrete leaf names), but pin it here so
// the contract is documented.
{"obj.versions/", true},
{"v_aaa", false}, // no slash at all
{"", false},
}
for _, c := range cases {
t.Run(c.key, func(t *testing.T) {
assert.Equal(t, c.want, isVersionFolderPath(c.key))
})
}
}
// ---------- isDeleteMarkerEntry ----------
func TestIsDeleteMarkerEntry_NilOrEmptyExtendedReturnsFalse(t *testing.T) {
assert.False(t, isDeleteMarkerEntry(nil))
assert.False(t, isDeleteMarkerEntry(&filer_pb.Entry{}))
assert.False(t, isDeleteMarkerEntry(&filer_pb.Entry{Extended: map[string][]byte{}}))
}
func TestIsDeleteMarkerEntry_TrueOnlyForLiteralTrue(t *testing.T) {
// The marker key must be exactly "true"; any other value is not a
// marker. Pinning catches a regression that does case-insensitive
// matching or treats "1" as truthy.
mk := func(val string) *filer_pb.Entry {
return &filer_pb.Entry{Extended: map[string][]byte{s3_constants.ExtDeleteMarkerKey: []byte(val)}}
}
assert.True(t, isDeleteMarkerEntry(mk("true")))
assert.False(t, isDeleteMarkerEntry(mk("True")))
assert.False(t, isDeleteMarkerEntry(mk("TRUE")))
assert.False(t, isDeleteMarkerEntry(mk("1")))
assert.False(t, isDeleteMarkerEntry(mk("")))
assert.False(t, isDeleteMarkerEntry(mk("false")))
}
// ---------- extractTags ----------
func TestExtractTags_NilOrEmptyReturnsNil(t *testing.T) {
assert.Nil(t, extractTags(nil))
assert.Nil(t, extractTags(map[string][]byte{}))
}
func TestExtractTags_OnlyKeysWithObjectTaggingPrefix(t *testing.T) {
// extractTags returns ExtVersionIdKey, Mime, etc. → no.
// It only picks up keys with the AmzObjectTagging prefix and strips
// that prefix to produce the tag map.
prefix := s3_constants.AmzObjectTagging + "-"
ext := map[string][]byte{
prefix + "env": []byte("prod"),
prefix + "team": []byte("data"),
"X-Amz-Other": []byte("ignored"),
"Seaweed-X-Internal": []byte("ignored"),
}
got := extractTags(ext)
require.Len(t, got, 2)
assert.Equal(t, "prod", got["env"])
assert.Equal(t, "data", got["team"])
}
func TestExtractTags_ReturnsNilWhenNoTaggingPrefixedKeys(t *testing.T) {
// Keys with no tagging prefix produce a nil map (not an empty map);
// the router treats nil as "no tags" without an extra branch.
ext := map[string][]byte{
"X-Amz-Other": []byte("ignored"),
"Seaweed-X-Internal": []byte("ignored"),
}
got := extractTags(ext)
assert.Nil(t, got)
}
// ---------- hasActiveEventDrivenAction ----------
func TestHasActiveEventDrivenAction(t *testing.T) {
// Build a snapshot with two action kinds and one of them set to
// scan-only (inactive in event-driven view). hasActiveEventDrivenAction
// must answer true only for the active event-driven kind.
rule := &s3lifecycle.Rule{
ID: "r",
Status: s3lifecycle.StatusEnabled,
ExpirationDays: 7,
AbortMPUDaysAfterInitiation: 3,
}
hash := s3lifecycle.RuleHash(rule)
expirationKey := s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: s3lifecycle.ActionKindExpirationDays}
abortKey := s3lifecycle.ActionKey{Bucket: "bk", RuleHash: hash, ActionKind: s3lifecycle.ActionKindAbortMPU}
prior := map[s3lifecycle.ActionKey]engine.PriorState{
expirationKey: {BootstrapComplete: true, Mode: engine.ModeEventDriven},
abortKey: {BootstrapComplete: true, Mode: engine.ModeScanOnly},
}
snap := engine.New().Compile(
[]engine.CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
engine.CompileOptions{PriorStates: prior},
)
keys := []s3lifecycle.ActionKey{expirationKey, abortKey}
// Active event-driven kind matches.
assert.True(t, hasActiveEventDrivenAction(snap, keys, s3lifecycle.ActionKindExpirationDays))
// Scan-only kind does NOT match — operator promoted it to scan-only
// and the router must respect that by skipping the event-driven path.
assert.False(t, hasActiveEventDrivenAction(snap, keys, s3lifecycle.ActionKindAbortMPU))
// A kind not in the keys list is false.
assert.False(t, hasActiveEventDrivenAction(snap, keys, s3lifecycle.ActionKindNoncurrentDays))
}
func TestHasActiveEventDrivenAction_NilActionSkipped(t *testing.T) {
// A key the snapshot doesn't know about returns nil from Action;
// the helper must skip rather than panic.
snap := engine.New().Compile(nil, engine.CompileOptions{})
keys := []s3lifecycle.ActionKey{
{Bucket: "ghost", ActionKind: s3lifecycle.ActionKindExpirationDays},
}
assert.False(t, hasActiveEventDrivenAction(snap, keys, s3lifecycle.ActionKindExpirationDays))
}
// ---------- engine.Snapshot accessors ----------
func TestSnapshot_BucketVersionedReportsCompiledFlag(t *testing.T) {
rule := &s3lifecycle.Rule{ID: "r", Status: s3lifecycle.StatusEnabled, ExpirationDays: 7}
snap := engine.New().Compile(
[]engine.CompileInput{
{Bucket: "vbk", Rules: []*s3lifecycle.Rule{rule}, Versioned: true},
{Bucket: "ubk", Rules: []*s3lifecycle.Rule{rule}, Versioned: false},
},
engine.CompileOptions{},
)
assert.True(t, snap.BucketVersioned("vbk"))
assert.False(t, snap.BucketVersioned("ubk"))
// Unknown bucket: not versioned, not a panic.
assert.False(t, snap.BucketVersioned("missing"))
}
func TestSnapshot_BucketActionKeysReturnsCompiledList(t *testing.T) {
// Every CompileInput rule emits one action key per RuleActionKind;
// BucketActionKeys must surface them all (regardless of Mode) so
// MatchPath can iterate.
rule := &s3lifecycle.Rule{ID: "r", Status: s3lifecycle.StatusEnabled, ExpirationDays: 7}
snap := engine.New().Compile(
[]engine.CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
engine.CompileOptions{},
)
keys := snap.BucketActionKeys("bk")
require.NotEmpty(t, keys)
for _, k := range keys {
assert.Equal(t, "bk", k.Bucket)
}
}
func TestSnapshot_BucketActionKeysUnknownBucketReturnsNil(t *testing.T) {
snap := engine.New().Compile(nil, engine.CompileOptions{})
assert.Nil(t, snap.BucketActionKeys("missing"))
}
func TestSnapshot_ActionUnknownKeyReturnsNil(t *testing.T) {
snap := engine.New().Compile(nil, engine.CompileOptions{})
got := snap.Action(s3lifecycle.ActionKey{Bucket: "ghost", ActionKind: s3lifecycle.ActionKindExpirationDays})
assert.Nil(t, got)
}
func TestSnapshot_AllActionsCoversEveryCompiledKind(t *testing.T) {
// AllActions must enumerate every compiled action regardless of
// active state, because the dispatcher uses it for full-snapshot
// reporting.
rule := &s3lifecycle.Rule{
ID: "r",
Status: s3lifecycle.StatusEnabled,
ExpirationDays: 7,
AbortMPUDaysAfterInitiation: 3,
}
snap := engine.New().Compile(
[]engine.CompileInput{{Bucket: "bk", Rules: []*s3lifecycle.Rule{rule}}},
engine.CompileOptions{},
)
all := snap.AllActions()
wantKinds := s3lifecycle.RuleActionKinds(rule)
require.Len(t, all, len(wantKinds))
seen := map[s3lifecycle.ActionKind]bool{}
for _, a := range all {
seen[a.Key.ActionKind] = true
}
for _, k := range wantKinds {
assert.True(t, seen[k], "missing kind %v in AllActions", k)
}
}
func TestSnapshot_SnapshotIDIsMonotonicAcrossRecompiles(t *testing.T) {
// Every Compile call advances snapshotIDSeq; pin that successive
// snapshots from the same Engine carry strictly increasing IDs so
// the dispatcher's stale-snapshot check works.
e := engine.New()
first := e.Compile(nil, engine.CompileOptions{})
second := e.Compile(nil, engine.CompileOptions{})
assert.Greater(t, second.SnapshotID(), first.SnapshotID(),
"second compile must produce a strictly greater snapshot id")
}
+641 -57
View File
@@ -1,9 +1,13 @@
package router
import (
"context"
"sort"
"strconv"
"strings"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
@@ -11,6 +15,34 @@ import (
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/reader"
)
// SiblingLister inspects the surviving versions of a versioned key.
// nil receiver or an error means "unknown" — callers suppress. Four
// queries: Survivors paginates the .versions/ container plus the bare
// null version (used by sole-survivor and bootstrap); LookupVersion
// fetches a single version file by id (used by pointer-transition
// routing to read the displaced version's identity and mtime);
// ListVersions paginates every version file in the .versions/
// container (used to compute NoncurrentIndex when a NewerNoncurrent
// rule is active); LookupNullVersion returns the bare-key entry that
// represents the null version (used by pointer-transition routing
// when oldID is empty and to include the null in expansion ranks).
type SiblingLister interface {
Survivors(ctx context.Context, bucket, objectKey string) (Survivors, error)
LookupVersion(ctx context.Context, bucket, objectKey, versionID string) (*filer_pb.Entry, error)
ListVersions(ctx context.Context, bucket, objectKey string) ([]*filer_pb.Entry, error)
LookupNullVersion(ctx context.Context, bucket, objectKey string) (entry *filer_pb.Entry, explicit bool, err error)
}
// Survivors describes the state under .versions/<key>/ plus the bare
// null-version that exists when versioning was turned on after the
// object was first PUT (s3api_object_versioning.go treats <bucket>/<key>
// as a regular file, the null version, in that case).
type Survivors struct {
Count int // entries under .versions/<key>/, capped at 2
LoneEntry *filer_pb.Entry // populated when Count == 1
HasNullVersion bool // bare <bucket>/<key> exists as a regular file
}
// Match is one (event, action) pair where EvaluateAction fired. The
// dispatcher runs `LifecycleDelete` at DueTime; identity-CAS in the RPC
// guards against drift between schedule time and dispatch time.
@@ -42,26 +74,52 @@ type EntryIdentity struct {
ExtendedHash []byte
}
// Route returns the matches that fire for ev against snap. Only EVENT_DRIVEN
// actions on this bucket are considered; actions in SCAN_AT_DATE or DISABLED
// modes are out-of-band of the event stream. Inactive actions
// (BootstrapComplete=false) are also skipped.
func Route(snap *engine.Snapshot, ev *reader.Event, now time.Time) []Match {
// Route returns the matches that fire for ev against snap. Only active
// event-driven actions are considered; SCAN_AT_DATE and DISABLED bypass
// this path.
func Route(ctx context.Context, snap *engine.Snapshot, ev *reader.Event, now time.Time, lister SiblingLister) []Match {
if snap == nil || ev == nil {
return nil
}
// Hard deletes carry no schedule-relevant state: an Expiration would
// hit NOOP_RESOLVED at dispatch time anyway, ExpiredObjectDeleteMarker
// only fires on the latest-version delete-marker which is a Create
// from the server's perspective. Skip rather than burn a schedule slot.
if ev.NewEntry == nil {
return nil
}
keys := snap.BucketActionKeys(ev.Bucket)
if len(keys) == 0 {
return nil
}
info := buildObjectInfo(ev, snap.BucketVersioned(ev.Bucket))
// Bootstrap-expanded version event: sibling state is pre-computed,
// info.Key is the LOGICAL key so rule prefixes match. Skip the
// meta-log path's version-folder skip.
if ev.BootstrapVersion != nil {
return routeBootstrapVersion(snap, ev, keys)
}
versioned := snap.BucketVersioned(ev.Bucket)
// .versions/ directory metadata update: when ExtLatestVersionIdKey
// changes, the OLD pointer value names a version that's now
// noncurrent. Route NoncurrentDays / NewerNoncurrent for it without
// waiting for the next bootstrap.
if versioned && ev.NewEntry != nil && ev.OldEntry != nil && ev.NewEntry.IsDirectory && isVersionsContainerKey(ev.Key) {
if !hasActiveEventDrivenAction(snap, keys, s3lifecycle.ActionKindNoncurrentDays) &&
!hasActiveEventDrivenAction(snap, keys, s3lifecycle.ActionKindNewerNoncurrent) {
return nil
}
return routePointerTransition(ctx, snap, ev, keys, lister)
}
// EXP_DM can fire on two version-folder events: the marker create
// (sole survivor immediately) and a noncurrent hard-delete that
// leaves only the marker behind. Both reach routeSoleSurvivorMarker.
if versioned && isVersionFolderPath(ev.Key) {
if !hasActiveEventDrivenAction(snap, keys, s3lifecycle.ActionKindExpiredDeleteMarker) {
return nil
}
return routeSoleSurvivorMarker(ctx, snap, ev, keys, lister)
}
if ev.NewEntry == nil {
return nil
}
info := buildObjectInfo(ev, versioned)
if info == nil {
return nil
}
@@ -87,13 +145,18 @@ func Route(snap *engine.Snapshot, ev *reader.Event, now time.Time) []Match {
if !info.IsMPUInit && key.ActionKind == s3lifecycle.ActionKindAbortMPU {
continue
}
// Schedule from ModTime, not the meta-log event time: a backdated
// or out-of-band entry update has eventTime ≈ now but ModTime far
// in the past, so eventTime+Delay would push the dispatch into the
// future even though the rule fires immediately. ModTime+Delay is
// the correct fire moment; the dispatcher's identity-CAS catches
// drift if the object changes meanwhile.
dueTime := info.ModTime.Add(action.Delay)
// Schedule from the per-kind due moment. ExpirationDate is
// rule-relative (the date IS the moment); other kinds are
// ModTime-relative. Using ModTime+Delay for ExpirationDate
// (Delay=0) puts dueTime at the entry's mtime — a backdated
// object's mtime is BEFORE the rule's date, so the eligibility
// check below would skip it. ComputeDueAt encapsulates both
// shapes; the dispatcher's identity-CAS catches drift if the
// object changes meanwhile.
dueTime := s3lifecycle.ComputeDueAt(action.Rule, key.ActionKind, info)
if dueTime.IsZero() {
continue
}
res := s3lifecycle.EvaluateAction(action.Rule, key.ActionKind, info, dueTime)
if res.Action == s3lifecycle.ActionNone {
continue
@@ -112,42 +175,540 @@ func Route(snap *engine.Snapshot, ev *reader.Event, now time.Time) []Match {
return matches
}
// buildObjectInfo derives an ObjectInfo from a meta-log event and the
// bucket's versioning state. Returns nil when the event has no usable
// shape (missing attributes, hard delete already handled upstream).
// routePointerTransition handles a .versions/ container update where
// ExtLatestVersionIdKey changed: the OLD pointer value names a version
// that just became noncurrent. Two lookup shapes:
//
// On a versioned bucket the storage layout (<key>.versions/v_<id>) is
// shared between the current latest and the noncurrent versions; the
// latest pointer lives in the .versions/ directory's Extended map and
// is updated separately. Without that pointer-transition signal here,
// the router conservatively classifies every event as if it were the
// current version (IsLatest=true) so it never deletes the live
// latest; bootstrap walking + the server-side dispatch guard handle
// noncurrent retention. NumVersions=0 keeps ExpiredObjectDeleteMarker
// (which requires sole-survivor) suppressed.
// - Pure NoncurrentVersionExpirationDays without NewerNoncurrentVersions:
// a single LookupVersion of oldID is enough — the displaced version
// is the only one that newly entered eligibility for this rule.
//
// MPU init directories at .uploads/<upload_id> populate IsMPUInit and
// use the destination object key from the entry's Extended map for
// filter matching, so a rule with Filter.Prefix=foo/ matches an MPU
// uploading to foo/bar.txt.
// - Any active NewerNoncurrentVersions rule: a pointer flip shifts
// every prior noncurrent's rank by one, so the version that *just
// crossed* the keep-count threshold needs evaluation too. List the
// full .versions/ container, rank newest-first, and route every
// eligible noncurrent. Identity-CAS handles dedup with earlier
// schedules.
//
// Without this branch the worker has to wait for the next bootstrap to
// schedule retention on a freshly-noncurrent version.
func routePointerTransition(ctx context.Context, snap *engine.Snapshot, ev *reader.Event, keys []s3lifecycle.ActionKey, lister SiblingLister) []Match {
if lister == nil {
return nil
}
logical := strings.TrimSuffix(ev.Key, s3_constants.VersionsFolder)
if logical == "" {
return nil
}
oldID := string(ev.OldEntry.Extended[s3_constants.ExtLatestVersionIdKey])
newID := string(ev.NewEntry.Extended[s3_constants.ExtLatestVersionIdKey])
if oldID == newID {
// Same id means the update didn't transition the pointer.
return nil
}
// oldID == "" doesn't mean "nothing displaced": a bare null may
// have been the implicit/explicit latest before the pointer
// flipped to a real id.
// newID == "" means a suspended-versioning write cleared the
// pointer and made the bare null current. The cached
// ExtLatestVersionMtimeKey may still hold the prior latest's
// mtime (stale), so we must NOT use successorModTimeFromContainer
// in that case — derive the successor clock from the null entry's
// mtime instead. latestIDForExpand carries the same substitution
// so the expansion path's latestPos lookup matches the null sibling.
var successor time.Time
latestIDForExpand := newID
if newID == "" {
nullEntry, _, err := lister.LookupNullVersion(ctx, ev.Bucket, logical)
if err != nil {
glog.V(2).Infof("lifecycle router: lookup null %s/%s: %v", ev.Bucket, logical, err)
return nil
}
if nullEntry == nil || nullEntry.Attributes == nil {
return nil
}
successor = time.Unix(nullEntry.Attributes.Mtime, int64(nullEntry.Attributes.MtimeNs))
latestIDForExpand = "null"
} else {
successor = successorModTimeFromContainer(ev.NewEntry)
}
if successor.IsZero() {
return nil
}
if needsFullExpansion(snap, keys) {
return routePointerTransitionExpand(ctx, snap, ev, keys, lister, logical, latestIDForExpand, successor)
}
return routePointerTransitionDisplaced(ctx, snap, ev, keys, lister, logical, oldID, successor)
}
// needsFullExpansion reports whether any active event-driven rule on
// this bucket cares about NoncurrentIndex (NewerNoncurrentVersions > 0
// in either NoncurrentDays or pure-count NewerNoncurrent).
func needsFullExpansion(snap *engine.Snapshot, keys []s3lifecycle.ActionKey) bool {
for _, k := range keys {
if k.ActionKind != s3lifecycle.ActionKindNoncurrentDays && k.ActionKind != s3lifecycle.ActionKindNewerNoncurrent {
continue
}
a := snap.Action(k)
if a == nil || !a.IsActive() || a.Mode != engine.ModeEventDriven {
continue
}
if a.Rule != nil && a.Rule.NewerNoncurrentVersions > 0 {
return true
}
}
return false
}
// successorModTimeFromContainer reads the cached latest-version mtime
// from the .versions/ container's Extended map.
// updateLatestVersionInDirectory writes it via setCachedListMetadata
// alongside ExtLatestVersionIdKey, but the directory's own
// Attributes.Mtime is preserved across pointer updates — using it
// directly would let a stale dir mtime trigger expiration immediately.
// Returns zero time if the cached mtime is missing or unparseable; the
// caller suppresses in that case.
func successorModTimeFromContainer(entry *filer_pb.Entry) time.Time {
raw, ok := entry.Extended[s3_constants.ExtLatestVersionMtimeKey]
if !ok || len(raw) == 0 {
return time.Time{}
}
secs, err := strconv.ParseInt(string(raw), 10, 64)
if err != nil || secs <= 0 {
return time.Time{}
}
return time.Unix(secs, 0)
}
// routePointerTransitionDisplaced is the single-lookup path: only the
// displaced version's noncurrent eligibility could have changed, so
// fetching just its file is enough. oldID == "" routes the bare null
// version instead — it was the implicit latest before the pointer
// flipped to a real id.
func routePointerTransitionDisplaced(ctx context.Context, snap *engine.Snapshot, ev *reader.Event, keys []s3lifecycle.ActionKey, lister SiblingLister, logical, oldID string, successor time.Time) []Match {
var displaced *filer_pb.Entry
displacedID := oldID
if oldID == "" {
nullEntry, _, err := lister.LookupNullVersion(ctx, ev.Bucket, logical)
if err != nil {
glog.V(2).Infof("lifecycle router: lookup null version %s/%s: %v", ev.Bucket, logical, err)
return nil
}
if nullEntry == nil {
return nil
}
displaced = nullEntry
displacedID = "null"
} else {
entry, err := lister.LookupVersion(ctx, ev.Bucket, logical, oldID)
if err != nil {
glog.V(2).Infof("lifecycle router: lookup displaced version %s/%s/%s: %v", ev.Bucket, logical, oldID, err)
return nil
}
displaced = entry
}
if displaced == nil || displaced.Attributes == nil {
return nil
}
idx := 0
info := &s3lifecycle.ObjectInfo{
Key: logical,
ModTime: time.Unix(displaced.Attributes.Mtime, int64(displaced.Attributes.MtimeNs)),
Size: int64(displaced.Attributes.FileSize),
IsLatest: false,
IsDeleteMarker: string(displaced.Extended[s3_constants.ExtDeleteMarkerKey]) == "true",
NoncurrentIndex: &idx,
SuccessorModTime: successor,
}
if tags := extractTags(displaced.Extended); len(tags) > 0 {
info.Tags = tags
}
return emitNoncurrentMatches(snap, ev, keys, info, displaced, displacedID, successor)
}
// routePointerTransitionExpand routes only the versions that newly
// became eligible by the pointer flip:
//
// - rank 0: the displaced version (newly noncurrent), needed for the
// pure-NoncurrentDays clock,
// - rank == rule.NewerNoncurrentVersions for each active rule that
// gates on count: the version at exactly that rank just crossed
// from kept to expired.
//
// Emitting every eligible noncurrent on every PUT would push
// O(versions) heap entries per flip — Schedule.Add doesn't dedup, so
// identity-CAS at dispatch only stops the wasted RPC, not the heap
// growth. Bootstrap still owns full backfill.
func routePointerTransitionExpand(ctx context.Context, snap *engine.Snapshot, ev *reader.Event, keys []s3lifecycle.ActionKey, lister SiblingLister, logical, newID string, successor time.Time) []Match {
rawVersions, err := lister.ListVersions(ctx, ev.Bucket, logical)
if err != nil {
glog.V(2).Infof("lifecycle router: list versions %s/%s: %v", ev.Bucket, logical, err)
return nil
}
// Include the bare null version in the sibling set: count-based
// ranks are wrong if a pre-versioning or suspended-null entry
// exists outside .versions/. ID is "null" for sort + emit.
nullEntry, _, nullErr := lister.LookupNullVersion(ctx, ev.Bucket, logical)
if nullErr != nil {
glog.V(2).Infof("lifecycle router: lookup null %s/%s: %v", ev.Bucket, logical, nullErr)
return nil
}
type sibling struct {
entry *filer_pb.Entry
id string
}
siblings := make([]sibling, 0, len(rawVersions)+1)
for _, v := range rawVersions {
if v == nil || v.Attributes == nil {
continue
}
id := string(v.Extended[s3_constants.ExtVersionIdKey])
if id == "" {
continue
}
siblings = append(siblings, sibling{entry: v, id: id})
}
if nullEntry != nil && nullEntry.Attributes != nil {
siblings = append(siblings, sibling{entry: nullEntry, id: "null"})
}
if len(siblings) == 0 {
return nil
}
sort.SliceStable(siblings, func(i, j int) bool {
mi := siblings[i].entry.Attributes.Mtime*int64(1e9) + int64(siblings[i].entry.Attributes.MtimeNs)
mj := siblings[j].entry.Attributes.Mtime*int64(1e9) + int64(siblings[j].entry.Attributes.MtimeNs)
if mi != mj {
return mi > mj
}
return s3lifecycle.CompareVersionIds(siblings[i].id, siblings[j].id) < 0
})
// Resolve latestPos by finding newID. Default to -1 so a missing
// newID (race with the listing, or torn write) suppresses the
// expansion: we'd otherwise call the actual newest sibling "latest"
// against the pointer's intent and misrank every noncurrent.
// Bootstrap repairs state on the next walk.
latestPos := -1
if newID != "" {
for i, s := range siblings {
if s.id == newID {
latestPos = i
break
}
}
}
if latestPos < 0 {
glog.V(2).Infof("lifecycle router: pointer transition %s/%s: new id %s not found in listing", ev.Bucket, logical, newID)
return nil
}
noncurrentCount := len(siblings) - 1
// Collect the target noncurrent ranks: 0 (the freshly displaced)
// plus N for each active count-gated rule.
rankSet := map[int]struct{}{0: {}}
for _, k := range keys {
if k.ActionKind != s3lifecycle.ActionKindNoncurrentDays && k.ActionKind != s3lifecycle.ActionKindNewerNoncurrent {
continue
}
a := snap.Action(k)
if a == nil || !a.IsActive() || a.Mode != engine.ModeEventDriven {
continue
}
if a.Rule != nil && a.Rule.NewerNoncurrentVersions > 0 {
rankSet[a.Rule.NewerNoncurrentVersions] = struct{}{}
}
}
ranks := make([]int, 0, len(rankSet))
for r := range rankSet {
ranks = append(ranks, r)
}
sort.Ints(ranks)
var matches []Match
for _, rank := range ranks {
if rank >= noncurrentCount {
continue
}
// Convert noncurrent rank to position in the sorted slice,
// skipping the latest's slot.
i := rank
if rank >= latestPos {
i = rank + 1
}
s := siblings[i]
// Successor mtime: the entry directly newer than this one in
// the sorted list. When the next-newer slot is the latest,
// use the cached successor (the new latest's mtime); otherwise
// the immediate predecessor's mtime.
var thisSuccessor time.Time
if i > 0 && i-1 != latestPos {
thisSuccessor = time.Unix(siblings[i-1].entry.Attributes.Mtime, int64(siblings[i-1].entry.Attributes.MtimeNs))
} else {
thisSuccessor = successor
}
idx := rank
info := &s3lifecycle.ObjectInfo{
Key: logical,
ModTime: time.Unix(s.entry.Attributes.Mtime, int64(s.entry.Attributes.MtimeNs)),
Size: int64(s.entry.Attributes.FileSize),
IsLatest: false,
IsDeleteMarker: string(s.entry.Extended[s3_constants.ExtDeleteMarkerKey]) == "true",
NoncurrentIndex: &idx,
SuccessorModTime: thisSuccessor,
NumVersions: len(siblings),
}
if tags := extractTags(s.entry.Extended); len(tags) > 0 {
info.Tags = tags
}
matches = append(matches, emitNoncurrentMatches(snap, ev, keys, info, s.entry, s.id, thisSuccessor)...)
}
return matches
}
// emitNoncurrentMatches walks NoncurrentDays / NewerNoncurrent action
// keys and emits Matches for each one that fires. Shared between the
// single-lookup and full-expansion paths.
func emitNoncurrentMatches(snap *engine.Snapshot, ev *reader.Event, keys []s3lifecycle.ActionKey, info *s3lifecycle.ObjectInfo, entry *filer_pb.Entry, versionID string, successor time.Time) []Match {
eventTime := time.Unix(0, ev.TsNs)
identity := buildIdentityFromEntry(entry)
var matches []Match
for _, key := range keys {
if key.ActionKind != s3lifecycle.ActionKindNoncurrentDays && key.ActionKind != s3lifecycle.ActionKindNewerNoncurrent {
continue
}
action := snap.Action(key)
if action == nil || !action.IsActive() || action.Mode != engine.ModeEventDriven {
continue
}
clock := successor
if clock.IsZero() {
clock = info.ModTime
}
dueTime := clock.Add(action.Delay)
res := s3lifecycle.EvaluateAction(action.Rule, key.ActionKind, info, dueTime)
if res.Action == s3lifecycle.ActionNone {
continue
}
matches = append(matches, Match{
Key: key,
Action: action,
Result: res,
EventTs: eventTime,
DueTime: dueTime,
Bucket: ev.Bucket,
ObjectKey: info.Key,
VersionID: versionID,
Identity: identity,
})
}
return matches
}
// routeSoleSurvivorMarker emits an EXP_DM Match against the LOGICAL key
// (so the dispatcher can call deleteSpecificObjectVersion) with the
// marker's version_id. Handles two events: a marker create (the new
// entry IS the marker) and a noncurrent hard-delete that leaves the
// marker behind (the listing's lone entry IS the marker). The server
// re-checks before deleting.
func routeSoleSurvivorMarker(ctx context.Context, snap *engine.Snapshot, ev *reader.Event, keys []s3lifecycle.ActionKey, lister SiblingLister) []Match {
if lister == nil {
return nil
}
// Skip the listing RPC for events that can't possibly produce a
// sole-survivor marker: a regular non-marker version create/update
// always lands at Count >= 2.
if ev.NewEntry != nil && !isDeleteMarkerEntry(ev.NewEntry) {
return nil
}
logicalKey, ok := logicalKeyFromVersionPath(ev.Key)
if !ok {
return nil
}
s, err := lister.Survivors(ctx, ev.Bucket, logicalKey)
if err != nil {
glog.V(2).Infof("lifecycle router: survivors %s/%s: %v", ev.Bucket, logicalKey, err)
return nil
}
// Pre-versioning bare-key objects (the "null" version) live outside
// .versions/. Treating count==1 as sole-survivor while a null
// version exists would let lifecycle delete the marker and re-expose
// the old object.
if s.Count != 1 || s.HasNullVersion || s.LoneEntry == nil {
return nil
}
if !isDeleteMarkerEntry(s.LoneEntry) {
return nil
}
versionID := string(s.LoneEntry.Extended[s3_constants.ExtVersionIdKey])
if versionID == "" {
// Empty version_id would BLOCK at dispatch and freeze the cursor.
return nil
}
entry := s.LoneEntry
info := &s3lifecycle.ObjectInfo{
Key: logicalKey,
ModTime: time.Unix(entry.Attributes.Mtime, int64(entry.Attributes.MtimeNs)),
Size: int64(entry.Attributes.FileSize),
IsLatest: true,
IsDeleteMarker: true,
NumVersions: 1,
}
if tags := extractTags(entry.Extended); len(tags) > 0 {
info.Tags = tags
}
eventTime := time.Unix(0, ev.TsNs)
identity := buildIdentityFromEntry(entry)
var matches []Match
for _, key := range keys {
if key.ActionKind != s3lifecycle.ActionKindExpiredDeleteMarker {
continue
}
action := snap.Action(key)
if action == nil || !action.IsActive() || action.Mode != engine.ModeEventDriven {
continue
}
dueTime := info.ModTime.Add(action.Delay)
res := s3lifecycle.EvaluateAction(action.Rule, key.ActionKind, info, dueTime)
if res.Action == s3lifecycle.ActionNone {
continue
}
matches = append(matches, Match{
Key: key,
Action: action,
Result: res,
EventTs: eventTime,
DueTime: dueTime,
Bucket: ev.Bucket,
ObjectKey: logicalKey,
VersionID: versionID,
Identity: identity,
})
}
return matches
}
// routeBootstrapVersion handles a synthesized event from BucketBootstrapper.
// The bootstrap walker has already listed .versions/<key>/, sorted siblings
// newest-first, and stamped each one's IsLatest / NoncurrentIndex /
// SuccessorModTime. The router only needs to assemble ObjectInfo and run
// the match loop with the standard kind gates. ev.NewEntry is the version
// file itself; ev.Key is the version-folder path; the LOGICAL key from
// BootstrapVersion drives prefix matching and the dispatcher.
func routeBootstrapVersion(snap *engine.Snapshot, ev *reader.Event, keys []s3lifecycle.ActionKey) []Match {
bv := ev.BootstrapVersion
entry := ev.NewEntry
if entry == nil || entry.Attributes == nil || bv.LogicalKey == "" {
return nil
}
idx := bv.NoncurrentIndex
info := &s3lifecycle.ObjectInfo{
Key: bv.LogicalKey,
ModTime: time.Unix(entry.Attributes.Mtime, int64(entry.Attributes.MtimeNs)),
Size: int64(entry.Attributes.FileSize),
IsLatest: bv.IsLatest,
IsDeleteMarker: bv.IsDeleteMarker,
NumVersions: bv.NumVersions,
SuccessorModTime: bv.SuccessorModTime,
}
if !bv.IsLatest {
info.NoncurrentIndex = &idx
}
if tags := extractTags(entry.Extended); len(tags) > 0 {
info.Tags = tags
}
eventTime := time.Unix(0, ev.TsNs)
identity := buildIdentityFromEntry(entry)
var matches []Match
for _, key := range keys {
action := snap.Action(key)
if action == nil || !action.IsActive() || action.Mode != engine.ModeEventDriven {
continue
}
// ABORT_MPU never applies to a versioned object.
if key.ActionKind == s3lifecycle.ActionKindAbortMPU {
continue
}
// Noncurrent rules clock from when this version was replaced
// (SuccessorModTime), not from when it was originally written.
// Bootstrap populates SuccessorModTime; fall back to ModTime
// for the latest version (no successor exists).
clock := info.ModTime
if !info.IsLatest && !info.SuccessorModTime.IsZero() {
clock = info.SuccessorModTime
}
dueTime := clock.Add(action.Delay)
res := s3lifecycle.EvaluateAction(action.Rule, key.ActionKind, info, dueTime)
if res.Action == s3lifecycle.ActionNone {
continue
}
// Pin the version_id only for kinds the dispatcher needs to
// target by version: noncurrent retention and the marker
// itself. EXPIRATION_DAYS / EXPIRATION_DATE on the latest
// must NOT carry it — between schedule and dispatch a fresh
// PUT can land, and identity-CAS against the original
// version's bytes would still pass even though the latest has
// moved on. Empty VersionID makes the dispatcher fetch the
// current latest, where identity-CAS resolves to STALE_IDENTITY
// and bootstrap re-schedules with the new latest's identity.
var matchVersionID string
switch key.ActionKind {
case s3lifecycle.ActionKindNoncurrentDays,
s3lifecycle.ActionKindNewerNoncurrent,
s3lifecycle.ActionKindExpiredDeleteMarker:
matchVersionID = bv.VersionID
}
matches = append(matches, Match{
Key: key,
Action: action,
Result: res,
EventTs: eventTime,
DueTime: dueTime,
Bucket: ev.Bucket,
ObjectKey: bv.LogicalKey,
VersionID: matchVersionID,
Identity: identity,
})
}
return matches
}
// logicalKeyFromVersionPath extracts <logical> from <logical>.versions/<file>.
// Returns false for a bucket-root marker (path = ".versions/<file>"), since
// AWS S3 has no concept of an object at the bucket key itself.
func logicalKeyFromVersionPath(versionPath string) (string, bool) {
lastSlash := strings.LastIndex(versionPath, "/")
if lastSlash <= 0 {
return "", false
}
parent := versionPath[:lastSlash]
if !strings.HasSuffix(parent, s3_constants.VersionsFolder) {
return "", false
}
logical := strings.TrimSuffix(parent, s3_constants.VersionsFolder)
if logical == "" {
return "", false
}
return logical, true
}
// buildObjectInfo derives an ObjectInfo from a meta-log event. Returns
// nil for shapes the router can't classify safely: missing attributes,
// non-MPU directories, version-folder files (those route through
// routeSoleSurvivorMarker upstream when EXP_DM applies). On a versioned
// bucket the latest pointer lives in the .versions/ directory's
// Extended map; without it we leave NumVersions=0 so the bootstrap walk
// drives noncurrent retention.
func buildObjectInfo(ev *reader.Event, versioned bool) *s3lifecycle.ObjectInfo {
entry := ev.NewEntry
if entry == nil || entry.Attributes == nil {
return nil
}
if destKey, ok := mpuInitInfo(ev, entry); ok {
// MPU intermediate state has no tags, no versions, no delete-marker
// semantics. info.Key is the user's destination key so a rule's
// Filter.Prefix matches the eventual object; the dispatcher already
// carries .uploads/<upload_id> in m.ObjectKey for ABORT_MPU.
return &s3lifecycle.ObjectInfo{
Key: destKey,
ModTime: time.Unix(entry.Attributes.Mtime, int64(entry.Attributes.MtimeNs)),
IsMPUInit: true,
}
}
// Directory entries that aren't MPU inits aren't lifecycle subjects:
// the .versions/ folder itself, prefix dirs, etc. — emit nothing.
if entry.IsDirectory {
return nil
}
@@ -159,22 +720,9 @@ func buildObjectInfo(ev *reader.Event, versioned bool) *s3lifecycle.ObjectInfo {
NumVersions: 1,
}
if versioned {
// On a versioned bucket the actual file path doesn't tell us
// whether the entry is the current latest or a noncurrent
// version — the latest pointer lives in the .versions/
// directory's Extended map and isn't part of this event. We
// also can't compute NumVersions / NoncurrentIndex here. Skip
// any version-folder file event for now; bootstrap walking
// drives noncurrent retention and current-version expiration
// for versioned buckets until pointer-transition routing
// lands. The bare-key path (null-version, pre-versioning
// objects) keeps the regular routing.
if isVersionFolderPath(ev.Key) {
return nil
}
// NumVersions=0 keeps ExpiredObjectDeleteMarker (sole-survivor
// gate) suppressed for the bare-key delete-marker case until
// sibling listing lands.
info.NumVersions = 0
}
if tags := extractTags(entry.Extended); len(tags) > 0 {
@@ -186,6 +734,18 @@ func buildObjectInfo(ev *reader.Event, versioned bool) *s3lifecycle.ObjectInfo {
return info
}
// isVersionsContainerKey reports whether the bucket-relative key IS a
// .versions/ container itself (e.g. "logs/foo.versions"), as opposed to
// a file inside one. Used to recognize directory-level events whose
// Extended map carries the latest pointer for an object.
func isVersionsContainerKey(key string) bool {
if key == s3_constants.VersionsFolder {
// Bucket-root .versions: no logical object key.
return false
}
return strings.HasSuffix(key, s3_constants.VersionsFolder)
}
// isVersionFolderPath reports whether the bucket-relative key sits inside a
// .versions/ folder — i.e. the path's parent segment ends with the
// VersionsFolder suffix. Used by the versioned-bucket gate so the router
@@ -226,7 +786,10 @@ func mpuInitInfo(ev *reader.Event, entry *filer_pb.Entry) (destKey string, ok bo
// buildIdentity captures the entry's schedule-time fingerprint for the CAS
// witness. Returns nil if the event has no entry to fingerprint (deletes).
func buildIdentity(ev *reader.Event) *EntryIdentity {
entry := ev.NewEntry
return buildIdentityFromEntry(ev.NewEntry)
}
func buildIdentityFromEntry(entry *filer_pb.Entry) *EntryIdentity {
if entry == nil {
return nil
}
@@ -266,10 +829,31 @@ func extractTags(ext map[string][]byte) map[string]string {
return out
}
// hasActiveEventDrivenAction gates I/O (e.g. sibling listing) on whether
// a match could actually fire. Mirrors the per-key filter in Route so
// disabled or scan-only actions don't pay the RPC.
func hasActiveEventDrivenAction(snap *engine.Snapshot, keys []s3lifecycle.ActionKey, kind s3lifecycle.ActionKind) bool {
for _, k := range keys {
if k.ActionKind != kind {
continue
}
a := snap.Action(k)
if a == nil {
continue
}
if a.IsActive() && a.Mode == engine.ModeEventDriven {
return true
}
}
return false
}
// isDeleteMarkerEntry mirrors every read site for ExtDeleteMarkerKey:
// production writes []byte("true").
func isDeleteMarkerEntry(entry *filer_pb.Entry) bool {
if entry == nil || len(entry.Extended) == 0 {
return false
}
v, ok := entry.Extended[s3_constants.ExtDeleteMarkerKey]
return ok && len(v) == 1 && v[0] == 1
return ok && string(v) == "true"
}
File diff suppressed because it is too large. Load diff
@@ -1,6 +1,7 @@
package router
import (
"sync"
"testing"
"time"
@@ -84,3 +85,119 @@ func TestScheduleAllowsDuplicates(t *testing.T) {
t.Fatalf("Drain dup count=%d, want 2", len(got))
}
}
func TestScheduleDrainBeforeAnyDueReturnsNothing(t *testing.T) {
// Drain at a time before the earliest DueTime must return an empty
// slice and leave the heap intact. Otherwise the dispatcher would
// consume future-due matches early.
s := NewSchedule()
t0 := time.Now()
s.Add(mkMatch(t0.Add(5*time.Second), "a"))
s.Add(mkMatch(t0.Add(10*time.Second), "b"))
got := s.Drain(t0)
if got != nil {
t.Fatalf("Drain before any due should be nil, got %+v", got)
}
if s.Len() != 2 {
t.Fatalf("Len after no-op Drain=%d, want 2", s.Len())
}
}
func TestScheduleNextDueAfterPartialDrain(t *testing.T) {
// After draining a prefix, NextDue must point at the earliest
// remaining Match — regression catch for a Drain implementation
// that forgets to maintain the heap invariant.
s := NewSchedule()
t0 := time.Now()
s.Add(mkMatch(t0.Add(1*time.Second), "a"))
s.Add(mkMatch(t0.Add(2*time.Second), "b"))
s.Add(mkMatch(t0.Add(3*time.Second), "c"))
got := s.Drain(t0.Add(1500 * time.Millisecond))
if len(got) != 1 || got[0].ObjectKey != "a" {
t.Fatalf("Drain prefix=%+v, want [a]", got)
}
due, ok := s.NextDue()
if !ok || !due.Equal(t0.Add(2*time.Second)) {
t.Fatalf("NextDue after partial Drain=%v ok=%v, want t+2s", due, ok)
}
}
func TestScheduleAddAfterDrainKeepsOrder(t *testing.T) {
// Adding to a non-empty schedule mid-stream — after a real Drain
// has popped at least one entry, a fresh Match with an earlier
// DueTime than the existing minimum must become the next drainable.
// Pins that heap.Pop + Push together preserve the heap invariant
// across the Drain → Add boundary.
s := NewSchedule()
t0 := time.Now()
s.Add(mkMatch(t0.Add(10*time.Second), "old"))
s.Add(mkMatch(t0.Add(6*time.Second), "drain_me"))
drained := s.Drain(t0.Add(7 * time.Second))
if len(drained) != 1 || drained[0].ObjectKey != "drain_me" {
t.Fatalf("pre-drain=%+v, want [drain_me]", drained)
}
s.Add(mkMatch(t0.Add(5*time.Second), "new")) // added after Drain, earlier than old
due, ok := s.NextDue()
if !ok || !due.Equal(t0.Add(5*time.Second)) {
t.Fatalf("NextDue=%v ok=%v, want t+5s", due, ok)
}
got := s.Drain(t0.Add(6 * time.Second))
if len(got) != 1 || got[0].ObjectKey != "new" {
t.Fatalf("Drain=%+v, want [new]", got)
}
}
func TestScheduleDrainOrderIsAscendingDueTime(t *testing.T) {
// Drain must return Matches in DueTime order regardless of insert
// order — explicit pinning of the contract documented on Drain.
s := NewSchedule()
t0 := time.Now()
for _, off := range []time.Duration{
5 * time.Second,
1 * time.Second,
3 * time.Second,
2 * time.Second,
4 * time.Second,
} {
s.Add(mkMatch(t0.Add(off), "k"))
}
got := s.Drain(t0.Add(10 * time.Second))
if len(got) != 5 {
t.Fatalf("Drain count=%d, want 5", len(got))
}
for i := 1; i < len(got); i++ {
if got[i].DueTime.Before(got[i-1].DueTime) {
t.Fatalf("Drain[%d]=%v is before Drain[%d]=%v", i, got[i].DueTime, i-1, got[i-1].DueTime)
}
}
}
func TestScheduleConcurrentAddDrainNoRace(t *testing.T) {
// The dispatcher's Add and Drain run on separate goroutines; the
// schedule's mutex must serialize them without deadlock. -race
// catches a regression that drops the lock on either path.
s := NewSchedule()
t0 := time.Now()
const N = 64
var wg sync.WaitGroup
wg.Add(N * 2)
for i := 0; i < N; i++ {
i := i
go func() {
defer wg.Done()
s.Add(mkMatch(t0.Add(time.Duration(i)*time.Millisecond), "k"))
}()
go func() {
defer wg.Done()
_ = s.Drain(t0.Add(10 * time.Second))
}()
}
wg.Wait()
}
+369 -40
View File
@@ -3,14 +3,18 @@ package scheduler
import (
"context"
"fmt"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/reader"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// EventInjector is the bootstrap-side hook into the dispatcher pipeline.
@@ -20,6 +24,46 @@ type EventInjector interface {
InjectEvent(ctx context.Context, ev *reader.Event) error
}
// listPageSize is the page size for paginated directory listings during
// the bucket walk. The filer caps SeaweedList(..., limit=0) at
// DirListingLimit (1000 by default) per call, so a single-page list
// would silently truncate large directories — a correctness bug for
// noncurrent retention since older versions past the page boundary
// would never reach the rank/sort math. Atomic so tests can shrink it
// without racing the async bootstrap goroutines other tests leave
// behind (KickOffNew dispatches walks via `go b.walkBucket(...)`,
// and a fresh test's Cleanup might land before those goroutines exit).
var listPageSize atomic.Uint32
func init() {
listPageSize.Store(1024)
}
// listAll issues paginated SeaweedList calls until the listing is
// exhausted, invoking fn for every entry. Pagination uses
// startFrom = lastEntryName (exclusive) to advance.
func listAll(ctx context.Context, client filer_pb.SeaweedFilerClient, dir string, fn func(*filer_pb.Entry) error) error {
pageSize := listPageSize.Load()
startFrom := ""
for {
var pageCount uint32
var lastName string
if err := filer_pb.SeaweedList(ctx, client, dir, "", func(e *filer_pb.Entry, _ bool) error {
pageCount++
if e != nil {
lastName = e.Name
}
return fn(e)
}, startFrom, false, pageSize); err != nil {
return err
}
if pageCount < pageSize {
return nil
}
startFrom = lastName
}
}
// BucketBootstrapper backfills already-existing entries when a freshly-PUT
// rule's bucket appears in the engine. The reader-driven path only sees
// meta-log events created after the rule lands; without this walk,
@@ -34,33 +78,70 @@ type EventInjector interface {
// Synthesized events carry TsNs=0 so dispatcher.advance is a no-op for
// them — the reader still resumes from its persisted cursor on restart.
//
// Bucket completion is in-memory per process; a fresh worker run walks
// each bucket once on first refresh.
// Walk state is tracked in-memory per process via two maps:
// - lastCompleted: time of the last successful walk, drives the
// BootstrapInterval cadence; zero interval means "walk once per
// process".
// - inFlight: buckets whose walk goroutines are still running.
// Skipped regardless of cadence so a walk that takes longer than
// BootstrapInterval can't trigger a duplicate goroutine on the
// next refresh.
type BucketBootstrapper struct {
FilerClient filer_pb.SeaweedFilerClient
BucketsPath string
Injector EventInjector
mu sync.Mutex
known map[string]bool
// BootstrapInterval gates re-walks. Zero means "walk once per
// process". Non-zero means "walk again once it's been at least
// this long since the last completed walk" — the cadence scan_only
// actions rely on, since they can only fire from bootstrap.
BootstrapInterval time.Duration
// Now overrides time.Now for tests.
Now func() time.Time
mu sync.Mutex
lastCompleted map[string]time.Time
inFlight map[string]bool
}
func (b *BucketBootstrapper) now() time.Time {
if b.Now != nil {
return b.Now()
}
return time.Now()
}
// KickOffNew launches a one-shot walker goroutine for every bucket
// in `buckets` that hasn't been seen before.
// that's not currently in flight and either has never completed a walk
// or whose last successful walk finished more than BootstrapInterval ago.
func (b *BucketBootstrapper) KickOffNew(ctx context.Context, buckets []string) {
if b.Injector == nil {
return
}
now := b.now()
b.mu.Lock()
if b.known == nil {
b.known = map[string]bool{}
if b.lastCompleted == nil {
b.lastCompleted = map[string]time.Time{}
}
if b.inFlight == nil {
b.inFlight = map[string]bool{}
}
fresh := make([]string, 0, len(buckets))
for _, bucket := range buckets {
if b.known[bucket] {
if b.inFlight[bucket] {
// Walk still running from an earlier KickOffNew — never
// double up regardless of cadence. A large bucket that
// takes longer than BootstrapInterval would otherwise
// have a fresh goroutine fire on every refresh tick.
continue
}
b.known[bucket] = true
if last, ok := b.lastCompleted[bucket]; ok {
if b.BootstrapInterval <= 0 || now.Sub(last) < b.BootstrapInterval {
continue
}
}
b.inFlight[bucket] = true
fresh = append(fresh, bucket)
}
b.mu.Unlock()
@@ -75,7 +156,26 @@ func (b *BucketBootstrapper) walkBucket(ctx context.Context, bucket string) {
root := strings.TrimSuffix(b.BucketsPath, "/") + "/" + bucket
glog.V(0).Infof("lifecycle bootstrap: starting walk for bucket %s (root=%s)", bucket, root)
count := 0
if err := walkBucketDir(ctx, b.FilerClient, root, root, func(entry *filer_pb.Entry, key string) error {
// skipBare records bucket-relative bare-key paths that
// expandVersionsDir already routed as the null version. Without it
// the walker's regular emission would also fire for the bare entry
// — in a versioned bucket buildObjectInfo classifies it as
// IsLatest=true, NumVersions=0, and ExpirationDays would create a
// stray delete marker that hides the real latest.
skipBare := map[string]bool{}
var cb func(entry *filer_pb.Entry, key string) error
cb = func(entry *filer_pb.Entry, key string) error {
if isVersionsDir(entry) {
n, err := b.expandVersionsDir(ctx, bucket, root, key, entry, cb, skipBare)
count += n
return err
}
if !entry.IsDirectory && skipBare[key] {
return nil
}
if entry.IsDirectoryKeyObject() && skipBare[key] {
return nil
}
ev := &reader.Event{
// TsNs=0 sentinel: dispatcher.advance treats <=0 as no-op,
// so the reader's persisted cursor isn't ratcheted forward
@@ -88,51 +188,267 @@ func (b *BucketBootstrapper) walkBucket(ctx context.Context, bucket string) {
}
count++
return b.Injector.InjectEvent(ctx, ev)
}); err != nil {
}
walkErr := walkBucketDir(ctx, b.FilerClient, root, root, cb)
b.mu.Lock()
delete(b.inFlight, bucket)
if walkErr == nil {
// Stamp completion so BootstrapInterval cadence measures from
// end-of-walk. Failures leave lastCompleted alone, so the next
// KickOffNew sees no record and walks the bucket again.
if b.lastCompleted == nil {
b.lastCompleted = map[string]time.Time{}
}
b.lastCompleted[bucket] = b.now()
}
b.mu.Unlock()
if walkErr != nil {
if ctx.Err() == nil {
glog.V(0).Infof("lifecycle bootstrap %s: %v", bucket, err)
glog.V(0).Infof("lifecycle bootstrap %s: %v", bucket, walkErr)
}
return
}
glog.V(0).Infof("lifecycle bootstrap: bucket %s injected %d entries", bucket, count)
}
// walkBucketDir lists every file under dir recursively and invokes cb
// with the filer entry plus its bucket-relative key. MPU init dirs at
// .uploads/<id> are emitted as a single (directory-shaped) entry so the
// router's MPU detection fires; deeper directories recurse.
func walkBucketDir(ctx context.Context, client filer_pb.SeaweedFilerClient, dir, bucketRoot string, cb func(entry *filer_pb.Entry, key string) error) error {
// versionItem is the per-sibling state expandVersionsDir builds: the
// filer entry plus its version_id (or "null" for the bare null version
// living outside .versions/). isExplicitNull marks bare entries the
// suspended-versioning write path tagged with ExtVersionIdKey="null"
// (s3api_object_handlers_put.go); we trust those as latest when the
// .versions/ pointer is missing. A pre-versioning bare object has no
// such marker, so a missing pointer there is a race window with a new
// version write and we keep the newest-sibling fallback.
type versionItem struct {
entry *filer_pb.Entry
versionID string
bareKey string // bucket-relative path; non-empty only for the null version
isExplicitNull bool
}
// expandVersionsDir lists <root>/<key>/ and, when the children look like
// SeaweedFS version files, injects one reader.Event per version with
// BootstrapVersion populated. The bare logical key (the "null" version,
// living outside .versions/) is included as a sibling so:
// - pre-versioning objects with a newer .versions/ history fire
// NoncurrentDays as id="null"
// - suspended-bucket writes (which clear the .versions/ latest pointer)
// correctly classify null as the current version while every
// .versions/ child becomes noncurrent
//
// versionsKey is the bucket-relative path of the .versions/ directory
// (e.g. "logs/foo.versions"). When the bare null version is included,
// its bucket-relative path is added to skipBare so the walker's regular
// emission for the same entry is suppressed.
//
// When no child has ExtVersionIdKey the directory is a coincidentally-
// named user folder; recurse via fallback (the bucket walk's own cb).
func (b *BucketBootstrapper) expandVersionsDir(ctx context.Context, bucket, root, versionsKey string, versionsEntry *filer_pb.Entry, fallback func(*filer_pb.Entry, string) error, skipBare map[string]bool) (int, error) {
logical := strings.TrimSuffix(versionsKey, s3_constants.VersionsFolder)
if logical == "" {
return 0, nil
}
versionsDir := strings.TrimSuffix(b.BucketsPath, "/") + "/" + bucket + "/" + versionsKey
// Collect file children only. Subdirectories under .versions/ would
// corrupt sort/rank math; the disambiguation pass below also wants
// to see only file-shaped children. Paginate so a hot key with
// thousands of versions doesn't truncate at DirListingLimit.
var children []*filer_pb.Entry
if err := filer_pb.SeaweedList(ctx, client, dir, "", func(e *filer_pb.Entry, _ bool) error {
children = append(children, e)
if err := listAll(ctx, b.FilerClient, versionsDir, func(e *filer_pb.Entry) error {
if e != nil && e.Attributes != nil && !e.IsDirectory {
children = append(children, e)
}
return nil
}, "", false, 0); err != nil {
}); err != nil {
return 0, fmt.Errorf("list %s: %w", versionsDir, err)
}
items := make([]versionItem, 0, len(children)+1)
for _, e := range children {
if id, ok := e.Extended[s3_constants.ExtVersionIdKey]; ok && len(id) > 0 {
items = append(items, versionItem{entry: e, versionID: string(id)})
}
}
if len(items) == 0 {
// Coincidentally-named user folder (or an empty .versions
// container). fallback is the bucket walk's own cb so nested
// .versions/ entries inside still expand.
if fallback == nil {
return 0, nil
}
if err := walkBucketDir(ctx, b.FilerClient, versionsDir, root, fallback); err != nil {
return 0, err
}
return 0, nil
}
// Look up the bare null version. SeaweedFS keeps it at the logical
// path for pre-versioning objects and for suspended-bucket writes.
// Both shapes count: regular file (PUT'd object) and explicit S3
// directory-key marker (object name ends in /).
if nullEntry, nullKey, explicit, ok := b.lookupNullVersion(ctx, bucket, logical); ok {
items = append(items, versionItem{
entry: nullEntry,
versionID: "null",
bareKey: nullKey,
isExplicitNull: explicit,
})
}
// Sort newest-first: primary by mtime ns, fallback by version_id
// (CompareVersionIds returns <0 when first arg is newer). PUTs only
// set second-level Mtime, so collisions in the same second are
// resolved by the canonical version-id ordering used elsewhere.
sort.SliceStable(items, func(i, j int) bool {
mi := items[i].entry.Attributes.Mtime*int64(1e9) + int64(items[i].entry.Attributes.MtimeNs)
mj := items[j].entry.Attributes.Mtime*int64(1e9) + int64(items[j].entry.Attributes.MtimeNs)
if mi != mj {
return mi > mj
}
return s3lifecycle.CompareVersionIds(items[i].versionID, items[j].versionID) < 0
})
// Resolve latest position.
// 1. Pointer names a real id -> that wins (in-order or backdated).
// 2. Pointer absent + items[0] is an EXPLICIT null (suspended write
// cleared the pointer and tagged the bare object as null, AND
// the bare object is newest by mtime) -> null is latest.
// 3. Pointer absent in any other shape: fall back to newest
// sibling. Catches the post-suspended re-enable race window —
// a fresh .versions/<v1> write whose pointer update hasn't
// landed yet outranks the older suspended-null bare object.
latestID := string(versionsEntry.Extended[s3_constants.ExtLatestVersionIdKey])
latestPos := 0
if latestID != "" {
for i, it := range items {
if it.versionID == latestID {
latestPos = i
break
}
}
} else if len(items) > 0 && items[0].versionID == "null" && items[0].isExplicitNull {
latestPos = 0
}
count := 0
for i, it := range items {
var successor time.Time
if i > 0 {
prev := items[i-1].entry.Attributes
successor = time.Unix(prev.Mtime, int64(prev.MtimeNs))
}
bv := &reader.BootstrapVersion{
LogicalKey: logical,
VersionID: it.versionID,
IsLatest: i == latestPos,
IsDeleteMarker: string(it.entry.Extended[s3_constants.ExtDeleteMarkerKey]) == "true",
NumVersions: len(items),
SuccessorModTime: successor,
}
if !bv.IsLatest {
rank := i
if i > latestPos {
rank = i - 1
}
bv.NoncurrentIndex = rank
}
// Event Key for bookkeeping: real version files keep the
// .versions/<file> path; the null version uses its bare path
// so the dispatcher's identity check resolves to the same
// entry the walker would have emitted.
evKey := versionsKey + "/" + it.entry.Name
if it.versionID == "null" {
evKey = it.bareKey
}
ev := &reader.Event{
TsNs: 0,
Bucket: bucket,
Key: evKey,
ShardID: s3lifecycle.ShardID(bucket, logical),
NewEntry: it.entry,
BootstrapVersion: bv,
}
if err := b.Injector.InjectEvent(ctx, ev); err != nil {
return count, err
}
if it.versionID == "null" && skipBare != nil {
skipBare[it.bareKey] = true
}
count++
}
return count, nil
}
// lookupNullVersion returns the bare-key entry that represents the null
// version of logical, if any. Both regular files and S3 directory-key
// markers (an empty directory entry with Mime set) qualify. The
// explicit return reports whether the entry's Extended map carries
// ExtVersionIdKey == "null" — the marker the suspended-versioning
// write path applies (s3api_object_handlers_put.go). bucketRelKey is
// the bucket-relative path the walker would otherwise emit, so the
// caller can suppress the duplicate.
func (b *BucketBootstrapper) lookupNullVersion(ctx context.Context, bucket, logical string) (entry *filer_pb.Entry, bucketRelKey string, explicit bool, ok bool) {
bucketPath := strings.TrimSuffix(b.BucketsPath, "/") + "/" + bucket
parent, name := util.NewFullPath(bucketPath, logical).DirAndName()
resp, err := filer_pb.LookupEntry(ctx, b.FilerClient, &filer_pb.LookupDirectoryEntryRequest{
Directory: parent,
Name: name,
})
if err != nil || resp == nil || resp.Entry == nil {
return nil, "", false, false
}
e := resp.Entry
if e.IsDirectory && !e.IsDirectoryKeyObject() {
return nil, "", false, false
}
if id, hasID := e.Extended[s3_constants.ExtVersionIdKey]; hasID && string(id) == "null" {
explicit = true
}
return e, strings.TrimPrefix(parent+"/"+name, bucketPath+"/"), explicit, true
}
// walkBucketDir streams entries under dir and invokes cb. Two kinds of
// directories are emitted whole rather than recursed into:
// - .uploads/<id> MPU init dirs (router fires ABORT_MPU off the dir entry)
// - <key>.versions/ directories (caller expands them into per-version
// events; recursing here would emit individual version files without
// the sibling state needed for NoncurrentDays / NewerNoncurrent)
//
// .versions/ dirs are processed before everything else at each level so
// the cb's expandVersionsDir call can record the bare null-version key
// in the walk-shared skip set before the same level emits the bare entry.
// Two streaming passes (rather than buffering the whole directory) trade
// a second listing for bounded memory on flat buckets with millions of
// entries.
func walkBucketDir(ctx context.Context, client filer_pb.SeaweedFilerClient, dir, bucketRoot string, cb func(entry *filer_pb.Entry, key string) error) error {
// Pass 1: .versions/ dirs only.
if err := listAll(ctx, client, dir, func(e *filer_pb.Entry) error {
if e == nil || e.Attributes == nil {
return nil
}
if !e.IsDirectory || !isVersionsDir(e) {
return nil
}
full := dir + "/" + e.Name
key := strings.TrimPrefix(full, bucketRoot+"/")
return cb(e, key)
}); err != nil {
return fmt.Errorf("list %s: %w", dir, err)
}
for _, entry := range children {
if entry == nil || entry.Attributes == nil {
continue
// Pass 2: everything else. Bare entries whose name was claimed by
// a sibling .versions/ expansion are dropped by the cb's skip-set.
return listAll(ctx, client, dir, func(e *filer_pb.Entry) error {
if e == nil || e.Attributes == nil {
return nil
}
full := dir + "/" + entry.Name
if e.IsDirectory && isVersionsDir(e) {
return nil
}
full := dir + "/" + e.Name
key := strings.TrimPrefix(full, bucketRoot+"/")
if entry.IsDirectory {
if isMPUInitDir(key, entry) {
if err := cb(entry, key); err != nil {
return err
}
continue
if e.IsDirectory {
if isMPUInitDir(key, e) {
return cb(e, key)
}
if err := walkBucketDir(ctx, client, full, bucketRoot, cb); err != nil {
return err
}
continue
return walkBucketDir(ctx, client, full, bucketRoot, cb)
}
if err := cb(entry, key); err != nil {
return err
}
}
return nil
return cb(e, key)
})
}
// isMPUInitDir mirrors router.mpuInitInfo: a directory at .uploads/<id>
@@ -152,3 +468,16 @@ func isMPUInitDir(key string, entry *filer_pb.Entry) bool {
return ok && len(v) > 0
}
// isVersionsDir matches `<x>.versions/` by name suffix. We can't gate on
// ExtLatestVersionIdKey here: createDeleteMarker writes the version file
// before updating the parent's Extended pointer, so a walk that races
// with that update would see the directory without the pointer and
// recurse into raw version files, losing the sibling state needed for
// noncurrent rules. expandVersionsDir handles disambiguation by
// inspecting children for ExtVersionIdKey; coincidentally-named
// directories that aren't real .versions storage fall through to a
// regular recursion.
func isVersionsDir(entry *filer_pb.Entry) bool {
return entry.IsDirectory && strings.HasSuffix(entry.Name, s3_constants.VersionsFolder)
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,236 @@
package scheduler
import (
"context"
"fmt"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/engine"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// Tests for LoadCompileInputs / IsBucketVersioned / AllActivePriorStates.
// LoadCompileInputs is the bridge between the filer's bucket directory
// and the engine snapshot the scheduler compiles every refresh —
// pagination, parse-error surfacing, and the empty/missing-XML skip
// semantics matter because a missed bucket silently disables lifecycle
// for that prefix until the next refresh.
const testBucketsRoot = "/buckets"
// minimalLifecycleXML is the smallest XML that ParseCanonical accepts as
// a non-empty rule set; the actual rule details are exercised by the
// lifecycle_xml package's own tests.
const minimalLifecycleXML = `<LifecycleConfiguration>
<Rule>
<ID>r1</ID>
<Status>Enabled</Status>
<Filter><Prefix>logs/</Prefix></Filter>
<Expiration><Days>30</Days></Expiration>
</Rule>
</LifecycleConfiguration>`
func bucketEntry(name string, extended map[string][]byte) *filer_pb.Entry {
return dirEntry(name, extended)
}
func TestIsBucketVersioned_MissingExtendedReturnsFalse(t *testing.T) {
assert.False(t, IsBucketVersioned(&filer_pb.Entry{}))
assert.False(t, IsBucketVersioned(&filer_pb.Entry{Extended: map[string][]byte{}}))
}
func TestIsBucketVersioned_AcceptsEnabledAndSuspended(t *testing.T) {
// Casing and surrounding whitespace are normalized so the worker
// tolerates whatever casing the writer chose.
for _, raw := range []string{"Enabled", "ENABLED", "enabled", " enabled ", "Suspended", "suspended"} {
t.Run(raw, func(t *testing.T) {
e := &filer_pb.Entry{Extended: map[string][]byte{s3_constants.ExtVersioningKey: []byte(raw)}}
assert.True(t, IsBucketVersioned(e), "value %q must classify as versioned", raw)
})
}
}
func TestIsBucketVersioned_RejectsOtherValues(t *testing.T) {
for _, raw := range []string{"", "Disabled", "Off", "true", "1", "garbage"} {
t.Run(raw, func(t *testing.T) {
e := &filer_pb.Entry{Extended: map[string][]byte{s3_constants.ExtVersioningKey: []byte(raw)}}
assert.False(t, IsBucketVersioned(e), "value %q must NOT classify as versioned", raw)
})
}
}
func TestAllActivePriorStates_EmptyInputs(t *testing.T) {
assert.Empty(t, AllActivePriorStates(nil))
assert.Empty(t, AllActivePriorStates([]engine.CompileInput{}))
}
func TestAllActivePriorStates_SeedsAllActionsAsActive(t *testing.T) {
// Every (bucket, ruleHash, actionKind) tuple from the inputs must
// receive a PriorState with BootstrapComplete=true and
// Mode=ModeEventDriven so the scheduler dispatches matched events
// immediately rather than waiting for a per-action bootstrap walk.
rule := &s3lifecycle.Rule{
ID: "r1",
Status: s3lifecycle.StatusEnabled,
ExpirationDays: 30,
}
inputs := []engine.CompileInput{{Bucket: "b1", Rules: []*s3lifecycle.Rule{rule}}}
prior := AllActivePriorStates(inputs)
hash := s3lifecycle.RuleHash(rule)
kinds := s3lifecycle.RuleActionKinds(rule)
require.NotEmpty(t, kinds, "expiration-days rule must yield at least one action kind")
for _, kind := range kinds {
key := s3lifecycle.ActionKey{Bucket: "b1", RuleHash: hash, ActionKind: kind}
state, ok := prior[key]
require.True(t, ok, "prior state missing for action kind %v", kind)
assert.True(t, state.BootstrapComplete, "bootstrap complete for kind %v", kind)
assert.Equal(t, engine.ModeEventDriven, state.Mode, "mode for kind %v", kind)
}
assert.Len(t, prior, len(kinds), "exactly one prior-state entry per action kind")
}
func TestAllActivePriorStates_KeysSeparatedByBucket(t *testing.T) {
// Two buckets sharing identical rules must still get distinct
// PriorState entries, otherwise refresh would conflate their state.
rule := &s3lifecycle.Rule{ID: "r1", Status: s3lifecycle.StatusEnabled, ExpirationDays: 30}
inputs := []engine.CompileInput{
{Bucket: "alpha", Rules: []*s3lifecycle.Rule{rule}},
{Bucket: "beta", Rules: []*s3lifecycle.Rule{rule}},
}
prior := AllActivePriorStates(inputs)
hash := s3lifecycle.RuleHash(rule)
for _, kind := range s3lifecycle.RuleActionKinds(rule) {
assert.Contains(t, prior, s3lifecycle.ActionKey{Bucket: "alpha", RuleHash: hash, ActionKind: kind})
assert.Contains(t, prior, s3lifecycle.ActionKey{Bucket: "beta", RuleHash: hash, ActionKind: kind})
}
}
func TestLoadCompileInputs_EmptyBucketDir(t *testing.T) {
// No buckets at all -> no inputs, no parse errors, no transport error.
client := &fakeFilerClient{tree: map[string][]*filer_pb.Entry{testBucketsRoot: {}}}
inputs, perr, err := LoadCompileInputs(context.Background(), client, testBucketsRoot)
require.NoError(t, err)
assert.Empty(t, inputs)
assert.Empty(t, perr)
}
func TestLoadCompileInputs_FilesAtBucketLevelSkipped(t *testing.T) {
// A bare file at the buckets root isn't a bucket; the loader must
// skip it without touching the parser.
client := &fakeFilerClient{tree: map[string][]*filer_pb.Entry{
testBucketsRoot: {fileEntry("stray.txt")},
}}
inputs, perr, err := LoadCompileInputs(context.Background(), client, testBucketsRoot)
require.NoError(t, err)
assert.Empty(t, inputs)
assert.Empty(t, perr)
}
func TestLoadCompileInputs_BucketWithoutLifecycleConfigSkipped(t *testing.T) {
// Buckets that don't carry the lifecycle XML extended attribute are
// silently skipped — operators may have many buckets without rules.
client := &fakeFilerClient{tree: map[string][]*filer_pb.Entry{
testBucketsRoot: {bucketEntry("b1", nil)},
}}
inputs, perr, err := LoadCompileInputs(context.Background(), client, testBucketsRoot)
require.NoError(t, err)
assert.Empty(t, inputs)
assert.Empty(t, perr)
}
func TestLoadCompileInputs_BucketWithEmptyLifecycleXMLSkipped(t *testing.T) {
// Empty bytes under the lifecycle key shouldn't reach the parser.
client := &fakeFilerClient{tree: map[string][]*filer_pb.Entry{
testBucketsRoot: {bucketEntry("b1", map[string][]byte{
BucketLifecycleConfigurationXMLKey: nil,
})},
}}
inputs, perr, err := LoadCompileInputs(context.Background(), client, testBucketsRoot)
require.NoError(t, err)
assert.Empty(t, inputs)
assert.Empty(t, perr)
}
func TestLoadCompileInputs_ValidConfigBecomesInput(t *testing.T) {
client := &fakeFilerClient{tree: map[string][]*filer_pb.Entry{
testBucketsRoot: {bucketEntry("b1", map[string][]byte{
BucketLifecycleConfigurationXMLKey: []byte(minimalLifecycleXML),
})},
}}
inputs, perr, err := LoadCompileInputs(context.Background(), client, testBucketsRoot)
require.NoError(t, err)
assert.Empty(t, perr)
require.Len(t, inputs, 1)
assert.Equal(t, "b1", inputs[0].Bucket)
assert.False(t, inputs[0].Versioned, "no versioning attr -> not versioned")
assert.NotEmpty(t, inputs[0].Rules)
}
func TestLoadCompileInputs_VersioningAttrPropagates(t *testing.T) {
client := &fakeFilerClient{tree: map[string][]*filer_pb.Entry{
testBucketsRoot: {bucketEntry("b1", map[string][]byte{
BucketLifecycleConfigurationXMLKey: []byte(minimalLifecycleXML),
s3_constants.ExtVersioningKey: []byte("Enabled"),
})},
}}
inputs, perr, err := LoadCompileInputs(context.Background(), client, testBucketsRoot)
require.NoError(t, err)
assert.Empty(t, perr)
require.Len(t, inputs, 1)
assert.True(t, inputs[0].Versioned)
}
func TestLoadCompileInputs_MalformedXMLBecomesParseError(t *testing.T) {
// Malformed XML must not abort the whole walk — surfacing it as a
// ParseError lets operators see the bucket-level failure while
// other buckets keep loading.
client := &fakeFilerClient{tree: map[string][]*filer_pb.Entry{
testBucketsRoot: {
bucketEntry("bad", map[string][]byte{
BucketLifecycleConfigurationXMLKey: []byte("<not-valid-xml"),
}),
bucketEntry("good", map[string][]byte{
BucketLifecycleConfigurationXMLKey: []byte(minimalLifecycleXML),
}),
},
}}
inputs, perr, err := LoadCompileInputs(context.Background(), client, testBucketsRoot)
require.NoError(t, err)
require.Len(t, perr, 1)
assert.Equal(t, "bad", perr[0].Bucket)
assert.Error(t, perr[0].Err)
require.Len(t, inputs, 1)
assert.Equal(t, "good", inputs[0].Bucket)
}
func TestLoadCompileInputs_PaginatesAcrossPages(t *testing.T) {
// pageSize is 1024 inside LoadCompileInputs; populate just over the
// boundary to force a second listing call. Every bucket has the same
// minimal config so the input count must equal the bucket count.
const total = 1030
entries := make([]*filer_pb.Entry, 0, total)
for i := 0; i < total; i++ {
entries = append(entries, bucketEntry(fmt.Sprintf("b%05d", i), map[string][]byte{
BucketLifecycleConfigurationXMLKey: []byte(minimalLifecycleXML),
}))
}
client := &fakeFilerClient{tree: map[string][]*filer_pb.Entry{
testBucketsRoot: entries,
}}
inputs, perr, err := LoadCompileInputs(context.Background(), client, testBucketsRoot)
require.NoError(t, err)
assert.Empty(t, perr)
require.Len(t, inputs, total, "pagination must surface every bucket")
// Order is preserved across pages, and the page boundary at 1023/1024
// (pageSize is 1024) must not skip or duplicate entries.
assert.Equal(t, "b00000", inputs[0].Bucket)
assert.Equal(t, "b01023", inputs[1023].Bucket, "last entry of first page")
assert.Equal(t, "b01024", inputs[1024].Bucket, "first entry of second page")
assert.Equal(t, fmt.Sprintf("b%05d", total-1), inputs[total-1].Bucket)
}
@@ -0,0 +1,77 @@
package scheduler
import (
"context"
"testing"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/dispatcher"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/reader"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// pipelineFanout is the thin shard-routing layer the bootstrapper sees
// as an EventInjector. It maps Event.ShardID to the pipeline that owns
// that shard. Was previously at 0% coverage.
func TestPipelineFanout_NilEventIsNoOp(t *testing.T) {
// A nil event must be silently absorbed; otherwise a follow-up
// panic in the receiving pipeline would crash the bootstrapper.
f := pipelineFanout{}
assert.NoError(t, f.InjectEvent(context.Background(), nil))
}
func TestPipelineFanout_UnknownShardIsNoOp(t *testing.T) {
// A shard not covered by any pipeline in the fanout returns nil
// rather than erroring; the comment in scheduler.go documents this
// as forward-compat for future shard-mapping changes that might
// introduce gaps.
f := pipelineFanout{0: &dispatcher.Pipeline{EventBuffer: 1}}
assert.NoError(t, f.InjectEvent(context.Background(), &reader.Event{ShardID: 99}))
}
func TestPipelineFanout_KnownShardSucceeds(t *testing.T) {
// A matching shard reaches the pipeline's InjectEvent, which writes
// to its (buffered) events channel and returns nil.
f := pipelineFanout{0: &dispatcher.Pipeline{EventBuffer: 1}}
assert.NoError(t, f.InjectEvent(context.Background(), &reader.Event{ShardID: 0}))
}
func TestPipelineFanout_PropagatesContextCancellation(t *testing.T) {
// When the underlying pipeline's InjectEvent blocks on a full
// buffer and the ctx is canceled, the fanout must propagate the
// ctx error. Pre-fill the pipeline's buffer (size 1) so the second
// send blocks long enough for the cancellation to win the select.
p := &dispatcher.Pipeline{EventBuffer: 1}
require.NoError(t, p.InjectEvent(context.Background(), &reader.Event{}))
f := pipelineFanout{0: p}
ctx, cancel := context.WithCancel(context.Background())
cancel()
err := f.InjectEvent(ctx, &reader.Event{ShardID: 0})
require.Error(t, err)
assert.ErrorIs(t, err, context.Canceled)
}
func TestPipelineFanout_RoutesToCorrectPipeline(t *testing.T) {
// Two pipelines, each with buffer=1: an event for shard 7 must
// fill pipeline B's buffer (proven by the second send to that
// pipeline blocking with canceled ctx) without affecting pipeline
// A's buffer (proven by the third send still succeeding to A
// because A's buffer is still empty).
pA := &dispatcher.Pipeline{EventBuffer: 1}
pB := &dispatcher.Pipeline{EventBuffer: 1}
f := pipelineFanout{0: pA, 7: pB}
require.NoError(t, f.InjectEvent(context.Background(), &reader.Event{ShardID: 7}))
// Second send to shard 7 would block on the full buffer; use a
// pre-canceled ctx to detect the buffer-full state without hanging.
canceledCtx, cancel := context.WithCancel(context.Background())
cancel()
err := f.InjectEvent(canceledCtx, &reader.Event{ShardID: 7})
require.Error(t, err, "B's buffer should be full so a canceled-ctx send returns ctx.Err")
// Send to shard 0 still succeeds because A's buffer is untouched.
require.NoError(t, f.InjectEvent(context.Background(), &reader.Event{ShardID: 0}))
}
+10 -8
View File
@@ -33,11 +33,12 @@ type Scheduler struct {
ClientID int32
ClientName string
Workers int
DispatchTick time.Duration
CheckpointTick time.Duration
RefreshInterval time.Duration
RetryBackoff time.Duration
Workers int
DispatchTick time.Duration
CheckpointTick time.Duration
RefreshInterval time.Duration
BootstrapInterval time.Duration
RetryBackoff time.Duration
}
// Run blocks until ctx is canceled. Spawns Workers + 1 goroutines: one
@@ -100,9 +101,10 @@ func (s *Scheduler) Run(ctx context.Context) error {
}
bs := &BucketBootstrapper{
FilerClient: s.FilerClient,
BucketsPath: s.BucketsPath,
Injector: pipelineFanout(pipelinesByShard),
FilerClient: s.FilerClient,
BucketsPath: s.BucketsPath,
Injector: pipelineFanout(pipelinesByShard),
BootstrapInterval: s.BootstrapInterval,
}
s.refreshEngine(ctx, bs)
+70
View File
@@ -1,6 +1,76 @@
package s3lifecycle
import (
"strconv"
)
// versionIdFormatThreshold distinguishes old vs new format version IDs.
// New format (inverted timestamps) produces values above this threshold;
// old format (raw timestamps) produces values below it.
const versionIdFormatThreshold = 0x4000000000000000
// CompareVersionIds returns negative if a is newer than b, positive if b
// is newer, 0 if equal. Mirrors compareVersionIds in s3api_version_id.go
// (kept duplicated to avoid the s3api -> s3lifecycle import cycle). Used
// as a tiebreak when version mtimes collide at second resolution.
func CompareVersionIds(a, b string) int {
if a == b {
return 0
}
if a == "null" {
return 1 // null sorts last
}
if b == "null" {
return -1
}
aIsNew := isNewFormatVersionId(a)
bIsNew := isNewFormatVersionId(b)
if aIsNew == bIsNew {
// Same format. New format (inverted timestamps) sorts smaller=newer
// lexicographically; old format sorts smaller=older.
if aIsNew {
if a < b {
return -1
}
return 1
}
if a < b {
return 1
}
return -1
}
at := getVersionTimestamp(a)
bt := getVersionTimestamp(b)
if at > bt {
return -1
}
if at < bt {
return 1
}
return 0
}
func isNewFormatVersionId(versionId string) bool {
if len(versionId) < 16 || versionId == "null" {
return false
}
t, err := strconv.ParseUint(versionId[:16], 16, 64)
if err != nil {
return false
}
return t > versionIdFormatThreshold
}
func getVersionTimestamp(versionId string) int64 {
if len(versionId) < 16 || versionId == "null" {
return 0
}
t, err := strconv.ParseUint(versionId[:16], 16, 64)
if err != nil {
return 0
}
if t > versionIdFormatThreshold {
return int64(^uint64(0)>>1) - int64(t)
}
return int64(t)
}
+168
View File
@@ -0,0 +1,168 @@
package s3lifecycle
import (
"testing"
"github.com/stretchr/testify/assert"
)
// CompareVersionIds is the version-id tiebreak the router falls back to
// when two versions land at the same mtime second; getting the format /
// null / mixed-format axes wrong silently inverts retention rankings,
// which would resurrect deleted versions or evict live ones. The tests
// below pin every documented branch.
const (
// 16-char hex prefix above 0x4000000000000000 → new-format inverted
// timestamp.
newFormatPrefix1 = "4123456789abcdef"
newFormatPrefix2 = "5123456789abcdef" // strictly larger than prefix1
// 16-char hex prefix at or below the threshold → old-format raw
// timestamp.
oldFormatPrefix1 = "0123456789abcdef"
oldFormatPrefix2 = "0223456789abcdef" // strictly larger than prefix1
)
func TestCompareVersionIds_EqualReturnsZero(t *testing.T) {
assert.Equal(t, 0, CompareVersionIds("abc", "abc"))
assert.Equal(t, 0, CompareVersionIds("null", "null"))
assert.Equal(t, 0, CompareVersionIds("", ""))
}
func TestCompareVersionIds_NullSortsLast(t *testing.T) {
// "null" represents the bare pre-versioning entry; the router treats
// it as older than any real version-id so genuine versions take
// precedence in tiebreaks.
assert.Equal(t, 1, CompareVersionIds("null", newFormatPrefix1))
assert.Equal(t, 1, CompareVersionIds("null", oldFormatPrefix1))
assert.Equal(t, -1, CompareVersionIds(newFormatPrefix1, "null"))
assert.Equal(t, -1, CompareVersionIds(oldFormatPrefix1, "null"))
}
func TestCompareVersionIds_BothNewFormatSmallerIsNewer(t *testing.T) {
// New-format encodes the timestamp inverted, so the lexicographically
// smaller string represents a newer wall-clock time.
assert.Equal(t, -1, CompareVersionIds(newFormatPrefix1, newFormatPrefix2),
"new-format: smaller lex → newer → -1")
assert.Equal(t, 1, CompareVersionIds(newFormatPrefix2, newFormatPrefix1),
"new-format: larger lex → older → 1")
}
func TestCompareVersionIds_BothOldFormatLargerIsNewer(t *testing.T) {
// Old-format encodes the timestamp raw, so the lexicographically
// larger string is the newer wall-clock time.
assert.Equal(t, 1, CompareVersionIds(oldFormatPrefix1, oldFormatPrefix2),
"old-format: smaller lex → older → 1")
assert.Equal(t, -1, CompareVersionIds(oldFormatPrefix2, oldFormatPrefix1),
"old-format: larger lex → newer → -1")
}
func TestCompareVersionIds_MixedFormatComparesByTimestamp(t *testing.T) {
// New-format inverted timestamp = MaxInt64 - prefix; old-format raw =
// prefix. With prefix1 = 0x4123… and old prefix1 = 0x0123… the
// inverted new value is small but still positive, while the raw old
// value is also small. Whichever is numerically larger wins.
at := getVersionTimestamp(newFormatPrefix1)
bt := getVersionTimestamp(oldFormatPrefix1)
if at == bt {
assert.Equal(t, 0, CompareVersionIds(newFormatPrefix1, oldFormatPrefix1))
return
}
if at > bt {
assert.Equal(t, -1, CompareVersionIds(newFormatPrefix1, oldFormatPrefix1))
assert.Equal(t, 1, CompareVersionIds(oldFormatPrefix1, newFormatPrefix1))
} else {
assert.Equal(t, 1, CompareVersionIds(newFormatPrefix1, oldFormatPrefix1))
assert.Equal(t, -1, CompareVersionIds(oldFormatPrefix1, newFormatPrefix1))
}
}
func TestCompareVersionIds_MixedFormatEqualTimestampReturnsZero(t *testing.T) {
// If a new-format inverted timestamp equals an old-format raw
// timestamp, neither is newer — should be 0. We can synthesize this:
// pick an old prefix P, the matching new prefix is MaxInt64 - P.
old := uint64(0x0000000000010000)
new_ := uint64(int64(^uint64(0)>>1) - int64(old))
oldHex := uintToHex16(old)
newHex := uintToHex16(new_)
// Sanity: new_ must be above the threshold, otherwise it'd be parsed
// as old-format and the test wouldn't exercise the mixed branch.
if !isNewFormatVersionId(newHex) {
t.Fatalf("constructed new-format prefix %q didn't classify as new", newHex)
}
if isNewFormatVersionId(oldHex) {
t.Fatalf("constructed old-format prefix %q classified as new", oldHex)
}
assert.Equal(t, 0, CompareVersionIds(newHex, oldHex), "mixed-format equal timestamps must be 0")
}
func TestIsNewFormatVersionId_TooShortRejected(t *testing.T) {
// Strings shorter than 16 chars can't carry a hex timestamp prefix;
// they must classify as old-format so getVersionTimestamp returns 0
// rather than panic on slice bounds.
assert.False(t, isNewFormatVersionId(""))
assert.False(t, isNewFormatVersionId("4123"))
assert.False(t, isNewFormatVersionId("4123456789abcde")) // 15 chars
}
func TestIsNewFormatVersionId_NullRejected(t *testing.T) {
assert.False(t, isNewFormatVersionId("null"))
}
func TestIsNewFormatVersionId_NonHexRejected(t *testing.T) {
// Parse failure on the 16-char prefix means the comparator falls
// back to old-format treatment. Non-hex characters or surrounding
// whitespace must reject without erroring out.
assert.False(t, isNewFormatVersionId("zzzzzzzzzzzzzzzz"))
assert.False(t, isNewFormatVersionId("0xff000000000000")) // "0x" prefix breaks ParseUint base-16
assert.False(t, isNewFormatVersionId("ABC GHIJKLMNOPQR")) // space mid-string
}
func TestIsNewFormatVersionId_ThresholdBoundary(t *testing.T) {
// versionIdFormatThreshold = 0x4000000000000000. The check is
// strictly greater than, so the threshold value itself must
// classify as old-format.
assert.False(t, isNewFormatVersionId("4000000000000000"), "exactly at threshold is old")
assert.True(t, isNewFormatVersionId("4000000000000001"), "one above threshold is new")
assert.False(t, isNewFormatVersionId("3fffffffffffffff"), "one below threshold is old")
}
func TestGetVersionTimestamp_ReturnsZeroOnMalformed(t *testing.T) {
assert.Equal(t, int64(0), getVersionTimestamp(""))
assert.Equal(t, int64(0), getVersionTimestamp("null"))
assert.Equal(t, int64(0), getVersionTimestamp("4123456789abcde")) // too short
assert.Equal(t, int64(0), getVersionTimestamp("zzzzzzzzzzzzzzzz")) // not hex
assert.Equal(t, int64(0), getVersionTimestamp("zzzzzzzzzzzzzzzzMORE")) // not hex prefix
}
func TestGetVersionTimestamp_OldFormatReturnsRawValue(t *testing.T) {
// Old-format: prefix below threshold, returned raw.
assert.Equal(t, int64(0x0123456789abcdef), getVersionTimestamp(oldFormatPrefix1))
assert.Equal(t, int64(0x0223456789abcdef), getVersionTimestamp(oldFormatPrefix2))
// Trailing characters past the 16-char prefix are ignored.
assert.Equal(t, int64(0x0123456789abcdef), getVersionTimestamp(oldFormatPrefix1+"-suffix"))
}
func TestGetVersionTimestamp_NewFormatReturnsInvertedValue(t *testing.T) {
// New-format inversion: int64 max - parsed value. So a smaller
// stored prefix yields a larger inverted timestamp (= newer time).
maxI64 := int64(^uint64(0) >> 1)
assert.Equal(t, maxI64-int64(0x4123456789abcdef), getVersionTimestamp(newFormatPrefix1))
assert.Equal(t, maxI64-int64(0x5123456789abcdef), getVersionTimestamp(newFormatPrefix2))
// The smaller-prefix-=-newer-timestamp invariant the comparator
// relies on:
assert.Greater(t, getVersionTimestamp(newFormatPrefix1), getVersionTimestamp(newFormatPrefix2))
}
// uintToHex16 turns a uint64 into a 16-char lowercase hex string,
// padding with leading zeros. Used for synthesizing mixed-format
// equal-timestamp pairs in TestCompareVersionIds_MixedFormatEqualTimestampReturnsZero.
func uintToHex16(v uint64) string {
const hex = "0123456789abcdef"
out := make([]byte, 16)
for i := 15; i >= 0; i-- {
out[i] = hex[v&0xf]
v >>= 4
}
return string(out)
}
+5 -3
View File
@@ -68,6 +68,7 @@ func (c *commandS3LifecycleRunShard) Do(args []string, env *CommandEnv, writer i
dispatchTick := fs.Duration("dispatch", 5*time.Second, "dispatcher tick cadence")
checkpointTick := fs.Duration("checkpoint", 30*time.Second, "cursor checkpoint cadence")
refreshInterval := fs.Duration("refresh", 5*time.Minute, "interval for rebuilding the engine snapshot from filer-backed bucket configs; 0 = compile once at startup")
bootstrapInterval := fs.Duration("bootstrap-interval", 0, "cadence for revisiting each bucket's bootstrap walk; 0 = walk once per process. scan_only actions only fire from bootstrap, so a long-running worker needs a non-zero value to handle their retention horizon")
runtime := fs.Duration("runtime", 0, "wall-clock cap on the run; 0 = no timeout. -events alone can hang on quiet shards")
if err := fs.Parse(args); err != nil {
return err
@@ -119,9 +120,10 @@ func (c *commandS3LifecycleRunShard) Do(args []string, env *CommandEnv, writer i
}
bsr := &scheduler.BucketBootstrapper{
FilerClient: filerClient,
BucketsPath: bucketsPath,
Injector: pipeline,
FilerClient: filerClient,
BucketsPath: bucketsPath,
Injector: pipeline,
BootstrapInterval: *bootstrapInterval,
}
bootstrapCtx, bootstrapCancel := context.WithCancel(context.Background())
defer bootstrapCancel()
+17
View File
@@ -577,6 +577,21 @@ var (
Name: "bootstrap_dispatch_total",
Help: "Counter of bootstrap-walk Delete dispatches by bucket and action kind.",
}, []string{"bucket", "kind"})
// S3LifecycleMetadataOnlyCounter counts successful LifecycleDelete
// dispatches that took the metadata-only path — entry was removed
// without per-chunk DeleteFile RPCs because the entry's Attributes
// .TtlSec > 0 and the volume's natural TTL will reclaim chunks. Per-
// rule cardinality (rule_hash hex-encoded) lets operators identify
// which specific rule is exercising the optimization; in clusters
// with many rules this can be reduced via Prometheus relabeling.
S3LifecycleMetadataOnlyCounter = prometheus.NewCounterVec(
prometheus.CounterOpts{
Namespace: Namespace,
Subsystem: "s3_lifecycle",
Name: "metadata_only_total",
Help: "Counter of LifecycleDelete completions that skipped per-chunk delete (volume TTL reclaim).",
}, []string{"bucket", "rule_hash"})
)
func init() {
@@ -652,6 +667,7 @@ func init() {
Gather.MustRegister(S3LifecycleCursorMinTsNs)
Gather.MustRegister(S3LifecycleEventCounter)
Gather.MustRegister(S3LifecycleBootstrapDispatchCounter)
Gather.MustRegister(S3LifecycleMetadataOnlyCounter)
Gather.MustRegister(UploadErrorCounter)
@@ -727,6 +743,7 @@ func DeleteBucketMetrics(bucket string) {
c += S3BucketObjectCountGauge.DeletePartialMatch(labels)
c += S3LifecycleDispatchCounter.DeletePartialMatch(labels)
c += S3LifecycleBootstrapDispatchCounter.DeletePartialMatch(labels)
c += S3LifecycleMetadataOnlyCounter.DeletePartialMatch(labels)
glog.V(0).Infof("delete bucket metrics, %s: %d", bucket, c)
}
+18
View File
@@ -5,6 +5,16 @@ import (
"sync"
)
// maxRetainedBufferCap caps the capacity of buffers we hand back to the
// sync.Pool. Buffers grown past this (e.g. by a 64 MiB chunk upload through
// volume.PostHandler -> needle.ParseUpload -> bytes.Buffer.ReadFrom) are
// dropped instead of pooled, so the underlying byte array becomes garbage
// and is collected. Without this cap the pool effectively hoards every
// high-water buffer for the process's lifetime — see #6541, where Harbor's
// concurrent UploadPartCopy filled the pool with 64 MiB buffers and RSS
// never receded.
const maxRetainedBufferCap = 4 * 1024 * 1024
var syncPool = sync.Pool{
New: func() interface{} {
return new(bytes.Buffer)
@@ -16,5 +26,13 @@ func SyncPoolGetBuffer() *bytes.Buffer {
}
func SyncPoolPutBuffer(buffer *bytes.Buffer) {
if buffer == nil {
return
}
if buffer.Cap() > maxRetainedBufferCap {
// Drop the buffer; let GC reclaim the oversized backing array.
return
}
buffer.Reset()
syncPool.Put(buffer)
}
+92
View File
@@ -0,0 +1,92 @@
package buffer_pool
import (
"bytes"
"testing"
)
// TestSyncPoolPutBuffer_DropsOversized is a regression guard for the volume-side
// retention amplifier in https://github.com/seaweedfs/seaweedfs/issues/6541.
//
// volume.PostHandler -> needle.ParseUpload -> bytes.Buffer.ReadFrom grows the
// buffer to chunk size. If we Put that buffer back as-is, sync.Pool keeps it
// at the grown capacity for the rest of the process's lifetime. With
// concurrent UploadPartCopy load that fills the pool with N × chunk-size
// backing arrays that never shrink — exactly the "RSS never recedes" pattern
// reported in the issue.
//
// We verify a Put + Get round trip can never round-trip a buffer larger than
// maxRetainedBufferCap, regardless of how big it grew while in use.
func TestSyncPoolPutBuffer_DropsOversized(t *testing.T) {
// Drain the pool so we start from a deterministic point. sync.Pool may
// still hold cached entries on other Ps, but for the small/big-cap
// distinction below that doesn't matter — we assert an invariant on
// every Get, not the identity of a specific buffer.
for i := 0; i < 64; i++ {
_ = SyncPoolGetBuffer()
}
big := &bytes.Buffer{}
big.Grow(maxRetainedBufferCap * 4) // simulate a large upload buffer
if got := big.Cap(); got <= maxRetainedBufferCap {
t.Fatalf("test setup: big.Cap=%d should exceed threshold %d",
got, maxRetainedBufferCap)
}
SyncPoolPutBuffer(big)
// Any number of Gets must not return a buffer with cap > threshold.
// (If big had been retained, sync.Pool's per-P cache would surface it
// on the very next Get on this goroutine.)
for i := 0; i < 16; i++ {
got := SyncPoolGetBuffer()
if cap := got.Cap(); cap > maxRetainedBufferCap {
t.Fatalf("Get %d returned buffer with cap=%d, exceeds threshold %d "+
"(regression: oversized buffers retained in pool?)",
i, cap, maxRetainedBufferCap)
}
}
}
// TestSyncPoolPutBuffer_KeepsRightSized verifies the cap is one-sided: we
// still pool reasonably-sized buffers so the common case (small uploads,
// header parsing) doesn't pay an alloc per request.
func TestSyncPoolPutBuffer_KeepsRightSized(t *testing.T) {
for i := 0; i < 64; i++ {
_ = SyncPoolGetBuffer()
}
small := &bytes.Buffer{}
small.Grow(maxRetainedBufferCap / 2)
smallCap := small.Cap()
SyncPoolPutBuffer(small)
// We don't assert pointer identity (sync.Pool can hand back any cached
// buffer), but the previously-Put buffer should appear among Gets on
// the same goroutine in the absence of a GC. If our cap-policy ever
// regresses to dropping right-sized buffers, this test starts seeing
// only fresh (cap=0) buffers and fails.
sawPooled := false
for i := 0; i < 8; i++ {
got := SyncPoolGetBuffer()
if got.Cap() == smallCap {
sawPooled = true
break
}
}
if !sawPooled {
t.Fatalf("right-sized buffer (cap=%d) never came back from the pool "+
"(regression: cap policy too aggressive?)", smallCap)
}
}
// TestSyncPoolPutBuffer_NilSafe documents that Put tolerates a nil buffer.
// The volume server defers Put on a buffer obtained via Get, but defensive
// callers in other paths may Put(nil); we should not panic.
func TestSyncPoolPutBuffer_NilSafe(t *testing.T) {
defer func() {
if r := recover(); r != nil {
t.Fatalf("SyncPoolPutBuffer(nil) panicked: %v", r)
}
}()
SyncPoolPutBuffer(nil)
}
+25 -15
View File
@@ -9,31 +9,34 @@ import (
const (
jobType = "s3_lifecycle"
defaultWorkers = 1
defaultDispatchTickMinutes = int64(1)
defaultCheckpointTickSeconds = int64(30)
defaultRefreshIntervalMinutes = int64(5)
defaultMaxRuntimeMinutes = int64(60)
defaultWorkers = 1
defaultDispatchTickMinutes = int64(1)
defaultCheckpointTickSeconds = int64(30)
defaultRefreshIntervalMinutes = int64(5)
defaultMaxRuntimeMinutes = int64(60)
defaultBootstrapIntervalMinutes = int64(0) // 0 = walk once per process
)
// Config is the parsed AdminConfigForm + WorkerConfigForm view.
type Config struct {
Workers int
DispatchTick time.Duration
CheckpointTick time.Duration
RefreshInterval time.Duration
MaxRuntime time.Duration
Workers int
DispatchTick time.Duration
CheckpointTick time.Duration
RefreshInterval time.Duration
BootstrapInterval time.Duration
MaxRuntime time.Duration
}
// ParseConfig pulls the lifecycle Handler config from the merged
// admin+worker config values. Missing fields fall back to defaults.
func ParseConfig(adminValues, workerValues map[string]*plugin_pb.ConfigValue) Config {
cfg := Config{
Workers: int(readInt64(adminValues, "workers", defaultWorkers)),
DispatchTick: time.Duration(readInt64(workerValues, "dispatch_tick_minutes", defaultDispatchTickMinutes)) * time.Minute,
CheckpointTick: time.Duration(readInt64(workerValues, "checkpoint_tick_seconds", defaultCheckpointTickSeconds)) * time.Second,
RefreshInterval: time.Duration(readInt64(workerValues, "refresh_interval_minutes", defaultRefreshIntervalMinutes)) * time.Minute,
MaxRuntime: time.Duration(readInt64(workerValues, "max_runtime_minutes", defaultMaxRuntimeMinutes)) * time.Minute,
Workers: int(readInt64(adminValues, "workers", defaultWorkers)),
DispatchTick: time.Duration(readInt64(workerValues, "dispatch_tick_minutes", defaultDispatchTickMinutes)) * time.Minute,
CheckpointTick: time.Duration(readInt64(workerValues, "checkpoint_tick_seconds", defaultCheckpointTickSeconds)) * time.Second,
RefreshInterval: time.Duration(readInt64(workerValues, "refresh_interval_minutes", defaultRefreshIntervalMinutes)) * time.Minute,
BootstrapInterval: time.Duration(readInt64(workerValues, "bootstrap_interval_minutes", defaultBootstrapIntervalMinutes)) * time.Minute,
MaxRuntime: time.Duration(readInt64(workerValues, "max_runtime_minutes", defaultMaxRuntimeMinutes)) * time.Minute,
}
if cfg.Workers <= 0 {
cfg.Workers = defaultWorkers
@@ -47,6 +50,13 @@ func ParseConfig(adminValues, workerValues map[string]*plugin_pb.ConfigValue) Co
if cfg.RefreshInterval <= 0 {
cfg.RefreshInterval = time.Duration(defaultRefreshIntervalMinutes) * time.Minute
}
// BootstrapInterval is intentionally NOT clamped — zero means
// "walk once per process", which is the legacy default for any
// deployment that hasn't opted into a cadence yet. Negative values
// fall back to zero.
if cfg.BootstrapInterval < 0 {
cfg.BootstrapInterval = 0
}
if cfg.MaxRuntime <= 0 {
cfg.MaxRuntime = time.Duration(defaultMaxRuntimeMinutes) * time.Minute
}
+32 -8
View File
@@ -24,6 +24,9 @@ func TestParseConfigDefaults(t *testing.T) {
if cfg.MaxRuntime != 60*time.Minute {
t.Errorf("MaxRuntime default=%v, want 60m", cfg.MaxRuntime)
}
if cfg.BootstrapInterval != 0 {
t.Errorf("BootstrapInterval default=%v, want 0 (walk-once-per-process)", cfg.BootstrapInterval)
}
}
func TestParseConfigOverrides(t *testing.T) {
@@ -31,10 +34,11 @@ func TestParseConfigOverrides(t *testing.T) {
"workers": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 4}},
}
worker := map[string]*plugin_pb.ConfigValue{
"dispatch_tick_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 2}},
"checkpoint_tick_seconds": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 15}},
"refresh_interval_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 10}},
"max_runtime_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 120}},
"dispatch_tick_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 2}},
"checkpoint_tick_seconds": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 15}},
"refresh_interval_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 10}},
"bootstrap_interval_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 120}},
"max_runtime_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 120}},
}
cfg := ParseConfig(admin, worker)
if cfg.Workers != 4 {
@@ -49,6 +53,9 @@ func TestParseConfigOverrides(t *testing.T) {
if cfg.RefreshInterval != 10*time.Minute {
t.Errorf("RefreshInterval=%v, want 10m", cfg.RefreshInterval)
}
if cfg.BootstrapInterval != 120*time.Minute {
t.Errorf("BootstrapInterval=%v, want 120m", cfg.BootstrapInterval)
}
if cfg.MaxRuntime != 120*time.Minute {
t.Errorf("MaxRuntime=%v, want 120m", cfg.MaxRuntime)
}
@@ -56,10 +63,11 @@ func TestParseConfigOverrides(t *testing.T) {
func TestParseConfigClampsZeroAndNegative(t *testing.T) {
worker := map[string]*plugin_pb.ConfigValue{
"dispatch_tick_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 0}},
"checkpoint_tick_seconds": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 0}},
"refresh_interval_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 0}},
"max_runtime_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: -5}},
"dispatch_tick_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 0}},
"checkpoint_tick_seconds": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 0}},
"refresh_interval_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 0}},
"bootstrap_interval_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: -5}},
"max_runtime_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: -5}},
}
cfg := ParseConfig(nil, worker)
if cfg.DispatchTick != 1*time.Minute {
@@ -71,7 +79,23 @@ func TestParseConfigClampsZeroAndNegative(t *testing.T) {
if cfg.RefreshInterval != 5*time.Minute {
t.Errorf("zero RefreshInterval should clamp to default, got %v", cfg.RefreshInterval)
}
if cfg.BootstrapInterval != 0 {
t.Errorf("negative BootstrapInterval should clamp to 0, got %v", cfg.BootstrapInterval)
}
if cfg.MaxRuntime != 60*time.Minute {
t.Errorf("negative MaxRuntime should clamp to default, got %v", cfg.MaxRuntime)
}
}
func TestParseConfigBootstrapIntervalZeroIsLegacy(t *testing.T) {
// Explicit zero stays zero (walk-once-per-process). Existing
// deployments that don't set bootstrap_interval_minutes get the
// legacy behavior unchanged.
worker := map[string]*plugin_pb.ConfigValue{
"bootstrap_interval_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 0}},
}
cfg := ParseConfig(nil, worker)
if cfg.BootstrapInterval != 0 {
t.Errorf("zero BootstrapInterval must stay zero, got %v", cfg.BootstrapInterval)
}
}
+25 -15
View File
@@ -122,6 +122,14 @@ func (h *Handler) Descriptor() *plugin_pb.JobTypeDescriptor {
Widget: plugin_pb.ConfigWidget_CONFIG_WIDGET_NUMBER,
MinValue: &plugin_pb.ConfigValue{Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 1}},
},
{
Name: "bootstrap_interval_minutes",
Label: "Bootstrap Re-walk Interval (minutes)",
Description: "How often each bucket is re-walked. scan_only rules — those whose retention horizon exceeds meta-log retention — only fire from the bootstrap walk, so a non-zero value is required to enforce them on a long-running worker. 0 keeps the legacy walk-once-per-process behavior.",
FieldType: plugin_pb.ConfigFieldType_CONFIG_FIELD_TYPE_INT64,
Widget: plugin_pb.ConfigWidget_CONFIG_WIDGET_NUMBER,
MinValue: &plugin_pb.ConfigValue{Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 0}},
},
{
Name: "max_runtime_minutes",
Label: "Max Runtime (minutes)",
@@ -134,10 +142,11 @@ func (h *Handler) Descriptor() *plugin_pb.JobTypeDescriptor {
},
},
DefaultValues: map[string]*plugin_pb.ConfigValue{
"dispatch_tick_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultDispatchTickMinutes}},
"checkpoint_tick_seconds": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultCheckpointTickSeconds}},
"refresh_interval_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultRefreshIntervalMinutes}},
"max_runtime_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultMaxRuntimeMinutes}},
"dispatch_tick_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultDispatchTickMinutes}},
"checkpoint_tick_seconds": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultCheckpointTickSeconds}},
"refresh_interval_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultRefreshIntervalMinutes}},
"bootstrap_interval_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultBootstrapIntervalMinutes}},
"max_runtime_minutes": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultMaxRuntimeMinutes}},
},
},
AdminRuntimeDefaults: &plugin_pb.AdminRuntimeDefaults{
@@ -240,17 +249,18 @@ func (h *Handler) Execute(ctx context.Context, request *plugin_pb.ExecuteJobRequ
rpc := s3_lifecycle_pb.NewSeaweedS3LifecycleInternalClient(s3Conn)
sched := &scheduler.Scheduler{
BucketsPath: bucketsPath,
Engine: engine.New(),
Persister: &dispatcher.FilerPersister{Store: dispatcher.NewFilerStoreClient(filerClient)},
Client: lifecycleRPCAdapter{c: rpc},
FilerClient: filerClient,
ClientID: util.RandomInt32(),
ClientName: "worker-s3-lifecycle",
Workers: cfg.Workers,
DispatchTick: cfg.DispatchTick,
CheckpointTick: cfg.CheckpointTick,
RefreshInterval: cfg.RefreshInterval,
BucketsPath: bucketsPath,
Engine: engine.New(),
Persister: &dispatcher.FilerPersister{Store: dispatcher.NewFilerStoreClient(filerClient)},
Client: lifecycleRPCAdapter{c: rpc},
FilerClient: filerClient,
ClientID: util.RandomInt32(),
ClientName: "worker-s3-lifecycle",
Workers: cfg.Workers,
DispatchTick: cfg.DispatchTick,
CheckpointTick: cfg.CheckpointTick,
RefreshInterval: cfg.RefreshInterval,
BootstrapInterval: cfg.BootstrapInterval,
}
if err := sched.Run(runCtx); err != nil {
glog.Warningf("s3 lifecycle execute: %v", err)
@@ -0,0 +1,520 @@
package s3_lifecycle
import (
"context"
"errors"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
)
// Tests cover the worker-handler surface that runs without a live filer
// or S3 server: pure helpers (clusterS3Endpoints, readString),
// Capability/Descriptor sanity, and the Detect input-validation /
// skip-activity / proposal paths driven by a recorder sender.
// recordingSender captures everything the handler sends so each Detect
// case can assert on activities, proposals, and completion.
type recordingSender struct {
proposals []*plugin_pb.DetectionProposals
completes []*plugin_pb.DetectionComplete
activities []*plugin_pb.ActivityEvent
// errOn forces the named send to fail; lets tests cover the
// SendComplete error-propagation path without a full transport stub.
errOn map[string]error
}
func (r *recordingSender) SendProposals(p *plugin_pb.DetectionProposals) error {
if err := r.errOn["proposals"]; err != nil {
return err
}
r.proposals = append(r.proposals, p)
return nil
}
func (r *recordingSender) SendComplete(c *plugin_pb.DetectionComplete) error {
if err := r.errOn["complete"]; err != nil {
return err
}
r.completes = append(r.completes, c)
return nil
}
func (r *recordingSender) SendActivity(a *plugin_pb.ActivityEvent) error {
if err := r.errOn["activity"]; err != nil {
return err
}
r.activities = append(r.activities, a)
return nil
}
// ---------- clusterS3Endpoints ----------
func TestClusterS3Endpoints_NilContext(t *testing.T) {
// A nil ClusterContext occurs in early-bootstrap detect calls; the
// handler must return an empty slice rather than panic.
assert.Nil(t, clusterS3Endpoints(nil))
}
func TestClusterS3Endpoints_EmptyList(t *testing.T) {
assert.Empty(t, clusterS3Endpoints(&plugin_pb.ClusterContext{}))
}
func TestClusterS3Endpoints_FiltersEmptyEntries(t *testing.T) {
// An empty-string address represents a stale registry entry the
// master is about to evict; never dial that. Order of the surviving
// entries must be preserved so the handler dials a deterministic
// host across detect runs.
cc := &plugin_pb.ClusterContext{S3GrpcAddresses: []string{"s3a:8333", "", "s3b:8333", ""}}
assert.Equal(t, []string{"s3a:8333", "s3b:8333"}, clusterS3Endpoints(cc))
}
func TestClusterS3Endpoints_AllValid(t *testing.T) {
cc := &plugin_pb.ClusterContext{S3GrpcAddresses: []string{"s3a:8333", "s3b:8333"}}
assert.Equal(t, []string{"s3a:8333", "s3b:8333"}, clusterS3Endpoints(cc))
}
// ---------- readString ----------
func TestReadString_MissingKeyReturnsFallback(t *testing.T) {
got := readString(map[string]*plugin_pb.ConfigValue{}, "missing", "fallback")
assert.Equal(t, "fallback", got)
}
func TestReadString_NilValueReturnsFallback(t *testing.T) {
got := readString(map[string]*plugin_pb.ConfigValue{"k": nil}, "k", "fallback")
assert.Equal(t, "fallback", got)
}
func TestReadString_WrongKindReturnsFallback(t *testing.T) {
// Configs are typed; an Int64 in a string slot is a writer-side bug
// the handler must tolerate rather than panic on a type assertion.
values := map[string]*plugin_pb.ConfigValue{
"k": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 42}},
}
assert.Equal(t, "fallback", readString(values, "k", "fallback"))
}
func TestReadString_StringValueReturned(t *testing.T) {
values := map[string]*plugin_pb.ConfigValue{
"k": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: "expected"}},
}
assert.Equal(t, "expected", readString(values, "k", "fallback"))
}
// ---------- Capability ----------
func TestCapability_AdvertisesJobType(t *testing.T) {
h := NewHandler(nil)
cap := h.Capability()
require.NotNil(t, cap)
assert.Equal(t, jobType, cap.JobType)
assert.True(t, cap.CanDetect)
assert.True(t, cap.CanExecute)
// Admin caps concurrency at one job per worker; a rebuild of the
// scheduler must wait for the prior one to exit.
assert.Equal(t, int32(1), cap.MaxDetectionConcurrency)
assert.Equal(t, int32(1), cap.MaxExecutionConcurrency)
}
// ---------- Detect ----------
func TestDetect_NilRequestErrors(t *testing.T) {
h := NewHandler(nil)
r := &recordingSender{}
err := h.Detect(context.Background(), nil, r)
require.Error(t, err)
assert.Empty(t, r.proposals)
assert.Empty(t, r.completes)
}
func TestDetect_NilSenderErrors(t *testing.T) {
h := NewHandler(nil)
err := h.Detect(context.Background(), &plugin_pb.RunDetectionRequest{}, nil)
require.Error(t, err)
}
func TestDetect_WrongJobTypeErrors(t *testing.T) {
// A request routed to this handler with a foreign JobType is the
// admin's bug; surface as an error so it's visible rather than
// silently emitting a bogus proposal.
h := NewHandler(nil)
r := &recordingSender{}
err := h.Detect(context.Background(), &plugin_pb.RunDetectionRequest{JobType: "different_job"}, r)
require.Error(t, err)
assert.Contains(t, err.Error(), "different_job")
}
func TestDetect_NoS3EndpointsCompletesWithSkipActivity(t *testing.T) {
// A cluster with no S3 servers registered yet must not spawn the
// scheduler; emit a "skipped" activity for operator visibility and
// complete with success so the admin doesn't classify as a failure.
h := NewHandler(nil)
r := &recordingSender{}
err := h.Detect(context.Background(), &plugin_pb.RunDetectionRequest{
JobType: jobType,
ClusterContext: &plugin_pb.ClusterContext{},
}, r)
require.NoError(t, err)
assert.Empty(t, r.proposals, "no S3 endpoints must not yield a proposal")
require.Len(t, r.activities, 1)
assert.Equal(t, "skipped", r.activities[0].Stage)
assert.Contains(t, r.activities[0].Message, "no s3 servers")
require.Len(t, r.completes, 1)
assert.True(t, r.completes[0].Success, "skip is success, not failure")
assert.Equal(t, jobType, r.completes[0].JobType)
}
func TestDetect_NoFilerAddressesCompletesWithSkipActivity(t *testing.T) {
h := NewHandler(nil)
r := &recordingSender{}
err := h.Detect(context.Background(), &plugin_pb.RunDetectionRequest{
JobType: jobType,
ClusterContext: &plugin_pb.ClusterContext{
S3GrpcAddresses: []string{"s3a:8333"},
// no FilerGrpcAddresses
},
}, r)
require.NoError(t, err)
assert.Empty(t, r.proposals)
require.Len(t, r.activities, 1)
assert.Equal(t, "skipped", r.activities[0].Stage)
assert.Contains(t, r.activities[0].Message, "no filer addresses")
require.Len(t, r.completes, 1)
assert.True(t, r.completes[0].Success)
}
func TestDetect_HappyPathProposesOneJobWithFirstFilerAddress(t *testing.T) {
// Detect must propose exactly one job that targets the first filer
// address in the cluster context; the master refreshes the list so
// a stale entry self-heals on the next run.
h := NewHandler(nil)
r := &recordingSender{}
err := h.Detect(context.Background(), &plugin_pb.RunDetectionRequest{
JobType: jobType,
ClusterContext: &plugin_pb.ClusterContext{
S3GrpcAddresses: []string{"s3a:8333"},
FilerGrpcAddresses: []string{"filer-a:18888", "filer-b:18888"},
},
}, r)
require.NoError(t, err)
assert.Empty(t, r.activities, "happy path emits no skip activity")
require.Len(t, r.proposals, 1)
require.Len(t, r.proposals[0].Proposals, 1)
prop := r.proposals[0].Proposals[0]
assert.Equal(t, jobType, prop.JobType)
assert.NotEmpty(t, prop.ProposalId, "proposal id must be unique-per-run")
require.Contains(t, prop.Parameters, "filer_grpc_address")
val := prop.Parameters["filer_grpc_address"].GetStringValue()
assert.Equal(t, "filer-a:18888", val, "first reachable filer is dialed")
require.Len(t, r.completes, 1)
assert.True(t, r.completes[0].Success)
assert.Equal(t, int32(1), r.completes[0].TotalProposals)
}
func TestDetect_EmptyJobTypeAccepted(t *testing.T) {
// Detect is sometimes invoked with an unset JobType (broadcast
// detect); the handler must accept and behave as if it matched.
h := NewHandler(nil)
r := &recordingSender{}
err := h.Detect(context.Background(), &plugin_pb.RunDetectionRequest{
ClusterContext: &plugin_pb.ClusterContext{
S3GrpcAddresses: []string{"s3a:8333"},
FilerGrpcAddresses: []string{"f:18888"},
},
}, r)
require.NoError(t, err)
require.Len(t, r.proposals, 1)
}
func TestDetect_PropagatesProposalsSendError(t *testing.T) {
// SendProposals failing must propagate; otherwise the worker would
// silently report success despite never delivering the proposal.
h := NewHandler(nil)
want := errors.New("transport down")
r := &recordingSender{errOn: map[string]error{"proposals": want}}
err := h.Detect(context.Background(), &plugin_pb.RunDetectionRequest{
JobType: jobType,
ClusterContext: &plugin_pb.ClusterContext{
S3GrpcAddresses: []string{"s3a:8333"},
FilerGrpcAddresses: []string{"f:18888"},
},
}, r)
assert.ErrorIs(t, err, want)
assert.Empty(t, r.proposals)
assert.Empty(t, r.completes, "complete must not fire when proposals fail")
}
func TestDetect_PropagatesCompleteSendError(t *testing.T) {
// SendComplete failing must propagate; otherwise the worker would
// report success to the admin despite the completion signal never
// landing. Proposals went out before the failure, so they remain in
// the recorder.
h := NewHandler(nil)
want := errors.New("transport down")
r := &recordingSender{errOn: map[string]error{"complete": want}}
err := h.Detect(context.Background(), &plugin_pb.RunDetectionRequest{
JobType: jobType,
ClusterContext: &plugin_pb.ClusterContext{
S3GrpcAddresses: []string{"s3a:8333"},
FilerGrpcAddresses: []string{"f:18888"},
},
}, r)
assert.ErrorIs(t, err, want)
assert.Len(t, r.proposals, 1, "proposals send before complete and remain recorded")
assert.Empty(t, r.completes)
}
// ---------- Descriptor ----------
func TestDescriptor_BasicShape(t *testing.T) {
// Sanity-check the Descriptor's public-facing identifiers so a
// rename in handler.go doesn't silently break the admin UI without
// an admin-side change too.
h := NewHandler(nil)
d := h.Descriptor()
require.NotNil(t, d)
assert.Equal(t, jobType, d.JobType)
assert.NotEmpty(t, d.DisplayName)
assert.NotEmpty(t, d.Description)
assert.Greater(t, d.DescriptorVersion, uint32(0), "descriptor version must be positive (admins use it for compat)")
}
func TestDescriptor_AdminConfigFormHasWorkersField(t *testing.T) {
// Workers is the only admin-side knob today; if it disappears, the
// admin form would render empty and operators couldn't tune
// concurrency.
h := NewHandler(nil)
d := h.Descriptor()
require.NotNil(t, d.AdminConfigForm)
assert.Equal(t, "s3-lifecycle-admin", d.AdminConfigForm.FormId)
// Walk every section's fields and find "workers".
var found bool
for _, sec := range d.AdminConfigForm.Sections {
for _, f := range sec.Fields {
if f.Name == "workers" {
found = true
assert.Equal(t, plugin_pb.ConfigFieldType_CONFIG_FIELD_TYPE_INT64, f.FieldType)
}
}
}
assert.True(t, found, "admin form must expose 'workers' field")
// Default value matches the constant used by ParseConfig.
dv, ok := d.AdminConfigForm.DefaultValues["workers"]
require.True(t, ok, "workers must have a default in AdminConfigForm")
assert.Equal(t, int64(defaultWorkers), dv.GetInt64Value())
}
func TestDescriptor_WorkerConfigFormCadenceDefaultsMatchParseConfig(t *testing.T) {
// Every default the parser reads must be exposed in the descriptor's
// DefaultValues; otherwise the admin UI would seed the form with a
// blank or zero value and the worker would silently clamp to the
// hardcoded fallback. Drift between the two is the bug this test
// catches.
h := NewHandler(nil)
d := h.Descriptor()
require.NotNil(t, d.WorkerConfigForm)
assert.Equal(t, "s3-lifecycle-worker", d.WorkerConfigForm.FormId)
wantDefaults := map[string]int64{
"dispatch_tick_minutes": defaultDispatchTickMinutes,
"checkpoint_tick_seconds": defaultCheckpointTickSeconds,
"refresh_interval_minutes": defaultRefreshIntervalMinutes,
"bootstrap_interval_minutes": defaultBootstrapIntervalMinutes,
"max_runtime_minutes": defaultMaxRuntimeMinutes,
}
for name, want := range wantDefaults {
t.Run(name, func(t *testing.T) {
dv, ok := d.WorkerConfigForm.DefaultValues[name]
require.True(t, ok, "WorkerConfigForm.DefaultValues missing %q", name)
assert.Equal(t, want, dv.GetInt64Value(), "default mismatch for %q", name)
})
}
// And the form fields themselves: every default must be paired with
// a field of matching name AND INT64 type so the admin can render +
// edit it and ParseConfig's readInt64 reads it correctly. Drift to
// e.g. STRING here would silently make the worker fall back to the
// hardcoded default and ignore admin edits.
declared := map[string]plugin_pb.ConfigFieldType{}
for _, sec := range d.WorkerConfigForm.Sections {
for _, f := range sec.Fields {
declared[f.Name] = f.FieldType
}
}
for name := range wantDefaults {
ft, ok := declared[name]
assert.True(t, ok, "WorkerConfigForm has no field named %q", name)
assert.Equal(t, plugin_pb.ConfigFieldType_CONFIG_FIELD_TYPE_INT64, ft, "field %q must be INT64 to match readInt64", name)
}
}
func TestDescriptor_AdminRuntimeDefaultsDailyCadence(t *testing.T) {
// Lifecycle is a daily batch; the admin must default to a 24-hour
// detection interval so cron pressure doesn't escalate. Bound the
// detection timeout so a stuck detect can't pin a worker slot
// indefinitely. Max 1 job per detection = scheduler runs alone.
h := NewHandler(nil)
d := h.Descriptor()
require.NotNil(t, d.AdminRuntimeDefaults)
assert.Equal(t, int32(24*60), d.AdminRuntimeDefaults.DetectionIntervalMinutes)
assert.Equal(t, int32(60), d.AdminRuntimeDefaults.DetectionTimeoutSeconds, "60s timeout caps a stuck detect at one minute")
assert.Equal(t, int32(1), d.AdminRuntimeDefaults.MaxJobsPerDetection)
}
// ---------- Execute ----------
// recordingExecSender captures Execute-side messages. The Execute path
// dials gRPC after passing validation, so these tests only exercise
// the validation surface that errors out before any dial — proving
// the handler refuses malformed jobs early instead of waiting on a
// 30s dial timeout.
type recordingExecSender struct {
progress []*plugin_pb.JobProgressUpdate
completed []*plugin_pb.JobCompleted
}
func (r *recordingExecSender) SendProgress(p *plugin_pb.JobProgressUpdate) error {
r.progress = append(r.progress, p)
return nil
}
func (r *recordingExecSender) SendCompleted(c *plugin_pb.JobCompleted) error {
r.completed = append(r.completed, c)
return nil
}
func TestExecute_NilRequestErrors(t *testing.T) {
h := NewHandler(nil)
err := h.Execute(context.Background(), nil, &recordingExecSender{})
require.Error(t, err)
assert.Contains(t, err.Error(), "nil")
}
func TestExecute_NilJobErrors(t *testing.T) {
// A non-nil request with nil Job is a writer-side bug; refuse it
// rather than panic dereferencing request.Job.JobType.
h := NewHandler(nil)
err := h.Execute(context.Background(), &plugin_pb.ExecuteJobRequest{}, &recordingExecSender{})
require.Error(t, err)
assert.Contains(t, err.Error(), "nil")
}
func TestExecute_NilSenderErrors(t *testing.T) {
h := NewHandler(nil)
err := h.Execute(context.Background(), &plugin_pb.ExecuteJobRequest{
Job: &plugin_pb.JobSpec{JobType: jobType},
}, nil)
require.Error(t, err)
assert.Contains(t, err.Error(), "nil")
}
func TestExecute_WrongJobTypeErrors(t *testing.T) {
// A foreign job type routed to this handler is the admin's bug;
// surface as an error rather than running a bogus scheduler.
h := NewHandler(nil)
err := h.Execute(context.Background(), &plugin_pb.ExecuteJobRequest{
Job: &plugin_pb.JobSpec{JobType: "different_job"},
}, &recordingExecSender{})
require.Error(t, err)
assert.Contains(t, err.Error(), "different_job")
}
func TestExecute_NoS3EndpointsErrors(t *testing.T) {
// Detect emits a "skipped" activity for this case; Execute is
// stricter — the admin shouldn't have routed an Execute request
// without S3 endpoints, so error out instead of silently no-oping.
h := NewHandler(nil)
err := h.Execute(context.Background(), &plugin_pb.ExecuteJobRequest{
Job: &plugin_pb.JobSpec{JobType: jobType},
ClusterContext: &plugin_pb.ClusterContext{}, // no S3GrpcAddresses
}, &recordingExecSender{})
require.Error(t, err)
assert.Contains(t, err.Error(), "no s3 servers")
}
func TestExecute_MissingFilerAddressErrors(t *testing.T) {
// filer_grpc_address is set by Detect when it builds the proposal;
// missing it means the proposal was tampered with or the admin
// dropped the parameter. Refuse rather than dial nothing.
h := NewHandler(nil)
err := h.Execute(context.Background(), &plugin_pb.ExecuteJobRequest{
Job: &plugin_pb.JobSpec{
JobType: jobType,
Parameters: map[string]*plugin_pb.ConfigValue{}, // no filer_grpc_address
},
ClusterContext: &plugin_pb.ClusterContext{
S3GrpcAddresses: []string{"s3a:8333"},
},
}, &recordingExecSender{})
require.Error(t, err)
assert.Contains(t, err.Error(), "filer_grpc_address")
}
func TestExecute_EmptyJobTypeAccepted(t *testing.T) {
// Same convention as Detect: an empty JobType is broadcast routing
// and must be accepted. The handler then errors at the next
// validation step (no S3 endpoints) rather than at the type check.
h := NewHandler(nil)
err := h.Execute(context.Background(), &plugin_pb.ExecuteJobRequest{
Job: &plugin_pb.JobSpec{}, // empty JobType
ClusterContext: &plugin_pb.ClusterContext{},
}, &recordingExecSender{})
require.Error(t, err)
assert.Contains(t, err.Error(), "no s3 servers", "validation flowed past the type check")
}
// ---------- lookupBucketsPath ----------
// stubFilerConfigClient implements filer_pb.SeaweedFilerClient for the
// GetFilerConfiguration call lookupBucketsPath relies on; methods that
// aren't named here would panic if called, which the tests rely on to
// keep the surface narrow.
type stubFilerConfigClient struct {
filer_pb.SeaweedFilerClient
resp *filer_pb.GetFilerConfigurationResponse
err error
}
func (c *stubFilerConfigClient) GetFilerConfiguration(_ context.Context, _ *filer_pb.GetFilerConfigurationRequest, _ ...grpc.CallOption) (*filer_pb.GetFilerConfigurationResponse, error) {
if c.err != nil {
return nil, c.err
}
return c.resp, nil
}
func TestLookupBucketsPath_PropagatesGRPCError(t *testing.T) {
// A failed config lookup must surface; without it, Execute would
// proceed to dial S3 with an empty buckets path and quietly never
// dispatch anything.
want := errors.New("filer down")
got, err := lookupBucketsPath(context.Background(), &stubFilerConfigClient{err: want})
assert.ErrorIs(t, err, want)
assert.Empty(t, got)
}
func TestLookupBucketsPath_UsesConfiguredDirBuckets(t *testing.T) {
// When the filer reports a non-empty DirBuckets, the worker honors
// it. Operators with a non-default layout (e.g. "/data/buckets")
// can't be routed to "/buckets".
got, err := lookupBucketsPath(context.Background(), &stubFilerConfigClient{
resp: &filer_pb.GetFilerConfigurationResponse{DirBuckets: "/data/buckets"},
})
require.NoError(t, err)
assert.Equal(t, "/data/buckets", got)
}
func TestLookupBucketsPath_EmptyDirBucketsFallsBackToDefault(t *testing.T) {
// Filer doesn't always populate DirBuckets (older configs); the
// helper falls back to the documented default "/buckets" rather
// than returning an empty path that would force-route to root.
got, err := lookupBucketsPath(context.Background(), &stubFilerConfigClient{
resp: &filer_pb.GetFilerConfigurationResponse{DirBuckets: ""},
})
require.NoError(t, err)
assert.Equal(t, "/buckets", got)
}