Repository navigation
refactor!: process tasks with FOCA plugins - #346
Conversation
Replace the middlewares of proTES with FOCA 0.18's plugin engine: TaskRuns.create_task() starts a pipeline run with the inbound request and the caller, runs the request and route phases, stores the task and forwards it to the candidates in turn through the forward phase, and returns the body and headers of the response phase. The default pipeline is FOCA's ordered failover (foca.routing.ordered). - Add pro_tes.gateway with the GatewayApp: validation, sanitization (URL credentials, inline content) and outbound checks of tasks. - Replace TesClient.create_task() by forward(), which sends the outbound request of the plugins with proTES's credentials and reports why an attempt failed. - Map the errors of the plugin engine; tasks that no TES instance accepts fail with 503 instead of 500. - Remove pro_tes.middleware, pro_tes.plugins (distance and random distribution) and geopy; custom.middlewares is refused by FOCA. - Extend the framework-free-tasks rule to all of pro_tes except the app, the controllers and the exceptions. BREAKING CHANGE: custom.middlewares is refused; set plugins.pipeline. Tasks go to the TES instances in order, with failover; distance-based and random distribution move to foca-plugins. No TES instance accepting a task gives 503. TaskRuns.create_task() takes inbound and principal and returns (body, headers); TesClient.create_task() is replaced by forward(). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Replace the middlewares page with an operator's guide to plugins: the phases of a task, pipelines, installing and enabling plugins, and the choices of clients. Update the configuration, API, access control, operations, development and reference pages, the README and CITATION.cff, and describe the upgrade from middlewares. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Remove credentials from the URLs of tasks that plugins of the forward phase changed, and check their inline contents before they are sent. Move the forwarding loop out of TaskRuns.create_task(), test that the mapped errors of the plugin engine keep their status, and note in the README that the routing plugins of foca-plugins aren't published yet. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Plugins of the forward phase can no longer change the method or path of the request (tasks are created with POST /ga4gh/tes/v1/tasks), nor choose credentials other than those of the backend: they may only drop them. Headers of accepted responses that FOCA refuses are left out instead of failing the attempt, which sent accepted tasks elsewhere. Without time left to connect, nothing is sent (connect_timeout). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Refuse outbound requests whose query isn't a mapping of names to lists of strings, or with headers that would change where or how they are sent (Host, Transfer-Encoding and others), so that they fail over instead of failing the request. Treat too deeply nested JSON of an accepted task as an unknown outcome. Document that plugins get the caller's validated access token. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideThis PR refactors task processing around FOCA 0.18’s plugin engine: proTES becomes a TES GatewayApp, executes plugin phases for validation, routing, forwarding, and response transformation, and enforces sanitization and outbound security boundaries. TES forwarding now reports FOCA attempt outcomes with ordered failover and preserves unknown outcomes, while legacy middleware/routing code is removed, configuration and API status semantics change, and documentation and tests are comprehensively migrated. Sequence diagram for FOCA plugin task processing and failoversequenceDiagram
actor Client
participant Controller
participant TaskRuns
participant Pipeline as FOCA_Pipeline
participant TES1 as TES_Backend_1
participant TES2 as TES_Backend_2
Client->>Controller: POST /ga4gh/tes/v1/tasks
Controller->>TaskRuns: create_task(task, inbound, principal)
TaskRuns->>Pipeline: request()
Pipeline-->>TaskRuns: sanitized and validated task
TaskRuns->>Pipeline: route(backends)
Pipeline-->>TaskRuns: ordered candidates
TaskRuns->>Pipeline: attempts(candidates)
Pipeline->>TES1: forward(outbound, task)
TES1-->>Pipeline: rejected or unavailable
Pipeline->>TES2: forward(outbound, task)
TES2-->>Pipeline: accepted(task_id, response)
Pipeline->>Pipeline: response phase
Pipeline-->>TaskRuns: transformed client response
TaskRuns-->>Controller: body and headers
Controller-->>Client: task response
Flow diagram for secure outbound TES forwardingflowchart TD
Start[Forward candidate task] --> Outbound[forward phase prepares outbound request]
Outbound --> Check{check_outbound passes?}
Check -->|No| Fail[Mark attempt failed and try next backend]
Check -->|Yes| Relay[relayed_task strips server fields, gateway tags, and URL credentials]
Relay --> Credentials[Add only selected backend credentials]
Credentials --> Send[TesClient.forward]
Send --> Result{Backend outcome}
Result -->|Accepted| Response[Run response phase and return response]
Result -->|Certain failure| Fail
Result -->|Unknown outcome| Unknown[Store SYSTEM_ERROR and stop failover]
File-Level Changes
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Documentation build overview
10 files changed ·
|
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## dev #346 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 27 23 -4
Lines 2195 2099 -96
=========================================
- Hits 2195 2099 -96 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Hey - I've found 3 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="pro_tes/ga4gh/tes/task_runs.py" line_range="259" />
<code_context>
+ db_document=db_document,
+ db_connector=db_connector,
+ )
+ except GatewayError:
+ # no backend accepted the task (in time), or a plugin of the
+ # `forward` phase rejected it
</code_context>
<issue_to_address>
**Accepted tasks lose tracking**
When a response-phase plugin raises an engine `GatewayError` after a backend accepts the task, `attempt.succeeded()` raises, then `create_task()` catches the error and `_discard_task()` deletes the stored task and owner roles even though the backend keeps running it; the caller loses tracking and cancellation access.
Preserve the stored task and its owner roles when a response-phase error occurs after the backend has accepted the task.
Also at `pro_tes/ga4gh/tes/task_runs.py:418-419`.
</issue_to_address>
### Comment 2
<location path="pro_tes/gateway.py" line_range="157" />
<code_context>
+ larger than `custom.controllers.post_task.max_inline_content`.
+ """
+ if isinstance(payload, dict):
+ handle_url_credentials(payload=payload, mode="strip")
+ limit = get_custom_config(CustomConfig).controllers.post_task.max_inline_content
+ check_inline_content(payload=payload, limit=limit)
</code_context>
<issue_to_address>
**Mapping payloads bypass sanitization**
When a request or forward plugin supplies a non-dict `Mapping` payload, `validate_task()` accepts any `Mapping`, but `sanitize_task()` and `relayed_task()` sanitize only `dict` instances. A plugin that supplies a mapping such as `UserDict` passes validation while URL credentials and oversized inline content bypass both checks and are sent to a backend.
Normalize accepted mappings to mutable dictionaries before sanitization and forwarding, or reject non-dict payloads consistently during validation.
Also at `pro_tes/gateway.py:279`.
</issue_to_address>
### Comment 3
<location path="pro_tes/ga4gh/tes/backends.py" line_range="669-670" />
<code_context>
# may raise before anything is sent, e.g., without credentials
- kwargs = self._request_params(data=data)
- timeout = kwargs.pop("timeout")
+ kwargs = self._request_params(data=data, params=params, auth=auth)
+ connect, read = kwargs.pop("timeout")
+ if connect_timeout is not None:
+ if connect_timeout <= 0:
</code_context>
<issue_to_address>
**Forwarding exceeds deadline**
When client-credentials token discovery or refresh takes longer than the remaining forwarding time, `_send()` calls `_request_params()` before applying `connect_timeout`, so credential requests consume the remaining budget while the stale timeout is still used for the TES request; the request starts after the deadline and the caller waits beyond the configured limit.
Recompute the remaining forwarding time after `_request_params()` and apply it to the TES request before sending.
Also at `pro_tes/ga4gh/tes/task_runs.py:306`.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 3 findings to address first, and the new default sends tasks to configured TES backends in order, so a wrong routing policy could silently send work—and its inputs—to an unintended configured backend; that execution cannot be undone by reverting. Enabled plugins also receive callers’ validated access tokens, making a mistaken trust decision consequential.
Blocking findings: pro_tes/ga4gh/tes/task_runs.py:259, pro_tes/gateway.py:157, pro_tes/ga4gh/tes/backends.py:670
Discard tasks only on errors before a backend accepted them, not on errors of the response phase. Accept only dict tasks from plugins, so that sanitization can't be bypassed with other mappings. Count the time taken to get a token against the time left to connect. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
Replaces proTES's own middlewares with FOCA 0.18's plugin engine (
foca.plugins), as decided in #321.pro_tes/gateway.py: proTES as a FOCA gateway (GatewayApp): task validation, sanitization after plugins (credentials in URLs stripped, inline contents limited) and outbound checks;relayed_task()drops server fields,gateway.*tags and URL credentials (also those offorwardplugins).TaskRuns.create_task()starts a pipeline run with the inbound request and the caller (built byfoca.plugins.adapterin the controller), runs therequestandroutephases, stores the task, then forwards it to the candidates in turn through theforwardphase and returns the body and headers of theresponsephase. Tasks without candidates, rejected by plugins, or accepted by no TES instance are not kept; outcome-unknown responses still stop failover (502,SYSTEM_ERROR).TesClient.create_task()is replaced byforward(), which sends the plugins' outbound request (query, headers, task) with the backend's credentials, without redirects;forward_reason()maps failures to the engine's attempt reasons. Forward plugins can't change the method or path (POST /ga4gh/tes/v1/tasks, checked incheck_outbound) and can't choose credentials other than the backend's (only drop them withauth: none), so that proTES's credentials can't be misdirected. Response headers that FOCA refuses are dropped instead of failing an accepted attempt; with no time left to connect, nothing is sent. Outbound requests with invalid queries or reserved headers (Host,Transfer-Encoding, ...) fail over (invalid_outbound); too deeply nested JSON of an accepted task counts as an unknown outcome (502).adapter.problem); the mapping inexceptions.pyis the fallback (a test checks it keeps the engine's statuses).foca.routing.ordered), set explicitly (commented) in the base config.custom.middlewaresis refused by FOCA with a hint.pro_tes.middleware,pro_tes.plugins(distance and random distribution, to move to foca-plugins astes.routing.distance/generic.routing.random),geopy, and the exceptions only they used.framework-free-tasks(ast-grep) now covers all ofpro_tes/exceptapp.py,exceptions.pyand the controllers.Principal.token); the docs say so and advise enabling only trusted plugins.docs/middlewares.md→docs/plugins.md(operator's view: phases, pipelines, installing/enabling plugins, client choices); configuration, API (statuses), access control, operations, development, reference, README, CITATION.cff; upgrade notes for all breaking changes.Breaking changes (for the release notes)
custom.middlewaresis refused; useplugins.pipeline.503(was500); new400(reservedgateway.*tags, invalid selections),508(loops), plugin rejection statuses.TaskRuns.create_task()takesinboundandprincipaland returns(body, headers);TesClient.create_task()→forward();NoTesInstancesAvailableand the middleware exceptions are removed.server.public_urlis now refused by FOCA (ValueError) before proTES's own check.Closes #333
Verification
coverage run -m pytest: 984 passed, 142 skipped (Helm not installed locally; chart tests run in CI);coverage report: 100%.ruff check .,ruff format --check .,mypy pro_tes tests: clean.ast-grep scan,ast-grep test --skip-snapshot-tests(4 rule tests),semgrep scan --config=.semgrep --error: clean.mkdocs build --strict: OK. Theplugins:examples indocs/plugins.mdvalidate with FOCA'sPluginsConfig.pre-commit run --all-files(hook repos can't be fetched through the sandbox proxy; its ruff, mypy, ast-grep and semgrep hooks were run directly as above), gitleaks and actionlint (not installed; no workflow changes).Sourcery review (3 threads, fixed in 812b3b2): tasks are discarded only on errors before a backend accepted them (FOCA already skips failing response steps); plugins' tasks must be dicts; token fetching counts against the time left to connect.
Declined review findings
test_settingsintests/test_gateway.pyinto other tests (low; it is cheap and documents the wiring).413from plugin-added inline contents (low): already covered bytest_create_task_inline_content_pluginintests/ga4gh/tes/test_server.py; theforwardphase is now covered bytest_forward_inline_content.ValueErrorhandling in the forwarding loop (low):relayed_task()moved out of thattry; the remainingValueErrors come from client construction (invalid backend entries), as the reason says.Principal.token) (medium): documented rather than stripped, since FOCA provides it on purpose (token exchange, pass-through); stripping it would be a FOCA-level decision._forward(), which returns from inside the loop; the guard stays as a defence against a FOCA bug and keeps mypy honest, tested bytest_no_outcome.Open questions
None.
🤖 Generated with Claude Code
Summary by Sourcery
Replace proTES middleware processing with FOCA's plugin engine for secure, configurable task routing and forwarding.
New Features:
Bug Fixes:
Enhancements:
Build:
Documentation:
Tests:
Chores: