| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "crypto/rand" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "regexp" |
| 8 | "strconv" |
| 9 | "strings" |
| 10 | "time" |
| 11 | |
| 12 | "amadan.net/oficina/equipo/internal/wire" |
| 13 | "gorm.io/gorm" |
| 14 | ) |
| 15 | |
| 16 | // Publishing a merged website (oficina/equipo discussion 11; Paul, |
| 17 | // 2026-11-12; places, 2026-11-26): Merge stays what merge authority makes |
| 18 | // it. After Equipo merged a task whose Review found a static site config |
| 19 | // (release/preview.json), the creator gets a separate publish card for |
| 20 | // the merged commit, naming the project's confirmed site place |
| 21 | // (places.go); with none, a place card comes first. Only their Publish, |
| 22 | // while an owner, places a publish step, on their primary at protocol 31, |
| 23 | // bound to the card's snapshot: place, binding, destination and mode. |
| 24 | // The app is minted by code once per project, site-<slug>-<six random |
| 25 | // characters>, the slug from the repository's name (never model text), |
| 26 | // and no other project can share it. authorizePublish decides the step's |
| 27 | // start and each final check, per phase of its mode, the deploy bound to |
| 28 | // the export it reported built. Every request, answer, decision, build |
| 29 | // and outcome is audited. |
| 30 | |
| 31 | // siteSlug is a repository's name in lower-case letters and digits, every |
| 32 | // other run of characters one hyphen, at most siteSlugMax long ("" when |
| 33 | // nothing usable is left). |
| 34 | func siteSlug(repo string) string { |
| 35 | name := repo[strings.LastIndex(repo, "/")+1:] |
| 36 | var b strings.Builder |
| 37 | for _, r := range strings.ToLower(name) { |
| 38 | switch { |
| 39 | case r >= 'a' && r <= 'z', r >= '0' && r <= '9': |
| 40 | b.WriteRune(r) |
| 41 | case b.Len() > 0 && !strings.HasSuffix(b.String(), "-"): |
| 42 | b.WriteByte('-') |
| 43 | } |
| 44 | } |
| 45 | slug := b.String() |
| 46 | if len(slug) > siteSlugMax { |
| 47 | slug = slug[:siteSlugMax] |
| 48 | } |
| 49 | return strings.TrimRight(slug, "-") |
| 50 | } |
| 51 | |
| 52 | // siteSlugMax leaves room in Carloku's 32 characters for "site-", the |
| 53 | // hyphen and the six-character suffix. |
| 54 | const siteSlugMax = wire.MaxSiteApp - len("site-") - 1 - siteSuffixLen |
| 55 | |
| 56 | const siteSuffixLen = 6 |
| 57 | |
| 58 | // mintSiteApp is a fresh app name for repo: site-<slug>-<six random |
| 59 | // lower-case base32 characters>, or site-<six> when the name gives no slug. |
| 60 | func mintSiteApp(repo string) string { |
| 61 | suffix := strings.ToLower(rand.Text())[:siteSuffixLen] |
| 62 | if slug := siteSlug(repo); slug != "" { |
| 63 | return "site-" + slug + "-" + suffix |
| 64 | } |
| 65 | return "site-" + suffix |
| 66 | } |
| 67 | |
| 68 | // publishView is a publish step's recorded word: the app it was placed |
| 69 | // for, then its built export, then its outcome. |
| 70 | func decodePublish(raw string) *wire.PublishResult { |
| 71 | if raw == "" { |
| 72 | return nil |
| 73 | } |
| 74 | var p wire.PublishResult |
| 75 | if json.Unmarshal([]byte(raw), &p) != nil { |
| 76 | return nil |
| 77 | } |
| 78 | return &p |
| 79 | } |
| 80 | |
| 81 | // publishRecord is a publish step's stored word: the result so far and |
| 82 | // the snapshot its creator's tap allowed. |
| 83 | type publishRecord struct { |
| 84 | wire.PublishResult |
| 85 | Snapshot *publishSnapshot `json:"snapshot,omitempty"` |
| 86 | } |
| 87 | |
| 88 | // encodePublish stores p with the snapshot prev carried, if any. |
| 89 | func encodePublish(p wire.PublishResult, prev string) string { |
| 90 | raw, _ := json.Marshal(publishRecord{PublishResult: p, Snapshot: stepSnapshot(prev)}) |
| 91 | return string(raw) |
| 92 | } |
| 93 | |
| 94 | // website reports whether the task is a website meant to ship: Review |
| 95 | // approved the commit that was merged and found its static site config. |
| 96 | func website(steps []stepRecord, cand string) bool { |
| 97 | for _, s := range steps { |
| 98 | if s.Specialist == wire.SpecialistReview && s.CandidateSHA == cand && s.State == wire.StepDone && s.Verdict == wire.VerdictApprove && s.HasPreview { |
| 99 | return true |
| 100 | } |
| 101 | } |
| 102 | return false |
| 103 | } |
| 104 | |
| 105 | // projectSite is the project's app: the stored one, else one minted now |
| 106 | // and stored on the project (chat_project_site_app is unique, so no two |
| 107 | // projects ever hold one app). ok is false when none is usable. |
| 108 | func (t *txn) projectSite(pr projectRecord) (string, bool, error) { |
| 109 | if pr.SiteApp != nil { |
| 110 | return *pr.SiteApp, wire.ValidSiteApp(*pr.SiteApp), nil |
| 111 | } |
| 112 | for range 5 { |
| 113 | app := mintSiteApp(pr.Repo) |
| 114 | var taken int64 |
| 115 | if err := t.db.Model(&projectRecord{}).Where("site_app = ?", app).Count(&taken).Error; err != nil { |
| 116 | return "", false, err |
| 117 | } |
| 118 | if taken > 0 || !wire.ValidSiteApp(app) { |
| 119 | continue |
| 120 | } |
| 121 | res := t.db.Model(&projectRecord{}).Where("id = ? AND site_app IS NULL", pr.ID).Update("site_app", app) |
| 122 | if res.Error != nil { |
| 123 | return "", false, res.Error |
| 124 | } |
| 125 | if res.RowsAffected != 1 { |
| 126 | return "", false, nil |
| 127 | } |
| 128 | return app, true, nil |
| 129 | } |
| 130 | return "", false, nil |
| 131 | } |
| 132 | |
| 133 | // offerPublish asks the creator, once per merged commit, whether to |
| 134 | // publish a merged website, at its merge (m, the merge step): never |
| 135 | // silently nothing. It publishes nothing itself. |
| 136 | func (t *txn) offerPublish(k *taskRecord, m *stepRecord) error { |
| 137 | if t.hk != nil || wire.NormalKind(k.Kind) == wire.KindExplore || k.MergedSHA == "" || k.PublishAsked == k.MergedSHA { |
| 138 | return nil |
| 139 | } |
| 140 | steps, err := t.steps(k.ID) |
| 141 | if err != nil || !website(steps, m.CandidateSHA) { |
| 142 | return err |
| 143 | } |
| 144 | _, err = t.offerSite(k, "", "runner:"+m.RunnerID, siteAsk{lane: k.Lane}) |
| 145 | return err |
| 146 | } |
| 147 | |
| 148 | // mergedWebsite reports whether k is a website Equipo merged, Review |
| 149 | // having approved the merged candidate with its site config. |
| 150 | func mergedWebsite(k taskRecord, steps []stepRecord) bool { |
| 151 | if wire.NormalKind(k.Kind) == wire.KindExplore || k.MergedSHA == "" || k.MergedInto == "" || k.CancelRequested { |
| 152 | return false |
| 153 | } |
| 154 | for _, s := range steps { |
| 155 | if s.Specialist == wire.SpecialistMerge && s.State == wire.StepDone && s.MergeSHA == k.MergedSHA { |
| 156 | return website(steps, s.CandidateSHA) |
| 157 | } |
| 158 | } |
| 159 | return false |
| 160 | } |
| 161 | |
| 162 | // Outcomes of offerSite. |
| 163 | const ( |
| 164 | siteOffered = "offered" |
| 165 | siteProposed = "proposed" |
| 166 | ) |
| 167 | |
| 168 | // siteAsk is who asks offerSite and where: lane is the conversation its |
| 169 | // cards and its reasons go to. since is set for a person's own request (a |
| 170 | // coordinator tool's turn): an open place card they cannot see there, or |
| 171 | // one older than the request, is superseded by a fresh one rather than |
| 172 | // standing in their way. Any other ask supersedes nothing. |
| 173 | type siteAsk struct { |
| 174 | lane string |
| 175 | since *time.Time |
| 176 | } |
| 177 | |
| 178 | // siteOffer is what offerSite did (siteOffered, siteProposed or "" when |
| 179 | // nothing was due), the reason when nothing could be offered, and the |
| 180 | // card raised, or the open one that stands. |
| 181 | type siteOffer struct { |
| 182 | did, missing string |
| 183 | card cardRecord |
| 184 | } |
| 185 | |
| 186 | // offerSite asks the creator about publishing k's merged commit: the |
| 187 | // publish card bound to a snapshot when the project's site is placed and |
| 188 | // the primary can do it now; else a place card (an owner, with a |
| 189 | // candidate to offer; first names the coordinator's candidate); else it |
| 190 | // says, once per commit and reason, what is missing. Nothing is due when |
| 191 | // a card is open or a publish of the commit is under way. |
| 192 | func (t *txn) offerSite(k *taskRecord, first, actor string, ask siteAsk) (siteOffer, error) { |
| 193 | var pr projectRecord |
| 194 | if err := t.db.Where("id = ?", k.ProjectID).First(&pr).Error; err != nil { |
| 195 | return siteOffer{}, err |
| 196 | } |
| 197 | // A publish card from before places names no place: settled first. |
| 198 | var legacy []cardRecord |
| 199 | if err := t.db.Where("task_id = ? AND kind = ? AND state = ? AND (place IS NULL OR place = '')", k.ID, wire.CardPublish, wire.CardOpen).Find(&legacy).Error; err != nil { |
| 200 | return siteOffer{}, err |
| 201 | } |
| 202 | for i := range legacy { |
| 203 | if err := t.settleLegacyPublish(&legacy[i]); err != nil { |
| 204 | return siteOffer{}, err |
| 205 | } |
| 206 | } |
| 207 | if open, err := t.openPublish(k.ID); err != nil || open.ID != "" { |
| 208 | return siteOffer{card: open}, err |
| 209 | } |
| 210 | // A primary that cannot publish at all is said first: no place card |
| 211 | // is raised for it. |
| 212 | if _, why, err := t.siteReach(k.Creator); err != nil || why != "" { |
| 213 | if err != nil { |
| 214 | return siteOffer{}, err |
| 215 | } |
| 216 | return siteOffer{missing: why}, t.sayPublishBlocked(k, ask.lane, why) |
| 217 | } |
| 218 | snap, missing, err := t.siteSnapshot(*k) |
| 219 | if err != nil { |
| 220 | return siteOffer{}, err |
| 221 | } |
| 222 | if missing == missingNoPlace { |
| 223 | open, err := t.openPlaceCards(pr.ID) |
| 224 | if err != nil { |
| 225 | return siteOffer{}, err |
| 226 | } |
| 227 | stands, stale := standingCard(open, k.Creator, ask.lane, ask.since) |
| 228 | if stands != nil { |
| 229 | return siteOffer{card: *stands}, nil |
| 230 | } |
| 231 | if len(stale) > 0 && ask.since == nil { |
| 232 | return siteOffer{}, nil |
| 233 | } |
| 234 | if t.isOwner(k.Creator) == nil { |
| 235 | c, ok, err := t.raisePlace(k.Creator, ask.lane, "", pr, k.ID, first) |
| 236 | if err != nil { |
| 237 | return siteOffer{}, err |
| 238 | } |
| 239 | if ok { |
| 240 | return siteOffer{did: siteProposed, card: c}, t.supersedePlaces(actor, stale, c) |
| 241 | } |
| 242 | missing = missingNoLogin |
| 243 | } else { |
| 244 | missing = missingNotOwner |
| 245 | } |
| 246 | } |
| 247 | if missing != "" { |
| 248 | return siteOffer{missing: missing}, t.sayPublishBlocked(k, ask.lane, missing) |
| 249 | } |
| 250 | steps, err := t.steps(k.ID) |
| 251 | if err != nil { |
| 252 | return siteOffer{}, err |
| 253 | } |
| 254 | if publishBlocked(steps, k.MergedSHA, snap.Mode) { |
| 255 | return siteOffer{}, nil |
| 256 | } |
| 257 | k.PublishAsked = k.MergedSHA |
| 258 | if err := t.db.Model(&taskRecord{}).Where("id = ?", k.ID).Update("publish_asked", k.MergedSHA).Error; err != nil { |
| 259 | return siteOffer{}, err |
| 260 | } |
| 261 | c, err := t.raisePublish(k, *snap, ask.lane) |
| 262 | if err != nil { |
| 263 | return siteOffer{}, err |
| 264 | } |
| 265 | return siteOffer{did: siteOffered, card: c}, t.auditPublish(actor, "publish.requested", k.ID, snap.App, k.MergedSHA, snap.Mode+"@"+snap.Place) |
| 266 | } |
| 267 | |
| 268 | // settleLegacyPublish settles a publish card raised before places: it |
| 269 | // grants nothing, and the task may be asked again. |
| 270 | func (t *txn) settleLegacyPublish(c *cardRecord) error { |
| 271 | c.State = wire.CardResolved |
| 272 | if err := t.saveCard(c); err != nil { |
| 273 | return err |
| 274 | } |
| 275 | if err := t.db.Model(&taskRecord{}).Where("id = ? AND publish_asked != ''", c.TaskID).Update("publish_asked", "").Error; err != nil { |
| 276 | return err |
| 277 | } |
| 278 | return t.auditPublish("instance", "publish.legacy_settled", c.TaskID, "", "", c.ID) |
| 279 | } |
| 280 | |
| 281 | // sayPublishBlocked says in lane (where it was asked) why the task's |
| 282 | // merged website was not offered for publishing, once per merged commit, |
| 283 | // reason and lane. |
| 284 | func (t *txn) sayPublishBlocked(k *taskRecord, lane, missing string) error { |
| 285 | reason := t.words("places.missing." + missing) |
| 286 | text := t.words("chat.publish_blocked", mdLabel(k.Title), TaskLink(k.ID), reason) |
| 287 | if reason == "" || text == "" { |
| 288 | return nil |
| 289 | } |
| 290 | idem := "publish-why:" + k.ID + ":" + short(k.MergedSHA) + ":" + missing |
| 291 | var n int64 |
| 292 | if err := t.db.Model(&messageRecord{}).Where("person = ? AND idempotency_key = ? AND coalesce(lane, '') = ?", k.Creator, idem, lane).Count(&n).Error; err != nil || n > 0 { |
| 293 | return err |
| 294 | } |
| 295 | m := messageRecord{ID: newID("m_"), Person: k.Creator, IdempotencyKey: idem, Role: wire.RoleCoordinator, Text: text, Revision: 1, CreatedAt: t.now(), Lane: lane} |
| 296 | if err := t.db.Create(&m).Error; err != nil { |
| 297 | return err |
| 298 | } |
| 299 | if err := t.auditPublish("instance", "publish.not_offered", k.ID, "", k.MergedSHA, missing); err != nil { |
| 300 | return err |
| 301 | } |
| 302 | return t.messageEvent(m) |
| 303 | } |
| 304 | |
| 305 | // raisePublish puts a publish card for the task's merged commit in its |
| 306 | // creator's lane, bound to snap: it names the app and the place, and |
| 307 | // says what a setup or a mint does with the owner's login. |
| 308 | func (t *txn) raisePublish(k *taskRecord, snap publishSnapshot, lane string) (cardRecord, error) { |
| 309 | now := t.now() |
| 310 | question := t.words("chat.card.publish_place_question", mdLabel(k.Title), snap.App, wire.ConsoleLabel(snap.Console), snap.Name) |
| 311 | if extra := t.words("chat.card.publish_" + snap.Mode + "_note"); extra != "" && question != "" { |
| 312 | question += " " + extra |
| 313 | } |
| 314 | if question == "" { |
| 315 | question = k.Title |
| 316 | } |
| 317 | opts, _ := json.Marshal([]string{wire.ChoicePublish, wire.ChoiceNotNow}) |
| 318 | c := cardRecord{ID: newID("c_"), Person: k.Creator, Kind: wire.CardPublish, State: wire.CardOpen, ProjectID: k.ProjectID, TaskID: k.ID, Name: k.Title, Question: question, Options: string(opts), Place: encodeSnapshot(snap), Revision: 1, CreatedAt: now, UpdatedAt: now, Lane: lane} |
| 319 | if err := t.db.Create(&c).Error; err != nil { |
| 320 | return cardRecord{}, err |
| 321 | } |
| 322 | return c, t.cardEvent(c) |
| 323 | } |
| 324 | |
| 325 | // answerPublish is the creator's answer on a publish card, valid only |
| 326 | // while it still asks about the task's merged commit and they are an |
| 327 | // owner: Publish places the publish step bound to the card's snapshot, |
| 328 | // once the snapshot is what the records say now; one that moved settles |
| 329 | // the card and asks again. Not now leaves it. |
| 330 | func (t *txn) answerPublish(person string, c cardRecord, in wire.AnswerCard) (wire.Card, wire.Card, error) { |
| 331 | if err := t.hkForbid("publish"); err != nil { |
| 332 | return wire.Card{}, wire.Card{}, err |
| 333 | } |
| 334 | v, err := t.cardView(c) |
| 335 | if err != nil { |
| 336 | return wire.Card{}, wire.Card{}, err |
| 337 | } |
| 338 | if in.Choice != wire.ChoicePublish && in.Choice != wire.ChoiceNotNow { |
| 339 | return wire.Card{}, wire.Card{}, ErrInvalid |
| 340 | } |
| 341 | if c.State != wire.CardOpen || c.Revision != in.Revision { |
| 342 | return wire.Card{}, v, ErrCardConflict |
| 343 | } |
| 344 | k, err := t.loadTask(c.TaskID) |
| 345 | if err != nil { |
| 346 | return wire.Card{}, wire.Card{}, err |
| 347 | } |
| 348 | if k.Creator != person || c.Person != person { |
| 349 | return wire.Card{}, wire.Card{}, ErrForbidden |
| 350 | } |
| 351 | if err := t.isOwner(person); err != nil { |
| 352 | return wire.Card{}, wire.Card{}, err |
| 353 | } |
| 354 | if in.Choice == wire.ChoicePublish { |
| 355 | if err := t.requireGoLive(person, k.ID); err != nil { |
| 356 | return wire.Card{}, wire.Card{}, err |
| 357 | } |
| 358 | } |
| 359 | steps, err := t.steps(k.ID) |
| 360 | if err != nil { |
| 361 | return wire.Card{}, wire.Card{}, err |
| 362 | } |
| 363 | snap := decodeSnapshot(c.Place) |
| 364 | if snap == nil && c.State == wire.CardOpen && c.Revision == in.Revision { |
| 365 | // A card from before places names no place: it is settled, and |
| 366 | // the person is asked afresh (a place first when none). |
| 367 | if err := t.settleLegacyPublish(&c); err != nil { |
| 368 | return wire.Card{}, wire.Card{}, err |
| 369 | } |
| 370 | if _, err := t.offerSite(&k, "", "owner:"+person, siteAsk{lane: c.Lane}); err != nil { |
| 371 | return wire.Card{}, wire.Card{}, err |
| 372 | } |
| 373 | out, err := t.cardView(c) |
| 374 | return out, wire.Card{}, err |
| 375 | } |
| 376 | if snap == nil || k.Stage != wire.StageDone || k.MergedSHA == "" || k.PublishAsked != k.MergedSHA || snap.SHA != k.MergedSHA || publishBlocked(steps, k.MergedSHA, snap.Mode) { |
| 377 | return wire.Card{}, v, ErrCardConflict |
| 378 | } |
| 379 | held, err := t.previewHeld(k, steps) |
| 380 | if err != nil { |
| 381 | return wire.Card{}, wire.Card{}, err |
| 382 | } |
| 383 | if in.Choice == wire.ChoicePublish { |
| 384 | now, _, err := t.siteSnapshot(k) |
| 385 | if err != nil { |
| 386 | return wire.Card{}, wire.Card{}, err |
| 387 | } |
| 388 | if now == nil || !now.sameTarget(*snap) { |
| 389 | // The place, the binding, the runner's reach or the mode moved |
| 390 | // since the card was raised: it is settled, and asked again. |
| 391 | c.State = wire.CardResolved |
| 392 | if err := t.saveCard(&c); err != nil { |
| 393 | return wire.Card{}, wire.Card{}, err |
| 394 | } |
| 395 | if err := t.auditPublish(person, "publish.stale", k.ID, snap.App, k.MergedSHA, c.ID); err != nil { |
| 396 | return wire.Card{}, wire.Card{}, err |
| 397 | } |
| 398 | if _, err := t.offerSite(&k, "", "owner:"+person, siteAsk{lane: c.Lane}); err != nil { |
| 399 | return wire.Card{}, wire.Card{}, err |
| 400 | } |
| 401 | out, err := t.cardView(c) |
| 402 | return out, wire.Card{}, err |
| 403 | } |
| 404 | } |
| 405 | c.State, c.Choice = wire.CardAnswered, in.Choice |
| 406 | if err := t.saveCard(&c); err != nil { |
| 407 | return wire.Card{}, wire.Card{}, err |
| 408 | } |
| 409 | if held { |
| 410 | // Answered, either way: the preview kept for it goes. |
| 411 | if err := t.releasePreview(k); err != nil { |
| 412 | return wire.Card{}, wire.Card{}, err |
| 413 | } |
| 414 | } |
| 415 | if in.Choice == wire.ChoiceNotNow { |
| 416 | if err := t.auditPublish(person, "publish.declined", k.ID, snap.App, k.MergedSHA, ""); err != nil { |
| 417 | return wire.Card{}, wire.Card{}, err |
| 418 | } |
| 419 | out, err := t.cardView(c) |
| 420 | return out, wire.Card{}, err |
| 421 | } |
| 422 | if err := t.auditPublish(person, "publish.approved", k.ID, snap.App, k.MergedSHA, snap.Mode+"@"+snap.Place+":"+shortDigest(snap.Destination)); err != nil { |
| 423 | return wire.Card{}, wire.Card{}, err |
| 424 | } |
| 425 | raw, _ := json.Marshal(publishRecord{PublishResult: wire.PublishResult{App: snap.App}, Snapshot: snap}) |
| 426 | s := stepRecord{Specialist: wire.SpecialistPublish, Person: k.Creator, CandidateSHA: k.MergedSHA, DecidedBy: decidedPerson + person, Publish: string(raw)} |
| 427 | if err := t.nextStep(&k, steps, s); err != nil { |
| 428 | return wire.Card{}, wire.Card{}, err |
| 429 | } |
| 430 | out, err := t.cardView(c) |
| 431 | return out, wire.Card{}, err |
| 432 | } |
| 433 | |
| 434 | // publishBlocked reports whether a publish of sha in mode may not be |
| 435 | // asked for now: one is under way, or, for a plain publish, one went |
| 436 | // live (one that failed or was never confirmed may be asked again). A mint may |
| 437 | // follow a done publish of the commit that left no key, and a setup one |
| 438 | // whose app a mint then found absent (setup is offered only while no |
| 439 | // creation attempt stands). |
| 440 | func publishBlocked(steps []stepRecord, sha, mode string) bool { |
| 441 | for _, s := range steps { |
| 442 | if s.Specialist != wire.SpecialistPublish || s.CandidateSHA != sha { |
| 443 | continue |
| 444 | } |
| 445 | if !wire.StepTerminal(s.State) { |
| 446 | return true |
| 447 | } |
| 448 | if (s.State == wire.StepDone || s.Withdrawn) && mode == wire.SitePublish { |
| 449 | // Only a publish that went live blocks another tap: one never |
| 450 | // confirmed (a setup whose deploy failed, a recovery stopped |
| 451 | // before its deploy) may be asked again, with the held key. |
| 452 | if p := decodePublish(s.Publish); p != nil && p.Outcome == wire.PublishPublished { |
| 453 | return true |
| 454 | } |
| 455 | } |
| 456 | } |
| 457 | return false |
| 458 | } |
| 459 | |
| 460 | // authorizePublish decides a publish step's start and each final check: |
| 461 | // the current attempt, on the creator's primary at protocol 31, of a task |
| 462 | // Equipo merged at exactly this commit into its default branch and did |
| 463 | // not cancel, whose creator is still an owner and placed it from the |
| 464 | // card; the place and binding still what the tap saw (sitePhase); a |
| 465 | // final check also needs the recorded built digest, exactly it, and the |
| 466 | // destination. Every decision is audited. |
| 467 | func (t *txn) authorizePublish(l Lease, s *stepRecord, purpose, digest, destination string) (string, error) { |
| 468 | refused, err := t.publishRefusal(l, s, purpose, digest, destination) |
| 469 | if err != nil { |
| 470 | return "", err |
| 471 | } |
| 472 | outcome := "allowed" |
| 473 | if refused != "" { |
| 474 | outcome = "refused:" + refused |
| 475 | } |
| 476 | app := "" |
| 477 | if p := decodePublish(s.Publish); p != nil { |
| 478 | app = p.App |
| 479 | } |
| 480 | return refused, t.auditPublish("runner:"+l.Runner.RunnerID, "publish.authorize", s.TaskID, app, s.CandidateSHA, s.ID+"/"+strconv.FormatInt(s.Attempt, 10)+":"+purpose+":"+outcome+":"+shortDigest(digest)) |
| 481 | } |
| 482 | |
| 483 | func (t *txn) publishRefusal(l Lease, s *stepRecord, purpose, digest, destination string) (string, error) { |
| 484 | if l.Protocol < wire.ProtocolPlaces || purpose != "" && purpose != wire.LeasePurposePublish && purpose != wire.LeasePurposeMint { |
| 485 | return "withdrawn", nil |
| 486 | } |
| 487 | primary, err := t.s.authority.PrimaryRunner(t.db, s.Person) |
| 488 | if err != nil { |
| 489 | return "", err |
| 490 | } |
| 491 | k, err := t.loadTask(s.TaskID) |
| 492 | if err != nil { |
| 493 | return "", err |
| 494 | } |
| 495 | if primary != l.Runner.RunnerID || s.Person != k.Creator || k.CancelRequested || k.Stage != wire.StageDone || k.MergedSHA == "" || k.MergedSHA != s.CandidateSHA || k.MergedInto == "" || s.DecidedBy != decidedPerson+k.Creator || t.isOwner(k.Creator) != nil { |
| 496 | return "withdrawn", nil |
| 497 | } |
| 498 | // The last check of a publish start and its deploy: the hand-off's |
| 499 | // person still puts things live (abilities §6.4). |
| 500 | if live, err := t.goLiveForTask(k.ID); err != nil || !live { |
| 501 | if err == nil { |
| 502 | return wire.CodeAbilityOff, nil |
| 503 | } |
| 504 | return "", err |
| 505 | } |
| 506 | steps, err := t.steps(k.ID) |
| 507 | if err != nil { |
| 508 | return "", err |
| 509 | } |
| 510 | if !mergedWebsite(k, steps) { |
| 511 | return "withdrawn", nil |
| 512 | } |
| 513 | // The creator's own Publish stands behind it: the task's newest |
| 514 | // publish card asks about this merged commit, is answered Publish and |
| 515 | // carries the step's snapshot. |
| 516 | var c cardRecord |
| 517 | if err := t.db.Where("task_id = ? AND kind = ? AND person = ?", k.ID, wire.CardPublish, k.Creator).Order("created_at DESC, rowid DESC").Limit(1).Find(&c).Error; err != nil { |
| 518 | return "", err |
| 519 | } |
| 520 | snap, card := stepSnapshot(s.Publish), decodeSnapshot(c.Place) |
| 521 | if c.ID == "" || k.PublishAsked != k.MergedSHA || c.State != wire.CardAnswered || c.Choice != wire.ChoicePublish || snap == nil || card == nil || *snap != *card || snap.SHA != s.CandidateSHA { |
| 522 | return "withdrawn", nil |
| 523 | } |
| 524 | p := decodePublish(s.Publish) |
| 525 | if p == nil || p.App != snap.App { |
| 526 | return "withdrawn", nil |
| 527 | } |
| 528 | if purpose != "" { |
| 529 | if p.Digest == "" { |
| 530 | return wire.RefusedPublishNotBuilt, nil |
| 531 | } |
| 532 | if digest != p.Digest || destination != snap.Destination { |
| 533 | return "withdrawn", nil |
| 534 | } |
| 535 | } |
| 536 | return t.sitePhase(k, s, *snap, purpose, l.Runner.RunnerID) |
| 537 | } |
| 538 | |
| 539 | // sitePhase decides one phase of a publish step's approved mode, which |
| 540 | // never changes: the place and binding at the snapshot's revisions and |
| 541 | // destination, and what that phase needs now. |
| 542 | // |
| 543 | // - setup: its start and deploy check need no creation attempt recorded |
| 544 | // (or this step's) and the owner's login; the allowed deploy check |
| 545 | // records the attempt, with this step's id, so setup is never offered |
| 546 | // again. Its mint check needs that attempt to be this step's. |
| 547 | // - mint: its start and mint check need an attempt, no held key, the |
| 548 | // login and no other step's mint; the allowed mint check records this |
| 549 | // step as the key's. Its deploy check needs that, whatever the reach |
| 550 | // says by then (the key it minted may not be in a hello yet). |
| 551 | // - publish: every phase needs the held key. |
| 552 | func (t *txn) sitePhase(k taskRecord, s *stepRecord, snap publishSnapshot, purpose, runner string) (string, error) { |
| 553 | b, pl, err := t.placedSite(k.ProjectID) |
| 554 | if err != nil { |
| 555 | return "", err |
| 556 | } |
| 557 | if b == nil || b.ID != snap.Binding || b.Revision != snap.BindingRevision || b.App != snap.App || pl.ID != snap.Place || pl.Revision != snap.PlaceRevision || pl.Console != snap.Console || pl.AccountSqid != snap.Sqid || pl.AccountName != snap.Name || wire.SiteDestination(pl.Console, pl.AccountSqid, pl.AccountName, b.App) != snap.Destination { |
| 558 | return "withdrawn", nil |
| 559 | } |
| 560 | r, missing, err := t.siteReach(k.Creator) |
| 561 | if err != nil { |
| 562 | return "", err |
| 563 | } |
| 564 | if missing != "" { |
| 565 | return "withdrawn", nil |
| 566 | } |
| 567 | login := reachLogin(r, snap.Console, snap.Sqid) |
| 568 | _, held := reachDeploy(r, snap.Console, snap.Sqid, snap.App) |
| 569 | now := t.now() |
| 570 | switch snap.Mode { |
| 571 | case wire.SiteSetup: |
| 572 | switch purpose { |
| 573 | case "", wire.LeasePurposePublish: |
| 574 | if !login || b.AppCreatedAt != nil && b.AppCreatedStep != s.ID { |
| 575 | return "withdrawn", nil |
| 576 | } |
| 577 | if purpose == wire.LeasePurposePublish && b.AppCreatedAt == nil { |
| 578 | if err := t.db.Model(&projectPlaceRecord{}).Where("id = ? AND app_created_at IS NULL", b.ID).Updates(map[string]any{"app_created_at": now, "app_created_step": s.ID}).Error; err != nil { |
| 579 | return "", err |
| 580 | } |
| 581 | if err := t.auditPlace("runner:"+runner, "site.create_allowed", k.ProjectID, snap.Console, snap.Name, snap.App+"/"+s.ID); err != nil { |
| 582 | return "", err |
| 583 | } |
| 584 | } |
| 585 | case wire.LeasePurposeMint: |
| 586 | if busy, err := t.otherMint(*b, s.ID); err != nil || !login || b.AppCreatedStep != s.ID || busy { |
| 587 | return "withdrawn", err |
| 588 | } |
| 589 | return "", t.allowMint(k, s, snap, *b, runner) |
| 590 | } |
| 591 | case wire.SiteMint: |
| 592 | switch purpose { |
| 593 | case "", wire.LeasePurposeMint: |
| 594 | busy, err := t.otherMint(*b, s.ID) |
| 595 | if err != nil || !login || held || b.AppCreatedAt == nil || busy { |
| 596 | return "withdrawn", err |
| 597 | } |
| 598 | if purpose == wire.LeasePurposeMint { |
| 599 | return "", t.allowMint(k, s, snap, *b, runner) |
| 600 | } |
| 601 | case wire.LeasePurposePublish: |
| 602 | if b.DeployStep != s.ID { |
| 603 | return "withdrawn", nil |
| 604 | } |
| 605 | } |
| 606 | case wire.SitePublish: |
| 607 | if purpose == wire.LeasePurposeMint || !held || b.AppCreatedAt == nil { |
| 608 | return "withdrawn", nil |
| 609 | } |
| 610 | default: |
| 611 | return "withdrawn", nil |
| 612 | } |
| 613 | return "", nil |
| 614 | } |
| 615 | |
| 616 | // otherMint reports whether another publish step's mint is still under |
| 617 | // way for the binding: one whose attempt ended (its key lost, refused or |
| 618 | // stored) never blocks a new tap's recovery. |
| 619 | func (t *txn) otherMint(b projectPlaceRecord, step string) (bool, error) { |
| 620 | if b.DeployStep == "" || b.DeployStep == step { |
| 621 | return false, nil |
| 622 | } |
| 623 | var other stepRecord |
| 624 | if err := t.db.Where("id = ?", b.DeployStep).Limit(1).Find(&other).Error; err != nil { |
| 625 | return false, err |
| 626 | } |
| 627 | return other.ID != "" && !wire.StepTerminal(other.State), nil |
| 628 | } |
| 629 | |
| 630 | // allowMint records that this step may mint the binding's deploy key, by |
| 631 | // the snapshot's name, on this runner, for the creator: once per step. |
| 632 | func (t *txn) allowMint(k taskRecord, s *stepRecord, snap publishSnapshot, b projectPlaceRecord, runner string) error { |
| 633 | if b.DeployStep == s.ID { |
| 634 | return nil |
| 635 | } |
| 636 | now := t.now() |
| 637 | if err := t.db.Model(&projectPlaceRecord{}).Where("id = ?", b.ID).Updates(map[string]any{"deploy_name": snap.DeployName, "deploy_runner": runner, "deploy_minted_by": k.Creator, "deploy_minted_at": now, "deploy_step": s.ID}).Error; err != nil { |
| 638 | return err |
| 639 | } |
| 640 | return t.auditPlace("runner:"+runner, "site.deploy_mint_allowed", k.ProjectID, snap.Console, snap.Name, snap.App+"/"+snap.DeployName+"/"+s.ID) |
| 641 | } |
| 642 | |
| 643 | // publishBuilt records a running publish report's export, once per |
| 644 | // attempt, from the primary at protocol 16. |
| 645 | func publishBuilt(l Lease, role string, s *stepRecord, v *wire.StepReport) bool { |
| 646 | b, p := v.Publish, decodePublish(s.Publish) |
| 647 | if s.Specialist != wire.SpecialistPublish || b == nil || p == nil || b.Phase != wire.PublishBuilt || p.Digest != "" || role != wire.RolePrimary || l.Protocol < wire.ProtocolPlaces { |
| 648 | return false |
| 649 | } |
| 650 | if !previewDigest.MatchString(b.Digest) || b.Files < 1 || b.Files > 2000 || b.Bytes < 0 || b.Bytes > 50<<20 { |
| 651 | return false |
| 652 | } |
| 653 | s.Publish = encodePublish(wire.PublishResult{Phase: wire.PublishBuilt, App: p.App, Digest: b.Digest, Files: b.Files, Bytes: b.Bytes}, s.Publish) |
| 654 | return true |
| 655 | } |
| 656 | |
| 657 | // siteURL is a published site's address: https on the app's own host. |
| 658 | var siteURL = regexp.MustCompile(`^https://site-[a-z0-9-]+\.[a-z0-9-]+(\.[a-z0-9-]+)+/$`) |
| 659 | |
| 660 | // acceptPublishDone judges a publish step's final report: from the |
| 661 | // primary at protocol 16, for the step's app, the export recorded as |
| 662 | // built, published with a URL on the app's own host, or unconfirmed. ok |
| 663 | // false ignores it. |
| 664 | func acceptPublishDone(l Lease, role string, s *stepRecord, v *wire.StepReport) (string, bool) { |
| 665 | d, built := v.Publish, decodePublish(s.Publish) |
| 666 | if d == nil || built == nil || built.Digest == "" || d.Phase != wire.PublishDone || role != wire.RolePrimary || l.Protocol < wire.ProtocolPlaces || !v.Termination || v.CandidateSHA != s.CandidateSHA { |
| 667 | return "", false |
| 668 | } |
| 669 | // An unconfirmed outcome may come without the digest (a restart that |
| 670 | // lost the export's marker): it is still this attempt's outcome. |
| 671 | if d.App != built.App || d.Digest != built.Digest && (d.Outcome != wire.PublishUnconfirmed || d.Digest != "") { |
| 672 | return "", false |
| 673 | } |
| 674 | out := wire.PublishResult{Phase: wire.PublishDone, App: built.App, Digest: built.Digest, Files: built.Files, Bytes: built.Bytes, Outcome: d.Outcome, Version: clipVersion(d.Version), DeployHeld: d.DeployHeld} |
| 675 | ownURL := d.URL != "" && len(d.URL) <= 200 && siteURL.MatchString(d.URL) && strings.HasPrefix(d.URL, "https://"+built.App+".") |
| 676 | switch d.Outcome { |
| 677 | case wire.PublishPublished: |
| 678 | if !ownURL { |
| 679 | return "", false |
| 680 | } |
| 681 | out.URL = d.URL |
| 682 | case wire.PublishUnconfirmed: |
| 683 | if ownURL { |
| 684 | out.URL = d.URL |
| 685 | } |
| 686 | default: |
| 687 | return "", false |
| 688 | } |
| 689 | return encodePublish(out, s.Publish), true |
| 690 | } |
| 691 | |
| 692 | // publishEnded says how a publish step ended in its creator's |
| 693 | // conversation: published at its URL, sent and not confirmed, or not |
| 694 | // published, which asks again. |
| 695 | func (t *txn) publishEnded(k *taskRecord, s *stepRecord) error { |
| 696 | p := decodePublish(s.Publish) |
| 697 | app := "" |
| 698 | if p != nil { |
| 699 | app = p.App |
| 700 | } |
| 701 | key, kind := "chat.publish_failed", "publish.failed" |
| 702 | var args []any |
| 703 | switch { |
| 704 | case s.State == wire.StepDone && p != nil && p.Outcome == wire.PublishPublished: |
| 705 | key, kind, args = "chat.published", "publish.published", []any{mdLabel(k.Title), TaskLink(k.ID), p.URL} |
| 706 | case s.State == wire.StepDone: |
| 707 | key, kind = "chat.publish_unconfirmed", "publish.unconfirmed" |
| 708 | case s.Reason == "publish_app_taken": |
| 709 | // The account already holds the name: nothing was deployed, and |
| 710 | // asking again would only meet it again. |
| 711 | key, args = "chat.publish_taken", []any{mdLabel(k.Title), TaskLink(k.ID), app} |
| 712 | case s.Reason == reasonAppUnproven: |
| 713 | // The app is there but this runner has no proof it made it: |
| 714 | // nothing is minted or deployed, and it is not asked again. |
| 715 | key, args = "chat.publish_unproven", []any{mdLabel(k.Title), TaskLink(k.ID), app} |
| 716 | } |
| 717 | if args == nil { |
| 718 | args = []any{mdLabel(k.Title), TaskLink(k.ID)} |
| 719 | } |
| 720 | if err := t.auditPublish("runner:"+s.RunnerID, kind, k.ID, app, s.CandidateSHA, s.ID+"/"+strconv.FormatInt(s.Attempt, 10)+":"+s.State+":"+s.Reason); err != nil { |
| 721 | return err |
| 722 | } |
| 723 | // Said in the lane of the publish card its person answered: a job's |
| 724 | // thread for a job's card, their conversation for one asked for there. |
| 725 | lane, err := t.siteLane(*k) |
| 726 | if err != nil { |
| 727 | return err |
| 728 | } |
| 729 | if text := t.words(key, args...); text != "" { |
| 730 | idem := "publish:" + s.ID + ":" + strconv.FormatInt(s.Attempt, 10) |
| 731 | var n int64 |
| 732 | if err := t.db.Model(&messageRecord{}).Where("person = ? AND idempotency_key = ?", k.Creator, idem).Count(&n).Error; err != nil { |
| 733 | return err |
| 734 | } |
| 735 | if n == 0 { |
| 736 | m := messageRecord{ID: newID("m_"), Person: k.Creator, IdempotencyKey: idem, Role: wire.RoleCoordinator, Text: text, Revision: 1, CreatedAt: t.now(), Lane: lane} |
| 737 | if err := t.db.Create(&m).Error; err != nil { |
| 738 | return err |
| 739 | } |
| 740 | if err := t.messageEvent(m); err != nil { |
| 741 | return err |
| 742 | } |
| 743 | } |
| 744 | } |
| 745 | if err := t.touchPublishCards(*k); err != nil { |
| 746 | return err |
| 747 | } |
| 748 | snap := stepSnapshot(s.Publish) |
| 749 | if snap != nil && snap.Mode == wire.SiteMint && s.Reason == reasonAppMissing { |
| 750 | // The mint found no app at all: the attempt created nothing, so |
| 751 | // the next card is a setup again (a new tap). |
| 752 | if err := t.db.Model(&projectPlaceRecord{}).Where("id = ?", snap.Binding).Updates(map[string]any{"app_created_at": nil, "app_created_step": "", "deploy_name": "", "deploy_runner": "", "deploy_minted_by": "", "deploy_minted_at": nil, "deploy_step": ""}).Error; err != nil { |
| 753 | return err |
| 754 | } |
| 755 | } |
| 756 | switch { |
| 757 | case s.State != wire.StepDone && app != "" && s.Reason != "publish_app_taken" && s.Reason != reasonAppUnproven: |
| 758 | // Nothing was published: the creator may ask for it again. |
| 759 | _, err := t.offerSite(k, "", "runner:"+s.RunnerID, siteAsk{lane: lane}) |
| 760 | return err |
| 761 | case s.State == wire.StepDone && snap != nil && snap.Mode != wire.SitePublish && (p == nil || !p.DeployHeld): |
| 762 | // Published, but no deploy key is held for it: the creator is |
| 763 | // asked to mint one (the recovery route; a new tap). |
| 764 | _, err := t.offerSite(k, "", "runner:"+s.RunnerID, siteAsk{lane: lane}) |
| 765 | return err |
| 766 | } |
| 767 | return nil |
| 768 | } |
| 769 | |
| 770 | // Reasons a mint refused before minting: the app is definitely absent |
| 771 | // (the setup attempt created nothing), or present without this runner's |
| 772 | // proof that it made it (never adopted). |
| 773 | const ( |
| 774 | reasonAppMissing = "publish_app_missing" |
| 775 | reasonAppUnproven = "publish_app_unproven" |
| 776 | ) |
| 777 | |
| 778 | // settlePublish ends a publish attempt that started but cannot run on and |
| 779 | // gave no outcome: once its export was recorded as built it may have |
| 780 | // deployed, so it is done and could not be confirmed; before that nothing |
| 781 | // was sent and it is cancelled. Either way no replacement attempt |
| 782 | // follows. It saves the step and says how it ended. |
| 783 | func (t *txn) settlePublish(k *taskRecord, s *stepRecord) error { |
| 784 | now := t.now() |
| 785 | s.Terminated, s.FinishedAt, s.Withdrawn = true, &now, false |
| 786 | if p := decodePublish(s.Publish); p != nil && p.Digest != "" { |
| 787 | s.State, s.Reason, s.Publish = wire.StepDone, "withdrawn", encodePublish(wire.PublishResult{Phase: wire.PublishDone, App: p.App, Digest: p.Digest, Files: p.Files, Bytes: p.Bytes, Outcome: wire.PublishUnconfirmed}, s.Publish) |
| 788 | } else { |
| 789 | s.State, s.Reason = wire.StepCancelled, "withdrawn" |
| 790 | } |
| 791 | if err := t.saveStep(s, k); err != nil { |
| 792 | return err |
| 793 | } |
| 794 | return t.publishEnded(k, s) |
| 795 | } |
| 796 | |
| 797 | // fencePublishes settles every queued or running publish step placed on |
| 798 | // a runner that connects below wire.ProtocolPlaces (a publish is bound |
| 799 | // to its place since 31): its dispatch is |
| 800 | // retired, one it may hold is cancelled, and the step ends |
| 801 | // runner_outdated. Nothing is published by it. |
| 802 | func (t *txn) fencePublishes(l Lease) error { |
| 803 | if l.Protocol >= wire.ProtocolPlaces { |
| 804 | return nil |
| 805 | } |
| 806 | var held []stepRecord |
| 807 | if err := t.db.Where("runner_id = ? AND specialist = ? AND state IN ?", l.Runner.RunnerID, wire.SpecialistPublish, []string{wire.StepQueued, wire.StepRunning}).Find(&held).Error; err != nil { |
| 808 | return err |
| 809 | } |
| 810 | for i := range held { |
| 811 | s := &held[i] |
| 812 | k, err := t.loadTask(s.TaskID) |
| 813 | if err != nil { |
| 814 | return err |
| 815 | } |
| 816 | now := t.now() |
| 817 | res := t.db.Model(&commandRecord{}).Where("runner_id = ? AND kind = ? AND acked_at IS NULL AND body LIKE ?", s.RunnerID, wire.FrameDispatch, `%"step_id":"`+s.ID+`"%`).Update("acked_at", now) |
| 818 | if res.Error != nil { |
| 819 | return res.Error |
| 820 | } |
| 821 | if res.RowsAffected == 0 && s.State == wire.StepRunning { |
| 822 | if err := t.commandTo(s.RunnerID, s.Person, wire.FrameCancelStep, wire.CancelStepCommand{Person: s.Person, TaskID: k.ID, StepID: s.ID, Attempt: s.Attempt}); err != nil { |
| 823 | return err |
| 824 | } |
| 825 | } |
| 826 | s.State, s.Reason, s.Terminated, s.FinishedAt = wire.StepCancelled, wire.ReasonRunnerOutdated, true, &now |
| 827 | if err := t.saveStep(s, &k); err != nil { |
| 828 | return err |
| 829 | } |
| 830 | if err := t.publishEnded(&k, s); err != nil { |
| 831 | return err |
| 832 | } |
| 833 | } |
| 834 | return nil |
| 835 | } |
| 836 | |
| 837 | // touchPublishCards gives a task's publish cards a new revision, so their |
| 838 | // site line follows the publish. |
| 839 | func (t *txn) touchPublishCards(k taskRecord) error { |
| 840 | var cards []cardRecord |
| 841 | if err := t.db.Where("task_id = ? AND kind = ?", k.ID, wire.CardPublish).Find(&cards).Error; err != nil { |
| 842 | return err |
| 843 | } |
| 844 | for i := range cards { |
| 845 | if err := t.saveCard(&cards[i]); err != nil { |
| 846 | return err |
| 847 | } |
| 848 | } |
| 849 | return nil |
| 850 | } |
| 851 | |
| 852 | // auditPublish writes one audit row for a publish action, with no |
| 853 | // credential: the task, the app and the merged commit, then what happened. |
| 854 | func (t *txn) auditPublish(actor, kind, task, app, sha, what string) error { |
| 855 | if t.s.authority.Audit == nil { |
| 856 | return nil |
| 857 | } |
| 858 | return t.s.authority.Audit(t.db, actor, kind, task+"/"+app+"@"+short(sha)+":"+what) |
| 859 | } |
| 860 | |
| 861 | // siteView is the task's website publishing, nil when it was never asked. |
| 862 | func (t *txn) siteView(k taskRecord, steps []stepRecord) (*wire.TaskSite, error) { |
| 863 | for i := len(steps) - 1; i >= 0; i-- { |
| 864 | s := steps[i] |
| 865 | if s.Specialist != wire.SpecialistPublish { |
| 866 | continue |
| 867 | } |
| 868 | p := decodePublish(s.Publish) |
| 869 | if p == nil { |
| 870 | continue |
| 871 | } |
| 872 | v := &wire.TaskSite{App: p.App, SHA: s.CandidateSHA, State: wire.SitePublishing} |
| 873 | switch { |
| 874 | case s.State == wire.StepDone && p.Outcome == wire.PublishPublished: |
| 875 | v.State, v.URL, v.At = wire.SitePublished, p.URL, s.FinishedAt |
| 876 | case s.State == wire.StepDone: |
| 877 | v.State, v.URL, v.At = wire.SiteUnconfirmed, p.URL, s.FinishedAt |
| 878 | case wire.StepTerminal(s.State): |
| 879 | v.State, v.At = wire.SiteFailed, s.FinishedAt |
| 880 | } |
| 881 | if v.State != wire.SiteFailed { |
| 882 | return v, nil |
| 883 | } |
| 884 | // A failed publish that was asked again reads as asked. |
| 885 | if open, err := t.openPublishCard(k.ID); err != nil || !open { |
| 886 | return v, err |
| 887 | } |
| 888 | break |
| 889 | } |
| 890 | if k.PublishAsked == "" { |
| 891 | return nil, nil |
| 892 | } |
| 893 | var c cardRecord |
| 894 | err := t.db.Where("task_id = ? AND kind = ?", k.ID, wire.CardPublish).Order("created_at DESC, rowid DESC").First(&c).Error |
| 895 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 896 | return nil, nil |
| 897 | } |
| 898 | if err != nil { |
| 899 | return nil, err |
| 900 | } |
| 901 | v := &wire.TaskSite{SHA: k.PublishAsked, State: wire.SiteAsked} |
| 902 | if snap := decodeSnapshot(c.Place); snap != nil { |
| 903 | v.App = snap.App |
| 904 | } |
| 905 | if c.State == wire.CardAnswered && c.Choice == wire.ChoiceNotNow { |
| 906 | v.State = wire.SiteDeclined |
| 907 | } |
| 908 | return v, nil |
| 909 | } |
| 910 | |
| 911 | // previewHeld reports whether the task's devbox preview stays up after |
| 912 | // the task ended (forgetTask's KeepPreview): its merged website's Publish |
| 913 | // is asked, on an open publish card or, before it, an open place card for |
| 914 | // the task, and no publish step was placed for the merged commit yet. A publish asked again after a failed one holds |
| 915 | // nothing: its preview went with the first answer. Only a devbox preview |
| 916 | // on a runner at wire.ProtocolAssistant or later is held: an older one |
| 917 | // never hears KeepPreview and takes its link down with the task. |
| 918 | func (t *txn) previewHeld(k taskRecord, steps []stepRecord) (bool, error) { |
| 919 | // A place card for the task holds it too: the publish card follows it. |
| 920 | placing, err := t.openPlaceCardFor(k.ID) |
| 921 | if err != nil { |
| 922 | return false, err |
| 923 | } |
| 924 | if k.MergedSHA == "" || k.PublishAsked != k.MergedSHA && !placing { |
| 925 | return false, nil |
| 926 | } |
| 927 | runner := "" |
| 928 | for _, s := range steps { |
| 929 | if s.Specialist == wire.SpecialistPublish && s.CandidateSHA == k.MergedSHA { |
| 930 | return false, nil |
| 931 | } |
| 932 | if r := decodePreview(s.Preview); s.Specialist == wire.SpecialistPreview && s.State == wire.StepDone && r != nil && r.Outcome == wire.PreviewDeployed && strings.HasPrefix(r.App, "eq-") { |
| 933 | runner = s.RunnerID |
| 934 | } |
| 935 | } |
| 936 | var protocol []int |
| 937 | if err := t.db.Model(&runnerSessionRecord{}).Where("runner_id = ?", runner).Pluck("protocol", &protocol).Error; err != nil || len(protocol) == 0 || protocol[0] < wire.ProtocolAssistant { |
| 938 | return false, err |
| 939 | } |
| 940 | if placing { |
| 941 | return true, nil |
| 942 | } |
| 943 | return t.openPublishCard(k.ID) |
| 944 | } |
| 945 | |
| 946 | // releasePreview takes down the preview previewHeld kept, once its |
| 947 | // Publish is answered: the task's forget_task again, now without |
| 948 | // KeepPreview and its sessions kept as long as at its end; the go-ahead |
| 949 | // cards that showed the preview get a new revision without it. |
| 950 | func (t *txn) releasePreview(k taskRecord) error { |
| 951 | keep := t.now().Add(wire.KeepMergedSessions) |
| 952 | if k.DoneAt != nil { |
| 953 | keep = k.DoneAt.Add(wire.KeepMergedSessions) |
| 954 | } |
| 955 | if err := t.forgetTask(k, &keep); err != nil { |
| 956 | return err |
| 957 | } |
| 958 | return t.touchOutcomes(k) |
| 959 | } |
| 960 | |
| 961 | func (t *txn) openPublishCard(task string) (bool, error) { |
| 962 | c, err := t.openPublish(task) |
| 963 | return c.ID != "", err |
| 964 | } |
| 965 | |
| 966 | // openPublish is the task's open publish card, if any. |
| 967 | func (t *txn) openPublish(task string) (cardRecord, error) { |
| 968 | var c cardRecord |
| 969 | err := t.db.Where("task_id = ? AND kind = ? AND state = ?", task, wire.CardPublish, wire.CardOpen).Order("created_at, id").Limit(1).Find(&c).Error |
| 970 | return c, err |
| 971 | } |
| 972 | |
| 973 | // siteLane is where a task's site is talked about: the lane of its newest |
| 974 | // publish card (where its person last decided), else the task's own. |
| 975 | func (t *txn) siteLane(k taskRecord) (string, error) { |
| 976 | var c cardRecord |
| 977 | if err := t.db.Where("task_id = ? AND kind = ?", k.ID, wire.CardPublish).Order("created_at DESC, id DESC").Limit(1).Find(&c).Error; err != nil || c.ID == "" { |
| 978 | return k.Lane, err |
| 979 | } |
| 980 | return c.Lane, nil |
| 981 | } |
| 982 | |
| 983 | // previewLink is the newest candidate's preview while it is up: an |
| 984 | // unexpired temporary site, or a devbox link until the task ends, or |
| 985 | // after while held (previewHeld). |
| 986 | func previewLink(k taskRecord, steps []stepRecord, cand string, now time.Time, held bool) string { |
| 987 | if cand == "" { |
| 988 | return "" |
| 989 | } |
| 990 | for i := len(steps) - 1; i >= 0; i-- { |
| 991 | s := steps[i] |
| 992 | // Of the candidate, or of the merged commit once done (a preview |
| 993 | // run again after the merge). |
| 994 | if s.Specialist != wire.SpecialistPreview || !previewOfTask(k, cand, s.CandidateSHA) || s.State != wire.StepDone { |
| 995 | continue |
| 996 | } |
| 997 | r := decodePreview(s.Preview) |
| 998 | if r == nil || r.Outcome != wire.PreviewDeployed || r.URL == "" { |
| 999 | continue |
| 1000 | } |
| 1001 | if !previewUp(k, s, now, held) { |
| 1002 | return "" |
| 1003 | } |
| 1004 | return r.URL |
| 1005 | } |
| 1006 | return "" |
| 1007 | } |
| 1008 | |
| 1009 | // publishCardView fills a publish card's site from its task. |
| 1010 | func (t *txn) publishCardView(v *wire.Card, c cardRecord) error { |
| 1011 | k, err := t.loadTask(c.TaskID) |
| 1012 | if err != nil { |
| 1013 | return err |
| 1014 | } |
| 1015 | steps, err := t.steps(k.ID) |
| 1016 | if err != nil { |
| 1017 | return err |
| 1018 | } |
| 1019 | site, err := t.siteView(k, steps) |
| 1020 | if err != nil || site == nil { |
| 1021 | return err |
| 1022 | } |
| 1023 | v.Site = &wire.CardSite{App: site.App, SHA: site.SHA, State: site.State, URL: site.URL} |
| 1024 | return nil |
| 1025 | } |
| 1026 | |
| 1027 | // mergeCardView adds a merge card's candidate preview, once it is up. |
| 1028 | func (t *txn) mergeCardView(v *wire.Card, c cardRecord) (err error) { |
| 1029 | v.PreviewURL, err = t.taskPreview(c.TaskID) |
| 1030 | return err |
| 1031 | } |
| 1032 | |
| 1033 | // taskPreview is the preview of the candidate the task's merge asks or |
| 1034 | // asked about while it is up (previewLink), held for its Publish too. |
| 1035 | func (t *txn) taskPreview(task string) (string, error) { |
| 1036 | k, err := t.loadTask(task) |
| 1037 | if err != nil { |
| 1038 | return "", err |
| 1039 | } |
| 1040 | steps, err := t.steps(k.ID) |
| 1041 | if err != nil { |
| 1042 | return "", err |
| 1043 | } |
| 1044 | cand := k.MergeAsked |
| 1045 | if cand == "" { |
| 1046 | cand = progressFor(k, steps).candidate |
| 1047 | } |
| 1048 | held, err := t.previewHeld(k, steps) |
| 1049 | return previewLink(k, steps, cand, t.now(), held), err |
| 1050 | } |
| 1051 | |