scopes
scopes/memstore.go
Separete out scopeTypes package. To avoid the same problem we had in the auth package (where importing the type required you to vendor all the database drivers, etc.) let's just separate out the scopeTypes package to hold the types, then everything can import that.
1 package scopes
3 import (
4 "sort"
5 "sync"
7 "code.secondbit.org/scopes.hg/types"
9 "golang.org/x/net/context"
10 )
12 type Memstore struct {
13 scopes map[string]scopeTypes.Scope
14 lock sync.RWMutex
15 }
17 func (m *Memstore) CreateScopes(scopes []scopeTypes.Scope, ctx context.Context) error {
18 m.lock.Lock()
19 defer m.lock.Unlock()
21 for _, scope := range scopes {
22 if _, ok := m.scopes[scope.ID]; ok {
23 return ErrScopeAlreadyExists(scope.ID)
24 }
25 }
26 for _, scope := range scopes {
27 m.scopes[scope.ID] = scope
28 }
29 return nil
30 }
32 func (m *Memstore) GetScopes(ids []string, ctx context.Context) (map[string]scopeTypes.Scope, error) {
33 m.lock.RLock()
34 defer m.lock.RUnlock()
36 scopes := map[string]scopeTypes.Scope{}
37 for _, id := range ids {
38 scope, ok := m.scopes[id]
39 if !ok {
40 continue
41 }
42 scopes[id] = scope
43 }
44 return scopes, nil
45 }
47 func (m *Memstore) UpdateScope(change scopeTypes.ScopeChange, ctx context.Context) error {
48 m.lock.Lock()
49 defer m.lock.Unlock()
51 scope, ok := m.scopes[change.ScopeID]
52 if !ok {
53 return ErrScopeNotFound
54 }
55 scope = scopeTypes.ApplyChange(change, scope)
56 m.scopes[change.ScopeID] = scope
57 return nil
58 }
60 func (m *Memstore) RemoveScopes(ids []string, ctx context.Context) error {
61 m.lock.Lock()
62 defer m.lock.Unlock()
64 for _, id := range ids {
65 delete(m.scopes, id)
66 }
67 return nil
68 }
70 func (m *Memstore) ListScopes(ctx context.Context) ([]scopeTypes.Scope, error) {
71 m.lock.RLock()
72 defer m.lock.RUnlock()
74 scopes := []scopeTypes.Scope{}
75 for _, scope := range m.scopes {
76 scopes = append(scopes, scope)
77 }
78 sorted := scopeTypes.Scopes(scopes)
79 sort.Sort(sorted)
80 scopes = sorted
81 return scopes, nil
82 }