Preserve legacy system suggestions and unreadable saved content across workspace writers. Compare explicit dictionary snapshots and normalize empty optional evidence during save readback; keep transient autosave failures retryable. Cover recovery entry points, source shapes, failed saves and stale-snapshot rejection with isolated HTTP and browser regressions.
167 lines
7.1 KiB
Go
167 lines
7.1 KiB
Go
package api
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
|
|
"droboticflow/internal/domain"
|
|
"github.com/go-chi/chi/v5"
|
|
)
|
|
|
|
// handleSliceEditRestoration writes an editing snapshot, never a generation or
|
|
// disposition command. The current server disposition remains authoritative.
|
|
func (s *server) handleSliceEditRestoration(w http.ResponseWriter, r *http.Request) {
|
|
task, err := s.getAnnotationTaskForAccess(r.Context(), chi.URLParam(r, "id"))
|
|
if err != nil {
|
|
renderError(w, 500, err)
|
|
return
|
|
}
|
|
if task == nil {
|
|
renderJSON(w, 404, map[string]string{"error": "Annotation task not found"})
|
|
return
|
|
}
|
|
principal, memberships, ok := s.ensureAnnotationTaskAccess(w, r, *task)
|
|
if !ok {
|
|
return
|
|
}
|
|
if principal == nil || principal.User.Role != domain.UserRoleAnnotator || !membershipHasRole(memberships, *task, domain.AnnotationRoleAnnotator) {
|
|
renderJSON(w, 403, map[string]string{"error": "annotator assignment is required"})
|
|
return
|
|
}
|
|
item, ok := s.requireLegacyHumanItemClaim(w, r, *task, domain.FanyuV58StageAnnotationCombined)
|
|
if !ok || rejectPendingCombinedSubmission(w, item) {
|
|
return
|
|
}
|
|
if rejectInvalidSavedAnnotationWorkspaces(w, item) {
|
|
return
|
|
}
|
|
workflow := mapValue(item.Subject.Payload["sliceWorkflow"])
|
|
failedEditing := failedSliceEditingAvailable(item)
|
|
busy := false
|
|
if job := item.ProcessingJob; job != nil {
|
|
busy = job.Status == "queued" || job.Status == "running" || job.Status == "processing" || (job.Status == "failed" && !failedEditing)
|
|
}
|
|
// Explicit workflow markers stay authoritative. For pre-workflow records,
|
|
// use server-owned persisted evidence, never the incoming undo snapshot.
|
|
initialSlice := len(workflow) == 0 && item.CurrentRevision == 0 && len(mapValue(item.Subject.Payload["materialization"])) == 0 && item.ProcessingJob == nil
|
|
phase := stringValue(workflow["phase"])
|
|
editablePhase := phase == "slice" || phase == "annotate" || initialSlice || failedEditing
|
|
blocked := busy
|
|
switch stringValue(workflow["status"]) {
|
|
case "processing", "running", "materializing", "queued":
|
|
blocked = true
|
|
case "failed":
|
|
blocked = !failedEditing
|
|
}
|
|
if !editablePhase && !blocked && item.Subject.Payload["sliceWorkflow"] == nil {
|
|
storedSlices := decodeMaterializationValue[domain.SliceSegment](annotationWorkspacePayload(item)["sliceSegments"])
|
|
if len(storedSlices) > 0 && len(validateSliceSegments(storedSlices, *task)) == 0 && len(validateCompleteSliceCoverage(storedSlices, *task)) == 0 {
|
|
// Generation evidence also covers all-discarded or partially edited
|
|
// tracks, which need not satisfy final annotation confirmation yet.
|
|
editablePhase, err = s.hasLegacyAnnotationGenerationEvidence(r.Context(), *task, item)
|
|
if err == nil && !editablePhase && !task.SourceIsFullVideo {
|
|
editablePhase, err = s.legacyAnnotationConfirmationReady(r.Context(), *task, item)
|
|
}
|
|
if err != nil {
|
|
renderError(w, 500, err)
|
|
return
|
|
}
|
|
}
|
|
}
|
|
if !editablePhase || blocked {
|
|
renderJSON(w, 409, map[string]string{"code": "slice_edit_restoration_unavailable", "error": "仅可在可编辑的切片或标注阶段撤销或重做切片"})
|
|
return
|
|
}
|
|
var body combinedAnnotationDraftInput
|
|
if !decodeJSON(w, r, &body) {
|
|
return
|
|
}
|
|
if body.Version != item.Version {
|
|
renderJSON(w, 409, map[string]string{"code": "version_conflict", "error": "Human item version conflict"})
|
|
return
|
|
}
|
|
original := item
|
|
item, err = sliceEditBaseline(original)
|
|
if err != nil {
|
|
renderJSON(w, 409, map[string]string{"error": err.Error()})
|
|
return
|
|
}
|
|
proposed := body.normalizedSliceSegments()
|
|
slices, issues := s.canonicalSliceDispositionState(r.Context(), item, proposed, body.normalizedOperations())
|
|
// Historical audit fields may be stale after an explicit discard/restore.
|
|
// The canonicalizer replaces them with current server-owned evidence.
|
|
for i, candidate := range proposed {
|
|
if !candidate.IsDiscarded() && candidate.DiscardReason != "" {
|
|
issues = append(issues, validationIssue{Field: fmt.Sprintf("sliceSegments.%d.discardReason", i), Code: "explicit_disposition_required", Message: "请通过舍弃操作设置原因,保留片段不能携带舍弃原因"})
|
|
}
|
|
}
|
|
if len(issues) > 0 {
|
|
renderValidationError(w, issues...)
|
|
return
|
|
}
|
|
if task.SourceIsFullVideo || stringValue(workflow["boundaryContract"]) == "hardware-frame-v1" {
|
|
timeline, err := s.annotationFrameTimelineForTask(r.Context(), *task, "left")
|
|
if err != nil {
|
|
renderJSON(w, 422, map[string]string{"error": err.Error()})
|
|
return
|
|
}
|
|
if task.SourceIsFullVideo {
|
|
task.CoverageStartSecond = floatValue(timeline["rangeStartSecond"])
|
|
task.CoverageEndSecond = floatValue(timeline["rangeEndSecond"])
|
|
task.CoverageMode = "full_common_range"
|
|
}
|
|
grid := annotationBoundaryGrid{Seconds: timeline["boundariesSeconds"].([]float64), Timestamps: timeline["boundaryTimestampUs"].([]int64)}
|
|
resolve := func(start, end *float64, startUS, endUS *int64, field string) {
|
|
a, firstErr := grid.resolve(*start)
|
|
b, lastErr := grid.resolve(*end)
|
|
if firstErr != nil || lastErr != nil || b <= a {
|
|
issues = append(issues, validationIssue{Field: field, Message: "切片和动作边界必须与有效帧对齐"})
|
|
return
|
|
}
|
|
*start, *end = grid.Seconds[a], grid.Seconds[b]
|
|
*startUS, *endUS = grid.Timestamps[a], grid.Timestamps[b]
|
|
}
|
|
for i := range slices {
|
|
v := &slices[i]
|
|
resolve(&v.Start, &v.End, &v.StartTimestampUS, &v.EndTimestampUS, "sliceSegments")
|
|
}
|
|
for i := range body.Segments {
|
|
v := &body.Segments[i]
|
|
resolve(&v.Start, &v.End, &v.StartTimestampUS, &v.EndTimestampUS, "segments")
|
|
}
|
|
}
|
|
issues = append(issues, validateSliceSegments(slices, *task)...)
|
|
issues = append(issues, validateCompleteSliceCoverage(slices, *task)...)
|
|
issues = append(issues, validateDraftCombinedAnnotationEvents(body.Segments, *task)...)
|
|
issues = append(issues, validateDraftStatuses(body.normalizedStatuses(), slices)...)
|
|
issues = append(issues, s.validateProjectSliceNames(r.Context(), item, slices, "restore")...)
|
|
issues = append(issues, s.canonicalActionDictionaries(r.Context(), item, body.Segments, "restore")...)
|
|
template, err := s.store.GetAnnotationTemplate(r.Context(), task.TemplateID)
|
|
if err != nil {
|
|
renderError(w, 500, err)
|
|
return
|
|
}
|
|
issues = append(issues, validateDraftFanyuV5CombinedSemanticSegments(body.Segments, slices, annotationTemplateWithTaskSnapshot(template, task))...)
|
|
if len(issues) > 0 {
|
|
renderValidationError(w, issues...)
|
|
return
|
|
}
|
|
now := nowISO()
|
|
workspace := map[string]any{"sliceSegments": slices, "operations": body.normalizedOperations(), "segments": body.normalizedSegments(), "statuses": body.normalizedStatuses(), "userId": principal.User.ID, "savedAt": now}
|
|
storeSliceEditWorkspace(item, original, workspace)
|
|
expected := item.Version
|
|
item.Version++
|
|
item.UpdatedAt = now
|
|
won, err := s.store.UpdateHumanItemVersioned(r.Context(), *item, expected)
|
|
if err != nil {
|
|
renderError(w, 500, err)
|
|
return
|
|
}
|
|
if !won {
|
|
renderJSON(w, 409, map[string]string{"code": "version_conflict", "error": "Human item version conflict"})
|
|
return
|
|
}
|
|
_ = s.appendHumanEvent(r.Context(), *item, "slice_edit_restored", principal.User.ID, map[string]any{"sliceCount": len(slices)})
|
|
renderJSON(w, 200, map[string]any{"item": item, "workspace": workspace})
|
|
}
|