Browse Source

cache

- refactoring
Alexey Kim 1 year ago
parent
commit
5f865d7ca4
5 changed files with 37 additions and 18 deletions
  1. 2 4
      cache/element.go
  2. 5 0
      cache/errors.go
  3. 2 2
      cache/icache.go
  4. 14 11
      cache/ttl_cache.go
  5. 14 1
      devops/docker-compose.yaml

+ 2 - 4
cache/element.go

@@ -1,10 +1,8 @@
 package cache
 
-import "github.com/mailru/easyjson"
-
 type Element interface {
-	easyjson.Unmarshaler
-	easyjson.Marshaler
+	Marshal() ([]byte, error)
+	Unmarshal([]byte) error
 
 	Key() string
 }

+ 5 - 0
cache/errors.go

@@ -0,0 +1,5 @@
+package cache
+
+import "errors"
+
+var ErrorNotFound = errors.New("unknown cache key")

+ 2 - 2
cache/icache.go

@@ -5,6 +5,6 @@ import "git.beejay.kim/Craft/Api/service"
 type Cache interface {
 	service.Service
 
-	Get(elm Element) bool
-	Set(elm Element) bool
+	Get(elm Element) error
+	Set(elm Element) error
 }

+ 14 - 11
cache/ttl_cache.go

@@ -2,7 +2,6 @@ package cache
 
 import (
 	"github.com/hashicorp/golang-lru/v2/expirable"
-	"github.com/mailru/easyjson"
 	"time"
 )
 
@@ -10,36 +9,40 @@ type ttlCache struct {
 	buf *expirable.LRU[string, []byte]
 }
 
+//goland:noinspection GoUnusedExportedFunction
 func NewTTLCache(size int, ttl time.Duration) Cache {
 	c := &ttlCache{}
 	c.buf = expirable.NewLRU[string, []byte](size, nil, ttl)
 	return c
 }
 
-func (c *ttlCache) Get(elm Element) bool {
-	buf, ok := c.buf.Get(elm.Key())
+func (c *ttlCache) Get(elm Element) error {
+	var k = elm.Key()
+
+	buf, ok := c.buf.Get(k)
 	if !ok {
-		return false
+		return ErrorNotFound
 	}
 
-	if err := easyjson.Unmarshal(buf, elm); err != nil {
-		return false
+	if err := elm.Unmarshal(buf); err != nil {
+		c.buf.Remove(k)
+		return err
 	}
 
-	return true
+	return nil
 }
 
-func (c *ttlCache) Set(elm Element) bool {
+func (c *ttlCache) Set(elm Element) error {
 	var k = elm.Key()
 
-	buf, err := easyjson.Marshal(elm)
+	buf, err := elm.Marshal()
 	if err != nil {
 		c.buf.Remove(k)
-		return false
+		return err
 	}
 
 	c.buf.Add(k, buf)
-	return true
+	return nil
 }
 
 func (c *ttlCache) String() string {

+ 14 - 1
devops/docker-compose.yaml

@@ -22,5 +22,18 @@ services:
       ]
     ports:
       - "8080:8080"
-      - "9090:9090"
+    restart: unless-stopped
+
+  craft.auth:
+    container_name: craft.auth
+    hostname: auth.craft
+    image: ghcr.io/kimbeejay/craft-auth:0.0.1
+    volumes:
+      - ./auth.yaml:/etc/craft/auth.yaml:ro
+    command:
+      [
+        "craft-auth",
+        "-C", "/etc/craft/auth.yaml",
+        "daemon", "-P", "3128"
+      ]
     restart: unless-stopped