oficina / alta Public

Clone
git clone https://amadan.net/oficina/alta

Plain git — no account needed to clone.

Download

Download this file

1// Package web is Alta's pages (team-provisioning-app.md §11): plain GETs
2// and form POSTs, no live updates, estilo's chrome, scriptless except
3// estilo's busy.js. Only one person ref, ALTA_OPERATOR_SUBJECT, sees any
4// page; any other signed-in identity gets the 404 an unknown page gets.
5package web
6
7import (
8 "context"
9 "errors"
10 "log/slog"
11 "net/http"
12 "net/mail"
13 "net/url"
14 "slices"
15 "strconv"
16 "strings"
17 "sync"
18 "time"
19
20 "amadan.net/oficina/alta/homeop"
21 "amadan.net/oficina/alta/provision"
22 "amadan.net/oficina/home/connect"
23 "amadan.net/oficina/home/handoff"
24 "amadan.net/oficina/home/handoff/seal"
25 "amadan.net/rastrillo/rastrillo/assertion"
26 "amadan.net/rastrillo/rastrillo/csrf"
27 "amadan.net/rastrillo/rastrillo/migrate"
28 "amadan.net/rastrillo/rastrillo/sessions"
29 "github.com/go-chi/chi/v5"
30)
31
32// Session lifetimes (§2): idle 30 minutes, absolute 12 hours.
33const (
34 IdleLifetime = 30 * time.Minute
35 AbsoluteLifetime = 12 * time.Hour
36)
37
38// Extra is the migration sets Alta's database carries beside its own:
39// sessions and the Home hand-off.
40var Extra = []*migrate.Set{sessions.Schema, migrate.MustFromFS(handoff.Migrations, "oficina_handoff")}
41
42// Config is the app's wiring.
43type Config struct {
44 Origin string
45 OperatorSubject string
46 Home *connect.DecodedCredentials
47 Engine *provision.Engine
48 Store *provision.Store
49 // HomeDirectory and HomeCredential are the two confirm origins.
50 HomeDirectory, HomeCredential string
51 Account string
52 Logger *slog.Logger
53 Now func() time.Time
54 // Tick is how often live runs are advanced in the background; zero
55 // disables (tests drive the engine themselves).
56 Tick time.Duration
57}
58
59// App is Alta's HTTP handler.
60type App struct {
61 cfg Config
62 sess *sessions.Sessions
63 consumer *handoff.Consumer
64 mux http.Handler
65
66 mu sync.Mutex
67 running map[int64]bool
68 done chan struct{}
69 stopOnce sync.Once
70}
71
72// New builds the app. Home sign-in is required: Alta has no other.
73func New(cfg Config) (*App, error) {
74 if cfg.Home == nil || cfg.OperatorSubject == "" || cfg.Engine == nil || cfg.Store == nil || cfg.Origin == "" {
75 return nil, errors.New("web: Home sign-in, the operator subject, the engine and the origin are required")
76 }
77 if !homeop.PersonRef(cfg.OperatorSubject) {
78 return nil, errors.New("web: ALTA_OPERATOR_SUBJECT is not a person ref")
79 }
80 if cfg.Logger == nil {
81 cfg.Logger = slog.Default()
82 }
83 if cfg.Now == nil {
84 cfg.Now = time.Now
85 }
86 db := cfg.Store.DB()
87 sess, err := sessions.New(sessions.Config{DB: db, Origin: cfg.Origin, TTL: AbsoluteLifetime, SigninPath: handoff.StartPath, Logger: cfg.Logger, Now: cfg.Now})
88 if err != nil {
89 return nil, err
90 }
91 sealer, err := seal.New(cfg.Home.DEK, "oficina/alta/handoff")
92 if err != nil {
93 return nil, err
94 }
95 store, err := handoff.NewStore(db, sealer, cfg.Home.Issuer, cfg.Origin, cfg.Home.Keys)
96 if err != nil {
97 return nil, err
98 }
99 a := &App{cfg: cfg, sess: sess, running: map[int64]bool{}, done: make(chan struct{})}
100 a.consumer, err = handoff.NewConsumer(handoff.ConsumerConfig{Store: store, ConsumerID: cfg.Home.ConsumerID, Now: cfg.Now,
101 CurrentSubject: func(r *http.Request) string {
102 if s, ok := sess.From(r); ok {
103 return s.Subject
104 }
105 return ""
106 },
107 Complete: func(w http.ResponseWriter, r *http.Request, c assertion.Claims) error {
108 // Any Home identity gets a session; only the operator gets a
109 // page. Refusing the session instead would loop the sign-in.
110 return sess.SignIn(w, r, sessions.Session{Subject: c.Subject, Method: "home", AuthTime: time.Unix(c.AuthTime, 0)})
111 },
112 Fail: func(w http.ResponseWriter, r *http.Request, status int) {
113 a.plain(w, status, "Unable to sign in. Start again.")
114 }})
115 if err != nil {
116 return nil, err
117 }
118 a.mux = a.routes()
119 if cfg.Tick > 0 {
120 go a.tick(cfg.Tick)
121 }
122 return a, nil
123}
124
125// Close stops the background ticker.
126func (a *App) Close() { a.stopOnce.Do(func() { close(a.done) }) }
127
128func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request) { a.mux.ServeHTTP(w, r) }
129
130func (a *App) routes() http.Handler {
131 r := chi.NewRouter()
132 r.Handle(assetPrefix+"*", assetHandler())
133 // The assertion callback is the one route outside CSRF: Home's page
134 // posts it cross-origin with its exact Origin.
135 r.Post(handoff.CallbackPath, a.consumer.Callback)
136 r.Group(func(r chi.Router) {
137 r.Use(csrf.Protect(a.cfg.Origin))
138 r.Use(a.sess.Middleware)
139 r.Get(handoff.StartPath, a.consumer.Start)
140 r.Get(handoff.FinishPath, a.consumer.Finish)
141 r.Post("/signout", a.signout)
142 r.Group(func(r chi.Router) {
143 r.Use(a.operatorOnly)
144 r.Get("/", a.index)
145 r.Get("/initialize", a.initializeForm)
146 r.Post("/initialize", a.initialize)
147 r.Get("/teams/new", a.newTeamForm)
148 r.Post("/teams", a.createTeam)
149 r.Get("/teams/{label}", a.team)
150 r.Post("/teams/{label}/apps", a.addApps)
151 r.Post("/teams/{label}/owner", a.retypeOwner)
152 r.Post("/teams/{label}/audit", a.audit)
153 r.Get("/teams/{label}/retire", a.retireForm)
154 r.Post("/teams/{label}/retire", a.retire)
155 r.Get("/runs/{id}", a.run)
156 r.Post("/runs/{id}/advance", a.advance)
157 r.Post("/runs/{id}/plan", a.resubmit)
158 })
159 })
160 r.NotFound(func(w http.ResponseWriter, r *http.Request) { a.notFound(w, r) })
161 return r
162}
163
164// operatorOnly sends a signed-out browser to Home's sign-in and answers
165// any identity but the operator's with the unknown page's 404. It also
166// keeps the idle clock.
167func (a *App) operatorOnly(next http.Handler) http.Handler {
168 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
169 s, ok := sessions.Current(r)
170 if !ok {
171 if r.Method == http.MethodGet || r.Method == http.MethodHead {
172 http.Redirect(w, r, handoff.StartPath+"?return_to="+url.QueryEscape(r.URL.RequestURI()), http.StatusSeeOther)
173 return
174 }
175 a.notFound(w, r)
176 return
177 }
178 if c, err := r.Cookie(a.sess.CookieName()); err == nil {
179 expired, err := a.cfg.Store.Seen(r.Context(), sessions.HashToken(c.Value), IdleLifetime)
180 if err != nil {
181 a.plain(w, http.StatusServiceUnavailable, "Try again.")
182 return
183 }
184 if expired {
185 a.sess.SignOut(w, r)
186 http.Redirect(w, r, handoff.StartPath+"?return_to="+url.QueryEscape(returnPath(r)), http.StatusSeeOther)
187 return
188 }
189 }
190 if s.Subject != a.cfg.OperatorSubject {
191 a.notFound(w, r)
192 return
193 }
194 w.Header().Set("Cache-Control", "no-store")
195 next.ServeHTTP(w, r)
196 })
197}
198
199func returnPath(r *http.Request) string {
200 if r.Method == http.MethodGet {
201 return r.URL.RequestURI()
202 }
203 return "/"
204}
205
206func (a *App) signout(w http.ResponseWriter, r *http.Request) {
207 a.sess.SignOut(w, r)
208 a.render(w, r, http.StatusOK, "signedout", page{Title: "Signed out", Bare: true})
209}
210
211// ---- background advancing ----
212
213// kick advances run in the background, once at a time per run.
214func (a *App) kick(id int64) {
215 a.mu.Lock()
216 if a.running[id] {
217 a.mu.Unlock()
218 return
219 }
220 a.running[id] = true
221 a.mu.Unlock()
222 go func() {
223 defer func() {
224 a.mu.Lock()
225 delete(a.running, id)
226 a.mu.Unlock()
227 }()
228 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
229 defer cancel()
230 _ = a.cfg.Engine.Advance(ctx, id)
231 }()
232}
233
234func (a *App) tick(every time.Duration) {
235 t := time.NewTicker(every)
236 defer t.Stop()
237 for {
238 select {
239 case <-a.done:
240 return
241 case <-t.C:
242 runs, err := a.cfg.Store.LiveRuns(context.Background())
243 if err != nil {
244 continue
245 }
246 for _, r := range runs {
247 a.kick(r.ID)
248 }
249 a.cfg.Store.SweepSeen(context.Background(), AbsoluteLifetime)
250 }
251 }
252}
253
254// ---- forms ----
255
256func errorCode(err error) string {
257 var fl *provision.Fail
258 var pk *provision.Park
259 switch {
260 case errors.As(err, &fl):
261 return fl.Code
262 case errors.As(err, &pk):
263 return pk.Code
264 }
265 return "transient"
266}
267
268func (a *App) index(w http.ResponseWriter, r *http.Request) {
269 ctx := r.Context()
270 teams, err := a.cfg.Store.Teams(ctx)
271 if err != nil {
272 a.plain(w, http.StatusServiceUnavailable, "Try again.")
273 return
274 }
275 var rows []teamRow
276 for _, t := range teams {
277 rows = append(rows, a.teamRow(ctx, t))
278 }
279 _, initialized, _ := a.cfg.Store.Done(ctx, "", "", "initialize")
280 inits, _ := a.cfg.Store.Runs(ctx, "")
281 a.render(w, r, http.StatusOK, "index", page{Title: "Teams", Data: map[string]any{"Teams": rows, "Initialized": initialized, "InitRuns": inits}})
282}
283
284type teamRow struct {
285 Label, Name string
286 Apps, Live int
287 Pending int
288 Retired int
289 RunID int64
290 RunState string
291 RunWords string
292}
293
294func (a *App) teamRow(ctx context.Context, t provision.Team) teamRow {
295 row := teamRow{Label: t.Label, Name: t.Name}
296 for app, st := range t.Apps {
297 if st == "retired" {
298 row.Retired++
299 continue
300 }
301 row.Apps++
302 if _, ok, _ := a.cfg.Store.Done(ctx, t.Label, app, provision.StepAudit); ok {
303 if spec, _ := provision.AppBySlug(app); spec.Roster {
304 row.Live++
305 continue
306 }
307 }
308 row.Pending++
309 }
310 if runs, _ := a.cfg.Store.Runs(ctx, t.Label); len(runs) > 0 {
311 row.RunID, row.RunState, row.RunWords = runs[0].ID, runs[0].State, describe(runs[0].Code)
312 }
313 return row
314}
315
316func (a *App) newTeamForm(w http.ResponseWriter, r *http.Request) {
317 a.render(w, r, http.StatusOK, "team_new", page{Title: "New team", Data: map[string]any{"Apps": provision.ProvisioningApps(), "Checked": map[string]bool{}, "Form": map[string]string{},
318 "Options": optionsView(provision.RunOptions{Profile: provision.ProfileOutside})}})
319}
320
321// formOptions is a run form's profile and samples choice. A form without
322// a profile field (Continue) answers the zero value: the engine continues
323// with the team's last choice.
324func formOptions(r *http.Request) provision.RunOptions {
325 return provision.RunOptions{Profile: provision.Profile(r.PostForm.Get("profile")), Samples: r.PostForm.Get("samples") == "1"}
326}
327
328// profileWords is each profile as the run form and the plan say it.
329var profileWords = map[provision.Profile]struct{ Name, Says string }{
330 provision.ProfileOutside: {"Outside", "Someone else's team. Calls' quality reports off, dashboards blank, Memoria AI off."},
331 provision.ProfileOwn: {"Own", "One of your own teams. Calls' quality reports on, each dashboard app names the team, and Memoria AI may be turned on after the run with your TensorX key."},
332}
333
334// profileChoice is one radio on a run form.
335type profileChoice struct {
336 Value, Name, Says string
337 Checked bool
338}
339
340// optionsView is a run's options for the form and the plan.
341func optionsView(o provision.RunOptions) map[string]any {
342 var choices []profileChoice
343 for _, p := range provision.Profiles {
344 w := profileWords[p]
345 choices = append(choices, profileChoice{Value: string(p), Name: w.Name, Says: w.Says, Checked: o.Profile == p})
346 }
347 w := profileWords[o.Profile]
348 return map[string]any{"Profile": string(o.Profile), "Name": w.Name, "Says": w.Says, "Samples": o.Samples, "Choices": choices}
349}
350
351func (a *App) createTeam(w http.ResponseWriter, r *http.Request) {
352 if err := r.ParseForm(); err != nil {
353 a.plain(w, http.StatusBadRequest, "Bad form.")
354 return
355 }
356 in := provision.NewTeam{Label: strings.TrimSpace(r.PostForm.Get("label")), Name: strings.TrimSpace(r.PostForm.Get("name")), Owner: strings.TrimSpace(r.PostForm.Get("owner")), Apps: r.PostForm["app"], Forked: r.PostForm.Get("forked") == "1",
357 Options: formOptions(r)} // no profile posted: outside, the default
358 if addr, err := mail.ParseAddress(in.Owner); err == nil && addr.Name == "" {
359 in.Owner = addr.Address
360 }
361 id, err := a.cfg.Engine.CreateTeam(r.Context(), in)
362 if err != nil && strings.HasPrefix(errorCode(err), "plan-refused-") {
363 // The label is recorded (never reused) and Home refused the plan:
364 // the team page is where the owner is corrected and a new plan
365 // submitted.
366 http.Redirect(w, r, "/teams/"+in.Label+"?audit="+url.QueryEscape(errorCode(err)), http.StatusSeeOther)
367 return
368 }
369 if err != nil {
370 checked := map[string]bool{}
371 for _, s := range in.Apps {
372 checked[s] = true
373 }
374 // The owner's address is echoed back into the form it came from,
375 // never logged or stored on a refusal.
376 a.render(w, r, http.StatusUnprocessableEntity, "team_new", page{Title: "New team", Error: describe(errorCode(err)),
377 Data: map[string]any{"Apps": provision.ProvisioningApps(), "Checked": checked, "Form": map[string]string{"label": in.Label, "name": in.Name, "owner": in.Owner}, "Forked": in.Forked,
378 "Options": optionsView(in.Options)}})
379 return
380 }
381 http.Redirect(w, r, "/runs/"+strconv.FormatInt(id, 10), http.StatusSeeOther)
382}
383
384func (a *App) initializeForm(w http.ResponseWriter, r *http.Request) {
385 a.render(w, r, http.StatusOK, "initialize", page{Title: "Initialize Home's directory", Data: map[string]any{"Sentence": provision.InitializeAttestation}})
386}
387
388func (a *App) initialize(w http.ResponseWriter, r *http.Request) {
389 _ = r.ParseForm()
390 id, err := a.cfg.Engine.StartInitialize(r.Context(), r.PostForm.Get("attestation"))
391 if err != nil {
392 a.render(w, r, http.StatusUnprocessableEntity, "initialize", page{Title: "Initialize Home's directory", Error: describe(errorCode(err)), Data: map[string]any{"Sentence": provision.InitializeAttestation}})
393 return
394 }
395 http.Redirect(w, r, "/runs/"+strconv.FormatInt(id, 10), http.StatusSeeOther)
396}
397
398func (a *App) teamFor(w http.ResponseWriter, r *http.Request) (provision.Team, bool) {
399 t, err := a.cfg.Store.Team(r.Context(), chi.URLParam(r, "label"))
400 if err != nil {
401 a.notFound(w, r)
402 return t, false
403 }
404 return t, true
405}
406
407// appView is one app's row on the team and run pages.
408type appView struct {
409 Slug, Name, Host, State string
410 Steps []stepView
411 Pending bool
412 // Written is the profile (and samples) the app's environment was
413 // written with, from step 7's record; "" until step 7 is done.
414 Written string
415}
416
417type stepView struct {
418 Name, State, Words string
419}
420
421func (a *App) appViews(ctx context.Context, t provision.Team, apps []string) []appView {
422 steps, _ := a.cfg.Store.Steps(ctx, t.Label)
423 by := map[string]provision.Step{}
424 for _, s := range steps {
425 by[s.App+"/"+s.Name] = s
426 }
427 var out []appView
428 for _, slug := range provision.SortApps(apps) {
429 spec, _ := provision.AppBySlug(slug)
430 v := appView{Slug: slug, Name: spec.Name, Host: provision.PublicHost(t.Label, slug), State: t.Apps[slug], Pending: !spec.Roster}
431 if opt, ok, _ := a.cfg.Store.WrittenOptions(ctx, t.Label, slug); ok {
432 v.Written = profileWords[opt.Profile].Name
433 if opt.Samples {
434 v.Written += ", samples"
435 }
436 }
437 names := provision.AppSteps(spec)
438 if t.Apps[slug] == "retired" {
439 names = provision.RetireSteps
440 }
441 for _, n := range names {
442 s, ok := by[slug+"/"+n]
443 sv := stepView{Name: n, State: "todo"}
444 if ok {
445 sv.State, sv.Words = s.State, describe(s.Code)
446 }
447 v.Steps = append(v.Steps, sv)
448 }
449 out = append(out, v)
450 }
451 return out
452}
453
454func (a *App) team(w http.ResponseWriter, r *http.Request) {
455 t, ok := a.teamFor(w, r)
456 if !ok {
457 return
458 }
459 ctx := r.Context()
460 var apps, addable []string
461 // An own-only app (Equipo, Base) is offered only to a team whose
462 // written apps are all under profile own, and never on the adoption
463 // label (team-bundle spec §5.1 rule 3). Add-apps refuses it as well
464 // (ownOnlyFits).
465 own := t.Label != provision.AdoptionLabel
466 for s := range t.Apps {
467 if opt, written, _ := a.cfg.Store.WrittenOptions(ctx, t.Label, s); written && opt.Profile != provision.ProfileOwn {
468 own = false
469 }
470 }
471 for _, s := range provision.Slugs() {
472 if _, in := t.Apps[s]; in {
473 apps = append(apps, s)
474 } else if spec, _ := provision.AppBySlug(s); !spec.AdoptionOnly && (!spec.OwnOnly || own) {
475 addable = append(addable, s)
476 }
477 }
478 runs, _ := a.cfg.Store.Runs(ctx, t.Label)
479 audit, _ := a.cfg.Store.AuditLog(ctx, t.Label, 40)
480 _, holdsOwner, _ := a.cfg.Store.Owner(ctx, t.Label)
481 // An app whose recipe still writes the owner (a stopgap allowlist) is
482 // the only reason to ask for the address again once the team is at
483 // Home. With every app in roster mode there is none.
484 needsOwner := provision.RetypeAllowed(t.Apps)
485 notice := ""
486 if code := r.URL.Query().Get("audit"); knownCode(code) {
487 notice = describe(code)
488 if app := r.URL.Query().Get("app"); app != "" {
489 if spec, ok := provision.AppBySlug(app); ok {
490 notice += " (" + spec.Name + ")"
491 }
492 }
493 }
494 // What Continue would do: the unfinished apps, each under its own
495 // choice, or the refusal it would meet.
496 cont, finished, _ := a.cfg.Engine.ContinueApps(ctx, t.Label)
497 var contNames []string
498 for _, s := range cont {
499 spec, _ := provision.AppBySlug(s)
500 contNames = append(contNames, spec.Name)
501 }
502 contWords := ""
503 contOpt, err := a.cfg.Engine.ContinuedOptions(ctx, t.Label, cont)
504 if err != nil {
505 contWords = describe(errorCode(err))
506 contOpt, _ = a.cfg.Store.LastOptions(ctx, t.Label)
507 }
508 a.render(w, r, http.StatusOK, "team", page{Title: t.Name, Context: t.Label, Notice: notice,
509 Data: map[string]any{"Team": t, "Apps": a.appViews(ctx, t, apps), "Addable": addable, "Runs": runs, "Audit": audit, "HoldsOwner": holdsOwner, "NeedsOwner": needsOwner, "Seeded": t.TeamSQID != "",
510 "Options": optionsView(contOpt), "Continue": strings.Join(contNames, ", "), "ContinueRefused": contWords,
511 // Every app finished, under choices that disagree: nothing to
512 // continue, and no one choice to continue it under.
513 "NothingToContinue": finished && contWords != ""}})
514}
515
516func (a *App) addApps(w http.ResponseWriter, r *http.Request) {
517 t, ok := a.teamFor(w, r)
518 if !ok {
519 return
520 }
521 _ = r.ParseForm()
522 apps := r.PostForm["app"]
523 if len(apps) == 0 {
524 // "Continue": the apps with steps still to do, under the choice
525 // the form posts (defaulted to each app's own; an app already
526 // written refuses any other), under a new plan.
527 var err error
528 if apps, _, err = a.cfg.Engine.ContinueApps(r.Context(), t.Label); err != nil {
529 http.Redirect(w, r, "/teams/"+t.Label+"?audit="+url.QueryEscape(errorCode(err)), http.StatusSeeOther)
530 return
531 }
532 }
533 id, err := a.cfg.Engine.AddApps(r.Context(), t.Label, apps, formOptions(r))
534 if err != nil {
535 http.Redirect(w, r, "/teams/"+t.Label+"?audit="+url.QueryEscape(errorCode(err)), http.StatusSeeOther)
536 return
537 }
538 http.Redirect(w, r, "/runs/"+strconv.FormatInt(id, 10), http.StatusSeeOther)
539}
540
541func (a *App) retypeOwner(w http.ResponseWriter, r *http.Request) {
542 t, ok := a.teamFor(w, r)
543 if !ok {
544 return
545 }
546 _ = r.ParseForm()
547 addr := strings.TrimSpace(r.PostForm.Get("owner"))
548 // Before the seed, a retyped owner goes back through Home's credential
549 // confirm on the resumed create-team; after it, only a stopgap
550 // allowlist may take one (RetypeAllowed).
551 if t.TeamSQID != "" && !provision.RetypeAllowed(t.Apps) {
552 http.Redirect(w, r, "/teams/"+t.Label+"?audit=owner-retype-refused", http.StatusSeeOther)
553 return
554 }
555 if !homeop.OwnerAddress(addr) {
556 http.Redirect(w, r, "/teams/"+t.Label+"?audit=owner-shape", http.StatusSeeOther)
557 return
558 }
559 if err := a.cfg.Store.SetOwner(r.Context(), t.Label, addr); err != nil {
560 a.plain(w, http.StatusServiceUnavailable, "Try again.")
561 return
562 }
563 a.cfg.Store.Audit(r.Context(), 0, t.Label, "", "owner-retyped", "")
564 http.Redirect(w, r, "/teams/"+t.Label, http.StatusSeeOther)
565}
566
567func (a *App) audit(w http.ResponseWriter, r *http.Request) {
568 t, ok := a.teamFor(w, r)
569 if !ok {
570 return
571 }
572 code, failed := "audit-ok", ""
573 for _, app := range provision.Slugs() {
574 if t.Apps[app] != "active" {
575 continue
576 }
577 spec, _ := provision.AppBySlug(app)
578 if err := a.cfg.Engine.AuditEnvironment(r.Context(), t.Label, spec); err != nil {
579 code, failed = errorCode(err), app
580 break
581 }
582 }
583 a.cfg.Store.Audit(r.Context(), 0, t.Label, failed, "audit", code)
584 http.Redirect(w, r, "/teams/"+t.Label+"?audit="+url.QueryEscape(code)+"&app="+url.QueryEscape(failed), http.StatusSeeOther)
585}
586
587func (a *App) retireForm(w http.ResponseWriter, r *http.Request) {
588 t, ok := a.teamFor(w, r)
589 if !ok {
590 return
591 }
592 var active []string
593 for _, s := range provision.Slugs() {
594 if t.Apps[s] == "active" {
595 active = append(active, s)
596 }
597 }
598 a.render(w, r, http.StatusOK, "retire", page{Title: "Retire apps", Context: t.Label, Data: map[string]any{"Team": t, "Apps": a.appViews(r.Context(), t, active)}})
599}
600
601func (a *App) retire(w http.ResponseWriter, r *http.Request) {
602 t, ok := a.teamFor(w, r)
603 if !ok {
604 return
605 }
606 _ = r.ParseForm()
607 id, err := a.cfg.Engine.RetireApps(r.Context(), t.Label, r.PostForm["app"], strings.TrimSpace(r.PostForm.Get("label")))
608 if err != nil {
609 var active []string
610 for _, s := range provision.Slugs() {
611 if t.Apps[s] == "active" {
612 active = append(active, s)
613 }
614 }
615 a.render(w, r, http.StatusUnprocessableEntity, "retire", page{Title: "Retire apps", Context: t.Label, Error: describe(errorCode(err)), Data: map[string]any{"Team": t, "Apps": a.appViews(r.Context(), t, active)}})
616 return
617 }
618 http.Redirect(w, r, "/runs/"+strconv.FormatInt(id, 10), http.StatusSeeOther)
619}
620
621func (a *App) runFor(w http.ResponseWriter, r *http.Request) (provision.Run, bool) {
622 id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
623 if err != nil {
624 a.notFound(w, r)
625 return provision.Run{}, false
626 }
627 run, err := a.cfg.Store.Run(r.Context(), id)
628 if err != nil {
629 a.notFound(w, r)
630 return provision.Run{}, false
631 }
632 return run, true
633}
634
635// roleView is one role's line in the plan section.
636type roleView struct {
637 Role, Confirm, Words, State string
638 Until time.Time
639}
640
641func (a *App) run(w http.ResponseWriter, r *http.Request) {
642 run, ok := a.runFor(w, r)
643 if !ok {
644 return
645 }
646 ctx := r.Context()
647 plans, _ := a.cfg.Store.Plans(ctx, run.PlanID)
648 var roles []roleView
649 for _, role := range []string{homeop.Directory, homeop.Credential} {
650 p, ok := plans[role]
651 if !ok {
652 continue
653 }
654 v := roleView{Role: role, State: p.State}
655 switch role {
656 case homeop.Directory:
657 v.Confirm, v.Words = a.cfg.HomeDirectory+"/operator/confirm", "Check the label, name and apps"
658 case homeop.Credential:
659 v.Confirm, v.Words = a.cfg.HomeCredential+"/operator/confirm", "Retype the owner's address"
660 if run.Kind != homeop.KindCreateTeam {
661 v.Words = "Check the apps"
662 }
663 }
664 if p.Window > 0 {
665 v.Until = time.Unix(p.Window, 0)
666 }
667 roles = append(roles, v)
668 }
669 data := map[string]any{"Run": run, "Roles": roles, "Prefix": homeop.PlanPrefix(run.PlanID), "Words": describe(run.Code),
670 "PlanExpires": time.Unix(run.PlanExpires, 0), "Live": run.State == "planned" || run.State == "running" || run.State == "parked"}
671 if run.Kind == homeop.KindCreateTeam || run.Kind == homeop.KindAddApps {
672 data["Options"] = optionsView(run.Options)
673 data["HasDocs"] = slices.Contains(run.Apps, "docs")
674 if run.Options.Profile == provision.ProfileOwn && slices.Contains(run.Apps, "memoria") {
675 data["MemoriaAI"] = true
676 }
677 }
678 title := "Initialize"
679 if run.Label != "" {
680 t, err := a.cfg.Store.Team(ctx, run.Label)
681 if err == nil {
682 data["Team"] = t
683 data["Apps"] = a.appViews(ctx, t, run.Apps)
684 title = t.Name
685 }
686 }
687 a.render(w, r, http.StatusOK, "run", page{Title: title, Context: run.Label, Data: data})
688}
689
690func (a *App) advance(w http.ResponseWriter, r *http.Request) {
691 run, ok := a.runFor(w, r)
692 if !ok {
693 return
694 }
695 a.kick(run.ID)
696 http.Redirect(w, r, "/runs/"+strconv.FormatInt(run.ID, 10), http.StatusSeeOther)
697}
698
699func (a *App) resubmit(w http.ResponseWriter, r *http.Request) {
700 run, ok := a.runFor(w, r)
701 if !ok {
702 return
703 }
704 if err := a.cfg.Engine.Resubmit(r.Context(), run.ID); err != nil {
705 var fl *provision.Fail
706 if errors.As(err, &fl) && fl.Code == "use-add-apps" && run.Label != "" {
707 http.Redirect(w, r, "/teams/"+run.Label, http.StatusSeeOther)
708 return
709 }
710 }
711 http.Redirect(w, r, "/runs/"+strconv.FormatInt(run.ID, 10), http.StatusSeeOther)
712}
713