-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
openapi.go
531 lines (441 loc) · 19.4 KB
/
openapi.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
// Package REST provides primitives to interact with the openapi HTTP API.
//
// Code generated by github.com/deepmap/oapi-codegen version v1.11.1-0.20220912230023-4a1477f6a8ba DO NOT EDIT.
package REST
import (
"bytes"
"compress/gzip"
"encoding/base64"
"fmt"
"net/http"
"net/url"
"path"
"strings"
"github.com/deepmap/oapi-codegen/pkg/runtime"
openapi_types "github.com/deepmap/oapi-codegen/pkg/types"
"github.com/getkin/kin-openapi/openapi3"
"github.com/labstack/echo/v4"
)
const (
DeviceAuthScopes = "deviceAuth.Scopes"
)
// Defines values for HealthResult.
const (
Down HealthResult = "Down"
Up HealthResult = "Up"
)
// Device a device
type Device struct {
// Id Device ID is the unique identifier for a remote device
Id DeviceID `json:"id"`
}
// DeviceID Device ID is the unique identifier for a remote device
type DeviceID = openapi_types.UUID
// DeviceList list of devices
type DeviceList struct {
// Count Amount of Items contained in List
Count ListItemCount `json:"count"`
// Items array of devices, it will always at least contain the device of the authenticated user
Items []Device `json:"items"`
}
// HealthAggregation defines model for HealthAggregation.
type HealthAggregation struct {
// Components The different Components of the Server
Components *[]HealthAggregationComponent `json:"components,omitempty"`
// Health A Health Check Result
Health HealthResult `json:"health"`
}
// HealthAggregationComponent defines model for HealthAggregationComponent.
type HealthAggregationComponent struct {
// Health A Health Check Result
Health HealthResult `json:"health"`
// Name The Name of the Component to be Health Checked
Name string `json:"name"`
}
// HealthResult A Health Check Result
type HealthResult string
// ListItemCount Amount of Items contained in List
type ListItemCount = int
// ModuleDataStream Module Data Stream
type ModuleDataStream = openapi_types.File
// ModuleName Module Name
type ModuleName = string
// RegistrationResult defines model for RegistrationResult.
type RegistrationResult struct {
Password string `json:"password"`
Username string `json:"username"`
}
// ShareResponse defines model for ShareResponse.
type ShareResponse struct {
ShareCode *string `json:"shareCode,omitempty"`
}
// DeviceIDQuery Device ID is the unique identifier for a remote device
type DeviceIDQuery = DeviceID
// ShareCode defines model for ShareCode.
type ShareCode = string
// XDeviceID Device ID is the unique identifier for a remote device
type XDeviceID = DeviceID
// DeviceListResponse list of devices
type DeviceListResponse = DeviceList
// ModuleDataAccepted An Empty JSON
type ModuleDataAccepted = interface{}
// RegisterParams defines parameters for Register.
type RegisterParams struct {
// Share The Share Code from the Share API. If presented in combination with a new Device ID,
// it can be used to add new devices to an account.
Share *ShareCode `form:"share,omitempty" json:"share,omitempty"`
// XDeviceID Unique Identifier of the calling Device. If calling Data endpoints, must be presented in order
// to be properly authenticated.
XDeviceID XDeviceID `json:"X-Device-ID"`
}
// ShareParams defines parameters for Share.
type ShareParams struct {
// XDeviceID Unique Identifier of the calling Device. If calling Data endpoints, must be presented in order
// to be properly authenticated.
XDeviceID XDeviceID `json:"X-Device-ID"`
}
// GetDevicesParams defines parameters for GetDevices.
type GetDevicesParams struct {
// XDeviceID Unique Identifier of the calling Device. If calling Data endpoints, must be presented in order
// to be properly authenticated.
XDeviceID XDeviceID `json:"X-Device-ID"`
}
// GetModuleParams defines parameters for GetModule.
type GetModuleParams struct {
// DeviceId Device Identifier to use for the Query. If given, takes precedence over X-Device-ID or other hints.
// Use to query data from devices in your account from another account.
DeviceId *DeviceIDQuery `form:"device-id,omitempty" json:"device-id,omitempty"`
// XDeviceID Unique Identifier of the calling Device. If calling Data endpoints, must be presented in order
// to be properly authenticated.
XDeviceID XDeviceID `json:"X-Device-ID"`
}
// CreateModuleParams defines parameters for CreateModule.
type CreateModuleParams struct {
// XDeviceID Unique Identifier of the calling Device. If calling Data endpoints, must be presented in order
// to be properly authenticated.
XDeviceID XDeviceID `json:"X-Device-ID"`
}
// ServerInterface represents all server handlers.
type ServerInterface interface {
// Register A Device
// (POST /auth/register)
Register(ctx echo.Context, params RegisterParams) error
// Share your Account
// (POST /auth/share)
Share(ctx echo.Context, params ShareParams) error
// Get All registered Devices for your Account
// (GET /devices)
GetDevices(ctx echo.Context, params GetDevicesParams) error
// Checks if the Service is Available for Processing Request
// (GET /health)
IsHealthy(ctx echo.Context) error
// Get Module Data
// (GET /modules/{name})
GetModule(ctx echo.Context, name ModuleName, params GetModuleParams) error
// Create/Update Module Data
// (POST /modules/{name})
CreateModule(ctx echo.Context, name ModuleName, params CreateModuleParams) error
// Checks if the Service is Operational
// (GET /ready)
IsReady(ctx echo.Context) error
}
// ServerInterfaceWrapper converts echo contexts to parameters.
type ServerInterfaceWrapper struct {
Handler ServerInterface
}
// Register converts echo context to params.
func (w *ServerInterfaceWrapper) Register(ctx echo.Context) error {
var err error
// Parameter object where we will unmarshal all parameters from the context
var params RegisterParams
// ------------- Optional query parameter "share" -------------
err = runtime.BindQueryParameter("form", true, false, "share", ctx.QueryParams(), ¶ms.Share)
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter share: %s", err))
}
headers := ctx.Request().Header
// ------------- Required header parameter "X-Device-ID" -------------
if valueList, found := headers[http.CanonicalHeaderKey("X-Device-ID")]; found {
var XDeviceID XDeviceID
n := len(valueList)
if n != 1 {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Expected one value for X-Device-ID, got %d", n))
}
err = runtime.BindStyledParameterWithLocation("simple", false, "X-Device-ID", runtime.ParamLocationHeader, valueList[0], &XDeviceID)
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter X-Device-ID: %s", err))
}
params.XDeviceID = XDeviceID
} else {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Header parameter X-Device-ID is required, but not found"))
}
// Invoke the callback with all the unmarshalled arguments
err = w.Handler.Register(ctx, params)
return err
}
// Share converts echo context to params.
func (w *ServerInterfaceWrapper) Share(ctx echo.Context) error {
var err error
ctx.Set(DeviceAuthScopes, []string{""})
// Parameter object where we will unmarshal all parameters from the context
var params ShareParams
headers := ctx.Request().Header
// ------------- Required header parameter "X-Device-ID" -------------
if valueList, found := headers[http.CanonicalHeaderKey("X-Device-ID")]; found {
var XDeviceID XDeviceID
n := len(valueList)
if n != 1 {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Expected one value for X-Device-ID, got %d", n))
}
err = runtime.BindStyledParameterWithLocation("simple", false, "X-Device-ID", runtime.ParamLocationHeader, valueList[0], &XDeviceID)
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter X-Device-ID: %s", err))
}
params.XDeviceID = XDeviceID
} else {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Header parameter X-Device-ID is required, but not found"))
}
// Invoke the callback with all the unmarshalled arguments
err = w.Handler.Share(ctx, params)
return err
}
// GetDevices converts echo context to params.
func (w *ServerInterfaceWrapper) GetDevices(ctx echo.Context) error {
var err error
ctx.Set(DeviceAuthScopes, []string{""})
// Parameter object where we will unmarshal all parameters from the context
var params GetDevicesParams
headers := ctx.Request().Header
// ------------- Required header parameter "X-Device-ID" -------------
if valueList, found := headers[http.CanonicalHeaderKey("X-Device-ID")]; found {
var XDeviceID XDeviceID
n := len(valueList)
if n != 1 {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Expected one value for X-Device-ID, got %d", n))
}
err = runtime.BindStyledParameterWithLocation("simple", false, "X-Device-ID", runtime.ParamLocationHeader, valueList[0], &XDeviceID)
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter X-Device-ID: %s", err))
}
params.XDeviceID = XDeviceID
} else {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Header parameter X-Device-ID is required, but not found"))
}
// Invoke the callback with all the unmarshalled arguments
err = w.Handler.GetDevices(ctx, params)
return err
}
// IsHealthy converts echo context to params.
func (w *ServerInterfaceWrapper) IsHealthy(ctx echo.Context) error {
var err error
// Invoke the callback with all the unmarshalled arguments
err = w.Handler.IsHealthy(ctx)
return err
}
// GetModule converts echo context to params.
func (w *ServerInterfaceWrapper) GetModule(ctx echo.Context) error {
var err error
// ------------- Path parameter "name" -------------
var name ModuleName
err = runtime.BindStyledParameterWithLocation("simple", false, "name", runtime.ParamLocationPath, ctx.Param("name"), &name)
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter name: %s", err))
}
ctx.Set(DeviceAuthScopes, []string{""})
// Parameter object where we will unmarshal all parameters from the context
var params GetModuleParams
// ------------- Optional query parameter "device-id" -------------
err = runtime.BindQueryParameter("form", true, false, "device-id", ctx.QueryParams(), ¶ms.DeviceId)
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter device-id: %s", err))
}
headers := ctx.Request().Header
// ------------- Required header parameter "X-Device-ID" -------------
if valueList, found := headers[http.CanonicalHeaderKey("X-Device-ID")]; found {
var XDeviceID XDeviceID
n := len(valueList)
if n != 1 {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Expected one value for X-Device-ID, got %d", n))
}
err = runtime.BindStyledParameterWithLocation("simple", false, "X-Device-ID", runtime.ParamLocationHeader, valueList[0], &XDeviceID)
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter X-Device-ID: %s", err))
}
params.XDeviceID = XDeviceID
} else {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Header parameter X-Device-ID is required, but not found"))
}
// Invoke the callback with all the unmarshalled arguments
err = w.Handler.GetModule(ctx, name, params)
return err
}
// CreateModule converts echo context to params.
func (w *ServerInterfaceWrapper) CreateModule(ctx echo.Context) error {
var err error
// ------------- Path parameter "name" -------------
var name ModuleName
err = runtime.BindStyledParameterWithLocation("simple", false, "name", runtime.ParamLocationPath, ctx.Param("name"), &name)
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter name: %s", err))
}
ctx.Set(DeviceAuthScopes, []string{""})
// Parameter object where we will unmarshal all parameters from the context
var params CreateModuleParams
headers := ctx.Request().Header
// ------------- Required header parameter "X-Device-ID" -------------
if valueList, found := headers[http.CanonicalHeaderKey("X-Device-ID")]; found {
var XDeviceID XDeviceID
n := len(valueList)
if n != 1 {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Expected one value for X-Device-ID, got %d", n))
}
err = runtime.BindStyledParameterWithLocation("simple", false, "X-Device-ID", runtime.ParamLocationHeader, valueList[0], &XDeviceID)
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter X-Device-ID: %s", err))
}
params.XDeviceID = XDeviceID
} else {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Header parameter X-Device-ID is required, but not found"))
}
// Invoke the callback with all the unmarshalled arguments
err = w.Handler.CreateModule(ctx, name, params)
return err
}
// IsReady converts echo context to params.
func (w *ServerInterfaceWrapper) IsReady(ctx echo.Context) error {
var err error
// Invoke the callback with all the unmarshalled arguments
err = w.Handler.IsReady(ctx)
return err
}
// This is a simple interface which specifies echo.Route addition functions which
// are present on both echo.Echo and echo.Group, since we want to allow using
// either of them for path registration
type EchoRouter interface {
CONNECT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route
DELETE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route
GET(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route
HEAD(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route
OPTIONS(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route
PATCH(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route
POST(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route
PUT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route
TRACE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route
}
// RegisterHandlers adds each server route to the EchoRouter.
func RegisterHandlers(router EchoRouter, si ServerInterface) {
RegisterHandlersWithBaseURL(router, si, "")
}
// Registers handlers, and prepends BaseURL to the paths, so that the paths
// can be served under a prefix.
func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL string) {
wrapper := ServerInterfaceWrapper{
Handler: si,
}
router.POST(baseURL+"/auth/register", wrapper.Register)
router.POST(baseURL+"/auth/share", wrapper.Share)
router.GET(baseURL+"/devices", wrapper.GetDevices)
router.GET(baseURL+"/health", wrapper.IsHealthy)
router.GET(baseURL+"/modules/:name", wrapper.GetModule)
router.POST(baseURL+"/modules/:name", wrapper.CreateModule)
router.GET(baseURL+"/ready", wrapper.IsReady)
}
// Base64 encoded, gzipped, json marshaled Swagger object
var swaggerSpec = []string{
"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",
"/+zA6LeKGwAA",
}
// GetSwagger returns the content of the embedded swagger specification file
// or error if failed to decode
func decodeSpec() ([]byte, error) {
zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, ""))
if err != nil {
return nil, fmt.Errorf("error base64 decoding spec: %s", err)
}
zr, err := gzip.NewReader(bytes.NewReader(zipped))
if err != nil {
return nil, fmt.Errorf("error decompressing spec: %s", err)
}
var buf bytes.Buffer
_, err = buf.ReadFrom(zr)
if err != nil {
return nil, fmt.Errorf("error decompressing spec: %s", err)
}
return buf.Bytes(), nil
}
var rawSpec = decodeSpecCached()
// a naive cached of a decoded swagger spec
func decodeSpecCached() func() ([]byte, error) {
data, err := decodeSpec()
return func() ([]byte, error) {
return data, err
}
}
// Constructs a synthetic filesystem for resolving external references when loading openapi specifications.
func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) {
var res = make(map[string]func() ([]byte, error))
if len(pathToFile) > 0 {
res[pathToFile] = rawSpec
}
return res
}
// GetSwagger returns the Swagger specification corresponding to the generated code
// in this file. The external references of Swagger specification are resolved.
// The logic of resolving external references is tightly connected to "import-mapping" feature.
// Externally referenced files must be embedded in the corresponding golang packages.
// Urls can be supported but this task was out of the scope.
func GetSwagger() (swagger *openapi3.T, err error) {
var resolvePath = PathToRawSpec("")
loader := openapi3.NewLoader()
loader.IsExternalRefsAllowed = true
loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) {
var pathToFile = url.String()
pathToFile = path.Clean(pathToFile)
getSpec, ok := resolvePath[pathToFile]
if !ok {
err1 := fmt.Errorf("path not found: %s", pathToFile)
return nil, err1
}
return getSpec()
}
var specData []byte
specData, err = rawSpec()
if err != nil {
return
}
swagger, err = loader.LoadFromData(specData)
if err != nil {
return
}
return
}