An HTTP cache system, RFC compliant, compatible with @tyktechnologies, @traefik, @caddyserver, @go-chi, @bnkamalesh, @beego, @devfeel, @labstack, @gofiber, @go-goyave, @go-kratos, @gin-gonic, @roadrunner-server, @zalando, @zeromicro, @nginx and @apache
Souin Table of Contents
2.1. Required configuration 2.1.1. Souin as plugin 2.1.2. Souin out-of-the-box 2.2. Optional configuration 4.1. Prometheus API 4.2. Souin API 4.3. Security API 5.1. Sequence diagram 8.1. Beego filter 8.2. Caddy module 8.3. Chi middleware 8.4. Dotweb middleware 8.5. Echo middleware 8.6. Fiber middleware 8.7. Gin middleware 8.8. Goa middleware 8.9. Go-zero middleware 8.10. Goyave middleware 8.11. Hertz middleware 8.12. Kratos filter 8.13. Roadrunner middleware 8.14. Skipper filter 8.15. Træfik plugin 8.16. Tyk plugin 8.17. Webgo middlewareSouin HTTP cache
Project description
Souin is a new HTTP cache system suitable for every reverse-proxy. It can be either placed on top of your current reverse-proxy whether it's Apache, Nginx or as plugin in your favorite reverse-proxy like Træfik, Caddy or Tyk. Since it's written in go, it can be deployed on any server and thanks to the docker integration, it will be easy to install on top of a Swarm, or a kubernetes instance. It's RFC compatible, supporting Vary, request coalescing, stale cache-control and other specifications related to the RFC-7234. It supports the newly written RFCs (currently in draft) http-cache-groups and http-invalidation. It also supports the Cache-Status HTTP response header, the YKey group such as Varnish, the Targeted HTTP Cache Control RFC, . It supports the ESI tags, thanks to the go-esi package.[!WARNING]
Since v1.7.0 Souin implements only one in-memory map storage. If you need a specific storage you have to take it from the storages repository and add it either in your code, during the build otherwise.
(e.g. with otter using caddy) You have to build your caddy module with the desired storage xcaddy build --with github.com/darkweak/souin/plugins/caddy --with github.com/darkweak/storages/otter/caddy and configure otter in your Caddyfile/JSON configuration file.
See the storages section or the documentation website about the storages.
Configuration
The configuration file is store at/anywhere/configuration.yml. You can supply your own as long as you use one of the minimal configurations below.
Required configuration
Souin as plugin
default_cache: # Required
ttl: 10s # Default TTL
Souin out-of-the-box
default_cache: # Required
ttl: 10s # Default TTL
reverseproxyurl: 'http://traefik' # If it's in the same network you can use http://your-service, otherwise just use https://yourdomain.com
| Key | Description | Value example | |:--------------------|:------------------------------------------------------------|:--------------------------------------------------------------------------------------------------------------------------| | default_cache.ttl | Duration to cache request (in seconds) | 10 |
Besides, it's highly recommended to set defaultcache.defaultcache_control (see it below) to avoid undesired caching for responses without Cache-Control header.
Optional configuration
# /anywhere/configuration.yml
api:
basepath: /souin-api # Default route basepath for every additional APIs to avoid conflicts with existing routes
prometheus: # Prometheus exposed metrics
basepath: /anything-for-prometheus-metrics # Change the prometheus endpoint basepath
souin: # Souin listing keys and cache management
basepath: /anything-for-souin # Change the souin endpoint basepath
cache_keys:
'.*\.css':
disable_body: true # Prevent the body from being used in the cache key
disable_host: true # Prevent the host from being used in the cache key
disable_method: true # Prevent the method from being used in the cache key
disable_query: true # Prevent the query string from being used in the cache key
disable_scheme: true # request scheme the query string from being used in the cache key
disable_vary: true # Prevent the varied headers string from being used in the cache key
hash: true # Hash the cache key instead of a plaintext one
hide: true # Prevent the cache key to be in the response Cache-Status header
headers: # Add headers to the key
- Authorization # Add the header value in the key
- Content-Type # Add the header value in the key
template: "{http.request.method}-{http.request.host}-{http.request.path}" # Use caddy placeholders to create the key (when this option is enabled, disable_* directives are skipped)
cdn: # If Souin is set after a CDN fill these informations
api_key: XXXX # Your provider API key if mandatory
provider: fastly # The provider placed before Souin (e.g. fastly, cloudflare, akamai, varnish)
strategy: soft # The strategy to purge the CDN cache based on tags (e.g. soft, hard)
dynamic: true # If true, you'll be able to add custom keys than the ones defined under the surrogate_keys key
default_cache:
allowedhttpverbs: # Allowed HTTP verbs to cache (default GET, HEAD).
- GET
- POST
- HEAD
allowedadditionalstatus_codes: # Allowed additional HTTP status code to cache.
- 202
- 400
cache_name: Souin # Override the cache name to use in the Cache-Status header
distributed: true # Use Olric or Etcd distributed storage
key:
disable_body: true # Prevent the body from being used in the cache key
disable_host: true # Prevent the host from being used in the cache key
disable_method: true # Prevent the method from being used in the cache key
disable_query: true # Prevent the query string from being used in the cache key
disable_scheme: true # Prevent the request scheme string from being used in the cache key
disable_vary: true # Prevent the varied headers string from being used in the cache key
hash: true # Hash the cache key instead of a plaintext one
hide: true # Prevent the cache key to be in the response Cache-Status header
headers: # Add headers to the key
- Authorization # Add the header value in the key
- Content-Type # Add the header value in the key
template: "{http.request.method}-{http.request.host}-{http.request.path}" # Use caddy placeholders to create the key (when this option is enabled, disable_* directives are skipped)
etcd: # If distributed is set to true, you'll have to define either the etcd or olric section
configuration: # Configure directly the Etcd client
endpoints: # Define multiple endpoints
- etcd-1:2379 # First node
- etcd-2:2379 # Second node
- etcd-3:2379 # Third node
mode: bypass # Override the RFC respect.
olric: # If distributed is set to true, you'll have to define either the etcd or olric section
url: 'olric:3320' # Olric server
regex:
exclude: 'ARegexHere' # Regex to exclude from cache
stale: 1000s # Stale duration
timeout: # Timeout configuration
backend: 10s # Backend timeout before returning an HTTP unavailable response
cache: 20ms # Cache provider (badger, etcd, nutsdb, olric, depending the configuration you set) timeout before returning a miss
ttl: 1000s # Default TTL
defaultcachecontrol: no-store # Set default value for Cache-Control response header if not set by upstream
log_level: INFO # Logs verbosity [ DEBUG, INFO, WARN, ERROR, DPANIC, PANIC, FATAL ], case do not matter
ssl_providers: # The {providers}.json to use
- traefik
urls:
'https:\/\/domain.com\/first-.+': # First regex route configuration
ttl: 1000s # Override default TTL
'https:\/\/domain.com\/second-route': # Second regex route configuration
ttl: 10s # Override default TTL
'https?:\/\/mysubdomain\.domain\.com': # Third regex route configuration
ttl: 50s # Override default TTL'
defaultcachecontrol: public, max-age=86400 # Override default default Cache-Control
ykeys:
TheFirstTest:
headers:
Content-Type: '.+'
TheSecondTest:
url: 'the/second/.+'
TheThirdTest:
TheFourthTest:
surrogate_keys:
TheFirstTest:
headers:
Content-Type: '.+'
TheSecondTest:
url: 'the/second/.+'
TheThirdTest:
TheFourthTest:
| Key | Description | Value example | |:--------------------------------------------------|:--------------------------------------------------------------------------------------------------------------------------------------------|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | api | The cache-handler API cache management | | | api.basepath | BasePath for all APIs to avoid conflicts | /your-non-conflicting-route(default: /souin-api) | | api.{api}.enable | (DEPRECATED) Enable the API with related routes | true(default: true if you define the api name, false then) | | api.{api}.security | (DEPRECATED) Enable the JWT Authentication token verification | true(default: false) | | api.security.secret | (DEPRECATED) JWT secret key | Any_charCanW0rk123 | | api.security.users | (DEPRECATED) Array of authorized users with username x password combo | - username: admin password: admin | | api.souin.security | Enable JWT validation to access the resource | true(default: false) | | cache_keys | Define the key generation rules for each URI matching the key regexp | | | cache_keys.{your regexp} | Regexp that the URI should match to override the key generation | .+\.css | | cachekeys.{your regexp}.disablebody | Disable the body part in the key matching the regexp (GraphQL context) | true(default: false) | | cachekeys.{your regexp}.disablehost | Disable the host part in the key matching the regexp | true(default: false) | | cachekeys.{your regexp}.disablemethod | Disable the method part in the key matching the regexp | true(default: false) | | cachekeys.{your regexp}.disablequery | Disable the query string part in the key matching the regexp | true(default: false) | | cachekeys.{your regexp}.disablescheme | Disable the request scheme string part in the key matching the regexp | true(default: false) | | cachekeys.{your regexp}.disablevary | Disable the vary string part in the key matching the regexp | true(default: false) | | cache_keys.{your regexp}.hash | Hash the key matching the regexp | true(default: false) | | cache_keys.{your regexp}.headers | Add headers to the key matching the regexp | - Authorization- Content-Type- X-Additional-Header | | cache_keys.{your regexp}.hide | Prevent the key from being exposed in the Cache-Status HTTP response header | true(default: false) | | cdn | The CDN management, if you use any cdn to proxy your requests Souin will handle that | | | cdn.provider | The provider placed before Souin | akamaifastlysouin | | cdn.api_key | The api key used to access to the provider | XXXX | | cdn.dynamic | Enable the dynamic keys returned by your backend application | false(default: true) | | cdn.email | The api key used to access to the provider if required, depending the provider | XXXX | | cdn.hostname | The hostname if required, depending the provider | domain.com | | cdn.network | The network if required, depending the provider | your_network | | cdn.strategy | The strategy to use to purge the cdn cache, soft will keep the content as a stale resource | hard(default: soft) | | cdn.serviceid | The service id if required, depending the provider | 123456id | | cdn.zoneid | The zone id if required, depending the provider | anywherezone | | defaultcache.allowedhttp_verbs | The HTTP verbs to support cache | - GET- POST(default: GET, HEAD) | | defaultcache.allowedadditionalstatuscodes | The additional HTTP status code to support cache | - 200- 404 | | default_cache.badger | Configure the Badger cache storage | | | defaultcache.badger.path | Configure Badger with a file | /anywhere/badgerconfiguration.json | | defaultcache.badger.configuration | Configure Badger directly in the Caddyfile or your JSON caddy configuration | See the Badger configuration for the options | | defaultcache.defaultcache_control | Set the default value of Cache-Control response header if not set by upstream (Souin treats empty Cache-Control as public if omitted) | no-store | | default_cache.etcd | Configure the Etcd cache storage | | | defaultcache.etcd.configuration | Configure Etcd directly in the Caddyfile or your JSON caddy configuration | See the Etcd configuration for the options | | default_cache.etcd.url | Set the Etcd cluster endpoint | http://etcd1:2379,http://etcd2:2379 | | default_cache.key | Override the key generation with the ability to disable unecessary parts | | | defaultcache.key.disablebody | Disable the body part in the key (GraphQL context) | true(default: false) | | defaultcache.key.disablehost | Disable the host part in the key | true(default: false) | | defaultcache.key.disablemethod | Disable the method part in the key | true(default: false) | | defaultcache.key.disablequery | Disable the query string part in the key | true(default: false) | | defaultcache.key.disablescheme | Disable the request scheme string part in the key | true(default: false) | | defaultcache.key.disablevary | Disable the request vary string part in the key | true(default: false) | | default_cache.key.hash | Hash the key name in the storage | true(default: false) | | default_cache.key.headers | Add headers to the key matching the regexp | - Authorization- Content-Type- X-Additional-Header | | default_cache.key.hide | Prevent the key from being exposed in the Cache-Status HTTP response header | true(default: false) | | defaultcache.key.template | Use caddy placeholders to create the key (when this option is enabled, disable* directives are skipped) | Placeholders documentation | | defaultcache.maxcacheablebodybytes | Set the maximum size (in bytes) for a response body to be cached (unlimited if omited) | 1048576 (1MB) | | defaultcache.mode | RFC respect tweaking | One of bypass bypassrequest bypass_response strict (default strict) | | default_cache.nats | Configure the Nats cache storage | | | default_cache.nats.url | Set the Nats cluster endpoint | nats://127.0.0.1:4222,nats://127.0.0.1:4223 | | defaultcache.nats.configuration | Configure Nats directly in the Caddyfile or your JSON caddy configuration | See the Nats configuration for the options | | default_cache.nuts | Configure the Nuts cache storage | | | default_cache.nuts.path | Set the Nuts file path storage | /anywhere/nuts/storage | | defaultcache.nuts.configuration | Configure Nuts directly in the Caddyfile or your JSON caddy configuration | See the Nuts configuration for the options | | default_cache.olric | Configure the Olric cache storage | | | defaultcache.olric.path | Configure Olric with a file | /anywhere/olricconfiguration.json | | defaultcache.olric.configuration | Configure Olric directly in the Caddyfile or your JSON caddy configuration | See the Olric configuration for the options | | default_cache.otter | Configure the Otter cache storage | | | default_cache.otter.configuration | Configure Otter directly in the Caddyfile or your JSON caddy configuration | | | default_cache.otter.configuration.size | Set the size of the pool in Otter | 999999 (default 10000) | | default_cache.port.{web,tls} | The device's local HTTP/TLS port that Souin should be listening on | Respectively 80 and 443 | | default_cache.redis | Configure the Redis cache storage | | | default_cache.redis.url | Set the Redis cluster endpoint | nats://127.0.0.1:4222,nats://127.0.0.1:4223 | | defaultcache.redis.configuration | Configure Redis directly in the Caddyfile or your JSON caddy configuration | See the Go-redis configuration for the options or See the Rueidis configuration for the options | | default_cache.regex.exclude | The regex used to prevent paths being cached | ^[A-z]+.*$ | | default_cache.stale | The stale duration | 25m | | default_cache.simplefs | Configure the SimpleFS cache storage | | | default_cache.simplefs.configuration | Configure SimpleFS directly in the Caddyfile or your JSON caddy configuration | | | default_cache.simplefs.configuration.size | Set the size of the pool in Otter | 999999 (default 10000) | | default_cache.timeout | The timeout configuration | | | default_cache.timeout.backend | The timeout duration to consider the backend as unreachable | 10s | | default_cache.timeout.cache | The timeout duration to consider the cache provider as unreachable | 10ms | | default_cache.ttl | The TTL duration | 120s | | log_level | The log level | One of DEBUG, INFO, WARN, ERROR, DPANIC, PANIC, FATAL it's case insensitive | | reverseproxyurl | The reverse-proxy's instance URL (Apache, Nginx, Træfik...) | - http://yourservice (Container way)http://localhost:81 (Local way)http://yourdomain.com:81 (Network way) | | ssl_providers | List of your providers handling certificates | - traefik- nginx- apache | | urls.{your url or regex} | List of your custom configuration depending each URL or regex | 'https:\/\/yourdomain.com' | | urls.{your url or regex}.ttl | Override the default TTL if defined | 90s10m | | urls.{your url or regex}.defaultcachecontrol | Override the default default Cache-Control if defined | public, max-age=86400 | | surrogate_keys.{key name}.headers | Headers that should match to be part of the surrogate key group | Authorization: ey.+Content-Type: json | | surrogate_keys.{key name}.headers.{header name} | Header name that should be present a match the regex to be part of the surrogate key group | Content-Type: json | | surrogate_keys.{key name}.url | Url that should match to be part of the surrogate key group | .+ | | disablesurrogatekey | Disable the Surrogate keys storage system | true | | ykeys.{key name}.headers | (DEPRECATED) Headers that should match to be part of the ykey group | Authorization: ey.+Content-Type: json | | ykeys.{key name}.headers.{header name} | (DEPRECATED) Header name that should be present a match the regex to be part of the ykey group | Content-Type: json | | ykeys.{key name}.url | (DEPRECATED) Url that should match to be part of the ykey group | .+ |
Storages
Sincev1.7.0 Souin implements only one storage. If you need a specific storage you have to take it from the storages repository and add it either in your code, during the build otherwise.
Supported storages
APIs
All endpoints are accessible through theapi.basepath configuration line or by default through /souin-api to avoid named route conflicts. Be sure to define an unused route to not break your existing application.
Prometheus API
Prometheus API expose some metrics about the cache. The base path for the prometheus API is/metrics.
Not supported inside Træfik because the deny the unsafe library usage inside plugins
| Method | Endpoint | Description | |:--------|:---------|:----------------------------------------| | GET | / | Expose the different keys listed below. |
| Key | Definition | |:-----------------------------------|:----------------------------------------------------| | souinrequestupstream_counter | Count the incoming requests that go to the upstream | | souinnocachedresponsecounter | Count the uncacheable responses | | souincachedresponse_counter | Count the cacheable responses | | souinavgresponse_time | Average response time |
Souin API
Souin API allow users to manage the cache. The base path for the souin API is/souin.
The Souin API supports the invalidation by surrogate keys such as Fastly which will replace the Varnish system. You can read the doc about this system.
This system is able to invalidate by tags your cloud provider cache. Actually it supports Akamai and Fastly but in a near future some other providers would be implemented like Cloudflare or Varnish.
| Method | Endpoint | Headers | Description | |:--------|:------------------|:-----------------------------------------------------------|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | GET | / | - | List stored keys cache | | GET | /surrogate_keys | - | List stored keys cache | | PURGE | /{id or regexp} | - | Purge selected item(s) depending. The parameter can be either a specific key or a regexp; use $ to end a specific key; without $, id is considered a regex | | PURGE | /?ykey={key} | - | Purge selected item(s) corresponding to the target ykey such as Varnish (deprecated) | | PURGE | / | Surrogate-Key: Surrogate-Key-First, Surrogate-Key-Second | Purge selected item(s) belong to the target key in the header Surrogate-Key (see Surrogate-Key system) | | PURGE | /flush | - | Purge all providers and surrogate storages |
Security API
DEPRECATED Security API allows users to protect other APIs with JWT authentication. The base path for the security API is/authentication.
| Method | Endpoint | Body | Headers | Description | |:-------|:-----------|:-------------------------------------------|:--------------------------------------------------------------------------------|:-----------------------------------------------------------------------------------------------------------------------| | POST | /login | {"username":"admin", "password":"admin"} | ['Content-Type' => 'json'] | Try to login, it returns a response which contains the cookie name souin-authorization-token with the JWT if succeed | | POST | /refresh | - | ['Content-Type' => 'json', 'Cookie' => 'souin-authorization-token=the-token'] | Refreshes the token, replaces the old with a new one |
Diagrams
Sequence diagram
See the sequence diagram for the minimal version belowCache systems
Supported providers - Badger - Etcd - NutsDB - Olric - Otter - Redis - SimplefsThe cache system sits on top of three providers at the moment. It provides two in-memory storage solutions (badger and nuts), and two distributed storages Olric and Etcd because setting, getting, updating and deleting keys in these providers is as easy as it gets. The Badger provider (default one): you can tune its configuration using the badger configuration inside your Souin configuration. In order to do that, you have to declare the badger block. See the following json example.
"badger": { "configuration": { "ValueDir": "default", "ValueLogFileSize": 16777216, "MemTableSize": 4194304, "ValueThreshold": 524288, "BypassLockGuard": true } }
The Nuts provider: you can tune its configuration using the nuts configuration inside your Souin configuration. In order to do that, you have to declare the nuts block. See the following json example.
"nuts": { "configuration": { "Dir": "default", "EntryIdxMode": 1, "RWMode": 0, "SegmentSize": 1024, "NodeNum": 42, "SyncEnable": true, "StartFileLoadingMode": 1 } }
The Otter provider: you can tune its configuration using the otter configuration inside your Souin configuration. In order to do that, you have to declare the otter block. See the following json example.
"otter": { "configuration": { "size": 9999999 } }
The Olric provider: you can tune its configuration using the olric configuration inside your Souin configuration and declare Souin has to use the distributed provider. In order to do that, you have to declare the olric block and the distributed directive. See the following json example.
"distributed": true, "olric": { "configuration": { # Olric configuration here... } } In order to do that, the Olric provider need to be either on the same network as the Souin instance when using docker-compose or over the internet, then it will use by default in-memory to avoid network latency as much as possible.
The Etcd provider: you can tune its configuration using the etcd configuration inside your Souin configuration and declare Souin has to use the distributed provider. In order to do that, you have to declare the etcd block and the distributed directive. See the following json example.
"distributed": true, "etcd": { "configuration": { # Etcd configuration here... } } In order to do that, the Etcd provider need to be either on the same network as the Souin instance when using docker-compose or over the internet, then it will use by default in-memory to avoid network latency as much as possible. Souin will return at first the response from the choosen provider when it gives a non-empty response, or fallback to the reverse proxy otherwise. Since v1.4.2, Souin supports Olric and since v1.6.10 it supports Etcd to handle distributed cache.
GraphQL
This feature is currently in beta. Souin can partially cache your GraphQL requests. It automatically handles the data retrieval and omit the caching for the mutations. However, it will invalidate whole cache keys with a body when you send a mutation request due to the inability to read and understand automatically which cached endpoint should be deleted. You can enable the GraphQL support with thedefaultcache.allowedhttp_verbs key to define the list of supported HTTP verbs like GET, POST, DELETE.
default_cache:
allowedhttpverbs:
- GET
- POST
- HEAD
Cache invalidation
The cache invalidation is built for CRUD requests, if you're doing a GET HTTP request, it will serve the cached response when it exists, otherwise the reverse-proxy response will be served. If you're doing a POST, PUT, PATCH or DELETE HTTP request, the related cache GET request, and the list endpoint will be dropped. It also supports invalidation via Souin API to invalidate the cache programmatically.Plugins
Beego filter
To use Souin as beego filter, you can refer to the Beego filter integration folder to discover how to configure it. You just have to define a new beego router and tell to the instance to use theHandle method like below:
import (
"net/http"
httpcache "github.com/darkweak/souin/plugins/beego" )
func main(){
// ... web.InsertFilterChain("/*", httpcache.NewHTTPCacheFilter()) // ...
}
Caddy module
To use Souin as caddy module, you can refer to the Caddy module integration folder to discover how to configure it. The related Caddyfile can be found here. Then you just have to run the following command:xcaddy build --with github.com/darkweak/souin/plugins/caddy
There is the fully configuration below ```caddy { log { level debug } cache { allowedhttpverbs GET POST PATCH allowedadditionalstatus_codes 202 api { basepath /some-basepath prometheus { security } souin { security } } badger { path thepathtoafile.json } cache_name Souin cache_keys { .*\.something { disable_body disable_host disable_method disable_query disable_scheme disable_vary headers X-Token Authorization hide hash } } cdn { api_key XXXX dynamic email darkweak@protonmail.com hostname domain.com network your_network provider fastly strategy soft serviceid 123456id zoneid anywherezone } key { disable_body disable_host disable_method
README truncated. View on GitHub