forked from longtao.wu/droboticflow
annotationReadCache handed the same *HumanItemRecord to every lookup in a request, and write handlers mutate the item they load (version, status, assignment, payload keys) before the versioned write. After a failed or conflicting write, later lookups in that request would see unsaved state. Keep the single store read per request but return a copy per lookup, with the payload, assignment and processing-job input maps cloned. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
49 lines
1.8 KiB
Go
49 lines
1.8 KiB
Go
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 ©
|
|
}
|