fix: session log error handling and scanner buffer size

- Replace deprecated os.IsNotExist with errors.Is(err, fs.ErrNotExist)
- Capture Close error in Append by calling it explicitly instead of defer
- Increase scanner buffer to 1 MB per line to handle large JSONL entries

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Mathias Bergqvist
2026-04-17 20:34:36 +02:00
parent 1b03532230
commit 5722532f7d

View File

@@ -4,7 +4,9 @@ package session
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"time"
@@ -44,21 +46,27 @@ func Append(sessionsDir, sessionID string, entry Entry) error {
if err != nil {
return fmt.Errorf("open session log: %w", err)
}
defer f.Close()
line, err := json.Marshal(entry)
if err != nil {
_ = f.Close()
return fmt.Errorf("marshal entry: %w", err)
}
_, err = fmt.Fprintf(f, "%s\n", line)
return err
if _, err = fmt.Fprintf(f, "%s\n", line); err != nil {
_ = f.Close()
return fmt.Errorf("write entry: %w", err)
}
if err = f.Close(); err != nil {
return fmt.Errorf("close session log: %w", err)
}
return nil
}
// Read returns all entries for sessionID. Returns empty slice if no log exists.
func Read(sessionsDir, sessionID string) ([]Entry, error) {
path := filepath.Join(sessionsDir, sessionID+".jsonl")
f, err := os.Open(path)
if os.IsNotExist(err) {
if errors.Is(err, fs.ErrNotExist) {
return nil, nil
}
if err != nil {
@@ -68,6 +76,7 @@ func Read(sessionsDir, sessionID string) ([]Entry, error) {
var entries []Entry
scanner := bufio.NewScanner(f)
scanner.Buffer(make([]byte, 0, 256*1024), 1<<20) // up to 1 MB per line
for scanner.Scan() {
line := scanner.Bytes()
if len(line) == 0 {