Files
TradarrV2/backend/internal/scraper/fetch_metrics.go

294 lines
8.7 KiB
Go

package scraper
import (
"context"
"sync"
)
type EvidenceFlag uint8
const (
NotEvaluated EvidenceFlag = iota
ObservedYes
ObservedNo
)
type IdentityFlag uint8
const (
IdentityNotEvaluated IdentityFlag = iota
IdentityYes
IdentityNo
IdentityMismatch
)
// FetchObservation is transient and cannot contain identifiers, text or errors.
// It is immediately reduced into counters, never stored or logged individually.
type MetadataIdentityCounts struct {
Associated int `json:"associated"`
SameSourceDifferentIdentity int `json:"same_source_different_identity"`
ValidOtherHost int `json:"valid_other_host"`
Invalid int `json:"invalid"`
Absent int `json:"absent"`
}
type JSONLDIdentityCounts struct {
Mismatch int `json:"mismatch"`
Associated int `json:"associated"`
}
type IdentityEvidenceCounts struct {
Canonical MetadataIdentityCounts `json:"canonical"`
OG MetadataIdentityCounts `json:"og"`
JSONLD JSONLDIdentityCounts `json:"jsonld"`
}
type GlobalEvidenceCounts struct {
GlobalPage int `json:"global_page"`
}
type ScopedEvidenceCounts struct {
ArticleRoot int `json:"article_root"`
OutsideRoot int `json:"outside_root"`
}
type BlockingEvidenceCounts struct {
Paywall ScopedEvidenceCounts `json:"paywall"`
Challenge GlobalEvidenceCounts `json:"challenge"`
Partial ScopedEvidenceCounts `json:"partial"`
Truncated ScopedEvidenceCounts `json:"truncated"`
Placeholder ScopedEvidenceCounts `json:"placeholder"`
Accessibility ScopedEvidenceCounts `json:"accessibility"`
BodyConflict ScopedEvidenceCounts `json:"body_conflict"`
}
func granularCounters(i *IdentityEvidenceCounts, b *BlockingEvidenceCounts) []*int {
return []*int{&i.Canonical.Associated, &i.Canonical.SameSourceDifferentIdentity, &i.Canonical.ValidOtherHost, &i.Canonical.Invalid, &i.Canonical.Absent,
&i.OG.Associated, &i.OG.SameSourceDifferentIdentity, &i.OG.ValidOtherHost, &i.OG.Invalid, &i.OG.Absent, &i.JSONLD.Mismatch, &i.JSONLD.Associated,
&b.Paywall.ArticleRoot, &b.Paywall.OutsideRoot, &b.Challenge.GlobalPage, &b.Partial.ArticleRoot, &b.Partial.OutsideRoot, &b.Truncated.ArticleRoot, &b.Truncated.OutsideRoot, &b.Placeholder.ArticleRoot, &b.Placeholder.OutsideRoot, &b.Accessibility.ArticleRoot, &b.Accessibility.OutsideRoot, &b.BodyConflict.ArticleRoot, &b.BodyConflict.OutsideRoot}
}
type FetchObservation struct {
CandidateBodySupported bool
CandidateBodyLength int
GranularSupported bool
IdentityEvidence IdentityEvidenceCounts
BlockingEvidence BlockingEvidenceCounts
HTTPStatus int
Network bool
Root EvidenceFlag
Identity IdentityFlag
Blocking EvidenceFlag
Length int
State string
}
type HTTPCounts struct {
TwoXX int `json:"2xx"`
ThreeXX int `json:"3xx"`
FourXX int `json:"4xx"`
FiveXX int `json:"5xx"`
Network int `json:"network"`
}
type EvidenceCounts struct {
Yes int `json:"yes"`
No int `json:"no"`
NotEvaluated int `json:"not_evaluated"`
}
type IdentityCounts struct {
Yes int `json:"yes"`
No int `json:"no"`
Mismatch int `json:"mismatch"`
NotEvaluated int `json:"not_evaluated"`
}
type LengthCounts struct {
Zero int `json:"0"`
Small int `json:"1-500"`
Medium int `json:"501-2000"`
Large int `json:">2000"`
}
type FetchContentCounts struct {
Complete int `json:"complete"`
Incomplete int `json:"incomplete"`
Unavailable int `json:"unavailable"`
}
type FetchMetrics struct {
CandidateBodySupported bool `json:"candidate_body_supported"`
CandidateLength LengthCounts `json:"candidate_body_characters"`
GranularSupported bool `json:"granular_supported"`
IdentityEvidence IdentityEvidenceCounts `json:"identity_evidence"`
BlockingEvidence BlockingEvidenceCounts `json:"blocking_evidence"`
Login string `json:"login,omitempty"`
SchemaVersion int `json:"schema_version"`
Supported bool `json:"supported"`
Attempted int `json:"attempted"`
HTTP HTTPCounts `json:"http"`
Root EvidenceCounts `json:"editorial_root"`
Identity IdentityCounts `json:"identity"`
Blocking EvidenceCounts `json:"blocking_marker"`
Length LengthCounts `json:"extracted_characters"`
Content FetchContentCounts `json:"completeness"`
}
type FetchMeter struct {
mu sync.Mutex
closed bool
counts FetchMetrics
}
type fetchMetricsKey struct{}
func WithFetchMetrics(ctx context.Context) (context.Context, *FetchMeter) {
m := &FetchMeter{counts: FetchMetrics{SchemaVersion: 1}}
return context.WithValue(ctx, fetchMetricsKey{}, m), m
}
func fetchMeter(ctx context.Context) *FetchMeter {
m, _ := ctx.Value(fetchMetricsKey{}).(*FetchMeter)
return m
}
func FetchMetricsEnabled(ctx context.Context) bool { return fetchMeter(ctx) != nil }
func EnableFetchMetrics(ctx context.Context) {
if m := fetchMeter(ctx); m != nil {
m.mu.Lock()
defer m.mu.Unlock()
if !m.closed {
m.counts.Supported = true
}
}
}
func addEvidence(c *EvidenceCounts, v EvidenceFlag) {
switch v {
case ObservedYes:
c.Yes++
case ObservedNo:
c.No++
default:
c.NotEvaluated++
}
}
func addLength(c *LengthCounts, n int) {
switch {
case n <= 0:
c.Zero++
case n <= 500:
c.Small++
case n <= 2000:
c.Medium++
default:
c.Large++
}
}
func RecordFetch(ctx context.Context, o FetchObservation) {
m := fetchMeter(ctx)
if m == nil {
return
}
m.mu.Lock()
defer m.mu.Unlock()
if m.closed {
return
}
c := &m.counts
c.Supported = true
c.Attempted++
if o.GranularSupported {
c.GranularSupported = true
dst := granularCounters(&c.IdentityEvidence, &c.BlockingEvidence)
for n, v := range granularCounters(&o.IdentityEvidence, &o.BlockingEvidence) {
if *v > 0 {
*dst[n]++
}
}
}
switch {
case o.Network:
c.HTTP.Network++
case o.HTTPStatus >= 200 && o.HTTPStatus < 300:
c.HTTP.TwoXX++
case o.HTTPStatus >= 300 && o.HTTPStatus < 400:
c.HTTP.ThreeXX++
case o.HTTPStatus >= 400 && o.HTTPStatus < 500:
c.HTTP.FourXX++
case o.HTTPStatus >= 500 && o.HTTPStatus < 600:
c.HTTP.FiveXX++
default:
c.HTTP.Network++
}
addEvidence(&c.Root, o.Root)
addEvidence(&c.Blocking, o.Blocking)
switch o.Identity {
case IdentityYes:
c.Identity.Yes++
case IdentityNo:
c.Identity.No++
case IdentityMismatch:
c.Identity.Mismatch++
default:
c.Identity.NotEvaluated++
}
addLength(&c.Length, o.Length)
if o.CandidateBodySupported {
c.CandidateBodySupported = true
addLength(&c.CandidateLength, o.CandidateBodyLength)
}
switch o.State {
case ContentComplete:
c.Content.Complete++
case ContentIncomplete:
c.Content.Incomplete++
default:
c.Content.Unavailable++
}
}
func (m *FetchMeter) Finish() FetchMetrics {
m.mu.Lock()
defer m.mu.Unlock()
m.closed = true
return m.counts
}
// MergeFetchMetrics accepts only a complete, bounded aggregate from the scraper
// RPC. Missing/old RPC metrics remain unsupported, never fabricated zero fetches.
func MergeFetchMetrics(ctx context.Context, c FetchMetrics, maximum int) bool {
if c.SchemaVersion != 1 || !c.Supported || c.Attempted < 0 || c.Attempted > maximum {
return false
}
groups := [][]int{{c.HTTP.TwoXX, c.HTTP.ThreeXX, c.HTTP.FourXX, c.HTTP.FiveXX, c.HTTP.Network}, {c.Root.Yes, c.Root.No, c.Root.NotEvaluated}, {c.Identity.Yes, c.Identity.No, c.Identity.Mismatch, c.Identity.NotEvaluated}, {c.Blocking.Yes, c.Blocking.No, c.Blocking.NotEvaluated}, {c.Length.Zero, c.Length.Small, c.Length.Medium, c.Length.Large}, {c.Content.Complete, c.Content.Incomplete, c.Content.Unavailable}}
for _, g := range groups {
sum := 0
for _, n := range g {
if n < 0 || n > maximum {
return false
}
sum += n
}
if sum != c.Attempted {
return false
}
}
candidateSum := 0
for _, n := range []int{c.CandidateLength.Zero, c.CandidateLength.Small, c.CandidateLength.Medium, c.CandidateLength.Large} {
if n < 0 || n > c.Attempted {
return false
}
candidateSum += n
}
if (c.CandidateBodySupported && candidateSum != c.Attempted) || (!c.CandidateBodySupported && candidateSum != 0) {
return false
}
for _, n := range granularCounters(&c.IdentityEvidence, &c.BlockingEvidence) {
if *n < 0 || *n > c.Attempted || (!c.GranularSupported && *n != 0) {
return false
}
}
switch c.Login {
case "", "confirmed", "unconfirmed", "refused":
default:
return false
}
m := fetchMeter(ctx)
if m == nil {
return false
}
m.mu.Lock()
defer m.mu.Unlock()
if m.closed || m.counts.Attempted != 0 {
return false
}
m.counts = c
return true
}