droboticflow/internal/api/annotation_random_claim.go

378 lines
15 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package api
import (
"context"
"crypto/sha256"
"droboticflow/internal/domain"
"droboticflow/internal/store"
"encoding/hex"
"errors"
"net/http"
"regexp"
"strings"
"time"
)
func randomClaimAnnotator(p *authenticatedPrincipal) bool {
return p != nil && p.User.Role == domain.UserRoleAnnotator
}
func annotationWorkerCannotRelease(p *authenticatedPrincipal) bool {
if p == nil {
return false
}
return p.User.Role == domain.UserRoleAnnotator || p.User.Role == domain.UserRoleQualityReviewer || p.User.Role == domain.UserRoleAcceptanceReviewer
}
func annotationClaimStage(batch *domain.HumanBatchRecord, id string) bool {
stage, _, ok := humanStage(batch, id)
return ok && stage.Kind == domain.HumanStageAnnotation && annotationRoleForHumanStage(stage) == domain.AnnotationRoleAnnotator
}
func (s *server) handleAnnotationClaimProjects(w http.ResponseWriter, r *http.Request) {
p, _ := currentPrincipal(r)
if !randomClaimAnnotator(p) {
renderJSON(w, 403, map[string]string{"error": "仅标注员使用项目随机领取"})
return
}
projects, e := s.store.ListProjectsByOrganization(r.Context(), p.User.OrganizationID)
if e != nil {
renderError(w, 500, e)
return
}
members, e := s.annotationMembershipsForUser(r.Context(), p.User.OrganizationID, "", p.User.ID)
if e != nil {
renderError(w, 500, e)
return
}
out := []domain.ProjectRecord{}
activeSuppliers := map[string]bool{}
for _, member := range members {
if member.Role != domain.AnnotationRoleAnnotator || member.SupplierID == "" {
continue
}
if _, checked := activeSuppliers[member.SupplierID]; checked {
continue
}
supplier, err := s.store.GetSupplier(r.Context(), member.SupplierID)
if err != nil {
renderError(w, 500, err)
return
}
activeSuppliers[member.SupplierID] = supplier != nil && supplier.OrganizationID == p.User.OrganizationID && strings.EqualFold(supplier.Status, "active")
}
eligibleMembers := []annotationProjectRole{}
for _, member := range members {
if activeSuppliers[member.SupplierID] {
eligibleMembers = append(eligibleMembers, member)
}
}
for _, project := range projects {
if project.DeletionTaskID != "" || strings.EqualFold(string(project.Status), "archived") {
continue
}
if membershipHasRole(eligibleMembers, domain.AnnotationTaskRecord{ProjectID: project.ID}, domain.AnnotationRoleAnnotator) || membershipHasRole(eligibleMembers, domain.AnnotationTaskRecord{ProjectID: project.ID, SupplierPool: true}, domain.AnnotationRoleAnnotator) {
out = append(out, project)
}
}
renderJSON(w, 200, map[string]any{"items": out})
}
var randomClaimRequestID = regexp.MustCompile(`^[a-zA-Z0-9_-]{16,100}$`)
// Only an aggregate is exposed. Candidate IDs, media and ordering stay private.
func (s *server) handleAnnotationClaimCount(w http.ResponseWriter, r *http.Request) {
p, _ := currentPrincipal(r)
if !randomClaimAnnotator(p) {
renderJSON(w, 403, map[string]string{"error": "仅标注员使用项目随机领取"})
return
}
id := strings.TrimSpace(r.URL.Query().Get("projectId"))
if id == "" {
renderValidationError(w, validationIssue{Field: "projectId", Message: "请选择项目"})
return
}
project, err := s.store.GetProject(r.Context(), id)
if err != nil {
renderError(w, 500, err)
return
}
if project == nil || project.OrganizationID != p.User.OrganizationID || project.DeletionTaskID != "" || strings.EqualFold(string(project.Status), "archived") {
renderJSON(w, 403, map[string]string{"error": "项目不存在、不可用或无权访问"})
return
}
members, err := s.annotationMembershipsForUser(r.Context(), p.User.OrganizationID, id, p.User.ID)
if err != nil {
renderError(w, 500, err)
return
}
suppliers := map[string]bool{}
for _, m := range members {
if m.Role != domain.AnnotationRoleAnnotator || m.SupplierID == "" {
continue
}
supplier, err := s.store.GetSupplier(r.Context(), m.SupplierID)
if err != nil {
renderError(w, 500, err)
return
}
if supplier != nil && supplier.OrganizationID == p.User.OrganizationID && strings.EqualFold(supplier.Status, "active") {
suppliers[m.SupplierID] = true
}
}
if len(suppliers) == 0 {
renderJSON(w, 403, map[string]string{"error": "当前账号没有该项目的有效标注权限"})
return
}
query := annotationClaimCountScope(id, suppliers, members)
count, err := s.store.CountAnnotationClaimCandidates(r.Context(), p.User.OrganizationID, query)
if err != nil {
renderError(w, 500, err)
return
}
renderJSON(w, 200, map[string]any{"projectId": id, "count": count})
}
func annotationClaimCountScope(projectID string, suppliers map[string]bool, members []annotationProjectRole) store.AnnotationClaimCountQuery {
query := store.AnnotationClaimCountQuery{ProjectID: projectID}
for supplierID := range suppliers {
query.ActiveSupplierIDs = append(query.ActiveSupplierIDs, supplierID)
}
for _, member := range members {
if member.Role != domain.AnnotationRoleAnnotator || member.ProjectID != projectID {
continue
}
scope := store.AnnotationClaimMembership{SupplierID: strings.TrimSpace(member.SupplierID), Legacy: member.AuthorizationMode != "supplier_grant"}
if member.AuthorizationMode == "supplier_grant" || member.AuthorizationMode == "both" {
scope.SupplierPool = member.GrantStatus == "active"
if !scope.SupplierPool {
for taskID, allowed := range member.DrainTaskIDs {
if allowed {
scope.DrainTaskIDs = append(scope.DrainTaskIDs, taskID)
}
}
}
}
query.Memberships = append(query.Memberships, scope)
}
return query
}
func (s *server) handleAnnotationRandomClaim(w http.ResponseWriter, r *http.Request) {
p, _ := currentPrincipal(r)
if !randomClaimAnnotator(p) {
renderJSON(w, 403, map[string]string{"error": "仅标注员使用项目随机领取"})
return
}
var body struct {
ProjectID string `json:"projectId"`
RequestID string `json:"requestId"`
BufferOnly bool `json:"bufferOnly,omitempty"`
}
if !decodeJSON(w, r, &body) {
return
}
body.ProjectID = strings.TrimSpace(body.ProjectID)
if body.ProjectID == "" || !randomClaimRequestID.MatchString(body.RequestID) {
renderValidationError(w, validationIssue{Field: "projectId/requestId", Message: "请选择项目,并提供有效的领取请求编号"})
return
}
ctx, cancel := context.WithTimeout(r.Context(), 25*time.Second)
defer cancel()
project, e := s.store.GetProject(ctx, body.ProjectID)
if e != nil {
renderError(w, 500, e)
return
}
if project == nil || project.OrganizationID != p.User.OrganizationID || project.DeletionTaskID != "" || strings.EqualFold(string(project.Status), "archived") {
renderJSON(w, 403, map[string]string{"error": "项目不存在、不可用或无权访问"})
return
}
members, e := s.annotationMembershipsForUser(ctx, p.User.OrganizationID, project.ID, p.User.ID)
if e != nil {
renderError(w, 500, e)
return
}
supplierIDs := map[string]bool{}
for _, member := range members {
if member.Role != domain.AnnotationRoleAnnotator || member.SupplierID == "" {
continue
}
supplier, e := s.store.GetSupplier(ctx, member.SupplierID)
if e != nil {
renderError(w, 500, e)
return
}
if supplier != nil && supplier.OrganizationID == p.User.OrganizationID && strings.EqualFold(supplier.Status, "active") {
supplierIDs[member.SupplierID] = true
}
}
if len(supplierIDs) == 0 {
renderJSON(w, 403, map[string]string{"error": "当前账号没有该项目的有效标注员及供应商权限", "code": "supplier_membership_required"})
return
}
sum := sha256.Sum256([]byte(p.User.OrganizationID + "\x00" + p.User.ID + "\x00" + project.ID + "\x00" + body.RequestID))
key := hex.EncodeToString(sum[:])
replay, e := s.store.GetHumanClaimReceipt(ctx, key)
if e != nil {
renderError(w, 500, e)
return
}
if replay != nil {
if replay.Intent != nil {
if _, err := s.store.CommitHumanClaim(ctx, store.HumanClaimCommit{Receipt: *replay}); err != nil {
renderRandomClaimError(w, err)
return
}
}
s.renderRandomClaimResult(ctx, w, r, replay.ItemID, true)
return
}
// B03 返工优先(spec §5.4-6,2026-10-12 确认):先清自己的错再领新——
// 定向归属我的返工任务存在时优先原样返回(不改版本、不重复领取)。
// 不设 Limit:列表按 createdAt 倒序分页,老的返工任务会被较新的领取记录
// 挤出窗口而静默失去优先权(评审轮 c3);个人名下条目量级小,全扫可接受。
if mine, me := s.store.ListHumanItems(ctx, p.User.OrganizationID, domain.HumanItemQuery{ProjectID: project.ID, ActorUserID: p.User.ID, CurrentStageID: domain.FanyuV58StageAnnotationCombined}); me == nil {
for _, item := range mine {
if store.AnnotationSourceAuditAdvisory() && store.AnnotationSourceUnavailable(item) {
continue
}
if !item.InheritedRework && item.ReviewRound > 0 && item.AssignedUserID == p.User.ID && (item.Status == domain.HumanItemRework || item.Status == domain.HumanItemClaimed) {
s.renderRandomClaimResult(ctx, w, r, item.ID, false)
return
}
}
}
batches := map[string]*domain.HumanBatchRecord{}
handled, e := s.store.VisitAnnotationClaimCandidates(ctx, p.User.OrganizationID, project.ID, func(candidate domain.HumanItemRecord) (bool, error) {
batch, loaded := batches[candidate.BatchID]
if !loaded {
batch, e = s.store.GetHumanBatch(ctx, candidate.BatchID)
if e != nil {
renderError(w, 500, e)
return true, nil
}
batches[candidate.BatchID] = batch
}
legacy := domain.AnnotationTaskRecord{ID: candidate.LegacyTaskID, ProjectID: candidate.ProjectID, SupplierID: candidate.SupplierID, ProcessingScope: candidate.ProcessingScope, ProcessingProfile: candidate.ProcessingProfile}
legacy.SupplierPool = batch != nil && batch.ProcessingProfile == domain.ProcessingProfileRawHuman && domain.IsFanyuV58ThreeRoleHumanLoop(batch.Stages)
if !membershipHasRole(members, legacy, domain.AnnotationRoleAnnotator) {
return false, nil
}
supplierID := candidate.SupplierID
if supplierID == "" {
for _, member := range members {
if member.Role == domain.AnnotationRoleAnnotator && supplierIDs[member.SupplierID] {
supplierID = member.SupplierID
break
}
}
}
if !supplierIDs[supplierID] {
return false, nil
}
if batch == nil || batch.OrganizationID != project.OrganizationID || batch.ProjectID != project.ID || batch.Status == domain.HumanBatchCompleted || !annotationClaimStage(batch, candidate.CurrentStageID) {
return false, nil
}
if body.BufferOnly && (batch.WorkflowID != candidate.WorkflowID || batch.ProcessingProfile != domain.ProcessingProfileRawHuman || !domain.IsFanyuV58ThreeRoleHumanLoop(batch.Stages)) {
return false, nil
}
item, e := s.store.GetHumanItem(ctx, candidate.ID)
if e != nil {
renderError(w, 500, e)
return true, nil
}
if item == nil || item.Version != candidate.Version || item.AssignedUserID != "" {
return false, nil
}
previous := item.Version
bind := item.SupplierID == ""
item.SupplierID = supplierID
item.AssignedUserID = p.User.ID
item.Status = domain.HumanItemClaimed
item.ClaimedAt = nowISO()
item.UpdatedAt = item.ClaimedAt
item.Version++
status := domain.AnnotationTaskStatusPendingAnnotation
if item.ReviewRound > 0 && item.CurrentStageID == domain.FanyuV58StageAnnotationCombined {
status = domain.AnnotationTaskStatusRework
}
commit := store.HumanClaimCommit{EnforceBuffer: batch.WorkflowID == item.WorkflowID && batch.ProcessingProfile == domain.ProcessingProfileRawHuman && domain.IsFanyuV58ThreeRoleHumanLoop(batch.Stages), Receipt: store.HumanClaimReceipt{ID: key, ItemID: item.ID, UserID: p.User.ID, ProjectID: project.ID, OrganizationID: project.OrganizationID}, Item: *item, ExpectedVersion: previous, BindSupplier: bind, TaskStatus: status,
Attempt: domain.HumanStageAttemptRecord{OrganizationID: item.OrganizationID, ItemID: item.ID, StageID: item.CurrentStageID, Round: item.ReviewRound, Status: domain.HumanItemClaimed, AssigneeUserID: p.User.ID},
Event: domain.HumanEventRecord{ID: "human-event-random-" + key, OrganizationID: item.OrganizationID, BatchID: item.BatchID, ItemID: item.ID, StageID: item.CurrentStageID, Round: item.ReviewRound, EventType: "claimed", ActorUserID: p.User.ID, ItemVersion: item.Version, Payload: map[string]any{"mode": "project_random", "supplierId": supplierID}},
}
result, e := s.store.CommitHumanClaim(ctx, commit)
if errors.Is(e, store.ErrHumanClaimConflict) {
return false, nil
}
if e != nil {
renderRandomClaimError(w, e)
return true, nil
}
if result == nil {
renderJSON(w, 409, map[string]string{"error": "原领取任务已不可用,请查看我的任务", "code": "claim_result_unavailable"})
return true, nil
}
s.renderRandomClaimResult(ctx, w, r, result.ID, false)
return true, nil
})
if e != nil {
renderError(w, 500, e)
return
}
if handled {
return
}
// A competing retry of the same request may have won while candidates moved.
if receipt, e := s.store.GetHumanClaimReceipt(ctx, key); e == nil && receipt != nil {
if receipt.Intent != nil {
if _, err := s.store.CommitHumanClaim(ctx, store.HumanClaimCommit{Receipt: *receipt}); err != nil {
renderRandomClaimError(w, err)
return
}
}
s.renderRandomClaimResult(ctx, w, r, receipt.ItemID, true)
return
}
renderJSON(w, 200, map[string]any{"item": nil, "code": "no_claimable_task", "message": "本项目暂无您可领取的标注任务"})
}
func renderRandomClaimError(w http.ResponseWriter, err error) {
if errors.Is(err, store.ErrAnnotationBufferFull) {
renderJSON(w, 409, map[string]string{"code": "annotation_buffer_full", "error": "个人任务池已满;请送检完成已有任务或调整容量"})
return
}
if errors.Is(err, store.ErrHumanClaimCandidateTaken) {
renderJSON(w, 409, map[string]string{"code": "claim_candidate_taken", "error": "该任务刚被其他人领取或已变化,本次未分配新任务,请再次随机领取"})
return
}
renderError(w, 500, err)
}
func (s *server) renderRandomClaimResult(ctx context.Context, w http.ResponseWriter, r *http.Request, id string, replayed bool) {
item, e := s.store.GetHumanItem(ctx, id)
if e != nil {
renderError(w, 500, e)
return
}
p, _ := currentPrincipal(r)
if item == nil || p == nil || (item.AssignedUserID != p.User.ID && item.LatestAuthorUserID != p.User.ID) {
renderJSON(w, 409, map[string]string{"error": "原领取任务已转交或不可用,请查看我的任务", "code": "claim_result_unavailable"})
return
}
task, e := s.store.GetAnnotationTask(ctx, item.LegacyTaskID)
if e != nil {
renderError(w, 500, e)
return
}
if task == nil {
renderJSON(w, 409, map[string]string{"error": "任务已经领取,但关联数据已不可用,请联系管理员;不会重新分配另一条任务", "code": "claim_result_unavailable"})
return
}
if err := newHumanDisplayResolver(s).enrichItem(ctx, item); err != nil {
renderError(w, http.StatusInternalServerError, err)
return
}
renderJSON(w, 200, map[string]any{"item": item, "task": task, "replayed": replayed})
}