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
134 changes: 134 additions & 0 deletions adapter/algolia.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
package adapter

import (
"context"
"encoding/json"
"fmt"
"regexp"
"strings"
"time"

"github.com/patch-it-dev/patch-it-plugins/fetch"
"gopkg.in/yaml.v3"
)

// Variables, not constants, only so tests can point them at a local server.
var (
// algoliaRefsURL lists every release tag of algolia/api-clients-automation,
// "released-2026-11-17-31c309fe2a" (or "released-2023-08-22" before
// 2024): the date, then the commit.
algoliaRefsURL = "https://api.github.com/repos/algolia/api-clients-automation/git/matching-refs/tags/released-"
// algoliaCommitURL is one tag's commit, for its date.
algoliaCommitURL = "https://api.github.com/repos/algolia/api-clients-automation/commits/%s"
// algoliaSpecURLTemplate is one API's bundled spec at one release tag: the
// spec Algolia generates its API clients from.
algoliaSpecURLTemplate = "https://raw.githubusercontent.com/algolia/api-clients-automation/%s/specs/bundled/%s.yml"
)

// Algolia adapts one of Algolia's REST API specs (Spec: "search",
// "ingestion", "recommend") in algolia/api-clients-automation for the openapi
// plugin, release by release.
type Algolia struct {
Spec string
}

var _ Adapter = Algolia{}

func (a Algolia) API() string { return "algolia-" + a.Spec }

var algoliaTag = regexp.MustCompile(`^released-(\d{4}-\d{2}-\d{2})(-[0-9a-f]+)?$`)

// LatestTag is the newest release tag. The name sorts by day, but a day can
// have several releases (three on 2024-09-19) whose commit suffix says
// nothing about their order, so those are told apart by their commit's date.
func (a Algolia) LatestTag(ctx context.Context) (string, error) {
body, err := fetch.Get(ctx, algoliaRefsURL, githubHeaders())
if err != nil {
return "", fmt.Errorf("listing algolia's release tags: %w", err)
}
var refs []struct {
Ref string `json:"ref"`
}
if err := json.Unmarshal(body, &refs); err != nil {
return "", fmt.Errorf("parsing github's tag refs: %w", err)
}
var day string
var sameDay []string
for _, r := range refs {
tag := strings.TrimPrefix(r.Ref, "refs/tags/")
m := algoliaTag.FindStringSubmatch(tag)
switch {
case m == nil:
continue
case m[1] > day:
day, sameDay = m[1], []string{tag}
case m[1] == day:
sameDay = append(sameDay, tag)
}
}
if len(sameDay) == 0 {
return "", fmt.Errorf("github lists no algolia release tag")
}
if len(sameDay) == 1 {
return sameDay[0], nil
}
var latest string
var latestAt time.Time
for _, tag := range sameDay {
at, err := algoliaCommitDate(ctx, tag)
if err != nil {
return "", err
}
if at.After(latestAt) {
latest, latestAt = tag, at
}
}
return latest, nil
}

func algoliaCommitDate(ctx context.Context, tag string) (time.Time, error) {
body, err := fetch.Get(ctx, fmt.Sprintf(algoliaCommitURL, tag), githubHeaders())
if err != nil {
return time.Time{}, fmt.Errorf("looking up algolia tag %s: %w", tag, err)
}
var c struct {
Commit struct {
Committer struct {
Date time.Time `json:"date"`
} `json:"committer"`
} `json:"commit"`
}
if err := json.Unmarshal(body, &c); err != nil || c.Commit.Committer.Date.IsZero() {
return time.Time{}, fmt.Errorf("algolia tag %s: no commit date", tag)
}
return c.Commit.Committer.Date, nil
}

// Fetch downloads the spec at tag and converts it from YAML to JSON, which is
// what diff.Parse reads (as for Datadog; the excerpts are re-serialized from
// the node either way).
//
// Version is the release's date from the tag (2026-11-17): Algolia's REST API
// has no version beyond the /1/ in its paths, and each API client has its own
// version numbers, so the day the spec was released is the closest thing to
// "the API version the change arrived in".
func (a Algolia) Fetch(ctx context.Context, tag string) (Spec, error) {
m := algoliaTag.FindStringSubmatch(tag)
if m == nil {
return Spec{}, fmt.Errorf("%q isn't an algolia release tag", tag)
}
url := fmt.Sprintf(algoliaSpecURLTemplate, tag, a.Spec)
body, err := fetch.Get(ctx, url, nil) // raw.githubusercontent.com needs no auth
if err != nil {
return Spec{}, fmt.Errorf("fetching algolia %s spec %s: %w", a.Spec, tag, err)
}
var doc any
if err := yaml.Unmarshal(body, &doc); err != nil {
return Spec{}, fmt.Errorf("parsing algolia %s spec %s as yaml: %w", a.Spec, tag, err)
}
content, err := json.Marshal(doc)
if err != nil {
return Spec{}, fmt.Errorf("converting algolia %s spec %s to json: %w", a.Spec, tag, err)
}
return Spec{Content: content, Version: m[1], SourceURL: url}, nil
}
108 changes: 108 additions & 0 deletions adapter/algolia_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
package adapter

import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
)

func fakeAlgoliaGitHub(t *testing.T, refs string, commitDates, specs map[string]string) {
t.Helper()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/refs":
w.Write([]byte(refs))
case strings.HasPrefix(r.URL.Path, "/commits/"):
d, ok := commitDates[strings.TrimPrefix(r.URL.Path, "/commits/")]
if !ok {
http.NotFound(w, r)
return
}
w.Write([]byte(`{"commit":{"committer":{"date":"` + d + `"}}}`))
default:
body, ok := specs[r.URL.Path]
if !ok {
http.NotFound(w, r)
return
}
w.Write([]byte(body))
}
}))
t.Cleanup(srv.Close)
oldRefs, oldCommit, oldSpec := algoliaRefsURL, algoliaCommitURL, algoliaSpecURLTemplate
algoliaRefsURL = srv.URL + "/refs"
algoliaCommitURL = srv.URL + "/commits/%s"
algoliaSpecURLTemplate = srv.URL + "/%s/%s.yml"
t.Cleanup(func() { algoliaRefsURL, algoliaCommitURL, algoliaSpecURLTemplate = oldRefs, oldCommit, oldSpec })
}

func refs(tags ...string) string {
var parts []string
for _, t := range tags {
parts = append(parts, `{"ref":"refs/tags/`+t+`","object":{"type":"commit"}}`)
}
return "[" + strings.Join(parts, ",") + "]"
}

func TestAlgoliaLatestTagIsTheNewestDay(t *testing.T) {
fakeAlgoliaGitHub(t, refs("released-2023-08-22", "released-2026-11-17-31c309fe2a", "released-2026-11-10-8d91e3d8a3", "v4.0.0"), nil, nil)
tag, err := Algolia{Spec: "search"}.LatestTag(context.Background())
if err != nil || tag != "released-2026-11-17-31c309fe2a" {
t.Errorf("got %q, %v", tag, err)
}
}

// Three releases on 2024-09-19: the suffix is a commit, so its order means
// nothing; the commit dates decide (a62c27d3b 10:17, 6e91dbf55 13:16,
// e47df6533 19:28, checked 2026-11-19).
func TestAlgoliaLatestTagBreaksASameDayTieByCommitDate(t *testing.T) {
fakeAlgoliaGitHub(t, refs("released-2024-09-19-6e91dbf55", "released-2024-09-19-e47df6533", "released-2024-09-19-a62c27d3b"), map[string]string{
"released-2024-09-19-6e91dbf55": "2024-09-19T13:16:52Z",
"released-2024-09-19-a62c27d3b": "2024-09-19T10:17:21Z",
"released-2024-09-19-e47df6533": "2024-09-19T19:28:05Z",
}, nil)
tag, err := Algolia{Spec: "search"}.LatestTag(context.Background())
if err != nil || tag != "released-2024-09-19-e47df6533" {
t.Errorf("got %q, %v; want the 19:28 release", tag, err)
}
}

func TestAlgoliaLatestTagFailures(t *testing.T) {
fakeAlgoliaGitHub(t, refs("v4.0.0"), nil, nil)
if _, err := (Algolia{Spec: "search"}).LatestTag(context.Background()); err == nil {
t.Error("no release tag: want an error")
}
fakeAlgoliaGitHub(t, refs("released-2024-09-19-6e91dbf55", "released-2024-09-19-a62c27d3b"), nil, nil)
if _, err := (Algolia{Spec: "search"}).LatestTag(context.Background()); err == nil {
t.Error("a same-day tie without commit dates: want an error, not a guess")
}
}

// The version is the release's date; the YAML is converted to JSON.
func TestAlgoliaFetch(t *testing.T) {
fakeAlgoliaGitHub(t, "", nil, map[string]string{
"/released-2025-04-01-c19ee6afb/search.yml": "openapi: 3.0.2\ninfo:\n title: Search API\npaths:\n /1/clusters:\n get:\n deprecated: true\n",
})
spec, err := Algolia{Spec: "search"}.Fetch(context.Background(), "released-2025-04-01-c19ee6afb")
if err != nil {
t.Fatal(err)
}
want := `{"info":{"title":"Search API"},"openapi":"3.0.2","paths":{"/1/clusters":{"get":{"deprecated":true}}}}`
if spec.Version != "2025-04-01" || string(spec.Content) != want || !strings.HasSuffix(spec.SourceURL, "/released-2025-04-01-c19ee6afb/search.yml") {
t.Errorf("got %q %s %s", spec.Version, spec.Content, spec.SourceURL)
}
if (Algolia{Spec: "search"}).API() != "algolia-search" {
t.Error("api slug")
}
for _, tag := range []string{"v4.0.0", "released-2025-04-01-c19ee6afb-x", "released-xx"} {
if _, err := (Algolia{Spec: "search"}).Fetch(context.Background(), tag); err == nil {
t.Errorf("%s: want an error", tag)
}
}
fakeAlgoliaGitHub(t, "", nil, map[string]string{"/released-2025-04-01/search.yml": "not: [valid: yaml"})
if _, err := (Algolia{Spec: "search"}).Fetch(context.Background(), "released-2025-04-01"); err == nil {
t.Error("invalid yaml: want an error")
}
}
3 changes: 3 additions & 0 deletions docs/plugins.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ The table between the `plugins:start` and `plugins:end` markers is also publishe
| [`gitlab`](https://github.com/patch-it-dev/patch-it-plugins/blob/main/providers/gitlab.md) | GitLab | REST API changes between releases, request side only (what callers send) | `openapi` | [gitlab-org/gitlab `doc/api/openapi`](https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/api/openapi) | live |
| [`vercel`](https://github.com/patch-it-dev/patch-it-plugins/blob/main/providers/vercel.md) | Vercel | REST API operations deprecated, and deprecated operations removed, between SDK releases of the spec | `openapi` | [vercel/sdk](https://github.com/vercel/sdk) (`vercel-spec.json`) | paused: merged, not in a tagged release yet, so patch-it's hosted ingestion service doesn't run it |
| [`supabase`](https://github.com/patch-it-dev/patch-it-plugins/blob/main/providers/supabase.md) | Supabase | Management API operations deprecated, and deprecated operations removed, between commits of the spec | `openapi` | [supabase/supabase](https://github.com/supabase/supabase) (`apps/docs/spec/api_v1_openapi.json`) | paused: merged, not in a tagged release yet, so patch-it's hosted ingestion service doesn't run it |
| [`algolia-search`](https://github.com/patch-it-dev/patch-it-plugins/blob/main/providers/algolia.md) | Algolia | Search API operations deprecated, and deprecated operations removed, between releases of the spec | `openapi` | [algolia/api-clients-automation](https://github.com/algolia/api-clients-automation) (`specs/bundled/search.yml`) | paused: merged, not in a tagged release yet, so patch-it's hosted ingestion service doesn't run it |
| [`algolia-ingestion`](https://github.com/patch-it-dev/patch-it-plugins/blob/main/providers/algolia.md) | Algolia | Ingestion API operations deprecated, and deprecated operations removed, between releases of the spec | `openapi` | [algolia/api-clients-automation](https://github.com/algolia/api-clients-automation) (`specs/bundled/ingestion.yml`) | paused: merged, not in a tagged release yet, so patch-it's hosted ingestion service doesn't run it |
| [`algolia-recommend`](https://github.com/patch-it-dev/patch-it-plugins/blob/main/providers/algolia.md) | Algolia | Recommend API operations deprecated, and deprecated operations removed, between releases of the spec | `openapi` | [algolia/api-clients-automation](https://github.com/algolia/api-clients-automation) (`specs/bundled/recommend.yml`) | paused: merged, not in a tagged release yet, so patch-it's hosted ingestion service doesn't run it |
| [`mongodb-atlas`](https://github.com/patch-it-dev/patch-it-plugins/blob/main/providers/mongodb-atlas.md) | MongoDB | Atlas Administration API versions deprecated and removed at their sunset date, per endpoint, from MongoDB's own API changelog | `apichangelog` | [mongodb/openapi `changelog/changelog.json`](https://github.com/mongodb/openapi/blob/main/changelog/changelog.json) | paused: merged, not in a tagged release yet, so patch-it's hosted ingestion service doesn't run it |
| [`openai-models`](https://github.com/patch-it-dev/patch-it-plugins/blob/main/providers/openai-models.md) | OpenAI | Model deprecations and shutdown dates (Chat Completions and Responses text models) | `retirements` | [OpenAI deprecations](https://developers.openai.com/api/docs/deprecations) | live |
| [`anthropic-models`](https://github.com/patch-it-dev/patch-it-plugins/blob/main/providers/anthropic-models.md) | Anthropic | Model deprecations and retirement dates (Messages API models) | `retirements` | [Anthropic model deprecations](https://platform.claude.com/docs/en/about-claude/model-deprecations) | live |
Expand Down
49 changes: 49 additions & 0 deletions plugins/openapi/algolia.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package openapi

import "github.com/patch-it-dev/patch-it-plugins/diff"

// algoliaDiff reads Algolia's specs like Supabase's: deprecations by the
// `deprecated` flag, quoting the whole operation, and path templates matched.
var algoliaDiff = diff.Options{PathTemplates: true, QuoteDeprecatedOperation: true}

// algoliaKeep keeps operation deprecations, and removals of operations
// marked deprecated first, of REST operations only. Algolia's specs also
// describe what only its API clients do, and a change to one of those isn't
// an API change:
//
// - helpers, marked `x-helper: true`: /saveObjects, /waitForTask,
// /replaceAllObjects, … (16 in the Search API on 2026-11-17);
// - the "custom request" methods for any path, operationId customGet,
// customPost, customPut and customDelete on /{path} (before 2024-03-25,
// /1{path}).
//
// In every release from 2023-08-22 to 2026-11-17 this keeps 9 Search API
// deprecations (the multi-cluster /1/clusters endpoints, 2025-04-01) and 9
// Ingestion API ones (the /1/tasks endpoints, 2025-01-22, and PUT
// /1/tasks/{taskID}/disable, 2024-07-26). None of the 17 removals in that
// history was deprecated first; 13 were the client-only entries above (the
// custom-request methods in all three specs on 2024-03-25, and /saveObjects).
func algoliaKeep(c diff.Change) bool {
// c.Node is the operation only because algoliaDiff sets
// QuoteDeprecatedOperation (a removal carries the old operation anyway);
// TestAlgoliaClientOnlyFilterThroughTheDiffer pins that.
op, _ := c.Node.(map[string]any)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking. This works only because algoliaDiff sets QuoteDeprecatedOperation. With that option set, diff.go:294 passes the whole operation as Node for an OperationDeprecated. Without it, Node is just the true from deprecated (diff.go:296), so op is nil and clientOnly would quietly let a deprecated helper through.

TestAlgoliaClientOnlyEntriesMakeNoEvent builds the diff.Change by hand, so it wouldn't notice that. You could run that case through diff.Changes(old, new) with algoliaDiff instead, or add a comment here saying this depends on the option.

if clientOnly(op) {
return false
}
return deprecationsOnly(algoliaDiff)(c)
}

// clientOnly is an Algolia spec entry for an API-client method, not a REST
// operation.
func clientOnly(op map[string]any) bool {
if helper, _ := op["x-helper"].(bool); helper {
return true
}
id, _ := op["operationId"].(string)
switch id {
case "customGet", "customPost", "customPut", "customDelete":
return true
}
return false
}
Loading
Loading