10 "golang.org/x/sys/unix"
13 // openSyncer returns the syncer of the file system that holds dir. It syncs
14 // with syncfs, which writes back only that file system.
15 func openSyncer(dir string) (*Syncer, error) {
16 file, err := os.Open(dir)
18 return nil, fmt.Errorf("open chat directory: %w", err)
21 s := newSyncer(func() error {
22 return unix.Syncfs(int(file.Fd()))
29 // Syncer makes the writes of a chat durable by group commit. Each write goes to
30 // the operating system at once, so a crash of the process loses nothing. After
31 // each write, Written starts a background sync of the file system of the chat,
32 // unless one runs already. Then the next sync starts when the running one ends.
33 // One sync makes every write before its start durable, so a sync covers many
34 // writes, and there is never more than one sync at a time. A power loss loses
35 // at most the writes after the start of the last finished sync.
37 // A failed sync can mean that the kernel dropped written data, so the error
38 // stays, and each later Flush returns it.
48 workers sync.WaitGroup
51 // Written tells the syncer that a write went to the operating system, and
52 // starts a sync when none runs.
53 func (s *Syncer) Written() {
55 defer s.mutex.Unlock()
61 // Flush returns when every write before the call is durable.
62 func (s *Syncer) Flush(ctx context.Context) error {
69 reached := s.durable >= target
90 // Close makes every write durable, waits for the syncs, and closes the
92 func (s *Syncer) Close() error {
93 err := s.Flush(context.Background())
96 err = errors.Join(err, s.file.Close())
103 // start starts a sync of the writes so far when none runs and a write is not
104 // durable. The caller holds the mutex.
105 func (s *Syncer) start() {
106 if s.running || s.durable == s.written || s.failure != nil {
115 // run syncs once, so the writes up to target become durable, and starts the
116 // next sync when writes came during this one.
117 func (s *Syncer) run(target uint64) {
118 defer s.workers.Done()
123 defer s.mutex.Unlock()
127 s.failure = fmt.Errorf("sync chat files: %w", err)
133 s.done = make(chan struct{})
137 // newSyncer returns a syncer that makes the writes durable with sync.
138 func newSyncer(sync func() error) *Syncer {
141 done: make(chan struct{}),