| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "crypto/rand" |
| 5 | "crypto/sha256" |
| 6 | "encoding/hex" |
| 7 | "encoding/json" |
| 8 | "errors" |
| 9 | "slices" |
| 10 | "sort" |
| 11 | "strings" |
| 12 | "time" |
| 13 | |
| 14 | "gorm.io/gorm" |
| 15 | |
| 16 | "amadan.net/oficina/equipo/internal/wire" |
| 17 | ) |
| 18 | |
| 19 | // Places (spec 2026-11-26-places-config.md, slice 1). A site place is a |
| 20 | // console and account the team confirmed; a project's binding names its |
| 21 | // app there. Only an owner's tap on a place card confirms one, choosing |
| 22 | // among candidates code derived from the creator's primary's reach: a |
| 23 | // tool names a candidate id, never a console, account or app. Confirming |
| 24 | // sends nothing to CARLOS. A publish card's tap is bound to a snapshot of |
| 25 | // the place, the binding, the mode and the destination, carried through |
| 26 | // the step, the dispatch and each final check (publish.go). |
| 27 | |
| 28 | // placeOption is one candidate on a place card with the hash its tap is |
| 29 | // bound to. |
| 30 | type placeOption struct { |
| 31 | wire.PlaceCandidate |
| 32 | Hash string `json:"hash"` |
| 33 | } |
| 34 | |
| 35 | // placeProposal is a place card's stored proposal (cardRecord.Place). |
| 36 | type placeProposal struct { |
| 37 | Kind string `json:"kind"` |
| 38 | ProjectID string `json:"project_id"` |
| 39 | TaskID string `json:"task_id,omitempty"` |
| 40 | Candidates []placeOption `json:"candidates"` |
| 41 | } |
| 42 | |
| 43 | func optionHash(c wire.PlaceCandidate) string { |
| 44 | sum := sha256.Sum256([]byte("place-option/v1\n" + c.ID + "\n" + c.Console + "\n" + c.Sqid + "\n" + c.Account)) |
| 45 | return hex.EncodeToString(sum[:]) |
| 46 | } |
| 47 | |
| 48 | // repoNamespace is the forge namespace a repository lives in |
| 49 | // (amadan.net/paulca/nearys: paulca). |
| 50 | func repoNamespace(repo string) string { |
| 51 | parts := strings.Split(repo, "/") |
| 52 | if len(parts) < 3 { |
| 53 | return "" |
| 54 | } |
| 55 | return parts[len(parts)-2] |
| 56 | } |
| 57 | |
| 58 | // siteCandidates ranks the accounts the hello's logins own, with fixed |
| 59 | // rules: the flagship account named like the repository's namespace; |
| 60 | // else, when there is exactly one, the only owned account; then the rest, |
| 61 | // flagship first, then by console and name. At most wire.MaxPlaceOptions. |
| 62 | func siteCandidates(h wire.Hello, repo string) []wire.PlaceCandidate { |
| 63 | if h.Capabilities == nil || h.Capabilities.Reach == nil { |
| 64 | return nil |
| 65 | } |
| 66 | var all []wire.PlaceCandidate |
| 67 | for _, l := range h.Capabilities.Reach.Logins { |
| 68 | for _, a := range l.Accounts { |
| 69 | all = append(all, wire.PlaceCandidate{ID: wire.CandidateID(l.Console, a.Sqid), Console: l.Console, ConsoleLabel: wire.ConsoleLabel(l.Console), Account: a.Name, Sqid: a.Sqid}) |
| 70 | } |
| 71 | } |
| 72 | ns := repoNamespace(repo) |
| 73 | rank := func(c wire.PlaceCandidate) int { |
| 74 | switch { |
| 75 | case c.Console == wire.FlagshipConsole && ns != "" && c.Account == ns: |
| 76 | return 0 |
| 77 | case len(all) == 1: |
| 78 | return 1 |
| 79 | case c.Console == wire.FlagshipConsole: |
| 80 | return 2 |
| 81 | } |
| 82 | return 3 |
| 83 | } |
| 84 | sort.SliceStable(all, func(i, j int) bool { |
| 85 | a, b := all[i], all[j] |
| 86 | if rank(a) != rank(b) { |
| 87 | return rank(a) < rank(b) |
| 88 | } |
| 89 | if a.Console != b.Console { |
| 90 | return a.Console < b.Console |
| 91 | } |
| 92 | return a.Account < b.Account |
| 93 | }) |
| 94 | if len(all) > wire.MaxPlaceOptions { |
| 95 | all = all[:wire.MaxPlaceOptions] |
| 96 | } |
| 97 | return all |
| 98 | } |
| 99 | |
| 100 | // siteBinding is the project's site binding and its place: nil, nil |
| 101 | // when it has none; the place nil while the binding is unplaced (an app |
| 102 | // kept from before places). |
| 103 | func (t *txn) siteBinding(projectID string) (*projectPlaceRecord, *placeRecord, error) { |
| 104 | var b projectPlaceRecord |
| 105 | err := t.db.Where("project_id = ? AND kind = ?", projectID, wire.PlaceSite).First(&b).Error |
| 106 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 107 | return nil, nil, nil |
| 108 | } |
| 109 | if err != nil { |
| 110 | return nil, nil, err |
| 111 | } |
| 112 | if b.PlaceID == "" { |
| 113 | return &b, nil, nil |
| 114 | } |
| 115 | var p placeRecord |
| 116 | if err := t.db.Where("id = ?", b.PlaceID).First(&p).Error; err != nil { |
| 117 | return nil, nil, err |
| 118 | } |
| 119 | return &b, &p, nil |
| 120 | } |
| 121 | |
| 122 | // placedSite is the project's confirmed site place and binding, or nils. |
| 123 | func (t *txn) placedSite(projectID string) (*projectPlaceRecord, *placeRecord, error) { |
| 124 | b, p, err := t.siteBinding(projectID) |
| 125 | if err != nil || b == nil || p == nil || p.State != wire.PlaceConfirmed || b.App == "" { |
| 126 | return nil, nil, err |
| 127 | } |
| 128 | return b, p, nil |
| 129 | } |
| 130 | |
| 131 | // Reasons a site cannot be published now (siteMode's missing), each a |
| 132 | // copy key places.missing.<reason>. |
| 133 | const ( |
| 134 | missingNoPlace = "no_place" |
| 135 | missingNoRunner = "no_runner" |
| 136 | missingRunnerOutdated = "runner_outdated" |
| 137 | missingCarlos = "carlos_outdated" |
| 138 | missingNoLogin = "no_login" |
| 139 | missingKeyless = "no_deploy" |
| 140 | missingNotOwner = "not_owner" |
| 141 | ) |
| 142 | |
| 143 | // siteReach is the person's primary's reach and carlos health, and the |
| 144 | // reason none can be used: no primary, one below protocol 31 or a carlos |
| 145 | // that is unreadable or too old. |
| 146 | func (t *txn) siteReach(person string) (*wire.Reach, string, error) { |
| 147 | primary, err := t.s.authority.PrimaryRunner(t.db, person) |
| 148 | if err != nil { |
| 149 | return nil, "", err |
| 150 | } |
| 151 | if primary == "" { |
| 152 | return nil, missingNoRunner, nil |
| 153 | } |
| 154 | rs, err := t.runners(person) |
| 155 | if err != nil { |
| 156 | return nil, "", err |
| 157 | } |
| 158 | i := slices.IndexFunc(rs, func(r runnerInfo) bool { return r.ID == primary }) |
| 159 | if i < 0 { |
| 160 | return nil, missingNoRunner, nil |
| 161 | } |
| 162 | if rs[i].Protocol < wire.ProtocolPlaces { |
| 163 | return nil, missingRunnerOutdated, nil |
| 164 | } |
| 165 | h, err := t.hello(person) |
| 166 | if err != nil { |
| 167 | return nil, "", err |
| 168 | } |
| 169 | if h.Capabilities == nil || h.Capabilities.Tools == nil || h.Capabilities.Tools.Carlos != wire.CarlosOK { |
| 170 | return nil, missingCarlos, nil |
| 171 | } |
| 172 | r := h.Capabilities.Reach |
| 173 | if r == nil { |
| 174 | r = &wire.Reach{} |
| 175 | } |
| 176 | return r, "", nil |
| 177 | } |
| 178 | |
| 179 | // reachLogin reports whether the reach holds an owner login on the |
| 180 | // console that owns the account sqid. |
| 181 | func reachLogin(r *wire.Reach, console, sqid string) bool { |
| 182 | for _, l := range r.Logins { |
| 183 | if l.Console == console { |
| 184 | for _, a := range l.Accounts { |
| 185 | if a.Sqid == sqid { |
| 186 | return true |
| 187 | } |
| 188 | } |
| 189 | } |
| 190 | } |
| 191 | return false |
| 192 | } |
| 193 | |
| 194 | // reachDeploy is the deploy key the reach holds for exactly this app at |
| 195 | // this console and account, if any (never a lost one). |
| 196 | func reachDeploy(r *wire.Reach, console, sqid, app string) (wire.ReachDeploy, bool) { |
| 197 | for _, d := range r.Deploys { |
| 198 | if d.Console == console && d.Account == sqid && d.App == app && !d.Lost { |
| 199 | return d, true |
| 200 | } |
| 201 | } |
| 202 | return wire.ReachDeploy{}, false |
| 203 | } |
| 204 | |
| 205 | // siteMode is how the person's primary may publish the bound site now: |
| 206 | // setup (the app was never created: the owner's login creates it and |
| 207 | // mints its key), mint (it was, and no key is held: the login only mints |
| 208 | // one), publish (the key is held); else "" and what is missing. |
| 209 | func (t *txn) siteMode(person string, b projectPlaceRecord, p placeRecord) (string, string, error) { |
| 210 | if err := t.isOwner(person); err != nil { |
| 211 | if errors.Is(err, ErrForbidden) { |
| 212 | return "", missingNotOwner, nil |
| 213 | } |
| 214 | return "", "", err |
| 215 | } |
| 216 | r, missing, err := t.siteReach(person) |
| 217 | if err != nil || missing != "" { |
| 218 | return "", missing, err |
| 219 | } |
| 220 | if b.AppCreatedAt == nil { |
| 221 | if reachLogin(r, p.Console, p.AccountSqid) { |
| 222 | return wire.SiteSetup, "", nil |
| 223 | } |
| 224 | return "", missingNoLogin, nil |
| 225 | } |
| 226 | if _, ok := reachDeploy(r, p.Console, p.AccountSqid, b.App); ok { |
| 227 | return wire.SitePublish, "", nil |
| 228 | } |
| 229 | if reachLogin(r, p.Console, p.AccountSqid) { |
| 230 | return wire.SiteMint, "", nil |
| 231 | } |
| 232 | return "", missingKeyless, nil |
| 233 | } |
| 234 | |
| 235 | // publishSnapshot is what a publish card's tap allows, stored on the card |
| 236 | // and copied to the step: the merged commit, the place and binding at |
| 237 | // their revisions, the destination, the mode and, for setup and mint, the |
| 238 | // key's name. Every final check compares it with the records then. |
| 239 | type publishSnapshot struct { |
| 240 | SHA string `json:"sha"` |
| 241 | Place string `json:"place"` |
| 242 | PlaceRevision int64 `json:"place_revision"` |
| 243 | Binding string `json:"binding"` |
| 244 | BindingRevision int64 `json:"binding_revision"` |
| 245 | Console string `json:"console"` |
| 246 | Sqid string `json:"sqid"` |
| 247 | Name string `json:"name"` |
| 248 | App string `json:"app"` |
| 249 | Mode string `json:"mode"` |
| 250 | DeployName string `json:"deploy_name,omitempty"` |
| 251 | Destination string `json:"destination"` |
| 252 | } |
| 253 | |
| 254 | // sameTarget reports whether two snapshots allow the same thing (the key |
| 255 | // name aside, minted afresh for every card). |
| 256 | func (a publishSnapshot) sameTarget(b publishSnapshot) bool { |
| 257 | a.DeployName, b.DeployName = "", "" |
| 258 | return a == b |
| 259 | } |
| 260 | |
| 261 | // deployName is a fresh deploy key name for app: eq-, the app without |
| 262 | // site-, a hyphen and four random characters, within CARLOS's 32. |
| 263 | func deployName(app string) string { |
| 264 | slug := strings.TrimPrefix(app, "site-") |
| 265 | if len(slug) > 24 { |
| 266 | slug = strings.TrimRight(slug[:24], "-") |
| 267 | } |
| 268 | return "eq-" + slug + "-" + strings.ToLower(rand.Text())[:4] |
| 269 | } |
| 270 | |
| 271 | // siteSnapshot is the snapshot a publish of k's merged commit would be |
| 272 | // bound to now, or the reason there is none. |
| 273 | func (t *txn) siteSnapshot(k taskRecord) (*publishSnapshot, string, error) { |
| 274 | b, p, err := t.placedSite(k.ProjectID) |
| 275 | if err != nil { |
| 276 | return nil, "", err |
| 277 | } |
| 278 | if b == nil { |
| 279 | return nil, missingNoPlace, nil |
| 280 | } |
| 281 | mode, missing, err := t.siteMode(k.Creator, *b, *p) |
| 282 | if err != nil || missing != "" { |
| 283 | return nil, missing, err |
| 284 | } |
| 285 | s := publishSnapshot{SHA: k.MergedSHA, Place: p.ID, PlaceRevision: p.Revision, Binding: b.ID, BindingRevision: b.Revision, Console: p.Console, Sqid: p.AccountSqid, Name: p.AccountName, App: b.App, Mode: mode, Destination: wire.SiteDestination(p.Console, p.AccountSqid, p.AccountName, b.App)} |
| 286 | if mode != wire.SitePublish { |
| 287 | s.DeployName = deployName(b.App) |
| 288 | } |
| 289 | return &s, "", nil |
| 290 | } |
| 291 | |
| 292 | func decodeSnapshot(raw string) *publishSnapshot { |
| 293 | var s publishSnapshot |
| 294 | if raw == "" || json.Unmarshal([]byte(raw), &s) != nil || s.Destination == "" { |
| 295 | return nil |
| 296 | } |
| 297 | return &s |
| 298 | } |
| 299 | |
| 300 | func encodeSnapshot(s publishSnapshot) string { |
| 301 | raw, _ := json.Marshal(s) |
| 302 | return string(raw) |
| 303 | } |
| 304 | |
| 305 | // stepSnapshot is the snapshot a publish step was placed with. |
| 306 | func stepSnapshot(raw string) *publishSnapshot { |
| 307 | var r struct { |
| 308 | Snapshot *publishSnapshot `json:"snapshot"` |
| 309 | } |
| 310 | if raw == "" || json.Unmarshal([]byte(raw), &r) != nil || r.Snapshot == nil || r.Snapshot.Destination == "" { |
| 311 | return nil |
| 312 | } |
| 313 | return r.Snapshot |
| 314 | } |
| 315 | |
| 316 | // raisePlace puts a place card for the project's site in person's lane, |
| 317 | // the one that asked: a job's merge raises it in the job's thread (J4), a |
| 318 | // person's own request where they asked, whichever lane the task was |
| 319 | // made in (production, 2026-11-27: publish_site asked in the conversation |
| 320 | // put the card in the task's job thread, where the person never saw it). |
| 321 | // The candidates the primary's reach offers, first (when named and |
| 322 | // offered) first, then Not now. task names the merged task the proposal |
| 323 | // is for, "" for none. ok false when there is nothing to offer. |
| 324 | func (t *txn) raisePlace(person, lane, turn string, pr projectRecord, task, first string) (cardRecord, bool, error) { |
| 325 | h, err := t.hello(person) |
| 326 | if err != nil { |
| 327 | return cardRecord{}, false, err |
| 328 | } |
| 329 | cands := siteCandidates(h, pr.Repo) |
| 330 | if i := slices.IndexFunc(cands, func(c wire.PlaceCandidate) bool { return c.ID == first }); i > 0 { |
| 331 | c := cands[i] |
| 332 | cands = append([]wire.PlaceCandidate{c}, slices.Delete(cands, i, i+1)...) |
| 333 | } |
| 334 | if len(cands) == 0 { |
| 335 | return cardRecord{}, false, nil |
| 336 | } |
| 337 | prop := placeProposal{Kind: wire.PlaceSite, ProjectID: pr.ID, TaskID: task} |
| 338 | opts := make([]string, 0, len(cands)+1) |
| 339 | for _, c := range cands { |
| 340 | prop.Candidates = append(prop.Candidates, placeOption{PlaceCandidate: c, Hash: optionHash(c)}) |
| 341 | opts = append(opts, c.ID) |
| 342 | } |
| 343 | opts = append(opts, wire.ChoiceNotNow) |
| 344 | rawOpts, _ := json.Marshal(opts) |
| 345 | rawProp, _ := json.Marshal(prop) |
| 346 | best := cands[0] |
| 347 | question := t.words("chat.card.place_question", mdLabel(projectTitle(pr)), best.ConsoleLabel, best.Account) |
| 348 | if question == "" { |
| 349 | question = projectTitle(pr) |
| 350 | } |
| 351 | now := t.now() |
| 352 | c := cardRecord{ID: newID("c_"), Person: person, Kind: wire.CardPlace, State: wire.CardOpen, TurnID: turn, ProjectID: pr.ID, TaskID: task, Name: projectTitle(pr), Question: question, Options: string(rawOpts), Place: string(rawProp), Revision: 1, CreatedAt: now, UpdatedAt: now, Lane: lane} |
| 353 | if err := t.db.Create(&c).Error; err != nil { |
| 354 | return cardRecord{}, false, err |
| 355 | } |
| 356 | if err := t.auditPlace(person, "place.proposed", pr.ID, best.Console, best.Account, c.ID); err != nil { |
| 357 | return cardRecord{}, false, err |
| 358 | } |
| 359 | return c, true, t.cardEvent(c) |
| 360 | } |
| 361 | |
| 362 | // projectTitle is a project's name for people. |
| 363 | func projectTitle(pr projectRecord) string { |
| 364 | if title := pr.shownTitle(); title != "" { |
| 365 | return title |
| 366 | } |
| 367 | return ProjectName(pr.Repo) |
| 368 | } |
| 369 | |
| 370 | // openPlaceCardFor reports whether a place card for the task is open. |
| 371 | func (t *txn) openPlaceCardFor(task string) (bool, error) { |
| 372 | var n int64 |
| 373 | err := t.db.Model(&cardRecord{}).Where("task_id = ? AND kind = ? AND state = ?", task, wire.CardPlace, wire.CardOpen).Count(&n).Error |
| 374 | return n > 0, err |
| 375 | } |
| 376 | |
| 377 | // openPlaceCards are the project's open place cards, oldest first. |
| 378 | func (t *txn) openPlaceCards(projectID string) ([]cardRecord, error) { |
| 379 | var out []cardRecord |
| 380 | err := t.db.Where("project_id = ? AND kind = ? AND state = ?", projectID, wire.CardPlace, wire.CardOpen).Order("created_at, id").Find(&out).Error |
| 381 | return out, err |
| 382 | } |
| 383 | |
| 384 | // standingCard splits open cards for a request by person in lane: the |
| 385 | // card that stands for it (theirs, in that lane, and for a person's own |
| 386 | // request (since set) raised no earlier than it), and the rest of their |
| 387 | // own, which a person's request supersedes. Another person's card is |
| 388 | // neither: it stays theirs, untouched. Any other request supersedes |
| 389 | // nothing. |
| 390 | func standingCard(cards []cardRecord, person, lane string, since *time.Time) (*cardRecord, []cardRecord) { |
| 391 | var stands *cardRecord |
| 392 | var rest []cardRecord |
| 393 | for i := range cards { |
| 394 | c := cards[i] |
| 395 | if c.Person != person { |
| 396 | continue |
| 397 | } |
| 398 | if stands == nil && c.Lane == lane && (since == nil || !c.CreatedAt.Before(*since)) { |
| 399 | stands = &c |
| 400 | continue |
| 401 | } |
| 402 | rest = append(rest, c) |
| 403 | } |
| 404 | return stands, rest |
| 405 | } |
| 406 | |
| 407 | // supersedePlaces settles open place cards a fresh one (by) replaced: |
| 408 | // they confirm nothing, say there is nothing to decide any more, and are |
| 409 | // audited. Only by's person's own open place cards for by's project are |
| 410 | // settled; any other card passed in is left as it is. |
| 411 | func (t *txn) supersedePlaces(actor string, cards []cardRecord, by cardRecord) error { |
| 412 | for i := range cards { |
| 413 | c := cards[i] |
| 414 | if c.ID == by.ID || c.Kind != wire.CardPlace || c.State != wire.CardOpen || c.Person != by.Person || c.ProjectID != by.ProjectID { |
| 415 | continue |
| 416 | } |
| 417 | c.State = wire.CardResolved |
| 418 | if err := t.saveCard(&c); err != nil { |
| 419 | return err |
| 420 | } |
| 421 | if err := t.auditPlace(actor, "place.superseded", c.ProjectID, "", "", c.ID+">"+by.ID); err != nil { |
| 422 | return err |
| 423 | } |
| 424 | } |
| 425 | return nil |
| 426 | } |
| 427 | |
| 428 | // cardAt is, for the coordinator's answer, where a card is for its |
| 429 | // person: their conversation, or the job thread it is in. |
| 430 | func cardAt(c cardRecord) string { |
| 431 | path := "/conversation" |
| 432 | if job, ok := wire.JobOf(c.Lane); ok { |
| 433 | path = "/jobs/" + job |
| 434 | } |
| 435 | return " The card is at " + path + "?card=" + c.ID + "#card-" + c.ID + ": link to it." |
| 436 | } |
| 437 | |
| 438 | // answerPlace is an owner's answer on a place card for their own |
| 439 | // conversation: a candidate the card offered, its hash as stored, still |
| 440 | // in their primary's reach now, confirms the place and binds the project |
| 441 | // (Not now leaves it). Nothing is sent to CARLOS. When the card was for a |
| 442 | // merged task, its publish card follows. |
| 443 | func (t *txn) answerPlace(person string, c cardRecord, in wire.AnswerCard) (wire.Card, wire.Card, error) { |
| 444 | if err := t.hkForbid("place"); err != nil { |
| 445 | return wire.Card{}, wire.Card{}, err |
| 446 | } |
| 447 | v, err := t.cardView(c) |
| 448 | if err != nil { |
| 449 | return wire.Card{}, wire.Card{}, err |
| 450 | } |
| 451 | var prop placeProposal |
| 452 | if json.Unmarshal([]byte(c.Place), &prop) != nil || prop.Kind != wire.PlaceSite { |
| 453 | return wire.Card{}, v, ErrCardConflict |
| 454 | } |
| 455 | if c.State != wire.CardOpen || c.Revision != in.Revision { |
| 456 | return wire.Card{}, v, ErrCardConflict |
| 457 | } |
| 458 | if c.Person != person { |
| 459 | return wire.Card{}, wire.Card{}, ErrForbidden |
| 460 | } |
| 461 | if err := t.isOwner(person); err != nil { |
| 462 | return wire.Card{}, wire.Card{}, err |
| 463 | } |
| 464 | var pr projectRecord |
| 465 | if err := t.db.Where("id = ?", prop.ProjectID).First(&pr).Error; err != nil { |
| 466 | return wire.Card{}, wire.Card{}, err |
| 467 | } |
| 468 | if in.Choice == wire.ChoiceNotNow { |
| 469 | // A merged task's preview held for this card goes with Not now. |
| 470 | var held bool |
| 471 | var k taskRecord |
| 472 | if prop.TaskID != "" { |
| 473 | if k, err = t.loadTask(prop.TaskID); err != nil { |
| 474 | return wire.Card{}, wire.Card{}, err |
| 475 | } |
| 476 | steps, err := t.steps(k.ID) |
| 477 | if err != nil { |
| 478 | return wire.Card{}, wire.Card{}, err |
| 479 | } |
| 480 | if held, err = t.previewHeld(k, steps); err != nil { |
| 481 | return wire.Card{}, wire.Card{}, err |
| 482 | } |
| 483 | } |
| 484 | c.State, c.Choice = wire.CardAnswered, in.Choice |
| 485 | if err := t.saveCard(&c); err != nil { |
| 486 | return wire.Card{}, wire.Card{}, err |
| 487 | } |
| 488 | if held { |
| 489 | if err := t.releasePreview(k); err != nil { |
| 490 | return wire.Card{}, wire.Card{}, err |
| 491 | } |
| 492 | } |
| 493 | if err := t.auditPlace(person, "place.declined", pr.ID, "", "", c.ID); err != nil { |
| 494 | return wire.Card{}, wire.Card{}, err |
| 495 | } |
| 496 | out, err := t.cardView(c) |
| 497 | return out, wire.Card{}, err |
| 498 | } |
| 499 | i := slices.IndexFunc(prop.Candidates, func(o placeOption) bool { return o.ID == in.Choice }) |
| 500 | if i < 0 { |
| 501 | return wire.Card{}, wire.Card{}, ErrInvalid |
| 502 | } |
| 503 | opt := prop.Candidates[i] |
| 504 | if opt.Hash != optionHash(opt.PlaceCandidate) || opt.ID != wire.CandidateID(opt.Console, opt.Sqid) { |
| 505 | return wire.Card{}, v, ErrCardConflict |
| 506 | } |
| 507 | // Still reachable now: the candidate is in the primary's current reach. |
| 508 | h, err := t.hello(person) |
| 509 | if err != nil { |
| 510 | return wire.Card{}, wire.Card{}, err |
| 511 | } |
| 512 | if !slices.ContainsFunc(siteCandidates(h, pr.Repo), func(c wire.PlaceCandidate) bool { return c == opt.PlaceCandidate }) { |
| 513 | return wire.Card{}, v, ErrCardConflict |
| 514 | } |
| 515 | b, place, err := t.siteBinding(pr.ID) |
| 516 | if err != nil { |
| 517 | return wire.Card{}, wire.Card{}, err |
| 518 | } |
| 519 | if place != nil { |
| 520 | // The project's site was placed meanwhile (slice 1 has no change). |
| 521 | return wire.Card{}, v, ErrCardConflict |
| 522 | } |
| 523 | p, err := t.confirmPlace(person, c, opt) |
| 524 | if err != nil { |
| 525 | return wire.Card{}, wire.Card{}, err |
| 526 | } |
| 527 | if _, err := t.bindSite(pr, b, p); err != nil { |
| 528 | return wire.Card{}, wire.Card{}, err |
| 529 | } |
| 530 | c.State, c.Choice = wire.CardAnswered, in.Choice |
| 531 | if err := t.saveCard(&c); err != nil { |
| 532 | return wire.Card{}, wire.Card{}, err |
| 533 | } |
| 534 | if prop.TaskID != "" { |
| 535 | k, err := t.loadTask(prop.TaskID) |
| 536 | if err != nil { |
| 537 | return wire.Card{}, wire.Card{}, err |
| 538 | } |
| 539 | if k.Creator == person && k.ProjectID == pr.ID { |
| 540 | if _, err := t.offerSite(&k, "", "owner:"+person, siteAsk{lane: c.Lane}); err != nil { |
| 541 | return wire.Card{}, wire.Card{}, err |
| 542 | } |
| 543 | } |
| 544 | } |
| 545 | out, err := t.cardView(c) |
| 546 | return out, wire.Card{}, err |
| 547 | } |
| 548 | |
| 549 | // confirmPlace is the confirmed place for the option: the existing one at |
| 550 | // that destination, else a new one, confirmed by person. |
| 551 | func (t *txn) confirmPlace(person string, c cardRecord, opt placeOption) (placeRecord, error) { |
| 552 | var p placeRecord |
| 553 | err := t.db.Where("kind = ? AND adapter = ? AND console = ? AND account_sqid = ?", wire.PlaceSite, wire.AdapterCarlosApp, opt.Console, opt.Sqid).First(&p).Error |
| 554 | now := t.now() |
| 555 | switch { |
| 556 | case errors.Is(err, gorm.ErrRecordNotFound): |
| 557 | p = placeRecord{ID: newID("pl_"), Kind: wire.PlaceSite, Adapter: wire.AdapterCarlosApp, Console: opt.Console, AccountSqid: opt.Sqid, AccountName: opt.Account, State: wire.PlaceConfirmed, Revision: 1, ProposedBy: "coordinator:" + c.Person, ProposedAt: &c.CreatedAt, ConfirmedBy: person, ConfirmedAt: &now, CreatedAt: now, UpdatedAt: now} |
| 558 | if err := t.db.Create(&p).Error; err != nil { |
| 559 | return p, err |
| 560 | } |
| 561 | case err != nil: |
| 562 | return p, err |
| 563 | case p.State != wire.PlaceConfirmed || p.AccountName != opt.Account: |
| 564 | p.State, p.AccountName, p.ConfirmedBy, p.ConfirmedAt, p.Revision, p.UpdatedAt = wire.PlaceConfirmed, opt.Account, person, &now, p.Revision+1, now |
| 565 | if err := t.db.Model(&placeRecord{}).Where("id = ?", p.ID).Select("state", "account_name", "confirmed_by", "confirmed_at", "revision", "updated_at").Updates(&p).Error; err != nil { |
| 566 | return p, err |
| 567 | } |
| 568 | } |
| 569 | return p, t.auditPlace(person, "place.confirmed", c.ProjectID, p.Console, p.AccountName, p.ID) |
| 570 | } |
| 571 | |
| 572 | // bindSite binds the project's site to place p: an unplaced binding (an |
| 573 | // app kept from before places) keeps its app and gains the place; none |
| 574 | // gets the app projectSite mints. Its revision moves either way; nothing |
| 575 | // says the app was created. |
| 576 | func (t *txn) bindSite(pr projectRecord, b *projectPlaceRecord, p placeRecord) (projectPlaceRecord, error) { |
| 577 | now := t.now() |
| 578 | if b != nil { |
| 579 | b.PlaceID, b.Revision, b.UpdatedAt = p.ID, b.Revision+1, now |
| 580 | err := t.db.Model(&projectPlaceRecord{}).Where("id = ? AND place_id = ''", b.ID).Select("place_id", "revision", "updated_at").Updates(b).Error |
| 581 | return *b, err |
| 582 | } |
| 583 | app, ok, err := t.projectSite(pr) |
| 584 | if err != nil { |
| 585 | return projectPlaceRecord{}, err |
| 586 | } |
| 587 | if !ok { |
| 588 | return projectPlaceRecord{}, ErrCardConflict |
| 589 | } |
| 590 | nb := projectPlaceRecord{ID: newID("pp_"), ProjectID: pr.ID, Kind: wire.PlaceSite, PlaceID: p.ID, App: app, Revision: 1, CreatedAt: now, UpdatedAt: now} |
| 591 | return nb, t.db.Create(&nb).Error |
| 592 | } |
| 593 | |
| 594 | // auditPlace writes one audit row for a place action, with no credential. |
| 595 | func (t *txn) auditPlace(actor, kind, project, console, account, what string) error { |
| 596 | if t.s.authority.Audit == nil { |
| 597 | return nil |
| 598 | } |
| 599 | return t.s.authority.Audit(t.db, actor, kind, project+"/"+console+"/"+account+":"+what) |
| 600 | } |
| 601 | |
| 602 | // placeCardView fills a place card's candidates. |
| 603 | func placeCardView(v *wire.Card, c cardRecord) { |
| 604 | var prop placeProposal |
| 605 | if json.Unmarshal([]byte(c.Place), &prop) != nil { |
| 606 | return |
| 607 | } |
| 608 | out := &wire.CardPlaceView{Kind: prop.Kind, Project: prop.ProjectID, Candidates: []wire.PlaceCandidate{}} |
| 609 | for _, o := range prop.Candidates { |
| 610 | out.Candidates = append(out.Candidates, o.PlaceCandidate) |
| 611 | } |
| 612 | v.Place = out |
| 613 | } |
| 614 | |