734 lines
21 KiB
Go
734 lines
21 KiB
Go
package calendar
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"sort"
|
|
"strings"
|
|
"syscall"
|
|
"time"
|
|
|
|
ical "github.com/emersion/go-ical"
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
var (
|
|
ErrForbidden = errors.New("calendar access denied")
|
|
ErrConflict = errors.New("calendar precondition failed")
|
|
ErrPreconditionRequired = errors.New("calendar If-Match required")
|
|
ErrMissing = errors.New("calendar not found")
|
|
ErrLimit = errors.New("calendar result limit exceeded; narrow the time range")
|
|
)
|
|
|
|
type Calendar struct {
|
|
ID string `json:"id"`
|
|
Name string `json:"name"`
|
|
PrettyName string `json:"pretty_name"`
|
|
Source *Source `json:"source,omitempty"`
|
|
ReadOnly bool `json:"read_only"`
|
|
Owner string `json:"owner"`
|
|
Public bool `json:"public"`
|
|
Members map[string]string `json:"members"` // principal UUID -> read/write
|
|
Months map[string]string `json:"months"` // month -> immutable generation hash
|
|
Version string `json:"version"`
|
|
DAVNames map[string]string `json:"dav_names,omitempty"` // UID -> client filename; canonical metadata, not a DB-only alias
|
|
}
|
|
|
|
func (c Calendar) CanRead(actor string) bool {
|
|
return c.Public || actor != "" && (actor == c.Owner || c.Members[actor] != "")
|
|
}
|
|
func (c Calendar) CanWrite(actor string) bool {
|
|
return c.Source == nil && actor != "" && (actor == c.Owner || c.Members[actor] == "write")
|
|
}
|
|
|
|
type Repository struct {
|
|
Root string
|
|
DB *sql.DB
|
|
PublicAllowed func(string) bool
|
|
postgres bool
|
|
}
|
|
|
|
func (r *Repository) canRead(domain string, c Calendar, actor string) bool {
|
|
if c.Public && r.PublicAllowed != nil && !r.PublicAllowed(domain) {
|
|
c.Public = false
|
|
}
|
|
return c.CanRead(actor)
|
|
}
|
|
|
|
func New(root string, db *sql.DB) (*Repository, error) {
|
|
if root == "" {
|
|
return nil, errors.New("calendar document root unavailable")
|
|
}
|
|
_, err := db.Exec(`CREATE TABLE IF NOT EXISTS calendar_index_state(domain TEXT NOT NULL,calendar TEXT NOT NULL,version TEXT NOT NULL,PRIMARY KEY(domain,calendar));
|
|
CREATE TABLE IF NOT EXISTS calendar_month_cache(domain TEXT NOT NULL,calendar TEXT NOT NULL,month TEXT NOT NULL,hash TEXT NOT NULL,PRIMARY KEY(domain,calendar,month));
|
|
CREATE TABLE IF NOT EXISTS calendar_event_cache(domain TEXT NOT NULL,calendar TEXT NOT NULL,uid TEXT NOT NULL,month TEXT NOT NULL,start INTEGER NOT NULL,"end" INTEGER NOT NULL,etag TEXT NOT NULL,data TEXT NOT NULL,PRIMARY KEY(domain,calendar,uid));
|
|
CREATE INDEX IF NOT EXISTS calendar_event_range ON calendar_event_cache(domain,calendar,start,"end");`)
|
|
return &Repository{Root: root, DB: db}, err
|
|
}
|
|
func validID(s string) bool { u, err := uuid.Parse(s); return err == nil && u.String() == s }
|
|
func (r *Repository) dir(domain, id string) (string, error) {
|
|
if !validID(domain) || !validID(id) {
|
|
return "", ErrMissing
|
|
}
|
|
return filepath.Join(r.Root, domain, id), nil
|
|
}
|
|
func atomicFile(path string, data []byte) error {
|
|
f, err := os.CreateTemp(filepath.Dir(path), ".calendar-")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer os.Remove(f.Name())
|
|
if _, err = f.Write(data); err != nil {
|
|
f.Close()
|
|
return err
|
|
}
|
|
if err = f.Sync(); err != nil {
|
|
f.Close()
|
|
return err
|
|
}
|
|
if err = f.Close(); err != nil {
|
|
return err
|
|
}
|
|
if err = os.Rename(f.Name(), path); err != nil {
|
|
return err
|
|
}
|
|
d, err := os.Open(filepath.Dir(path))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer d.Close()
|
|
return d.Sync()
|
|
}
|
|
func lock(ctx context.Context, dir string) (func(), error) {
|
|
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
|
defer cancel()
|
|
f, err := os.OpenFile(filepath.Join(dir, ".lock"), os.O_CREATE|os.O_RDWR, 0600)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for {
|
|
err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
|
|
if err == nil {
|
|
return func() { syscall.Flock(int(f.Fd()), syscall.LOCK_UN); f.Close() }, nil
|
|
}
|
|
if err != syscall.EWOULDBLOCK && err != syscall.EAGAIN {
|
|
f.Close()
|
|
return nil, err
|
|
}
|
|
select {
|
|
case <-ctx.Done():
|
|
f.Close()
|
|
return nil, ctx.Err()
|
|
case <-time.After(10 * time.Millisecond):
|
|
}
|
|
}
|
|
}
|
|
func readMeta(dir string) (Calendar, error) {
|
|
var c Calendar
|
|
b, e := os.ReadFile(filepath.Join(dir, "calendar.json"))
|
|
if os.IsNotExist(e) {
|
|
return c, ErrMissing
|
|
}
|
|
if e != nil {
|
|
return c, e
|
|
}
|
|
e = json.Unmarshal(b, &c)
|
|
if e != nil {
|
|
return c, e
|
|
}
|
|
c.ReadOnly = c.Source != nil
|
|
if c.PrettyName == "" {
|
|
c.PrettyName = "calendar-" + c.ID
|
|
} // deterministic migration, no read-side writes
|
|
if !ValidPrettyName(c.PrettyName) {
|
|
return c, ErrInvalid
|
|
}
|
|
if c.ID != filepath.Base(dir) || !validID(c.ID) || !validID(c.Owner) || !validID(c.Version) || strings.TrimSpace(c.Name) == "" {
|
|
return c, ErrInvalid
|
|
}
|
|
for month, hash := range c.Months {
|
|
if _, e = time.Parse("2006-01", month); e != nil {
|
|
return c, ErrInvalid
|
|
}
|
|
if bytes, e := hex.DecodeString(hash); e != nil || len(bytes) != 32 {
|
|
return c, ErrInvalid
|
|
}
|
|
}
|
|
if c.Months == nil {
|
|
c.Months = map[string]string{}
|
|
}
|
|
for id, role := range c.Members {
|
|
if !validID(id) || (role != "read" && role != "write") {
|
|
return c, ErrInvalid
|
|
}
|
|
}
|
|
return c, e
|
|
}
|
|
func saveMeta(dir string, c *Calendar) error {
|
|
c.Version = uuid.NewString()
|
|
b, e := json.MarshalIndent(c, "", " ")
|
|
if e != nil {
|
|
return e
|
|
}
|
|
return atomicFile(filepath.Join(dir, "calendar.json"), b)
|
|
}
|
|
func (r *Repository) Create(ctx context.Context, domain, actor, name string, pretty ...string) (Calendar, error) {
|
|
c := Calendar{ID: uuid.NewString(), Name: strings.TrimSpace(name), Owner: actor, Members: map[string]string{}, Months: map[string]string{}}
|
|
c.PrettyName = "calendar-" + c.ID
|
|
if len(pretty) > 0 {
|
|
c.PrettyName = pretty[0]
|
|
}
|
|
if !ValidPrettyName(c.PrettyName) {
|
|
return c, ErrInvalid
|
|
}
|
|
if actor == "" || c.Name == "" || len(c.Name) > 200 {
|
|
return c, ErrInvalid
|
|
}
|
|
dir, e := r.dir(domain, c.ID)
|
|
if e != nil {
|
|
return c, e
|
|
}
|
|
parent := filepath.Dir(dir)
|
|
if e = os.MkdirAll(parent, 0700); e != nil {
|
|
return c, e
|
|
}
|
|
unlock, e := lock(ctx, parent)
|
|
if e != nil {
|
|
return c, e
|
|
}
|
|
defer unlock()
|
|
if e = r.uniqueName(domain, c.ID, c.PrettyName); e != nil {
|
|
return c, e
|
|
}
|
|
dirs, e := os.ReadDir(parent)
|
|
if e != nil {
|
|
return c, e
|
|
}
|
|
count := 0
|
|
for _, entry := range dirs {
|
|
if entry.IsDir() && validID(entry.Name()) {
|
|
if _, e := os.Stat(filepath.Join(parent, entry.Name(), "calendar.json")); e == nil {
|
|
count++
|
|
}
|
|
}
|
|
}
|
|
if count >= 256 {
|
|
return c, ErrLimit
|
|
}
|
|
if e = os.MkdirAll(dir, 0700); e != nil {
|
|
return c, e
|
|
}
|
|
e = saveMeta(dir, &c)
|
|
if e == nil {
|
|
for _, path := range []string{parent, r.Root, filepath.Dir(r.Root)} {
|
|
f, err := os.Open(path)
|
|
if err != nil {
|
|
return c, err
|
|
}
|
|
err = f.Sync()
|
|
f.Close()
|
|
if err != nil {
|
|
return c, err
|
|
}
|
|
}
|
|
}
|
|
return c, e
|
|
}
|
|
func (r *Repository) List(domain, actor string) ([]Calendar, error) {
|
|
if !validID(domain) {
|
|
return nil, ErrMissing
|
|
}
|
|
dirs, e := os.ReadDir(filepath.Join(r.Root, domain))
|
|
if os.IsNotExist(e) {
|
|
return []Calendar{}, nil
|
|
}
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
out := []Calendar{}
|
|
for _, d := range dirs {
|
|
if !d.IsDir() || !validID(d.Name()) {
|
|
continue
|
|
}
|
|
c, e := readMeta(filepath.Join(r.Root, domain, d.Name()))
|
|
if errors.Is(e, ErrMissing) {
|
|
continue
|
|
} // interrupted, uncommitted creation
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
if r.canRead(domain, c, actor) {
|
|
out = append(out, c)
|
|
}
|
|
}
|
|
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
|
|
return out, nil
|
|
}
|
|
func (r *Repository) Get(domain, id, actor string) (Calendar, error) {
|
|
dir, e := r.dir(domain, id)
|
|
if e != nil {
|
|
return Calendar{}, e
|
|
}
|
|
c, e := readMeta(dir)
|
|
if e == nil && !r.canRead(domain, c, actor) {
|
|
e = ErrMissing
|
|
}
|
|
return c, e
|
|
}
|
|
func (r *Repository) Settings(ctx context.Context, domain, id, actor, version, name string, public bool, members map[string]string, pretty ...string) (Calendar, error) {
|
|
dir, e := r.dir(domain, id)
|
|
if e != nil {
|
|
return Calendar{}, e
|
|
}
|
|
// Domain lock first, then calendar lock: serialize name reservations.
|
|
release, e := lock(ctx, filepath.Dir(dir))
|
|
if e != nil {
|
|
return Calendar{}, e
|
|
}
|
|
defer release()
|
|
unlock, e := lock(ctx, dir)
|
|
if e != nil {
|
|
return Calendar{}, e
|
|
}
|
|
defer unlock()
|
|
c, e := readMeta(dir)
|
|
if e != nil {
|
|
return c, e
|
|
}
|
|
if actor == "" || c.Owner != actor {
|
|
return c, ErrForbidden
|
|
}
|
|
if version != c.Version {
|
|
return c, ErrConflict
|
|
}
|
|
nameChanged := len(pretty) > 0 && pretty[0] != c.PrettyName
|
|
if nameChanged {
|
|
if !ValidPrettyName(pretty[0]) {
|
|
return c, ErrInvalid
|
|
}
|
|
if e = r.uniqueName(domain, id, pretty[0]); e != nil {
|
|
return c, e
|
|
}
|
|
c.PrettyName = pretty[0]
|
|
}
|
|
if public && r.PublicAllowed != nil && !r.PublicAllowed(domain) {
|
|
return c, ErrForbidden
|
|
}
|
|
if strings.TrimSpace(name) == "" || len(name) > 200 || len(members) > 200 {
|
|
return c, ErrInvalid
|
|
}
|
|
for id, role := range members {
|
|
if !validID(id) || (role != "read" && role != "write") {
|
|
return c, ErrInvalid
|
|
}
|
|
}
|
|
c.Name = name
|
|
c.Public = public
|
|
c.Members = members
|
|
if nameChanged {
|
|
if e = renameSnapshots(dir, &c); e != nil {
|
|
return c, e
|
|
}
|
|
}
|
|
e = saveMeta(dir, &c)
|
|
if e == nil {
|
|
pruneSnapshots(dir, c)
|
|
}
|
|
return c, e
|
|
}
|
|
|
|
// Delete removes one complete calendar. The Domain lock serializes deletion
|
|
// with creation/pretty-name reservation and the calendar lock serializes it
|
|
// with event/source writes. Cache rows are disposable, but deleting them
|
|
// before the atomic directory rename means a failed rename can safely rebuild
|
|
// them from the still-visible canonical files on the next access.
|
|
func (r *Repository) Delete(ctx context.Context, domain, id, actor, version string) (resultErr error) {
|
|
defer func() { resultErr = r.failure(resultErr) }()
|
|
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
|
defer cancel()
|
|
dir, err := r.dir(domain, id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
parent := filepath.Dir(dir)
|
|
release, err := lock(ctx, parent)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer release()
|
|
unlock, err := lock(ctx, dir)
|
|
if os.IsNotExist(err) {
|
|
return ErrMissing
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer unlock()
|
|
c, err := readMeta(dir)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if actor == "" || c.Owner != actor {
|
|
return ErrForbidden
|
|
}
|
|
if version == "" || version != c.Version {
|
|
return ErrConflict
|
|
}
|
|
tx, err := r.DB.BeginTx(ctx, nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer tx.Rollback()
|
|
for _, table := range []string{"calendar_event_cache", "calendar_month_cache", "calendar_index_state"} {
|
|
if _, err = tx.ExecContext(ctx, `DELETE FROM `+table+` WHERE domain=`+r.p(1)+` AND calendar=`+r.p(2), domain, id); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if err = tx.Commit(); err != nil {
|
|
return err
|
|
}
|
|
tombstone := filepath.Join(parent, ".deleted-calendar-"+id+"-"+uuid.NewString())
|
|
if err = os.Rename(dir, tombstone); err != nil {
|
|
return err
|
|
}
|
|
if err = syncDirectory(parent); err != nil {
|
|
return err
|
|
}
|
|
if err = os.RemoveAll(tombstone); err != nil {
|
|
return err
|
|
}
|
|
return syncDirectory(parent)
|
|
}
|
|
|
|
func syncDirectory(path string) error {
|
|
dir, err := os.Open(path)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer dir.Close()
|
|
return dir.Sync()
|
|
}
|
|
|
|
// refresh reconciles only changed monthly generations. A crash after manifest
|
|
// commit but before index commit repairs itself on the next request.
|
|
func (r *Repository) refresh(ctx context.Context, domain string, c Calendar, dir string) (resultErr error) {
|
|
defer func() { resultErr = r.failure(resultErr) }()
|
|
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
|
defer cancel()
|
|
var version string
|
|
if err := r.DB.QueryRowContext(ctx, `SELECT version FROM calendar_index_state WHERE domain=`+r.p(1)+` AND calendar=`+r.p(2), domain, c.ID).Scan(&version); err == nil && version == c.Version {
|
|
return nil
|
|
} else if err != nil && err != sql.ErrNoRows {
|
|
return err
|
|
}
|
|
tx, e := r.DB.BeginTx(ctx, nil)
|
|
if e != nil {
|
|
return e
|
|
}
|
|
defer tx.Rollback()
|
|
rows, e := tx.QueryContext(ctx, `SELECT month,hash FROM calendar_month_cache WHERE domain=`+r.p(1)+` AND calendar=`+r.p(2), domain, c.ID)
|
|
if e != nil {
|
|
return e
|
|
}
|
|
known := map[string]string{}
|
|
for rows.Next() {
|
|
var m, h string
|
|
if e = rows.Scan(&m, &h); e != nil {
|
|
rows.Close()
|
|
return e
|
|
}
|
|
known[m] = h
|
|
}
|
|
e = rows.Err()
|
|
rows.Close()
|
|
if e != nil {
|
|
return e
|
|
}
|
|
for m, h := range known {
|
|
if c.Months[m] != h {
|
|
if _, e = tx.ExecContext(ctx, `DELETE FROM calendar_event_cache WHERE domain=`+r.p(1)+` AND calendar=`+r.p(2)+` AND month=`+r.p(3), domain, c.ID, m); e != nil {
|
|
return e
|
|
}
|
|
if _, e = tx.ExecContext(ctx, `DELETE FROM calendar_month_cache WHERE domain=`+r.p(1)+` AND calendar=`+r.p(2)+` AND month=`+r.p(3), domain, c.ID, m); e != nil {
|
|
return e
|
|
}
|
|
}
|
|
}
|
|
for m, h := range c.Months {
|
|
if known[m] == h {
|
|
continue
|
|
}
|
|
if len(h) != 64 || strings.ContainsAny(h, "/\\") || len(m) != 7 {
|
|
return ErrInvalid
|
|
}
|
|
b, e := os.ReadFile(filepath.Join(dir, m+"."+h+".ics"))
|
|
if e != nil {
|
|
return e
|
|
}
|
|
if digest(b) != h {
|
|
return fmt.Errorf("calendar snapshot checksum mismatch")
|
|
}
|
|
cal, e := ical.NewDecoder(strings.NewReader(string(b))).Decode()
|
|
if e != nil {
|
|
return e
|
|
}
|
|
for _, child := range cal.Children {
|
|
data, e := encode(envelope(child))
|
|
if e != nil {
|
|
return e
|
|
}
|
|
event, e := Parse(data)
|
|
if e != nil {
|
|
return e
|
|
}
|
|
if _, e = tx.ExecContext(ctx, `INSERT INTO calendar_event_cache(domain,calendar,uid,month,start,"end",etag,data) VALUES(`+r.p(1)+`,`+r.p(2)+`,`+r.p(3)+`,`+r.p(4)+`,`+r.p(5)+`,`+r.p(6)+`,`+r.p(7)+`,`+r.p(8)+`)`, domain, c.ID, event.UID, m, event.Start.Unix(), event.End.Unix(), event.ETag, event.Data); e != nil {
|
|
return e
|
|
}
|
|
}
|
|
if _, e = tx.ExecContext(ctx, `INSERT INTO calendar_month_cache(domain,calendar,month,hash) VALUES(`+r.p(1)+`,`+r.p(2)+`,`+r.p(3)+`,`+r.p(4)+`)`, domain, c.ID, m, h); e != nil {
|
|
return e
|
|
}
|
|
}
|
|
if _, e = tx.ExecContext(ctx, `INSERT INTO calendar_index_state(domain,calendar,version) VALUES(`+r.p(1)+`,`+r.p(2)+`,`+r.p(3)+`) ON CONFLICT(domain,calendar) DO UPDATE SET version=excluded.version`, domain, c.ID, c.Version); e != nil {
|
|
return e
|
|
}
|
|
return tx.Commit()
|
|
}
|
|
func (r *Repository) locked(ctx context.Context, domain, id, actor string) (Calendar, string, func(), error) {
|
|
return r.lockedWithGuard(ctx, domain, id, actor, nil)
|
|
}
|
|
|
|
// The guard runs under the metadata lock, BEFORE reading any ICS snapshots.
|
|
func (r *Repository) lockedWithGuard(ctx context.Context, domain, id, actor string, guard func(Calendar) bool) (Calendar, string, func(), error) {
|
|
dir, e := r.dir(domain, id)
|
|
if e != nil {
|
|
return Calendar{}, "", nil, e
|
|
}
|
|
unlock, e := lock(ctx, dir)
|
|
if os.IsNotExist(e) {
|
|
e = ErrMissing
|
|
}
|
|
if e != nil {
|
|
return Calendar{}, "", nil, e
|
|
}
|
|
c, e := readMeta(dir)
|
|
if e == nil && !r.canRead(domain, c, actor) {
|
|
e = ErrMissing
|
|
}
|
|
if e == nil && guard != nil && !guard(c) {
|
|
e = ErrForbidden
|
|
}
|
|
if e == nil {
|
|
e = r.refresh(ctx, domain, c, dir)
|
|
}
|
|
if e != nil {
|
|
unlock()
|
|
return c, dir, nil, e
|
|
}
|
|
return c, dir, unlock, nil
|
|
}
|
|
func (r *Repository) Query(ctx context.Context, domain, id, actor string, start, end time.Time) ([]Event, error) {
|
|
return r.query(ctx, domain, id, actor, start, end, true)
|
|
}
|
|
func (r *Repository) QueryETags(ctx context.Context, domain, id, actor string, start, end time.Time) ([]Event, error) {
|
|
return r.query(ctx, domain, id, actor, start, end, false)
|
|
}
|
|
func (r *Repository) query(ctx context.Context, domain, id, actor string, start, end time.Time, withData bool) ([]Event, error) {
|
|
return r.queryLimit(ctx, domain, id, actor, start, end, withData, 5001)
|
|
}
|
|
|
|
// Upcoming bounds body parsing for the navigation modal, even in busy calendars.
|
|
func (r *Repository) Upcoming(ctx context.Context, domain, id, actor string, start, end time.Time) ([]Event, error) {
|
|
return r.queryLimit(ctx, domain, id, actor, start, end, true, 20)
|
|
}
|
|
func (r *Repository) queryLimit(ctx context.Context, domain, id, actor string, start, end time.Time, withData bool, limit int) (result []Event, resultErr error) {
|
|
defer func() { resultErr = r.failure(resultErr) }()
|
|
if !end.After(start) || end.Sub(start) > 370*24*time.Hour {
|
|
return nil, ErrInvalid
|
|
}
|
|
_, _, unlock, e := r.locked(ctx, domain, id, actor)
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
defer unlock()
|
|
columns := "uid,etag"
|
|
if withData {
|
|
columns = "data"
|
|
}
|
|
rows, e := r.DB.QueryContext(ctx, `SELECT `+columns+` FROM calendar_event_cache WHERE domain=`+r.p(1)+` AND calendar=`+r.p(2)+` AND start<`+r.p(3)+` AND ("end">`+r.p(4)+` OR (start="end" AND start>=`+r.p(5)+`)) ORDER BY start,uid LIMIT `+r.p(6), domain, id, end.Unix(), start.Unix(), start.Unix(), limit)
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
defer rows.Close()
|
|
out := []Event{}
|
|
for rows.Next() {
|
|
if !withData {
|
|
var v Event
|
|
if e = rows.Scan(&v.UID, &v.ETag); e != nil {
|
|
return nil, e
|
|
}
|
|
out = append(out, v)
|
|
continue
|
|
}
|
|
var data string
|
|
if e = rows.Scan(&data); e != nil {
|
|
return nil, e
|
|
}
|
|
v, e := Parse(data)
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
out = append(out, v)
|
|
}
|
|
if len(out) > 5000 {
|
|
return nil, ErrLimit
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
func (r *Repository) Event(ctx context.Context, domain, id, actor, uid string) (result Event, resultErr error) {
|
|
defer func() { resultErr = r.failure(resultErr) }()
|
|
_, _, unlock, e := r.locked(ctx, domain, id, actor)
|
|
if e != nil {
|
|
return Event{}, e
|
|
}
|
|
defer unlock()
|
|
var data string
|
|
e = r.DB.QueryRowContext(ctx, `SELECT data FROM calendar_event_cache WHERE domain=`+r.p(1)+` AND calendar=`+r.p(2)+` AND uid=`+r.p(3), domain, id, uid).Scan(&data)
|
|
if e == sql.ErrNoRows {
|
|
e = ErrMissing
|
|
}
|
|
if e != nil {
|
|
return Event{}, e
|
|
}
|
|
return Parse(data)
|
|
}
|
|
|
|
// Change commits a replacement manifest only after every affected month is
|
|
// durable. Moving an event across months is atomic, even across process crashes.
|
|
func (r *Repository) Change(ctx context.Context, domain, id, actor, uid, match string, item *Event) (Event, error) {
|
|
c, dir, unlock, e := r.locked(ctx, domain, id, actor)
|
|
if e != nil {
|
|
return Event{}, e
|
|
}
|
|
defer unlock()
|
|
return r.changeLocked(ctx, domain, actor, uid, match, item, c, dir)
|
|
}
|
|
|
|
func (r *Repository) changeLocked(ctx context.Context, domain, actor, uid, match string, item *Event, c Calendar, dir string) (result Event, resultErr error) {
|
|
defer func() { resultErr = r.failure(resultErr) }()
|
|
id := c.ID
|
|
if !c.CanWrite(actor) {
|
|
return Event{}, ErrForbidden
|
|
}
|
|
var oldData, oldMonth, oldTag string
|
|
e := r.DB.QueryRowContext(ctx, `SELECT data,month,etag FROM calendar_event_cache WHERE domain=`+r.p(1)+` AND calendar=`+r.p(2)+` AND uid=`+r.p(3), domain, id, uid).Scan(&oldData, &oldMonth, &oldTag)
|
|
exists := e == nil
|
|
if e != nil && e != sql.ErrNoRows {
|
|
return Event{}, e
|
|
}
|
|
if (exists && match != oldTag) || (!exists && match != "*") {
|
|
return Event{}, ErrConflict
|
|
}
|
|
if !exists && item == nil {
|
|
return Event{}, ErrMissing
|
|
}
|
|
next := Event{}
|
|
newMonth := ""
|
|
if item != nil {
|
|
next, e = Parse(item.Data)
|
|
if e != nil {
|
|
return Event{}, e
|
|
}
|
|
if next.UID != uid {
|
|
return Event{}, ErrInvalid
|
|
}
|
|
newMonth = next.Start.Format("2006-01")
|
|
} else {
|
|
delete(c.DAVNames, uid)
|
|
}
|
|
months := map[string]bool{}
|
|
if oldMonth != "" {
|
|
months[oldMonth] = true
|
|
}
|
|
if newMonth != "" {
|
|
months[newMonth] = true
|
|
}
|
|
for month := range months {
|
|
rows, e := r.DB.QueryContext(ctx, `SELECT data FROM calendar_event_cache WHERE domain=`+r.p(1)+` AND calendar=`+r.p(2)+` AND month=`+r.p(3)+` AND uid<>`+r.p(4)+` ORDER BY uid`, domain, id, month, uid)
|
|
if e != nil {
|
|
return Event{}, e
|
|
}
|
|
children := []*ical.Component{}
|
|
for rows.Next() {
|
|
var data string
|
|
if e = rows.Scan(&data); e != nil {
|
|
rows.Close()
|
|
return Event{}, e
|
|
}
|
|
ch, e := component(data)
|
|
if e != nil {
|
|
rows.Close()
|
|
return Event{}, e
|
|
}
|
|
children = append(children, ch)
|
|
}
|
|
e = rows.Err()
|
|
rows.Close()
|
|
if e != nil {
|
|
return Event{}, e
|
|
}
|
|
if newMonth == month {
|
|
ch, e := component(next.Data)
|
|
if e != nil {
|
|
return Event{}, e
|
|
}
|
|
children = append(children, ch)
|
|
}
|
|
if len(children) == 0 {
|
|
delete(c.Months, month)
|
|
continue
|
|
}
|
|
if len(children) > 5000 {
|
|
return Event{}, fmt.Errorf("monthly event limit exceeded")
|
|
}
|
|
cal := envelope(children...)
|
|
cal.Props.SetText("NAME", c.PrettyName)
|
|
data, e := encode(cal)
|
|
if e != nil {
|
|
return Event{}, e
|
|
}
|
|
if len(data) > 16<<20 {
|
|
return Event{}, fmt.Errorf("monthly calendar size limit exceeded")
|
|
}
|
|
hash := digest([]byte(data))
|
|
if e = atomicFile(filepath.Join(dir, month+"."+hash+".ics"), []byte(data)); e != nil {
|
|
return Event{}, e
|
|
}
|
|
c.Months[month] = hash
|
|
}
|
|
if e = saveMeta(dir, &c); e != nil {
|
|
return Event{}, e
|
|
}
|
|
// Only current generations are retained. Interrupted writes are harmless
|
|
// unreferenced files; clean them on the next successful commit.
|
|
files, _ := filepath.Glob(filepath.Join(dir, "*.ics"))
|
|
keep := map[string]bool{}
|
|
for month, hash := range c.Months {
|
|
keep[month+"."+hash+".ics"] = true
|
|
}
|
|
for _, file := range files {
|
|
if !keep[filepath.Base(file)] {
|
|
_ = os.Remove(file)
|
|
}
|
|
}
|
|
// The committed files, not the database cache, determine success. A subsequent read
|
|
// reconciles the cache; retries with the old ETag correctly get 412.
|
|
return next, nil
|
|
}
|