specoracle

package
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 16, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Overview

Package specoracle keeps a local, gitignored cache of the OpenAPI blocks JFrog embeds on each docs.jfrog.com endpoint page and compares them with the specs this project authors under api/. JFrog's definitions are proprietary, so the cache is a test oracle only: it is fetched on demand, never committed, and the committed artefact is the parity baseline, which lists only paths, field names and status codes (decision record 0001).

Role

devtools layer: the library behind tools/specoracle, whose subcommands the Makefile's oracle targets run, and behind TestAccSpecParity in api/; never linked into the server binary. It imports only the standard library and gopkg.in/yaml.v3.

Inputs

  • Fetch: the llms.txt index of each API family and the endpoint pages it lists, over HTTP. By default 4 pages at a time, each after a 200 ms pause, with up to 3 attempts on 429, 5xx and transport errors and a backoff that doubles from that pause, under a user agent that names this project. When a family's index fails, the parent llms.txt one directory up, in the section that lists the most pages an earlier fetch found for the family (FetchOptions.Known, which tools/specoracle reads from api/oracle-inventory.json).
  • The cache directory, .specoracle by convention: one <family>/<page>.json file per block, and manifest.json (Load, BuildInventory, Scaffold).
  • Our bundled specs, api/*.openapi.yaml (LoadOurs), and the accepted gaps, api/parity-baseline.json (ReadBaseline).

Outputs

  • The cache and its Manifest: each page's file, status and checksum, or why it was skipped or failed, and each family's record: which index its pages came from, or why none did (CheckFamilies).
  • A Report: the operations JFrog documents that we do not define, divergent operations with their findings, matched operations and our extras, with a per-family Summary and a String that diffs cleanly.
  • api/parity-baseline.json (WriteBaseline), and the Diff of a report against it: regressions and improvements.
  • The Inventory of every named schema, field, enum, parameter and operation in the cache, as api/oracle-inventory.json and the Markdown of research 14.
  • Scaffold: a draft OpenAPI 3.0.3 fragment for one family, every description the TODO(author) Placeholder, and every operation's x-idempotency, x-cost and x-pagination too (decision 0043).

Invariants

  • The cache is never committed, because JFrog's definitions are proprietary. What is committed from it, the baseline, the inventory and scaffolded fragments, holds facts such as paths, field names, types, enums and status codes, never JFrog's prose.
  • The comparison covers only what a client observes on the wire, never descriptions, and both sides pass through one normaliser, so a second parser cannot skew it.
  • An operation, parameter or response marked x-artifactweave-extension: true is left out on both sides: an optional extension JFrog's clients never send or can ignore (#1395), such as the shared 429 and 503 every admitted operation declares, so declaring one never moves the baseline.
  • One bad page never hides the rest: Fetch records a page that fails or has no block in the manifest, and Load records a block that does not parse in the oracle's Errors.
  • A whole family is never dropped without a failure: CheckFamilies names every family the cache holds no block of, with its index URL, and the parity test, the baseline and the inventory refuse such a cache (#1308).
  • A missing baseline file reads as an empty baseline, so a repository that forgot to commit it fails on every gap instead of passing.
  • TestAccSpecParity treats a cache without manifest.json as no cache and skips.

References

  • Decision 0001: docs/research/decisions/0001-mirror-the-jfrog-api-surface.md.
  • Research 01: docs/research/01-jfrog-api-landscape.md#parity-oracle; research 14: docs/research/14-data-model-inventory.md.
  • Plan: docs/implementation/plan.md#p0-foundations, task 10, and #p1-data-model-and-api-schemas, tasks 1 and 3.
  • docs/testing/ci.md: the parity job, which restores or fetches the cache.
  • Target layout: docs/research/architecture-options/5-modular-monolith.md, lines 113 to 116 (the devtools tree) and line 1041 (the mapping row).
  • https://github.com/weaveplatform/artifactweave/issues/990

Status

Implemented P0 (fetch, comparison and baseline) and P1 (inventory and scaffold). Moved here in P9d.

Testing

  • TestUnitExtractBlock, TestUnitParseIndexAndSlugs: a page's embedded block, an index's links, and the cache's file names.
  • TestAccFetchWritesCacheAndManifest: against a local HTTP server, pages with a block are cached, a page without one, a 404 and an index that keeps failing are recorded, and a flaky page succeeds on retry. TestAccFetchErrors: no index, no cache directory, a cancelled context.
  • TestAccFetchTakesAFailedFamilyIndexFromItsParent, TestAccFetchRecordsEachFamilyNoSourceGave: against a chi model of docs.jfrog.com, a family whose index answers 404 or keeps failing is fetched from its parent section, and each way the fallback can fail leaves the family missing and named by CheckFamilies. TestUnitCheckFamiliesReadsTheManifest, TestUnitKnownPagesReadsTheInventory, TestUnitParentURLAndSections.
  • TestUnitLoadAndCompare, TestUnitLoadOursErrors, TestUnitAddMergesOperationsSharingAKey: both sides load through one normaliser, a broken block becomes a parse error while a spec that cannot be read fails, two pages that document one route merge, and the report, summary and text agree.
  • TestUnitLoadOursSkipsExtensions: an operation, a parameter and a response marked as an extension are not compared.
  • TestUnitBaselineRoundTrip: a written baseline reads back, Diff splits regressions from improvements, and an absent file reads as empty.
  • TestUnitBuildInventory, TestUnitManifestSourcesDegrades, TestUnitScaffold, TestUnitScaffoldHelpers, TestUnitHelpers.

TestAccSpecParity in api/parity_test.go runs the comparison on the real specs against the cache and api/parity-baseline.json.

Index

Constants

View Source
const DefaultUserAgent = "artifactweave-specoracle (https://github.com/weaveplatform/artifactweave)"

DefaultUserAgent identifies the fetcher to docs.jfrog.com so a polite operator can find us if the crawl misbehaves.

View Source
const ManifestFile = "manifest.json"

ManifestFile is the name of the manifest written into the cache directory. Its presence is how TestAccSpecParity decides whether a cache exists.

View Source
const Placeholder = "TODO(author)"

Placeholder is written into every description a scaffolded fragment carries. TestAccOpenAPIFieldDescriptions rejects it once the fragment loses its x-draft marker, so an author cannot ship a scaffold by accident.

Variables

View Source
var (
	// ErrMissingFamily is wrapped once for each family CheckFamilies finds
	// missing.
	ErrMissingFamily = errors.New("specoracle: API family missing from the oracle cache")
	// ErrNoFamilies marks a manifest written before Fetch recorded families,
	// which cannot show whether one is missing.
	ErrNoFamilies = errors.New("specoracle: manifest records no API families")
)
View Source
var (

	// ErrBadStatus is wrapped around unexpected HTTP statuses.
	ErrBadStatus = errors.New("specoracle: unexpected http status")
)

Sentinel errors, wrapped with context where they are returned.

Functions

func CheckFamilies

func CheckFamilies(cacheDir string) error

CheckFamilies returns an error naming each family, with its index URL and what went wrong, that the cache in cacheDir lacks. Every family Fetch is given was fetched when it was added, so a missing one is a docs or network fault, not a family JFrog dropped. The parity test and the commands that rewrite committed files from the cache refuse such a cache: comparing it reports the family's baseline entries as improvements, and rewriting the baseline from it would delete them (#1308).

func ExtractBlock

func ExtractBlock(page string) ([]byte, bool)

ExtractBlock finds the OpenAPI document embedded in an endpoint page. The pages carry it under an "OpenAPI definition" heading as a fenced json block; older renderings inline the JSON. Both are handled, and HTML entities are decoded because some pages escape angle brackets inside descriptions. The returned bytes are compacted JSON so cache hashes are stable across whitespace changes on the site.

func FamilySlug

func FamilySlug(index string) string

FamilySlug turns an index URL into a directory name, dropping the host, the "reference" segment and the llms.txt file name: https://docs.jfrog.com/artifactory/reference/jfrog-artifactory-repositories-api/llms.txt becomes artifactory-jfrog-artifactory-repositories-api.

func KnownPages

func KnownPages(inventoryPath string) (map[string][]string, error)

KnownPages reads, from an inventory WriteJSON wrote, the page URLs of each family. The inventory is committed, so it records a good fetch even where the cache starts empty, as it does each week in CI. A missing file gives no pages and no error, which only turns the fallback off.

func NormalisePath

func NormalisePath(p string) string

NormalisePath replaces every {name} with {} so differently named path parameters still match.

func PageSlug

func PageSlug(pageURL string) string

PageSlug is the last path segment of a page URL without its .md suffix.

func ParseIndex

func ParseIndex(body string) [][2]string

ParseIndex extracts (title, url) pairs from an llms.txt body.

Types

type Baseline

type Baseline struct {
	Missing   []string            `json:"missing"`
	Divergent map[string][]string `json:"divergent"`
}

Baseline is the committed list of accepted gaps. It names only operation keys and finding strings (paths, field names, status codes), never JFrog's text, so it can live in the repository while the cache cannot.

func ReadBaseline

func ReadBaseline(path string) (Baseline, error)

ReadBaseline loads a baseline file. A missing file is an empty baseline, which makes every documented operation a regression: that is the right failure mode for a repository that forgot to commit the file.

type ContentRecord

type ContentRecord struct {
	Media  string `json:"media"`
	Schema string `json:"schema,omitempty"`
}

ContentRecord names the schema behind one media type.

type Diff

type Diff struct {
	Regressions  []string
	Improvements []string
}

Diff splits the report against a baseline into regressions (new gaps) and improvements (baseline entries that no longer apply and can be removed).

type FamilyRecord

type FamilyRecord struct {
	Index  string `json:"index"`
	Family string `json:"family"`
	// Source is the llms.txt whose links were fetched: Index itself, or the
	// parent index when Index failed. Empty when neither gave the pages.
	Source string `json:"source,omitempty"`
	// Section is the parent index heading the pages were taken from.
	Section string `json:"section,omitempty"`
	// Error says why Index gave no pages. It stays set when the parent index
	// stood in, so the fetch still reports the broken family index.
	Error string `json:"error,omitempty"`
}

FamilyRecord says where the page list of one API family came from.

type FamilySummary

type FamilySummary struct {
	Family    string
	Total     int
	Missing   int
	Divergent int
	Matched   int
}

FamilySummary is one row of Summary.

type FetchOptions

type FetchOptions struct {
	// Indexes are llms.txt URLs; each lists endpoint pages as "- [Title](url): text".
	Indexes []string
	// CacheDir receives <index-slug>/<page-slug>.json files and the manifest.
	CacheDir string
	// Client is used for every request; nil means http.DefaultClient with a timeout.
	Client *http.Client
	// Concurrency bounds parallel page fetches (default 4).
	Concurrency int
	// Delay is the pause before each page request (default 200 ms).
	Delay time.Duration
	// UserAgent overrides DefaultUserAgent.
	UserAgent string
	// Retries is the number of attempts on 429 and 5xx responses (default 3).
	Retries int
	// Known maps a family slug to page URLs an earlier good fetch found for
	// that family. When the family's own index fails, they pick its section
	// of the parent index (see fetchFamily); without them a failed index
	// leaves the family missing.
	Known map[string][]string
}

FetchOptions configures Fetch. Zero values pick polite defaults.

type Inventory

type Inventory struct {
	GeneratedAt time.Time      `json:"generated_at"`
	Pages       int            `json:"pages"`
	Schemas     []SchemaRecord `json:"schemas"`
	Operations  []OpRecord     `json:"operations"`
	Errors      []string       `json:"errors,omitempty"`
}

Inventory is what `specoracle inventory` writes.

func BuildInventory

func BuildInventory(cacheDir string) (Inventory, error)

BuildInventory extracts schemas and operations from every cached block.

func (Inventory) WriteJSON

func (i Inventory) WriteJSON(path string) error

WriteJSON writes the inventory as indented JSON.

func (Inventory) WriteMarkdown

func (i Inventory) WriteMarkdown(path string) error

WriteMarkdown writes the human-readable inventory: one operations table and one fields table per family, no prose from the source.

type Manifest

type Manifest struct {
	FetchedAt time.Time `json:"fetched_at"`
	UserAgent string    `json:"user_agent"`
	// Families has one record per index Fetch was given, so a family that
	// yielded no page is still on record (Missing, CheckFamilies).
	Families []FamilyRecord  `json:"families"`
	Entries  []ManifestEntry `json:"entries"`
}

Manifest is written as manifest.json and lists what the cache holds.

func Fetch

func Fetch(ctx context.Context, opts FetchOptions) (Manifest, error)

Fetch downloads every endpoint page listed by the indexes, extracts the embedded OpenAPI block and writes it into CacheDir. Pages without a block and transport failures are recorded in the manifest rather than aborting, because the docs site changes and a single bad page must not hide the rest. A family whose index fails is recorded in Families, and its pages come from the parent index where Known identifies them.

func ReadManifest

func ReadManifest(cacheDir string) (Manifest, error)

ReadManifest reads the manifest Fetch wrote into cacheDir.

func (Manifest) Blocks

func (m Manifest) Blocks() int

Blocks returns the number of entries with a cached OpenAPI block.

func (Manifest) Missing

func (m Manifest) Missing() []FamilyRecord

Missing lists the families of which the cache holds no OpenAPI block. Load reads only what is cached, so the comparison cannot tell such a family from one JFrog stopped documenting.

type ManifestEntry

type ManifestEntry struct {
	Index   string `json:"index"`
	Family  string `json:"family"`
	Title   string `json:"title"`
	URL     string `json:"url"`
	File    string `json:"file,omitempty"`
	Status  int    `json:"status,omitempty"`
	SHA256  string `json:"sha256,omitempty"`
	Skipped string `json:"skipped,omitempty"`
	Error   string `json:"error,omitempty"`
}

ManifestEntry records one page of one index.

type OpRecord

type OpRecord struct {
	Key        string                     `json:"key"`
	Family     string                     `json:"family"`
	Tag        string                     `json:"tag,omitempty"`
	ID         string                     `json:"id,omitempty"`
	Method     string                     `json:"method"`
	Path       string                     `json:"path"`
	Source     string                     `json:"source"`
	Params     []ParamRecord              `json:"params,omitempty"`
	Request    []ContentRecord            `json:"request,omitempty"`
	Responses  map[string][]ContentRecord `json:"responses"`
	Deprecated bool                       `json:"deprecated,omitempty"`
}

OpRecord is one documented operation.

type Operation

type Operation struct {
	// Key is "METHOD /full/path" with every path parameter name replaced by
	// {}, because clients never see parameter names.
	Key          string
	Family       string
	Source       string
	ID           string
	Method       string
	Path         string
	Params       []Param
	RequestMedia []string
	RequestProps []string
	// Responses maps a status code to the property paths of its JSON body.
	Responses  map[string][]string
	Deprecated bool
}

Operation is one method on one full path, flattened to what matters for wire compatibility. Property paths use "a.b" for nested objects and "a[].b" for array items.

type Oracle

type Oracle struct {
	Ops    map[string]Operation
	Errors []string
}

Oracle is a set of operations plus the parse problems met while loading.

func Load

func Load(cacheDir string) (Oracle, error)

Load reads every cached block under cacheDir. A block that fails to parse is recorded in Errors and skipped: one bad page must not hide the rest. The cache is exactly two levels deep (family/page.json), so a plain directory listing is enough and avoids walking symlinks.

func LoadOurs

func LoadOurs(paths ...string) (Oracle, error)

LoadOurs reads the project's own YAML specs the same way, so both sides go through one normaliser and the comparison cannot be skewed by a second parser.

type Param

type Param struct {
	Name     string
	In       string
	Required bool
	Type     string
	Enum     []string
}

Param is a normalised parameter.

type ParamRecord

type ParamRecord struct {
	Name     string   `json:"name"`
	In       string   `json:"in"`
	Required bool     `json:"required,omitempty"`
	Type     string   `json:"type,omitempty"`
	Enum     []string `json:"enum,omitempty"`
	Default  any      `json:"default,omitempty"`
}

ParamRecord is an operation parameter with the facts clients depend on.

type Report

type Report struct {
	// Missing lists operation keys JFrog documents that we do not define.
	Missing []string
	// Divergent maps an operation key to the findings against our definition.
	Divergent map[string][]string
	// Matched lists keys we define with no findings.
	Matched []string
	// Extra lists keys we define that JFrog does not document (probes, stubs).
	Extra []string
	// Families records the family of every JFrog key, for the summary.
	Families map[string]string
	// Errors carries parse problems from either side.
	Errors []string
}

Report is the outcome of comparing JFrog's operations with ours.

func Compare

func Compare(theirs, ours Oracle) Report

Compare checks every documented operation against ours. Descriptions are never compared: only what a client can observe on the wire.

func (Report) Diff

func (r Report) Diff(b Baseline) Diff

Diff compares the report with the accepted baseline.

func (Report) String

func (r Report) String() string

String renders the report in a stable order so it can be diffed.

func (Report) Summary

func (r Report) Summary() []FamilySummary

Summary counts outcomes per documentation family, sorted by family.

func (Report) WriteBaseline

func (r Report) WriteBaseline(path string) error

WriteBaseline records the report's current gaps as the accepted baseline.

type ScaffoldOptions

type ScaffoldOptions struct {
	// CacheDir is the oracle cache.
	CacheDir string
	// Family is the cache directory (index slug) to scaffold.
	Family string
	// ServiceBase is our service prefix, for example "/artifactory". Only
	// operations whose full path starts with it are emitted; the rest are
	// listed in Result.Skipped so the author can scaffold them elsewhere.
	ServiceBase string
	// Tag is written on every operation; defaults to the family's last word.
	Tag string
	// SkipSchemas are component names the service already defines (the shared
	// error envelope, for instance); references are kept but the schema is not
	// emitted again.
	SkipSchemas []string
}

ScaffoldOptions selects what to scaffold and how to name it.

type ScaffoldResult

type ScaffoldResult struct {
	YAML       []byte
	Operations int
	Schemas    int
	// Skipped lists operation keys outside ServiceBase.
	Skipped []string
	// Renamed maps original schema names to the family-prefixed names used
	// because another family defines the same name with a different shape.
	Renamed map[string]string
}

ScaffoldResult reports what was written and what the author must resolve.

func Scaffold

func Scaffold(opts ScaffoldOptions) (ScaffoldResult, error)

Scaffold converts every block of one family into an OpenAPI 3.0.3 fragment (paths plus components) with placeholder descriptions. Structure is a fact about the wire protocol; prose is not, so none of JFrog's is carried over.

type SchemaField

type SchemaField struct {
	Name     string   `json:"name"`
	Type     string   `json:"type,omitempty"`
	Format   string   `json:"format,omitempty"`
	Ref      string   `json:"ref,omitempty"`
	Items    string   `json:"items,omitempty"`
	Enum     []string `json:"enum,omitempty"`
	Required bool     `json:"required,omitempty"`
	ReadOnly bool     `json:"read_only,omitempty"`
	// WriteOnly marks fields JFrog accepts but never returns, such as passwords.
	WriteOnly bool `json:"write_only,omitempty"`
	Nullable  bool `json:"nullable,omitempty"`
	Default   any  `json:"default,omitempty"`
}

SchemaField is one property of a named schema.

type SchemaRecord

type SchemaRecord struct {
	Family   string        `json:"family"`
	Name     string        `json:"name"`
	Type     string        `json:"type,omitempty"`
	Composed []string      `json:"composed,omitempty"`
	Fields   []SchemaField `json:"fields,omitempty"`
	Variants int           `json:"variants"`
	UsedBy   int           `json:"used_by"`
}

SchemaRecord is a named component schema within one family. Variants counts the distinct shapes the same name has across that family's blocks; anything above one means authors must look at both pages before trusting the fields.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL