package runnerproto import ( "bytes" "crypto/sha256" "encoding/hex" "encoding/json" "strings" "time" "amadan.net/oficina/equipo/internal/equipo/team" ) type Event struct { Version int `json:"version"` ID string `json:"id"` TaskID string `json:"task_id"` AssignmentID string `json:"assignment_id"` ServerID string `json:"server_id"` AgentID string `json:"agent_id"` SessionID string `json:"session_id"` Epoch string `json:"epoch"` Kind string `json:"kind"` TurnID string `json:"turn_id"` RequestID string `json:"request_id"` Sequence *int64 `json:"sequence"` Scope team.Scope `json:"scope"` Handle team.Handle `json:"handle"` ActionID team.ActionID `json:"action_id,omitempty"` Payload json.RawMessage `json:"payload"` SourceTime time.Time `json:"source_time"` Isolation team.IsolationSnapshot `json:"isolation"` } func (e Event) Validate() error { preparation := (e.Kind == "namespace.owner" || e.Kind == "namespace.launch") && e.Scope.Job == 0 && e.Handle.Attempt == 0 if e.Version != DirectVersion || e.Scope.Account == "" || (!preparation && (e.Scope.Job <= 0 || e.Handle.Attempt <= 0)) || e.Handle.Fence <= 0 || e.Handle.Runner == "" || e.SourceTime.IsZero() || e.SourceTime.Location() != time.UTC || !json.Valid(e.Payload) || len(e.Payload) > MaxEventBytes || e.ActionID < 0 { return ErrInvalid } for _, s := range []string{e.ID, e.TaskID, e.AssignmentID, e.ServerID, e.AgentID, e.SessionID, e.Kind} { if s == "" || len(s) > 256 || strings.ContainsRune(s, 0) { return ErrInvalid } } for _, s := range []string{e.Epoch, e.TurnID, e.RequestID} { if len(s) > 256 || strings.ContainsRune(s, 0) { return ErrInvalid } } if e.Sequence != nil && (*e.Sequence < 0 || e.Epoch == "") { return ErrInvalid } if (e.Kind == "turn_completed" || e.Kind == "turn_failed") && (e.TurnID == "" || e.ActionID <= 0) { return ErrInvalid } if (e.Kind == "timeline_replacement" || e.Kind == "timeline_ready") && e.Epoch == "" { return ErrInvalid } return nil } func EventHash(v any) string { b, _ := json.Marshal(v) sum := sha256.Sum256(b) return hex.EncodeToString(sum[:]) } func (e Event) StreamKey() string { return EventHash([]string{e.AssignmentID, e.ServerID, e.AgentID, e.SessionID}) } func (e Event) DedupKey() string { if e.Sequence != nil { return EventHash([]any{e.StreamKey(), e.Epoch, *e.Sequence}) } stable := e.RequestID if stable == "" { stable = e.TurnID } if stable == "" { stable = e.ID } return EventHash([]string{e.StreamKey(), e.Kind, stable}) } func (e Event) ContentHash() string { // Delivery IDs may change across history/live overlap; content may not. e.ID = "" e.Isolation = team.IsolationSnapshot{} if e.Sequence == nil && e.Kind != "timeline_replacement" && e.Kind != "timeline_ready" && e.Kind != "timeline_gap" { e.Epoch = "" } var payload any decoder := json.NewDecoder(bytes.NewReader(e.Payload)) decoder.UseNumber() if decoder.Decode(&payload) == nil { e.Payload, _ = json.Marshal(payload) } return EventHash(e) }