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