| 1 | package sheets |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "unicode/utf8" |
| 7 | |
| 8 | access "amadan.net/oficina/agent-access.git" |
| 9 | "amadan.net/oficina/home/connect/linkstore" |
| 10 | "amadan.net/oficina/sheets/internal/sheets/store" |
| 11 | "github.com/google/uuid" |
| 12 | "gorm.io/gorm" |
| 13 | ) |
| 14 | |
| 15 | // Only hashes, coordinates and sealed client attribution reach the receipt. |
| 16 | type sheetAgentEdit struct { |
| 17 | Coordinate string `gorm:"primaryKey"` |
| 18 | Content string `gorm:"not null"` |
| 19 | SheetID uint64 `gorm:"not null"` |
| 20 | TabID uint64 `gorm:"not null"` |
| 21 | Before uint64 `gorm:"not null"` |
| 22 | Revision uint64 `gorm:"not null"` |
| 23 | MemberID uint64 `gorm:"not null"` |
| 24 | FirstEventID uint64 `gorm:"not null"` |
| 25 | LastEventID uint64 `gorm:"not null"` |
| 26 | ClientSealed []byte `gorm:"not null"` |
| 27 | } |
| 28 | |
| 29 | func (sheetAgentEdit) TableName() string { return "sheets_agent_edits" } |
| 30 | |
| 31 | type sheetAgentSetRange struct { |
| 32 | Team string `json:"team"` |
| 33 | SheetID string `json:"sheet_id"` |
| 34 | TabID string `json:"tab_id"` |
| 35 | ExpectedRevision string `json:"expected_revision"` |
| 36 | ClientID string `json:"client_id"` |
| 37 | Cells []sheetAgentCell `json:"cells"` |
| 38 | } |
| 39 | |
| 40 | func (a *sheetAgent) editor(ctx context.Context, db *gorm.DB, member Member, sheetID, tabID uint64) error { |
| 41 | role, err := a.role(ctx, db, sheetID, member) |
| 42 | if err != nil { |
| 43 | return err |
| 44 | } |
| 45 | if !role.Allows(SheetEditor) { |
| 46 | return errNoAccess |
| 47 | } |
| 48 | var tab store.Tab |
| 49 | return db.WithContext(ctx).Where("id=? AND sheet_id=?", tabID, sheetID).Take(&tab).Error |
| 50 | } |
| 51 | |
| 52 | func (a *sheetAgent) editorInTx(ctx context.Context, tx *gorm.DB, p access.Principal, expected Member, sheetID, tabID uint64) error { |
| 53 | state, ok := ctx.Value(sheetAgentKey{}).(*sheetAgentContext) |
| 54 | if !ok || state == nil || state.verify == nil { |
| 55 | return linkstore.ErrRefused |
| 56 | } |
| 57 | if err := state.verify(ctx); err != nil { |
| 58 | return err |
| 59 | } |
| 60 | person, err := a.app.home.ResolveOn(ctx, tx.Statement.ConnPool, p.Subject) |
| 61 | if err != nil { |
| 62 | return err |
| 63 | } |
| 64 | if person.ID <= 0 || uint64(person.ID) != expected.ID || person.Label != expected.Address { |
| 65 | return linkstore.ErrRefused |
| 66 | } |
| 67 | var current Member |
| 68 | if err = tx.First(¤t, person.ID).Error; err != nil { |
| 69 | return err |
| 70 | } |
| 71 | if current.Address != expected.Address { |
| 72 | return linkstore.ErrRefused |
| 73 | } |
| 74 | current.team = expected.team |
| 75 | return a.editor(ctx, tx, current, sheetID, tabID) |
| 76 | } |
| 77 | |
| 78 | func (a *sheetAgent) setRange(ctx context.Context, p access.Principal, member Member, input sheetAgentSetRange) (any, error) { |
| 79 | sheetID, err := sheetAgentID(input.SheetID) |
| 80 | if err != nil { |
| 81 | return nil, err |
| 82 | } |
| 83 | tabID, err := sheetAgentID(input.TabID) |
| 84 | if err != nil { |
| 85 | return nil, err |
| 86 | } |
| 87 | expected, err := sheetAgentID(input.ExpectedRevision) |
| 88 | if err != nil { |
| 89 | return nil, err |
| 90 | } |
| 91 | id, err := uuid.Parse(input.ClientID) |
| 92 | if err != nil || id == uuid.Nil || id.String() != input.ClientID { |
| 93 | return nil, access.Fail("invalid", "Use a canonical nonzero client UUID.") |
| 94 | } |
| 95 | writes := make([]store.CellWrite, len(input.Cells)) |
| 96 | for i, cell := range input.Cells { |
| 97 | if !inCellRange(cell.Row, cell.Column) || len(cell.Raw) > maxRawBytes || !utf8.ValidString(cell.Raw) { |
| 98 | return nil, access.Fail("invalid", "Invalid cell coordinate or input.") |
| 99 | } |
| 100 | writes[i] = store.CellWrite{Row: cell.Row, Col: cell.Column, Raw: cell.Raw} |
| 101 | } |
| 102 | if err = store.ValidateCellWrites(writes); err != nil { |
| 103 | return nil, access.Fail("invalid", "Invalid cell batch.") |
| 104 | } |
| 105 | if err = a.editor(ctx, a.app.db, member, sheetID, tabID); err != nil { |
| 106 | return nil, sheetAgentFailure(err) |
| 107 | } |
| 108 | h, err := store.Open(a.app.db, a.app.sealer, tabID) |
| 109 | if err != nil { |
| 110 | return nil, sheetAgentFailure(err) |
| 111 | } |
| 112 | defer h.Release() |
| 113 | coordinate := a.digest("edit-coordinate", []string{"sheets_set_range", a.identityIssuer, a.issuer, a.team, p.Subject, p.Client, input.ClientID}) |
| 114 | payload := a.digest("edit-content", input) |
| 115 | var applied uint64 |
| 116 | report, err := h.SetBatchInTransaction(ctx, a.app.writeGuard(ctx, sheetID, member, SheetEditor), writes, member.ID, func(tx *gorm.DB, apply func(uint64) (uint64, error)) error { |
| 117 | if e := a.bind(tx); e != nil { |
| 118 | return e |
| 119 | } |
| 120 | if e := a.editorInTx(ctx, tx, p, member, sheetID, tabID); e != nil { |
| 121 | return e |
| 122 | } |
| 123 | var receipt sheetAgentEdit |
| 124 | e := tx.Where("coordinate=?", coordinate).Take(&receipt).Error |
| 125 | if e == nil { |
| 126 | if receipt.Content != payload || receipt.SheetID != sheetID || receipt.TabID != tabID { |
| 127 | return access.Fail("conflict", "This client UUID already names a different edit.") |
| 128 | } |
| 129 | applied = receipt.Revision |
| 130 | return a.editorInTx(ctx, tx, p, member, sheetID, tabID) |
| 131 | } |
| 132 | if !errors.Is(e, gorm.ErrRecordNotFound) { |
| 133 | return e |
| 134 | } |
| 135 | var previousEvent uint64 |
| 136 | if e = tx.Model(&store.Event{}).Where("tab_id=? AND kind=?", tabID, store.KindInput).Select("COALESCE(MAX(id),0)").Scan(&previousEvent).Error; e != nil { |
| 137 | return e |
| 138 | } |
| 139 | applied, e = apply(expected) |
| 140 | if e != nil { |
| 141 | return e |
| 142 | } |
| 143 | var events struct { |
| 144 | First, Last uint64 |
| 145 | Count int64 |
| 146 | } |
| 147 | if e = tx.Model(&store.Event{}).Where("tab_id=? AND kind=? AND id>?", tabID, store.KindInput, previousEvent).Select("COALESCE(MIN(id),0) AS first, COALESCE(MAX(id),0) AS last, COUNT(*) AS count").Scan(&events).Error; e != nil { |
| 148 | return e |
| 149 | } |
| 150 | if events.First == 0 || events.Last < events.First || events.Count != int64(len(writes)) { |
| 151 | return access.Fail("unavailable", "The edit's native event attribution is incomplete.") |
| 152 | } |
| 153 | client, e := a.app.sealer.Seal("agent.edit.client/"+coordinate, []byte(p.Client)) |
| 154 | if e != nil { |
| 155 | return e |
| 156 | } |
| 157 | receipt = sheetAgentEdit{Coordinate: coordinate, Content: payload, SheetID: sheetID, TabID: tabID, Before: expected, Revision: applied, MemberID: member.ID, FirstEventID: events.First, LastEventID: events.Last, ClientSealed: client} |
| 158 | if e = tx.Create(&receipt).Error; e != nil { |
| 159 | return e |
| 160 | } |
| 161 | if _, e = sheetAgentBounded(a.created(sheetID, tabID, applied)); e != nil { |
| 162 | return e |
| 163 | } |
| 164 | return a.editorInTx(ctx, tx, p, member, sheetID, tabID) |
| 165 | }) |
| 166 | if errors.Is(err, store.ErrRevisionConflict) { |
| 167 | return nil, access.Fail("conflict", "This tab changed. Read it again before editing.") |
| 168 | } |
| 169 | if err != nil { |
| 170 | return nil, sheetAgentFailure(err) |
| 171 | } |
| 172 | if report.Stamps > 0 { |
| 173 | a.app.publishReport(SheetSummary{ID: sheetID, TabID: tabID}, h, report) |
| 174 | } |
| 175 | a.remember(ctx, sheetID) |
| 176 | if state, ok := ctx.Value(sheetAgentKey{}).(*sheetAgentContext); ok && state != nil { |
| 177 | if state.edits == nil { |
| 178 | state.edits = make(map[uint64]bool) |
| 179 | } |
| 180 | state.edits[sheetID] = true |
| 181 | } |
| 182 | return sheetAgentBounded(a.created(sheetID, tabID, applied)) |
| 183 | } |
| 184 | |