Skip to content

refactor!: process tasks with FOCA plugins - #346

Merged
uniqueg merged 7 commits into
devfrom
refactor/task-plugins
Oct 31, 2026
Merged

uniqueg merged 7 commits into
devfrom
refactor/task-plugins

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 30, 2026 •

Copy link
Copy Markdown
Member

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 of forward plugins).
  • TaskRuns.create_task() starts a pipeline run with the inbound request and the caller (built by foca.plugins.adapter in the controller), runs the request and route phases, stores the task, then forwards it to the candidates in turn through the forward phase and returns the body and headers of the response phase. 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 by forward(), 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 in check_outbound) and can't choose credentials other than the backend's (only drop them with auth: 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).
  • Errors of the engine are returned as problem details by the controller (adapter.problem); the mapping in exceptions.py is the fallback (a test checks it keeps the engine's statuses).
  • Default pipeline: FOCA's ordered failover (foca.routing.ordered), set explicitly (commented) in the base config. custom.middlewares is refused by FOCA with a hint.
  • Removed: pro_tes.middleware, pro_tes.plugins (distance and random distribution, to move to foca-plugins as tes.routing.distance / generic.routing.random), geopy, and the exceptions only they used.
  • framework-free-tasks (ast-grep) now covers all of pro_tes/ except app.py, exceptions.py and the controllers.
  • Plugins get the caller's validated access token from FOCA (Principal.token); the docs say so and advise enabling only trusted plugins.
  • Docs: 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.middlewares is refused; use plugins.pipeline.
  • Tasks go to the TES instances in configured order with failover; distance-based and random distribution leave proTES (foca-plugins, once published); no more DB-IP/Nominatim lookups.
  • No TES instance accepting a task: 503 (was 500); new 400 (reserved gateway.* tags, invalid selections), 508 (loops), plugin rejection statuses.
  • TaskRuns.create_task() takes inbound and principal and returns (body, headers); TesClient.create_task() → forward(); NoTesInstancesAvailable and the middleware exceptions are removed.
  • A registry entry without server.public_url is 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. The plugins: examples in docs/plugins.md validate with FOCA's PluginsConfig.
  • Not run locally: 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).
  • CI: all checks passed (Lint, Test (MongoDB 7.0), Test (mongomock), Chart, Docs, Smoke test, Release readiness, Scan image, CodeQL, Read the Docs; image push/publish skipped on PRs).

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

  • Quality: fold test_settings in tests/test_gateway.py into other tests (low; it is cheap and documents the wiring).
  • Quality: add a pipeline test for 413 from plugin-added inline contents (low): already covered by test_create_task_inline_content_plugin in tests/ga4gh/tes/test_server.py; the forward phase is now covered by test_forward_inline_content.
  • Quality: narrow the ValueError handling in the forwarding loop (low): relayed_task() moved out of that try; the remaining ValueErrors come from client construction (invalid backend entries), as the reason says.
  • Quality: re-wrap some edited paragraphs (low, cosmetic).
  • Adversarial: plugins receive the caller's bearer token (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.
  • Quality: drop the unreachable "Forwarding ended without outcome" guard (medium, partly): the loop moved into _forward(), which returns from inside the loop; the guard stays as a defence against a FOCA bug and keeps mypy honest, tested by test_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:

  • Process TES task creation through FOCA's configurable plugin pipeline, including request, routing, forwarding, and response phases.
  • Support plugin-controlled backend selection, failover, outbound request customization, and client response customization with gateway safety checks.
  • Expose plugin engine errors as problem details and add loop detection, reserved gateway tag handling, and caller token access for trusted plugins.

Bug Fixes:

  • Prevent plugin or backend request changes from misdirecting proTES credentials or sending unsafe outbound requests.
  • Ensure credentials added by plugins, oversized inline content, reserved gateway tags, and invalid outbound requests are sanitized or rejected appropriately.

Enhancements:

  • Replace proTES middleware and built-in routing implementations with FOCA's plugin engine and ordered failover routing.
  • Refactor TES forwarding to preserve accepted-task outcomes, apply backend-specific credentials safely, and report structured attempt reasons.
  • Remove the distance-based and random routing dependencies and implementations from proTES.

Build:

  • Remove the geolocation dependency and update project configuration for FOCA plugin-based routing.

Documentation:

  • Replace middleware documentation with operator guidance for plugin pipelines, installation, configuration, security, API behavior, and upgrade changes.

Tests:

  • Add comprehensive coverage for gateway callbacks, plugin phases, failover behavior, outbound safety, response handling, error mapping, and legacy configuration rejection.

Chores:

  • Expand framework-free code checks across the pro_tes package while retaining framework integration only in application, controller, and exception layers.

uniqueg and others added 5 commits October 30, 2026 19:20
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]>
@sourcery-ai

sourcery-ai Bot commented Oct 30, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

This 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 failover

sequenceDiagram
    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
Loading

Flow diagram for secure outbound TES forwarding

flowchart 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]
Loading

File-Level Changes

Change Details Files
Replaced proTES’s custom middleware stack with FOCA’s plugin gateway and pipeline lifecycle.
  • Registered a TES GatewayApp with request, route, forward, and response phases.
  • Moved task validation, URL credential stripping, inline-content checks, tag filtering, and outbound safety checks into gateway callbacks.
  • Passed FOCA inbound requests and principals through the controller and TaskRuns pipeline execution.
  • Added plugin-driven routing, rejection, failover, response transformation, loop detection, and problem-detail handling.
pro_tes/gateway.py
pro_tes/app.py
pro_tes/celery_worker.py
pro_tes/ga4gh/tes/server.py
pro_tes/ga4gh/tes/task_runs.py
pro_tes/exceptions.py
.ast-grep/rules/framework-free-tasks.yml
Redesigned TES forwarding around FOCA outbound requests and backend attempt outcomes.
  • Replaced TesClient.create_task() with forward() supporting plugin-selected method-independent request metadata, query, headers, payload, and backend credentials.
  • Prevented credential misdirection, redirects, reserved headers, path/method changes, invalid queries, and unsafe outbound tasks.
  • Mapped connection, HTTP, authentication, timeout, and unknown-outcome failures to FOCA attempt reasons while preserving failover semantics.
  • Returned accepted backend response payloads and headers through the response phase; stored uncertain outcomes as SYSTEM_ERROR.
pro_tes/ga4gh/tes/backends.py
pro_tes/ga4gh/tes/task_runs.py
pro_tes/gateway.py
Changed configuration and deployment behavior to use FOCA plugin configuration and ordered failover by default.
  • Added an explicit foca.routing.ordered pipeline to the base configuration.
  • Rejected legacy custom.middlewares configuration with migration guidance.
  • Removed bundled distance/random routing, geopy, and middleware-specific exceptions and APIs.
  • Updated startup validation so FOCA loads plugins and validates gateway backends before serving.
pro_tes/config.yaml
pro_tes/config_models.py
pyproject.toml
pro_tes/app.py
pro_tes/celery_worker.py
pro_tes/middleware/**
pro_tes/plugins/**
Updated API behavior, security boundaries, documentation, and upgrade guidance for the plugin architecture.
  • Changed no-backend and timeout failures to 503, added plugin statuses, 508 loop detection, problem_type fields, and revised task-retention semantics.
  • Documented plugin phases, installation and enablement, client pipeline/backend selection, caller-token exposure, and trusted-plugin requirements.
  • Updated references, README, configuration, operations, access-control, API, development, and upgrade documentation.
docs/plugins.md
docs/api.md
docs/configuration.md
docs/access-control.md
docs/operations.md
docs/development.md
docs/upgrading.md
docs/reference.md
docs/index.md
README.md
mkdocs.yml
CITATION.cff
Expanded and reorganized tests around FOCA plugin execution, gateway callbacks, forwarding, security, and configuration migration.
  • Added fake plugin registration and gateway runtime isolation fixtures.
  • Covered request/route/forward/response phases, alternative rollback, rejection, sanitization, reserved tags, credential handling, failover, timeouts, loops, and response headers.
  • Updated backend client tests for outbound requests and reason mapping, and removed obsolete middleware and geolocation tests.
tests/ga4gh/tes/conftest.py
tests/ga4gh/tes/test_plugins.py
tests/ga4gh/tes/test_server.py
tests/ga4gh/tes/test_backends.py
tests/test_gateway.py
tests/conftest.py
tests/test_app.py
tests/test_security.py
tests/ga4gh/tes/test_access_control.py
tests/ga4gh/tes/test_backend_list.py
tests/ga4gh/tes/test_models.py
tests/test_fixtures.py
tests/middleware/**
tests/plugins/**

Possibly linked issues

  • #refactor!: process tasks with FOCA plugins: The PR implements the issue’s proposed FOCA plugin migration and its acceptance criteria, including gateway setup, forwarding outcomes, tag handling, and middleware removal.
  • refactor!: run task plugins with FOCA #321: The PR implements the same FOCA plugin-engine migration, including plugin phases, ordered failover, legacy middleware removal, and updated docs and tests.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@read-the-docs-community

read-the-docs-community Bot commented Oct 30, 2026 •

Copy link
Copy Markdown

Documentation build overview

📚 proTES | 🛠️ Build #35537187 | 📁 Comparing ddb6805 against latest (61b963a)

  🔍 Preview build  

10 files changed · + 1 added · ± 8 modified · - 1 deleted

+ Added

± Modified

- Deleted

@codecov

codecov Bot commented Oct 30, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (61b963a) to head (ddb6805).

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@uniqueg
uniqueg marked this pull request as ready for review October 30, 2026 23:49

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread pro_tes/ga4gh/tes/task_runs.py Resolved
Comment thread pro_tes/gateway.py Resolved
Comment thread pro_tes/ga4gh/tes/backends.py Resolved
uniqueg and others added 2 commits October 31, 2026 00:59
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]>
@uniqueg
uniqueg merged commit d9f3efa into dev Oct 31, 2026
20 checks passed
@uniqueg
uniqueg deleted the refactor/task-plugins branch October 31, 2026 00:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

refactor!: process tasks with FOCA plugins

1 participant