| 1 | package mapa |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/rand" |
| 6 | "encoding/binary" |
| 7 | "encoding/json" |
| 8 | "errors" |
| 9 | "fmt" |
| 10 | "log/slog" |
| 11 | "sync" |
| 12 | "sync/atomic" |
| 13 | "time" |
| 14 | |
| 15 | "gorm.io/gorm" |
| 16 | |
| 17 | "amadan.net/oficina/mapa/internal/mapa/seal" |
| 18 | ) |
| 19 | |
| 20 | // ErrUnlogged is a write that tried to commit without an event. §3.1: a |
| 21 | // write that logs no event is invisible to the index and to S1, so it is |
| 22 | // refused rather than committed (gate 8). |
| 23 | var ErrUnlogged = errors.New("mapa: a write logged no event") |
| 24 | |
| 25 | // Store is every durable read and write. Handlers never touch a sealed |
| 26 | // column directly; a write goes through Store.write, which is what makes |
| 27 | // gate 8 hold by construction rather than by care. |
| 28 | type Store struct { |
| 29 | database *gorm.DB |
| 30 | sealer *seal.Sealer |
| 31 | // now is the clock. Tests move it to age drafts and revisions. |
| 32 | now func() time.Time |
| 33 | // generation counts committed writes in this process. Readers that |
| 34 | // keep derived state (the index, the viewer cache) compare it before |
| 35 | // asking the database whether anything changed. |
| 36 | generation atomic.Int64 |
| 37 | viewers viewerCache |
| 38 | // nonces draws a new page's nonce, its public id. Random; a test |
| 39 | // may replace it (SetNonces). |
| 40 | nonces func(rung string) (int64, error) |
| 41 | // written is told of each committed write, in the writer's request: |
| 42 | // the index catches itself up there (review M3). |
| 43 | writtenMutex sync.Mutex |
| 44 | written []func(context.Context) |
| 45 | log *slog.Logger |
| 46 | // images is the object store, the blob slots and the limits |
| 47 | // (images.go). |
| 48 | images images |
| 49 | // small is the small-image cache (images_cache.go): bytes only, |
| 50 | // served after the read rule has passed. |
| 51 | small smallImages |
| 52 | // writing counts the write transactions open: IMG7 holds that no |
| 53 | // object store call is made inside one (§2.4). |
| 54 | writing atomic.Int32 |
| 55 | // sweepOpened counts the drafts the image sweep unsealed: IMG7 |
| 56 | // holds the common wake to none. |
| 57 | sweepOpened atomic.Int64 |
| 58 | } |
| 59 | |
| 60 | // afterWrite registers fn to run after each committed write. |
| 61 | func (store *Store) afterWrite(fn func(context.Context)) { |
| 62 | store.writtenMutex.Lock() |
| 63 | defer store.writtenMutex.Unlock() |
| 64 | store.written = append(store.written, fn) |
| 65 | } |
| 66 | |
| 67 | // SetLogger names where the store reports what it cannot return. |
| 68 | func (store *Store) SetLogger(logger *slog.Logger) { store.log = logger } |
| 69 | |
| 70 | func (store *Store) logger() *slog.Logger { |
| 71 | if store.log == nil { |
| 72 | return slog.Default() |
| 73 | } |
| 74 | return store.log |
| 75 | } |
| 76 | |
| 77 | // NewStore returns a Store over database. |
| 78 | func NewStore(database *gorm.DB, sealer *seal.Sealer) *Store { |
| 79 | fenceBookkeeping(database) |
| 80 | store := &Store{database: database, sealer: sealer, now: time.Now, |
| 81 | nonces: func(string) (int64, error) { return randomPositive() }} |
| 82 | store.images.slots = make(chan struct{}, BlobSlots) |
| 83 | store.images.reads = make(chan struct{}, UploadReads) |
| 84 | store.UseImages(ImageSetup{}) |
| 85 | return store |
| 86 | } |
| 87 | |
| 88 | // SetNonces replaces how page nonces are drawn. Tests only: gate 1 gives |
| 89 | // team pages and private pages separate, repeatable streams, so two |
| 90 | // teams that differ only in private writes get the same team page ids, |
| 91 | // as they would in expectation with random ones. Never in production. |
| 92 | func (store *Store) SetNonces(next func(rung string) int64) { |
| 93 | store.nonces = func(rung string) (int64, error) { return next(rung), nil } |
| 94 | } |
| 95 | |
| 96 | // RowID is the row id of the page a public id names, gone or not. |
| 97 | func (store *Store) RowID(ctx context.Context, |
| 98 | public string) (int64, bool, error) { |
| 99 | ref, found, err := store.refOf(ctx, public) |
| 100 | return ref.ID, found, err |
| 101 | } |
| 102 | |
| 103 | // SetClock replaces the clock. Tests only: nothing in production moves |
| 104 | // time. |
| 105 | func (store *Store) SetClock(now func() time.Time) { store.now = now } |
| 106 | |
| 107 | // Tx is one write transaction. It counts the events it logs, and |
| 108 | // Store.write refuses to commit a Tx that logged none. |
| 109 | type Tx struct { |
| 110 | db *gorm.DB |
| 111 | store *Store |
| 112 | at time.Time |
| 113 | events int |
| 114 | // importing is set by ImportCreate and ImportUpdate alone: their |
| 115 | // commits keep the record's Imported mark (import_store.go). |
| 116 | importing bool |
| 117 | } |
| 118 | |
| 119 | // write runs change in one transaction and commits only if it logged at |
| 120 | // least one event. Draft writes (drafts.go) and retention (retention.go) |
| 121 | // do not come through here: they are the two write paths exempt from |
| 122 | // gate 8, by name (§5). |
| 123 | func (store *Store) write(ctx context.Context, |
| 124 | change func(*Tx) error) error { |
| 125 | store.writing.Add(1) |
| 126 | defer store.writing.Add(-1) |
| 127 | err := store.database.WithContext(ctx).Transaction( |
| 128 | func(database *gorm.DB) error { |
| 129 | tx := &Tx{db: database, store: store, at: store.now().UTC()} |
| 130 | if err := change(tx); err != nil { |
| 131 | return err |
| 132 | } |
| 133 | if tx.events == 0 { |
| 134 | return ErrUnlogged |
| 135 | } |
| 136 | return nil |
| 137 | }) |
| 138 | if err != nil { |
| 139 | return err |
| 140 | } |
| 141 | store.generation.Add(1) |
| 142 | store.writtenMutex.Lock() |
| 143 | written := append([]func(context.Context){}, store.written...) |
| 144 | store.writtenMutex.Unlock() |
| 145 | for _, fn := range written { |
| 146 | fn(context.WithoutCancel(ctx)) |
| 147 | } |
| 148 | return nil |
| 149 | } |
| 150 | |
| 151 | // Generation is how many writes this process has committed. |
| 152 | func (store *Store) Generation() int64 { return store.generation.Load() } |
| 153 | |
| 154 | // log appends one event, in the same transaction as the change it names. |
| 155 | func (tx *Tx) log(actor int64, object string, objectID int64, |
| 156 | verb string, revision int64) error { |
| 157 | nonce, err := randomPositive() |
| 158 | if err != nil { |
| 159 | return err |
| 160 | } |
| 161 | event := Event{Nonce: nonce, At: tx.at, ActorID: actor, |
| 162 | ObjectKind: object, ObjectID: objectID, Verb: verb, |
| 163 | Revision: revision} |
| 164 | if err := tx.db.Create(&event).Error; err != nil { |
| 165 | return fmt.Errorf("mapa: logging %s: %w", verb, err) |
| 166 | } |
| 167 | tx.events++ |
| 168 | return nil |
| 169 | } |
| 170 | |
| 171 | // randomPositive is a random positive int63: page and event nonces, and |
| 172 | // revisions (§5, doctrine §6.6). Never zero, so a zero always means "not |
| 173 | // set". |
| 174 | func randomPositive() (int64, error) { |
| 175 | var raw [8]byte |
| 176 | for { |
| 177 | if _, err := rand.Read(raw[:]); err != nil { |
| 178 | return 0, err |
| 179 | } |
| 180 | value := int64(binary.BigEndian.Uint64(raw[:]) >> 1) |
| 181 | if value != 0 { |
| 182 | return value, nil |
| 183 | } |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | // Record is what a page says: one sealed value on the page row and on |
| 188 | // each revision. Title is set for team pages and Date for daily notes; |
| 189 | // a scratch page is its body alone (§8's S3 layout). |
| 190 | type Record struct { |
| 191 | Title string `json:"title,omitempty"` |
| 192 | Date string `json:"date,omitempty"` |
| 193 | Body string `json:"body"` |
| 194 | // Origin is where an imported page came from, carried forward by |
| 195 | // every later commit (Notion import spec §14.2). |
| 196 | Origin *Origin `json:"origin,omitempty"` |
| 197 | // Imported marks a revision the import wrote. tx.commit clears it on |
| 198 | // every write but the import's own (gate I18). |
| 199 | Imported bool `json:"imported,omitempty"` |
| 200 | // Icon and Banner are a team page's look (columns and icons spec |
| 201 | // §2.1, §3.1), carried forward by every commit as Origin is. |
| 202 | Icon *Icon `json:"icon,omitempty"` |
| 203 | Banner *Banner `json:"banner,omitempty"` |
| 204 | } |
| 205 | |
| 206 | // Origin is an imported page's source and its times there. |
| 207 | type Origin struct { |
| 208 | Source string `json:"source"` |
| 209 | Created string `json:"created,omitempty"` |
| 210 | Edited string `json:"edited,omitempty"` |
| 211 | } |
| 212 | |
| 213 | // sealRecord seals a record under purpose. |
| 214 | func (store *Store) sealRecord(purpose string, record Record) ([]byte, |
| 215 | error) { |
| 216 | plain, err := json.Marshal(record) |
| 217 | if err != nil { |
| 218 | return nil, err |
| 219 | } |
| 220 | return store.sealer.Seal(purpose, plain) |
| 221 | } |
| 222 | |
| 223 | // openRecord opens a record sealed under purpose. An empty value is an |
| 224 | // empty record: a pruned or never-written one. |
| 225 | func (store *Store) openRecord(purpose string, sealed []byte) (Record, |
| 226 | error) { |
| 227 | var record Record |
| 228 | if len(sealed) == 0 { |
| 229 | return record, nil |
| 230 | } |
| 231 | plain, err := store.sealer.Open(purpose, sealed) |
| 232 | if err != nil { |
| 233 | return record, fmt.Errorf("mapa: opening a record: %w", err) |
| 234 | } |
| 235 | return record, json.Unmarshal(plain, &record) |
| 236 | } |
| 237 | |
| 238 | // OpenPage returns a page's record. |
| 239 | func (store *Store) OpenPage(page Page) (Record, error) { |
| 240 | return store.openRecord(seal.PurposeRecord, page.SealedRecord) |
| 241 | } |
| 242 | |