package api import ( "context" "droboticflow/internal/domain" "maps" "net/http" "strings" ) type annotationReadCacheKey struct{} type annotationRequestReads struct { items map[string]*domain.HumanItemRecord summary bool } func annotationReadCache(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if strings.HasPrefix(r.URL.Path, "/api/plugins/annotation-qa/tasks/") { view := r.URL.Query().Get("view") detailPath := !strings.Contains(strings.TrimPrefix(r.URL.Path, "/api/plugins/annotation-qa/tasks/"), "/") reads := &annotationRequestReads{items: map[string]*domain.HumanItemRecord{}, summary: detailPath && r.Method == http.MethodGet && (view == "status" || view == "summary")} r = r.WithContext(context.WithValue(r.Context(), annotationReadCacheKey{}, reads)) } next.ServeHTTP(w, r) }) } // Detached jobs must reread ownership and state, not inherit an HTTP snapshot. func withoutAnnotationReadCache(ctx context.Context) context.Context { return context.WithValue(ctx, annotationReadCacheKey{}, (*annotationRequestReads)(nil)) } // Each lookup gets its own copy of the cached snapshot. Handlers change the // version, status, assignment and top-level payload keys of the item they load // before a versioned write; sharing one pointer would let a failed or // conflicting write leak unsaved state into later lookups in the request. func annotationRequestItemCopy(item *domain.HumanItemRecord) *domain.HumanItemRecord { copy := *item copy.Subject.Payload = maps.Clone(item.Subject.Payload) copy.LegacyAssignment = maps.Clone(item.LegacyAssignment) if item.ProcessingJob != nil { job := *item.ProcessingJob job.Input = maps.Clone(item.ProcessingJob.Input) copy.ProcessingJob = &job } return © }