app

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: 108 Imported by: 0

Documentation

Overview

Package app wires configuration, the stores, the modules and the HTTP router together. cmd/artifactweave stays a thin cobra shim that calls Run and the other commands' functions; tests drive Run with a fake handler.

Role

app: the composition root. It opens what the modules share (the metadata store, the blob tiers and their mirrors, the keyring and the work queue), builds the access, artifacts and configuration modules over them in buildModules, has the artifacts module open its remote sources, and builds over all of it the single chi router that serves every JFrog path prefix (NewRouter). It may import any package, and only cmd/artifactweave and the server test harness (test/server/support/harness) import it.

Inputs

  • The loaded config.Config (app/config), which cmd/artifactweave reads with config.Load from the file, the environment and the flags. app reads the keys a module owns only through its accessors, Access, Artifacts and Configuration, and the platform's keys as fields.
  • The command line, through cmd/artifactweave: serve calls Run, migrate calls Migrate, keys rotate calls RotateKeys, and config apply calls ApplyDescriptor with the descriptor file it names.

Outputs

  • Run: serves until its context is cancelled, then drains the HTTP server and closes what it opened.
  • Migrate: the up, down and version actions over the schema migrations, and ErrUnknownMigration for any other action.
  • RotateKeys: re-seals every sealed value under the newest master key.
  • ApplyDescriptor: applies a YAML descriptor to the configured store, or with dryRun only checks it.
  • Keyring, the keyring from master_key and master_key_previous, and OpenStore, the configured metadata store.
  • InitialPasswordFile: the file under the data directory where the first start writes a generated admin password.
  • RouterConfig and NewRouter: the HTTP handler that serves /artifactory, /access, /event, /router, /jfconnect, /v2 and the other specified service prefixes over the stores, services and settings a RouterConfig names. Run serves it; the server test harness builds it for the suites under test/server.
  • Runtime, RuntimeOptions and OpenRuntime: what serve holds open, with the costs it is opened with, exported so that the server test harness builds the router over the stores and modules serve uses.

Invariants

  • OpenRuntime first sets the xz dictionary budget from xz.dictionary_budget, which every decode in the process shares, those of the work queue included (#1354).
  • OpenRuntime opens the store, which applies pending migrations, seeds the built-in principals and applies the bootstrap, then opens the token service, the authenticator, both blob tiers, the garbage collector and the work queue, builds the modules, registers the artifacts module's work and opens its remote sources, in that order, and starts the background loops last. A failure on the way closes what it opened so far.
  • buildModules does no I/O, so building the modules once the work queue is open moves none of the start-up I/O. The multipart upload service and the garbage collector are built before them and take access's store-only bindings, as the bootstrap does.
  • The store opens, and its migrations finish, before the listener accepts a request.
  • Requests run on a context that the shutdown signal does not cancel, so the drain lets them finish; they are cancelled only once it expires.
  • NewRouter installs its middleware in one order: the error profiles, the request ID, panic recovery, the access log, the base URL, the Smart Remote trace, the Docker API version header and registry challenge, content type normalisation, collection slashes, plus as space, the Idempotency-Key gate, the API recovery context and the xz request holder (xzRequests, so a request's xz readers are one holder of the dictionary budget); then, each only when configured, the ingress request limits, the forced authentication of Maven and P2 virtual repositories (itemkit.ForceAuthentication), authentication, the API restrictions and the principal request limits; then the Helm partial reindex. The ingress limits count a request before anyone is authenticated and the principal limits charge the caller after (decision 0043). The forced authentication goes just before authentication, where 7.x's filter sits, so it answers the same whether anonymous access is on or off.
  • Both request limits admit a request under the x-cost class of the spec operation it addresses, which limits_cost.go finds in the generated operation table before routing, so the specs are the one place a class is set. Only a request no spec operation addresses (an alias, a native protocol route, a 404 or a 405) takes the class the path rules give it: the probes, the recovery API and expensiveRequest.
  • Hand-written routes are mounted before the generated strict servers, and the 501 stubs of hand-written operations last, so each hand-written route claims the pattern its spec derives instead of the generated handler or the stub (decision 0002). Each spec's strict server embeds the modules' partials at depth one and the generated 501 stubs at depth two, so an implemented operation shadows its stub and two partials claiming one operation fail to compile.

References

  • Decision 0001: docs/research/decisions/0001-mirror-the-jfrog-api-surface.md (the routes, statuses and envelopes the router serves).
  • Decision 0002: docs/research/decisions/0002-spec-first-flat-crud-handwritten-item-paths.md (one strict server per spec, and hand-written item paths mounted first).
  • Decision 0009: docs/research/decisions/0009-configuration-as-code.md (the application configuration that Run and the commands take, and config apply).
  • Decision 0016: docs/research/decisions/0016-observability-and-health.md (the structured log, which the HTTP server's error log joins).
  • Decision 0033: docs/research/decisions/0033-persistent-work-queue.md (the work queue that OpenRuntime starts).
  • Decision 0043: docs/research/decisions/0043-api-reliability.md (the request limits and their place in the middleware chain).
  • Decision 0044: docs/research/decisions/0044-modular-monolith-migration.md (app is the composition root and may import any package).
  • Target layout: docs/research/architecture-options/5-modular-monolith.md, lines 746 to 805 (the composition root, router.go at lines 748 to 762), 389 to 409 (where the server root's files went) and 819 to 834 (the router's strict servers composed by embedding).
  • https://github.com/weaveplatform/artifactweave/issues/1092, https://github.com/weaveplatform/artifactweave/issues/1094, https://github.com/weaveplatform/artifactweave/issues/1096 and https://github.com/weaveplatform/artifactweave/issues/1097

Status

Implemented P0 to P9c. Moved here in P9d (WEB-18); WEB-19 added the module settings, WEB-20 the module constructors, which took over the remote wiring and the garbage collection loop, and WEB-21 gave each file one job: run.go serves, platform.go opens what the modules share, modules.go builds the modules, bootstrap.go and seed.go prepare the first start, runtime.go holds the runtime and serverlog.go the HTTP server's error log. TST-07 exported the runtime and moved the remote suites to test/server/artifacts. WEB-22 brought the router here: router.go builds it and limits.go holds the request limits. IDEM-01 added keyed.go, the shared replay that wraps every generated server's keyed operations, with each module's bindings, and the Idempotency-Key gate over the operation table.

Testing

The tests start the runtime from a configuration as serve would, each beside the file it tests: run_test.go covers Run; runtime_test.go OpenRuntime, its loops and Close; platform_test.go Keyring, OpenStore, Migrate, RotateKeys, the blob tiers and their mirrors; modules_test.go buildModules and the token service; seed_test.go and bootstrap_test.go the first start and config apply; serverlog_test.go the HTTP server's error log. hash_test.go lowers the password hashing cost and the token key size for all of them. The suites that read remote content through the composed runtime run from test/server/artifacts/<type>, over the harness's App and RemoteWorld.

The whole-router guards run beside NewRouter over fixtures_test.go: the status tables (status_test.go and status_<x>_test.go), the route and principal matrices (matrix_test.go), the spec checks (spec_test.go, spec_contract_test.go), the 501 stubs (stub_test.go), the error profiles (error_profiles_p8_test.go), the request limits (limits_test.go; the classes admission takes from the table, limits_cost_test.go; every spec operation's 429 and 503, limits_operations_test.go), the Docker list errors' registry envelope (docker_list_errors_test.go), the keyed operations' bindings and key gate (keyed_test.go), the API reliability ledger (api_ledger_test.go, which make api-ledger runs to regenerate docs/research/api-reliability/operations.json) and decision 0043's operation rules (api_principles_test.go, whose rules are checked against the admission and error profiles here, with a fixture per rule in api_principles_fixtures_test.go). They must not import the harness, which imports app.

Index

Constants

View Source
const InitialPasswordFile = "initial-admin-password"

InitialPasswordFile is where the first start writes a generated admin password, under the data directory. A file with mode 0600 rather than a log line, because logs are shipped and kept where the password must not be.

Variables

View Source
var ErrUnknownMigration = errors.New("app: unknown migrate action")

ErrUnknownMigration reports a migrate action other than up, down or version.

Functions

func ApplyDescriptor

func ApplyDescriptor(
	ctx context.Context,
	cfg config.Config,
	file string,
	dryRun bool,
	w io.Writer,
) error

ApplyDescriptor runs `artifactweave config apply`: it applies the descriptor in file to the store the configuration names, as `migrate` and `keys rotate` work on the store directly, and writes what changed to w. With dryRun it checks the whole descriptor against the current state and writes nothing.

It works on the store rather than calling a running server so that it needs no admin credentials in the CI job, only the configuration the server itself uses, and so that it can prepare a store before the first start. It runs the same code as PATCH /api/system/configuration.

func Keyring

func Keyring(cfg config.Config) (*crypt.Keyring, error)

Keyring builds the keyring from master_key and, during a rotation, master_key_previous (crypt.ParseVersionedKey). It returns nil without error when no master key is configured, for the commands that run without one.

func Migrate

func Migrate(
	ctx context.Context,
	cfg config.Config,
	action string,
	to int,
	module string,
	w io.Writer,
) error

Migrate runs `artifactweave migrate <action>` over every module's stream, or over module's stream alone when module is set. "up" applies every pending migration. "down" reverts the migrations newer than to, which needs a module unless to is 0, everything; a negative to reverts one step, the newest migration of module's stream or, with no module, of the last stream in the canonical order that has any applied. "version" reports each stream's applied and latest versions, one line per stream. up and down write one line of outcome to w. A module that no stream has fails with dialect.ErrUnknownModule.

func NewRouter

func NewRouter(cfg RouterConfig) http.Handler

NewRouter returns the handler for every JFrog path prefix over cfg: /artifactory, /access, /event, /router, /jfconnect and /v2; /distribution, /worker, /pfed and /grid, whose specified operations answer 501 until they are built; and the products artifactweave does not implement, which answer 501 naming the product (Mission Control 404). Flat CRUD families come from the generated strict servers, and the item paths, protocols and other hand-written routes are mounted ahead of them. When cfg sets a Store but no Access or Configuration contract, NewRouter binds them over it first, as RouterConfig.Access and RouterConfig.Configuration describe.

func OpenStore

func OpenStore(
	ctx context.Context,
	cfg config.Config,
	o appsql.Options,
) (*appsql.Store, error)

OpenStore opens the configured metadata store. The SQLite file's directory is created when missing, so a first start needs nothing but a data directory path.

func RotateKeys

func RotateKeys(ctx context.Context, cfg config.Config, w io.Writer) error

RotateKeys runs `artifactweave keys rotate`: it opens the store with the configured keyring (master_key and master_key_previous), re-seals every sealed value under the newest version, and every sealed Terraform state in the blob store too (decision 0041), and reports how many changed. Once it has run, master_key_previous can be removed.

func Run

func Run(ctx context.Context, cfg config.Config, log *slog.Logger) error

Run opens the store and blob stores, serves until ctx is cancelled, then drains and closes them and returns nil. Any startup, listener or serve failure is returned wrapped.

Types

type RouterConfig

type RouterConfig struct {
	// RequestLimits owns shared request rates and this process's concurrency
	// permits. Nil disables limits for embedders; the application wires them.
	RequestLimits *apilimit.Service
	// RemoteHTTP owns repository-scoped connection pools, of which the
	// router needs only Remove, for a deleted repository. The application
	// closes it after draining requests; source adapters resolve credentials
	// per revision. Assign it only a pool that exists, or leave it nil: a nil
	// *upstream.Pool stored in it is a non-nil interface, so a delete would
	// call Remove on the nil pool, which panics on the pool's lock.
	RemoteHTTP interface{ Remove(key string) }
	// Keys derives the key for short-lived Terraform download URLs.
	Keys *crypt.Keyring
	// BaseURL is the operator-configured public base URL; empty means derive
	// it from the request. Override and X-Forwarded-* headers take precedence.
	BaseURL string
	// CompatVersion is the Artifactory version reported to clients; it gates
	// client features, so it is configuration rather than the build version.
	CompatVersion string
	// Revision is the real artifactweave build identifier.
	Revision string
	// Logger receives access and panic logs; nil falls back to slog.Default so
	// tests and library users need not wire one.
	Logger *slog.Logger
	// RemoteSources is the direct remote read boundary. Nil preserves cache-only
	// behavior; production activation belongs to the adapter tickets. Native
	// protocols opt in separately through their pkgroute.Source map.
	RemoteSources *source.Service
	// RegistrySources opts Docker, OCI and OCI Helm into authenticated remote reads.
	RegistrySources *source.Service
	// Store is the metadata store and Blobs the blob store that the content
	// handlers read and write. ColdBlobs is the archive tier, nil when none
	// is configured.
	Store     RouterStore
	Blobs     blob.Store
	ColdBlobs blob.Store
	// GC is the garbage collector the runtime schedules; POST
	// /api/system/storage/gc runs the same one. Nil builds one per request,
	// for tests.
	GC *gc.Collector
	// BlobLocation describes the hot blob store in the storage summary.
	BlobLocation usage.Location
	// Auth verifies credentials. Nil serves every route without
	// authentication, which only tests do: such a handler has no store and
	// answers just the system endpoints and the stubs.
	Auth *authn.Authenticator
	// Mirrors administers the blob mirrors; nil when no tier is a mirror.
	Mirrors artifactshttp.Mirrors
	// RemoteStatus serves artifactweave-only, administrator-only diagnostics.
	RemoteStatus func(context.Context, string, string) (smart.SmartStatus, error)
	// Multipart serves the JFrog CLI's multipart upload protocol; nil
	// reports it unsupported, so the CLI uploads in one request.
	Multipart *multipart.Service
	// Tokens issues, refreshes and revokes access tokens for the token API;
	// nil answers that API 501.
	Tokens *token.Service
	// Access is the access module's API, which app builds over Store, Auth
	// and Tokens. When every contract in it is nil and Store is set,
	// NewRouter binds one over those fields, with AllowBasicAuthTokens and
	// GlobalEnvironmentLimit as its settings, so a RouterConfig built by
	// hand, as tests build it, answers as the application's does. Without a
	// store it stays zero.
	Access accessapi.API
	// Configuration is the configuration module's API, through which PATCH
	// /api/system/configuration applies the descriptor and the item routes
	// read its minimum redirect size. When both its contracts are nil and
	// Store is set, NewRouter binds one over Store and Access with the
	// descriptor core, as it binds Access. Without a store it stays zero.
	Configuration configapi.API
	// AllowBasicAuthTokens lets a password sent with Basic create tokens
	// through POST /access/api/v1/tokens (token.allow_basic_auth); the zero
	// value refuses it, as Artifactory 7.x does by default.
	AllowBasicAuthTokens bool
	// PasswordHash is the cost of passwords the security API sets; the zero
	// value is production's. Only Go code can choose another: tests use a
	// tiny cost.
	PasswordHash authn.HashParams
	// Redirect tunes downloadRedirect and cdnRedirect (decision 0029).
	Redirect itemkit.Redirect
	// FolderDownloadMaxConcurrent is how many folder archive downloads run
	// at once (download.folder.max_concurrent_requests); zero means
	// Artifactory's 10.
	FolderDownloadMaxConcurrent int
	// AQL bounds AQL searches; the zero value has no cap. Its MaxResults
	// caps the GET searches too.
	AQL artifactshttp.AQLLimits
	// Search limits what the GET searches return; the zero value limits
	// nothing.
	Search artifactshttp.SearchLimits
	// DockerSubdomainMatch turns on the Docker subdomain method
	// (docker.subdomain_match): <repo>.<BaseURL host>/v2/... addresses repo.
	DockerSubdomainMatch bool
	// AllowDuplicateBuildEntries accepts a build-info publish whose module
	// lists one file twice (build.block_duplicate_entries false); the zero
	// value refuses it, as Artifactory 7.x does by default.
	AllowDuplicateBuildEntries bool
	// EnforceIdenticalChecksumDeploy makes a checksum deploy over a file
	// with the same content need the delete permission
	// (deploy.enforce_permission_check_on_identical_checksum_deploy); the
	// zero value lets it through with deploy alone, as Artifactory 7.x does
	// by default.
	EnforceIdenticalChecksumDeploy bool
	// NPMLoginTokenExpiry is how long a token from npm login lasts
	// (npm.login_token_expiry); zero means decision 0034's default.
	NPMLoginTokenExpiry time.Duration
	// NPMMaxPublishSize caps an npm publish request (npm.max_publish_size);
	// zero means decision 0034's default.
	NPMMaxPublishSize int64
	// GlobalEnvironmentLimit caps the global environments, DEV and PROD
	// included (environments.global_limit); zero means
	// roles.DefaultGlobalEnvironmentLimit.
	GlobalEnvironmentLimit int
	// Work is the runtime's work queue, which formats ask for derived work
	// (decision 0033). Nil writes that work to the store's queue directly,
	// where the workers find it on their next poll.
	Work *work.Queue
	// Formats returns a package type's format; nil means
	// FormatSettings.For. Only tests set it, to substitute formats that
	// record their hooks.
	Formats format.Registry
	// FormatSettings are the formats' server-wide options, such as
	// npm.tag_latest_by_publish; the zero value is each format's default.
	FormatSettings ecosystem.Settings
	// CranArchiveMoverEnabled enables the administrator-only legacy archive
	// migration API. Its zero value leaves migration disabled.
	CranArchiveMoverEnabled bool
	HuggingFaceXetEnabled   bool
	// Protocols are mounted through the router kit after the built-in ones
	// (artifactshttp.Protocols). Only tests set it, to mount a test-only
	// protocol.
	Protocols []pkgroute.Protocol
}

RouterConfig is what NewRouter needs: the stores, the services app opens over them and the settings it reads from the application configuration. The content routes need Store and Blobs; a nil service turns off what it serves, as each field says, and the zero value of a setting is Artifactory 7.x's default. The caller owns every store and service here and closes them only after the handler has drained.

type RouterStore

type RouterStore interface {
	// The artifacts handlers, with their item kit, package routes and
	// replays.
	artifactshttp.Store
	// The Docker registry's uploads.
	registry.Store
	// The repositories given to the descriptor core and the access
	// handlers, and the request budget's repository lookup.
	repos.Store
	// The access module's bindings.
	accessmodule.Store
	// The access handlers and the authentication middleware.
	accesshttp.Store
	// The system handlers' instance identity.
	instance.Store
	// The receipts of the keyed operations' replay (keyed.go).
	Replays() idempotency.ReplayStore
}

RouterStore is the metadata store NewRouter hands to the handlers, middleware and bindings it builds: the union of the store types they declare, so the router asks for no accessor that none of them uses, and a handler that starts using one more makes this interface, and nothing else, grow. Every call joins the transaction its context carries. The composite SQL store is a RouterStore, as is the in-memory composite that the tests build routers over.

type Runtime

type Runtime struct {
	// Keys is the master key's keyring, nil without a master key.
	Keys *crypt.Keyring
	// Store is the metadata store, with its pending migrations applied.
	Store *appsql.Store
	// Auth authenticates requests against Store's users and Tokens.
	Auth *authn.Authenticator
	// Tokens issues and verifies access tokens.
	Tokens *token.Service
	// Artifacts is the artifacts module, whose remote sources, remote
	// HTTP pool and registry sources serve hands the server.
	Artifacts *artifacts.Module

	// Blobs is the hot tier's blob store; coldBlobs is the cold tier's,
	// nil when cold_blob configures none.
	Blobs blob.Store

	// Work runs derived work after the changes that need it (decision 0033).
	Work *work.Queue
	// contains filtered or unexported fields
}

Runtime is what serve holds open: the metadata store, the blob tiers, the work queue, the modules, and the background loops (mirror repair, GC and the work queue's workers). OpenRuntime opens it and Close releases it. Test support reads its exported fields to build a router over the stores and modules serve would use.

func OpenRuntime

func OpenRuntime(
	ctx context.Context,
	cfg config.Config,
	log *slog.Logger,
	opts RuntimeOptions,
) (*Runtime, error)

OpenRuntime opens the store (applying pending migrations), builds both blob tiers and the modules, and starts a repair loop for each mirror, the garbage collector and the work queue's workers, with the costs opts sets. On failure everything opened so far is closed again. The caller closes the runtime with Close.

func (*Runtime) Close

func (rt *Runtime) Close(ctx context.Context) error

Close stops the background loops, waits until ctx ends for mirror commits still running after their quorum (so they are recorded rather than left pending for the repair worker), and closes the store. It is called once, after the HTTP server over the runtime has drained; the error joins the mirrors' and the store's.

type RuntimeOptions

type RuntimeOptions struct {
	// PasswordHash is the Argon2id cost of the seeded admin password and
	// of the passwords the authenticator hashes. A lower cost than
	// production's is safe in tests: verification reads the cost from
	// each stored hash, so every password still checks, only sooner.
	PasswordHash authn.HashParams
	// TokenKeyBits is the RSA size of the access-token signing key the
	// first start creates.
	TokenKeyBits int
}

RuntimeOptions tune what OpenRuntime builds; the zero value is production. A zero field keeps the package default, which is production's everywhere but app's own tests (hash_test.go).

Directories

Path Synopsis
adapters
inmem
Package inmem is the composite in-memory store: the platform's in-memory store and every module's, over one in-memory unit of work, so a transaction begun through any of them spans them all.
Package inmem is the composite in-memory store: the platform's in-memory store and every module's, over one in-memory unit of work, so a transaction begun through any of them spans them all.
sql
Package sql is the composite SQL store: the platform's store and every module's SQL store over one dialect store, so a transaction begun through any of them spans them all.
Package sql is the composite SQL store: the platform's store and every module's SQL store over one dialect store, so a transaction begun through any of them spans them all.
sql/postgres
Package postgres opens the composite SQL store on PostgreSQL: the pool of the platform/sql/postgres driver, migrated and wrapped in the composite store of app/adapters/sql.
Package postgres opens the composite SQL store on PostgreSQL: the pool of the platform/sql/postgres driver, migrated and wrapped in the composite store of app/adapters/sql.
sql/sqlite
Package sqlite opens the composite SQL store on SQLite: the pool of the platform/sql/sqlite driver, migrated and wrapped in the composite store of app/adapters/sql.
Package sqlite opens the composite SQL store on SQLite: the pool of the platform/sql/sqlite driver, migrated and wrapped in the composite store of app/adapters/sql.
Package apptest supplies the stores that the package format contract runs on, which only the composition root may build: FormatBackends hands artifacts/core/formattest the in-memory, SQLite and PostgreSQL composite stores, so that the contract suite opens no store of its own and artifacts core never imports app.
Package apptest supplies the stores that the package format contract runs on, which only the composition root may build: FormatBackends hands artifacts/core/formattest the in-memory, SQLite and PostgreSQL composite stores, so that the contract suite opens no store of its own and artifacts core never imports app.
Package config loads the application configuration described in docs/operations/configuration-reference.md and decision record 0009.
Package config loads the application configuration described in docs/operations/configuration-reference.md and decision record 0009.
Package storetest is the contract suite of the composite stores and the suites that need a whole composite: Run holds every backend of the metadata store (in memory, SQLite in memory and in a file, PostgreSQL) to one set of expectations, and the SQL suites check key rotation, sealed repository headers, layout fencing across a reopen, a crashed replayed write and the refusal of a legacy migration history on both SQL composites.
Package storetest is the contract suite of the composite stores and the suites that need a whole composite: Run holds every backend of the metadata store (in memory, SQLite in memory and in a file, PostgreSQL) to one set of expectations, and the SQL suites check key rotation, sealed repository headers, layout fencing across a reopen, a crashed replayed write and the refusal of a legacy migration history on both SQL composites.

Jump to

Keyboard shortcuts

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