Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ TAG is a high-performance S3-compatible caching proxy for [Tigris](https://tigri
- **Request Coalescing**: Streaming broadcast pattern reduces duplicate upstream requests under concurrent load
- **Range Request Caching**: Background fetch of full objects on range cache miss for optimal ML training workloads
- **Block-Aligned Caching** *(default)*: Caches large objects as fixed-size blocks (RFC 0001) so a small range read fetches and caches only the covering blocks instead of the whole object — ideal for sparse reads of large files (Parquet footers/row-groups, SST blocks). Enabled by default at 1 MiB blocks; size `block_size` to your read granularity, or set `block_caching_enabled: false` to cache whole objects.
- **Conditional Requests**: Supports If-None-Match and If-Modified-Since for efficient cache validation
- **Conditional Requests**: Supports `If-None-Match` and `If-Modified-Since`; for GET, successful forced revalidation returns a bodyless `304` when the client's validator matches the origin-confirmed representation
- **AWS SigV4 Authentication**: Full AWS Signature Version 4 validation and re-signing; repeated ASCII spaces are normalized only for signature calculation, not in forwarded metadata
- **Prometheus Metrics**: Comprehensive metrics for monitoring cache efficiency and performance
- **Kubernetes Ready**: Includes deployment manifests for production use
Expand Down
18 changes: 14 additions & 4 deletions cache/object.go
Original file line number Diff line number Diff line change
Expand Up @@ -291,8 +291,8 @@ func (m *CachedObjectMeta) MatchesETag(etag string) bool {
// list that contains the live ETag never match — fatal on the authoritative
// paths (origin-less and tiered), where there is no upstream to answer
// correctly instead: legal conditional writes 412 and valid 304s are lost.
// Splitting on ',' is exact here because ETags are quoted strings whose only
// legal inner characters exclude ',' (RFC 7232 §2.3).
// Commas delimit list members only outside quotes: the opaque tag itself may
// contain a comma (RFC 7232 §2.3). Backslashes are literal, not quote escapes.
//
// strong selects the comparison function (RFC 7232 §2.3.2): If-Match REQUIRES
// strong comparison — a W/ weak validator never matches, so a conditional
Expand All @@ -305,8 +305,18 @@ func (m *CachedObjectMeta) MatchesETagHeader(header string, strong bool) bool {
if header == "*" {
return true
}
for _, candidate := range strings.Split(header, ",") {
candidate = strings.TrimSpace(candidate)
start, quoted := 0, false
for i := 0; i <= len(header); i++ {
if i < len(header) {
if header[i] == '"' {
quoted = !quoted
}
if header[i] != ',' || quoted {
continue
}
}
candidate := strings.TrimSpace(header[start:i])
start = i + 1
if candidate == "*" {
return true
}
Expand Down
35 changes: 35 additions & 0 deletions cache/object_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,41 @@ func TestCachedObjectMeta_IsCacheable(t *testing.T) {
}
}

func TestCachedObjectMeta_MatchesETagHeader(t *testing.T) {
tests := []struct {
name string
etag string
header string
strong bool
want bool
}{
{name: "single comma tag", etag: `"a,b"`, header: `"a,b"`, want: true},
{name: "weak comma in list", etag: `"a,b"`, header: `"other", W/"a,b"`, want: true},
{name: "strong comma in list", etag: `"a,b"`, header: `"other", "a,b"`, strong: true, want: true},
{name: "weak client cannot match strongly", etag: `"a,b"`, header: `W/"a,b"`, strong: true},
{name: "weak stored tag cannot match strongly", etag: `W/"a,b"`, header: `"a,b"`, strong: true},
{name: "weak stored tag matches weakly", etag: `W/"a,b"`, header: `"a,b"`, want: true},
{name: "prefix is not a tag", etag: `"a"`, header: `"a,b"`},
{name: "suffix is not a tag", etag: `"b"`, header: `"a,b"`},
{name: "next tag after comma tag", etag: `"current"`, header: `"a,b", "current"`, want: true},
{name: "backslash is literal", etag: `"a\,b"`, header: `W/"a\,b", "other"`, want: true},
{name: "ordinary list", etag: `"current"`, header: `"old", "current"`, want: true},
{name: "bare tag compatibility", etag: `"current"`, header: `old, current`, want: true},
{name: "empty list elements", etag: `"a,b"`, header: `, , "a,b",`, want: true},
{name: "wildcard", etag: `"a,b"`, header: " * ", strong: true, want: true},
{name: "no stored validator", header: "*"},
{name: "empty header", etag: `"a,b"`},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
meta := &CachedObjectMeta{ETag: tt.etag}
if got := meta.MatchesETagHeader(tt.header, tt.strong); got != tt.want {
t.Errorf("MatchesETagHeader(%q, strong=%v) for %q = %v, want %v", tt.header, tt.strong, tt.etag, got, tt.want)
}
})
}
}

func TestMakeMetaKey(t *testing.T) {
expected := "meta|my-bucket|path/to/object.txt"
result := MakeMetaKey("my-bucket", "path/to/object.txt")
Expand Down
6 changes: 3 additions & 3 deletions docs/cache-control.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,15 @@ TAG supports RFC 7234-compliant cache revalidation. Clients can control caching
| ------------- | -------------------------------------------------------------------------------- |
| `HIT` | A cache entry was selected to serve the response (including revalidation that confirmed the object is unchanged) |
| `MISS` | Not in cache, fetched from upstream and now cached |
| `REVALIDATED` | Revalidated with upstream, object changed, new content returned |
| `REVALIDATED` | Revalidation found a changed object; client validators may still yield a bodyless 304 |
| `BYPASS` | Cache bypassed entirely (client requested `no-store`, or the request carries a representation selector: `versionId`, `partNumber`, `response-*`) |
| `DISABLED` | Caching is disabled server-side (`TAG_CACHE_DISABLED=true`) |

In block mode, a committed stream can recover missing bytes from an upstream range only after validating the cached ETag and exact range. Because `HIT` is committed before the body streams, it describes the cache-backed request, not each byte's source or whether the transfer completed. See [S3 compatibility](s3-compatibility.md#caching-behavior) for incomplete cache-range behavior.

## Force Revalidation

Send `Cache-Control: no-cache` or `Cache-Control: max-age=0` to force TAG to check with upstream before serving a cached object. TAG sends a conditional request using the cached ETag. If the object hasn't changed, upstream returns 304 and TAG serves from cache (`X-Cache: HIT`). If changed, TAG streams the new content (`X-Cache: REVALIDATED`).
Send `Cache-Control: no-cache` or `Cache-Control: max-age=0` to force TAG to check with upstream before serving a cached object. For GET, TAG sends a synthetic conditional request using the cached ETag. The origin reply checks cache freshness; TAG then evaluates the client's original validators against the confirmed representation. Multiple `If-None-Match` field values are treated as one comma-separated list, and `If-None-Match` takes precedence over `If-Modified-Since`. If they match, TAG returns a bodyless 304 without reading the cached body. Otherwise, an origin 304 serves the cached full object or requested range (`X-Cache: HIT`). If that 304 changes the cached ETag and the client still needs a body, TAG forwards the original request before committing so the body matches the new validator. An origin 200 or 206 returns the changed full or ranged response (`X-Cache: REVALIDATED`) unless the client's validator matches the new representation; in that case TAG returns a bodyless 304 while preserving the existing cache update or rewarm when eligible. This conditional-response behavior applies to GET; HEAD uses its separate revalidation path.

```bash
# Force revalidation on GET
Expand All @@ -30,7 +30,7 @@ curl -H "Cache-Control: no-cache" -H "Range: bytes=0-99" \
http://localhost:8080/my-bucket/my-key
```

If the revalidation request to upstream fails, TAG serves the stale cached copy as a fallback.
If the revalidation request to upstream fails, TAG serves the stale cached copy as a fallback. The client's validators are evaluated against that stale representation, but an origin failure remains a failed revalidation rather than a successful validation.

## Bypass Cache

Expand Down
4 changes: 2 additions & 2 deletions docs/s3-compatibility.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,15 +81,15 @@ TAG adds a caching layer for read operations. The `X-Cache` response header indi
| ---------- | -------------------------------------------------------- |
| `HIT` | A cache entry was selected to serve the request; block streams may also recover a verified upstream remainder |
| `MISS` | Fetched from Tigris and cached |
| `BYPASS` | Caching skipped (e.g., conditional request returned 304) |
| `BYPASS` | Caching skipped (e.g., `no-store` or a representation selector) |
| `DISABLED` | Caching is turned off |

Key caching behaviors:

- **Request coalescing** — Multiple concurrent GETs for the same object are coalesced into a single upstream fetch using a broadcast/subscriber pattern. For live requests, a fetch failure before response commitment returns TAG's existing S3 error response to waiting GETs; errors after commitment terminate the stream.
- **Range requests** — If the full object is cached, range requests are served from cache. On a range cache miss, the range is served directly from Tigris while a background fetch populates the cache with the full object.
- **Incomplete cached ranges** — TAG checks that a cached range supplies the requested byte count. A committed block GET can recover an unwritten suffix only when the upstream ETag and exact range match. `X-Cache: HIT` is committed before the body streams, so it describes the cache-backed request, not per-byte provenance or successful completion. If the ETag changes, TAG rejects the suffix without appending it; the already-sent 200 status and Content-Length remain, so the client may receive only the cached prefix while the handler reports an error. A whole-object cached Range response commits its 206 when the first nonempty cache chunk arrives and cannot restart upstream; a later positive short read returns a handler error while its 206 and Content-Length remain. Client write failures are not retried upstream.
- **Conditional requests** — `If-None-Match` and `If-Modified-Since` are evaluated against cached metadata and can return 304 without hitting Tigris.
- **Conditional requests** — On a normal cache hit, repeated `If-None-Match` fields are treated as one list and take precedence over `If-Modified-Since`; a match can return 304 from metadata. For GET, after successful forced revalidation, TAG checks the client's original validators against the origin-confirmed representation; a match returns a bodyless 304, while a mismatch keeps the full or ranged response path.
- **Write-through invalidation** — In proxy mode, PUT, DELETE, CopyObject, and DeleteObjects invalidate affected cache entries before forwarding. For cache-enabled DeleteObjects requests with a nonempty parsed key list, TAG completes an upstream 2xx only after the post-success invalidation attempts return, bounded by a 10-second fence timeout; a fence that does not converge in time is logged as a warning and the 2xx is still returned.
- **Tombstone protection** — A short-lived tombstone is written on DELETE to prevent in-flight background cache writes from resurrecting deleted objects.
- **Multipart completion replay** — A fully captured successful response is cached for five seconds when TAG can identify a caller. A replay must match the exact bucket, object key, and upload ID and pass local validation for the saved access key; transparent mode also checks the caller's current bucket authorization. Entries without a saved caller identity are treated as misses; other requests follow normal forwarding and authorization.
Expand Down
89 changes: 71 additions & 18 deletions proxy/get_object.go
Original file line number Diff line number Diff line change
Expand Up @@ -934,27 +934,80 @@ func (s *Service) handleRangeWithBackgroundCache(
return nil
}

// writeNotModifiedFromCache answers a conditional request with 304 when the
// cached entry satisfies the request's validators. Per RFC 7232 §3.3, a
// request carrying If-None-Match is judged by it ALONE — If-Modified-Since is
// ignored, matching or not: LastModified is second-granular, so falling back
// to it could 304 a client across a same-second overwrite it should see.
// Returns true when it wrote the response. Shared by the proxying GET hit
// path and the origin-less handler so the two cannot drift.
func (s *Service) writeNotModifiedFromCache(w http.ResponseWriter, r *http.Request, meta *cache.CachedObjectMeta, operation string, start time.Time) bool {
if inm := r.Header.Get("If-None-Match"); inm != "" {
if !meta.MatchesETagHeader(inm, false) {
return false
// clientIfNoneMatch combines repeated If-None-Match field values into the
// comma-separated list defined by the HTTP field. Empty field values do not
// replace a later nonempty validator.
func clientIfNoneMatch(r *http.Request) (string, bool) {
if r == nil {
return "", false
}
values := r.Header.Values("If-None-Match")
if len(values) == 0 {
return "", false
}
if len(values) == 1 {
if strings.TrimSpace(values[0]) == "" {
return "", false
}
} else {
ims := r.Header.Get("If-Modified-Since")
if ims == "" {
return false
return values[0], true
}

nonempty := make([]string, 0, len(values))
for _, value := range values {
if strings.TrimSpace(value) != "" {
nonempty = append(nonempty, value)
}
t, parseErr := http.ParseTime(ims)
if parseErr != nil || meta.IsModifiedSince(t) {
return false
}
switch len(nonempty) {
case 0:
return "", false
case 1:
return nonempty[0], true
default:
return strings.Join(nonempty, ","), true
}
}

// clientNotModified evaluates GET validators in RFC 7232 order. If-None-Match
// uses weak/list comparison and takes precedence over If-Modified-Since because
// Last-Modified is only second-granular.
func clientNotModified(r *http.Request, meta *cache.CachedObjectMeta) bool {
return clientNotModifiedWithWildcard(r, meta, false)
}

// revalidationClientNotModified also handles If-None-Match: * when the current
// upstream representation has no ETag. The revalidation response itself proves
// that this representation exists; CachedObjectMeta's ETag matcher cannot infer
// existence from an empty validator.
func revalidationClientNotModified(r *http.Request, meta *cache.CachedObjectMeta) bool {
return clientNotModifiedWithWildcard(r, meta, true)
}

func clientNotModifiedWithWildcard(r *http.Request, meta *cache.CachedObjectMeta, wildcardMatchesExisting bool) bool {
if r == nil || meta == nil {
return false
}
if inm, ok := clientIfNoneMatch(r); ok {
if wildcardMatchesExisting && strings.TrimSpace(inm) == "*" {
return true
}
return meta.MatchesETagHeader(inm, false)
}
ims := r.Header.Get("If-Modified-Since")
if ims == "" {
return false
}
t, parseErr := http.ParseTime(ims)
return parseErr == nil && !meta.IsModifiedSince(t)
}

// writeNotModifiedFromCache answers a conditional request with 304 when the
// cached entry satisfies the client's validators. Returns true when it wrote
// the response. Shared by the proxying GET hit path and the origin-less handler
// so the two cannot drift.
func (s *Service) writeNotModifiedFromCache(w http.ResponseWriter, r *http.Request, meta *cache.CachedObjectMeta, operation string, start time.Time) bool {
if !clientNotModified(r, meta) {
return false
}
writeCacheStatus(w, XCacheHit)
w.Header().Set("ETag", meta.ETag)
Expand Down
Loading
Loading