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.
9 "golang.org/x/net/context"
11 "code.secondbit.org/uuid.hg"
15 // ErrDeviceNotFound is returned when the specified device couldn't be found.
16 ErrDeviceNotFound = errors.New("device not found")
19 // Device represents a specific device that updates can be pushed to.
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 {
34 if change.Name != nil {
35 result.Name = *change.Name
37 if change.Owner != nil {
38 result.Owner = *change.Owner
40 // We don't want to accidentally leave a slice that
41 // is owned by both behind.
42 result.Owner = d.Owner.Copy()
44 if change.Type != nil {
45 result.Type = *change.Type
47 if change.LastSeen != nil {
48 result.LastSeen = *change.LastSeen
50 if change.PushToken != nil {
51 result.PushToken = *change.PushToken
56 // DeviceChange represents a set of changes to a Device that will be used
57 // to update a Device.
58 type DeviceChange struct {
67 // Storer is an interface to control how data is stored in and retrieved from
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)
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())
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)
93 log.Printf("Error retrieving Storer: %+v\n", err)
96 results, err = storer.GetDevices(ids, c)
98 log.Printf("Error retrieving Devices from %T: %+v\n", storer, err)
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)
111 result, ok := results[id.String()]
113 return Device{}, ErrDeviceNotFound
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)
123 log.Printf("Error retrieving Storer: %+v\n", err)
126 change.DeviceID = device.ID
127 err = storer.UpdateDevice(change, c)
131 return ApplyChange(device, change), nil
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)
139 log.Printf("Error retrieving Storer: %+v\n", err)
142 return storer.DeleteDevices(ids, c)
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)
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)
157 log.Printf("Error retrieving Storer: %+v\n", err)
158 return []Device{}, err
160 modified := make([]Device, 0, len(devices))
161 for _, device := range devices {
162 if device.ID.IsZero() {
163 device.ID = uuid.NewID()
165 if device.Created.IsZero() {
166 device.Created = time.Now()
168 if device.LastSeen.IsZero() {
169 device.LastSeen = time.Now()
171 modified = append(modified, device)
173 err = storer.CreateDevices(modified, c)
175 return []Device{}, err
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)
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
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
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)
202 log.Printf("Error retrieving Storer: %+v\n", err)
203 return []Device{}, err
205 devices, err := storer.ListDevicesByOwner(user, c)
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
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)