scopes
2015-12-13
Parent:b93938562a17
scopes/memstore.go
Port over Postgres storage and tests. Do the minimum possible port of the code from auth to get Postgres working and make the tests run and pass again. This leaves a bug where the ErrScopeAlreadyExists type, when populatd from Postgres, contains the entire error string returned from the database, instead of parsing the ID itself out. Which is a thing we should do and add a test for.
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 NewMemstore() *Memstore {
18 return &Memstore{
19 scopes: map[string]scopeTypes.Scope{},
20 }
21 }
23 func (m *Memstore) CreateScopes(scopes []scopeTypes.Scope, ctx context.Context) error {
24 m.lock.Lock()
25 defer m.lock.Unlock()
27 for _, scope := range scopes {
28 if _, ok := m.scopes[scope.ID]; ok {
29 return ErrScopeAlreadyExists(scope.ID)
30 }
31 }
32 for _, scope := range scopes {
33 m.scopes[scope.ID] = scope
34 }
35 return nil
36 }
38 func (m *Memstore) GetScopes(ids []string, ctx context.Context) (map[string]scopeTypes.Scope, error) {
39 m.lock.RLock()
40 defer m.lock.RUnlock()
42 scopes := map[string]scopeTypes.Scope{}
43 for _, id := range ids {
44 scope, ok := m.scopes[id]
45 if !ok {
46 continue
47 }
48 scopes[id] = scope
49 }
50 return scopes, nil
51 }
53 func (m *Memstore) UpdateScope(change scopeTypes.ScopeChange, ctx context.Context) error {
54 m.lock.Lock()
55 defer m.lock.Unlock()
57 scope, ok := m.scopes[change.ScopeID]
58 if !ok {
59 return ErrScopeNotFound
60 }
61 scope = scopeTypes.ApplyChange(change, scope)
62 m.scopes[change.ScopeID] = scope
63 return nil
64 }
66 func (m *Memstore) RemoveScopes(ids []string, ctx context.Context) error {
67 m.lock.Lock()
68 defer m.lock.Unlock()
70 for _, id := range ids {
71 delete(m.scopes, id)
72 }
73 return nil
74 }
76 func (m *Memstore) ListScopes(ctx context.Context) ([]scopeTypes.Scope, error) {
77 m.lock.RLock()
78 defer m.lock.RUnlock()
80 scopes := []scopeTypes.Scope{}
81 for _, scope := range m.scopes {
82 scopes = append(scopes, scope)
83 }
84 sorted := scopeTypes.Scopes(scopes)
85 sort.Sort(sorted)
86 scopes = sorted
87 return scopes, nil
88 }