-
Notifications
You must be signed in to change notification settings - Fork 0
/
databases.go
420 lines (345 loc) · 10.9 KB
/
databases.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
package turso
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"os"
"time"
)
type Database struct {
ID string `json:"dbId" mapstructure:"dbId"`
Name string
Regions []string
PrimaryRegion string
Hostname string
Version string
Group string
Sleeping bool
}
type DatabasesClient client
func (c *DatabasesClient) List(ctx context.Context) ([]Database, error) {
res, err := c.client.Get(ctx, c.URL(""), nil)
if err != nil {
return nil, fmt.Errorf("failed to get database listing: %s", err)
}
defer res.Body.Close()
if c.client.isNotMemberErr(res.StatusCode) {
return nil, c.client.notMemberErr()
}
if res.StatusCode != http.StatusOK {
return nil, fmt.Errorf("failed to get database listing: %w", parseResponseError(res))
}
type ListResponse struct {
Databases []Database `json:"databases"`
}
resp, err := unmarshal[ListResponse](res)
return resp.Databases, err
}
func (c *DatabasesClient) Delete(ctx context.Context, database string) error {
url := c.URL("/" + database)
res, err := c.client.Delete(ctx, url, nil)
if err != nil {
return fmt.Errorf("failed to delete database: %s", err)
}
defer res.Body.Close()
if c.client.isNotMemberErr(res.StatusCode) {
return c.client.notMemberErr()
}
if res.StatusCode == http.StatusNotFound {
return fmt.Errorf("database %s not found", database)
}
if res.StatusCode != http.StatusOK {
return fmt.Errorf("failed to delete database: %w", parseResponseError(res))
}
return nil
}
type CreateDatabaseResponse struct {
Database Database
Username string
}
type DBSeed struct {
Type string `json:"type"`
Name string `json:"value,omitempty"`
URL string `json:"url,omitempty"`
Timestamp *time.Time `json:"timestamp,omitempty"`
}
type CreateDatabaseBody struct {
Name string `json:"name"`
Location string `json:"location"`
Image string `json:"image,omitempty"`
Extensions string `json:"extensions,omitempty"`
Group string `json:"group,omitempty"`
Seed *DBSeed `json:"seed,omitempty"`
Schema string `json:"schema,omitempty"`
IsSchema bool `json:"is_schema,omitempty"`
}
func (c *DatabasesClient) Create(ctx context.Context, name, location, image, extensions, group string, schema string, isSchema bool, seed *DBSeed) (*CreateDatabaseResponse, error) {
params := CreateDatabaseBody{name, location, image, extensions, group, seed, schema, isSchema}
body, err := marshal(params)
if err != nil {
return nil, fmt.Errorf("could not serialize request body: %w", err)
}
res, err := c.client.Post(ctx, c.URL(""), body)
if err != nil {
return nil, fmt.Errorf("failed to create database: %s", err)
}
defer res.Body.Close()
if c.client.isNotMemberErr(res.StatusCode) {
return nil, c.client.notMemberErr()
}
if res.StatusCode == http.StatusUnprocessableEntity {
return nil, fmt.Errorf("database name '%s' is not available", name)
}
if res.StatusCode != http.StatusOK {
return nil, parseResponseError(res)
}
data, err := unmarshal[*CreateDatabaseResponse](res)
if err != nil {
return nil, fmt.Errorf("failed to deserialize response: %w", err)
}
return data, nil
}
func (c *DatabasesClient) Seed(ctx context.Context, name string, dbFile *os.File) error {
url := c.URL(fmt.Sprintf("/%s/seed", name))
res, err := c.client.Upload(ctx, url, dbFile)
if err != nil {
return fmt.Errorf("failed to create database: %w", err)
}
defer res.Body.Close()
if c.client.isNotMemberErr(res.StatusCode) {
return c.client.notMemberErr()
}
if res.StatusCode == http.StatusUnprocessableEntity {
return fmt.Errorf("database name '%s' is not available", name)
}
if res.StatusCode != http.StatusOK {
return parseResponseError(res)
}
return nil
}
func (c *DatabasesClient) UploadDump(ctx context.Context, dbFile *os.File) (string, error) {
url := c.URL("/dumps")
res, err := c.client.Upload(ctx, url, dbFile)
if err != nil {
return "", fmt.Errorf("failed to upload the dump file: %w", err)
}
defer res.Body.Close()
if c.client.isNotMemberErr(res.StatusCode) {
return "", c.client.notMemberErr()
}
if res.StatusCode != http.StatusOK {
return "", parseResponseError(res)
}
type response struct {
DumpURL string `json:"dump_url"`
}
data, err := unmarshal[response](res)
if err != nil {
return "", err
}
return data.DumpURL, nil
}
type DatabaseTokenRequest struct {
Permissions *PermissionsClaim `json:"permissions,omitempty"`
}
func (c *DatabasesClient) Token(ctx context.Context, database string, expiration string, readOnly bool, permissions *PermissionsClaim) (string, error) {
authorization := ""
if readOnly {
authorization = "&authorization=read-only"
}
url := c.URL(fmt.Sprintf("/%s/auth/tokens?expiration=%s%s", database, expiration, authorization))
req := DatabaseTokenRequest{permissions}
body, err := marshal(req)
if err != nil {
return "", fmt.Errorf("could not serialize request body: %w", err)
}
res, err := c.client.Post(ctx, url, body)
if err != nil {
return "", fmt.Errorf("failed to get database token: %w", err)
}
defer res.Body.Close()
if c.client.isNotMemberErr(res.StatusCode) {
return "", c.client.notMemberErr()
}
if res.StatusCode != http.StatusOK {
return "", fmt.Errorf("failed to get database token: %w", parseResponseError(res))
}
type JwtResponse struct{ Jwt string }
data, err := unmarshal[JwtResponse](res)
if err != nil {
return "", err
}
return data.Jwt, nil
}
func (c *DatabasesClient) Rotate(ctx context.Context, database string) error {
url := c.URL(fmt.Sprintf("/%s/auth/rotate", database))
res, err := c.client.Post(ctx, url, nil)
if err != nil {
return fmt.Errorf("failed to rotate database keys: %w", err)
}
defer res.Body.Close()
if c.client.isNotMemberErr(res.StatusCode) {
return c.client.notMemberErr()
}
if res.StatusCode != http.StatusOK {
return fmt.Errorf("failed to rotate database keys: %w", parseResponseError(res))
}
return nil
}
func (c *DatabasesClient) Update(ctx context.Context, database string, group bool) error {
url := c.URL(fmt.Sprintf("/%s/update", database))
if group {
url += "?group=true"
}
res, err := c.client.Post(ctx, url, nil)
if err != nil {
return fmt.Errorf("failed to update database: %w", err)
}
defer res.Body.Close()
if c.client.isNotMemberErr(res.StatusCode) {
return c.client.notMemberErr()
}
if res.StatusCode != http.StatusOK {
return fmt.Errorf("failed to update database: %w", parseResponseError(res))
}
return nil
}
type Stats struct {
TopQueries []struct {
Query string `json:"query"`
RowsRead int `json:"rows_read"`
RowsWritten int `json:"rows_written"`
} `json:"top_queries,omitempty"`
}
func (c *DatabasesClient) Stats(ctx context.Context, database string) (Stats, error) {
url := c.URL(fmt.Sprintf("/%s/stats", database))
res, err := c.client.Get(ctx, url, nil)
if err != nil {
return Stats{}, fmt.Errorf("failed to update database: %w", err)
}
defer res.Body.Close()
if c.client.isNotMemberErr(res.StatusCode) {
return Stats{}, c.client.notMemberErr()
}
if res.StatusCode != http.StatusOK {
return Stats{}, fmt.Errorf("failed to get stats for database: %w", parseResponseError(res))
}
return unmarshal[Stats](res)
}
type Body struct {
Org string `json:"org"`
}
func (c *DatabasesClient) Transfer(ctx context.Context, database, org string) error {
url := c.URL(fmt.Sprintf("/%s/transfer", database))
body, err := json.Marshal(Body{Org: org})
bodyReader := bytes.NewReader(body)
if err != nil {
return fmt.Errorf("could not serialize request body: %w", err)
}
res, err := c.client.Post(ctx, url, bodyReader)
if err != nil {
return fmt.Errorf("failed to transfer database")
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return fmt.Errorf("failed to transfer %s database to org %s: %w", database, org, parseResponseError(res))
}
return nil
}
func (c *DatabasesClient) Wakeup(ctx context.Context, database string) error {
url := c.URL(fmt.Sprintf("/%s/wakeup", database))
res, err := c.client.Post(ctx, url, nil)
if err != nil {
return fmt.Errorf("failed to wakeup database: %w", err)
}
defer res.Body.Close()
if c.client.isNotMemberErr(res.StatusCode) {
return c.client.notMemberErr()
}
if res.StatusCode != http.StatusOK {
return fmt.Errorf("failed to wakeup database: %w", parseResponseError(res))
}
return nil
}
type Usage struct {
RowsRead uint64 `json:"rows_read,omitempty"`
RowsWritten uint64 `json:"rows_written,omitempty"`
StorageBytesUsed uint64 `json:"storage_bytes,omitempty"`
BytesSynced uint64 `json:"bytes_synced,omitempty"`
}
type InstanceUsage struct {
UUID string `json:"uuid,omitempty"`
Usage Usage `json:"usage"`
}
type DbUsage struct {
UUID string `json:"uuid,omitempty"`
Instances []InstanceUsage `json:"instances"`
Usage Usage `json:"usage"`
}
type DbUsageResponse struct {
DbUsage DbUsage `json:"database"`
}
func (c *DatabasesClient) Usage(ctx context.Context, database string) (DbUsage, error) {
url := c.URL(fmt.Sprintf("/%s/usage", database))
res, err := c.client.Get(ctx, url, nil)
if err != nil {
return DbUsage{}, fmt.Errorf("failed to get database usage: %w", err)
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return DbUsage{}, fmt.Errorf("failed to get database usage: %w", parseResponseError(res))
}
body, err := unmarshal[DbUsageResponse](res)
if err != nil {
return DbUsage{}, err
}
return body.DbUsage, nil
}
func (c *DatabasesClient) URL(suffix string) string {
prefix := "/v1"
if c.client.Org != "" {
prefix = "/v1/organizations/" + c.client.Org
}
return prefix + "/databases" + suffix
}
type DatabaseConfig struct {
AllowAttach bool `json:"allow_attach"`
}
func (c *DatabasesClient) GetConfig(ctx context.Context, database string) (DatabaseConfig, error) {
url := c.URL(fmt.Sprintf("/%s/configuration", database))
res, err := c.client.Get(ctx, url, nil)
if err != nil {
return DatabaseConfig{}, fmt.Errorf("failed to get database: %w", err)
}
defer res.Body.Close()
if c.client.isNotMemberErr(res.StatusCode) {
return DatabaseConfig{}, c.client.notMemberErr()
}
if res.StatusCode != http.StatusOK {
err = parseResponseError(res)
return DatabaseConfig{}, fmt.Errorf("failed to get config for database: %d %s", res.StatusCode, err)
}
return unmarshal[DatabaseConfig](res)
}
func (c *DatabasesClient) UpdateConfig(ctx context.Context, database string, config DatabaseConfig) error {
url := c.URL(fmt.Sprintf("/%s/configuration", database))
body, err := marshal(config)
if err != nil {
return fmt.Errorf("could not serialize request body: %w", err)
}
res, err := c.client.Patch(ctx, url, body)
if err != nil {
return fmt.Errorf("failed to update database: %w", err)
}
defer res.Body.Close()
if c.client.isNotMemberErr(res.StatusCode) {
return c.client.notMemberErr()
}
if res.StatusCode != http.StatusOK {
err = parseResponseError(res)
return fmt.Errorf("failed to update config for database: %d %s", res.StatusCode, err)
}
return nil
}