16 // position names one line of a day file: the day as YYYYMMDD, the byte offset
17 // of the line, and its length with the newline.
18 type position struct {
24 // journal appends JSON lines to one file for each day in dir, named
25 // YYYY-MM-DD.jsonl, and reads them back by their position. It keeps the file of
26 // the last day open for writes and each file that it read open for reads.
32 readers map[uint32]*os.File
35 // Write appends line to the file of day, YYYY-MM-DD, with one write to the
36 // operating system, without a buffer. A crash of the process then loses
37 // nothing. It returns the position of the line.
38 func (j *journal) Write(day string, line []byte) (position, error) {
39 number, err := dayNumber(day)
41 return position{}, err
47 return position{}, err
50 j.file, err = os.OpenFile(filepath.Join(j.dir, day+".jsonl"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600)
52 return position{}, fmt.Errorf("open day file: %w", err)
55 info, err := j.file.Stat()
57 return position{}, fmt.Errorf("read day file size: %w", err)
61 j.size = uint64(info.Size())
64 _, err = j.file.Write(line)
66 return position{}, fmt.Errorf("write line: %w", err)
72 length: uint32(len(line)),
74 j.size += uint64(len(line))
79 func (j *journal) closeWriter() error {
88 return fmt.Errorf("close day file: %w", err)
94 // Read returns the line at place without its newline.
95 func (j *journal) Read(place position) ([]byte, error) {
96 reader, open := j.readers[place.day]
99 reader, err = os.Open(filepath.Join(j.dir, dayName(place.day)+".jsonl"))
101 return nil, fmt.Errorf("open day file: %w", err)
104 if j.readers == nil {
105 j.readers = make(map[uint32]*os.File)
108 j.readers[place.day] = reader
111 line := make([]byte, place.length)
112 _, err := reader.ReadAt(line, int64(place.offset))
114 return nil, fmt.Errorf("read line of %s: %w", dayName(place.day), err)
117 if len(line) == 0 || line[len(line)-1] != '\n' {
118 return nil, fmt.Errorf("line of %s at %d does not end its record", dayName(place.day), place.offset)
121 return line[:len(line)-1], nil
124 // Close closes the open day files.
125 func (j *journal) Close() error {
126 err := j.closeWriter()
127 for day, reader := range j.readers {
128 err = errors.Join(err, reader.Close())
129 delete(j.readers, day)
135 // Scan gives each line of the day files from place on to add, with its
136 // position, oldest day first. The zero position starts at the first line.
137 func (j *journal) Scan(ctx context.Context, place position, add func([]byte, position) error) error {
138 paths, err := filepath.Glob(filepath.Join(j.dir, "*.jsonl"))
140 return fmt.Errorf("list day files: %w", err)
144 for _, path := range paths {
145 day, err := dayNumber(strings.TrimSuffix(filepath.Base(path), ".jsonl"))
155 if day == place.day {
156 offset = place.offset
159 err = scanFile(ctx, path, day, offset, add)
168 // scanFile gives each line of the day file at path from offset on to add.
169 func scanFile(ctx context.Context, path string, day uint32, offset uint64, add func([]byte, position) error) (err error) {
170 file, err := os.Open(path)
172 return fmt.Errorf("open day file: %w", err)
176 err = errors.Join(err, file.Close())
179 _, err = file.Seek(int64(offset), io.SeekStart)
181 return fmt.Errorf("seek day file: %w", err)
184 reader := bufio.NewReader(file)
186 if ctx.Err() != nil {
190 line, err := reader.ReadBytes('\n')
191 if errors.Is(err, io.EOF) && len(line) == 0 {
195 if errors.Is(err, io.EOF) {
196 return fmt.Errorf("%s ends in an incomplete line at %d", filepath.Base(path), offset)
200 return fmt.Errorf("read %s: %w", filepath.Base(path), err)
206 length: uint32(len(line)),
209 err = add(line[:len(line)-1], place)
211 return fmt.Errorf("%s at %d: %w", filepath.Base(path), offset, err)
214 offset += uint64(len(line))
218 // dayNumber returns the day YYYY-MM-DD as the number YYYYMMDD.
219 func dayNumber(day string) (uint32, error) {
220 number, err := strconv.ParseUint(strings.ReplaceAll(day, "-", ""), 10, 32)
221 if err != nil || len(day) != len("2006-01-02") {
222 return 0, fmt.Errorf("invalid day %q", day)
225 return uint32(number), nil
228 // dayName returns the day number YYYYMMDD as YYYY-MM-DD.
229 func dayName(day uint32) string {
230 return fmt.Sprintf("%04d-%02d-%02d", day/10000, day/100%100, day%100)