summaryrefslogblamecommitdiff
path: root/internal/storage/file.go
blob: 7619e32367e23ff2675a4d81582276f7d60f6203 (plain) (tree)

































































                                                                                  
package storage

import (
	"context"
	"encoding/gob"
	"fmt"
	"io"
	"log"
	"os"

	"go.neonxp.dev/djson/internal/model"
)

type FileStorage struct {
	enc          *gob.Encoder
	dec          *gob.Decoder
	fh           *os.File
	fileName     string
	mutationsLog []model.Mutation
}

func NewFileStorage(fileName string) (*FileStorage, error) {
	fh, err := os.OpenFile(fileName, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0o666)
	if err != nil {
		return nil, err
	}

	return &FileStorage{
		fileName:     fileName,
		fh:           fh,
		enc:          gob.NewEncoder(fh),
		dec:          gob.NewDecoder(fh),
		mutationsLog: []model.Mutation{},
	}, nil
}

func (fs *FileStorage) Commit(ctx context.Context, mut model.Mutation) error {
	if fs.enc == nil {
		return fmt.Errorf("file storage not initiated")
	}
	return fs.enc.Encode(mut)
}

func (fs *FileStorage) Load() chan model.Mutation {
	ch := make(chan model.Mutation)
	go func() {
		for {
			m := model.Mutation{}
			if err := fs.dec.Decode(&m); err != nil {
				if err != io.EOF {
					log.Println(err.Error())
				}
				close(ch)
				return
			}
			log.Println("Loaded from fs", m.String())
			fs.mutationsLog = append(fs.mutationsLog, m)
			ch <- m
		}
	}()
	return ch
}

func (fs *FileStorage) Close() error {
	return fs.fh.Close()
}