-
Notifications
You must be signed in to change notification settings - Fork 0
/
fastschema.go
752 lines (625 loc) · 17.6 KB
/
fastschema.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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
package fastschema
import (
"context"
"embed"
"encoding/json"
"fmt"
"net/http"
"os"
"path"
"strings"
"github.com/fastschema/fastschema/db"
"github.com/fastschema/fastschema/fs"
"github.com/fastschema/fastschema/logger"
"github.com/fastschema/fastschema/pkg/entdbadapter"
"github.com/fastschema/fastschema/pkg/errors"
"github.com/fastschema/fastschema/pkg/openapi"
"github.com/fastschema/fastschema/pkg/rclonefs"
"github.com/fastschema/fastschema/pkg/restfulresolver"
"github.com/fastschema/fastschema/pkg/utils"
"github.com/fastschema/fastschema/pkg/zaplogger"
"github.com/fastschema/fastschema/schema"
cs "github.com/fastschema/fastschema/services/content"
ms "github.com/fastschema/fastschema/services/file"
rs "github.com/fastschema/fastschema/services/role"
ss "github.com/fastschema/fastschema/services/schema"
ts "github.com/fastschema/fastschema/services/tool"
us "github.com/fastschema/fastschema/services/user"
"github.com/fatih/color"
"github.com/joho/godotenv"
)
//go:embed all:dash/*
var embedDashStatic embed.FS
type App struct {
config *fs.Config
cwd string
dir string
envFile string
dataDir string
logDir string
publicDir string
schemasDir string
migrationDir string
schemaBuilder *schema.Builder
restResolver *restfulresolver.RestfulResolver
resources *fs.ResourcesManager
api *fs.Resource
hooks *fs.Hooks
roles []*fs.Role
disks []fs.Disk
defaultDisk fs.Disk
setupToken string
startupMessages []string
statics []*fs.StaticFs
openAPISpec []byte
}
func New(config *fs.Config) (_ *App, err error) {
a := &App{
config: config.Clone(),
disks: []fs.Disk{},
roles: []*fs.Role{},
hooks: &fs.Hooks{
DBHooks: &db.Hooks{},
},
}
if a.cwd, err = os.Getwd(); err != nil {
return nil, err
}
if err := a.prepareConfig(); err != nil {
return nil, err
}
if err = a.init(); err != nil {
return nil, err
}
return a, nil
}
func (a *App) CWD() string {
return a.cwd
}
func (a *App) init() (err error) {
if err = a.getDefaultDisk(); err != nil {
return err
}
if err = a.getDefaultLogger(); err != nil {
return err
}
if err = a.createSchemaBuilder(); err != nil {
return err
}
if err = a.createResources(); err != nil {
return err
}
if err = a.getDefaultDBClient(); err != nil {
return err
}
// if a local disk has a public path, then add it to the statics
for _, disk := range a.disks {
publicPath := disk.LocalPublicPath()
if publicPath != "" {
a.startupMessages = append(
a.startupMessages,
fmt.Sprintf("Serving files from disk [%s:%s] at %s", disk.Name(), publicPath, disk.Root()),
)
a.statics = append(a.statics, &fs.StaticFs{
BasePath: publicPath,
Root: http.Dir(disk.Root()),
})
}
}
setupToken, err := a.SetupToken(context.Background())
if err != nil {
return err
}
if setupToken != "" {
type setupData struct {
Token string `json:"token"`
Username string `json:"username"`
Email string `json:"email"`
Password string `json:"password"`
}
a.api.Add(fs.NewResource("setup", func(c fs.Context, setupData *setupData) (bool, error) {
if setupToken == "" {
return false, errors.BadRequest("Setup token is not available")
}
if setupData == nil || setupData.Token != setupToken {
return false, errors.Forbidden("Invalid setup data or token")
}
if err := ts.Setup(
c.Context(),
a.DB(),
a.Logger(),
setupData.Username, setupData.Email, setupData.Password,
); err != nil {
return false, err
}
if err := a.UpdateCache(c.Context()); err != nil {
return false, err
}
setupToken = ""
a.setupToken = ""
return true, nil
}, &fs.Meta{
Post: "/setup",
Public: true,
}))
setupURL := fmt.Sprintf(
"%s/setup/?token=%s\033[0m",
a.config.DashURL,
setupToken,
)
a.startupMessages = append(a.startupMessages, fmt.Sprintf(
"Visit the following URL to setup the app: %s",
setupURL,
))
}
a.statics = append(a.statics, &fs.StaticFs{
BasePath: "/" + a.config.DashBaseName,
Root: http.FS(embedDashStatic),
PathPrefix: "dash",
})
return nil
}
func (a *App) Config() *fs.Config {
return a.config
}
func (a *App) Key() string {
return a.config.AppKey
}
func (a *App) Dir() string {
return a.dir
}
func (a *App) Reload(ctx context.Context, migration *db.Migration) (err error) {
if a.DB() != nil {
if err = a.DB().Close(); err != nil {
return err
}
}
if err = a.createSchemaBuilder(); err != nil {
return err
}
newDB, err := a.DB().Reload(ctx, a.schemaBuilder, migration)
if err != nil {
return err
}
a.config.DB = newDB
if _, err := a.CreateOpenAPISpec(true); err != nil {
return err
}
return nil
}
// UpdateCache updates the application cache.
// It fetches all roles from the database and stores them in the cache.
func (a *App) UpdateCache(ctx context.Context) (err error) {
if a.roles, err = db.Query[*fs.Role](a.DB()).Select(
"id",
"name",
"description",
"root",
"permissions",
schema.FieldCreatedAt,
schema.FieldUpdatedAt,
schema.FieldDeletedAt,
).Get(ctx); err != nil {
return err
}
return nil
}
// CreateOpenAPISpec generates the openapi spec for the app.
func (a *App) CreateOpenAPISpec(overrides ...bool) ([]byte, error) {
overrides = append(overrides, false)
if a.openAPISpec == nil || overrides[0] {
s, err := openapi.NewSpec(&openapi.OpenAPISpecConfig{
BaseURL: a.config.BaseURL,
Resources: a.Resources(),
SchemaBuilder: a.schemaBuilder,
})
if err != nil {
return nil, err
}
a.openAPISpec = s.Spec()
}
return a.openAPISpec, nil
}
func (a *App) Start() error {
addr := fmt.Sprintf(":%s", a.config.Port)
if err := a.resources.Init(); err != nil {
return err
}
if !a.config.HideResourcesInfo {
a.resources.Print()
}
a.restResolver = restfulresolver.NewRestfulResolver(a.resources, a.Logger(), a.statics...)
fmt.Printf("\n")
for _, msg := range a.startupMessages {
color.Green("> %s", msg)
}
fmt.Printf("\n")
return a.restResolver.Start(addr)
}
func (a *App) Shutdown() error {
if a.DB() != nil {
if err := a.DB().Close(); err != nil {
return err
}
}
if a.restResolver != nil {
if err := a.restResolver.Shutdown(); err != nil {
return err
}
}
return nil
}
func (a *App) SchemaBuilder() *schema.Builder {
return a.schemaBuilder
}
func (a *App) DB() db.Client {
return a.config.DB
}
func (a *App) API() *fs.Resource {
return a.api
}
func (a *App) Logger() logger.Logger {
return a.config.Logger
}
func (a *App) Resources() *fs.ResourcesManager {
return a.resources
}
func (a *App) Roles() []*fs.Role {
return a.roles
}
func (a *App) Hooks() *fs.Hooks {
return a.hooks
}
func (a *App) Disks() []fs.Disk {
return a.disks
}
func (a *App) Disk(names ...string) fs.Disk {
if len(names) == 0 {
return a.defaultDisk
}
for _, disk := range a.disks {
if disk.Name() == names[0] {
return disk
}
}
return nil
}
func (a *App) AddResource(resource *fs.Resource) {
a.resources.Add(resource)
}
func (a *App) AddMiddlewares(middlewares ...fs.Middleware) {
a.resources.Middlewares = append(a.resources.Middlewares, middlewares...)
}
func (a *App) OnPreResolve(middlewares ...fs.Middleware) {
a.hooks.PreResolve = append(a.hooks.PreResolve, middlewares...)
}
func (a *App) OnPostResolve(middlewares ...fs.Middleware) {
a.hooks.PostResolve = append(a.hooks.PostResolve, middlewares...)
}
func (a *App) OnPostDBGet(hooks ...db.PostDBGet) {
a.hooks.DBHooks.PostDBGet = append(a.hooks.DBHooks.PostDBGet, hooks...)
}
func (a *App) SetupToken(ctx context.Context) (string, error) {
// If there is no roles and users, then the app is not setup
// we need to setup the app.
// Generate a random token and return it to enable the setup.
// If there are roles or users, then the app is already setup.
// Return an empty string to disable the setup.
needSetup, err := a.needSetup(ctx)
if err != nil {
return "", err
}
if !needSetup {
return "", nil
}
if a.setupToken == "" {
a.setupToken = utils.RandomString(32)
}
return a.setupToken, nil
}
func (a *App) needSetup(ctx context.Context) (bool, error) {
// If there is no roles and users, then the app is not setup
// we need to setup the app.
var err error
var userCount int
var roleCount int
countOption := &db.CountOption{
Column: "id",
Unique: true,
}
if userCount, err = db.Query[*fs.User](a.DB()).Count(ctx, countOption); err != nil {
return false, err
}
if roleCount, err = db.Query[*fs.Role](a.DB()).Count(ctx, countOption); err != nil {
return false, err
}
return userCount == 0 && roleCount == 0, nil
}
func (a *App) getDefaultDBClient() (err error) {
if a.DB() != nil {
return nil
}
if a.config.DBConfig == nil {
a.config.DBConfig = &db.Config{
Driver: utils.Env("DB_DRIVER", "sqlite"),
Name: utils.Env("DB_NAME"),
User: utils.Env("DB_USER"),
Pass: utils.Env("DB_PASS"),
Host: utils.Env("DB_HOST", "localhost"),
Port: utils.Env("DB_PORT"),
LogQueries: utils.Env("DB_LOGGING", "false") == "true",
Logger: a.Logger(),
MigrationDir: a.migrationDir,
Hooks: func() *db.Hooks {
return &db.Hooks{
PostDBGet: a.hooks.DBHooks.PostDBGet,
}
},
}
}
// If driver is sqlite and the DB_NAME (file path) is not set,
// Set the DB_NAME to the default sqlite db file path.
if a.config.DBConfig.Driver == "sqlite" && a.config.DBConfig.Name == "" {
a.config.DBConfig.Name = path.Join(a.dataDir, "fastschema.db")
a.startupMessages = append(
a.startupMessages,
fmt.Sprintf("Using default sqlite db file: %s", a.config.DBConfig.Name),
)
}
if a.config.DB, err = entdbadapter.NewClient(a.config.DBConfig, a.schemaBuilder); err != nil {
return err
}
if err := a.UpdateCache(context.Background()); err != nil {
return err
}
return nil
}
func (a *App) getDefaultLogger() (err error) {
if a.config.Logger == nil {
if a.config.LoggerConfig == nil {
a.config.LoggerConfig = &logger.Config{
Development: utils.Env("APP_ENV", "development") == "development",
LogFile: path.Join(a.logDir, "app.log"),
}
}
a.config.Logger, err = zaplogger.NewZapLogger(a.config.LoggerConfig)
}
return err
}
func (a *App) getDefaultDisk() (err error) {
if a.config.StorageConfig == nil {
a.config.StorageConfig = &fs.StorageConfig{}
}
defaultDiskName := a.config.StorageConfig.DefaultDisk
if defaultDiskName == "" {
defaultDiskName = utils.Env("STORAGE_DEFAULT_DISK", "public")
}
storageDisksConfig := a.config.StorageConfig.DisksConfig
if utils.Env("STORAGE_DISKS") != "" && storageDisksConfig == nil {
if err := json.Unmarshal([]byte(utils.Env("STORAGE_DISKS")), &storageDisksConfig); err != nil {
return err
}
}
// if threre is no disk config, add a default disk
if storageDisksConfig == nil {
storageDisksConfig = []*fs.DiskConfig{{
Name: "public",
Driver: "local",
PublicPath: "/files",
BaseURL: fmt.Sprintf("%s/files", a.config.BaseURL),
Root: a.publicDir,
}}
}
if a.disks, err = rclonefs.NewFromConfig(storageDisksConfig, a.dataDir); err != nil {
return err
}
foundDefaultDisk := false
for _, disk := range a.disks {
if disk.Name() == defaultDiskName {
a.defaultDisk = disk
foundDefaultDisk = true
break
}
}
if defaultDiskName != "" && !foundDefaultDisk {
return fmt.Errorf("default disk [%s] not found", defaultDiskName)
}
if a.defaultDisk == nil && len(a.disks) > 0 {
a.defaultDisk = a.disks[0]
}
return nil
}
func (a *App) createSchemaBuilder() (err error) {
if a.schemaBuilder, err = schema.NewBuilderFromDir(
a.schemasDir,
append(fs.SystemSchemaTypes, a.config.SystemSchemas...)...,
); err != nil {
return err
}
return nil
}
func (a *App) createResources() error {
userService := us.New(a)
roleService := rs.New(a)
fileService := ms.New(a)
schemaService := ss.New(a)
contentService := cs.New(a)
toolService := ts.New(a)
a.hooks.DBHooks.PostDBGet = append(a.hooks.DBHooks.PostDBGet, fileService.FileListHook)
a.hooks.PreResolve = append(a.hooks.PreResolve, roleService.Authorize)
a.resources = fs.NewResourcesManager()
a.resources.Middlewares = append(a.resources.Middlewares, roleService.ParseUser)
a.resources.Hooks = func() *fs.Hooks {
return a.hooks
}
var createArg = func(t fs.ArgType, desc string) fs.Arg {
return fs.Arg{Type: t, Required: true, Description: desc}
}
a.api = a.resources.Group(a.config.APIBaseName)
a.api.Group("user").
Add(fs.NewResource("logout", userService.Logout, &fs.Meta{
Post: "/logout",
Public: true,
})).
Add(fs.NewResource("me", userService.Me, &fs.Meta{Public: true})).
Add(fs.NewResource("login", userService.Login, &fs.Meta{
Post: "/login",
Public: true,
}))
a.api.Group("schema").
Add(fs.NewResource("list", schemaService.List, &fs.Meta{Get: "/"})).
Add(fs.NewResource("create", schemaService.Create, &fs.Meta{Post: "/"})).
Add(fs.NewResource("detail", schemaService.Detail, &fs.Meta{
Get: "/:name",
Args: fs.Args{"name": createArg(fs.TypeString, "The schema name")},
})).
Add(fs.NewResource("update", schemaService.Update, &fs.Meta{
Put: "/:name",
Args: fs.Args{"name": createArg(fs.TypeString, "The schema name")},
})).
Add(fs.NewResource("delete", schemaService.Delete, &fs.Meta{
Delete: "/:name",
Args: fs.Args{"name": createArg(fs.TypeString, "The schema name")},
}))
a.api.Group("content", &fs.Meta{
Prefix: "/content/:schema",
Args: fs.Args{
"schema": {
Required: true,
Type: fs.TypeString,
Description: "The schema name",
},
},
}).
Add(fs.NewResource("list", contentService.List, &fs.Meta{Get: "/"})).
Add(fs.NewResource("detail", contentService.Detail, &fs.Meta{
Get: "/:id",
Args: fs.Args{"id": createArg(fs.TypeUint64, "The content ID")},
})).
Add(fs.NewResource("create", contentService.Create, &fs.Meta{Post: "/"})).
Add(fs.NewResource("update", contentService.Update, &fs.Meta{
Put: "/:id",
Args: fs.Args{"id": createArg(fs.TypeUint64, "The content ID")},
})).
Add(fs.NewResource("delete", contentService.Delete, &fs.Meta{
Delete: "/:id",
Args: fs.Args{"id": createArg(fs.TypeUint64, "The content ID")},
}))
a.api.Group("role").
Add(fs.NewResource("list", roleService.List, &fs.Meta{Get: "/"})).
Add(fs.NewResource("resources", roleService.ResourcesList, &fs.Meta{
Get: "/resources",
})).
Add(fs.NewResource("detail", roleService.Detail, &fs.Meta{
Get: "/:id",
Args: fs.Args{"id": createArg(fs.TypeUint64, "The role ID")},
})).
Add(fs.NewResource("create", roleService.Create, &fs.Meta{Post: "/"})).
Add(fs.NewResource("update", roleService.Update, &fs.Meta{
Put: "/:id",
Args: fs.Args{"id": createArg(fs.TypeUint64, "The role ID")},
})).
Add(fs.NewResource("delete", roleService.Delete, &fs.Meta{
Delete: "/:id",
Args: fs.Args{"id": createArg(fs.TypeUint64, "The role ID")},
}))
a.api.Group("file").
Add(fs.NewResource("upload", fileService.Upload, &fs.Meta{Post: "/upload"})).
Add(fs.NewResource("delete", fileService.Delete, &fs.Meta{Delete: "/"}))
a.api.Group("tool").
Add(fs.NewResource("stats", toolService.Stats, &fs.Meta{
Get: "/stats",
Public: true,
}))
a.resources.Group("docs").
Add(fs.NewResource("spec", func(c fs.Context, _ any) (any, error) {
return a.CreateOpenAPISpec()
}, &fs.Meta{Get: "/openapi.json"})).
Add(fs.NewResource("viewer", func(c fs.Context, _ any) (any, error) {
header := make(http.Header)
header.Set("Content-Type", "text/html")
return &fs.HTTPResponse{
StatusCode: http.StatusOK,
Header: header,
Body: []byte(utils.CreateSwaggerUIPage(
a.config.BaseURL + "/docs/openapi.json",
)),
}, nil
}, &fs.Meta{Get: "/"}))
return nil
}
func (a *App) getAppDir() {
defer func() {
a.startupMessages = append(a.startupMessages, fmt.Sprintf("Using app directory: %s", a.dir))
}()
if a.config.Dir == "" {
a.dir = a.cwd
return
}
if strings.HasPrefix(a.config.Dir, "/") {
a.dir = a.config.Dir
return
}
a.dir = path.Join(a.cwd, a.config.Dir)
}
func (a *App) prepareConfig() (err error) {
a.getAppDir()
a.dataDir = path.Join(a.dir, "data")
a.logDir = path.Join(a.dataDir, "logs")
a.publicDir = path.Join(a.dataDir, "public")
a.schemasDir = path.Join(a.dataDir, "schemas")
a.migrationDir = path.Join(a.dataDir, "migrations")
envFile := path.Join(a.dataDir, ".env")
if err = utils.MkDirs(
a.logDir,
a.publicDir,
a.schemasDir,
a.migrationDir,
); err != nil {
return err
}
if utils.IsFileExists(envFile) {
a.envFile = envFile
if err := godotenv.Load(envFile); err != nil {
return err
}
}
if a.config.AppKey == "" {
a.config.AppKey = utils.Env("APP_KEY")
}
if a.config.Port == "" {
a.config.Port = utils.Env("APP_PORT", "8000")
}
if a.config.BaseURL == "" {
a.config.BaseURL = utils.Env("APP_BASE_URL")
}
if a.config.DashURL == "" {
a.config.DashURL = utils.Env("APP_DASH_URL")
}
if a.config.APIBaseName == "" {
a.config.APIBaseName = utils.Env("APP_API_BASE_NAME", "api")
}
if a.config.DashBaseName == "" {
a.config.DashBaseName = utils.Env("APP_DASH_BASE_NAME", "dash")
}
if a.config.BaseURL == "" {
a.config.BaseURL = fmt.Sprintf("http://localhost:%s", a.config.Port)
}
if a.config.DashURL == "" {
a.config.DashURL = fmt.Sprintf("%s/%s", a.config.BaseURL, a.config.DashBaseName)
}
if a.config.AppKey == "" {
a.config.AppKey = utils.RandomString(32)
if err := utils.AppendFile(
envFile,
fmt.Sprintf("APP_KEY=%s\n", a.config.AppKey),
); err != nil {
return err
}
a.startupMessages = append(
a.startupMessages,
fmt.Sprintf("APP_KEY is not set. A new key is generated and saved to %s", envFile),
)
}
return nil
}