hs-hath 1.3.0 → 1.4.0
raw patch · 36 files changed
+1377/−496 lines, 36 filesdep +data-defaultdep ~crypton-connectionPVP ok
version bump matches the API change (PVP)
Dependencies added: data-default
Dependency ranges changed: crypton-connection
API changes (from Hackage documentation)
- Hath.Cache.Filesystem: newFsCache :: FilePath -> IO FsCache
- Hath.Cache.Filesystem: sweep :: FsCache -> Int64 -> IO (Int, Int64)
+ Hath.Cache.FileStatus: regularFile :: FilePath -> IO (Maybe (Int64, Int64))
+ Hath.Cache.FileStatus: touch :: FilePath -> IO ()
+ Hath.Cache.Filesystem: cachedBytes :: FsCache -> IO Int64
+ Hath.Cache.Filesystem: cachedFiles :: FsCache -> IO Int
+ Hath.Cache.Filesystem: evict :: FsCache -> Int64 -> IO (Int, Int64)
+ Hath.Cache.Filesystem: instance GHC.Classes.Eq Hath.Cache.Filesystem.Range
+ Hath.Cache.Filesystem: instance GHC.Show.Show Hath.Cache.Filesystem.Range
+ Hath.Cache.Filesystem: openFsCache :: FilePath -> IO Int64 -> Bool -> Bool -> IO FsCache
+ Hath.Cache.Filesystem: saveState :: FsCache -> IO ()
+ Hath.Cache.SQLite: isEmpty :: Connection -> IO Bool
+ Hath.DiskSpace: availableBytes :: FilePath -> IO (Maybe Int64)
+ Hath.Download: via :: Maybe ImageProxy -> Request -> IO (Manager, Request)
+ Hath.Gallery.Downloader: instance GHC.Classes.Eq Hath.Gallery.Downloader.Outcome
+ Hath.RPC: BadNetwork :: Stop
+ Hath.RPC: NotLoggedIn :: Stop
+ Hath.RPC: RPCServers :: ![ByteString] -> !Int -> !Maybe ByteString -> !Maybe ByteString -> RPCServers
+ Hath.RPC: [rpcCurrent] :: RPCServers -> !Maybe ByteString
+ Hath.RPC: [rpcKnown] :: RPCServers -> ![ByteString]
+ Hath.RPC: [rpcLastFailed] :: RPCServers -> !Maybe ByteString
+ Hath.RPC: [rpcPort] :: RPCServers -> !Int
+ Hath.RPC: data RPCServers
+ Hath.RPC: data Stop
+ Hath.RPC: failedRPCServer :: ByteString -> RPCServers -> RPCServers
+ Hath.RPC: forgetRPCServerFailure :: IO ()
+ Hath.RPC: instance GHC.Classes.Eq Hath.RPC.RPCServers
+ Hath.RPC: instance GHC.Classes.Eq Hath.RPC.Stop
+ Hath.RPC: instance GHC.Show.Show Hath.RPC.RPCServers
+ Hath.RPC: instance GHC.Show.Show Hath.RPC.Stop
+ Hath.RPC: loginFailure :: HathError -> (Int, Text)
+ Hath.RPC: pickRPCServer :: Int -> RPCServers -> RPCServers
+ Hath.Server: SessionLost :: ServerAction
+ Hath.Server: [skipStartupVerify] :: ServerOptions -> !Bool
+ Hath.Server.App: SessionLost :: ServerAction
+ Hath.Server.Range: fileETag :: FileURI -> ByteString
+ Hath.Server.Range: notModified :: ByteString -> RequestHeaders -> Bool
+ Hath.Server.Range: requestedPart :: ByteString -> Int -> RequestHeaders -> Maybe (Int, Int)
+ Hath.Settings: HTTPProxy :: !ByteString -> !Int -> ImageProxy
+ Hath.Settings: SOCKSProxy :: !String -> !Int -> ImageProxy
+ Hath.Settings: [imageProxyHost] :: HathSettings -> !ByteString
+ Hath.Settings: [imageProxyPort] :: HathSettings -> !Int
+ Hath.Settings: [imageProxyType] :: HathSettings -> !ByteString
+ Hath.Settings: [rescanCache] :: HathSettings -> !Bool
+ Hath.Settings: [rpcServerPort] :: HathSettings -> !Int
+ Hath.Settings: [staticRangeCount] :: HathSettings -> !Int
+ Hath.Settings: [verifyCache] :: HathSettings -> !Bool
+ Hath.Settings: data ImageProxy
+ Hath.Settings: imageProxy :: HathSettings -> Maybe ImageProxy
+ Hath.Settings: instance GHC.Classes.Eq Hath.Settings.ImageProxy
+ Hath.Settings: instance GHC.Show.Show Hath.Settings.ImageProxy
- Hath.Download: fetchFile :: Int -> Request -> (Int -> ByteString -> IO ()) -> IO (Either Text Int)
+ Hath.Download: fetchFile :: Int -> Maybe ImageProxy -> Request -> (Int -> ByteString -> IO ()) -> IO (Either Text Int)
- Hath.Locate: Streamed :: !(ByteString -> IO ()) -> IO () -> Located
+ Hath.Locate: Streamed :: !Relay -> Located
- Hath.Locate: locateResource :: forall (r :: EffectRow). Members '[Cache :: (Type -> Type) -> Type -> Type, RPC :: (Type -> Type) -> Type -> Type, Reader StatsEnv, Log Message, Reader ClientConfig, Error HathError :: (Type -> Type) -> Type -> Type, Embed IO, Final IO] r => Int -> ByteString -> FileURI -> (ByteString, ByteString) -> Sem r (Either Status Located)
+ Hath.Locate: locateResource :: forall (r :: EffectRow). Members '[Cache :: (Type -> Type) -> Type -> Type, RPC :: (Type -> Type) -> Type -> Type, Reader StatsEnv, Log Message, Reader ClientConfig, Error HathError :: (Type -> Type) -> Type -> Type, Embed IO, Final IO] r => HathSettings -> ByteString -> FileURI -> (ByteString, ByteString) -> Sem r (Either Status Located)
- Hath.RPC: toldToStop :: HathError -> Bool
+ Hath.RPC: toldToStop :: HathError -> Maybe Stop
- Hath.Server: ServerOptions :: !Bool -> !Bool -> ServerOptions
+ Hath.Server: ServerOptions :: !Bool -> !Bool -> !Bool -> ServerOptions
- Hath.Server: startServer :: ClientConfig -> ServerOptions -> HathSettings -> (CertificateChain, PrivKey) -> TChan ServerAction -> IO ()
+ Hath.Server: startServer :: ClientConfig -> ServerOptions -> HathSettings -> (CertificateChain, PrivKey) -> TChan ServerAction -> IO ExitCode
- Hath.Settings: HathSettings :: !ByteString -> !Int -> !Int64 -> !Int64 -> !Int64 -> ![ByteString] -> !Int -> !Int -> !Int -> HathSettings
+ Hath.Settings: HathSettings :: !ByteString -> !Int -> !Int64 -> !Int64 -> !Int64 -> ![ByteString] -> !Int -> !Int -> !Int -> !Int -> !Int -> !Bool -> !Bool -> !ByteString -> !ByteString -> !Int -> HathSettings
Files
- CHANGELOG.md +39/−0
- README.md +52/−46
- app/Main.hs +33/−12
- cbits/available.c +23/−0
- hs-hath.cabal +33/−10
- src/Hath/Cache.hs +2/−4
- src/Hath/Cache/FileStatus.hs +48/−0
- src/Hath/Cache/Filesystem.hs +261/−92
- src/Hath/Cache/R2.hs +3/−8
- src/Hath/Cache/SQLite.hs +4/−0
- src/Hath/Config.hs +36/−13
- src/Hath/DiskSpace.hs +12/−0
- src/Hath/Download.hs +46/−21
- src/Hath/Error.hs +1/−3
- src/Hath/FileURI.hs +1/−3
- src/Hath/Gallery/Downloader.hs +40/−19
- src/Hath/Locate.hs +108/−88
- src/Hath/Protocol.hs +1/−10
- src/Hath/RPC.hs +108/−31
- src/Hath/Server.hs +71/−35
- src/Hath/Server/App.hs +3/−1
- src/Hath/Server/ConnectionLimit.hs +2/−7
- src/Hath/Server/Handlers.hs +55/−34
- src/Hath/Server/Range.hs +52/−0
- src/Hath/ServerTime.hs +1/−8
- src/Hath/Settings.hs +44/−0
- src/Hath/Stats.hs +3/−8
- src/Hath/Version.hs +7/−4
- test/APISpec.hs +0/−1
- test/FileURISpec.hs +0/−1
- test/FilesystemSpec.hs +83/−11
- test/Integration.hs +77/−7
- test/ProtocolSpec.hs +0/−3
- test/RPCSpec.hs +39/−4
- test/RangeSpec.hs +39/−0
- test/Spec.hs +50/−12
CHANGELOG.md view
@@ -4,6 +4,45 @@ and this project adheres to the [Haskell Package Versioning Policy](https://pvp.haskell.org/). +## [1.4.0] - 2026-11-29++### Upgrade notes+- **Supervisor**: on `FAIL_NOT_LOGGED_IN` from `still_alive`, the client now exits with status 1 instead of continuing; have the supervisor restart it on failure+- **Startup**: the client now refuses to start with an empty `Filesystem` or `SQLite` cache while more than 20 static ranges are assigned, or on `Filesystem` if the disk cannot hold the cache size+- **Image proxy**: a proxy set on the H@H settings page now takes effect; clear it there if the proxy is unreachable+- **Release archives** no longer contain `migrate-to-r2` or `hath-bench`+- **`client-login`**: delete `version`, `proxy` and `lruCacheSize`, with their types and defaults, to silence the warning on startup (see Deprecated)+- **Library API**: exports and signatures changed (see Changed)++### Added+- Multi-arch Docker image (`ghcr.io/pe200012/hs-hath`, `linux/amd64` and `linux/arm64`) on distroless nonroot, plus `compose.yaml`+- `--version` reads `HATH_BUILD_COMMIT` at compile time when set+- Windows build support and `hs-hath-<version>-windows-x64.zip` release archives (Ctrl+C and Ctrl+Break trigger graceful shutdown; closing the console window exits immediately)+- `Hath.Cache.FileStatus` module for cross-platform file status and mtime lookups+- RPC failover between the `rpc_server_ip` servers, as in the official client+- Image proxy from the H@H settings page, for cache misses, proxy tests and retried gallery downloads+- `ETag`, `If-None-Match` (304) and single byte ranges for cached files; `Cache-Control` adds `immutable`+- Filesystem backend: totals saved at shutdown and reused at start; SHA-1 check of a file last served over a week ago; `verify_cache` and `rescan_cache`+- Official startup checks: refuse an empty cache with more than 20 static ranges, and a disk too small for the cache size+- No caching while less than `diskremaining_bytes` (at least 100 MiB) would be left free; gallery downloads pause under `diskremaining_bytes` + 1000 MiB++### Changed+- Release archives ship only `hs-hath` and `LICENSE` (build `migrate-to-r2` and `hath-bench` from source); Linux builds are static musl binaries for `amd64` and `arm64` without UPX+- `unix` dependency is gated to non-Windows targets+- Filesystem backend deletes blacklisted entries only if they are regular files+- A failed login waits 5 s before exiting, 15 min on `FAIL_STARTUP_LOOP`+- `FAIL_NOT_LOGGED_IN` from `still_alive` shuts down with exit status 1+- Requests that miss the same file share one upstream download+- Filesystem eviction works through the directory with the oldest file instead of rescanning the whole cache+- Library: `Hath.Cache.Filesystem` exports `openFsCache` and `evict` instead of `newFsCache` and `sweep`; `startServer` returns an `ExitCode`; `ServerOptions` has `skipStartupVerify`; `toldToStop` returns `Maybe Stop`; `locateResource` takes the settings and `fetchFile` the image proxy++### Deprecated+- `version`, `proxy` and `lruCacheSize` in `client-login`: never used; they may now be omitted, trigger a warning if present, and will be removed+- Library: `Hath.Config` deprecates `version`, `proxy`, `lruCacheSize` and `ClientProxy`++### Removed+- `service/` (personal VPN/tunnel Dockerfile and compose file)+ ## [1.3.0] - 2026-11-18 ### Upgrade notes
README.md view
@@ -1,56 +1,61 @@ # hs-hath -A [Hentai@Home](https://ehwiki.org/wiki/Hentai@Home) client written in Haskell, also on [Hackage](https://hackage.haskell.org/package/hs-hath).+A [Hentai@Home](https://ehwiki.org/wiki/Hentai@Home) client written in Haskell, also on [Hackage](https://hackage.haskell.org/package/hs-hath). Supports local disk, SQLite, and S3-compatible (e.g. Cloudflare R2) cache backends, Dhall configuration, and Prometheus metrics at `/metrics`. Expect ~200 MiB RAM on average. -It caches files on the local disk, in an SQLite database, or in S3-compatible storage (such as Cloudflare R2), uses Dhall for configuration, and exposes Prometheus metrics at `/metrics`.+## Install -## Getting Started+Prebuilt static binaries for Linux (`amd64`, `arm64`) and Windows (`x64`) are available on [GitHub Releases](https://github.com/pe200012/hs-hath/releases). -### Prerequisites+Multi-arch Docker images (`linux/amd64`, `linux/arm64`) are published to `ghcr.io/pe200012/hs-hath`. With [`compose.yaml`](compose.yaml): -* [Stack](https://docs.haskellstack.org/)-* SQLite 3-* The `openssl` command, only to run the test suite and `hath-bench`, which create certificates with it+```sh+mkdir cache download+cp client-login.example client-login # set clientId and key+echo HATH_PORT=443 > .env # port from your H@H settings page+docker compose up -d+``` -### Installation+To build from source, install [Stack](https://docs.haskellstack.org/) and SQLite 3, then run: -1. Build the project:- ```sh- stack build- ```-2. Copy `client-login.example` to `client-login` and fill in your credentials and paths:- ```sh- cp client-login.example client-login- ```- ```dhall- in ClientConfig::{- , clientId = "<YOURID>"- , key = "<YOURKEY>"- , version = "176"- , downloadDir = "./download"- , cachePath = "./cache"- , cacheBackend = CacheBackend.CacheBackendFilesystem- , r2Config = None R2Config- }- ```- The example defines the record's types and defaults, so the file only names what differs. `version`, `proxy` and `lruCacheSize` are not read. `cacheBackend` is one of:+```sh+stack build+``` - * `CacheBackendFilesystem`: files under `cachePath` (a directory) as `xxxx/<file id>`, sent straight from disk. The least recently served files are evicted to stay under the disk limit set on the H@H settings page.- * `CacheBackendSQLite`: files stored in the database file at `cachePath`. Nothing is evicted, and every cached file is checked against its hash at start unless `--skip-startup-verify` is given.- * `CacheBackendR2`: `r2Config = Some { r2Endpoint = "https://<account id>.r2.cloudflarestorage.com", r2Bucket = "<bucket>" }`, with `R2_ACCESS_KEY` and `R2_SECRET_KEY` in the environment. A hit is answered with a redirect to a presigned link; nothing is evicted.+## Configuration +Copy `client-login.example` to `client-login` and fill it in. `hs-hath` reads `./client-login` unless given `-c FILE`.++```dhall+in ClientConfig::{+ , clientId = "<YOURID>"+ , key = "<YOURKEY>"+ , downloadDir = "./download"+ , cachePath = "./cache"+ , cacheBackend = CacheBackend.CacheBackendFilesystem+ , r2Config = None R2Config+ }+```++`version`, `proxy` and `lruCacheSize` are deprecated and have no effect. If your file still has them, delete them along with their types and defaults (see `client-login.example`).++`cacheBackend` options:++* `CacheBackendFilesystem`: stores and serves files from `cachePath`, evicting least recently served files to stay under the H@H disk limit.+* `CacheBackendSQLite`: stores files in an SQLite database at `cachePath`, with no eviction. Checks every file at startup unless `--skip-startup-verify` is passed.+* `CacheBackendR2`: serves hits via presigned redirects, with no eviction. Requires `r2Config = Some { r2Endpoint = "https://<account id>.r2.cloudflarestorage.com", r2Bucket = "<bucket>" }`, `R2_ACCESS_KEY` and `R2_SECRET_KEY` in the environment, and a store returning `ETag`, `Content-Length`, and `Last-Modified` (missing `ETag` fails cache writes).+ ## Usage -Run the client:+Start the client with `hs-hath` (or `stack exec hs-hath` when built with Stack). Run `hs-hath --help` for all CLI options. -```sh-stack exec hs-hath-```+On Windows, stop the client with Ctrl+C so it notifies the server; closing the console window terminates it immediately. -The configuration is read from `./client-login`; `-c FILE` names another file. `stack exec hs-hath -- --help` lists the other options.+With `docker run`, pass `-p <port>:<port>`, `--stop-timeout 45` (graceful shutdown takes up to 30s), and `-u <uid>:<gid>` matching the host files (default uid is `65532`). -Prometheus metrics are served at `/metrics`, and the settings the server assigned at `/admin/settings`, once `HATH_METRICS_TOKEN` is set in the environment (any long random string, for example from `openssl rand -hex 32`). A request must send it as `Authorization: Bearer <token>`; in Prometheus:+## Metrics +Set `HATH_METRICS_TOKEN` (e.g. `openssl rand -hex 32`) to enable `/metrics` and `/admin/settings` with `Authorization: Bearer <token>`. Both endpoints return 404 when unset.+ ```yaml scrape_configs: - job_name: hath@@ -61,17 +66,18 @@ - targets: ["<host>:<port>"] ``` -Without the variable both paths answer 404, like any path the official client does not have.+## Proxies and tunnels -## Notes & Caveats+Behind a reverse proxy on a loopback or private address, pass `--trust-proxy-headers` so flood control reads client IPs from `X-Forwarded-For`. The connection limit does not apply behind a local proxy. -* **Memory usage**: Not optimized yet — expect ~200 MiB RAM on average.-* **S3 / Cloudflare R2**: The object store must return `ETag`, `Content-Length`, and `Last-Modified` headers; missing `ETag` will fail cache writes.-* **Reverse proxy**: Run with `--trust-proxy-headers`, which takes the reader's address from `X-Forwarded-For` when the proxy is on a loopback or private address. Flood control then counts readers, and server commands (`/servercmd/`) are taken from the RPC servers' addresses only. The connection limit sees only the peer's address and never refuses a local one, so it does not apply to a proxy on a local address.-* **Tunnels** (rathole, frp, a plain port forward that rewrites the source): hs-hath sees every connection come from a local address and cannot tell readers apart, so neither flood control nor the connection limit applies; limit connections where the tunnel meets the internet. A server command from a local address is accepted on its key alone.-* **Start-up**: If the server refuses `client_start` because another client is connected or the client id is in use, hs-hath exits. After any other failure (for example `FAIL_CONNECT_TEST`) it stays up without announcing itself, as the official client does, so that the port can be tested; restart it once the cause is fixed. A certificate with less than 24 h left is refused at start.-* **Galleries** are saved as `<downloadDir>/<title> [<gid>]`, or `[<gid>-<xres>x]` for a resized one, and `galleryinfo.txt` is written once all of a gallery's files are there.+With tunnels that rewrite the source IP (rathole, frp, port forwarding), every connection arrives from a local address, so flood control and connection limits do not apply and `/servercmd/` is authenticated by key alone. Rate-limit at the tunnel ingress. +## Startup and exit conditions++* Run it under a supervisor that restarts it: it exits on a failed login and with status 1 on a lost session.+* Refuses to start with an empty `Filesystem` or `SQLite` cache while more than 20 static ranges are assigned, or on `Filesystem` if the disk cannot hold the cache size set on the H@H settings page.+* On a failed connection test, it stays running without announcing itself so the port can be tested.+ ## License -Distributed under the GPL-3.0 License. See [`LICENSE`](LICENSE).+GPL-3.0. See [`LICENSE`](LICENSE).
app/Main.hs view
@@ -1,3 +1,5 @@+{-# LANGUAGE CPP #-}+ module Main ( main ) where import Database.SQLite.Simple ( withConnection )@@ -5,7 +7,12 @@ import Hath.CLI ( Options(..), applyOptionsToConfig, parseOptions ) import Hath.Cache.SQLite ( VerificationStats(..), initializeDB, verifyAllFiles ) import Hath.Config ( CacheBackend(..), ClientConfig(..), readClientConfig )-import Hath.RPC ( clientLogin, getCertificate, runRPCIO, serverStat )+import Hath.RPC ( clientLogin+ , getCertificate+ , loginFailure+ , runRPCIO+ , serverStat+ ) import Hath.Server ( ServerAction(GracefulShutdown) , ServerOptions(..) , needsRenewal@@ -15,9 +22,13 @@ import Relude +#if defined(mingw32_HOST_OS)+import GHC.ConsoleHandler ( Handler(Catch), installHandler )+#else import System.Posix ( Handler(Catch), installHandler, sigINT, sigTERM )+#endif -import UnliftIO ( newTChanIO, writeTChan )+import UnliftIO ( TChan, newTChanIO, readTChan, timeout, writeTChan ) main :: IO () main = do@@ -31,21 +42,22 @@ when (cacheBackend config == CacheBackendSQLite) $ prepareSQLiteCache options config actions <- newTChanIO- forM_ [ sigINT, sigTERM ] $ \signal- -> installHandler signal (Catch $ atomically $ writeTChan actions GracefulShutdown) Nothing+ onStop $ atomically $ writeTChan actions GracefulShutdown - runRPCIO config serverStat >>= either (`giveUp` "RPC is not available, exiting...") pure- settings <- runRPCIO config clientLogin >>= either (`giveUp` "Unable to login, exiting...") pure+ runRPCIO config serverStat+ >>= either (\e -> giveUp actions 5 ("RPC is not available (" <> show e <> "), exiting...")) pure+ settings <- runRPCIO config clientLogin >>= either (uncurry (giveUp actions) . loginFailure) pure certs <- runRPCIO config getCertificate- >>= either (`giveUp` "Unable to fetch certs, exiting...") pure+ >>= either (\e -> giveUp actions 5 ("Unable to fetch certs (" <> show e <> "), exiting...")) pure now <- serverNow when (needsRenewal now (fst certs)) $ do putStrLn "The certificate from the server expires within a day; try again later." exitFailure- startServer+ exitWith =<< startServer config ServerOptions { disableRateLimit = optDisableRateLimit options , trustProxyHeaders = optTrustProxyHeaders options+ , skipStartupVerify = optSkipStartupVerify options } settings certs@@ -65,8 +77,17 @@ $ putStrLn $ "WARNING: " <> show (corruptedCount stats) <> " corrupted files were found and removed." -giveUp :: Show failure => failure -> String -> IO a-giveUp failure message = do- print failure- putStrLn message+-- On Windows, GHC's RTS does not catch console window close events.+onStop :: IO () -> IO ()+#if defined(mingw32_HOST_OS)+onStop stop = void $ installHandler $ Catch $ const stop+#else+onStop stop = forM_ [ sigINT, sigTERM ] $ \signal -> installHandler signal (Catch stop) Nothing+#endif++-- | Wait before exiting so a supervisor restart does not hammer the RPC server; a stop signal cuts the wait short.+giveUp :: TChan ServerAction -> Int -> Text -> IO a+giveUp actions seconds message = do+ putTextLn message+ void $ timeout (seconds * 1000000) $ atomically $ readTChan actions exitFailure
+ cbits/available.c view
@@ -0,0 +1,23 @@+#include <stdint.h>++#ifdef _WIN32+#include <windows.h>++int64_t hath_available_bytes(const wchar_t *path)+{+ ULARGE_INTEGER available;+ if (!GetDiskFreeSpaceExW(path, &available, NULL, NULL))+ return -1;+ return (int64_t) available.QuadPart;+}+#else+#include <sys/statvfs.h>++int64_t hath_available_bytes(const char *path)+{+ struct statvfs st;+ if (statvfs(path, &st) != 0)+ return -1;+ return (int64_t) st.f_bavail * (int64_t) st.f_frsize;+}+#endif
hs-hath.cabal view
@@ -5,7 +5,7 @@ -- see: https://github.com/sol/hpack name: hs-hath-version: 1.3.0+version: 1.4.0 synopsis: A Haskell implementation of the Hentai@Home client description: Please see the README on GitHub at <https://github.com/pe200012/hs-hath#readme> category: Web@@ -37,11 +37,13 @@ exposed-modules: Hath.AtomicFile Hath.Cache+ Hath.Cache.FileStatus Hath.Cache.Filesystem Hath.Cache.R2 Hath.Cache.SQLite Hath.CLI Hath.Config+ Hath.DiskSpace Hath.Download Hath.Error Hath.FileURI@@ -59,6 +61,7 @@ Hath.Server.Handlers Hath.Server.LegacyCiphers Hath.Server.Middleware+ Hath.Server.Range Hath.ServerTime Hath.Settings Hath.Stats@@ -76,6 +79,8 @@ LambdaCase GADTs ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wmissing-export-lists -Wmissing-home-modules -Wpartial-fields -Wredundant-constraints+ c-sources:+ cbits/available.c build-depends: base >=4.7 && <4.22 , bytestring >=0.11 && <0.13@@ -84,7 +89,9 @@ , conduit ==1.3.* , containers >=0.6 && <0.8 , crypton ==1.0.*+ , crypton-connection ==0.4.* , crypton-x509 ==1.7.*+ , data-default >=0.7 && <0.9 , dhall ==1.42.* , directory ==1.3.* , filepath >=1.4 && <1.6@@ -109,12 +116,14 @@ , time >=1.12 && <1.15 , tls >=2.0 && <2.4 , tls-session-manager >=0.0.5 && <0.1- , unix ==2.8.* , unliftio ==0.2.* , wai ==3.2.* , wai-extra ==3.1.* , warp ==3.4.* default-language: GHC2021+ if !os(windows)+ build-depends:+ unix ==2.8.* library hs-hath-cryptostore exposed-modules:@@ -190,12 +199,14 @@ , time >=1.12 && <1.15 , tls >=2.0 && <2.4 , tls-session-manager >=0.0.5 && <0.1- , unix ==2.8.* , unliftio ==0.2.* , wai ==3.2.* , wai-extra ==3.1.* , warp ==3.4.* default-language: GHC2021+ if !os(windows)+ build-depends:+ unix ==2.8.* library hs-hath-minio exposed-modules:@@ -288,7 +299,6 @@ , tls >=2.0 && <2.4 , tls-session-manager >=0.0.5 && <0.1 , transformers ==0.*- , unix ==2.8.* , unliftio ==0.* , unliftio-core ==0.* , unordered-containers ==0.*@@ -302,6 +312,9 @@ , relude (Relude as Prelude) , relude default-language: GHC2021+ if !os(windows)+ build-depends:+ unix ==2.8.* library hs-hath-warp-tls exposed-modules:@@ -349,12 +362,14 @@ , time >=1.12 && <1.15 , tls >=2.1.3 && <2.6 , tls-session-manager >=0.0.4 && <1- , unix ==2.8.* , unliftio ==0.2.* , wai ==3.2.* , wai-extra ==3.1.* , warp >=3.3.29 && <3.6 default-language: GHC2021+ if !os(windows)+ build-depends:+ unix ==2.8.* executable hath-bench main-is: Bench.hs@@ -398,12 +413,14 @@ , time >=1.12 && <1.15 , tls >=2.0 && <2.4 , tls-session-manager >=0.0.5 && <0.1- , unix ==2.8.* , unliftio ==0.2.* , wai ==3.2.* , wai-extra ==3.1.* , warp ==3.4.* default-language: GHC2021+ if !os(windows)+ build-depends:+ unix ==2.8.* executable hs-hath main-is: Main.hs@@ -412,7 +429,6 @@ default-extensions: NoImplicitPrelude OverloadedStrings- QuasiQuotes LambdaCase GADTs ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wmissing-export-lists -Wmissing-home-modules -Wpartial-fields -Wredundant-constraints -threaded -rtsopts -with-rtsopts=-N -fpedantic-bottoms@@ -446,12 +462,14 @@ , time >=1.12 && <1.15 , tls >=2.0 && <2.4 , tls-session-manager >=0.0.5 && <0.1- , unix ==2.8.* , unliftio ==0.2.* , wai ==3.2.* , wai-extra ==3.1.* , warp ==3.4.* default-language: GHC2021+ if !os(windows)+ build-depends:+ unix ==2.8.* executable migrate-to-r2 main-is: Migrate.hs@@ -495,12 +513,14 @@ , time >=1.12 && <1.15 , tls >=2.0 && <2.4 , tls-session-manager >=0.0.5 && <0.1- , unix ==2.8.* , unliftio ==0.2.* , wai ==3.2.* , wai-extra ==3.1.* , warp ==3.4.* default-language: GHC2021+ if !os(windows)+ build-depends:+ unix ==2.8.* test-suite hs-hath-test type: exitcode-stdio-1.0@@ -517,6 +537,7 @@ MockRPC ProtocolSpec R2Spec+ RangeSpec RPCSpec SQLiteSpec Paths_hs_hath@@ -565,9 +586,11 @@ , time >=1.12 && <1.15 , tls >=2.0 && <2.4 , tls-session-manager >=0.0.5 && <0.1- , unix ==2.8.* , unliftio ==0.2.* , wai ==3.2.* , wai-extra ==3.1.* , warp ==3.4.* default-language: GHC2021+ if !os(windows)+ build-depends:+ unix ==2.8.*
src/Hath/Cache.hs view
@@ -1,8 +1,7 @@ {-# LANGUAGE DataKinds #-} {-# LANGUAGE TemplateHaskell #-} --- | The file cache as the rest of the client sees it. The backends--- ("Hath.Cache.Filesystem", "Hath.Cache.R2", "Hath.Cache.SQLite") interpret it.+-- | Cache effect interpreted by Filesystem, R2, and SQLite backends. module Hath.Cache ( Cache(..) , CacheHit(..)@@ -28,9 +27,8 @@ data Cache m a where LookupFile :: FileURI -> Cache m (Maybe CacheHit)- -- | Keep a file whose content has already been verified against its id. StoreFile :: FileURI -> ByteString -> Cache m ()- -- | Delete a file the network has blacklisted. A file we do not have is no error.+ -- | Deleting a missing file is a no-op. DeleteFile :: FileURI -> Cache m () makeSem ''Cache
+ src/Hath/Cache/FileStatus.hs view
@@ -0,0 +1,48 @@+{-# LANGUAGE CPP #-}++-- | Cross-platform file status and mtime helpers (without following symlinks).+module Hath.Cache.FileStatus ( regularFile, touch ) where++import Relude++#if defined(mingw32_HOST_OS)+import Data.Time.Clock ( getCurrentTime )+import Data.Time.Clock.POSIX ( utcTimeToPOSIXSeconds )++import System.Directory ( doesFileExist+ , getFileSize+ , getModificationTime+ , pathIsSymbolicLink+ , setModificationTime+ )+#else+import Foreign.C.Types ( CTime(..) )++import qualified System.Posix.Files as Posix+#endif++-- | @(sizeBytes, mtimeUnix)@ for a regular file, or 'Nothing' for symlinks and other types. Throws if missing.+regularFile :: FilePath -> IO (Maybe ( Int64, Int64 ))++touch :: FilePath -> IO ()++#if defined(mingw32_HOST_OS)+regularFile path = do+ link <- pathIsSymbolicLink path+ file <- doesFileExist path+ if link || not file+ then pure Nothing+ else do+ size <- getFileSize path+ mtime <- getModificationTime path+ pure $ Just ( fromIntegral size, floor (utcTimeToPOSIXSeconds mtime) )++touch path = getCurrentTime >>= setModificationTime path+#else+regularFile path = Posix.getSymbolicLinkStatus path <&> \st -> do+ guard (Posix.isRegularFile st)+ let CTime mtime = Posix.modificationTime st+ pure ( fromIntegral (Posix.fileSize st), mtime )++touch = Posix.touchFile+#endif
src/Hath/Cache/Filesystem.hs view
@@ -1,48 +1,169 @@ {-# LANGUAGE DataKinds #-} --- | The Filesystem backend: files on disk as @root\/xxxx\/fileid@. Hits are served--- straight from the file ('LocalFile'); the file's mtime is the LRU clock, and--- 'runEvictor' keeps the cache under the disk limit the server assigns.-module Hath.Cache.Filesystem ( FsCache, newFsCache, runCacheFilesystem, runEvictor, sweep ) where+-- | The Filesystem backend: files on disk as @root\/xxxx\/fileid@, a directory per+-- static range. Hits are served straight from the file ('LocalFile'); the file's+-- mtime is the LRU clock, and 'runEvictor' keeps the cache under the disk limit+-- the server assigns.+module Hath.Cache.Filesystem+ ( FsCache+ , openFsCache+ , cachedFiles+ , cachedBytes+ , saveState+ , runCacheFilesystem+ , runEvictor+ , evict+ ) where import Colog ( Message ) import Colog.Polysemy ( Log ) import Control.Concurrent ( threadDelay ) +import Crypto.Hash ( SHA1, hashlazy )++import Data.ByteArray.Encoding ( Base(Base16), convertToBase ) import qualified Data.ByteString.Char8 as BS+import qualified Data.Map.Strict as Map+import qualified Data.Set as Set import Data.String.Interpolate ( i )--import Foreign.C.Types ( CTime(..) )+import qualified Data.Text as T+import Data.Time.Clock.POSIX ( getPOSIXTime ) import Hath.AtomicFile ( writeFileAtomic ) import Hath.Cache ( Cache(..), CacheHit(..) )+import Hath.Cache.FileStatus ( regularFile, touch )+import Hath.DiskSpace ( availableBytes ) import Hath.Error ( HathError(..) )-import Hath.FileURI ( FileURI(..), renderFileURIBytes )-import Hath.Log ( logError )+import Hath.FileURI ( FileURI(..), parseFileURI, renderFileURIBytes )+import Hath.Log ( logError, logWarning ) import Polysemy import Polysemy.Error ( Error, throw ) import Relude -import System.Directory ( createDirectoryIfMissing, listDirectory, removeFile )-import System.FilePath ( (</>), takeFileName )-import qualified System.Posix.Files as Posix+import System.Directory ( createDirectoryIfMissing+ , doesDirectoryExist+ , listDirectory+ , removeFile+ )+import System.FilePath ( (</>), takeDirectory, takeFileName ) import UnliftIO.Exception ( tryAny ) data FsCache- = FsCache { fsRoot :: !FilePath- , fsUsed :: !(IORef Int64)- -- ^ bytes on disk as of the last sweep, plus writes and deletes since+ = FsCache { fsRoot :: !FilePath+ , fsReserve :: !(IO Int64)+ -- ^ minimum free bytes to keep on disk+ , fsRanges :: !(IORef (Map Text Range))+ -- ^ by directory; one that holds nothing has no entry } -newFsCache :: FilePath -> IO FsCache-newFsCache root = do+data Range = Range { rangeBytes :: !Int64, rangeFiles :: !Int, rangeOldest :: !Int64 }+ deriving ( Eq, Show )++-- | Open the cache at @root@ with what the last shutdown saved of it, or else+-- scan it (official CacheHandler.java:83-160); @rescan@ ignores what was saved,+-- and @verify@ also checks every file's SHA-1, deleting those that fail.+openFsCache :: FilePath -> IO Int64 -> Bool -> Bool -> IO FsCache+openFsCache root reserve rescan verify = do createDirectoryIfMissing True root- FsCache root <$> newIORef 0+ saved <- if rescan || verify+ then pure Nothing+ else loadState root+ -- from now on the file would be out of date, and a crash must not leave it behind+ void $ tryAny $ removeFile (statePath root)+ ranges <- case saved of+ Just ranges -> ranges <$ putStrLn [i|Cache: #{describe ranges}, as saved at the last shutdown|]+ Nothing -> do+ putStrLn $ if verify+ then "Verifying the cache..."+ else "Scanning the cache..."+ ( ranges, corrupt ) <- scan root verify+ putStrLn [i|Cache: #{describe ranges}|]+ when (corrupt > 0) $ putStrLn [i|Deleted #{corrupt} files that failed their SHA-1 check|]+ pure ranges+ FsCache root reserve <$> newIORef ranges+ where+ describe ranges+ = [i|#{sum (rangeFiles <$> ranges)} files, #{sum (rangeBytes <$> ranges) `div` mib} MiB|]+ :: Text +cachedFiles :: FsCache -> IO Int+cachedFiles fs = sum . fmap rangeFiles <$> readIORef (fsRanges fs)++cachedBytes :: FsCache -> IO Int64+cachedBytes fs = sum . fmap rangeBytes <$> readIORef (fsRanges fs)++statePath :: FilePath -> FilePath+statePath root = root </> "hs-hath.state"++stateHeader :: Text+stateHeader = "hs-hath cache state 1"++saveState :: FsCache -> IO ()+saveState fs = do+ ranges <- readIORef (fsRanges fs)+ -- an empty state file would skip the scan even if the cache files return+ unless (null ranges) $ writeFileAtomic (statePath (fsRoot fs)) $ encodeUtf8 $ unlines $ stateHeader+ : [ unwords [ dir, show bytes, show files, show oldest ]+ | ( dir, Range bytes files oldest ) <- Map.toList ranges+ ]++loadState :: FilePath -> IO (Maybe (Map Text Range))+loadState root = tryAny (decodeUtf8 <$> readFileBS (statePath root)) >>= \case+ Right content+ | header : rows <- lines content, header == stateHeader, Just ranges <- traverse row rows -> do+ present <- allM (doesDirectoryExist . (root </>) . toString . fst) ranges+ pure $ Map.fromList ranges <$ guard present+ _ -> pure Nothing+ where+ row line = case words line of+ [ dir, bytes, files, oldest ]+ | T.length dir == 4 -> (,) dir+ <$> (Range <$> readMaybe (toString bytes) <*> readMaybe (toString files)+ <*> readMaybe (toString oldest))+ _ -> Nothing++scan :: FilePath -> Bool -> IO ( Map Text Range, Int )+scan root verify = do+ dirs <- filter ((== 4) . length) <$> listDirectory root+ foldlM visit ( mempty, 0 ) dirs+ where+ visit ( ranges, corrupt ) dir = do+ files <- listRange root (toText dir)+ kept <- if verify+ then filterM intact files+ else pure files+ let range = Range (sum [ size | ( _, size, _ ) <- kept ]) (length kept)+ (foldl' min maxBound [ mtime | ( mtime, _, _ ) <- kept ]) <$ guard (not (null kept))+ pure ( maybe ranges (\r -> Map.insert (toText dir) r ranges) range+ , corrupt + length files - length kept+ )++ intact ( _, _, path ) = case parseFileURI (BS.pack (takeFileName path)) of+ Nothing -> pure True+ Just uri -> tryAny (sha1File path) >>= \case+ Right hash+ | hash /= fileHash uri -> False <$ tryAny (removeFile path)+ _ -> pure True++-- | (mtime, size, path) of our files in one directory: those named for it.+listRange :: FilePath -> Text -> IO [ ( Int64, Int64, FilePath ) ]+listRange root dir = do+ names <- fromRight [] <$> tryAny (listDirectory (root </> toString dir))+ fmap catMaybes $ forM (filter (toString dir `isPrefixOf`) names) $ \name -> do+ let path = root </> toString dir </> name+ tryAny (regularFile path) <&> \case+ Right (Just ( size, mtime )) -> Just ( mtime, size, path )+ _ -> Nothing++sha1File :: FilePath -> IO ByteString+sha1File path = do+ content <- readFileLBS path+ pure $! convertToBase Base16 (hashlazy @SHA1 content)+ fileURIToPath :: FilePath -> FileURI -> FilePath fileURIToPath root uri = root </> take 4 fileId </> fileId where@@ -50,107 +171,155 @@ -- ('Hath.FileURI.parseFileURI' admits nothing else), so Char8 reads it exactly. fileId = takeFileName (BS.unpack (renderFileURIBytes uri)) -addUsed :: FsCache -> Int64 -> IO ()-addUsed fs n = atomicModifyIORef' (fsUsed fs) $ \used -> ( used + n, () )+rangeOf :: FilePath -> Text+rangeOf = toText . takeFileName . takeDirectory +added :: FsCache -> FilePath -> Int64 -> Int64 -> IO ()+added fs path size mtime = atomicModifyIORef'_ (fsRanges fs)+ $ Map.insertWith grow (rangeOf path) (Range size 1 mtime)+ where+ grow _ r = Range (rangeBytes r + size) (rangeFiles r + 1) (min mtime (rangeOldest r))++removeCached :: FsCache -> FilePath -> Int64 -> IO (Either SomeException ())+removeCached fs path size = do+ removed <- tryAny (removeFile path)+ whenRight_ removed $ \() -> atomicModifyIORef'_ (fsRanges fs) $ Map.update shrink (rangeOf path)+ pure removed+ where+ shrink r+ | rangeFiles r <= 1 = Nothing+ | otherwise = Just r { rangeBytes = rangeBytes r - size, rangeFiles = rangeFiles r - 1 }++-- | A file served before this long ago gets its SHA-1 checked before it is+-- served again (official CacheHandler.java:417, a week).+checkAfterSeconds :: Int64+checkAfterSeconds = 7 * 86400+ runCacheFilesystem :: Members '[ Embed IO, Log Message, Error HathError ] r => FsCache -> Sem (Cache : r) a -> Sem r a runCacheFilesystem fs = interpret $ \case- LookupFile uri -> embed $ do+ LookupFile uri -> do let path = fileURIToPath (fsRoot fs) uri- tryAny (Posix.getSymbolicLinkStatus path) >>= \case- Right st- | Posix.isRegularFile st && fromIntegral (Posix.fileSize st) == fileSize uri -> do- -- a hit makes the file the newest, so eviction takes it last- void $ tryAny $ Posix.touchFile path- pure $ Just $ LocalFile path- | Posix.isRegularFile st -> do+ embed (tryAny (regularFile path)) >>= \case+ Right (Just ( size, mtime ))+ | size /= fromIntegral (fileSize uri) -> do -- truncated (written in place by an older version): drop it so it gets refetched- void $ removeCached fs path st+ void $ embed $ removeCached fs path size pure Nothing- _ -> pure Nothing+ | otherwise -> do+ now <- embed unixTime+ intact <- if mtime < now - checkAfterSeconds+ then embed $ either (const True) (== fileHash uri) <$> tryAny (sha1File path)+ else pure True+ if intact+ then do+ -- a hit makes the file the newest, so eviction takes it last+ void $ embed $ tryAny $ touch path+ pure $ Just $ LocalFile path+ else do+ logWarning [i|#{uri} failed its SHA-1 check; deleted from the cache|]+ void $ embed $ removeCached fs path size+ pure Nothing+ _ -> pure Nothing StoreFile uri bytes -> do let path = fileURIToPath (fsRoot fs) uri- embed (tryAny (writeFileAtomic path bytes)) >>= \case- Left err -> do- logError [i|Filesystem write failed for #{path}: #{err}|]- throw $ StorageError (show err)- Right () -> embed $ addUsed fs (fromIntegral $ BS.length bytes)+ size = fromIntegral (BS.length bytes)+ reserve <- embed $ fsReserve fs+ available <- embed $ availableBytes (fsRoot fs)+ if maybe False (< reserve + size) available+ then logWarning [i|Not caching #{uri}: less than #{reserve `div` mib} MiB would be left on the disk|]+ else do+ replaced <- embed $ tryAny (regularFile path)+ embed (tryAny (writeFileAtomic path bytes)) >>= \case+ Left err -> do+ logError [i|Filesystem write failed for #{path}: #{err}|]+ throw $ StorageError (show err)+ Right () -> embed $ do+ whenJust (join (rightToMaybe replaced)) $ \( old, _ ) -> removeCachedCount fs path old+ added fs path size =<< unixTime DeleteFile uri -> do let path = fileURIToPath (fsRoot fs) uri- embed (tryAny (Posix.getSymbolicLinkStatus path)) >>= \case- Left _ -> pass- Right st -> embed (removeCached fs path st) >>= \case+ embed (tryAny (regularFile path)) >>= \case+ Right (Just ( size, _ )) -> embed (removeCached fs path size) >>= \case Left err -> throw $ StorageError [i|Could not delete #{path}: #{err}|] Right () -> pass+ _ -> pass -removeCached :: FsCache -> FilePath -> Posix.FileStatus -> IO (Either SomeException ())-removeCached fs path st = do- removed <- tryAny (removeFile path)- whenRight_ removed $ \() -> addUsed fs (negate $ fromIntegral $ Posix.fileSize st)- pure removed+removeCachedCount :: FsCache -> FilePath -> Int64 -> IO ()+removeCachedCount fs path size = atomicModifyIORef'_ (fsRanges fs) $ Map.adjust shrink (rangeOf path)+ where+ shrink r = r { rangeBytes = rangeBytes r - size, rangeFiles = rangeFiles r - 1 } -- | Evict this far below the limit, so eviction does not run on every write: -- 100 MiB like the official client, less for tiny limits. wantFree :: Int64 -> Int64-wantFree limit = min (100 * 1024 * 1024) (limit `div` 10)+wantFree limit = min (100 * mib) (limit `div` 10) --- | Keep the cache under the disk limit (0 = no limit yet), forever. The first--- sweep learns how much is already on disk; after that we only rescan when over.+-- | Keep the cache under the disk limit (0 = no limit yet), forever. runEvictor :: FsCache -> IO Int64 -> IO Void-runEvictor fs getLimit- = attempt >> infinitely (do- threadDelay (10 * 1000000)- limit <- getLimit- used <- readIORef (fsUsed fs)- when (limit > 0 && used > limit) attempt)- where- attempt = tryAny (getLimit >>= sweep fs) >>= \case- Left err -> putStrLn [i|Cache eviction failed: #{err}|]- Right ( 0, _ ) -> pass- Right ( n, bytes ) -> putStrLn- [i|Evicted #{n} least recently served files (#{bytes `div` 1048576} MiB) to stay under the disk limit|]+runEvictor fs getLimit = infinitely $ do+ limit <- getLimit+ used <- cachedBytes fs+ when (limit > 0 && used > limit) $ tryAny (evict fs (used - limit + wantFree limit)) >>= \case+ Left err -> putStrLn [i|Cache eviction failed: #{err}|]+ Right ( 0, _ ) -> pass+ Right ( n, bytes ) -> putStrLn+ [i|Evicted #{n} least recently served files (#{bytes `div` mib} MiB) to stay under the disk limit|]+ threadDelay (10 * 1000000) --- | Rescan the cache; if it is over the limit, delete the least recently served--- files until it is 'wantFree' under. Returns the files and bytes evicted.--- ponytail: a full scan per sweep, fine for ~10^5 files; keep an index if caches grow far past that-sweep :: FsCache -> Int64 -> IO ( Int, Int64 )-sweep fs limit = do- before <- readIORef (fsUsed fs)- files <- scanCache (fsRoot fs)- let total = sum [ size | ( _, size, _ ) <- files ]- victims- | limit > 0 && total > limit- = takeBytes (total - limit + wantFree limit) (sortOn fst3 files)- | otherwise = []- freed <- fmap catMaybes $ forM victims $ \( _, size, rel ) -> rightToMaybe . (size <$)- <$> tryAny (removeFile (fsRoot fs </> decodeUtf8 (fromShort rel)))- -- keep what was written meanwhile- atomicModifyIORef' (fsUsed fs) $ \used -> ( used - before + total - sum freed, () )- pure ( length freed, sum freed )+-- | Delete at least @want@ bytes (or until empty) starting from the directory with+-- the oldest file, taking files within 'slack' of its oldest mtime+-- (official CacheHandler.checkAndPruneCache).+evict :: FsCache -> Int64 -> IO ( Int, Int64 )+evict fs want = go 0 0 where- fst3 ( t, _, _ ) = t+ go n freed+ | freed >= want = pure ( n, freed )+ | otherwise = readIORef (fsRanges fs) >>= \ranges -> case oldestRange ranges of+ Nothing -> pure ( n, freed )+ Just ( dir, oldest ) -> do+ now <- unixTime+ files <- sortOn fst3 <$> listRange (fsRoot fs) dir+ let cutoff = oldest + slack (now - oldest)+ victims = takeBytes (want - freed) (takeWhile ((< cutoff) . fst3) files)+ gone <- fmap catMaybes $ forM victims $ \( _, size, path ) -> rightToMaybe+ . (( path, size ) <$) <$> removeCached fs path size+ let deleted = Set.fromList (map fst gone)+ atomicModifyIORef'_ (fsRanges fs) $ case filter ((`Set.notMember` deleted) . thd3) files of+ [] -> Map.delete dir+ ( t, _, _ ) : _ -> Map.adjust (\r -> r { rangeOldest = t }) dir+ go (n + length gone) (freed + sum (map snd gone)) - takeBytes n (x@( _, size, _ ) : xs)- | n > 0 = x : takeBytes (n - size) xs+ oldestRange = Map.foldlWithKey' older Nothing++ older found dir r = case found of+ Just ( _, t )+ | t <= rangeOldest r -> found+ _ -> Just ( dir, rangeOldest r )++ -- official CacheHandler.java:579-594+ slack age+ | age > 180 * day = 30 * day+ | age > 90 * day = 7 * day+ | age > 30 * day = 3 * day+ | otherwise = day++ day = 86400++ takeBytes k (x@( _, size, _ ) : xs)+ | k > 0 = x : takeBytes (k - size) xs takeBytes _ _ = [] --- | (mtime, size, path relative to root) of our files: root/xxxx/xxxx….-scanCache :: FilePath -> IO [ ( Int64, Int64, ShortByteString ) ]-scanCache root = do- dirs <- filter ((== 4) . length) <$> listDirectory root- fmap concat $ forM dirs $ \dir -> do- names <- fromRight [] <$> tryAny (listDirectory (root </> dir))- fmap catMaybes $ forM (filter (dir `isPrefixOf`) names) $ \name -> do- let rel = dir </> name- tryAny (Posix.getSymbolicLinkStatus (root </> rel)) <&> \case- Right st- | Posix.isRegularFile st -> let- CTime mtime = Posix.modificationTime st- in - Just ( mtime, fromIntegral (Posix.fileSize st), toShort (encodeUtf8 rel) )- _ -> Nothing+ fst3 ( a, _, _ ) = a++ thd3 ( _, _, c ) = c++unixTime :: IO Int64+unixTime = floor <$> getPOSIXTime++mib :: Int64+mib = 1048576
src/Hath/Cache/R2.hs view
@@ -1,7 +1,6 @@ {-# LANGUAGE DataKinds #-} --- | The R2 backend (any S3-compatible store): hits are answered with a redirect--- to a presigned link, so the reader fetches the file from the bucket itself.+-- | S3-compatible / R2 cache backend; hits redirect to presigned URLs. module Hath.Cache.R2 ( R2Connection(..) , mkR2Connection@@ -57,8 +56,7 @@ -- ^ Presigned links and when we stop handing them out (monotonic seconds). } --- | Connect with the endpoint and bucket from the config and the credentials--- from @R2_ACCESS_KEY@ and @R2_SECRET_KEY@.+-- | Connect using @R2_ACCESS_KEY@ and @R2_SECRET_KEY@ from the environment. mkR2Connection :: R2Config -> IO (Either Text R2Connection) mkR2Connection cfg = do accessKeyMay <- lookupEnv "R2_ACCESS_KEY"@@ -73,7 +71,6 @@ , cvSecretKey = SecretKey $ BA.convert (encodeUtf8 @String @ByteString secretKey) , cvSessionToken = Nothing }- -- the IsString instance parses the endpoint URL baseConnInfo = fromString $ toString $ r2Endpoint cfg manager <- newManager tlsManagerSettings minioConn <- Minio.mkMinioConn (setCreds creds $ setRegion "auto" baseConnInfo) manager@@ -122,7 +119,6 @@ Just ( expiry, link ) | now < expiry -> pure $ Just $ Redirect link _ -> do- -- ask the bucket whether it has the object before sending anyone there found <- embed $ minio $ headObject bucket objectKey [] case found of Right _ -> fmap Redirect <$> embed (rememberLink uri now)@@ -147,10 +143,9 @@ minio :: Minio.Minio a -> IO (Either Text a) minio = runR2 conn - -- Sign a link (local, no request) and reuse it for 10 min.+ -- Valid 20m, cached 10m (minimum 10m remaining when served). rememberLink :: FileURI -> Double -> IO (Maybe ByteString) rememberLink uri now- -- valid 20 min, handed out for 10, so every link given lasts at least 10 min = minio (presignedGetObjectUrl bucket (fileURIToKey uri) 1200 [] []) >>= \case Left _ -> pure Nothing Right link -> do
src/Hath/Cache/SQLite.hs view
@@ -5,6 +5,7 @@ module Hath.Cache.SQLite ( initializeDB , runCacheSQLite+ , isEmpty , VerificationStats(..) , verifyAllFiles ) where@@ -52,6 +53,9 @@ DeleteFile uri -> embed $ execute conn "DELETE FROM files WHERE file_id = ?" (Only (renderFileURIText uri))++isEmpty :: Connection -> IO Bool+isEmpty conn = null @[] @(Only Int) <$> query_ conn "SELECT 1 FROM files LIMIT 1" data VerificationStats = VerificationStats { verifiedCount :: !Int
src/Hath/Config.hs view
@@ -8,32 +8,37 @@ , readClientConfig ) where -import Dhall ( FromDhall, ToDhall, auto, input )+import qualified Data.Text as T+import Data.Text.IO ( hPutStrLn ) +import Dhall ( FromDhall, ToDhall, auto, input, inputExpr )+import Dhall.Core ( Expr(RecordLit) )+import qualified Dhall.Map as Dhall+ import Relude --- | The field names are the keys of the Dhall record, and the record must match--- exactly, so removing or renaming a field breaks every existing config file.--- That is why the fields nothing reads are still here.+-- | Dhall record schema: deprecate a field in 'readClientConfig' before removing or renaming it. data ClientConfig = ClientConfig { clientId :: !Text , key :: !Text- -- ^ The client key: it signs our requests and proves the server's replies. , version :: !Text- -- ^ Not read; the build we announce is 'Hath.Protocol.clientBuild'. , proxy :: !(Maybe ClientProxy)- -- ^ Not read; no request goes through a proxy. , downloadDir :: !Text , cachePath :: !Text- -- ^ A directory (Filesystem) or a database file (SQLite); R2 has no use for it.+ -- ^ Directory (Filesystem) or database file (SQLite); unused by R2. , cacheBackend :: !CacheBackend , r2Config :: !(Maybe R2Config) , lruCacheSize :: !Int64- -- ^ Not read. } deriving ( Show, Generic ) +{-# DEPRECATED version "Unused: hs-hath announces Hath.Protocol.clientBuild. To be removed." #-}++{-# DEPRECATED proxy, ClientProxy "Unused: the image proxy comes from the H@H settings page. To be removed." #-}++{-# DEPRECATED lruCacheSize "Unused: there is no in-memory file cache. To be removed." #-}+ instance FromDhall ClientConfig instance ToDhall ClientConfig@@ -52,8 +57,7 @@ instance ToDhall CacheBackend --- | Where the bucket is. Its credentials come from the environment--- (@R2_ACCESS_KEY@, @R2_SECRET_KEY@), not from the config file.+-- | Bucket location; credentials come from @R2_ACCESS_KEY@ and @R2_SECRET_KEY@. data R2Config = R2Config { r2Endpoint :: !Text, r2Bucket :: !Text } deriving ( Show, Generic ) @@ -75,6 +79,25 @@ , lruCacheSize = 100 * 1024 * 1024 } --- | Evaluate a Dhall expression, usually a path such as @./client-login@.+-- | Fields a @client-login@ may leave out, with the value they then take.+deprecatedFields :: [ ( Text, Text ) ]+deprecatedFields+ = [ ( "version", "\"\"" )+ , ( "proxy", "None { host : Text, port : Integer, auth : Optional { _1 : Text, _2 : Text } }" )+ , ( "lruCacheSize", "+104857600" )+ ]++-- | Fills in the deprecated fields left out; warns on stderr about those present. readClientConfig :: Text -> IO ClientConfig-readClientConfig = input auto+readClientConfig source = do+ present <- inputExpr source <&> \case+ RecordLit fields -> filter (`Dhall.member` fields) (map fst deprecatedFields)+ _ -> []+ unless (null present)+ $ hPutStrLn stderr+ $ "Warning: client-login fields with no effect, to be removed in a later release: "+ <> T.intercalate ", " present+ <> ". Delete them, with their types and defaults (see client-login.example)."+ input auto $ case [ name <> " = " <> value | ( name, value ) <- deprecatedFields, name `notElem` present ] of+ [] -> source+ missing -> "(" <> source <> ") // { " <> T.intercalate ", " missing <> " }"
+ src/Hath/DiskSpace.hs view
@@ -0,0 +1,12 @@+-- | Free space on the disk that holds a path.+module Hath.DiskSpace ( availableBytes ) where++import Relude++import System.Posix.Internals ( CFilePath, withFilePath )++foreign import ccall safe "hath_available_bytes" available :: CFilePath -> IO Int64++-- | Bytes we may still write there; Nothing if the system will not say.+availableBytes :: FilePath -> IO (Maybe Int64)+availableBytes path = withFilePath path available <&> \n -> n <$ guard (n >= 0)
src/Hath/Download.hs view
@@ -1,32 +1,61 @@--- | Downloads from other servers: reading a reply's body with a limit on the--- wait for every read, and whole downloads as the official FileDownloader makes--- them (proxy tests, gallery files).-module Hath.Download ( fetchFile, receive ) where+-- | HTTP downloads matching official FileDownloader (proxy tests, gallery files).+module Hath.Download ( fetchFile, receive, via ) where import qualified Data.ByteString.Char8 as BS+import Data.Default ( def ) import qualified Data.List as List import Data.String.Interpolate ( i ) import Hath.Protocol ( outgoingHeaders ) import Hath.RPC ( connectMicros, httpManager, worthRetrying )+import Hath.Settings ( ImageProxy(..) ) +import Network.Connection ( ProxySettings(SockSettingsSimple) ) import qualified Network.HTTP.Client as HC+import Network.HTTP.Client.Internal ( throwHttp )+import Network.HTTP.Client.TLS ( mkManagerSettings ) import Network.HTTP.Types ( hContentLength, statusCode ) import Relude +import System.IO.Unsafe ( unsafePerformIO )+ import UnliftIO ( timeout, tryAny ) --- | Download as the official FileDownloader does (FileDownloader.java:147-299):--- up to three attempts, one right after another, each with 5 s to connect and--- 10 s for the reply's headers and for every read. An attempt succeeds if its--- reply has a status below 400 and announces its length, at most--- @max_allowed_filesize@, and that many bytes arrive. @keep@ gets them chunk by--- chunk with the offset of each, so a new attempt starts again at 0. A 404 or--- 410 is not tried again. Right is the length, Left why the last attempt failed.-fetchFile :: Int -> HC.Request -> (Int -> ByteString -> IO ()) -> IO (Either Text Int)-fetchFile maxAllowedFileSize request keep = go (3 :: Int)+via :: Maybe ImageProxy -> HC.Request -> IO ( HC.Manager, HC.Request )+via proxy request = case proxy of+ Nothing -> pure ( httpManager, request )+ Just (HTTPProxy host port) -> pure ( httpManager, request { HC.proxy = Just (HC.Proxy host port) } )+ Just (SOCKSProxy host port) -> (, request) <$> socksManager host port++-- | One manager for the SOCKS proxy last asked for; the settings can name another.+socksManager :: String -> Int -> IO HC.Manager+socksManager host port = readIORef socksManagers >>= \case+ Just ( for, manager )+ | for == ( host, port ) -> pure manager+ _ -> do+ let settings+ = mkManagerSettings def (Just (SockSettingsSimple host (fromIntegral port)))+ manager <- HC.newManager settings+ { HC.managerRawConnection = within5s <$> HC.managerRawConnection settings+ , HC.managerTlsConnection = within5s <$> HC.managerTlsConnection settings+ }+ manager <$ writeIORef socksManagers (Just ( ( host, port ), manager )) where+ within5s connect address host' port'+ = timeout connectMicros (connect address host' port') >>= maybe (throwHttp HC.ConnectionTimeout) pure++socksManagers :: IORef (Maybe ( ( String, Int ), HC.Manager ))+socksManagers = unsafePerformIO (newIORef Nothing)++{-# NOINLINE socksManagers #-}++-- | Download matching FileDownloader.java:147-299: up to 3 attempts (5s connect,+-- 10s headers/read), enforcing @max_allowed_filesize@ and skipping retries on 404/410.+fetchFile+ :: Int -> Maybe ImageProxy -> HC.Request -> (Int -> ByteString -> IO ()) -> IO (Either Text Int)+fetchFile maxAllowedFileSize proxy request keep = go (3 :: Int)+ where go attemptsLeft = attempt >>= \case Left ( status, why ) | attemptsLeft > 1, worthRetrying status -> go (attemptsLeft - 1)@@ -34,9 +63,9 @@ Right size -> pure (Right size) -- the length, or else the status that failed it (none if something else did) and why- attempt- = either (\e -> Left ( Nothing, describe e )) id- <$> tryAny (HC.withResponse sent httpManager answer)+ attempt = do+ ( manager, req ) <- via proxy sent+ either (\e -> Left ( Nothing, describe e )) id <$> tryAny (HC.withResponse req manager answer) answer response = case ( statusCode (HC.responseStatus response), announced ) of ( status, _ )@@ -59,10 +88,7 @@ readMicros = 10 * 1000000 --- | Read a body of @size@ bytes, handing each chunk to @keep@ with the offset it--- starts at, and waiting up to @readMicros@ for every read. Left says why it--- broke off: upstream failed or sent too little or too much, or a read waited--- too long.+-- | Read exactly @size@ bytes with per-read timeout @readMicros@, passing @(offset, chunk)@ to @keep@. receive :: Int -> Int -> HC.BodyReader -> (Int -> ByteString -> IO ()) -> IO (Either Text ()) receive readMicros size body keep = either (Left . describe) id <$> tryAny (go 0) where@@ -78,7 +104,6 @@ | BS.length chunk > size - received -> pure $ Left [i|it sent more than #{size} bytes|] | otherwise -> keep received chunk >> go (received + BS.length chunk) --- | Why a download failed, in http-client's words where it has them. describe :: SomeException -> Text describe e = case fromException e of Just (HC.HttpExceptionRequest _ content) -> show content
src/Hath/Error.hs view
@@ -4,12 +4,10 @@ data HathError = TransportError !Text- -- ^ The HTTP exchange with the RPC server failed, every time it was tried. | EmptyResponse | RequestFailure !Text- -- ^ The RPC server answered with this status instead of @OK@.+ -- ^ Non-@OK@ status returned by the RPC server. | CertificateFailure !Text- -- ^ The PKCS#12 file from @get_cert@ could not be read. | StorageError !Text deriving ( Show, Eq )
src/Hath/FileURI.hs view
@@ -20,16 +20,14 @@ data FileURI = FileURI { fileHash :: !ByteString- -- ^ SHA-1 of the content, in hex , fileSize :: !Int , fileXRes :: !Int- -- ^ 0, as is 'fileYRes', for an id without a resolution+ -- ^ 0 (with 'fileYRes') when the file has no resolution. , fileYRes :: !Int , fileExt :: !ByteString } deriving ( Eq, Ord ) --- | Shows the file id itself, which is what logs want. instance Show FileURI where show = toString . renderFileURIText
src/Hath/Gallery/Downloader.hs view
@@ -15,6 +15,7 @@ import Hath.AtomicFile ( writeFileAtomic ) import Hath.Config ( ClientConfig(..) )+import Hath.DiskSpace ( availableBytes ) import Hath.Download ( fetchFile ) import Hath.Error ( HathError ) import Hath.Gallery ( GalleryFile(..)@@ -30,7 +31,7 @@ , reportDownloadFailures , runRPCIO )-import Hath.Settings ( HathSettings(..) )+import Hath.Settings ( HathSettings(..), ImageProxy, imageProxy ) import Hath.Stats ( StatsEnv, addDlBytes, incDlFile, incDlTask ) import qualified Network.HTTP.Client as HC@@ -80,7 +81,7 @@ Nothing -> logWarning [i|Unexpected download location for gallery #{galleryID gallery}; the gallery downloader stops|] Just directory -> do- downloadGallery (maxAllowedFileSize current) directory gallery+ downloadGallery current directory gallery go (Just gallery) -- | Make the gallery's directory and give its path. If the file system will@@ -107,13 +108,13 @@ -- | Download a gallery's files, write its @galleryinfo.txt@ if all of them came -- (GalleryDownloader.java:132-150), and report the sources that failed. downloadGallery :: Members '[ RPC, Reader StatsEnv, Log Message, Error HathError, Embed IO ] r- => Int+ => HathSettings -> FilePath -> GalleryMetadata -> Sem r ()-downloadGallery maxSize directory gallery = do+downloadGallery settings directory gallery = do logInfo [i|Starting download of gallery: #{galleryTitle gallery}|]- ( complete, failures ) <- downloadFiles maxSize directory gallery+ ( complete, failures ) <- downloadFiles settings directory gallery if complete then do logInfo [i|Finished download of gallery: #{galleryTitle gallery}|]@@ -132,11 +133,11 @@ -- True if all of them are there in the end; and the sources that failed, as -- @host-fileindex-xres@. downloadFiles :: Members '[ RPC, Reader StatsEnv, Log Message, Error HathError, Embed IO ] r- => Int+ => HathSettings -> FilePath -> GalleryMetadata -> Sem r ( Bool, [ Text ] )-downloadFiles maxSize directory gallery = go 0 0 [] [ ( file, 1 ) | file <- files ]+downloadFiles settings directory gallery = go 0 0 [] [ ( file, 1 ) | file <- files ] where files = galleryFileList gallery @@ -145,12 +146,15 @@ | null missing = pure ( True, failures ) | not (anotherRound (length files) rounds failed) = pure ( False, failures ) | otherwise = do- outcomes <- mapM (uncurry (ensureFile maxSize directory gallery)) missing+ outcomes <- mapM (uncurry (ensureFile settings directory gallery)) missing let stillMissing- = [ ( file, attempt + 1 ) | ( ( file, attempt ), Failed _ ) <- zip missing outcomes ]+ = [ ( file, if outcome == Postponed then attempt else attempt + 1 )+ | ( ( file, attempt ), outcome ) <- zip missing outcomes+ , outcome `notElem` [ Present, Downloaded ]+ ] go (rounds + 1)- (failed + length stillMissing)+ (failed + length [ () | Failed _ <- outcomes ]) (failures <> [ source | Failed (Just source) <- outcomes ]) stillMissing @@ -163,29 +167,46 @@ = Present -- ^ it was there already, intact | Downloaded+ | Postponed+ -- ^ not tried, for want of disk space | Failed !(Maybe Text)--- ^ with the source that failed, if the server named one+ -- ^ with the source that failed, if the server named one+ deriving ( Eq ) -- | Get one file into the directory unless it is there already, intact -- (GalleryDownloader.java:392-474): ask the server where to download it from, -- this being attempt @attempt@ at it, and check what comes. The official--- client then waits 1 s after a download, 5 s after a failure.+-- client then waits 1 s after a download, 5 s after a failure; it waits 5+-- minutes instead while the disk has less than @diskremaining_bytes@ and 1000+-- MiB free (GalleryDownloader.java:86-90, 128-130). Retries go through the+-- image proxy, if one is set. ensureFile :: Members '[ RPC, Reader StatsEnv, Log Message, Error HathError, Embed IO ] r- => Int+ => HathSettings -> FilePath -> GalleryMetadata -> GalleryFile -> Int -> Sem r Outcome-ensureFile maxSize directory gallery file attempt = embed (intactAt path file) >>= \case+ensureFile settings directory gallery file attempt = embed (intactAt path file) >>= \case True -> pure Present False -> do- outcome <- download+ free <- embed $ availableBytes directory+ outcome <- if maybe False (< diskRemainingBytes settings + 1000 * 1048576) free+ then Postponed <$ logWarning+ "Gallery download suspended; there is less than the minimum allowed space left on the disk"+ else download embed $ threadDelay $ case outcome of Downloaded -> 1000000+ Postponed -> 300000000 _ -> 5000000 pure outcome where+ maxSize = maxAllowedFileSize settings++ proxy+ | attempt > 1 = imageProxy settings+ | otherwise = Nothing+ name = BS.unpack (galleryFileName file) <.> BS.unpack (galleryFileExt file) path = directory </> name@@ -197,7 +218,7 @@ Nothing -> do logWarning [i|No source to download #{name} from|] pure (Failed Nothing)- Just request -> embed (fetchBytes maxSize request) >>= \case+ Just request -> embed (fetchBytes maxSize proxy request) >>= \case Right bytes | hasExpectedHash file bytes -> do embed $ writeFileAtomic path bytes@@ -225,11 +246,11 @@ hasExpectedHash :: GalleryFile -> ByteString -> Bool hasExpectedHash file content = maybe True (== sha1Hex content) (galleryFileHash file) -fetchBytes :: Int -> HC.Request -> IO (Either Text ByteString)-fetchBytes maxSize request = do+fetchBytes :: Int -> Maybe ImageProxy -> HC.Request -> IO (Either Text ByteString)+fetchBytes maxSize proxy request = do chunks <- newIORef [] -- a chunk at offset 0 begins another attempt, so what came before is dropped let keep 0 chunk = writeIORef chunks [ chunk ] keep _ chunk = modifyIORef' chunks (chunk :)- fetched <- fetchFile maxSize request keep+ fetched <- fetchFile maxSize proxy request keep forM fetched $ \_ -> BS.concat . reverse <$> readIORef chunks
src/Hath/Locate.hs view
@@ -7,12 +7,13 @@ import Colog.Polysemy ( Log ) import Control.Concurrent ( forkIOWithUnmask )-import Control.Exception ( finally, mask_, onException )+import Control.Exception ( finally, mask, mask_, onException ) import qualified Data.ByteString.Char8 as BS import Data.ByteString.Internal ( fromForeignPtr, fromForeignPtr0, mallocByteString ) import Data.ByteString.Unsafe ( unsafeUseAsCStringLen ) import qualified Data.List as List+import qualified Data.Map.Strict as Map import Data.String.Interpolate ( i ) import Foreign.ForeignPtr ( ForeignPtr, withForeignPtr )@@ -21,12 +22,13 @@ import Hath.Cache ( Cache, CacheHit, lookupFile, storeFile ) import Hath.Config ( ClientConfig )-import Hath.Download ( receive )+import Hath.Download ( receive, via ) import Hath.Error ( HathError )-import Hath.FileURI ( FileURI(..) )+import Hath.FileURI ( FileURI(..), renderFileURIBytes ) import Hath.Log ( logInfo, logWarning ) import Hath.Protocol ( hathRequestToken, outgoingHeaders, sha1Hex )-import Hath.RPC ( RPC, connectMicros, fileSources, httpManager )+import Hath.RPC ( RPC, connectMicros, fileSources )+import Hath.Settings ( HathSettings(maxAllowedFileSize), imageProxy ) import Hath.Stats ( StatsEnv, addDownload, incFetched ) import qualified Network.HTTP.Client as HC@@ -57,16 +59,13 @@ -- | A cache miss, coming in from upstream on a thread of its own, which -- caches the file once it is complete. Call it with a chunk writer to -- relay the file as it arrives; it throws if the download breaks off.- | Streamed !((ByteString -> IO ()) -> IO ())+ | Streamed !Relay --- | Look in the cache; on a miss, ask the RPC server where the file is, by the--- @fileindex@ and @xres@ of the request and the file id as the reader asked for--- it, and start fetching it. Left is the status the reader gets when that--- fails (see 'openUpstream'), or 503 while the downloads under way hold all--- they may ('bufferBudget').------ Like the official client, we serve any file the server sends readers here--- for; static ranges only matter for pruning the cache.+type Relay = (ByteString -> IO ()) -> IO ()++-- | Cache lookup with upstream fetch fallback (serves any file routed here;+-- static ranges only affect cache pruning). A file already coming in for+-- another request is relayed from that download. Returns 503 if 'bufferBudget' is full. locateResource :: Members '[ Cache@@ -79,66 +78,94 @@ , Final IO ] r- => Int+ => HathSettings -> ByteString -> FileURI -> ( ByteString, ByteString ) -> Sem r (Either Status Located)-locateResource maxAllowedFileSize fileId uri ( fileIndex, xres ) = lookupFile uri >>= \case+locateResource settings fileId uri ( fileIndex, xres ) = lookupFile uri >>= \case Just hit -> pure $ Right $ Stored hit Nothing -> do- logInfo [i|Fetching resource: #{uri}|]- openUpstream maxAllowedFileSize fileId uri fileIndex xres >>= \case- Left status -> do- logWarning [i|Could not fetch #{uri}: #{statusCode status}|]- pure (Left status)- Right response -> do- -- runs on the download's thread, after the handler has returned- finish <- deferToIO $ \case- Left why -> logWarning [i|Fetching #{uri} failed: #{why}|]- Right content -> do- addDownload (BS.length content)- -- a failed cache write only costs us the next hit- catch @HathError (storeFile uri content)- $ \e -> logWarning [i|Cache write failed for #{uri}: #{e}|]- embed (download uri response finish) >>= \case- Just relay -> Right (Streamed relay) <$ incFetched- Nothing -> do- logWarning- [i|Not fetching #{uri}: the downloads under way hold #{bufferBudget `div` 1048576} MiB already|]- pure (Left status503)+ cfg <- ask @ClientConfig+ sources <- lowerToIO $ fileSources fileIndex xres fileId `catch` \(e :: HathError)+ -> [] <$ logWarning [i|srfetch failed for #{uri}: #{e}|]+ begin <- lowerToIO $ logInfo [i|Fetching resource: #{uri}|]+ fetched <- lowerToIO incFetched+ warn <- deferToIO logWarning+ -- runs on the download's thread, after the handler has returned+ finish <- deferToIO $ \case+ Left why -> logWarning [i|Fetching #{uri} failed: #{why}|]+ Right content -> do+ addDownload (BS.length content)+ -- a failed cache write only costs us the next hit+ catch @HathError (storeFile uri content)+ $ \e -> logWarning [i|Cache write failed for #{uri}: #{e}|]+ embed $ fmap Streamed <$> shared (renderFileURIBytes uri) (\landed -> do+ void begin+ urls <- filter (not . BS.null) . fromMaybe [] <$> sources+ openUpstream cfg settings fileId uri urls >>= \case+ Left status -> Left status <$ warn [i|Could not fetch #{uri}: #{statusCode status}|]+ Right response -> download uri response finish landed >>= \case+ Just relay -> Right relay <$ fetched+ Nothing -> Left status503+ <$ warn+ [i|Not fetching #{uri}: the downloads under way hold #{bufferBudget `div` 1048576} MiB already|]) --- | Open the first source that answers with the file, as the official--- ProxyFileDownloader does; the caller reads the body and must close the--- response. Without sources the reader gets a 404. If no source will do, a 502--- once one of them has answered, or a 500 if none could be reached: the--- official client changes its status only for a source it connected to--- (ProxyFileDownloader.java:71-111).-openUpstream :: Members '[ RPC, Reader ClientConfig, Log Message, Error HathError, Embed IO ] r- => Int+-- | Misses under way, by file id, each with what its first request found.+inFlight :: TVar (Map ByteString (TMVar (Either Status Relay)))+inFlight = unsafePerformIO (newTVarIO mempty)++{-# NOINLINE inFlight #-}++-- | Fetch a file with @lead@, unless another request is fetching it already: then+-- take what that one gets. @lead@ is given what its download must call when it is+-- over, which lets the next miss of the file fetch it again.+shared :: ByteString -> (IO () -> IO (Either Status Relay)) -> IO (Either Status Relay)+shared key lead = mask $ \restore -> join $ atomically $ do+ flights <- readTVar inFlight+ case Map.lookup key flights of+ Just flight -> pure $ restore $ atomically $ readTMVar flight+ Nothing -> do+ flight <- newEmptyTMVar+ writeTVar inFlight (Map.insert key flight flights)+ let forget = modifyTVar' inFlight (Map.update (\f -> f <$ guard (f /= flight)) key)+ settle result = atomically $ do+ void $ tryPutTMVar flight result+ when (isLeft result) forget+ pure $ do+ result <- restore (lead (atomically forget)) `onException` settle (Left status500)+ result <$ settle result++-- | Open the first valid upstream source (ProxyFileDownloader.java:71-111), through+-- the image proxy if one is set. Caller must close the response. Returns 404 if+-- no sources, 502 if one answered, 500 otherwise.+openUpstream :: ClientConfig+ -> HathSettings -> ByteString -> FileURI- -> ByteString- -> ByteString- -> Sem r (Either Status (HC.Response HC.BodyReader))-openUpstream maxAllowedFileSize fileId uri fileIndex xres = do- urls <- filter (not . BS.null) <$> fileSources fileIndex xres fileId `catch` \(e :: HathError)- -> [] <$ logWarning [i|srfetch failed for #{uri}: #{e}|]- cfg <- ask @ClientConfig- let request url = do- req <- HC.parseRequest (BS.unpack url)- pure- req { HC.requestHeaders- = outgoingHeaders [ ( "Hath-Request", hathRequestToken cfg fileId ) ]- -- 5 s to connect, then 30 s for the headers (ProxyFileDownloader.java:86-87)- , HC.responseTimeout = HC.responseTimeoutMicro (connectMicros + seconds 30)- }- open url = case request url of- Nothing -> pure Unreachable- Just req -> try @IO @HC.HttpException (HC.responseOpen req httpManager) >>= \case+ -> [ ByteString ]+ -> IO (Either Status (HC.Response HC.BodyReader))+openUpstream cfg settings fileId uri urls+ | null urls = pure (Left status404)+ | otherwise = firstOpened status500 urls+ where+ request url = do+ req <- HC.parseRequest (BS.unpack url)+ pure+ req { HC.requestHeaders+ = outgoingHeaders [ ( "Hath-Request", hathRequestToken cfg fileId ) ]+ -- 5 s to connect, then 30 s for the headers (ProxyFileDownloader.java:86-87)+ , HC.responseTimeout = HC.responseTimeoutMicro (connectMicros + seconds 30)+ }++ open url = case request url of+ Nothing -> pure Unreachable+ Just req -> do+ ( manager, sent ) <- via (imageProxy settings) req+ try @IO @HC.HttpException (HC.responseOpen sent manager) >>= \case Right response | usableReply- maxAllowedFileSize+ (maxAllowedFileSize settings) uri (statusCode (HC.responseStatus response)) (HC.responseHeaders response) -> pure (Opened response)@@ -146,16 +173,14 @@ Left (HC.HttpExceptionRequest _ HC.ConnectionTimeout) -> pure Unreachable Left (HC.HttpExceptionRequest _ (HC.ConnectionFailure _)) -> pure Unreachable Left _ -> pure Answered- firstOpened failure = \case- [] -> pure (Left failure)- url : rest -> open url >>= \case- Opened response -> pure (Right response)- Answered -> firstOpened status502 rest- Unreachable -> firstOpened failure rest- if null urls- then pure (Left status404)- else embed (firstOpened status500 urls) + firstOpened failure = \case+ [] -> pure (Left failure)+ url : rest -> open url >>= \case+ Opened response -> pure (Right response)+ Answered -> firstOpened status502 rest+ Unreachable -> firstOpened failure rest+ data Attempt = Opened !(HC.Response HC.BodyReader) | Answered@@ -171,17 +196,15 @@ where announced = readMaybe . BS.unpack =<< List.lookup hContentLength headers --- | Fetch a body on a thread of its own, into a buffer of the file's size. The--- reader relays from the buffer, and the buffer, once verified, is what the--- cache keeps, so the file is in memory once. A reader that goes away leaves--- the download running, as the official ProxyFileDownloader's thread does.--- @finish@ gets the verified file, or why there is none. Nothing, with the--- response closed, if the buffer would not fit the 'bufferBudget'.+-- | Fetch into a shared buffer on a background thread (survives reader disconnect,+-- matching ProxyFileDownloader), calling @landed@ when it is over. Returns+-- 'Nothing' if 'bufferBudget' is exceeded. download :: FileURI -> HC.Response HC.BodyReader -> (Either Text ByteString -> IO ())- -> IO (Maybe ((ByteString -> IO ()) -> IO ()))-download uri response finish = mask_ $ reserve size >>= \case+ -> IO ()+ -> IO (Maybe Relay)+download uri response finish landed = mask_ $ reserve size >>= \case False -> Nothing <$ HC.responseClose response -- what is reserved must be released whatever happens, or the budget shrinks for good True -> flip onException (release size >> HC.responseClose response) $ do@@ -190,7 +213,7 @@ let keep offset chunk = do copyInto buffer offset chunk atomically $ writeTVar progress (Receiving (offset + BS.length chunk))- void $ forkIOWithUnmask $ \unmask -> flip finally (release size) $ unmask $ do+ void $ forkIOWithUnmask $ \unmask -> flip finally (release size >> landed) $ unmask $ do -- 30 s for every read and 300 s for the whole (ProxyFileDownloader.java:186-200) received <- fromMaybe (Left "it took over 300 s") <$> timeout (seconds 300) (receive (seconds 30) size (HC.responseBody response) keep)@@ -223,16 +246,12 @@ data Progress = Receiving !Int | Received | Broken --- | What the downloads under way may hold between them. A file being fetched--- is in memory until it is cached, and every request for it meanwhile fetches--- it again, so without a limit one valid link, asked for often enough, takes--- all the memory there is.+-- | Cap total in-flight miss buffers to prevent memory exhaustion on hot misses. -- ponytail: a fixed 512 MiB; make it an option if a node has less to spare bufferBudget :: Int bufferBudget = 512 * 1024 * 1024 --- | Whether a download of @size@ bytes may start while those under way hold--- @taken@. A file larger than the budget is fetched when nothing else is.+-- | A single file larger than 'bufferBudget' is still allowed when nothing else is in flight. withinBudget :: Int -> Int -> Bool withinBudget taken size = taken == 0 || taken + size <= bufferBudget @@ -257,10 +276,11 @@ copyInto buffer offset chunk = unsafeUseAsCStringLen chunk $ \( source, len ) -> withForeignPtr buffer $ \start -> copyBytes (start `plusPtr` offset) (castPtr source) len --- | In microseconds. seconds :: Int -> Int seconds = (* 1000000) --- | Lower a Sem action into IO so it can run after the request handler has returned. deferToIO :: Member (Final IO) r => (x -> Sem r ()) -> Sem r (x -> IO ()) deferToIO k = withWeavingToFinal $ \s lower _ -> pure ((\x -> void (lower (k x <$ s))) <$ s)++lowerToIO :: Member (Final IO) r => Sem r a -> Sem r (IO (Maybe a))+lowerToIO action = withWeavingToFinal $ \s lower ins -> pure ((ins <$> lower (action <$ s)) <$ s)
src/Hath/Protocol.hs view
@@ -64,7 +64,6 @@ outgoingHeaders :: [ Header ] -> [ Header ] outgoingHeaders headers = headers <> [ userAgent, ( "Accept-Encoding", "" ) ] --- | SHA-1 in lower-case hex, the form every H\@H signature and file id uses. sha1Hex :: ByteString -> ByteString sha1Hex = convertToBase Base16 . Crypto.hash @ByteString @SHA1 @@ -74,7 +73,6 @@ signature :: [ ByteString ] -> ByteString signature = sha1Hex . BS.intercalate "-" --- | @actkey@ of an RPC request, for its @act@, @add@ and @acttime@. rpcActionKey :: ClientConfig -> Text -> Text -> Int64 -> Text rpcActionKey cfg act add time = decodeUtf8@@ -109,7 +107,6 @@ where escape = BS.intercalate ";" . map (urlEncode True) . BS.split ';' --- | The key the RPC server puts on a @servercmd@ request. Only it knows our key. serverCommandKey :: ClientConfig -> Text -> Text -> Int -> Text serverCommandKey cfg command additional time = decodeUtf8@@ -122,7 +119,6 @@ , encodeUtf8 (key cfg) ] --- | @testkey@ of a @\/t\/@ speed test of the given size and time. speedTestKey :: ClientConfig -> Int -> Int64 -> ByteString speedTestKey cfg size time = signature@@ -133,13 +129,10 @@ , encodeUtf8 (key cfg) ] --- | The second half of the keystamp that lets a reader fetch a file id at a given time. keystampHash :: ClientConfig -> Int64 -> ByteString -> ByteString keystampHash cfg time fileId = BS.take 10 $ signature [ show time, fileId, encodeUtf8 (key cfg), "hotlinkthis" ] --- | The @Hath-Request@ header that authenticates us to an image server, for a--- file id as the reader asked for it. hathRequestToken :: ClientConfig -> ByteString -> ByteString hathRequestToken cfg fileId = encodeUtf8 (clientId cfg) <> "-" <> sha1Hex (encodeUtf8 (key cfg) <> fileId)@@ -154,9 +147,7 @@ && sameSecret (BS.map toLower hash) (keystampHash cfg (fromIntegral issued) fileId) _ -> False --- | Whether a key or signature we were sent is the one we computed. The--- comparison takes as long wherever the two first differ, so the time a--- refusal takes does not tell a forger how much of a guess was right.+-- | Constant-time equality for keys and signatures. sameSecret :: ByteString -> ByteString -> Bool sameSecret = constEq
src/Hath/RPC.hs view
@@ -12,11 +12,13 @@ , connectMicros , serverStat , clientLogin+ , loginFailure , clientStart , StartFailure(..) , startFailure , clientStop , stillAlive+ , Stop(..) , toldToStop , overload , clientSettings@@ -27,6 +29,10 @@ , galleryFileSource , reportDownloadFailures , failureReport+ , RPCServers(..)+ , pickRPCServer+ , failedRPCServer+ , forgetRPCServerFailure ) where import Colog ( Message, richMessageAction )@@ -34,6 +40,8 @@ import Control.Exception ( try ) +import Crypto.Number.Generate ( generateBetween )+ import Crypto.Store.PKCS12 ( readP12FileFromMemory , recover , recoverAuthenticated@@ -62,8 +70,9 @@ , rpcQuery , verifyRPCResponse )+import Hath.Server.FloodControl ( parseIPv4 ) import Hath.ServerTime ( serverNow, setServerTime )-import Hath.Settings ( HathSettings+import Hath.Settings ( HathSettings(rpcServerIPs, rpcServerPort) , defaultHathSettings , parseSettings , settingNumber@@ -124,26 +133,76 @@ . runLogAction @IO richMessageAction . runRPC --- | The RPC server, unless @HATH_RPC_HOST@ (@host@ or @host:port@) names another;--- the tests and hath-bench point us at theirs that way.+-- | The RPC server to send a request to, unless @HATH_RPC_HOST@ (@host@ or+-- @host:port@) names another; the tests and hath-bench point us at theirs that way. rpcServer :: IO ( String, Int )-rpcServer = lookupEnv "HATH_RPC_HOST" <&> \case- Nothing -> ( "rpc.hentaiathome.net", 80 )- Just override -> case break (== ':') override of+rpcServer = lookupEnv "HATH_RPC_HOST" >>= \case+ Nothing -> do+ servers <- readIORef rpcServers+ pick <- generateBetween 0 (max 0 (fromIntegral (length (rpcKnown servers)) - 1))+ atomicModifyIORef' rpcServers $ \now -> let+ chosen = pickRPCServer (fromIntegral pick) now+ in + ( chosen, maybe ( "rpc.hentaiathome.net", 80 ) (( , rpcPort now ) . BS.unpack) (rpcCurrent chosen) )+ Just override -> pure $ case break (== ':') override of ( host, ':' : port ) -> ( host, fromMaybe 80 (readMaybe port) ) ( host, _ ) -> ( host, 80 ) +-- | The RPC servers the server assigned (@rpc_server_ip@ and @rpc_server_port@),+-- the one in use, and the one that last failed (official Settings.java:205-233, 623-682).+data RPCServers+ = RPCServers { rpcKnown :: ![ ByteString ]+ , rpcPort :: !Int+ , rpcCurrent :: !(Maybe ByteString)+ , rpcLastFailed :: !(Maybe ByteString)+ }+ deriving ( Eq, Show )++rpcServers :: IORef RPCServers+rpcServers = unsafePerformIO $ newIORef (RPCServers [] 80 Nothing Nothing)++{-# NOINLINE rpcServers #-}++useRPCServers :: HathSettings -> IO ()+useRPCServers settings = atomicModifyIORef'_ rpcServers $ \servers -> servers+ { rpcKnown = known+ , rpcPort = rpcServerPort settings+ , rpcCurrent = mfilter (`elem` known) (rpcCurrent servers)+ }+ where+ -- the addresses come as ::ffff:a.b.c.d; we connect over IPv4+ known+ = [ v4 | ip <- rpcServerIPs settings, let v4 = fromMaybe ip (BS.stripPrefix "::ffff:" ip)+ , isJust (parseIPv4 v4) ]++pickRPCServer :: Int -> RPCServers -> RPCServers+pickRPCServer n servers+ | isJust (rpcCurrent servers) = servers+ | otherwise = servers { rpcCurrent = candidates !!? (n `mod` max 1 (length candidates)) }+ where+ candidates = case filter ((/= rpcLastFailed servers) . Just) (rpcKnown servers) of+ [] -> rpcKnown servers+ others -> others++failedRPCServer :: ByteString -> RPCServers -> RPCServers+failedRPCServer host servers+ | rpcCurrent servers == Just host = servers { rpcCurrent = Nothing, rpcLastFailed = Just host }+ | otherwise = servers++-- | Let the server that failed be picked again, so that the load evens out once+-- it is back (official HentaiAtHomeClient.java:305-308, every 4 hours).+forgetRPCServerFailure :: IO ()+forgetRPCServerFailure = atomicModifyIORef'_ rpcServers $ \servers -> case rpcLastFailed servers of+ Nothing -> servers+ Just _ -> servers { rpcCurrent = Nothing, rpcLastFailed = Nothing }+ -- | How long to wait for a reply, connecting included. The official client -- waits up to an hour; a reader waiting on @srfetch@ would not. rpcTimeoutMicros :: Int rpcTimeoutMicros = 60 * 1000000 --- | The connections of every request we send: to the RPC server, for proxy--- tests, to image servers. Each gives up after 'connectMicros' if it cannot--- connect, as the official client's do (FileDownloader.java:165,--- ProxyFileDownloader.java:86). http-client has no setting for that alone (its--- response timeout counts the connection too), so every request sets its own--- response timeout.+-- | Shared HTTP manager with 'connectMicros' connect timeout (FileDownloader.java:165,+-- ProxyFileDownloader.java:86). Each request sets its own response timeout. httpManager :: HC.Manager httpManager = unsafePerformIO@@ -162,7 +221,6 @@ connectMicros :: Int connectMicros = 5 * 1000000 --- | One GET to the RPC server, signed with the client key and the server's time. request :: Members '[ Embed IO, Error HathError, Reader ClientConfig ] r => ByteString -> Text@@ -173,7 +231,7 @@ reply <- embed $ do ( host, port ) <- rpcServer time <- serverNow- exchange+ outcome <- exchange HC.defaultRequest { HC.host = BS.pack host , HC.port = port@@ -182,17 +240,17 @@ , HC.requestHeaders = outgoingHeaders [ ( "Connection", "Close" ) ] , HC.responseTimeout = HC.responseTimeoutMicro rpcTimeoutMicros }+ -- what the official client takes for no response (ServerResponse.java:60-76)+ when (either (const True) ("TEMPORARILY_UNAVAILABLE" `BS.isPrefixOf`) outcome)+ $ atomicModifyIORef'_ rpcServers (failedRPCServer (BS.pack host))+ pure outcome fromEither reply --- | The longest reply we take, as the official client reads one into memory--- (FileDownloader.java:186). The RPC server is reached over plain HTTP: who--- sits in between could otherwise send a reply without end.+-- | Cap plain-HTTP RPC replies (FileDownloader.java:186). maxReplyBytes :: Int maxReplyBytes = 10485760 --- | Send a request and read the body of its 2xx reply. Like the official--- FileDownloader, make up to three attempts, one right after another--- (FileDownloader.java:147, 280-292).+-- | Up to 3 attempts (FileDownloader.java:147, 280-292). exchange :: HC.Request -> IO (Either HathError ByteString) exchange req = go (3 :: Int) where@@ -219,9 +277,7 @@ httpError status = ( Just status, "HTTP " <> show status ) --- | Whether an attempt that failed with this HTTP status (none if the exchange--- broke off) is worth repeating. FileDownloader repeats every failure but 404--- and 410, which HttpURLConnection reports as FileNotFoundException.+-- | Retry all failures except 404/410 (matching FileDownloader). worthRetrying :: Maybe Int -> Bool worthRetrying = maybe True (`notElem` [ 404, 410 ]) @@ -255,8 +311,23 @@ clientLogin :: Members '[ RPC, Error HathError, Log Message, Embed IO ] r => Sem r HathSettings clientLogin = do logInfo "Logging in"- parseSettings defaultHathSettings <$> settingsPayload "client_login"+ settings <- parseSettings defaultHathSettings <$> settingsPayload "client_login"+ settings <$ embed (useRPCServers settings) +-- | What to say when login fails, and how many seconds to wait before exiting:+-- a supervisor that restarts us at once would have us refused for restarting+-- too often (official ServerHandler.java:244-266), and then blocked 15 minutes.+loginFailure :: HathError -> ( Int, Text )+loginFailure = \case+ RequestFailure status+ | "FAIL_STARTUP_LOOP" `T.isPrefixOf` status -> ( 900+ , "The server detected that the client is stuck in a startup loop, and has blocked it for 15 minutes. Fix whatever is preventing the client from starting; it exits in 15 minutes."+ )+ | "FAIL_UNSUPPORTED_LOCATION" `T.isPrefixOf` status -> ( 5+ , "The client appears to be located in a country that H@H does not support."+ )+ failure -> ( 5, [i|Unable to log in (#{failure}), exiting...|] )+ -- | Tell the server we are listening. It tests our port before it answers. clientStart :: Members '[ RPC, Error HathError ] r => Sem r () clientStart = void $ payload =<< callRPC "client_start" ""@@ -289,13 +360,17 @@ stillAlive :: Members '[ RPC, Error HathError ] r => Sem r () stillAlive = void $ payload =<< callRPC "still_alive" "" --- | Whether a failed still_alive means we must shut down: the server answers--- @TERM_BAD_NETWORK@ to a client it cannot reach (official CakeSphere.run). Any--- other failure waits for the next heartbeat.-toldToStop :: HathError -> Bool+data Stop = BadNetwork | NotLoggedIn+ deriving ( Eq, Show )++-- | Reason a failed 'stillAlive' requires shutdown: @TERM_BAD_NETWORK@+-- (official CakeSphere.run) or @FAIL_NOT_LOGGED_IN@ (session lost).+toldToStop :: HathError -> Maybe Stop toldToStop = \case- RequestFailure status -> "TERM_BAD_NETWORK" `T.isPrefixOf` status- _ -> False+ RequestFailure status+ | "TERM_BAD_NETWORK" `T.isPrefixOf` status -> Just BadNetwork+ | "FAIL_NOT_LOGGED_IN" `T.isPrefixOf` status -> Just NotLoggedIn+ _ -> Nothing -- | Tell the server we are close to our connection limit; it then sends us -- fewer readers for a while (official ServerHandler.notifyOverload).@@ -305,7 +380,9 @@ -- | The settings as the server has them now, applied onto the ones we hold. clientSettings :: Members '[ RPC, Error HathError, Embed IO ] r => HathSettings -> Sem r HathSettings-clientSettings current = parseSettings current <$> settingsPayload "client_settings"+clientSettings current = do+ settings <- parseSettings current <$> settingsPayload "client_settings"+ settings <$ embed (useRPCServers settings) -- | Our TLS certificate. The server sends a PKCS#12 file whose password is the client key. getCertificate :: Members '[ RPC, Error HathError, Reader ClientConfig ] r
src/Hath/Server.hs view
@@ -22,13 +22,17 @@ import Database.SQLite.Simple ( withConnection ) import Hath.Cache ( CacheRunner(..), deleteFile )-import Hath.Cache.Filesystem ( newFsCache+import Hath.Cache.Filesystem ( cachedBytes+ , cachedFiles+ , openFsCache , runCacheFilesystem , runEvictor+ , saveState ) import Hath.Cache.R2 ( mkR2Connection, runCacheR2 )-import Hath.Cache.SQLite ( initializeDB, runCacheSQLite )+import Hath.Cache.SQLite ( initializeDB, isEmpty, runCacheSQLite ) import Hath.Config ( CacheBackend(..), ClientConfig(..) )+import Hath.DiskSpace ( availableBytes ) import Hath.Error ( HathError ) import Hath.Gallery.Downloader ( runGalleryDownloader ) import Hath.Log ( logWarning )@@ -41,6 +45,8 @@ , overload , runRPCIO , startFailure+ , Stop(..)+ , forgetRPCServerFailure , stillAlive , toldToStop )@@ -84,7 +90,10 @@ import Relude +import System.Exit ( ExitCode(..) )+ import UnliftIO ( TChan+ , finally , mapConcurrently_ , race , readTChan@@ -114,16 +123,18 @@ -- ^ no flood control, for when every reader appears to come from one address , trustProxyHeaders :: !Bool -- ^ take the reader's address from @X-Forwarded-For@+ , skipStartupVerify :: !Bool+ -- ^ ignore @verify_cache@ } --- | Serve until told to shut down, then return; exit if the RPC server will not--- have us. The settings and certificate are the ones it gave us at login.+-- | Serve until told to shut down, then return how to exit; exit if the RPC+-- server will not have us. The settings and certificate are the ones it gave us at login. startServer :: ClientConfig -> ServerOptions -> HathSettings -> ( CertificateChain, PrivKey ) -> TChan ServerAction- -> IO ()+ -> IO ExitCode startServer config options settings certs actions = do settingsVar <- newTVarIO settings downloadRequest <- newEmptyMVar@@ -136,7 +147,9 @@ runGalleryDownloader config stats settingsVar downloadRequest `alongside` withCacheBackend config- (diskLimitBytes <$> readTVarIO settingsVar)+ settings+ (skipStartupVerify options)+ settingsVar (\cache -> serverLoop ServerEnv { envConfig = config , envSettings = settingsVar@@ -153,12 +166,16 @@ alongside :: IO a -> IO b -> IO b alongside background action = withAsync background (const action) --- | Open the cache the config asks for. The Filesystem backend also gets its--- evictor, which follows the disk limit the server assigns.-withCacheBackend :: ClientConfig -> IO Int64 -> (CacheRunner -> IO a) -> IO a-withCacheBackend config diskLimit use = case cacheBackend config of+-- | Open the cache the config asks for, and refuse to go on with one the+-- network would lose trust in (official CacheHandler.java:140-157). The+-- Filesystem backend also gets its evictor, which follows the disk limit the+-- server assigns, and its state saved at the end.+withCacheBackend+ :: ClientConfig -> HathSettings -> Bool -> TVar HathSettings -> (CacheRunner -> IO a) -> IO a+withCacheBackend config settings skipVerify settingsVar use = case cacheBackend config of CacheBackendSQLite -> withConnection (toString $ cachePath config) $ \conn -> do initializeDB conn+ refuseEmpty =<< isEmpty conn use CacheRunner { runCacheWith = runCacheSQLite conn } CacheBackendR2 -> case r2Config config of Nothing -> die "cacheBackend=r2 but r2Config is missing"@@ -166,16 +183,35 @@ Left err -> die $ "Failed to initialize R2: " <> toString err Right conn -> use CacheRunner { runCacheWith = runCacheR2 conn } CacheBackendFilesystem -> do- fs <- newFsCache (toString $ cachePath config)- runEvictor fs diskLimit `alongside` use CacheRunner { runCacheWith = runCacheFilesystem fs }+ let root = toString (cachePath config)+ -- what the disk must keep free (CacheHandler.hasFreeDiskSpace)+ reserve = max (100 * mib) . diskRemainingBytes <$> readTVarIO settingsVar+ fs <- openFsCache root reserve (rescanCache settings) (verifyCache settings && not skipVerify)+ flip finally (saveState fs) $ do+ refuseEmpty . (== 0) =<< cachedFiles fs+ used <- cachedBytes fs+ available <- availableBytes root+ whenJust available $ \free -> when (free < diskLimitBytes settings - used) $ die+ [i|The storage device does not have enough space available for the set maximum cache size: #{diskLimitBytes settings `div` gib} GiB is set, and #{(free + used) `div` gib} GiB is available for the cache. Free up space for H@H, or reduce the cache size on #{settingsPage}|]+ runEvictor fs (diskLimitBytes <$> readTVarIO settingsVar)+ `alongside` use CacheRunner { runCacheWith = runCacheFilesystem fs }+ where+ refuseEmpty noFiles = when (noFiles && staticRangeCount settings > 20) $ die+ [i|This client has static ranges assigned to it, but the cache is empty. Check file permissions and file system integrity. If the cache has been deleted or is otherwise lost, reset your static ranges on #{settingsPage}|] + settingsPage = [i|https://e-hentai.org/hentaiathome.php?cid=#{clientId config}|] :: String++ mib = 1048576 :: Int64++ gib = 1024 * mib+ -- | Bind the port, announce ourselves with client_start, then serve and -- handle commands until one ends the client (official HentaiAtHomeClient.run): -- -- * 'Cert' fetches a new certificate and swaps it in for the next handshakes; -- the listener and open transfers carry on. -- * 'GracefulShutdown' ends the client as 'shutDown' says.-serverLoop :: ServerEnv -> ( CertificateChain, PrivKey ) -> IO ()+serverLoop :: ServerEnv -> ( CertificateChain, PrivKey ) -> IO ExitCode serverLoop env certs = do let config = envConfig env credentials <- newIORef certs@@ -203,9 +239,9 @@ | otherwise = commands env credentials race (waitCatch web) untilShutdown >>= \case Left outcome -> die [i|The web server stopped: #{outcome}|]- Right ()- | started -> shutDown config (join $ readMVar closeListener) (void $ waitCatch web)- | otherwise -> pass+ Right exit+ | started -> exit <$ shutDown config (join $ readMVar closeListener) (void $ waitCatch web)+ | otherwise -> pure exit where tlsSettings credentials -- asked on every handshake (SNI or not), so a swapped certificate applies at once@@ -222,9 +258,7 @@ , tlsSessionManagerConfig = Just SM.defaultConfig } --- | Warp's exception printer, minus connections that never got past TLS:--- scanners probing old protocols and cipher suites, and clients that connect--- and send nothing (thousands a day). None of them reached the application.+-- | Warp exception handler suppressing pre-app TLS handshake noise and empty disconnects. quietHandshakes :: Maybe Request -> SomeException -> IO () quietHandshakes req e | Just (HandshakeFailed _) <- fromException e = pass@@ -245,9 +279,10 @@ Refused why -> die (toString why) Unannounced why -> False <$ putStrLn (toString why) -commands :: ServerEnv -> IORef ( CertificateChain, PrivKey ) -> IO ()+commands :: ServerEnv -> IORef ( CertificateChain, PrivKey ) -> IO ExitCode commands env credentials = atomically (readTChan (envActions env)) >>= \case- GracefulShutdown -> pass+ GracefulShutdown -> pure ExitSuccess+ SessionLost -> pure (ExitFailure 1) Cert -> do renewed <- refreshCerts (envConfig env) now <- serverNow@@ -255,14 +290,13 @@ Just new@( chain, _ ) | not (needsRenewal now chain) -> writeIORef credentials new >> commands env credentials -- the official client refuses such a certificate too- | otherwise -> putStrLn "The new certificate expires within a day as well; shutting down"- Nothing -> putStrLn "Could not get a new certificate; shutting down"+ | otherwise -> ExitSuccess+ <$ putStrLn "The new certificate expires within a day as well; shutting down"+ Nothing -> ExitSuccess <$ putStrLn "Could not get a new certificate; shutting down" --- | What the official client does once client_start went through: refresh the--- settings, delete the files blacklisted in the last three days, then, at its--- intervals, send still_alive (110 s), delete what the last 12 hours--- blacklisted (6 h) and look at the certificate (5 min). What ends the client--- goes through the command channel.+-- | Post-start periodic tasks: initial settings + 3d blacklist, then+-- still_alive (110s), 12h blacklist (6h), cert expiry check (5m), and letting+-- a failed RPC server be picked again (4h). housekeeping :: ServerEnv -> IORef ( CertificateChain, PrivKey ) -> IO () housekeeping env credentials = do logFailure refreshSettings@@ -272,6 +306,7 @@ [ ( seconds 110, heartbeat ) , ( hours 6, applyBlacklist config (envCache env) 43200 ) , ( minutes 5, checkCertificate )+ , ( hours 4, forgetRPCServerFailure ) ] where config = envConfig env@@ -282,12 +317,15 @@ heartbeat = runRPCIO config stillAlive >>= \case Right () -> pass- Left failure- | toldToStop failure -> do+ Left failure -> case toldToStop failure of+ Just BadNetwork -> do putStrLn "The client is shutting down since the network is misconfigured; correct firewall/forwarding settings then restart the client." send GracefulShutdown- | otherwise -> putStrLn [i|Failed stillAlive test: #{failure}; will retry later|]+ Just NotLoggedIn -> do+ putStrLn "The server no longer knows this client's session; shutting down to log in again."+ send SessionLost+ Nothing -> putStrLn [i|Failed stillAlive test: #{failure}; will retry later|] -- the official client gives up a day before the certificate expires; we fetch another first checkCertificate = do@@ -324,10 +362,8 @@ Left failure -> [i|Failed to retrieve the file blacklist, will try again later: #{failure}|] Right count -> [i|Blacklist: #{count} files, deleted from the cache where present|] --- | End a client that client_start announced (official--- HentaiAtHomeClient.shutdown and httpServerShutdown): client_stop, so the--- network sends no one new; 5 s more of serving, for readers already on their--- way; then no new connections, and up to 25 s for open ones to finish.+-- | Graceful shutdown (HentaiAtHomeClient.shutdown / httpServerShutdown):+-- send client_stop, keep serving 5s, stop listening, drain up to 25s. shutDown :: ClientConfig -> IO () -> IO () -> IO () shutDown config closeListener drained = do runRPCIO config clientStop >>= \case
src/Hath/Server/App.hs view
@@ -27,7 +27,9 @@ = Cert -- ^ fetch a new certificate and serve it from now on | GracefulShutdown--- ^ tell the RPC server we are leaving, let open transfers finish, then return+ -- ^ tell the RPC server we are leaving, let open transfers finish, then return+ | SessionLost+-- ^ the same, then exit with a failure, so that a supervisor starts us again and we log in anew data ServerEnv = ServerEnv
src/Hath/Server/ConnectionLimit.hs view
@@ -1,6 +1,4 @@--- | The cap on open connections, and the overload notice near it, as the--- official client applies them to a connection it accepts--- (HTTPServer.java:242-255).+-- | Open connection cap and overload notifications (HTTPServer.java:242-255). module Hath.Server.ConnectionLimit ( Admission(..), admission, overloadDue, connectionLimit ) where import Control.Concurrent ( forkIO )@@ -37,10 +35,7 @@ overloadDue :: Double -> Maybe Double -> Bool overloadDue now = maybe True (< now - 30) --- | Warp's 'Network.Wai.Handler.Warp.setOnOpen' and--- 'Network.Wai.Handler.Warp.setOnClose' hooks for the limit. A refused--- connection is closed without a reply. Near the limit, the notice runs on a--- thread of its own, so that the connection does not wait for the RPC server.+-- | Warp @setOnOpen@ / @setOnClose@ hooks enforcing 'maxConnections'. connectionLimit :: TVar HathSettings -> IO () -> IO ( SockAddr -> IO Bool, SockAddr -> IO () ) connectionLimit settingsVar notifyOverload = do open <- newIORef (0 :: Int)
src/Hath/Server/Handlers.hs view
@@ -33,22 +33,29 @@ ) import Hath.Server.App ( App, ServerAction(..), ServerEnv(..), runApp ) import Hath.Server.FloodControl ( isLocalIP, isRPCServer, sockAddrIP )+import Hath.Server.Range ( fileETag, notModified, requestedPart ) import Hath.ServerTime ( serverNow )-import Hath.Settings ( HathSettings(maxAllowedFileSize, rpcServerIPs) )+import Hath.Settings ( HathSettings(maxAllowedFileSize, rpcServerIPs), imageProxy ) import Hath.Stats ( addDownload, addUpload, incServed, readMetrics ) import qualified Network.HTTP.Client as HC import Network.HTTP.Types ( Header , Status+ , hAcceptRanges , hAuthorization , hCacheControl , hContentLength+ , hContentRange+ , hContentType+ , hETag , hLocation , methodGet , methodHead , status200+ , status206 , status301 , status302+ , status304 , status400 , status403 , status404@@ -81,7 +88,7 @@ handle env req = case route (Wai.rawPathInfo req) of Favicon -> pure $ redirect status301 "https://e-hentai.org/favicon.ico" [] Robots -> pure $ bytes status200 "text/plain; charset=ISO-8859-1" "User-agent: *\nDisallow: /"- File fileId options -> resource env (Wai.requestMethod req == methodHead) fileId options+ File fileId options -> resource env req fileId options ServerCmd command additional time commandKey -> serverCommand env (Wai.remoteHost req) command additional time commandKey Test size time testKey -> speedTest size time testKey@@ -89,17 +96,14 @@ AdminSettings -> tokenHolder >> ours . show <$> embed @IO (readTVarIO (envSettings env)) Refuse status -> throw status where- -- /metrics and /admin/settings are not the official client's, and tell- -- what a reader has no business knowing (the RPC servers' addresses, for- -- one). They answer whoever sends the token; with none set, they are not there.+ -- Private endpoints; hidden (404) unless HATH_METRICS_TOKEN is set. tokenHolder = case envMetricsToken env of Nothing -> throw status404 Just token -> unless (sameSecret sent ("Bearer " <> token)) $ throw status403 sent = fromMaybe "" (List.lookup hAuthorization (Wai.requestHeaders req)) - -- what they say changes, so they do not carry the official client's year- -- of Cache-Control+ -- Strip default 1-year Cache-Control. ours = Wai.mapResponseHeaders (filter ((/= hCacheControl) . fst)) . bytes status200 "text/plain;charset=utf-8"@@ -108,39 +112,54 @@ -- | @\/h\/\<file id>\/\<options>@: a file for a reader (HTTPResponse.java:161-228). -- The options carry the keystamp the H\@H server issued for this file, which -- entitles the reader to it, and the @fileindex@ and @xres@ to fetch it by.-resource :: ServerEnv -> Bool -> ByteString -> ByteString -> App Wai.Response-resource env headOnly fileId optionsText = do+resource :: ServerEnv -> Wai.Request -> ByteString -> ByteString -> App Wai.Response+resource env req fileId optionsText = do now <- embed serverNow cfg <- ask @ClientConfig unless (keystampValid cfg now fileId (fromMaybe "" (Map.lookup "keystamp" options))) $ throw status403 ( uri, fetchBy ) <- maybe (throw status404) pure ((,) <$> parseFileURI fileId <*> fetchParams options)- let headers = responseHeaders (mimeType uri) (fileSize uri)- served response = response <$ unless headOnly (incServed >> addUpload (fileSize uri))+ let size = fileSize uri+ etag = fileETag uri+ -- the browser may keep the file for good: no other file has its id+ file = (<> [ ( hETag, etag ), ( hCacheControl, "public, max-age=31536000, immutable" ) ])+ . filter ((/= hCacheControl) . fst)+ part = requestedPart etag size (Wai.requestHeaders req)+ ( offset, len ) = fromMaybe ( 0, size ) part+ status+ | isJust part = status206+ | otherwise = status200+ headers = file (responseHeaders (mimeType uri) size)+ served sent response+ = response <$ unless (Wai.requestMethod req == methodHead) (incServed >> addUpload sent) settings <- embed @IO (readTVarIO (envSettings env))- locateResource (maxAllowedFileSize settings) fileId uri fetchBy >>= either throw pure >>= \case- Stored (Redirect url)- -> pure $ redirect status302 url [ ( "Cache-Control", "public, max-age=600" ) ]- -- Warp sets the length of a file it sends, and answers Range and If-Modified-Since- Stored (LocalFile path) -> served- $ Wai.responseFile status200 (filter ((/= hContentLength) . fst) headers) path Nothing- Stored (InMemory content) -> served $ Wai.responseLBS status200 headers (fromStrict content)- -- a cache miss: relay upstream bytes as they arrive, like the official proxy- -- mode. Warp does not run the body of a HEAD response; the file is fetched- -- all the same, as by the official client.- Streamed relay -> served $ Wai.responseStream status200 headers $ \write flush -> relay- (\chunk -> write (byteString chunk) >> flush)+ if notModified etag (Wai.requestHeaders req)+ then pure $ Wai.responseLBS status304 (file (filter ((`notElem` [ hContentType, hContentLength ]) . fst) (responseHeaders "" 0))) ""+ else locateResource settings fileId uri fetchBy >>= either throw pure >>= \case+ Stored (Redirect url)+ -> pure $ redirect status302 url [ ( "Cache-Control", "public, max-age=600" ) ]+ -- Warp sets the length, and the Content-Range of a part+ Stored (LocalFile path) -> served len+ $ Wai.responseFile status (filter ((/= hContentLength) . fst) headers) path+ $ Just+ $ Wai.FilePart (toInteger offset) (toInteger len) (toInteger size)+ Stored (InMemory content) -> served len+ $ Wai.responseLBS status (ranged headers) (fromStrict (BS.take len (BS.drop offset content)))+ where+ ranged+ = ([ ( hContentRange, [i|bytes #{offset}-#{offset + len - 1}/#{size}|] ) | isJust part ] <>)+ . (( hAcceptRanges, "bytes" ) :)+ . map (\h@( name, _ ) -> if name == hContentLength then ( name, show len ) else h)+ -- a cache miss: stream the whole file as it arrives, like the official proxy+ -- mode. Warp skips the body on HEAD, but the file is still fetched.+ Streamed relay -> served size $ Wai.responseStream status200 headers $ \write flush -> relay+ (\chunk -> write (byteString chunk) >> flush) where options = parseURLParams optionsText --- | @\/servercmd\/\<command>\/\<additional>\/\<time>\/\<key>@: a command from the--- RPC server (HTTPResponse.java:230-260). Its key proves the sender: only the--- RPC server knows ours. Like the official client, we also want it to come--- from one of the RPC servers' addresses, as flood control sees the peer. But--- behind a tunnel, or a proxy that does not pass addresses on, every peer is a--- local one and the RPC server would never get through, so a local peer's--- command is judged by its key alone.+-- | @\/servercmd\/\<command>\/\<additional>\/\<time>\/\<key>@ (HTTPResponse.java:230-260).+-- Requires an RPC server IP, or a local peer (tunnels/proxies) authenticated by key alone. serverCommand :: ServerEnv -> SockAddr -> Text -> Text -> Int -> Text -> App Wai.Response serverCommand env peer command additional time commandKey = do settings <- embed @IO (readTVarIO (envSettings env))@@ -241,7 +260,7 @@ results <- embed $ replicateConcurrently (proxyTestCount test)- (timedDownload (maxAllowedFileSize settings) (proxyTestSize test) request)+ (timedDownload settings (proxyTestSize test) request) let succeeded = catMaybes results addUpload (proxyTestCount test * fromIntegral (proxyTestSize test)) pure [i|OK:#{length succeeded}-#{sum succeeded}|]@@ -256,10 +275,12 @@ -- FileDownloader times it (FileDownloader.java:130-315): the first byte is the -- first any of its attempts received. It counts if a body of the announced -- length arrived, at least the test size (HTTPResponse.java:112).-timedDownload :: Int -> Int64 -> HC.Request -> IO (Maybe Int64)-timedDownload maxSize testSize request = do+timedDownload :: HathSettings -> Int64 -> HC.Request -> IO (Maybe Int64)+timedDownload settings testSize request = do firstByte <- newIORef Nothing- fetched <- timeout testTimeoutMicros $ fetchFile maxSize request $ \_ _+ fetched <- timeout testTimeoutMicros+ $ fetchFile (maxAllowedFileSize settings) (imageProxy settings) request+ $ \_ _ -> whenNothingM_ (readIORef firstByte) (writeIORef firstByte . Just =<< getMonotonicTime) end <- getMonotonicTime start <- readIORef firstByte
+ src/Hath/Server/Range.hs view
@@ -0,0 +1,52 @@+-- | Conditional and partial requests for a file, which never changes: its id+-- names its content.+module Hath.Server.Range ( fileETag, notModified, requestedPart ) where++import qualified Data.ByteString.Char8 as BS+import qualified Data.List as List++import Hath.FileURI ( FileURI(..) )++import Network.HTTP.Types ( ByteRange(..)+ , RequestHeaders+ , hIfNoneMatch+ , hIfRange+ , hRange+ , parseByteRanges+ )++import Relude++fileETag :: FileURI -> ByteString+fileETag uri = "\"" <> fileHash uri <> "\""++-- | Weak ETag comparison per RFC 9110 13.1.2 (matches @*@ or @W/@-prefixed tags).+notModified :: ByteString -> RequestHeaders -> Bool+notModified etag headers+ = any (any matches . BS.split ',') [ v | ( n, v ) <- headers, n == hIfNoneMatch ]+ where+ matches tag = case BS.strip tag of+ "*" -> True+ t -> fromMaybe t (BS.stripPrefix "W/" t) == etag++-- | Single byte range as @(offset, length)@, or 'Nothing' to send the whole file+-- (full-file, multi-range, unsatisfiable, or mismatched @If-Range@; RFC 9110 13.1.5, 14.2).+requestedPart :: ByteString -> Int -> RequestHeaders -> Maybe ( Int, Int )+requestedPart etag size headers = do+ ranges <- parseByteRanges =<< List.lookup hRange headers+ guard (all (== etag) (List.lookup hIfRange headers))+ ( offset, len ) <- case ranges of+ [ range ] -> bounds range+ _ -> Nothing+ ( fromInteger offset, fromInteger len ) <$ guard (( offset, len ) /= ( 0, n ))+ where+ n = toInteger size++ bounds = \case+ ByteRangeFrom from+ | from < n -> Just ( from, n - from )+ ByteRangeFromTo from to+ | from <= to, from < n -> Just ( from, min to (n - 1) - from + 1 )+ ByteRangeSuffix k+ | k > 0 -> Just ( max 0 (n - k), min k n )+ _ -> Nothing
src/Hath/ServerTime.hs view
@@ -1,9 +1,4 @@--- | The RPC server's clock. Keystamps, server commands, speed tests and the--- signatures of our own RPC requests all carry its time, so we sign and check--- with it rather than ours (official Settings.getServerTime). As the official--- client does, we keep its offset from our clock in one global: it is read--- wherever a time is signed or checked, and set from whichever reply carries--- @server_time@.+-- | RPC server clock offset (official Settings.getServerTime), updated from @server_time@ replies. module Hath.ServerTime ( serverNow, setServerTime ) where import Data.Time.Clock.System ( SystemTime(systemSeconds), getSystemTime )@@ -12,13 +7,11 @@ import System.IO.Unsafe ( unsafePerformIO ) --- | Seconds to add to our clock to get the server's. offset :: IORef Int64 offset = unsafePerformIO (newIORef 0) {-# NOINLINE offset #-} --- | The server's time in Unix seconds: ours until a reply has told us its own. serverNow :: IO Int64 serverNow = (+) <$> readIORef offset <*> ourNow
src/Hath/Settings.hs view
@@ -1,6 +1,8 @@ -- | The settings the RPC server assigns to this client. module Hath.Settings ( HathSettings(..)+ , ImageProxy(..)+ , imageProxy , defaultHathSettings , parseSettings , settingNumber@@ -8,6 +10,7 @@ ) where import qualified Data.ByteString.Char8 as BS+import Data.Char ( toLower ) import Relude @@ -22,12 +25,19 @@ , diskRemainingBytes :: !Int64 , rpcServerIPs :: ![ ByteString ] -- ^ As sent by the server, e.g. @::ffff:192.0.2.10@. These are exempt from flood control.+ , rpcServerPort :: !Int , maxConnectionsOverride :: !Int -- ^ @max_connections@: when above 0, 'maxConnections' is this. , maxAllowedFileSize :: !Int -- ^ @max_allowed_filesize@: a cache miss or download larger than this is not fetched. , maxFilenameLength :: !Int -- ^ @max_filename_length@: how long the name of a gallery's directory may get.+ , staticRangeCount :: !Int+ , verifyCache :: !Bool+ , rescanCache :: !Bool+ , imageProxyType :: !ByteString+ , imageProxyHost :: !ByteString+ , imageProxyPort :: !Int } deriving ( Show ) @@ -40,10 +50,17 @@ , diskLimitBytes = 0 , diskRemainingBytes = 0 , rpcServerIPs = []+ , rpcServerPort = 80 , maxConnectionsOverride = 0 -- the official client's defaults (Settings.java:58) , maxAllowedFileSize = 1073741824 , maxFilenameLength = 125+ , staticRangeCount = 0+ , verifyCache = False+ , rescanCache = False+ , imageProxyType = ""+ , imageProxyHost = ""+ , imageProxyPort = 0 } -- | Apply @name=value@ lines onto the settings we have. @client_settings@ only@@ -59,12 +76,39 @@ ( "disklimit_bytes", Just n ) -> settings { diskLimitBytes = n } ( "diskremaining_bytes", Just n ) -> settings { diskRemainingBytes = n } ( "rpc_server_ip", _ ) -> settings { rpcServerIPs = BS.split ';' value }+ ( "rpc_server_port", Just n ) -> settings { rpcServerPort = fromIntegral n } ( "max_connections", Just n ) -> settings { maxConnectionsOverride = fromIntegral n } ( "max_allowed_filesize", Just n ) -> settings { maxAllowedFileSize = fromIntegral n } ( "max_filename_length", Just n ) -> settings { maxFilenameLength = fromIntegral n }+ -- sent at login only (Settings.java:318-332)+ ( "static_ranges", _ )+ -> settings { staticRangeCount = length (filter ((== 4) . BS.length) (BS.split ';' value)) }+ ( "static_range_count", Just n ) -> settings { staticRangeCount = fromIntegral n }+ ( "verify_cache", _ ) -> settings { verifyCache = value == "true", rescanCache = value == "true" }+ ( "rescan_cache", _ ) -> settings { rescanCache = value == "true" }+ ( "image_proxy_type", _ ) -> settings { imageProxyType = BS.map toLower value }+ ( "image_proxy_host", _ ) -> settings { imageProxyHost = BS.map toLower value }+ ( "image_proxy_port", Just n ) -> settings { imageProxyPort = fromIntegral n } _ -> settings where ( name, value ) = nameValue line++-- | Image proxy from the H\@H settings page, used for cache misses, proxy tests,+-- and retried gallery downloads (Settings.getImageProxy; defaults: SOCKS 1080, HTTP 8080).+data ImageProxy = SOCKSProxy !String !Int | HTTPProxy !ByteString !Int+ deriving ( Eq, Show )++imageProxy :: HathSettings -> Maybe ImageProxy+imageProxy settings+ | BS.null host = Nothing+ | imageProxyType settings == "http" = Just $ HTTPProxy host (port 8080)+ | otherwise = Just $ SOCKSProxy (BS.unpack host) (port 1080)+ where+ host = imageProxyHost settings++ port standard+ | imageProxyPort settings > 0 = imageProxyPort settings+ | otherwise = standard -- | How many connections we take at once (Settings.getMaxConnections). maxConnections :: HathSettings -> Int
src/Hath/Stats.hs view
@@ -1,7 +1,6 @@ {-# LANGUAGE DataKinds #-} --- | The counters behind @\/metrics@, and their rendering in the Prometheus--- text format.+-- | Prometheus counters and rendering for @\/metrics@. module Hath.Stats ( StatsEnv , newStatsEnv@@ -46,8 +45,7 @@ , statsDurationSum :: !(IORef Double) } --- | Upper bounds of the request duration buckets, in seconds. A duration--- includes sending the body, so large files land in the upper buckets.+-- | Bucket upper bounds in seconds (includes body transfer time). durationBounds :: [ Double ] durationBounds = [ 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60 ] @@ -110,8 +108,7 @@ now <- getMonotonicTime renderMetrics stats (round (now - statsStart stats)) --- | The metrics in the Prometheus text format, given the uptime in seconds.--- They come in the order earlier versions printed them.+-- | Render metrics in Prometheus text format, preserving legacy metric ordering. renderMetrics :: StatsEnv -> Int64 -> IO Text renderMetrics stats uptime = do let counter name help field = scalar "counter" name help <$> readIORef (field stats)@@ -142,8 +139,6 @@ , name <> " " <> show value ] --- | The request duration histogram, from the count of each bucket: cumulative--- counts per upper bound (le is inclusive), then the sum and the count. durationHistogram :: [ Int64 ] -> Double -> Text durationHistogram counts total = unlines
src/Hath/Version.hs view
@@ -1,6 +1,6 @@ {-# LANGUAGE TemplateHaskell #-} --- | What this binary was built from, fixed when this module is compiled.+-- | Build commit and timestamp embedded at compile time. module Hath.Version ( versionInfo ) where import Control.Exception ( catch )@@ -23,13 +23,16 @@ , "Build Date: " <> date ] where- -- "unknown" when the build does not run in a git checkout commit :: Text commit = T.strip $( runIO- (readProcess "git" [ "rev-parse", "--short=7", "HEAD" ] "" `catch` \(_ :: SomeException)- -> pure "unknown")+ (lookupEnv "HATH_BUILD_COMMIT"+ >>= maybe+ (readProcess "git" [ "rev-parse", "--short=7", "HEAD" ] "" `catch` \(_ :: SomeException)+ -> pure "unknown")+ pure+ . mfilter (not . null)) >>= stringE )
test/APISpec.hs view
@@ -15,7 +15,6 @@ import Test.Hspec --- | What a path comes to, shown so that failures can be read. routed :: ByteString -> Text routed path = case route path of Favicon -> "favicon"
test/FileURISpec.hs view
@@ -10,7 +10,6 @@ import Test.Hspec.QuickCheck ( prop ) import Test.QuickCheck --- | A file the official client would accept, with or without a resolution. fileURI :: Gen FileURI fileURI = do digest <- BS.pack <$> vectorOf 40 (elements ([ '0' .. '9' ] <> [ 'a' .. 'f' ]))
test/FilesystemSpec.hs view
@@ -6,10 +6,17 @@ import Colog.Polysemy ( Log, runLogAction ) import qualified Data.ByteString as BS-import Data.Time.Clock.POSIX ( posixSecondsToUTCTime )+import Data.Time.Clock.POSIX ( getPOSIXTime, posixSecondsToUTCTime ) import Hath.Cache ( Cache, CacheHit(..), deleteFile, lookupFile, storeFile )-import Hath.Cache.Filesystem ( FsCache, newFsCache, runCacheFilesystem, sweep )+import Hath.Cache.Filesystem ( FsCache+ , cachedBytes+ , cachedFiles+ , evict+ , openFsCache+ , runCacheFilesystem+ , saveState+ ) import Hath.Error ( HathError ) import Hath.FileURI ( FileURI(..) ) import Hath.Protocol ( sha1Hex )@@ -21,9 +28,11 @@ import System.Directory ( createDirectoryIfMissing , doesFileExist+ , removeDirectory+ , removeFile , setModificationTime )-import System.FilePath ( (</>) )+import System.FilePath ( (</>), takeDirectory ) import System.IO.Temp ( withSystemTempDirectory ) import Test.Hspec@@ -57,8 +66,16 @@ withCache :: (FilePath -> FsCache -> IO a) -> IO a withCache k = withSystemTempDirectory "hath-test" $ \tmp -> do let root = tmp </> "cache"- newFsCache root >>= k root+ open root >>= k root +open :: FilePath -> IO FsCache+open root = openFsCache root (pure 0) False False++age :: Int -> FilePath -> IO ()+age days path = do+ now <- getPOSIXTime+ setModificationTime path (posixSecondsToUTCTime (now - fromIntegral (days * 86400)))+ filesystemSpecs :: Spec filesystemSpecs = describe "Filesystem cache" $ do let content = "test content for Filesystem storage"@@ -92,18 +109,73 @@ paths <- forM [ a, b, c ] $ \x -> store fs x >> fromMaybe (error "stored") <$> served fs x forM_ (zip paths [ 100, 200, 300 ]) $ \( p, t ) -> setModificationTime p (posixSecondsToUTCTime t)- -- serving a makes it the newest, so b is now the least recently served- void $ served fs a createDirectoryIfMissing True (root </> "abcd") writeFileBS (root </> "notes.txt") "not ours" writeFileBS (root </> "abcd" </> "other") "not ours"- -- 3000 bytes against a 2500 byte limit (evicting down to 2250): one file has to go- sweep fs 2500 >>= (`shouldBe` ( 1, 1000 ))+ -- the ages as files on disk have them, which serving a then changes+ fs' <- openFsCache root (pure 0) True False+ void $ served fs' a+ evict fs' 1000 >>= (`shouldBe` ( 1, 1000 )) mapM doesFileExist paths >>= (`shouldBe` [ True, False, True ]) mapM doesFileExist [ root </> "notes.txt", root </> "abcd" </> "other" ] >>= (`shouldBe` [ True, True ])+ cachedBytes fs' `shouldReturn` 2000 - it "evicts nothing under the limit, or without one" $ withCache $ \_ fs -> do+ it "evicts nothing from an empty cache" $ withCache $ \_ fs -> evict fs 1000 `shouldReturn` ( 0, 0 )++ it "takes the totals saved at shutdown instead of scanning, once" $ withCache $ \root fs -> do store fs content- sweep fs 0 >>= (`shouldBe` ( 0, 0 ))- sweep fs 1000000 >>= (`shouldBe` ( 0, 0 ))+ saveState fs+ -- a file the saved totals do not know of+ let other = "another file, stored behind the cache's back"+ dir = decodeUtf8 (BS.take 4 (sha1Hex other))+ createDirectoryIfMissing True (root </> dir)+ writeFileBS (root </> dir </> (dir <> "-other")) other+ reopened <- open root+ cachedFiles reopened `shouldReturn` 1+ cachedBytes reopened `shouldReturn` fromIntegral (BS.length content)+ -- they were used up: a crash now must not leave them for the next start+ rescanned <- open root+ cachedFiles rescanned `shouldReturn` 2++ it "scans when a directory the saved totals name is gone" $ withCache $ \root fs -> do+ store fs content+ Just path <- served fs content+ saveState fs+ removeFile path+ removeDirectory (takeDirectory path)+ reopened <- open root+ cachedFiles reopened `shouldReturn` 0++ it "checks a file not served for a week before serving it" $ withCache $ \_ fs -> do+ store fs content+ Just path <- served fs content+ let corrupt = BS.map (const 120) content+ writeFileBS path corrupt+ -- served recently: not checked yet+ served fs content >>= (`shouldBe` Just path)+ age 8 path+ served fs content >>= (`shouldBe` Nothing)+ doesFileExist path >>= (`shouldBe` False)+ cachedFiles fs `shouldReturn` 0++ it "serves an intact file not served for a week" $ withCache $ \_ fs -> do+ store fs content+ Just path <- served fs content+ age 8 path+ served fs content >>= (`shouldBe` Just path)++ it "deletes the files that fail their SHA-1 when verifying at start" $ withCache $ \root fs -> do+ store fs content+ Just path <- served fs content+ writeFileBS path (BS.map (const 120) content)+ verified <- openFsCache root (pure 0) False True+ cachedFiles verified `shouldReturn` 0+ doesFileExist path >>= (`shouldBe` False)++ it "does not store a file that would leave the disk under its reserve"+ $ withSystemTempDirectory "hath-test" $ \tmp -> do+ fs <- openFsCache tmp (pure (2 ^ (62 :: Int))) False False+ store fs content+ served fs content >>= (`shouldBe` Nothing)+ cachedFiles fs `shouldReturn` 0
test/Integration.hs view
@@ -14,9 +14,9 @@ import Database.SQLite.Simple ( Connection, SQLError, close, open ) import Hath.Cache ( Cache(..), CacheRunner(..) )-import Hath.Cache.Filesystem ( newFsCache, runCacheFilesystem )+import Hath.Cache.Filesystem ( openFsCache, runCacheFilesystem ) import Hath.Cache.SQLite ( initializeDB, runCacheSQLite )-import Hath.Config ( ClientConfig(..), defaultClientConfig )+import Hath.Config ( CacheBackend(..), ClientConfig(..), defaultClientConfig ) import Hath.Error ( HathError(StorageError) ) import Hath.Locate ( heldBytes ) import Hath.Protocol ( sha1HexText )@@ -68,6 +68,7 @@ import Relude import System.Directory ( createDirectoryIfMissing )+import System.Exit ( ExitCode(..) ) import System.FilePath ( (</>) ) import System.IO.Temp ( withSystemTempDirectory ) import System.Process ( readProcess )@@ -75,7 +76,7 @@ import Test.Hspec -import UnliftIO ( TChan, newTChanIO, writeTChan )+import UnliftIO ( TChan, newTChanIO, replicateConcurrently, writeTChan ) testConfig :: ClientConfig testConfig@@ -143,7 +144,7 @@ directory = root </> toString (T.take 4 fileId) createDirectoryIfMissing True directory writeFileBS (directory </> toString fileId) content- fs <- newFsCache root+ fs <- openFsCache root (pure 0) False False withAppUsing id CacheRunner { runCacheWith = runCacheFilesystem fs }@@ -247,7 +248,7 @@ Just [ "Genetic Lifeform and Distributed Open Server 1.6.6" , "close"- , "public, max-age=31536000"+ , "public, max-age=31536000, immutable" , "1" ] map (`header` response) [ "User-Agent", "X-Content-Type-Options" ]@@ -263,6 +264,56 @@ header "Content-Length" response `shouldBe` Just "15" header "Content-Type" response `shouldBe` Just "image/jpeg" + it "sends the part of a Filesystem hit a request asks for"+ $ withFilesystemHit "ON_DISK_CONTENT"+ $ \port fileId -> do+ time <- now+ response <- fetchWith [ ( "Range", "bytes=3-6" ) ] port (filePath fileId time fetchable)+ statusCode (responseStatus response) `shouldBe` 206+ body response `shouldBe` "DISK"+ header "Content-Range" response `shouldBe` Just "bytes 3-6/15"++ it "answers 304 to a request that names the file's ETag"+ $ withFilesystemHit "ON_DISK_CONTENT"+ $ \port fileId -> do+ time <- now+ plain <- fetch port (filePath fileId time fetchable)+ let etag = fromMaybe "" (header "ETag" plain)+ etag `shouldBe` [i|"#{T.take 40 fileId}"|]+ again <- fetchWith [ ( "If-None-Match", etag ) ] port (filePath fileId time fetchable)+ statusCode (responseStatus again) `shouldBe` 304+ body again `shouldBe` ""++ it "sends the part of a cached file a request asks for, once it is in the database" $ do+ let content = "IN_THE_DATABASE"+ withApp content $ \port -> do+ time <- now+ let path = filePath (fileIdFor content "jpg") time fetchable+ void $ fetch port path+ -- the file is written to the database after it has been sent+ let partial n = do+ response <- fetchWith [ ( "Range", "bytes=-8" ) ] port path+ if statusCode (responseStatus response) == 206 || n == (0 :: Int)+ then pure response+ else threadDelay 100000 >> partial (n - 1)+ response <- partial 20+ statusCode (responseStatus response) `shouldBe` 206+ body response `shouldBe` "DATABASE"+ header "Content-Range" response `shouldBe` Just "bytes 7-14/15"++ it "fetches a file once for the requests that miss it at the same time" $ do+ seen <- newIORef []+ let content = "FETCHED_ONCE_FOR_ALL_OF_THEM"+ mock = defaultMockRPC { mockFileContent = content+ , mockPauseHalfway = 500000+ , mockSeen = atomicModifyIORef'_ seen . (:) . fst+ }+ withMock mock $ \port -> do+ time <- now+ responses <- replicateConcurrently 3 $ fetch port (filePath (fileIdFor content "jpg") time fetchable)+ map body responses `shouldBe` replicate 3 content+ filter (== "srfetch") <$> readIORef seen `shouldReturn` [ "srfetch" ]+ it "does not serve even a cached file without its fileindex and xres, as the official client" $ withFilesystemHit "ON_DISK_CONTENT" $ \port fileId -> do@@ -402,6 +453,22 @@ responses <- replicateM 13 $ fetch port (filePath (fileIdFor "x" "jpg") time fetchable) responseStatus <$> responses `shouldBe` replicate 13 status200 + describe "Startup" $ it "refuses an empty cache when the client has more than 20 static ranges" $ do+ withSystemTempDirectory "hath-empty" $ \dir -> do+ certs <- CertificateChain <$> readSignedObject "vendor/warp-tls-3.4.18/certificate.pem"+ privateKey <- readKeyFile "vendor/warp-tls-3.4.18/key.pem"+ >>= maybe (fail "no private key in the test key file") pure . listToMaybe+ actions <- newTChanIO+ let config = testConfig { cacheBackend = CacheBackendFilesystem+ , cachePath = toText (dir </> "cache")+ }+ options = ServerOptions { disableRateLimit = True+ , trustProxyHeaders = False+ , skipStartupVerify = False+ }+ startServer config options defaultHathSettings { staticRangeCount = 21 } ( certs, privateKey ) actions+ `shouldThrow` (== ExitFailure 1)+ describe "Flood control" $ it "blocks an address after ten requests, whatever they ask for, and no other" $ behindProxy defaultMockRPC@@ -697,8 +764,11 @@ actions <- newTChanIO let config = testConfig { cachePath = toText (dir </> "cache.db") } settings = defaultHathSettings { clientPort = port }- options = ServerOptions { disableRateLimit = True, trustProxyHeaders = False }- bracket (forkIO $ startServer config options settings ( certs, privateKey ) actions) killThread+ options = ServerOptions { disableRateLimit = True+ , trustProxyHeaders = False+ , skipStartupVerify = False+ }+ bracket (forkIO $ void $ startServer config options settings ( certs, privateKey ) actions) killThread $ \_ -> do waitUntilListening port result <- action port actions
test/ProtocolSpec.hs view
@@ -14,15 +14,12 @@ import Test.Hspec.QuickCheck ( prop ) import Test.QuickCheck --- | Text free of the separators these formats use. word :: Gen ByteString word = BS.pack <$> listOf1 (elements ([ 'a' .. 'z' ] <> [ '0' .. '9' ] <> " ._/")) --- | A client key, the time of a reply and its payload lines. reply :: Gen ( ByteString, ByteString, [ ByteString ] ) reply = (,,) <$> word <*> (BS.pack <$> listOf1 (elements [ '0' .. '9' ])) <*> listOf word --- | A reply as the 1.6.6 server signs it. signed :: ByteString -> ByteString -> [ ByteString ] -> ByteString signed clientKey time payload = "OK-" <> time <> "-" <> sha1Hex (time <> "-" <> clientKey <> body) <> body
test/RPCSpec.hs view
@@ -7,11 +7,16 @@ import Hath.Config ( ClientConfig(..), defaultClientConfig ) import Hath.Error ( HathError(..) ) import Hath.FileURI ( parseFileURI )-import Hath.RPC ( StartFailure(..)+import Hath.RPC ( RPCServers(..)+ , StartFailure(..)+ , Stop(..) , clientStart+ , failedRPCServer , getBlacklist+ , loginFailure , nextGallery , overload+ , pickRPCServer , runRPCIO , startFailure , toldToStop@@ -89,12 +94,42 @@ $ \failure -> startFailure 443 failure `shouldSatisfy` (not . refused) describe "a failed still_alive" $ do- it "stops the client on TERM_BAD_NETWORK"- $ toldToStop (RequestFailure "TERM_BAD_NETWORK") `shouldBe` True+ it "stops the client on TERM_BAD_NETWORK and FAIL_NOT_LOGGED_IN" $ do+ toldToStop (RequestFailure "TERM_BAD_NETWORK") `shouldBe` Just BadNetwork+ toldToStop (RequestFailure "FAIL_NOT_LOGGED_IN") `shouldBe` Just NotLoggedIn it "waits for the next one otherwise" $ map toldToStop [ RequestFailure "FAIL", TransportError "HTTP 500", EmptyResponse ]- `shouldBe` [ False, False, False ]+ `shouldBe` [ Nothing, Nothing, Nothing ]++ describe "a failed login" $ do+ it "waits out the 15 minute block of a startup loop"+ $ fst (loginFailure (RequestFailure "FAIL_STARTUP_LOOP")) `shouldBe` 900++ it "waits 5 s otherwise" $ map+ (fst . loginFailure)+ [ RequestFailure "FAIL_UNSUPPORTED_LOCATION", RequestFailure "FAIL", TransportError "HTTP 500" ]+ `shouldBe` [ 5, 5, 5 ]++ describe "the RPC server" $ do+ let servers = RPCServers [ "192.0.2.1", "192.0.2.2", "192.0.2.3" ] 80 Nothing Nothing++ it "is one of those assigned, kept until it fails" $ do+ let picked = pickRPCServer 1 servers+ rpcCurrent picked `shouldBe` Just "192.0.2.2"+ rpcCurrent (pickRPCServer 0 picked) `shouldBe` Just "192.0.2.2"++ it "is never the one that failed last, while there are others" $ do+ let failed = failedRPCServer "192.0.2.2" (pickRPCServer 1 servers)+ rpcCurrent failed `shouldBe` Nothing+ forM_ [ 0 .. 5 ] $ \n -> rpcCurrent (pickRPCServer n failed) `shouldNotBe` Just "192.0.2.2"++ it "stays the one that failed when it is the only one" $ do+ let only = RPCServers [ "192.0.2.1" ] 80 Nothing (Just "192.0.2.1")+ rpcCurrent (pickRPCServer 0 only) `shouldBe` Just "192.0.2.1"++ it "is none until some are assigned"+ $ rpcCurrent (pickRPCServer 0 (RPCServers [] 80 Nothing Nothing)) `shouldBe` Nothing describe "overload" $ it "is sent as act=overload" $ do seen <- newIORef []
+ test/RangeSpec.hs view
@@ -0,0 +1,39 @@+module RangeSpec ( rangeSpecs ) where++import Hath.Server.Range ( notModified, requestedPart )++import Relude++import Test.Hspec++rangeSpecs :: Spec+rangeSpecs = describe "Conditional requests" $ do+ let etag = "\"0123456789abcdef0123456789abcdef01234567\""++ describe "notModified" $ do+ it "matches the ETag in a list, weak or not, or *" $ do+ notModified etag [ ( "If-None-Match", "\"other\", W/" <> etag ) ] `shouldBe` True+ notModified etag [ ( "If-None-Match", "*" ) ] `shouldBe` True++ it "does not match another ETag, or none"+ $ map (notModified etag) [ [ ( "If-None-Match", "\"other\"" ) ], [] ]+ `shouldBe` [ False, False ]++ describe "requestedPart" $ do+ let part range = requestedPart etag 1000 [ ( "Range", range ) ]++ it "reads the three forms of a byte range" $ do+ part "bytes=100-199" `shouldBe` Just ( 100, 100 )+ part "bytes=900-" `shouldBe` Just ( 900, 100 )+ part "bytes=-10" `shouldBe` Just ( 990, 10 )++ it "cuts a range short at the end of the file" $ part "bytes=990-5000" `shouldBe` Just ( 990, 10 )++ it "sends the whole file for a range that covers it, does not fit, or comes with others"+ $ map part [ "bytes=0-", "bytes=1000-", "bytes=0-1,5-6", "lines=1-2" ]+ `shouldBe` [ Nothing, Nothing, Nothing, Nothing ]++ it "honours If-Range only when it names the ETag" $ do+ requestedPart etag 1000 [ ( "Range", "bytes=0-9" ), ( "If-Range", etag ) ] `shouldBe` Just ( 0, 10 )+ requestedPart etag 1000 [ ( "Range", "bytes=0-9" ), ( "If-Range", "Sat, 01 Jan 2000 00:00:00 GMT" ) ]+ `shouldBe` Nothing
test/Spec.hs view
@@ -24,7 +24,9 @@ ) import Hath.Server ( needsRenewal ) import Hath.Settings ( HathSettings(..)+ , ImageProxy(..) , defaultHathSettings+ , imageProxy , maxConnections , parseSettings , settingNumber@@ -53,6 +55,8 @@ import R2Spec ( r2Specs ) +import RangeSpec ( rangeSpecs )+ import RPCSpec ( rpcSpecs ) import Relude hiding ( runReader )@@ -69,6 +73,7 @@ floodControlSpecs connectionLimitSpecs locateSpecs+ rangeSpecs gallerySpecs settingsSpecs rpcSpecs@@ -92,6 +97,28 @@ diskLimitBytes refreshed `shouldBe` 2000 rpcServerIPs refreshed `shouldBe` [ "192.0.2.1", "192.0.2.2" ] + describe "static ranges" $ it "are counted from static_ranges, or as static_range_count says" $ do+ staticRangeCount (parseSettings defaultHathSettings [ "static_ranges=0a1b;2c3d;;bad" ])+ `shouldBe` 2+ staticRangeCount (parseSettings defaultHathSettings [ "static_range_count=25" ]) `shouldBe` 25++ describe "verify_cache" $ it "asks for a rescan too" $ do+ let verify = parseSettings defaultHathSettings [ "verify_cache=true" ]+ ( verifyCache verify, rescanCache verify ) `shouldBe` ( True, True )++ describe "imageProxy" $ do+ let proxy = imageProxy . parseSettings defaultHathSettings++ it "is none without a host" $ proxy [ "image_proxy_type=http", "image_proxy_port=3128" ]+ `shouldBe` Nothing++ it "is SOCKS on 1080 unless the settings say otherwise" $ do+ proxy [ "image_proxy_host=Proxy.example" ] `shouldBe` Just (SOCKSProxy "proxy.example" 1080)+ proxy [ "image_proxy_host=proxy.example", "image_proxy_type=HTTP" ]+ `shouldBe` Just (HTTPProxy "proxy.example" 8080)+ proxy [ "image_proxy_host=proxy.example", "image_proxy_port=9050" ]+ `shouldBe` Just (SOCKSProxy "proxy.example" 9050)+ describe "max_allowed_filesize" $ it "is taken from the settings" $ maxAllowedFileSize (parseSettings defaultHathSettings [ "max_allowed_filesize=1000" ])@@ -133,19 +160,30 @@ it "has nothing to serve without a certificate" $ needsRenewal 0 (CertificateChain []) `shouldBe` True --- | hath-bench writes its config this way. configSpecs :: Spec-configSpecs = describe "ClientConfig" $ it "reads back what ToDhall writes" $ do- let config- = defaultClientConfig- { clientId = "12345"- , key = "a \"quoted\" key"- , cachePath = "/tmp/hs-cache.db"- , cacheBackend = CacheBackendR2- , r2Config = Just (R2Config "https://r2.example" "bucket")- }- readBack <- readClientConfig (Dhall.pretty (embed inject config))- show @Text readBack `shouldBe` show config+configSpecs = describe "ClientConfig" $ do+ -- hath-bench writes its config this way+ it "reads back what ToDhall writes" $ do+ let config+ = defaultClientConfig+ { clientId = "12345"+ , key = "a \"quoted\" key"+ , cachePath = "/tmp/hs-cache.db"+ , cacheBackend = CacheBackendR2+ , r2Config = Just (R2Config "https://r2.example" "bucket")+ }+ readBack <- readClientConfig (Dhall.pretty (embed inject config))+ show @Text readBack `shouldBe` show config+ it "reads a client-login without the deprecated fields" $ do+ readBack <- readClientConfig+ "{ clientId = \"1\", key = \"k\", downloadDir = \"d\", cachePath = \"c\", cacheBackend = < CacheBackendSQLite | CacheBackendR2 | CacheBackendFilesystem >.CacheBackendFilesystem, r2Config = None { r2Endpoint : Text, r2Bucket : Text } }"+ show @Text readBack+ `shouldBe` show defaultClientConfig { clientId = "1"+ , key = "k"+ , downloadDir = "d"+ , cachePath = "c"+ , cacheBackend = CacheBackendFilesystem+ } metricsSpecs :: Spec metricsSpecs