Dragonfly2

Форк
0
/
certify.go 
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

17
package cache
18

19
import (
20
	"context"
21
	"crypto/tls"
22

23
	"github.com/johanbrandhorst/certify"
24
)
25

26
const (
27
	// CertifyCacheDirName is dir name of certify cache.
28
	CertifyCacheDirName = "certs"
29
)
30

31
type certifyCache struct {
32
	caches []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.
38
func NewCertifyMutliCache(caches ...certify.Cache) certify.Cache {
39
	return &certifyCache{caches: caches}
40
}
41

42
// Get gets cert from cache one by one, if found, puts it back to all previous caches.
43
func (c *certifyCache) Get(ctx context.Context, key string) (cert *tls.Certificate, err error) {
44
	var foundCacheIdx int = -1
45
	for i, cache := range c.caches {
46
		if cert, err = cache.Get(ctx, key); err == nil {
47
			foundCacheIdx = i
48
			break
49
		}
50
	}
51

52
	// put cert in previous cache
53
	for i := 0; i < foundCacheIdx; i++ {
54
		_ = c.caches[i].Put(ctx, key, cert)
55
	}
56

57
	if err == nil {
58
		return
59
	}
60

61
	return nil, certify.ErrCacheMiss
62
}
63

64
// Put puts cert to all caches.
65
func (c *certifyCache) Put(ctx context.Context, key string, cert *tls.Certificate) error {
66
	for _, cache := range c.caches {
67
		if err := cache.Put(ctx, key, cert); err != nil {
68
			return err
69
		}
70
	}
71
	return nil
72
}
73

74
// Delete deletes cert from all caches.
75
func (c *certifyCache) Delete(ctx context.Context, key string) error {
76
	for _, cache := range c.caches {
77
		if err := cache.Delete(ctx, key); err != nil {
78
			return err
79
		}
80
	}
81
	return nil
82
}
83

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.