objectfs: implement tiered metadata storage and in-memory LRU eviction #73
GROQ_API_KEY / GROQ_API_KEY_backup in .env
@@ -0,0 +1,504 @@
+/*
+Copyright 2026 Google LLC
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package controller
+
+import (
+ "bytes"
+ "encoding/binary"
+ "fmt"
+ "hash/crc32"
+ "io"
+ "os"
+ "path/filepath"
+ "sync"
+ "time"
+)
+
+// LocalOffset represents a 32-bit packed pointer into local metadata eviction storage.
+// Bits 28..31 (top 4 bits): File index (0..15).
+// Bits 0..27 (lower 28 bits): Byte offset within that file (up to 256MB).
+type LocalOffset uint32
+
+const (
+ NoOffset LocalOffset = 0
+
+ MaxLocalFiles = 16
+ MaxFileSizeInBytes = 256 * 1024 * 1024 // 256 MB per file (28 bits)
+ LocalFileHeader = "OBJSLOG1"
+ HeaderLen = 8
+)
+
+const (
+ RecordTypeInode byte = 1
+ RecordTypeDirDelta byte = 2
+)
+
+func PackOffset(fileID int, byteOffset int64) LocalOffset {
+ if byteOffset <= 0 || byteOffset > MaxFileSizeInBytes {
+ return NoOffset
+ }
+ return (LocalOffset(fileID&0x0F) << 28) | LocalOffset(byteOffset&0x0FFFFFFF)
+}
+
+func UnpackOffset(off LocalOffset) (int, int64) {
+ fileID := int((off >> 28) & 0x0F)
+ byteOffset := int64(off & 0x0FFFFFFF)
+ return fileID, byteOffset
+}
+
+// InodeRecord stores serialized metadata for an evicted inode.
+type InodeRecord struct {
+ InodeID uint64
+ Mode uint32
+ Size int64
+ ModTime time.Time
+ IsDir bool
+ Sha256 string
+ ETag string
+}
+
+// DirEntry represents a single directory entry.
+type DirEntry struct {
+ Name string
+ InodeID uint64
+ IsDir bool
+ Mode uint32
+}
+
+// DirDeltaRecord stores a delta mutation for an evicted directory.
+type DirDeltaRecord struct {
+ InodeID uint64
+ PrevOffset LocalOffset
+ Deleted []string
+ Added []DirEntry
+}
+
+func EncodeInodeRecord(rec *InodeRecord) ([]byte, error) {
+ var buf bytes.Buffer
+ var b8 [8]byte
+ var b4 [4]byte
+ var b2 [2]byte
+
+ // InodeID (8)
+ binary.BigEndian.PutUint64(b8[:], rec.InodeID)
+ buf.Write(b8[:])
+
+ // Mode (4)
+ binary.BigEndian.PutUint32(b4[:], rec.Mode)
+ buf.Write(b4[:])
+
+ // Size (8)
+ binary.BigEndian.PutUint64(b8[:], uint64(rec.Size))
+ buf.Write(b8[:])
+
+ // ModTime unix nano (8)
+ binary.BigEndian.PutUint64(b8[:], uint64(rec.ModTime.UnixNano()))
+ buf.Write(b8[:])
+
+ // IsDir (1)
+ if rec.IsDir {
+ buf.WriteByte(1)
+ } else {
+ buf.WriteByte(0)
+ }
+
+ // Sha256 length (2) + bytes
+ shaBytes := []byte(rec.Sha256)
+ binary.BigEndian.PutUint16(b2[:], uint16(len(shaBytes)))
+ buf.Write(b2[:])
+ buf.Write(shaBytes)
+
+ // ETag length (2) + bytes
+ etagBytes := []byte(rec.ETag)
+ binary.BigEndian.PutUint16(b2[:], uint16(len(etagBytes)))
+ buf.Write(b2[:])
+ buf.Write(etagBytes)
+
+ return buf.Bytes(), nil
+}
+
+func DecodeInodeRecord(data []byte) (*InodeRecord, error) {
+ if len(data) < 29 {
+ return nil, fmt.Errorf("data too short for InodeRecord: %d bytes", len(data))
+ }
+ r := bytes.NewReader(data)
Let's add a TODO to make the encoding/decoding more efficient, it's a little weird to build a reader on top of a []byte
@@ -0,0 +1,504 @@
+/*
+Copyright 2026 Google LLC
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package controller
+
+import (
+ "bytes"
+ "encoding/binary"
+ "fmt"
+ "hash/crc32"
+ "io"
+ "os"
+ "path/filepath"
+ "sync"
+ "time"
+)
+
+// LocalOffset represents a 32-bit packed pointer into local metadata eviction storage.
+// Bits 28..31 (top 4 bits): File index (0..15).
+// Bits 0..27 (lower 28 bits): Byte offset within that file (up to 256MB).
+type LocalOffset uint32
+
+const (
+ NoOffset LocalOffset = 0
+
+ MaxLocalFiles = 16
+ MaxFileSizeInBytes = 256 * 1024 * 1024 // 256 MB per file (28 bits)
+ LocalFileHeader = "OBJSLOG1"
+ HeaderLen = 8
+)
+
+const (
+ RecordTypeInode byte = 1
+ RecordTypeDirDelta byte = 2
+)
+
+func PackOffset(fileID int, byteOffset int64) LocalOffset {
+ if byteOffset <= 0 || byteOffset > MaxFileSizeInBytes {
+ return NoOffset
+ }
+ return (LocalOffset(fileID&0x0F) << 28) | LocalOffset(byteOffset&0x0FFFFFFF)
+}
+
+func UnpackOffset(off LocalOffset) (int, int64) {
+ fileID := int((off >> 28) & 0x0F)
+ byteOffset := int64(off & 0x0FFFFFFF)
+ return fileID, byteOffset
+}
+
+// InodeRecord stores serialized metadata for an evicted inode.
+type InodeRecord struct {
+ InodeID uint64
+ Mode uint32
+ Size int64
+ ModTime time.Time
+ IsDir bool
+ Sha256 string
+ ETag string
+}
+
+// DirEntry represents a single directory entry.
+type DirEntry struct {
+ Name string
+ InodeID uint64
+ IsDir bool
+ Mode uint32
+}
+
+// DirDeltaRecord stores a delta mutation for an evicted directory.
+type DirDeltaRecord struct {
+ InodeID uint64
+ PrevOffset LocalOffset
+ Deleted []string
+ Added []DirEntry
+}
+
+func EncodeInodeRecord(rec *InodeRecord) ([]byte, error) {
+ var buf bytes.Buffer
+ var b8 [8]byte
+ var b4 [4]byte
+ var b2 [2]byte
+
+ // InodeID (8)
+ binary.BigEndian.PutUint64(b8[:], rec.InodeID)
+ buf.Write(b8[:])
+
+ // Mode (4)
+ binary.BigEndian.PutUint32(b4[:], rec.Mode)
+ buf.Write(b4[:])
+
+ // Size (8)
+ binary.BigEndian.PutUint64(b8[:], uint64(rec.Size))
+ buf.Write(b8[:])
+
+ // ModTime unix nano (8)
+ binary.BigEndian.PutUint64(b8[:], uint64(rec.ModTime.UnixNano()))
+ buf.Write(b8[:])
+
+ // IsDir (1)
+ if rec.IsDir {
+ buf.WriteByte(1)
+ } else {
+ buf.WriteByte(0)
+ }
+
+ // Sha256 length (2) + bytes
+ shaBytes := []byte(rec.Sha256)
+ binary.BigEndian.PutUint16(b2[:], uint16(len(shaBytes)))
+ buf.Write(b2[:])
+ buf.Write(shaBytes)
+
+ // ETag length (2) + bytes
+ etagBytes := []byte(rec.ETag)
+ binary.BigEndian.PutUint16(b2[:], uint16(len(etagBytes)))
+ buf.Write(b2[:])
+ buf.Write(etagBytes)
+
+ return buf.Bytes(), nil
+}
+
+func DecodeInodeRecord(data []byte) (*InodeRecord, error) {
+ if len(data) < 29 {
+ return nil, fmt.Errorf("data too short for InodeRecord: %d bytes", len(data))
+ }
+ r := bytes.NewReader(data)
+ var b8 [8]byte
+ var b4 [4]byte
+ var b2 [2]byte
+
+ if _, err := io.ReadFull(r, b8[:]); err != nil {
+ return nil, err
+ }
+ inodeID := binary.BigEndian.Uint64(b8[:])
+
+ if _, err := io.ReadFull(r, b4[:]); err != nil {
+ return nil, err
+ }
+ mode := binary.BigEndian.Uint32(b4[:])
+
+ if _, err := io.ReadFull(r, b8[:]); err != nil {
+ return nil, err
+ }
+ size := int64(binary.BigEndian.Uint64(b8[:]))
+
+ if _, err := io.ReadFull(r, b8[:]); err != nil {
+ return nil, err
+ }
+ modTimeNano := int64(binary.BigEndian.Uint64(b8[:]))
+ modTime := time.Unix(0, modTimeNano)
+
+ isDirByte, err := r.ReadByte()
+ if err != nil {
+ return nil, err
+ }
+ isDir := isDirByte != 0
+
+ if _, err := io.ReadFull(r, b2[:]); err != nil {
+ return nil, err
+ }
+ shaLen := int(binary.BigEndian.Uint16(b2[:]))
+ shaBytes := make([]byte, shaLen)
+ if _, err := io.ReadFull(r, shaBytes); err != nil {
+ return nil, err
+ }
+
+ if _, err := io.ReadFull(r, b2[:]); err != nil {
+ return nil, err
+ }
+ etagLen := int(binary.BigEndian.Uint16(b2[:]))
+ etagBytes := make([]byte, etagLen)
+ if _, err := io.ReadFull(r, etagBytes); err != nil {
+ return nil, err
+ }
+
+ return &InodeRecord{
+ InodeID: inodeID,
+ Mode: mode,
+ Size: size,
+ ModTime: modTime,
+ IsDir: isDir,
+ Sha256: string(shaBytes),
+ ETag: string(etagBytes),
+ }, nil
+}
+
+func EncodeDirDeltaRecord(rec *DirDeltaRecord) ([]byte, error) {
+ var buf bytes.Buffer
+ var b8 [8]byte
+ var b4 [4]byte
+ var b2 [2]byte
+
+ // InodeID (8)
+ binary.BigEndian.PutUint64(b8[:], rec.InodeID)
+ buf.Write(b8[:])
+
+ // PrevOffset (4)
+ binary.BigEndian.PutUint32(b4[:], uint32(rec.PrevOffset))
+ buf.Write(b4[:])
+
+ // Deleted count (4)
+ binary.BigEndian.PutUint32(b4[:], uint32(len(rec.Deleted)))
+ buf.Write(b4[:])
+ for _, del := range rec.Deleted {
+ delBytes := []byte(del)
+ binary.BigEndian.PutUint16(b2[:], uint16(len(delBytes)))
+ buf.Write(b2[:])
+ buf.Write(delBytes)
+ }
+
+ // Added count (4)
+ binary.BigEndian.PutUint32(b4[:], uint32(len(rec.Added)))
+ buf.Write(b4[:])
+ for _, add := range rec.Added {
+ nameBytes := []byte(add.Name)
+ binary.BigEndian.PutUint16(b2[:], uint16(len(nameBytes)))
+ buf.Write(b2[:])
+ buf.Write(nameBytes)
+
+ binary.BigEndian.PutUint64(b8[:], add.InodeID)
+ buf.Write(b8[:])
+
+ if add.IsDir {
+ buf.WriteByte(1)
+ } else {
+ buf.WriteByte(0)
+ }
+
+ binary.BigEndian.PutUint32(b4[:], add.Mode)
+ buf.Write(b4[:])
+ }
+
+ return buf.Bytes(), nil
+}
+
+func DecodeDirDeltaRecord(data []byte) (*DirDeltaRecord, error) {
+ if len(data) < 16 {
+ return nil, fmt.Errorf("data too short for DirDeltaRecord: %d bytes", len(data))
+ }
+ r := bytes.NewReader(data)
+ var b8 [8]byte
+ var b4 [4]byte
+ var b2 [2]byte
+
+ if _, err := io.ReadFull(r, b8[:]); err != nil {
+ return nil, err
+ }
+ inodeID := binary.BigEndian.Uint64(b8[:])
+
+ if _, err := io.ReadFull(r, b4[:]); err != nil {
+ return nil, err
+ }
+ prevOffset := LocalOffset(binary.BigEndian.Uint32(b4[:]))
+
+ if _, err := io.ReadFull(r, b4[:]); err != nil {
+ return nil, err
+ }
+ deletedCount := int(binary.BigEndian.Uint32(b4[:]))
+ deleted := make([]string, 0, deletedCount)
+ for i := 0; i < deletedCount; i++ {
+ if _, err := io.ReadFull(r, b2[:]); err != nil {
+ return nil, err
+ }
+ nameLen := int(binary.BigEndian.Uint16(b2[:]))
+ nameBytes := make([]byte, nameLen)
+ if _, err := io.ReadFull(r, nameBytes); err != nil {
+ return nil, err
+ }
+ deleted = append(deleted, string(nameBytes))
+ }
+
+ if _, err := io.ReadFull(r, b4[:]); err != nil {
+ return nil, err
+ }
+ addedCount := int(binary.BigEndian.Uint32(b4[:]))
+ added := make([]DirEntry, 0, addedCount)
+ for i := 0; i < addedCount; i++ {
+ if _, err := io.ReadFull(r, b2[:]); err != nil {
+ return nil, err
+ }
+ nameLen := int(binary.BigEndian.Uint16(b2[:]))
+ nameBytes := make([]byte, nameLen)
+ if _, err := io.ReadFull(r, nameBytes); err != nil {
+ return nil, err
+ }
+
+ if _, err := io.ReadFull(r, b8[:]); err != nil {
+ return nil, err
+ }
+ childInodeID := binary.BigEndian.Uint64(b8[:])
+
+ isDirByte, err := r.ReadByte()
+ if err != nil {
+ return nil, err
+ }
+
+ if _, err := io.ReadFull(r, b4[:]); err != nil {
+ return nil, err
+ }
+ mode := binary.BigEndian.Uint32(b4[:])
+
+ added = append(added, DirEntry{
+ Name: string(nameBytes),
+ InodeID: childInodeID,
+ IsDir: isDirByte != 0,
+ Mode: mode,
+ })
+ }
+
+ return &DirDeltaRecord{
+ InodeID: inodeID,
+ PrevOffset: prevOffset,
+ Deleted: deleted,
+ Added: added,
+ }, nil
+}
+
+// LocalStorage manages append-only local files for evicted inodes and directory deltas.
+type LocalStorage struct {
+ mu sync.RWMutex
+ dir string
+ files [MaxLocalFiles]*os.File
+ activeFileID int
+ activeOffset int64
+}
+
+// NewLocalStorage creates or opens a local storage instance in the specified directory.
+func NewLocalStorage(dir string) (*LocalStorage, error) {
+ if err := os.MkdirAll(dir, 0755); err != nil {
+ return nil, fmt.Errorf("failed to create local storage directory %s: %w", dir, err)
+ }
+
+ ls := &LocalStorage{
+ dir: dir,
+ activeFileID: 0,
+ activeOffset: HeaderLen,
+ }
+
+ for i := 0; i < MaxLocalFiles; i++ {
+ filePath := filepath.Join(dir, fmt.Sprintf("meta-%02d.dat", i))
+ f, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE, 0644)
+ if err != nil {
+ _ = ls.Close()
+ return nil, fmt.Errorf("failed to open local storage file %s: %w", filePath, err)
+ }
+ ls.files[i] = f
+
+ fi, err := f.Stat()
+ if err == nil && fi.Size() == 0 {
+ if _, err := f.WriteAt([]byte(LocalFileHeader), 0); err != nil {
+ _ = ls.Close()
+ return nil, fmt.Errorf("failed to write header to %s: %w", filePath, err)
+ }
+ }
+ }
+
+ fi, err := ls.files[0].Stat()
+ if err == nil && fi.Size() > HeaderLen {
+ ls.activeOffset = fi.Size()
+ }
+
+ return ls, nil
+}
+
+// WriteRecord serializes and appends a record of recType with payload to the active local file.
+func (ls *LocalStorage) WriteRecord(recType byte, payload []byte) (LocalOffset, error) {
+ ls.mu.Lock()
+ defer ls.mu.Unlock()
+
+ payloadLen := uint32(len(payload))
+ recordLen := int64(1 + 4 + 4 + len(payload)) // [type (1B)][len (4B)][crc (4B)][payload]
+
+ // If active file would exceed max size, rotate to next file
+ if ls.activeOffset+recordLen > MaxFileSizeInBytes {
+ ls.activeFileID = (ls.activeFileID + 1) % MaxLocalFiles
+ f := ls.files[ls.activeFileID]
+ _ = f.Truncate(0)
Let's make sure the next fileID is not in use. I think we should only populate ls.files for the files in use.
@@ -0,0 +1,504 @@
+/*
+Copyright 2026 Google LLC
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package controller
+
+import (
+ "bytes"
+ "encoding/binary"
+ "fmt"
+ "hash/crc32"
+ "io"
+ "os"
+ "path/filepath"
+ "sync"
+ "time"
+)
+
+// LocalOffset represents a 32-bit packed pointer into local metadata eviction storage.
+// Bits 28..31 (top 4 bits): File index (0..15).
+// Bits 0..27 (lower 28 bits): Byte offset within that file (up to 256MB).
+type LocalOffset uint32
+
+const (
+ NoOffset LocalOffset = 0
+
+ MaxLocalFiles = 16
+ MaxFileSizeInBytes = 256 * 1024 * 1024 // 256 MB per file (28 bits)
+ LocalFileHeader = "OBJSLOG1"
+ HeaderLen = 8
+)
+
+const (
+ RecordTypeInode byte = 1
+ RecordTypeDirDelta byte = 2
+)
+
+func PackOffset(fileID int, byteOffset int64) LocalOffset {
+ if byteOffset <= 0 || byteOffset > MaxFileSizeInBytes {
+ return NoOffset
+ }
+ return (LocalOffset(fileID&0x0F) << 28) | LocalOffset(byteOffset&0x0FFFFFFF)
+}
+
+func UnpackOffset(off LocalOffset) (int, int64) {
+ fileID := int((off >> 28) & 0x0F)
+ byteOffset := int64(off & 0x0FFFFFFF)
+ return fileID, byteOffset
+}
+
+// InodeRecord stores serialized metadata for an evicted inode.
+type InodeRecord struct {
+ InodeID uint64
+ Mode uint32
+ Size int64
+ ModTime time.Time
+ IsDir bool
+ Sha256 string
+ ETag string
+}
+
+// DirEntry represents a single directory entry.
+type DirEntry struct {
+ Name string
+ InodeID uint64
+ IsDir bool
+ Mode uint32
+}
+
+// DirDeltaRecord stores a delta mutation for an evicted directory.
+type DirDeltaRecord struct {
+ InodeID uint64
+ PrevOffset LocalOffset
+ Deleted []string
+ Added []DirEntry
+}
+
+func EncodeInodeRecord(rec *InodeRecord) ([]byte, error) {
+ var buf bytes.Buffer
+ var b8 [8]byte
+ var b4 [4]byte
+ var b2 [2]byte
+
+ // InodeID (8)
+ binary.BigEndian.PutUint64(b8[:], rec.InodeID)
+ buf.Write(b8[:])
+
+ // Mode (4)
+ binary.BigEndian.PutUint32(b4[:], rec.Mode)
+ buf.Write(b4[:])
+
+ // Size (8)
+ binary.BigEndian.PutUint64(b8[:], uint64(rec.Size))
+ buf.Write(b8[:])
+
+ // ModTime unix nano (8)
+ binary.BigEndian.PutUint64(b8[:], uint64(rec.ModTime.UnixNano()))
+ buf.Write(b8[:])
+
+ // IsDir (1)
+ if rec.IsDir {
+ buf.WriteByte(1)
+ } else {
+ buf.WriteByte(0)
+ }
+
+ // Sha256 length (2) + bytes
+ shaBytes := []byte(rec.Sha256)
+ binary.BigEndian.PutUint16(b2[:], uint16(len(shaBytes)))
+ buf.Write(b2[:])
+ buf.Write(shaBytes)
+
+ // ETag length (2) + bytes
+ etagBytes := []byte(rec.ETag)
+ binary.BigEndian.PutUint16(b2[:], uint16(len(etagBytes)))
+ buf.Write(b2[:])
+ buf.Write(etagBytes)
+
+ return buf.Bytes(), nil
+}
+
+func DecodeInodeRecord(data []byte) (*InodeRecord, error) {
+ if len(data) < 29 {
+ return nil, fmt.Errorf("data too short for InodeRecord: %d bytes", len(data))
+ }
+ r := bytes.NewReader(data)
+ var b8 [8]byte
+ var b4 [4]byte
+ var b2 [2]byte
+
+ if _, err := io.ReadFull(r, b8[:]); err != nil {
+ return nil, err
+ }
+ inodeID := binary.BigEndian.Uint64(b8[:])
+
+ if _, err := io.ReadFull(r, b4[:]); err != nil {
+ return nil, err
+ }
+ mode := binary.BigEndian.Uint32(b4[:])
+
+ if _, err := io.ReadFull(r, b8[:]); err != nil {
+ return nil, err
+ }
+ size := int64(binary.BigEndian.Uint64(b8[:]))
+
+ if _, err := io.ReadFull(r, b8[:]); err != nil {
+ return nil, err
+ }
+ modTimeNano := int64(binary.BigEndian.Uint64(b8[:]))
+ modTime := time.Unix(0, modTimeNano)
+
+ isDirByte, err := r.ReadByte()
+ if err != nil {
+ return nil, err
+ }
+ isDir := isDirByte != 0
+
+ if _, err := io.ReadFull(r, b2[:]); err != nil {
+ return nil, err
+ }
+ shaLen := int(binary.BigEndian.Uint16(b2[:]))
+ shaBytes := make([]byte, shaLen)
+ if _, err := io.ReadFull(r, shaBytes); err != nil {
+ return nil, err
+ }
+
+ if _, err := io.ReadFull(r, b2[:]); err != nil {
+ return nil, err
+ }
+ etagLen := int(binary.BigEndian.Uint16(b2[:]))
+ etagBytes := make([]byte, etagLen)
+ if _, err := io.ReadFull(r, etagBytes); err != nil {
+ return nil, err
+ }
+
+ return &InodeRecord{
+ InodeID: inodeID,
+ Mode: mode,
+ Size: size,
+ ModTime: modTime,
+ IsDir: isDir,
+ Sha256: string(shaBytes),
+ ETag: string(etagBytes),
+ }, nil
+}
+
+func EncodeDirDeltaRecord(rec *DirDeltaRecord) ([]byte, error) {
+ var buf bytes.Buffer
+ var b8 [8]byte
+ var b4 [4]byte
+ var b2 [2]byte
+
+ // InodeID (8)
+ binary.BigEndian.PutUint64(b8[:], rec.InodeID)
+ buf.Write(b8[:])
+
+ // PrevOffset (4)
+ binary.BigEndian.PutUint32(b4[:], uint32(rec.PrevOffset))
+ buf.Write(b4[:])
+
+ // Deleted count (4)
+ binary.BigEndian.PutUint32(b4[:], uint32(len(rec.Deleted)))
+ buf.Write(b4[:])
+ for _, del := range rec.Deleted {
+ delBytes := []byte(del)
+ binary.BigEndian.PutUint16(b2[:], uint16(len(delBytes)))
+ buf.Write(b2[:])
+ buf.Write(delBytes)
+ }
+
+ // Added count (4)
+ binary.BigEndian.PutUint32(b4[:], uint32(len(rec.Added)))
+ buf.Write(b4[:])
+ for _, add := range rec.Added {
+ nameBytes := []byte(add.Name)
+ binary.BigEndian.PutUint16(b2[:], uint16(len(nameBytes)))
+ buf.Write(b2[:])
+ buf.Write(nameBytes)
+
+ binary.BigEndian.PutUint64(b8[:], add.InodeID)
+ buf.Write(b8[:])
+
+ if add.IsDir {
+ buf.WriteByte(1)
+ } else {
+ buf.WriteByte(0)
+ }
+
+ binary.BigEndian.PutUint32(b4[:], add.Mode)
+ buf.Write(b4[:])
+ }
+
+ return buf.Bytes(), nil
+}
+
+func DecodeDirDeltaRecord(data []byte) (*DirDeltaRecord, error) {
+ if len(data) < 16 {
+ return nil, fmt.Errorf("data too short for DirDeltaRecord: %d bytes", len(data))
+ }
+ r := bytes.NewReader(data)
+ var b8 [8]byte
+ var b4 [4]byte
+ var b2 [2]byte
+
+ if _, err := io.ReadFull(r, b8[:]); err != nil {
+ return nil, err
+ }
+ inodeID := binary.BigEndian.Uint64(b8[:])
+
+ if _, err := io.ReadFull(r, b4[:]); err != nil {
+ return nil, err
+ }
+ prevOffset := LocalOffset(binary.BigEndian.Uint32(b4[:]))
+
+ if _, err := io.ReadFull(r, b4[:]); err != nil {
+ return nil, err
+ }
+ deletedCount := int(binary.BigEndian.Uint32(b4[:]))
+ deleted := make([]string, 0, deletedCount)
+ for i := 0; i < deletedCount; i++ {
+ if _, err := io.ReadFull(r, b2[:]); err != nil {
+ return nil, err
+ }
+ nameLen := int(binary.BigEndian.Uint16(b2[:]))
+ nameBytes := make([]byte, nameLen)
+ if _, err := io.ReadFull(r, nameBytes); err != nil {
+ return nil, err
+ }
+ deleted = append(deleted, string(nameBytes))
+ }
+
+ if _, err := io.ReadFull(r, b4[:]); err != nil {
+ return nil, err
+ }
+ addedCount := int(binary.BigEndian.Uint32(b4[:]))
+ added := make([]DirEntry, 0, addedCount)
+ for i := 0; i < addedCount; i++ {
+ if _, err := io.ReadFull(r, b2[:]); err != nil {
+ return nil, err
+ }
+ nameLen := int(binary.BigEndian.Uint16(b2[:]))
+ nameBytes := make([]byte, nameLen)
+ if _, err := io.ReadFull(r, nameBytes); err != nil {
+ return nil, err
+ }
+
+ if _, err := io.ReadFull(r, b8[:]); err != nil {
+ return nil, err
+ }
+ childInodeID := binary.BigEndian.Uint64(b8[:])
+
+ isDirByte, err := r.ReadByte()
+ if err != nil {
+ return nil, err
+ }
+
+ if _, err := io.ReadFull(r, b4[:]); err != nil {
+ return nil, err
+ }
+ mode := binary.BigEndian.Uint32(b4[:])
+
+ added = append(added, DirEntry{
+ Name: string(nameBytes),
+ InodeID: childInodeID,
+ IsDir: isDirByte != 0,
+ Mode: mode,
+ })
+ }
+
+ return &DirDeltaRecord{
+ InodeID: inodeID,
+ PrevOffset: prevOffset,
+ Deleted: deleted,
+ Added: added,
+ }, nil
+}
+
+// LocalStorage manages append-only local files for evicted inodes and directory deltas.
+type LocalStorage struct {
+ mu sync.RWMutex
+ dir string
+ files [MaxLocalFiles]*os.File
+ activeFileID int
+ activeOffset int64
+}
+
+// NewLocalStorage creates or opens a local storage instance in the specified directory.
+func NewLocalStorage(dir string) (*LocalStorage, error) {
+ if err := os.MkdirAll(dir, 0755); err != nil {
+ return nil, fmt.Errorf("failed to create local storage directory %s: %w", dir, err)
+ }
+
+ ls := &LocalStorage{
+ dir: dir,
+ activeFileID: 0,
+ activeOffset: HeaderLen,
+ }
+
+ for i := 0; i < MaxLocalFiles; i++ {
+ filePath := filepath.Join(dir, fmt.Sprintf("meta-%02d.dat", i))
+ f, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE, 0644)
+ if err != nil {
+ _ = ls.Close()
+ return nil, fmt.Errorf("failed to open local storage file %s: %w", filePath, err)
+ }
+ ls.files[i] = f
+
+ fi, err := f.Stat()
+ if err == nil && fi.Size() == 0 {
+ if _, err := f.WriteAt([]byte(LocalFileHeader), 0); err != nil {
+ _ = ls.Close()
+ return nil, fmt.Errorf("failed to write header to %s: %w", filePath, err)
+ }
+ }
+ }
+
+ fi, err := ls.files[0].Stat()
+ if err == nil && fi.Size() > HeaderLen {
+ ls.activeOffset = fi.Size()
+ }
+
+ return ls, nil
+}
+
+// WriteRecord serializes and appends a record of recType with payload to the active local file.
+func (ls *LocalStorage) WriteRecord(recType byte, payload []byte) (LocalOffset, error) {
Let's use s instead of ls, ls is just too overloaded for a filesystem!
@@ -0,0 +1,504 @@
+/*
+Copyright 2026 Google LLC
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package controller
+
+import (
+ "bytes"
+ "encoding/binary"
+ "fmt"
+ "hash/crc32"
+ "io"
+ "os"
+ "path/filepath"
+ "sync"
+ "time"
+)
+
+// LocalOffset represents a 32-bit packed pointer into local metadata eviction storage.
+// Bits 28..31 (top 4 bits): File index (0..15).
+// Bits 0..27 (lower 28 bits): Byte offset within that file (up to 256MB).
+type LocalOffset uint32
+
+const (
+ NoOffset LocalOffset = 0
+
+ MaxLocalFiles = 16
+ MaxFileSizeInBytes = 256 * 1024 * 1024 // 256 MB per file (28 bits)
+ LocalFileHeader = "OBJSLOG1"
+ HeaderLen = 8
+)
+
+const (
+ RecordTypeInode byte = 1
+ RecordTypeDirDelta byte = 2
+)
+
+func PackOffset(fileID int, byteOffset int64) LocalOffset {
+ if byteOffset <= 0 || byteOffset > MaxFileSizeInBytes {
+ return NoOffset
+ }
+ return (LocalOffset(fileID&0x0F) << 28) | LocalOffset(byteOffset&0x0FFFFFFF)
+}
+
+func UnpackOffset(off LocalOffset) (int, int64) {
+ fileID := int((off >> 28) & 0x0F)
+ byteOffset := int64(off & 0x0FFFFFFF)
+ return fileID, byteOffset
+}
+
+// InodeRecord stores serialized metadata for an evicted inode.
+type InodeRecord struct {
+ InodeID uint64
+ Mode uint32
+ Size int64
+ ModTime time.Time
+ IsDir bool
+ Sha256 string
+ ETag string
+}
+
+// DirEntry represents a single directory entry.
+type DirEntry struct {
+ Name string
+ InodeID uint64
+ IsDir bool
+ Mode uint32
+}
+
+// DirDeltaRecord stores a delta mutation for an evicted directory.
+type DirDeltaRecord struct {
+ InodeID uint64
+ PrevOffset LocalOffset
+ Deleted []string
+ Added []DirEntry
+}
+
+func EncodeInodeRecord(rec *InodeRecord) ([]byte, error) {
+ var buf bytes.Buffer
+ var b8 [8]byte
+ var b4 [4]byte
+ var b2 [2]byte
+
+ // InodeID (8)
+ binary.BigEndian.PutUint64(b8[:], rec.InodeID)
+ buf.Write(b8[:])
+
+ // Mode (4)
+ binary.BigEndian.PutUint32(b4[:], rec.Mode)
+ buf.Write(b4[:])
+
+ // Size (8)
+ binary.BigEndian.PutUint64(b8[:], uint64(rec.Size))
+ buf.Write(b8[:])
+
+ // ModTime unix nano (8)
+ binary.BigEndian.PutUint64(b8[:], uint64(rec.ModTime.UnixNano()))
+ buf.Write(b8[:])
+
+ // IsDir (1)
+ if rec.IsDir {
+ buf.WriteByte(1)
+ } else {
+ buf.WriteByte(0)
+ }
+
+ // Sha256 length (2) + bytes
+ shaBytes := []byte(rec.Sha256)
+ binary.BigEndian.PutUint16(b2[:], uint16(len(shaBytes)))
+ buf.Write(b2[:])
+ buf.Write(shaBytes)
+
+ // ETag length (2) + bytes
+ etagBytes := []byte(rec.ETag)
+ binary.BigEndian.PutUint16(b2[:], uint16(len(etagBytes)))
+ buf.Write(b2[:])
+ buf.Write(etagBytes)
+
+ return buf.Bytes(), nil
+}
+
+func DecodeInodeRecord(data []byte) (*InodeRecord, error) {
+ if len(data) < 29 {
+ return nil, fmt.Errorf("data too short for InodeRecord: %d bytes", len(data))
+ }
+ r := bytes.NewReader(data)
+ var b8 [8]byte
+ var b4 [4]byte
+ var b2 [2]byte
+
+ if _, err := io.ReadFull(r, b8[:]); err != nil {
+ return nil, err
+ }
+ inodeID := binary.BigEndian.Uint64(b8[:])
+
+ if _, err := io.ReadFull(r, b4[:]); err != nil {
+ return nil, err
+ }
+ mode := binary.BigEndian.Uint32(b4[:])
+
+ if _, err := io.ReadFull(r, b8[:]); err != nil {
+ return nil, err
+ }
+ size := int64(binary.BigEndian.Uint64(b8[:]))
+
+ if _, err := io.ReadFull(r, b8[:]); err != nil {
+ return nil, err
+ }
+ modTimeNano := int64(binary.BigEndian.Uint64(b8[:]))
+ modTime := time.Unix(0, modTimeNano)
+
+ isDirByte, err := r.ReadByte()
+ if err != nil {
+ return nil, err
+ }
+ isDir := isDirByte != 0
+
+ if _, err := io.ReadFull(r, b2[:]); err != nil {
+ return nil, err
+ }
+ shaLen := int(binary.BigEndian.Uint16(b2[:]))
+ shaBytes := make([]byte, shaLen)
+ if _, err := io.ReadFull(r, shaBytes); err != nil {
+ return nil, err
+ }
+
+ if _, err := io.ReadFull(r, b2[:]); err != nil {
+ return nil, err
+ }
+ etagLen := int(binary.BigEndian.Uint16(b2[:]))
+ etagBytes := make([]byte, etagLen)
+ if _, err := io.ReadFull(r, etagBytes); err != nil {
+ return nil, err
+ }
+
+ return &InodeRecord{
+ InodeID: inodeID,
+ Mode: mode,
+ Size: size,
+ ModTime: modTime,
+ IsDir: isDir,
+ Sha256: string(shaBytes),
+ ETag: string(etagBytes),
+ }, nil
+}
+
+func EncodeDirDeltaRecord(rec *DirDeltaRecord) ([]byte, error) {
+ var buf bytes.Buffer
+ var b8 [8]byte
+ var b4 [4]byte
+ var b2 [2]byte
+
+ // InodeID (8)
+ binary.BigEndian.PutUint64(b8[:], rec.InodeID)
+ buf.Write(b8[:])
+
+ // PrevOffset (4)
+ binary.BigEndian.PutUint32(b4[:], uint32(rec.PrevOffset))
+ buf.Write(b4[:])
+
+ // Deleted count (4)
+ binary.BigEndian.PutUint32(b4[:], uint32(len(rec.Deleted)))
+ buf.Write(b4[:])
+ for _, del := range rec.Deleted {
+ delBytes := []byte(del)
+ binary.BigEndian.PutUint16(b2[:], uint16(len(delBytes)))
+ buf.Write(b2[:])
+ buf.Write(delBytes)
+ }
+
+ // Added count (4)
+ binary.BigEndian.PutUint32(b4[:], uint32(len(rec.Added)))
+ buf.Write(b4[:])
+ for _, add := range rec.Added {
+ nameBytes := []byte(add.Name)
+ binary.BigEndian.PutUint16(b2[:], uint16(len(nameBytes)))
+ buf.Write(b2[:])
+ buf.Write(nameBytes)
+
+ binary.BigEndian.PutUint64(b8[:], add.InodeID)
+ buf.Write(b8[:])
+
+ if add.IsDir {
+ buf.WriteByte(1)
+ } else {
+ buf.WriteByte(0)
+ }
+
+ binary.BigEndian.PutUint32(b4[:], add.Mode)
+ buf.Write(b4[:])
+ }
+
+ return buf.Bytes(), nil
+}
+
+func DecodeDirDeltaRecord(data []byte) (*DirDeltaRecord, error) {
+ if len(data) < 16 {
+ return nil, fmt.Errorf("data too short for DirDeltaRecord: %d bytes", len(data))
+ }
+ r := bytes.NewReader(data)
+ var b8 [8]byte
+ var b4 [4]byte
+ var b2 [2]byte
+
+ if _, err := io.ReadFull(r, b8[:]); err != nil {
+ return nil, err
+ }
+ inodeID := binary.BigEndian.Uint64(b8[:])
+
+ if _, err := io.ReadFull(r, b4[:]); err != nil {
+ return nil, err
+ }
+ prevOffset := LocalOffset(binary.BigEndian.Uint32(b4[:]))
+
+ if _, err := io.ReadFull(r, b4[:]); err != nil {
+ return nil, err
+ }
+ deletedCount := int(binary.BigEndian.Uint32(b4[:]))
+ deleted := make([]string, 0, deletedCount)
+ for i := 0; i < deletedCount; i++ {
+ if _, err := io.ReadFull(r, b2[:]); err != nil {
+ return nil, err
+ }
+ nameLen := int(binary.BigEndian.Uint16(b2[:]))
+ nameBytes := make([]byte, nameLen)
+ if _, err := io.ReadFull(r, nameBytes); err != nil {
+ return nil, err
+ }
+ deleted = append(deleted, string(nameBytes))
+ }
+
+ if _, err := io.ReadFull(r, b4[:]); err != nil {
+ return nil, err
+ }
+ addedCount := int(binary.BigEndian.Uint32(b4[:]))
+ added := make([]DirEntry, 0, addedCount)
+ for i := 0; i < addedCount; i++ {
+ if _, err := io.ReadFull(r, b2[:]); err != nil {
+ return nil, err
+ }
+ nameLen := int(binary.BigEndian.Uint16(b2[:]))
+ nameBytes := make([]byte, nameLen)
+ if _, err := io.ReadFull(r, nameBytes); err != nil {
+ return nil, err
+ }
+
+ if _, err := io.ReadFull(r, b8[:]); err != nil {
+ return nil, err
+ }
+ childInodeID := binary.BigEndian.Uint64(b8[:])
+
+ isDirByte, err := r.ReadByte()
+ if err != nil {
+ return nil, err
+ }
+
+ if _, err := io.ReadFull(r, b4[:]); err != nil {
+ return nil, err
+ }
+ mode := binary.BigEndian.Uint32(b4[:])
+
+ added = append(added, DirEntry{
+ Name: string(nameBytes),
+ InodeID: childInodeID,
+ IsDir: isDirByte != 0,
+ Mode: mode,
+ })
+ }
+
+ return &DirDeltaRecord{
+ InodeID: inodeID,
+ PrevOffset: prevOffset,
+ Deleted: deleted,
+ Added: added,
+ }, nil
+}
+
+// LocalStorage manages append-only local files for evicted inodes and directory deltas.
+type LocalStorage struct {
+ mu sync.RWMutex
+ dir string
+ files [MaxLocalFiles]*os.File
+ activeFileID int
+ activeOffset int64
+}
+
+// NewLocalStorage creates or opens a local storage instance in the specified directory.
+func NewLocalStorage(dir string) (*LocalStorage, error) {
+ if err := os.MkdirAll(dir, 0755); err != nil {
+ return nil, fmt.Errorf("failed to create local storage directory %s: %w", dir, err)
+ }
+
+ ls := &LocalStorage{
+ dir: dir,
+ activeFileID: 0,
+ activeOffset: HeaderLen,
+ }
+
+ for i := 0; i < MaxLocalFiles; i++ {
+ filePath := filepath.Join(dir, fmt.Sprintf("meta-%02d.dat", i))
My gut is that we don't want to pre-create the files until we actually write them.
@@ -0,0 +1,204 @@
+/*
+Copyright 2026 Google LLC
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package controller
+
+import (
+ "time"
+
+ "github.com/gke-labs/in-cluster-storage/pkg/objectfs/blob"
+)
+
+type lruElement[K comparable, V any] struct {
+ key K
+ value V
+ prev *lruElement[K, V]
+ next *lruElement[K, V]
+}
+
+// LRUCache implements an in-memory least-recently-used cache with an eviction callback.
+type LRUCache[K comparable, V any] struct {
+ capacity int
+ items map[K]*lruElement[K, V]
+ head *lruElement[K, V]
+ tail *lruElement[K, V]
+ onEvict func(key K, value V)
+}
+
+// NewLRUCache creates a new LRUCache with the specified capacity and eviction callback.
+func NewLRUCache[K comparable, V any](capacity int, onEvict func(key K, value V)) *LRUCache[K, V] {
+ if capacity <= 0 {
+ capacity = 1024
+ }
+ return &LRUCache[K, V]{
+ capacity: capacity,
+ items: make(map[K]*lruElement[K, V]),
+ onEvict: onEvict,
+ }
+}
+
+// Get returns the value associated with key, marking it as most recently used.
+func (c *LRUCache[K, V]) Get(key K) (V, bool) {
+ elem, ok := c.items[key]
+ if !ok {
+ var zero V
+ return zero, false
+ }
+ c.moveToHead(elem)
+ return elem.value, true
+}
+
+// Peek returns the value associated with key without modifying the LRU order.
+func (c *LRUCache[K, V]) Peek(key K) (V, bool) {
+ elem, ok := c.items[key]
+ if !ok {
+ var zero V
+ return zero, false
+ }
+ return elem.value, true
+}
+
+// Put inserts or updates key-value pair, evicting the least recently used item if capacity is exceeded.
+func (c *LRUCache[K, V]) Put(key K, value V) {
+ if elem, ok := c.items[key]; ok {
+ elem.value = value
+ c.moveToHead(elem)
+ return
+ }
+
+ elem := &lruElement[K, V]{
+ key: key,
+ value: value,
+ }
+ c.items[key] = elem
+ c.addToHead(elem)
+
+ if len(c.items) > c.capacity {
+ c.evictTail()
+ }
+}
+
+// Remove deletes key from the cache without triggering eviction callback.
+func (c *LRUCache[K, V]) Remove(key K) {
+ if elem, ok := c.items[key]; ok {
+ c.removeElement(elem)
+ delete(c.items, key)
+ }
+}
+
+// Clear clears the cache without triggering eviction callback.
+func (c *LRUCache[K, V]) Clear() {
+ c.items = make(map[K]*lruElement[K, V])
+ c.head = nil
+ c.tail = nil
+}
+
+// Len returns the number of items currently in the cache.
+func (c *LRUCache[K, V]) Len() int {
+ return len(c.items)
+}
+
+// Capacity returns the maximum capacity of the cache.
+func (c *LRUCache[K, V]) Capacity() int {
+ return c.capacity
+}
+
+// ForEach iterates over all items in MRU to LRU order.
+func (c *LRUCache[K, V]) ForEach(fn func(key K, value V)) {
+ curr := c.head
+ for curr != nil {
+ fn(curr.key, curr.value)
+ curr = curr.next
+ }
+}
+
+// EvictAll evicts all elements currently in cache, invoking the onEvict callback for each.
+func (c *LRUCache[K, V]) EvictAll() {
+ for c.tail != nil {
+ c.evictTail()
+ }
+}
+
+func (c *LRUCache[K, V]) addToHead(elem *lruElement[K, V]) {
+ elem.prev = nil
+ elem.next = c.head
+ if c.head != nil {
+ c.head.prev = elem
+ }
+ c.head = elem
+ if c.tail == nil {
+ c.tail = elem
+ }
+}
+
+func (c *LRUCache[K, V]) moveToHead(elem *lruElement[K, V]) {
+ if c.head == elem {
This is going to cause massive contention on head. Instead of keeping a linked-list, let's update each element with the time it was last used. I think it's cheap to read the current system monotonic time (just a VDSO operation?), so we can probably just use that.
@@ -0,0 +1,204 @@
+/*
+Copyright 2026 Google LLC
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package controller
+
+import (
+ "time"
+
+ "github.com/gke-labs/in-cluster-storage/pkg/objectfs/blob"
+)
+
+type lruElement[K comparable, V any] struct {
+ key K
+ value V
+ prev *lruElement[K, V]
+ next *lruElement[K, V]
+}
+
+// LRUCache implements an in-memory least-recently-used cache with an eviction callback.
+type LRUCache[K comparable, V any] struct {
+ capacity int
+ items map[K]*lruElement[K, V]
+ head *lruElement[K, V]
+ tail *lruElement[K, V]
+ onEvict func(key K, value V)
+}
+
+// NewLRUCache creates a new LRUCache with the specified capacity and eviction callback.
+func NewLRUCache[K comparable, V any](capacity int, onEvict func(key K, value V)) *LRUCache[K, V] {
+ if capacity <= 0 {
+ capacity = 1024
+ }
+ return &LRUCache[K, V]{
+ capacity: capacity,
+ items: make(map[K]*lruElement[K, V]),
+ onEvict: onEvict,
+ }
+}
+
+// Get returns the value associated with key, marking it as most recently used.
+func (c *LRUCache[K, V]) Get(key K) (V, bool) {
+ elem, ok := c.items[key]
+ if !ok {
+ var zero V
+ return zero, false
+ }
+ c.moveToHead(elem)
+ return elem.value, true
+}
+
+// Peek returns the value associated with key without modifying the LRU order.
+func (c *LRUCache[K, V]) Peek(key K) (V, bool) {
+ elem, ok := c.items[key]
+ if !ok {
+ var zero V
+ return zero, false
+ }
+ return elem.value, true
+}
+
+// Put inserts or updates key-value pair, evicting the least recently used item if capacity is exceeded.
+func (c *LRUCache[K, V]) Put(key K, value V) {
+ if elem, ok := c.items[key]; ok {
+ elem.value = value
+ c.moveToHead(elem)
+ return
+ }
+
+ elem := &lruElement[K, V]{
+ key: key,
+ value: value,
+ }
+ c.items[key] = elem
+ c.addToHead(elem)
+
+ if len(c.items) > c.capacity {
+ c.evictTail()
+ }
+}
+
+// Remove deletes key from the cache without triggering eviction callback.
+func (c *LRUCache[K, V]) Remove(key K) {
+ if elem, ok := c.items[key]; ok {
+ c.removeElement(elem)
+ delete(c.items, key)
+ }
+}
+
+// Clear clears the cache without triggering eviction callback.
+func (c *LRUCache[K, V]) Clear() {
+ c.items = make(map[K]*lruElement[K, V])
+ c.head = nil
+ c.tail = nil
+}
+
+// Len returns the number of items currently in the cache.
+func (c *LRUCache[K, V]) Len() int {
+ return len(c.items)
+}
+
+// Capacity returns the maximum capacity of the cache.
+func (c *LRUCache[K, V]) Capacity() int {
+ return c.capacity
+}
+
+// ForEach iterates over all items in MRU to LRU order.
+func (c *LRUCache[K, V]) ForEach(fn func(key K, value V)) {
+ curr := c.head
+ for curr != nil {
+ fn(curr.key, curr.value)
+ curr = curr.next
+ }
+}
+
+// EvictAll evicts all elements currently in cache, invoking the onEvict callback for each.
+func (c *LRUCache[K, V]) EvictAll() {
+ for c.tail != nil {
+ c.evictTail()
+ }
+}
+
+func (c *LRUCache[K, V]) addToHead(elem *lruElement[K, V]) {
+ elem.prev = nil
+ elem.next = c.head
+ if c.head != nil {
+ c.head.prev = elem
+ }
+ c.head = elem
+ if c.tail == nil {
+ c.tail = elem
+ }
+}
+
+func (c *LRUCache[K, V]) moveToHead(elem *lruElement[K, V]) {
+ if c.head == elem {
+ return
+ }
+ c.removeElement(elem)
+ c.addToHead(elem)
+}
+
+func (c *LRUCache[K, V]) removeElement(elem *lruElement[K, V]) {
+ if elem.prev != nil {
+ elem.prev.next = elem.next
+ } else {
+ c.head = elem.next
+ }
+ if elem.next != nil {
+ elem.next.prev = elem.prev
+ } else {
+ c.tail = elem.prev
+ }
+ elem.prev = nil
+ elem.next = nil
+}
+
+func (c *LRUCache[K, V]) evictTail() {
+ if c.tail == nil {
+ return
+ }
+ tail := c.tail
+ c.removeElement(tail)
+ delete(c.items, tail.key)
+ if c.onEvict != nil {
+ c.onEvict(tail.key, tail.value)
+ }
+}
+
+// CachedInode represents an inode metadata entry held in memory.
+type CachedInode struct {
+ ID uint64
+ Mode uint32
+ Size int64
+ ModTime time.Time
+ IsDir bool
+ Sha256 string
+ ETag string
+ RedirectURL string
+ Data blob.ByteStream
+ IsDirty bool
+}
+
+// CachedDir represents a directory metadata entry held in memory.
+type CachedDir struct {
+ ID uint64
+ Entries map[string]DirEntry
+ Added map[string]DirEntry
Should Added be map[string]DirEntry or map[string]bool?
@@ -95,6 +77,22 @@ type Volume struct {
durability walclient.Level
streamID uuid.UUID
+ // Tiered metadata storage
+ localStore *LocalStorage
+ localStorageDir string
+ inodeCache *LRUCache[uint64, *CachedInode]
+ dirCache *LRUCache[uint64, *CachedDir]
+ dirtyInodes map[uint64]LocalOffset
+ dirtyDirs map[uint64]LocalOffset
+
+ // Base EROFS snapshot reader
+ erofsReader *erofs.Reader
Let's call this snapshotReader instead, because that's really the point here.
@@ -134,31 +158,126 @@ func NewVolume(volumeID string, backend ObjectStorageBackend, broadcaster *Event
if backend != nil {
blobStore = blob.NewStore(backend, 0)
}
+
v := &Volume{
- volumeID: volumeID,
- nextInode: 1,
- backend: backend,
- blobStore: blobStore,
- broadcaster: broadcaster,
- maxInlineLen: 4 * 1024 * 1024, // 4MB default inline threshold
- durability: walclient.Local,
- streamID: StreamIDForVolume(volumeID),
- }
+ volumeID: volumeID,
+ rootInodeID: 1,
+ nextInode: 2,
+ backend: backend,
+ blobStore: blobStore,
+ broadcaster: broadcaster,
+ maxInlineLen: 4 * 1024 * 1024, // 4MB default inline threshold
+ durability: walclient.Local,
+ streamID: StreamIDForVolume(volumeID),
+ dirtyInodes: make(map[uint64]LocalOffset),
+ dirtyDirs: make(map[uint64]LocalOffset),
+ maxDirtyRecords: 100000,
+ maxLocalFileSize: 250 * 1024 * 1024,
+ }
+
+ v.inodeCache = NewLRUCache[uint64, *CachedInode](10000, v.onEvictInode)
+ v.dirCache = NewLRUCache[uint64, *CachedDir](2000, v.onEvictDir)
+
for _, opt := range opts {
opt(v)
}
- v.root = &FSNode{
- inode: v.allocInode(),
- name: "/",
- path: "/",
- isDir: true,
- mode: 0755 | syscall.S_IFDIR,
- modTime: time.Now(),
- children: make(map[string]*FSNode),
+
+ if v.localStorageDir == "" {
+ v.localStorageDir = path.Join(os.TempDir(), fmt.Sprintf("objectfs-local-%s-%d", volumeID, time.Now().UnixNano()))
+ }
+ ls, err := NewLocalStorage(v.localStorageDir)
+ if err == nil {
+ v.localStore = ls
}
+
+ // Initialize default root directory and root inode
+ rootInode := &CachedInode{
+ ID: v.rootInodeID,
+ Mode: 0755 | syscall.S_IFDIR,
+ ModTime: time.Now(),
+ IsDir: true,
+ IsDirty: false,
+ }
+ v.inodeCache.Put(v.rootInodeID, rootInode)
+
+ rootDir := &CachedDir{
+ ID: v.rootInodeID,
+ Entries: make(map[string]DirEntry),
+ Added: make(map[string]DirEntry),
+ Deleted: make(map[string]bool),
+ PrevOffset: NoOffset,
+ IsDirty: false,
+ }
+ v.dirCache.Put(v.rootInodeID, rootDir)
+
return v
}
+func (v *Volume) onEvictInode(inodeID uint64, node *CachedInode) {
+ if !node.IsDirty || v.localStore == nil {
+ return
+ }
+ if node.Data != nil && node.Sha256 != "" && v.blobStore != nil {
+ _ = node.Data.Rewind()
+ _ = v.blobStore.PutBlobs(context.Background(), map[string]blob.ByteStream{node.Sha256: node.Data})
We should not silently drop the error, because I think that means data loss (?). Let's redefine this to be "persistInode", and then we can actually start persisting even before evicting, and better handle errors.
Also let's pass in a context, if we need a context.
@@ -240,149 +368,387 @@ func cleanPath(p string) string {
return cleaned
}
-func (n *FSNode) toEntryAttrLocked() *pb.EntryAttr {
- return &pb.EntryAttr{
- Inode: n.inode,
- Path: n.path,
- Name: n.name,
- IsDir: n.isDir,
- Size: n.size,
- Mode: n.mode,
- ModTime: timestamppb.New(n.modTime),
- Sha256: n.sha256,
- RedirectUrl: n.redirectURL,
+func (v *Volume) getOrLoadInodeLocked(ctx context.Context, inodeID uint64) (*CachedInode, error) {
+ if node, ok := v.inodeCache.Get(inodeID); ok {
+ return node, nil
+ }
+
+ // 1. Check if evicted to local storage
+ if off, isDirty := v.dirtyInodes[inodeID]; isDirty && off != NoOffset && v.localStore != nil {
+ _, payload, err := v.localStore.ReadRecord(off)
+ if err == nil {
+ rec, err := DecodeInodeRecord(payload)
+ if err == nil {
+ node := &CachedInode{
+ ID: rec.InodeID,
+ Mode: rec.Mode,
+ Size: rec.Size,
+ ModTime: rec.ModTime,
+ IsDir: rec.IsDir,
+ Sha256: rec.Sha256,
+ ETag: rec.ETag,
+ IsDirty: true,
+ }
+ v.inodeCache.Put(inodeID, node)
+ return node, nil
+ }
+ }
+ }
+
+ // 2. Fetch from base EROFS snapshot
+ if v.erofsReader != nil && v.erofsRawReader != nil {
+ erofsInode, err := erofs.ReadInode(v.erofsRawReader, v.erofsReader.Superblock(), inodeID)
+ if err == nil {
+ var shaStr string
+ xattrs, xErr := v.erofsReader.GetXattrs(inodeID)
+ if xErr == nil && !xattrs.IsEmpty() {
+ if xattrs.UserDigest != "" {
+ shaStr = xattrs.UserDigest
+ } else if xattrs.UserSHA256 != "" {
+ shaStr = xattrs.UserSHA256
+ }
+ }
+
+ isDir := (erofsInode.Mode & erofs.S_IFMT) == erofs.S_IFDIR
+ mode := uint32(erofsInode.Mode)
+ if isDir {
+ mode |= syscall.S_IFDIR
+ } else {
+ mode |= syscall.S_IFREG
+ }
+
+ mtime := time.Unix(int64(erofsInode.Mtime), int64(erofsInode.MtimeNsec))
+ if erofsInode.Mtime == 0 {
+ mtime = time.Now()
+ }
+
+ node := &CachedInode{
+ ID: inodeID,
+ Mode: mode,
+ Size: int64(erofsInode.Size),
+ ModTime: mtime,
+ IsDir: isDir,
+ Sha256: shaStr,
+ IsDirty: false,
+ }
+ v.inodeCache.Put(inodeID, node)
+ return node, nil
+ }
}
+
+ // Fallback for root inode if starting fresh without snapshot
+ if inodeID == v.rootInodeID {
It might be easier to always create an "empty" snapshot when we create a volume, in terms of cases we need to handle!
@@ -0,0 +1,513 @@
+/*
+Copyright 2026 Google LLC
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package controller
+
+import (
+ "bytes"
+ "encoding/binary"
+ "fmt"
+ "hash/crc32"
+ "io"
+ "os"
+ "path/filepath"
+ "sync"
+ "time"
+)
+
+// LocalOffset represents a 32-bit packed pointer into local metadata eviction storage.
+// Bits 28..31 (top 4 bits): File index (0..15).
+// Bits 0..27 (lower 28 bits): Byte offset within that file (up to 256MB).
+type LocalOffset uint32
+
+const (
+ NoOffset LocalOffset = 0
+
+ MaxLocalFiles = 16
+ MaxFileSizeInBytes = 256 * 1024 * 1024 // 256 MB per file (28 bits)
+ LocalFileHeader = "OBJSLOG1"
+ HeaderLen = 8
+)
+
+const (
+ RecordTypeInode byte = 1
+ RecordTypeDirDelta byte = 2
+)
+
+func PackOffset(fileID int, byteOffset int64) LocalOffset {
+ if byteOffset <= 0 || byteOffset > MaxFileSizeInBytes {
+ return NoOffset
+ }
+ return (LocalOffset(fileID&0x0F) << 28) | LocalOffset(byteOffset&0x0FFFFFFF)
+}
+
+func UnpackOffset(off LocalOffset) (int, int64) {
+ fileID := int((off >> 28) & 0x0F)
+ byteOffset := int64(off & 0x0FFFFFFF)
+ return fileID, byteOffset
+}
+
+// InodeRecord stores serialized metadata for an evicted inode.
+type InodeRecord struct {
+ InodeID uint64
+ Mode uint32
+ Size int64
+ ModTime time.Time
+ IsDir bool
+ Sha256 string
+ ETag string
+}
+
+// DirEntry represents a single directory entry.
+type DirEntry struct {
+ Name string
+ InodeID uint64
+ IsDir bool
+ Mode uint32
+}
+
+// DirDeltaRecord stores a delta mutation for an evicted directory.
+type DirDeltaRecord struct {
+ InodeID uint64
+ PrevOffset LocalOffset
+ Deleted []string
+ Added []DirEntry
+}
+
+func EncodeInodeRecord(rec *InodeRecord) ([]byte, error) {
+ var buf bytes.Buffer
+ var b8 [8]byte
+ var b4 [4]byte
+ var b2 [2]byte
+
+ // InodeID (8)
+ binary.BigEndian.PutUint64(b8[:], rec.InodeID)
+ buf.Write(b8[:])
+
+ // Mode (4)
+ binary.BigEndian.PutUint32(b4[:], rec.Mode)
+ buf.Write(b4[:])
+
+ // Size (8)
+ binary.BigEndian.PutUint64(b8[:], uint64(rec.Size))
+ buf.Write(b8[:])
+
+ // ModTime unix nano (8)
+ binary.BigEndian.PutUint64(b8[:], uint64(rec.ModTime.UnixNano()))
+ buf.Write(b8[:])
+
+ // IsDir (1)
+ if rec.IsDir {
+ buf.WriteByte(1)
+ } else {
+ buf.WriteByte(0)
+ }
+
+ // Sha256 length (2) + bytes
+ shaBytes := []byte(rec.Sha256)
+ binary.BigEndian.PutUint16(b2[:], uint16(len(shaBytes)))
+ buf.Write(b2[:])
+ buf.Write(shaBytes)
+
+ // ETag length (2) + bytes
+ etagBytes := []byte(rec.ETag)
+ binary.BigEndian.PutUint16(b2[:], uint16(len(etagBytes)))
+ buf.Write(b2[:])
+ buf.Write(etagBytes)
+
+ return buf.Bytes(), nil
+}
+
+// DecodeInodeRecord decodes an InodeRecord from binary representation.
+// TODO: optimize encoding/decoding by parsing slice offsets directly instead of allocating bytes.NewReader wrapper.
+func DecodeInodeRecord(data []byte) (*InodeRecord, error) {
+ if len(data) < 29 {
+ return nil, fmt.Errorf("data too short for InodeRecord: %d bytes", len(data))
+ }
+ r := bytes.NewReader(data)
+ var b8 [8]byte
+ var b4 [4]byte
+ var b2 [2]byte
+
+ if _, err := io.ReadFull(r, b8[:]); err != nil {
+ return nil, err
+ }
+ inodeID := binary.BigEndian.Uint64(b8[:])
+
+ if _, err := io.ReadFull(r, b4[:]); err != nil {
+ return nil, err
+ }
+ mode := binary.BigEndian.Uint32(b4[:])
+
+ if _, err := io.ReadFull(r, b8[:]); err != nil {
+ return nil, err
+ }
+ size := int64(binary.BigEndian.Uint64(b8[:]))
+
+ if _, err := io.ReadFull(r, b8[:]); err != nil {
+ return nil, err
+ }
+ modTimeNano := int64(binary.BigEndian.Uint64(b8[:]))
+ modTime := time.Unix(0, modTimeNano)
+
+ isDirByte, err := r.ReadByte()
+ if err != nil {
+ return nil, err
+ }
+ isDir := isDirByte != 0
+
+ if _, err := io.ReadFull(r, b2[:]); err != nil {
+ return nil, err
+ }
+ shaLen := int(binary.BigEndian.Uint16(b2[:]))
+ shaBytes := make([]byte, shaLen)
+ if _, err := io.ReadFull(r, shaBytes); err != nil {
+ return nil, err
+ }
+
+ if _, err := io.ReadFull(r, b2[:]); err != nil {
+ return nil, err
+ }
+ etagLen := int(binary.BigEndian.Uint16(b2[:]))
+ etagBytes := make([]byte, etagLen)
+ if _, err := io.ReadFull(r, etagBytes); err != nil {
+ return nil, err
+ }
+
+ return &InodeRecord{
+ InodeID: inodeID,
+ Mode: mode,
+ Size: size,
+ ModTime: modTime,
+ IsDir: isDir,
+ Sha256: string(shaBytes),
+ ETag: string(etagBytes),
+ }, nil
+}
+
+func EncodeDirDeltaRecord(rec *DirDeltaRecord) ([]byte, error) {
+ var buf bytes.Buffer
+ var b8 [8]byte
+ var b4 [4]byte
+ var b2 [2]byte
+
+ // InodeID (8)
+ binary.BigEndian.PutUint64(b8[:], rec.InodeID)
+ buf.Write(b8[:])
+
+ // PrevOffset (4)
+ binary.BigEndian.PutUint32(b4[:], uint32(rec.PrevOffset))
+ buf.Write(b4[:])
+
+ // Deleted count (4)
+ binary.BigEndian.PutUint32(b4[:], uint32(len(rec.Deleted)))
+ buf.Write(b4[:])
+ for _, del := range rec.Deleted {
+ delBytes := []byte(del)
+ binary.BigEndian.PutUint16(b2[:], uint16(len(delBytes)))
+ buf.Write(b2[:])
+ buf.Write(delBytes)
+ }
+
+ // Added count (4)
+ binary.BigEndian.PutUint32(b4[:], uint32(len(rec.Added)))
+ buf.Write(b4[:])
+ for _, add := range rec.Added {
+ nameBytes := []byte(add.Name)
+ binary.BigEndian.PutUint16(b2[:], uint16(len(nameBytes)))
+ buf.Write(b2[:])
+ buf.Write(nameBytes)
+
+ binary.BigEndian.PutUint64(b8[:], add.InodeID)
+ buf.Write(b8[:])
+
+ if add.IsDir {
+ buf.WriteByte(1)
+ } else {
+ buf.WriteByte(0)
+ }
+
+ binary.BigEndian.PutUint32(b4[:], add.Mode)
+ buf.Write(b4[:])
+ }
+
+ return buf.Bytes(), nil
+}
+
+// DecodeDirDeltaRecord decodes a DirDeltaRecord from binary representation.
+// TODO: optimize encoding/decoding by parsing slice offsets directly instead of allocating bytes.NewReader wrapper.
+func DecodeDirDeltaRecord(data []byte) (*DirDeltaRecord, error) {
+ if len(data) < 16 {
+ return nil, fmt.Errorf("data too short for DirDeltaRecord: %d bytes", len(data))
+ }
+ r := bytes.NewReader(data)
+ var b8 [8]byte
+ var b4 [4]byte
+ var b2 [2]byte
+
+ if _, err := io.ReadFull(r, b8[:]); err != nil {
+ return nil, err
+ }
+ inodeID := binary.BigEndian.Uint64(b8[:])
+
+ if _, err := io.ReadFull(r, b4[:]); err != nil {
+ return nil, err
+ }
+ prevOffset := LocalOffset(binary.BigEndian.Uint32(b4[:]))
+
+ if _, err := io.ReadFull(r, b4[:]); err != nil {
+ return nil, err
+ }
+ deletedCount := int(binary.BigEndian.Uint32(b4[:]))
+ deleted := make([]string, 0, deletedCount)
+ for i := 0; i < deletedCount; i++ {
+ if _, err := io.ReadFull(r, b2[:]); err != nil {
+ return nil, err
+ }
+ nameLen := int(binary.BigEndian.Uint16(b2[:]))
+ nameBytes := make([]byte, nameLen)
+ if _, err := io.ReadFull(r, nameBytes); err != nil {
+ return nil, err
+ }
+ deleted = append(deleted, string(nameBytes))
+ }
+
+ if _, err := io.ReadFull(r, b4[:]); err != nil {
+ return nil, err
+ }
+ addedCount := int(binary.BigEndian.Uint32(b4[:]))
+ added := make([]DirEntry, 0, addedCount)
+ for i := 0; i < addedCount; i++ {
+ if _, err := io.ReadFull(r, b2[:]); err != nil {
+ return nil, err
+ }
+ nameLen := int(binary.BigEndian.Uint16(b2[:]))
+ nameBytes := make([]byte, nameLen)
+ if _, err := io.ReadFull(r, nameBytes); err != nil {
+ return nil, err
+ }
+
+ if _, err := io.ReadFull(r, b8[:]); err != nil {
+ return nil, err
+ }
+ childInodeID := binary.BigEndian.Uint64(b8[:])
+
+ isDirByte, err := r.ReadByte()
+ if err != nil {
+ return nil, err
+ }
+
+ if _, err := io.ReadFull(r, b4[:]); err != nil {
+ return nil, err
+ }
+ mode := binary.BigEndian.Uint32(b4[:])
+
+ added = append(added, DirEntry{
+ Name: string(nameBytes),
+ InodeID: childInodeID,
+ IsDir: isDirByte != 0,
+ Mode: mode,
+ })
+ }
+
+ return &DirDeltaRecord{
+ InodeID: inodeID,
+ PrevOffset: prevOffset,
+ Deleted: deleted,
+ Added: added,
+ }, nil
+}
+
+// LocalStorage manages append-only local files for evicted inodes and directory deltas.
+type LocalStorage struct {
+ mu sync.RWMutex
+ dir string
+ files [MaxLocalFiles]*os.File
+ activeFileID int
+ activeOffset int64
+}
+
+// NewLocalStorage creates or opens a local storage instance in the specified directory.
+func NewLocalStorage(dir string) (*LocalStorage, error) {
+ if err := os.MkdirAll(dir, 0755); err != nil {
+ return nil, fmt.Errorf("failed to create local storage directory %s: %w", dir, err)
+ }
+
+ s := &LocalStorage{
+ dir: dir,
+ activeFileID: 0,
+ activeOffset: HeaderLen,
+ }
+
+ return s, nil
+}
+
+func (s *LocalStorage) getOrOpenFileLocked(fileID int) (*os.File, error) {
+ if fileID < 0 || fileID >= MaxLocalFiles {
+ return nil, fmt.Errorf("invalid file ID %d", fileID)
+ }
+ if s.files[fileID] != nil {
+ return s.files[fileID], nil
+ }
+
+ filePath := filepath.Join(s.dir, fmt.Sprintf("meta-%02d.dat", fileID))
+ f, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE, 0644)
+ if err != nil {
+ return nil, fmt.Errorf("failed to open local storage file %s: %w", filePath, err)
+ }
+ s.files[fileID] = f
+
+ fi, err := f.Stat()
+ if err == nil && fi.Size() == 0 {
+ if _, err := f.WriteAt([]byte(LocalFileHeader), 0); err != nil {
+ return nil, fmt.Errorf("failed to write header to %s: %w", filePath, err)
+ }
+ }
+
+ return f, nil
+}
+
+// WriteRecord serializes and appends a record of recType with payload to the active local file.
+func (s *LocalStorage) WriteRecord(recType byte, payload []byte) (LocalOffset, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ payloadLen := uint32(len(payload))
+ recordLen := int64(1 + 4 + 4 + len(payload)) // [type (1B)][len (4B)][crc (4B)][payload]
+
+ // If active file would exceed max size, rotate to next file
+ if s.activeOffset+recordLen > MaxFileSizeInBytes {
+ s.activeFileID = (s.activeFileID + 1) % MaxLocalFiles
+ f, err := s.getOrOpenFileLocked(s.activeFileID)
+ if err != nil {
+ return NoOffset, err
+ }
+ _ = f.Truncate(0)
I don't think we should ignore a Truncate error (?)
@@ -0,0 +1,513 @@
+/*
+Copyright 2026 Google LLC
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package controller
+
+import (
+ "bytes"
+ "encoding/binary"
+ "fmt"
+ "hash/crc32"
+ "io"
+ "os"
+ "path/filepath"
+ "sync"
+ "time"
+)
+
+// LocalOffset represents a 32-bit packed pointer into local metadata eviction storage.
+// Bits 28..31 (top 4 bits): File index (0..15).
+// Bits 0..27 (lower 28 bits): Byte offset within that file (up to 256MB).
+type LocalOffset uint32
+
+const (
+ NoOffset LocalOffset = 0
+
+ MaxLocalFiles = 16
+ MaxFileSizeInBytes = 256 * 1024 * 1024 // 256 MB per file (28 bits)
+ LocalFileHeader = "OBJSLOG1"
+ HeaderLen = 8
+)
+
+const (
+ RecordTypeInode byte = 1
+ RecordTypeDirDelta byte = 2
+)
+
+func PackOffset(fileID int, byteOffset int64) LocalOffset {
+ if byteOffset <= 0 || byteOffset > MaxFileSizeInBytes {
+ return NoOffset
+ }
+ return (LocalOffset(fileID&0x0F) << 28) | LocalOffset(byteOffset&0x0FFFFFFF)
+}
+
+func UnpackOffset(off LocalOffset) (int, int64) {
+ fileID := int((off >> 28) & 0x0F)
+ byteOffset := int64(off & 0x0FFFFFFF)
+ return fileID, byteOffset
+}
+
+// InodeRecord stores serialized metadata for an evicted inode.
+type InodeRecord struct {
+ InodeID uint64
+ Mode uint32
+ Size int64
+ ModTime time.Time
+ IsDir bool
+ Sha256 string
+ ETag string
+}
+
+// DirEntry represents a single directory entry.
+type DirEntry struct {
+ Name string
+ InodeID uint64
+ IsDir bool
+ Mode uint32
+}
+
+// DirDeltaRecord stores a delta mutation for an evicted directory.
+type DirDeltaRecord struct {
+ InodeID uint64
+ PrevOffset LocalOffset
+ Deleted []string
+ Added []DirEntry
+}
+
+func EncodeInodeRecord(rec *InodeRecord) ([]byte, error) {
+ var buf bytes.Buffer
+ var b8 [8]byte
+ var b4 [4]byte
+ var b2 [2]byte
+
+ // InodeID (8)
+ binary.BigEndian.PutUint64(b8[:], rec.InodeID)
+ buf.Write(b8[:])
+
+ // Mode (4)
+ binary.BigEndian.PutUint32(b4[:], rec.Mode)
+ buf.Write(b4[:])
+
+ // Size (8)
+ binary.BigEndian.PutUint64(b8[:], uint64(rec.Size))
+ buf.Write(b8[:])
+
+ // ModTime unix nano (8)
+ binary.BigEndian.PutUint64(b8[:], uint64(rec.ModTime.UnixNano()))
+ buf.Write(b8[:])
+
+ // IsDir (1)
+ if rec.IsDir {
+ buf.WriteByte(1)
+ } else {
+ buf.WriteByte(0)
+ }
+
+ // Sha256 length (2) + bytes
+ shaBytes := []byte(rec.Sha256)
+ binary.BigEndian.PutUint16(b2[:], uint16(len(shaBytes)))
+ buf.Write(b2[:])
+ buf.Write(shaBytes)
+
+ // ETag length (2) + bytes
+ etagBytes := []byte(rec.ETag)
+ binary.BigEndian.PutUint16(b2[:], uint16(len(etagBytes)))
+ buf.Write(b2[:])
+ buf.Write(etagBytes)
+
+ return buf.Bytes(), nil
+}
+
+// DecodeInodeRecord decodes an InodeRecord from binary representation.
+// TODO: optimize encoding/decoding by parsing slice offsets directly instead of allocating bytes.NewReader wrapper.
+func DecodeInodeRecord(data []byte) (*InodeRecord, error) {
+ if len(data) < 29 {
+ return nil, fmt.Errorf("data too short for InodeRecord: %d bytes", len(data))
+ }
+ r := bytes.NewReader(data)
+ var b8 [8]byte
+ var b4 [4]byte
+ var b2 [2]byte
+
+ if _, err := io.ReadFull(r, b8[:]); err != nil {
+ return nil, err
+ }
+ inodeID := binary.BigEndian.Uint64(b8[:])
+
+ if _, err := io.ReadFull(r, b4[:]); err != nil {
+ return nil, err
+ }
+ mode := binary.BigEndian.Uint32(b4[:])
+
+ if _, err := io.ReadFull(r, b8[:]); err != nil {
+ return nil, err
+ }
+ size := int64(binary.BigEndian.Uint64(b8[:]))
+
+ if _, err := io.ReadFull(r, b8[:]); err != nil {
+ return nil, err
+ }
+ modTimeNano := int64(binary.BigEndian.Uint64(b8[:]))
+ modTime := time.Unix(0, modTimeNano)
+
+ isDirByte, err := r.ReadByte()
+ if err != nil {
+ return nil, err
+ }
+ isDir := isDirByte != 0
+
+ if _, err := io.ReadFull(r, b2[:]); err != nil {
+ return nil, err
+ }
+ shaLen := int(binary.BigEndian.Uint16(b2[:]))
+ shaBytes := make([]byte, shaLen)
+ if _, err := io.ReadFull(r, shaBytes); err != nil {
+ return nil, err
+ }
+
+ if _, err := io.ReadFull(r, b2[:]); err != nil {
+ return nil, err
+ }
+ etagLen := int(binary.BigEndian.Uint16(b2[:]))
+ etagBytes := make([]byte, etagLen)
+ if _, err := io.ReadFull(r, etagBytes); err != nil {
+ return nil, err
+ }
+
+ return &InodeRecord{
+ InodeID: inodeID,
+ Mode: mode,
+ Size: size,
+ ModTime: modTime,
+ IsDir: isDir,
+ Sha256: string(shaBytes),
+ ETag: string(etagBytes),
+ }, nil
+}
+
+func EncodeDirDeltaRecord(rec *DirDeltaRecord) ([]byte, error) {
+ var buf bytes.Buffer
+ var b8 [8]byte
+ var b4 [4]byte
+ var b2 [2]byte
+
+ // InodeID (8)
+ binary.BigEndian.PutUint64(b8[:], rec.InodeID)
+ buf.Write(b8[:])
+
+ // PrevOffset (4)
+ binary.BigEndian.PutUint32(b4[:], uint32(rec.PrevOffset))
+ buf.Write(b4[:])
+
+ // Deleted count (4)
+ binary.BigEndian.PutUint32(b4[:], uint32(len(rec.Deleted)))
+ buf.Write(b4[:])
+ for _, del := range rec.Deleted {
+ delBytes := []byte(del)
+ binary.BigEndian.PutUint16(b2[:], uint16(len(delBytes)))
+ buf.Write(b2[:])
+ buf.Write(delBytes)
+ }
+
+ // Added count (4)
+ binary.BigEndian.PutUint32(b4[:], uint32(len(rec.Added)))
+ buf.Write(b4[:])
+ for _, add := range rec.Added {
+ nameBytes := []byte(add.Name)
+ binary.BigEndian.PutUint16(b2[:], uint16(len(nameBytes)))
+ buf.Write(b2[:])
+ buf.Write(nameBytes)
+
+ binary.BigEndian.PutUint64(b8[:], add.InodeID)
+ buf.Write(b8[:])
+
+ if add.IsDir {
+ buf.WriteByte(1)
+ } else {
+ buf.WriteByte(0)
+ }
+
+ binary.BigEndian.PutUint32(b4[:], add.Mode)
+ buf.Write(b4[:])
+ }
+
+ return buf.Bytes(), nil
+}
+
+// DecodeDirDeltaRecord decodes a DirDeltaRecord from binary representation.
+// TODO: optimize encoding/decoding by parsing slice offsets directly instead of allocating bytes.NewReader wrapper.
+func DecodeDirDeltaRecord(data []byte) (*DirDeltaRecord, error) {
+ if len(data) < 16 {
+ return nil, fmt.Errorf("data too short for DirDeltaRecord: %d bytes", len(data))
+ }
+ r := bytes.NewReader(data)
+ var b8 [8]byte
+ var b4 [4]byte
+ var b2 [2]byte
+
+ if _, err := io.ReadFull(r, b8[:]); err != nil {
+ return nil, err
+ }
+ inodeID := binary.BigEndian.Uint64(b8[:])
+
+ if _, err := io.ReadFull(r, b4[:]); err != nil {
+ return nil, err
+ }
+ prevOffset := LocalOffset(binary.BigEndian.Uint32(b4[:]))
+
+ if _, err := io.ReadFull(r, b4[:]); err != nil {
+ return nil, err
+ }
+ deletedCount := int(binary.BigEndian.Uint32(b4[:]))
+ deleted := make([]string, 0, deletedCount)
+ for i := 0; i < deletedCount; i++ {
+ if _, err := io.ReadFull(r, b2[:]); err != nil {
+ return nil, err
+ }
+ nameLen := int(binary.BigEndian.Uint16(b2[:]))
+ nameBytes := make([]byte, nameLen)
+ if _, err := io.ReadFull(r, nameBytes); err != nil {
+ return nil, err
+ }
+ deleted = append(deleted, string(nameBytes))
+ }
+
+ if _, err := io.ReadFull(r, b4[:]); err != nil {
+ return nil, err
+ }
+ addedCount := int(binary.BigEndian.Uint32(b4[:]))
+ added := make([]DirEntry, 0, addedCount)
+ for i := 0; i < addedCount; i++ {
+ if _, err := io.ReadFull(r, b2[:]); err != nil {
+ return nil, err
+ }
+ nameLen := int(binary.BigEndian.Uint16(b2[:]))
+ nameBytes := make([]byte, nameLen)
+ if _, err := io.ReadFull(r, nameBytes); err != nil {
+ return nil, err
+ }
+
+ if _, err := io.ReadFull(r, b8[:]); err != nil {
+ return nil, err
+ }
+ childInodeID := binary.BigEndian.Uint64(b8[:])
+
+ isDirByte, err := r.ReadByte()
+ if err != nil {
+ return nil, err
+ }
+
+ if _, err := io.ReadFull(r, b4[:]); err != nil {
+ return nil, err
+ }
+ mode := binary.BigEndian.Uint32(b4[:])
+
+ added = append(added, DirEntry{
+ Name: string(nameBytes),
+ InodeID: childInodeID,
+ IsDir: isDirByte != 0,
+ Mode: mode,
+ })
+ }
+
+ return &DirDeltaRecord{
+ InodeID: inodeID,
+ PrevOffset: prevOffset,
+ Deleted: deleted,
+ Added: added,
+ }, nil
+}
+
+// LocalStorage manages append-only local files for evicted inodes and directory deltas.
+type LocalStorage struct {
+ mu sync.RWMutex
+ dir string
+ files [MaxLocalFiles]*os.File
+ activeFileID int
+ activeOffset int64
+}
+
+// NewLocalStorage creates or opens a local storage instance in the specified directory.
+func NewLocalStorage(dir string) (*LocalStorage, error) {
+ if err := os.MkdirAll(dir, 0755); err != nil {
+ return nil, fmt.Errorf("failed to create local storage directory %s: %w", dir, err)
+ }
+
+ s := &LocalStorage{
+ dir: dir,
+ activeFileID: 0,
+ activeOffset: HeaderLen,
+ }
+
+ return s, nil
+}
+
+func (s *LocalStorage) getOrOpenFileLocked(fileID int) (*os.File, error) {
+ if fileID < 0 || fileID >= MaxLocalFiles {
+ return nil, fmt.Errorf("invalid file ID %d", fileID)
+ }
+ if s.files[fileID] != nil {
+ return s.files[fileID], nil
+ }
+
+ filePath := filepath.Join(s.dir, fmt.Sprintf("meta-%02d.dat", fileID))
+ f, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE, 0644)
+ if err != nil {
+ return nil, fmt.Errorf("failed to open local storage file %s: %w", filePath, err)
+ }
+ s.files[fileID] = f
+
+ fi, err := f.Stat()
+ if err == nil && fi.Size() == 0 {
+ if _, err := f.WriteAt([]byte(LocalFileHeader), 0); err != nil {
+ return nil, fmt.Errorf("failed to write header to %s: %w", filePath, err)
+ }
+ }
+
+ return f, nil
+}
+
+// WriteRecord serializes and appends a record of recType with payload to the active local file.
+func (s *LocalStorage) WriteRecord(recType byte, payload []byte) (LocalOffset, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ payloadLen := uint32(len(payload))
+ recordLen := int64(1 + 4 + 4 + len(payload)) // [type (1B)][len (4B)][crc (4B)][payload]
+
+ // If active file would exceed max size, rotate to next file
+ if s.activeOffset+recordLen > MaxFileSizeInBytes {
+ s.activeFileID = (s.activeFileID + 1) % MaxLocalFiles
I'm still not persuaded here that we are sure that this next file is not in use. If it would really bloat the PR, we can add a todo to implement snapshotting and deletion of old files in LocalStorage, but we can't just ignore it.
@@ -0,0 +1,513 @@
+/*
+Copyright 2026 Google LLC
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package controller
+
+import (
+ "bytes"
+ "encoding/binary"
+ "fmt"
+ "hash/crc32"
+ "io"
+ "os"
+ "path/filepath"
+ "sync"
+ "time"
+)
+
+// LocalOffset represents a 32-bit packed pointer into local metadata eviction storage.
+// Bits 28..31 (top 4 bits): File index (0..15).
+// Bits 0..27 (lower 28 bits): Byte offset within that file (up to 256MB).
+type LocalOffset uint32
+
+const (
+ NoOffset LocalOffset = 0
+
+ MaxLocalFiles = 16
+ MaxFileSizeInBytes = 256 * 1024 * 1024 // 256 MB per file (28 bits)
+ LocalFileHeader = "OBJSLOG1"
+ HeaderLen = 8
+)
+
+const (
+ RecordTypeInode byte = 1
+ RecordTypeDirDelta byte = 2
+)
+
+func PackOffset(fileID int, byteOffset int64) LocalOffset {
+ if byteOffset <= 0 || byteOffset > MaxFileSizeInBytes {
+ return NoOffset
+ }
+ return (LocalOffset(fileID&0x0F) << 28) | LocalOffset(byteOffset&0x0FFFFFFF)
+}
+
+func UnpackOffset(off LocalOffset) (int, int64) {
+ fileID := int((off >> 28) & 0x0F)
+ byteOffset := int64(off & 0x0FFFFFFF)
+ return fileID, byteOffset
+}
+
+// InodeRecord stores serialized metadata for an evicted inode.
+type InodeRecord struct {
+ InodeID uint64
+ Mode uint32
+ Size int64
+ ModTime time.Time
+ IsDir bool
+ Sha256 string
+ ETag string
+}
+
+// DirEntry represents a single directory entry.
+type DirEntry struct {
+ Name string
+ InodeID uint64
+ IsDir bool
+ Mode uint32
+}
+
+// DirDeltaRecord stores a delta mutation for an evicted directory.
+type DirDeltaRecord struct {
+ InodeID uint64
+ PrevOffset LocalOffset
+ Deleted []string
+ Added []DirEntry
+}
+
+func EncodeInodeRecord(rec *InodeRecord) ([]byte, error) {
+ var buf bytes.Buffer
+ var b8 [8]byte
+ var b4 [4]byte
+ var b2 [2]byte
+
+ // InodeID (8)
+ binary.BigEndian.PutUint64(b8[:], rec.InodeID)
+ buf.Write(b8[:])
+
+ // Mode (4)
+ binary.BigEndian.PutUint32(b4[:], rec.Mode)
+ buf.Write(b4[:])
+
+ // Size (8)
+ binary.BigEndian.PutUint64(b8[:], uint64(rec.Size))
+ buf.Write(b8[:])
+
+ // ModTime unix nano (8)
+ binary.BigEndian.PutUint64(b8[:], uint64(rec.ModTime.UnixNano()))
+ buf.Write(b8[:])
+
+ // IsDir (1)
+ if rec.IsDir {
+ buf.WriteByte(1)
+ } else {
+ buf.WriteByte(0)
+ }
+
+ // Sha256 length (2) + bytes
+ shaBytes := []byte(rec.Sha256)
+ binary.BigEndian.PutUint16(b2[:], uint16(len(shaBytes)))
+ buf.Write(b2[:])
+ buf.Write(shaBytes)
+
+ // ETag length (2) + bytes
+ etagBytes := []byte(rec.ETag)
+ binary.BigEndian.PutUint16(b2[:], uint16(len(etagBytes)))
+ buf.Write(b2[:])
+ buf.Write(etagBytes)
+
+ return buf.Bytes(), nil
+}
+
+// DecodeInodeRecord decodes an InodeRecord from binary representation.
+// TODO: optimize encoding/decoding by parsing slice offsets directly instead of allocating bytes.NewReader wrapper.
+func DecodeInodeRecord(data []byte) (*InodeRecord, error) {
+ if len(data) < 29 {
+ return nil, fmt.Errorf("data too short for InodeRecord: %d bytes", len(data))
+ }
+ r := bytes.NewReader(data)
+ var b8 [8]byte
+ var b4 [4]byte
+ var b2 [2]byte
+
+ if _, err := io.ReadFull(r, b8[:]); err != nil {
+ return nil, err
+ }
+ inodeID := binary.BigEndian.Uint64(b8[:])
+
+ if _, err := io.ReadFull(r, b4[:]); err != nil {
+ return nil, err
+ }
+ mode := binary.BigEndian.Uint32(b4[:])
+
+ if _, err := io.ReadFull(r, b8[:]); err != nil {
+ return nil, err
+ }
+ size := int64(binary.BigEndian.Uint64(b8[:]))
+
+ if _, err := io.ReadFull(r, b8[:]); err != nil {
+ return nil, err
+ }
+ modTimeNano := int64(binary.BigEndian.Uint64(b8[:]))
+ modTime := time.Unix(0, modTimeNano)
+
+ isDirByte, err := r.ReadByte()
+ if err != nil {
+ return nil, err
+ }
+ isDir := isDirByte != 0
+
+ if _, err := io.ReadFull(r, b2[:]); err != nil {
+ return nil, err
+ }
+ shaLen := int(binary.BigEndian.Uint16(b2[:]))
+ shaBytes := make([]byte, shaLen)
+ if _, err := io.ReadFull(r, shaBytes); err != nil {
+ return nil, err
+ }
+
+ if _, err := io.ReadFull(r, b2[:]); err != nil {
+ return nil, err
+ }
+ etagLen := int(binary.BigEndian.Uint16(b2[:]))
+ etagBytes := make([]byte, etagLen)
+ if _, err := io.ReadFull(r, etagBytes); err != nil {
+ return nil, err
+ }
+
+ return &InodeRecord{
+ InodeID: inodeID,
+ Mode: mode,
+ Size: size,
+ ModTime: modTime,
+ IsDir: isDir,
+ Sha256: string(shaBytes),
+ ETag: string(etagBytes),
+ }, nil
+}
+
+func EncodeDirDeltaRecord(rec *DirDeltaRecord) ([]byte, error) {
+ var buf bytes.Buffer
+ var b8 [8]byte
+ var b4 [4]byte
+ var b2 [2]byte
+
+ // InodeID (8)
+ binary.BigEndian.PutUint64(b8[:], rec.InodeID)
+ buf.Write(b8[:])
+
+ // PrevOffset (4)
+ binary.BigEndian.PutUint32(b4[:], uint32(rec.PrevOffset))
+ buf.Write(b4[:])
+
+ // Deleted count (4)
+ binary.BigEndian.PutUint32(b4[:], uint32(len(rec.Deleted)))
+ buf.Write(b4[:])
+ for _, del := range rec.Deleted {
+ delBytes := []byte(del)
+ binary.BigEndian.PutUint16(b2[:], uint16(len(delBytes)))
+ buf.Write(b2[:])
+ buf.Write(delBytes)
+ }
+
+ // Added count (4)
+ binary.BigEndian.PutUint32(b4[:], uint32(len(rec.Added)))
+ buf.Write(b4[:])
+ for _, add := range rec.Added {
+ nameBytes := []byte(add.Name)
+ binary.BigEndian.PutUint16(b2[:], uint16(len(nameBytes)))
+ buf.Write(b2[:])
+ buf.Write(nameBytes)
+
+ binary.BigEndian.PutUint64(b8[:], add.InodeID)
+ buf.Write(b8[:])
+
+ if add.IsDir {
+ buf.WriteByte(1)
+ } else {
+ buf.WriteByte(0)
+ }
+
+ binary.BigEndian.PutUint32(b4[:], add.Mode)
+ buf.Write(b4[:])
+ }
+
+ return buf.Bytes(), nil
+}
+
+// DecodeDirDeltaRecord decodes a DirDeltaRecord from binary representation.
+// TODO: optimize encoding/decoding by parsing slice offsets directly instead of allocating bytes.NewReader wrapper.
+func DecodeDirDeltaRecord(data []byte) (*DirDeltaRecord, error) {
+ if len(data) < 16 {
+ return nil, fmt.Errorf("data too short for DirDeltaRecord: %d bytes", len(data))
+ }
+ r := bytes.NewReader(data)
+ var b8 [8]byte
+ var b4 [4]byte
+ var b2 [2]byte
+
+ if _, err := io.ReadFull(r, b8[:]); err != nil {
+ return nil, err
+ }
+ inodeID := binary.BigEndian.Uint64(b8[:])
+
+ if _, err := io.ReadFull(r, b4[:]); err != nil {
+ return nil, err
+ }
+ prevOffset := LocalOffset(binary.BigEndian.Uint32(b4[:]))
+
+ if _, err := io.ReadFull(r, b4[:]); err != nil {
+ return nil, err
+ }
+ deletedCount := int(binary.BigEndian.Uint32(b4[:]))
+ deleted := make([]string, 0, deletedCount)
+ for i := 0; i < deletedCount; i++ {
+ if _, err := io.ReadFull(r, b2[:]); err != nil {
+ return nil, err
+ }
+ nameLen := int(binary.BigEndian.Uint16(b2[:]))
+ nameBytes := make([]byte, nameLen)
+ if _, err := io.ReadFull(r, nameBytes); err != nil {
+ return nil, err
+ }
+ deleted = append(deleted, string(nameBytes))
+ }
+
+ if _, err := io.ReadFull(r, b4[:]); err != nil {
+ return nil, err
+ }
+ addedCount := int(binary.BigEndian.Uint32(b4[:]))
+ added := make([]DirEntry, 0, addedCount)
+ for i := 0; i < addedCount; i++ {
+ if _, err := io.ReadFull(r, b2[:]); err != nil {
+ return nil, err
+ }
+ nameLen := int(binary.BigEndian.Uint16(b2[:]))
+ nameBytes := make([]byte, nameLen)
+ if _, err := io.ReadFull(r, nameBytes); err != nil {
+ return nil, err
+ }
+
+ if _, err := io.ReadFull(r, b8[:]); err != nil {
+ return nil, err
+ }
+ childInodeID := binary.BigEndian.Uint64(b8[:])
+
+ isDirByte, err := r.ReadByte()
+ if err != nil {
+ return nil, err
+ }
+
+ if _, err := io.ReadFull(r, b4[:]); err != nil {
+ return nil, err
+ }
+ mode := binary.BigEndian.Uint32(b4[:])
+
+ added = append(added, DirEntry{
+ Name: string(nameBytes),
+ InodeID: childInodeID,
+ IsDir: isDirByte != 0,
+ Mode: mode,
+ })
+ }
+
+ return &DirDeltaRecord{
+ InodeID: inodeID,
+ PrevOffset: prevOffset,
+ Deleted: deleted,
+ Added: added,
+ }, nil
+}
+
+// LocalStorage manages append-only local files for evicted inodes and directory deltas.
+type LocalStorage struct {
+ mu sync.RWMutex
+ dir string
+ files [MaxLocalFiles]*os.File
+ activeFileID int
+ activeOffset int64
+}
+
+// NewLocalStorage creates or opens a local storage instance in the specified directory.
+func NewLocalStorage(dir string) (*LocalStorage, error) {
+ if err := os.MkdirAll(dir, 0755); err != nil {
+ return nil, fmt.Errorf("failed to create local storage directory %s: %w", dir, err)
+ }
+
+ s := &LocalStorage{
+ dir: dir,
+ activeFileID: 0,
+ activeOffset: HeaderLen,
+ }
+
+ return s, nil
+}
+
+func (s *LocalStorage) getOrOpenFileLocked(fileID int) (*os.File, error) {
+ if fileID < 0 || fileID >= MaxLocalFiles {
+ return nil, fmt.Errorf("invalid file ID %d", fileID)
+ }
+ if s.files[fileID] != nil {
+ return s.files[fileID], nil
+ }
+
+ filePath := filepath.Join(s.dir, fmt.Sprintf("meta-%02d.dat", fileID))
+ f, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE, 0644)
+ if err != nil {
+ return nil, fmt.Errorf("failed to open local storage file %s: %w", filePath, err)
+ }
+ s.files[fileID] = f
+
+ fi, err := f.Stat()
+ if err == nil && fi.Size() == 0 {
+ if _, err := f.WriteAt([]byte(LocalFileHeader), 0); err != nil {
+ return nil, fmt.Errorf("failed to write header to %s: %w", filePath, err)
+ }
+ }
+
+ return f, nil
+}
+
+// WriteRecord serializes and appends a record of recType with payload to the active local file.
+func (s *LocalStorage) WriteRecord(recType byte, payload []byte) (LocalOffset, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ payloadLen := uint32(len(payload))
+ recordLen := int64(1 + 4 + 4 + len(payload)) // [type (1B)][len (4B)][crc (4B)][payload]
+
+ // If active file would exceed max size, rotate to next file
+ if s.activeOffset+recordLen > MaxFileSizeInBytes {
+ s.activeFileID = (s.activeFileID + 1) % MaxLocalFiles
+ f, err := s.getOrOpenFileLocked(s.activeFileID)
+ if err != nil {
+ return NoOffset, err
+ }
+ _ = f.Truncate(0)
+ if _, err := f.WriteAt([]byte(LocalFileHeader), 0); err != nil {
+ return NoOffset, fmt.Errorf("failed to initialize rotated file %d: %w", s.activeFileID, err)
+ }
+ s.activeOffset = HeaderLen
+ }
+
+ f, err := s.getOrOpenFileLocked(s.activeFileID)
+ if err != nil {
+ return NoOffset, err
+ }
+
+ crc := crc32.ChecksumIEEE(payload)
+ headerBuf := make([]byte, 9)
+ headerBuf[0] = recType
+ binary.BigEndian.PutUint32(headerBuf[1:5], payloadLen)
+ binary.BigEndian.PutUint32(headerBuf[5:9], crc)
+
+ recordOffset := s.activeOffset
+ if _, err := f.WriteAt(headerBuf, recordOffset); err != nil {
+ return NoOffset, fmt.Errorf("failed to write record header: %w", err)
+ }
+ if len(payload) > 0 {
+ if _, err := f.WriteAt(payload, recordOffset+9); err != nil {
+ return NoOffset, fmt.Errorf("failed to write record payload: %w", err)
+ }
+ }
+
+ s.activeOffset += recordLen
+ return PackOffset(s.activeFileID, recordOffset), nil
+}
+
+// ReadRecord retrieves and verifies a record from the specified LocalOffset.
+func (s *LocalStorage) ReadRecord(off LocalOffset) (byte, []byte, error) {
+ if off == NoOffset {
+ return 0, nil, fmt.Errorf("invalid offset %d", off)
+ }
+ fileID, byteOffset := UnpackOffset(off)
+ if fileID < 0 || fileID >= MaxLocalFiles {
+ return 0, nil, fmt.Errorf("invalid file ID %d in offset %d", fileID, off)
+ }
+
+ s.mu.Lock()
+ f, err := s.getOrOpenFileLocked(fileID)
+ s.mu.Unlock()
+
+ if err != nil {
+ return 0, nil, err
+ }
+
+ headerBuf := make([]byte, 9)
+ if _, err := f.ReadAt(headerBuf, byteOffset); err != nil {
+ return 0, nil, fmt.Errorf("failed to read record header at offset %d: %w", off, err)
+ }
+
+ recType := headerBuf[0]
+ payloadLen := binary.BigEndian.Uint32(headerBuf[1:5])
+ expectedCrc := binary.BigEndian.Uint32(headerBuf[5:9])
+
+ payload := make([]byte, payloadLen)
+ if payloadLen > 0 {
+ if _, err := f.ReadAt(payload, byteOffset+9); err != nil {
+ return 0, nil, fmt.Errorf("failed to read record payload at offset %d: %w", off, err)
+ }
+ }
+
+ actualCrc := crc32.ChecksumIEEE(payload)
+ if actualCrc != expectedCrc {
+ return 0, nil, fmt.Errorf("CRC mismatch at offset %d: expected %x, got %x", off, expectedCrc, actualCrc)
+ }
+
+ return recType, payload, nil
+}
+
+// Truncate truncates all local storage files and resets write pointers.
+func (s *LocalStorage) Truncate() error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ for i := 0; i < MaxLocalFiles; i++ {
+ f := s.files[i]
+ if f != nil {
+ _ = f.Truncate(0)
+ if _, err := f.WriteAt([]byte(LocalFileHeader), 0); err != nil {
+ return fmt.Errorf("failed to reset file %d: %w", i, err)
+ }
+ }
+ }
+ s.activeFileID = 0
+ s.activeOffset = HeaderLen
+ return nil
+}
This method feels very unsafe and I would rather not have it at all.
I can understand deleting all the files if we want to clean-up on exit (because the index to read these files is in-memory), but truncating should never be useful.
@@ -0,0 +1,189 @@
+/*
+Copyright 2026 Google LLC
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package controller
+
+import (
+ "time"
+
+ "github.com/gke-labs/in-cluster-storage/pkg/objectfs/blob"
+)
+
+type cacheElement[K comparable, V any] struct {
+ key K
+ value V
+ lastUsed int64 // Unix nanoseconds
+}
+
+// LRUCache implements an in-memory least-recently-used cache tracking access times.
+type LRUCache[K comparable, V any] struct {
+ capacity int
+ items map[K]*cacheElement[K, V]
+ onEvict func(key K, value V)
+}
+
+// NewLRUCache creates a new LRUCache with the specified capacity and eviction callback.
+func NewLRUCache[K comparable, V any](capacity int, onEvict func(key K, value V)) *LRUCache[K, V] {
+ if capacity <= 0 {
+ capacity = 1024
+ }
+ return &LRUCache[K, V]{
+ capacity: capacity,
+ items: make(map[K]*cacheElement[K, V]),
+ onEvict: onEvict,
+ }
+}
+
+// Get returns the value associated with key, updating its lastUsed timestamp.
+func (c *LRUCache[K, V]) Get(key K) (V, bool) {
+ elem, ok := c.items[key]
+ if !ok {
+ var zero V
+ return zero, false
+ }
+ elem.lastUsed = time.Now().UnixNano()
Is time.Now().UnixNano() a fast monotonic clock? Let's extract it into a function readMonotonicClock, so we can add a comment and potentially change the implementation in future.
@@ -95,6 +77,22 @@ type Volume struct {
durability walclient.Level
streamID uuid.UUID
+ // Tiered metadata storage
+ localStore *LocalStorage
+ localStorageDir string
+ inodeCache *LRUCache[uint64, *CachedInode]
+ dirCache *LRUCache[uint64, *CachedDir]
+ dirtyInodes map[uint64]LocalOffset
Let's add a comment here about dirtyInodes and dirtyDirs: these are inodes and dirs that have changed since the snapshot. There may be additional changes not yet flushed in inodeCache and dirCache.
@@ -0,0 +1,516 @@
+/*
+Copyright 2026 Google LLC
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package controller
+
+import (
+ "bytes"
+ "encoding/binary"
+ "fmt"
+ "hash/crc32"
+ "io"
+ "os"
+ "path/filepath"
+ "sync"
+ "time"
+)
+
+// LocalOffset represents a 32-bit packed pointer into local metadata eviction storage.
+// Bits 28..31 (top 4 bits): File index (0..15).
+// Bits 0..27 (lower 28 bits): Byte offset within that file (up to 256MB).
+type LocalOffset uint32
+
+const (
+ NoOffset LocalOffset = 0
+
+ MaxLocalFiles = 16
+ MaxFileSizeInBytes = 256 * 1024 * 1024 // 256 MB per file (28 bits)
+ LocalFileHeader = "OBJSLOG1"
+ HeaderLen = 8
+)
+
+const (
+ RecordTypeInode byte = 1
+ RecordTypeDirDelta byte = 2
+)
+
+func PackOffset(fileID int, byteOffset int64) LocalOffset {
+ if byteOffset <= 0 || byteOffset > MaxFileSizeInBytes {
+ return NoOffset
+ }
+ return (LocalOffset(fileID&0x0F) << 28) | LocalOffset(byteOffset&0x0FFFFFFF)
+}
+
+func UnpackOffset(off LocalOffset) (int, int64) {
+ fileID := int((off >> 28) & 0x0F)
+ byteOffset := int64(off & 0x0FFFFFFF)
+ return fileID, byteOffset
+}
+
+// InodeRecord stores serialized metadata for an evicted inode.
+type InodeRecord struct {
+ InodeID uint64
+ Mode uint32
+ Size int64
+ ModTime time.Time
+ IsDir bool
+ Sha256 string
+ ETag string
+}
+
+// DirEntry represents a single directory entry.
+type DirEntry struct {
+ Name string
+ InodeID uint64
+ IsDir bool
+ Mode uint32
+}
+
+// DirDeltaRecord stores a delta mutation for an evicted directory.
+type DirDeltaRecord struct {
+ InodeID uint64
+ PrevOffset LocalOffset
+ Deleted []string
+ Added []DirEntry
+}
+
+func EncodeInodeRecord(rec *InodeRecord) ([]byte, error) {
+ var buf bytes.Buffer
+ var b8 [8]byte
+ var b4 [4]byte
+ var b2 [2]byte
+
+ // InodeID (8)
+ binary.BigEndian.PutUint64(b8[:], rec.InodeID)
+ buf.Write(b8[:])
+
+ // Mode (4)
+ binary.BigEndian.PutUint32(b4[:], rec.Mode)
+ buf.Write(b4[:])
+
+ // Size (8)
+ binary.BigEndian.PutUint64(b8[:], uint64(rec.Size))
+ buf.Write(b8[:])
+
+ // ModTime unix nano (8)
+ binary.BigEndian.PutUint64(b8[:], uint64(rec.ModTime.UnixNano()))
+ buf.Write(b8[:])
+
+ // IsDir (1)
+ if rec.IsDir {
+ buf.WriteByte(1)
+ } else {
+ buf.WriteByte(0)
+ }
+
+ // Sha256 length (2) + bytes
+ shaBytes := []byte(rec.Sha256)
+ binary.BigEndian.PutUint16(b2[:], uint16(len(shaBytes)))
+ buf.Write(b2[:])
+ buf.Write(shaBytes)
+
+ // ETag length (2) + bytes
+ etagBytes := []byte(rec.ETag)
+ binary.BigEndian.PutUint16(b2[:], uint16(len(etagBytes)))
+ buf.Write(b2[:])
+ buf.Write(etagBytes)
+
+ return buf.Bytes(), nil
+}
+
+// DecodeInodeRecord decodes an InodeRecord from binary representation.
+// TODO: optimize encoding/decoding by parsing slice offsets directly instead of allocating bytes.NewReader wrapper.
+func DecodeInodeRecord(data []byte) (*InodeRecord, error) {
+ if len(data) < 29 {
+ return nil, fmt.Errorf("data too short for InodeRecord: %d bytes", len(data))
+ }
+ r := bytes.NewReader(data)
+ var b8 [8]byte
+ var b4 [4]byte
+ var b2 [2]byte
+
+ if _, err := io.ReadFull(r, b8[:]); err != nil {
+ return nil, err
+ }
+ inodeID := binary.BigEndian.Uint64(b8[:])
+
+ if _, err := io.ReadFull(r, b4[:]); err != nil {
+ return nil, err
+ }
+ mode := binary.BigEndian.Uint32(b4[:])
+
+ if _, err := io.ReadFull(r, b8[:]); err != nil {
+ return nil, err
+ }
+ size := int64(binary.BigEndian.Uint64(b8[:]))
+
+ if _, err := io.ReadFull(r, b8[:]); err != nil {
+ return nil, err
+ }
+ modTimeNano := int64(binary.BigEndian.Uint64(b8[:]))
+ modTime := time.Unix(0, modTimeNano)
+
+ isDirByte, err := r.ReadByte()
+ if err != nil {
+ return nil, err
+ }
+ isDir := isDirByte != 0
+
+ if _, err := io.ReadFull(r, b2[:]); err != nil {
+ return nil, err
+ }
+ shaLen := int(binary.BigEndian.Uint16(b2[:]))
+ shaBytes := make([]byte, shaLen)
+ if _, err := io.ReadFull(r, shaBytes); err != nil {
+ return nil, err
+ }
+
+ if _, err := io.ReadFull(r, b2[:]); err != nil {
+ return nil, err
+ }
+ etagLen := int(binary.BigEndian.Uint16(b2[:]))
+ etagBytes := make([]byte, etagLen)
+ if _, err := io.ReadFull(r, etagBytes); err != nil {
+ return nil, err
+ }
+
+ return &InodeRecord{
+ InodeID: inodeID,
+ Mode: mode,
+ Size: size,
+ ModTime: modTime,
+ IsDir: isDir,
+ Sha256: string(shaBytes),
+ ETag: string(etagBytes),
+ }, nil
+}
+
+func EncodeDirDeltaRecord(rec *DirDeltaRecord) ([]byte, error) {
+ var buf bytes.Buffer
+ var b8 [8]byte
+ var b4 [4]byte
+ var b2 [2]byte
+
+ // InodeID (8)
+ binary.BigEndian.PutUint64(b8[:], rec.InodeID)
+ buf.Write(b8[:])
+
+ // PrevOffset (4)
+ binary.BigEndian.PutUint32(b4[:], uint32(rec.PrevOffset))
+ buf.Write(b4[:])
+
+ // Deleted count (4)
+ binary.BigEndian.PutUint32(b4[:], uint32(len(rec.Deleted)))
+ buf.Write(b4[:])
+ for _, del := range rec.Deleted {
+ delBytes := []byte(del)
+ binary.BigEndian.PutUint16(b2[:], uint16(len(delBytes)))
+ buf.Write(b2[:])
+ buf.Write(delBytes)
+ }
+
+ // Added count (4)
+ binary.BigEndian.PutUint32(b4[:], uint32(len(rec.Added)))
+ buf.Write(b4[:])
+ for _, add := range rec.Added {
+ nameBytes := []byte(add.Name)
+ binary.BigEndian.PutUint16(b2[:], uint16(len(nameBytes)))
+ buf.Write(b2[:])
+ buf.Write(nameBytes)
+
+ binary.BigEndian.PutUint64(b8[:], add.InodeID)
+ buf.Write(b8[:])
+
+ if add.IsDir {
+ buf.WriteByte(1)
+ } else {
+ buf.WriteByte(0)
+ }
+
+ binary.BigEndian.PutUint32(b4[:], add.Mode)
+ buf.Write(b4[:])
+ }
+
+ return buf.Bytes(), nil
+}
+
+// DecodeDirDeltaRecord decodes a DirDeltaRecord from binary representation.
+// TODO: optimize encoding/decoding by parsing slice offsets directly instead of allocating bytes.NewReader wrapper.
+func DecodeDirDeltaRecord(data []byte) (*DirDeltaRecord, error) {
+ if len(data) < 16 {
+ return nil, fmt.Errorf("data too short for DirDeltaRecord: %d bytes", len(data))
+ }
+ r := bytes.NewReader(data)
+ var b8 [8]byte
+ var b4 [4]byte
+ var b2 [2]byte
+
+ if _, err := io.ReadFull(r, b8[:]); err != nil {
+ return nil, err
+ }
+ inodeID := binary.BigEndian.Uint64(b8[:])
+
+ if _, err := io.ReadFull(r, b4[:]); err != nil {
+ return nil, err
+ }
+ prevOffset := LocalOffset(binary.BigEndian.Uint32(b4[:]))
+
+ if _, err := io.ReadFull(r, b4[:]); err != nil {
+ return nil, err
+ }
+ deletedCount := int(binary.BigEndian.Uint32(b4[:]))
+ deleted := make([]string, 0, deletedCount)
+ for i := 0; i < deletedCount; i++ {
+ if _, err := io.ReadFull(r, b2[:]); err != nil {
+ return nil, err
+ }
+ nameLen := int(binary.BigEndian.Uint16(b2[:]))
+ nameBytes := make([]byte, nameLen)
+ if _, err := io.ReadFull(r, nameBytes); err != nil {
+ return nil, err
+ }
+ deleted = append(deleted, string(nameBytes))
+ }
+
+ if _, err := io.ReadFull(r, b4[:]); err != nil {
+ return nil, err
+ }
+ addedCount := int(binary.BigEndian.Uint32(b4[:]))
+ added := make([]DirEntry, 0, addedCount)
+ for i := 0; i < addedCount; i++ {
+ if _, err := io.ReadFull(r, b2[:]); err != nil {
+ return nil, err
+ }
+ nameLen := int(binary.BigEndian.Uint16(b2[:]))
+ nameBytes := make([]byte, nameLen)
+ if _, err := io.ReadFull(r, nameBytes); err != nil {
+ return nil, err
+ }
+
+ if _, err := io.ReadFull(r, b8[:]); err != nil {
+ return nil, err
+ }
+ childInodeID := binary.BigEndian.Uint64(b8[:])
+
+ isDirByte, err := r.ReadByte()
+ if err != nil {
+ return nil, err
+ }
+
+ if _, err := io.ReadFull(r, b4[:]); err != nil {
+ return nil, err
+ }
+ mode := binary.BigEndian.Uint32(b4[:])
+
+ added = append(added, DirEntry{
+ Name: string(nameBytes),
+ InodeID: childInodeID,
+ IsDir: isDirByte != 0,
+ Mode: mode,
+ })
+ }
+
+ return &DirDeltaRecord{
+ InodeID: inodeID,
+ PrevOffset: prevOffset,
+ Deleted: deleted,
+ Added: added,
+ }, nil
+}
+
+// LocalStorage manages append-only local files for evicted inodes and directory deltas.
+type LocalStorage struct {
+ mu sync.RWMutex
+ dir string
+ files [MaxLocalFiles]*os.File
+ activeFileID int
+ activeOffset int64
+}
+
+// NewLocalStorage creates or opens a local storage instance in the specified directory.
+func NewLocalStorage(dir string) (*LocalStorage, error) {
+ if err := os.MkdirAll(dir, 0755); err != nil {
+ return nil, fmt.Errorf("failed to create local storage directory %s: %w", dir, err)
+ }
+
+ s := &LocalStorage{
+ dir: dir,
+ activeFileID: 0,
+ activeOffset: HeaderLen,
+ }
+
+ return s, nil
+}
+
+func (s *LocalStorage) getOrOpenFileLocked(fileID int) (*os.File, error) {
+ if fileID < 0 || fileID >= MaxLocalFiles {
+ return nil, fmt.Errorf("invalid file ID %d", fileID)
+ }
+ if s.files[fileID] != nil {
+ return s.files[fileID], nil
+ }
+
+ filePath := filepath.Join(s.dir, fmt.Sprintf("meta-%02d.dat", fileID))
+ f, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE, 0644)
Let's pass O_EXCL here, then I'll feel good that we aren't silently overwriting data. We'll have to handle the garbage collection, but we won't fail silently
codebot-robot
Residual = Change × (1 − Confidence)
justinsb
This PR implements tiered metadata storage and in-memory LRU eviction for ObjectFS, preventing unbounded RAM consumption and scaling to millions of files without keeping full directory hierarchies in memory.
Key Changes
WithMaxRAMEntries) with eviction callbacks.meta-00.dat...meta-15.dat) with CRC32 verification and 32-bit packed pointer offsets (4 bits file ID, 28 bits offset up to 256MB).docs/objectfs.mdto document the tiered metadata architecture and marked roadmap items complete.Fixes #72