ducky/devices

Paddy 2015-12-14 Parent:03c49b4d3d9f Child:a700ede02f91

15:c24a6c5fcd8c Go to Latest

ducky/devices/devices.go

Begin implementation on apiv1. Begin implementing the apiv1 package, which will define the first iteration of our API endpoints and logic. Each API package should be self-contained and able to run without depending on each other. Think of them as interfaces into manipulating the business logic defined in the devices package. The point is to have total control over backwards compatibility, as long as our business logic doesn't change. If that happens, we're in a bad place, but not as bad as it could be. This required us to pull in all our API tools; the api package, its dependencies, the scopeTypes package (so we can define scopes for our API), the trout router, etc. We also updated uuid to the latest, which now includes a license. Hooray? The new apiv1 package consists of a few things: * The devices.go file defines the types the API will use to communicate, along with some helpers to convert from API types to devices types. There's also a stub for validating the device creation requests, which I haven't implemented yet because I'm a pretty bad person. * endpoints.go just contains a helper function that builds our routes and assigns handlers to them, giving us an http.Handler in the returns that we can listen with. * handlers.go defines our HTTP handlers, which will read requests and write responses, after doing the appropriate validation and executing the appropriating business logic. Right now, we only have a handler for creating devices, and it doesn't actually do any validation. Also, we have some user-correctable errors being returned as 500s right now, which is Bad. Fortunately, they're all marked with BUG, so I can at least come back to them. * response.go defines the Response type that will be used for returning information after a request is executed. It may eventually get some helpers, but for now it's pretty basic. * scopes.go defines the Scopes that we're going to be using in the package to control access. It should probably (eventually) include a helper to register the Scopes, or we should have a collector service that pulls in all the packages, finds all their Scopes, and registers them. I haven't decided how I want to manage Scope registration just yet. We exported the getStorer function (now GetStorer) so other packages can use it. I'm not sure how I feel about this just yet. We also had to create a WithStorer helper method that embeds the Storer into a context.Context, so we can bootstrap in devicesd. We erroneously had Created in the DeviceChange struct, but there's no reason the Created property of a Device should ever change, so it was removed from the logic, from the struct, and from the tests. Our CreateMany helper was erroneously creating the un-modified Devices that were passed in, instead of the Devices that had sensible defaults filled. We created a _very minimal_ (e.g., needs some work before it's ready for production) devicesd package that will spin up a simple server, just so we could take a peek at our apiv1 endpoints as they'd actually be used. (It worked. Yay?) We should continue to expand on this with configuration, more information being logged, etc.

History
1 package devices
3 import (
4 "errors"
5 "fmt"
6 "log"
7 "time"
9 "golang.org/x/net/context"
11 "code.secondbit.org/uuid.hg"
12 )
14 var (
15 // ErrDeviceNotFound is returned when the specified device couldn't be found.
16 ErrDeviceNotFound = errors.New("device not found")
17 )
19 // Device represents a specific device that updates can be pushed to.
20 type Device struct {
21 ID uuid.ID
22 Name string
23 Owner uuid.ID
24 Type DeviceType
25 Created time.Time
26 LastSeen time.Time
27 PushToken string
28 }
30 // ApplyChange returns a Device that is a copy of the passed Device,
31 // but with the passed DeviceChange applied.
32 func ApplyChange(d Device, change DeviceChange) Device {
33 result := d
34 if change.Name != nil {
35 result.Name = *change.Name
36 }
37 if change.Owner != nil {
38 result.Owner = *change.Owner
39 } else {
40 // We don't want to accidentally leave a slice that
41 // is owned by both behind.
42 result.Owner = d.Owner.Copy()
43 }
44 if change.Type != nil {
45 result.Type = *change.Type
46 }
47 if change.LastSeen != nil {
48 result.LastSeen = *change.LastSeen
49 }
50 if change.PushToken != nil {
51 result.PushToken = *change.PushToken
52 }
53 return result
54 }
56 // DeviceChange represents a set of changes to a Device that will be used
57 // to update a Device.
58 type DeviceChange struct {
59 DeviceID uuid.ID
60 Name *string
61 Owner *uuid.ID
62 Type *DeviceType
63 LastSeen *time.Time
64 PushToken *string
65 }
67 // Storer is an interface to control how data is stored in and retrieved from
68 // the datastore.
69 type Storer interface {
70 GetDevices(ids []uuid.ID, c context.Context) (map[string]Device, error)
71 UpdateDevice(change DeviceChange, c context.Context) error
72 DeleteDevices(ids []uuid.ID, c context.Context) error
73 CreateDevices(devices []Device, c context.Context) error
74 ListDevicesByOwner(user uuid.ID, c context.Context) ([]Device, error)
75 }
77 // ErrDeviceAlreadyExists is returned when a Device is added to a Storer, but a
78 // Device with the same ID already exists in the Storer. The ID underlying
79 // ErrDeviceAlreadyExists will hold the ID that already exists.
80 type ErrDeviceAlreadyExists uuid.ID
82 func (e ErrDeviceAlreadyExists) Error() string {
83 return fmt.Sprintf("device with ID %s already exists in datastore", uuid.ID(e).String())
84 }
86 // GetMany returns as many of the Devices specified by the passed IDs as possible.
87 // They are returned as a map, with the key being the string version of the ID.
88 // No error will be returned if a Device can't be found.
89 func GetMany(ids []uuid.ID, c context.Context) (map[string]Device, error) {
90 results := map[string]Device{}
91 storer, err := GetStorer(c)
92 if err != nil {
93 log.Printf("Error retrieving Storer: %+v\n", err)
94 return results, err
95 }
96 results, err = storer.GetDevices(ids, c)
97 if err != nil {
98 log.Printf("Error retrieving Devices from %T: %+v\n", storer, err)
99 return results, err
100 }
101 return results, nil
102 }
104 // Get returns the Device specified by the passed ID. If the Device can't be found,
105 // an ErrDeviceNotFound error is returned.
106 func Get(id uuid.ID, c context.Context) (Device, error) {
107 results, err := GetMany([]uuid.ID{id}, c)
108 if err != nil {
109 return Device{}, err
110 }
111 result, ok := results[id.String()]
112 if !ok {
113 return Device{}, ErrDeviceNotFound
114 }
115 return result, nil
116 }
118 // Update applies the DeviceChange to the passed Device, and returns the result. If
119 // the Device can't be found, an ErrDeviceNotFound error was returned.
120 func Update(device Device, change DeviceChange, c context.Context) (Device, error) {
121 storer, err := GetStorer(c)
122 if err != nil {
123 log.Printf("Error retrieving Storer: %+v\n", err)
124 return Device{}, err
125 }
126 change.DeviceID = device.ID
127 err = storer.UpdateDevice(change, c)
128 if err != nil {
129 return Device{}, err
130 }
131 return ApplyChange(device, change), nil
132 }
134 // DeleteMany removes the passed IDs from the datastore. No error is returned if the
135 // ID doesn't correspond to a Device in the datastore.
136 func DeleteMany(ids []uuid.ID, c context.Context) error {
137 storer, err := GetStorer(c)
138 if err != nil {
139 log.Printf("Error retrieving Storer: %+v\n", err)
140 return err
141 }
142 return storer.DeleteDevices(ids, c)
143 }
145 // Delete removes the passed ID from the datastore. No error is returned if the ID doesn't
146 // correspond to a Device in the datastore.
147 func Delete(id uuid.ID, c context.Context) error {
148 return DeleteMany([]uuid.ID{id}, c)
149 }
151 // CreateMany stores the passed Devices in the datastore, assigning default values if
152 // necessary. The Devices that were ultimately stored (including any default values, if
153 // applicable) are returned.
154 func CreateMany(devices []Device, c context.Context) ([]Device, error) {
155 storer, err := GetStorer(c)
156 if err != nil {
157 log.Printf("Error retrieving Storer: %+v\n", err)
158 return []Device{}, err
159 }
160 modified := make([]Device, 0, len(devices))
161 for _, device := range devices {
162 if device.ID.IsZero() {
163 device.ID = uuid.NewID()
164 }
165 if device.Created.IsZero() {
166 device.Created = time.Now()
167 }
168 if device.LastSeen.IsZero() {
169 device.LastSeen = time.Now()
170 }
171 modified = append(modified, device)
172 }
173 err = storer.CreateDevices(modified, c)
174 if err != nil {
175 return []Device{}, err
176 }
177 return modified, nil
178 }
180 // Create stores the passed Device in the datastore, assigning default values if
181 // necessary. The Devices that were ultimately stored (including any default values, if
182 // applicable) are returned.
183 func Create(device Device, c context.Context) (Device, error) {
184 devices, err := CreateMany([]Device{device}, c)
185 if err != nil {
186 return Device{}, err
187 }
188 // There should never be a case where we don't return a result.
189 // Ideally, we'd return an error here instead of letting the panic
190 // happen, but seeing as I can't come up with a reason the error would
191 // occur, I'm having trouble coming up with a reasonable error to return.
192 return devices[0], nil
193 }
195 // ListByOwner returns a slice of all the Devices with an Owner property that
196 // matches the passed ID. There's no guarantee on the order the Devices will be
197 // returned in.
198 func ListByOwner(user uuid.ID, c context.Context) ([]Device, error) {
199 // BUG(paddy): Eventually, we'll need to support paging for devices. But right now, I don't foresee any user creating enough of them to make pagination worthwhile.
200 storer, err := GetStorer(c)
201 if err != nil {
202 log.Printf("Error retrieving Storer: %+v\n", err)
203 return []Device{}, err
204 }
205 devices, err := storer.ListDevicesByOwner(user, c)
206 return devices, err
207 }
209 // ToMap transforms the passed slice into a map by using the String method of
210 // each Device's ID as the key, and the Device as the value.
211 func ToMap(devices []Device) map[string]Device {
212 results := make(map[string]Device, len(devices))
213 for _, device := range devices {
214 results[device.ID.String()] = device
215 }
216 return results
217 }
219 // ToSlice transforms the passed map of Devices into a slice of Devices.
220 func ToSlice(devices map[string]Device) []Device {
221 results := make([]Device, 0, len(devices))
222 for _, device := range devices {
223 results = append(results, device)
224 }
225 return results
226 }