X-Git-Url: https://git.giacomolli.uk/onechat/blobdiff_plain/baf7a940be8927278e3b4b87e7366cebfc16532f..0cb73c3dde36d0078f3c1aa4200f2edcb5ceed38:/journal.go?ds=inline diff --git a/journal.go b/journal.go index c12f7d0..745ae79 100644 --- a/journal.go +++ b/journal.go @@ -71,16 +71,33 @@ func (j *Journal) Write(day string, line []byte) (Position, error) { offset: j.size, length: uint32(len(line)), } + j.size += uint64(len(line)) return place, nil } +func (j *Journal) closeWriter() error { + if j.file == nil { + return nil + } + + err := j.file.Close() + j.file = nil + j.day = 0 + if err != nil { + return fmt.Errorf("close day file: %w", err) + } + + return nil +} + // Read returns the line at place without its newline. func (j *Journal) Read(place Position) ([]byte, error) { reader, open := j.readers[place.day] if !open { var err error + reader, err = os.Open(filepath.Join(j.dir, journalDayName(place.day)+".jsonl")) if err != nil { return nil, fmt.Errorf("open day file: %w", err) @@ -111,6 +128,7 @@ func (j *Journal) Close() error { err := j.closeWriter() for day, reader := range j.readers { err = errors.Join(err, reader.Close()) + delete(j.readers, day) } @@ -128,6 +146,7 @@ func (j *Journal) Scan(ctx context.Context, place Position, add func([]byte, Pos } slices.Sort(paths) + for n, path := range paths { day, err := journalDayNumber(strings.TrimSuffix(filepath.Base(path), ".jsonl")) if err != nil { @@ -152,21 +171,6 @@ func (j *Journal) Scan(ctx context.Context, place Position, add func([]byte, Pos return nil } -func (j *Journal) closeWriter() error { - if j.file == nil { - return nil - } - - err := j.file.Close() - j.file = nil - j.day = 0 - if err != nil { - return fmt.Errorf("close day file: %w", err) - } - - return nil -} - // journalDayNumber returns the day YYYY-MM-DD as the number YYYYMMDD. func journalDayNumber(day string) (uint32, error) { number, err := strconv.ParseUint(strings.ReplaceAll(day, "-", ""), 10, 32)