| 1 | package mapa |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "time" |
| 8 | |
| 9 | "gorm.io/gorm" |
| 10 | |
| 11 | "amadan.net/oficina/mapa/internal/mapa/seal" |
| 12 | "amadan.net/oficina/notion.git/notion" |
| 13 | ) |
| 14 | |
| 15 | // The credential (Notion import spec §6): a Notion internal integration |
| 16 | // token, pasted by an importer, verified with one call, sealed under its |
| 17 | // own purpose and never rendered. Each act on it is the person's and |
| 18 | // logs an event of object kind import (§14.2). |
| 19 | |
| 20 | // Refusals an importer can act on. |
| 21 | var ( |
| 22 | ErrRunActive = errors.New("An import is running. Stop the run first.") |
| 23 | ErrOtherWorkspace = errors.New("This import came from another " + |
| 24 | "Notion workspace. Forget the import first.") |
| 25 | ErrNotConnected = errors.New("Mapa isn't connected to Notion.") |
| 26 | ) |
| 27 | |
| 28 | // Import event verbs, on object kind import. |
| 29 | const ( |
| 30 | VerbConnected = "connected" |
| 31 | VerbTokenReplaced = "token_replaced" |
| 32 | VerbDisconnected = "disconnected" |
| 33 | VerbFinished = "finished" |
| 34 | VerbForgotten = "forgotten" |
| 35 | VerbStarted = "started" |
| 36 | VerbStopped = "stopped" |
| 37 | VerbResumed = "resumed" |
| 38 | VerbStartedOver = "started_over" |
| 39 | ) |
| 40 | |
| 41 | // connection is the one connection row, if there is one. |
| 42 | func connection(database *gorm.DB) (NotionConnection, bool, error) { |
| 43 | var row NotionConnection |
| 44 | err := database.Order("id").First(&row).Error |
| 45 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 46 | return row, false, nil |
| 47 | } |
| 48 | return row, err == nil, err |
| 49 | } |
| 50 | |
| 51 | // activeRun is the run in surveying or writing, if any. |
| 52 | func activeRun(database *gorm.DB) (NotionRun, bool, error) { |
| 53 | var run NotionRun |
| 54 | err := database.Where("state IN ?", []string{runSurveying, |
| 55 | runWriting}).Order("id DESC").First(&run).Error |
| 56 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 57 | return run, false, nil |
| 58 | } |
| 59 | return run, err == nil, err |
| 60 | } |
| 61 | |
| 62 | // Connect saves a verified token, or replaces the one saved. A token |
| 63 | // for a workspace other than the map's is refused while a map exists, |
| 64 | // and replacing a token ends any resumable run: a Resume never runs on |
| 65 | // a token other than the one its survey used (spec §8.3). |
| 66 | func (store *Store) Connect(ctx context.Context, who, token string, |
| 67 | workspace notion.Workspace) error { |
| 68 | return store.write(ctx, func(tx *Tx) error { |
| 69 | actor, err := tx.member(who) |
| 70 | if err != nil { |
| 71 | return err |
| 72 | } |
| 73 | if err := tx.refuseActive(); err != nil { |
| 74 | return err |
| 75 | } |
| 76 | if err := tx.claimWorkspace(workspace); err != nil { |
| 77 | return err |
| 78 | } |
| 79 | row, found, err := connection(tx.db) |
| 80 | if err != nil { |
| 81 | return err |
| 82 | } |
| 83 | verb := VerbConnected |
| 84 | if found { |
| 85 | verb = VerbTokenReplaced |
| 86 | if err := tx.endResumable(runDisconnected); err != nil { |
| 87 | return err |
| 88 | } |
| 89 | } |
| 90 | return tx.saveConnection(actor, row, token, workspace, verb) |
| 91 | }) |
| 92 | } |
| 93 | |
| 94 | func (tx *Tx) saveConnection(actor int64, row NotionConnection, token string, |
| 95 | workspace notion.Workspace, verb string) error { |
| 96 | sealedToken, err := tx.store.sealer.Seal(seal.PurposeNotionToken, |
| 97 | []byte(token)) |
| 98 | if err != nil { |
| 99 | return err |
| 100 | } |
| 101 | plain, _ := json.Marshal(workspace) |
| 102 | sealedWorkspace, err := tx.store.sealer.Seal( |
| 103 | seal.PurposeNotionWorkspace, plain) |
| 104 | if err != nil { |
| 105 | return err |
| 106 | } |
| 107 | if row.ID == 0 { |
| 108 | row = NotionConnection{CreatedBy: actor, CreatedAt: tx.at} |
| 109 | } |
| 110 | row.VerifiedAt, row.SealedToken = tx.at, sealedToken |
| 111 | row.SealedWorkspace = sealedWorkspace |
| 112 | if err := tx.db.Save(&row).Error; err != nil { |
| 113 | return err |
| 114 | } |
| 115 | return tx.log(actor, ObjectImport, row.ID, verb, 0) |
| 116 | } |
| 117 | |
| 118 | // claimWorkspace records the map's workspace, or refuses another while |
| 119 | // a map exists. The identity is the workspace id when Notion gives one, |
| 120 | // else its name (spec §8.3: whether /v1/users/me carries an id is |
| 121 | // unverified until §19 step 5). |
| 122 | func (tx *Tx) claimWorkspace(workspace notion.Workspace) error { |
| 123 | row, found, err := tx.store.mapRowOf(tx.db, workspaceKey) |
| 124 | if err != nil { |
| 125 | return err |
| 126 | } |
| 127 | if found { |
| 128 | place, err := tx.store.openCoordinate(row) |
| 129 | if err != nil || place.Workspace == workspace.Identity() { |
| 130 | return err |
| 131 | } |
| 132 | var others int64 |
| 133 | err = tx.db.Model(&NotionPage{}).Where("state <> ?", |
| 134 | mapWorkspace).Count(&others).Error |
| 135 | if err != nil || others > 0 { |
| 136 | return errors.Join(ErrOtherWorkspace, err) |
| 137 | } |
| 138 | } |
| 139 | sealed, err := tx.store.sealCoordinate(coordinate{ |
| 140 | NotionID: workspaceKey, Workspace: workspace.Identity()}) |
| 141 | if err != nil { |
| 142 | return err |
| 143 | } |
| 144 | row.State, row.SealedCoordinate = mapWorkspace, sealed |
| 145 | return saveRow(tx.db, &row) |
| 146 | } |
| 147 | |
| 148 | // refuseActive refuses a person's act while a run is surveying or |
| 149 | // writing. Stop always works, so a stuck run never blocks one. |
| 150 | func (tx *Tx) refuseActive() error { |
| 151 | _, active, err := activeRun(tx.db) |
| 152 | if err == nil && active { |
| 153 | return ErrRunActive |
| 154 | } |
| 155 | return err |
| 156 | } |
| 157 | |
| 158 | // endResumable ends any interrupted or stopped run with code, clearing |
| 159 | // staged trees, so the next run is a Start. |
| 160 | func (tx *Tx) endResumable(code string) error { |
| 161 | err := tx.db.Model(&NotionRun{}).Where("state IN ?", |
| 162 | []string{runInterrupted, runStopped}).Updates(map[string]any{ |
| 163 | "state": runFailed, "error_code": code, "finished_at": tx.at}).Error |
| 164 | if err != nil { |
| 165 | return err |
| 166 | } |
| 167 | return clearStaged(tx.db) |
| 168 | } |
| 169 | |
| 170 | // clearStaged deletes every staged tree. A row left staged by a run |
| 171 | // that ended goes back to what it was: its map coordinate is unchanged. |
| 172 | func clearStaged(database *gorm.DB) error { |
| 173 | return database.Model(&NotionPage{}). |
| 174 | Where("sealed_staged IS NOT NULL"). |
| 175 | Update("sealed_staged", nil).Error |
| 176 | } |
| 177 | |
| 178 | // Disconnect deletes the token. The map stays. |
| 179 | func (store *Store) Disconnect(ctx context.Context, who string) error { |
| 180 | return store.connectionAct(ctx, who, VerbDisconnected, |
| 181 | func(tx *Tx) error { return tx.endResumable(runDisconnected) }) |
| 182 | } |
| 183 | |
| 184 | // Finish is the importer saying Notion is no longer the source: the |
| 185 | // token and every staged tree go, and the map stays, set aside for the |
| 186 | // databases phase (spec §8.6). A new import after it is a new import. |
| 187 | func (store *Store) Finish(ctx context.Context, who string) error { |
| 188 | return store.connectionAct(ctx, who, VerbFinished, func(tx *Tx) error { |
| 189 | if err := tx.endResumable(runFinished); err != nil { |
| 190 | return err |
| 191 | } |
| 192 | return tx.db.Model(&NotionPage{}).Where("state NOT IN ?", |
| 193 | []string{mapRow, mapDatabase, mapWorkspace}). |
| 194 | Update("state", mapFinished).Error |
| 195 | }) |
| 196 | } |
| 197 | |
| 198 | // connectionAct deletes the connection and runs more, as one write. |
| 199 | func (store *Store) connectionAct(ctx context.Context, who, verb string, |
| 200 | more func(*Tx) error) error { |
| 201 | return store.write(ctx, func(tx *Tx) error { |
| 202 | actor, err := tx.member(who) |
| 203 | if err != nil { |
| 204 | return err |
| 205 | } |
| 206 | if err := tx.refuseActive(); err != nil { |
| 207 | return err |
| 208 | } |
| 209 | row, found, err := connection(tx.db) |
| 210 | if err != nil || !found { |
| 211 | return errors.Join(ErrNotConnected, err) |
| 212 | } |
| 213 | if err := tx.db.Delete(&row).Error; err != nil { |
| 214 | return err |
| 215 | } |
| 216 | if err := more(tx); err != nil { |
| 217 | return err |
| 218 | } |
| 219 | return tx.log(actor, ObjectImport, row.ID, verb, 0) |
| 220 | }) |
| 221 | } |
| 222 | |
| 223 | // Forget deletes the map, every row that joins a Notion id to a Mapa |
| 224 | // page, and the token with it: a Forget that left the token let "Run |
| 225 | // again" duplicate every page, and let another workspace's token onto |
| 226 | // the map (Fable M6; Paul's ruling: Forget is one of the token-deleting |
| 227 | // acts, spec §6). The pages stay. The next Connect claims a workspace |
| 228 | // afresh. |
| 229 | func (store *Store) Forget(ctx context.Context, who string) error { |
| 230 | return store.write(ctx, func(tx *Tx) error { |
| 231 | actor, err := tx.member(who) |
| 232 | if err != nil { |
| 233 | return err |
| 234 | } |
| 235 | if err := tx.refuseActive(); err != nil { |
| 236 | return err |
| 237 | } |
| 238 | if err := tx.endResumable(runForgotten); err != nil { |
| 239 | return err |
| 240 | } |
| 241 | err = tx.db.Where("1 = 1").Delete(&NotionConnection{}).Error |
| 242 | if err != nil { |
| 243 | return err |
| 244 | } |
| 245 | err = tx.db.Where("1 = 1").Delete(&NotionPage{}).Error |
| 246 | if err != nil { |
| 247 | return err |
| 248 | } |
| 249 | // Where each image went is the map too: block ids joined to |
| 250 | // Mapa pages and images (Fable round 3, M3). |
| 251 | err = tx.db.Where("1 = 1").Delete(&NotionImage{}).Error |
| 252 | if err != nil { |
| 253 | return err |
| 254 | } |
| 255 | return tx.log(actor, ObjectImport, 0, VerbForgotten, 0) |
| 256 | }) |
| 257 | } |
| 258 | |
| 259 | // token opens the saved token, for a run. |
| 260 | func (store *Store) token(ctx context.Context) (string, error) { |
| 261 | row, found, err := connection(store.database.WithContext(ctx)) |
| 262 | if err != nil || !found { |
| 263 | return "", errors.Join(ErrNotConnected, err) |
| 264 | } |
| 265 | plain, err := store.sealer.Open(seal.PurposeNotionToken, row.SealedToken) |
| 266 | return string(plain), err |
| 267 | } |
| 268 | |
| 269 | // IdleTokenWindow is how long a connection may go without a run before |
| 270 | // retention deletes its token (spec §6). |
| 271 | const IdleTokenWindow = 90 * 24 * time.Hour |
| 272 | |