forked from bokwoon95/notebrew
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfs_database.go
2129 lines (2046 loc) · 65.3 KB
/
fs_database.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
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package notebrew
import (
"bytes"
"compress/gzip"
"context"
"database/sql"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"log/slog"
"os"
"path"
"strings"
"sync"
"syscall"
"time"
"unicode/utf8"
"github.com/bokwoon95/notebrew/sq"
"github.com/bokwoon95/notebrew/stacktrace"
)
var wildcardReplacer = strings.NewReplacer(`%`, `\%`, `_`, `\_`, `\`, `\\`)
var gzipReaderPool = sync.Pool{}
var gzipWriterPool = sync.Pool{
New: func() any {
// Use compression level 4 for best balance between space and
// performance.
// https://blog.klauspost.com/gzip-performance-for-go-webservers/
gzipWriter, _ := gzip.NewWriterLevel(nil, 4)
return gzipWriter
},
}
// DatabaseFSConfig holds the parameters needed to construct a DatabaseFS.
type DatabaseFSConfig struct {
// (Required) DB is the sql database.
DB *sql.DB
// (Required) Dialect is the database dialect. Currently, the only dialects
// supported are "sqlite", "postgres" and "mysql".
Dialect string
// ErrorCode converts an error returned by a database query into a
// dialect-specific error code.
ErrorCode func(error) string
// (Required) ObjectStorage is used for storage of binary objects.
ObjectStorage ObjectStorage
// (Required) Logger is used for reporting errors that cannot be handled
// and are thrown away.
Logger *slog.Logger
// UpdateStorageUsed is called whenever the storage used by a site changes
// (delta being the number of bytes that have been added or removed).
// Specifically, this happens on calls to OpenWriter, Remove, RemoveAll and
// Copy.
UpdateStorageUsed func(ctx context.Context, siteName string, delta int64) error
}
// DatabaseFS implements a writeable filesystem using a database and an
// ObjectStorage provider.
type DatabaseFS struct {
// DB is the sql database.
DB *sql.DB
// Dialect is the database dialect. Currently, the only dialects supported
// are "sqlite", "postgres" and "mysql".
Dialect string
// ErrorCode converts an error returned by a database query into a
// dialect-specific error code.
ErrorCode func(error) string
// ObjectStorage is used for storage of binary objects.
ObjectStorage ObjectStorage
// Logger is used for reporting errors that cannot be handled and are
// thrown away.
Logger *slog.Logger
// UpdateStorageUsed is called whenever the storage used by a site changes
// (delta being the number of bytes that have been added or removed).
// Specifically, this happens on calls to OpenWriter, Remove, RemoveAll and
// Copy.
UpdateStorageUsed func(ctx context.Context, siteName string, delta int64) error
// ctx provides the context of all operations called on the DatabaseFS.
ctx context.Context
// values is a key-value store containing values used by some filesystem
// operations. Currently, the following values are recognized:
//
// - "modTime" => time.Time (sets the modTime for files created by OpenWriter/Mkdir/MkdirAll)
//
// - "creationTime" => time.Time (sets the creationTime for files created by OpenWriter/Mkdir/MkdirAll)
//
// - "caption" => string (sets the caption for images created by OpenWriter)
values map[string]any
}
// NewDatabaseFS constructs a new DatabaseFS.
func NewDatabaseFS(config DatabaseFSConfig) (*DatabaseFS, error) {
databaseFS := &DatabaseFS{
DB: config.DB,
Dialect: config.Dialect,
ErrorCode: config.ErrorCode,
ObjectStorage: config.ObjectStorage,
Logger: config.Logger,
UpdateStorageUsed: config.UpdateStorageUsed,
ctx: context.Background(),
}
return databaseFS, nil
}
// As writes the current databaseFS into the target if it is a valid DatabaseFS
// pointer.
func (fsys *DatabaseFS) As(target any) bool {
switch target := target.(type) {
case *DatabaseFS:
*target = *fsys
return true
case **DatabaseFS:
*target = fsys
return true
default:
return false
}
}
// WithContext returns a new FS with the given context.
func (fsys *DatabaseFS) WithContext(ctx context.Context) FS {
return &DatabaseFS{
DB: fsys.DB,
Dialect: fsys.Dialect,
ErrorCode: fsys.ErrorCode,
ObjectStorage: fsys.ObjectStorage,
Logger: fsys.Logger,
UpdateStorageUsed: fsys.UpdateStorageUsed,
ctx: ctx,
values: fsys.values,
}
}
// WithValues returns a new FS with the given values.
//
// Currently, the following values are recognized:
//
// - "modTime" => time.Time (sets the modTime for files created by OpenWriter/Mkdir/MkdirAll)
//
// - "creationTime" => time.Time (sets the creationTime for files created by OpenWriter/Mkdir/MkdirAll)
//
// - "caption" => string (sets the caption for images created by OpenWriter)
//
// These values will apply to *all* filesystem operations, so if you only want
// to set the modTime or creationTime for a specific file you will have to
// create a new instance of a DatabaseFS using WithValues(), create that file,
// then throw the DatabaseFS instance away.
func (fsys *DatabaseFS) WithValues(values map[string]any) FS {
return &DatabaseFS{
DB: fsys.DB,
Dialect: fsys.Dialect,
ErrorCode: fsys.ErrorCode,
ObjectStorage: fsys.ObjectStorage,
Logger: fsys.Logger,
UpdateStorageUsed: fsys.UpdateStorageUsed,
ctx: fsys.ctx,
values: values,
}
}
// DatabaseFileInfo describes a file returned by DatabaseFS.
type DatabaseFileInfo struct {
FileID ID
FilePath string
isDir bool
size int64
modTime time.Time
CreationTime time.Time
}
// DatabaseFile represents a readable instance of a file returned by
// DatabaseFS.
type DatabaseFile struct {
// ctx provides the context of all operations called on the DatabaseFile.
ctx context.Context
// FileType of the DatabaseFile.
fileType FileType
// FileInfo of the DatabaseFile.
info *DatabaseFileInfo
// Whether the file is fulltext indexed.
isFulltextIndexed bool
// buf holds the raw bytes of the DatabaseFile. It may be gzipped,
// depending on whether the file is gzippable and is not fulltext indexed.
buf *bytes.Buffer
// If the file is gzippable and is not fulltext indexed, the raw bytes of
// the file are gzipped and Read operations should read from the gzipReader
// instead (which in turn reads from the raw bytes inside the buffer).
gzipReader *gzip.Reader
// If the file is an object, it is not stored by the database but rather by
// the filesystem's ObjectStorage provider. In which case, readCloser would
// be a reference to the object.
readCloser io.ReadCloser
}
// Open implements the Open FS operation for DatabaseFS.
func (fsys *DatabaseFS) Open(name string) (fs.File, error) {
err := fsys.ctx.Err()
if err != nil {
return nil, stacktrace.New(err)
}
if !fs.ValidPath(name) || strings.Contains(name, "\\") {
return nil, &fs.PathError{Op: "open", Path: name, Err: fs.ErrInvalid}
}
// If we are opening the root dir, return a hardcoded DatabaseFile
// representing the root (the root directory is not stored in a database
// FS, it is an implicit construct).
if name == "." {
file := &DatabaseFile{
ctx: fsys.ctx,
info: &DatabaseFileInfo{FilePath: ".", isDir: true},
}
return file, nil
}
var fileType FileType
if ext := path.Ext(name); ext != "" {
fileType = AllowedFileTypes[ext]
}
file, err := sq.FetchOne(fsys.ctx, fsys.DB, sq.Query{
Dialect: fsys.Dialect,
Format: "SELECT {*} FROM files WHERE file_path = {name}",
Values: []any{
sq.StringParam("name", name),
},
}, func(row *sq.Row) *DatabaseFile {
file := &DatabaseFile{
ctx: fsys.ctx,
fileType: fileType,
info: &DatabaseFileInfo{},
}
file.info.FileID = row.UUID("file_id")
file.info.FilePath = row.String("file_path")
file.info.isDir = row.Bool("is_dir")
file.info.size = row.Int64("size")
file.info.modTime = row.Time("mod_time")
file.info.CreationTime = row.Time("creation_time")
if !fileType.Has(AttributeObject) {
file.buf = bytes.NewBuffer(row.Bytes(bufPool.Get().(*bytes.Buffer).Bytes(), "COALESCE(text, data)"))
}
return file
})
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, &fs.PathError{Op: "open", Path: name, Err: fs.ErrNotExist}
}
return nil, stacktrace.New(err)
}
file.isFulltextIndexed = IsFulltextIndexed(file.info.FilePath)
if fileType.Has(AttributeObject) {
file.readCloser, err = fsys.ObjectStorage.Get(file.ctx, file.info.FileID.String()+path.Ext(file.info.FilePath))
if err != nil {
return nil, stacktrace.New(err)
}
// Writing an *os.File to net/http's ResponseWriter is fast on Linux
// because it uses the low-level sendfile(2) system call. If the
// underlying readCloser is an *os.File, return it directly so that
// static files can be served much faster.
// https://www.reddit.com/r/golang/comments/b9ewko/rob_pike_discovers_sendfile2_old_but_informative/hphp294/
// https://github.com/golang/go/blob/master/src/internal/poll/sendfile_linux.go
// https://github.com/golang/go/blob/f229e7031a6efb2f23241b5da000c3b3203081d6/src/io/io.go#L404
// https://github.com/golang/go/blob/f229e7031a6efb2f23241b5da000c3b3203081d6/src/net/tcpsock_posix.go#L47
if file, ok := file.readCloser.(*os.File); ok {
return file, nil
}
} else {
if file.fileType.Has(AttributeGzippable) && !file.isFulltextIndexed {
// Do NOT pass file.buf directly to gzip.Reader or it will do an
// unwanted read from the buffer! We want to keep file.buf unread
// in case someone wants to reach directly into it and pull out the
// raw gzipped bytes.
r := bytes.NewReader(file.buf.Bytes())
file.gzipReader, _ = gzipReaderPool.Get().(*gzip.Reader)
if file.gzipReader == nil {
file.gzipReader, err = gzip.NewReader(r)
if err != nil {
return nil, stacktrace.New(err)
}
} else {
err = file.gzipReader.Reset(r)
if err != nil {
return nil, stacktrace.New(err)
}
}
}
}
return file, nil
}
// Stat implements the fs.StatFS interface.
func (fsys *DatabaseFS) Stat(name string) (fs.FileInfo, error) {
err := fsys.ctx.Err()
if err != nil {
return nil, err
}
if !fs.ValidPath(name) || strings.Contains(name, "\\") {
return nil, &fs.PathError{Op: "stat", Path: name, Err: fs.ErrInvalid}
}
if name == "." {
return &DatabaseFileInfo{FilePath: ".", isDir: true}, nil
}
fileInfo, err := sq.FetchOne(fsys.ctx, fsys.DB, sq.Query{
Dialect: fsys.Dialect,
Format: "SELECT {*} FROM files WHERE file_path = {name}",
Values: []any{
sq.StringParam("name", name),
},
}, func(row *sq.Row) *DatabaseFileInfo {
return &DatabaseFileInfo{
FileID: row.UUID("file_id"),
FilePath: row.String("file_path"),
isDir: row.Bool("is_dir"),
size: row.Int64("size"),
modTime: row.Time("mod_time"),
CreationTime: row.Time("creation_time"),
}
})
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, &fs.PathError{Op: "stat", Path: name, Err: fs.ErrNotExist}
}
return nil, stacktrace.New(err)
}
return fileInfo, nil
}
// Base name of the file.
func (fileInfo *DatabaseFileInfo) Name() string { return path.Base(fileInfo.FilePath) }
// Size of the file in bytes.
func (fileInfo *DatabaseFileInfo) Size() int64 { return fileInfo.size }
// Modification time.
func (fileInfo *DatabaseFileInfo) ModTime() time.Time { return fileInfo.modTime }
// Whether the file is a directory.
func (fileInfo *DatabaseFileInfo) IsDir() bool { return fileInfo.isDir }
// Sys always returns nil.
func (fileInfo *DatabaseFileInfo) Sys() any { return nil }
// Type bits (needed to implement fs.DirEntry).
func (fileInfo *DatabaseFileInfo) Type() fs.FileMode { return fileInfo.Mode().Type() }
// Returns the file info (needed to implement fs.DirEntry).
func (fileInfo *DatabaseFileInfo) Info() (fs.FileInfo, error) { return fileInfo, nil }
// File mode bits.
func (fileInfo *DatabaseFileInfo) Mode() fs.FileMode {
if fileInfo.isDir {
return fs.ModeDir
}
return 0
}
// Stat returns the file info describing the file.
func (file *DatabaseFile) Stat() (fs.FileInfo, error) {
return file.info, nil
}
// Read reads up to len(b) bytes from the DatabaseFile and stores them in b. It
// returns the number of bytes read and any error encountered. At end of file,
// Read returns 0, io.EOF.
func (file *DatabaseFile) Read(p []byte) (n int, err error) {
err = file.ctx.Err()
if err != nil {
return 0, stacktrace.New(err)
}
if file.info.isDir {
return 0, &fs.PathError{Op: "read", Path: file.info.FilePath, Err: syscall.EISDIR}
}
if file.fileType.Has(AttributeObject) {
return file.readCloser.Read(p)
} else {
if file.fileType.Has(AttributeGzippable) && !file.isFulltextIndexed {
return file.gzipReader.Read(p)
} else {
return file.buf.Read(p)
}
}
}
// Close closes the DatabaseFile from reading.
func (file *DatabaseFile) Close() error {
if file.info.isDir {
return nil
}
if file.fileType.Has(AttributeObject) {
if file.readCloser == nil {
return fs.ErrClosed
}
err := file.readCloser.Close()
if err != nil {
return err
}
file.readCloser = nil
} else {
if file.fileType.Has(AttributeGzippable) && !file.isFulltextIndexed {
if file.gzipReader == nil {
return fs.ErrClosed
}
file.gzipReader.Reset(bytes.NewReader(nil))
gzipReaderPool.Put(file.gzipReader)
file.gzipReader = nil
if file.buf.Cap() <= maxPoolableBufferCapacity {
file.buf.Reset()
bufPool.Put(file.buf)
}
file.buf = nil
} else {
if file.buf == nil {
return fs.ErrClosed
}
if file.buf.Cap() <= maxPoolableBufferCapacity {
file.buf.Reset()
bufPool.Put(file.buf)
}
file.buf = nil
}
}
return nil
}
// DatabaseFileWriter represents a writable file on a DatabaseFS.
type DatabaseFileWriter struct {
// database connection.
db *sql.DB
// dialect of the database.
dialect string
// objectStorage is only used for deleting the object from object storage
// in case the database write fails (we don't want a bunch of partial
// writes to bloat the object storage with objects that have no database
// record).
objectStorage ObjectStorage
// logger is used for reporting errors that cannot be handled and are
// thrown away.
logger *slog.Logger
// updateStorageUsed is used to update the storage used by the site after
// the file has been fully written.
updateStorageUsed func(ctx context.Context, siteName string, delta int64) error
// ctx provides the context of all operations called on the DatabaseFileWriter.
ctx context.Context
// fileType of file.
fileType FileType
// Whether the file is fulltext indexed.
isFulltextIndexed bool
// Whether we are writing to an existing file or creating a new one.
exists bool
// fileID of the file.
fileID ID
// fileID of the file's parent.
parentID ID
// filePath of the file.
filePath string
// The file's initial size (if it exists).
initialSize int64
// The file's size after being written.
size int64
// buf holds the raw bytes of the DatabaseFileWriter. It may have first
// gone through the gzipWriter, depending on whether the file is gzippable
// and is not fulltext indexed.
buf *bytes.Buffer
// If the file is gzippable and is not fulltext indexed, all writes to the
// file first go through the gzipWriter before going into the buffer.
gzipWriter *gzip.Writer
// The value of the modTime to be set for the file.
modTime time.Time
// The value of the creationTime to be set for the file.
creationTime time.Time
// The value of the caption to be set for the image file. Images are stored
// in object storage so we can use the database's text field for storing
// captions.
caption string
// objectStorageWriter writes to the object in object storage.
objectStorageWriter *io.PipeWriter
// objectStorageResult holds the result of writing to the object in object
// storage.
objectStorageResult chan error
// writeFailed records if any writes to the DatabaseFileWriter failed.
writeFailed bool
}
// OpenWriter implements the OpenWriter FS operation for DatabaseFS.
func (fsys *DatabaseFS) OpenWriter(name string, _ fs.FileMode) (io.WriteCloser, error) {
err := fsys.ctx.Err()
if err != nil {
return nil, err
}
if !fs.ValidPath(name) || strings.Contains(name, "\\") {
return nil, &fs.PathError{Op: "openwriter", Path: name, Err: fs.ErrInvalid}
}
if name == "." {
return nil, &fs.PathError{Op: "openwriter", Path: name, Err: syscall.EISDIR}
}
var fileType FileType
if ext := path.Ext(name); ext != "" {
fileType = AllowedFileTypes[ext]
}
now := time.Now().UTC()
modTime := now
if value, ok := fsys.values["modTime"].(time.Time); ok {
modTime = value
}
creationTime := now
if value, ok := fsys.values["creationTime"].(time.Time); ok {
creationTime = value
}
caption := ""
if value, ok := fsys.values["caption"].(string); ok {
caption = value
}
file := &DatabaseFileWriter{
db: fsys.DB,
dialect: fsys.Dialect,
objectStorage: fsys.ObjectStorage,
logger: fsys.Logger,
updateStorageUsed: fsys.UpdateStorageUsed,
ctx: fsys.ctx,
fileType: fileType,
isFulltextIndexed: IsFulltextIndexed(name),
filePath: name,
modTime: modTime,
creationTime: creationTime,
caption: caption,
}
// Get the fileID as well as the parentID (if the file exists).
parentDir := path.Dir(file.filePath)
if parentDir == "." {
// If parentDir is the root directory ".", it doesn't exist in the
// database (it exists implicitly) so we don't have to fetch the
// parentID.
result, err := sq.FetchOne(fsys.ctx, fsys.DB, sq.Query{
Dialect: fsys.Dialect,
Format: "SELECT {*} FROM files WHERE file_path = {filePath}",
Values: []any{
sq.StringParam("filePath", file.filePath),
},
}, func(row *sq.Row) (result struct {
fileID ID
isDir bool
size int64
}) {
result.fileID = row.UUID("file_id")
result.isDir = row.Bool("is_dir")
result.size = row.Int64("size")
return result
})
if err != nil {
if !errors.Is(err, sql.ErrNoRows) {
return nil, stacktrace.New(err)
}
file.fileID = NewID()
} else {
if result.isDir {
return nil, &fs.PathError{Op: "openwriter", Path: name, Err: syscall.EISDIR}
}
file.exists = true
file.fileID = result.fileID
file.initialSize = result.size
}
} else {
results, err := sq.FetchAll(fsys.ctx, fsys.DB, sq.Query{
Dialect: fsys.Dialect,
Format: "SELECT {*} FROM files WHERE file_path IN ({parentDir}, {filePath})",
Values: []any{
sq.StringParam("parentDir", parentDir),
sq.StringParam("filePath", file.filePath),
},
}, func(row *sq.Row) (result struct {
fileID ID
filePath string
isDir bool
size int64
}) {
result.fileID = row.UUID("file_id")
result.filePath = row.String("file_path")
result.isDir = row.Bool("is_dir")
result.size = row.Int64("size")
return result
})
if err != nil {
return nil, stacktrace.New(err)
}
for _, result := range results {
switch result.filePath {
case name:
if result.isDir {
return nil, &fs.PathError{Op: "openwriter", Path: name, Err: syscall.EISDIR}
}
file.exists = true
file.fileID = result.fileID
file.initialSize = result.size
case parentDir:
if !result.isDir {
return nil, &fs.PathError{Op: "openwriter", Path: name, Err: syscall.ENOTDIR}
}
file.parentID = result.fileID
}
}
if file.parentID.IsZero() {
return nil, &fs.PathError{Op: "openwriter", Path: name, Err: fs.ErrNotExist}
}
if file.fileID.IsZero() {
file.fileID = NewID()
}
}
// Prepare the underlying writers.
if fileType.Has(AttributeObject) {
pipeReader, pipeWriter := io.Pipe()
file.objectStorageWriter = pipeWriter
file.objectStorageResult = make(chan error, 1)
go func() {
defer stacktrace.RecoverPanic(&err)
file.objectStorageResult <- fsys.ObjectStorage.Put(file.ctx, file.fileID.String()+path.Ext(file.filePath), pipeReader)
}()
} else {
if file.fileType.Has(AttributeGzippable) && !file.isFulltextIndexed {
file.buf = bufPool.Get().(*bytes.Buffer)
file.gzipWriter = gzipWriterPool.Get().(*gzip.Writer)
file.gzipWriter.Reset(file.buf)
} else {
file.buf = bufPool.Get().(*bytes.Buffer)
}
}
return file, nil
}
// Write writes len(b) bytes from b to the DatabaseFileWriter. It returns the
// number of bytes written and an error, if any. Write returns a non-nil error
// when n != len(b).
func (file *DatabaseFileWriter) Write(p []byte) (n int, err error) {
err = file.ctx.Err()
if err != nil {
file.writeFailed = true
return 0, err
}
if file.fileType.Has(AttributeObject) {
n, err = file.objectStorageWriter.Write(p)
if err != nil {
file.writeFailed = true
return n, stacktrace.New(err)
}
} else {
if file.fileType.Has(AttributeGzippable) && !file.isFulltextIndexed {
n, err = file.gzipWriter.Write(p)
if err != nil {
file.writeFailed = true
return n, stacktrace.New(err)
}
} else {
n, err = file.buf.Write(p)
if err != nil {
file.writeFailed = true
return n, stacktrace.New(err)
}
}
}
file.size += int64(n)
return n, nil
}
// ReadFrom implements io.ReaderFrom.
func (file *DatabaseFileWriter) ReadFrom(r io.Reader) (n int64, err error) {
err = file.ctx.Err()
if err != nil {
file.writeFailed = true
return 0, stacktrace.New(err)
}
if file.fileType.Has(AttributeObject) {
n, err = io.Copy(file.objectStorageWriter, r)
if err != nil {
file.writeFailed = true
return 0, stacktrace.New(err)
}
} else {
if file.fileType.Has(AttributeGzippable) && !file.isFulltextIndexed {
n, err = io.Copy(file.gzipWriter, r)
if err != nil {
file.writeFailed = true
return 0, stacktrace.New(err)
}
} else {
n, err = file.buf.ReadFrom(r)
if err != nil {
file.writeFailed = true
return 0, stacktrace.New(err)
}
}
}
file.size += int64(n)
return n, nil
}
// Close saves the contents of the DatabaseFileWriter into the database and
// closes the DatabaseFileWriter.
func (file *DatabaseFileWriter) Close() error {
if file.fileType.Has(AttributeObject) {
if file.objectStorageWriter == nil {
return fs.ErrClosed
}
file.objectStorageWriter.Close()
file.objectStorageWriter = nil
err := <-file.objectStorageResult
if err != nil {
return stacktrace.New(err)
}
} else {
if file.fileType.Has(AttributeGzippable) && !file.isFulltextIndexed {
if file.gzipWriter == nil {
return fs.ErrClosed
}
err := file.gzipWriter.Close()
if err != nil {
return stacktrace.New(err)
}
defer func() {
file.gzipWriter.Reset(io.Discard)
gzipWriterPool.Put(file.gzipWriter)
file.gzipWriter = nil
if file.buf.Cap() <= maxPoolableBufferCapacity {
file.buf.Reset()
bufPool.Put(file.buf)
}
file.buf = nil
}()
} else {
if file.buf == nil {
return fs.ErrClosed
}
defer func() {
if file.buf.Cap() <= maxPoolableBufferCapacity {
file.buf.Reset()
bufPool.Put(file.buf)
}
file.buf = nil
}()
}
}
if file.writeFailed {
return nil
}
if file.exists {
// If file exists, just have to update the file entry in the database.
if file.fileType.Has(AttributeObject) {
var text sql.NullString
if file.fileType.Has(AttributeImg) && file.caption != "" {
text = sql.NullString{String: file.caption, Valid: true}
}
_, err := sq.Exec(file.ctx, file.db, sq.Query{
Dialect: file.dialect,
Format: "UPDATE files SET text = {text}, data = NULL, size = {size}, mod_time = {modTime} WHERE file_id = {fileID}",
Values: []any{
sq.Param("text", text),
sq.Int64Param("size", file.size),
sq.TimeParam("modTime", file.modTime),
sq.UUIDParam("fileID", file.fileID),
},
})
if err != nil {
return stacktrace.New(err)
}
} else {
if file.fileType.Has(AttributeGzippable) && !file.isFulltextIndexed {
_, err := sq.Exec(file.ctx, file.db, sq.Query{
Dialect: file.dialect,
Format: "UPDATE files SET text = NULL, data = {data}, size = {size}, mod_time = {modTime} WHERE file_id = {fileID}",
Values: []any{
sq.BytesParam("data", file.buf.Bytes()),
sq.Int64Param("size", file.size),
sq.TimeParam("modTime", file.modTime),
sq.UUIDParam("fileID", file.fileID),
},
})
if err != nil {
return stacktrace.New(err)
}
} else {
_, err := sq.Exec(file.ctx, file.db, sq.Query{
Dialect: file.dialect,
Format: "UPDATE files SET text = {text}, data = NULL, size = {size}, mod_time = {modTime} WHERE file_id = {fileID}",
Values: []any{
sq.BytesParam("text", file.buf.Bytes()),
sq.Int64Param("size", file.size),
sq.TimeParam("modTime", file.modTime),
sq.UUIDParam("fileID", file.fileID),
},
})
if err != nil {
return stacktrace.New(err)
}
}
}
} else {
// If we reach here it means file doesn't exist. Insert a new file entry
// into the database.
if file.fileType.Has(AttributeObject) {
var text sql.NullString
if file.fileType.Has(AttributeImg) && file.caption != "" {
text = sql.NullString{String: file.caption, Valid: true}
}
_, err := sq.Exec(file.ctx, file.db, sq.Query{
Dialect: file.dialect,
Format: "INSERT INTO files (file_id, parent_id, file_path, size, text, mod_time, creation_time, is_dir)" +
" VALUES ({fileID}, {parentID}, {filePath}, {size}, {text}, {modTime}, {creationTime}, FALSE)",
Values: []any{
sq.UUIDParam("fileID", file.fileID),
sq.UUIDParam("parentID", file.parentID),
sq.StringParam("filePath", file.filePath),
sq.Int64Param("size", file.size),
sq.Param("text", text),
sq.TimeParam("modTime", file.modTime),
sq.TimeParam("creationTime", file.creationTime),
},
})
if err != nil {
go func() {
defer stacktrace.RecoverPanic(&err)
// This is a cleanup operation - don't pass in the file.ctx
// because file.ctx may be canceled and prevent the
// cleanup.
err := file.objectStorage.Delete(context.Background(), file.fileID.String()+path.Ext(file.filePath))
if err != nil {
file.logger.Error(stacktrace.New(err).Error())
}
}()
return err
}
} else {
if file.fileType.Has(AttributeGzippable) && !file.isFulltextIndexed {
_, err := sq.Exec(file.ctx, file.db, sq.Query{
Dialect: file.dialect,
Format: "INSERT INTO files (file_id, parent_id, file_path, size, data, mod_time, creation_time, is_dir)" +
" VALUES ({fileID}, {parentID}, {filePath}, {size}, {data}, {modTime}, {creationTime}, FALSE)",
Values: []any{
sq.UUIDParam("fileID", file.fileID),
sq.UUIDParam("parentID", file.parentID),
sq.StringParam("filePath", file.filePath),
sq.Int64Param("size", file.size),
sq.BytesParam("data", file.buf.Bytes()),
sq.TimeParam("modTime", file.modTime),
sq.TimeParam("creationTime", file.creationTime),
},
})
if err != nil {
return stacktrace.New(err)
}
} else {
_, err := sq.Exec(file.ctx, file.db, sq.Query{
Dialect: file.dialect,
Format: "INSERT INTO files (file_id, parent_id, file_path, size, text, mod_time, creation_time, is_dir)" +
" VALUES ({fileID}, {parentID}, {filePath}, {size}, {text}, {modTime}, {creationTime}, FALSE)",
Values: []any{
sq.UUIDParam("fileID", file.fileID),
sq.UUIDParam("parentID", file.parentID),
sq.StringParam("filePath", file.filePath),
sq.Int64Param("size", file.size),
sq.BytesParam("text", file.buf.Bytes()),
sq.TimeParam("modTime", file.modTime),
sq.TimeParam("creationTime", file.creationTime),
},
})
if err != nil {
return stacktrace.New(err)
}
}
}
}
delta := file.size - file.initialSize
if delta == 0 {
return nil
}
// Update the site's storage used.
if file.updateStorageUsed != nil {
var sitePrefix string
head, _, _ := strings.Cut(file.filePath, "/")
if strings.HasPrefix(head, "@") || strings.Contains(head, ".") {
sitePrefix = head
}
err := file.updateStorageUsed(file.ctx, strings.TrimPrefix(sitePrefix, "@"), delta)
if err != nil {
return stacktrace.New(err)
}
}
// Update the size of all ancestor directories.
ancestors := make([]string, 0, strings.Count(file.filePath, "/"))
for dir := path.Dir(file.filePath); dir != "."; dir = path.Dir(dir) {
ancestors = append(ancestors, dir)
}
if len(ancestors) > 0 {
_, err := sq.Exec(file.ctx, file.db, sq.Query{
Dialect: file.dialect,
Format: "UPDATE files" +
" SET size = CASE WHEN coalesce(size, 0) + {delta} >= 0 THEN coalesce(size, 0) + {delta} ELSE 0 END" +
" WHERE file_path IN ({ancestors})" +
" AND is_dir",
Values: []any{
sq.Int64Param("delta", delta),
sq.Param("ancestors", ancestors),
},
})
if err != nil {
return stacktrace.New(err)
}
}
return nil
}
// ReadDir implements the ReadDir FS operation for DatabaseFS.
func (fsys *DatabaseFS) ReadDir(name string) ([]fs.DirEntry, error) {
err := fsys.ctx.Err()
if err != nil {
return nil, err
}
if !fs.ValidPath(name) || strings.Contains(name, "\\") {
return nil, &fs.PathError{Op: "readdir", Path: name, Err: fs.ErrInvalid}
}
// NOTE: strictly speaking we should return some kind of error
// (syscall.ENOTDIR/fs.ErrNotExist) if name is not a dir, but that requires
// an additional database call and I'm not comfortable with that. For now
// we will just return zero entries and no error if the user calls
// ReadDir() on a file. This may change in the future if notebrew needs to
// differentiate calling ReadDir on a file vs on a directory.
var condition sq.Expression
if name == "." {
condition = sq.Expr("parent_id IS NULL")
} else {
condition = sq.Expr("parent_id = (SELECT file_id FROM files WHERE file_path = {})", name)
}
dirEntries, err := sq.FetchAll(fsys.ctx, fsys.DB, sq.Query{
Dialect: fsys.Dialect,
Format: "SELECT {*} FROM files WHERE {condition} ORDER BY file_path",
Values: []any{
sq.Param("condition", condition),
},
}, func(row *sq.Row) fs.DirEntry {
file := &DatabaseFileInfo{}
file.FileID = row.UUID("file_id")
file.FilePath = row.String("file_path")
file.isDir = row.Bool("is_dir")
file.size = row.Int64("size")
file.modTime = row.Time("mod_time")
file.CreationTime = row.Time("creation_time")
return file
})
if err != nil {
return nil, stacktrace.New(err)
}
return dirEntries, nil
}
// Mkdir implements the Mkdir FS operation for DatabaseFS.
func (fsys *DatabaseFS) Mkdir(name string, _ fs.FileMode) error {
err := fsys.ctx.Err()
if err != nil {
return err
}