ducky/devices

Paddy 2015-11-27 Parent:f5a9d5f8f28d Child:683050b4546b

10:74dbc04879a7 Go to Latest

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.

History
paddy@4 1 package devices
paddy@4 2
paddy@4 3 import (
paddy@4 4 "sync"
paddy@4 5
paddy@4 6 "code.secondbit.org/uuid.hg"
paddy@4 7 "golang.org/x/net/context"
paddy@4 8 )
paddy@4 9
paddy@4 10 type Memstore struct {
paddy@4 11 devices map[string]Device
paddy@4 12 lock sync.RWMutex
paddy@4 13 }
paddy@4 14
paddy@4 15 func NewMemstore() *Memstore {
paddy@4 16 return &Memstore{
paddy@4 17 devices: map[string]Device{},
paddy@4 18 }
paddy@4 19 }
paddy@4 20
paddy@4 21 func (m *Memstore) GetDevices(ids []uuid.ID, c context.Context) (map[string]Device, error) {
paddy@4 22 m.lock.RLock()
paddy@4 23 defer m.lock.RUnlock()
paddy@4 24
paddy@4 25 results := map[string]Device{}
paddy@4 26
paddy@4 27 for _, id := range ids {
paddy@4 28 device, ok := m.devices[id.String()]
paddy@4 29 if !ok {
paddy@4 30 continue
paddy@4 31 }
paddy@4 32 results[id.String()] = device
paddy@4 33 }
paddy@4 34 return results, nil
paddy@4 35 }
paddy@4 36
paddy@4 37 func (m *Memstore) UpdateDevice(change DeviceChange, c context.Context) error {
paddy@10 38 m.lock.Lock()
paddy@10 39 defer m.lock.Unlock()
paddy@10 40
paddy@10 41 device, ok := m.devices[change.DeviceID.String()]
paddy@10 42 if !ok {
paddy@10 43 return nil // TODO: return an error
paddy@10 44 }
paddy@10 45
paddy@10 46 device = ApplyChange(device, change)
paddy@10 47 m.devices[change.DeviceID.String()] = device
paddy@10 48
paddy@4 49 return nil
paddy@4 50 }
paddy@4 51
paddy@4 52 func (m *Memstore) DeleteDevices(id []uuid.ID, c context.Context) error {
paddy@4 53 return nil
paddy@4 54 }
paddy@4 55
paddy@4 56 func (m *Memstore) CreateDevices(devices []Device, c context.Context) error {
paddy@4 57 m.lock.Lock()
paddy@4 58 defer m.lock.Unlock()
paddy@4 59
paddy@4 60 for _, device := range devices {
paddy@5 61 if _, ok := m.devices[device.ID.String()]; ok {
paddy@5 62 return ErrDeviceAlreadyExists(device.ID)
paddy@5 63 }
paddy@5 64 }
paddy@5 65
paddy@5 66 for _, device := range devices {
paddy@4 67 m.devices[device.ID.String()] = device
paddy@4 68 }
paddy@4 69 return nil
paddy@4 70 }
paddy@4 71
paddy@4 72 func (m *Memstore) ListDevicesByOwner(user uuid.ID, c context.Context) ([]Device, error) {
paddy@8 73 var devices []Device
paddy@8 74 for _, device := range m.devices {
paddy@8 75 if !device.Owner.Equal(user) {
paddy@8 76 continue
paddy@8 77 }
paddy@8 78 devices = append(devices, device)
paddy@8 79 }
paddy@8 80 return devices, nil
paddy@4 81 }