package handlers import ( "errors" "net/http" "time" "github.com/gin-gonic/gin" "adam-french.co.uk/usaco-site/internal/jobs" ) // saveTimeout bounds a job's commit: a sync, the edit and a push. const saveTimeout = 2 * time.Minute // initJobs registers the job kinds, with the save funcs that commit their // drafts (explain.go, review.go, concept.go). Routes calls it, and so does // ResumeJobs, whichever runs first. func (s *Server) initJobs() { s.jobsOnce.Do(func() { if s.Jobs == nil { s.Jobs = jobs.New("") } s.explainJobs = s.Jobs.Kind("explain", jobs.Options{Save: s.saveExplain}) s.reviewJobs = s.Jobs.Kind("review", jobs.Options{Save: s.saveReview, Discard: s.discardReview}) s.evalJobs = s.Jobs.Kind("evaluate", jobs.Options{}) s.newConceptJobs = s.Jobs.Kind("concept", jobs.Options{Save: s.saveConcept}) s.conceptJobs = s.Jobs.Kind("rewrite", jobs.Options{Save: s.saveConcept}) }) } // ResumeJobs saves the drafts a restart interrupted. main calls it once the // first sync has made the clone ready. func (s *Server) ResumeJobs() { s.initJobs() s.Jobs.Resume() } // startJob starts work as key's job of kind k, or answers why it cannot: // busy (409) when one is running, 503 while the server shuts down. func startJob(ctx *gin.Context, k *jobs.Kind, key, busy string, work jobs.Work) bool { err := k.Start(key, work) switch { case err == nil: return true case errors.Is(err, jobs.ErrDraining): ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "the server is restarting; try again in a minute"}) default: ctx.JSON(http.StatusConflict, gin.H{"error": busy}) } return false } // claudeReady answers 503 without CLAUDE_API_KEY, and 429 once this month's // Claude budget is spent; it is checked before any job that calls Claude. func (s *Server) claudeReady(ctx *gin.Context) bool { if s.Claude == nil { ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "Claude is not configured on this server (CLAUDE_API_KEY)"}) return false } if err := s.Usage.Allow(time.Now()); err != nil { ctx.JSON(http.StatusTooManyRequests, gin.H{"error": err.Error()}) return false } return true } // retrySave commits an unsaved job's draft again; the page then polls the // job's usual status route. func (s *Server) retrySave(ctx *gin.Context) { k := s.Jobs.Lookup(ctx.Param("kind")) if k == nil { ctx.JSON(http.StatusNotFound, gin.H{"error": "no such job"}) return } st, err := k.Retry(ctx.Param("key")) switch { case errors.Is(err, jobs.ErrBusy): ctx.JSON(http.StatusConflict, gin.H{"error": "it is still running"}) case err != nil: ctx.JSON(http.StatusNotFound, gin.H{"error": "there is nothing unsaved to save"}) default: ctx.JSON(http.StatusAccepted, st) } } // usage is the Claude spend for the stats page. func (s *Server) usage(ctx *gin.Context) { ctx.JSON(http.StatusOK, s.Usage.Summarize(time.Now())) }