131 lines
4.2 KiB
Go
131 lines
4.2 KiB
Go
package bell_connector
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"gorm.io/gorm"
|
|
"gorm.io/gorm/clause"
|
|
)
|
|
|
|
var ErrInboundConflict = errors.New("idempotency_conflict")
|
|
|
|
func AcceptEvent(ctx context.Context, db *gorm.DB, payload []byte, evidenceOwnerID string, now time.Time) (AcceptResult, error) {
|
|
identity, err := parseEventIdentity(payload)
|
|
if err != nil {
|
|
return AcceptResult{}, err
|
|
}
|
|
canonical, err := canonicalPayload(payload)
|
|
if err != nil {
|
|
return AcceptResult{}, err
|
|
}
|
|
digestBytes := sha256.Sum256(canonical)
|
|
digest := hex.EncodeToString(digestBytes[:])
|
|
result := AcceptResult{ProducerID: identity.ProducerID, SourceEventID: identity.SourceEventID, PayloadSHA256: digest}
|
|
err = db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
|
if tx.Dialector.Name() == "postgres" {
|
|
key := fmt.Sprintf("%d:%s:%s", len(identity.ProducerID), identity.ProducerID, identity.SourceEventID)
|
|
if lockErr := tx.Exec("SELECT pg_advisory_xact_lock(hashtextextended(?, 0))", key).Error; lockErr != nil {
|
|
return lockErr
|
|
}
|
|
}
|
|
var existing InboundEvent
|
|
lookup := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("producer_id = ? AND source_event_id = ?", identity.ProducerID, identity.SourceEventID).First(&existing).Error
|
|
if lookup == nil {
|
|
if existing.PayloadSHA256 != digest {
|
|
return ErrInboundConflict
|
|
}
|
|
result.Disposition = "duplicate"
|
|
return nil
|
|
}
|
|
if !errors.Is(lookup, gorm.ErrRecordNotFound) {
|
|
return lookup
|
|
}
|
|
fact := InboundEvent{ID: uuid.NewString(), ProducerID: identity.ProducerID, SourceEventID: identity.SourceEventID, Payload: append([]byte(nil), canonical...), PayloadSHA256: digest, ReceivedAt: now.UTC()}
|
|
if err := tx.Create(&fact).Error; err != nil {
|
|
return err
|
|
}
|
|
if _, err := EnqueueEvent(tx, canonical, now); err != nil {
|
|
return err
|
|
}
|
|
if err := retainEvidence(tx, canonical, evidenceOwnerID, now); err != nil {
|
|
return err
|
|
}
|
|
result.Disposition = "accepted"
|
|
return nil
|
|
})
|
|
return result, err
|
|
}
|
|
|
|
func retainEvidence(tx *gorm.DB, payload []byte, ownerID string, now time.Time) error {
|
|
var envelope struct {
|
|
Evidence []json.RawMessage `json:"evidence"`
|
|
}
|
|
decoder := json.NewDecoder(bytes.NewReader(payload))
|
|
if err := decoder.Decode(&envelope); err != nil {
|
|
return err
|
|
}
|
|
for _, raw := range envelope.Evidence {
|
|
var metadata struct {
|
|
EvidenceID string `json:"evidence_id"`
|
|
OwnerID string `json:"owner_id"`
|
|
Status string `json:"status"`
|
|
ExpiresAt string `json:"expires_at"`
|
|
}
|
|
if err := json.Unmarshal(raw, &metadata); err != nil || !safeIdentifier(metadata.EvidenceID) || !safeIdentifier(metadata.OwnerID) {
|
|
return errors.New("invalid evidence metadata")
|
|
}
|
|
if ownerID != "" && metadata.OwnerID != ownerID {
|
|
continue
|
|
}
|
|
canonical, err := canonicalPayload(raw)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var expiresAt *time.Time
|
|
if metadata.ExpiresAt != "" {
|
|
parsed, parseErr := time.Parse(time.RFC3339Nano, metadata.ExpiresAt)
|
|
if parseErr != nil {
|
|
return parseErr
|
|
}
|
|
parsed = parsed.UTC()
|
|
expiresAt = &parsed
|
|
}
|
|
record := EvidenceRecord{EvidenceID: metadata.EvidenceID, OwnerID: metadata.OwnerID, Status: metadata.Status, Payload: canonical, ExpiresAt: expiresAt, UpdatedAt: now.UTC()}
|
|
var existing EvidenceRecord
|
|
lookup := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&existing, "evidence_id = ?", metadata.EvidenceID).Error
|
|
if lookup == nil {
|
|
if existing.OwnerID != metadata.OwnerID || !validEvidenceTransition(existing.Status, metadata.Status) {
|
|
return errors.New("evidence metadata transition is invalid")
|
|
}
|
|
} else if !errors.Is(lookup, gorm.ErrRecordNotFound) {
|
|
return lookup
|
|
}
|
|
if err := tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "evidence_id"}}, DoUpdates: clause.AssignmentColumns([]string{"status", "payload", "expires_at", "updated_at"})}).Create(&record).Error; err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func validEvidenceTransition(from, to string) bool {
|
|
if from == to {
|
|
return true
|
|
}
|
|
switch from {
|
|
case "pending":
|
|
return to == "processing" || to == "success" || to == "failed"
|
|
case "processing":
|
|
return to == "success" || to == "failed"
|
|
default:
|
|
return false
|
|
}
|
|
}
|