droboticflow-new/internal/api/human_evidence_cache.go

148 lines
4.3 KiB
Go

package api
import (
"context"
"crypto/sha256"
"droboticflow/internal/domain"
"encoding/hex"
"encoding/json"
"fmt"
"path/filepath"
"sync"
"time"
)
// Cache only the authorized item's evidence index, never an authorization or
// review decision. Every endpoint still reloads and checks item/run scope first.
const humanEvidenceTTL = 30 * time.Second
const humanEvidenceCacheBytes = 16 << 20
type humanEvidenceEntry struct {
document runArtifactManifestDocument
expires, timeUsed time.Time
bytes int
}
type humanEvidenceFlight struct {
done chan struct{}
document runArtifactManifestDocument
err error
}
type humanEvidenceCache struct {
mu sync.Mutex
entries map[string]humanEvidenceEntry
flights map[string]*humanEvidenceFlight
}
func humanEvidenceKey(item *domain.HumanItemRecord, run *domain.RunRecord, artifact *domain.ExecutionArtifact) string {
data, err := json.Marshal(struct {
Org, Project, Item, Run, ParentRun string
Version, Revision int
Artifact *domain.ExecutionArtifact
}{item.OrganizationID, item.ProjectID, item.ID, run.ID, run.ParentRunID, item.Version, item.CurrentRevision, artifact})
if err != nil {
return ""
}
sum := sha256.Sum256(data)
return hex.EncodeToString(sum[:])
}
func cloneEvidenceDocument(d runArtifactManifestDocument) runArtifactManifestDocument {
d.Members = append([]runArtifactManifestMember(nil), d.Members...)
d.Summary = mapValue(normalizeStructuredValue(d.Summary))
return d
}
func (c *humanEvidenceCache) get(ctx context.Context, key string, build func(context.Context) runArtifactManifestDocument) (runArtifactManifestDocument, bool, error) {
if err := ctx.Err(); err != nil {
return runArtifactManifestDocument{}, false, err
}
c.mu.Lock()
if c.entries == nil {
c.entries = map[string]humanEvidenceEntry{}
c.flights = map[string]*humanEvidenceFlight{}
}
now := time.Now()
for k, e := range c.entries {
if !now.Before(e.expires) {
delete(c.entries, k)
}
}
if e, ok := c.entries[key]; ok {
e.timeUsed = now
c.entries[key] = e
c.mu.Unlock()
return cloneEvidenceDocument(e.document), true, nil
}
if f, ok := c.flights[key]; ok {
c.mu.Unlock()
select {
case <-ctx.Done():
return runArtifactManifestDocument{}, false, ctx.Err()
case <-f.done:
return cloneEvidenceDocument(f.document), false, f.err
}
}
f := &humanEvidenceFlight{done: make(chan struct{})}
c.flights[key] = f
c.mu.Unlock()
d, err := buildHumanEvidenceIndex(ctx, build)
c.mu.Lock()
f.document, f.err = d, err
if err == nil && d.Recognized && d.Message == "" && len(d.Members) > 0 {
encoded, _ := json.Marshal(d)
size := len(encoded)
for _, m := range d.Members {
size += len(m.inlineContent)
}
if size <= humanEvidenceCacheBytes {
c.entries[key] = humanEvidenceEntry{document: d, expires: time.Now().Add(humanEvidenceTTL), timeUsed: now, bytes: size}
for {
total := 0
oldest := ""
oldestAt := time.Now()
for k, e := range c.entries {
total += e.bytes
if oldest == "" || e.timeUsed.Before(oldestAt) {
oldest, oldestAt = k, e.timeUsed
}
}
if len(c.entries) <= 16 && total <= humanEvidenceCacheBytes {
break
}
delete(c.entries, oldest)
}
}
}
delete(c.flights, key)
close(f.done)
c.mu.Unlock()
return cloneEvidenceDocument(d), false, err
}
// Re-check just the requested file, including canonical workspace aliases and
// the existing parent-run evidence rule. Never trust cached symlink resolution.
func (s *server) cachedEvidenceFileAvailable(run *domain.RunRecord, artifact *domain.ExecutionArtifact) bool {
root, err := filepath.EvalSymlinks(cleanWorkspaceMountPath(s.workspaceMountPath))
if err != nil {
return false
}
contentRun := *run
if artifact.RunID != "" && artifact.RunID != run.ID {
if artifact.RunID != run.ParentRunID {
return false
}
contentRun.ID = artifact.RunID
}
validator := &server{workspaceMountPath: root}
_, ok := validator.safeRunArtifactManifestLocalFile(&contentRun, artifact.Path)
return ok
}
func buildHumanEvidenceIndex(ctx context.Context, build func(context.Context) runArtifactManifestDocument) (document runArtifactManifestDocument, err error) {
defer func() {
if recover() != nil {
err = fmt.Errorf("evidence index build failed")
}
}()
document = build(ctx)
return document, ctx.Err()
}