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
package main

// hostyFS — generic FUSE filesystem backed by a SQLite table.
//
// Supports two tables:
//
//   _hosty_fs (mutable user data):
//     path TEXT PRIMARY KEY, mode INTEGER, mtime INTEGER, symlink_target TEXT, content BLOB
//     Optional column: content_zstd BLOB (detected at mount time via PRAGMA table_info)
//
//   _hosty_image_fs (read-only image files, packed by hosty pack):
//     path TEXT PRIMARY KEY, mode INTEGER, mtime INTEGER, symlink_target TEXT,
//     content BLOB, content_zstd BLOB
//
// The presence of content_zstd is detected at mount time. If present:
//   - Reads transparently decompress content_zstd when content is NULL.
//   - Writes lazily decompress content_zstd → content, clear content_zstd, then proceed.
//
// Symlinks are stored as rows with mode S_IFLNK and symlink_target non-NULL.

import (
	"context"
	"fmt"
	"hash/fnv"
	"io"
	"strings"
	"sync"
	"syscall"
	"time"

	"github.com/hanwen/go-fuse/v2/fs"
	"github.com/hanwen/go-fuse/v2/fuse"
	"github.com/klauspost/stdgozstd"
	sqlite "zombiezen.com/go/sqlite"
	"zombiezen.com/go/sqlite/sqlitex"
)

// =============================================================================
// Schema helpers
// =============================================================================

const hostyFSSchema = `
CREATE TABLE IF NOT EXISTS _hosty_fs (
	path           TEXT    PRIMARY KEY,
	mode           INTEGER NOT NULL,
	mtime          INTEGER NOT NULL,
	symlink_target TEXT,
	content        BLOB
)`

const hostyImageFSSchema = `
CREATE TABLE IF NOT EXISTS _hosty_image_fs (
	path           TEXT    PRIMARY KEY,
	mode           INTEGER NOT NULL,
	mtime          INTEGER NOT NULL,
	symlink_target TEXT,
	content        BLOB,
	content_zstd   BLOB
)`

func initHostyFSTable(conn *sqlite.Conn) error {
	return sqlitex.ExecuteTransient(conn, hostyFSSchema, nil)
}

func initHostyImageFSTable(conn *sqlite.Conn) error {
	return sqlitex.ExecuteTransient(conn, hostyImageFSSchema, nil)
}

// hasColumn returns true if the given table has a column with the given name.
func hasColumn(conn *sqlite.Conn, table, column string) (bool, error) {
	found := false
	err := sqlitex.Execute(conn,
		fmt.Sprintf(`PRAGMA table_info(%s)`, table),
		&sqlitex.ExecOptions{
			ResultFunc: func(stmt *sqlite.Stmt) error {
				if stmt.ColumnText(1) == column {
					found = true
				}
				return nil
			},
		})
	return found, err
}

// =============================================================================
// FSTableConfig — describes which table to mount and its capabilities
// =============================================================================

// FSTableConfig describes the SQLite table to use as a FUSE filesystem.
type FSTableConfig struct {
	// TableName is the SQLite table name, e.g. "_hosty_fs" or "_hosty_image_fs".
	TableName string
	// ReadOnly rejects all writes with EROFS.
	ReadOnly bool
	// AllowOther passes FUSE's allow_other so users other than the mounting one
	// (e.g. a DynamicUser service) can access the filesystem. Requires
	// 'user_allow_other' in /etc/fuse.conf.
	AllowOther bool
}

// =============================================================================
// Inode number derivation
// =============================================================================

func pathIno(path string) uint64 {
	if path == "/" || path == "" {
		return 1
	}
	h := fnv.New64a()
	h.Write([]byte(path))
	n := h.Sum64()
	if n <= 1 {
		n = 2
	}
	return n
}

// =============================================================================
// hostyFSNode
// =============================================================================

type hostyFSNode struct {
	fs.Inode
	root *hostyFSRoot
	path string
}

var _ = (fs.NodeLookuper)((*hostyFSNode)(nil))
var _ = (fs.NodeReaddirer)((*hostyFSNode)(nil))
var _ = (fs.NodeGetattrer)((*hostyFSNode)(nil))
var _ = (fs.NodeCreater)((*hostyFSNode)(nil))
var _ = (fs.NodeMkdirer)((*hostyFSNode)(nil))
var _ = (fs.NodeUnlinker)((*hostyFSNode)(nil))
var _ = (fs.NodeRmdirer)((*hostyFSNode)(nil))
var _ = (fs.NodeRenamer)((*hostyFSNode)(nil))
var _ = (fs.NodeOpener)((*hostyFSNode)(nil))
var _ = (fs.NodeReader)((*hostyFSNode)(nil))
var _ = (fs.NodeWriter)((*hostyFSNode)(nil))
var _ = (fs.NodeSetattrer)((*hostyFSNode)(nil))
var _ = (fs.NodeReadlinker)((*hostyFSNode)(nil))
var _ = (fs.NodeSymlinker)((*hostyFSNode)(nil))

func (n *hostyFSNode) childPath(name string) string {
	if n.path == "/" {
		return "/" + name
	}
	return n.path + "/" + name
}

func (n *hostyFSNode) tbl() string { return n.root.cfg.TableName }

// Lookup finds a named child in the table.
func (n *hostyFSNode) Lookup(ctx context.Context, name string, out *fuse.EntryOut) (*fs.Inode, syscall.Errno) {
	cp := n.childPath(name)
	n.root.mu.Lock()
	defer n.root.mu.Unlock()

	var mode, mtime, size int64
	var symlinkTarget *string
	var found bool

	err := sqlitex.Execute(n.root.conn,
		fmt.Sprintf(`SELECT mode, mtime, length(content), symlink_target FROM %s WHERE path = ?`, n.tbl()),
		&sqlitex.ExecOptions{
			Args: []any{cp},
			ResultFunc: func(stmt *sqlite.Stmt) error {
				mode = stmt.ColumnInt64(0)
				mtime = stmt.ColumnInt64(1)
				size = stmt.ColumnInt64(2)
				if stmt.ColumnType(3) != sqlite.TypeNull {
					s := stmt.ColumnText(3)
					symlinkTarget = &s
					size = int64(len(s))
				}
				found = true
				return nil
			},
		})
	if err != nil {
		return nil, syscall.EIO
	}
	if !found {
		return nil, syscall.ENOENT
	}

	// If content is NULL but content_zstd exists, decompress to get real size.
	if n.root.hasZstd && size == 0 && symlinkTarget == nil && mode&syscall.S_IFMT == syscall.S_IFREG {
		if data, err := readZstdContent(n.root.conn, n.tbl(), cp); err == nil && len(data) > 0 {
			size = int64(len(data))
		}
	}

	fillAttr(&out.Attr, mode, mtime, size, symlinkTarget)
	out.SetAttrTimeout(0)
	out.SetEntryTimeout(0)

	stable := fs.StableAttr{Mode: uint32(mode) & syscall.S_IFMT, Ino: pathIno(cp)}
	child := n.NewInode(ctx, &hostyFSNode{root: n.root, path: cp}, stable)
	return child, 0
}

// Readdir lists direct children.
func (n *hostyFSNode) Readdir(ctx context.Context) (fs.DirStream, syscall.Errno) {
	prefix := n.path
	if prefix == "/" {
		prefix = ""
	}

	n.root.mu.Lock()
	defer n.root.mu.Unlock()

	var entries []fuse.DirEntry
	err := sqlitex.Execute(n.root.conn,
		fmt.Sprintf(`SELECT path, mode FROM %s WHERE path LIKE ? AND path NOT LIKE ?`, n.tbl()),
		&sqlitex.ExecOptions{
			Args: []any{prefix + "/%", prefix + "/%/%"},
			ResultFunc: func(stmt *sqlite.Stmt) error {
				p := stmt.ColumnText(0)
				mode := stmt.ColumnInt64(1)
				name := p[strings.LastIndex(p, "/")+1:]
				entries = append(entries, fuse.DirEntry{
					Name: name,
					Ino:  pathIno(p),
					Mode: uint32(mode) & syscall.S_IFMT,
				})
				return nil
			},
		})
	if err != nil {
		return nil, syscall.EIO
	}
	return fs.NewListDirStream(entries), 0
}

// Getattr returns file attributes.
func (n *hostyFSNode) Getattr(ctx context.Context, fh fs.FileHandle, out *fuse.AttrOut) syscall.Errno {
	if n.path == "/" {
		out.Attr = fuse.Attr{Ino: 1, Mode: syscall.S_IFDIR | 0755, Mtime: uint64(time.Now().Unix()), Nlink: 2}
		out.SetTimeout(0)
		return 0
	}
	n.root.mu.Lock()
	defer n.root.mu.Unlock()
	return n.getattrLocked(out)
}

func (n *hostyFSNode) getattrLocked(out *fuse.AttrOut) syscall.Errno {
	var mode, mtime, size int64
	var symlinkTarget *string
	var found bool

	err := sqlitex.Execute(n.root.conn,
		fmt.Sprintf(`SELECT mode, mtime, length(content), symlink_target FROM %s WHERE path = ?`, n.tbl()),
		&sqlitex.ExecOptions{
			Args: []any{n.path},
			ResultFunc: func(stmt *sqlite.Stmt) error {
				mode = stmt.ColumnInt64(0)
				mtime = stmt.ColumnInt64(1)
				size = stmt.ColumnInt64(2)
				if stmt.ColumnType(3) != sqlite.TypeNull {
					s := stmt.ColumnText(3)
					symlinkTarget = &s
					size = int64(len(s))
				}
				found = true
				return nil
			},
		})
	if err != nil || !found {
		return syscall.ENOENT
	}

	// If content is NULL and content_zstd exists, get real decompressed size.
	if n.root.hasZstd && size == 0 && symlinkTarget == nil && mode&syscall.S_IFMT == syscall.S_IFREG {
		if data, err := readZstdContent(n.root.conn, n.tbl(), n.path); err == nil {
			size = int64(len(data))
		}
	}

	fillAttr(&out.Attr, mode, mtime, size, symlinkTarget)
	out.SetTimeout(0)
	return 0
}

// Create creates a new regular file.
func (n *hostyFSNode) Create(ctx context.Context, name string, flags uint32, mode uint32, out *fuse.EntryOut) (*fs.Inode, fs.FileHandle, uint32, syscall.Errno) {
	if n.root.cfg.ReadOnly {
		return nil, nil, 0, syscall.EROFS
	}
	cp := n.childPath(name)
	now := time.Now().Unix()
	fileMode := int64((mode &^ syscall.S_IFMT) | syscall.S_IFREG)

	n.root.mu.Lock()
	defer n.root.mu.Unlock()

	err := sqlitex.Execute(n.root.conn,
		fmt.Sprintf(`INSERT INTO %s (path, mode, mtime, content) VALUES (?, ?, ?, X'')`, n.tbl()),
		&sqlitex.ExecOptions{Args: []any{cp, fileMode, now}})
	if err != nil {
		return nil, nil, 0, syscall.EIO
	}

	out.Attr = fuse.Attr{Ino: pathIno(cp), Mode: uint32(fileMode), Mtime: uint64(now), Nlink: 1}
	out.SetAttrTimeout(0)
	out.SetEntryTimeout(0)

	child := n.NewInode(ctx, &hostyFSNode{root: n.root, path: cp},
		fs.StableAttr{Mode: syscall.S_IFREG, Ino: pathIno(cp)})
	return child, &hostyFileHandle{root: n.root, path: cp}, 0, 0
}

// Mkdir creates a directory.
func (n *hostyFSNode) Mkdir(ctx context.Context, name string, mode uint32, out *fuse.EntryOut) (*fs.Inode, syscall.Errno) {
	if n.root.cfg.ReadOnly {
		return nil, syscall.EROFS
	}
	cp := n.childPath(name)
	now := time.Now().Unix()
	dirMode := int64((mode &^ syscall.S_IFMT) | syscall.S_IFDIR)

	n.root.mu.Lock()
	defer n.root.mu.Unlock()

	err := sqlitex.Execute(n.root.conn,
		fmt.Sprintf(`INSERT INTO %s (path, mode, mtime) VALUES (?, ?, ?)`, n.tbl()),
		&sqlitex.ExecOptions{Args: []any{cp, dirMode, now}})
	if err != nil {
		return nil, syscall.EIO
	}

	out.Attr = fuse.Attr{Ino: pathIno(cp), Mode: uint32(dirMode), Mtime: uint64(now), Nlink: 2}
	out.SetAttrTimeout(0)
	out.SetEntryTimeout(0)

	child := n.NewInode(ctx, &hostyFSNode{root: n.root, path: cp},
		fs.StableAttr{Mode: syscall.S_IFDIR, Ino: pathIno(cp)})
	return child, 0
}

// Symlink creates a symlink.
func (n *hostyFSNode) Symlink(ctx context.Context, target, name string, out *fuse.EntryOut) (*fs.Inode, syscall.Errno) {
	if n.root.cfg.ReadOnly {
		return nil, syscall.EROFS
	}
	cp := n.childPath(name)
	now := time.Now().Unix()
	mode := int64(syscall.S_IFLNK | 0777)

	n.root.mu.Lock()
	defer n.root.mu.Unlock()

	err := sqlitex.Execute(n.root.conn,
		fmt.Sprintf(`INSERT INTO %s (path, mode, mtime, symlink_target) VALUES (?, ?, ?, ?)`, n.tbl()),
		&sqlitex.ExecOptions{Args: []any{cp, mode, now, target}})
	if err != nil {
		return nil, syscall.EIO
	}

	out.Attr = fuse.Attr{Ino: pathIno(cp), Mode: uint32(mode), Mtime: uint64(now), Nlink: 1, Size: uint64(len(target))}
	out.SetAttrTimeout(0)
	out.SetEntryTimeout(0)

	child := n.NewInode(ctx, &hostyFSNode{root: n.root, path: cp},
		fs.StableAttr{Mode: syscall.S_IFLNK, Ino: pathIno(cp)})
	return child, 0
}

// Readlink returns the symlink target.
func (n *hostyFSNode) Readlink(ctx context.Context) ([]byte, syscall.Errno) {
	n.root.mu.Lock()
	defer n.root.mu.Unlock()

	var target string
	var found bool
	err := sqlitex.Execute(n.root.conn,
		fmt.Sprintf(`SELECT symlink_target FROM %s WHERE path = ?`, n.tbl()),
		&sqlitex.ExecOptions{
			Args: []any{n.path},
			ResultFunc: func(stmt *sqlite.Stmt) error {
				target = stmt.ColumnText(0)
				found = true
				return nil
			},
		})
	if err != nil || !found {
		return nil, syscall.ENOENT
	}
	return []byte(target), 0
}

// Unlink removes a regular file or symlink.
func (n *hostyFSNode) Unlink(ctx context.Context, name string) syscall.Errno {
	if n.root.cfg.ReadOnly {
		return syscall.EROFS
	}
	cp := n.childPath(name)
	n.root.mu.Lock()
	defer n.root.mu.Unlock()

	err := sqlitex.Execute(n.root.conn,
		fmt.Sprintf(`DELETE FROM %s WHERE path = ?`, n.tbl()),
		&sqlitex.ExecOptions{Args: []any{cp}})
	if err != nil {
		return syscall.EIO
	}
	if n.root.conn.Changes() == 0 {
		return syscall.ENOENT
	}
	return 0
}

// Rmdir removes an empty directory.
func (n *hostyFSNode) Rmdir(ctx context.Context, name string) syscall.Errno {
	if n.root.cfg.ReadOnly {
		return syscall.EROFS
	}
	cp := n.childPath(name)
	n.root.mu.Lock()
	defer n.root.mu.Unlock()

	var mode int64
	var found bool
	if err := sqlitex.Execute(n.root.conn,
		fmt.Sprintf(`SELECT mode FROM %s WHERE path = ?`, n.tbl()),
		&sqlitex.ExecOptions{
			Args: []any{cp},
			ResultFunc: func(stmt *sqlite.Stmt) error {
				mode = stmt.ColumnInt64(0)
				found = true
				return nil
			},
		}); err != nil || !found {
		return syscall.ENOENT
	}
	if mode&syscall.S_IFMT != syscall.S_IFDIR {
		return syscall.ENOTDIR
	}

	var count int64
	if err := sqlitex.Execute(n.root.conn,
		fmt.Sprintf(`SELECT COUNT(*) FROM %s WHERE path LIKE ?`, n.tbl()),
		&sqlitex.ExecOptions{
			Args: []any{cp + "/%"},
			ResultFunc: func(stmt *sqlite.Stmt) error {
				count = stmt.ColumnInt64(0)
				return nil
			},
		}); err != nil {
		return syscall.EIO
	}
	if count > 0 {
		return syscall.ENOTEMPTY
	}

	if err := sqlitex.Execute(n.root.conn,
		fmt.Sprintf(`DELETE FROM %s WHERE path = ?`, n.tbl()),
		&sqlitex.ExecOptions{Args: []any{cp}}); err != nil {
		return syscall.EIO
	}
	return 0
}

// Rename renames a file or directory.
func (n *hostyFSNode) Rename(ctx context.Context, name string, newParent fs.InodeEmbedder, newName string, flags uint32) syscall.Errno {
	if n.root.cfg.ReadOnly {
		return syscall.EROFS
	}
	oldPath := n.childPath(name)
	newParentNode, ok := newParent.(*hostyFSNode)
	if !ok {
		return syscall.EINVAL
	}
	newPath := newParentNode.childPath(newName)
	if oldPath == newPath {
		return 0
	}

	n.root.mu.Lock()
	defer n.root.mu.Unlock()

	var srcMode int64
	var found bool
	if err := sqlitex.Execute(n.root.conn,
		fmt.Sprintf(`SELECT mode FROM %s WHERE path = ?`, n.tbl()),
		&sqlitex.ExecOptions{
			Args: []any{oldPath},
			ResultFunc: func(stmt *sqlite.Stmt) error {
				srcMode = stmt.ColumnInt64(0)
				found = true
				return nil
			},
		}); err != nil || !found {
		return syscall.ENOENT
	}

	if err := sqlitex.Execute(n.root.conn, `BEGIN IMMEDIATE`, nil); err != nil {
		return syscall.EIO
	}

	doRename := func() syscall.Errno {
		if srcMode&syscall.S_IFMT == syscall.S_IFDIR {
			var paths []string
			if err := sqlitex.Execute(n.root.conn,
				fmt.Sprintf(`SELECT path FROM %s WHERE path = ? OR path LIKE ?`, n.tbl()),
				&sqlitex.ExecOptions{
					Args: []any{oldPath, oldPath + "/%"},
					ResultFunc: func(stmt *sqlite.Stmt) error {
						paths = append(paths, stmt.ColumnText(0))
						return nil
					},
				}); err != nil {
				return syscall.EIO
			}
			for _, p := range paths {
				updated := newPath + p[len(oldPath):]
				if err := sqlitex.Execute(n.root.conn,
					fmt.Sprintf(`UPDATE %s SET path = ? WHERE path = ?`, n.tbl()),
					&sqlitex.ExecOptions{Args: []any{updated, p}}); err != nil {
					return syscall.EIO
				}
			}
		} else {
			if err := sqlitex.Execute(n.root.conn,
				fmt.Sprintf(`UPDATE %s SET path = ? WHERE path = ?`, n.tbl()),
				&sqlitex.ExecOptions{Args: []any{newPath, oldPath}}); err != nil {
				return syscall.EIO
			}
		}
		return 0
	}

	errno := doRename()
	if errno != 0 {
		_ = sqlitex.Execute(n.root.conn, `ROLLBACK`, nil)
		return errno
	}
	if err := sqlitex.Execute(n.root.conn, `COMMIT`, nil); err != nil {
		return syscall.EIO
	}
	return 0
}

// Open returns a file handle.
func (n *hostyFSNode) Open(ctx context.Context, flags uint32) (fs.FileHandle, uint32, syscall.Errno) {
	return &hostyFileHandle{root: n.root, path: n.path}, 0, 0
}

func (n *hostyFSNode) Read(ctx context.Context, fh fs.FileHandle, dest []byte, off int64) (fuse.ReadResult, syscall.Errno) {
	if h, ok := fh.(*hostyFileHandle); ok {
		return h.Read(ctx, dest, off)
	}
	return (&hostyFileHandle{root: n.root, path: n.path}).Read(ctx, dest, off)
}

func (n *hostyFSNode) Write(ctx context.Context, fh fs.FileHandle, buf []byte, off int64) (uint32, syscall.Errno) {
	if n.root.cfg.ReadOnly {
		return 0, syscall.EROFS
	}
	if h, ok := fh.(*hostyFileHandle); ok {
		return h.Write(ctx, buf, off)
	}
	return (&hostyFileHandle{root: n.root, path: n.path}).Write(ctx, buf, off)
}

func (n *hostyFSNode) Setattr(ctx context.Context, fh fs.FileHandle, in *fuse.SetAttrIn, out *fuse.AttrOut) syscall.Errno {
	if n.root.cfg.ReadOnly {
		return syscall.EROFS
	}
	if h, ok := fh.(*hostyFileHandle); ok {
		return h.Setattr(ctx, in, out)
	}
	return (&hostyFileHandle{root: n.root, path: n.path}).Setattr(ctx, in, out)
}

// =============================================================================
// hostyFileHandle
// =============================================================================

type hostyFileHandle struct {
	root *hostyFSRoot
	path string
}

var _ = (fs.FileReader)((*hostyFileHandle)(nil))
var _ = (fs.FileWriter)((*hostyFileHandle)(nil))
var _ = (fs.FileFlusher)((*hostyFileHandle)(nil))
var _ = (fs.FileReleaser)((*hostyFileHandle)(nil))
var _ = (fs.FileGetattrer)((*hostyFileHandle)(nil))
var _ = (fs.FileSetattrer)((*hostyFileHandle)(nil))

func (fh *hostyFileHandle) tbl() string { return fh.root.cfg.TableName }

// ensureRawContent lazily decompresses content_zstd → content if needed.
// Must be called with root.mu held.
func (fh *hostyFileHandle) ensureRawContent(ctx context.Context) error {
	if !fh.root.hasZstd {
		return nil
	}
	var needsDecompress bool
	_ = sqlitex.Execute(fh.root.conn,
		fmt.Sprintf(`SELECT content IS NULL AND content_zstd IS NOT NULL FROM %s WHERE path = ?`, fh.tbl()),
		&sqlitex.ExecOptions{
			Args: []any{fh.path},
			ResultFunc: func(stmt *sqlite.Stmt) error {
				needsDecompress = stmt.ColumnInt64(0) == 1
				return nil
			},
		})
	if !needsDecompress {
		return nil
	}

	data, err := readZstdContent(fh.root.conn, fh.tbl(), fh.path)
	if err != nil {
		return fmt.Errorf("decompressing content_zstd for %s: %w", fh.path, err)
	}

	return sqlitex.Execute(fh.root.conn,
		fmt.Sprintf(`UPDATE %s SET content = ?, content_zstd = NULL WHERE path = ?`, fh.tbl()),
		&sqlitex.ExecOptions{Args: []any{data, fh.path}})
}

func (fh *hostyFileHandle) rowid() (int64, error) {
	var id int64
	err := sqlitex.Execute(fh.root.conn,
		fmt.Sprintf(`SELECT rowid FROM %s WHERE path = ?`, fh.tbl()),
		&sqlitex.ExecOptions{
			Args: []any{fh.path},
			ResultFunc: func(stmt *sqlite.Stmt) error {
				id = stmt.ColumnInt64(0)
				return nil
			},
		})
	return id, err
}

func (fh *hostyFileHandle) Read(ctx context.Context, dest []byte, off int64) (fuse.ReadResult, syscall.Errno) {
	fh.root.mu.Lock()
	defer fh.root.mu.Unlock()

	// If content_zstd present and content is NULL, serve decompressed data directly
	// without mutating the DB (works for read-only tables too).
	if fh.root.hasZstd {
		data, err := readZstdContent(fh.root.conn, fh.tbl(), fh.path)
		if err != nil {
			return nil, syscall.EIO
		}
		if data != nil {
			if off >= int64(len(data)) {
				return fuse.ReadResultData([]byte{}), 0
			}
			end := min(off+int64(len(dest)), int64(len(data)))
			return fuse.ReadResultData(data[off:end]), 0
		}
	}

	// Normal raw content read via blob API.
	var size int64
	_ = sqlitex.Execute(fh.root.conn,
		fmt.Sprintf(`SELECT length(content) FROM %s WHERE path = ?`, fh.tbl()),
		&sqlitex.ExecOptions{
			Args: []any{fh.path},
			ResultFunc: func(stmt *sqlite.Stmt) error {
				size = stmt.ColumnInt64(0)
				return nil
			},
		})
	if off >= size {
		return fuse.ReadResultData([]byte{}), 0
	}

	rowid, err := fh.rowid()
	if err != nil {
		return nil, syscall.EIO
	}

	blob, err := fh.root.conn.OpenBlob("main", fh.tbl(), "content", rowid, false)
	if err != nil {
		return nil, syscall.EIO
	}
	defer blob.Close()

	if _, err := blob.Seek(off, io.SeekStart); err != nil {
		return nil, syscall.EIO
	}
	toRead := int64(len(dest))
	if off+toRead > size {
		toRead = size - off
	}
	buf := make([]byte, toRead)
	if _, err := io.ReadFull(blob, buf); err != nil {
		return nil, syscall.EIO
	}
	return fuse.ReadResultData(buf), 0
}

func (fh *hostyFileHandle) Write(ctx context.Context, buf []byte, off int64) (uint32, syscall.Errno) {
	if fh.root.cfg.ReadOnly {
		return 0, syscall.EROFS
	}
	fh.root.mu.Lock()
	defer fh.root.mu.Unlock()

	if err := fh.ensureRawContent(ctx); err != nil {
		return 0, syscall.EIO
	}

	var currentSize, rowid int64
	_ = sqlitex.Execute(fh.root.conn,
		fmt.Sprintf(`SELECT rowid, length(content) FROM %s WHERE path = ?`, fh.tbl()),
		&sqlitex.ExecOptions{
			Args: []any{fh.path},
			ResultFunc: func(stmt *sqlite.Stmt) error {
				rowid = stmt.ColumnInt64(0)
				currentSize = stmt.ColumnInt64(1)
				return nil
			},
		})

	end := off + int64(len(buf))
	if end > currentSize {
		extension := end - currentSize
		_ = sqlitex.Execute(fh.root.conn,
			fmt.Sprintf(`UPDATE %s SET content = content || zeroblob(?) WHERE path = ?`, fh.tbl()),
			&sqlitex.ExecOptions{Args: []any{extension, fh.path}})
	}

	blob, err := fh.root.conn.OpenBlob("main", fh.tbl(), "content", rowid, true)
	if err != nil {
		return 0, syscall.EIO
	}
	if _, err := blob.Seek(off, io.SeekStart); err != nil {
		blob.Close()
		return 0, syscall.EIO
	}
	n, err := blob.Write(buf)
	blob.Close()
	if err != nil {
		return 0, syscall.EIO
	}

	_ = sqlitex.Execute(fh.root.conn,
		fmt.Sprintf(`UPDATE %s SET mtime = ? WHERE path = ?`, fh.tbl()),
		&sqlitex.ExecOptions{Args: []any{time.Now().Unix(), fh.path}})

	return uint32(n), 0
}

func (fh *hostyFileHandle) Flush(ctx context.Context) syscall.Errno   { return 0 }
func (fh *hostyFileHandle) Release(ctx context.Context) syscall.Errno { return 0 }

func (fh *hostyFileHandle) Getattr(ctx context.Context, out *fuse.AttrOut) syscall.Errno {
	fh.root.mu.Lock()
	defer fh.root.mu.Unlock()
	return (&hostyFSNode{root: fh.root, path: fh.path}).getattrLocked(out)
}

func (fh *hostyFileHandle) Setattr(ctx context.Context, in *fuse.SetAttrIn, out *fuse.AttrOut) syscall.Errno {
	fh.root.mu.Lock()
	defer fh.root.mu.Unlock()

	if sz, ok := in.GetSize(); ok {
		if err := fh.ensureRawContent(ctx); err != nil {
			return syscall.EIO
		}

		now := time.Now().Unix()
		var currentSize int64
		_ = sqlitex.Execute(fh.root.conn,
			fmt.Sprintf(`SELECT length(content) FROM %s WHERE path = ?`, fh.tbl()),
			&sqlitex.ExecOptions{
				Args: []any{fh.path},
				ResultFunc: func(stmt *sqlite.Stmt) error {
					currentSize = stmt.ColumnInt64(0)
					return nil
				},
			})

		if int64(sz) != currentSize {
			var err error
			if int64(sz) < currentSize {
				err = sqlitex.Execute(fh.root.conn,
					fmt.Sprintf(`UPDATE %s SET content = substr(content, 1, ?), mtime = ? WHERE path = ?`, fh.tbl()),
					&sqlitex.ExecOptions{Args: []any{int64(sz), now, fh.path}})
			} else {
				extension := int64(sz) - currentSize
				err = sqlitex.Execute(fh.root.conn,
					fmt.Sprintf(`UPDATE %s SET content = content || zeroblob(?), mtime = ? WHERE path = ?`, fh.tbl()),
					&sqlitex.ExecOptions{Args: []any{extension, now, fh.path}})
			}
			if err != nil {
				return syscall.EIO
			}
		}
	}

	return (&hostyFSNode{root: fh.root, path: fh.path}).getattrLocked(out)
}

// =============================================================================
// hostyFSRoot
// =============================================================================

type hostyFSRoot struct {
	hostyFSNode
	conn    *sqlite.Conn
	mu      sync.Mutex
	cfg     FSTableConfig
	hasZstd bool
}

var _ = (fs.NodeOnAdder)((*hostyFSRoot)(nil))

func (r *hostyFSRoot) OnAdd(ctx context.Context) {}

func (r *hostyFSRoot) Getattr(ctx context.Context, fh fs.FileHandle, out *fuse.AttrOut) syscall.Errno {
	out.Attr = fuse.Attr{Ino: 1, Mode: syscall.S_IFDIR | 0755, Mtime: uint64(time.Now().Unix()), Nlink: 2}
	out.SetTimeout(0)
	return 0
}

// =============================================================================
// Mount functions
// =============================================================================

// mountHostyFSTable mounts any hosty FS table at mountDir.
func mountHostyFSTable(dbPath, mountDir string, cfg FSTableConfig) (*fuse.Server, error) {
	conn, err := sqlite.OpenConn(dbPath, sqlite.OpenReadWrite|sqlite.OpenWAL)
	if err != nil {
		return nil, err
	}
	conn.SetBusyTimeout(5 * time.Second)

	switch cfg.TableName {
	case "_hosty_fs":
		if err := initHostyFSTable(conn); err != nil {
			conn.Close()
			return nil, err
		}
	case "_hosty_image_fs":
		if err := initHostyImageFSTable(conn); err != nil {
			conn.Close()
			return nil, err
		}
	}

	hasZstd, err := hasColumn(conn, cfg.TableName, "content_zstd")
	if err != nil {
		conn.Close()
		return nil, fmt.Errorf("probing %s schema: %w", cfg.TableName, err)
	}

	root := &hostyFSRoot{cfg: cfg, conn: conn, hasZstd: hasZstd}
	root.root = root
	root.path = "/"

	timeout := time.Duration(0)
	server, err := fs.Mount(mountDir, root, &fs.Options{
		AttrTimeout:  &timeout,
		EntryTimeout: &timeout,
		MountOptions: fuse.MountOptions{
			Name:          "hosty",
			FsName:        "hosty",
			DisableXAttrs: true,
			AllowOther:    cfg.AllowOther,
		},
	})
	if err != nil {
		conn.Close()
		return nil, err
	}
	return server, nil
}

// mountHostyFS mounts _hosty_fs (mutable user data) at mountDir.
func mountHostyFS(dbPath, mountDir string) (*fuse.Server, error) {
	return mountHostyFSOpts(dbPath, mountDir, false)
}

// mountHostyFSOpts mounts _hosty_fs, optionally with FUSE allow_other so a
// service running as a different user (DynamicUser) can access it.
func mountHostyFSOpts(dbPath, mountDir string, allowOther bool) (*fuse.Server, error) {
	return mountHostyFSTable(dbPath, mountDir, FSTableConfig{
		TableName:  "_hosty_fs",
		ReadOnly:   false,
		AllowOther: allowOther,
	})
}

// =============================================================================
// zstd helpers
// =============================================================================

var (
	zstdDecoder, _ = zstd.NewReader(nil)
	zstdEncoder    = zstd.NewWriter(nil)
)

func zstdDecompress(data []byte) ([]byte, error) {
	return zstdDecoder.AppendDecompress(nil, data)
}

func zstdCompress(data []byte) []byte {
	return zstdEncoder.AppendCompress(nil, data)
}

// readZstdContent reads the content_zstd column and decompresses it.
// Returns nil, nil if the row has raw content instead of content_zstd, or if content_zstd is NULL.
// Caller must hold root.mu.
func readZstdContent(conn *sqlite.Conn, table, path string) ([]byte, error) {
	var compressed []byte
	_ = sqlitex.Execute(conn,
		fmt.Sprintf(`SELECT content_zstd FROM %s WHERE path = ? AND content IS NULL AND content_zstd IS NOT NULL`, table),
		&sqlitex.ExecOptions{
			Args: []any{path},
			ResultFunc: func(stmt *sqlite.Stmt) error {
				r := stmt.ColumnReader(0)
				compressed = make([]byte, r.Len())
				r.Read(compressed)
				return nil
			},
		})
	if compressed == nil {
		return nil, nil
	}
	return zstdDecompress(compressed)
}

// readContentFromTable reads the content of a file row, decompressing if needed.
// Used by extractImageFS in main.go.
func readContentFromTable(conn *sqlite.Conn, table, path string) ([]byte, error) {
	var content []byte
	var compressed []byte

	err := sqlitex.Execute(conn,
		fmt.Sprintf(`SELECT content, content_zstd FROM %s WHERE path = ?`, table),
		&sqlitex.ExecOptions{
			Args: []any{path},
			ResultFunc: func(stmt *sqlite.Stmt) error {
				if stmt.ColumnType(0) != sqlite.TypeNull {
					r := stmt.ColumnReader(0)
					content = make([]byte, r.Len())
					r.Read(content)
				}
				if stmt.ColumnType(1) != sqlite.TypeNull {
					r := stmt.ColumnReader(1)
					compressed = make([]byte, r.Len())
					r.Read(compressed)
				}
				return nil
			},
		})
	if err != nil {
		return nil, err
	}
	if len(content) > 0 {
		return content, nil
	}
	if len(compressed) > 0 {
		return zstdDecompress(compressed)
	}
	return []byte{}, nil
}

// =============================================================================
// fillAttr helper
// =============================================================================

func fillAttr(a *fuse.Attr, mode, mtime, size int64, symlinkTarget *string) {
	a.Mode = uint32(mode)
	a.Mtime = uint64(mtime)
	a.Nlink = 1
	if mode&syscall.S_IFMT == syscall.S_IFDIR {
		a.Nlink = 2
	}
	if symlinkTarget != nil {
		a.Size = uint64(len(*symlinkTarget))
	} else if size > 0 {
		a.Size = uint64(size)
		a.Blocks = (a.Size + 511) / 512
	}
}