forked from juju/juju
-
Notifications
You must be signed in to change notification settings - Fork 0
/
autocertcache.go
73 lines (63 loc) · 1.81 KB
/
autocertcache.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// Copyright 2016 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package state
import (
"github.com/juju/errors"
"golang.org/x/crypto/acme/autocert"
"golang.org/x/net/context"
"gopkg.in/mgo.v2"
"github.com/juju/juju/mongo"
)
// AutocertCache returns an implementation
// of autocert.Cache backed by the state.
func (st *State) AutocertCache() autocert.Cache {
return autocertCache{st}
}
type autocertCache struct {
st *State
}
type autocertCacheDoc struct {
Name string `bson:"_id"`
Data []byte `bson:"data"`
}
// Put implements autocert.Cache.Put.
func (cache autocertCache) Put(ctx context.Context, name string, data []byte) error {
coll, closeColl := cache.coll()
defer closeColl()
_, err := coll.UpsertId(name, autocertCacheDoc{
Name: name,
Data: data,
})
if err != nil {
return errors.Annotatef(err, "cannot store autocert key %q", name)
}
return nil
}
// Get implements autocert.Cache.Get.
func (cache autocertCache) Get(ctx context.Context, name string) ([]byte, error) {
coll, closeColl := cache.coll()
defer closeColl()
var doc autocertCacheDoc
err := coll.FindId(name).One(&doc)
if err == nil {
return doc.Data, nil
}
if errors.Cause(err) == mgo.ErrNotFound {
return nil, autocert.ErrCacheMiss
}
return nil, errors.Annotatef(err, "cannot get autocert key %q", name)
}
// Delete implements autocert.Cache.Delete.
func (cache autocertCache) Delete(ctx context.Context, name string) error {
coll, closeColl := cache.coll()
defer closeColl()
err := coll.RemoveId(name)
if err == nil || errors.Cause(err) == mgo.ErrNotFound {
return nil
}
return errors.Annotatef(err, "cannot delete autocert key %q", name)
}
func (cache autocertCache) coll() (mongo.WriteCollection, func()) {
coll, closer := cache.st.getCollection(autocertCacheC)
return coll.Writeable(), closer
}