⚠ Migrate TwinProduction/gatus to TwiN/gatus
This commit is contained in:
1
vendor/github.com/TwiN/gocache/.gitattributes
generated
vendored
Normal file
1
vendor/github.com/TwiN/gocache/.gitattributes
generated
vendored
Normal file
@ -0,0 +1 @@
|
||||
* text=lf
|
1
vendor/github.com/TwiN/gocache/.gitignore
generated
vendored
Normal file
1
vendor/github.com/TwiN/gocache/.gitignore
generated
vendored
Normal file
@ -0,0 +1 @@
|
||||
.idea
|
20
vendor/github.com/TwiN/gocache/Dockerfile
generated
vendored
Normal file
20
vendor/github.com/TwiN/gocache/Dockerfile
generated
vendored
Normal file
@ -0,0 +1,20 @@
|
||||
# Build the go application into a binary
|
||||
FROM golang:alpine as builder
|
||||
WORKDIR /app
|
||||
ADD . ./
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -mod vendor -a -installsuffix cgo -o bin/gocache-server cmd/server/main.go
|
||||
RUN apk --update add --no-cache ca-certificates
|
||||
|
||||
FROM scratch
|
||||
ENV APP_HOME=/app
|
||||
ENV APP_DATA=/app/data
|
||||
ENV PORT=6379
|
||||
ENV MAX_CACHE_SIZE=100000
|
||||
ENV MAX_MEMORY_USAGE=0
|
||||
ENV AUTOSAVE="false"
|
||||
VOLUME ${APP_DATA}
|
||||
WORKDIR ${APP_HOME}
|
||||
COPY --from=builder /app/bin/gocache-server ./bin/gocache-server
|
||||
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
|
||||
EXPOSE ${PORT}
|
||||
ENTRYPOINT ["/app/bin/gocache-server"]
|
9
vendor/github.com/TwiN/gocache/LICENSE.md
generated
vendored
Normal file
9
vendor/github.com/TwiN/gocache/LICENSE.md
generated
vendored
Normal file
@ -0,0 +1,9 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2021 TwiN
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
24
vendor/github.com/TwiN/gocache/Makefile
generated
vendored
Normal file
24
vendor/github.com/TwiN/gocache/Makefile
generated
vendored
Normal file
@ -0,0 +1,24 @@
|
||||
db: docker-build
|
||||
dr: docker-run
|
||||
drmem: docker-run-max-memory-usage
|
||||
|
||||
docker-build:
|
||||
docker build --tag=gocache-server .
|
||||
|
||||
docker-run:
|
||||
docker run -p 6666:6379 -e AUTOSAVE=true -e MAX_CACHE_SIZE=0 --name gocache-server -d gocache-server
|
||||
|
||||
docker-run-max-memory-usage:
|
||||
docker run -p 6666:6379 -e AUTOSAVE=true -e MAX_CACHE_SIZE=0 -e MAX_MEMORY_USAGE=524288000 --name gocache-server -d gocache-server
|
||||
|
||||
run:
|
||||
PORT=6666 go run cmd/server/main.go
|
||||
|
||||
start-redis:
|
||||
docker run -p 6379:6379 --name redis -d redis
|
||||
|
||||
redis-benchmark:
|
||||
redis-benchmark -p 6666 -t set,get -n 10000000 -r 200000 -q -P 512 -c 512
|
||||
|
||||
memtier-benchmark:
|
||||
memtier_benchmark --port 6666 --hide-histogram --key-maximum 100000 --ratio 1:1 --expiry-range 1-100 --key-pattern R:R --randomize -n 100000
|
580
vendor/github.com/TwiN/gocache/README.md
generated
vendored
Normal file
580
vendor/github.com/TwiN/gocache/README.md
generated
vendored
Normal file
@ -0,0 +1,580 @@
|
||||
# gocache
|
||||
|
||||

|
||||
[](https://goreportcard.com/report/github.com/TwiN/gocache)
|
||||
[](https://codecov.io/gh/TwiN/gocache)
|
||||
[](https://github.com/TwiN/gocache)
|
||||
[](https://pkg.go.dev/github.com/TwiN/gocache)
|
||||
[](https://github.com/TwiN)
|
||||
|
||||
gocache is an easy-to-use, high-performance, lightweight and thread-safe (goroutine-safe) in-memory key-value cache
|
||||
with support for LRU and FIFO eviction policies as well as expiration, bulk operations and even persistence to file.
|
||||
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Features](#features)
|
||||
- [Usage](#usage)
|
||||
- [Initializing the cache](#initializing-the-cache)
|
||||
- [Functions](#functions)
|
||||
- [Examples](#examples)
|
||||
- [Creating or updating an entry](#creating-or-updating-an-entry)
|
||||
- [Getting an entry](#getting-an-entry)
|
||||
- [Deleting an entry](#deleting-an-entry)
|
||||
- [Complex example](#complex-example)
|
||||
- [Persistence](#persistence)
|
||||
- [Limitations](#limitations)
|
||||
- [Eviction](#eviction)
|
||||
- [MaxSize](#maxsize)
|
||||
- [MaxMemoryUsage](#maxmemoryusage)
|
||||
- [Expiration](#expiration)
|
||||
- [Server](#server)
|
||||
- [Running the server with Docker](#running-the-server-with-docker)
|
||||
- [Performance](#performance)
|
||||
- [Summary](#summary)
|
||||
- [Results](#results)
|
||||
- [FAQ](#faq)
|
||||
- [How can I persist the data on application termination?](#how-can-i-persist-the-data-on-application-termination)
|
||||
- [How can I automatically save the cache to a file every 5 minutes?](#how-can-i-automatically-save-the-cache-to-a-file-every-5-minutes)
|
||||
- [Why does the memory usage not go down?](#why-does-the-memory-usage-not-go-down)
|
||||
|
||||
|
||||
## Features
|
||||
gocache supports the following cache eviction policies:
|
||||
- First in first out (FIFO)
|
||||
- Least recently used (LRU)
|
||||
|
||||
It also supports cache entry TTL, which is both active and passive. Active expiration means that if you attempt
|
||||
to retrieve a cache key that has already expired, it will delete it on the spot and the behavior will be as if
|
||||
the cache key didn't exist. As for passive expiration, there's a background task that will take care of deleting
|
||||
expired keys.
|
||||
|
||||
It also includes what you'd expect from a cache, like bulk operations, persistence and patterns.
|
||||
|
||||
While meant to be used as a library, there's a Redis-compatible cache server included.
|
||||
See the [Server](#server) section.
|
||||
It may also serve as a good reference to use in order to implement gocache in your own applications.
|
||||
|
||||
|
||||
## Usage
|
||||
```
|
||||
go get -u github.com/TwiN/gocache
|
||||
```
|
||||
|
||||
If you're interested in using gocache as a server rather than an embedded library, see [Server](#server)
|
||||
|
||||
|
||||
### Initializing the cache
|
||||
```go
|
||||
cache := gocache.NewCache().WithMaxSize(1000).WithEvictionPolicy(gocache.LeastRecentlyUsed)
|
||||
```
|
||||
|
||||
If you're planning on using expiration (`SetWithTTL` or `Expire`) and you want expired entries to be automatically deleted
|
||||
in the background, make sure to start the janitor when you instantiate the cache:
|
||||
|
||||
```go
|
||||
cache.StartJanitor()
|
||||
```
|
||||
|
||||
### Functions
|
||||
| Function | Description |
|
||||
| --------------------------------- | ----------- |
|
||||
| WithMaxSize | Sets the max size of the cache. `gocache.NoMaxSize` means there is no limit. If not set, the default max size is `gocache.DefaultMaxSize`.
|
||||
| WithMaxMemoryUsage | Sets the max memory usage of the cache. `gocache.NoMaxMemoryUsage` means there is no limit. The default behavior is to not evict based on memory usage.
|
||||
| WithEvictionPolicy | Sets the eviction algorithm to be used when the cache reaches the max size. If not set, the default eviction policy is `gocache.FirstInFirstOut` (FIFO).
|
||||
| WithForceNilInterfaceOnNilPointer | Configures whether values with a nil pointer passed to write functions should be forcefully set to nil. Defaults to true.
|
||||
| StartJanitor | Starts the janitor, which is in charge of deleting expired cache entries in the background.
|
||||
| StopJanitor | Stops the janitor.
|
||||
| Set | Same as `SetWithTTL`, but with no expiration (`gocache.NoExpiration`)
|
||||
| SetAll | Same as `Set`, but in bulk
|
||||
| SetWithTTL | Creates or updates a cache entry with the given key, value and expiration time. If the max size after the aforementioned operation is above the configured max size, the tail will be evicted. Depending on the eviction policy, the tail is defined as the oldest
|
||||
| Get | Gets a cache entry by its key.
|
||||
| GetByKeys | Gets a map of entries by their keys. The resulting map will contain all keys, even if some of the keys in the slice passed as parameter were not present in the cache.
|
||||
| GetAll | Gets all cache entries.
|
||||
| GetKeysByPattern | Retrieves a slice of keys that matches a given pattern.
|
||||
| Delete | Removes a key from the cache.
|
||||
| DeleteAll | Removes multiple keys from the cache.
|
||||
| Count | Gets the size of the cache. This includes cache keys which may have already expired, but have not been removed yet.
|
||||
| Clear | Wipes the cache.
|
||||
| TTL | Gets the time until a cache key expires.
|
||||
| Expire | Sets the expiration time of an existing cache key.
|
||||
| SaveToFile | Stores the content of the cache to a file so that it can be read using `ReadFromFile`. See [persistence](#persistence).
|
||||
| ReadFromFile | Populates the cache using a file created using `SaveToFile`. See [persistence](#persistence).
|
||||
|
||||
For further documentation, please refer to [Go Reference](https://pkg.go.dev/github.com/TwiN/gocache)
|
||||
|
||||
|
||||
### Examples
|
||||
|
||||
#### Creating or updating an entry
|
||||
```go
|
||||
cache.Set("key", "value")
|
||||
cache.Set("key", 1)
|
||||
cache.Set("key", struct{ Text string }{Test: "value"})
|
||||
cache.SetWithTTL("key", []byte("value"), 24*time.Hour)
|
||||
```
|
||||
|
||||
#### Getting an entry
|
||||
```go
|
||||
value, exists := cache.Get("key")
|
||||
```
|
||||
You can also get multiple entries by using `cache.GetByKeys([]string{"key1", "key2"})`
|
||||
|
||||
#### Deleting an entry
|
||||
```go
|
||||
cache.Delete("key")
|
||||
```
|
||||
You can also delete multiple entries by using `cache.DeleteAll([]string{"key1", "key2"})`
|
||||
|
||||
#### Complex example
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/TwiN/gocache"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cache := gocache.NewCache().WithEvictionPolicy(gocache.LeastRecentlyUsed).WithMaxSize(10000)
|
||||
cache.StartJanitor() // Passively manages expired entries
|
||||
|
||||
cache.Set("key", "value")
|
||||
cache.SetWithTTL("key-with-ttl", "value", 60*time.Minute)
|
||||
cache.SetAll(map[string]interface{}{"k1": "v1", "k2": "v2", "k3": "v3"})
|
||||
|
||||
value, exists := cache.Get("key")
|
||||
fmt.Printf("[Get] key=key; value=%s; exists=%v\n", value, exists)
|
||||
for key, value := range cache.GetByKeys([]string{"k1", "k2", "k3"}) {
|
||||
fmt.Printf("[GetByKeys] key=%s; value=%s\n", key, value)
|
||||
}
|
||||
for _, key := range cache.GetKeysByPattern("key*", 0) {
|
||||
fmt.Printf("[GetKeysByPattern] key=%s\n", key)
|
||||
}
|
||||
|
||||
fmt.Println("Cache size before persisting cache to file:", cache.Count())
|
||||
err := cache.SaveToFile("cache.bak")
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("failed to persist cache to file: %s", err.Error()))
|
||||
}
|
||||
|
||||
cache.Expire("key", time.Hour)
|
||||
time.Sleep(500*time.Millisecond)
|
||||
timeUntilExpiration, _ := cache.TTL("key")
|
||||
fmt.Println("Number of minutes before 'key' expires:", int(timeUntilExpiration.Seconds()))
|
||||
|
||||
cache.Delete("key")
|
||||
cache.DeleteAll([]string{"k1", "k2", "k3"})
|
||||
|
||||
fmt.Println("Cache size before restoring cache from file:", cache.Count())
|
||||
_, err = cache.ReadFromFile("cache.bak")
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("failed to restore cache from file: %s", err.Error()))
|
||||
}
|
||||
|
||||
fmt.Println("Cache size after restoring cache from file:", cache.Count())
|
||||
cache.Clear()
|
||||
fmt.Println("Cache size after clearing the cache:", cache.Count())
|
||||
}
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Output</summary>
|
||||
|
||||
```
|
||||
[Get] key=key; value=value; exists=true
|
||||
[GetByKeys] key=k2; value=v2
|
||||
[GetByKeys] key=k3; value=v3
|
||||
[GetByKeys] key=k1; value=v1
|
||||
[GetKeysByPattern] key=key
|
||||
[GetKeysByPattern] key=key-with-ttl
|
||||
Cache size before persisting cache to file: 5
|
||||
Number of minutes before 'key' expires: 3599
|
||||
Cache size before restoring cache from file: 1
|
||||
Cache size after restoring cache from file: 5
|
||||
Cache size after clearing the cache: 0
|
||||
```
|
||||
</details>
|
||||
|
||||
|
||||
## Persistence
|
||||
While gocache is an in-memory cache, you can still save the content of the cache in a file
|
||||
and vice versa.
|
||||
|
||||
To save the content of the cache to a file:
|
||||
```go
|
||||
err := cache.SaveToFile(TestCacheFile)
|
||||
```
|
||||
|
||||
To retrieve the content of the cache from a file:
|
||||
```go
|
||||
numberOfEntriesEvicted, err := newCache.ReadFromFile(TestCacheFile)
|
||||
```
|
||||
The `numberOfEntriesEvicted` will be non-zero only if the number of entries
|
||||
in the file is higher than the cache's configured `MaxSize`.
|
||||
|
||||
### Limitations
|
||||
While you can cache structs in memory out of the box, persisting structs to a file requires you to
|
||||
**register the custom interfaces that your application uses with the `gob` package**.
|
||||
|
||||
```go
|
||||
type YourCustomStruct struct {
|
||||
A string
|
||||
B int
|
||||
}
|
||||
|
||||
// ...
|
||||
cache.Set("key", YourCustomStruct{A: "test", B: 123})
|
||||
```
|
||||
To persist your custom struct properly:
|
||||
```go
|
||||
gob.Register(YourCustomStruct{})
|
||||
cache.SaveToFile("gocache.bak")
|
||||
```
|
||||
The same applies for restoring the cache from a file:
|
||||
```go
|
||||
cache := NewCache()
|
||||
gob.Register(YourCustomStruct{})
|
||||
cache.ReadFromFile(TestCacheFile)
|
||||
value, _ := cache.Get("key")
|
||||
fmt.Println(value.(YourCustomStruct))
|
||||
```
|
||||
You only need to persist the struct once, so adding the following function in a file would suffice:
|
||||
```go
|
||||
func init() {
|
||||
gob.Register(YourCustomStruct{})
|
||||
}
|
||||
```
|
||||
|
||||
Failure to register your custom structs will prevent gocache from persisting and/or parsing the value of each keys that
|
||||
use said custom structs.
|
||||
|
||||
That being said, assuming that you're using gocache as a cache, this shouldn't create any bugs on your end, because
|
||||
every key that cannot be parsed are not populated into the cache by `ReadFromFile`.
|
||||
|
||||
In other words, if you're falling back to a database or something similar when the cache doesn't have the key requested,
|
||||
you'll be fine.
|
||||
|
||||
Note that if you need to modify the type of a variable in a struct, you should change the name of that variable as well.
|
||||
For instance, if the struct has a `CreatedAt` variable with the type `time.Time` and that variable type is later
|
||||
modified to `uint64`, decoding the struct would fail, however, if you rename the variable to `CreatedAtUnixTimeInMs`,
|
||||
there won't be any decoding issues other than the loss of data for that field. You could also obviously handle the
|
||||
migration gracefully by keeping both variables, populating the `CreatedAtUnixTimeInMs` variable with the `CreatedAt`
|
||||
value and then removing the `CreatedAt` field.
|
||||
|
||||
|
||||
## Eviction
|
||||
|
||||
### MaxSize
|
||||
Eviction by MaxSize is the default behavior, and is also the most efficient.
|
||||
|
||||
The code below will create a cache that has a maximum size of 1000:
|
||||
```go
|
||||
cache := gocache.NewCache().WithMaxSize(1000)
|
||||
```
|
||||
This means that whenever an operation causes the total size of the cache to go above 1000, the tail will be evicted.
|
||||
|
||||
### MaxMemoryUsage
|
||||
Eviction by MaxMemoryUsage is **disabled by default**, and is in alpha.
|
||||
|
||||
The code below will create a cache that has a maximum memory usage of 50MB:
|
||||
```go
|
||||
cache := gocache.NewCache().WithMaxSize(0).WithMaxMemoryUsage(50*gocache.Megabyte)
|
||||
```
|
||||
This means that whenever an operation causes the total memory usage of the cache to go above 50MB, one or more tails
|
||||
will be evicted.
|
||||
|
||||
Unlike evictions caused by reaching the MaxSize, evictions triggered by MaxMemoryUsage may lead to multiple entries
|
||||
being evicted in a row. The reason for this is that if, for instance, you had 100 entries of 0.1MB each and you suddenly added
|
||||
a single entry of 10MB, 100 entries would need to be evicted to make enough space for that new big entry.
|
||||
|
||||
It's very important to keep in mind that eviction by MaxMemoryUsage is approximate.
|
||||
|
||||
**The only memory taken into consideration is the size of the cache, not the size of the entire application.**
|
||||
If you pass along 100MB worth of data in a matter of seconds, even though the cache's memory usage will remain
|
||||
under 50MB (or whatever you configure the MaxMemoryUsage to), the memory footprint generated by that 100MB will
|
||||
still exist until the next GC cycle.
|
||||
|
||||
As previously mentioned, this is a work in progress, and here's a list of the things you should keep in mind:
|
||||
- The memory usage of structs are a gross estimation and may not reflect the actual memory usage.
|
||||
- Native types (string, int, bool, []byte, etc.) are the most accurate for calculating the memory usage.
|
||||
- Adding an entry bigger than the configured MaxMemoryUsage will work, but it will evict all other entries.
|
||||
|
||||
|
||||
## Expiration
|
||||
There are two ways that the deletion of expired keys can take place:
|
||||
- Active
|
||||
- Passive
|
||||
|
||||
**Active deletion of expired keys** happens when an attempt is made to access the value of a cache entry that expired.
|
||||
`Get`, `GetByKeys` and `GetAll` are the only functions that can trigger active deletion of expired keys.
|
||||
|
||||
**Passive deletion of expired keys** runs in the background and is managed by the janitor.
|
||||
If you do not start the janitor, there will be no passive deletion of expired keys.
|
||||
|
||||
|
||||
## Server
|
||||
For the sake of convenience, a ready-to-go cache server is available through the `server` package.
|
||||
|
||||
#### As an application
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/TwiN/gocache"
|
||||
gocacheserver "github.com/TwiN/gocache/server"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cache := gocache.NewCache().WithEvictionPolicy(gocache.LeastRecentlyUsed).WithMaxSize(100000)
|
||||
server := gocacheserver.NewServer(cache).WithPort(6379)
|
||||
// This is a blocking function, therefore, you are expected to run this on a goroutine
|
||||
server.Start()
|
||||
}
|
||||
```
|
||||
|
||||
The reason why the server is in a different package is because `gocache` limit its external dependencies to the strict
|
||||
minimum (e.g. boltdb for persistence), however, rather than re-inventing the wheel, the server implementation uses
|
||||
redcon, which is a very good Redis server framework for Go.
|
||||
|
||||
That way, those who desire to use gocache without the server will not add any extra dependencies
|
||||
as long as they don't import the `server` package.
|
||||
|
||||
If you'd like to run it through the CLI:
|
||||
```
|
||||
go run cmd/server/main.go
|
||||
```
|
||||
|
||||
Any Redis client should be able to interact with the server, though only the following instructions are supported:
|
||||
- [X] GET
|
||||
- [X] SET
|
||||
- [X] DEL
|
||||
- [X] PING
|
||||
- [X] QUIT
|
||||
- [X] INFO
|
||||
- [X] EXPIRE
|
||||
- [X] SETEX
|
||||
- [X] TTL
|
||||
- [X] FLUSHDB
|
||||
- [X] EXISTS
|
||||
- [X] ECHO
|
||||
- [X] MGET
|
||||
- [X] MSET
|
||||
- [X] SCAN (kind of - cursor is not currently supported)
|
||||
- [ ] KEYS
|
||||
|
||||
|
||||
## Running the server with Docker
|
||||
[](https://cloud.docker.com/repository/docker/twinproduction/gocache-server)
|
||||
|
||||
```
|
||||
docker run --name gocache-server -p 6379:6379 twinproduction/gocache-server
|
||||
```
|
||||
|
||||
To build it locally, refer to the Makefile's `docker-build` and `docker-run` steps.
|
||||
|
||||
|
||||
## Performance
|
||||
|
||||
### Summary
|
||||
- **Set**: Both map and gocache have the same performance.
|
||||
- **Get**: Map is faster than gocache.
|
||||
|
||||
This is because gocache keeps track of the head and the tail for eviction and expiration/TTL.
|
||||
|
||||
Ultimately, the difference is negligible.
|
||||
|
||||
We could add a way to disable eviction or disable expiration altogether just to match the map's performance,
|
||||
but if you're looking into using a library like gocache, odds are, you want more than just a map.
|
||||
|
||||
|
||||
### Results
|
||||
| key | value |
|
||||
|:------ |:-------- |
|
||||
| goos | windows |
|
||||
| goarch | amd64 |
|
||||
| cpu | i7-9700K |
|
||||
| mem | 32G DDR4 |
|
||||
|
||||
```
|
||||
// Normal map
|
||||
BenchmarkMap_Get
|
||||
BenchmarkMap_Get-8 46087372 26.7 ns/op
|
||||
BenchmarkMap_Set
|
||||
BenchmarkMap_Set/small_value-8 3841911 389 ns/op
|
||||
BenchmarkMap_Set/medium_value-8 3887074 391 ns/op
|
||||
BenchmarkMap_Set/large_value-8 3921956 393 ns/op
|
||||
// Gocache
|
||||
BenchmarkCache_Get
|
||||
BenchmarkCache_Get/FirstInFirstOut-8 27273036 46.4 ns/op
|
||||
BenchmarkCache_Get/LeastRecentlyUsed-8 26648248 46.3 ns/op
|
||||
BenchmarkCache_Set
|
||||
BenchmarkCache_Set/FirstInFirstOut_small_value-8 2919584 405 ns/op
|
||||
BenchmarkCache_Set/FirstInFirstOut_medium_value-8 2990841 391 ns/op
|
||||
BenchmarkCache_Set/FirstInFirstOut_large_value-8 2970513 391 ns/op
|
||||
BenchmarkCache_Set/LeastRecentlyUsed_small_value-8 2962939 402 ns/op
|
||||
BenchmarkCache_Set/LeastRecentlyUsed_medium_value-8 2962963 390 ns/op
|
||||
BenchmarkCache_Set/LeastRecentlyUsed_large_value-8 2962928 394 ns/op
|
||||
BenchmarkCache_SetUsingMaxMemoryUsage
|
||||
BenchmarkCache_SetUsingMaxMemoryUsage/small_value-8 2683356 447 ns/op
|
||||
BenchmarkCache_SetUsingMaxMemoryUsage/medium_value-8 2637578 441 ns/op
|
||||
BenchmarkCache_SetUsingMaxMemoryUsage/large_value-8 2672434 443 ns/op
|
||||
BenchmarkCache_SetWithMaxSize
|
||||
BenchmarkCache_SetWithMaxSize/100_small_value-8 4782966 252 ns/op
|
||||
BenchmarkCache_SetWithMaxSize/10000_small_value-8 4067967 296 ns/op
|
||||
BenchmarkCache_SetWithMaxSize/100000_small_value-8 3762055 328 ns/op
|
||||
BenchmarkCache_SetWithMaxSize/100_medium_value-8 4760479 252 ns/op
|
||||
BenchmarkCache_SetWithMaxSize/10000_medium_value-8 4081050 295 ns/op
|
||||
BenchmarkCache_SetWithMaxSize/100000_medium_value-8 3785050 330 ns/op
|
||||
BenchmarkCache_SetWithMaxSize/100_large_value-8 4732909 254 ns/op
|
||||
BenchmarkCache_SetWithMaxSize/10000_large_value-8 4079533 297 ns/op
|
||||
BenchmarkCache_SetWithMaxSize/100000_large_value-8 3712820 331 ns/op
|
||||
BenchmarkCache_SetWithMaxSizeAndLRU
|
||||
BenchmarkCache_SetWithMaxSizeAndLRU/100_small_value-8 4761732 254 ns/op
|
||||
BenchmarkCache_SetWithMaxSizeAndLRU/10000_small_value-8 4084474 296 ns/op
|
||||
BenchmarkCache_SetWithMaxSizeAndLRU/100000_small_value-8 3761402 329 ns/op
|
||||
BenchmarkCache_SetWithMaxSizeAndLRU/100_medium_value-8 4783075 254 ns/op
|
||||
BenchmarkCache_SetWithMaxSizeAndLRU/10000_medium_value-8 4103980 296 ns/op
|
||||
BenchmarkCache_SetWithMaxSizeAndLRU/100000_medium_value-8 3646023 331 ns/op
|
||||
BenchmarkCache_SetWithMaxSizeAndLRU/100_large_value-8 4779025 254 ns/op
|
||||
BenchmarkCache_SetWithMaxSizeAndLRU/10000_large_value-8 4096192 296 ns/op
|
||||
BenchmarkCache_SetWithMaxSizeAndLRU/100000_large_value-8 3726823 331 ns/op
|
||||
BenchmarkCache_GetSetMultipleConcurrent
|
||||
BenchmarkCache_GetSetMultipleConcurrent-8 707142 1698 ns/op
|
||||
BenchmarkCache_GetSetConcurrentWithFrequentEviction
|
||||
BenchmarkCache_GetSetConcurrentWithFrequentEviction/FirstInFirstOut-8 3616256 334 ns/op
|
||||
BenchmarkCache_GetSetConcurrentWithFrequentEviction/LeastRecentlyUsed-8 3636367 331 ns/op
|
||||
BenchmarkCache_GetConcurrentWithLRU
|
||||
BenchmarkCache_GetConcurrentWithLRU/FirstInFirstOut-8 4405557 268 ns/op
|
||||
BenchmarkCache_GetConcurrentWithLRU/LeastRecentlyUsed-8 4445475 269 ns/op
|
||||
BenchmarkCache_WithForceNilInterfaceOnNilPointer
|
||||
BenchmarkCache_WithForceNilInterfaceOnNilPointer/true_with_nil_struct_pointer-8 6184591 191 ns/op
|
||||
BenchmarkCache_WithForceNilInterfaceOnNilPointer/true-8 6090482 191 ns/op
|
||||
BenchmarkCache_WithForceNilInterfaceOnNilPointer/false_with_nil_struct_pointer-8 6184629 187 ns/op
|
||||
BenchmarkCache_WithForceNilInterfaceOnNilPointer/false-8 6281781 186 ns/op
|
||||
(Trimmed "BenchmarkCache_" for readability)
|
||||
WithForceNilInterfaceOnNilPointerWithConcurrency
|
||||
WithForceNilInterfaceOnNilPointerWithConcurrency/true_with_nil_struct_pointer-8 4379564 268 ns/op
|
||||
WithForceNilInterfaceOnNilPointerWithConcurrency/true-8 4379558 265 ns/op
|
||||
WithForceNilInterfaceOnNilPointerWithConcurrency/false_with_nil_struct_pointer-8 4444456 261 ns/op
|
||||
WithForceNilInterfaceOnNilPointerWithConcurrency/false-8 4493896 262 ns/op
|
||||
```
|
||||
|
||||
|
||||
## FAQ
|
||||
|
||||
### How can I persist the data on application termination?
|
||||
|
||||
Because this library doesn't persist immediately after every write operations, persistence is instead expected to be
|
||||
done on a schedule, like for instance, every 10 minutes.
|
||||
|
||||
While this prevents you from losing all of your data, you may still lose some data if the application stopped 9 minutes
|
||||
after the previous "auto save".
|
||||
|
||||
To increase your odds of not losing any data, you can use Go's `signal` package, more specifically its `Notify` function
|
||||
which allows listening for termination signals like SIGTERM and SIGINT. Once a termination signal is caught, you can
|
||||
add the necessary logic for a graceful shutdown.
|
||||
|
||||
In the following example, the code that would usually be present in the `main` function is moved to a different function
|
||||
named `Start` which is launched on a different goroutine so that listening for a termination signals is what blocks the
|
||||
main goroutine instead:
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
"github.com/TwiN/gocache"
|
||||
)
|
||||
|
||||
const CacheFile = "gocache.data"
|
||||
|
||||
var cache = gocache.NewCache()
|
||||
|
||||
func main() {
|
||||
// Load persisted data from file
|
||||
cache.ReadFromFile(CacheFile)
|
||||
// Start everything else on another goroutine to prevent blocking the main goroutine
|
||||
go Start()
|
||||
// Wait for termination signal
|
||||
sig := make(chan os.Signal, 1)
|
||||
done := make(chan bool, 1)
|
||||
signal.Notify(sig, os.Interrupt, syscall.SIGTERM)
|
||||
go func() {
|
||||
<-sig
|
||||
log.Println("Received termination signal, attempting to gracefully shut down")
|
||||
err := cache.SaveToFile(CacheFile)
|
||||
if err != nil {
|
||||
log.Println("Failed to save storage provider:", err.Error())
|
||||
}
|
||||
done <- true
|
||||
}()
|
||||
<-done
|
||||
log.Println("Shutting down")
|
||||
}
|
||||
```
|
||||
|
||||
Note that this won't protect you from a SIGKILL, as this signal cannot be caught.
|
||||
|
||||
|
||||
### How can I automatically save the cache to a file every 5 minutes?
|
||||
|
||||
Beside using the suggestion above, automatically persisting the cache on an interval will protect your application from
|
||||
sudden terminations triggered by signals that cannot be caught, such as the force kill signal received by an application
|
||||
being OOMKilled.
|
||||
|
||||
The simplest implementation could be something like this:
|
||||
```go
|
||||
const CacheFile = "gocache.data"
|
||||
|
||||
func main() {
|
||||
cache := gocache.NewCache()
|
||||
cache.ReadFromFile(CacheFile)
|
||||
go autoSave(10*time.Minute)
|
||||
// ...
|
||||
}
|
||||
|
||||
func autoSave(interval time.Duration) {
|
||||
for {
|
||||
err := cache.SaveToFile(CacheFile)
|
||||
if err != nil {
|
||||
log.Println("Failed to persist cache to file:", err.Error())
|
||||
}
|
||||
time.Sleep(interval)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### Why does the memory usage not go down?
|
||||
|
||||
> **NOTE**: As of Go 1.16, this no longer applies. See [golang/go#42330](https://github.com/golang/go/issues/42330)
|
||||
|
||||
By default, Go uses `MADV_FREE` if the kernel supports it to release memory, which is significantly more efficient
|
||||
than using `MADV_DONTNEED`. Unfortunately, this means that RSS doesn't go down unless the OS actually needs the
|
||||
memory.
|
||||
|
||||
Technically, the memory _is_ available to the kernel, even if it shows a high memory usage, but the OS will only
|
||||
use that memory if it needs to. In the case that the OS does need the freed memory, the RSS will go down and you'll
|
||||
notice the memory usage lowering.
|
||||
|
||||
[reference](https://github.com/golang/go/issues/33376#issuecomment-666455792)
|
||||
|
||||
You can reproduce this by following the steps below:
|
||||
- Start the server
|
||||
- Note the memory usage
|
||||
- Create 500k keys
|
||||
- Note the memory usage
|
||||
- Flush the cache
|
||||
- Note that the memory usage has not decreased, despite the cache being empty.
|
||||
|
||||
**Substituting gocache for a normal map will yield the same result.**
|
||||
|
||||
If the released memory still appearing as used is a problem for you,
|
||||
you can set the environment variable `GODEBUG` to `madvdontneed=1`.
|
108
vendor/github.com/TwiN/gocache/entry.go
generated
vendored
Normal file
108
vendor/github.com/TwiN/gocache/entry.go
generated
vendored
Normal file
@ -0,0 +1,108 @@
|
||||
package gocache
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// Entry is a cache entry
|
||||
type Entry struct {
|
||||
// Key is the name of the cache entry
|
||||
Key string
|
||||
|
||||
// Value is the value of the cache entry
|
||||
Value interface{}
|
||||
|
||||
// RelevantTimestamp is the variable used to store either:
|
||||
// - creation timestamp, if the Cache's EvictionPolicy is FirstInFirstOut
|
||||
// - last access timestamp, if the Cache's EvictionPolicy is LeastRecentlyUsed
|
||||
//
|
||||
// Note that updating an existing entry will also update this value
|
||||
RelevantTimestamp time.Time
|
||||
|
||||
// Expiration is the unix time in nanoseconds at which the entry will expire (-1 means no expiration)
|
||||
Expiration int64
|
||||
|
||||
next *Entry
|
||||
previous *Entry
|
||||
}
|
||||
|
||||
// Accessed updates the Entry's RelevantTimestamp to now
|
||||
func (entry *Entry) Accessed() {
|
||||
entry.RelevantTimestamp = time.Now()
|
||||
}
|
||||
|
||||
// Expired returns whether the Entry has expired
|
||||
func (entry Entry) Expired() bool {
|
||||
if entry.Expiration > 0 {
|
||||
if time.Now().UnixNano() > entry.Expiration {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// SizeInBytes returns the size of an entry in bytes, approximately.
|
||||
func (entry *Entry) SizeInBytes() int {
|
||||
return toBytes(entry.Key) + toBytes(entry.Value) + 32
|
||||
}
|
||||
|
||||
func toBytes(value interface{}) int {
|
||||
switch value.(type) {
|
||||
case string:
|
||||
return int(unsafe.Sizeof(value)) + len(value.(string))
|
||||
case int8, uint8, bool:
|
||||
return int(unsafe.Sizeof(value)) + 1
|
||||
case int16, uint16:
|
||||
return int(unsafe.Sizeof(value)) + 2
|
||||
case int32, uint32, float32, complex64:
|
||||
return int(unsafe.Sizeof(value)) + 4
|
||||
case int64, uint64, int, uint, float64, complex128:
|
||||
return int(unsafe.Sizeof(value)) + 8
|
||||
case []interface{}:
|
||||
size := 0
|
||||
for _, v := range value.([]interface{}) {
|
||||
size += toBytes(v)
|
||||
}
|
||||
return int(unsafe.Sizeof(value)) + size
|
||||
case []string:
|
||||
size := 0
|
||||
for _, v := range value.([]string) {
|
||||
size += toBytes(v)
|
||||
}
|
||||
return int(unsafe.Sizeof(value)) + size
|
||||
case []int8:
|
||||
return int(unsafe.Sizeof(value)) + len(value.([]int8))
|
||||
case []uint8:
|
||||
return int(unsafe.Sizeof(value)) + len(value.([]uint8))
|
||||
case []bool:
|
||||
return int(unsafe.Sizeof(value)) + len(value.([]bool))
|
||||
case []int16:
|
||||
return int(unsafe.Sizeof(value)) + (len(value.([]int16)) * 2)
|
||||
case []uint16:
|
||||
return int(unsafe.Sizeof(value)) + (len(value.([]uint16)) * 2)
|
||||
case []int32:
|
||||
return int(unsafe.Sizeof(value)) + (len(value.([]int32)) * 4)
|
||||
case []uint32:
|
||||
return int(unsafe.Sizeof(value)) + (len(value.([]uint32)) * 4)
|
||||
case []float32:
|
||||
return int(unsafe.Sizeof(value)) + (len(value.([]float32)) * 4)
|
||||
case []complex64:
|
||||
return int(unsafe.Sizeof(value)) + (len(value.([]complex64)) * 4)
|
||||
case []int64:
|
||||
return int(unsafe.Sizeof(value)) + (len(value.([]int64)) * 8)
|
||||
case []uint64:
|
||||
return int(unsafe.Sizeof(value)) + (len(value.([]uint64)) * 8)
|
||||
case []int:
|
||||
return int(unsafe.Sizeof(value)) + (len(value.([]int)) * 8)
|
||||
case []uint:
|
||||
return int(unsafe.Sizeof(value)) + (len(value.([]uint)) * 8)
|
||||
case []float64:
|
||||
return int(unsafe.Sizeof(value)) + (len(value.([]float64)) * 8)
|
||||
case []complex128:
|
||||
return int(unsafe.Sizeof(value)) + (len(value.([]complex128)) * 8)
|
||||
default:
|
||||
return int(unsafe.Sizeof(value)) + len(fmt.Sprintf("%v", value))
|
||||
}
|
||||
}
|
567
vendor/github.com/TwiN/gocache/gocache.go
generated
vendored
Normal file
567
vendor/github.com/TwiN/gocache/gocache.go
generated
vendored
Normal file
@ -0,0 +1,567 @@
|
||||
package gocache
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"reflect"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
Debug = false
|
||||
)
|
||||
|
||||
const (
|
||||
// NoMaxSize means that the cache has no maximum number of entries in the cache
|
||||
// Setting Cache.maxSize to this value also means there will be no eviction
|
||||
NoMaxSize = 0
|
||||
|
||||
// NoMaxMemoryUsage means that the cache has no maximum number of entries in the cache
|
||||
NoMaxMemoryUsage = 0
|
||||
|
||||
// DefaultMaxSize is the max size set if no max size is specified
|
||||
DefaultMaxSize = 100000
|
||||
|
||||
// NoExpiration is the value that must be used as TTL to specify that the given key should never expire
|
||||
NoExpiration = -1
|
||||
|
||||
Kilobyte = 1024
|
||||
Megabyte = 1024 * Kilobyte
|
||||
Gigabyte = 1024 * Megabyte
|
||||
)
|
||||
|
||||
var (
|
||||
ErrKeyDoesNotExist = errors.New("key does not exist") // Returned when a cache key does not exist
|
||||
ErrKeyHasNoExpiration = errors.New("key has no expiration") // Returned when a cache key has no expiration
|
||||
ErrJanitorAlreadyRunning = errors.New("janitor is already running") // Returned when the janitor has already been started
|
||||
)
|
||||
|
||||
// Cache is the core struct of gocache which contains the data as well as all relevant configuration fields
|
||||
type Cache struct {
|
||||
// maxSize is the maximum amount of entries that can be in the cache at any given time
|
||||
// By default, this is set to DefaultMaxSize
|
||||
maxSize int
|
||||
|
||||
// maxMemoryUsage is the maximum amount of memory that can be taken up by the cache at any time
|
||||
// By default, this is set to NoMaxMemoryUsage, meaning that the default behavior is to not evict
|
||||
// based on maximum memory usage
|
||||
maxMemoryUsage int
|
||||
|
||||
// evictionPolicy is the eviction policy
|
||||
evictionPolicy EvictionPolicy
|
||||
|
||||
// stats is the object that contains cache statistics/metrics
|
||||
stats *Statistics
|
||||
|
||||
// entries is the content of the cache
|
||||
entries map[string]*Entry
|
||||
|
||||
// mutex is the lock for making concurrent operations on the cache
|
||||
mutex sync.RWMutex
|
||||
|
||||
// head is the cache entry at the head of the cache
|
||||
head *Entry
|
||||
|
||||
// tail is the last cache node and also the next entry that will be evicted
|
||||
tail *Entry
|
||||
|
||||
// stopJanitor is the channel used to stop the janitor
|
||||
stopJanitor chan bool
|
||||
|
||||
// memoryUsage is the approximate memory usage of the cache (dataset only) in bytes
|
||||
memoryUsage int
|
||||
|
||||
// forceNilInterfaceOnNilPointer determines whether all Set-like functions should set a value as nil if the
|
||||
// interface passed has a nil value but not a nil type.
|
||||
//
|
||||
// By default, interfaces are only nil when both their type and value is nil.
|
||||
// This means that when you pass a pointer to a nil value, the type of the interface
|
||||
// will still show as nil, which means that if you don't cast the interface after
|
||||
// retrieving it, a nil check will return that the value is not false.
|
||||
forceNilInterfaceOnNilPointer bool
|
||||
}
|
||||
|
||||
// MaxSize returns the maximum amount of keys that can be present in the cache before
|
||||
// new entries trigger the eviction of the tail
|
||||
func (cache *Cache) MaxSize() int {
|
||||
return cache.maxSize
|
||||
}
|
||||
|
||||
// MaxMemoryUsage returns the configured maxMemoryUsage of the cache
|
||||
func (cache *Cache) MaxMemoryUsage() int {
|
||||
return cache.maxMemoryUsage
|
||||
}
|
||||
|
||||
// EvictionPolicy returns the EvictionPolicy of the Cache
|
||||
func (cache *Cache) EvictionPolicy() EvictionPolicy {
|
||||
return cache.evictionPolicy
|
||||
}
|
||||
|
||||
// Stats returns statistics from the cache
|
||||
func (cache *Cache) Stats() Statistics {
|
||||
cache.mutex.RLock()
|
||||
stats := Statistics{
|
||||
EvictedKeys: cache.stats.EvictedKeys,
|
||||
ExpiredKeys: cache.stats.ExpiredKeys,
|
||||
Hits: cache.stats.Hits,
|
||||
Misses: cache.stats.Misses,
|
||||
}
|
||||
cache.mutex.RUnlock()
|
||||
return stats
|
||||
}
|
||||
|
||||
// MemoryUsage returns the current memory usage of the cache's dataset in bytes
|
||||
// If MaxMemoryUsage is set to NoMaxMemoryUsage, this will return 0
|
||||
func (cache *Cache) MemoryUsage() int {
|
||||
return cache.memoryUsage
|
||||
}
|
||||
|
||||
// WithMaxSize sets the maximum amount of entries that can be in the cache at any given time
|
||||
// A maxSize of 0 or less means infinite
|
||||
func (cache *Cache) WithMaxSize(maxSize int) *Cache {
|
||||
if maxSize < 0 {
|
||||
maxSize = NoMaxSize
|
||||
}
|
||||
if maxSize != NoMaxSize && cache.Count() == 0 {
|
||||
cache.entries = make(map[string]*Entry, maxSize)
|
||||
}
|
||||
cache.maxSize = maxSize
|
||||
return cache
|
||||
}
|
||||
|
||||
// WithMaxMemoryUsage sets the maximum amount of memory that can be used by the cache at any given time
|
||||
//
|
||||
// NOTE: This is approximate.
|
||||
//
|
||||
// Setting this to NoMaxMemoryUsage will disable eviction by memory usage
|
||||
func (cache *Cache) WithMaxMemoryUsage(maxMemoryUsageInBytes int) *Cache {
|
||||
if maxMemoryUsageInBytes < 0 {
|
||||
maxMemoryUsageInBytes = NoMaxMemoryUsage
|
||||
}
|
||||
cache.maxMemoryUsage = maxMemoryUsageInBytes
|
||||
return cache
|
||||
}
|
||||
|
||||
// WithEvictionPolicy sets eviction algorithm.
|
||||
// Defaults to FirstInFirstOut (FIFO)
|
||||
func (cache *Cache) WithEvictionPolicy(policy EvictionPolicy) *Cache {
|
||||
cache.evictionPolicy = policy
|
||||
return cache
|
||||
}
|
||||
|
||||
// WithForceNilInterfaceOnNilPointer sets whether all Set-like functions should set a value as nil if the
|
||||
// interface passed has a nil value but not a nil type.
|
||||
//
|
||||
// In Go, an interface is only nil if both its type and value are nil, which means that a nil pointer
|
||||
// (e.g. (*Struct)(nil)) will retain its attribution to the type, and the unmodified value returned from
|
||||
// Cache.Get, for instance, would return false when compared with nil if this option is set to false.
|
||||
//
|
||||
// We can bypass this by detecting if the interface's value is nil and setting it to nil rather than
|
||||
// a nil pointer, which will make the value returned from Cache.Get return true when compared with nil.
|
||||
// This is exactly what passing true to WithForceNilInterfaceOnNilPointer does, and it's also the default behavior.
|
||||
//
|
||||
// Alternatively, you may pass false to WithForceNilInterfaceOnNilPointer, which will mean that you'll have
|
||||
// to cast the value returned from Cache.Get to its original type to check for whether the pointer returned
|
||||
// is nil or not.
|
||||
//
|
||||
// If set to true:
|
||||
// cache := gocache.NewCache().WithForceNilInterfaceOnNilPointer(true)
|
||||
// cache.Set("key", (*Struct)(nil))
|
||||
// value, _ := cache.Get("key")
|
||||
// // the following returns true, because the interface{} was forcefully set to nil
|
||||
// if value == nil {}
|
||||
// // the following will panic, because the value has been casted to its type (which is nil)
|
||||
// if value.(*Struct) == nil {}
|
||||
//
|
||||
// If set to false:
|
||||
// cache := gocache.NewCache().WithForceNilInterfaceOnNilPointer(false)
|
||||
// cache.Set("key", (*Struct)(nil))
|
||||
// value, _ := cache.Get("key")
|
||||
// // the following returns false, because the interface{} returned has a non-nil type (*Struct)
|
||||
// if value == nil {}
|
||||
// // the following returns true, because the value has been casted to its type
|
||||
// if value.(*Struct) == nil {}
|
||||
//
|
||||
// In other words, if set to true, you do not need to cast the value returned from the cache to
|
||||
// to check if the value is nil.
|
||||
//
|
||||
// Defaults to true
|
||||
func (cache *Cache) WithForceNilInterfaceOnNilPointer(forceNilInterfaceOnNilPointer bool) *Cache {
|
||||
cache.forceNilInterfaceOnNilPointer = forceNilInterfaceOnNilPointer
|
||||
return cache
|
||||
}
|
||||
|
||||
// NewCache creates a new Cache
|
||||
//
|
||||
// Should be used in conjunction with Cache.WithMaxSize, Cache.WithMaxMemoryUsage and/or Cache.WithEvictionPolicy
|
||||
// gocache.NewCache().WithMaxSize(10000).WithEvictionPolicy(gocache.LeastRecentlyUsed)
|
||||
//
|
||||
func NewCache() *Cache {
|
||||
return &Cache{
|
||||
maxSize: DefaultMaxSize,
|
||||
evictionPolicy: FirstInFirstOut,
|
||||
stats: &Statistics{},
|
||||
entries: make(map[string]*Entry),
|
||||
mutex: sync.RWMutex{},
|
||||
stopJanitor: nil,
|
||||
forceNilInterfaceOnNilPointer: true,
|
||||
}
|
||||
}
|
||||
|
||||
// Set creates or updates a key with a given value
|
||||
func (cache *Cache) Set(key string, value interface{}) {
|
||||
cache.SetWithTTL(key, value, NoExpiration)
|
||||
}
|
||||
|
||||
// SetWithTTL creates or updates a key with a given value and sets an expiration time (-1 is NoExpiration)
|
||||
//
|
||||
// The TTL provided must be greater than 0, or NoExpiration (-1). If a negative value that isn't -1 (NoExpiration) is
|
||||
// provided, the entry will not be created if the key doesn't exist
|
||||
func (cache *Cache) SetWithTTL(key string, value interface{}, ttl time.Duration) {
|
||||
// An interface is only nil if both its value and its type are nil, however, passing a nil pointer as an interface{}
|
||||
// means that the interface itself is not nil, because the interface value is nil but not the type.
|
||||
if cache.forceNilInterfaceOnNilPointer {
|
||||
if value != nil && (reflect.ValueOf(value).Kind() == reflect.Ptr && reflect.ValueOf(value).IsNil()) {
|
||||
value = nil
|
||||
}
|
||||
}
|
||||
cache.mutex.Lock()
|
||||
entry, ok := cache.get(key)
|
||||
if !ok {
|
||||
// A negative TTL that isn't -1 (NoExpiration) or 0 is an entry that will expire instantly,
|
||||
// so might as well just not create it in the first place
|
||||
if ttl != NoExpiration && ttl < 1 {
|
||||
cache.mutex.Unlock()
|
||||
return
|
||||
}
|
||||
// Cache entry doesn't exist, so we have to create a new one
|
||||
entry = &Entry{
|
||||
Key: key,
|
||||
Value: value,
|
||||
RelevantTimestamp: time.Now(),
|
||||
next: cache.head,
|
||||
}
|
||||
if cache.head == nil {
|
||||
cache.tail = entry
|
||||
} else {
|
||||
cache.head.previous = entry
|
||||
}
|
||||
cache.head = entry
|
||||
cache.entries[key] = entry
|
||||
if cache.maxMemoryUsage != NoMaxMemoryUsage {
|
||||
cache.memoryUsage += entry.SizeInBytes()
|
||||
}
|
||||
} else {
|
||||
// A negative TTL that isn't -1 (NoExpiration) or 0 is an entry that will expire instantly,
|
||||
// so might as well just delete it immediately instead of updating it
|
||||
if ttl != NoExpiration && ttl < 1 {
|
||||
cache.delete(key)
|
||||
cache.mutex.Unlock()
|
||||
return
|
||||
}
|
||||
if cache.maxMemoryUsage != NoMaxMemoryUsage {
|
||||
// Subtract the old entry from the cache's memoryUsage
|
||||
cache.memoryUsage -= entry.SizeInBytes()
|
||||
}
|
||||
// Update existing entry's value
|
||||
entry.Value = value
|
||||
entry.RelevantTimestamp = time.Now()
|
||||
if cache.maxMemoryUsage != NoMaxMemoryUsage {
|
||||
// Add the memory usage of the new entry to the cache's memoryUsage
|
||||
cache.memoryUsage += entry.SizeInBytes()
|
||||
}
|
||||
// Because we just updated the entry, we need to move it back to HEAD
|
||||
cache.moveExistingEntryToHead(entry)
|
||||
}
|
||||
if ttl != NoExpiration {
|
||||
entry.Expiration = time.Now().Add(ttl).UnixNano()
|
||||
} else {
|
||||
entry.Expiration = NoExpiration
|
||||
}
|
||||
// If the cache doesn't have a maxSize/maxMemoryUsage, then there's no point
|
||||
// checking if we need to evict an entry, so we'll just return now
|
||||
if cache.maxSize == NoMaxSize && cache.maxMemoryUsage == NoMaxMemoryUsage {
|
||||
cache.mutex.Unlock()
|
||||
return
|
||||
}
|
||||
// If there's a maxSize and the cache has more entries than the maxSize, evict
|
||||
if cache.maxSize != NoMaxSize && len(cache.entries) > cache.maxSize {
|
||||
cache.evict()
|
||||
}
|
||||
// If there's a maxMemoryUsage and the memoryUsage is above the maxMemoryUsage, evict
|
||||
if cache.maxMemoryUsage != NoMaxMemoryUsage && cache.memoryUsage > cache.maxMemoryUsage {
|
||||
for cache.memoryUsage > cache.maxMemoryUsage && len(cache.entries) > 0 {
|
||||
cache.evict()
|
||||
}
|
||||
}
|
||||
cache.mutex.Unlock()
|
||||
}
|
||||
|
||||
// SetAll creates or updates multiple values
|
||||
func (cache *Cache) SetAll(entries map[string]interface{}) {
|
||||
for key, value := range entries {
|
||||
cache.SetWithTTL(key, value, NoExpiration)
|
||||
}
|
||||
}
|
||||
|
||||
// Get retrieves an entry using the key passed as parameter
|
||||
// If there is no such entry, the value returned will be nil and the boolean will be false
|
||||
// If there is an entry, the value returned will be the value cached and the boolean will be true
|
||||
func (cache *Cache) Get(key string) (interface{}, bool) {
|
||||
cache.mutex.Lock()
|
||||
entry, ok := cache.get(key)
|
||||
if !ok {
|
||||
cache.mutex.Unlock()
|
||||
cache.stats.Misses++
|
||||
return nil, false
|
||||
}
|
||||
if entry.Expired() {
|
||||
cache.stats.ExpiredKeys++
|
||||
cache.delete(key)
|
||||
cache.mutex.Unlock()
|
||||
return nil, false
|
||||
}
|
||||
cache.stats.Hits++
|
||||
if cache.evictionPolicy == LeastRecentlyUsed {
|
||||
entry.Accessed()
|
||||
if cache.head == entry {
|
||||
cache.mutex.Unlock()
|
||||
return entry.Value, true
|
||||
}
|
||||
// Because the eviction policy is LRU, we need to move the entry back to HEAD
|
||||
cache.moveExistingEntryToHead(entry)
|
||||
}
|
||||
cache.mutex.Unlock()
|
||||
return entry.Value, true
|
||||
}
|
||||
|
||||
// GetValue retrieves an entry using the key passed as parameter
|
||||
// Unlike Get, this function only returns the value
|
||||
func (cache *Cache) GetValue(key string) interface{} {
|
||||
value, _ := cache.Get(key)
|
||||
return value
|
||||
}
|
||||
|
||||
// GetByKeys retrieves multiple entries using the keys passed as parameter
|
||||
// All keys are returned in the map, regardless of whether they exist or not, however, entries that do not exist in the
|
||||
// cache will return nil, meaning that there is no way of determining whether a key genuinely has the value nil, or
|
||||
// whether it doesn't exist in the cache using only this function.
|
||||
func (cache *Cache) GetByKeys(keys []string) map[string]interface{} {
|
||||
entries := make(map[string]interface{})
|
||||
for _, key := range keys {
|
||||
entries[key], _ = cache.Get(key)
|
||||
}
|
||||
return entries
|
||||
}
|
||||
|
||||
// GetAll retrieves all cache entries
|
||||
//
|
||||
// If the eviction policy is LeastRecentlyUsed, note that unlike Get and GetByKeys, this does not update the last access
|
||||
// timestamp. The reason for this is that since all cache entries will be accessed, updating the last access timestamp
|
||||
// would provide very little benefit while harming the ability to accurately determine the next key that will be evicted
|
||||
//
|
||||
// You should probably avoid using this if you have a lot of entries.
|
||||
//
|
||||
// GetKeysByPattern is a good alternative if you want to retrieve entries that you do not have the key for, as it only
|
||||
// retrieves the keys and does not trigger active eviction and has a parameter for setting a limit to the number of keys
|
||||
// you wish to retrieve.
|
||||
func (cache *Cache) GetAll() map[string]interface{} {
|
||||
entries := make(map[string]interface{})
|
||||
cache.mutex.Lock()
|
||||
for key, entry := range cache.entries {
|
||||
if entry.Expired() {
|
||||
cache.delete(key)
|
||||
continue
|
||||
}
|
||||
entries[key] = entry.Value
|
||||
}
|
||||
cache.stats.Hits += uint64(len(entries))
|
||||
cache.mutex.Unlock()
|
||||
return entries
|
||||
}
|
||||
|
||||
// GetKeysByPattern retrieves a slice of keys that match a given pattern
|
||||
// If the limit is set to 0, the entire cache will be searched for matching keys.
|
||||
// If the limit is above 0, the search will stop once the specified number of matching keys have been found.
|
||||
//
|
||||
// e.g.
|
||||
// cache.GetKeysByPattern("*some*", 0) will return all keys containing "some" in them
|
||||
// cache.GetKeysByPattern("*some*", 5) will return 5 keys (or less) containing "some" in them
|
||||
//
|
||||
// Note that GetKeysByPattern does not trigger active evictions, nor does it count as accessing the entry, the latter
|
||||
// only applying if the cache uses the LeastRecentlyUsed eviction policy.
|
||||
// The reason for that behavior is that these two (active eviction and access) only applies when you access the value
|
||||
// of the cache entry, and this function only returns the keys.
|
||||
func (cache *Cache) GetKeysByPattern(pattern string, limit int) []string {
|
||||
var matchingKeys []string
|
||||
cache.mutex.Lock()
|
||||
for key, value := range cache.entries {
|
||||
if value.Expired() {
|
||||
continue
|
||||
}
|
||||
if MatchPattern(pattern, key) {
|
||||
matchingKeys = append(matchingKeys, key)
|
||||
if limit > 0 && len(matchingKeys) >= limit {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
cache.mutex.Unlock()
|
||||
return matchingKeys
|
||||
}
|
||||
|
||||
// Delete removes a key from the cache
|
||||
//
|
||||
// Returns false if the key did not exist.
|
||||
func (cache *Cache) Delete(key string) bool {
|
||||
cache.mutex.Lock()
|
||||
ok := cache.delete(key)
|
||||
cache.mutex.Unlock()
|
||||
return ok
|
||||
}
|
||||
|
||||
// DeleteAll deletes multiple entries based on the keys passed as parameter
|
||||
//
|
||||
// Returns the number of keys deleted
|
||||
func (cache *Cache) DeleteAll(keys []string) int {
|
||||
numberOfKeysDeleted := 0
|
||||
cache.mutex.Lock()
|
||||
for _, key := range keys {
|
||||
if cache.delete(key) {
|
||||
numberOfKeysDeleted++
|
||||
}
|
||||
}
|
||||
cache.mutex.Unlock()
|
||||
return numberOfKeysDeleted
|
||||
}
|
||||
|
||||
// Count returns the total amount of entries in the cache, regardless of whether they're expired or not
|
||||
func (cache *Cache) Count() int {
|
||||
cache.mutex.RLock()
|
||||
count := len(cache.entries)
|
||||
cache.mutex.RUnlock()
|
||||
return count
|
||||
}
|
||||
|
||||
// Clear deletes all entries from the cache
|
||||
func (cache *Cache) Clear() {
|
||||
cache.mutex.Lock()
|
||||
cache.entries = make(map[string]*Entry)
|
||||
cache.memoryUsage = 0
|
||||
cache.head = nil
|
||||
cache.tail = nil
|
||||
cache.mutex.Unlock()
|
||||
}
|
||||
|
||||
// TTL returns the time until the cache entry specified by the key passed as parameter
|
||||
// will be deleted.
|
||||
func (cache *Cache) TTL(key string) (time.Duration, error) {
|
||||
cache.mutex.RLock()
|
||||
entry, ok := cache.get(key)
|
||||
cache.mutex.RUnlock()
|
||||
if !ok {
|
||||
return 0, ErrKeyDoesNotExist
|
||||
}
|
||||
if entry.Expiration == NoExpiration {
|
||||
return 0, ErrKeyHasNoExpiration
|
||||
}
|
||||
timeUntilExpiration := time.Until(time.Unix(0, entry.Expiration))
|
||||
if timeUntilExpiration < 0 {
|
||||
// The key has already expired but hasn't been deleted yet.
|
||||
// From the client's perspective, this means that the cache entry doesn't exist
|
||||
return 0, ErrKeyDoesNotExist
|
||||
}
|
||||
return timeUntilExpiration, nil
|
||||
}
|
||||
|
||||
// Expire sets a key's expiration time
|
||||
//
|
||||
// A TTL of -1 means that the key will never expire
|
||||
// A TTL of 0 means that the key will expire immediately
|
||||
// If using LRU, note that this does not reset the position of the key
|
||||
//
|
||||
// Returns true if the cache key exists and has had its expiration time altered
|
||||
func (cache *Cache) Expire(key string, ttl time.Duration) bool {
|
||||
entry, ok := cache.get(key)
|
||||
if !ok || entry.Expired() {
|
||||
return false
|
||||
}
|
||||
if ttl != NoExpiration {
|
||||
entry.Expiration = time.Now().Add(ttl).UnixNano()
|
||||
} else {
|
||||
entry.Expiration = NoExpiration
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// get retrieves an entry using the key passed as parameter, but unlike Get, it doesn't update the access time or
|
||||
// move the position of the entry to the head
|
||||
func (cache *Cache) get(key string) (*Entry, bool) {
|
||||
entry, ok := cache.entries[key]
|
||||
return entry, ok
|
||||
}
|
||||
|
||||
func (cache *Cache) delete(key string) bool {
|
||||
entry, ok := cache.entries[key]
|
||||
if ok {
|
||||
if cache.maxMemoryUsage != NoMaxMemoryUsage {
|
||||
cache.memoryUsage -= entry.SizeInBytes()
|
||||
}
|
||||
cache.removeExistingEntryReferences(entry)
|
||||
delete(cache.entries, key)
|
||||
}
|
||||
return ok
|
||||
}
|
||||
|
||||
// moveExistingEntryToHead replaces the current cache head for an existing entry
|
||||
func (cache *Cache) moveExistingEntryToHead(entry *Entry) {
|
||||
if !(entry == cache.head && entry == cache.tail) {
|
||||
cache.removeExistingEntryReferences(entry)
|
||||
}
|
||||
if entry != cache.head {
|
||||
entry.next = cache.head
|
||||
entry.previous = nil
|
||||
if cache.head != nil {
|
||||
cache.head.previous = entry
|
||||
}
|
||||
cache.head = entry
|
||||
}
|
||||
}
|
||||
|
||||
// removeExistingEntryReferences modifies the next and previous reference of an existing entry and re-links
|
||||
// the next and previous entry accordingly, as well as the cache head or/and the cache tail if necessary.
|
||||
// Note that it does not remove the entry from the cache, only the references.
|
||||
func (cache *Cache) removeExistingEntryReferences(entry *Entry) {
|
||||
if cache.tail == entry && cache.head == entry {
|
||||
cache.tail = nil
|
||||
cache.head = nil
|
||||
} else if cache.tail == entry {
|
||||
cache.tail = cache.tail.previous
|
||||
} else if cache.head == entry {
|
||||
cache.head = cache.head.next
|
||||
}
|
||||
if entry.previous != nil {
|
||||
entry.previous.next = entry.next
|
||||
}
|
||||
if entry.next != nil {
|
||||
entry.next.previous = entry.previous
|
||||
}
|
||||
entry.next = nil
|
||||
entry.previous = nil
|
||||
}
|
||||
|
||||
// evict removes the tail from the cache
|
||||
func (cache *Cache) evict() {
|
||||
if cache.tail == nil || len(cache.entries) == 0 {
|
||||
return
|
||||
}
|
||||
if cache.tail != nil {
|
||||
oldTail := cache.tail
|
||||
cache.removeExistingEntryReferences(oldTail)
|
||||
delete(cache.entries, oldTail.Key)
|
||||
if cache.maxMemoryUsage != NoMaxMemoryUsage {
|
||||
cache.memoryUsage -= oldTail.SizeInBytes()
|
||||
}
|
||||
cache.stats.EvictedKeys++
|
||||
}
|
||||
}
|
141
vendor/github.com/TwiN/gocache/janitor.go
generated
vendored
Normal file
141
vendor/github.com/TwiN/gocache/janitor.go
generated
vendored
Normal file
@ -0,0 +1,141 @@
|
||||
package gocache
|
||||
|
||||
import (
|
||||
"log"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
// JanitorShiftTarget is the target number of expired keys to find during passive clean up duty
|
||||
// before pausing the passive expired keys eviction process
|
||||
JanitorShiftTarget = 25
|
||||
|
||||
// JanitorMaxIterationsPerShift is the maximum number of nodes to traverse before pausing
|
||||
JanitorMaxIterationsPerShift = 1000
|
||||
|
||||
// JanitorMinShiftBackOff is the minimum interval between each iteration of steps
|
||||
// defined by JanitorMaxIterationsPerShift
|
||||
JanitorMinShiftBackOff = time.Millisecond * 50
|
||||
|
||||
// JanitorMaxShiftBackOff is the maximum interval between each iteration of steps
|
||||
// defined by JanitorMaxIterationsPerShift
|
||||
JanitorMaxShiftBackOff = time.Millisecond * 500
|
||||
)
|
||||
|
||||
// StartJanitor starts the janitor on a different goroutine
|
||||
// The janitor's job is to delete expired keys in the background, in other words, it takes care of passive eviction.
|
||||
// It can be stopped by calling Cache.StopJanitor.
|
||||
// If you do not start the janitor, expired keys will only be deleted when they are accessed through Get, GetByKeys, or
|
||||
// GetAll.
|
||||
func (cache *Cache) StartJanitor() error {
|
||||
if cache.stopJanitor != nil {
|
||||
return ErrJanitorAlreadyRunning
|
||||
}
|
||||
cache.stopJanitor = make(chan bool)
|
||||
go func() {
|
||||
// rather than starting from the tail on every run, we can try to start from the last traversed entry
|
||||
var lastTraversedNode *Entry
|
||||
totalNumberOfExpiredKeysInPreviousRunFromTailToHead := 0
|
||||
backOff := JanitorMinShiftBackOff
|
||||
for {
|
||||
select {
|
||||
case <-time.After(backOff):
|
||||
// Passive clean up duty
|
||||
cache.mutex.Lock()
|
||||
if cache.tail != nil {
|
||||
start := time.Now()
|
||||
steps := 0
|
||||
expiredEntriesFound := 0
|
||||
current := cache.tail
|
||||
if lastTraversedNode != nil {
|
||||
// Make sure the lastTraversedNode is still in the cache, otherwise we might be traversing nodes that were already deleted.
|
||||
// Furthermore, we need to make sure that the entry from the cache has the same pointer as the lastTraversedNode
|
||||
// to verify that there isn't just a new cache entry with the same key (i.e. in case lastTraversedNode got evicted)
|
||||
if entryFromCache, isInCache := cache.get(lastTraversedNode.Key); isInCache && entryFromCache == lastTraversedNode {
|
||||
current = lastTraversedNode
|
||||
}
|
||||
}
|
||||
if current == cache.tail {
|
||||
if Debug {
|
||||
log.Printf("There are currently %d entries in the cache. The last walk resulted in finding %d expired keys", len(cache.entries), totalNumberOfExpiredKeysInPreviousRunFromTailToHead)
|
||||
}
|
||||
totalNumberOfExpiredKeysInPreviousRunFromTailToHead = 0
|
||||
}
|
||||
for current != nil {
|
||||
// since we're walking from the tail to the head, we get the previous reference
|
||||
var previous *Entry
|
||||
steps++
|
||||
if current.Expired() {
|
||||
expiredEntriesFound++
|
||||
// Because delete will remove the previous reference from the entry, we need to store the
|
||||
// previous reference before we delete it
|
||||
previous = current.previous
|
||||
cache.delete(current.Key)
|
||||
cache.stats.ExpiredKeys++
|
||||
}
|
||||
if current == cache.head {
|
||||
lastTraversedNode = nil
|
||||
break
|
||||
}
|
||||
// Travel to the current node's previous node only if no specific previous node has been specified
|
||||
if previous != nil {
|
||||
current = previous
|
||||
} else {
|
||||
current = current.previous
|
||||
}
|
||||
lastTraversedNode = current
|
||||
if steps == JanitorMaxIterationsPerShift || expiredEntriesFound >= JanitorShiftTarget {
|
||||
if expiredEntriesFound > 0 {
|
||||
backOff = JanitorMinShiftBackOff
|
||||
} else {
|
||||
if backOff*2 <= JanitorMaxShiftBackOff {
|
||||
backOff *= 2
|
||||
} else {
|
||||
backOff = JanitorMaxShiftBackOff
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
if Debug {
|
||||
log.Printf("traversed %d nodes and found %d expired entries in %s before stopping\n", steps, expiredEntriesFound, time.Since(start))
|
||||
}
|
||||
totalNumberOfExpiredKeysInPreviousRunFromTailToHead += expiredEntriesFound
|
||||
} else {
|
||||
if backOff*2 < JanitorMaxShiftBackOff {
|
||||
backOff *= 2
|
||||
} else {
|
||||
backOff = JanitorMaxShiftBackOff
|
||||
}
|
||||
}
|
||||
cache.mutex.Unlock()
|
||||
case <-cache.stopJanitor:
|
||||
cache.stopJanitor <- true
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
//if Debug {
|
||||
// go func() {
|
||||
// var m runtime.MemStats
|
||||
// for {
|
||||
// runtime.ReadMemStats(&m)
|
||||
// log.Printf("Alloc=%vMB; HeapReleased=%vMB; Sys=%vMB; HeapInUse=%vMB; HeapObjects=%v; HeapObjectsFreed=%v; GC=%v; cache.memoryUsage=%vMB; cacheSize=%d\n", m.Alloc/1024/1024, m.HeapReleased/1024/1024, m.Sys/1024/1024, m.HeapInuse/1024/1024, m.HeapObjects, m.Frees, m.NumGC, cache.memoryUsage/1024/1024, cache.Count())
|
||||
// time.Sleep(3 * time.Second)
|
||||
// }
|
||||
// }()
|
||||
//}
|
||||
return nil
|
||||
}
|
||||
|
||||
// StopJanitor stops the janitor
|
||||
func (cache *Cache) StopJanitor() {
|
||||
if cache.stopJanitor != nil {
|
||||
// Tell the janitor to stop, and then wait for the janitor to reply on the same channel that it's stopping
|
||||
// This may seem a bit odd, but this allows us to avoid a data race condition when trying to set
|
||||
// cache.stopJanitor to nil
|
||||
cache.stopJanitor <- true
|
||||
<-cache.stopJanitor
|
||||
cache.stopJanitor = nil
|
||||
}
|
||||
}
|
12
vendor/github.com/TwiN/gocache/pattern.go
generated
vendored
Normal file
12
vendor/github.com/TwiN/gocache/pattern.go
generated
vendored
Normal file
@ -0,0 +1,12 @@
|
||||
package gocache
|
||||
|
||||
import "path/filepath"
|
||||
|
||||
// MatchPattern checks whether a string matches a pattern
|
||||
func MatchPattern(pattern, s string) bool {
|
||||
if pattern == "*" {
|
||||
return true
|
||||
}
|
||||
matched, _ := filepath.Match(pattern, s)
|
||||
return matched
|
||||
}
|
154
vendor/github.com/TwiN/gocache/persistence.go
generated
vendored
Normal file
154
vendor/github.com/TwiN/gocache/persistence.go
generated
vendored
Normal file
@ -0,0 +1,154 @@
|
||||
package gocache
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/gob"
|
||||
"log"
|
||||
"os"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
bolt "go.etcd.io/bbolt"
|
||||
)
|
||||
|
||||
// SaveToFile stores the content of the cache to a file so that it can be read using
|
||||
// the ReadFromFile function
|
||||
func (cache *Cache) SaveToFile(path string) error {
|
||||
db, err := bolt.Open(path, os.ModePerm, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
start := time.Now()
|
||||
cache.mutex.RLock()
|
||||
bulkEntries := make([]*Entry, len(cache.entries))
|
||||
i := 0
|
||||
for _, v := range cache.entries {
|
||||
bulkEntries[i] = v
|
||||
i++
|
||||
}
|
||||
cache.mutex.RUnlock()
|
||||
if Debug {
|
||||
log.Printf("unlocked after %s", time.Since(start))
|
||||
}
|
||||
err = db.Update(func(tx *bolt.Tx) error {
|
||||
_ = tx.DeleteBucket([]byte("entries"))
|
||||
bucket, err := tx.CreateBucket([]byte("entries"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, bulkEntry := range bulkEntries {
|
||||
buffer := bytes.Buffer{}
|
||||
err = gob.NewEncoder(&buffer).Encode(bulkEntry)
|
||||
if err != nil {
|
||||
// Failed to encode the value, so we'll skip it.
|
||||
// This is likely due to the fact that the custom struct wasn't registered using gob.Register(...)
|
||||
// See [Persistence - Limitations](https://github.com/TwiN/gocache#limitations)
|
||||
continue
|
||||
}
|
||||
bucket.Put([]byte(bulkEntry.Key), buffer.Bytes())
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return db.Close()
|
||||
}
|
||||
|
||||
// ReadFromFile populates the cache using a file created using cache.SaveToFile(path)
|
||||
//
|
||||
// Note that if the number of entries retrieved from the file exceed the configured maxSize,
|
||||
// the extra entries will be automatically evicted according to the EvictionPolicy configured.
|
||||
// This function returns the number of entries evicted, and because this function only reads
|
||||
// from a file and does not modify it, you can safely retry this function after configuring
|
||||
// the cache with the appropriate maxSize, should you desire to.
|
||||
func (cache *Cache) ReadFromFile(path string) (int, error) {
|
||||
db, err := bolt.Open(path, os.ModePerm, nil)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer db.Close()
|
||||
cache.mutex.Lock()
|
||||
defer cache.mutex.Unlock()
|
||||
err = db.View(func(tx *bolt.Tx) error {
|
||||
bucket := tx.Bucket([]byte("entries"))
|
||||
// If the bucket doesn't exist, there's nothing to read, so we'll return right now
|
||||
if bucket == nil {
|
||||
return nil
|
||||
}
|
||||
err = bucket.ForEach(func(k, v []byte) error {
|
||||
buffer := new(bytes.Buffer)
|
||||
decoder := gob.NewDecoder(buffer)
|
||||
entry := Entry{}
|
||||
buffer.Write(v)
|
||||
err := decoder.Decode(&entry)
|
||||
if err != nil {
|
||||
// Failed to decode the value, so we'll skip it.
|
||||
// This is likely due to the fact that the custom struct wasn't registered using gob.Register(...)
|
||||
//
|
||||
// Could also be due to a breaking change in a struct's variable. For instance, if the struct has
|
||||
// a variable with a type map[string]string and that variable is modified to map[string]int,
|
||||
// decoding the struct would fail. This can be avoided by using a different variable name every
|
||||
// time you must change the type of a variable within a struct.
|
||||
//
|
||||
// See [Persistence - Limitations](https://github.com/TwiN/gocache#limitations)
|
||||
return err
|
||||
}
|
||||
cache.entries[string(k)] = &entry
|
||||
buffer.Reset()
|
||||
return nil
|
||||
})
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
// Because pointers don't get stored in the file, we need to relink everything from head to tail
|
||||
var entries []*Entry
|
||||
for _, v := range cache.entries {
|
||||
entries = append(entries, v)
|
||||
}
|
||||
// Sort the slice of entries from oldest to newest
|
||||
sort.Slice(entries, func(i, j int) bool {
|
||||
return entries[i].RelevantTimestamp.Before(entries[j].RelevantTimestamp)
|
||||
})
|
||||
// Relink the nodes from tail to head
|
||||
var previous *Entry
|
||||
for i := range entries {
|
||||
current := entries[i]
|
||||
if previous == nil {
|
||||
cache.tail = current
|
||||
cache.head = current
|
||||
} else {
|
||||
previous.previous = current
|
||||
current.next = previous
|
||||
cache.head = current
|
||||
}
|
||||
previous = entries[i]
|
||||
if cache.maxMemoryUsage != NoMaxMemoryUsage {
|
||||
cache.memoryUsage += current.SizeInBytes()
|
||||
}
|
||||
}
|
||||
// If the cache doesn't have a maxSize/maxMemoryUsage, then there's no point checking if we need to evict
|
||||
// an entry, so we'll just return now
|
||||
if cache.maxSize == NoMaxSize && cache.maxMemoryUsage == NoMaxMemoryUsage {
|
||||
return 0, nil
|
||||
}
|
||||
// Evict what needs to be evicted
|
||||
numberOfEvictions := 0
|
||||
// If there's a maxSize and the cache has more entries than the maxSize, evict
|
||||
if cache.maxSize != NoMaxSize && len(cache.entries) > cache.maxSize {
|
||||
for len(cache.entries) > cache.maxSize {
|
||||
numberOfEvictions++
|
||||
cache.evict()
|
||||
}
|
||||
}
|
||||
// If there's a maxMemoryUsage and the memoryUsage is above the maxMemoryUsage, evict
|
||||
if cache.maxMemoryUsage != NoMaxMemoryUsage && cache.memoryUsage > cache.maxMemoryUsage {
|
||||
for cache.memoryUsage > cache.maxMemoryUsage && len(cache.entries) > 0 {
|
||||
numberOfEvictions++
|
||||
cache.evict()
|
||||
}
|
||||
}
|
||||
return numberOfEvictions, nil
|
||||
}
|
33
vendor/github.com/TwiN/gocache/policy.go
generated
vendored
Normal file
33
vendor/github.com/TwiN/gocache/policy.go
generated
vendored
Normal file
@ -0,0 +1,33 @@
|
||||
package gocache
|
||||
|
||||
// EvictionPolicy is what dictates how evictions are handled
|
||||
type EvictionPolicy string
|
||||
|
||||
var (
|
||||
// LeastRecentlyUsed is an eviction policy that causes the most recently accessed cache entry to be moved to the
|
||||
// head of the cache. Effectively, this causes the cache entries that have not been accessed for some time to
|
||||
// gradually move closer and closer to the tail, and since the tail is the entry that gets deleted when an eviction
|
||||
// is required, it allows less used cache entries to be evicted while keeping recently accessed entries at or close
|
||||
// to the head.
|
||||
//
|
||||
// For instance, creating a Cache with a Cache.MaxSize of 3 and creating the entries 1, 2 and 3 in that order would
|
||||
// put 3 at the head and 1 at the tail:
|
||||
// 3 (head) -> 2 -> 1 (tail)
|
||||
// If the cache entry 1 was then accessed, 1 would become the head and 2 the tail:
|
||||
// 1 (head) -> 3 -> 2 (tail)
|
||||
// If a cache entry 4 was then created, because the Cache.MaxSize is 3, the tail (2) would then be evicted:
|
||||
// 4 (head) -> 1 -> 3 (tail)
|
||||
LeastRecentlyUsed EvictionPolicy = "LeastRecentlyUsed"
|
||||
|
||||
// FirstInFirstOut is an eviction policy that causes cache entries to be evicted in the same order that they are
|
||||
// created.
|
||||
//
|
||||
// For instance, creating a Cache with a Cache.MaxSize of 3 and creating the entries 1, 2 and 3 in that order would
|
||||
// put 3 at the head and 1 at the tail:
|
||||
// 3 (head) -> 2 -> 1 (tail)
|
||||
// If the cache entry 1 was then accessed, unlike with LeastRecentlyUsed, nothing would change:
|
||||
// 3 (head) -> 2 -> 1 (tail)
|
||||
// If a cache entry 4 was then created, because the Cache.MaxSize is 3, the tail (1) would then be evicted:
|
||||
// 4 (head) -> 3 -> 2 (tail)
|
||||
FirstInFirstOut EvictionPolicy = "FirstInFirstOut"
|
||||
)
|
15
vendor/github.com/TwiN/gocache/statistics.go
generated
vendored
Normal file
15
vendor/github.com/TwiN/gocache/statistics.go
generated
vendored
Normal file
@ -0,0 +1,15 @@
|
||||
package gocache
|
||||
|
||||
type Statistics struct {
|
||||
// EvictedKeys is the number of keys that were evicted
|
||||
EvictedKeys uint64
|
||||
|
||||
// ExpiredKeys is the number of keys that were automatically deleted as a result of expiring
|
||||
ExpiredKeys uint64
|
||||
|
||||
// Hits is the number of cache hits
|
||||
Hits uint64
|
||||
|
||||
// Misses is the number of cache misses
|
||||
Misses uint64
|
||||
}
|
Reference in New Issue
Block a user