Dragonfly2
82 строки · 2.2 Кб
1/*
2* Copyright 2022 The Dragonfly Authors
3*
4* Licensed under the Apache License, Version 2.0 (the "License");
5* you may not use this file except in compliance with the License.
6* You may obtain a copy of the License at
7*
8* http://www.apache.org/licenses/LICENSE-2.0
9*
10* Unless required by applicable law or agreed to in writing, software
11* distributed under the License is distributed on an "AS IS" BASIS,
12* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13* See the License for the specific language governing permissions and
14* limitations under the License.
15*/
16
17package cache
18
19import (
20"context"
21"crypto/tls"
22
23"github.com/johanbrandhorst/certify"
24)
25
26const (
27// CertifyCacheDirName is dir name of certify cache.
28CertifyCacheDirName = "certs"
29)
30
31type certifyCache struct {
32caches []certify.Cache
33}
34
35// NewCertifyMutliCache returns a certify.Cache with multiple caches
36// Such as, cache.NewCertifyMutliCache(certify.NewMemCache(), certify.DirCache("certs"))
37// This multiple cache will get certs from mem cache first, then dir cache to avoid read from filesystem every times.
38func NewCertifyMutliCache(caches ...certify.Cache) certify.Cache {
39return &certifyCache{caches: caches}
40}
41
42// Get gets cert from cache one by one, if found, puts it back to all previous caches.
43func (c *certifyCache) Get(ctx context.Context, key string) (cert *tls.Certificate, err error) {
44var foundCacheIdx int = -1
45for i, cache := range c.caches {
46if cert, err = cache.Get(ctx, key); err == nil {
47foundCacheIdx = i
48break
49}
50}
51
52// put cert in previous cache
53for i := 0; i < foundCacheIdx; i++ {
54_ = c.caches[i].Put(ctx, key, cert)
55}
56
57if err == nil {
58return
59}
60
61return nil, certify.ErrCacheMiss
62}
63
64// Put puts cert to all caches.
65func (c *certifyCache) Put(ctx context.Context, key string, cert *tls.Certificate) error {
66for _, cache := range c.caches {
67if err := cache.Put(ctx, key, cert); err != nil {
68return err
69}
70}
71return nil
72}
73
74// Delete deletes cert from all caches.
75func (c *certifyCache) Delete(ctx context.Context, key string) error {
76for _, cache := range c.caches {
77if err := cache.Delete(ctx, key); err != nil {
78return err
79}
80}
81return nil
82}
83