Skip to content

PostgreSQL backup tool with Point-In-Time-Recovery and restore verification

FEATURE (runtime): Replace Valkey with local providers

Rostislav Duginbda723759975
diff --git a/.agents/skills/humanizer/SKILL.md b/.agents/skills/humanizer/SKILL.md
index e568523f..c06b67fb 100644
--- a/.agents/skills/humanizer/SKILL.md
+++ b/.agents/skills/humanizer/SKILL.md
@@ -9,7 +9,7 @@ description: |
voice, negative parallelisms, and filler phrases.
license: MIT
metadata:
- version: "2.10.0"
+ version: "2.10.1"
---
# Humanizer: Remove AI Writing Patterns
@@ -381,6 +381,10 @@ Before delivering text, ask of each noun: "Where can the reader find what this m
This rule applies to all prose, including chat responses, not only repository documents.
+### 35. Oxford commas
+
+**Rule:** Do not put a comma before the coordinating conjunction in a list of three or more items. Write "red, white and blue," not "red, white, and blue." Restructure the sentence if omitting the comma would make the list ambiguous. Preserve punctuation in quotations, code and user-provided text unless the user asks to edit it.
+
## DETECTION GUIDANCE
### What NOT to flag (false positives)
diff --git a/.env.example b/.env.example
index dafc0b69..07fcd489 100644
--- a/.env.example
+++ b/.env.example
@@ -17,13 +17,6 @@ GOOSE_DRIVER=postgres
GOOSE_DBSTRING=postgres://postgres:Q1234567@localhost:5437/databasus?sslmode=disable
GOOSE_TEST_DBSTRING=postgres://postgres:Q1234567@localhost:5438/databasus?sslmode=disable
-# valkey
-VALKEY_HOST=127.0.0.1
-VALKEY_PORT=6379
-VALKEY_USERNAME=
-VALKEY_PASSWORD=
-VALKEY_IS_SSL=false
-
# logging (see example values at https://databasus.com/advanced-config/#log-shipping)
LOG_LEVEL=info
LOG_FILE_IS_ENABLED=true
diff --git a/.github/workflows/ci-release.yml b/.github/workflows/ci-release.yml
index 9b6c8235..e34e3335 100644
--- a/.github/workflows/ci-release.yml
+++ b/.github/workflows/ci-release.yml
@@ -43,7 +43,7 @@ jobs:
- name: Install golangci-lint
run: |
go install github.com/golangci/golangci-lint/v2/cmd/[email protected]
- echo "$(go env GOPATH)/bin" >> $GITHUB_PATH
+ echo "$(go env GOPATH)/bin" >> "$GITHUB_PATH"
- name: Install swag for swagger generation
run: go install github.com/swaggo/swag/cmd/[email protected]
@@ -182,7 +182,7 @@ jobs:
- name: Install golangci-lint
run: |
go install github.com/golangci/golangci-lint/v2/cmd/[email protected]
- echo "$(go env GOPATH)/bin" >> $GITHUB_PATH
+ echo "$(go env GOPATH)/bin" >> "$GITHUB_PATH"
- name: Run golangci-lint
run: |
@@ -293,11 +293,6 @@ jobs:
# Wait for test database (postgres listens on 5432 inside the container)
timeout 60 bash -c 'until docker exec backend-db-test pg_isready -U postgres; do sleep 2; done'
- # Wait for Valkey (cache)
- echo "Waiting for Valkey..."
- timeout 60 bash -c 'until docker exec backend-valkey valkey-cli ping 2>/dev/null | grep -q PONG; do sleep 2; done'
- echo "Valkey is ready!"
-
# 5004 = shared logical-postgres-16 fixture; 5007-5008 = shared physical-postgres 17/18
# primary sources. The per-version, no-summary, tablespace, mTLS and restore-target
# physical containers — like the per-version logical PG tests — run on testcontainers and
@@ -319,10 +314,11 @@ jobs:
run: |
cd backend
go install github.com/pressly/goose/v3/cmd/[email protected]
- export PATH="$(go env GOPATH)/bin:$PATH"
+ go_binary_directory="$(go env GOPATH)/bin"
+ export PATH="${go_binary_directory}:${PATH}"
set -a && . ../.env && set +a
- # cleanup_test_db creates databasus_w0..w{workers-1}, flushes Valkey, and
- # resets the test PG containers. Then migrate each slot DB so every
+ # cleanup_test_db creates databasus_w0..w{workers-1} and resets the test PG
+ # containers. Then migrate each slot DB so every
# parallel `go test` worker connects to a migrated metadata DB.
go run ./cmd/cleanup_test_db
for i in $(seq 0 $((TEST_PARALLEL_WORKERS - 1))); do
@@ -339,8 +335,8 @@ jobs:
# Ryuk stays disabled to match backend/Makefile's `test` target, so CI and local runs
# share one code path.
TESTCONTAINERS_RYUK_DISABLED: "true"
- # Each package runs in its own metadata DB + Valkey logical DB, so
- # packages run in parallel; -p must equal the provisioned worker count.
+ # Each package runs in its own metadata DB, so packages run in parallel.
+ # -p must equal the provisioned worker count.
TEST_PARALLEL_WORKERS: "8"
run: |
cd backend
@@ -738,7 +734,7 @@ jobs:
id: current_version
run: |
LATEST_TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo "v0.0.0")
- echo "current_version=${LATEST_TAG#v}" >> $GITHUB_OUTPUT
+ echo "current_version=${LATEST_TAG#v}" >> "$GITHUB_OUTPUT"
echo "Current version: ${LATEST_TAG#v}"
- name: Analyze commits and determine version bump
@@ -752,7 +748,7 @@ jobs:
if [ "$LATEST_TAG" = "v0.0.0" ]; then
COMMITS=$(git log --pretty=format:"%s" --no-merges)
else
- COMMITS=$(git log ${LATEST_TAG}..HEAD --pretty=format:"%s" --no-merges)
+ COMMITS=$(git log "${LATEST_TAG}..HEAD" --pretty=format:"%s" --no-merges)
fi
echo "Analyzing commits:"
@@ -794,15 +790,15 @@ jobs:
BUMP_TYPE="none"
fi
- echo "bump_type=$BUMP_TYPE" >> $GITHUB_OUTPUT
+ echo "bump_type=$BUMP_TYPE" >> "$GITHUB_OUTPUT"
if [ "$BUMP_TYPE" != "none" ]; then
NEW_VERSION=$(npx semver -i $BUMP_TYPE $CURRENT_VERSION)
- echo "new_version=$NEW_VERSION" >> $GITHUB_OUTPUT
- echo "should_release=true" >> $GITHUB_OUTPUT
+ echo "new_version=$NEW_VERSION" >> "$GITHUB_OUTPUT"
+ echo "should_release=true" >> "$GITHUB_OUTPUT"
echo "New version will be: $NEW_VERSION"
else
- echo "should_release=false" >> $GITHUB_OUTPUT
+ echo "should_release=false" >> "$GITHUB_OUTPUT"
echo "No version bump needed"
fi
@@ -1053,7 +1049,7 @@ jobs:
if [ "$LATEST_TAG" = "v0.0.0" ]; then
COMMITS=$(git log --pretty=format:"%s|%H|%an|%ad" --date=short --no-merges)
else
- COMMITS=$(git log ${LATEST_TAG}..HEAD --pretty=format:"%s|%H|%an|%ad" --date=short --no-merges)
+ COMMITS=$(git log "${LATEST_TAG}..HEAD" --pretty=format:"%s|%H|%an|%ad" --date=short --no-merges)
fi
# Build the changelog with real newlines (NL) instead of \n literals
@@ -1081,24 +1077,33 @@ jobs:
TEMP="${COMMIT_MSG#FEATURE}"
TEMP="${TEMP#"${TEMP%%[![:space:]]*}"}"
if [[ "$TEMP" == \(* ]]; then
- AREA=$(echo "$TEMP" | sed 's/^(\([^)]*\)).*/\1/')
- DESC=$(echo "$TEMP" | sed 's/^([^)]*):[[:space:]]*//')
+ AREA="${TEMP%%)*}"
+ AREA="${AREA#(}"
+ DESC="${TEMP#*)}"
+ DESC="${DESC#:}"
+ DESC="${DESC#"${DESC%%[![:space:]]*}"}"
FEATURES="${FEATURES}- **${AREA}**: ${DESC} ([${SHORT_HASH}](https://github.com/${{ github.repository }}/commit/${COMMIT_HASH}))${NL}"
fi
elif [[ "$COMMIT_MSG" == FIX* ]]; then
TEMP="${COMMIT_MSG#FIX}"
TEMP="${TEMP#"${TEMP%%[![:space:]]*}"}"
if [[ "$TEMP" == \(* ]]; then
- AREA=$(echo "$TEMP" | sed 's/^(\([^)]*\)).*/\1/')
- DESC=$(echo "$TEMP" | sed 's/^([^)]*):[[:space:]]*//')
+ AREA="${TEMP%%)*}"
+ AREA="${AREA#(}"
+ DESC="${TEMP#*)}"
+ DESC="${DESC#:}"
+ DESC="${DESC#"${DESC%%[![:space:]]*}"}"
FIXES="${FIXES}- **${AREA}**: ${DESC} ([${SHORT_HASH}](https://github.com/${{ github.repository }}/commit/${COMMIT_HASH}))${NL}"
fi
elif [[ "$COMMIT_MSG" == REFACTOR* ]]; then
TEMP="${COMMIT_MSG#REFACTOR}"
TEMP="${TEMP#"${TEMP%%[![:space:]]*}"}"
if [[ "$TEMP" == \(* ]]; then
- AREA=$(echo "$TEMP" | sed 's/^(\([^)]*\)).*/\1/')
- DESC=$(echo "$TEMP" | sed 's/^([^)]*):[[:space:]]*//')
+ AREA="${TEMP%%)*}"
+ AREA="${AREA#(}"
+ DESC="${TEMP#*)}"
+ DESC="${DESC#:}"
+ DESC="${DESC#"${DESC%%[![:space:]]*}"}"
REFACTORS="${REFACTORS}- **${AREA}**: ${DESC} ([${SHORT_HASH}](https://github.com/${{ github.repository }}/commit/${COMMIT_HASH}))${NL}"
fi
fi
diff --git a/.gitignore b/.gitignore
index 8fc25a46..c2b0f66b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -5,7 +5,6 @@ pgdata/
pgdata-test/
mysqldata/
mariadbdata/
-valkey-data/
victoria-logs-data/
wal-queue/
temp/
diff --git a/Dockerfile b/Dockerfile
index 0df2fa7a..33510ca4 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -110,15 +110,14 @@ ENV CONTAINER_ARCH=$TARGETARCH
ENV ENV_MODE=production
# ========= Install all apt packages in a single layer =========
-# Base packages + PostgreSQL 17 (pgdg repo) + Valkey (greensec repo) + rclone, in
-# one RUN to minimise layer count and cache-export overhead.
+# Base packages, PostgreSQL 17 and rclone share one RUN to minimise layer count
+# and cache-export overhead.
#
# - wget: build-only — fetches the repo signing keys, then purged at the end of
# this RUN (see the "minimal attack surface" note on the runtime stage above).
# - Repo keys: scoped signed-by keyrings, not the deprecated global apt-key trust
# store, so a compromised repo key cannot vouch for any other repository.
# - Codename: hardcoded "bookworm" (base image is pinned), so no lsb-release.
-# - Valkey: bound to localhost only — never exposed outside the container.
# - Default cluster: the app runs its own cluster from /databasus-data/pgdata, so
# the one the package creates at 17/main is never read. Dropped inside this RUN
# so its data files never reach a layer; the server binaries under
@@ -132,12 +131,8 @@ RUN set -eux; \
wget -qO /usr/share/keyrings/pgdg.asc https://www.postgresql.org/media/keys/ACCC4CF8.asc; \
echo "deb [signed-by=/usr/share/keyrings/pgdg.asc] http://apt.postgresql.org/pub/repos/apt bookworm-pgdg main" \
> /etc/apt/sources.list.d/pgdg.list; \
- wget -qO /usr/share/keyrings/greensec.github.io-valkey-debian.key \
- https://greensec.github.io/valkey-debian/public.key; \
- echo "deb [signed-by=/usr/share/keyrings/greensec.github.io-valkey-debian.key] https://greensec.github.io/valkey-debian/repo bookworm main" \
- > /etc/apt/sources.list.d/valkey-debian.list; \
apt-get update; \
- apt-get install -y --no-install-recommends postgresql-17 valkey; \
+ apt-get install -y --no-install-recommends postgresql-17; \
pg_dropcluster --stop 17 main; \
apt-get purge -y --auto-remove wget; \
rm -rf /var/lib/apt/lists/*
diff --git a/adr/0006-cloud-load-and-traffic-distribution-between-nodes.md b/adr/0006-cloud-load-and-traffic-distribution-between-nodes.md
index da929228..bf6003e2 100644
--- a/adr/0006-cloud-load-and-traffic-distribution-between-nodes.md
+++ b/adr/0006-cloud-load-and-traffic-distribution-between-nodes.md
@@ -61,3 +61,9 @@ A per-user lock caps each user to one in-flight operation of each kind so one te
## References
- [ADR-0004](./0004-focus-on-streaming-chunk-by-chunk-with-backpressure.md) — chunk-streaming with backpressure (the memory-safety foundation this scheduling sits on top of).
+
+## Replacement note (2026-09-06)
+
+Databasus now supports one application process per installation. Valkey-backed runtime state was
+replaced by a process-local cache, publish-subscribe provider and rate-limiting provider. The
+multi-node coordination decision above remains as historical context.
diff --git a/adr/0013-reuse-shared-in-memory-test-databases.md b/adr/0013-reuse-shared-in-memory-test-databases.md
index 9e118018..728e4c30 100644
--- a/adr/0013-reuse-shared-in-memory-test-databases.md
+++ b/adr/0013-reuse-shared-in-memory-test-databases.md
@@ -129,3 +129,9 @@ pub/sub channels.
- `backend/internal/config/config.go` (`applyTestWorkerSlot` / `claimTestWorkerSlot`)
- `backend/internal/features/backups/backups/backuping/nodes/registry.go`
- `backend/Makefile`
+
+## Replacement note (2026-09-06)
+
+Valkey-backed test state was replaced by a process-local cache, publish-subscribe provider and
+rate-limiting provider. Each test binary now owns that transient state. Worker slots still isolate
+the shared metadata databases.
diff --git a/backend/cmd/cleanup_test_db/main.go b/backend/cmd/cleanup_test_db/main.go
index e1117688..5ae843d0 100644
--- a/backend/cmd/cleanup_test_db/main.go
+++ b/backend/cmd/cleanup_test_db/main.go
@@ -30,7 +30,6 @@ import (
gormLogger "gorm.io/gorm/logger"
"databasus-backend/internal/config"
- cache_utils "databasus-backend/internal/util/cache"
"databasus-backend/internal/util/logger"
)
@@ -51,11 +50,6 @@ func main() {
os.Exit(1)
}
- if err := resetValkey(log); err != nil {
- log.Error("failed to reset Valkey", "error", err)
- os.Exit(1)
- }
-
if err := resetMetadataDb(log, env); err != nil {
log.Error("failed to reset metadata DB", "error", err)
os.Exit(1)
@@ -67,22 +61,6 @@ func main() {
}
}
-// resetValkey wipes every key so each `make test` starts from a clean cache.
-// Without this, a -failfast'd previous run can leave in-flight backup claims and
-// other state that breaks the next run's scheduler assumptions.
-func resetValkey(log *slog.Logger) error {
- log.Info("resetting Valkey")
-
- // FLUSHALL, not ClearAllCache: parallel test workers each use their own Valkey
- // logical DB (0..pool-1), so a per-DB clear would leave the others dirty.
- if err := cache_utils.FlushAll(); err != nil {
- return fmt.Errorf("flush cache: %w", err)
- }
-
- log.Info("valkey reset complete")
- return nil
-}
-
// resetMetadataDb drops and recreates the metadata DB for every test worker slot
// (databasus_test_w0 .. databasus_test_w{pool-1}). Tests run with `go test -p`,
// each binary claiming one slot DB; provisioning all of them up front lets the
diff --git a/backend/cmd/main.go b/backend/cmd/main.go
index 19a9ca45..167c7593 100644
--- a/backend/cmd/main.go
+++ b/backend/cmd/main.go
@@ -52,7 +52,6 @@ import (
verification_runs "databasus-backend/internal/features/verification/runs"
workspaces_controllers "databasus-backend/internal/features/workspaces/controllers"
"databasus-backend/internal/middleware"
- cache_utils "databasus-backend/internal/util/cache"
env_utils "databasus-backend/internal/util/env"
files_utils "databasus-backend/internal/util/files"
"databasus-backend/internal/util/logger"
@@ -89,20 +88,10 @@ func main() {
return
}
- cache_utils.TestCacheConnection()
-
- log.Info("clearing cache")
-
- err := cache_utils.ClearAllCache()
- if err != nil {
- log.Error("failed to clear cache", "error", err)
- logger.ExitAfterFlush(1)
- }
-
runMigrations(log)
// create directories that used for backups and restore
- err = files_utils.EnsureDirectories([]string{
+ err := files_utils.EnsureDirectories([]string{
config.GetEnv().TempFolder,
config.GetEnv().DataFolder,
})
diff --git a/backend/go.mod b/backend/go.mod
index 62790a02..7da30c0b 100644
--- a/backend/go.mod
+++ b/backend/go.mod
@@ -27,7 +27,6 @@ require (
github.com/swaggo/gin-swagger v1.6.0
github.com/swaggo/swag v1.16.4
github.com/testcontainers/testcontainers-go v0.42.0
- github.com/valkey-io/valkey-go v1.0.70
go.mongodb.org/mongo-driver v1.17.9
go.opentelemetry.io/contrib/bridges/otelslog v0.20.0
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.21.0
@@ -176,6 +175,8 @@ require (
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/ncw/swift/v2 v2.0.5 // indirect
github.com/oklog/ulid v1.3.1 // indirect
+ github.com/onsi/ginkgo/v2 v2.25.3 // indirect
+ github.com/onsi/gomega v1.38.3 // indirect
github.com/opencontainers/go-digest v1.0.0 // indirect
github.com/opencontainers/image-spec v1.1.1 // indirect
github.com/oracle/oci-go-sdk/v65 v65.111.0 // indirect
diff --git a/backend/go.sum b/backend/go.sum
index d7c5bc10..44e5bed1 100644
--- a/backend/go.sum
+++ b/backend/go.sum
@@ -78,8 +78,8 @@ github.com/IBM/go-sdk-core/v5 v5.21.2 h1:mJ5QbLPOm4g5qhZiVB6wbSllfpeUExftGoyPek2
github.com/IBM/go-sdk-core/v5 v5.21.2/go.mod h1:ngpMgwkjur1VNUjqn11LPk3o5eCyOCRbcfg/0YAY7Hc=
github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc=
github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE=
-github.com/Masterminds/semver/v3 v3.2.0 h1:3MEsd0SM6jqZojhjLWWeBY+Kcjy9i6MQAeY7YgDP83g=
-github.com/Masterminds/semver/v3 v3.2.0/go.mod h1:qvl/7zhW3nngYb5+80sSMF+FG2BjYrf8m9wsX0PNOMQ=
+github.com/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1Xbatp0=
+github.com/Masterminds/semver/v3 v3.4.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM=
github.com/Max-Sum/base32768 v0.0.0-20230304063302-18e6ce5945fd h1:nzE1YQBdx1bq9IlZinHa+HVffy+NmVRoKr+wHN8fpLE=
github.com/Max-Sum/base32768 v0.0.0-20230304063302-18e6ce5945fd/go.mod h1:C8yoIfvESpM3GD07OCHU7fqI7lhwyZ2Td1rbNbTAhnc=
github.com/Microsoft/go-winio v0.5.2/go.mod h1:WpS1mjBmmwHBEWmogvA2mj8546UReBk4v8QkMxJ6pZY=
@@ -406,8 +406,8 @@ github.com/google/pprof v0.0.0-20200212024743-f11f1df84d12/go.mod h1:ZgVRPoUq/hf
github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM=
github.com/google/pprof v0.0.0-20200430221834-fc25d7d30c6d/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM=
github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM=
-github.com/google/pprof v0.0.0-20240509144519-723abb6459b7 h1:velgFPYr1X9TDwLIfkV7fWqsFlf7TeP11M/7kPd/dVI=
-github.com/google/pprof v0.0.0-20240509144519-723abb6459b7/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw=
+github.com/google/pprof v0.0.0-20250403155104-27863c87afa6 h1:BHT72Gu3keYf3ZEu2J0b1vyeLSOYI8bm5wbJM/8yDe8=
+github.com/google/pprof v0.0.0-20250403155104-27863c87afa6/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0=
github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM=
@@ -593,8 +593,8 @@ github.com/oklog/ulid v1.3.1 h1:EGfNDEx6MqHz8B3uNV6QAib1UR2Lm97sHi3ocA6ESJ4=
github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U=
github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE=
github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU=
-github.com/onsi/ginkgo/v2 v2.17.3 h1:oJcvKpIb7/8uLpDDtnQuf18xVnwKp8DTD7DQ6gTd/MU=
-github.com/onsi/ginkgo/v2 v2.17.3/go.mod h1:nP2DPOQoNsQmsVyv5rDA8JkXQoCs6goXIvr/PRJ1eCc=
+github.com/onsi/ginkgo/v2 v2.25.3 h1:Ty8+Yi/ayDAGtk4XxmmfUy4GabvM+MegeB4cDLRi6nw=
+github.com/onsi/ginkgo/v2 v2.25.3/go.mod h1:43uiyQC4Ed2tkOzLsEYm7hnrb7UJTWHYNsuy3bG/snE=
github.com/onsi/gomega v1.38.3 h1:eTX+W6dobAYfFeGC2PV6RwXRu/MyT+cQguijutvkpSM=
github.com/onsi/gomega v1.38.3/go.mod h1:ZCU1pkQcXDO5Sl9/VVEGlDyp+zm0m1cmeG5TOzLgdh4=
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
@@ -728,8 +728,6 @@ github.com/ulikunitz/xz v0.5.15 h1:9DNdB5s+SgV3bQ2ApL10xRc35ck0DuIX/isZvIk+ubY=
github.com/ulikunitz/xz v0.5.15/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=
github.com/unknwon/goconfig v1.0.0 h1:rS7O+CmUdli1T+oDm7fYj1MwqNWtEJfNj+FqcUHML8U=
github.com/unknwon/goconfig v1.0.0/go.mod h1:qu2ZQ/wcC/if2u32263HTVC39PeOQRSmidQk3DuDFQ8=
-github.com/valkey-io/valkey-go v1.0.70 h1:mjYNT8qiazxDAJ0QNQ8twWT/YFOkOoRd40ERV2mB49Y=
-github.com/valkey-io/valkey-go v1.0.70/go.mod h1:VGhZ6fs68Qrn2+OhH+6waZH27bjpgQOiLyUQyXuYK5k=
github.com/wk8/go-ordered-map/v2 v2.1.8 h1:5h/BUHu93oj4gIdvHHHGsScSTMijfx5PeYkE/fJgbpc=
github.com/wk8/go-ordered-map/v2 v2.1.8/go.mod h1:5nJHM5DyteebpVlHnWMV0rPz6Zp7+xBAnxjb1X5vnTw=
github.com/xanzy/ssh-agent v0.3.3 h1:+/15pJfg/RsTxqYcX6fHqOXZwwMP+2VyYWJeWM2qQFM=
@@ -800,6 +798,8 @@ go.opentelemetry.io/otel/trace v1.45.0 h1:l/mP6Uv7oNO7/TblbhpbgMidxhq1uO/rPsikOy
go.opentelemetry.io/otel/trace v1.45.0/go.mod h1:qoJJA2xNMnxRrdISU/kLtfUH2wNeQbiv+jhs/CxI8bc=
go.opentelemetry.io/proto/otlp v1.11.0 h1:5rrYs0Ykyj50sdU/JU0x8etU+LubXWb+gED6TbEdMIk=
go.opentelemetry.io/proto/otlp v1.11.0/go.mod h1:SmVizdCOAm3XBtG1g1NnOdhW6jtddT72hLMhv8VwA8E=
+go.uber.org/automaxprocs v1.6.0 h1:O3y2/QNTOdbF+e/dpXNNW7Rx2hZ4sTIPyybbxyNqTUs=
+go.uber.org/automaxprocs v1.6.0/go.mod h1:ifeIMSnPZuznNm6jmdzmU3/bfk01Fe2fotchwEFJ8r8=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0=
diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go
index 892f5428..e6c5e57e 100644
--- a/backend/internal/config/config.go
+++ b/backend/internal/config/config.go
@@ -27,10 +27,8 @@ const (
)
const (
- // defaultTestParallelWorkers is the number of parallel test workers, used
- // when TEST_PARALLEL_WORKERS is unset. Each worker gets its own metadata DB
- // and Valkey logical DB, so this must stay <= 16 (Valkey's default logical DB
- // count) and equal to the `go test -p` value.
+ // defaultTestParallelWorkers must equal the `go test -p` value so every running package can
+ // claim an isolated metadata database.
defaultTestParallelWorkers = 8
// testSlotAdvisoryLockBase is the first pg_advisory_lock key reserved for
@@ -51,22 +49,7 @@ type EnvVariables struct {
DatabaseDsn string `env:"DATABASE_DSN" required:"true"`
TestDatabaseDsn string `env:"TEST_DATABASE_DSN"`
TestParallelWorkers int `env:"TEST_PARALLEL_WORKERS"`
- // Internal Valkey
- ValkeyHost string `env:"VALKEY_HOST" required:"true"`
- ValkeyPort string `env:"VALKEY_PORT" required:"true"`
- ValkeyUsername string `env:"VALKEY_USERNAME"`
- ValkeyPassword string `env:"VALKEY_PASSWORD"`
- ValkeyIsSsl bool `env:"VALKEY_IS_SSL" required:"true"`
-
- // Per-worker test isolation (computed, only set under `go test`): each test
- // binary claims a slot 0..TestParallelWorkers-1 that selects its own metadata DB
- // (DatabaseDsn is rewritten to dbname=<base>_w{slot}), its own Valkey logical
- // DB (ValkeySelectDB), and a cache-key namespace ("w{slot}:"). All zero/empty in
- // production.
- ValkeySelectDB int
- CacheNamespace string
-
- TestLocalhost string `env:"TEST_LOCALHOST"`
+ TestLocalhost string `env:"TEST_LOCALHOST"`
ShowDbInstallationVerificationLogs bool `env:"SHOW_DB_INSTALLATION_VERIFICATION_LOGS"`
@@ -185,9 +168,9 @@ func loadEnvVariables() {
// Only a real `go test` binary claims a per-worker slot; the cleanup_test_db
// command and any other tool run with IsTesting=true must operate on all
- // slots, so they keep the base test DSN and default Valkey DB.
+ // slots, so they keep the base test DSN.
if strings.Contains(os.Args[0], ".test") {
- applyTestWorkerSlot()
+ claimTestWorkerSlotAndSelectMetadataDatabase()
}
}
@@ -212,16 +195,6 @@ func loadEnvVariables() {
env.TestLocalhost = "localhost"
}
- // Valkey
- if env.ValkeyHost == "" {
- log.Error("VALKEY_HOST is empty")
- logger.ExitAfterFlush(1)
- }
- if env.ValkeyPort == "" {
- log.Error("VALKEY_PORT is empty")
- logger.ExitAfterFlush(1)
- }
-
// Store the data and temp folders one level below the root
// (projectRoot/databasus-data -> /databasus-data)
env.DataFolder = filepath.Join(filepath.Dir(backendRoot), "databasus-data", "backups")
@@ -283,10 +256,7 @@ func isTestProcess(arguments []string) bool {
//nolint:unused // assigned-only: keeps the advisory-lock connection alive for the process lifetime
var slotLockConn *sql.Conn
-// applyTestWorkerSlot claims a free slot for this test binary and rewrites the
-// env so the worker runs fully isolated: its own metadata DB, Valkey logical DB,
-// and registry namespace.
-func applyTestWorkerSlot() {
+func claimTestWorkerSlotAndSelectMetadataDatabase() {
baseDbName, _, err := RewriteDbName(env.TestDatabaseDsn, systemDbName)
if err != nil {
log.Error("could not parse TEST_DATABASE_DSN for slot isolation", "error", err)
@@ -303,8 +273,6 @@ func applyTestWorkerSlot() {
}
env.DatabaseDsn = slotDsn
- env.ValkeySelectDB = slot
- env.CacheNamespace = fmt.Sprintf("w%d:", slot)
log.Info("claimed test worker slot", "slot", slot, "db", slotDbName)
}
diff --git a/backend/internal/features/backups/backups/backuping/logical/backuper.go b/backend/internal/features/backups/backups/backuping/logical/backuper.go
index 1b288340..333cd5af 100644
--- a/backend/internal/features/backups/backups/backuping/logical/backuper.go
+++ b/backend/internal/features/backups/backups/backuping/logical/backuper.go
@@ -26,16 +26,16 @@ import (
const partialBackupCleanupTimeout = 30 * time.Second
type Backuper struct {
- databaseService *databases.DatabaseService
- fieldEncryptor util_encryption.FieldEncryptor
- workspaceService *workspaces_services.WorkspaceService
- backupRepository *backups_core_logical.BackupRepository
- backupConfigService *backups_config_logical.BackupConfigService
- storageService *storages.StorageService
- notificationSender backups_core_logical.NotificationSender
- backupCancelManager *tasks_cancellation.TaskCancelManager
- logger *slog.Logger
- createBackupUseCase backups_core_logical.CreateBackupUsecase
+ databaseService *databases.DatabaseService
+ fieldEncryptor util_encryption.FieldEncryptor
+ workspaceService *workspaces_services.WorkspaceService
+ backupRepository *backups_core_logical.BackupRepository
+ backupConfigService *backups_config_logical.BackupConfigService
+ storageService *storages.StorageService
+ notificationSender backups_core_logical.NotificationSender
+ taskCancellationRegistry *tasks_cancellation.Registry
+ logger *slog.Logger
+ createBackupUseCase backups_core_logical.CreateBackupUsecase
}
func (b *Backuper) MakeBackup(ctx context.Context, backupID uuid.UUID, isCallNotifier bool) {
@@ -67,8 +67,8 @@ func (b *Backuper) MakeBackup(ctx context.Context, backupID uuid.UUID, isCallNot
// Detached from the caller so a finished HTTP request cannot cancel a running backup.
executionCtx, cancel := context.WithCancel(context.Background())
- b.backupCancelManager.RegisterTask(backup.ID, cancel)
- defer b.backupCancelManager.UnregisterTask(backup.ID)
+ b.taskCancellationRegistry.RegisterTask(backup.ID, cancel)
+ defer b.taskCancellationRegistry.UnregisterTask(backup.ID)
storage, err := b.storageService.GetStorageByID(executionCtx, *backupConfig.StorageID)
if err != nil {
diff --git a/backend/internal/features/backups/backups/backuping/logical/backuper_test.go b/backend/internal/features/backups/backups/backuping/logical/backuper_test.go
index fece528e..479d2eb4 100644
--- a/backend/internal/features/backups/backups/backuping/logical/backuper_test.go
+++ b/backend/internal/features/backups/backups/backuping/logical/backuper_test.go
@@ -20,12 +20,12 @@ import (
users_enums "databasus-backend/internal/features/users/enums"
users_testing "databasus-backend/internal/features/users/testing"
workspaces_testing "databasus-backend/internal/features/workspaces/testing"
- cache_utils "databasus-backend/internal/util/cache"
+ "databasus-backend/internal/util/cache"
util_logger "databasus-backend/internal/util/logger"
)
func Test_BackupExecuted_NotificationSent(t *testing.T) {
- cache_utils.ClearAllCache()
+ cache.GetStore().Clear(t.Context())
user := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleAdmin)
router := CreateTestRouter()
workspace := workspaces_testing.CreateTestWorkspace(t.Context(), "Test Workspace", user, router)
diff --git a/backend/internal/features/backups/backups/backuping/logical/di.go b/backend/internal/features/backups/backups/backuping/logical/di.go
index eeff84a4..1f4a7302 100644
--- a/backend/internal/features/backups/backups/backuping/logical/di.go
+++ b/backend/internal/features/backups/backups/backuping/logical/di.go
@@ -18,7 +18,10 @@ import (
var backupRepository = &backups_core_logical.BackupRepository{}
-var taskCancelManager = tasks_cancellation.GetTaskCancelManager()
+var (
+ taskCancellationRegistry = tasks_cancellation.GetRegistry()
+ taskCancellationRequester = tasks_cancellation.GetRequester()
+)
var backupCleaner = &BackupCleaner{
backupRepository,
@@ -38,7 +41,7 @@ var backuper = &Backuper{
backups_config_logical.GetBackupConfigService(),
storages.GetStorageService(),
notifiers.GetNotifierService(),
- taskCancelManager,
+ taskCancellationRegistry,
logger.GetLogger(),
usecases_logical.GetCreateBackupUsecase(),
}
@@ -46,7 +49,7 @@ var backuper = &Backuper{
var backupsScheduler = &BackupsScheduler{
backupRepository,
backups_config_logical.GetBackupConfigService(),
- taskCancelManager,
+ taskCancellationRequester,
databases.GetDatabaseService(),
time.Now().UTC(),
logger.GetLogger(),
diff --git a/backend/internal/features/backups/backups/backuping/logical/scheduler.go b/backend/internal/features/backups/backups/backuping/logical/scheduler.go
index 46eb9f3d..aff5e15f 100644
--- a/backend/internal/features/backups/backups/backuping/logical/scheduler.go
+++ b/backend/internal/features/backups/backups/backuping/logical/scheduler.go
@@ -25,10 +25,10 @@ const (
)
type BackupsScheduler struct {
- backupRepository *backups_core_logical.BackupRepository
- backupConfigService *backups_config_logical.BackupConfigService
- taskCancelManager *task_cancellation.TaskCancelManager
- databaseService *databases.DatabaseService
+ backupRepository *backups_core_logical.BackupRepository
+ backupConfigService *backups_config_logical.BackupConfigService
+ taskCancellationRequester *task_cancellation.Requester
+ databaseService *databases.DatabaseService
lastBackupTime time.Time
logger *slog.Logger
@@ -313,9 +313,9 @@ func (s *BackupsScheduler) failBackupsInProgress(ctx context.Context, logger *sl
}
for _, backup := range backupsInProgress {
- if err := s.taskCancelManager.CancelTask(backup.ID); err != nil {
+ if err := s.taskCancellationRequester.RequestCancellation(ctx, backup.ID); err != nil {
logger.ErrorContext(ctx,
- "failed to cancel backup via task cancel manager",
+ "failed to request backup cancellation",
"backup_id",
backup.ID,
"error",
diff --git a/backend/internal/features/backups/backups/backuping/logical/scheduler_test.go b/backend/internal/features/backups/backups/backuping/logical/scheduler_test.go
index 6fef48ae..11111731 100644
--- a/backend/internal/features/backups/backups/backuping/logical/scheduler_test.go
+++ b/backend/internal/features/backups/backups/backuping/logical/scheduler_test.go
@@ -18,7 +18,7 @@ import (
users_enums "databasus-backend/internal/features/users/enums"
users_testing "databasus-backend/internal/features/users/testing"
workspaces_testing "databasus-backend/internal/features/workspaces/testing"
- cache_utils "databasus-backend/internal/util/cache"
+ cache "databasus-backend/internal/util/cache"
"databasus-backend/internal/util/logger"
"databasus-backend/internal/util/period"
"databasus-backend/internal/util/testing/containers"
@@ -59,7 +59,7 @@ func Test_RunPendingBackups_ByDatabaseType_OnlySchedulesNonAgentManagedBackups(t
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
- cache_utils.ClearAllCache()
+ cache.GetStore().Clear(t.Context())
user := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleAdmin)
router := CreateTestRouter()
@@ -128,7 +128,7 @@ func Test_RunPendingBackups_ByDatabaseType_OnlySchedulesNonAgentManagedBackups(t
}
func Test_RunPendingBackups_WhenLastBackupWasYesterday_CreatesNewBackup(t *testing.T) {
- cache_utils.ClearAllCache()
+ cache.GetStore().Clear(t.Context())
// setup data
user := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleAdmin)
router := CreateTestRouter()
@@ -194,7 +194,7 @@ func Test_RunPendingBackups_WhenLastBackupWasYesterday_CreatesNewBackup(t *testi
}
func Test_RunPendingBackups_WhenLastBackupWasRecentlyCompleted_SkipsBackup(t *testing.T) {
- cache_utils.ClearAllCache()
+ cache.GetStore().Clear(t.Context())
// setup data
user := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleAdmin)
router := CreateTestRouter()
@@ -258,7 +258,7 @@ func Test_RunPendingBackups_WhenLastBackupWasRecentlyCompleted_SkipsBackup(t *te
}
func Test_RunPendingBackups_WhenLastBackupFailedAndRetriesDisabled_SkipsBackup(t *testing.T) {
- cache_utils.ClearAllCache()
+ cache.GetStore().Clear(t.Context())
// setup data
user := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleAdmin)
router := CreateTestRouter()
@@ -326,7 +326,7 @@ func Test_RunPendingBackups_WhenLastBackupFailedAndRetriesDisabled_SkipsBackup(t
}
func Test_RunPendingBackups_WhenLastBackupFailedAndRetriesEnabled_CreatesNewBackup(t *testing.T) {
- cache_utils.ClearAllCache()
+ cache.GetStore().Clear(t.Context())
// setup data
user := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleAdmin)
router := CreateTestRouter()
@@ -396,7 +396,7 @@ func Test_RunPendingBackups_WhenLastBackupFailedAndRetriesEnabled_CreatesNewBack
}
func Test_RunPendingBackups_WhenFailedBackupsExceedMaxRetries_SkipsBackup(t *testing.T) {
- cache_utils.ClearAllCache()
+ cache.GetStore().Clear(t.Context())
// setup data
user := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleAdmin)
router := CreateTestRouter()
@@ -467,7 +467,7 @@ func Test_RunPendingBackups_WhenFailedBackupsExceedMaxRetries_SkipsBackup(t *tes
}
func Test_RunPendingBackups_WhenBackupsDisabled_SkipsBackup(t *testing.T) {
- cache_utils.ClearAllCache()
+ cache.GetStore().Clear(t.Context())
user := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleAdmin)
router := CreateTestRouter()
workspace := workspaces_testing.CreateTestWorkspace(t.Context(), "Test Workspace", user, router)
@@ -528,7 +528,7 @@ func Test_RunPendingBackups_WhenBackupsDisabled_SkipsBackup(t *testing.T) {
}
func Test_FailBackupsInProgress_WhenSchedulerStarts_CancelsBackupsAndUpdatesStatus(t *testing.T) {
- cache_utils.ClearAllCache()
+ cache.GetStore().Clear(t.Context())
user := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleAdmin)
router := CreateTestRouter()
@@ -549,7 +549,7 @@ func Test_FailBackupsInProgress_WhenSchedulerStarts_CancelsBackupsAndUpdatesStat
notifiers.RemoveTestNotifier(notifier)
workspaces_testing.RemoveTestWorkspace(t.Context(), workspace, router)
- cache_utils.ClearAllCache()
+ cache.GetStore().Clear(t.Context())
}()
backupConfig, err := backups_config_logical.GetBackupConfigService().GetBackupConfigByDbId(database.ID)
@@ -635,7 +635,7 @@ func Test_FailBackupsInProgress_WhenSchedulerStarts_CancelsBackupsAndUpdatesStat
}
func Test_StartBackup_WhenBackupAlreadyInProgress_SkipsNewBackup(t *testing.T) {
- cache_utils.ClearAllCache()
+ cache.GetStore().Clear(t.Context())
user := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleAdmin)
router := CreateTestRouter()
workspace := workspaces_testing.CreateTestWorkspace(t.Context(), "Test Workspace", user, router)
@@ -702,7 +702,7 @@ func Test_StartBackup_WhenBackupAlreadyInProgress_SkipsNewBackup(t *testing.T) {
func Test_RunPendingBackups_WhenLastBackupFailedWithIsSkipRetry_SkipsBackupEvenWithRetriesEnabled(
t *testing.T,
) {
- cache_utils.ClearAllCache()
+ cache.GetStore().Clear(t.Context())
user := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleAdmin)
router := CreateTestRouter()
workspace := workspaces_testing.CreateTestWorkspace(t.Context(), "Test Workspace", user, router)
@@ -778,7 +778,7 @@ func Test_RunPendingBackups_WhenLastBackupFailedWithIsSkipRetry_SkipsBackupEvenW
}
func Test_StartBackup_When2BackupsStartedForDifferentDatabases_BothUseCasesAreCalled(t *testing.T) {
- cache_utils.ClearAllCache()
+ cache.GetStore().Clear(t.Context())
// Create mock tracking use case
mockUseCase := NewMockTrackingBackupUsecase()
diff --git a/backend/internal/features/backups/backups/backuping/logical/setup_test.go b/backend/internal/features/backups/backups/backuping/logical/setup_test.go
index d174230c..28bc5686 100644
--- a/backend/internal/features/backups/backups/backuping/logical/setup_test.go
+++ b/backend/internal/features/backups/backups/backuping/logical/setup_test.go
@@ -3,18 +3,8 @@ package backuping_logical
import (
"os"
"testing"
-
- cache_utils "databasus-backend/internal/util/cache"
)
-// TestMain wipes Valkey at the start of this package's test binary so the
-// scheduler/backuper subscriptions don't inherit leftover state from a
-// previous run that died before its deferred Unsubscribe fired (e.g. a
-// -failfast'd suite that exited mid-test).
func TestMain(m *testing.M) {
- if err := cache_utils.ClearAllCache(); err != nil {
- panic(err)
- }
-
os.Exit(m.Run())
}
diff --git a/backend/internal/features/backups/backups/backuping/logical/testing.go b/backend/internal/features/backups/backups/backuping/logical/testing.go
index 6b34680f..6c717875 100644
--- a/backend/internal/features/backups/backups/backuping/logical/testing.go
+++ b/backend/internal/features/backups/backups/backuping/logical/testing.go
@@ -21,7 +21,7 @@ import (
workspaces_services "databasus-backend/internal/features/workspaces/services"
workspaces_testing "databasus-backend/internal/features/workspaces/testing"
"databasus-backend/internal/storage"
- cache_utils "databasus-backend/internal/util/cache"
+ "databasus-backend/internal/util/cache"
"databasus-backend/internal/util/encryption"
"databasus-backend/internal/util/logger"
)
@@ -86,7 +86,7 @@ type BackupTestFixture struct {
func CreateBackupTestFixture(t *testing.T, workspaceName string) *BackupTestFixture {
t.Helper()
- if err := cache_utils.ClearAllCache(); err != nil {
+ if err := cache.GetStore().Clear(t.Context()); err != nil {
t.Fatalf("clear cache before backup fixture: %v", err)
}
@@ -151,7 +151,7 @@ func CreateTestBackuper() *Backuper {
backups_config_logical.GetBackupConfigService(),
storages.GetStorageService(),
notifiers.GetNotifierService(),
- taskCancelManager,
+ taskCancellationRegistry,
logger.GetLogger(),
usecases_logical.GetCreateBackupUsecase(),
}
@@ -166,7 +166,7 @@ func CreateTestBackuperWithUseCase(useCase backups_core_logical.CreateBackupUsec
backups_config_logical.GetBackupConfigService(),
storages.GetStorageService(),
notifiers.GetNotifierService(),
- taskCancelManager,
+ taskCancellationRegistry,
logger.GetLogger(),
useCase,
}
@@ -183,7 +183,7 @@ func CreateTestSchedulerWithBackuper(backuper *Backuper) *BackupsScheduler {
return &BackupsScheduler{
backupRepository,
backups_config_logical.GetBackupConfigService(),
- taskCancelManager,
+ taskCancellationRequester,
databases.GetDatabaseService(),
time.Now().UTC(),
logger.GetLogger(),
@@ -240,14 +240,7 @@ func WaitForBackupCompletion(
t.Logf("WaitForBackupCompletion: timeout waiting for backup to complete")
}
-// StartSchedulerForTest starts the BackupsScheduler in a goroutine for testing.
-// The scheduler subscribes to task completions and manages backup lifecycle.
-// Returns a context cancel function that should be deferred to stop the scheduler.
-//
-// PubSubManager.Subscribe handshakes with Valkey before returning, so we
-// don't need to sleep here waiting for the subscription to register. Poll
-// the scheduler's hasRun flag instead to be sure Run() has entered its
-// loop before the caller proceeds.
+// Polling hasRun prevents the caller from racing scheduler startup without relying on a timing delay.
func StartSchedulerForTest(t *testing.T, scheduler *BackupsScheduler) context.CancelFunc {
ctx, cancel := context.WithCancel(context.Background())
diff --git a/backend/internal/features/backups/backups/backuping/physical/backuper.go b/backend/internal/features/backups/backups/backuping/physical/backuper.go
index 376b916e..a8492246 100644
--- a/backend/internal/features/backups/backups/backuping/physical/backuper.go
+++ b/backend/internal/features/backups/backups/backuping/physical/backuper.go
@@ -32,21 +32,21 @@ import (
// PhysicalBackuper drives a FULL or INCR through the postgresql executor.
// The scheduler invokes MakeBackup directly in a goroutine.
type PhysicalBackuper struct {
- databaseService *databases.DatabaseService
- fieldEncryptor util_encryption.FieldEncryptor
- workspaceService *workspaces_services.WorkspaceService
- fullRepo *physical_repositories.PhysicalFullBackupRepository
- incrRepo *physical_repositories.PhysicalIncrementalBackupRepository
- inFlightRepo *physical_repositories.PhysicalInFlightBackupRepository
- historyRepo *physical_repositories.PhysicalWalHistoryRepository
- backupConfigService *backups_config_physical.BackupConfigService
- storageService *storages.StorageService
- notificationSender NotificationSender
- taskCancelManager *tasks_cancellation.TaskCancelManager
- secretKeyService *encryption_secrets.SecretKeyService
- logger *slog.Logger
- fullExecutor FullBackupExecutor
- incrExecutor IncrementalBackupExecutor
+ databaseService *databases.DatabaseService
+ fieldEncryptor util_encryption.FieldEncryptor
+ workspaceService *workspaces_services.WorkspaceService
+ fullRepo *physical_repositories.PhysicalFullBackupRepository
+ incrRepo *physical_repositories.PhysicalIncrementalBackupRepository
+ inFlightRepo *physical_repositories.PhysicalInFlightBackupRepository
+ historyRepo *physical_repositories.PhysicalWalHistoryRepository
+ backupConfigService *backups_config_physical.BackupConfigService
+ storageService *storages.StorageService
+ notificationSender NotificationSender
+ taskCancellationRegistry *tasks_cancellation.Registry
+ secretKeyService *encryption_secrets.SecretKeyService
+ logger *slog.Logger
+ fullExecutor FullBackupExecutor
+ incrExecutor IncrementalBackupExecutor
}
func (b *PhysicalBackuper) MakeBackup(ctx context.Context, backupID uuid.UUID, isCallNotifier bool) {
@@ -97,8 +97,8 @@ func (b *PhysicalBackuper) runFullBackup(
// Detached from the caller so a finished HTTP request cannot cancel a running backup; the
// caller's ctx stays in use for logging, which is what carries request_id and user_id.
executionCtx, cancel := context.WithCancel(context.Background())
- b.taskCancelManager.RegisterTask(fullBackup.ID, cancel)
- defer b.taskCancelManager.UnregisterTask(fullBackup.ID)
+ b.taskCancellationRegistry.RegisterTask(fullBackup.ID, cancel)
+ defer b.taskCancellationRegistry.UnregisterTask(fullBackup.ID)
rawSizeMb := b.getSourceClusterSizeMb(executionCtx, logger, backupCtx.Database)
@@ -193,8 +193,8 @@ func (b *PhysicalBackuper) runIncrementalBackup(
}
executionCtx, cancel := context.WithCancel(context.Background())
- b.taskCancelManager.RegisterTask(incrBackup.ID, cancel)
- defer b.taskCancelManager.UnregisterTask(incrBackup.ID)
+ b.taskCancellationRegistry.RegisterTask(incrBackup.ID, cancel)
+ defer b.taskCancellationRegistry.UnregisterTask(incrBackup.ID)
incrBackupSpec := postgresql_executor.IncrementalBackupSpec{
CommonBackupSpec: postgresql_executor.CommonBackupSpec{
diff --git a/backend/internal/features/backups/backups/backuping/physical/cancellation_listener.go b/backend/internal/features/backups/backups/backuping/physical/cancellation_listener.go
index c88ba9de..a35b8a4c 100644
--- a/backend/internal/features/backups/backups/backuping/physical/cancellation_listener.go
+++ b/backend/internal/features/backups/backups/backuping/physical/cancellation_listener.go
@@ -11,14 +11,14 @@ import (
)
type PhysicalBackupCancellationListener struct {
- canceller *PhysicalBackupCanceller
- walStreamerRepo *physical_repositories.PhysicalWalStreamerRepository
- taskCancelManager *tasks_cancellation.TaskCancelManager
- logger *slog.Logger
+ canceller *PhysicalBackupCanceller
+ walStreamerRepo *physical_repositories.PhysicalWalStreamerRepository
+ taskCancellationRequester *tasks_cancellation.Requester
+ logger *slog.Logger
}
func (l *PhysicalBackupCancellationListener) OnBackupsDisabled(ctx context.Context, databaseID uuid.UUID) {
- l.canceller.CancelInFlightForDatabase(databaseID)
+ l.canceller.CancelInFlightForDatabase(ctx, databaseID)
l.cancelStreamingAndDeleteStreamerRow(ctx, databaseID)
}
@@ -27,7 +27,7 @@ func (l *PhysicalBackupCancellationListener) OnWalStreamingDisabled(ctx context.
}
func (l *PhysicalBackupCancellationListener) OnBeforeDatabaseRemove(ctx context.Context, databaseID uuid.UUID) error {
- l.canceller.CancelInFlightForDatabase(databaseID)
+ l.canceller.CancelInFlightForDatabase(ctx, databaseID)
l.cancelStreamingAndDeleteStreamerRow(ctx, databaseID)
return nil
@@ -41,7 +41,7 @@ func (l *PhysicalBackupCancellationListener) cancelStreamingAndDeleteStreamerRow
) {
logger := l.logger.With("database_id", databaseID)
- if err := l.taskCancelManager.CancelTask(databaseID); err != nil {
+ if err := l.taskCancellationRequester.RequestCancellation(ctx, databaseID); err != nil {
logger.ErrorContext(ctx, "failed to cancel wal streamer task", "error", err)
}
diff --git a/backend/internal/features/backups/backups/backuping/physical/cancellation_listener_test.go b/backend/internal/features/backups/backups/backuping/physical/cancellation_listener_test.go
index faa7350c..a7778ae5 100644
--- a/backend/internal/features/backups/backups/backuping/physical/cancellation_listener_test.go
+++ b/backend/internal/features/backups/backups/backuping/physical/cancellation_listener_test.go
@@ -18,11 +18,11 @@ func newTestCancellationListener() *PhysicalBackupCancellationListener {
return &PhysicalBackupCancellationListener{
NewPhysicalBackupCanceller(
physical_repositories.GetInFlightBackupRepository(),
- tasks_cancellation.GetTaskCancelManager(),
+ tasks_cancellation.GetRequester(),
logger.GetLogger(),
),
physical_repositories.GetWalStreamerRepository(),
- tasks_cancellation.GetTaskCancelManager(),
+ tasks_cancellation.GetRequester(),
logger.GetLogger(),
}
}
diff --git a/backend/internal/features/backups/backups/backuping/physical/canceller.go b/backend/internal/features/backups/backups/backuping/physical/canceller.go
index 7374a7c9..ccedf104 100644
--- a/backend/internal/features/backups/backups/backuping/physical/canceller.go
+++ b/backend/internal/features/backups/backups/backuping/physical/canceller.go
@@ -1,6 +1,7 @@
package backuping_physical
import (
+ "context"
"log/slog"
"github.com/google/uuid"
@@ -16,28 +17,28 @@ import (
// listener, the database-remove listener, and the user-facing cancel/delete
// endpoints.
type PhysicalBackupCanceller struct {
- inFlightRepo *physical_repositories.PhysicalInFlightBackupRepository
- taskCancelManager *tasks_cancellation.TaskCancelManager
- logger *slog.Logger
+ inFlightRepo *physical_repositories.PhysicalInFlightBackupRepository
+ taskCancellationRequester *tasks_cancellation.Requester
+ logger *slog.Logger
}
func NewPhysicalBackupCanceller(
inFlightRepo *physical_repositories.PhysicalInFlightBackupRepository,
- taskCancelManager *tasks_cancellation.TaskCancelManager,
+ taskCancellationRequester *tasks_cancellation.Requester,
logger *slog.Logger,
) *PhysicalBackupCanceller {
- return &PhysicalBackupCanceller{inFlightRepo, taskCancelManager, logger}
+ return &PhysicalBackupCanceller{inFlightRepo, taskCancellationRequester, logger}
}
// CancelInFlightForDatabase cancels whatever backup the database currently holds
// in flight, whichever it is. Use it for teardown (config disable, db removal)
// where any running backup must stop. A no claim is a no-op.
-func (c *PhysicalBackupCanceller) CancelInFlightForDatabase(databaseID uuid.UUID) {
+func (c *PhysicalBackupCanceller) CancelInFlightForDatabase(ctx context.Context, databaseID uuid.UUID) {
logger := c.logger.With("database_id", databaseID)
claim, err := c.inFlightRepo.FindByDatabaseID(databaseID)
if err != nil {
- logger.Error("failed to look up in-flight backup for cancel", "error", err)
+ logger.ErrorContext(ctx, "failed to look up in-flight backup for cancellation", "error", err)
return
}
@@ -46,7 +47,10 @@ func (c *PhysicalBackupCanceller) CancelInFlightForDatabase(databaseID uuid.UUID
return
}
- c.cancelClaim(logger, databaseID, claim.BackupID)
+ c.cancelClaim(ctx, logger, CancelInFlightBackupSpec{
+ DatabaseID: databaseID,
+ BackupID: claim.BackupID,
+ })
}
// CancelInFlightBackup cancels the database's in-flight backup only when the
@@ -54,27 +58,36 @@ func (c *PhysicalBackupCanceller) CancelInFlightForDatabase(databaseID uuid.UUID
// cancelled, so a delete path can tell "I stopped the running backup" from
// "nothing was running for this row". Scoping by backupID avoids stopping a
// newer backup that took the claim after the targeted one finished.
-func (c *PhysicalBackupCanceller) CancelInFlightBackup(databaseID, backupID uuid.UUID) (bool, error) {
- claim, err := c.inFlightRepo.FindByDatabaseID(databaseID)
+func (c *PhysicalBackupCanceller) CancelInFlightBackup(
+ ctx context.Context,
+ spec CancelInFlightBackupSpec,
+) (bool, error) {
+ claim, err := c.inFlightRepo.FindByDatabaseID(spec.DatabaseID)
if err != nil {
return false, err
}
- if claim == nil || claim.BackupID != backupID {
+ if claim == nil || claim.BackupID != spec.BackupID {
return false, nil
}
- c.cancelClaim(c.logger.With("database_id", databaseID), databaseID, backupID)
+ c.cancelClaim(ctx, c.logger.With("database_id", spec.DatabaseID), spec)
return true, nil
}
-func (c *PhysicalBackupCanceller) cancelClaim(logger *slog.Logger, databaseID, backupID uuid.UUID) {
- if err := c.taskCancelManager.CancelTask(backupID); err != nil {
- logger.Error("failed to cancel in-flight backup task", "backup_id", backupID, "error", err)
+func (c *PhysicalBackupCanceller) cancelClaim(
+ ctx context.Context,
+ logger *slog.Logger,
+ spec CancelInFlightBackupSpec,
+) {
+ if err := c.taskCancellationRequester.RequestCancellation(ctx, spec.BackupID); err != nil {
+ logger.ErrorContext(ctx, "failed to request in-flight backup cancellation",
+ "backup_id", spec.BackupID, "error", err)
}
- if err := c.inFlightRepo.ReleaseOwned(databaseID, backupID); err != nil {
- logger.Error("failed to release in-flight claim", "backup_id", backupID, "error", err)
+ if err := c.inFlightRepo.ReleaseOwned(spec.DatabaseID, spec.BackupID); err != nil {
+ logger.ErrorContext(ctx, "failed to release in-flight claim",
+ "backup_id", spec.BackupID, "error", err)
}
}
diff --git a/backend/internal/features/backups/backups/backuping/physical/di.go b/backend/internal/features/backups/backups/backuping/physical/di.go
index f57ee4da..a17724f6 100644
--- a/backend/internal/features/backups/backups/backuping/physical/di.go
+++ b/backend/internal/features/backups/backups/backuping/physical/di.go
@@ -33,7 +33,7 @@ var physicalBackuper = &PhysicalBackuper{
backups_config_physical.GetBackupConfigService(),
storages.GetStorageService(),
notifiers.GetNotifierService(),
- tasks_cancellation.GetTaskCancelManager(),
+ tasks_cancellation.GetRegistry(),
encryption_secrets.GetSecretKeyService(),
logger.GetLogger(),
postgresql_executor.NewCreateFullBackupUsecase(),
@@ -48,7 +48,7 @@ var physicalBackupsScheduler = &PhysicalBackupsScheduler{
physical_repositories.GetInFlightBackupRepository(),
backups_config_physical.GetBackupConfigService(),
chain_view.GetChainViewService(),
- tasks_cancellation.GetTaskCancelManager(),
+ tasks_cancellation.GetRequester(),
physicalBackuper,
atomicTime{},
logger.GetLogger(),
@@ -78,7 +78,7 @@ var physicalWalStreamSupervisor = &PhysicalWalStreamSupervisor{
physical_repositories.GetWalHistoryRepository(),
physical_repositories.GetWalStreamerRepository(),
notifiers.GetNotifierService(),
- tasks_cancellation.GetTaskCancelManager(),
+ tasks_cancellation.GetRegistry(),
encryption_secrets.GetSecretKeyService(),
encryption.GetFieldEncryptor(),
logger.GetLogger(),
@@ -103,7 +103,7 @@ var physicalSlotCleanupListener = postgresql_executor.NewPhysicalSlotCleanupList
var physicalBackupCanceller = NewPhysicalBackupCanceller(
physical_repositories.GetInFlightBackupRepository(),
- tasks_cancellation.GetTaskCancelManager(),
+ tasks_cancellation.GetRequester(),
logger.GetLogger(),
)
@@ -112,7 +112,7 @@ func GetPhysicalBackupCanceller() *PhysicalBackupCanceller { return physicalBack
var physicalBackupCancellationListener = &PhysicalBackupCancellationListener{
physicalBackupCanceller,
physical_repositories.GetWalStreamerRepository(),
- tasks_cancellation.GetTaskCancelManager(),
+ tasks_cancellation.GetRequester(),
logger.GetLogger(),
}
diff --git a/backend/internal/features/backups/backups/backuping/physical/dto.go b/backend/internal/features/backups/backups/backuping/physical/dto.go
index 9fdfbee3..d83bc04b 100644
--- a/backend/internal/features/backups/backups/backuping/physical/dto.go
+++ b/backend/internal/features/backups/backups/backuping/physical/dto.go
@@ -57,3 +57,8 @@ type chainAlert struct {
Heading string
Message string
}
+
+type CancelInFlightBackupSpec struct {
+ DatabaseID uuid.UUID
+ BackupID uuid.UUID
+}
diff --git a/backend/internal/features/backups/backups/backuping/physical/scheduler.go b/backend/internal/features/backups/backups/backuping/physical/scheduler.go
index 3dc669e8..3e25f9b4 100644
--- a/backend/internal/features/backups/backups/backuping/physical/scheduler.go
+++ b/backend/internal/features/backups/backups/backuping/physical/scheduler.go
@@ -38,13 +38,13 @@ import (
// - CANCELED: neither COMPLETED nor CHAIN_BROKEN; the chain it belonged to stays
// extendable and resumes on cadence — no immediate auto-retry.
type PhysicalBackupsScheduler struct {
- fullRepo *physical_repositories.PhysicalFullBackupRepository
- incrRepo *physical_repositories.PhysicalIncrementalBackupRepository
- inFlightRepo *physical_repositories.PhysicalInFlightBackupRepository
- backupConfigService *backups_config_physical.BackupConfigService
- chainViewService *chain_view.ChainViewService
- taskCancelManager *tasks_cancellation.TaskCancelManager
- backuper *PhysicalBackuper
+ fullRepo *physical_repositories.PhysicalFullBackupRepository
+ incrRepo *physical_repositories.PhysicalIncrementalBackupRepository
+ inFlightRepo *physical_repositories.PhysicalInFlightBackupRepository
+ backupConfigService *backups_config_physical.BackupConfigService
+ chainViewService *chain_view.ChainViewService
+ taskCancellationRequester *tasks_cancellation.Requester
+ backuper *PhysicalBackuper
lastTickTime atomicTime
logger *slog.Logger
@@ -683,7 +683,7 @@ func (s *PhysicalBackupsScheduler) failOrphanedBackup(
// Best-effort cancel of any locally-registered task; harmless if none
// (a fresh process holds no registrations).
- if err := s.taskCancelManager.CancelTask(backupID); err != nil {
+ if err := s.taskCancellationRequester.RequestCancellation(ctx, backupID); err != nil {
logger.ErrorContext(ctx, "failed to cancel orphaned backup task", "error", err)
}
diff --git a/backend/internal/features/backups/backups/backuping/physical/setup_test.go b/backend/internal/features/backups/backups/backuping/physical/setup_test.go
index c67adef8..bbf8c2e0 100644
--- a/backend/internal/features/backups/backups/backuping/physical/setup_test.go
+++ b/backend/internal/features/backups/backups/backuping/physical/setup_test.go
@@ -3,14 +3,8 @@ package backuping_physical
import (
"os"
"testing"
-
- cache_utils "databasus-backend/internal/util/cache"
)
func TestMain(m *testing.M) {
- if err := cache_utils.ClearAllCache(); err != nil {
- panic(err)
- }
-
os.Exit(m.Run())
}
diff --git a/backend/internal/features/backups/backups/backuping/physical/testing.go b/backend/internal/features/backups/backups/backuping/physical/testing.go
index 845c10a7..93b527cb 100644
--- a/backend/internal/features/backups/backups/backuping/physical/testing.go
+++ b/backend/internal/features/backups/backups/backuping/physical/testing.go
@@ -45,7 +45,7 @@ func CreateTestPhysicalBackuper(notificationSender NotificationSender) *Physical
backups_config_physical.GetBackupConfigService(),
storages.GetStorageService(),
sender,
- tasks_cancellation.GetTaskCancelManager(),
+ tasks_cancellation.GetRegistry(),
encryption_secrets.GetSecretKeyService(),
logger.GetLogger(),
postgresql_executor.NewCreateFullBackupUsecase(),
@@ -62,7 +62,7 @@ func CreateTestPhysicalScheduler() *PhysicalBackupsScheduler {
physical_repositories.GetInFlightBackupRepository(),
backups_config_physical.GetBackupConfigService(),
chain_view.GetChainViewService(),
- tasks_cancellation.GetTaskCancelManager(),
+ tasks_cancellation.GetRequester(),
CreateTestPhysicalBackuper(nil),
atomicTime{},
logger.GetLogger(),
@@ -97,7 +97,7 @@ func CreateTestWalStreamSupervisor(spec WalStreamSupervisorTestSpec) *PhysicalWa
physical_repositories.GetWalHistoryRepository(),
physical_repositories.GetWalStreamerRepository(),
spec.NotificationSender,
- tasks_cancellation.GetTaskCancelManager(),
+ tasks_cancellation.GetRegistry(),
encryption_secrets.GetSecretKeyService(),
encryption.GetFieldEncryptor(),
logger.GetLogger(),
diff --git a/backend/internal/features/backups/backups/backuping/physical/wal_supervisor.go b/backend/internal/features/backups/backups/backuping/physical/wal_supervisor.go
index e8a2a1a2..b1cb332e 100644
--- a/backend/internal/features/backups/backups/backuping/physical/wal_supervisor.go
+++ b/backend/internal/features/backups/backups/backuping/physical/wal_supervisor.go
@@ -33,17 +33,17 @@ import (
// heartbeat table: every tick CAS-claims the databases that are unclaimed /
// FAILED / stale, so exactly one process streams a given database at a time.
type PhysicalWalStreamSupervisor struct {
- databaseService *databases.DatabaseService
- backupConfigService *backups_config_physical.BackupConfigService
- storageService *storages.StorageService
- walSegmentRepo *physical_repositories.PhysicalWalSegmentRepository
- historyRepo *physical_repositories.PhysicalWalHistoryRepository
- walStreamerRepo *physical_repositories.PhysicalWalStreamerRepository
- notificationSender NotificationSender
- taskCancelManager *tasks_cancellation.TaskCancelManager
- secretKeyService *encryption_secrets.SecretKeyService
- fieldEncryptor util_encryption.FieldEncryptor
- logger *slog.Logger
+ databaseService *databases.DatabaseService
+ backupConfigService *backups_config_physical.BackupConfigService
+ storageService *storages.StorageService
+ walSegmentRepo *physical_repositories.PhysicalWalSegmentRepository
+ historyRepo *physical_repositories.PhysicalWalHistoryRepository
+ walStreamerRepo *physical_repositories.PhysicalWalStreamerRepository
+ notificationSender NotificationSender
+ taskCancellationRegistry *tasks_cancellation.Registry
+ secretKeyService *encryption_secrets.SecretKeyService
+ fieldEncryptor util_encryption.FieldEncryptor
+ logger *slog.Logger
chainAlertMinInterval time.Duration
@@ -254,7 +254,7 @@ func (s *PhysicalWalStreamSupervisor) startStreamer(
}
// Derive from the supervisor's run ctx so a process shutdown cancels every
- // streamer; the per-DB cancel (registered with TaskCancelManager + stored on
+ // streamer; the per-DB cancel (registered with the task cancellation registry and stored on
// runningStreamer) handles targeted teardown on disable / demote / db-remove.
streamerCtx, cancel := context.WithCancel(ctx)
done := make(chan struct{})
@@ -264,7 +264,7 @@ func (s *PhysicalWalStreamSupervisor) startStreamer(
watchDir: filepath.Join(config.GetEnv().DataFolder, "wal-queue", db.ID.String()),
}
- s.taskCancelManager.RegisterTask(db.ID, func() {
+ s.taskCancellationRegistry.RegisterTask(db.ID, func() {
streamer.shouldRemoveWatchDir.Store(true)
cancel()
})
@@ -299,7 +299,7 @@ func (s *PhysicalWalStreamSupervisor) startStreamer(
go func() {
defer close(done)
defer tunneledDatabase.Close()
- defer s.taskCancelManager.UnregisterTask(db.ID)
+ defer s.taskCancellationRegistry.UnregisterTask(db.ID)
defer s.removeWatchDirIfRequested(logger, streamer)
if err := supervisor.Run(streamerCtx); err != nil {
diff --git a/backend/internal/features/backups/backups/controllers/logical/controller_test.go b/backend/internal/features/backups/backups/controllers/logical/controller_test.go
index 632df55b..8f1454d3 100644
--- a/backend/internal/features/backups/backups/controllers/logical/controller_test.go
+++ b/backend/internal/features/backups/backups/controllers/logical/controller_test.go
@@ -1178,7 +1178,7 @@ func Test_CancelBackup_InProgressBackup_SuccessfullyCancelled(t *testing.T) {
assert.NoError(t, err)
// Register a cancellable context for the backup
- task_cancellation.GetTaskCancelManager().RegisterTask(backup.ID, func() {})
+ task_cancellation.GetRegistry().RegisterTask(backup.ID, func() {})
resp := test_utils.MakePostRequest(
t,
diff --git a/backend/internal/features/backups/backups/controllers/physical/controller_test.go b/backend/internal/features/backups/backups/controllers/physical/controller_test.go
index 09b84a1e..a3c4b54d 100644
--- a/backend/internal/features/backups/backups/controllers/physical/controller_test.go
+++ b/backend/internal/features/backups/backups/controllers/physical/controller_test.go
@@ -1121,7 +1121,7 @@ func occupyUserStreamSlot(t *testing.T, userID uuid.UUID) {
t.Helper()
restoreTokenService := backups_download.GetRestoreTokenService()
- if err := restoreTokenService.AcquireSlot(userID); err != nil {
+ if err := restoreTokenService.AcquireSlot(t.Context(), userID); err != nil {
t.Fatalf("occupy stream slot: %v", err)
}
diff --git a/backend/internal/features/backups/backups/controllers/physical/setup_test.go b/backend/internal/features/backups/backups/controllers/physical/setup_test.go
index d0900d3b..1ca8113a 100644
--- a/backend/internal/features/backups/backups/controllers/physical/setup_test.go
+++ b/backend/internal/features/backups/backups/controllers/physical/setup_test.go
@@ -5,11 +5,9 @@ import (
"testing"
backuping_physical "databasus-backend/internal/features/backups/backups/backuping/physical"
- cache_utils "databasus-backend/internal/util/cache"
)
func TestMain(m *testing.M) {
- cache_utils.ClearAllCache()
backuping_physical.SetupDependencies()
os.Exit(m.Run())
diff --git a/backend/internal/features/backups/backups/core/physical/chain_view/setup_test.go b/backend/internal/features/backups/backups/core/physical/chain_view/setup_test.go
index 29e73111..e6e8a4ee 100644
--- a/backend/internal/features/backups/backups/core/physical/chain_view/setup_test.go
+++ b/backend/internal/features/backups/backups/core/physical/chain_view/setup_test.go
@@ -5,11 +5,9 @@ import (
"testing"
backuping_physical "databasus-backend/internal/features/backups/backups/backuping/physical"
- cache_utils "databasus-backend/internal/util/cache"
)
func TestMain(m *testing.M) {
- cache_utils.ClearAllCache()
backuping_physical.SetupDependencies()
exitCode := m.Run()
diff --git a/backend/internal/features/backups/backups/core/physical/service/setup_test.go b/backend/internal/features/backups/backups/core/physical/service/setup_test.go
index c7ac82d3..7849a4f4 100644
--- a/backend/internal/features/backups/backups/core/physical/service/setup_test.go
+++ b/backend/internal/features/backups/backups/core/physical/service/setup_test.go
@@ -5,11 +5,9 @@ import (
"testing"
backuping_physical "databasus-backend/internal/features/backups/backups/backuping/physical"
- cache_utils "databasus-backend/internal/util/cache"
)
func TestMain(m *testing.M) {
- cache_utils.ClearAllCache()
backuping_physical.SetupDependencies()
os.Exit(m.Run())
diff --git a/backend/internal/features/backups/backups/download/di.go b/backend/internal/features/backups/backups/download/di.go
index 08233d51..c47af359 100644
--- a/backend/internal/features/backups/backups/download/di.go
+++ b/backend/internal/features/backups/backups/download/di.go
@@ -6,7 +6,7 @@ import (
"databasus-backend/internal/features/backups/backups/download/restore_token"
"databasus-backend/internal/features/backups/backups/download/stream_guard"
"databasus-backend/internal/features/storages"
- cache_utils "databasus-backend/internal/util/cache"
+ "databasus-backend/internal/util/cache"
util_encryption "databasus-backend/internal/util/encryption"
"databasus-backend/internal/util/logger"
)
@@ -23,15 +23,15 @@ var (
)
func init() {
- valkeyClient := cache_utils.GetValkeyClient()
+ cacheStore := cache.GetStore()
guard := stream_guard.NewGuard(
- stream_guard.NewTracker(valkeyClient),
+ stream_guard.NewTracker(cacheStore),
logger.GetLogger(),
)
downloadTokenService = download_token.NewService(guard, logger.GetLogger())
- restoreTokenService = restore_token.NewService(guard, valkeyClient, logger.GetLogger())
+ restoreTokenService = restore_token.NewService(guard, cacheStore, logger.GetLogger())
downloadTokenBackgroundService = download_token.NewBackgroundService(downloadTokenService, logger.GetLogger())
restoreStreamWriter = restore_stream.NewWriter(
diff --git a/backend/internal/features/backups/backups/download/download_token/service.go b/backend/internal/features/backups/backups/download/download_token/service.go
index ce555adb..e7851782 100644
--- a/backend/internal/features/backups/backups/download/download_token/service.go
+++ b/backend/internal/features/backups/backups/download/download_token/service.go
@@ -30,7 +30,7 @@ func NewService(guard *stream_guard.Guard, logger *slog.Logger) *Service {
}
func (s *Service) Generate(ctx context.Context, backupID, userID uuid.UUID) (string, error) {
- if s.IsDownloadInProgress(userID) {
+ if s.IsDownloadInProgress(ctx, userID) {
return "", stream_guard.ErrDownloadAlreadyInProgress
}
@@ -74,7 +74,7 @@ func (s *Service) ValidateAndConsume(
return nil, errors.New("token expired")
}
- if err := s.AcquireSlot(downloadToken.UserID); err != nil {
+ if err := s.AcquireSlot(ctx, downloadToken.UserID); err != nil {
return nil, err
}
diff --git a/backend/internal/features/backups/backups/download/restore_stream/setup_test.go b/backend/internal/features/backups/backups/download/restore_stream/setup_test.go
index 3d8af06d..3634ff24 100644
--- a/backend/internal/features/backups/backups/download/restore_stream/setup_test.go
+++ b/backend/internal/features/backups/backups/download/restore_stream/setup_test.go
@@ -3,12 +3,8 @@ package restore_stream_test
import (
"os"
"testing"
-
- cache_utils "databasus-backend/internal/util/cache"
)
func TestMain(m *testing.M) {
- cache_utils.ClearAllCache()
-
os.Exit(m.Run())
}
diff --git a/backend/internal/features/backups/backups/download/restore_token/service.go b/backend/internal/features/backups/backups/download/restore_token/service.go
index 8a260d92..e8c84856 100644
--- a/backend/internal/features/backups/backups/download/restore_token/service.go
+++ b/backend/internal/features/backups/backups/download/restore_token/service.go
@@ -7,9 +7,9 @@ import (
"time"
"github.com/google/uuid"
- "github.com/valkey-io/valkey-go"
"databasus-backend/internal/features/backups/backups/download/stream_guard"
+ "databasus-backend/internal/util/cache"
)
// Service issues and consumes single-use tokens authorizing a physical restore
@@ -22,10 +22,10 @@ type Service struct {
logger *slog.Logger
}
-func NewService(guard *stream_guard.Guard, client valkey.Client, logger *slog.Logger) *Service {
+func NewService(guard *stream_guard.Guard, cacheStore cache.Store, logger *slog.Logger) *Service {
return &Service{
guard,
- newStore(client),
+ newStore(cacheStore),
logger,
}
}
@@ -37,17 +37,19 @@ func (s *Service) GenerateRestoreToken(
databaseID, userID uuid.UUID,
targetTime *time.Time,
) (string, error) {
- if s.IsDownloadInProgress(userID) {
+ if s.IsDownloadInProgress(ctx, userID) {
return "", stream_guard.ErrDownloadAlreadyInProgress
}
token := stream_guard.GenerateSecureToken()
- s.store.issue(token, &Token{
+ if err := s.store.issue(ctx, token, Token{
DatabaseID: databaseID,
UserID: userID,
TargetTime: targetTime,
- })
+ }); err != nil {
+ return "", err
+ }
s.logger.InfoContext(ctx, "generated restore token", "database_id", databaseID, "user_id", userID)
@@ -61,17 +63,19 @@ func (s *Service) GenerateBackupRestoreToken(
ctx context.Context,
databaseID, userID, backupID uuid.UUID,
) (string, error) {
- if s.IsDownloadInProgress(userID) {
+ if s.IsDownloadInProgress(ctx, userID) {
return "", stream_guard.ErrDownloadAlreadyInProgress
}
token := stream_guard.GenerateSecureToken()
- s.store.issue(token, &Token{
+ if err := s.store.issue(ctx, token, Token{
DatabaseID: databaseID,
UserID: userID,
BackupID: &backupID,
- })
+ }); err != nil {
+ return "", err
+ }
s.logger.InfoContext(ctx, "generated backup restore token",
"database_id", databaseID, "user_id", userID, "backup_id", backupID)
@@ -93,12 +97,15 @@ func (s *Service) ValidateAndConsumeRestoreToken(
ctx context.Context,
token string,
) (*Token, error) {
- restoreToken := s.store.consume(token)
+ restoreToken, err := s.store.consume(ctx, token)
+ if err != nil {
+ return nil, err
+ }
if restoreToken == nil {
return nil, errors.New("invalid or expired restore token")
}
- if err := s.AcquireSlot(restoreToken.UserID); err != nil {
+ if err := s.AcquireSlot(ctx, restoreToken.UserID); err != nil {
return nil, err
}
diff --git a/backend/internal/features/backups/backups/download/restore_token/store.go b/backend/internal/features/backups/backups/download/restore_token/store.go
index ee0323d1..3ada0156 100644
--- a/backend/internal/features/backups/backups/download/restore_token/store.go
+++ b/backend/internal/features/backups/backups/download/restore_token/store.go
@@ -1,12 +1,12 @@
package restore_token
import (
+ "context"
"time"
"github.com/google/uuid"
- "github.com/valkey-io/valkey-go"
- cache_utils "databasus-backend/internal/util/cache"
+ "databasus-backend/internal/util/cache"
)
const restoreTokenPrefix = "physical_restore_token:"
@@ -37,26 +37,26 @@ type Token struct {
BackupID *uuid.UUID `json:"backupId"`
}
-// store holds issued restore tokens in Valkey. Consuming via GETDEL makes
-// single-use atomic across instances: two concurrent stream requests can never
-// both consume the same token, which a DB find-then-mark-used path cannot
-// guarantee without extra locking.
type store struct {
- cache *cache_utils.CacheUtil[Token]
+ tokens *cache.JSONStore[Token]
}
-func newStore(client valkey.Client) *store {
+func newStore(cacheStore cache.Store) *store {
return &store{
- cache: cache_utils.NewCacheUtil[Token](client, restoreTokenPrefix),
+ tokens: cache.NewJSONStore[Token](cacheStore, restoreTokenPrefix),
}
}
-func (s *store) issue(token string, restoreToken *Token) {
- s.cache.SetWithExpiration(token, restoreToken, restoreTokenTTL)
+func (s *store) issue(ctx context.Context, token string, restoreToken Token) error {
+ return s.tokens.SetWithLifetime(ctx, cache.ExpiringValue[Token]{
+ Key: token,
+ Value: restoreToken,
+ Lifetime: restoreTokenTTL,
+ })
}
// consume atomically reads and deletes the token, returning nil when it is
// missing, expired, or already consumed.
-func (s *store) consume(token string) *Token {
- return s.cache.GetAndDelete(token)
+func (s *store) consume(ctx context.Context, token string) (*Token, error) {
+ return s.tokens.ReadAndDelete(ctx, token)
}
diff --git a/backend/internal/features/backups/backups/download/restore_token/store_test.go b/backend/internal/features/backups/backups/download/restore_token/store_test.go
new file mode 100644
index 00000000..5a87472e
--- /dev/null
+++ b/backend/internal/features/backups/backups/download/restore_token/store_test.go
@@ -0,0 +1,67 @@
+package restore_token
+
+import (
+ "context"
+ "errors"
+ "testing"
+
+ "github.com/google/uuid"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ "databasus-backend/internal/util/cache"
+)
+
+type failingStore struct {
+ err error
+}
+
+func (s failingStore) Get(context.Context, string) ([]byte, bool, error) {
+ return nil, false, s.err
+}
+
+func (s failingStore) Set(context.Context, cache.Entry) error {
+ return s.err
+}
+
+func (s failingStore) CreateIfAbsent(context.Context, cache.Entry) (bool, error) {
+ return false, s.err
+}
+
+func (s failingStore) ReadAndDelete(context.Context, string) ([]byte, bool, error) {
+ return nil, false, s.err
+}
+
+func (s failingStore) Delete(context.Context, string) error {
+ return s.err
+}
+
+func (s failingStore) Clear(context.Context) error {
+ return s.err
+}
+
+func Test_Store_IssueAndConsume_ConsumesTokenOnce(t *testing.T) {
+ tokenStore := newStore(cache.NewMemoryStore(4096))
+ restoreToken := Token{DatabaseID: uuid.New(), UserID: uuid.New()}
+
+ require.NoError(t, tokenStore.issue(t.Context(), "token", restoreToken))
+ consumedToken, err := tokenStore.consume(t.Context(), "token")
+ require.NoError(t, err)
+ require.NotNil(t, consumedToken)
+ assert.Equal(t, restoreToken, *consumedToken)
+
+ consumedToken, err = tokenStore.consume(t.Context(), "token")
+ require.NoError(t, err)
+ assert.Nil(t, consumedToken)
+}
+
+func Test_Store_WhenProviderFails_ReturnsError(t *testing.T) {
+ providerError := errors.New("provider failed")
+ tokenStore := newStore(failingStore{err: providerError})
+
+ err := tokenStore.issue(t.Context(), "token", Token{})
+ assert.ErrorIs(t, err, providerError)
+
+ _, err = tokenStore.consume(t.Context(), "token")
+ assert.ErrorIs(t, err, providerError)
+}
diff --git a/backend/internal/features/backups/backups/download/stream_guard/guard.go b/backend/internal/features/backups/backups/download/stream_guard/guard.go
index f8f81d93..71906a66 100644
--- a/backend/internal/features/backups/backups/download/stream_guard/guard.go
+++ b/backend/internal/features/backups/backups/download/stream_guard/guard.go
@@ -23,20 +23,33 @@ func NewGuard(
return &Guard{tracker, logger}
}
-func (g *Guard) IsDownloadInProgress(userID uuid.UUID) bool {
- return g.tracker.IsDownloadInProgress(userID)
+func (g *Guard) IsDownloadInProgress(ctx context.Context, userID uuid.UUID) bool {
+ isInProgress, err := g.tracker.IsDownloadInProgress(ctx, userID)
+ if err != nil {
+ g.logger.ErrorContext(ctx, "failed to read stream lock", "error", err)
+
+ return true
+ }
+
+ return isInProgress
}
func (g *Guard) RefreshDownloadLock(ctx context.Context, userID uuid.UUID) {
- g.tracker.RefreshDownloadLock(ctx, userID)
+ if err := g.tracker.RefreshDownloadLock(ctx, userID); err != nil {
+ g.logger.ErrorContext(ctx, "failed to refresh stream lock", "error", err)
+ }
}
func (g *Guard) ReleaseDownloadLock(ctx context.Context, userID uuid.UUID) {
- g.tracker.ReleaseDownloadLock(ctx, userID)
+ if err := g.tracker.ReleaseDownloadLock(ctx, userID); err != nil {
+ g.logger.ErrorContext(ctx, "failed to release stream lock", "error", err)
+
+ return
+ }
+
g.logger.InfoContext(ctx, "released stream lock", "user_id", userID)
}
-// AcquireSlot takes the per-user single-stream lock.
-func (g *Guard) AcquireSlot(userID uuid.UUID) error {
- return g.tracker.AcquireDownloadLock(userID)
+func (g *Guard) AcquireSlot(ctx context.Context, userID uuid.UUID) error {
+ return g.tracker.AcquireDownloadLock(ctx, userID)
}
diff --git a/backend/internal/features/backups/backups/download/stream_guard/tracker.go b/backend/internal/features/backups/backups/download/stream_guard/tracker.go
index 1ed4e28f..e2410684 100644
--- a/backend/internal/features/backups/backups/download/stream_guard/tracker.go
+++ b/backend/internal/features/backups/backups/download/stream_guard/tracker.go
@@ -5,9 +5,8 @@ import (
"time"
"github.com/google/uuid"
- "github.com/valkey-io/valkey-go"
- cache_utils "databasus-backend/internal/util/cache"
+ "databasus-backend/internal/util/cache"
)
const (
@@ -22,44 +21,53 @@ const (
)
type Tracker struct {
- cache *cache_utils.CacheUtil[string]
+ locks *cache.JSONStore[string]
}
-func NewTracker(client valkey.Client) *Tracker {
+func NewTracker(store cache.Store) *Tracker {
return &Tracker{
- cache: cache_utils.NewCacheUtil[string](client, downloadLockPrefix),
+ locks: cache.NewJSONStore[string](store, downloadLockPrefix),
}
}
-func (t *Tracker) AcquireDownloadLock(userID uuid.UUID) error {
- key := userID.String()
-
- existingLock := t.cache.Get(key)
- if existingLock != nil {
+func (t *Tracker) AcquireDownloadLock(ctx context.Context, userID uuid.UUID) error {
+ isCreated, err := t.locks.CreateIfAbsent(
+ ctx,
+ cache.ExpiringValue[string]{
+ Key: userID.String(),
+ Value: downloadLockValue,
+ Lifetime: downloadLockTTL,
+ },
+ )
+ if err != nil {
+ return err
+ }
+ if !isCreated {
return ErrDownloadAlreadyInProgress
}
- value := downloadLockValue
- t.cache.SetWithExpiration(key, &value, downloadLockTTL)
-
return nil
}
-func (t *Tracker) RefreshDownloadLock(ctx context.Context, userID uuid.UUID) {
- key := userID.String()
- value := downloadLockValue
- t.cache.SetWithExpiration(key, &value, downloadLockTTL)
+func (t *Tracker) RefreshDownloadLock(ctx context.Context, userID uuid.UUID) error {
+ return t.locks.SetWithLifetime(ctx, cache.ExpiringValue[string]{
+ Key: userID.String(),
+ Value: downloadLockValue,
+ Lifetime: downloadLockTTL,
+ })
}
-func (t *Tracker) ReleaseDownloadLock(ctx context.Context, userID uuid.UUID) {
- key := userID.String()
- t.cache.Invalidate(key)
+func (t *Tracker) ReleaseDownloadLock(ctx context.Context, userID uuid.UUID) error {
+ return t.locks.Delete(ctx, userID.String())
}
-func (t *Tracker) IsDownloadInProgress(userID uuid.UUID) bool {
- key := userID.String()
- existingLock := t.cache.Get(key)
- return existingLock != nil
+func (t *Tracker) IsDownloadInProgress(ctx context.Context, userID uuid.UUID) (bool, error) {
+ existingLock, err := t.locks.Get(ctx, userID.String())
+ if err != nil {
+ return false, err
+ }
+
+ return existingLock != nil, nil
}
func GetDownloadHeartbeatInterval() time.Duration {
diff --git a/backend/internal/features/backups/backups/download/stream_guard/tracker_test.go b/backend/internal/features/backups/backups/download/stream_guard/tracker_test.go
new file mode 100644
index 00000000..8735ed56
--- /dev/null
+++ b/backend/internal/features/backups/backups/download/stream_guard/tracker_test.go
@@ -0,0 +1,84 @@
+package stream_guard
+
+import (
+ "context"
+ "errors"
+ "sync"
+ "sync/atomic"
+ "testing"
+
+ "github.com/google/uuid"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ "databasus-backend/internal/util/cache"
+)
+
+type failingStore struct {
+ err error
+}
+
+func (s failingStore) Get(context.Context, string) ([]byte, bool, error) {
+ return nil, false, s.err
+}
+
+func (s failingStore) Set(context.Context, cache.Entry) error {
+ return s.err
+}
+
+func (s failingStore) CreateIfAbsent(context.Context, cache.Entry) (bool, error) {
+ return false, s.err
+}
+
+func (s failingStore) ReadAndDelete(context.Context, string) ([]byte, bool, error) {
+ return nil, false, s.err
+}
+
+func (s failingStore) Delete(context.Context, string) error {
+ return s.err
+}
+
+func (s failingStore) Clear(context.Context) error {
+ return s.err
+}
+
+func Test_Tracker_AcquireDownloadLock_ConcurrentCallersAcquireOneLock(t *testing.T) {
+ tracker := NewTracker(cache.NewMemoryStore(4096))
+ userID := uuid.New()
+
+ const callerCount = 32
+ var acquiredCount atomic.Int64
+ var waitGroup sync.WaitGroup
+ for range callerCount {
+ waitGroup.Go(func() {
+ err := tracker.AcquireDownloadLock(t.Context(), userID)
+ if err == nil {
+ acquiredCount.Add(1)
+ return
+ }
+
+ assert.ErrorIs(t, err, ErrDownloadAlreadyInProgress)
+ })
+ }
+ waitGroup.Wait()
+
+ assert.Equal(t, int64(1), acquiredCount.Load())
+}
+
+func Test_Tracker_WhenStoreFails_FailsClosed(t *testing.T) {
+ storeError := errors.New("store failed")
+ tracker := NewTracker(failingStore{err: storeError})
+
+ err := tracker.AcquireDownloadLock(t.Context(), uuid.New())
+ require.ErrorIs(t, err, storeError)
+}
+
+func Test_Tracker_ReleasedLockCanBeAcquiredAgain(t *testing.T) {
+ memoryStore := cache.NewMemoryStore(4096)
+ tracker := NewTracker(memoryStore)
+ userID := uuid.New()
+
+ require.NoError(t, tracker.AcquireDownloadLock(t.Context(), userID))
+ require.NoError(t, tracker.ReleaseDownloadLock(t.Context(), userID))
+ require.NoError(t, tracker.AcquireDownloadLock(t.Context(), userID))
+}
diff --git a/backend/internal/features/backups/backups/services/di.go b/backend/internal/features/backups/backups/services/di.go
index af3bcb83..c534ac21 100644
--- a/backend/internal/features/backups/backups/services/di.go
+++ b/backend/internal/features/backups/backups/services/di.go
@@ -24,7 +24,7 @@ import (
"databasus-backend/internal/util/logger"
)
-var taskCancelManager = task_cancellation.GetTaskCancelManager()
+var taskCancellationRequester = task_cancellation.GetRequester()
var backupService = &LogicalBackupService{
databases.GetDatabaseService(),
@@ -40,7 +40,7 @@ var backupService = &LogicalBackupService{
[]backups_core_logical.BackupRemoveListener{},
workspaces_services.GetWorkspaceService(),
audit_logs.GetAuditLogService(),
- taskCancelManager,
+ taskCancellationRequester,
backups_download.GetDownloadTokenService(),
backuping_logical.GetBackupsScheduler(),
backuping_logical.GetBackupCleaner(),
diff --git a/backend/internal/features/backups/backups/services/logical_service.go b/backend/internal/features/backups/backups/services/logical_service.go
index 9fd9ef2c..256a91cc 100644
--- a/backend/internal/features/backups/backups/services/logical_service.go
+++ b/backend/internal/features/backups/backups/services/logical_service.go
@@ -47,12 +47,12 @@ type LogicalBackupService struct {
backupRemoveListeners []backups_core_logical.BackupRemoveListener
- workspaceService *workspaces_services.WorkspaceService
- auditLogService *audit_logs.AuditLogService
- taskCancelManager *task_cancellation.TaskCancelManager
- downloadTokenService *download_token.Service
- backupSchedulerService *backuping_logical.BackupsScheduler
- backupCleaner *backuping_logical.BackupCleaner
+ workspaceService *workspaces_services.WorkspaceService
+ auditLogService *audit_logs.AuditLogService
+ taskCancellationRequester *task_cancellation.Requester
+ downloadTokenService *download_token.Service
+ backupSchedulerService *backuping_logical.BackupsScheduler
+ backupCleaner *backuping_logical.BackupCleaner
}
func (s *LogicalBackupService) AddBackupRemoveListener(listener backups_core_logical.BackupRemoveListener) {
@@ -256,7 +256,7 @@ func (s *LogicalBackupService) CancelBackup(
return errors.New("backup is not in progress")
}
- if err := s.taskCancelManager.CancelTask(backupID); err != nil {
+ if err := s.taskCancellationRequester.RequestCancellation(ctx, backupID); err != nil {
return err
}
@@ -459,7 +459,7 @@ func (s *LogicalBackupService) ReleaseDownloadLock(ctx context.Context, userID u
}
func (s *LogicalBackupService) IsDownloadInProgress(userID uuid.UUID) bool {
- return s.downloadTokenService.IsDownloadInProgress(userID)
+ return s.downloadTokenService.IsDownloadInProgress(context.Background(), userID)
}
func (s *LogicalBackupService) deleteDbBackups(ctx context.Context, databaseID uuid.UUID) error {
diff --git a/backend/internal/features/backups/backups/services/physical_service.go b/backend/internal/features/backups/backups/services/physical_service.go
index 77300433..a7f3ece4 100644
--- a/backend/internal/features/backups/backups/services/physical_service.go
+++ b/backend/internal/features/backups/backups/services/physical_service.go
@@ -212,7 +212,10 @@ func (s *PhysicalBackupService) CancelBackup(ctx context.Context, user *users_mo
return ErrBackupNotInProgress
}
- cancelled, err := s.canceller.CancelInFlightBackup(databaseID, backupID)
+ cancelled, err := s.canceller.CancelInFlightBackup(ctx, backuping_physical.CancelInFlightBackupSpec{
+ DatabaseID: databaseID,
+ BackupID: backupID,
+ })
if err != nil {
return err
}
@@ -395,7 +398,7 @@ func (s *PhysicalBackupService) writeRestoreStream(
}
func (s *PhysicalBackupService) deleteFull(ctx context.Context, full *physical_models.PhysicalFullBackup) error {
- s.stopInFlightForDelete(full.DatabaseID, func(inFlightBackupID uuid.UUID) bool {
+ s.stopInFlightForDelete(ctx, full.DatabaseID, func(inFlightBackupID uuid.UUID) bool {
if inFlightBackupID == full.ID {
return true
}
@@ -420,7 +423,7 @@ func (s *PhysicalBackupService) deleteIncremental(
ctx context.Context,
target *physical_models.PhysicalIncrementalBackup,
) error {
- s.stopInFlightForDelete(target.DatabaseID, func(inFlightBackupID uuid.UUID) bool {
+ s.stopInFlightForDelete(ctx, target.DatabaseID, func(inFlightBackupID uuid.UUID) bool {
if inFlightBackupID == target.ID {
return true
}
@@ -446,12 +449,14 @@ func (s *PhysicalBackupService) deleteIncremental(
// stops before its row disappears. Best-effort: lookup failures are logged, not
// fatal — a stale claim expires on its own and the delete proceeds.
func (s *PhysicalBackupService) stopInFlightForDelete(
+ ctx context.Context,
databaseID uuid.UUID,
willDelete func(inFlightBackupID uuid.UUID) bool,
) {
claim, err := s.inFlightBackupRepository.FindByDatabaseID(databaseID)
if err != nil {
- s.logger.Error("failed to look up in-flight backup for delete", "database_id", databaseID, "error", err)
+ s.logger.ErrorContext(ctx, "failed to look up in-flight backup for delete",
+ "database_id", databaseID, "error", err)
return
}
@@ -461,7 +466,7 @@ func (s *PhysicalBackupService) stopInFlightForDelete(
}
if willDelete(claim.BackupID) {
- s.canceller.CancelInFlightForDatabase(databaseID)
+ s.canceller.CancelInFlightForDatabase(ctx, databaseID)
}
}
diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/backup_slot_test.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/backup_slot_test.go
index 6bd685ff..b43718e9 100644
--- a/backend/internal/features/backups/backups/usecases/physical/postgresql/backup_slot_test.go
+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/backup_slot_test.go
@@ -846,7 +846,7 @@ func Test_BackupSlot_DroppedAfterCancelledMidRun(t *testing.T) {
if exists {
slotObserved.Store(true)
- _ = tasks_cancellation.GetTaskCancelManager().CancelTask(fixture.BackupID)
+ _ = tasks_cancellation.GetRequester().RequestCancellation(context.Background(), fixture.BackupID)
return
}
}
diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/setup_test.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/setup_test.go
index 10534b4e..8d05d9d4 100644
--- a/backend/internal/features/backups/backups/usecases/physical/postgresql/setup_test.go
+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/setup_test.go
@@ -5,14 +5,12 @@ import (
"testing"
backuping_physical "databasus-backend/internal/features/backups/backups/backuping/physical"
- cache_utils "databasus-backend/internal/util/cache"
)
// SetupDependencies registers the PhysicalSlotCleanupListener on
// DatabaseService.AddDbRemoveListener so RemoveTestDatabase drops
// per-backup and WAL streamer slots when test databases are torn down.
func TestMain(m *testing.M) {
- cache_utils.ClearAllCache()
backuping_physical.SetupDependencies()
os.Exit(m.Run())
diff --git a/backend/internal/features/restores/controller_test.go b/backend/internal/features/restores/controller_test.go
index 2c1f2083..7a9eb388 100644
--- a/backend/internal/features/restores/controller_test.go
+++ b/backend/internal/features/restores/controller_test.go
@@ -34,7 +34,7 @@ import (
users_testing "databasus-backend/internal/features/users/testing"
workspaces_models "databasus-backend/internal/features/workspaces/models"
workspaces_testing "databasus-backend/internal/features/workspaces/testing"
- cache_utils "databasus-backend/internal/util/cache"
+ "databasus-backend/internal/util/cache"
util_encryption "databasus-backend/internal/util/encryption"
test_utils "databasus-backend/internal/util/testing"
"databasus-backend/internal/util/testing/containers"
@@ -389,7 +389,7 @@ func Test_RestoreBackup_DiskSpaceValidation(t *testing.T) {
}
func Test_CancelRestore_InProgressRestore_SuccessfullyCancelled(t *testing.T) {
- cache_utils.ClearAllCache()
+ cache.GetStore().Clear(t.Context())
tasks_cancellation.SetupDependencies()
user := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleAdmin)
@@ -422,7 +422,7 @@ func Test_CancelRestore_InProgressRestore_SuccessfullyCancelled(t *testing.T) {
notifiers.RemoveTestNotifier(notifier)
workspaces_testing.RemoveTestWorkspace(t.Context(), workspace, router)
- cache_utils.ClearAllCache()
+ cache.GetStore().Clear(t.Context())
}()
backups_config_logical.EnableBackupsForTestDatabase(t.Context(), database.ID, storage)
diff --git a/backend/internal/features/restores/di.go b/backend/internal/features/restores/di.go
index 8785e47d..78e526b6 100644
--- a/backend/internal/features/restores/di.go
+++ b/backend/internal/features/restores/di.go
@@ -32,7 +32,7 @@ var (
audit_logs.GetAuditLogService(),
encryption.GetFieldEncryptor(),
disk.GetDiskService(),
- tasks_cancellation.GetTaskCancelManager(),
+ tasks_cancellation.GetRequester(),
}
)
diff --git a/backend/internal/features/restores/restoring/di.go b/backend/internal/features/restores/restoring/di.go
index b498f4ec..cd3f9af2 100644
--- a/backend/internal/features/restores/restoring/di.go
+++ b/backend/internal/features/restores/restoring/di.go
@@ -11,19 +11,16 @@ import (
"databasus-backend/internal/features/restores/usecases"
"databasus-backend/internal/features/storages"
tasks_cancellation "databasus-backend/internal/features/tasks/cancellation"
- cache_utils "databasus-backend/internal/util/cache"
+ "databasus-backend/internal/util/cache"
"databasus-backend/internal/util/encryption"
"databasus-backend/internal/util/logger"
)
var restoreRepository = &restores_core.RestoreRepository{}
-var restoreDatabaseCache = cache_utils.NewCacheUtil[RestoreDatabaseCache](
- cache_utils.GetValkeyClient(),
- "restore_db:",
-)
+var restoreDatabaseCache = cache.NewJSONStore[RestoreDatabaseCache](cache.GetStore(), "restore_db")
-var restoreCancelManager = tasks_cancellation.GetTaskCancelManager()
+var taskCancellationRegistry = tasks_cancellation.GetRegistry()
var restorer = &Restorer{
databases.GetDatabaseService(),
@@ -35,7 +32,7 @@ var restorer = &Restorer{
logger.GetLogger(),
usecases.GetRestoreBackupUsecase(),
restoreDatabaseCache,
- restoreCancelManager,
+ taskCancellationRegistry,
}
var restoresScheduler = &RestoresScheduler{
diff --git a/backend/internal/features/restores/restoring/dto.go b/backend/internal/features/restores/restoring/dto.go
index 635d80fd..0772c7f4 100644
--- a/backend/internal/features/restores/restoring/dto.go
+++ b/backend/internal/features/restores/restoring/dto.go
@@ -13,3 +13,10 @@ type RestoreDatabaseCache struct {
MariadbDatabase *mariadb.MariadbDatabase `json:"mariadbDatabase,omitzero"`
MongodbDatabase *mongodb.MongodbDatabase `json:"mongodbDatabase,omitzero"`
}
+
+func (c *RestoreDatabaseCache) HasDatabaseConfiguration() bool {
+ return c.PostgresqlLogicalDatabase != nil ||
+ c.MysqlDatabase != nil ||
+ c.MariadbDatabase != nil ||
+ c.MongodbDatabase != nil
+}
diff --git a/backend/internal/features/restores/restoring/restorer.go b/backend/internal/features/restores/restoring/restorer.go
index 3336a436..b71bbdf8 100644
--- a/backend/internal/features/restores/restoring/restorer.go
+++ b/backend/internal/features/restores/restoring/restorer.go
@@ -16,52 +16,55 @@ import (
restores_core "databasus-backend/internal/features/restores/core"
"databasus-backend/internal/features/storages"
tasks_cancellation "databasus-backend/internal/features/tasks/cancellation"
- cache_utils "databasus-backend/internal/util/cache"
+ "databasus-backend/internal/util/cache"
util_encryption "databasus-backend/internal/util/encryption"
)
type Restorer struct {
- databaseService *databases.DatabaseService
- backupService *backups_services.LogicalBackupService
- fieldEncryptor util_encryption.FieldEncryptor
- restoreRepository *restores_core.RestoreRepository
- backupConfigService *backups_config_logical.BackupConfigService
- storageService *storages.StorageService
- logger *slog.Logger
- restoreBackupUsecase restores_core.RestoreBackupUsecase
- cacheUtil *cache_utils.CacheUtil[RestoreDatabaseCache]
- restoreCancelManager *tasks_cancellation.TaskCancelManager
+ databaseService *databases.DatabaseService
+ backupService *backups_services.LogicalBackupService
+ fieldEncryptor util_encryption.FieldEncryptor
+ restoreRepository *restores_core.RestoreRepository
+ backupConfigService *backups_config_logical.BackupConfigService
+ storageService *storages.StorageService
+ logger *slog.Logger
+ restoreBackupUsecase restores_core.RestoreBackupUsecase
+ restoreDatabaseCache *cache.JSONStore[RestoreDatabaseCache]
+ taskCancellationRegistry *tasks_cancellation.Registry
}
-func (r *Restorer) MakeRestore(ctx context.Context, restoreID uuid.UUID) {
- logger := r.logger.With("restore_id", restoreID)
+type restoreMetadataLookup struct {
+ restoreID uuid.UUID
+ fallbackDatabaseCache *RestoreDatabaseCache
+}
- // Get and delete cached DB credentials atomically
- dbCache := r.cacheUtil.GetAndDelete(restoreID.String())
+func (r *Restorer) MakeRestore(
+ ctx context.Context,
+ restoreID uuid.UUID,
+ fallbackDatabaseCache *RestoreDatabaseCache,
+) {
+ logger := r.logger.With("restore_id", restoreID)
- if dbCache == nil {
- // Cache miss - fail immediately
- restore, err := r.restoreRepository.FindByID(restoreID)
- if err != nil {
- logger.ErrorContext(ctx, "failed to get restore by ID after cache miss", "error", err)
- return
- }
+ restore, err := r.restoreRepository.FindByID(restoreID)
+ if err != nil {
+ logger.ErrorContext(ctx, "failed to get restore by ID", "error", err)
+ return
+ }
- errMsg := "Database credentials expired or missing from cache (most likely due to instance restart)"
- restore.FailMessage = &errMsg
+ databaseCache := r.getRestoreDatabaseCache(ctx, restoreMetadataLookup{
+ restoreID: restore.ID,
+ fallbackDatabaseCache: fallbackDatabaseCache,
+ }, logger)
+ if !databaseCache.HasDatabaseConfiguration() {
+ failMessage := "Database credentials expired or missing from cache (most likely due to instance restart)"
+ restore.FailMessage = &failMessage
restore.Status = restores_core.RestoreStatusFailed
-
if err := r.restoreRepository.Save(restore); err != nil {
- logger.ErrorContext(ctx, "failed to save restore after cache miss", "error", err)
+ logger.ErrorContext(ctx, "failed to save restore after missing metadata", "error", err)
}
- logger.ErrorContext(ctx, "restore failed: cache miss")
- return
- }
+ logger.ErrorContext(ctx, "restore failed because database credentials are missing")
- restore, err := r.restoreRepository.FindByID(restoreID)
- if err != nil {
- logger.ErrorContext(ctx, "failed to get restore by ID", "error", err)
return
}
@@ -92,8 +95,8 @@ func (r *Restorer) MakeRestore(ctx context.Context, restoreID uuid.UUID) {
// Detached from the caller so a finished HTTP request cannot cancel a running restore.
executionCtx, cancel := context.WithCancel(context.Background())
- r.restoreCancelManager.RegisterTask(restore.ID, cancel)
- defer r.restoreCancelManager.UnregisterTask(restore.ID)
+ r.taskCancellationRegistry.RegisterTask(restore.ID, cancel)
+ defer r.taskCancellationRegistry.UnregisterTask(restore.ID)
storage, err := r.storageService.GetStorageByID(executionCtx, *backupConfig.StorageID)
if err != nil {
@@ -106,10 +109,10 @@ func (r *Restorer) MakeRestore(ctx context.Context, restoreID uuid.UUID) {
// Create restoring database from cached credentials
restoringToDB := &databases.Database{
Type: database.Type,
- PostgresqlLogical: dbCache.PostgresqlLogicalDatabase,
- Mysql: dbCache.MysqlDatabase,
- Mariadb: dbCache.MariadbDatabase,
- Mongodb: dbCache.MongodbDatabase,
+ PostgresqlLogical: databaseCache.PostgresqlLogicalDatabase,
+ Mysql: databaseCache.MysqlDatabase,
+ Mariadb: databaseCache.MariadbDatabase,
+ Mongodb: databaseCache.MongodbDatabase,
}
// The restore target is the only endpoint this function connects to, so one tunnel covers
@@ -156,8 +159,8 @@ func (r *Restorer) MakeRestore(ctx context.Context, restoreID uuid.UUID) {
// IsExcludeExtensions is a transient choice carried on the target config from the restore
// request; IsSkipUserMappings is a persisted property of the source database being restored.
restoreOptions := restores_core.RestoreOptions{}
- if dbCache.PostgresqlLogicalDatabase != nil {
- restoreOptions.IsExcludeExtensions = dbCache.PostgresqlLogicalDatabase.IsExcludeExtensions
+ if databaseCache.PostgresqlLogicalDatabase != nil {
+ restoreOptions.IsExcludeExtensions = databaseCache.PostgresqlLogicalDatabase.IsExcludeExtensions
}
if database.PostgresqlLogical != nil {
restoreOptions.IsSkipUserMappings = database.PostgresqlLogical.IsSkipUserMappings
@@ -232,3 +235,22 @@ func (r *Restorer) MakeRestore(ctx context.Context, restoreID uuid.UUID) {
logger.InfoContext(ctx, fmt.Sprintf("restore finished in %d ms", restore.RestoreDurationMs),
"backup_id", backup.ID)
}
+
+func (r *Restorer) getRestoreDatabaseCache(
+ ctx context.Context,
+ lookup restoreMetadataLookup,
+ logger *slog.Logger,
+) *RestoreDatabaseCache {
+ databaseCache, err := r.restoreDatabaseCache.ReadAndDelete(ctx, lookup.restoreID.String())
+ if err != nil {
+ logger.WarnContext(ctx, "failed to read restore metadata from cache", "error", err)
+ }
+ if databaseCache != nil {
+ return databaseCache
+ }
+ if lookup.fallbackDatabaseCache != nil {
+ return lookup.fallbackDatabaseCache
+ }
+
+ return &RestoreDatabaseCache{}
+}
diff --git a/backend/internal/features/restores/restoring/restorer_test.go b/backend/internal/features/restores/restoring/restorer_test.go
index a947d8d9..0dccc6e9 100644
--- a/backend/internal/features/restores/restoring/restorer_test.go
+++ b/backend/internal/features/restores/restoring/restorer_test.go
@@ -1,10 +1,15 @@
package restoring
import (
+ "errors"
+ "io"
+ "log/slog"
"testing"
"time"
+ "github.com/google/uuid"
"github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
"databasus-backend/internal/config"
backups_controllers_logical "databasus-backend/internal/features/backups/backups/controllers/logical"
@@ -18,11 +23,36 @@ import (
users_enums "databasus-backend/internal/features/users/enums"
users_testing "databasus-backend/internal/features/users/testing"
workspaces_testing "databasus-backend/internal/features/workspaces/testing"
- cache_utils "databasus-backend/internal/util/cache"
+ "databasus-backend/internal/util/cache"
)
+func Test_GetRestoreDatabaseCache_WhenProviderFails_UsesSuppliedMetadata(t *testing.T) {
+ databaseConfiguration := &postgresql_logical.PostgresqlLogicalDatabase{Host: "database.internal"}
+ databaseCacheFallback := &RestoreDatabaseCache{
+ PostgresqlLogicalDatabase: databaseConfiguration,
+ }
+ restorer := &Restorer{
+ restoreDatabaseCache: cache.NewJSONStore[RestoreDatabaseCache](
+ NewFailingRestoreMetadataStore(errors.New("provider failed")),
+ "restore_db",
+ ),
+ }
+ testLogger := slog.New(slog.NewTextHandler(io.Discard, nil))
+
+ databaseCache := restorer.getRestoreDatabaseCache(
+ t.Context(),
+ restoreMetadataLookup{
+ restoreID: uuid.New(),
+ fallbackDatabaseCache: databaseCacheFallback,
+ },
+ testLogger,
+ )
+
+ assert.Same(t, databaseConfiguration, databaseCache.PostgresqlLogicalDatabase)
+}
+
func Test_MakeRestore_WhenCacheMissed_RestoreFails(t *testing.T) {
- cache_utils.ClearAllCache()
+ cache.GetStore().Clear(t.Context())
user := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleAdmin)
router := CreateTestRouter()
@@ -55,7 +85,7 @@ func Test_MakeRestore_WhenCacheMissed_RestoreFails(t *testing.T) {
storages.RemoveTestStorage(t.Context(), storage.ID)
workspaces_testing.RemoveTestWorkspace(t.Context(), workspace, router)
- cache_utils.ClearAllCache()
+ cache.GetStore().Clear(t.Context())
}()
backup := backups_controllers_logical.CreateTestBackup(database.ID, storage.ID)
@@ -71,7 +101,7 @@ func Test_MakeRestore_WhenCacheMissed_RestoreFails(t *testing.T) {
// Create restorer and execute restore (should fail due to cache miss)
restorer := CreateTestRestorer()
- restorer.MakeRestore(t.Context(), restore.ID)
+ restorer.MakeRestore(t.Context(), restore.ID, nil)
// Verify restore failed with appropriate error message
updatedRestore, err := restoreRepository.FindByID(restore.ID)
@@ -86,7 +116,7 @@ func Test_MakeRestore_WhenCacheMissed_RestoreFails(t *testing.T) {
}
func Test_MakeRestore_WhenTaskStarts_CacheDeletedImmediately(t *testing.T) {
- cache_utils.ClearAllCache()
+ cache.GetStore().Clear(t.Context())
user := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleAdmin)
router := CreateTestRouter()
@@ -123,7 +153,7 @@ func Test_MakeRestore_WhenTaskStarts_CacheDeletedImmediately(t *testing.T) {
storages.RemoveTestStorage(t.Context(), storage.ID)
workspaces_testing.RemoveTestWorkspace(t.Context(), workspace, router)
- cache_utils.ClearAllCache()
+ cache.GetStore().Clear(t.Context())
}()
backup := backups_controllers_logical.CreateTestBackup(database.ID, storage.ID)
@@ -148,17 +178,26 @@ func Test_MakeRestore_WhenTaskStarts_CacheDeletedImmediately(t *testing.T) {
Version: "16",
},
}
- restoreDatabaseCache.SetWithExpiration(restore.ID.String(), dbCache, 1*time.Hour)
+ require.NoError(t, restoreDatabaseCache.SetWithLifetime(
+ t.Context(),
+ cache.ExpiringValue[RestoreDatabaseCache]{
+ Key: restore.ID.String(),
+ Value: *dbCache,
+ Lifetime: time.Hour,
+ },
+ ))
// Verify cache exists before restore starts
- cachedDB := restoreDatabaseCache.Get(restore.ID.String())
+ cachedDB, err := restoreDatabaseCache.Get(t.Context(), restore.ID.String())
+ require.NoError(t, err)
assert.NotNil(t, cachedDB, "Cache should exist before restore starts")
// Start restore (this will call GetAndDelete)
restorer := CreateTestRestorer()
- restorer.MakeRestore(t.Context(), restore.ID)
+ restorer.MakeRestore(t.Context(), restore.ID, nil)
// Verify cache was deleted immediately
- cachedDBAfter := restoreDatabaseCache.Get(restore.ID.String())
+ cachedDBAfter, err := restoreDatabaseCache.Get(t.Context(), restore.ID.String())
+ require.NoError(t, err)
assert.Nil(t, cachedDBAfter, "Cache should be deleted immediately when task starts")
}
diff --git a/backend/internal/features/restores/restoring/scheduler.go b/backend/internal/features/restores/restoring/scheduler.go
index 38f64aca..8cf66168 100644
--- a/backend/internal/features/restores/restoring/scheduler.go
+++ b/backend/internal/features/restores/restoring/scheduler.go
@@ -10,7 +10,7 @@ import (
"github.com/google/uuid"
restores_core "databasus-backend/internal/features/restores/core"
- cache_utils "databasus-backend/internal/util/cache"
+ "databasus-backend/internal/util/cache"
)
const jobName = "restore_scheduler"
@@ -21,15 +21,19 @@ const (
)
type RestoresScheduler struct {
- restoreRepository *restores_core.RestoreRepository
- lastCheckTime time.Time
- logger *slog.Logger
- restorer *Restorer
- cacheUtil *cache_utils.CacheUtil[RestoreDatabaseCache]
+ restoreRepository *restores_core.RestoreRepository
+ lastCheckTime time.Time
+ logger *slog.Logger
+ restorer restoreExecutor
+ restoreDatabaseCache *cache.JSONStore[RestoreDatabaseCache]
hasRun atomic.Bool
}
+type restoreExecutor interface {
+ MakeRestore(ctx context.Context, restoreID uuid.UUID, databaseCache *RestoreDatabaseCache)
+}
+
func (s *RestoresScheduler) Run(ctx context.Context) {
if s.hasRun.Swap(true) {
panic(fmt.Sprintf("%T.Run() called multiple times", s))
@@ -72,35 +76,18 @@ func (s *RestoresScheduler) IsSchedulerRunning() bool {
func (s *RestoresScheduler) StartRestore(
ctx context.Context,
restoreID uuid.UUID,
- dbCache *RestoreDatabaseCache,
+ databaseCache *RestoreDatabaseCache,
) error {
- // If dbCache not provided, try to fetch from DB (for backward compatibility/testing)
- if dbCache == nil {
- restore, err := s.restoreRepository.FindByID(restoreID)
- if err != nil {
- s.logger.Error(
- "Failed to find restore by ID",
- "restore_id",
- restoreID,
- "error",
- err,
- )
- return err
- }
-
- // Create cache DTO from restore (may be nil if not in DB)
- dbCache = &RestoreDatabaseCache{
- PostgresqlLogicalDatabase: restore.PostgresqlLogicalDatabase,
- MysqlDatabase: restore.MysqlDatabase,
- MariadbDatabase: restore.MariadbDatabase,
- MongodbDatabase: restore.MongodbDatabase,
- }
+ if err := s.restoreDatabaseCache.SetWithLifetime(ctx, cache.ExpiringValue[RestoreDatabaseCache]{
+ Key: restoreID.String(),
+ Value: *databaseCache,
+ Lifetime: time.Hour,
+ }); err != nil {
+ s.logger.WarnContext(ctx, "failed to cache restore metadata", "restore_id", restoreID, "error", err)
}
- // Cache database credentials with 1-hour expiration
- s.cacheUtil.SetWithExpiration(restoreID.String(), dbCache, 1*time.Hour)
-
- go s.restorer.MakeRestore(ctx, restoreID)
+ executionContext := context.WithoutCancel(ctx)
+ go s.restorer.MakeRestore(executionContext, restoreID, databaseCache)
s.logger.InfoContext(ctx, "triggered restore", "restore_id", restoreID)
diff --git a/backend/internal/features/restores/restoring/scheduler_test.go b/backend/internal/features/restores/restoring/scheduler_test.go
new file mode 100644
index 00000000..f06d6db0
--- /dev/null
+++ b/backend/internal/features/restores/restoring/scheduler_test.go
@@ -0,0 +1,63 @@
+package restoring
+
+import (
+ "context"
+ "errors"
+ "io"
+ "log/slog"
+ "testing"
+
+ "github.com/google/uuid"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ postgresql_logical "databasus-backend/internal/features/databases/databases/postgresql/logical"
+ "databasus-backend/internal/util/cache"
+)
+
+type restoreExecution struct {
+ ctx context.Context
+ restoreID uuid.UUID
+ databaseCache *RestoreDatabaseCache
+}
+
+type recordingRestoreExecutor struct {
+ executions chan restoreExecution
+}
+
+func (e *recordingRestoreExecutor) MakeRestore(
+ ctx context.Context,
+ restoreID uuid.UUID,
+ databaseCache *RestoreDatabaseCache,
+) {
+ e.executions <- restoreExecution{ctx, restoreID, databaseCache}
+}
+
+func Test_StartRestore_WhenProviderFails_CarriesMetadataIntoDetachedWorker(t *testing.T) {
+ providerError := errors.New("provider failed")
+ executor := &recordingRestoreExecutor{executions: make(chan restoreExecution, 1)}
+ testLogger := slog.New(slog.NewTextHandler(io.Discard, nil))
+ scheduler := &RestoresScheduler{
+ logger: testLogger,
+ restorer: executor,
+ restoreDatabaseCache: cache.NewJSONStore[RestoreDatabaseCache](
+ NewFailingRestoreMetadataStore(providerError),
+ "restore_db",
+ ),
+ }
+ restoreID := uuid.New()
+ databaseCache := &RestoreDatabaseCache{
+ PostgresqlLogicalDatabase: &postgresql_logical.PostgresqlLogicalDatabase{
+ Host: "database.internal",
+ },
+ }
+ requestContext, cancelRequest := context.WithCancel(t.Context())
+
+ require.NoError(t, scheduler.StartRestore(requestContext, restoreID, databaseCache))
+ cancelRequest()
+ execution := <-executor.executions
+
+ assert.Equal(t, restoreID, execution.restoreID)
+ assert.Same(t, databaseCache, execution.databaseCache)
+ assert.NoError(t, execution.ctx.Err())
+}
diff --git a/backend/internal/features/restores/restoring/testing.go b/backend/internal/features/restores/restoring/testing.go
index e41df5d0..43a50d18 100644
--- a/backend/internal/features/restores/restoring/testing.go
+++ b/backend/internal/features/restores/restoring/testing.go
@@ -21,10 +21,43 @@ import (
tasks_cancellation "databasus-backend/internal/features/tasks/cancellation"
workspaces_controllers "databasus-backend/internal/features/workspaces/controllers"
workspaces_testing "databasus-backend/internal/features/workspaces/testing"
+ "databasus-backend/internal/util/cache"
"databasus-backend/internal/util/encryption"
"databasus-backend/internal/util/logger"
)
+type failingRestoreMetadataStore struct {
+ err error
+}
+
+func NewFailingRestoreMetadataStore(providerError error) cache.Store {
+ return failingRestoreMetadataStore{err: providerError}
+}
+
+func (s failingRestoreMetadataStore) Get(context.Context, string) ([]byte, bool, error) {
+ return nil, false, s.err
+}
+
+func (s failingRestoreMetadataStore) Set(context.Context, cache.Entry) error {
+ return s.err
+}
+
+func (s failingRestoreMetadataStore) CreateIfAbsent(context.Context, cache.Entry) (bool, error) {
+ return false, s.err
+}
+
+func (s failingRestoreMetadataStore) ReadAndDelete(context.Context, string) ([]byte, bool, error) {
+ return nil, false, s.err
+}
+
+func (s failingRestoreMetadataStore) Delete(context.Context, string) error {
+ return s.err
+}
+
+func (s failingRestoreMetadataStore) Clear(context.Context) error {
+ return s.err
+}
+
func CreateTestRouter() *gin.Engine {
router := workspaces_testing.CreateTestRouter(
workspaces_controllers.GetWorkspaceController(),
@@ -47,7 +80,7 @@ func CreateTestRestorer() *Restorer {
logger.GetLogger(),
usecases.GetRestoreBackupUsecase(),
restoreDatabaseCache,
- tasks_cancellation.GetTaskCancelManager(),
+ tasks_cancellation.GetRegistry(),
}
}
@@ -62,7 +95,7 @@ func CreateTestRestorerWithUsecase(usecase restores_core.RestoreBackupUsecase) *
logger.GetLogger(),
usecase,
restoreDatabaseCache,
- tasks_cancellation.GetTaskCancelManager(),
+ tasks_cancellation.GetRegistry(),
}
}
diff --git a/backend/internal/features/restores/service.go b/backend/internal/features/restores/service.go
index 3b9fe282..d4fc7407 100644
--- a/backend/internal/features/restores/service.go
+++ b/backend/internal/features/restores/service.go
@@ -28,18 +28,18 @@ import (
)
type RestoreService struct {
- backupService *backups_services.LogicalBackupService
- restoreRepository *restores_core.RestoreRepository
- storageService *storages.StorageService
- backupConfigService *backups_config_logical.BackupConfigService
- restoreBackupUsecase *usecases.RestoreBackupUsecase
- databaseService *databases.DatabaseService
- logger *slog.Logger
- workspaceService *workspaces_services.WorkspaceService
- auditLogService *audit_logs.AuditLogService
- fieldEncryptor encryption.FieldEncryptor
- diskService *disk.DiskService
- taskCancelManager *tasks_cancellation.TaskCancelManager
+ backupService *backups_services.LogicalBackupService
+ restoreRepository *restores_core.RestoreRepository
+ storageService *storages.StorageService
+ backupConfigService *backups_config_logical.BackupConfigService
+ restoreBackupUsecase *usecases.RestoreBackupUsecase
+ databaseService *databases.DatabaseService
+ logger *slog.Logger
+ workspaceService *workspaces_services.WorkspaceService
+ auditLogService *audit_logs.AuditLogService
+ fieldEncryptor encryption.FieldEncryptor
+ diskService *disk.DiskService
+ taskCancellationRequester *tasks_cancellation.Requester
}
func (s *RestoreService) OnBeforeBackupRemove(backup *backups_core_logical.LogicalBackup) error {
@@ -237,7 +237,7 @@ func (s *RestoreService) CancelRestore(
return errors.New("restore is not in progress")
}
- if err := s.taskCancelManager.CancelTask(restoreID); err != nil {
+ if err := s.taskCancellationRequester.RequestCancellation(ctx, restoreID); err != nil {
return err
}
diff --git a/backend/internal/features/system/healthcheck/service.go b/backend/internal/features/system/healthcheck/service.go
index ee809c99..6f7f001a 100644
--- a/backend/internal/features/system/healthcheck/service.go
+++ b/backend/internal/features/system/healthcheck/service.go
@@ -6,14 +6,12 @@ import (
"fmt"
"log/slog"
"strings"
- "time"
backuping_logical "databasus-backend/internal/features/backups/backups/backuping/logical"
"databasus-backend/internal/features/disk"
verification_agents "databasus-backend/internal/features/verification/agents"
verification_runs "databasus-backend/internal/features/verification/runs"
"databasus-backend/internal/storage"
- cache_utils "databasus-backend/internal/util/cache"
"databasus-backend/internal/util/tools"
)
@@ -31,18 +29,6 @@ func (s *HealthcheckService) IsHealthy(ctx context.Context) error {
// Each branch is a degradation the probe exists to surface. Returning the reason to the caller only
// answers "is it healthy now"; logging it is what leaves a history to read afterwards.
func (s *HealthcheckService) performHealthCheck(ctx context.Context) error {
- pingCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
- defer cancel()
-
- client := cache_utils.GetValkeyClient()
- pingResult := client.Do(pingCtx, client.B().Ping().Build())
- if pingResult.Error() != nil {
- s.logger.WarnContext(ctx, "healthcheck degraded: cannot connect to valkey",
- "error", pingResult.Error())
-
- return errors.New("cannot connect to valkey")
- }
-
diskUsage, err := s.diskService.GetDiskUsage(ctx)
if err != nil {
s.logger.WarnContext(ctx, "healthcheck degraded: cannot get disk usage", "error", err)
diff --git a/backend/internal/features/tasks/cancellation/cancel_manager.go b/backend/internal/features/tasks/cancellation/cancel_manager.go
deleted file mode 100644
index 992ac22a..00000000
--- a/backend/internal/features/tasks/cancellation/cancel_manager.go
+++ /dev/null
@@ -1,76 +0,0 @@
-package task_cancellation
-
-import (
- "context"
- "log/slog"
- "sync"
-
- "github.com/google/uuid"
-
- cache_utils "databasus-backend/internal/util/cache"
-)
-
-const taskCancelChannel = "task:cancel"
-
-type TaskCancelManager struct {
- mu sync.RWMutex
- cancelFuncs map[uuid.UUID]context.CancelFunc
- pubsub *cache_utils.PubSubManager
- logger *slog.Logger
-}
-
-func (m *TaskCancelManager) StartSubscription() {
- ctx := context.Background()
-
- handler := func(message string) {
- taskID, err := uuid.Parse(message)
- if err != nil {
- m.logger.Error("Invalid task ID in cancel message", "message", message, "error", err)
- return
- }
-
- m.mu.Lock()
- defer m.mu.Unlock()
-
- cancelFunc, exists := m.cancelFuncs[taskID]
- if exists {
- cancelFunc()
- delete(m.cancelFuncs, taskID)
- m.logger.Info("Cancelled task via Pub/Sub", "taskID", taskID)
- }
- }
-
- err := m.pubsub.Subscribe(ctx, taskCancelChannel, handler)
- if err != nil {
- m.logger.Error("Failed to subscribe to task cancel channel", "error", err)
- } else {
- m.logger.Info("Successfully subscribed to task cancel channel")
- }
-}
-
-func (m *TaskCancelManager) RegisterTask(task uuid.UUID, cancelFunc context.CancelFunc) {
- m.mu.Lock()
- defer m.mu.Unlock()
- m.cancelFuncs[task] = cancelFunc
- m.logger.Debug("Registered task", "taskID", task)
-}
-
-func (m *TaskCancelManager) CancelTask(taskID uuid.UUID) error {
- ctx := context.Background()
-
- err := m.pubsub.Publish(ctx, taskCancelChannel, taskID.String())
- if err != nil {
- m.logger.Error("Failed to publish cancel message", "taskID", taskID, "error", err)
- return err
- }
-
- m.logger.Info("Published task cancel message", "taskID", taskID)
- return nil
-}
-
-func (m *TaskCancelManager) UnregisterTask(taskID uuid.UUID) {
- m.mu.Lock()
- defer m.mu.Unlock()
- delete(m.cancelFuncs, taskID)
- m.logger.Debug("Unregistered task", "taskID", taskID)
-}
diff --git a/backend/internal/features/tasks/cancellation/cancel_manager_test.go b/backend/internal/features/tasks/cancellation/cancel_manager_test.go
deleted file mode 100644
index e696ac08..00000000
--- a/backend/internal/features/tasks/cancellation/cancel_manager_test.go
+++ /dev/null
@@ -1,200 +0,0 @@
-package task_cancellation
-
-import (
- "context"
- "sync"
- "testing"
- "time"
-
- "github.com/google/uuid"
- "github.com/stretchr/testify/assert"
-)
-
-func Test_RegisterTask_TaskRegisteredSuccessfully(t *testing.T) {
- manager := taskCancelManager
-
- taskID := uuid.New()
- _, cancel := context.WithCancel(t.Context())
- defer cancel()
-
- manager.RegisterTask(taskID, cancel)
-
- manager.mu.RLock()
- _, exists := manager.cancelFuncs[taskID]
- manager.mu.RUnlock()
- assert.True(t, exists, "Task should be registered")
-}
-
-func Test_UnregisterTask_TaskUnregisteredSuccessfully(t *testing.T) {
- manager := taskCancelManager
-
- taskID := uuid.New()
- _, cancel := context.WithCancel(t.Context())
- defer cancel()
-
- manager.RegisterTask(taskID, cancel)
- manager.UnregisterTask(taskID)
-
- manager.mu.RLock()
- _, exists := manager.cancelFuncs[taskID]
- manager.mu.RUnlock()
- assert.False(t, exists, "Task should be unregistered")
-}
-
-func Test_CancelTask_OnSameInstance_TaskCancelledViaPubSub(t *testing.T) {
- manager := taskCancelManager
-
- taskID := uuid.New()
- ctx, cancel := context.WithCancel(t.Context())
-
- cancelled := false
- var mu sync.Mutex
-
- wrappedCancel := func() {
- mu.Lock()
- cancelled = true
- mu.Unlock()
- cancel()
- }
-
- manager.RegisterTask(taskID, wrappedCancel)
- manager.StartSubscription()
- time.Sleep(100 * time.Millisecond)
-
- err := manager.CancelTask(taskID)
- assert.NoError(t, err, "Cancel should not return error")
-
- time.Sleep(500 * time.Millisecond)
-
- mu.Lock()
- wasCancelled := cancelled
- mu.Unlock()
-
- assert.True(t, wasCancelled, "Cancel function should have been called")
- assert.Error(t, ctx.Err(), "Context should be cancelled")
-}
-
-func Test_CancelTask_FromDifferentInstance_TaskCancelledOnRunningInstance(t *testing.T) {
- manager1 := taskCancelManager
- manager2 := taskCancelManager
-
- taskID := uuid.New()
- ctx, cancel := context.WithCancel(t.Context())
-
- cancelled := false
- var mu sync.Mutex
-
- wrappedCancel := func() {
- mu.Lock()
- cancelled = true
- mu.Unlock()
- cancel()
- }
-
- manager1.RegisterTask(taskID, wrappedCancel)
-
- manager1.StartSubscription()
- manager2.StartSubscription()
- time.Sleep(100 * time.Millisecond)
-
- err := manager2.CancelTask(taskID)
- assert.NoError(t, err, "Cancel should not return error")
-
- time.Sleep(500 * time.Millisecond)
-
- mu.Lock()
- wasCancelled := cancelled
- mu.Unlock()
-
- assert.True(t, wasCancelled, "Cancel function should have been called on instance 1")
- assert.Error(t, ctx.Err(), "Context should be cancelled")
-}
-
-func Test_CancelTask_WhenTaskDoesNotExist_NoErrorReturned(t *testing.T) {
- manager := taskCancelManager
-
- manager.StartSubscription()
- time.Sleep(100 * time.Millisecond)
-
- nonExistentID := uuid.New()
- err := manager.CancelTask(nonExistentID)
- assert.NoError(t, err, "Cancelling non-existent task should not error")
-}
-
-func Test_CancelTask_WithMultipleTasks_AllTasksCancelled(t *testing.T) {
- manager := taskCancelManager
-
- numTasks := 5
- taskIDs := make([]uuid.UUID, numTasks)
- contexts := make([]context.Context, numTasks)
- cancels := make([]context.CancelFunc, numTasks)
- cancelledFlags := make([]bool, numTasks)
- var mu sync.Mutex
-
- for i := range numTasks {
- taskIDs[i] = uuid.New()
- contexts[i], cancels[i] = context.WithCancel(t.Context())
-
- idx := i
- wrappedCancel := func() {
- mu.Lock()
- cancelledFlags[idx] = true
- mu.Unlock()
- cancels[idx]()
- }
-
- manager.RegisterTask(taskIDs[i], wrappedCancel)
- }
-
- manager.StartSubscription()
- time.Sleep(100 * time.Millisecond)
-
- for i := range numTasks {
- err := manager.CancelTask(taskIDs[i])
- assert.NoError(t, err, "Cancel should not return error")
- }
-
- time.Sleep(1 * time.Second)
-
- mu.Lock()
- for i := range numTasks {
- assert.True(t, cancelledFlags[i], "Task %d should be cancelled", i)
- assert.Error(t, contexts[i].Err(), "Context %d should be cancelled", i)
- }
- mu.Unlock()
-}
-
-func Test_CancelTask_AfterUnregister_TaskNotCancelled(t *testing.T) {
- manager := taskCancelManager
-
- taskID := uuid.New()
- _, cancel := context.WithCancel(t.Context())
- defer cancel()
-
- cancelled := false
- var mu sync.Mutex
-
- wrappedCancel := func() {
- mu.Lock()
- cancelled = true
- mu.Unlock()
- cancel()
- }
-
- manager.RegisterTask(taskID, wrappedCancel)
- manager.StartSubscription()
- time.Sleep(100 * time.Millisecond)
-
- manager.UnregisterTask(taskID)
-
- err := manager.CancelTask(taskID)
- assert.NoError(t, err, "Cancel should not return error")
-
- time.Sleep(500 * time.Millisecond)
-
- mu.Lock()
- wasCancelled := cancelled
- mu.Unlock()
-
- assert.False(t, wasCancelled, "Cancel function should not be called after unregister")
-}
diff --git a/backend/internal/features/tasks/cancellation/di.go b/backend/internal/features/tasks/cancellation/di.go
index 740b9d68..4b04ae57 100644
--- a/backend/internal/features/tasks/cancellation/di.go
+++ b/backend/internal/features/tasks/cancellation/di.go
@@ -4,23 +4,34 @@ import (
"context"
"sync"
- "github.com/google/uuid"
-
- cache_utils "databasus-backend/internal/util/cache"
"databasus-backend/internal/util/logger"
+ "databasus-backend/internal/util/pubsub"
+)
+
+var (
+ taskCancellationRegistry = NewRegistry()
+ taskCancellationRequester = NewRequester(pubsub.GetBroker(), logger.GetLogger())
+ taskCancellationListener = NewListener(
+ pubsub.GetBroker(),
+ taskCancellationRegistry,
+ logger.GetLogger(),
+ )
)
-var taskCancelManager = &TaskCancelManager{
- sync.RWMutex{},
- make(map[uuid.UUID]context.CancelFunc),
- cache_utils.NewPubSubManager(),
- logger.GetLogger(),
+func GetRegistry() *Registry {
+ return taskCancellationRegistry
+}
+
+func GetRequester() *Requester {
+ return taskCancellationRequester
}
-func GetTaskCancelManager() *TaskCancelManager {
- return taskCancelManager
+func GetListener() *Listener {
+ return taskCancellationListener
}
var SetupDependencies = sync.OnceFunc(func() {
- taskCancelManager.StartSubscription()
+ if err := taskCancellationListener.Start(context.Background()); err != nil {
+ panic(err)
+ }
})
diff --git a/backend/internal/features/tasks/cancellation/listener.go b/backend/internal/features/tasks/cancellation/listener.go
new file mode 100644
index 00000000..5ebd3f5f
--- /dev/null
+++ b/backend/internal/features/tasks/cancellation/listener.go
@@ -0,0 +1,67 @@
+package task_cancellation
+
+import (
+ "context"
+ "log/slog"
+ "sync"
+
+ "github.com/google/uuid"
+
+ "databasus-backend/internal/util/pubsub"
+)
+
+type Listener struct {
+ mutex sync.Mutex
+ broker pubsub.Broker
+ registry *Registry
+ logger *slog.Logger
+ subscription pubsub.Subscription
+}
+
+func NewListener(broker pubsub.Broker, registry *Registry, logger *slog.Logger) *Listener {
+ return &Listener{
+ broker: broker,
+ registry: registry,
+ logger: logger,
+ }
+}
+
+func (l *Listener) Start(ctx context.Context) error {
+ l.mutex.Lock()
+ defer l.mutex.Unlock()
+
+ subscription, err := l.broker.Subscribe(ctx, taskCancelChannel, l.cancelTask)
+ if err != nil {
+ return err
+ }
+ l.subscription = subscription
+
+ l.logger.InfoContext(ctx, "subscribed to task cancellations")
+
+ return nil
+}
+
+func (l *Listener) Close() error {
+ l.mutex.Lock()
+ defer l.mutex.Unlock()
+
+ if l.subscription == nil {
+ return nil
+ }
+
+ err := l.subscription.Close()
+ l.subscription = nil
+
+ return err
+}
+
+func (l *Listener) cancelTask(message string) {
+ taskID, err := uuid.Parse(message)
+ if err != nil {
+ l.logger.Error("received invalid task cancellation", "error", err)
+
+ return
+ }
+
+ l.registry.CancelRegisteredTask(taskID)
+}
diff --git a/backend/internal/features/tasks/cancellation/listener_test.go b/backend/internal/features/tasks/cancellation/listener_test.go
new file mode 100644
index 00000000..5f411c15
--- /dev/null
+++ b/backend/internal/features/tasks/cancellation/listener_test.go
@@ -0,0 +1,50 @@
+package task_cancellation
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ "databasus-backend/internal/util/pubsub"
+)
+
+func Test_Listener_WithSharedBroker_CancelsTasksInEveryRegistry(t *testing.T) {
+ broker := pubsub.NewLocalBroker(NewTestLogger())
+ t.Cleanup(func() { require.NoError(t, broker.Close()) })
+
+ firstRegistry := NewRegistry()
+ secondRegistry := NewRegistry()
+ firstListener := NewListener(broker, firstRegistry, NewTestLogger())
+ secondListener := NewListener(broker, secondRegistry, NewTestLogger())
+ require.NoError(t, firstListener.Start(t.Context()))
+ require.NoError(t, secondListener.Start(t.Context()))
+ t.Cleanup(func() { require.NoError(t, firstListener.Close()) })
+ t.Cleanup(func() { require.NoError(t, secondListener.Close()) })
+
+ taskID := uuid.New()
+ firstContext, cancelFirstTask := context.WithCancel(t.Context())
+ secondContext, cancelSecondTask := context.WithCancel(t.Context())
+ firstRegistry.RegisterTask(taskID, cancelFirstTask)
+ secondRegistry.RegisterTask(taskID, cancelSecondTask)
+
+ taskCancellationRequester := NewRequester(broker, NewTestLogger())
+ require.NoError(t, taskCancellationRequester.RequestCancellation(t.Context(), taskID))
+
+ assertContextCanceled(t, firstContext)
+ assertContextCanceled(t, secondContext)
+}
+
+func assertContextCanceled(t *testing.T, taskContext context.Context) {
+ t.Helper()
+
+ select {
+ case <-taskContext.Done():
+ assert.ErrorIs(t, taskContext.Err(), context.Canceled)
+ case <-time.After(time.Second):
+ t.Fatal("task context was not canceled")
+ }
+}
diff --git a/backend/internal/features/tasks/cancellation/registry.go b/backend/internal/features/tasks/cancellation/registry.go
new file mode 100644
index 00000000..e3b114c7
--- /dev/null
+++ b/backend/internal/features/tasks/cancellation/registry.go
@@ -0,0 +1,46 @@
+package task_cancellation
+
+import (
+ "context"
+ "sync"
+
+ "github.com/google/uuid"
+)
+
+type Registry struct {
+ mutex sync.Mutex
+ cancelTasks map[uuid.UUID]context.CancelFunc
+}
+
+func NewRegistry() *Registry {
+ return &Registry{
+ cancelTasks: make(map[uuid.UUID]context.CancelFunc),
+ }
+}
+
+func (r *Registry) RegisterTask(taskID uuid.UUID, cancelTask context.CancelFunc) {
+ r.mutex.Lock()
+ r.cancelTasks[taskID] = cancelTask
+ r.mutex.Unlock()
+}
+
+func (r *Registry) UnregisterTask(taskID uuid.UUID) {
+ r.mutex.Lock()
+ delete(r.cancelTasks, taskID)
+ r.mutex.Unlock()
+}
+
+func (r *Registry) CancelRegisteredTask(taskID uuid.UUID) {
+ r.mutex.Lock()
+ cancelTask, isRegistered := r.cancelTasks[taskID]
+ if isRegistered {
+ delete(r.cancelTasks, taskID)
+ }
+ r.mutex.Unlock()
+
+ if !isRegistered {
+ return
+ }
+
+ cancelTask()
+}
diff --git a/backend/internal/features/tasks/cancellation/registry_test.go b/backend/internal/features/tasks/cancellation/registry_test.go
new file mode 100644
index 00000000..5f7586ff
--- /dev/null
+++ b/backend/internal/features/tasks/cancellation/registry_test.go
@@ -0,0 +1,26 @@
+package task_cancellation
+
+import (
+ "context"
+ "testing"
+
+ "github.com/google/uuid"
+ "github.com/stretchr/testify/assert"
+)
+
+func Test_Registry_CancelRegisteredTask_CancelsAndRemovesTask(t *testing.T) {
+ registry := NewRegistry()
+ taskID := uuid.New()
+ taskContext, cancelTask := context.WithCancel(t.Context())
+ registry.RegisterTask(taskID, cancelTask)
+
+ registry.CancelRegisteredTask(taskID)
+ assert.ErrorIs(t, taskContext.Err(), context.Canceled)
+
+ secondContext, secondCancelTask := context.WithCancel(t.Context())
+ defer secondCancelTask()
+ registry.RegisterTask(taskID, secondCancelTask)
+ registry.UnregisterTask(taskID)
+ registry.CancelRegisteredTask(taskID)
+ assert.NoError(t, secondContext.Err())
+}
diff --git a/backend/internal/features/tasks/cancellation/requester.go b/backend/internal/features/tasks/cancellation/requester.go
new file mode 100644
index 00000000..7ab82983
--- /dev/null
+++ b/backend/internal/features/tasks/cancellation/requester.go
@@ -0,0 +1,37 @@
+package task_cancellation
+
+import (
+ "context"
+ "fmt"
+ "log/slog"
+
+ "github.com/google/uuid"
+
+ "databasus-backend/internal/util/pubsub"
+)
+
+const taskCancelChannel = "task:cancel"
+
+type Requester struct {
+ broker pubsub.Broker
+ logger *slog.Logger
+}
+
+func NewRequester(broker pubsub.Broker, logger *slog.Logger) *Requester {
+ return &Requester{broker, logger}
+}
+
+func (r *Requester) RequestCancellation(ctx context.Context, taskID uuid.UUID) error {
+ if err := r.broker.Publish(ctx, pubsub.Publication{
+ Channel: taskCancelChannel,
+ Message: taskID.String(),
+ }); err != nil {
+ r.logger.ErrorContext(ctx, "failed to publish task cancellation", "task_id", taskID, "error", err)
+
+ return fmt.Errorf("publish task cancellation: %w", err)
+ }
+
+ r.logger.InfoContext(ctx, "published task cancellation", "task_id", taskID)
+
+ return nil
+}
diff --git a/backend/internal/features/tasks/cancellation/requester_test.go b/backend/internal/features/tasks/cancellation/requester_test.go
new file mode 100644
index 00000000..9b4d65eb
--- /dev/null
+++ b/backend/internal/features/tasks/cancellation/requester_test.go
@@ -0,0 +1,36 @@
+package task_cancellation
+
+import (
+ "context"
+ "errors"
+ "testing"
+
+ "github.com/google/uuid"
+ "github.com/stretchr/testify/assert"
+
+ "databasus-backend/internal/util/pubsub"
+)
+
+type failingBroker struct {
+ err error
+}
+
+func (b failingBroker) Subscribe(context.Context, string, pubsub.MessageHandler) (pubsub.Subscription, error) {
+ return nil, b.err
+}
+
+func (b failingBroker) Publish(context.Context, pubsub.Publication) error {
+ return b.err
+}
+
+func (b failingBroker) Close() error {
+ return b.err
+}
+
+func Test_Requester_WhenBrokerFails_ReturnsError(t *testing.T) {
+ publicationError := errors.New("publication failed")
+ taskCancellationRequester := NewRequester(failingBroker{err: publicationError}, NewTestLogger())
+
+ err := taskCancellationRequester.RequestCancellation(t.Context(), uuid.New())
+ assert.ErrorIs(t, err, publicationError)
+}
diff --git a/backend/internal/features/tasks/cancellation/testing.go b/backend/internal/features/tasks/cancellation/testing.go
new file mode 100644
index 00000000..f9f4e131
--- /dev/null
+++ b/backend/internal/features/tasks/cancellation/testing.go
@@ -0,0 +1,10 @@
+package task_cancellation
+
+import (
+ "io"
+ "log/slog"
+)
+
+func NewTestLogger() *slog.Logger {
+ return slog.New(slog.NewTextHandler(io.Discard, nil))
+}
diff --git a/backend/internal/features/tests/logical/shared/setup.go b/backend/internal/features/tests/logical/shared/setup.go
index 0a1ed78a..8d70bb10 100644
--- a/backend/internal/features/tests/logical/shared/setup.go
+++ b/backend/internal/features/tests/logical/shared/setup.go
@@ -9,18 +9,12 @@ import (
"testing"
"databasus-backend/internal/features/restores/restoring"
- cache_utils "databasus-backend/internal/util/cache"
)
-// Setup clears this worker's Valkey logical DB and installs the in-process
-// restorer the per-engine tests drive through the API. It returns a teardown
-// to run from each engine package's TestMain so every parallel test binary
-// runs against its own isolated control plane.
+// Setup installs the in-process restorer the per-engine tests drive through the API. It returns a
+// teardown to run from each engine package's TestMain so every parallel test binary runs against
+// its own isolated control plane.
func Setup() func() {
- // Best-effort clean slate for this worker's Valkey logical DB; a stale key
- // here is harmless because each worker uses its own DB and namespace.
- _ = cache_utils.ClearAllCache()
-
restorer := restoring.CreateTestRestorer()
cancelRestore := restoring.StartRestorerForTest(&testing.T{}, restorer)
diff --git a/backend/internal/features/tests/physical/postgresql/shared/setup.go b/backend/internal/features/tests/physical/postgresql/shared/setup.go
index c87913eb..7279d759 100644
--- a/backend/internal/features/tests/physical/postgresql/shared/setup.go
+++ b/backend/internal/features/tests/physical/postgresql/shared/setup.go
@@ -8,7 +8,6 @@ import (
"testing"
backuping_physical "databasus-backend/internal/features/backups/backups/backuping/physical"
- cache_utils "databasus-backend/internal/util/cache"
)
// Setup starts the single-instance production wiring the whole suite drives through the HTTP
@@ -19,7 +18,6 @@ import (
// slot. The returned func tears them down after m.Run(). Each version package calls this in its own
// TestMain, so the two majors run with fully isolated control planes.
func Setup() func() {
- _ = cache_utils.ClearAllCache()
backuping_physical.SetupDependencies()
stopScheduler := backuping_physical.StartPhysicalSchedulerForTest(&testing.T{})
diff --git a/backend/internal/features/users/controllers/di.go b/backend/internal/features/users/controllers/di.go
index 4a0eb8a1..6ed9b72d 100644
--- a/backend/internal/features/users/controllers/di.go
+++ b/backend/internal/features/users/controllers/di.go
@@ -2,12 +2,14 @@ package users_controllers
import (
users_services "databasus-backend/internal/features/users/services"
- cache_utils "databasus-backend/internal/util/cache"
+ "databasus-backend/internal/util/logger"
+ "databasus-backend/internal/util/ratelimiter"
)
var userController = &UserController{
users_services.GetUserService(),
- cache_utils.NewRateLimiter(cache_utils.GetValkeyClient()),
+ ratelimiter.GetCounter(),
+ logger.GetLogger(),
}
var settingsController = &SettingsController{
diff --git a/backend/internal/features/users/controllers/user_controller.go b/backend/internal/features/users/controllers/user_controller.go
index 0f209aa8..9bed0d69 100644
--- a/backend/internal/features/users/controllers/user_controller.go
+++ b/backend/internal/features/users/controllers/user_controller.go
@@ -2,6 +2,7 @@ package users_controllers
import (
"errors"
+ "log/slog"
"net/http"
"time"
@@ -12,13 +13,14 @@ import (
users_errors "databasus-backend/internal/features/users/errors"
user_middleware "databasus-backend/internal/features/users/middleware"
users_services "databasus-backend/internal/features/users/services"
- cache_utils "databasus-backend/internal/util/cache"
cloudflare_turnstile "databasus-backend/internal/util/cloudflare_turnstile"
+ "databasus-backend/internal/util/ratelimiter"
)
type UserController struct {
userService *users_services.UserService
- rateLimiter *cache_utils.RateLimiter
+ rateLimiter ratelimiter.Counter
+ logger *slog.Logger
}
func (c *UserController) RegisterRoutes(router *gin.RouterGroup) {
@@ -141,8 +143,14 @@ func (c *UserController) SignIn(ctx *gin.Context) {
}
}
- allowed, _ := c.rateLimiter.CheckLimit(request.Email, "signin", 10, 1*time.Minute)
- if !allowed {
+ isAllowed, err := c.rateLimiter.RecordAttemptAndCheckIsAllowed(
+ ctx.Request.Context(),
+ ratelimiter.Attempt{Scope: "signin", Identifier: request.Email, Limit: 10, Window: time.Minute},
+ )
+ if err != nil {
+ c.logger.ErrorContext(ctx.Request.Context(), "failed to evaluate sign-in rate limit", "error", err)
+ }
+ if err != nil || !isAllowed {
ctx.JSON(
http.StatusTooManyRequests,
gin.H{"error": "Rate limit exceeded. Please try again later."},
@@ -438,13 +446,19 @@ func (c *UserController) SendResetPasswordCode(ctx *gin.Context) {
}
}
- allowed, _ := c.rateLimiter.CheckLimit(
- request.Email,
- "reset-password",
- 3,
- 1*time.Hour,
+ isAllowed, err := c.rateLimiter.RecordAttemptAndCheckIsAllowed(
+ ctx.Request.Context(),
+ ratelimiter.Attempt{
+ Scope: "reset-password",
+ Identifier: request.Email,
+ Limit: 3,
+ Window: time.Hour,
+ },
)
- if !allowed {
+ if err != nil {
+ c.logger.ErrorContext(ctx.Request.Context(), "failed to evaluate password reset rate limit", "error", err)
+ }
+ if err != nil || !isAllowed {
ctx.JSON(
http.StatusTooManyRequests,
gin.H{"error": "Rate limit exceeded. Please try again later."},
@@ -452,7 +466,7 @@ func (c *UserController) SendResetPasswordCode(ctx *gin.Context) {
return
}
- err := c.userService.SendResetPasswordCode(ctx.Request.Context(), request.Email)
+ err = c.userService.SendResetPasswordCode(ctx.Request.Context(), request.Email)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
diff --git a/backend/internal/features/users/controllers/user_controller_test.go b/backend/internal/features/users/controllers/user_controller_test.go
index c11ccb32..f59c9a5d 100644
--- a/backend/internal/features/users/controllers/user_controller_test.go
+++ b/backend/internal/features/users/controllers/user_controller_test.go
@@ -1,12 +1,18 @@
package users_controllers
import (
+ "bytes"
+ "context"
"encoding/json"
+ "errors"
"fmt"
+ "log/slog"
"net/http"
"net/http/httptest"
+ "strings"
"testing"
+ "github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"golang.org/x/oauth2"
@@ -15,9 +21,48 @@ import (
users_enums "databasus-backend/internal/features/users/enums"
users_services "databasus-backend/internal/features/users/services"
users_testing "databasus-backend/internal/features/users/testing"
+ "databasus-backend/internal/util/ratelimiter"
test_utils "databasus-backend/internal/util/testing"
)
+type failingRateLimitCounter struct {
+ err error
+}
+
+func (c failingRateLimitCounter) RecordAttemptAndCheckIsAllowed(
+ context.Context,
+ ratelimiter.Attempt,
+) (bool, error) {
+ return false, c.err
+}
+
+func Test_SignIn_WhenRateLimiterFails_RejectsWithoutLoggingEmail(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ var logOutput bytes.Buffer
+ controller := &UserController{
+ userService: nil,
+ rateLimiter: failingRateLimitCounter{err: errors.New("counter failed")},
+ logger: slog.New(slog.NewTextHandler(&logOutput, nil)),
+ }
+ router := gin.New()
+ router.POST("/users/signin", controller.SignIn)
+
+ email := "[email protected]"
+ request := httptest.NewRequest(
+ http.MethodPost,
+ "/users/signin",
+ strings.NewReader(`{"email":"`+email+`","password":"password"}`),
+ )
+ request.Header.Set("Content-Type", "application/json")
+ response := httptest.NewRecorder()
+
+ router.ServeHTTP(response, request)
+
+ assert.Equal(t, http.StatusTooManyRequests, response.Code)
+ assert.NotContains(t, logOutput.String(), email)
+}
+
func Test_SignUpUser_WithValidData_UserCreated(t *testing.T) {
router := createUserTestRouter()
diff --git a/backend/internal/features/verification/agents/di.go b/backend/internal/features/verification/agents/di.go
index e00341bf..1a68f84b 100644
--- a/backend/internal/features/verification/agents/di.go
+++ b/backend/internal/features/verification/agents/di.go
@@ -2,8 +2,8 @@ package verification_agents
import (
audit_logs "databasus-backend/internal/features/audit_logs"
- cache_utils "databasus-backend/internal/util/cache"
"databasus-backend/internal/util/logger"
+ "databasus-backend/internal/util/ratelimiter"
)
var agentRepository = &AgentRepository{}
@@ -11,7 +11,7 @@ var agentRepository = &AgentRepository{}
var agentService = &AgentService{
agentRepository,
audit_logs.GetAuditLogService(),
- cache_utils.NewRateLimiter(cache_utils.GetValkeyClient()),
+ ratelimiter.GetCounter(),
logger.GetLogger(),
nil,
}
diff --git a/backend/internal/features/verification/agents/middleware.go b/backend/internal/features/verification/agents/middleware.go
index d09027a4..71743a55 100644
--- a/backend/internal/features/verification/agents/middleware.go
+++ b/backend/internal/features/verification/agents/middleware.go
@@ -7,6 +7,8 @@ import (
"github.com/gin-gonic/gin"
"github.com/google/uuid"
+
+ "databasus-backend/internal/util/ratelimiter"
)
const (
@@ -33,14 +35,24 @@ func (s *AgentService) RequireAgentAuth() gin.HandlerFunc {
return
}
- isAllowed, rateLimitErr := s.rateLimiter.CheckLimit(
- agentID.String(), rateLimitAgentEndpoint,
- rateLimitAgentMax, rateLimitAgentWindow,
+ isAllowed, rateLimitErr := s.rateLimiter.RecordAttemptAndCheckIsAllowed(
+ ctx.Request.Context(),
+ ratelimiter.Attempt{
+ Scope: rateLimitAgentEndpoint,
+ Identifier: agentID.String(),
+ Limit: rateLimitAgentMax,
+ Window: rateLimitAgentWindow,
+ },
)
if rateLimitErr != nil {
s.logger.ErrorContext(ctx.Request.Context(), "verification agent rate limit check failed",
- "error", rateLimitErr, "agent_id", agentID, "client_ip", clientIP)
- } else if !isAllowed {
+ "error", rateLimitErr)
+ ctx.AbortWithStatusJSON(http.StatusTooManyRequests,
+ gin.H{"error": "too many requests"})
+
+ return
+ }
+ if !isAllowed {
s.logger.WarnContext(ctx.Request.Context(), "verification agent per-agent rate limit hit",
"agent_id", agentID, "client_ip", clientIP)
ctx.AbortWithStatusJSON(http.StatusTooManyRequests,
diff --git a/backend/internal/features/verification/agents/middleware_test.go b/backend/internal/features/verification/agents/middleware_test.go
new file mode 100644
index 00000000..f35c460b
--- /dev/null
+++ b/backend/internal/features/verification/agents/middleware_test.go
@@ -0,0 +1,51 @@
+package verification_agents
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+ "github.com/google/uuid"
+ "github.com/stretchr/testify/assert"
+
+ "databasus-backend/internal/util/ratelimiter"
+)
+
+type failingRateLimitCounter struct {
+ err error
+}
+
+func (c failingRateLimitCounter) RecordAttemptAndCheckIsAllowed(
+ context.Context,
+ ratelimiter.Attempt,
+) (bool, error) {
+ return false, c.err
+}
+
+func Test_RequireAgentAuth_WhenRateLimiterFails_RejectsWithoutLoggingAgentID(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ var logOutput bytes.Buffer
+ service := &AgentService{
+ rateLimiter: failingRateLimitCounter{err: errors.New("counter failed")},
+ logger: slog.New(slog.NewTextHandler(&logOutput, nil)),
+ }
+ router := gin.New()
+ router.GET("/agents/:agentId", service.RequireAgentAuth(), func(ctx *gin.Context) {
+ ctx.Status(http.StatusNoContent)
+ })
+
+ agentID := uuid.New()
+ request := httptest.NewRequest(http.MethodGet, "/agents/"+agentID.String(), nil)
+ response := httptest.NewRecorder()
+
+ router.ServeHTTP(response, request)
+
+ assert.Equal(t, http.StatusTooManyRequests, response.Code)
+ assert.NotContains(t, logOutput.String(), agentID.String())
+}
diff --git a/backend/internal/features/verification/agents/service.go b/backend/internal/features/verification/agents/service.go
index f13e011b..110bf526 100644
--- a/backend/internal/features/verification/agents/service.go
+++ b/backend/internal/features/verification/agents/service.go
@@ -14,13 +14,13 @@ import (
audit_logs "databasus-backend/internal/features/audit_logs"
audit_logs_models "databasus-backend/internal/features/audit_logs/models"
users_models "databasus-backend/internal/features/users/models"
- cache_utils "databasus-backend/internal/util/cache"
+ "databasus-backend/internal/util/ratelimiter"
)
type AgentService struct {
agentRepository *AgentRepository
auditLogService *audit_logs.AuditLogService
- rateLimiter *cache_utils.RateLimiter
+ rateLimiter ratelimiter.Counter
logger *slog.Logger
heartbeatListeners []AgentHeartbeatedListener
diff --git a/backend/internal/util/cache/cache.go b/backend/internal/util/cache/cache.go
deleted file mode 100644
index d634cf59..00000000
--- a/backend/internal/util/cache/cache.go
+++ /dev/null
@@ -1,139 +0,0 @@
-package cache_utils
-
-import (
- "context"
- "crypto/tls"
- "sync"
-
- "github.com/valkey-io/valkey-go"
-
- "databasus-backend/internal/config"
-)
-
-var valkeyClient valkey.Client
-
-var initCache = sync.OnceFunc(func() {
- env := config.GetEnv()
-
- options := valkey.ClientOption{
- InitAddress: []string{env.ValkeyHost + ":" + env.ValkeyPort},
- Password: env.ValkeyPassword,
- Username: env.ValkeyUsername,
- // 0 in production; per-worker logical DB under `go test` so parallel test
- // binaries never share keys (see config.applyTestWorkerSlot).
- SelectDB: env.ValkeySelectDB,
- }
-
- if env.ValkeyIsSsl {
- options.TLSConfig = &tls.Config{
- ServerName: env.ValkeyHost,
- }
- }
-
- client, err := valkey.NewClient(options)
- if err != nil {
- panic(err)
- }
-
- valkeyClient = client
-})
-
-func getCache() valkey.Client {
- initCache()
- return valkeyClient
-}
-
-func GetValkeyClient() valkey.Client {
- return getCache()
-}
-
-func TestCacheConnection() {
- // Get Valkey client from cache package
- client := getCache()
-
- // Create a simple test cache util for strings
- cacheUtil := NewCacheUtil[string](client, "test:")
-
- // Test data
- testKey := "connection_test"
- testValue := "valkey_is_working"
-
- // Test Set operation
- cacheUtil.Set(testKey, &testValue)
-
- // Test Get operation
- retrievedValue := cacheUtil.Get(testKey)
-
- // Verify the value was retrieved correctly
- if retrievedValue == nil {
- panic("Cache test failed: could not retrieve cached value")
- }
-
- if *retrievedValue != testValue {
- panic("Cache test failed: retrieved value does not match expected")
- }
-
- // Clean up - remove test key
- cacheUtil.Invalidate(testKey)
-
- // Verify cleanup worked
- cleanupCheck := cacheUtil.Get(testKey)
- if cleanupCheck != nil {
- panic("Cache test failed: test key was not properly invalidated")
- }
-}
-
-// FlushAll wipes every key across all Valkey logical DBs (FLUSHALL), regardless
-// of which DB the client selected. Used by cleanup_test_db to reset the cache for
-// every test worker slot at once; ClearAllCache only touches the selected DB.
-func FlushAll() error {
- client := getCache()
-
- ctx, cancel := context.WithTimeout(context.Background(), DefaultQueueTimeout)
- defer cancel()
-
- return client.Do(ctx, client.B().Flushall().Build()).Error()
-}
-
-func ClearAllCache() error {
- pattern := "*"
- cursor := uint64(0)
- batchSize := int64(100)
-
- cacheUtil := NewCacheUtil[string](getCache(), "")
-
- for {
- ctx, cancel := context.WithTimeout(context.Background(), DefaultQueueTimeout)
-
- result := cacheUtil.client.Do(
- ctx,
- cacheUtil.client.B().Scan().Cursor(cursor).Match(pattern).Count(batchSize).Build(),
- )
- cancel()
-
- if result.Error() != nil {
- return result.Error()
- }
-
- scanResult, err := result.AsScanEntry()
- if err != nil {
- return err
- }
-
- if len(scanResult.Elements) > 0 {
- delCtx, delCancel := context.WithTimeout(context.Background(), cacheUtil.timeout)
- cacheUtil.client.Do(
- delCtx,
- cacheUtil.client.B().Del().Key(scanResult.Elements...).Build(),
- )
- delCancel()
- }
-
- cursor = scanResult.Cursor
- if cursor == 0 {
- break
- }
- }
-
- return nil
-}
diff --git a/backend/internal/util/cache/cache_test.go b/backend/internal/util/cache/cache_test.go
deleted file mode 100644
index 5abfc428..00000000
--- a/backend/internal/util/cache/cache_test.go
+++ /dev/null
@@ -1,93 +0,0 @@
-package cache_utils
-
-import (
- "context"
- "testing"
- "time"
-
- "github.com/stretchr/testify/assert"
-)
-
-func Test_ClearAllCache_AfterClear_CacheIsEmpty(t *testing.T) {
- client := getCache()
-
- // Arrange: Set up multiple cache entries with different prefixes
- testKeys := []struct {
- prefix string
- key string
- value string
- }{
- {"test:user:", "user1", "John Doe"},
- {"test:user:", "user2", "Jane Smith"},
- {"test:session:", "session1", "abc123"},
- {"test:session:", "session2", "def456"},
- {"test:data:", "item1", "value1"},
- }
-
- // Set all test keys
- for _, tk := range testKeys {
- cacheUtil := NewCacheUtil[string](client, tk.prefix)
- cacheUtil.Set(tk.key, &tk.value)
- }
-
- // Verify keys were set correctly before clearing
- for _, tk := range testKeys {
- cacheUtil := NewCacheUtil[string](client, tk.prefix)
- retrieved := cacheUtil.Get(tk.key)
- assert.NotNil(t, retrieved, "Key %s should exist before clearing", tk.prefix+tk.key)
- assert.Equal(t, tk.value, *retrieved, "Retrieved value should match set value")
- }
-
- // Act: Clear all cache
- err := ClearAllCache()
-
- // Assert: No error returned
- assert.NoError(t, err, "ClearAllCache should not return an error")
-
- // Assert: All keys should be deleted
- for _, tk := range testKeys {
- cacheUtil := NewCacheUtil[string](client, tk.prefix)
- retrieved := cacheUtil.Get(tk.key)
- assert.Nil(t, retrieved, "Key %s should be deleted after clearing", tk.prefix+tk.key)
- }
-}
-
-func Test_SetWithExpiration_SetsCorrectTTL(t *testing.T) {
- client := getCache()
-
- // Create a cache utility
- testPrefix := "test:ttl:"
- cacheUtil := NewCacheUtil[string](client, testPrefix)
-
- // Set a value with 1-hour expiration
- testKey := "key1"
- testValue := "test value"
- oneHour := 1 * time.Hour
-
- cacheUtil.SetWithExpiration(testKey, &testValue, oneHour)
-
- // Verify the value was set
- retrieved := cacheUtil.Get(testKey)
- assert.NotNil(t, retrieved, "Value should be stored")
- assert.Equal(t, testValue, *retrieved, "Retrieved value should match")
-
- // Check the TTL using Valkey TTL command
- ctx, cancel := context.WithTimeout(t.Context(), DefaultCacheTimeout)
- defer cancel()
-
- fullKey := testPrefix + testKey
- ttlResult := client.Do(ctx, client.B().Ttl().Key(fullKey).Build())
- assert.NoError(t, ttlResult.Error(), "TTL command should not error")
-
- ttlSeconds, err := ttlResult.AsInt64()
- assert.NoError(t, err, "TTL should be retrievable as int64")
-
- // TTL should be approximately 1 hour (3600 seconds)
- // Allow for a small margin (within 10 seconds of 3600)
- expectedTTL := int64(3600)
- assert.GreaterOrEqual(t, ttlSeconds, expectedTTL-10, "TTL should be close to 1 hour")
- assert.LessOrEqual(t, ttlSeconds, expectedTTL, "TTL should not exceed 1 hour")
-
- // Clean up
- cacheUtil.Invalidate(testKey)
-}
diff --git a/backend/internal/util/cache/cachetest/contract.go b/backend/internal/util/cache/cachetest/contract.go
new file mode 100644
index 00000000..53b5c1a2
--- /dev/null
+++ b/backend/internal/util/cache/cachetest/contract.go
@@ -0,0 +1,110 @@
+// Package cachetest provides reusable contract checks for cache providers.
+package cachetest
+
+import (
+ "context"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ "databasus-backend/internal/util/cache"
+)
+
+type StoreFactory func(t *testing.T) cache.Store
+
+func RunStoreContract(t *testing.T, createStore StoreFactory) {
+ t.Helper()
+
+ t.Run("Test_Store_WhenPayloadMutates_CopiesValuesAndClearsEntries", func(t *testing.T) {
+ store := createStore(t)
+ sourcePayload := []byte("value")
+ require.NoError(t, store.Set(t.Context(), cache.Entry{
+ Key: "entry", Payload: sourcePayload, Lifetime: time.Minute,
+ }))
+ sourcePayload[0] = 'X'
+
+ storedPayload, isFound, err := store.Get(t.Context(), "entry")
+ require.NoError(t, err)
+ require.True(t, isFound)
+ assert.Equal(t, []byte("value"), storedPayload)
+ storedPayload[0] = 'X'
+
+ storedPayload, isFound, err = store.Get(t.Context(), "entry")
+ require.NoError(t, err)
+ require.True(t, isFound)
+ assert.Equal(t, []byte("value"), storedPayload)
+
+ require.NoError(t, store.Clear(t.Context()))
+ _, isFound, err = store.Get(t.Context(), "entry")
+ require.NoError(t, err)
+ assert.False(t, isFound)
+ })
+
+ t.Run("Test_Store_WhenContextCanceled_ReturnsError", func(t *testing.T) {
+ store := createStore(t)
+ canceledContext, cancel := context.WithCancel(t.Context())
+ cancel()
+
+ err := store.Set(canceledContext, cache.Entry{
+ Key: "entry", Payload: []byte("value"), Lifetime: time.Minute,
+ })
+ assert.ErrorIs(t, err, context.Canceled)
+ })
+
+ t.Run("Test_CreateIfAbsent_WithConcurrentCallers_ReservesOneCreator", func(t *testing.T) {
+ store := createStore(t)
+ const callerCount = 32
+ var createdCount atomic.Int64
+ operationErrors := make(chan error, callerCount)
+ var waitGroup sync.WaitGroup
+ for callerIndex := range callerCount {
+ waitGroup.Go(func() {
+ isCreated, err := store.CreateIfAbsent(t.Context(), cache.Entry{
+ Key: "reservation", Payload: []byte{byte(callerIndex)}, Lifetime: time.Minute,
+ })
+ operationErrors <- err
+ if isCreated {
+ createdCount.Add(1)
+ }
+ })
+ }
+ waitGroup.Wait()
+ close(operationErrors)
+ for operationError := range operationErrors {
+ require.NoError(t, operationError)
+ }
+ assert.Equal(t, int64(1), createdCount.Load())
+ })
+
+ t.Run("Test_ReadAndDelete_WithConcurrentConsumers_ReturnsOneValue", func(t *testing.T) {
+ store := createStore(t)
+ require.NoError(t, store.Set(t.Context(), cache.Entry{
+ Key: "token", Payload: []byte("secret"), Lifetime: time.Minute,
+ }))
+
+ const callerCount = 32
+ var consumedCount atomic.Int64
+ operationErrors := make(chan error, callerCount)
+ var waitGroup sync.WaitGroup
+ for range callerCount {
+ waitGroup.Go(func() {
+ payload, isFound, err := store.ReadAndDelete(t.Context(), "token")
+ operationErrors <- err
+ if isFound {
+ assert.Equal(t, []byte("secret"), payload)
+ consumedCount.Add(1)
+ }
+ })
+ }
+ waitGroup.Wait()
+ close(operationErrors)
+ for operationError := range operationErrors {
+ require.NoError(t, operationError)
+ }
+ assert.Equal(t, int64(1), consumedCount.Load())
+ })
+}
diff --git a/backend/internal/util/cache/doc.go b/backend/internal/util/cache/doc.go
new file mode 100644
index 00000000..e46dc153
--- /dev/null
+++ b/backend/internal/util/cache/doc.go
@@ -0,0 +1,2 @@
+// Package cache defines transient key-value storage contracts and local providers.
+package cache
diff --git a/backend/internal/util/cache/errors.go b/backend/internal/util/cache/errors.go
new file mode 100644
index 00000000..77915fd4
--- /dev/null
+++ b/backend/internal/util/cache/errors.go
@@ -0,0 +1,8 @@
+package cache
+
+import "errors"
+
+var (
+ ErrInvalidLifetime = errors.New("cache entry lifetime must be positive")
+ ErrPayloadBudgetReached = errors.New("cache payload budget reached")
+)
diff --git a/backend/internal/util/cache/global.go b/backend/internal/util/cache/global.go
new file mode 100644
index 00000000..121dd979
--- /dev/null
+++ b/backend/internal/util/cache/global.go
@@ -0,0 +1,7 @@
+package cache
+
+var defaultStore Store = NewMemoryStore(DefaultPayloadBudgetBytes)
+
+func GetStore() Store {
+ return defaultStore
+}
diff --git a/backend/internal/util/cache/json_store.go b/backend/internal/util/cache/json_store.go
new file mode 100644
index 00000000..e34118f9
--- /dev/null
+++ b/backend/internal/util/cache/json_store.go
@@ -0,0 +1,114 @@
+package cache
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "strconv"
+ "time"
+)
+
+type JSONStore[T any] struct {
+ store Store
+ namespace string
+ defaultLifetime time.Duration
+}
+
+type ExpiringValue[T any] struct {
+ Key string
+ Value T
+ Lifetime time.Duration
+}
+
+func NewJSONStore[T any](store Store, namespace string) *JSONStore[T] {
+ return NewJSONStoreWithLifetime[T](store, namespace, DefaultLifetime)
+}
+
+func NewJSONStoreWithLifetime[T any](
+ store Store,
+ namespace string,
+ defaultLifetime time.Duration,
+) *JSONStore[T] {
+ return &JSONStore[T]{store, namespace, defaultLifetime}
+}
+
+func (s *JSONStore[T]) Get(ctx context.Context, key string) (*T, error) {
+ payload, isFound, err := s.store.Get(ctx, s.key(key))
+ if err != nil {
+ return nil, err
+ }
+ if !isFound {
+ return nil, nil
+ }
+
+ return decode[T](payload)
+}
+
+func (s *JSONStore[T]) Set(ctx context.Context, key string, item T) error {
+ return s.SetWithLifetime(ctx, ExpiringValue[T]{
+ Key: key,
+ Value: item,
+ Lifetime: s.defaultLifetime,
+ })
+}
+
+func (s *JSONStore[T]) SetWithLifetime(
+ ctx context.Context,
+ expiringValue ExpiringValue[T],
+) error {
+ payload, err := json.Marshal(expiringValue.Value)
+ if err != nil {
+ return fmt.Errorf("encode cached value: %w", err)
+ }
+
+ return s.store.Set(ctx, Entry{
+ Key: s.key(expiringValue.Key),
+ Payload: payload,
+ Lifetime: expiringValue.Lifetime,
+ })
+}
+
+func (s *JSONStore[T]) CreateIfAbsent(
+ ctx context.Context,
+ expiringValue ExpiringValue[T],
+) (bool, error) {
+ payload, err := json.Marshal(expiringValue.Value)
+ if err != nil {
+ return false, fmt.Errorf("encode cached value: %w", err)
+ }
+
+ return s.store.CreateIfAbsent(ctx, Entry{
+ Key: s.key(expiringValue.Key),
+ Payload: payload,
+ Lifetime: expiringValue.Lifetime,
+ })
+}
+
+func (s *JSONStore[T]) ReadAndDelete(ctx context.Context, key string) (*T, error) {
+ payload, isFound, err := s.store.ReadAndDelete(ctx, s.key(key))
+ if err != nil {
+ return nil, err
+ }
+ if !isFound {
+ return nil, nil
+ }
+
+ return decode[T](payload)
+}
+
+func (s *JSONStore[T]) Delete(ctx context.Context, key string) error {
+ return s.store.Delete(ctx, s.key(key))
+}
+
+func (s *JSONStore[T]) key(key string) string {
+ return strconv.Itoa(len(s.namespace)) + ":" + s.namespace + ":" + key
+}
+
+func decode[T any](payload []byte) (*T, error) {
+ var item T
+ if err := json.Unmarshal(payload, &item); err != nil {
+ return nil, fmt.Errorf("decode cached value: %w", err)
+ }
+
+ return &item, nil
+}
diff --git a/backend/internal/util/cache/json_store_test.go b/backend/internal/util/cache/json_store_test.go
new file mode 100644
index 00000000..2eda0a1f
--- /dev/null
+++ b/backend/internal/util/cache/json_store_test.go
@@ -0,0 +1,113 @@
+package cache
+
+import (
+ "context"
+ "errors"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+type failingStore struct {
+ err error
+}
+
+func (s failingStore) Get(context.Context, string) ([]byte, bool, error) {
+ return nil, false, s.err
+}
+
+func (s failingStore) Set(context.Context, Entry) error {
+ return s.err
+}
+
+func (s failingStore) CreateIfAbsent(context.Context, Entry) (bool, error) {
+ return false, s.err
+}
+
+func (s failingStore) ReadAndDelete(context.Context, string) ([]byte, bool, error) {
+ return nil, false, s.err
+}
+
+func (s failingStore) Delete(context.Context, string) error {
+ return s.err
+}
+
+func (s failingStore) Clear(context.Context) error {
+ return s.err
+}
+
+func Test_JSONStore_DefaultAndCustomLifetime(t *testing.T) {
+ currentTime := time.Date(2026, time.September, 6, 12, 0, 0, 0, time.UTC)
+ memoryStore := newMemoryStore(1024, func() time.Time { return currentTime })
+ jsonStore := NewJSONStore[string](memoryStore, "values")
+
+ require.NoError(t, jsonStore.Set(t.Context(), "default", "default value"))
+ require.NoError(t, jsonStore.SetWithLifetime(t.Context(), ExpiringValue[string]{
+ Key: "custom",
+ Value: "custom value",
+ Lifetime: time.Minute,
+ }))
+
+ currentTime = currentTime.Add(time.Minute)
+ customValue, err := jsonStore.Get(t.Context(), "custom")
+ require.NoError(t, err)
+ assert.Nil(t, customValue)
+
+ defaultValue, err := jsonStore.Get(t.Context(), "default")
+ require.NoError(t, err)
+ require.NotNil(t, defaultValue)
+ assert.Equal(t, "default value", *defaultValue)
+}
+
+func Test_JSONStore_NamespacesKeepIdenticalKeysIndependent(t *testing.T) {
+ memoryStore := NewMemoryStore(1024)
+ firstStore := NewJSONStore[string](memoryStore, "first")
+ secondStore := NewJSONStore[string](memoryStore, "second")
+
+ require.NoError(t, firstStore.Set(t.Context(), "shared", "first value"))
+ require.NoError(t, secondStore.Set(t.Context(), "shared", "second value"))
+
+ firstValue, err := firstStore.Get(t.Context(), "shared")
+ require.NoError(t, err)
+ require.NotNil(t, firstValue)
+ assert.Equal(t, "first value", *firstValue)
+
+ secondValue, err := secondStore.Get(t.Context(), "shared")
+ require.NoError(t, err)
+ require.NotNil(t, secondValue)
+ assert.Equal(t, "second value", *secondValue)
+}
+
+func Test_JSONStore_WhenPayloadMalformed_ReturnsDecodeError(t *testing.T) {
+ memoryStore := NewMemoryStore(1024)
+ jsonStore := NewJSONStore[string](memoryStore, "values")
+ require.NoError(t, memoryStore.Set(t.Context(), Entry{
+ Key: jsonStore.key("malformed"),
+ Payload: []byte("{"),
+ Lifetime: time.Minute,
+ }))
+
+ value, err := jsonStore.Get(t.Context(), "malformed")
+ assert.Nil(t, value)
+ assert.ErrorContains(t, err, "decode cached value")
+}
+
+func Test_JSONStore_WhenValueCannotBeEncoded_ReturnsEncodeError(t *testing.T) {
+ jsonStore := NewJSONStore[func()](NewMemoryStore(1024), "functions")
+
+ err := jsonStore.Set(t.Context(), "function", func() {})
+ assert.ErrorContains(t, err, "encode cached value")
+}
+
+func Test_JSONStore_WhenProviderFails_ReturnsProviderError(t *testing.T) {
+ providerError := errors.New("provider failed")
+ jsonStore := NewJSONStore[string](failingStore{err: providerError}, "values")
+
+ _, err := jsonStore.Get(t.Context(), "key")
+ assert.ErrorIs(t, err, providerError)
+
+ err = jsonStore.Set(t.Context(), "key", "value")
+ assert.ErrorIs(t, err, providerError)
+}
diff --git a/backend/internal/util/cache/memory_store.go b/backend/internal/util/cache/memory_store.go
new file mode 100644
index 00000000..1147ded7
--- /dev/null
+++ b/backend/internal/util/cache/memory_store.go
@@ -0,0 +1,208 @@
+package cache
+
+import (
+ "context"
+ "sync"
+ "time"
+)
+
+type memoryEntry struct {
+ payload []byte
+ expiresAt time.Time
+ sizeBytes int64
+}
+
+type MemoryStore struct {
+ mutex sync.Mutex
+ entries map[string]memoryEntry
+ payloadBytes int64
+ payloadBudgetBytes int64
+ getCurrentTime func() time.Time
+}
+
+func NewMemoryStore(payloadBudgetBytes int64) *MemoryStore {
+ return newMemoryStore(payloadBudgetBytes, func() time.Time {
+ return time.Now().UTC()
+ })
+}
+
+func newMemoryStore(payloadBudgetBytes int64, getCurrentTime func() time.Time) *MemoryStore {
+ if payloadBudgetBytes <= 0 {
+ panic("cache payload budget must be positive")
+ }
+
+ return &MemoryStore{
+ entries: make(map[string]memoryEntry),
+ payloadBudgetBytes: payloadBudgetBytes,
+ getCurrentTime: getCurrentTime,
+ }
+}
+
+func (s *MemoryStore) Get(ctx context.Context, key string) ([]byte, bool, error) {
+ if err := ctx.Err(); err != nil {
+ return nil, false, err
+ }
+
+ s.mutex.Lock()
+ defer s.mutex.Unlock()
+
+ entry, isFound := s.getLiveEntry(key, s.getCurrentTime())
+ if !isFound {
+ return nil, false, nil
+ }
+
+ return append([]byte(nil), entry.payload...), true, nil
+}
+
+func (s *MemoryStore) Set(ctx context.Context, entry Entry) error {
+ if err := validateWrite(ctx, entry); err != nil {
+ return err
+ }
+
+ s.mutex.Lock()
+ defer s.mutex.Unlock()
+
+ currentTime := s.getCurrentTime()
+
+ return s.store(entry, currentTime)
+}
+
+func (s *MemoryStore) CreateIfAbsent(ctx context.Context, entry Entry) (bool, error) {
+ if err := validateWrite(ctx, entry); err != nil {
+ return false, err
+ }
+
+ s.mutex.Lock()
+ defer s.mutex.Unlock()
+
+ currentTime := s.getCurrentTime()
+ if _, isFound := s.getLiveEntry(entry.Key, currentTime); isFound {
+ return false, nil
+ }
+
+ if err := s.store(entry, currentTime); err != nil {
+ return false, err
+ }
+
+ return true, nil
+}
+
+func (s *MemoryStore) ReadAndDelete(ctx context.Context, key string) ([]byte, bool, error) {
+ if err := ctx.Err(); err != nil {
+ return nil, false, err
+ }
+
+ s.mutex.Lock()
+ defer s.mutex.Unlock()
+
+ entry, isFound := s.getLiveEntry(key, s.getCurrentTime())
+ if !isFound {
+ return nil, false, nil
+ }
+
+ s.remove(key, entry)
+
+ return append([]byte(nil), entry.payload...), true, nil
+}
+
+func (s *MemoryStore) Delete(ctx context.Context, key string) error {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+
+ s.mutex.Lock()
+ defer s.mutex.Unlock()
+
+ if entry, isFound := s.entries[key]; isFound {
+ s.remove(key, entry)
+ }
+
+ return nil
+}
+
+func (s *MemoryStore) Clear(ctx context.Context) error {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+
+ s.mutex.Lock()
+ defer s.mutex.Unlock()
+
+ s.entries = make(map[string]memoryEntry)
+ s.payloadBytes = 0
+
+ return nil
+}
+
+func validateWrite(ctx context.Context, entry Entry) error {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+
+ if entry.Lifetime <= 0 {
+ return ErrInvalidLifetime
+ }
+
+ return nil
+}
+
+func (s *MemoryStore) getLiveEntry(key string, currentTime time.Time) (memoryEntry, bool) {
+ entry, isFound := s.entries[key]
+ if !isFound {
+ return memoryEntry{}, false
+ }
+
+ if !currentTime.Before(entry.expiresAt) {
+ s.remove(key, entry)
+
+ return memoryEntry{}, false
+ }
+
+ return entry, true
+}
+
+func (s *MemoryStore) reclaimExpired(currentTime time.Time) {
+ for key, entry := range s.entries {
+ if !currentTime.Before(entry.expiresAt) {
+ s.remove(key, entry)
+ }
+ }
+}
+
+func (s *MemoryStore) store(entry Entry, currentTime time.Time) error {
+ entrySizeBytes := int64(len(entry.Key) + len(entry.Payload))
+ previousSizeBytes := s.getStoredEntrySizeBytes(entry.Key)
+
+ if s.payloadBytes-previousSizeBytes+entrySizeBytes > s.payloadBudgetBytes {
+ s.reclaimExpired(currentTime)
+ previousSizeBytes = s.getStoredEntrySizeBytes(entry.Key)
+
+ if s.payloadBytes-previousSizeBytes+entrySizeBytes > s.payloadBudgetBytes {
+ return ErrPayloadBudgetReached
+ }
+ }
+
+ payload := append([]byte(nil), entry.Payload...)
+ s.entries[entry.Key] = memoryEntry{
+ payload: payload,
+ expiresAt: currentTime.Add(entry.Lifetime),
+ sizeBytes: entrySizeBytes,
+ }
+ s.payloadBytes = s.payloadBytes - previousSizeBytes + entrySizeBytes
+
+ return nil
+}
+
+func (s *MemoryStore) getStoredEntrySizeBytes(key string) int64 {
+ entry, isFound := s.entries[key]
+ if !isFound {
+ return 0
+ }
+
+ return entry.sizeBytes
+}
+
+func (s *MemoryStore) remove(key string, entry memoryEntry) {
+ delete(s.entries, key)
+ s.payloadBytes -= entry.sizeBytes
+}
diff --git a/backend/internal/util/cache/memory_store_test.go b/backend/internal/util/cache/memory_store_test.go
new file mode 100644
index 00000000..5d1d9f0d
--- /dev/null
+++ b/backend/internal/util/cache/memory_store_test.go
@@ -0,0 +1,113 @@
+package cache
+
+import (
+ "context"
+ "errors"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func Test_MemoryStore_Contract(t *testing.T) {
+ currentTime := time.Date(2026, time.September, 6, 12, 0, 0, 0, time.UTC)
+ store := newMemoryStore(128, func() time.Time { return currentTime })
+ ctx := t.Context()
+
+ require.NoError(t, store.Set(ctx, Entry{Key: "alpha", Payload: []byte("value"), Lifetime: time.Minute}))
+
+ payload, isFound, err := store.Get(ctx, "alpha")
+ require.NoError(t, err)
+ require.True(t, isFound)
+ assert.Equal(t, []byte("value"), payload)
+
+ payload[0] = 'X'
+ storedPayload, isFound, err := store.Get(ctx, "alpha")
+ require.NoError(t, err)
+ require.True(t, isFound)
+ assert.Equal(t, []byte("value"), storedPayload)
+
+ sourcePayload := []byte("source")
+ require.NoError(t, store.Set(ctx, Entry{Key: "copied", Payload: sourcePayload, Lifetime: time.Minute}))
+ sourcePayload[0] = 'X'
+ storedPayload, isFound, err = store.Get(ctx, "copied")
+ require.NoError(t, err)
+ require.True(t, isFound)
+ assert.Equal(t, []byte("source"), storedPayload)
+
+ currentTime = currentTime.Add(time.Minute)
+ _, isFound, err = store.Get(ctx, "alpha")
+ require.NoError(t, err)
+ assert.False(t, isFound)
+
+ require.NoError(t, store.Clear(ctx))
+ _, isFound, err = store.Get(ctx, "copied")
+ require.NoError(t, err)
+ assert.False(t, isFound)
+}
+
+func Test_MemoryStore_WhenContextCanceled_DoesNotChangeEntries(t *testing.T) {
+ store := NewMemoryStore(128)
+ require.NoError(t, store.Set(t.Context(), Entry{Key: "existing", Payload: []byte("value"), Lifetime: time.Minute}))
+
+ canceledContext, cancel := context.WithCancel(t.Context())
+ cancel()
+
+ assert.ErrorIs(
+ t,
+ store.Set(canceledContext, Entry{Key: "new", Payload: []byte("value"), Lifetime: time.Minute}),
+ context.Canceled,
+ )
+ _, isFound, err := store.Get(t.Context(), "new")
+ require.NoError(t, err)
+ assert.False(t, isFound)
+
+ assert.ErrorIs(t, store.Delete(canceledContext, "existing"), context.Canceled)
+ _, isFound, err = store.Get(t.Context(), "existing")
+ require.NoError(t, err)
+ assert.True(t, isFound)
+}
+
+func Test_MemoryStore_WhenPayloadBudgetReached_RejectsWriteWithoutEvictingLiveEntries(t *testing.T) {
+ currentTime := time.Date(2026, time.September, 6, 12, 0, 0, 0, time.UTC)
+ store := newMemoryStore(10, func() time.Time { return currentTime })
+
+ require.NoError(t, store.Set(t.Context(), Entry{Key: "a", Payload: []byte("1234"), Lifetime: time.Minute}))
+ require.NoError(t, store.Set(t.Context(), Entry{Key: "b", Payload: []byte("1234"), Lifetime: time.Minute}))
+
+ err := store.Set(t.Context(), Entry{Key: "c", Payload: []byte("1"), Lifetime: time.Minute})
+ assert.ErrorIs(t, err, ErrPayloadBudgetReached)
+
+ _, isFound, err := store.Get(t.Context(), "a")
+ require.NoError(t, err)
+ assert.True(t, isFound)
+ _, isFound, err = store.Get(t.Context(), "b")
+ require.NoError(t, err)
+ assert.True(t, isFound)
+
+ currentTime = currentTime.Add(time.Minute)
+ require.NoError(t, store.Set(t.Context(), Entry{Key: "r", Payload: []byte("x"), Lifetime: time.Minute}))
+}
+
+func Test_MemoryStore_WhenWriteFitsBudget_DoesNotScanUnrelatedEntries(t *testing.T) {
+ currentTime := time.Date(2026, time.September, 6, 12, 0, 0, 0, time.UTC)
+ store := newMemoryStore(128, func() time.Time { return currentTime })
+
+ require.NoError(t, store.Set(t.Context(), Entry{
+ Key: "expired", Payload: []byte("value"), Lifetime: time.Minute,
+ }))
+ currentTime = currentTime.Add(time.Minute)
+
+ require.NoError(t, store.Set(t.Context(), Entry{
+ Key: "current", Payload: []byte("value"), Lifetime: time.Minute,
+ }))
+ assert.Contains(t, store.entries, "expired")
+}
+
+func Test_MemoryStore_WhenLifetimeInvalid_ReturnsError(t *testing.T) {
+ store := NewMemoryStore(128)
+
+ err := store.Set(t.Context(), Entry{Key: "invalid", Payload: []byte("value")})
+ assert.True(t, errors.Is(err, ErrInvalidLifetime))
+}
diff --git a/backend/internal/util/cache/pubsub.go b/backend/internal/util/cache/pubsub.go
deleted file mode 100644
index 89d411b6..00000000
--- a/backend/internal/util/cache/pubsub.go
+++ /dev/null
@@ -1,201 +0,0 @@
-package cache_utils
-
-import (
- "context"
- "fmt"
- "log/slog"
- "strings"
- "sync"
- "time"
-
- "github.com/google/uuid"
- "github.com/valkey-io/valkey-go"
-
- "databasus-backend/internal/util/logger"
-)
-
-// readyMarkerPrefix tags the self-published probe that Subscribe uses to
-// confirm the SUBSCRIBE command has been accepted by Valkey before
-// returning. The wrapped handler intercepts these markers and never
-// forwards them to the real handler.
-const readyMarkerPrefix = "__databasus_subscribe_ready__:"
-
-// subscribeReadyTimeout caps how long Subscribe waits for its own ready
-// marker to round-trip. 5s is generous enough to absorb a stressed CI host
-// without making subscriber-setup hang dominate startup time.
-const subscribeReadyTimeout = 5 * time.Second
-
-// subscribeReadyPollInterval is how often we re-publish the ready marker
-// while waiting. Each publish before the subscriber is registered is lost
-// (pubsub is fire-and-forget); we keep republishing until the subscriber
-// catches one.
-const subscribeReadyPollInterval = 25 * time.Millisecond
-
-type PubSubManager struct {
- client valkey.Client
- subscriptions map[string]context.CancelFunc
- mu sync.RWMutex
- logger *slog.Logger
-}
-
-func NewPubSubManager() *PubSubManager {
- return &PubSubManager{
- client: getCache(),
- subscriptions: make(map[string]context.CancelFunc),
- logger: logger.GetLogger(),
- }
-}
-
-func (m *PubSubManager) Subscribe(
- ctx context.Context,
- channel string,
- handler func(message string),
-) error {
- m.mu.Lock()
- if _, exists := m.subscriptions[channel]; exists {
- m.mu.Unlock()
- return fmt.Errorf("already subscribed to channel: %s", channel)
- }
-
- subCtx, cancel := context.WithCancel(ctx)
- m.subscriptions[channel] = cancel
- m.mu.Unlock()
-
- readyMarker := readyMarkerPrefix + uuid.New().String()
- ready := make(chan struct{})
- readyOnce := sync.Once{}
-
- wrappedHandler := func(message string) {
- if strings.HasPrefix(message, readyMarkerPrefix) {
- if message == readyMarker {
- readyOnce.Do(func() { close(ready) })
- }
- return
- }
-
- handler(message)
- }
-
- go m.subscriptionLoop(subCtx, channel, wrappedHandler)
-
- if err := m.waitForSubscribeReady(ctx, channel, readyMarker, ready); err != nil {
- cancel()
-
- m.mu.Lock()
- delete(m.subscriptions, channel)
- m.mu.Unlock()
-
- return err
- }
-
- return nil
-}
-
-func (m *PubSubManager) Publish(ctx context.Context, channel, message string) error {
- cmd := m.client.B().Publish().Channel(channel).Message(message).Build()
- result := m.client.Do(ctx, cmd)
-
- if err := result.Error(); err != nil {
- m.logger.ErrorContext(ctx, "failed to publish message to Redis", "channel", channel, "error", err)
- return fmt.Errorf("failed to publish message: %w", err)
- }
-
- return nil
-}
-
-func (m *PubSubManager) Close() error {
- m.mu.Lock()
- defer m.mu.Unlock()
-
- for channel, cancel := range m.subscriptions {
- cancel()
- delete(m.subscriptions, channel)
- }
-
- return nil
-}
-
-func (m *PubSubManager) subscriptionLoop(
- ctx context.Context,
- channel string,
- handler func(message string),
-) {
- defer func() {
- if r := recover(); r != nil {
- m.logger.ErrorContext(ctx, "panic in subscription handler", "channel", channel, "panic", r)
- }
- }()
-
- m.logger.InfoContext(ctx, "starting subscription", "channel", channel)
-
- err := m.client.Receive(
- ctx,
- m.client.B().Subscribe().Channel(channel).Build(),
- func(msg valkey.PubSubMessage) {
- defer func() {
- if r := recover(); r != nil {
- m.logger.ErrorContext(ctx, "panic in message handler", "channel", channel, "panic", r)
- }
- }()
-
- handler(msg.Message)
- },
- )
-
- if err != nil && ctx.Err() == nil {
- m.logger.ErrorContext(ctx, "subscription error", "channel", channel, "error", err)
- } else if ctx.Err() != nil {
- m.logger.InfoContext(ctx, "subscription cancelled", "channel", channel)
- }
-
- m.mu.Lock()
- delete(m.subscriptions, channel)
- m.mu.Unlock()
-}
-
-// waitForSubscribeReady republishes a unique marker on the channel until
-// the subscriber's wrapped handler observes it. This proves that the
-// SUBSCRIBE command has been accepted by Valkey and our handler is in the
-// receive path. Without this handshake, callers race the SUBSCRIBE ack and
-// can publish-then-miss the next message; tests papered over it with
-// time.Sleep heuristics that broke under load.
-func (m *PubSubManager) waitForSubscribeReady(
- ctx context.Context,
- channel string,
- readyMarker string,
- ready <-chan struct{},
-) error {
- deadline := time.NewTimer(subscribeReadyTimeout)
- defer deadline.Stop()
-
- tick := time.NewTicker(subscribeReadyPollInterval)
- defer tick.Stop()
-
- publishCtx, cancelPublish := context.WithTimeout(ctx, subscribeReadyTimeout)
- defer cancelPublish()
-
- publish := func() {
- _ = m.client.Do(
- publishCtx,
- m.client.B().Publish().Channel(channel).Message(readyMarker).Build(),
- ).Error()
- }
-
- publish()
-
- for {
- select {
- case <-ready:
- return nil
-
- case <-tick.C:
- publish()
-
- case <-deadline.C:
- return fmt.Errorf("subscribe ready timeout on channel %q after %s", channel, subscribeReadyTimeout)
-
- case <-ctx.Done():
- return ctx.Err()
- }
- }
-}
diff --git a/backend/internal/util/cache/rate_limiter.go b/backend/internal/util/cache/rate_limiter.go
deleted file mode 100644
index 194ba585..00000000
--- a/backend/internal/util/cache/rate_limiter.go
+++ /dev/null
@@ -1,85 +0,0 @@
-package cache_utils
-
-import (
- "context"
- "fmt"
- "time"
-
- "github.com/google/uuid"
- "github.com/valkey-io/valkey-go"
-)
-
-type RateLimiter struct {
- client valkey.Client
-}
-
-func NewRateLimiter(client valkey.Client) *RateLimiter {
- return &RateLimiter{
- client: client,
- }
-}
-
-func (r *RateLimiter) CheckLimit(
- identifier string,
- endpoint string,
- maxRequests int,
- windowDuration time.Duration,
-) (bool, error) {
- requestID := uuid.New().String()
- keyPrefix := fmt.Sprintf("ratelimit:%s:%s", endpoint, identifier)
- fullKey := fmt.Sprintf("%s:%s", keyPrefix, requestID)
-
- ctx, cancel := context.WithTimeout(context.Background(), DefaultCacheTimeout)
- defer cancel()
-
- // Set the key with TTL
- setCmd := r.client.B().
- Set().
- Key(fullKey).
- Value("1").
- ExSeconds(int64(windowDuration.Seconds())).
- Build()
- if err := r.client.Do(ctx, setCmd).Error(); err != nil {
- return true, fmt.Errorf("failed to set rate limit key: %w", err)
- }
-
- // Count keys matching the pattern
- count, err := r.countKeys(keyPrefix)
- if err != nil {
- return true, fmt.Errorf("failed to count rate limit keys: %w", err)
- }
-
- return count <= maxRequests, nil
-}
-
-func (r *RateLimiter) countKeys(keyPrefix string) (int, error) {
- pattern := keyPrefix + ":*"
- cursor := uint64(0)
- totalCount := 0
-
- for {
- ctx, cancel := context.WithTimeout(context.Background(), DefaultCacheTimeout)
-
- scanCmd := r.client.B().Scan().Cursor(cursor).Match(pattern).Count(100).Build()
- result := r.client.Do(ctx, scanCmd)
- cancel()
-
- if result.Error() != nil {
- return 0, result.Error()
- }
-
- scanResult, err := result.AsScanEntry()
- if err != nil {
- return 0, err
- }
-
- totalCount += len(scanResult.Elements)
- cursor = scanResult.Cursor
-
- if cursor == 0 {
- break
- }
- }
-
- return totalCount, nil
-}
diff --git a/backend/internal/util/cache/store.go b/backend/internal/util/cache/store.go
new file mode 100644
index 00000000..9592b09c
--- /dev/null
+++ b/backend/internal/util/cache/store.go
@@ -0,0 +1,26 @@
+package cache
+
+import (
+ "context"
+ "time"
+)
+
+const (
+ DefaultLifetime = 10 * time.Minute
+ DefaultPayloadBudgetBytes = 256 * 1024 * 1024
+)
+
+type Entry struct {
+ Key string
+ Payload []byte
+ Lifetime time.Duration
+}
+
+type Store interface {
+ Get(ctx context.Context, key string) ([]byte, bool, error)
+ Set(ctx context.Context, entry Entry) error
+ CreateIfAbsent(ctx context.Context, entry Entry) (bool, error)
+ ReadAndDelete(ctx context.Context, key string) ([]byte, bool, error)
+ Delete(ctx context.Context, key string) error
+ Clear(ctx context.Context) error
+}
diff --git a/backend/internal/util/cache/store_contract_test.go b/backend/internal/util/cache/store_contract_test.go
new file mode 100644
index 00000000..4a519fe1
--- /dev/null
+++ b/backend/internal/util/cache/store_contract_test.go
@@ -0,0 +1,14 @@
+package cache_test
+
+import (
+ "testing"
+
+ "databasus-backend/internal/util/cache"
+ "databasus-backend/internal/util/cache/cachetest"
+)
+
+func Test_MemoryStore_ProviderContract(t *testing.T) {
+ cachetest.RunStoreContract(t, func(*testing.T) cache.Store {
+ return cache.NewMemoryStore(64 * 1024)
+ })
+}
diff --git a/backend/internal/util/cache/utils.go b/backend/internal/util/cache/utils.go
deleted file mode 100644
index cd65d4c9..00000000
--- a/backend/internal/util/cache/utils.go
+++ /dev/null
@@ -1,125 +0,0 @@
-package cache_utils
-
-import (
- "context"
- "encoding/json"
- "time"
-
- "github.com/valkey-io/valkey-go"
-
- "databasus-backend/internal/util/logger"
-)
-
-const (
- DefaultCacheTimeout = 10 * time.Second
- DefaultCacheExpiry = 10 * time.Minute
- DefaultQueueTimeout = 30 * time.Second
-)
-
-type CacheUtil[T any] struct {
- client valkey.Client
- prefix string
- timeout time.Duration
- expiry time.Duration
-}
-
-func NewCacheUtil[T any](client valkey.Client, prefix string) *CacheUtil[T] {
- return &CacheUtil[T]{
- client: client,
- prefix: prefix,
- timeout: DefaultCacheTimeout,
- expiry: DefaultCacheExpiry,
- }
-}
-
-func (c *CacheUtil[T]) Get(key string) *T {
- ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
- defer cancel()
-
- fullKey := c.prefix + key
- result := c.client.Do(ctx, c.client.B().Get().Key(fullKey).Build())
-
- if err := result.Error(); err != nil {
- // A missing key is the normal case and says nothing; anything else means the cache is down,
- // which is otherwise indistinguishable from a miss at every call site.
- if !valkey.IsValkeyNil(err) {
- logger.GetLogger().Warn("cache read failed", "cache_key", fullKey, "error", err)
- }
-
- return nil
- }
-
- data, err := result.AsBytes()
- if err != nil {
- logger.GetLogger().Warn("cache read returned an unreadable value", "cache_key", fullKey, "error", err)
-
- return nil
- }
-
- var item T
- if err := json.Unmarshal(data, &item); err != nil {
- logger.GetLogger().Warn("cache read returned malformed json", "cache_key", fullKey, "error", err)
-
- return nil
- }
-
- return &item
-}
-
-func (c *CacheUtil[T]) Set(key string, item *T) {
- ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
- defer cancel()
-
- data, err := json.Marshal(item)
- if err != nil {
- return
- }
-
- fullKey := c.prefix + key
- c.client.Do(ctx, c.client.B().Set().Key(fullKey).Value(string(data)).Ex(c.expiry).Build())
-}
-
-func (c *CacheUtil[T]) SetWithExpiration(key string, item *T, expiry time.Duration) {
- ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
- defer cancel()
-
- data, err := json.Marshal(item)
- if err != nil {
- return
- }
-
- fullKey := c.prefix + key
- c.client.Do(ctx, c.client.B().Set().Key(fullKey).Value(string(data)).Ex(expiry).Build())
-}
-
-func (c *CacheUtil[T]) GetAndDelete(key string) *T {
- ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
- defer cancel()
-
- fullKey := c.prefix + key
- result := c.client.Do(ctx, c.client.B().Getdel().Key(fullKey).Build())
-
- if result.Error() != nil {
- return nil
- }
-
- data, err := result.AsBytes()
- if err != nil {
- return nil
- }
-
- var item T
- if err := json.Unmarshal(data, &item); err != nil {
- return nil
- }
-
- return &item
-}
-
-func (c *CacheUtil[T]) Invalidate(key string) {
- ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
- defer cancel()
-
- fullKey := c.prefix + key
- c.client.Do(ctx, c.client.B().Del().Key(fullKey).Build())
-}
diff --git a/backend/internal/util/pubsub/broker.go b/backend/internal/util/pubsub/broker.go
new file mode 100644
index 00000000..be129907
--- /dev/null
+++ b/backend/internal/util/pubsub/broker.go
@@ -0,0 +1,20 @@
+package pubsub
+
+import "context"
+
+type MessageHandler func(message string)
+
+type Publication struct {
+ Channel string
+ Message string
+}
+
+type Subscription interface {
+ Close() error
+}
+
+type Broker interface {
+ Subscribe(ctx context.Context, channel string, handler MessageHandler) (Subscription, error)
+ Publish(ctx context.Context, publication Publication) error
+ Close() error
+}
diff --git a/backend/internal/util/pubsub/broker_contract_test.go b/backend/internal/util/pubsub/broker_contract_test.go
new file mode 100644
index 00000000..55abaf1d
--- /dev/null
+++ b/backend/internal/util/pubsub/broker_contract_test.go
@@ -0,0 +1,18 @@
+package pubsub_test
+
+import (
+ "io"
+ "log/slog"
+ "testing"
+
+ "databasus-backend/internal/util/pubsub"
+ "databasus-backend/internal/util/pubsub/pubsubtest"
+)
+
+func Test_LocalBroker_ProviderContract(t *testing.T) {
+ pubsubtest.RunBrokerContract(t, func(*testing.T) pubsub.Broker {
+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))
+
+ return pubsub.NewLocalBroker(logger)
+ })
+}
diff --git a/backend/internal/util/pubsub/doc.go b/backend/internal/util/pubsub/doc.go
new file mode 100644
index 00000000..bc3000de
--- /dev/null
+++ b/backend/internal/util/pubsub/doc.go
@@ -0,0 +1,2 @@
+// Package pubsub defines message publication contracts and a process-local broker.
+package pubsub
diff --git a/backend/internal/util/pubsub/errors.go b/backend/internal/util/pubsub/errors.go
new file mode 100644
index 00000000..337eca51
--- /dev/null
+++ b/backend/internal/util/pubsub/errors.go
@@ -0,0 +1,5 @@
+package pubsub
+
+import "errors"
+
+var ErrBrokerClosed = errors.New("publish-subscribe broker is closed")
diff --git a/backend/internal/util/pubsub/global.go b/backend/internal/util/pubsub/global.go
new file mode 100644
index 00000000..48d9a88a
--- /dev/null
+++ b/backend/internal/util/pubsub/global.go
@@ -0,0 +1,9 @@
+package pubsub
+
+import "databasus-backend/internal/util/logger"
+
+var defaultBroker Broker = NewLocalBroker(logger.GetLogger())
+
+func GetBroker() Broker {
+ return defaultBroker
+}
diff --git a/backend/internal/util/pubsub/local_broker.go b/backend/internal/util/pubsub/local_broker.go
new file mode 100644
index 00000000..db71f0a6
--- /dev/null
+++ b/backend/internal/util/pubsub/local_broker.go
@@ -0,0 +1,266 @@
+package pubsub
+
+import (
+ "context"
+ "log/slog"
+ "sync"
+)
+
+type LocalBroker struct {
+ mutex sync.Mutex
+ subscriptions map[string]map[*localSubscription]struct{}
+ publicationGates map[string]chan struct{}
+ isClosed bool
+ logger *slog.Logger
+}
+
+type localSubscription struct {
+ broker *LocalBroker
+ channel string
+ handler MessageHandler
+ subscriptionContext context.Context
+ mailbox chan string
+ stopped chan struct{}
+ done chan struct{}
+ stateMutex sync.Mutex
+ isClosed bool
+ pendingCount int
+}
+
+func NewLocalBroker(logger *slog.Logger) *LocalBroker {
+ return &LocalBroker{
+ subscriptions: make(map[string]map[*localSubscription]struct{}),
+ publicationGates: make(map[string]chan struct{}),
+ logger: logger,
+ }
+}
+
+func (b *LocalBroker) Subscribe(
+ ctx context.Context,
+ channel string,
+ handler MessageHandler,
+) (Subscription, error) {
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+
+ subscription := &localSubscription{
+ broker: b,
+ channel: channel,
+ handler: handler,
+ subscriptionContext: ctx,
+ mailbox: make(chan string),
+ stopped: make(chan struct{}),
+ done: make(chan struct{}),
+ }
+
+ b.mutex.Lock()
+ if b.isClosed {
+ b.mutex.Unlock()
+
+ return nil, ErrBrokerClosed
+ }
+ if b.subscriptions[channel] == nil {
+ b.subscriptions[channel] = make(map[*localSubscription]struct{})
+ }
+ b.subscriptions[channel][subscription] = struct{}{}
+ b.mutex.Unlock()
+
+ go subscription.run()
+
+ return subscription, nil
+}
+
+func (b *LocalBroker) Publish(ctx context.Context, publication Publication) error {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+
+ publicationGate, err := b.getPublicationGate(publication.Channel)
+ if err != nil {
+ return err
+ }
+
+ select {
+ case publicationGate <- struct{}{}:
+ defer func() { <-publicationGate }()
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+
+ subscriptions, err := b.reserveSubscriptions(publication.Channel)
+ if err != nil {
+ return err
+ }
+
+ for subscriptionIndex, subscription := range subscriptions {
+ select {
+ case subscription.mailbox <- publication.Message:
+ subscription.releaseDelivery()
+ case <-ctx.Done():
+ for _, pendingSubscription := range subscriptions[subscriptionIndex:] {
+ pendingSubscription.releaseDelivery()
+ }
+
+ return ctx.Err()
+ }
+ }
+
+ return nil
+}
+
+func (b *LocalBroker) Close() error {
+ b.mutex.Lock()
+ if b.isClosed {
+ b.mutex.Unlock()
+
+ return nil
+ }
+ b.isClosed = true
+
+ subscriptions := make([]*localSubscription, 0)
+ for _, channelSubscriptions := range b.subscriptions {
+ for subscription := range channelSubscriptions {
+ subscriptions = append(subscriptions, subscription)
+ }
+ }
+ b.subscriptions = make(map[string]map[*localSubscription]struct{})
+ b.mutex.Unlock()
+
+ for _, subscription := range subscriptions {
+ if err := subscription.Close(); err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
+func (b *LocalBroker) getPublicationGate(channel string) (chan struct{}, error) {
+ b.mutex.Lock()
+ defer b.mutex.Unlock()
+
+ if b.isClosed {
+ return nil, ErrBrokerClosed
+ }
+
+ publicationGate := b.publicationGates[channel]
+ if publicationGate == nil {
+ publicationGate = make(chan struct{}, 1)
+ b.publicationGates[channel] = publicationGate
+ }
+
+ return publicationGate, nil
+}
+
+func (b *LocalBroker) reserveSubscriptions(channel string) ([]*localSubscription, error) {
+ b.mutex.Lock()
+ defer b.mutex.Unlock()
+
+ if b.isClosed {
+ return nil, ErrBrokerClosed
+ }
+
+ channelSubscriptions := b.subscriptions[channel]
+ subscriptions := make([]*localSubscription, 0, len(channelSubscriptions))
+ for subscription := range channelSubscriptions {
+ if subscription.reserveDelivery() {
+ subscriptions = append(subscriptions, subscription)
+ }
+ }
+
+ return subscriptions, nil
+}
+
+func (b *LocalBroker) closeSubscription(subscription *localSubscription) {
+ b.mutex.Lock()
+ subscription.stateMutex.Lock()
+ if !subscription.isClosed {
+ subscription.isClosed = true
+ channelSubscriptions := b.subscriptions[subscription.channel]
+ delete(channelSubscriptions, subscription)
+ if len(channelSubscriptions) == 0 {
+ delete(b.subscriptions, subscription.channel)
+ }
+ if subscription.pendingCount == 0 {
+ close(subscription.stopped)
+ }
+ }
+ subscription.stateMutex.Unlock()
+ b.mutex.Unlock()
+}
+
+func (s *localSubscription) Close() error {
+ s.broker.closeSubscription(s)
+
+ return nil
+}
+
+func (s *localSubscription) reserveDelivery() bool {
+ s.stateMutex.Lock()
+ defer s.stateMutex.Unlock()
+
+ if s.isClosed || s.subscriptionContext.Err() != nil {
+ return false
+ }
+
+ s.pendingCount++
+
+ return true
+}
+
+func (s *localSubscription) releaseDelivery() {
+ s.stateMutex.Lock()
+ defer s.stateMutex.Unlock()
+
+ s.pendingCount--
+ if s.isClosed && s.pendingCount == 0 {
+ close(s.stopped)
+ }
+}
+
+func (s *localSubscription) run() {
+ defer close(s.done)
+
+ for {
+ select {
+ case message := <-s.mailbox:
+ s.invoke(s.subscriptionContext, message)
+ case <-s.subscriptionContext.Done():
+ s.broker.closeSubscription(s)
+ s.drain(s.subscriptionContext)
+
+ return
+ case <-s.stopped:
+ return
+ }
+ }
+}
+
+func (s *localSubscription) drain(ctx context.Context) {
+ for {
+ select {
+ case message := <-s.mailbox:
+ s.invoke(ctx, message)
+ case <-s.stopped:
+ return
+ }
+ }
+}
+
+func (s *localSubscription) invoke(ctx context.Context, message string) {
+ defer func() {
+ if recovered := recover(); recovered != nil {
+ s.broker.logger.ErrorContext(
+ ctx,
+ "panic in publish-subscribe handler",
+ "channel",
+ s.channel,
+ "panic",
+ recovered,
+ )
+ }
+ }()
+
+ s.handler(message)
+}
diff --git a/backend/internal/util/pubsub/local_broker_test.go b/backend/internal/util/pubsub/local_broker_test.go
new file mode 100644
index 00000000..6f7ddacb
--- /dev/null
+++ b/backend/internal/util/pubsub/local_broker_test.go
@@ -0,0 +1,169 @@
+package pubsub
+
+import (
+ "context"
+ "io"
+ "log/slog"
+ "runtime"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func newTestBroker() *LocalBroker {
+ return NewLocalBroker(slog.New(slog.NewTextHandler(io.Discard, nil)))
+}
+
+func Test_LocalBroker_WhenPublicationContextEnds_ReturnsError(t *testing.T) {
+ broker := newTestBroker()
+ t.Cleanup(func() { require.NoError(t, broker.Close()) })
+
+ handlerStarted := make(chan struct{})
+ releaseHandler := make(chan struct{})
+ _, err := broker.Subscribe(t.Context(), "tasks", func(string) {
+ close(handlerStarted)
+ <-releaseHandler
+ })
+ require.NoError(t, err)
+
+ require.NoError(t, broker.Publish(t.Context(), Publication{Channel: "tasks", Message: "first"}))
+ <-handlerStarted
+
+ publicationContext, cancel := context.WithTimeout(t.Context(), 10*time.Millisecond)
+ defer cancel()
+ err = broker.Publish(publicationContext, Publication{Channel: "tasks", Message: "second"})
+ assert.ErrorIs(t, err, context.DeadlineExceeded)
+ close(releaseHandler)
+}
+
+func Test_LocalSubscription_ClosePreservesSnapshottedPublication(t *testing.T) {
+ broker := newTestBroker()
+ t.Cleanup(func() { require.NoError(t, broker.Close()) })
+
+ handlerStarted := make(chan struct{})
+ releaseHandler := make(chan struct{})
+ messages := make(chan string, 2)
+ subscription, err := broker.Subscribe(t.Context(), "tasks", func(message string) {
+ messages <- message
+ if message == "first" {
+ close(handlerStarted)
+ <-releaseHandler
+ }
+ })
+ require.NoError(t, err)
+ require.NoError(t, broker.Publish(t.Context(), Publication{Channel: "tasks", Message: "first"}))
+ <-handlerStarted
+
+ publicationFinished := make(chan error, 1)
+ go func() {
+ publicationFinished <- broker.Publish(
+ t.Context(),
+ Publication{Channel: "tasks", Message: "second"},
+ )
+ }()
+ local := subscription.(*localSubscription)
+ waitForPendingDeliveries(t, local, 1)
+
+ require.NoError(t, subscription.Close())
+ close(releaseHandler)
+ require.NoError(t, <-publicationFinished)
+ <-local.done
+
+ assert.Equal(t, "first", <-messages)
+ assert.Equal(t, "second", <-messages)
+ require.NoError(t, broker.Publish(t.Context(), Publication{Channel: "tasks", Message: "third"}))
+ select {
+ case message := <-messages:
+ t.Fatalf("closed subscription received %q", message)
+ default:
+ }
+}
+
+func Test_LocalSubscription_HandlerCanCloseItsSubscription(t *testing.T) {
+ broker := newTestBroker()
+ t.Cleanup(func() { require.NoError(t, broker.Close()) })
+
+ closeFinished := make(chan error, 1)
+ var subscription Subscription
+ createdSubscription, err := broker.Subscribe(t.Context(), "tasks", func(string) {
+ closeFinished <- subscription.Close()
+ })
+ require.NoError(t, err)
+ subscription = createdSubscription
+
+ require.NoError(t, broker.Publish(t.Context(), Publication{Channel: "tasks", Message: "cancel"}))
+ require.NoError(t, <-closeFinished)
+}
+
+func Test_LocalSubscription_HandlerCanCloseBroker(t *testing.T) {
+ broker := newTestBroker()
+
+ closeFinished := make(chan error, 1)
+ _, err := broker.Subscribe(t.Context(), "tasks", func(string) {
+ closeFinished <- broker.Close()
+ })
+ require.NoError(t, err)
+
+ require.NoError(t, broker.Publish(t.Context(), Publication{Channel: "tasks", Message: "cancel"}))
+ require.NoError(t, <-closeFinished)
+}
+
+func Test_LocalSubscription_ContextCancellationDrainsSnapshottedPublication(t *testing.T) {
+ broker := newTestBroker()
+ t.Cleanup(func() { require.NoError(t, broker.Close()) })
+
+ subscriptionContext, cancelSubscription := context.WithCancel(t.Context())
+ handlerStarted := make(chan struct{})
+ releaseHandler := make(chan struct{})
+ messages := make(chan string, 2)
+ subscription, err := broker.Subscribe(subscriptionContext, "tasks", func(message string) {
+ messages <- message
+ if message == "first" {
+ close(handlerStarted)
+ <-releaseHandler
+ }
+ })
+ require.NoError(t, err)
+ require.NoError(t, broker.Publish(t.Context(), Publication{Channel: "tasks", Message: "first"}))
+ <-handlerStarted
+
+ publicationFinished := make(chan error, 1)
+ go func() {
+ publicationFinished <- broker.Publish(
+ t.Context(),
+ Publication{Channel: "tasks", Message: "second"},
+ )
+ }()
+ local := subscription.(*localSubscription)
+ waitForPendingDeliveries(t, local, 1)
+ cancelSubscription()
+ close(releaseHandler)
+
+ require.NoError(t, <-publicationFinished)
+ <-local.done
+ assert.Equal(t, "first", <-messages)
+ assert.Equal(t, "second", <-messages)
+}
+
+func waitForPendingDeliveries(t *testing.T, subscription *localSubscription, pendingCount int) {
+ t.Helper()
+
+ deadline := time.After(time.Second)
+ for {
+ subscription.stateMutex.Lock()
+ currentPendingCount := subscription.pendingCount
+ subscription.stateMutex.Unlock()
+ if currentPendingCount == pendingCount {
+ return
+ }
+
+ select {
+ case <-deadline:
+ t.Fatalf("pending delivery count remained %d", currentPendingCount)
+ default:
+ runtime.Gosched()
+ }
+ }
+}
diff --git a/backend/internal/util/pubsub/pubsubtest/contract.go b/backend/internal/util/pubsub/pubsubtest/contract.go
new file mode 100644
index 00000000..cd13838d
--- /dev/null
+++ b/backend/internal/util/pubsub/pubsubtest/contract.go
@@ -0,0 +1,99 @@
+// Package pubsubtest provides reusable contract checks for message brokers.
+package pubsubtest
+
+import (
+ "context"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ "databasus-backend/internal/util/pubsub"
+)
+
+type BrokerFactory func(t *testing.T) pubsub.Broker
+
+func RunBrokerContract(t *testing.T, createBroker BrokerFactory) {
+ t.Helper()
+
+ t.Run("Test_Subscribe_WhenPublished_FansOutImmediately", func(t *testing.T) {
+ broker := createBroker(t)
+ t.Cleanup(func() { require.NoError(t, broker.Close()) })
+ firstMessages := make(chan string, 1)
+ secondMessages := make(chan string, 1)
+
+ _, err := broker.Subscribe(t.Context(), "tasks", func(message string) { firstMessages <- message })
+ require.NoError(t, err)
+ _, err = broker.Subscribe(t.Context(), "tasks", func(message string) { secondMessages <- message })
+ require.NoError(t, err)
+ require.NoError(t, broker.Publish(t.Context(), pubsub.Publication{
+ Channel: "tasks", Message: "cancel",
+ }))
+
+ assert.Equal(t, "cancel", <-firstMessages)
+ assert.Equal(t, "cancel", <-secondMessages)
+ })
+
+ t.Run("Test_Publish_WithOverlappingMessages_PreservesOrder", func(t *testing.T) {
+ broker := createBroker(t)
+ t.Cleanup(func() { require.NoError(t, broker.Close()) })
+ messages := make(chan string, 2)
+ _, err := broker.Subscribe(t.Context(), "tasks", func(message string) { messages <- message })
+ require.NoError(t, err)
+
+ require.NoError(t, broker.Publish(t.Context(), pubsub.Publication{Channel: "tasks", Message: "first"}))
+ require.NoError(t, broker.Publish(t.Context(), pubsub.Publication{Channel: "tasks", Message: "second"}))
+
+ assert.Equal(t, "first", <-messages)
+ assert.Equal(t, "second", <-messages)
+ })
+
+ t.Run("Test_Subscribe_WhenContextCanceled_StopsLaterDelivery", func(t *testing.T) {
+ broker := createBroker(t)
+ t.Cleanup(func() { require.NoError(t, broker.Close()) })
+ subscriptionContext, cancelSubscription := context.WithCancel(t.Context())
+ messages := make(chan string, 1)
+ _, err := broker.Subscribe(
+ subscriptionContext,
+ "tasks",
+ func(message string) { messages <- message },
+ )
+ require.NoError(t, err)
+ cancelSubscription()
+
+ require.NoError(t, broker.Publish(t.Context(), pubsub.Publication{
+ Channel: "tasks", Message: "cancel",
+ }))
+ select {
+ case message := <-messages:
+ t.Fatalf("canceled subscription received %q", message)
+ default:
+ }
+ })
+
+ t.Run("Test_Publish_WhenHandlerPanics_IsolatesOtherSubscriptions", func(t *testing.T) {
+ broker := createBroker(t)
+ t.Cleanup(func() { require.NoError(t, broker.Close()) })
+ healthyMessages := make(chan string, 2)
+ _, err := broker.Subscribe(t.Context(), "tasks", func(string) { panic("handler failed") })
+ require.NoError(t, err)
+ _, err = broker.Subscribe(t.Context(), "tasks", func(message string) { healthyMessages <- message })
+ require.NoError(t, err)
+
+ require.NoError(t, broker.Publish(t.Context(), pubsub.Publication{Channel: "tasks", Message: "first"}))
+ require.NoError(t, broker.Publish(t.Context(), pubsub.Publication{Channel: "tasks", Message: "second"}))
+ assert.Equal(t, "first", <-healthyMessages)
+ assert.Equal(t, "second", <-healthyMessages)
+ })
+
+ t.Run("Test_Close_WhenRepeated_RejectsLaterOperations", func(t *testing.T) {
+ broker := createBroker(t)
+ require.NoError(t, broker.Close())
+ require.NoError(t, broker.Close())
+ assert.ErrorIs(t, broker.Publish(t.Context(), pubsub.Publication{
+ Channel: "tasks", Message: "cancel",
+ }), pubsub.ErrBrokerClosed)
+ _, err := broker.Subscribe(t.Context(), "tasks", func(string) {})
+ assert.ErrorIs(t, err, pubsub.ErrBrokerClosed)
+ })
+}
diff --git a/backend/internal/util/ratelimiter/counter.go b/backend/internal/util/ratelimiter/counter.go
new file mode 100644
index 00000000..fc292ad1
--- /dev/null
+++ b/backend/internal/util/ratelimiter/counter.go
@@ -0,0 +1,17 @@
+package ratelimiter
+
+import (
+ "context"
+ "time"
+)
+
+type Attempt struct {
+ Scope string
+ Identifier string
+ Limit int
+ Window time.Duration
+}
+
+type Counter interface {
+ RecordAttemptAndCheckIsAllowed(ctx context.Context, attempt Attempt) (bool, error)
+}
diff --git a/backend/internal/util/ratelimiter/counter_contract_test.go b/backend/internal/util/ratelimiter/counter_contract_test.go
new file mode 100644
index 00000000..a95a3e0d
--- /dev/null
+++ b/backend/internal/util/ratelimiter/counter_contract_test.go
@@ -0,0 +1,15 @@
+package ratelimiter_test
+
+import (
+ "testing"
+
+ "databasus-backend/internal/util/cache"
+ "databasus-backend/internal/util/ratelimiter"
+ "databasus-backend/internal/util/ratelimiter/ratelimitertest"
+)
+
+func Test_MemoryCounter_ProviderContract(t *testing.T) {
+ ratelimitertest.RunCounterContract(t, func(*testing.T) ratelimiter.Counter {
+ return ratelimiter.NewMemoryCounter(cache.NewMemoryStore(64 * 1024))
+ })
+}
diff --git a/backend/internal/util/ratelimiter/doc.go b/backend/internal/util/ratelimiter/doc.go
new file mode 100644
index 00000000..5804cc85
--- /dev/null
+++ b/backend/internal/util/ratelimiter/doc.go
@@ -0,0 +1,2 @@
+// Package ratelimiter defines request-counting contracts and local rate limiting.
+package ratelimiter
diff --git a/backend/internal/util/ratelimiter/errors.go b/backend/internal/util/ratelimiter/errors.go
new file mode 100644
index 00000000..4967c31b
--- /dev/null
+++ b/backend/internal/util/ratelimiter/errors.go
@@ -0,0 +1,5 @@
+package ratelimiter
+
+import "errors"
+
+var ErrInvalidSettings = errors.New("rate limit and window must be positive")
diff --git a/backend/internal/util/ratelimiter/global.go b/backend/internal/util/ratelimiter/global.go
new file mode 100644
index 00000000..f3a85b92
--- /dev/null
+++ b/backend/internal/util/ratelimiter/global.go
@@ -0,0 +1,9 @@
+package ratelimiter
+
+import "databasus-backend/internal/util/cache"
+
+var defaultCounter Counter = NewMemoryCounter(cache.GetStore())
+
+func GetCounter() Counter {
+ return defaultCounter
+}
diff --git a/backend/internal/util/ratelimiter/memory_counter.go b/backend/internal/util/ratelimiter/memory_counter.go
new file mode 100644
index 00000000..a3fc696f
--- /dev/null
+++ b/backend/internal/util/ratelimiter/memory_counter.go
@@ -0,0 +1,84 @@
+package ratelimiter
+
+import (
+ "context"
+ "strconv"
+ "sync"
+ "time"
+
+ "databasus-backend/internal/util/cache"
+)
+
+const cacheNamespace = "rate_limit_attempts"
+
+type MemoryCounter struct {
+ mutex sync.Mutex
+ attempts *cache.JSONStore[[]time.Time]
+ getCurrentTime func() time.Time
+}
+
+func NewMemoryCounter(store cache.Store) *MemoryCounter {
+ return newMemoryCounter(store, func() time.Time {
+ return time.Now().UTC()
+ })
+}
+
+func newMemoryCounter(store cache.Store, getCurrentTime func() time.Time) *MemoryCounter {
+ return &MemoryCounter{
+ attempts: cache.NewJSONStore[[]time.Time](store, cacheNamespace),
+ getCurrentTime: getCurrentTime,
+ }
+}
+
+func (c *MemoryCounter) RecordAttemptAndCheckIsAllowed(
+ ctx context.Context,
+ attempt Attempt,
+) (bool, error) {
+ if attempt.Limit <= 0 || attempt.Window <= 0 {
+ return false, ErrInvalidSettings
+ }
+ if err := ctx.Err(); err != nil {
+ return false, err
+ }
+
+ c.mutex.Lock()
+ defer c.mutex.Unlock()
+
+ currentTime := c.getCurrentTime()
+ storedAttempts, err := c.attempts.Get(ctx, counterKey(attempt))
+ if err != nil {
+ return false, err
+ }
+
+ windowStart := currentTime.Add(-attempt.Window)
+ recentAttempts := make([]time.Time, 0, attempt.Limit+1)
+ if storedAttempts != nil {
+ for _, recordedAt := range *storedAttempts {
+ if recordedAt.After(windowStart) {
+ recentAttempts = append(recentAttempts, recordedAt)
+ }
+ }
+ }
+
+ recentAttempts = append(recentAttempts, currentTime)
+ if len(recentAttempts) > attempt.Limit+1 {
+ recentAttempts = recentAttempts[len(recentAttempts)-(attempt.Limit+1):]
+ }
+
+ if err := c.attempts.SetWithLifetime(
+ ctx,
+ cache.ExpiringValue[[]time.Time]{
+ Key: counterKey(attempt),
+ Value: recentAttempts,
+ Lifetime: attempt.Window,
+ },
+ ); err != nil {
+ return false, err
+ }
+
+ return len(recentAttempts) <= attempt.Limit, nil
+}
+
+func counterKey(attempt Attempt) string {
+ return strconv.Itoa(len(attempt.Scope)) + ":" + attempt.Scope + ":" + attempt.Identifier
+}
diff --git a/backend/internal/util/ratelimiter/memory_counter_test.go b/backend/internal/util/ratelimiter/memory_counter_test.go
new file mode 100644
index 00000000..bc6cb52d
--- /dev/null
+++ b/backend/internal/util/ratelimiter/memory_counter_test.go
@@ -0,0 +1,100 @@
+package ratelimiter
+
+import (
+ "context"
+ "errors"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ "databasus-backend/internal/util/cache"
+)
+
+type failingStore struct {
+ err error
+}
+
+func (s failingStore) Get(context.Context, string) ([]byte, bool, error) {
+ return nil, false, s.err
+}
+
+func (s failingStore) Set(context.Context, cache.Entry) error {
+ return s.err
+}
+
+func (s failingStore) CreateIfAbsent(context.Context, cache.Entry) (bool, error) {
+ return false, s.err
+}
+
+func (s failingStore) ReadAndDelete(context.Context, string) ([]byte, bool, error) {
+ return nil, false, s.err
+}
+
+func (s failingStore) Delete(context.Context, string) error {
+ return s.err
+}
+
+func (s failingStore) Clear(context.Context) error {
+ return s.err
+}
+
+func Test_MemoryCounter_SlidingWindowCountsRejectedAttempts(t *testing.T) {
+ currentTime := time.Date(2026, time.September, 6, 12, 0, 0, 0, time.UTC)
+ counter := newMemoryCounter(cache.NewMemoryStore(4096), func() time.Time { return currentTime })
+ attempt := Attempt{Scope: "signin", Identifier: "user", Limit: 2, Window: time.Minute}
+
+ isAllowed, err := counter.RecordAttemptAndCheckIsAllowed(t.Context(), attempt)
+ require.NoError(t, err)
+ assert.True(t, isAllowed)
+
+ currentTime = currentTime.Add(10 * time.Second)
+ isAllowed, err = counter.RecordAttemptAndCheckIsAllowed(t.Context(), attempt)
+ require.NoError(t, err)
+ assert.True(t, isAllowed)
+
+ currentTime = currentTime.Add(10 * time.Second)
+ isAllowed, err = counter.RecordAttemptAndCheckIsAllowed(t.Context(), attempt)
+ require.NoError(t, err)
+ assert.False(t, isAllowed)
+
+ currentTime = currentTime.Add(10 * time.Second)
+ isAllowed, err = counter.RecordAttemptAndCheckIsAllowed(t.Context(), attempt)
+ require.NoError(t, err)
+ assert.False(t, isAllowed)
+
+ currentTime = currentTime.Add(40 * time.Second)
+ isAllowed, err = counter.RecordAttemptAndCheckIsAllowed(t.Context(), attempt)
+ require.NoError(t, err)
+ assert.False(t, isAllowed)
+
+ currentTime = currentTime.Add(20 * time.Second)
+ isAllowed, err = counter.RecordAttemptAndCheckIsAllowed(t.Context(), attempt)
+ require.NoError(t, err)
+ assert.True(t, isAllowed)
+}
+
+func Test_MemoryCounter_WhenSettingsInvalid_DoesNotRecordAttempt(t *testing.T) {
+ counter := NewMemoryCounter(cache.NewMemoryStore(4096))
+ attempt := Attempt{Scope: "signin", Identifier: "user", Limit: 0, Window: time.Minute}
+
+ _, err := counter.RecordAttemptAndCheckIsAllowed(t.Context(), attempt)
+ assert.ErrorIs(t, err, ErrInvalidSettings)
+
+ attempt.Limit = 1
+ isAllowed, err := counter.RecordAttemptAndCheckIsAllowed(t.Context(), attempt)
+ require.NoError(t, err)
+ assert.True(t, isAllowed)
+}
+
+func Test_MemoryCounter_WhenProviderFails_ReturnsErrorAndRejectsAttempt(t *testing.T) {
+ providerError := errors.New("provider failed")
+ counter := NewMemoryCounter(failingStore{err: providerError})
+
+ isAllowed, err := counter.RecordAttemptAndCheckIsAllowed(t.Context(), Attempt{
+ Scope: "signin", Identifier: "user", Limit: 1, Window: time.Minute,
+ })
+ assert.False(t, isAllowed)
+ assert.ErrorIs(t, err, providerError)
+}
diff --git a/backend/internal/util/ratelimiter/ratelimitertest/contract.go b/backend/internal/util/ratelimiter/ratelimitertest/contract.go
new file mode 100644
index 00000000..ba5b722f
--- /dev/null
+++ b/backend/internal/util/ratelimiter/ratelimitertest/contract.go
@@ -0,0 +1,95 @@
+// Package ratelimitertest provides reusable contract checks for rate-limit counters.
+package ratelimitertest
+
+import (
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ "databasus-backend/internal/util/ratelimiter"
+)
+
+type CounterFactory func(t *testing.T) ratelimiter.Counter
+
+func RunCounterContract(t *testing.T, createCounter CounterFactory) {
+ t.Helper()
+
+ t.Run("Test_RecordAttemptAndCheckIsAllowed_AfterLimit_CountsRejectedAttempts", func(t *testing.T) {
+ counter := createCounter(t)
+ attempt := ratelimiter.Attempt{
+ Scope: "signin", Identifier: "user", Limit: 2, Window: time.Minute,
+ }
+
+ firstIsAllowed, err := counter.RecordAttemptAndCheckIsAllowed(t.Context(), attempt)
+ require.NoError(t, err)
+ assert.True(t, firstIsAllowed)
+ secondIsAllowed, err := counter.RecordAttemptAndCheckIsAllowed(t.Context(), attempt)
+ require.NoError(t, err)
+ assert.True(t, secondIsAllowed)
+ thirdIsAllowed, err := counter.RecordAttemptAndCheckIsAllowed(t.Context(), attempt)
+ require.NoError(t, err)
+ assert.False(t, thirdIsAllowed)
+ fourthIsAllowed, err := counter.RecordAttemptAndCheckIsAllowed(t.Context(), attempt)
+ require.NoError(t, err)
+ assert.False(t, fourthIsAllowed)
+ })
+
+ t.Run("Test_RecordAttemptAndCheckIsAllowed_WithDifferentKeys_KeepsCountersIndependent", func(t *testing.T) {
+ counter := createCounter(t)
+ attempt := ratelimiter.Attempt{
+ Scope: "signin", Identifier: "first", Limit: 1, Window: time.Minute,
+ }
+ isAllowed, err := counter.RecordAttemptAndCheckIsAllowed(t.Context(), attempt)
+ require.NoError(t, err)
+ assert.True(t, isAllowed)
+ isAllowed, err = counter.RecordAttemptAndCheckIsAllowed(t.Context(), attempt)
+ require.NoError(t, err)
+ assert.False(t, isAllowed)
+
+ attempt.Identifier = "second"
+ isAllowed, err = counter.RecordAttemptAndCheckIsAllowed(t.Context(), attempt)
+ require.NoError(t, err)
+ assert.True(t, isAllowed)
+ attempt.Scope = "password_reset"
+ attempt.Identifier = "first"
+ isAllowed, err = counter.RecordAttemptAndCheckIsAllowed(t.Context(), attempt)
+ require.NoError(t, err)
+ assert.True(t, isAllowed)
+ })
+
+ t.Run("Test_RecordAttemptAndCheckIsAllowed_AtConcurrentBoundary_AllowsOneRequest", func(t *testing.T) {
+ counter := createCounter(t)
+ attempt := ratelimiter.Attempt{
+ Scope: "signin", Identifier: "user", Limit: 5, Window: time.Minute,
+ }
+ for range 4 {
+ isAllowed, err := counter.RecordAttemptAndCheckIsAllowed(t.Context(), attempt)
+ require.NoError(t, err)
+ require.True(t, isAllowed)
+ }
+
+ const callerCount = 32
+ var allowedCount atomic.Int64
+ operationErrors := make(chan error, callerCount)
+ var waitGroup sync.WaitGroup
+ for range callerCount {
+ waitGroup.Go(func() {
+ isAllowed, err := counter.RecordAttemptAndCheckIsAllowed(t.Context(), attempt)
+ operationErrors <- err
+ if isAllowed {
+ allowedCount.Add(1)
+ }
+ })
+ }
+ waitGroup.Wait()
+ close(operationErrors)
+ for operationError := range operationErrors {
+ require.NoError(t, operationError)
+ }
+ assert.Equal(t, int64(1), allowedCount.Load())
+ })
+}
diff --git a/deploy/helm/README.md b/deploy/helm/README.md
index f9c60115..fb726700 100644
--- a/deploy/helm/README.md
+++ b/deploy/helm/README.md
@@ -31,7 +31,9 @@ Then open `http://localhost:4005` in your browser.
| `image.tag` | Image tag | `latest` |
| `image.pullPolicy` | Image pull policy | `Always` |
| `imagePullSecrets` | Image pull secrets | `[]` |
-| `replicaCount` | Number of replicas | `1` |
+
+The chart always renders one application replica because transient cache,
+publish-subscribe and rate-limit state is process-local.
### Custom Root CA
@@ -374,7 +376,7 @@ The app does **not** automount the ServiceAccount token by default
A restricted-PSS values example wiring seccomp, no privilege escalation, AppArmor,
a dedicated ServiceAccount and a read-only root filesystem:
-Databasus, PostgreSQL and Valkey run under one non-root operating-system account
+Databasus and PostgreSQL run under one non-root operating-system account
named `databasus`. The image normally selects the numeric IDs from mounted data
and falls back to `999:999`. If the volume requires different IDs, set `PUID`
and `PGID` through `extraEnv`.
diff --git a/deploy/helm/templates/statefulset.yaml b/deploy/helm/templates/statefulset.yaml
index 8e29b2ff..d68a5156 100644
--- a/deploy/helm/templates/statefulset.yaml
+++ b/deploy/helm/templates/statefulset.yaml
@@ -7,7 +7,7 @@ metadata:
{{- include "databasus.labels" . | nindent 4 }}
spec:
serviceName: {{ include "databasus.fullname" . }}-headless
- replicas: {{ .Values.replicaCount }}
+ replicas: 1
selector:
matchLabels:
{{- include "databasus.selectorLabels" . | nindent 6 }}
diff --git a/deploy/helm/values.yaml b/deploy/helm/values.yaml
index efce0065..2655edef 100644
--- a/deploy/helm/values.yaml
+++ b/deploy/helm/values.yaml
@@ -10,9 +10,6 @@ image:
imagePullSecrets: []
-# StatefulSet configuration
-replicaCount: 1
-
# RootCA setup, need name of secret in same namespace
customRootCA: ""
@@ -48,7 +45,7 @@ extraEnvFrom: []
# Extra volumes and volume mounts for the databasus container.
# Use emptyDir mounts here to satisfy `securityContext.readOnlyRootFilesystem: true`
-# -- PostgreSQL and Valkey need writable /tmp, sockets and runtime dirs.
+# -- PostgreSQL needs writable /tmp, sockets and runtime dirs.
extraVolumes: []
# - name: tmp
# emptyDir: {}
@@ -78,7 +75,7 @@ service:
enabled: true
# Security context for the pod (e.g. fsGroup for volume permissions)
# NOTE: The entrypoint runs as root to select PUID/PGID, prepare volumes and
-# bootstrap PostgreSQL. Databasus, PostgreSQL and Valkey then run as the same
+# bootstrap PostgreSQL. Databasus and PostgreSQL then run as the same
# non-root `databasus` account through gosu. Do not set
# runAsNonRoot or runAsUser here -- it will prevent the container from starting.
podSecurityContext: {}
diff --git a/docker-compose.yml b/docker-compose.yml
index a7d695a7..56e2e710 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -57,21 +57,6 @@ services:
container_name: backend-db-test
shm_size: 10gb
- # Valkey for caching
- backend-valkey:
- image: valkey/valkey:9.0.1-alpine
- ports:
- - "${VALKEY_PORT}:6379"
- volumes:
- - /data
- container_name: backend-valkey
- healthcheck:
- test: ["CMD", "valkey-cli", "ping"]
- interval: 10s
- timeout: 5s
- retries: 5
- start_period: 20s
-
# VictoriaLogs for external logging
backend-victoria-logs:
image: victoriametrics/victoria-logs:latest
@@ -251,4 +236,3 @@ services:
fi
sleep 10
done
-
diff --git a/docker/start.sh b/docker/start.sh
index eb89a5ae..4014144f 100755
--- a/docker/start.sh
+++ b/docker/start.sh
@@ -345,34 +345,6 @@ prepare_and_verify_storage() {
gosu databasus /app/main --test-storage
}
-configure_and_start_valkey() {
- echo "Configuring Valkey cache..."
- cat > /tmp/valkey.conf <<'VALKEY_CONFIG'
-port 6379
-bind 127.0.0.1
-protected-mode yes
-save ""
-maxmemory 256mb
-maxmemory-policy allkeys-lru
-VALKEY_CONFIG
-
- echo "Starting Valkey..."
- gosu databasus valkey-server /tmp/valkey.conf &
-
- echo "Waiting for Valkey to be ready..."
- local valkey_readiness_attempt
- for ((valkey_readiness_attempt = 1; valkey_readiness_attempt <= 30; valkey_readiness_attempt++)); do
- if gosu databasus valkey-cli ping >/dev/null 2>&1; then
- echo "Valkey is ready!"
- return
- fi
- sleep 1
- done
-
- echo "ERROR: Valkey did not become ready." >&2
- return 1
-}
-
initialize_postgresql_cluster() {
if [ -s /databasus-data/pgdata/PG_VERSION ]; then
return
@@ -615,7 +587,6 @@ main() {
reject_legacy_postgresus_volume
configure_runtime_identity
generate_frontend_runtime_configuration
- configure_and_start_valkey
prepare_and_verify_storage
bootstrap_postgresql
reject_legacy_wal_configuration
diff --git a/e2e/docker-storage/run.sh b/e2e/docker-storage/run.sh
index b2a0ae2e..1241c1f6 100755
--- a/e2e/docker-storage/run.sh
+++ b/e2e/docker-storage/run.sh
@@ -155,9 +155,14 @@ assert_storage_permission_failure() {
grep -Fq "Required operation:" <<<"${container_logs}"
grep -Fq "Set PUID and PGID or fix the mounted directory permissions:" <<<"${container_logs}"
grep -Fq "https://databasus.com/advanced-config/#docker-storage-permissions" <<<"${container_logs}"
- grep -Fq "Valkey is ready!" <<<"${container_logs}"
- ! grep -Fq "Starting PostgreSQL..." <<<"${container_logs}"
- ! grep -Fq "Starting Databasus application..." <<<"${container_logs}"
+ if grep -Fq "Starting PostgreSQL..." <<<"${container_logs}"; then
+ echo "PostgreSQL started after a failed storage check" >&2
+ return 1
+ fi
+ if grep -Fq "Starting Databasus application..." <<<"${container_logs}"; then
+ echo "Databasus started after a failed storage check" >&2
+ return 1
+ fi
assert_no_storage_probe_remains "${container_name}"
}
@@ -189,7 +194,6 @@ assert_single_runtime_identity() {
local container_name="$1"
local runtime_gid
local runtime_uid
- local service_name
local service_pid
runtime_uid="$(docker exec "${container_name}" id -u databasus)"
@@ -205,13 +209,11 @@ assert_single_runtime_identity() {
[[ "$(docker exec "${container_name}" stat -c %u /proc/1)" == "${runtime_uid}" ]]
[[ "$(docker exec "${container_name}" stat -c %g /proc/1)" == "${runtime_gid}" ]]
- for service_name in postgres valkey-server; do
- service_pid="$(docker exec "${container_name}" /bin/sh -eu -c '
- pidof "$1" | cut -d" " -f1
- ' sh "${service_name}")"
- [[ "$(docker exec "${container_name}" stat -c %u "/proc/${service_pid}")" == "${runtime_uid}" ]]
- [[ "$(docker exec "${container_name}" stat -c %g "/proc/${service_pid}")" == "${runtime_gid}" ]]
- done
+ service_pid="$(docker exec "${container_name}" /bin/sh -eu -c '
+ pidof postgres | cut -d" " -f1
+ ')"
+ [[ "$(docker exec "${container_name}" stat -c %u "/proc/${service_pid}")" == "${runtime_uid}" ]]
+ [[ "$(docker exec "${container_name}" stat -c %g "/proc/${service_pid}")" == "${runtime_gid}" ]]
}
assert_postgresql_runtime_authentication() {
diff --git a/website/app/(en)/advanced-config/page.tsx b/website/app/(en)/advanced-config/page.tsx
index 0c3e13a6..fa40f6ee 100644
--- a/website/app/(en)/advanced-config/page.tsx
+++ b/website/app/(en)/advanced-config/page.tsx
@@ -418,7 +418,7 @@ export default function AdvancedConfigPage() {
</table>
<p>
- Databasus, PostgreSQL, and Valkey use the same non-root operating-system
+ Databasus and PostgreSQL use the same non-root operating-system
account named <code>databasus</code>.
</p>
diff --git a/website/app/[lang]/advanced-config/content/es.tsx b/website/app/[lang]/advanced-config/content/es.tsx
index c180eb7a..5c118bc8 100644
--- a/website/app/[lang]/advanced-config/content/es.tsx
+++ b/website/app/[lang]/advanced-config/content/es.tsx
@@ -432,7 +432,7 @@ export default function AdvancedConfigPage() {
</table>
<p>
- Databasus, PostgreSQL y Valkey usan la misma cuenta del sistema
+ Databasus y PostgreSQL usan la misma cuenta del sistema
operativo sin privilegios root, llamada <code>databasus</code>.
</p>
diff --git a/website/app/[lang]/advanced-config/content/fr.tsx b/website/app/[lang]/advanced-config/content/fr.tsx
index d7342cee..61320e44 100644
--- a/website/app/[lang]/advanced-config/content/fr.tsx
+++ b/website/app/[lang]/advanced-config/content/fr.tsx
@@ -436,7 +436,7 @@ export default function AdvancedConfigPage() {
</table>
<p>
- Databasus, PostgreSQL et Valkey utilisent le même compte du
+ Databasus et PostgreSQL utilisent le même compte du
système d&apos;exploitation sans privilèges root, nommé{" "}
<code>databasus</code>.
</p>
diff --git a/website/app/[lang]/advanced-config/content/pt.tsx b/website/app/[lang]/advanced-config/content/pt.tsx
index bd8dfe77..1ca7aa7c 100644
--- a/website/app/[lang]/advanced-config/content/pt.tsx
+++ b/website/app/[lang]/advanced-config/content/pt.tsx
@@ -425,7 +425,7 @@ export default function AdvancedConfigPage() {
</table>
<p>
- Databasus, PostgreSQL e Valkey usam a mesma conta do sistema
+ Databasus e PostgreSQL usam a mesma conta do sistema
operacional sem privilégios root chamada <code>databasus</code>.
</p>
diff --git a/website/app/[lang]/advanced-config/content/ru.tsx b/website/app/[lang]/advanced-config/content/ru.tsx
index c2fa5b31..aa71b07e 100644
--- a/website/app/[lang]/advanced-config/content/ru.tsx
+++ b/website/app/[lang]/advanced-config/content/ru.tsx
@@ -422,7 +422,7 @@ export default function AdvancedConfigPage() {
</table>
<p>
- Databasus, PostgreSQL и Valkey работают под одной учетной записью
+ Databasus и PostgreSQL работают под одной учетной записью
ОС без прав root с именем <code>databasus</code>.
</p>
diff --git a/website/app/[lang]/advanced-config/content/zh.tsx b/website/app/[lang]/advanced-config/content/zh.tsx
index c1ac72fc..db0d9719 100644
--- a/website/app/[lang]/advanced-config/content/zh.tsx
+++ b/website/app/[lang]/advanced-config/content/zh.tsx
@@ -401,7 +401,7 @@ export default function AdvancedConfigPage() {
</table>
<p>
- Databasus、PostgreSQL 和 Valkey 使用同一个名为 <code>databasus</code> 的无 root 权限操作系统账户。
+ Databasus 和 PostgreSQL 使用同一个名为 <code>databasus</code> 的无 root 权限操作系统账户。
</p>
<p>