| 1 | package docs |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | crand "crypto/rand" |
| 6 | "encoding/binary" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "io" |
| 10 | "time" |
| 11 | |
| 12 | "gorm.io/gorm" |
| 13 | ) |
| 14 | |
| 15 | // errUnknownVisibility is a visibility form posting something other than |
| 16 | // the two rungs this column holds. |
| 17 | var errUnknownVisibility = errors.New("docs: unknown visibility") |
| 18 | |
| 19 | // suiteClock is the feed's clock, for touched_at only. Nothing the suite |
| 20 | // contract matches on — a revision, a cursor's nonce — is read from it, so a |
| 21 | // clock set back across a restore cannot make a value repeat. A variable so |
| 22 | // a test can set it back and show exactly that. |
| 23 | var suiteClock = time.Now |
| 24 | |
| 25 | // randomSource is where revisions and feed nonces come from: crypto/rand. |
| 26 | // A variable so a test can force particular draws; a source that fails is |
| 27 | // an error, and the change that wanted the value does not commit. Nothing |
| 28 | // falls back to a clock, a counter or math/rand, which a restore or an |
| 29 | // attacker could reproduce. |
| 30 | var randomSource io.Reader = crand.Reader |
| 31 | |
| 32 | // errNoRandomness is a randomSource that could not be read. |
| 33 | var errNoRandomness = errors.New("docs: no randomness for a revision or a feed nonce") |
| 34 | |
| 35 | // randomPositive is a fresh positive int63 from randomSource: eight bytes, |
| 36 | // the sign bit cleared, and a zero drawn again (0 is memoria's "not a |
| 37 | // sibling" value and below the column's CHECK). |
| 38 | func randomPositive() (int64, error) { |
| 39 | for { |
| 40 | var b [8]byte |
| 41 | if _, err := io.ReadFull(randomSource, b[:]); err != nil { |
| 42 | return 0, errNoRandomness |
| 43 | } |
| 44 | if n := int64(binary.BigEndian.Uint64(b[:]) & (1<<63 - 1)); n != 0 { |
| 45 | return n, nil |
| 46 | } |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | // newRevision is the revision a change is given: a fresh random positive |
| 51 | // int63 that taken does not report. Revisions are not counted up and not |
| 52 | // read from a clock (Astra on oficina/docs feat/suite-producer, two rounds, |
| 53 | // 2026-11-01): after a restore from a backup — including one taken before |
| 54 | // migration 0011, and one restored onto a clock set back — a counter or a |
| 55 | // clock issues again a revision it issued before, for different content, |
| 56 | // and S2 answers VISIBLE against a copy the asker may no longer read. A draw |
| 57 | // matches any one earlier value with probability 2^-63 (spec §8.2.2 has the |
| 58 | // cumulative figure), whatever the clock, the migration's timing or the |
| 59 | // backup. Order is not needed: memoria only ever matches revisions for |
| 60 | // equality (memoria models.go, SiblingRevision), and S2's STALE is decided |
| 61 | // from this log (Rule), not by comparing numbers. |
| 62 | // |
| 63 | // taken is asked about every draw, and a draw it reports is drawn again. |
| 64 | // For a document that exists it is logRevisionTaken: the current revision |
| 65 | // and every revision suite_feed holds for that document, because suite |
| 66 | // revision 11 §6.6 (91affa1) makes a revision unique per item against the |
| 67 | // whole log — a draw equal to a prior revision gives an old name to new |
| 68 | // bytes, and a consumer still holding that prior copy would be told VISIBLE |
| 69 | // over it. A new document has no log, and nothing is taken. |
| 70 | func newRevision(taken func(int64) (bool, error)) (int64, error) { |
| 71 | for { |
| 72 | r, err := randomPositive() |
| 73 | if err != nil { |
| 74 | return 0, err |
| 75 | } |
| 76 | used, err := taken(r) |
| 77 | if err != nil { |
| 78 | return 0, err |
| 79 | } |
| 80 | if !used { |
| 81 | return r, nil |
| 82 | } |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | // noRevisionTaken is newRevision's taken for a document being created: it |
| 87 | // has no current revision and no log yet. |
| 88 | func noRevisionTaken(int64) (bool, error) { return false, nil } |
| 89 | |
| 90 | // logRevisionTaken reports a draw that is the document's current revision |
| 91 | // or any revision its suite_feed rows hold, read in the caller's |
| 92 | // transaction. suite_feed_document_revision (0012) keeps it one index probe, |
| 93 | // since every applied update bumps and the log only grows. |
| 94 | func logRevisionTaken(tx *gorm.DB, docID, current int64) func(int64) (bool, error) { |
| 95 | return func(r int64) (bool, error) { |
| 96 | if r == current { |
| 97 | return true, nil |
| 98 | } |
| 99 | var held []int64 |
| 100 | if err := tx.Model(&SuiteFeedRow{}).Where("document_id = ? AND revision = ?", docID, r).Limit(1).Pluck("revision", &held).Error; err != nil { |
| 101 | return false, fmt.Errorf("docs: read the log of document %d: %w", docID, err) |
| 102 | } |
| 103 | return len(held) > 0, nil |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | // announce appends one row to suite_feed, with a fresh random nonce for the |
| 108 | // S1 cursor. Called only inside the transaction that made the change it |
| 109 | // records, so the log and the documents table can never disagree about a |
| 110 | // committed revision (spec §8.2.2). |
| 111 | func announce(tx *gorm.DB, docID, revision int64, gone bool) error { |
| 112 | nonce, err := randomPositive() |
| 113 | if err != nil { |
| 114 | return err |
| 115 | } |
| 116 | row := &SuiteFeedRow{DocumentID: docID, Revision: revision, Gone: gone, TouchedAt: suiteClock().UTC(), Stamp: nonce} |
| 117 | if err := tx.Create(row).Error; err != nil { |
| 118 | return fmt.Errorf("docs: announce document %d: %w", docID, err) |
| 119 | } |
| 120 | return nil |
| 121 | } |
| 122 | |
| 123 | // bumpRevision moves a document to a new revision (newRevision, never one |
| 124 | // its log holds) and announces it, in the caller's transaction. Every change a suite consumer |
| 125 | // must re-read goes through here: an applied update, a rename, a visibility |
| 126 | // change and a deletion (gone). A row that is not there is an error rather |
| 127 | // than a silent no-op, because a bump that touched nothing would announce a |
| 128 | // revision no document has. |
| 129 | func bumpRevision(tx *gorm.DB, docID int64, gone bool) error { |
| 130 | var current int64 |
| 131 | if err := tx.Model(&Document{}).Where("id = ?", docID).Select("revision").Scan(¤t).Error; err != nil { |
| 132 | return fmt.Errorf("docs: read revision of document %d: %w", docID, err) |
| 133 | } |
| 134 | revision, err := newRevision(logRevisionTaken(tx, docID, current)) |
| 135 | if err != nil { |
| 136 | return err |
| 137 | } |
| 138 | // UpdateColumn, not Update: GORM's Update also stamps updated_at, and a |
| 139 | // bump is not an edit — the list's recency must not move on a rename of |
| 140 | // the rung or a deletion's bookkeeping. |
| 141 | res := tx.Model(&Document{}).Where("id = ?", docID).UpdateColumn("revision", revision) |
| 142 | if res.Error != nil { |
| 143 | return fmt.Errorf("docs: bump revision of document %d: %w", docID, res.Error) |
| 144 | } |
| 145 | if res.RowsAffected != 1 { |
| 146 | return fmt.Errorf("docs: bump revision of document %d: %d rows", docID, res.RowsAffected) |
| 147 | } |
| 148 | return announce(tx, docID, revision, gone) |
| 149 | } |
| 150 | |
| 151 | // SetVisibility moves a document between the private and team rungs (spec |
| 152 | // §8.2.1). The owner's alone, through the owner-scoped Get and ownerMutation, |
| 153 | // exactly as granting is: a writer may edit a document and still may not |
| 154 | // decide who else reads it. Setting the rung it is already on changes |
| 155 | // nothing and announces nothing. |
| 156 | func (s *Store) SetVisibility(ctx context.Context, owner int64, sqid string, v Visibility) error { |
| 157 | if !v.valid() { |
| 158 | return errUnknownVisibility |
| 159 | } |
| 160 | doc, err := s.Get(ctx, owner, sqid) |
| 161 | if err != nil { |
| 162 | return err |
| 163 | } |
| 164 | return s.ownerMutation(ctx, owner, doc.ID, func(tx *gorm.DB) error { |
| 165 | res := tx.Model(&Document{}). |
| 166 | Where("id = ? AND deleted_at IS NULL AND visibility <> ?", doc.ID, v). |
| 167 | UpdateColumn("visibility", v) |
| 168 | if res.Error != nil { |
| 169 | return res.Error |
| 170 | } |
| 171 | if res.RowsAffected == 0 { |
| 172 | return nil |
| 173 | } |
| 174 | return bumpRevision(tx, doc.ID, false) |
| 175 | }) |
| 176 | } |
| 177 | |
| 178 | // deleteDocument soft-deletes a document and announces it gone, in one |
| 179 | // transaction, with no owner check: the tests' way in (TestSoftDelete). |
| 180 | // The person's way in is Store.Delete (delete.go), behind the owner's |
| 181 | // guard; both go through softDelete, so neither can forget the feed row. |
| 182 | func (s *Store) deleteDocument(ctx context.Context, docID int64) error { |
| 183 | defer s.warm.drop(ctx, docID) // warm.go, rule 6 |
| 184 | return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| 185 | return softDelete(tx, docID) |
| 186 | }) |
| 187 | } |
| 188 | |
| 189 | // softDelete stamps deleted_at and bumps the document's revision as a |
| 190 | // deletion, so the suite feed announces it gone. A document already |
| 191 | // deleted is left alone and announced nothing. |
| 192 | func softDelete(tx *gorm.DB, docID int64) error { |
| 193 | res := tx.Model(&Document{}). |
| 194 | Where("id = ? AND deleted_at IS NULL", docID). |
| 195 | Update("deleted_at", time.Now().UTC()) |
| 196 | if res.Error != nil { |
| 197 | return res.Error |
| 198 | } |
| 199 | if res.RowsAffected == 0 { |
| 200 | return nil |
| 201 | } |
| 202 | return bumpRevision(tx, docID, true) |
| 203 | } |
| 204 | |