ducky/devices
ducky/devices/memstore.go
Implement and test updating devices, and reuse contexts. Update all our tests to use the same context.Context instance within each test case, so static analysis about how we're passing contexts around dosn't get tripped up. Also, write a test that will check to make sure that our Storer implementations all actually update the Device correctly. We create every possible permutation of a DeviceChange, just to make sure they all work.
1 package devices
3 import (
4 "sync"
6 "code.secondbit.org/uuid.hg"
7 "golang.org/x/net/context"
8 )
10 type Memstore struct {
11 devices map[string]Device
12 lock sync.RWMutex
13 }
15 func NewMemstore() *Memstore {
16 return &Memstore{
17 devices: map[string]Device{},
18 }
19 }
21 func (m *Memstore) GetDevices(ids []uuid.ID, c context.Context) (map[string]Device, error) {
22 m.lock.RLock()
23 defer m.lock.RUnlock()
25 results := map[string]Device{}
27 for _, id := range ids {
28 device, ok := m.devices[id.String()]
29 if !ok {
30 continue
31 }
32 results[id.String()] = device
33 }
34 return results, nil
35 }
37 func (m *Memstore) UpdateDevice(change DeviceChange, c context.Context) error {
38 m.lock.Lock()
39 defer m.lock.Unlock()
41 device, ok := m.devices[change.DeviceID.String()]
42 if !ok {
43 return nil // TODO: return an error
44 }
46 device = ApplyChange(device, change)
47 m.devices[change.DeviceID.String()] = device
49 return nil
50 }
52 func (m *Memstore) DeleteDevices(id []uuid.ID, c context.Context) error {
53 return nil
54 }
56 func (m *Memstore) CreateDevices(devices []Device, c context.Context) error {
57 m.lock.Lock()
58 defer m.lock.Unlock()
60 for _, device := range devices {
61 if _, ok := m.devices[device.ID.String()]; ok {
62 return ErrDeviceAlreadyExists(device.ID)
63 }
64 }
66 for _, device := range devices {
67 m.devices[device.ID.String()] = device
68 }
69 return nil
70 }
72 func (m *Memstore) ListDevicesByOwner(user uuid.ID, c context.Context) ([]Device, error) {
73 var devices []Device
74 for _, device := range m.devices {
75 if !device.Owner.Equal(user) {
76 continue
77 }
78 devices = append(devices, device)
79 }
80 return devices, nil
81 }