apiknowledge

package
v1.172.0 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: Apache-2.0 Imports: 33 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package apiknowledge is a vendor's knowledge for an API catalog (#2880): the archive of pages and automations the catalog's vendor publishes at a URL, read under limits, checked, compared with what is serving, and applied or held for an administrator. It is pulled only while a trusted connection references the catalog, and seen only by a caller whose persona reaches one.

Index

Constants

View Source
const (
	DefaultMaxArchiveBytes    = 20 << 20
	DefaultMaxPages           = 200
	DefaultMaxPageBytes       = 256 << 10
	DefaultMaxAutomations     = 100
	DefaultMaxAutomationBytes = 256 << 10
)

The defaults, and the configuration keys a refusal names.

View Source
const (
	KindPage       = "page"
	KindAutomation = "automation"
)

Kinds of item an archive holds.

View Source
const (
	TriggerSchedule = "schedule"
	TriggerManual   = "manual"
)

Triggers a check records.

View Source
const (
	ChangeApplied   = "applied"
	ChangePending   = "pending"
	ChangeDiscarded = "discarded"
)

Change statuses.

View Source
const (
	Added   = "added"
	Changed = "changed"
	Removed = "removed"
)

Item changes a report names.

View Source
const (
	ResultUnchanged = "unchanged"
	ResultApplied   = "applied"
	ResultHeld      = "held"
	ResultFailed    = "failed"
	ResultUntrusted = "untrusted"
)

Results a check records.

View Source
const (
	StatusServing = "serving"
	StatusHeld    = "held"
	StatusSkipped = "skipped"
)

Item statuses.

View Source
const (
	KindTemplate = "template"
	KindLibrary  = "library"
)

Automation kinds.

View Source
const FormatVersion = 1

FormatVersion is the archive format this platform reads.

View Source
const LockKey int64 = 4713210406

LockKey is the advisory lock a pass holds, so one replica checks at a time.

Variables

View Source
var ErrNotFound = errors.New("not found")

ErrNotFound is a catalog with no knowledge URL, or a template or change that does not exist.

View Source
var ErrUntrusted = errors.New("no connection of this catalog is trusted, so nothing is imported")

ErrUntrusted refuses an Accept while no connection of the catalog is trusted.

Functions

func DisplayURL

func DisplayURL(raw string) string

DisplayURL is the URL without its query, user and fragment: what an error says the archive was fetched from.

func MaskedURL

func MaskedURL(raw string) string

MaskedURL is the URL an administrator is shown: its query's names, each value masked. A name with no value may be the key itself (?<token>), so it is masked whole.

func Scrub

func Scrub(text, raw string) string

Scrub removes the knowledge URL's query, and each value in it as written and escaped, from text, leaving the URL as DisplayURL writes it. Every sentence a check stores or shows passes through it.

func SourceHash

func SourceHash(source string) string

SourceHash is the hash an automation's version is compared by.

func Summary

func Summary(r Report) string

Summary is a report in one paragraph.

func TooLarge

func TooLarge(maxBytes int64) error

TooLarge is the refusal of an archive whose download passed max bytes, naming the key that sets it.

func ValidName

func ValidName(s string) bool

ValidName reports whether s is a vendor automation name.

func ValidSlug

func ValidSlug(s string) bool

ValidSlug reports whether s is a vendor page slug.

func ValidateURL

func ValidateURL(raw string) error

ValidateURL refuses a knowledge URL that is not an absolute http(s) address with a host. Whether http and a private host are allowed is the fetch's guard to decide, as it decides for a spec URL.

Types

type Archive

type Archive struct {
	Vendor      string            `json:"vendor"`
	Entry       string            `json:"entry"`
	Pages       []Page            `json:"pages"`
	Automations []Automation      `json:"automations"`
	Recordings  map[string][]byte `json:"recordings,omitempty"`
}

Archive is a vendor's archive as read: its manifest, its pages and its automations, in name order, and the recorded runs its automations' tests replay, by run id.

func Read

func Read(ctx context.Context, data []byte, lim Limits) (*Archive, error)

Read reads an archive from its bytes under lim, refusing it whole when it passes a limit, holds an unsafe or unexpected entry, or its manifest is missing or wrong.

func (*Archive) Page

func (a *Archive) Page(slug string) *Page

Page is the archive's page with slug, or nil.

type Automation

type Automation struct {
	Name        string         `json:"name"`
	Source      string         `json:"source"`
	Description string         `json:"description,omitempty"`
	Version     int            `json:"version,omitempty"`
	Params      []script.Param `json:"params,omitempty"`
}

Automation is one script: automations/<name>.star, exactly the source a person would save, with what the manifest says of it. Whether it is a template or a library is read from the source; a library names its version, which never changes once published.

type Backend

type Backend interface {
	Get(ctx context.Context, catalog string) (*Source, error)
	Sources(ctx context.Context) ([]Source, error)
	Due(ctx context.Context, now time.Time) ([]string, error)
	Record(ctx context.Context, catalog string, o Outcome) error
	ReplaceItems(ctx context.Context, catalog string, items []Item) error
	AddChange(ctx context.Context, c Change, pending *Archive, etag string) (string, error)
	Pending(ctx context.Context, catalog string) (*Change, error)
	Decide(ctx context.Context, id, status, by string) (bool, error)
	CurrentAutomations(ctx context.Context, catalogs []string) ([]VendorAutomation, error)
	Automation(ctx context.Context, catalog, name string, version int) (*VendorAutomation, error)
	PutAutomation(ctx context.Context, a VendorAutomation) error
	RetireAutomations(ctx context.Context, catalog string, kept []string) error
	VersionHash(ctx context.Context, catalog, name string, version int) (string, error)
	LatestVersion(ctx context.Context, catalog, name string) (int, error)
	LoaderOwners(ctx context.Context, catalog string) (Owners, error)
}

Backend is the knowledge tables a service reads and writes (*Store).

type Change

type Change struct {
	ID        string     `json:"id"`
	Catalog   string     `json:"catalog"`
	Status    string     `json:"status"`
	Trigger   string     `json:"trigger"`
	Report    Report     `json:"report"`
	CreatedBy string     `json:"created_by"`
	CreatedAt time.Time  `json:"created_at"`
	DecidedBy string     `json:"decided_by,omitempty"`
	DecidedAt *time.Time `json:"decided_at,omitempty"`
	// Held and HeldETag are a pending update's archive and the ETag it was
	// fetched with, read by Pending alone and never served.
	Held     *Archive `json:"-"`
	HeldETag string   `json:"-"`
}

Change is one update of a catalog's archive and what became of it.

type Checker

type Checker struct {
	// Registered lists every tool the deployment registers.
	Registered func() []string
	// Secrets finds credentials, the deployment's stored values included.
	Secrets secretscan.Detector
}

Checker is what every page and automation passes before it applies: invisible, bidirectional and control characters removed, no tool the deployment does not register, no credential shape and none of the deployment's own secret values.

func (Checker) Check

func (c Checker) Check(ctx context.Context, a *Archive) ([]Finding, error)

Check cleans a's text in place and returns the items it holds back. An error is a scan that could not run, which refuses the archive rather than apply text it could not check.

type Fetched

type Fetched struct {
	Data        []byte
	ETag        string
	NotModified bool
}

Fetched is an archive as its host answered.

type Fetcher

type Fetcher func(ctx context.Context, url, etag string) (*Fetched, error)

Fetcher reads the archive at url, sending etag as If-None-Match. Its error may hold the URL; the service never stores or shows it unscrubbed.

type Finding

type Finding struct {
	Kind   string `json:"kind"`
	Name   string `json:"name"`
	Reason string `json:"reason"`
}

Finding is one item held for an administrator, and why: the field and the kind of what was found, never the value.

type Gate

type Gate func(ctx context.Context, catalog string, a Automation, carried map[string][]byte, libs scriptlib.Source) string

Gate is why the platform's save gate refuses one vendor automation, "" when it saves. carried is the archive's recorded runs, and libs reads the archive's libraries before the stored ones.

type Item

type Item struct {
	Kind   string `json:"kind"`
	Name   string `json:"name"`
	Status string `json:"status"`
	Reason string `json:"reason,omitempty"`
}

Item is what the last import made of one page or automation.

type ItemChange

type ItemChange struct {
	Name string `json:"name"`
	// Kind is an automation's: template or library. Empty for a page.
	Kind    string `json:"kind,omitempty"`
	Change  string `json:"change"`
	Version int    `json:"version,omitempty"`
	From    int    `json:"from,omitempty"`
	Before  string `json:"before,omitempty"`
	After   string `json:"after,omitempty"`
}

ItemChange is one page or automation an update adds, changes or removes. Before and After are a page's bodies, for the diff a held update shows.

type Libraries

type Libraries struct {
	Store   *Store
	Trusted func(ctx context.Context) map[string][]string
}

Libraries is where every run, draft, test and save reads a vendor library (lib:<catalog>/<name>@<version>) from. A version once published is read whatever the catalog's trust: a script keeps running the version it names. Only a source starting to load one needs a trusted connection (Admit).

func (*Libraries) Admit

func (l *Libraries) Admit(ctx context.Context, name string) string

Admit implements scriptlib.Namespaced.

func (*Libraries) LibrarySource

func (l *Libraries) LibrarySource(ctx context.Context, name string, version int) (string, error)

LibrarySource implements scriptlib.Source.

type Limits

type Limits struct {
	MaxArchiveBytes    int64 `yaml:"max_archive_bytes"`
	MaxPages           int   `yaml:"max_pages"`
	MaxPageBytes       int64 `yaml:"max_page_bytes"`
	MaxAutomations     int   `yaml:"max_automations"`
	MaxAutomationBytes int64 `yaml:"max_automation_bytes"`
}

Limits bound one archive. A non-positive field takes its default. They are the apigateway.catalog_fetch.knowledge configuration section, so the key a refusal names is the key an operator raises.

func (Limits) Normalized

func (l Limits) Normalized() Limits

Normalized returns the limits with every non-positive field at its default.

type LoaderScript

type LoaderScript struct {
	ID    string
	Name  string
	Owner string
}

LoaderScript is an automation that loads one of a catalog's libraries.

type Loop

type Loop struct {
	Service *Service
	DB      *sql.DB
	// contains filtered or unexported fields
}

Loop checks every catalog whose scheduled knowledge check has come.

func (*Loop) RunOnce

func (l *Loop) RunOnce(ctx context.Context) error

RunOnce checks the due catalogs under the advisory lock, returning bgloop.ErrSkipped when another replica holds it. A catalog whose check fails is stamped with the failure and checked again an interval on.

func (*Loop) Start

func (l *Loop) Start(ctx context.Context)

Start begins the loop; it checks at once.

func (*Loop) Stop

func (l *Loop) Stop()

Stop ends the loop and waits for a pass in progress.

type Notice

type Notice struct {
	Key     string
	Catalog string
	Title   string
	Body    string
	// Owners is set when the catalog stopped being trusted: the automations
	// loading its libraries, by owner, each owner to be told.
	Owners Owners
}

Notice is what a check tells the deployment's channels.

type Outcome

type Outcome struct {
	Result  string
	Error   string
	ETag    *string
	Vendor  string
	Entry   string
	Applied bool
}

Outcome is what one check records on the source.

type Owners

type Owners map[string][]LoaderScript

Owners is the automations loading the catalog's libraries, by owner.

type Page

type Page struct {
	Slug    string   `json:"slug"`
	Title   string   `json:"title"`
	Summary string   `json:"summary"`
	Tags    []string `json:"tags"`
	Body    string   `json:"body"`
}

Page is one knowledge page: pages/<slug>.md, front matter then markdown.

type RefusedError

type RefusedError struct{ Reason string }

RefusedError is an archive refused whole: nothing from it applies. Its text is the reason an administrator reads on the catalog page.

func (*RefusedError) Error

func (e *RefusedError) Error() string

type Report

type Report struct {
	Pages       []ItemChange `json:"pages"`
	Automations []ItemChange `json:"automations"`
	Held        []Finding    `json:"held"`
	Skipped     []Finding    `json:"skipped"`
	First       bool         `json:"first,omitempty"`
}

Report is what an update changes: each page and automation added, changed or removed, and the items held or skipped.

func (Report) Empty

func (r Report) Empty() bool

Empty reports whether the update changes nothing.

type Result

type Result struct {
	Result string  `json:"result"`
	Error  string  `json:"error,omitempty"`
	Report *Report `json:"report,omitempty"`
}

Result is what one check did.

type Service

type Service struct {
	Store   Backend
	Pages   knowledgepage.VendorReconciler
	Checker Checker
	Gate    Gate
	// Trusted is each catalog's trusted connections as this replica serves
	// them now.
	Trusted func(ctx context.Context) map[string][]string
	Fetch   Fetcher
	Limits  Limits
	Notify  func(ctx context.Context, n Notice)
}

Service keeps catalogs' vendor knowledge current.

func (*Service) Accept

func (s *Service) Accept(ctx context.Context, catalog, by string) (Result, error)

Accept applies the catalog's held update.

func (*Service) Check

func (s *Service) Check(ctx context.Context, catalog, trigger, author string) (Result, error)

Check fetches the catalog's archive and applies it, holds it, or records why it could not.

func (*Service) Discard

func (s *Service) Discard(ctx context.Context, catalog, by string) error

Discard drops the catalog's held update; what serves stays.

func (*Service) Revoked

func (s *Service) Revoked(ctx context.Context) error

Revoked records, and tells administrators and the owners of automations loading its libraries, every catalog whose knowledge was imported while a connection of it was trusted and has none trusted now. The loop runs it every minute, so a trust taken away is told within one, not at the next scheduled check; serving stops at once on its own, since every read asks the live connections.

type Settings

type Settings struct {
	URL      *string
	Hold     bool
	Interval int
}

Settings is what an administrator sets on a catalog's knowledge. A nil URL keeps the one stored: the URL is written, never read back.

type Source

type Source struct {
	Catalog       string     `json:"catalog"`
	URL           string     `json:"-"`
	Hold          bool       `json:"hold"`
	Interval      int        `json:"refresh_interval_seconds"`
	ETag          string     `json:"-"`
	Vendor        string     `json:"vendor"`
	Entry         string     `json:"entry"`
	LastCheckedAt *time.Time `json:"last_checked_at,omitempty"`
	LastResult    string     `json:"last_result"`
	LastError     string     `json:"last_error,omitempty"`
	LastAppliedAt *time.Time `json:"last_applied_at,omitempty"`
	UpdatedBy     string     `json:"updated_by"`
	UpdatedAt     time.Time  `json:"updated_at"`
}

Source is where a catalog's archive is and how its last check went. URL is the knowledge URL as written; nothing outside the admin catalog routes reads it.

type Store

type Store struct{ DB *sql.DB }

Store is the knowledge tables of migration 000278.

func (*Store) AddChange

func (s *Store) AddChange(ctx context.Context, c Change, pending *Archive, etag string) (string, error)

AddChange records an update. A pending one carries the checked archive and supersedes the catalog's earlier pending update.

func (*Store) Automation

func (s *Store) Automation(ctx context.Context, catalog, name string, version int) (*VendorAutomation, error)

Automation is one version of a vendor automation; version 0 is the current one.

func (*Store) CurrentAutomations

func (s *Store) CurrentAutomations(ctx context.Context, catalogs []string) ([]VendorAutomation, error)

CurrentAutomations is the current version of each automation of the catalogs, by catalog then name.

func (*Store) Decide

func (s *Store) Decide(ctx context.Context, id, status, by string) (bool, error)

Decide marks the pending update applied or discarded by an administrator, and reports whether one was pending.

func (*Store) Delete

func (s *Store) Delete(ctx context.Context, catalog string) (bool, error)

Delete removes the catalog's knowledge URL with its items, held change and current automations; the versions a script loads are kept.

func (*Store) Due

func (s *Store) Due(ctx context.Context, now time.Time) ([]string, error)

Due is every catalog whose next check is due.

func (*Store) Get

func (s *Store) Get(ctx context.Context, catalog string) (*Source, error)

Get is the catalog's knowledge source, or ErrNotFound.

func (*Store) History

func (s *Store) History(ctx context.Context, catalog string, limit int) ([]Change, error)

History is the catalog's updates, newest first.

func (*Store) Items

func (s *Store) Items(ctx context.Context, catalog string) ([]Item, error)

Items is the catalog's item list.

func (*Store) LatestVersion

func (s *Store) LatestVersion(ctx context.Context, catalog, name string) (int, error)

LatestVersion is the highest version of the automation, 0 for none.

func (*Store) LoaderOwners

func (s *Store) LoaderOwners(ctx context.Context, catalog string) (Owners, error)

LoaderOwners is every automation whose current source loads one of the catalog's libraries, by owner.

func (*Store) Loaders

func (s *Store) Loaders(ctx context.Context, catalog, name string) (map[int]int, error)

Loaders counts the scripts whose current source loads each version of the library, by version.

func (*Store) Pending

func (s *Store) Pending(ctx context.Context, catalog string) (*Change, error)

Pending is the catalog's update waiting for an administrator, with the archive it holds, or ErrNotFound.

func (*Store) Put

func (s *Store) Put(ctx context.Context, catalog string, set Settings, by string) error

Put saves the catalog's knowledge settings. A changed URL forgets the stored ETag and makes the catalog due at once.

func (*Store) PutAutomation

func (s *Store) PutAutomation(ctx context.Context, a VendorAutomation) error

PutAutomation makes a the catalog's current version of its name: the version it names when it is new, the current one untouched when its source is unchanged.

func (*Store) Record

func (s *Store) Record(ctx context.Context, catalog string, o Outcome) error

Record writes a check's outcome and schedules the next one.

func (*Store) ReplaceItems

func (s *Store) ReplaceItems(ctx context.Context, catalog string, items []Item) error

ReplaceItems makes items the catalog's item list.

func (*Store) RetireAutomations

func (s *Store) RetireAutomations(ctx context.Context, catalog string, kept []string) error

RetireAutomations takes the current version away from each of the catalog's automations not in kept; every version stays loadable.

func (*Store) Sources

func (s *Store) Sources(ctx context.Context) ([]Source, error)

Sources is every catalog with a knowledge URL.

func (*Store) VersionHash

func (s *Store) VersionHash(ctx context.Context, catalog, name string, version int) (string, error)

VersionHash is the source hash a version was published with, "" when it was not.

type VendorAutomation

type VendorAutomation struct {
	Catalog     string            `json:"catalog"`
	Name        string            `json:"name"`
	Version     int               `json:"version"`
	Kind        string            `json:"kind"`
	Description string            `json:"description"`
	Source      string            `json:"source,omitempty"`
	Params      []script.Param    `json:"params"`
	Recordings  map[string][]byte `json:"-"`
	Current     bool              `json:"current"`
	CreatedAt   time.Time         `json:"created_at"`
}

VendorAutomation is one version of a vendor's template or library.

Jump to

Keyboard shortcuts

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