Repository navigation
Description
Problem
Gateways built with FOCA (proTES now, proWES later) need one engine that
runs installed, allowlisted plugins on task requests, with defined
order, fallbacks, failure semantics and timeouts. proTES's own handler
imports classes by dotted path from config, instantiates them per
request, shares one mutable Flask request between alternatives (a failed
alternative leaves partial changes), and has no time bound.
Proposal
New package foca.plugins, framework-free:
- Model (
foca.plugins.model): dataclassesPrincipal(subject,
issuer,groups,claims,token),InboundRequest,Backend,
Location,OutboundRequest,BackendResponse, andHeaders, a
case-insensitive mutable mapping (not Werkzeug's). Inbound headers
excludeAuthorizationandCookie; the token is in
Principal.token(no capability grants: every plugin gets claims and
token, decision Q18).Backend.authnames the backend's credential
type (client_credentials|basic|none); the values are attached
by the app, never put in the model. - Base (
foca.plugins.base):Plugin[Config, Params]with
setup(config), hookson_request,on_route,on_forward,
on_response,close(); class attributesapis,phases(derived
from implemented hooks),capabilities(generic descriptors, pattern
^[a-z0-9][a-z0-9.-]*$),maturity,api_version; exceptions
NotApplicable,Rejected(status, title, detail)(400, 403, 409,
413, 422 only),PluginError; forward outcomes for apps:
NotAccepted(reason)and its subclassOutcomeUnknown(reason),
reason codes[a-z0-9_]{1,64}(e.g.connect_error,http_403,
read_timeout), exported fromfoca.plugins;API_VERSION = 1. - Config (
foca.plugins.config, top-level FOCA config key
plugins; one field added tofoca.models.config.Config):
available(allowlist:distribution,versionspecifier,config,
client_selectable,roles,enabled),defaults(timeout10,
pipeline_timeout30,forward_timeout60,workers8),
gateway_id,pipeline(steps withid,alternatives,timeout,
on_failure: fail|skip; short forms- plugin: xand the plain
string- x),presets;
reserved keyswhen/needsrejected ("reserved for a later
version"); unknown keys rejected. - Loader (
foca.plugins.loader): only entry points of group
foca.pluginsnamed inavailableare imported; pins checked
(packaging); duplicate IDs, unknown IDs, version mismatches,
unsupportedapi_versionorapisstop the app; RECORD digest of
each distribution computed once (for provenance). Amiddlewareskey
at the top level or incustomis a startup error with a migration
hint toplugins(Q15), checked on the raw merged config in
ConfigParserbeforeConfigand the app's custom model are
validated (whengatewayis set), so the hint wins over pydantic's
"extra inputs are not permitted". Plugins are instantiated once per
process andConfig-validated at startup. - Runtime (
foca.plugins.runtime): apps pass
Foca(..., gateway=GatewayApp(api, validate, sanitize, validate_outbound));create_app()loads the plugins once (fail
fast);get_host()returns the process's host, created lazily on
first use (after Gunicorn/Celery forks;os.register_at_forkmakes
children forget it), and works in Celery without Flask. - Engine (
foca.plugins.engine):PluginHost(conf, api, validate, sanitize, validate_outbound);host.start(inbound, principal, tags)
→PipelineRunwithrequest(),route(initial),
attempts(candidates)(yieldsAttemptwithoutbound;
report(exc)withNotAccepted/OutcomeUnknown,
succeeded(response, remote_id=...)).validatefailures are
invalid_output(next alternative); exceptions ofsanitize
propagate unchanged (stop, e.g. 413);validate_outboundruns per
attempt after the forward phase, failure = not accepted with reason
invalid_outbound(next candidate).
Each alternative works on a deep copy, committed on success;
outcomesok,not_applicable,error,timeout,
invalid_output,rejected(6.2); hooks run in a bounded
ThreadPoolExecutorand are abandoned at the deadline; saturation
fails fast. Route output must be a subset of the candidates. Errors:
PipelineFailed(500, problem type.../plugin-step-failed),
PipelineRejected(4xx),NoBackendAvailable(503),ForwardTimeout
(503 after the totalforward_timeout, with the attempts so far),
LoopDetected(508). The engine addsVia: 1.1 <gateway_id>to
outbound requests and raisesLoopDetectedif the inboundVia
already names this gateway (Q22). Credentials are attached by the app
after the forward phase. If no step implementson_route, the
default route step is appended (P6 provides it). - Adapter (
foca.plugins.adapter): the only module of
foca.pluginsthat imports Flask/Connexion; buildsInboundRequest
andPrincipalfrom the current request and the controller'sbody;
Principal.groups=get_current_groups(), the mapped access-control
roles (same code as access control);request_id()= a safe client
X-Request-ID(≤ 128 characters of[A-Za-z0-9._:-]) or a new uuid4
hex. No host registration here (seeruntime). - ast-grep rule
no-framework-imports-in-plugins(with rule tests):
noflask,werkzeug,connexion,starletteimports in
foca/plugins/exceptadapter.py. - Docs: configuration page
plugins(operator view), "Plugins"
concepts page (incl. how apps integrate:GatewayApp,get_host(),
forward outcomes), API reference, migration note. - Dependency:
packaging(version specifiers).
Acceptance criteria
- Unlisted installed plugins are never imported (tests with fake entry
points for the loader's lookup). get_host()is lazy, per process and fork-safe; works without a Flask
app context (Celery);create_app()fails fast on plugin errors.sanitizeexceptions propagate;validateandvalidate_outbound
failures giveinvalid_output/invalid_outbound.- Legacy-key hint appears also when the app's custom model forbids extra
keys. - Every outcome of 6.2 is tested, including a hanging plugin abandoned
at its timeout, executor saturation, a failed alternative leaving no
trace,on_failure: skip,Rejectedstopping at once. - Startup errors for unknown IDs, pin mismatches, duplicate IDs,
unsupportedapi_version, reserved keys,middlewareskeys (with the
hint). Viaadded outbound; inbound loop →LoopDetected.foca/models/config.pygets only thepluginsfield (other lanes edit
the file).- 100% coverage, mypy, ruff, ast-grep, semgrep,
mkdocs build --strict.
Surviving the Connexion 3 migration
No framework types anywhere in the engine, model, config or hooks; the
engine gets inbound request, principal and tags as arguments and never
reads Flask g or the request context; get_host() is a per-process
singleton, not tied to current_app. rc1 replaces only
foca.plugins.adapter (e.g. on Starlette's request, or on H1-S draft
C's current_request() once it exists). Hooks are def now; P8 adds
async def support without changing signatures. The bounded executor
maps to anyio.to_thread in 1.0.
Dependencies
- None (no longer blocked by H1-S draft C, which moved to v0.19.0).
- Blocks: feat(plugins): resolve per-request pipelines #487, feat(plugins): record provenance #488, feat(utils): add a guarded HTTP client #490 (
ctx.http),
feat(plugins): add default failover router #491, feat(plugins): add plugin test kit #492, feat(plugins): write gateway tags #494.
Open questions
- Loop status:
508 Loop Detected(chosen) or400?
Added during review (PR #496): FrozenMapping (read-only, deep-copyable mapping for Principal.claims, exported from foca.plugins); InvalidVia (400, slug invalid-via) for inbound Via headers over 1024 characters; outbound Via = inbound Via plus this gateway's entry (RFC 9110 §7.6.3); public get_current_claims() in foca.security.access_control.
Added after the Sourcery review (PR #496): one gateway app per process: runtime.configure() raises RuntimeError if a host for other settings is in use, and runtime.reset() closes the host (for tests); the cached host is closed at exit; problem_response() gained a keyword-only title=; Principal.token is set only for validated tokens.
Activity
fix(plugins): address Sourcery review of engine
test(plugins): check the exported names