package jsondb import ( "crypto/rand" "crypto/subtle" "encoding/hex" "encoding/json" "fmt" "net/url" "os" "strings" "time" again "git.rootprojects.org/root/go-again" ) type JSONDB struct { dburl string path string json *dbjson } type dbjson struct { Schedules []Schedule `json:"schedules"` } func Connect(dburl string) (*JSONDB, error) { u, err := url.Parse(dburl) if nil != err { return nil, err } // json:/abspath/to/db.json fmt.Println("url.Opaque:", u.Opaque) // json:///abspath/to/db.json fmt.Println("url.Path:", u.Path) fmt.Println(u) path := u.Opaque if "" == path { path = u.Path if "" == path { // json:relpath/to/db.json // json://relpath/to/db.json path = strings.TrimSuffix(u.Host+"/"+u.Path, "/") } } f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0700) if nil != err { return nil, fmt.Errorf("Couldn't open %q: %s", path, err) } stat, err := f.Stat() if 0 == stat.Size() { _, err := f.Write([]byte(`{"schedules":[]}`)) f.Close() if nil != err { return nil, err } f, err = os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0700) if nil != err { return nil, err } } decoder := json.NewDecoder(f) db := &dbjson{} err = decoder.Decode(db) f.Close() if nil != err { return nil, fmt.Errorf("Couldn't parse %q as JSON: %s", path, err) } return &JSONDB{ dburl: dburl, path: path, json: db, }, nil } // A copy of again.Schedule, but with access_id json-able type Schedule struct { ID string `json:"id" db:"id"` AccessID string `json:"access_id" db:"access_id"` Date string `json:"date" db:"date"` Time string `json:"time" db:"time"` TZ string `json:"tz" db:"tz"` NextRunAt time.Time `json:"next_run_at" db:"next_run_at"` Disabled bool `json:"disabled" db:"disabled"` Webhooks []again.Webhook `json:"webhooks" db"webhooks"` } func ctcmp(x string, y string) bool { return 1 == subtle.ConstantTimeCompare([]byte(x), []byte(y)) } func (db *JSONDB) List(accessID string) ([]*again.Schedule, error) { schedules := []*again.Schedule{} for i := range db.json.Schedules { s := db.json.Schedules[i] if !s.Disabled && ctcmp(accessID, s.AccessID) { schedules = append(schedules, &again.Schedule{ ID: s.ID, AccessID: s.AccessID, Date: s.Date, Time: s.Time, TZ: s.TZ, NextRunAt: s.NextRunAt, Webhooks: s.Webhooks, }) } } return schedules, nil } func (db *JSONDB) get(id string) (int, *Schedule) { for i := range db.json.Schedules { schedule := db.json.Schedules[i] if ctcmp(id, schedule.ID) { return i, &schedule } } return -1, nil } func genID() (string, error) { b := make([]byte, 16) _, err := rand.Read(b) if nil != err { return "", err } return hex.EncodeToString(b), nil } func (db *JSONDB) Set(s again.Schedule) (*again.Schedule, error) { exists := false index := -1 if "" == s.ID { id, err := genID() if nil != err { return nil, err } s.ID = id } else { i, old := db.get(s.ID) index = i exists = nil != old if !exists || !ctcmp(old.AccessID, s.AccessID) { return nil, fmt.Errorf("invalid id") } } schedule := Schedule{ ID: s.ID, AccessID: s.AccessID, Date: s.Date, Time: s.Time, TZ: s.TZ, NextRunAt: s.NextRunAt, Webhooks: s.Webhooks, } if exists { db.json.Schedules[index] = schedule } else { db.json.Schedules = append(db.json.Schedules, schedule) } err := db.save(s.AccessID) if nil != err { return nil, err } return &s, nil } func (db *JSONDB) save(accessID string) error { // TODO per-user files (w/ mutex lock or channel on open and write) tmppath := db.path + ".tmp" bakpath := db.path + ".bak" os.Remove(tmppath) // ignore error f, err := os.OpenFile(tmppath, os.O_RDWR|os.O_CREATE, 0700) if nil != err { return err } encoder := json.NewEncoder(f) err = encoder.Encode(db.json) f.Close() if nil != err { return err } os.Remove(bakpath) // ignore error err = os.Rename(db.path, bakpath) if nil != err { return err } err = os.Rename(tmppath, db.path) if nil != err { return err } return nil }