Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ Go module `github.com/patch-it-dev/patch-it-plugins`; the only dependency is `go

```
core/plugin/ the Plugin interface (Extract) in its two shapes, Versioned (ListVersions, ReadAt) and Living (Read);
ErrNothingToRead; the registry of providers and sources, Env, Result
ErrNothingToRead; the shape guard (Shape, anchors, ErrShapeChanged); the registry, Env, Result
core/fetch/ the HTTP fetch with retries and the ETag / Last-Modified cache
core/github/ the newest release / commit on GitHub, and a commit's SHA and date (one place)
core/versions/ every version of a source: GitHub releases, tags and commits, PyPI, npm
Expand Down
14 changes: 14 additions & 0 deletions core/diff/diff.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,20 @@ func Parse(data []byte) (*Spec, error) {
return &Spec{Version: version, doc: doc}, nil
}

// Operations is how many operations the spec has: every method under every
// path. What the shape guard counts.
func (s *Spec) Operations() int {
n := 0
for _, item := range obj(s.doc["paths"]) {
for _, m := range methods {
if _, ok := obj(item)[m]; ok {
n++
}
}
}
return n
}

// methods are the operation keys a path item can hold. Anything else under a
// path (parameters, servers, summary) is not an operation.
var methods = []string{"get", "put", "post", "delete", "patch", "head", "options", "trace"}
Expand Down
16 changes: 16 additions & 0 deletions core/extract/feed.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,22 @@ func ParseFeed(b []byte) ([]Entry, error) {
return out, nil
}

// FeedTitle is an RSS channel's or an Atom feed's own title, as text: ""
// when b isn't one or has none.
func FeedTitle(b []byte) string {
var f struct {
RSS string `xml:"channel>title"`
Atom string `xml:"title"`
}
if err := xml.Unmarshal(b, &f); err != nil {
return ""
}
if f.RSS != "" {
return Text(f.RSS)
}
return Text(f.Atom)
}

func trimAll(ss []string) []string {
var out []string
for _, s := range ss {
Expand Down
3 changes: 3 additions & 0 deletions core/kit/notices.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,7 @@ type Notices interface {
// Count is how many notices were read: what the shape guard compares
// with the last read.
Count() int
// Has says whether entry is among what was read, as the reader names
// an entry: what a source's anchors (plugin.Anchor) are checked with.
Has(entry string) bool
}
2 changes: 2 additions & 0 deletions core/plugin/plugin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ type testPlugin struct {

func (p testPlugin) Name() string { return p.name }

func (p testPlugin) WithShape(Shape) Plugin { return p }

func (p testPlugin) Read(_ context.Context, env Env, _ Snapshot) (Snapshot, error) {
if p.err != nil {
return Snapshot{}, p.err
Expand Down
23 changes: 20 additions & 3 deletions core/plugin/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,8 +117,13 @@ type Source struct {
// sources without a table kept elsewhere. Only names checked by hand;
// none is fine when no package maps to the source.
Packages []string
// Shape is what the shape guard checks this source's reads against: the
// kind's defaults when zero, anchors for a living page (Shape). Set with
// a comment saying why, and for an anchor where it is on the page.
Shape Shape
// Plugin runs it. Its Name is the source's id ("algolia/search-api"),
// which every event's `api` carries.
// which every event's `api` carries. RegisterProvider replaces it with
// the same plugin given Shape (Guarded.WithShape).
Plugin Plugin
}

Expand All @@ -145,8 +150,10 @@ func RegisterProvider(p Provider) {
panic("plugin: " + err.Error())
}
for i := range p.Sources {
p.Sources[i].Kind = KindOf(p.Sources[i].Plugin)
p.Sources[i].Page = PageOf(p.ID)
s := &p.Sources[i]
s.Kind = KindOf(s.Plugin)
s.Page = PageOf(p.ID)
s.Plugin = s.Plugin.(Guarded).WithShape(s.Shape)
}
mu.Lock()
defer mu.Unlock()
Expand Down Expand Up @@ -197,6 +204,8 @@ func (p Provider) check() error {
return fmt.Errorf("source %q has no Plugin", id)
case shape(s.Plugin) == "":
return fmt.Errorf("source %q: its plugin must be exactly one of plugin.Versioned (ListVersions, ReadAt) or plugin.Living (Read)", id)
case !isGuarded(s.Plugin):
return fmt.Errorf("source %q: its plugin (kinds/%s) doesn't run the shape guard: every kind implements plugin.Guarded", id, KindOf(s.Plugin))
case s.Plugin.Name() != id:
return fmt.Errorf("source %q: its plugin's Name is %q; a plugin is named by its source's id", id, s.Plugin.Name())
case !slices.Contains(Layers(), s.Layer):
Expand All @@ -210,6 +219,9 @@ func (p Provider) check() error {
case s.Kind != "" && s.Kind != KindOf(s.Plugin):
return fmt.Errorf("source %q: Kind %q, but its plugin is in kinds/%s", id, s.Kind, KindOf(s.Plugin))
}
if err := s.Shape.check(shape(s.Plugin)); err != nil {
return fmt.Errorf("source %q: %w", id, err)
}
for _, u := range s.URLs {
if !absolute(u) {
return fmt.Errorf("source %q: URL %q isn't absolute", id, u)
Expand Down Expand Up @@ -240,6 +252,11 @@ func shape(p Plugin) string {
return ""
}

func isGuarded(p Plugin) bool {
_, ok := p.(Guarded)
return ok
}

func absolute(u string) bool {
parsed, err := url.Parse(u)
return err == nil && (parsed.Scheme == "https" || parsed.Scheme == "http") && parsed.Host != ""
Expand Down
30 changes: 30 additions & 0 deletions core/plugin/provider_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,16 @@ type fake struct{ name string }
func (f fake) Name() string { return f.name }
func (fake) Read(context.Context, Env, Snapshot) (Snapshot, error) { return Snapshot{}, nil }
func (fake) Extract(context.Context, Env, Snapshot, Snapshot) (Result, error) { return Result{}, nil }
func (f fake) WithShape(Shape) Plugin { return f }

// unguarded is a living plugin that doesn't run the shape guard: refused.
type unguarded struct{ name string }

func (u unguarded) Name() string { return u.name }
func (unguarded) Read(context.Context, Env, Snapshot) (Snapshot, error) { return Snapshot{}, nil }
func (unguarded) Extract(context.Context, Env, Snapshot, Snapshot) (Result, error) {
return Result{}, nil
}

// both is a plugin that is Versioned and Living: refused.
type both struct{ fake }
Expand Down Expand Up @@ -97,6 +107,26 @@ func TestRegisterProviderRefusesIncompleteMetadata(t *testing.T) {
s.Plugin = neither{"x9/api"}
return s
}()}},
"no shape guard": {ID: "x11", Name: "X", Category: CategoryAI, Homepage: "https://x.example", Sources: []Source{func() Source {
s := src("api", "x11")
s.Plugin = unguarded{"x11/api"}
return s
}()}},
"undated anchor": {ID: "x12", Name: "X", Category: CategoryAI, Homepage: "https://x.example", Sources: []Source{func() Source {
s := src("api", "x12")
s.Shape.Anchors = []Anchor{{Entry: "gpt-4"}}
return s
}()}},
"three anchors": {ID: "x13", Name: "X", Category: CategoryAI, Homepage: "https://x.example", Sources: []Source{func() Source {
s := src("api", "x13")
s.Shape.Anchors = []Anchor{{"a", "2026-11-21"}, {"b", "2026-11-21"}, {"c", "2026-11-21"}}
return s
}()}},
"ratio above 1": {ID: "x14", Name: "X", Category: CategoryAI, Homepage: "https://x.example", Sources: []Source{func() Source {
s := src("api", "x14")
s.Shape.MinRatio = 1.5
return s
}()}},
"wrong page": {ID: "x10", Name: "X", Category: CategoryAI, Homepage: "https://x.example", Sources: []Source{func() Source {
s := src("api", "x10")
s.Page = "providers/x10.md" // not providers/x10/README.md
Expand Down
162 changes: 162 additions & 0 deletions core/plugin/shape.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
package plugin

import (
"errors"
"fmt"
"regexp"
"strings"
)

// ErrShapeChanged is what a plugin returns, wrapped, when a read doesn't look
// like the source it reads any more: a page that lost most of what the read
// before found, a page without an entry its source declares it always has
// (an anchor), or a versioned source whose newest releases all have nothing
// to read after ones that did. The source most likely changed its layout, or
// something else is served in its place, so the read is refused: never
// stored, never read as removals. errors.Is finds it through any wrapping,
// and whoever runs the plugin reports it (patch-it's hosted ingestion
// service opens an issue in this repo).
var ErrShapeChanged = errors.New("the source's shape changed")

// Shape is what a source declares about its own reads, for the shape guard
// every kind runs (Guarded). The zero value is the kind's defaults, which fit
// most sources: a source sets a field only with a reason, in a comment next
// to it in its provider.go.
type Shape struct {
// MinRatio: a read that finds fewer than MinRatio times what the read
// before found fails with ErrShapeChanged. 0 is the kind's default (its
// DefaultMinRatio). Compared only when the read before found at least
// MinItemsCompared; a read that finds nothing after one that found
// anything always fails.
MinRatio float64
// Anchors are one or two entries a living source's page always lists,
// so a read without one fails with ErrShapeChanged. Each is declared by
// hand after checking the live page, with the date checked: never taken
// from a saved copy. Living sources only.
Anchors []Anchor
// NothingToReadAfter: a versioned source whose newest this many releases
// in a row have nothing to read (ErrNothingToRead), after one that had
// something, is a shape signal (NothingToRead). 0 is
// DefaultNothingToReadAfter.
NothingToReadAfter int
}

// Anchor is one entry a living page always lists, as its kind's reader names
// an entry (a model id on a deprecations page, an API version on an
// end-of-life table, the feed's own title or an entry's title on a feed).
type Anchor struct {
Entry string
// Checked is the day the entry was seen on the live page: YYYY-MM-DD.
Checked string
}

const (
// MinItemsCompared is the smallest read before that MinRatio is
// compared with: below it, a few legitimate removals are a large share.
MinItemsCompared = 10
// DefaultNothingToReadAfter is Shape.NothingToReadAfter's default.
DefaultNothingToReadAfter = 3
// MaxAnchors is how many anchors a source may declare: one or two
// entries that won't leave the page, not a copy of it.
MaxAnchors = 2
)

// Guarded is a plugin that runs the shape guard with its source's Shape.
// Every kind is one: RegisterProvider refuses a plugin that isn't, and hands
// each registered plugin its source's Shape through WithShape. A plugin
// built by hand and never given a Shape (a golden test over trimmed copies,
// far smaller than the real releases) runs no guard: the guard's methods
// are nil-safe, and a kind keeps a *Shape that is nil until WithShape.
type Guarded interface {
Plugin
// WithShape is the plugin with s as its source's Shape.
WithShape(s Shape) Plugin
}

// CheckCount is the shape guard on how much a read found: now items, against
// before found by the read before (before < 0: there was none). kindDefault
// is the kind's ratio, used when the source sets none. what names the items
// for the error ("operations", "retirements").
func (s *Shape) CheckCount(what string, kindDefault float64, before, now int) error {
if s == nil || before <= 0 {
return nil
}
if now == 0 {
return fmt.Errorf("%w: the read found no %s, the read before found %d", ErrShapeChanged, what, before)
}
ratio := s.MinRatio
if ratio == 0 {
ratio = kindDefault
}
if before >= MinItemsCompared && float64(now) < ratio*float64(before) {
return fmt.Errorf("%w: the read found %d %s, the read before found %d (less than %.0f%%)", ErrShapeChanged, now, what, before, ratio*100)
}
return nil
}

// CheckAnchors is the shape guard on what a read found: every anchor the
// source declares must be among it (has).
func (s *Shape) CheckAnchors(has func(entry string) bool) error {
if s == nil {
return nil
}
var missing []string
for _, a := range s.Anchors {
if !has(a.Entry) {
missing = append(missing, fmt.Sprintf("%q (seen on %s)", a.Entry, a.Checked))
}
}
if len(missing) > 0 {
return fmt.Errorf("%w: the page no longer lists %s", ErrShapeChanged, strings.Join(missing, ", "))
}
return nil
}

// NothingToRead is the shape guard on a versioned source's releases, for
// whoever runs it: read says, for each release extracted, oldest first,
// whether it had something to read (false: ErrNothingToRead). When the newest
// NothingToReadAfter (or more) in a row had nothing, after one that had
// something, the source probably moved its changelog or guide or changed its
// layout: the error wraps ErrShapeChanged, not ErrNothingToRead. A source
// that has never had anything to read isn't flagged: nothing says it ever
// could be.
func (s Shape) NothingToRead(read []bool) error {
n := s.NothingToReadAfter
if n == 0 {
n = DefaultNothingToReadAfter
}
run := 0
for i := len(read) - 1; i >= 0; i-- {
if read[i] {
if run >= n {
return fmt.Errorf("%w: the newest %d releases in a row have nothing to read, after one that had", ErrShapeChanged, run)
}
return nil
}
run++
}
return nil
}

var day = regexp.MustCompile(`^\d{4}-\d{2}-\d{2}$`)

// check is what a Shape must be, for a source of the given shape ("living"
// or "versioned").
func (s Shape) check(shape string) error {
switch {
case s.MinRatio < 0 || s.MinRatio > 1:
return fmt.Errorf("Shape.MinRatio %v isn't between 0 and 1", s.MinRatio)
case s.NothingToReadAfter < 0:
return fmt.Errorf("Shape.NothingToReadAfter %d is negative", s.NothingToReadAfter)
case len(s.Anchors) > MaxAnchors:
return fmt.Errorf("%d anchors, at most %d", len(s.Anchors), MaxAnchors)
case len(s.Anchors) > 0 && shape != "living":
return errors.New("anchors are for living pages; a versioned source's releases are guarded by count and NothingToRead")
}
for _, a := range s.Anchors {
if strings.TrimSpace(a.Entry) == "" || !day.MatchString(a.Checked) {
return fmt.Errorf("anchor %q: an entry and the day it was checked (YYYY-MM-DD) are both required", a.Entry)
}
}
return nil
}
Loading
Loading