Compare commits

...
9 Commits
Author SHA1 Message Date
lukaszraczylo 6f604367da fix(websocket): start the event loop and throttle drop warnings
The app built the websocket server but never called Start, so nothing read the 256-slot broadcast channel. After the first 256 events every event was dropped with a warning, and dashboard clients blocked forever on the unbuffered register channel, leaking a goroutine per connection and never receiving events. Run now starts the loop with the other workers. Dropped events are counted in gohoarder_websocket_events_dropped_total and warned about at most once a minute.
2026-11-23 12:56:32 +00:00
lukaszraczylo c98720c02e docs: describe cache.idle_ttl and the cleanup run
Document the new idle_ttl key in the example config and the README.
Explain that artifacts never expire by age and that metadata entries
refresh after default_ttl.
2026-11-23 12:50:01 +00:00
lukaszraczylo 9a44683fbd feat(ui): note the idle eviction window on the stats page
The stats page now reads idle_ttl from the stats API. It shows
"Cached items not requested for 7 days are removed." in an info alert.
The note stays hidden when idle eviction is off.
2026-11-23 12:50:00 +00:00
lukaszraczylo d6edd40d79 feat(cache): evict items idle past cache.idle_ttl
Every cached item got a 7-day expiry at store time. A popular tarball
left the cache seven days after it was cached, however often clients
requested it.

Artifacts now get no age-based expiry. Cleanup removes any item whose
last_accessed is older than cache.idle_ttl (default 168h, 0 disables).
It reads the items in bounded batches of 500 through the indexed
last_accessed column and deletes them through deletePackage. Metadata
entries keep the freshness expiry from default_ttl.

Startup and each cleanup run clear the expiry that earlier versions set
on artifact rows. Cleanup records the idle and ttl eviction reasons and
logs the count and bytes freed. The stats API reports idle_ttl in
seconds. Package deletes are soft deletes and no history table has a
foreign key to packages, so download history stays intact.
2026-11-23 12:49:47 +00:00
lukaszraczylo 99c885cd88 fix(ui): stack package rows on phones and drop pager edge buttons
At 320px the package name shared a row with the registry badge, size and downloads, so it had about 90px and scoped names broke mid-word. Below sm the name now takes the full width with the meta row underneath. The pager's first and last buttons wrapped onto a second line inside the card; the page list already reaches the first and last pages, so the edge buttons are off.
2026-11-23 12:29:40 +00:00
lukaszraczylo c022824d2b fix(ui): swap native key prompt for a dialog; add favicon 2026-11-23 03:18:43 +00:00
lukaszraczylo 5420480ef8 fix(metadata): keep created_at on CVE bypass edit; repair MySQL suite 2026-11-23 03:18:42 +00:00
lukaszraczylo bde9eebf3d fix(ui): show the PyPI release version in every version display 2026-11-23 03:18:42 +00:00
github-actions[bot]andGitHub f65c0cc1f3 chore(deps): update dependencies
Automated dependency update. All tests passed.
2026-11-23 03:17:22 +00:00
44 changed files with 1730 additions and 186 deletions
+12 -1
View File
@@ -233,7 +233,9 @@ security:
enabled: true
cache:
default_ttl: 86400 # 24 hours in seconds
default_ttl: 24h # Freshness window for metadata pages (version lists, package documents)
idle_ttl: 168h # Remove cached items not requested for 7 days; 0 disables
cleanup_interval: 1h
logging:
level: "info" # debug, info, warn, error
@@ -245,6 +247,15 @@ upstream:
go: "https://proxy.golang.org"
```
#### Cache cleanup
Every `cleanup_interval` the cleanup run removes:
- **Idle items.** Any cached item, artifact or metadata page, whose last request is older than `idle_ttl` (default `168h`, seven days). Each request, hit or miss, resets the clock. Set `idle_ttl: 0` to turn idle eviction off.
- **Stale metadata.** Version lists, package documents and Go `.mod`/`.info` files past `default_ttl`. They refresh on the next request.
Artifacts (tarballs, wheels, module zips) never expire by age, so a package that clients keep requesting stays cached. Size-based LRU eviction at `max_size_bytes` is unchanged. Removed items keep their download history in the statistics.
### Environment Variables
All configuration values can be overridden with environment variables:
+2 -1
View File
@@ -89,8 +89,9 @@ metadata:
log_level: "warn" # GORM log level: silent, error, warn, info
cache:
default_ttl: "168h" # 7 days
default_ttl: "168h" # Freshness window for metadata pages (version lists, packuments, .mod/.info); artifacts never expire by age
cleanup_interval: "1h"
idle_ttl: "168h" # Remove cached items not requested for this long; "0" disables
max_size_bytes: 536870912000 # 500GB
per_project_quota: 53687091200 # 50GB
ttl_overrides:
+3
View File
@@ -5,3 +5,6 @@ VITE_BACKEND_URL=http://localhost:8080
# Frontend dev server port
# The Vite development server will run on this port
VITE_PORT=5173
# Origin sent on the dev WebSocket proxy, for a backend with an allowed-origins list
# VITE_WS_ORIGIN=https://gohoarder.example.com
+1
View File
@@ -4,6 +4,7 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="color-scheme" content="light dark" />
<link rel="icon" href="data:," />
<title>GoHoarder dashboard</title>
</head>
<body>
+144 -87
View File
@@ -24,19 +24,19 @@ importers:
version: 7.3.1
'@perfect-design/ui':
specifier: 0.3.10
version: 0.3.10([email protected](@vue/[email protected])([email protected])([email protected]5([email protected])))([email protected])([email protected]5([email protected]))
version: 0.3.10([email protected](@vue/[email protected])([email protected])([email protected]6([email protected])))([email protected])([email protected]6([email protected]))
axios:
specifier: ^1.20.0
version: 1.21.1
version: 1.21.1([email protected]([email protected]))([email protected])
pinia:
specifier: ^4.0.0
version: 4.1.0(@vue/[email protected])([email protected])([email protected]5([email protected]))
version: 4.1.0(@vue/[email protected])([email protected])([email protected]6([email protected]))
vue:
specifier: ^3.5.26
version: 3.5.45([email protected])
version: 3.5.46([email protected])
vue-router:
specifier: ^5.3.1
version: 5.5.1(@vue/[email protected])([email protected])([email protected](@vue/[email protected])([email protected])([email protected]5([email protected])))([email protected])([email protected]([email protected])([email protected]))([email protected]5([email protected]))
version: 5.5.1(@vue/[email protected])([email protected])([email protected](@vue/[email protected])([email protected])([email protected]6([email protected])))([email protected])([email protected]([email protected])([email protected]))([email protected]6([email protected]))
devDependencies:
'@tailwindcss/vite':
specifier: ^4.3.3
@@ -46,13 +46,13 @@ importers:
version: 7.0.1(@testing-library/[email protected])([email protected]([email protected])([email protected]([email protected])([email protected])))
'@testing-library/vue':
specifier: ^8.1.0
version: 8.1.0(@vue/[email protected]5)(@vue/[email protected])(@vue/[email protected]5)([email protected]5([email protected]))
version: 8.1.0(@vue/[email protected]6)(@vue/[email protected])(@vue/[email protected]6)([email protected]6([email protected]))
'@vitejs/plugin-vue':
specifier: ^6.0.3
version: 6.0.11([email protected]([email protected])([email protected]))([email protected]5([email protected]))
version: 6.0.11([email protected]([email protected])([email protected]))([email protected]6([email protected]))
'@vue/test-utils':
specifier: ^2.4.6
version: 2.6.0(@vue/[email protected]5)(@vue/[email protected]5)([email protected]5([email protected]))
version: 2.6.0(@vue/[email protected]6)(@vue/[email protected]6)([email protected]6([email protected]))
jsdom:
specifier: ^31.0.0
version: 31.0.1
@@ -654,18 +654,30 @@ packages:
'@vue/[email protected]':
resolution: {integrity: sha512-XGHJrM6ufZARAc/w+tyOswStw9tdKiqCKBScI4gGaNxD+aaGu/HQWgKJ+JItjRLPqenQ7iE7G8AJC7T5ew1p+g==}
'@vue/[email protected]':
resolution: {integrity: sha512-yb+N8/mgBcoeqCJPVyJI/D3OphLrSMXnB3ZQUNmRLU/1fsMW4bFfdJWNi9oIj7+EA3ULKKkP7b/VCpcYQYeiuQ==}
'@vue/[email protected]':
resolution: {integrity: sha512-W5AoBFWdw1lQAKiHowkfgFKFab82oSRT6sGsPfw/q1GRjsy/ZJFLHGhJyBRIFN9APLTUduDH9U2JAiPOIyKuYg==}
'@vue/[email protected]':
resolution: {integrity: sha512-LbP2d19GSOYGPmvMBBCVJVlv7TKtjM1Cfeyu3cYia720pknZP+1cLX7H5MVatvruT6MuJhiPuNbQBW/MDn/EwA==}
'@vue/[email protected]':
resolution: {integrity: sha512-Bj3lCSw3DQnDRDxw115XqdLDd0+18Nftlgd8OXSGG+ud74hxJIE17eYrM+VWgQrTMsvJbLh9Hzf2MkwAzru36Q==}
'@vue/[email protected]':
resolution: {integrity: sha512-MKFjb2UX0M/l/jhfzqMLrI8VM4pfvFKG3pqFZkSZFHRLtNld/O4RtUPZFWSwhro/14qP88UQEkWzHxAZAQ0tsw==}
'@vue/[email protected]':
resolution: {integrity: sha512-hjUvMxGh+QIgegwksfp6BRBYleE/a8veZHvTR6sa+o+bM4HU+WnrUZlhN0X+pDcsl8Lhwmbu72xPvLMk3XUwog==}
'@vue/[email protected]':
resolution: {integrity: sha512-RF5sbZOfYz5AK00tOJUn2PwFXR2fS1u2HVzI8D9VF9rGAFxuGBqg2bB1kJ3ZHMprqSltXnT9MZE1IsqjSM8oew==}
'@vue/[email protected]':
resolution: {integrity: sha512-qebChL3aP0m1k+TlSf+fZWvOwAf3flBCi5o+n01ykR3DX4mTIWheFltmoiQ12+z66/4cGeXqbB2P7sPWkGhQNQ==}
'@vue/[email protected]':
resolution: {integrity: sha512-6u4vXBlIBAC1wMplIZgpyPn7uh/s4Bf6F5bMzvLv+EdJ0aHs/+4B7Ygv864EStQSjRbsRzTko/kUG1A1IejQ3A==}
@@ -678,17 +690,17 @@ packages:
'@vue/[email protected]':
resolution: {integrity: sha512-kRB+3hHg0c+BdD1XLAvwjVMQd5pC05zijSlPDRI3ERvC/s04JlRs5upy2KjeMg/9m9oD5zuMVh9yVvkKfZqoJg==}
'@vue/[email protected]5':
resolution: {integrity: sha512-WqkyubNWpI4OYBOipSrjIssMdJO8K1i9Zts/Wm8Er10/0msOEwCyWWWvZnAI7WW3kQsTong6DJp8Cbb+vd4cPA==}
'@vue/[email protected]6':
resolution: {integrity: sha512-+FHtYTvGxgFoX3oRs7soz6JHizGv50Q26WJN6PWtXuTLXRfkfUpDUTRuoTA/kiZVVt8NMeMpsPQLh9h++ReUjQ==}
'@vue/[email protected]5':
resolution: {integrity: sha512-bzIO3+FABjpj85uIKSc+Qnj36/sxDNI3tcH9i6w6xKA1k6e0ejv0G0jMCfeJBvK3yGL5XbJ3DMZj+ClqyCHFYw==}
'@vue/[email protected]6':
resolution: {integrity: sha512-eJUzKAUaHAmtnys/l9qduPzUnBrYMkmsCU7TN+vbSOSpm8kcETT7nacKxIO4MBej/XiOraVzq+lSeZv7o1//jQ==}
'@vue/[email protected]5':
resolution: {integrity: sha512-ZvRTFMDgfqTDYWvJfoVpQTJx1RN5M6l7Pyd6wfdY2NaXzbPQVh9ezeQYFbNPP6bIcRVn2SqSSR25N/jSW69BFw==}
'@vue/[email protected]6':
resolution: {integrity: sha512-6L7lbBvXTYBFFjIt25a0pgdpmn3Ns8RqUnNVibRzF4bgyiWJvqOhKEV5MXYWKlCttZE3aGeJN8mveo+6IrIKXA==}
'@vue/[email protected]5':
resolution: {integrity: sha512-1fNXUHhhsWf4EVL4XixbGBU5mKdiIXJAB82feHRTyPPo6ZUEYWIJuEeUl3mVV6QDBp50HJOX4obLhxYXlrjrzA==}
'@vue/[email protected]6':
resolution: {integrity: sha512-4mc0YWREc6OZ5pDCigvKPDzIUV+aciiH92yvyTS6xaHHxW/80rMceQQn11pYe7OEEBt2YQgYWR9zF8QF30GJUQ==}
'@vue/[email protected]':
resolution: {integrity: sha512-H82XLH0DjmSOdbEwO15x3QTo1f5PWEtv237eLpYKc0mqLu+B8hnq16lFWmuBmNurkeiG3wr+oM1FhOll/YVFRg==}
@@ -696,6 +708,9 @@ packages:
'@vue/[email protected]':
resolution: {integrity: sha512-ue9fgHmVNPlP7iW3+cxoBX/Cnlw53dHlVSw0JKGY6z1lObg8pHoj928M2nzG4/yVsMZ3NaRZ2s2z61uC16NDwQ==}
'@vue/[email protected]':
resolution: {integrity: sha512-P1WePbdzHrcIciWtmY2Im9EFhdakd3rZxYqvalOa3SfoxtF35Q8Uhmj1tKn6bWP4utcOpN8ao6BoJUItq0Uf+g==}
'@vue/[email protected]':
resolution: {integrity: sha512-kTB6s2p34cA/xXSpt17G0enU9A3F3pdm+o5GZgE3WGXXXpXJ5SVBsRhgCJNCc+ekGAzY0T7Hjyo5yEfwencBlg==}
peerDependencies:
@@ -855,8 +870,8 @@ packages:
[email protected]:
resolution: {integrity: sha512-YUifsXXuknHlUsmlgyY0PKzgPOr7/FjCePfHNt0jxm83wHZi44VDMQ7/fGNkjY3/jV1MC+1CmZbaHzugyeRtpg==}
[email protected].3:
resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==}
[email protected].4:
resolution: {integrity: sha512-PoKaoPzQapnEoqUSnHx1u6W6ku8CVEgKsnpmmzU3m1nwkidpPBQ8V/Zq2+bWNrsOKoKLwTGdbx6xF7BXP1zLVQ==}
[email protected]:
resolution: {integrity: sha512-JQUCCK+/CAGbGGx618PlFZMXH81Jtj7t73CHv9dd/zVWvxgGT2zLFRjnKb+Ng46GIwcy+f7f88qd4duqllK+WQ==}
@@ -1476,6 +1491,10 @@ packages:
resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==}
engines: {node: '>=0.10.0'}
[email protected]:
resolution: {integrity: sha512-J7ZjMvHd9O1fcT/5V09QWaaSl2BbWx3F6O08spde82Namf9UB0GxRVIPiNbVsdKkoizHiSpTodo3vp2bAy91MA==}
engines: {node: '>=6.0.0'}
[email protected]:
resolution: {integrity: sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==}
@@ -1710,8 +1729,8 @@ packages:
peerDependencies:
typescript: '>=5.0.0'
[email protected]5:
resolution: {integrity: sha512-3cvsib8m9c0vB24+MDKsgcW4+Da4xaBl9Z/5Tbm2pmSIsRPxcil4cdXjXlVsmJ2g64XJo5h+IRd7rsdGT9pZaw==}
[email protected]6:
resolution: {integrity: sha512-0kW5CgfjMPBqmH158049SaE1muufp+K/ZyrwvSEwrwYky6QB7zL2y8kXfruneKb9O12eh0xAJL6CVSpzb9o0Kg==}
peerDependencies:
typescript: '*'
peerDependenciesMeta:
@@ -1901,11 +1920,11 @@ snapshots:
'@floating-ui/[email protected]': {}
'@floating-ui/[email protected]([email protected]5([email protected]))':
'@floating-ui/[email protected]([email protected]6([email protected]))':
dependencies:
'@floating-ui/dom': 1.8.0
'@floating-ui/utils': 0.2.12
vue: 3.5.45([email protected])
vue: 3.5.46([email protected])
'@fontsource/[email protected]': {}
@@ -1948,13 +1967,13 @@ snapshots:
'@oxc-project/[email protected]': {}
'@perfect-design/[email protected]([email protected](@vue/[email protected])([email protected])([email protected]5([email protected])))([email protected])([email protected]5([email protected]))':
'@perfect-design/[email protected]([email protected](@vue/[email protected])([email protected])([email protected]6([email protected])))([email protected])([email protected]6([email protected]))':
dependencies:
pinia: 4.1.0(@vue/[email protected])([email protected])([email protected]5([email protected]))
reka-ui: 2.11.0([email protected]5([email protected]))
pinia: 4.1.0(@vue/[email protected])([email protected])([email protected]6([email protected]))
reka-ui: 2.11.0([email protected]6([email protected]))
tailwind-merge: 3.7.1
tailwindcss: 4.3.5
vue: 3.5.45([email protected])
vue: 3.5.46([email protected])
'@rolldown/[email protected]':
optional: true
@@ -2077,10 +2096,10 @@ snapshots:
'@tanstack/[email protected]': {}
'@tanstack/[email protected]([email protected]5([email protected]))':
'@tanstack/[email protected]([email protected]6([email protected]))':
dependencies:
'@tanstack/virtual-core': 3.13.14
vue: 3.5.45([email protected])
vue: 3.5.46([email protected])
'@testing-library/[email protected]':
dependencies:
@@ -2116,12 +2135,12 @@ snapshots:
optionalDependencies:
vitest: 5.1.1([email protected])([email protected]([email protected])([email protected]))
'@testing-library/[email protected](@vue/[email protected]5)(@vue/[email protected])(@vue/[email protected]5)([email protected]5([email protected]))':
'@testing-library/[email protected](@vue/[email protected]6)(@vue/[email protected])(@vue/[email protected]6)([email protected]6([email protected]))':
dependencies:
'@babel/runtime': 7.28.4
'@testing-library/dom': 9.3.4
'@vue/test-utils': 2.6.0(@vue/[email protected]5)(@vue/[email protected]5)([email protected]5([email protected]))
vue: 3.5.45([email protected])
'@vue/test-utils': 2.6.0(@vue/[email protected]6)(@vue/[email protected]6)([email protected]6([email protected]))
vue: 3.5.46([email protected])
optionalDependencies:
'@vue/compiler-sfc': 3.5.45
transitivePeerDependencies:
@@ -2141,11 +2160,11 @@ snapshots:
'@types/[email protected]': {}
'@vitejs/[email protected]([email protected]([email protected])([email protected]))([email protected]5([email protected]))':
'@vitejs/[email protected]([email protected]([email protected])([email protected]))([email protected]6([email protected]))':
dependencies:
'@rolldown/pluginutils': 1.0.1
vite: 8.3.8([email protected])([email protected])
vue: 3.5.45([email protected])
vue: 3.5.46([email protected])
'@vitest/[email protected]([email protected]([email protected])([email protected]))':
dependencies:
@@ -2182,7 +2201,7 @@ snapshots:
optionalDependencies:
typescript: 6.0.3
'@vue-macros/[email protected]([email protected]5([email protected]))':
'@vue-macros/[email protected]([email protected]6([email protected]))':
dependencies:
'@vue/compiler-sfc': 3.5.45
ast-kit: 2.2.0
@@ -2190,7 +2209,7 @@ snapshots:
magic-string-ast: 1.0.3
unplugin-utils: 0.3.2
optionalDependencies:
vue: 3.5.45([email protected])
vue: 3.5.46([email protected])
'@vue/[email protected]':
dependencies:
@@ -2208,6 +2227,14 @@ snapshots:
estree-walker: 2.0.2
source-map-js: 1.2.2
'@vue/[email protected]':
dependencies:
'@babel/parser': 7.29.13
'@vue/shared': 3.5.46
entities: 7.0.1
estree-walker: 2.0.2
source-map-js: 1.2.4
'@vue/[email protected]':
dependencies:
'@vue/compiler-core': 3.5.44
@@ -2218,6 +2245,11 @@ snapshots:
'@vue/compiler-core': 3.5.45
'@vue/shared': 3.5.45
'@vue/[email protected]':
dependencies:
'@vue/compiler-core': 3.5.46
'@vue/shared': 3.5.46
'@vue/[email protected]':
dependencies:
'@babel/parser': 7.29.13
@@ -2230,11 +2262,28 @@ snapshots:
postcss: 8.5.32
source-map-js: 1.2.2
'@vue/[email protected]':
dependencies:
'@babel/parser': 7.29.13
'@vue/compiler-core': 3.5.46
'@vue/compiler-dom': 3.5.46
'@vue/compiler-ssr': 3.5.46
'@vue/shared': 3.5.46
estree-walker: 2.0.2
magic-string: 0.30.21
postcss: 8.5.32
source-map-js: 1.2.4
'@vue/[email protected]':
dependencies:
'@vue/compiler-dom': 3.5.45
'@vue/shared': 3.5.45
'@vue/[email protected]':
dependencies:
'@vue/compiler-dom': 3.5.46
'@vue/shared': 3.5.46
'@vue/[email protected]':
dependencies:
'@vue/devtools-kit': 8.2.1
@@ -2258,61 +2307,63 @@ snapshots:
path-browserify: 1.0.1
picomatch: 4.0.7
'@vue/[email protected]5':
'@vue/[email protected]6':
dependencies:
'@vue/shared': 3.5.45
'@vue/shared': 3.5.46
'@vue/[email protected]5':
'@vue/[email protected]6':
dependencies:
'@vue/reactivity': 3.5.45
'@vue/shared': 3.5.45
'@vue/reactivity': 3.5.46
'@vue/shared': 3.5.46
'@vue/[email protected]5':
'@vue/[email protected]6':
dependencies:
'@vue/reactivity': 3.5.45
'@vue/runtime-core': 3.5.45
'@vue/shared': 3.5.45
csstype: 3.2.3
'@vue/reactivity': 3.5.46
'@vue/runtime-core': 3.5.46
'@vue/shared': 3.5.46
csstype: 3.2.4
'@vue/[email protected]5':
'@vue/[email protected]6':
dependencies:
'@vue/compiler-ssr': 3.5.45
'@vue/runtime-dom': 3.5.45
'@vue/shared': 3.5.45
'@vue/compiler-ssr': 3.5.46
'@vue/runtime-dom': 3.5.46
'@vue/shared': 3.5.46
'@vue/[email protected]': {}
'@vue/[email protected]': {}
'@vue/[email protected](@vue/[email protected])(@vue/[email protected])([email protected]([email protected]))':
'@vue/[email protected]': {}
'@vue/[email protected](@vue/[email protected])(@vue/[email protected])([email protected]([email protected]))':
dependencies:
'@vue/compiler-dom': 3.5.45
'@vue/compiler-dom': 3.5.46
js-beautify: 2.0.3
vue: 3.5.45([email protected])
vue: 3.5.46([email protected])
vue-component-type-helpers: 3.3.12
optionalDependencies:
'@vue/server-renderer': 3.5.45
'@vue/server-renderer': 3.5.46
'@vueuse/[email protected]([email protected]5([email protected]))':
'@vueuse/[email protected]([email protected]6([email protected]))':
dependencies:
'@types/web-bluetooth': 0.0.21
'@vueuse/metadata': 14.4.0
'@vueuse/shared': 14.4.0([email protected]5([email protected]))
vue: 3.5.45([email protected])
'@vueuse/shared': 14.4.0([email protected]6([email protected]))
vue: 3.5.46([email protected])
'@vueuse/[email protected]': {}
'@vueuse/[email protected]([email protected]5([email protected]))':
'@vueuse/[email protected]([email protected]6([email protected]))':
dependencies:
vue: 3.5.45([email protected])
vue: 3.5.46([email protected])
[email protected]: {}
[email protected]: {}
[email protected]:
[email protected]([email protected]):
dependencies:
debug: 4.4.3
debug: 4.4.3([email protected])
transitivePeerDependencies:
- supports-color
@@ -2368,11 +2419,11 @@ snapshots:
dependencies:
possible-typed-array-names: 1.1.0
[email protected]:
[email protected]([email protected]([email protected]))([email protected]):
dependencies:
follow-redirects: 1.16.3
follow-redirects: 1.16.3([email protected]([email protected]))
form-data: 4.0.6
https-proxy-agent: 5.0.1
https-proxy-agent: 5.0.1([email protected])
proxy-from-env: 2.1.0
transitivePeerDependencies:
- debug
@@ -2445,7 +2496,7 @@ snapshots:
[email protected]: {}
[email protected].3: {}
[email protected].4: {}
[email protected]:
dependencies:
@@ -2454,9 +2505,11 @@ snapshots:
transitivePeerDependencies:
- '@noble/hashes'
[email protected]:
[email protected]([email protected]):
dependencies:
ms: 2.1.3
optionalDependencies:
supports-color: 7.2.0
[email protected]: {}
@@ -2600,7 +2653,9 @@ snapshots:
optionalDependencies:
picomatch: 4.0.7
[email protected]: {}
[email protected]([email protected]([email protected])):
optionalDependencies:
debug: 4.4.3([email protected])
[email protected]:
dependencies:
@@ -2675,10 +2730,10 @@ snapshots:
transitivePeerDependencies:
- '@noble/hashes'
[email protected]:
[email protected]([email protected]):
dependencies:
agent-base: 6.0.2
debug: 4.4.3
agent-base: 6.0.2([email protected])
debug: 4.4.3([email protected])
transitivePeerDependencies:
- supports-color
@@ -2968,11 +3023,11 @@ snapshots:
[email protected]: {}
[email protected](@vue/[email protected])([email protected])([email protected]5([email protected])):
[email protected](@vue/[email protected])([email protected])([email protected]6([email protected])):
dependencies:
'@vue/devtools-api': 8.2.1
nostics: 1.3.0
vue: 3.5.45([email protected])
vue: 3.5.46([email protected])
optionalDependencies:
typescript: 6.0.3
@@ -3030,18 +3085,18 @@ snapshots:
gopd: 1.2.0
set-function-name: 2.0.2
[email protected]([email protected]5([email protected])):
[email protected]([email protected]6([email protected])):
dependencies:
'@floating-ui/vue': 2.0.1([email protected]5([email protected]))
'@floating-ui/vue': 2.0.1([email protected]6([email protected]))
'@internationalized/date': 3.10.1
'@internationalized/number': 3.6.5
'@tanstack/vue-virtual': 3.13.14([email protected]5([email protected]))
'@vueuse/core': 14.4.0([email protected]5([email protected]))
'@vueuse/shared': 14.4.0([email protected]5([email protected]))
'@tanstack/vue-virtual': 3.13.14([email protected]6([email protected]))
'@vueuse/core': 14.4.0([email protected]6([email protected]))
'@vueuse/shared': 14.4.0([email protected]6([email protected]))
aria-hidden: 1.2.6
defu: 6.1.7
ohash: 2.0.11
vue: 3.5.45([email protected])
vue: 3.5.46([email protected])
[email protected]:
dependencies:
@@ -3124,6 +3179,8 @@ snapshots:
[email protected]: {}
[email protected]: {}
[email protected]: {}
[email protected]:
@@ -3240,9 +3297,9 @@ snapshots:
[email protected]: {}
[email protected](@vue/[email protected])([email protected])([email protected](@vue/[email protected])([email protected])([email protected]5([email protected])))([email protected])([email protected]([email protected])([email protected]))([email protected]5([email protected])):
[email protected](@vue/[email protected])([email protected])([email protected](@vue/[email protected])([email protected])([email protected]6([email protected])))([email protected])([email protected]([email protected])([email protected]))([email protected]6([email protected])):
dependencies:
'@vue-macros/common': 3.1.4([email protected]5([email protected]))
'@vue-macros/common': 3.1.4([email protected]6([email protected]))
'@vue/devtools-api': 8.2.1
ast-walker-scope: 0.10.0
chokidar: 6.0.0
@@ -3258,10 +3315,10 @@ snapshots:
tinyglobby: 0.2.17
unplugin: 3.7.0([email protected])([email protected])([email protected]([email protected])([email protected]))
unplugin-utils: 0.3.2
vue: 3.5.45([email protected])
vue: 3.5.46([email protected])
optionalDependencies:
'@vue/compiler-sfc': 3.5.45
pinia: 4.1.0(@vue/[email protected])([email protected])([email protected]5([email protected]))
pinia: 4.1.0(@vue/[email protected])([email protected])([email protected]6([email protected]))
vite: 8.3.8([email protected])([email protected])
transitivePeerDependencies:
- '@farmfe/core'
@@ -3280,13 +3337,13 @@ snapshots:
'@vue/language-core': 3.3.14
typescript: 6.0.3
[email protected]5([email protected]):
[email protected]6([email protected]):
dependencies:
'@vue/compiler-dom': 3.5.45
'@vue/compiler-sfc': 3.5.45
'@vue/runtime-dom': 3.5.45
'@vue/server-renderer': 3.5.45
'@vue/shared': 3.5.45
'@vue/compiler-dom': 3.5.46
'@vue/compiler-sfc': 3.5.46
'@vue/runtime-dom': 3.5.46
'@vue/server-renderer': 3.5.46
'@vue/shared': 3.5.46
optionalDependencies:
typescript: 6.0.3
@@ -85,7 +85,7 @@
:hint="
bypassForm.type === 'cve'
? 'Enter the CVE ID, for example CVE-2021-23337.'
: 'Enter a package, for example npm/[email protected], or npm/lodash for all versions.'
: 'Enter a package, for example npm/[email protected], or npm/lodash for all versions. PyPI packages use the release version, for example pypi/[email protected].'
"
required
>
@@ -137,6 +137,24 @@
</DialogContent>
</Dialog>
<Dialog v-model:open="showKeyDialog">
<DialogContent size="sm">
<DialogHeader>
<DialogTitle>Admin API key</DialogTitle>
<DialogDescription>Enter your admin API key to manage bypasses.</DialogDescription>
</DialogHeader>
<form class="flex flex-col gap-4" @submit.prevent="submitApiKey">
<Field label="API key" required>
<Input v-model="keyInput" type="password" autocomplete="off" />
</Field>
<DialogFooter>
<Button variant="outline" @click="showKeyDialog = false">Cancel</Button>
<Button type="submit" :disabled="keyInput.trim() === ''">Continue</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
<ConfirmDialog
v-model:open="showDeleteModal"
title="Delete bypass?"
@@ -222,6 +240,8 @@ const bypassForm = ref({ ...EMPTY_FORM })
// Get API key from localStorage or prompt user
const apiKey = ref<string>('')
const keyInput = ref('')
const showKeyDialog = ref(false)
const filteredBypasses = computed(() => {
let filtered = bypasses.value
@@ -264,16 +284,23 @@ onMounted(() => {
})
function promptForApiKey() {
const key = prompt('Enter your admin API key:')
if (key) {
apiKey.value = key
localStorage.setItem('admin_api_key', key)
fetchBypasses()
} else {
error.value = 'Admin API key required to manage bypasses'
}
keyInput.value = ''
showKeyDialog.value = true
}
function submitApiKey() {
const key = keyInput.value.trim()
if (!key) return
apiKey.value = key
localStorage.setItem('admin_api_key', key)
showKeyDialog.value = false
fetchBypasses()
}
watch(showKeyDialog, (open) => {
if (!open && !apiKey.value) error.value = 'Admin API key required to manage bypasses'
})
async function fetchBypasses() {
if (!apiKey.value) {
promptForApiKey()
+4 -3
View File
@@ -127,7 +127,7 @@ import type { IconDefinition } from '@perfect-design/ui/lib/icons-tools'
import { usePackageStore, type Package } from '../stores/packages'
import { useRealtimeStore } from '../stores/realtime'
import type { EventType, RealtimeEvent } from '@/lib/ws'
import { formatBytes, formatNumber } from '@/lib/format'
import { displayVersion, formatBytes, formatNumber, withVersionPrefix } from '@/lib/format'
import {
faBox,
faBoxOpen,
@@ -190,7 +190,8 @@ function labelForEvent(type: EventType): string {
function describeEvent(evt: RealtimeEvent): string {
const p = evt.payload
const name = typeof p.name === 'string' ? p.name : ''
const version = typeof p.version === 'string' ? `@${p.version}` : ''
const shown = typeof p.release_version === 'string' && p.release_version ? p.release_version : p.version
const version = typeof shown === 'string' ? `@${shown}` : ''
const registry = typeof p.registry === 'string' ? `[${p.registry}] ` : ''
if (evt.type === 'stats_update') return ''
if (name) return `${registry}${name}${version}`
@@ -250,7 +251,7 @@ const chartLabels = computed(() => chartData.value.map((_, index) => getChartLab
const packageColumns: DataTableColumn<Package>[] = [
{ key: 'name', header: 'Package', rowHeader: true },
{ key: 'version', header: 'Version' },
{ key: 'version', header: 'Version', accessor: (pkg) => withVersionPrefix(displayVersion(pkg)) },
{ key: 'registry', header: 'Registry' },
{ key: 'size', header: 'Size', numeric: true, accessor: (pkg) => formatBytes(pkg.size) },
{ key: 'download_count', header: 'Downloads', numeric: true, accessor: (pkg) => formatNumber(pkg.download_count) },
+4 -2
View File
@@ -7,7 +7,7 @@
<template #description>
<span class="flex flex-wrap items-center gap-2">
<Badge variant="outline">{{ registry }}</Badge>
<Badge variant="outline" class="font-mono">v{{ version }}</Badge>
<Badge variant="outline" class="font-mono">{{ withVersionPrefix(shownVersion) }}</Badge>
</span>
</template>
</PageHeader>
@@ -184,7 +184,7 @@ import {
TableRow,
} from '@perfect-design/ui'
import SeveritySummary from './SeveritySummary.vue'
import { formatDate } from '@/lib/format'
import { formatDate, withVersionPrefix } from '@/lib/format'
import { faArrowLeft, faChevronDown, faChevronUp, faCircleCheck } from '@/lib/icons'
import { NO_VULNERABILITIES, SEVERITY_TONES, formatSeverityName, severityRank } from '@/lib/severity'
@@ -201,6 +201,7 @@ const packageName = computed(() => {
return nameParam as string
})
const version = computed(() => route.params.version as string)
const shownVersion = computed(() => vulnerabilities.value?.package?.release_version || version.value)
interface BypassInfo {
id: string
@@ -221,6 +222,7 @@ interface Vulnerability {
}
interface VulnerabilityResponse {
package?: { release_version?: string }
scanned: boolean
scanner: string
scanned_at: string
+4 -2
View File
@@ -47,8 +47,9 @@
:value="`${group.registry}:${group.name}`"
>
<AccordionTrigger :heading-level="2">
<span class="flex w-full min-w-0 items-center justify-between gap-4">
<span class="min-w-0 text-start">
<!-- Stacked below sm: a side-by-side row leaves the name ~90px at 320px and breaks scoped names mid-word. -->
<span class="flex w-full min-w-0 flex-col items-start gap-2 sm:flex-row sm:items-center sm:justify-between sm:gap-4">
<span class="w-full min-w-0 text-start sm:w-auto">
<span class="block break-words font-semibold">{{ group.name }}</span>
<span class="block text-sm text-muted-foreground">
{{ group.versions.length }} version{{ group.versions.length > 1 ? 's' : '' }}
@@ -115,6 +116,7 @@
:page="currentPage"
:total="allGroupedPackages.length"
:page-size="itemsPerPage"
:show-edges="false"
@update:page="changePage"
/>
</div>
+42
View File
@@ -207,4 +207,46 @@ describe('Stats.vue', () => {
expect(wrapper.findAll('tbody th')).toHaveLength(0)
expect(wrapper.text()).toContain('No registries reported')
})
describe('idle eviction note', () => {
const baseStats = {
registry: '',
total_packages: 100,
total_size: 1073741824,
max_cache_size: 10737418240,
total_downloads: 500,
scanned_packages: 90,
vulnerable_packages: 5,
blocked_packages: 0,
}
async function render(idleTtl?: number) {
const wrapper = mount(Stats)
const store = usePackageStore()
store.loading = false
store.stats = idleTtl === undefined ? { ...baseStats } : { ...baseStats, idle_ttl: idleTtl }
await wrapper.vm.$nextTick()
return wrapper
}
it.each([
[604800, 'Cached items not requested for 7 days are removed.'],
[86400, 'Cached items not requested for 1 day are removed.'],
[129600, 'Cached items not requested for 36 hours are removed.'],
[5400, 'Cached items not requested for 90 minutes are removed.'],
])('shows the window for idle_ttl=%i', async (seconds, sentence) => {
const wrapper = await render(seconds)
expect(wrapper.text()).toContain(sentence)
})
it('hides the note when idle eviction is off', async () => {
const wrapper = await render(0)
expect(wrapper.text()).not.toContain('not requested')
})
it('hides the note when the API sends no idle_ttl', async () => {
const wrapper = await render()
expect(wrapper.text()).not.toContain('not requested')
})
})
})
+9 -1
View File
@@ -13,6 +13,10 @@
/>
<template v-else>
<Alert v-if="idleTtl > 0" variant="info">
<AlertDescription>Cached items not requested for {{ formatDuration(idleTtl) }} are removed.</AlertDescription>
</Alert>
<Card>
<CardHeader>
<CardTitle as="h2">Overall statistics</CardTitle>
@@ -91,6 +95,8 @@ import { storeToRefs } from 'pinia'
import { useRouter } from 'vue-router'
import { usePackageStore } from '../stores/packages'
import {
Alert,
AlertDescription,
Card,
CardContent,
CardHeader,
@@ -103,7 +109,7 @@ import {
StatGroup,
type DataTableColumn,
} from '@perfect-design/ui'
import { formatBytes, formatNumber } from '@/lib/format'
import { formatBytes, formatDuration, formatNumber } from '@/lib/format'
import { faBan, faDownload, faHardDrive, faBoxesStacked, faCircleCheck, faTriangleExclamation } from '@/lib/icons'
const store = usePackageStore()
@@ -162,6 +168,8 @@ const registries = computed(() => {
}))
})
const idleTtl = computed(() => stats.value?.idle_ttl || 0)
const storagePercentage = computed(() => {
const totalSize = stats.value?.total_size || 0
const maxSize = stats.value?.max_cache_size || 1
+117
View File
@@ -140,6 +140,31 @@ describe('view smoke tests (strict mode throw, fixture data)', () => {
expect(document.body.querySelector('textarea')).not.toBeNull()
})
it('BypassManagementPanel asks for the admin key in a dialog, not a native prompt', async () => {
localStorage.clear()
const prompt = vi.spyOn(window, 'prompt')
const { wrapper, problems } = await smoke(BypassManagementPanel, '/admin/bypasses')
await flushPromises()
expect(problems).toEqual([])
expect(prompt).not.toHaveBeenCalled()
expect(document.body.textContent).toContain('Enter your admin API key to manage bypasses.')
const input = document.body.querySelector<HTMLInputElement>('input[type="password"]')
expect(input).not.toBeNull()
input!.value = 'secret-key'
input!.dispatchEvent(new Event('input', { bubbles: true }))
await flushPromises()
document.body.querySelector<HTMLFormElement>('input[type="password"]')!.form!.requestSubmit()
await flushPromises()
expect(localStorage.getItem('admin_api_key')).toBe('secret-key')
expect(vi.mocked(axios.get)).toHaveBeenCalledWith(
expect.stringContaining('/api/admin/bypasses'),
expect.objectContaining({ headers: { Authorization: 'Bearer secret-key' } }),
)
expect(wrapper.text()).toContain('CVE-2026-0002')
})
it('Stats renders totals, the storage tile and the registry table', async () => {
const { wrapper, problems } = await smoke(Stats, '/stats')
expect(problems).toEqual([])
@@ -186,3 +211,95 @@ describe('view smoke tests (strict mode throw, fixture data)', () => {
expect(usePackageStore().packages.length).toBe(PACKAGES.length)
})
})
describe('PyPI rows show the release version, not the file name', () => {
const FILE = 'six-1.17.0-py2.py3-none-any.whl'
const SIX = {
id: 'pypi-six',
registry: 'pypi',
name: 'six',
version: FILE,
release_version: '1.17.0',
size: 1,
cached_at: '2026-02-01T10:00:00Z',
last_accessed: '2026-02-01T10:00:00Z',
download_count: 1,
vulnerabilities: {
scanned: true,
status: 'vulnerable',
counts: { critical: 1, high: 0, moderate: 0, low: 0 },
total: 1,
scannedAt: '2026-02-01T10:05:00Z',
isBlocked: false,
},
}
beforeEach(() => {
vi.mocked(axios.get).mockImplementation(async (url: string) => {
if (url.endsWith('/vulnerabilities')) {
return { data: { ...VULNERABILITY_REPORT, package: { release_version: '1.17.0' } } } as never
}
if (url.startsWith('/api/packages')) return { data: { packages: [SIX] } } as never
return respond(url) as never
})
})
it('Dashboard recent packages', async () => {
const { wrapper } = await smoke(Dashboard, '/')
await flushPromises()
expect(wrapper.text()).toContain('v1.17.0')
expect(wrapper.text()).not.toContain('py2.py3-none-any.whl')
})
it('Dashboard activity feed', async () => {
const router = await createTestRouter('/')
const pinia = createPinia()
setActivePinia(pinia)
const rt = useRealtimeStore()
vi.spyOn(rt, 'connect').mockImplementation(() => {})
rt.events = [{ type: 'package_cached', payload: { name: 'six', version: FILE, release_version: '1.17.0', registry: 'pypi' }, timestamp: Date.now() }]
const { wrapper, restore: r } = await mountStrict(Dashboard, { global: { plugins: [pinia, router] } })
restore = r
await flushPromises()
const feed = wrapper.find('[data-testid="ws-event-feed"]').text()
expect(feed).toContain('[email protected]')
expect(feed).not.toContain('whl')
})
it('VulnerablePackages version column', async () => {
const { wrapper } = await smoke(VulnerablePackages, '/vulnerable-packages')
await flushPromises()
await wrapper.find('button[aria-expanded]').trigger('click')
await flushPromises()
expect(wrapper.text()).toContain('v1.17.0')
expect(wrapper.text()).not.toContain('py2.py3-none-any.whl')
})
it('PackageDetails header badge', async () => {
const { wrapper } = await smoke(PackageDetails, `/package/pypi/six/${FILE}`)
const router = (wrapper.vm as unknown as { $router: Awaited<ReturnType<typeof createTestRouter>> }).$router
await router.push(`/package/pypi/six/${FILE}`)
await flushPromises()
expect(wrapper.text()).toContain('v1.17.0')
expect(wrapper.text()).not.toContain('py2.py3-none-any.whl')
})
it('PackageDetails falls back to the route version without a release version', async () => {
vi.mocked(axios.get).mockImplementation(async (url: string) => respond(url) as never)
const { wrapper } = await smoke(PackageDetails, '/package/npm/left-pad/1.3.0')
const router = (wrapper.vm as unknown as { $router: Awaited<ReturnType<typeof createTestRouter>> }).$router
await router.push('/package/npm/left-pad/1.3.0')
await flushPromises()
expect(wrapper.text()).toContain('v1.3.0')
})
it('bypass form tells PyPI users to use the release version', async () => {
const { wrapper } = await smoke(BypassManagementPanel, '/admin/bypasses')
await wrapper.findAll('button').find((b) => b.text() === 'Create bypass')!.trigger('click')
await flushPromises()
const pkg = Array.from(document.body.querySelectorAll<HTMLElement>('button, [role="radio"]')).find((e) => e.textContent?.trim() === 'Package bypass')
pkg!.click()
await flushPromises()
expect(document.body.textContent).toContain('pypi/[email protected]')
})
})
+15
View File
@@ -0,0 +1,15 @@
import { describe, expect, it } from 'vitest'
import { formatDuration } from './format'
describe('formatDuration', () => {
it.each([
[604800, '7 days'],
[86400, '1 day'],
[129600, '36 hours'],
[3600, '1 hour'],
[5400, '90 minutes'],
[60, '1 minute'],
])('formats %i seconds as %s', (seconds, expected) => {
expect(formatDuration(seconds)).toBe(expected)
})
})
+15
View File
@@ -11,6 +11,21 @@ export function formatBytes(bytes: number): string {
return Math.round((bytes / Math.pow(BYTES_PER_UNIT, i)) * 100) / 100 + ' ' + BYTE_UNITS[i]
}
const SECONDS_PER_DAY = 86400
const SECONDS_PER_HOUR = 3600
const SECONDS_PER_MINUTE = 60
function plural(n: number, unit: string): string {
return `${n} ${unit}${n === 1 ? '' : 's'}`
}
/** Whole days, hours or minutes, using the largest unit that divides the span evenly. */
export function formatDuration(seconds: number): string {
if (seconds % SECONDS_PER_DAY === 0) return plural(seconds / SECONDS_PER_DAY, 'day')
if (seconds % SECONDS_PER_HOUR === 0) return plural(seconds / SECONDS_PER_HOUR, 'hour')
return plural(Math.round(seconds / SECONDS_PER_MINUTE), 'minute')
}
export function formatDate(date: string): string {
if (!date) return 'N/A'
const parsed = new Date(date)
+2
View File
@@ -40,6 +40,8 @@ export interface Stats {
scanned_packages: number
vulnerable_packages: number
blocked_packages: number
/** Seconds a cached item can go unrequested before cleanup removes it; 0 means never. */
idle_ttl?: number
}
export const usePackageStore = defineStore('packages', () => {
+3
View File
@@ -5,6 +5,7 @@ import { themeBootScript } from '@perfect-design/ui/stores/theme-boot'
// Get backend URL from environment or use default
const BACKEND_URL = process.env.VITE_BACKEND_URL || 'http://localhost:8080'
const WS_ORIGIN = process.env.VITE_WS_ORIGIN
const FRONTEND_PORT = parseInt(process.env.VITE_PORT || '5173')
// Applies the saved colour mode before first paint so a dark system never flashes light.
@@ -33,6 +34,8 @@ export default defineConfig({
target: BACKEND_URL.replace('http', 'ws'),
ws: true,
changeOrigin: true,
// A backend with an origin allowlist refuses the dev server origin; set this to an allowed one.
...(WS_ORIGIN ? { headers: { Origin: WS_ORIGIN } } : {}),
},
},
},
+3 -3
View File
@@ -15,6 +15,7 @@ require (
github.com/gorilla/websocket v1.5.3
github.com/lib/pq v1.12.3
github.com/prometheus/client_golang v1.25.0
github.com/prometheus/client_model v0.6.3
github.com/rs/zerolog v1.35.1
github.com/spf13/cobra v1.10.2
github.com/spf13/viper v1.21.0
@@ -87,7 +88,7 @@ require (
github.com/jcmturner/rpc/v2 v2.0.3 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/klauspost/compress v1.20.4 // indirect
github.com/klauspost/compress v1.20.5 // indirect
github.com/lufia/plan9stats v0.0.0-20260802145828-341c2f0c90b5 // indirect
github.com/magiconair/properties v1.18.13 // indirect
github.com/mattn/go-colorable v0.1.16 // indirect
@@ -110,7 +111,6 @@ require (
github.com/pelletier/go-toml/v2 v2.4.3 // indirect
github.com/philhofer/fwd v1.2.1 // indirect
github.com/power-devops/perfstat v0.0.0-20260916203055-22a1a467d9f0 // indirect
github.com/prometheus/client_model v0.6.3 // indirect
github.com/prometheus/common v0.74.0 // indirect
github.com/prometheus/procfs v0.23.0 // indirect
github.com/sagikazarmark/locafero v0.12.0 // indirect
@@ -127,7 +127,7 @@ require (
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasthttp v1.79.0 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/auto/sdk v1.2.2 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0 // indirect
go.opentelemetry.io/otel v1.47.0 // indirect
go.opentelemetry.io/otel/log v1.47.0 // indirect
+6 -6
View File
@@ -149,8 +149,8 @@ github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/klauspost/compress v1.20.4 h1:dD0v/bvxtjCBqQu6sx1TNWkalEY5lNTIe+HY9w8TeNI=
github.com/klauspost/compress v1.20.4/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
github.com/klauspost/compress v1.20.5 h1:rJj5VjH4xQxbnLphg6eqUcDxRFCw1jpMdDY9qXlrwSs=
github.com/klauspost/compress v1.20.5/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
@@ -218,8 +218,8 @@ github.com/prometheus/common v0.74.0 h1:6iYW8MsYvmEnXFD9zLGgF0qmReaRhs3OMONu1c/n
github.com/prometheus/common v0.74.0/go.mod h1:i/02C+FCst5B1etKgWesNrD49n+onplJCqUCtUKkOeA=
github.com/prometheus/procfs v0.23.0 h1:ad+S6FTkzwaMgacKLM5h6bNKExS+DMH0YiUwXItH/o4=
github.com/prometheus/procfs v0.23.0/go.mod h1:3AVXO0FqLafyYFU/V/IQRZlC8Rgqz8Dm/x6pKLK+RIk=
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/rs/zerolog v1.35.1 h1:m7xQeoiLIiV0BCEY4Hs+j2NG4Gp2o2KPKmhnnLiazKI=
github.com/rs/zerolog v1.35.1/go.mod h1:EjML9kdfa/RMA7h/6z6pYmq1ykOuA8/mjWaEvGI+jcw=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
@@ -278,8 +278,8 @@ github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcY
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/auto/sdk v1.2.2 h1:ErNn7NW2t1F9CFBLb9iyPMyLRbcEd07l5m/StCe9AEE=
go.opentelemetry.io/auto/sdk v1.2.2/go.mod h1:Ca3X8ec6gdTYjAirla//dnp05ECtQPfN4Ut74OJLVsQ=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0 h1:LxwW/9ctSCv+QkE/cLR7M91ZIkXNMqJtEMi1vCw9U8s=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0/go.mod h1:tOsftB4SslBwwErVEPaenU2RpThXWPIU8DoJHEC4dyw=
go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM=
+1
View File
@@ -73,6 +73,7 @@ data:
cache:
default_ttl: {{ .Values.cache.defaultTTL | quote }}
cleanup_interval: {{ .Values.cache.cleanupInterval | quote }}
idle_ttl: {{ .Values.cache.idleTTL | quote }}
max_size_bytes: {{ .Values.cache.maxSizeBytes }}
per_project_quota: {{ .Values.cache.perProjectQuota }}
ttl_overrides:
+1
View File
@@ -377,6 +377,7 @@ migration:
cache:
defaultTTL: "168h" # 7 days
cleanupInterval: "1h"
idleTTL: "168h" # Remove cached items not requested for this long; "0" disables
maxSizeBytes: 536870912000 # 500GB
perProjectQuota: 53687091200 # 50GB
ttlOverrides:
+15 -6
View File
@@ -233,6 +233,7 @@ func (a *App) initializeComponents() error {
a.cache, err = cache.New(a.storage, a.metadata, a.scanManager, a.analyticsEngine, cache.Config{
DefaultTTL: a.config.Cache.DefaultTTL,
CleanupInterval: cleanupInterval,
IdleTTL: a.config.Cache.IdleTTL,
MaxPackageSize: a.config.Security.Scanners.Static.MaxPackageSize,
FailClosed: a.config.Security.FailClosed,
})
@@ -592,6 +593,19 @@ func (a *App) setupServer() error {
return nil
}
// startWorkers starts the background loops that live as long as ctx.
func (a *App) startWorkers(ctx context.Context) {
// Without the event loop the broadcast channel fills after 256 events and websocket clients never register.
a.wsServer.Start(ctx)
// Start download data aggregation worker (runs every hour)
go a.startAggregationWorker(ctx)
// Start periodic stats broadcaster (every 30s) so connected WS clients
// see live counter updates without polling.
go a.startStatsBroadcaster(ctx)
}
func (a *App) Run() error {
// Cancellable worker context: aggregation + stats broadcaster goroutines
// watch ctx.Done() and exit, so Shutdown can stop them before closing
@@ -600,12 +614,7 @@ func (a *App) Run() error {
a.cancel = cancel
defer cancel()
// Start download data aggregation worker (runs every hour)
go a.startAggregationWorker(ctx)
// Start periodic stats broadcaster (every 30s) so connected WS clients
// see live counter updates without polling.
go a.startStatsBroadcaster(ctx)
a.startWorkers(ctx)
// Start Fiber server in goroutine. Branch on TLS to pick Listen vs ListenTLS.
errChan := make(chan error, 1)
+1
View File
@@ -407,6 +407,7 @@ func (a *App) handleStats(c fiber.Ctx) error {
"total_downloads": cacheStats.TotalDownloads,
"total_size": cacheStats.TotalSize,
"max_cache_size": a.config.Cache.MaxSizeBytes,
"idle_ttl": int64(a.config.Cache.IdleTTL / time.Second), // seconds, 0 = idle eviction off
"cache_hits": cacheStats.TotalDownloads,
"cache_misses": 0, // TODO: Track cache misses
"cache_evictions": 0, // TODO: Track evictions
+19 -9
View File
@@ -45,11 +45,15 @@ func (a *App) handleVulnerabilities(c fiber.Ctx) error {
Str("version", version).
Msg("Getting vulnerabilities for package")
pkg, pkgErr := a.metadata.GetPackage(ctx, registry, name, version)
releaseVersion := ""
if pkgErr == nil && pkg != nil {
releaseVersion = pkg.ReleaseVersion
}
// Get scan result from metadata store
scanResult, err := a.metadata.GetScanResult(ctx, registry, name, version)
if err != nil {
// Check if package exists
pkg, pkgErr := a.metadata.GetPackage(ctx, registry, name, version)
if pkgErr != nil {
return c.Status(fiber.StatusNotFound).JSON(fiber.Map{"error": "package not found"})
}
@@ -57,9 +61,10 @@ func (a *App) handleVulnerabilities(c fiber.Ctx) error {
// Package exists but not scanned yet
return c.Status(fiber.StatusOK).JSON(fiber.Map{
"package": fiber.Map{
"registry": registry,
"name": name,
"version": version,
"registry": registry,
"name": name,
"version": version,
"release_version": releaseVersion,
},
"scanned": false,
"status": "pending",
@@ -89,11 +94,15 @@ func (a *App) handleVulnerabilities(c fiber.Ctx) error {
}
packageKey := registry + "/" + bypassName + "@" + version
packageKeyNoVersion := registry + "/" + bypassName
releaseKey := ""
if releaseVersion != "" {
releaseKey = registry + "/" + bypassName + "@" + releaseVersion
}
bypassedCVEs := make(map[string]*metadata.CVEBypass)
for _, bypass := range bypasses {
if bypass.Type == metadata.BypassTypeCVE && bypass.Active {
// Check if bypass applies to this package
if bypass.AppliesTo == "" || bypass.AppliesTo == packageKey || bypass.AppliesTo == packageKeyNoVersion {
if bypass.AppliesTo == "" || bypass.AppliesTo == packageKey || bypass.AppliesTo == packageKeyNoVersion || (releaseKey != "" && bypass.AppliesTo == releaseKey) {
bypassedCVEs[strings.ToUpper(bypass.Target)] = bypass
}
}
@@ -141,9 +150,10 @@ func (a *App) handleVulnerabilities(c fiber.Ctx) error {
// Build response
response := fiber.Map{
"package": fiber.Map{
"registry": registry,
"name": name,
"version": version,
"registry": registry,
"name": name,
"version": version,
"release_version": releaseVersion,
},
"scanned": true,
"scanner": scanResult.Scanner,
+39
View File
@@ -0,0 +1,39 @@
package app
import (
"encoding/json"
"net/http"
"testing"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/config"
)
func TestStatsReportsIdleTTLSeconds(t *testing.T) {
for name, tt := range map[string]struct {
idle time.Duration
want float64
}{
"a week": {idle: 168 * time.Hour, want: 604800},
"disabled": {idle: 0, want: 0},
} {
t.Run(name, func(t *testing.T) {
a := newTestApp(t, func(c *config.Config) { c.Cache.IdleTTL = tt.idle })
code, _, body := doRequest(t, a, "/api/stats", nil)
if code != http.StatusOK {
t.Fatalf("status %d, body %q", code, body)
}
var resp struct {
Stats map[string]any `json:"stats"`
}
if err := json.Unmarshal([]byte(body), &resp); err != nil {
t.Fatalf("decode %q: %v", body, err)
}
got, ok := resp.Stats["idle_ttl"].(float64)
if !ok || got != tt.want {
t.Errorf("stats.idle_ttl = %v, want %v (body %s)", resp.Stats["idle_ttl"], tt.want, body)
}
})
}
}
+30
View File
@@ -0,0 +1,30 @@
package app
import (
"context"
"testing"
"time"
)
// TestWorkersDrainTheBroadcastChannel pins that the app starts the websocket
// event loop: without it the 256-slot broadcast channel fills and every later
// event is dropped.
func TestWorkersDrainTheBroadcastChannel(t *testing.T) {
a := newTestApp(t, nil)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
a.startWorkers(ctx)
const events = 1000
for i := 0; i < events; i++ {
a.wsServer.BroadcastEvent("cache_hit", map[string]interface{}{"i": i})
if i%200 == 0 {
time.Sleep(5 * time.Millisecond)
}
}
if dropped := a.wsServer.Dropped(); dropped != 0 {
t.Fatalf("dropped %d of %d events; the broadcast loop is not draining the channel", dropped, events)
}
}
+10 -1
View File
@@ -147,7 +147,16 @@ func (f *fakeStore) GetTimeSeriesStats(context.Context, string, string) (*metada
return nil, metadata.ErrNotImplemented
}
func (f *fakeStore) AggregateDownloadData(context.Context) error { return metadata.ErrNotImplemented }
func (f *fakeStore) Close() error { return nil }
func (f *fakeStore) ListIdlePackages(context.Context, time.Time, int) ([]*metadata.Package, error) {
return nil, metadata.ErrNotImplemented
}
func (f *fakeStore) ListExpiredPackages(context.Context, time.Time, int) ([]*metadata.Package, error) {
return nil, metadata.ErrNotImplemented
}
func (f *fakeStore) ClearArtifactExpiry(context.Context) (int64, error) {
return 0, metadata.ErrNotImplemented
}
func (f *fakeStore) Close() error { return nil }
// fastCfg uses bcrypt.MinCost so tests that hash multiple keys stay snappy.
func fastCfg() Config { return Config{BcryptCost: bcrypt.MinCost} }
+143 -38
View File
@@ -81,17 +81,28 @@ func (m *Manager) emit(eventType string, payload map[string]interface{}) {
// Config holds cache manager configuration
type Config struct {
DefaultTTL time.Duration // Default TTL for cached packages
CleanupInterval time.Duration // How often to run cleanup
EvictionThreshold float64 // Trigger eviction when usage > threshold (0.0-1.0)
MaxConcurrent int // Max concurrent upstream fetches
MaxPackageSize int64 // Maximum package size in bytes (0 = default 2GB)
ScanWaitTimeout time.Duration // How long the first download waits for its scan (0 = 30s)
FailClosed bool // Refuse a package whose scan did not finish in time
Now func() time.Time // Clock; nil means time.Now
DefaultTTL time.Duration // Freshness TTL for metadata entries
CleanupInterval time.Duration // How often to run cleanup
IdleTTL time.Duration // Remove entries not requested for this long (0 = off)
EvictionThreshold float64 // Trigger eviction when usage > threshold (0.0-1.0)
MaxConcurrent int // Max concurrent upstream fetches
MaxPackageSize int64 // Maximum package size in bytes (0 = default 2GB)
ScanWaitTimeout time.Duration // How long the first download waits for its scan (0 = 30s)
FailClosed bool // Refuse a package whose scan did not finish in time
}
const defaultScanWaitTimeout = 30 * time.Second
// cleanupBatchSize bounds how many rows one cleanup query reads.
const cleanupBatchSize = metadata.DefaultBatchSize
// Eviction metric reasons.
const (
evictReasonTTL = "ttl"
evictReasonIdle = "idle"
)
// scannerToggle is implemented by scanners that can be switched off.
type scannerToggle interface {
Enabled() bool
@@ -155,6 +166,10 @@ func New(storage storage.StorageBackend, metadata metadata.MetadataStore, scanne
log.Info().Msg("Cache manager initialized with analytics tracking enabled")
}
if config.Now == nil {
config.Now = time.Now
}
if config.DefaultTTL == 0 {
config.DefaultTTL = 7 * 24 * time.Hour // 7 days default
}
@@ -191,6 +206,9 @@ func New(storage storage.StorageBackend, metadata metadata.MetadataStore, scanne
stopCh: make(chan struct{}),
}
// Rows cached before idle eviction existed carry an age-based expiry.
manager.clearArtifactExpiry(bgCtx)
// Start background cleanup worker
manager.cleanupWG.Add(1)
go manager.cleanupWorker()
@@ -241,9 +259,9 @@ func (m *Manager) getOrFetch(ctx context.Context, registry, name, version string
pkg, err := m.metadata.GetPackage(ctx, registry, name, version)
if err == nil {
// Package found in metadata, check if expired
if pkg.ExpiresAt != nil && time.Now().After(*pkg.ExpiresAt) {
if pkg.ExpiresAt != nil && m.now().After(*pkg.ExpiresAt) {
log.Debug().Str("package", name).Str("version", version).Msg("Package expired, re-fetching")
metrics.RecordCacheEviction("ttl")
metrics.RecordCacheEviction(evictReasonTTL)
// Delete expired package
_ = m.deletePackage(ctx, pkg) // #nosec G104 -- Async cleanup
} else {
@@ -297,8 +315,7 @@ func (m *Manager) getOrFetch(ctx context.Context, registry, name, version string
// entries (index pages, lists, .mod/.info) are not scannable
// packages, so skip them to avoid a bogus "clean" verdict and
// the extra database round-trip.
isMetadataEntry := version == "list" || version == "page" || version == "latest" || version == "metadata" ||
strings.HasSuffix(name, ".mod") || strings.HasSuffix(name, ".info")
isMetadataEntry := metadata.IsMetadataEntry(name, version)
if m.scanner != nil && !isMetadataEntry {
blocked, reason, vulnErr := m.scanner.CheckVulnerabilities(ctx, registry, name, version)
if vulnErr != nil {
@@ -313,12 +330,12 @@ func (m *Manager) getOrFetch(ctx context.Context, registry, name, version string
// underlying transport is non-blocking. Only emitted on
// the cache-hit path — the miss-then-fetch path is
// covered by EventPackageCached emitted from store().
m.emit(string(websocket.EventPackageDownloaded), map[string]interface{}{
m.emit(string(websocket.EventPackageDownloaded), withReleaseVersion(map[string]interface{}{
"registry": registry,
"name": name,
"version": version,
"cache_hit": true,
})
}, pkg.ReleaseVersion))
// Data is intentionally nil; Get() opens a fresh reader per caller.
return &CacheEntry{
@@ -553,8 +570,16 @@ func (m *Manager) store(ctx context.Context, registry, name, version, releaseVer
_ = tempFile.Close() // #nosec G104 -- cleanup; scan may still read the file
// Create metadata entry
now := time.Now()
expiresAt := now.Add(m.config.DefaultTTL)
now := m.now()
isMetadataEntry := metadata.IsMetadataEntry(name, version)
// Artifacts are immutable, so only idle eviction removes them; metadata
// entries must refresh and keep a freshness expiry.
var expiresAt *time.Time
if isMetadataEntry {
exp := now.Add(m.config.DefaultTTL)
expiresAt = &exp
}
pkg := &metadata.Package{
ID: uuid.New().String(),
@@ -570,7 +595,7 @@ func (m *Manager) store(ctx context.Context, registry, name, version, releaseVer
AuthProvider: authProvider,
CachedAt: now,
LastAccessed: now,
ExpiresAt: &expiresAt,
ExpiresAt: expiresAt,
DownloadCount: 0,
Metadata: make(map[string]string),
}
@@ -583,8 +608,6 @@ func (m *Manager) store(ctx context.Context, registry, name, version, releaseVer
// TRADEOFF: metadata pages share the cache's DefaultTTL and are not refreshed
// based on upstream Cache-Control. Plumbing per-response TTL from registry handlers
// is out of scope here and tracked separately.
isMetadataEntry := version == "list" || version == "page" || version == "latest" || version == "metadata" ||
strings.HasSuffix(name, ".mod") || strings.HasSuffix(name, ".info")
if err := m.metadata.SavePackage(ctx, pkg); err != nil {
// Clean up storage if metadata save fails
_ = m.storage.Delete(ctx, storageKey) // #nosec G104 -- Cleanup, error logged
@@ -602,13 +625,13 @@ func (m *Manager) store(ctx context.Context, registry, name, version, releaseVer
scanStatus = "pending"
}
}
m.emit(string(websocket.EventPackageCached), map[string]interface{}{
m.emit(string(websocket.EventPackageCached), withReleaseVersion(map[string]interface{}{
"registry": registry,
"name": name,
"version": version,
"size": size,
"scan_status": scanStatus,
})
}, releaseVersion))
// Scan package if scanner is enabled (run in background to not block cache operations)
// Skip scanning metadata entries (index pages, lists, etc.)
@@ -738,7 +761,7 @@ func (m *Manager) evict(ctx context.Context, needed int64) error {
return nil
}
// cleanupWorker runs periodic cleanup of expired packages.
// cleanupWorker runs periodic cleanup of expired and idle packages.
// Exits when stopCh is closed (via Close()).
func (m *Manager) cleanupWorker() {
defer m.cleanupWG.Done()
@@ -751,39 +774,113 @@ func (m *Manager) cleanupWorker() {
case <-m.stopCh:
return
case <-ticker.C:
ctx := context.Background()
m.cleanup(ctx)
m.cleanup(m.bgCtx)
}
}
}
// cleanup removes expired packages
func (m *Manager) cleanup(ctx context.Context) {
log.Debug().Msg("Starting cleanup worker")
func (m *Manager) now() time.Time {
return m.config.Now()
}
// List all packages
packages, err := m.metadata.ListPackages(ctx, &metadata.ListOptions{})
// clearArtifactExpiry drops the age-based expiry that older versions set on artifacts.
func (m *Manager) clearArtifactExpiry(ctx context.Context) {
cleared, err := m.metadata.ClearArtifactExpiry(ctx)
if err != nil {
log.Error().Err(err).Msg("Failed to list packages for cleanup")
log.Error().Err(err).Msg("Failed to clear artifact expiry")
return
}
if cleared > 0 {
log.Info().Int64("count", cleared).Msg("Cleared age-based expiry from cached artifacts")
}
}
now := time.Now()
var cleaned int
// purgeResult totals the packages one purge pass removed.
type purgeResult struct {
bytes int64
count int
}
for _, pkg := range packages {
if pkg.ExpiresAt != nil && now.After(*pkg.ExpiresAt) {
if err := m.deletePackage(ctx, pkg); err != nil {
log.Warn().Err(err).Str("package", pkg.Name).Msg("Failed to clean up expired package")
// purge deletes packages in bounded batches until the list query runs dry.
// stillDue re-checks each package just before deletion so one requested after
// the batch was read is kept.
func (m *Manager) purge(
ctx context.Context,
reason string,
list func(limit int) ([]*metadata.Package, error),
stillDue func(*metadata.Package) bool,
) purgeResult {
var res purgeResult
seen := make(map[string]struct{})
for ctx.Err() == nil {
batch, err := list(cleanupBatchSize)
if err != nil {
log.Error().Err(err).Str("reason", reason).Msg("Failed to list packages for cleanup")
return res
}
unseen := 0
for _, pkg := range batch {
key := m.generateStorageKey(pkg.Registry, pkg.Name, pkg.Version)
if _, dup := seen[key]; dup {
continue
}
cleaned++
seen[key] = struct{}{}
unseen++
current, err := m.metadata.GetPackage(ctx, pkg.Registry, pkg.Name, pkg.Version)
if err != nil || current == nil || !stillDue(current) {
continue
}
if err := m.deletePackage(ctx, current); err != nil {
log.Warn().Err(err).Str("package", pkg.Name).Str("reason", reason).Msg("Failed to clean up package")
continue
}
res.count++
res.bytes += current.Size
metrics.RecordCacheEviction(reason)
}
// A short batch is the last one; a batch of only repeats means every
// remaining row failed to delete.
if len(batch) < cleanupBatchSize || unseen == 0 {
return res
}
}
return res
}
if cleaned > 0 {
log.Info().Int("count", cleaned).Msg("Cleanup completed")
// cleanup removes metadata entries past their freshness expiry and, when
// IdleTTL is set, every package not requested within IdleTTL.
func (m *Manager) cleanup(ctx context.Context) {
start := m.now()
log.Debug().Msg("Starting cleanup worker")
m.clearArtifactExpiry(ctx)
expired := m.purge(ctx, evictReasonTTL,
func(limit int) ([]*metadata.Package, error) {
return m.metadata.ListExpiredPackages(ctx, start, limit)
},
func(p *metadata.Package) bool { return p.ExpiresAt != nil && p.ExpiresAt.Before(start) })
var idle purgeResult
if m.config.IdleTTL > 0 {
cutoff := start.Add(-m.config.IdleTTL)
idle = m.purge(ctx, evictReasonIdle,
func(limit int) ([]*metadata.Package, error) {
return m.metadata.ListIdlePackages(ctx, cutoff, limit)
},
func(p *metadata.Package) bool { return p.LastAccessed.Before(cutoff) })
}
log.Info().
Int("expired", expired.count).
Int("idle", idle.count).
Int64("bytes_freed", expired.bytes+idle.bytes).
Dur("idle_ttl", m.config.IdleTTL).
Msg("Cleanup completed")
}
// generateStorageKey generates a storage key for a package
@@ -853,3 +950,11 @@ func (m *Manager) Close() error {
return err
}
// withReleaseVersion adds release_version to an event payload when the cache key is not a release version.
func withReleaseVersion(payload map[string]interface{}, releaseVersion string) map[string]interface{} {
if releaseVersion != "" {
payload["release_version"] = releaseVersion
}
return payload
}
+11
View File
@@ -230,6 +230,17 @@ func (m *MockMetadataStore) AggregateDownloadData(ctx context.Context) error {
return args.Error(0)
}
// The idle-eviction queries are not mocked per test: no expiry, no idle rows.
func (m *MockMetadataStore) ListIdlePackages(context.Context, time.Time, int) ([]*metadata.Package, error) {
return nil, nil
}
func (m *MockMetadataStore) ListExpiredPackages(context.Context, time.Time, int) ([]*metadata.Package, error) {
return nil, nil
}
func (m *MockMetadataStore) ClearArtifactExpiry(context.Context) (int64, error) { return 0, nil }
// API key methods are not used by the cache package; stub them out so the
// mock continues to satisfy metadata.MetadataStore after the interface gained
// API key persistence methods.
+398
View File
@@ -0,0 +1,398 @@
package cache
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"sort"
"strings"
"sync"
"testing"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/lukaszraczylo/gohoarder/pkg/metrics"
"github.com/lukaszraczylo/gohoarder/pkg/storage"
"github.com/prometheus/client_golang/prometheus"
dto "github.com/prometheus/client_model/go"
"github.com/stretchr/testify/require"
)
func evictions(c prometheus.Counter) float64 {
var m dto.Metric
if err := c.Write(&m); err != nil {
panic(err)
}
return m.GetCounter().GetValue()
}
type fakeClock struct {
now time.Time
mu sync.Mutex
}
func newFakeClock() *fakeClock {
return &fakeClock{now: time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)}
}
func (c *fakeClock) Now() time.Time {
c.mu.Lock()
defer c.mu.Unlock()
return c.now
}
func (c *fakeClock) Advance(d time.Duration) {
c.mu.Lock()
defer c.mu.Unlock()
c.now = c.now.Add(d)
}
type memStorage struct {
storage.StorageBackend
objects map[string][]byte
mu sync.Mutex
}
func newMemStorage() *memStorage { return &memStorage{objects: map[string][]byte{}} }
func (s *memStorage) Get(_ context.Context, key string) (io.ReadCloser, error) {
s.mu.Lock()
defer s.mu.Unlock()
b, ok := s.objects[key]
if !ok {
return nil, errors.New("not found")
}
return io.NopCloser(bytes.NewReader(b)), nil
}
func (s *memStorage) Put(_ context.Context, key string, data io.Reader, _ *storage.PutOptions) error {
b, err := io.ReadAll(data)
if err != nil {
return err
}
s.mu.Lock()
defer s.mu.Unlock()
s.objects[key] = b
return nil
}
func (s *memStorage) Delete(_ context.Context, key string) error {
s.mu.Lock()
defer s.mu.Unlock()
delete(s.objects, key)
return nil
}
func (s *memStorage) GetQuota(context.Context) (*storage.QuotaInfo, error) {
return &storage.QuotaInfo{}, nil
}
func (s *memStorage) Close() error { return nil }
func (s *memStorage) has(key string) bool {
s.mu.Lock()
defer s.mu.Unlock()
_, ok := s.objects[key]
return ok
}
// memMetadata mirrors the real store's contract: UpdateDownloadCount stamps
// last_accessed, and the list queries are ordered and bounded.
type memMetadata struct {
metadata.MetadataStore
clock *fakeClock
pkgs map[string]*metadata.Package
onList func()
maxLimit int
mu sync.Mutex
idleCalls int
}
func newMemMetadata(clock *fakeClock) *memMetadata {
return &memMetadata{clock: clock, pkgs: map[string]*metadata.Package{}}
}
func pkgKey(registry, name, version string) string { return registry + "/" + name + "/" + version }
func (m *memMetadata) SavePackage(_ context.Context, pkg *metadata.Package) error {
m.mu.Lock()
defer m.mu.Unlock()
cp := *pkg
m.pkgs[pkgKey(pkg.Registry, pkg.Name, pkg.Version)] = &cp
return nil
}
func (m *memMetadata) GetPackage(_ context.Context, registry, name, version string) (*metadata.Package, error) {
m.mu.Lock()
defer m.mu.Unlock()
p, ok := m.pkgs[pkgKey(registry, name, version)]
if !ok {
return nil, errors.New("not found")
}
cp := *p
return &cp, nil
}
func (m *memMetadata) DeletePackage(_ context.Context, registry, name, version string) error {
m.mu.Lock()
defer m.mu.Unlock()
delete(m.pkgs, pkgKey(registry, name, version))
return nil
}
func (m *memMetadata) UpdateDownloadCount(_ context.Context, registry, name, version string) error {
m.mu.Lock()
defer m.mu.Unlock()
p, ok := m.pkgs[pkgKey(registry, name, version)]
if !ok {
return errors.New("not found")
}
p.DownloadCount++
p.LastAccessed = m.clock.Now()
return nil
}
func (m *memMetadata) list(limit int, match func(*metadata.Package) bool, less func(a, b *metadata.Package) bool) []*metadata.Package {
m.mu.Lock()
if limit > m.maxLimit {
m.maxLimit = limit
}
var out []*metadata.Package
for _, p := range m.pkgs {
if match(p) {
cp := *p
out = append(out, &cp)
}
}
m.mu.Unlock()
sort.Slice(out, func(i, j int) bool { return less(out[i], out[j]) })
if limit > 0 && len(out) > limit {
out = out[:limit]
}
if m.onList != nil {
m.onList()
}
return out
}
func (m *memMetadata) ListIdlePackages(_ context.Context, idleBefore time.Time, limit int) ([]*metadata.Package, error) {
m.mu.Lock()
m.idleCalls++
m.mu.Unlock()
return m.list(limit,
func(p *metadata.Package) bool { return p.LastAccessed.Before(idleBefore) },
func(a, b *metadata.Package) bool { return a.LastAccessed.Before(b.LastAccessed) }), nil
}
func (m *memMetadata) ListExpiredPackages(_ context.Context, before time.Time, limit int) ([]*metadata.Package, error) {
return m.list(limit,
func(p *metadata.Package) bool { return p.ExpiresAt != nil && p.ExpiresAt.Before(before) },
func(a, b *metadata.Package) bool { return a.ExpiresAt.Before(*b.ExpiresAt) }), nil
}
func (m *memMetadata) ClearArtifactExpiry(context.Context) (int64, error) {
m.mu.Lock()
defer m.mu.Unlock()
var n int64
for _, p := range m.pkgs {
if p.ExpiresAt != nil && !metadata.IsMetadataEntry(p.Name, p.Version) {
p.ExpiresAt = nil
n++
}
}
return n, nil
}
func (m *memMetadata) Close() error { return nil }
func (m *memMetadata) count() int {
m.mu.Lock()
defer m.mu.Unlock()
return len(m.pkgs)
}
type idleHarness struct {
mgr *Manager
clock *fakeClock
meta *memMetadata
store *memStorage
fetches int
}
func newIdleHarness(t *testing.T, cfg Config) *idleHarness {
t.Helper()
h := &idleHarness{clock: newFakeClock(), store: newMemStorage()}
h.meta = newMemMetadata(h.clock)
cfg.Now = h.clock.Now
if cfg.CleanupInterval == 0 {
cfg.CleanupInterval = 24 * time.Hour
}
return h.start(t, cfg)
}
func (h *idleHarness) start(t *testing.T, cfg Config) *idleHarness {
t.Helper()
mgr, err := New(h.store, h.meta, nil, nil, cfg)
require.NoError(t, err)
t.Cleanup(func() { _ = mgr.Close() })
h.mgr = mgr
return h
}
func (h *idleHarness) get(t *testing.T, name, version string) *CacheEntry {
t.Helper()
entry, err := h.mgr.Get(context.Background(), "npm", name, version, func(context.Context) (*FetchResult, error) {
h.fetches++
return &FetchResult{Data: io.NopCloser(strings.NewReader("payload-" + name)), UpstreamURL: "https://upstream/" + name}, nil
})
require.NoError(t, err)
_ = entry.Data.Close()
return entry
}
func (h *idleHarness) exists(name, version string) bool {
_, err := h.meta.GetPackage(context.Background(), "npm", name, version)
return err == nil && h.store.has(fmt.Sprintf("npm/%s/%s", name, version))
}
const (
day = 24 * time.Hour
artifactVer = "4.17.21"
)
func TestIdleTTL_AccessedArtifactSurvivesDefaultTTL(t *testing.T) {
h := newIdleHarness(t, Config{DefaultTTL: 2 * day, IdleTTL: 3 * day})
entry := h.get(t, "lodash", artifactVer)
require.Nil(t, entry.Package.ExpiresAt, "an artifact is immutable: no age-based expiry")
h.clock.Advance(2 * day)
h.get(t, "lodash", artifactVer) // touches last_accessed
h.clock.Advance(2 * day) // 4 days after caching, past DefaultTTL; idle for only 2
h.mgr.cleanup(context.Background())
require.True(t, h.exists("lodash", artifactVer))
h.get(t, "lodash", artifactVer)
require.Equal(t, 1, h.fetches, "served from cache, not re-fetched")
}
func TestIdleTTL_IdleArtifactIsDeletedFromStorageAndMetadata(t *testing.T) {
h := newIdleHarness(t, Config{DefaultTTL: 2 * day, IdleTTL: 3 * day})
h.get(t, "lodash", artifactVer)
h.get(t, "left-pad", "1.3.0")
h.clock.Advance(2 * day)
h.get(t, "left-pad", "1.3.0") // keeps left-pad alive
h.clock.Advance(2 * day) // lodash idle for 4 days
before := evictions(metrics.CacheEvictions.WithLabelValues("idle"))
h.mgr.cleanup(context.Background())
require.False(t, h.exists("lodash", artifactVer))
require.False(t, h.store.has("npm/lodash/"+artifactVer), "storage object removed")
_, err := h.meta.GetPackage(context.Background(), "npm", "lodash", artifactVer)
require.Error(t, err, "metadata row removed")
require.True(t, h.exists("left-pad", "1.3.0"))
require.Equal(t, before+1, evictions(metrics.CacheEvictions.WithLabelValues("idle")))
}
func TestIdleTTL_IdleMetadataEntryIsDeleted(t *testing.T) {
h := newIdleHarness(t, Config{DefaultTTL: 30 * day, IdleTTL: 3 * day})
h.get(t, "lodash", "metadata")
h.clock.Advance(4 * day)
h.mgr.cleanup(context.Background())
require.False(t, h.exists("lodash", "metadata"))
}
func TestIdleTTL_MetadataEntryPastFreshnessTTLIsRefetched(t *testing.T) {
h := newIdleHarness(t, Config{DefaultTTL: time.Hour, IdleTTL: 7 * day})
entry := h.get(t, "lodash", "metadata")
require.NotNil(t, entry.Package.ExpiresAt)
require.Equal(t, h.clock.Now().Add(time.Hour), *entry.Package.ExpiresAt)
h.clock.Advance(30 * time.Minute)
h.get(t, "lodash", "metadata")
require.Equal(t, 1, h.fetches, "still fresh")
h.clock.Advance(2 * time.Hour) // recently requested, but stale
before := evictions(metrics.CacheEvictions.WithLabelValues("ttl"))
h.get(t, "lodash", "metadata")
require.Equal(t, 2, h.fetches, "stale metadata is re-fetched")
require.Equal(t, before+1, evictions(metrics.CacheEvictions.WithLabelValues("ttl")))
}
func TestIdleTTL_CleanupRemovesExpiredMetadataOnly(t *testing.T) {
h := newIdleHarness(t, Config{DefaultTTL: time.Hour, IdleTTL: 30 * day})
h.get(t, "lodash", "metadata")
h.get(t, "lodash", artifactVer)
h.clock.Advance(2 * time.Hour)
h.mgr.cleanup(context.Background())
require.False(t, h.exists("lodash", "metadata"), "past its freshness expiry")
require.True(t, h.exists("lodash", artifactVer), "artifacts have no age-based expiry")
}
func TestIdleTTL_ZeroDisablesIdleEviction(t *testing.T) {
h := newIdleHarness(t, Config{DefaultTTL: 2 * day, IdleTTL: 0})
h.get(t, "lodash", artifactVer)
h.clock.Advance(365 * day)
h.mgr.cleanup(context.Background())
require.True(t, h.exists("lodash", artifactVer))
require.Zero(t, h.meta.idleCalls, "no idle query when disabled")
}
func TestIdleTTL_CleanupReadsBoundedBatches(t *testing.T) {
h := newIdleHarness(t, Config{DefaultTTL: day, IdleTTL: day})
const total = 1250
for i := 0; i < total; i++ {
name := fmt.Sprintf("pkg-%d", i)
h.get(t, name, "1.0.0")
}
h.clock.Advance(2 * day)
h.mgr.cleanup(context.Background())
require.Zero(t, h.meta.count(), "every idle item removed across batches")
require.Positive(t, h.meta.maxLimit)
require.LessOrEqual(t, h.meta.maxLimit, cleanupBatchSize, "never loads more than one batch")
require.Zero(t, len(h.store.objects))
}
func TestIdleTTL_ItemRequestedDuringCleanupSurvives(t *testing.T) {
h := newIdleHarness(t, Config{DefaultTTL: 30 * day, IdleTTL: day})
h.get(t, "lodash", artifactVer)
h.clock.Advance(2 * day)
h.meta.onList = func() {
h.meta.onList = nil
require.NoError(t, h.meta.UpdateDownloadCount(context.Background(), "npm", "lodash", artifactVer))
}
h.mgr.cleanup(context.Background())
require.True(t, h.exists("lodash", artifactVer), "a request between listing and deleting wins")
}
func TestIdleTTL_StartupClearsLegacyArtifactExpiry(t *testing.T) {
h := &idleHarness{clock: newFakeClock(), store: newMemStorage()}
h.meta = newMemMetadata(h.clock)
past := h.clock.Now().Add(-day)
require.NoError(t, h.meta.SavePackage(context.Background(), &metadata.Package{
Registry: "npm", Name: "lodash", Version: artifactVer, StorageKey: "npm/lodash/" + artifactVer,
LastAccessed: h.clock.Now(), ExpiresAt: &past,
}))
require.NoError(t, h.store.Put(context.Background(), "npm/lodash/"+artifactVer, strings.NewReader("x"), nil))
h.start(t, Config{DefaultTTL: 7 * day, IdleTTL: 7 * day, Now: h.clock.Now, CleanupInterval: 24 * time.Hour})
h.get(t, "lodash", artifactVer)
require.Zero(t, h.fetches, "the legacy 7-day expiry no longer evicts a popular artifact")
p, err := h.meta.GetPackage(context.Background(), "npm", "lodash", artifactVer)
require.NoError(t, err)
require.Nil(t, p.ExpiresAt)
}
+13
View File
@@ -0,0 +1,13 @@
package cache
import "testing"
func TestWithReleaseVersion(t *testing.T) {
with := withReleaseVersion(map[string]interface{}{"version": "six-1.17.0.tar.gz"}, "1.17.0")
if with["release_version"] != "1.17.0" || with["version"] != "six-1.17.0.tar.gz" {
t.Errorf("payload = %v", with)
}
if _, ok := withReleaseVersion(map[string]interface{}{"version": "1.3.0"}, "")["release_version"]; ok {
t.Error("empty release version must not be sent")
}
}
+8
View File
@@ -133,11 +133,15 @@ type MySQLConfig struct {
ParseTime bool `mapstructure:"parse_time" json:"parse_time"`
}
// DefaultIdleTTL is how long a cached item can go unrequested before cleanup removes it.
const DefaultIdleTTL = 7 * 24 * time.Hour
// CacheConfig contains cache management configuration
type CacheConfig struct {
TTLOverrides map[string]time.Duration `mapstructure:"ttl_overrides" json:"ttl_overrides"`
DefaultTTL time.Duration `mapstructure:"default_ttl" json:"default_ttl"`
CleanupInterval time.Duration `mapstructure:"cleanup_interval" json:"cleanup_interval"`
IdleTTL time.Duration `mapstructure:"idle_ttl" json:"idle_ttl"` // 0 disables idle eviction
MaxSizeBytes int64 `mapstructure:"max_size_bytes" json:"max_size_bytes"`
PerProjectQuota int64 `mapstructure:"per_project_quota" json:"per_project_quota"`
}
@@ -353,6 +357,7 @@ func Default() *Config {
Cache: CacheConfig{
DefaultTTL: 7 * 24 * time.Hour,
CleanupInterval: 1 * time.Hour,
IdleTTL: DefaultIdleTTL,
MaxSizeBytes: 500 * 1024 * 1024 * 1024, // 500GB
PerProjectQuota: 50 * 1024 * 1024 * 1024, // 50GB
TTLOverrides: map[string]time.Duration{
@@ -505,6 +510,9 @@ func (c *Config) Validate() error {
if c.Cache.DefaultTTL < 0 {
return fmt.Errorf("cache.default_ttl cannot be negative")
}
if c.Cache.IdleTTL < 0 {
return fmt.Errorf("cache.idle_ttl cannot be negative")
}
if c.Cache.MaxSizeBytes < 0 {
return fmt.Errorf("cache.max_size_bytes cannot be negative")
}
+51
View File
@@ -0,0 +1,51 @@
package config
import (
"os"
"path/filepath"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func loadCacheYAML(t *testing.T, cacheYAML string) (*Config, error) {
t.Helper()
path := filepath.Join(t.TempDir(), "config.yaml")
require.NoError(t, os.WriteFile(path, []byte(cacheYAML), 0600))
return Load(path)
}
func TestIdleTTLDefaultsToAWeek(t *testing.T) {
require.Equal(t, 168*time.Hour, Default().Cache.IdleTTL)
cfg, err := loadCacheYAML(t, "cache:\n default_ttl: 24h\n")
require.NoError(t, err)
require.Equal(t, 168*time.Hour, cfg.Cache.IdleTTL, "an unset key keeps the default")
}
func TestIdleTTLParse(t *testing.T) {
tests := []struct {
name string
yaml string
want time.Duration
wantErr bool
}{
{name: "duration string", yaml: "cache:\n idle_ttl: 72h\n", want: 72 * time.Hour},
{name: "zero disables", yaml: "cache:\n idle_ttl: 0\n", want: 0},
{name: "quoted zero disables", yaml: "cache:\n idle_ttl: \"0\"\n", want: 0},
{name: "quoted duration", yaml: "cache:\n idle_ttl: \"168h\"\n", want: 168 * time.Hour},
{name: "negative rejected", yaml: "cache:\n idle_ttl: -1h\n", wantErr: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cfg, err := loadCacheYAML(t, tt.yaml)
if tt.wantErr {
require.ErrorContains(t, err, "cache.idle_ttl")
return
}
require.NoError(t, err)
require.Equal(t, tt.want, cfg.Cache.IdleTTL)
})
}
}
+58
View File
@@ -9,6 +9,7 @@ import (
"io/fs"
"os"
"path/filepath"
"sort"
"sync"
"time"
@@ -157,6 +158,63 @@ func (s *Store) ListPackages(ctx context.Context, opts *metadata.ListOptions) ([
return packages, nil
}
// filterPackages returns package records (not scan results) matching keep,
// ordered by key ascending and capped at limit.
func (s *Store) filterPackages(ctx context.Context, limit int, keep func(*metadata.Package) bool, key func(*metadata.Package) time.Time) ([]*metadata.Package, error) {
all, err := s.ListPackages(ctx, nil)
if err != nil {
return nil, err
}
var out []*metadata.Package
for _, p := range all {
if p.Registry != "" && p.Name != "" && keep(p) {
out = append(out, p)
}
}
sort.Slice(out, func(i, j int) bool { return key(out[i]).Before(key(out[j])) })
if limit <= 0 {
limit = metadata.DefaultBatchSize
}
if len(out) > limit {
out = out[:limit]
}
return out, nil
}
// ListIdlePackages returns packages last accessed before idleBefore, oldest first.
func (s *Store) ListIdlePackages(ctx context.Context, idleBefore time.Time, limit int) ([]*metadata.Package, error) {
return s.filterPackages(ctx, limit,
func(p *metadata.Package) bool { return p.LastAccessed.Before(idleBefore) },
func(p *metadata.Package) time.Time { return p.LastAccessed })
}
// ListExpiredPackages returns packages whose ExpiresAt is before the given time, oldest first.
func (s *Store) ListExpiredPackages(ctx context.Context, expiredBefore time.Time, limit int) ([]*metadata.Package, error) {
return s.filterPackages(ctx, limit,
func(p *metadata.Package) bool { return p.ExpiresAt != nil && p.ExpiresAt.Before(expiredBefore) },
func(p *metadata.Package) time.Time { return *p.ExpiresAt })
}
// ClearArtifactExpiry removes ExpiresAt from every non-metadata package.
func (s *Store) ClearArtifactExpiry(ctx context.Context) (int64, error) {
all, err := s.ListPackages(ctx, nil)
if err != nil {
return 0, err
}
var cleared int64
for _, p := range all {
if p.Registry == "" || p.Name == "" || p.ExpiresAt == nil || metadata.IsMetadataEntry(p.Name, p.Version) {
continue
}
p.ExpiresAt = nil
if err := s.SavePackage(ctx, p); err != nil {
return cleared, err
}
cleared++
}
return cleared, nil
}
// DeletePackage deletes package metadata
func (s *Store) DeletePackage(ctx context.Context, registry, name, version string) error {
s.mu.Lock()
+52
View File
@@ -0,0 +1,52 @@
package file
import (
"context"
"testing"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/stretchr/testify/require"
)
func TestListIdlePackages(t *testing.T) {
ctx := context.Background()
s, _ := newStore(t)
now := time.Now()
for i, p := range []struct {
name string
age time.Duration
}{{"old-a", 10 * 24 * time.Hour}, {"old-b", 9 * 24 * time.Hour}, {"fresh", time.Hour}} {
require.NoError(t, s.SavePackage(ctx, &metadata.Package{
Registry: "npm", Name: p.name, Version: "1", LastAccessed: now.Add(-p.age), Size: int64(i),
}))
}
require.NoError(t, s.SaveScanResult(ctx, &metadata.ScanResult{Registry: "npm", PackageName: "old-a", PackageVersion: "1"}))
got, err := s.ListIdlePackages(ctx, now.Add(-7*24*time.Hour), 1)
require.NoError(t, err)
require.Len(t, got, 1)
require.Equal(t, "old-a", got[0].Name, "oldest first, scan results are not packages")
got, err = s.ListIdlePackages(ctx, now.Add(-7*24*time.Hour), 10)
require.NoError(t, err)
require.Len(t, got, 2)
}
func TestListExpiredPackagesAndClearArtifactExpiry(t *testing.T) {
ctx := context.Background()
s, _ := newStore(t)
past := time.Now().Add(-time.Hour)
for _, v := range []string{"list", "1.0.0"} {
require.NoError(t, s.SavePackage(ctx, &metadata.Package{Registry: "npm", Name: "x", Version: v, ExpiresAt: &past}))
}
cleared, err := s.ClearArtifactExpiry(ctx)
require.NoError(t, err)
require.Equal(t, int64(1), cleared)
got, err := s.ListExpiredPackages(ctx, time.Now(), 10)
require.NoError(t, err)
require.Len(t, got, 1)
require.Equal(t, "list", got[0].Version)
}
+76 -7
View File
@@ -490,7 +490,11 @@ func (s *GORMStoreV2) ListPackages(ctx context.Context, opts *metadata.ListOptio
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to list packages")
}
// Convert to metadata.Package
return s.modelsToPackages(models), nil
}
// modelsToPackages converts rows to metadata packages, resolving registry names once.
func (s *GORMStoreV2) modelsToPackages(models []PackageModel) []*metadata.Package {
packages := make([]*metadata.Package, len(models))
// Snapshot id->name mapping under read lock once to avoid repeated locking
s.registryCacheMu.RLock()
@@ -502,8 +506,48 @@ func (s *GORMStoreV2) ListPackages(ctx context.Context, opts *metadata.ListOptio
for i, model := range models {
packages[i] = s.modelToPackage(&model, idToName[model.RegistryID])
}
return packages
}
return packages, nil
// listBatch runs a bounded, index-ordered query over live packages.
func (s *GORMStoreV2) listBatch(ctx context.Context, where, order string, arg time.Time, limit int) ([]*metadata.Package, error) {
if limit <= 0 {
limit = metadata.DefaultBatchSize
}
var models []PackageModel
if err := s.db.WithContext(ctx).
Where(where, arg).
Order(order).
Limit(limit).
Find(&models).Error; err != nil {
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to list packages")
}
return s.modelsToPackages(models), nil
}
// ListIdlePackages returns live packages last accessed before idleBefore, oldest first.
func (s *GORMStoreV2) ListIdlePackages(ctx context.Context, idleBefore time.Time, limit int) ([]*metadata.Package, error) {
return s.listBatch(ctx, "last_accessed < ?", "last_accessed ASC", idleBefore, limit)
}
// ListExpiredPackages returns live packages whose expires_at is before the given time, oldest first.
func (s *GORMStoreV2) ListExpiredPackages(ctx context.Context, expiredBefore time.Time, limit int) ([]*metadata.Package, error) {
return s.listBatch(ctx, "expires_at < ?", "expires_at ASC", expiredBefore, limit)
}
// ClearArtifactExpiry nulls expires_at on every row that is not a metadata entry.
func (s *GORMStoreV2) ClearArtifactExpiry(ctx context.Context) (int64, error) {
query := s.db.WithContext(ctx).Model(&PackageModel{}).
Where("expires_at IS NOT NULL").
Where("version NOT IN ?", metadata.MetadataVersions)
for _, suffix := range metadata.MetadataNameSuffixes {
query = query.Where("name NOT LIKE ?", "%"+suffix)
}
result := query.UpdateColumn("expires_at", nil)
if result.Error != nil {
return 0, errors.Wrap(result.Error, errors.ErrCodeStorageFailure, "failed to clear artifact expiry")
}
return result.RowsAffected, nil
}
// UpdateDownloadCount increments download count and records event
@@ -977,11 +1021,7 @@ func (s *GORMStoreV2) SaveCVEBypass(ctx context.Context, bypass *metadata.CVEByp
if bypass.ID != "" {
id, err := strconv.ParseInt(bypass.ID, 10, 64)
if err == nil {
model.ID = id
if err := s.db.WithContext(ctx).Save(model).Error; err != nil {
return errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to update CVE bypass")
}
return nil
return s.updateCVEBypass(ctx, id, model)
}
}
@@ -997,6 +1037,35 @@ func (s *GORMStoreV2) SaveCVEBypass(ctx context.Context, bypass *metadata.CVEByp
return nil
}
// updateCVEBypass rewrites the editable columns only, so created_at and usage counters survive an edit.
func (s *GORMStoreV2) updateCVEBypass(ctx context.Context, id int64, model *CVEBypassModel) error {
db := s.db.WithContext(ctx)
res := db.Model(&CVEBypassModel{}).Where("id = ?", id).Updates(map[string]interface{}{
"type": model.Type,
"target": model.Target,
"reason": model.Reason,
"created_by": model.CreatedBy,
"expires_at": model.ExpiresAt,
"notify_on_expiry": model.NotifyOnExpiry,
"active": model.Active,
})
if res.Error != nil {
return errors.Wrap(res.Error, errors.ErrCodeStorageFailure, "failed to update CVE bypass")
}
if res.RowsAffected > 0 {
return nil
}
// MySQL reports 0 rows for an unchanged row, so tell that apart from a missing one.
var count int64
if err := db.Model(&CVEBypassModel{}).Where("id = ?", id).Count(&count).Error; err != nil {
return errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to update CVE bypass")
}
if count == 0 {
return errors.NotFound("CVE bypass not found")
}
return nil
}
// GetActiveCVEBypasses retrieves all active (non-expired) CVE bypasses
func (s *GORMStoreV2) GetActiveCVEBypasses(ctx context.Context) ([]*metadata.CVEBypass, error) {
var models []CVEBypassModel
@@ -91,9 +91,20 @@ func (s *MySQLV2IntegrationTestSuite) TearDownTest() {
"registries",
}
for _, table := range tables {
s.store.db.Exec("TRUNCATE TABLE " + table)
}
// FOREIGN_KEY_CHECKS is per connection, so truncate on one pinned connection.
err := s.store.db.Connection(func(tx *gorm.DB) error {
if err := tx.Exec("SET FOREIGN_KEY_CHECKS = 0").Error; err != nil {
return err
}
defer tx.Exec("SET FOREIGN_KEY_CHECKS = 1")
for _, table := range tables {
if err := tx.Exec("TRUNCATE TABLE " + table).Error; err != nil {
return err
}
}
return nil
})
s.Require().NoError(err)
// Re-seed default registries after truncate
defaultRegistries := []RegistryModel{
@@ -124,10 +135,11 @@ func TestMySQLV2IntegrationTestSuite(t *testing.T) {
// Test_MySQLV2_SpecificFeatures tests MySQL-specific features
func (s *MySQLV2IntegrationTestSuite) Test_MySQLV2_SpecificFeatures() {
// Test that we're actually using MySQL
var version string
err := s.store.db.Raw("SELECT VERSION()").Scan(&version).Error
// VERSION() is a bare number ("8.0.46"); the server flavour is in version_comment.
var comment string
err := s.store.db.Raw("SELECT @@version_comment").Scan(&comment).Error
s.NoError(err)
s.Contains(version, "MySQL")
s.Contains(comment, "MySQL")
}
// Test_MySQLV2_NoPartitioning tests that partition manager is nil for MySQL
@@ -713,6 +713,36 @@ func (s *GORMStoreV2TestSuite) Test_V2_SaveCVEBypass_Update() {
s.NoError(err)
}
// Test_V2_SaveCVEBypass_UpdateKeepsCreatedAt guards against an edit zeroing created_at.
func (s *GORMStoreV2TestSuite) Test_V2_SaveCVEBypass_UpdateKeepsCreatedAt() {
bypass := &metadata.CVEBypass{
Type: metadata.BypassTypeCVE, Target: "CVE-2024-0003", Reason: "before",
CreatedBy: "[email protected]", ExpiresAt: time.Now().Add(time.Hour), Active: true,
}
s.Require().NoError(s.store.SaveCVEBypass(s.ctx, bypass))
var before CVEBypassModel
s.Require().NoError(s.store.db.First(&before, bypass.ID).Error)
bypass.Reason = "after"
s.Require().NoError(s.store.SaveCVEBypass(s.ctx, bypass))
var after CVEBypassModel
s.Require().NoError(s.store.db.First(&after, bypass.ID).Error)
s.Equal("after", after.Reason)
s.False(after.CreatedAt.IsZero())
s.WithinDuration(before.CreatedAt, after.CreatedAt, time.Second)
}
// Test_V2_SaveCVEBypass_UpdateMissing tests that editing an unknown bypass fails.
func (s *GORMStoreV2TestSuite) Test_V2_SaveCVEBypass_UpdateMissing() {
err := s.store.SaveCVEBypass(s.ctx, &metadata.CVEBypass{
ID: "999999", Type: metadata.BypassTypeCVE, Target: "CVE-2024-0004", Reason: "x",
CreatedBy: "[email protected]", ExpiresAt: time.Now().Add(time.Hour), Active: true,
})
s.Error(err)
}
// Test_V2_GetActiveCVEBypasses tests retrieving active CVE bypasses
func (s *GORMStoreV2TestSuite) Test_V2_GetActiveCVEBypasses() {
// Create active bypass with unique target
@@ -0,0 +1,42 @@
//go:build pgintegration
package gormstore
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestPostgresIdleEviction(t *testing.T) {
store, _ := newPostgresStore(t)
reset := func(t *testing.T) {
t.Helper()
require.NoError(t, store.db.Exec(
"TRUNCATE packages, download_events, download_stats_hourly, download_stats_daily RESTART IDENTITY CASCADE").Error)
}
for name, check := range map[string]func(*testing.T, *GORMStoreV2){
"list idle": checkListIdlePackages,
"list expired": checkListExpiredPackages,
"clear artifact expiry": checkClearArtifactExpiry,
"delete keeps history": checkDeleteKeepsDownloadHistory,
} {
t.Run(name, func(t *testing.T) {
reset(t)
check(t, store)
})
}
}
func TestPostgresHistoryTablesHaveNoPackageForeignKey(t *testing.T) {
store, _ := newPostgresStore(t)
var referencing []string
require.NoError(t, store.db.Raw(
"SELECT conrelid::regclass::text FROM pg_constraint WHERE contype = 'f' AND confrelid = 'packages'::regclass",
).Scan(&referencing).Error)
for _, table := range []string{"download_events", "download_stats_hourly", "download_stats_daily"} {
require.NotContains(t, referencing, table, "%s must not reference packages: a package delete would restrict or cascade over history", table)
}
}
@@ -0,0 +1,163 @@
package gormstore
import (
"context"
"fmt"
"testing"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/stretchr/testify/require"
)
func savePkg(t *testing.T, store *GORMStoreV2, name, version string, lastAccessed time.Time, expiresAt *time.Time) {
t.Helper()
require.NoError(t, store.SavePackage(context.Background(), &metadata.Package{
Registry: "npm", Name: name, Version: version,
StorageKey: fmt.Sprintf("npm/%s/%s", name, version),
Size: 100, CachedAt: lastAccessed, LastAccessed: lastAccessed, ExpiresAt: expiresAt,
}))
}
func names(pkgs []*metadata.Package) []string {
out := make([]string, len(pkgs))
for i, p := range pkgs {
out[i] = p.Name
}
return out
}
func checkListIdlePackages(t *testing.T, store *GORMStoreV2) {
ctx := context.Background()
now := time.Now().UTC()
savePkg(t, store, "idle-oldest", "1.0.0", now.Add(-10*24*time.Hour), nil)
savePkg(t, store, "idle-middle", "1.0.0", now.Add(-9*24*time.Hour), nil)
savePkg(t, store, "idle-newest", "1.0.0", now.Add(-8*24*time.Hour), nil)
savePkg(t, store, "recent", "1.0.0", now.Add(-24*time.Hour), nil)
savePkg(t, store, "touched", "1.0.0", now.Add(-12*24*time.Hour), nil)
require.NoError(t, store.UpdateDownloadCount(ctx, "npm", "touched", "1.0.0"))
cutoff := now.Add(-7 * 24 * time.Hour)
batch, err := store.ListIdlePackages(ctx, cutoff, 2)
require.NoError(t, err)
require.Equal(t, []string{"idle-oldest", "idle-middle"}, names(batch), "oldest first, capped at the limit")
require.Equal(t, "npm", batch[0].Registry)
require.Equal(t, "npm/idle-oldest/1.0.0", batch[0].StorageKey)
require.Equal(t, int64(100), batch[0].Size)
for _, p := range batch {
require.NoError(t, store.DeletePackage(ctx, p.Registry, p.Name, p.Version))
}
batch, err = store.ListIdlePackages(ctx, cutoff, 2)
require.NoError(t, err)
require.Equal(t, []string{"idle-newest"}, names(batch), "deleted rows leave the result; a touched row is not idle")
batch, err = store.ListIdlePackages(ctx, cutoff, 0)
require.NoError(t, err, "a non-positive limit falls back to the default batch size")
require.Equal(t, []string{"idle-newest"}, names(batch))
}
func checkListExpiredPackages(t *testing.T, store *GORMStoreV2) {
ctx := context.Background()
now := time.Now().UTC()
past, future := now.Add(-time.Hour), now.Add(time.Hour)
savePkg(t, store, "stale-meta", "list", now, &past)
savePkg(t, store, "fresh-meta", "list", now, &future)
savePkg(t, store, "no-expiry", "1.0.0", now, nil)
got, err := store.ListExpiredPackages(ctx, now, 10)
require.NoError(t, err)
require.Equal(t, []string{"stale-meta"}, names(got))
}
func checkClearArtifactExpiry(t *testing.T, store *GORMStoreV2) {
ctx := context.Background()
now := time.Now().UTC()
exp := now.Add(24 * time.Hour)
savePkg(t, store, "lodash", "4.17.21", now, &exp)
savePkg(t, store, "left-pad", "1.3.0", now, &exp)
savePkg(t, store, "lodash", "list", now, &exp)
savePkg(t, store, "lodash", "page", now, &exp)
savePkg(t, store, "lodash", "latest", now, &exp)
savePkg(t, store, "lodash", "metadata", now, &exp)
savePkg(t, store, "golang.org/x/text/@v/v0.3.0.mod", "v0.3.0", now, &exp)
savePkg(t, store, "golang.org/x/text/@v/v0.3.0.info", "v0.3.0", now, &exp)
cleared, err := store.ClearArtifactExpiry(ctx)
require.NoError(t, err)
require.Equal(t, int64(2), cleared, "only the two artifacts lose their expiry")
for _, a := range [][2]string{{"lodash", "4.17.21"}, {"left-pad", "1.3.0"}} {
p, getErr := store.GetPackage(ctx, "npm", a[0], a[1])
require.NoError(t, getErr)
require.Nil(t, p.ExpiresAt, a[0])
}
for _, m := range [][2]string{
{"lodash", "list"}, {"lodash", "page"}, {"lodash", "latest"}, {"lodash", "metadata"},
{"golang.org/x/text/@v/v0.3.0.mod", "v0.3.0"}, {"golang.org/x/text/@v/v0.3.0.info", "v0.3.0"},
} {
p, getErr := store.GetPackage(ctx, "npm", m[0], m[1])
require.NoError(t, getErr)
require.NotNil(t, p.ExpiresAt, "metadata entry %s@%s keeps its freshness expiry", m[0], m[1])
}
again, err := store.ClearArtifactExpiry(ctx)
require.NoError(t, err)
require.Zero(t, again, "idempotent")
}
// A deleted package must not change the download totals: history rows carry
// package_id with no foreign key, and the soft delete keeps the package row.
func checkDeleteKeepsDownloadHistory(t *testing.T, store *GORMStoreV2) {
ctx := context.Background()
recordDownloads(t, store, 3)
// Two of the three downloads sit in a completed hour, ready to aggregate.
require.NoError(t, store.db.Exec(
"UPDATE download_events SET downloaded_at = ? WHERE id IN (SELECT id FROM (SELECT id FROM download_events ORDER BY id LIMIT 2) AS first_two)",
time.Now().UTC().Add(-3*time.Hour)).Error)
total := func(label string) {
t.Helper()
for _, period := range []string{"1day", "7day", "30day"} {
ts, err := store.GetTimeSeriesStats(ctx, period, "")
require.NoError(t, err)
require.Equal(t, int64(3), sumPoints(ts), "%s (%s)", label, period)
}
}
total("before delete")
require.NoError(t, store.DeletePackage(ctx, "npm", "left-pad", "1.3.0"))
total("after delete")
// Re-caching the key hard-deletes the stale soft-deleted row.
now := time.Now()
require.NoError(t, store.SavePackage(ctx, &metadata.Package{
Registry: "npm", Name: "left-pad", Version: "1.3.0", StorageKey: "npm/left-pad/1.3.0",
Size: 10, CachedAt: now, LastAccessed: now,
}))
total("after re-cache")
// Aggregation writes package_id rows for a package that is gone again.
require.NoError(t, store.DeletePackage(ctx, "npm", "left-pad", "1.3.0"))
require.NoError(t, store.AggregateDownloadData(ctx))
total("after delete and aggregation")
}
func TestListIdlePackages(t *testing.T) { checkListIdlePackages(t, newTimeSeriesStore(t)) }
func TestListExpiredPackages(t *testing.T) { checkListExpiredPackages(t, newTimeSeriesStore(t)) }
func TestClearArtifactExpiry(t *testing.T) { checkClearArtifactExpiry(t, newTimeSeriesStore(t)) }
func TestDeletePackageKeepsDownloadHistory(t *testing.T) {
checkDeleteKeepsDownloadHistory(t, newTimeSeriesStore(t))
}
func (s *GORMStoreV2TestSuite) Test_V2_ListIdlePackages() { checkListIdlePackages(s.T(), s.store) }
func (s *GORMStoreV2TestSuite) Test_V2_ListExpiredPackages() {
checkListExpiredPackages(s.T(), s.store)
}
func (s *GORMStoreV2TestSuite) Test_V2_ClearArtifactExpiry() {
checkClearArtifactExpiry(s.T(), s.store)
}
func (s *GORMStoreV2TestSuite) Test_V2_DeleteKeepsDownloadHistory() {
checkDeleteKeepsDownloadHistory(s.T(), s.store)
}
+38 -1
View File
@@ -14,6 +14,31 @@ import (
// Callers should treat it as a non-fatal capability check.
var ErrNotImplemented = errors.New("metadata: operation not implemented by this backend")
// DefaultBatchSize bounds the rows a list query returns when the caller passes no limit.
const DefaultBatchSize = 500
// MetadataVersions are the cache-key versions of metadata pages (index, list, latest).
var MetadataVersions = []string{"list", "page", "latest", "metadata"}
// MetadataNameSuffixes mark Go module metadata files (.mod, .info).
var MetadataNameSuffixes = []string{".mod", ".info"}
// IsMetadataEntry reports whether a cache entry is a metadata page that must
// refresh, as opposed to an immutable artifact.
func IsMetadataEntry(name, version string) bool {
for _, v := range MetadataVersions {
if version == v {
return true
}
}
for _, suffix := range MetadataNameSuffixes {
if strings.HasSuffix(name, suffix) {
return true
}
}
return false
}
// Store is an alias for MetadataStore for convenience
type Store = MetadataStore
@@ -31,9 +56,21 @@ type MetadataStore interface {
// ListPackages lists packages with optional filtering
ListPackages(ctx context.Context, opts *ListOptions) ([]*Package, error)
// UpdateDownloadCount increments download counter
// UpdateDownloadCount increments download counter and stamps last_accessed
UpdateDownloadCount(ctx context.Context, registry, name, version string) error
// ListIdlePackages returns up to limit packages last accessed before
// idleBefore, oldest first. A limit <= 0 means DefaultBatchSize.
ListIdlePackages(ctx context.Context, idleBefore time.Time, limit int) ([]*Package, error)
// ListExpiredPackages returns up to limit packages whose ExpiresAt is before
// the given time, oldest first. A limit <= 0 means DefaultBatchSize.
ListExpiredPackages(ctx context.Context, expiredBefore time.Time, limit int) ([]*Package, error)
// ClearArtifactExpiry removes ExpiresAt from every non-metadata entry and
// returns the number of rows changed. It is idempotent.
ClearArtifactExpiry(ctx context.Context) (int64, error)
// GetStats returns statistics
GetStats(ctx context.Context, registry string) (*Stats, error)
+8
View File
@@ -62,6 +62,14 @@ var (
[]string{"reason"}, // ttl, lru, manual
)
// WebSocketEventsDropped counts realtime events dropped because the broadcast channel was full.
WebSocketEventsDropped = promauto.NewCounter(
prometheus.CounterOpts{
Name: "gohoarder_websocket_events_dropped_total",
Help: "Realtime dashboard events dropped because the broadcast channel was full",
},
)
// Storage metrics
StorageOperations = promauto.NewCounterVec(
prometheus.CounterOpts{
+12 -2
View File
@@ -528,6 +528,15 @@ func normalizeBypassPackageName(registry, name string) string {
return name
}
// releaseVersionKey returns "registry/name@release_version" for packages keyed by file name (PyPI), else "".
func (m *Manager) releaseVersionKey(ctx context.Context, registry, packageName, version, bypassName string) string {
pkg, err := m.metadataStore.GetPackage(ctx, registry, packageName, version)
if err != nil || pkg == nil || pkg.ReleaseVersion == "" {
return ""
}
return fmt.Sprintf("%s/%s@%s", registry, bypassName, pkg.ReleaseVersion)
}
// CheckVulnerabilities checks if a package exceeds vulnerability thresholds
func (m *Manager) CheckVulnerabilities(ctx context.Context, registry, packageName, version string) (bool, string, error) {
if !m.enabled {
@@ -545,10 +554,11 @@ func (m *Manager) CheckVulnerabilities(ctx context.Context, registry, packageNam
bypassName := normalizeBypassPackageName(registry, packageName)
packageKey := fmt.Sprintf("%s/%s@%s", registry, bypassName, version)
packageKeyNoVersion := fmt.Sprintf("%s/%s", registry, bypassName)
releaseKey := m.releaseVersionKey(ctx, registry, packageName, version, bypassName)
for _, bypass := range bypasses {
if bypass.Type == metadata.BypassTypePackage && bypass.Active {
if bypass.Target == packageKey || bypass.Target == packageKeyNoVersion {
if bypass.Target == packageKey || bypass.Target == packageKeyNoVersion || (releaseKey != "" && bypass.Target == releaseKey) {
log.Info().
Str("package", packageKey).
Str("bypass_id", bypass.ID).
@@ -605,7 +615,7 @@ func (m *Manager) CheckVulnerabilities(ctx context.Context, registry, packageNam
for _, bypass := range bypasses {
if bypass.Type == metadata.BypassTypeCVE && bypass.Active {
// Check if bypass applies to this package (if AppliesTo is set)
if bypass.AppliesTo != "" && bypass.AppliesTo != packageKey && bypass.AppliesTo != packageKeyNoVersion {
if bypass.AppliesTo != "" && bypass.AppliesTo != packageKey && bypass.AppliesTo != packageKeyNoVersion && (releaseKey == "" || bypass.AppliesTo != releaseKey) {
continue // This bypass doesn't apply to this package
}
bypassedCVEs[strings.ToUpper(bypass.Target)] = bypass
+45
View File
@@ -118,6 +118,13 @@ func (m *stubMetadataStore) GetTimeSeriesStats(context.Context, string, string)
return nil, nil
}
func (m *stubMetadataStore) AggregateDownloadData(context.Context) error { return nil }
func (m *stubMetadataStore) ListIdlePackages(context.Context, time.Time, int) ([]*metadata.Package, error) {
return nil, nil
}
func (m *stubMetadataStore) ListExpiredPackages(context.Context, time.Time, int) ([]*metadata.Package, error) {
return nil, nil
}
func (m *stubMetadataStore) ClearArtifactExpiry(context.Context) (int64, error) { return 0, nil }
func (m *stubMetadataStore) SaveAPIKey(context.Context, *metadata.APIKey) error {
return metadata.ErrNotImplemented
}
@@ -453,3 +460,41 @@ func TestScanner_DisabledReportsNotEnabled(t *testing.T) {
assert.False(t, mgr.Enabled())
assert.True(t, newTestManager(t, &stubMetadataStore{}).Enabled())
}
// releasePackageStore returns a PyPI-style package whose cache key is a file name.
type releasePackageStore struct {
*stubBypassStore
}
func (m *releasePackageStore) GetPackage(_ context.Context, _, _, version string) (*metadata.Package, error) {
return &metadata.Package{Name: "six", Version: version, ReleaseVersion: "1.17.0"}, nil
}
func TestCheckVulnerabilities_PackageBypassMatchesReleaseVersion(t *testing.T) {
const file = "six-1.17.0-py2.py3-none-any.whl"
cases := []struct {
name string
target string
blocked bool
}{
{"release version target", "pypi/[email protected]", false},
{"file name target", "pypi/six@" + file, false},
{"other release", "pypi/[email protected]", true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
store := &releasePackageStore{&stubBypassStore{
stubMetadataStore: &stubMetadataStore{},
bypasses: []*metadata.CVEBypass{{ID: "b1", Type: metadata.BypassTypePackage, Target: tc.target, Active: true}},
scan: &metadata.ScanResult{
ID: "r", Scanner: "stub", ScannedAt: time.Now(), Status: metadata.ScanStatusVulnerable,
Vulnerabilities: []metadata.Vulnerability{{ID: "CVE-1", Severity: "HIGH"}},
},
}}
mgr := newTestManager(t, store)
blocked, _, err := mgr.CheckVulnerabilities(context.Background(), "pypi", "six", file)
require.NoError(t, err)
assert.Equal(t, tc.blocked, blocked)
})
}
}
+26 -1
View File
@@ -7,10 +7,13 @@ import (
"encoding/json"
"net/http"
"sync"
"sync/atomic"
"time"
"github.com/gorilla/websocket"
"github.com/rs/zerolog/log"
"github.com/lukaszraczylo/gohoarder/pkg/metrics"
)
// EventType represents the type of event being broadcast
@@ -59,6 +62,8 @@ type Server struct {
unregister chan *Client
upgrader websocket.Upgrader
mu sync.RWMutex
dropped atomic.Uint64
lastWarn atomic.Int64
}
// Config holds WebSocket server configuration
@@ -222,10 +227,30 @@ func (s *Server) Broadcast(eventType EventType, data map[string]interface{}) {
select {
case s.broadcast <- event:
default:
log.Warn().Msg("Broadcast channel full - dropping event")
s.recordDrop()
}
}
// dropWarnInterval bounds the drop warning to one line per interval, so a burst does not flood the log.
const dropWarnInterval = time.Minute
// recordDrop counts a dropped event and warns at most once per dropWarnInterval.
func (s *Server) recordDrop() {
total := s.dropped.Add(1)
metrics.WebSocketEventsDropped.Inc()
now := time.Now().UnixNano()
last := s.lastWarn.Load()
if now-last < int64(dropWarnInterval) || !s.lastWarn.CompareAndSwap(last, now) {
return
}
log.Warn().Uint64("dropped_total", total).Msg("Broadcast channel full - dropping events")
}
// Dropped returns how many events were dropped because the broadcast channel was full.
func (s *Server) Dropped() uint64 {
return s.dropped.Load()
}
// BroadcastEvent satisfies the events.Broadcaster contract used by
// cache/scanner sub-systems. It accepts a string event type and an
// arbitrary payload (typically map[string]any) and forwards to the