/
ephemeral.go
87 lines (76 loc) · 2.01 KB
/
ephemeral.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package storage
import (
"fmt"
"sync"
protoV1 "github.com/algorandfoundation/did-algo/proto/did/v1"
"github.com/pkg/errors"
"go.bryk.io/pkg/did"
)
type record struct {
id *did.Identifier
proof *did.ProofLD
}
// Ephemeral provides an in-memory store for development and testing.
type Ephemeral struct {
entries map[string]*record
mu sync.Mutex
}
// Open is a no-op for the ephemeral store. As an example just setup
// internally used structures.
func (e *Ephemeral) Open(_ string) error {
e.entries = make(map[string]*record)
return nil
}
// Close will release used-memory.
func (e *Ephemeral) Close() error {
e.mu.Lock()
for k := range e.entries {
delete(e.entries, k)
}
e.mu.Unlock()
e.entries = nil
return nil
}
// Exists returns true if the provided DID instance is already available
// in the store.
func (e *Ephemeral) Exists(id *did.Identifier) bool {
key := fmt.Sprintf("%s:%s", id.Method(), id.Subject())
e.mu.Lock()
_, ok := e.entries[key]
e.mu.Unlock()
return ok
}
// Get a previously stored DID instance.
func (e *Ephemeral) Get(req *protoV1.QueryRequest) (*did.Identifier, *did.ProofLD, error) {
key := fmt.Sprintf("%s:%s", req.Method, req.Subject)
e.mu.Lock()
r, ok := e.entries[key]
e.mu.Unlock()
if !ok {
return nil, nil, errors.New("no information available")
}
return r.id, r.proof, nil
}
// Save will create or update an entry for the provided DID instance.
func (e *Ephemeral) Save(id *did.Identifier, proof *did.ProofLD) (string, error) {
key := fmt.Sprintf("%s:%s", id.Method(), id.Subject())
e.mu.Lock()
e.entries[key] = &record{
id: id,
proof: proof,
}
e.mu.Unlock()
return "", nil
}
// Delete any existing record for the provided DID instance.
func (e *Ephemeral) Delete(id *did.Identifier) error {
key := fmt.Sprintf("%s:%s", id.Method(), id.Subject())
e.mu.Lock()
delete(e.entries, key)
e.mu.Unlock()
return nil
}
// Description returns a brief summary for the storage instance.
func (e *Ephemeral) Description() string {
return "ephemeral in-memory data store"
}