Skip to content

API reference

Reference of the app's Python code, generated from its docstrings. For the HTTP API, see API and the Swagger UI of a deployment.

App

app

App factory, and entry point for development.

The image serves the app with Gunicorn (pro_wes.wsgi:app, with proWES's settings, pro_wes.gunicorn); python -m pro_wes.app runs it with Flask's development server, on the host and port of the config (section server).

init_app

init_app() -> App

Initialize FOCA application.

Creates the storage directory of the runs, checks that it is writable, checks that the service info (config section service_info) has the fields of the WES specification, and that no configured WES instance (custom.wes.backends) is proWES itself; warns if no token issuer is trusted (security.auth.issuers). Run requests that aren't forms are refused before Connexion validates them (:py:func:pro_wes.ga4gh.wes.controllers.check_run_request_body).

Returns:

Type Description
App

FOCA application.

Raises:

Type Description
PermissionError

The storage directory of the runs is not writable.

ValidationError

The service info lacks WES fields or has invalid ones.

ValueError

A configured WES instance is at or below the public URL of proWES (server.public_url).

main

main() -> None

Run the app with Flask's development server.

On the host and port of the config (server.host, server.port), with its debug mode (server.debug). For development; not for production.

wsgi

WSGI entry point.

gunicorn

Gunicorn settings of proWES.

FOCA's settings for apps in containers (:py:mod:foca.gunicorn_config; e.g., the address 0.0.0.0:8080, or the port of the environment variable PORT), e.g.::

gunicorn --config python:pro_wes.gunicorn pro_wes.wsgi:app

The app is not created here, but by each Gunicorn worker after it forked (pro_wes.wsgi), so that it is initialized once per worker and MongoDB clients aren't shared across forks. The number of workers and threads can be set with the environment variables GUNICORN_PROCESSES and GUNICORN_THREADS, as before; other settings via GUNICORN_CMD_ARGS, which takes precedence over this module.

Configuration

config_models

Custom app config models.

DEFAULT_API_PATH module-attribute

DEFAULT_API_PATH = '/ga4gh/wes/v1'

Path of the WES API, relative to the URL of a backend, as the WES specification has it; that of the API of proWES too.

MAX_TIMEOUT module-attribute

MAX_TIMEOUT = 86400

Maximum timeout of requests to WES instances, in seconds (a day); larger values (and infinity) overflow the deadlines of FOCA's guarded client.

Timeout module-attribute

Timeout = Annotated[float, Field(gt=0, le=MAX_TIMEOUT, allow_inf_nan=False)]

Timeout of requests to WES instances, in seconds: positive and finite.

WesBackendEntry module-attribute

WesBackendEntry = Annotated[WesServiceEntry | WesRegistryEntry, Field(discriminator='type')]

Entry of custom.wes.backends.

MAX_QUERY_LIMIT module-attribute

MAX_QUERY_LIMIT = 2 ** 62

Largest maximum page size of GET /runs (max_page_size): MongoDB takes 8-byte integers only as the limit of a query (the page size plus one).

WesServiceEntry

Bases: ServiceEntry

WES instance of custom.wes.backends (type: ga4gh-wes).

The backend entry of FOCA (:py:class:foca.plugins.backends.ServiceEntry), whose types are those of TES instances only (FOCA 0.22), for WES instances, with the API path. proWES doesn't authenticate at WES instances yet (#120): auth must be none.

Parameters:

Name Type Description Default
type

Type of the entry (ga4gh-wes).

required
auth

Credentials for the WES instance: none (none).

required
api_path

Path of the WES API, relative to url, for WES instances that serve it elsewhere than the WES specification says; / if it is at url itself.

required
**data

Other fields of :py:class:foca.plugins.backends.ServiceEntry (url, url_schemes, id, labels, location).

required

Attributes:

Name Type Description
type Literal['ga4gh-wes']

Type of the entry.

auth Literal['none']

Credentials for the WES instance.

api_path str

Path of the WES API, relative to url, without trailing slash (empty if it is at url itself).

check_api_path classmethod

check_api_path(value: str) -> str

Check the API path, and remove trailing slashes.

Parameters:

Name Type Description Default
value str

API path, as given.

required

Returns:

Type Description
str

The API path.

Raises:

Type Description
ValueError

The path is not absolute, has characters other than unreserved ones (e.g., a query), or segments . or ...

WesRegistryEntry

Bases: RegistryEntry

Service registry of custom.wes.backends (type: ga4gh-service-registry).

The registry entry of FOCA (:py:class:foca.plugins.backends.RegistryEntry), whose verified WES instances are used, at the API path of the WES specification. proWES doesn't authenticate at WES instances yet (#120): auth must be none.

Parameters:

Name Type Description Default
auth

Credentials for the discovered WES instances: none (none).

required
**data

Other fields of :py:class:foca.plugins.backends.RegistryEntry.

required

Attributes:

Name Type Description
auth Literal['none']

Credentials for the discovered WES instances.

Wes

Bases: BaseModel

WES backend configuration.

Parameters:

Name Type Description Default
backends

WES instances that runs may be forwarded to, in order: configured ones (type: ga4gh-wes) and service registries whose verified WES instances are used (type: ga4gh-service-registry; cf. :py:mod:foca.plugins.backends). None by default: runs are refused until a deployment configures them.

required
max_response_size

Maximum size of each response of a WES instance, in bytes (by default FOCA's, 16 MiB); larger responses fail the request.

required
version_cache_ttl

Seconds that the WES version of a WES instance, as read from its service info, is cached (cf. :py:mod:pro_wes.ga4gh.wes.routing).

required

Attributes:

Name Type Description
backends list[WesBackendEntry]

WES instances that runs may be forwarded to, in order.

max_response_size PositiveInt

Maximum size of each response of a WES instance, in bytes.

version_cache_ttl PositiveInt

Seconds that the WES version of a WES instance, as read from its service info, is cached.

known_versions

known_versions() -> Self

Refuse labels wes.version of versions that proWES doesn't support.

Returns:

Type Description
Self

The configuration.

Raises:

Type Description
ValueError

The label of an entry is set to another version.

unique_ids

unique_ids() -> Self

Check that the identifiers of the entries are unique.

Returns:

Type Description
Self

The configuration.

Raises:

Type Description
ValueError

Two entries have the same identifier.

Defaults

Bases: BaseModel

Model for global default parameters.

Parameters:

Name Type Description Default
timeout

Timeout of requests to WES instances (e.g., status and cancellation), in seconds, for each request as a whole. May be overridden by more specific parameters for each endpoint.

required

Attributes:

Name Type Description
timeout Timeout

Timeout of requests to WES instances, in seconds.

PostRuns

Bases: BaseModel

Model for controller config parameters for operation POST /runs.

Attributes:

Name Type Description
storage_path Path

Location inside the app container where storage will be mounted.

db_insert_attempts int

How many times the controller will create new run identifiers for inserting a new run document in the database. If exceeded, a 500/InternalServerError will be returned.

id_charset str

Characters of run identifiers, taken as is (expressions such as string.digits are not evaluated).

id_length int

Length of run identifiers.

timeout_post Timeout

Timeout of sending a new workflow run request to a remote WES instance, and of reading run logs, in seconds, for each request as a whole.

timeout_job int | None

How long, in seconds, a background job tracking a workflow run is allowed to run. Set to None to disable timing out.

polling_wait float

How long, in seconds, the worker should wait in between status update calls.

polling_attempts int

How often the worker should attempt in a row to receive a valid run status response from the remote WES service until an error is raised and the job is set to state SYSTEM_ERROR. Once a valid response is obtained, the counter is reset to 1.

max_attachments NonNegativeInt

Maximum number of workflow attachments of a run (0 allows none); runs with more are rejected with 413 Content Too Large.

max_attachment_size PositiveInt

Maximum size of each workflow attachment, in bytes; runs with larger ones are rejected with 413 Content Too Large. All attachments together are limited by the size of request bodies (server.max_content_length).

max_tags_size Annotated[int, Field(ge=2)]

Maximum size of the tags of a run, in bytes: of their JSON text, as stored (UTF-8, after removing credentials in URLs, cf. url_credentials); runs with larger tags are rejected with 400 Bad Request. Stored runs with larger tags (e.g., stored before the limit) are listed by GET /runs with empty tags. At least 2, the size of no tags ({}).

url_credentials Literal['reject', 'strip']

What happens to runs with credentials in the URLs of their run requests (https://user:password@host/..., in workflow_url and in the strings of workflow_params, workflow_engine_parameters and tags; cf. pro_wes.utils.urls.has_credentials): they are rejected with 400 Bad Request (reject), or the credentials are removed (strip), before runs are stored or forwarded.

id_charset_valid classmethod

id_charset_valid(value: str) -> str

Ensure that the characters of run identifiers can be used.

Parameters:

Name Type Description Default
value str

Characters of run identifiers.

required

Returns:

Type Description
str

The characters.

Raises:

Type Description
ValueError

The characters are empty or an expression (e.g., string.digits), which FOCA no longer evaluates.

ListRuns

Bases: BaseModel

Model for controller config parameters for operation GET /runs.

Parameters:

Name Type Description Default
default_page_size

Number of runs per page of requests without page_size; 1 to max_page_size.

required
max_page_size

Largest number of runs per page; requests with larger page sizes (or below 1) are refused with 400 Bad Request, so that no request lists more runs at once.

required

Attributes:

Name Type Description
default_page_size PositiveInt

Number of runs per page of requests without page_size.

max_page_size Annotated[int, Field(ge=1, le=MAX_QUERY_LIMIT)]

Largest number of runs per page.

default_within_max

default_within_max() -> Self

Check that the default page size is at most the maximum.

Returns:

Type Description
Self

The configuration.

Raises:

Type Description
ValueError

The default page size is larger than the maximum.

CustomConfig

Bases: BaseModel

Custom app configuration.

Parameters:

Name Type Description Default
defaults

Global configuration parameters.

required
post_runs

Configuration parameters for operation POST /runs.

required
list_runs

Configuration parameters for operation GET /runs.

required
wes

WES backends that runs are forwarded to.

required

Attributes:

Name Type Description
defaults Defaults

Global configuration parameters.

post_runs PostRuns

Configuration parameters for operation POST /runs.

list_runs ListRuns

Configuration parameters for operation GET /runs.

wes Wes

WES backends that runs are forwarded to.

no_service_info classmethod

no_service_info(data: Any) -> Any

Refuse the service info of earlier versions (custom.service_info).

Without this check, it would be ignored, and the service info of the configuration served instead.

Parameters:

Name Type Description Default
data Any

Values of the section.

required

Returns:

Type Description
Any

The values, unchanged.

Raises:

Type Description
ValueError

The section has key service_info.

Controllers

controllers

Controller for GA4GH WES API endpoints.

GET /service-info is served by FOCA (foca.api.service_info; cf. pro_wes.ga4gh.wes.service_info).

The operations on runs get the owner of the caller (user_id, cf. :py:func:pro_wes.security.current_owner), which replaces any user_id of the request: callers create, list, read and cancel only their own runs.

RunWorkflow

RunWorkflow(*args: Any, **kwargs: Any) -> dict[str, str]

Start workflow run.

Controller for POST /runs.

Parameters:

Name Type Description Default
*args Any

Positional arguments passed along with request.

()
**kwargs Any

Additional keyword arguments passed along with request.

{}

Returns:

Type Description
dict[str, str]

Response object according to WES API schema RunId. Cf. pro_wes/api/20230914.tag_1_1_0.workflow_execution_service.openapi.yaml

Raises:

Type Description
Forbidden

The caller's token has no subject that can own runs (cf. :py:func:pro_wes.security.current_owner).

UrlEncodedAttachment

The run request is URL-encoded with workflow attachments (400).

ListRuns

ListRuns(*args: Any, **kwargs: Any) -> dict[str, Any]

Return list of workflow runs.

Controller for GET /runs.

Parameters:

Name Type Description Default
*args Any

Positional arguments passed along with request.

()
**kwargs Any

Keyword arguments passed along with request.

{}

Returns:

Type Description
dict[str, Any]

Response object according to WES API schema RunListResponse. Cf. pro_wes/api/20230914.tag_1_1_0.workflow_execution_service.openapi.yaml

Raises:

Type Description
Forbidden

The caller's token has no subject that can own runs (cf. :py:func:pro_wes.security.current_owner).

GetRunLog

GetRunLog(run_id: str, *args: Any, **kwargs: Any) -> dict[str, Any]

Return detailed information about a workflow run.

Controller for GET /runs/{run_id}.

Parameters:

Name Type Description Default
run_id str

Workflow run identifier.

required
*args Any

Positional arguments passed along with request.

()
**kwargs Any

Additional keyword arguments passed along with request.

{}

Returns:

Type Description
dict[str, Any]

Response object according to WES API schema RunLog. Cf. pro_wes/api/20230914.tag_1_1_0.workflow_execution_service.openapi.yaml

Raises:

Type Description
Forbidden

The run belongs to another caller, or the caller's token has no subject that can own runs (cf. :py:func:pro_wes.security.current_owner).

RunNotFound

The requested workflow run is not available.

GetRunStatus

GetRunStatus(run_id: str, *args: Any, **kwargs: Any) -> dict[str, Any]

Return status information about a workflow run.

Controller for GET /runs/{run_id}/status.

Parameters:

Name Type Description Default
run_id str

Workflow run identifier.

required
*args Any

Positional arguments passed along with request.

()
**kwargs Any

Additional keyword arguments passed along with request.

{}

Returns:

Type Description
dict[str, Any]

Response object according to WES API schema RunStatus. Cf. pro_wes/api/20230914.tag_1_1_0.workflow_execution_service.openapi.yaml

Raises:

Type Description
Forbidden

The run belongs to another caller, or the caller's token has no subject that can own runs (cf. :py:func:pro_wes.security.current_owner).

RunNotFound

The requested workflow run is not available.

CancelRun

CancelRun(run_id: str, *args: Any, **kwargs: Any) -> dict[str, str]

Cancel workflow run.

Controller for POST /runs/{run_id}/cancel.

Parameters:

Name Type Description Default
run_id str

Workflow run identifier.

required
*args Any

Positional arguments passed along with request.

()
**kwargs Any

Additional keyword arguments passed along with request.

{}

Returns:

Type Description
dict[str, str]

Response object according to WES API schema RunId. Cf. pro_wes/api/20230914.tag_1_1_0.workflow_execution_service.openapi.yaml

Raises:

Type Description
Forbidden

The run belongs to another caller, or the caller's token has no subject that can own runs (cf. :py:func:pro_wes.security.current_owner).

RunNotFound

The requested workflow run is not available.

ListTasks

ListTasks(run_id: str, *args: Any, **kwargs: Any) -> NoReturn

Return the tasks of a workflow run (WES 1.1.0).

Controller for GET /runs/{run_id}/tasks; not served yet (#124).

Parameters:

Name Type Description Default
run_id str

Workflow run identifier.

required
*args Any

Positional arguments passed along with request.

()
**kwargs Any

Additional keyword arguments passed along with request.

{}

Raises:

Type Description
TasksNotServed

Always (501 Not Implemented).

GetTask

GetTask(run_id: str, task_id: str, *args: Any, **kwargs: Any) -> NoReturn

Return a task of a workflow run (WES 1.1.0).

Controller for GET /runs/{run_id}/tasks/{task_id}; not served yet (#124).

Parameters:

Name Type Description Default
run_id str

Workflow run identifier.

required
task_id str

Task identifier.

required
*args Any

Positional arguments passed along with request.

()
**kwargs Any

Additional keyword arguments passed along with request.

{}

Raises:

Type Description
TasksNotServed

Always (501 Not Implemented).

check_run_request_body

check_run_request_body() -> None

Refuse run requests whose body Connexion can't read as a form.

Called before each request (before_request of the Flask app, cf. pro_wes.app.init_app), so before Connexion's validation, which fails with an AttributeError (500) on bodies that aren't forms. Decided by the headers only; the body isn't read. Other requests are left to the operations, and so are run requests without a token where one is required: Connexion refuses them with 401 before it reads the body, so that clients learn about the body only once they are authenticated.

Raises:

Type Description
UnsupportedMediaType

The run request isn't a form (415), e.g., JSON, or has no media type.

MissingBoundary

The run request is multipart/form-data without a boundary (400).

Unauthorized

The run request, which would be refused, has an invalid token (401; as FOCA's validation raises it, so that the token is validated once).

workflow_runs

Controllers for the /runs and children routes.

Upload

Bases: NamedTuple

Workflow attachment of a run request, checked and read.

Attributes:

Name Type Description
filename str

Name of the file as indicated in the run request.

name str

Safe file name, under which it is written to the working directory of the run.

content bytes

Contents of the file.

WorkflowRuns

WorkflowRuns()

Class for WES API server-side controller methods.

Attributes:

Name Type Description
config CustomConfig

Custom configuration of the app.

db_client Collection[dict[str, Any]]

Database collection storing workflow run objects.

Class constructor.

run_workflow

run_workflow(**kwargs: Any) -> dict[str, str]

Start workflow run.

Controller for POST /runs.

Parameters:

Name Type Description Default
**kwargs Any

Additional keyword arguments passed along with request.

{}

Returns:

Type Description
dict[str, str]

Workflow run identifier.

Raises:

Type Description
NoBackendAvailable

No WES instance is available (custom.wes.backends), or none that can run the request and some didn't answer so far; nothing is stored.

InvalidFieldsProblem

No WES instance can run the request unchanged (by its WES version); nothing is stored.

list_runs

list_runs(**kwargs: Any) -> dict[str, Any]

Return list of workflow runs.

Controller for GET /runs.

Parameters:

Name Type Description Default
**kwargs Any

Keyword arguments passed along with request.

{}

Returns:

Type Description
dict[str, Any]

Response object according to WES API schema RunListResponse. Cf. pro_wes/api/20230914.tag_1_1_0.workflow_execution_service.openapi.yaml

Raises:

Type Description
InvalidFieldsProblem

The page size is below 1 or above custom.list_runs.max_page_size, or the page token is malformed (400).

get_run_log

get_run_log(run_id: str, **kwargs: Any) -> dict[str, Any]

Return detailed information about a workflow run.

Controller for GET /runs/{run_id}.

Parameters:

Name Type Description Default
run_id str

Workflow run identifier.

required
**kwargs Any

Additional keyword arguments passed along with request.

{}

Returns:

Type Description
dict[str, Any]

Response object according to WES API schema RunLog. Cf. pro_wes/api/20230914.tag_1_1_0.workflow_execution_service.openapi.yaml

Raises:

Type Description
Forbidden

The requester is not allowed to access the resource.

RunNotFound

The requested workflow run is not available.

get_run_status

get_run_status(run_id: str, **kwargs: Any) -> dict[str, Any]

Return status information about a workflow run.

Controller for GET /runs/{run_id}/status.

Parameters:

Name Type Description Default
run_id str

Workflow run identifier.

required
**kwargs Any

Additional keyword arguments passed along with request.

{}

Returns:

Type Description
dict[str, Any]

Response object according to WES API schema RunStatus. Cf. pro_wes/api/20230914.tag_1_1_0.workflow_execution_service.openapi.yaml

Raises:

Type Description
Forbidden

The requester is not allowed to access the resource.

RunNotFound

The requested workflow run is not available.

cancel_run

cancel_run(run_id: str, **kwargs: Any) -> dict[str, str]

Cancel workflow run.

Controller for POST /runs/{run_id}/cancel.

Only runs in a cancelable state (:py:attr:State.is_cancelable), and runs of unknown state or that proWES itself set to SYSTEM_ERROR (e.g., it lost track of them) that have a remote run, are canceled at the WES instance; others (e.g., finished runs) are refused without contacting it. The stored state is left as it is, also if the WES instance refuses the cancellation or can't be reached.

Parameters:

Name Type Description Default
run_id str

Workflow run identifier.

required
**kwargs Any

Additional keyword arguments passed along with request.

{}

Returns:

Type Description
dict[str, str]

Workflow run identifier, once the WES instance has accepted the

dict[str, str]

cancellation.

Raises:

Type Description
Forbidden

The requester is not allowed to access the resource, or the WES instance answered with 403.

RunNotFound

The requested workflow run is not available.

RunNotCancelable

The workflow run is not in a cancelable state.

WesEndpointProblem

The workflow run has no remote run to cancel.

BadRequest

The WES instance answered with 400.

Unauthorized

The WES instance answered with 401.

EngineRefused

The WES instance answered with another error (e.g., 404, 500).

EngineInvalidResponse

The WES instance sent an invalid response.

EngineUnavailable

The WES instance couldn't be reached, or its response not read.

service_info

WES fields of the service info (GET /service-info).

The service info is served by FOCA (foca.api.service_info) from config section service_info: the fields of the GA4GH service info and the WES fields that are configured (e.g., workflow_type_versions) from service_info.service, the system state counts from :py:func:runtime_fields, which FOCA calls for each request. The configured workflow types and versions are read by :py:func:pro_wes.utils.config.workflow_type_versions.

runtime_fields

runtime_fields() -> dict[str, Any]

Get the fields of the service info that are computed at runtime.

Called by FOCA (service_info.runtime_fields in the configuration) in an app context, on startup and for each request.

Returns:

Type Description
dict[str, Any]

System state counts (system_state_counts).

state_counts

state_counts() -> dict[str, int]

Count the stored runs by state.

Must be called in an app context.

Returns:

Type Description
dict[str, int]

Number of runs in each state that proWES knows (State); runs in

dict[str, int]

other states are left out (with a warning).

models

proWES schema models.

MetaEnum

Bases: EnumMeta

Metaclass for enumerators.

BaseEnum

Bases: Enum

Base class for enumerators.

Attachment

Bases: BaseModel

Model for workflow attachment.

Stored with the run; the contents are written to the storage of the runs only (not to the database).

Parameters:

Name Type Description Default
filename

Name of the file as indicated in the run request.

required
path

Path to the file on the app's storage system, inside the working directory of the run, with a safe file name.

required

RunRequest

Bases: BaseModel

Model for WES API RunRequest schema.

workflow_engine and workflow_engine_version of WES 1.1.0 (pro_wes.ga4gh.wes.versions.ENGINE_FIELDS) are None unless set: empty fields choose no engine. Only WES instances of WES 1.1 can run requests that set them (cf. pro_wes.ga4gh.wes.versions).

Parameters:

Name Type Description Default
workflow_params

Workflow parameters. Cf. pro_wes/api/20230914.tag_1_1_0.workflow_execution_service.openapi.yaml

required
workflow_type

Workflow type. Cf. pro_wes/api/20230914.tag_1_1_0.workflow_execution_service.openapi.yaml

required
workflow_type_version

Workflow type version. Cf. pro_wes/api/20230914.tag_1_1_0.workflow_execution_service.openapi.yaml

required
tags

Tags. Cf. pro_wes/api/20230914.tag_1_1_0.workflow_execution_service.openapi.yaml

required
workflow_engine_parameters

Workflow engine parameters. Cf. pro_wes/api/20230914.tag_1_1_0.workflow_execution_service.openapi.yaml

required
workflow_url

Workflow URL. Cf. pro_wes/api/20230914.tag_1_1_0.workflow_execution_service.openapi.yaml

required
workflow_engine

Workflow engine. Cf. pro_wes/api/20230914.tag_1_1_0.workflow_execution_service.openapi.yaml

required
workflow_engine_version

Workflow engine version. Cf. pro_wes/api/20230914.tag_1_1_0.workflow_execution_service.openapi.yaml

required

Attributes:

Name Type Description
workflow_params str

Workflow parameters. Cf. pro_wes/api/20230914.tag_1_1_0.workflow_execution_service.openapi.yaml

workflow_type str

Workflow type. Cf. pro_wes/api/20230914.tag_1_1_0.workflow_execution_service.openapi.yaml

workflow_type_version str

Workflow type version. Cf. pro_wes/api/20230914.tag_1_1_0.workflow_execution_service.openapi.yaml

tags str | None

Tags. Cf. pro_wes/api/20230914.tag_1_1_0.workflow_execution_service.openapi.yaml

workflow_engine_parameters str | None

Workflow engine parameters. Cf. pro_wes/api/20230914.tag_1_1_0.workflow_execution_service.openapi.yaml

workflow_url str

Workflow URL. Cf. pro_wes/api/20230914.tag_1_1_0.workflow_execution_service.openapi.yaml

workflow_engine str | None

Workflow engine. Cf. pro_wes/api/20230914.tag_1_1_0.workflow_execution_service.openapi.yaml

workflow_engine_version str | None

Workflow engine version. Cf. pro_wes/api/20230914.tag_1_1_0.workflow_execution_service.openapi.yaml

Raises:

Type Description
ValidationError

The class was instantianted with an illegal data type.

empty_engine_field_chooses_none classmethod

empty_engine_field_chooses_none(value: str | None) -> str | None

Treat empty workflow engine fields as not set.

Empty fields choose no engine (version), so they are neither stored nor forwarded.

Parameters:

Name Type Description Default
value str | None

Field value to be validated.

required

Returns:

Type Description
str | None

The value, or None if it is empty.

workflow_engine_set_with_version

workflow_engine_set_with_version() -> RunRequest

Ensure that a workflow engine version comes with its engine.

The WES specification requires workflow_engine if workflow_engine_version is set. Requests of POST /runs are checked before, with an error that points at the field; this check keeps the model consistent wherever else it is built (e.g., the form data of WesClient.post_run).

Returns:

Type Description
RunRequest

The validated model.

Raises:

Type Description
ValueError

The workflow engine version is set without the workflow engine.

required_str_field_not_empty classmethod

required_str_field_not_empty(value: str) -> str

Ensure that required strings are not empty.

Parameters:

Name Type Description Default
value str

Field value to be validated.

required

Returns:

Type Description
str

Validated field value.

Raises:

Type Description
ValueError

The value is either missing or constitutes an empty string.

json_serialized_object_field_valid classmethod

json_serialized_object_field_valid(value: str | None, info: ValidationInfo) -> str

Ensure that a string can be JSON deserialized into an object.

Due to limitations of OpenAPI, the form data fields indicated in the decorator were defined in the WES API specification as atomic strings, even though those strings are expected to be JSON-serialized representations of objects. This validator ensures that the values provided to these form fields can indeed be deserialized into objects.

Note that the WES specification does not currently dictate how clients should indicate that no value is to be specified for optional fields. In order to maintain compatibility with upstream clients, while ensuring that a JSON deserializable representation is propagated, empty strings, missing field values and null for are set to the empty JSON string object '{}' for optional fields and cause a ValueError to be raised for required fields.

The values of tags and workflow_engine_parameters must be strings, as in the WES specification (not checked for stored runs, validation context STORED_CONTEXT).

Parameters:

Name Type Description Default
value str | None

Field value to be validated.

required
info ValidationInfo

Validation context, with the name of the field.

required

Returns:

Type Description
str

Validated (and possibly sanitized) field value.

Raises:

Type Description
ValueError

The value is required but it is either missing or does not represent any actual content.

ValueError

The value could not be JSON deserialized, or has an object with duplicate keys (not checked for stored runs).

ValueError

The value could be JSON decoded, but the deserialized value does not represent an object/dictionary.

ValueError

The tags or workflow engine parameters have values other than strings.

workflow_type_and_version_supported

workflow_type_and_version_supported(info: ValidationInfo) -> RunRequest

Ensure that this instance supports the workflow type and version.

Requests of stored runs (validation context STORED_CONTEXT) are not checked: the app accepted them, possibly with another configuration than that of the process reading them (e.g., the worker).

Parameters:

Name Type Description Default
info ValidationInfo

Validation context.

required

Returns:

Type Description
RunRequest

The validated model.

Raises:

Type Description
NoSuitableEngine

No suitable workflow engine known to process request.

Log

Bases: BaseModel

Model for task log, including the log of the workflow engine itself.

Cf. pro_wes/api/20230914.tag_1_1_0.workflow_execution_service.openapi.yaml

Attributes:

Name Type Description
cmd list[str] | None

List of executed commands.

end_time str | None

Time when the task stopped executing, in ISO 8601 format "%Y-%m-%dT%H:%M:%SZ".

exit_code int | None

Exit code of the task.

name str | None

The name of the task.

start_time str | None

Time when the task started executing, in ISO 8601 format "%Y-%m-%dT%H:%M:%SZ".

stderr str | None

A URL to retrieve standard error logs of the task.

stdout str | None

A URL to retrieve standard output logs of the task.

system_logs list[str] | None

Logs of the system that are relevant to the task or run, but not tied to it (e.g., the error message of a SYSTEM_ERROR); WES 1.1.0.

State

Bases: BaseEnum

Enumerator for supported workflow run states.

Cf. pro_wes/api/20230914.tag_1_1_0.workflow_execution_service.openapi.yaml

Attributes:

Name Type Description
UNKNOWN

The state of the task is unknown.

QUEUED

The task is queued.

INITIALIZING

The task has been assigned to a worker and is currently preparing to run.

RUNNING

The task is running.

PAUSED

The task is paused.

COMPLETE

The task has completed running.

EXECUTOR_ERROR

The task encountered an error in one of the Executor processes.

SYSTEM_ERROR

The task was stopped due to a system error.

CANCELED

The task was canceled by the user.

CANCELING

The task was canceled by the user, and is in the process of stopping.

PREEMPTED

The task was stopped (preempted) by the system (WES 1.1.0), e.g., as the resources it ran on were reclaimed; final: proWES doesn't resubmit the run.

is_finished property

is_finished: bool

Check if a state is among the set of finished states.

is_cancelable property

is_cancelable: bool

Check if a state is among the set of cancelable states.

RunLog

Bases: BaseModel

Model for entire workflow run log.

Parameters:

Name Type Description Default
outputs

Name and destination of workflow outputs.

required
request

Form data passed during original workflow run request.

required
run_id

Unique identifier of workflow run.

required
run_log

Log of workflow engine itself.

required
state

State of workflow run.

required
task_logs

List of workflow task/job logs.

required

Attributes:

Name Type Description
outputs dict[str, Any] | None

Name and destination of workflow outputs.

request RunRequest | None

Form data passed during original workflow run request.

run_id str | None

Unique identifier of workflow run.

run_log Log | None

Log of workflow engine itself.

state State

State of workflow run.

task_logs list[Log] | None

List of workflow task/job logs.

WesEndpoint

Bases: BaseModel

Model for information on the external WES endpoint.

The endpoint to which the incoming workflow run request was relayed.

Parameters:

Name Type Description Default
host

Host at which the WES API is served that is processing this request; note that this should include the path information but not the base path path defined in the WES API specification; e.g., specify https://my.wes.com/api if the actual API is hosted at https://my.wes.com/api/ga4gh/wes/v1.

required
base_path

Override the default path suffix defined in the WES API specification, i.e., /ga4gh/wes/v1.

required
run_id

Identifier for workflow run on external WES endpoint.

required
wes_version

WES version of the WES instance that the run was forwarded in (e.g., 1.0; cf. :py:mod:pro_wes.ga4gh.wes.versions); none for runs stored by earlier versions of proWES.

required

Attributes:

Name Type Description
host str

Host at which the WES API is served that is processing this request; note that this should include the path information but not the base path path defined in the WES API specification; e.g., specify https://my.wes.com/api if the actual API is hosted at https://my.wes.com/api/ga4gh/wes/v1.

base_path str | None

Override the default path suffix defined in the WES API specification, i.e., /ga4gh/wes/v1.

run_id str | None

Identifier for workflow run on external WES endpoint.

wes_version str | None

WES version of the WES instance that the run was forwarded in.

DbDocument

Bases: BaseModel

Model for workflow run request database document.

Parameters:

Name Type Description Default
attachments

Names of attached files.

required
run_log

Complete logging information for workflow run.

required
system_error_by_prowes

Whether proWES itself set the state to SYSTEM_ERROR (e.g., it lost track of the run), rather than the WES instance reporting it.

required
task_id

Identifier of worker task.

required
user_id

Identifier of resource owner.

required
wes_endpoint

Information about the endpoint to where the run request was forwarded.

required
work_dir

Working directory for workflow run.

required

Attributes:

Name Type Description
attachments list[Attachment]

Names of attached files.

run_log RunLog

Complete logging information for workflow run.

system_error_by_prowes bool

Whether proWES itself set the state to SYSTEM_ERROR (e.g., it lost track of the run), rather than the WES instance reporting it.

task_id str | None

Identifier of worker task.

user_id str | None

Identifier of resource owner.

wes_endpoint WesEndpoint | None

Information about the endpoint to where the run request was forwarded.

work_dir str | None

Working directory for workflow run.

RunId

Bases: BaseModel

Response model for POST /runs.

Parameters:

Name Type Description Default
run_id

Workflow run identifier.

required

Attributes:

Name Type Description
run_id str

Workflow run identifier.

RunStatus

Bases: BaseModel

Response model for GET /runs/{run_id}/status.

Parameters:

Name Type Description Default
run_id

Workflow run identifier.

required
state

Workflow run state.

required

Attributes:

Name Type Description
run_id str

Workflow run identifier.

state State

Workflow run state.

ErrorResponse

Bases: BaseModel

Response model for WES errors.

Parameters:

Name Type Description Default
msg

Detailed error message.

required
status_code

HTTP status code.

required

Attributes:

Name Type Description
msg str | None

Detailed error message.

status_code int

HTTP status code.

RunSummary

Bases: RunStatus

Summary of a workflow run, as listed by GET /runs (WES 1.1.0).

Parameters:

Name Type Description Default
run_id

Workflow run identifier.

required
state

Workflow run state.

required
start_time

When the run started executing, in ISO 8601 format.

required
end_time

When the run stopped executing, in ISO 8601 format.

required
tags

Key-value tags added by the client when it created the run.

required

Attributes:

Name Type Description
run_id str

Workflow run identifier.

state State

Workflow run state.

start_time str | None

When the run started executing, in ISO 8601 format.

end_time str | None

When the run stopped executing, in ISO 8601 format.

tags dict[str, str]

Key-value tags added by the client when it created the run.

RunListResponse

Bases: BaseModel

List of workflow runs that the service has processed or is processing.

Items are RunSummary or RunStatus (WES 1.0.1 instances), as WES 1.1.0 allows (anyOf).

Parameters:

Name Type Description Default
runs

List of runs, with the run identifier and state of each, and the summary fields where the WES instance returns them.

required
next_page_token

Token to receive the next page of results.

required

WorkflowTypeVersion

Bases: BaseModel

Available workflow types supported by a given instance of the service.

Parameters:

Name Type Description Default
workflow_type_version

List of one or more acceptable versions for the workflow type.

required

WorkflowEngineVersion

Bases: BaseModel

Available versions of a workflow engine (WES 1.1.0).

Parameters:

Name Type Description Default
workflow_engine_version

List of one or more available versions of the workflow engine; an array, as in the WES specification (not null).

required

DefaultWorkflowEngineParameter

Bases: BaseModel

Model for default workflow engine parameters.

Parameters:

Name Type Description Default
name

Parameter name.

required
type

Parameter type.

required
default_value

Stringified version of default parameter.

required

Attributes:

Name Type Description
name str | None

Parameter name.

type str | None

Parameter type.

default_value str | None

Stringified version of default parameter.

ServiceInfoWesBase

Bases: BaseModel

Base model for WES-specific service info fields.

Parameters:

Name Type Description Default
workflow_type_versions

Workflow types and versions supported by this service.

required
supported_wes_versions

The version(s) of the WES schema supported by this service.

required
supported_filesystem_protocols

The filesystem protocols supported by this service.

required
workflow_engine_versions

Workflow engine versions supported by this service.

required
default_workflow_engine_parameters

Default workflow engine parameters set by this service.

required
auth_instructions_url

URL to web page with human-readable instructions on how to get an authorization token for use with this service.

required
tags

Additional information about this service as key-value pairs.

required

Attributes:

Name Type Description
workflow_type_versions dict[str, WorkflowTypeVersion]

Workflow types and versions supported by this service.

supported_wes_versions list[str]

The version(s) of the WES schema supported by this service.

supported_filesystem_protocols list[str]

The filesystem protocols supported by this service.

workflow_engine_versions dict[str, WorkflowEngineVersion]

Workflow engine versions supported by this service.

default_workflow_engine_parameters list[DefaultWorkflowEngineParameter]

Default workflow engine parameters set by this service.

auth_instructions_url str

URL to web page with human-readable instructions on how to get an authorization token for use with this service.

tags dict[str, str]

Additional information about this service as key-value pairs.

ServiceInfoBase

Bases: ServiceInfoWesBase, Service

Based model for service info.

ServiceInfo

Bases: ServiceInfoBase

Full model for service info.

Checks the service info that FOCA serves on startup (pro_wes.app), as FOCA checks the fields of the GA4GH service info only, and the service info of remote WES services (pro_wes.ga4gh.wes.client_wes).

Parameters:

Name Type Description Default
system_state_counts

State counts for workflow runs available on this service.

required

Attributes:

Name Type Description
system_state_counts dict[str, int]

State counts for workflow runs available on this service.

models

proWES schema models.

Organization

Bases: BaseModel

Model for organization implementing GA4GH services.

Attributes:

Name Type Description
name str

Name of the organization responsible for the service.

url AnyUrl

URL of the website of the organization (RFC 3986 format).

ServiceType

Bases: BaseModel

Model for GA4GH service type.

Attributes:

Name Type Description
group str

Namespace in reverse domain name format. Use org.ga4gh for implementations compliant with official GA4GH specifications. For services with custom APIs not standardized by GA4GH, or implementations diverging from official GA4GH specifications, use a different namespace (e.g. your organization's reverse domain name).

artifact str

Name of the API or GA4GH specification implemented. Official GA4GH types should be assigned as part of standards approval process. Custom artifacts are supported.

version str

Version of the API or specification. GA4GH specifications use semantic versioning.

Service

Bases: BaseModel

Model for GA4GH service.

Attributes:

Name Type Description
id str

Unique ID of this service. Reverse domain name notation is recommended, though not required. The identifier should attempt to be globally unique so it can be used in downstream aggregator services e.g. Service Registry.

name str

Name of this service. Should be human readable.

type ServiceType

Type of this service.

description str | None

Description of the service. Should be human readable and provide information about the service.

organization Organization

Organization providing the service.

contactUrl AnyUrl | EmailStr | None

URL of the contact for the provider of this service, e.g. a link to a contact form (RFC 3986 format), or an email (RFC 2368 format).

documentationUrl AnyUrl | None

URL of the documentation of this service (RFC 3986 format). This should help someone learn how to use your service, including any specifics required to access data, e.g. authentication.

createdAt datetime | None

Timestamp describing when the service was first deployed and available (RFC 3339 format).

updatedAt datetime | None

Timestamp describing when the service was last updated (RFC 3339 format).

environment str | None

Environment the service is running in. Use this to distinguish between production, development and testing/staging deployments. Suggested values are prod, test, dev, staging. However this is advised and not enforced.

version str

Version of the service being described. Semantic versioning is recommended, but other identifiers, such as dates or commit hashes, are also allowed. The version should be changed whenever the service is updated.

WES instances and client

backends

WES backends of proWES: configured and discovered in service registries.

The backend list custom.wes.backends is a typed backend list of FOCA (:py:mod:foca.plugins.backends), with entries for WES instances (:py:class:pro_wes.config_models.WesServiceEntry) and service registries (:py:class:pro_wes.config_models.WesRegistryEntry). FOCA 0.22 knows the backends of TES gateways only, so the API type of WES is registered here (API_TYPES, unless FOCA has one), and :py:class:WesBackendList takes the entries of proWES; expanding them, discovery (GET /services and GET /verifications of each registry, with FOCA's guarded HTTP client) and its caches are FOCA's.

New runs go to the first backend of the list that can run them, by its WES version (:py:func:pro_wes.ga4gh.wes.routing.select_backend), until plugins choose them (#121).

The API type is registered when this module is imported, which the app (pro_wes.app) and the controllers do before any backend list is used; it must match the entry type of :py:class:pro_wes.config_models.WesServiceEntry (ga4gh-wes) and DEFAULT_API_PATH.

WES_API module-attribute

WES_API = 'wes'

API of the backends (cf. foca.plugins.backends.API_TYPES).

WesBackendList

WesBackendList(entries: Sequence[WesServiceEntry | WesRegistryEntry], public_url: str | None = None)

Bases: BackendList

Backends of proWES, from its backend list (custom.wes.backends).

FOCA's backend list (:py:class:foca.plugins.backends.BackendList), whose validation knows the entries of TES instances only (FOCA 0.22), with the entries of proWES, validated by its config model (:py:class:pro_wes.config_models.Wes).

Attributes:

Name Type Description
entries

Entries, in order.

api

API of the backends (wes).

public_url

Public URL of proWES, normalized, if known: backends at or below it are never candidates.

Create the list.

Parameters:

Name Type Description Default
entries Sequence[WesServiceEntry | WesRegistryEntry]

Entries, in order, validated.

required
public_url str | None

Public URL of proWES (e.g., server.public_url).

None

get_backend_list

get_backend_list() -> WesBackendList

Get the backend list of proWES.

Must be called in an app context.

Returns:

Type Description
WesBackendList

The backends of custom.wes.backends, without those at or below the

WesBackendList

public URL of proWES (server.public_url).

check_backends

check_backends() -> None

Check the backend list, on startup.

Must be called in an app context. Reads no registry.

Raises:

Type Description
ValueError

The list has registry entries, but proWES has no public URL (server.public_url), so a registry that lists proWES itself couldn't be told apart (as FOCA's gateways require it); or a configured WES instance, or its WES API (url and api_path), is at or below the public URL, so that runs would be forwarded to proWES itself.

api_path

api_path(backend: Backend, backend_list: WesBackendList) -> str

Get the path of the WES API of a backend.

Parameters:

Name Type Description Default
backend Backend

Candidate of the list.

required
backend_list WesBackendList

List that it comes from.

required

Returns:

Type Description
str

API path of its entry, for configured WES instances; that of the WES

str

specification, for discovered ones (registries list the URLs of

str

services with it, cf. API_TYPES).

routing

Routing of new runs to WES instances, by their WES versions.

The WES version of a WES instance (:py:func:backend_version) is the label wes.version of its entry; otherwise, what its service info reports (read without credentials, leniently, and cached per process for custom.wes.version_cache_ttl seconds). WES instances of unknown versions count as the oldest supported version (:py:data:pro_wes.ga4gh.wes.versions.OLDEST).

New runs go to the first WES instance of the backend list that can run them unchanged (:py:func:eligible_backends, :py:func:select_backend), in the version of that WES instance. Until FOCA's gateway plugins choose and order the WES instances (#121), these are the candidates of the route phase.

PROBE_TIMEOUT module-attribute

PROBE_TIMEOUT = 5.0

Seconds that reading the service info of a WES instance may take, and that all reads for one run may take before the cached versions count.

PROBE_RETRY module-attribute

PROBE_RETRY = 60.0

Seconds after which a failed read, or one without a supported version, is tried again.

PROBE_REFUSED module-attribute

PROBE_REFUSED = frozenset({HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN})

Statuses of service infos that need credentials (logged with a hint).

PROBE_NOT_FOUND module-attribute

PROBE_NOT_FOUND = frozenset({HTTPStatus.NOT_FOUND, HTTPStatus.GONE})

Statuses of WES instances without a service info, which count as answers.

BackendVersions

BackendVersions()

WES versions of WES instances, from their service info, cached.

Thread-safe (a lost update only reads a service info once more, and failures keep what other threads have read meanwhile); each process (e.g., each Gunicorn worker) has its own cache.

Create an empty cache.

clear

clear() -> None

Remove all cached versions.

get

get(backend: Backend, probe: bool = True, timeout: float = PROBE_TIMEOUT) -> WesVersion

Get the WES version of a WES instance.

Never raises: runs can be forwarded to WES instances of unknown versions.

Parameters:

Name Type Description Default
backend Backend

Backend.

required
probe bool

Whether to read the service info of the WES instance if no version is cached, or the cached one expired.

True
timeout float

Time that reading the service info may take, in seconds.

PROBE_TIMEOUT

Returns:

Type Description
WesVersion

The version of the label wes.version of the backend, else that

WesVersion

of its service info, else (e.g., if the WES instance is

WesVersion

unavailable) the oldest supported version.

was_read

was_read(backend: Backend) -> bool

Tell whether reading the service info of a WES instance was tried.

Parameters:

Name Type Description Default
backend Backend

Backend.

required

Returns:

Type Description
bool

Whether this process has tried to read it (and still knows).

confirmed

confirmed(backend: Backend) -> bool

Tell whether a WES instance stated its WES version or answered at all.

Doesn't read its service info.

Parameters:

Name Type Description Default
backend Backend

Backend.

required

Returns:

Type Description
bool

Whether the version comes from the label of the backend or an

bool

answer of the WES instance, not from having no answer so far.

SelectedBackend dataclass

SelectedBackend(url: str, api_path: str, version: WesVersion)

WES instance that a new run is forwarded to.

Attributes:

Name Type Description
url str

Base URL of the WES instance.

api_path str

Path of its WES API.

version WesVersion

Its WES version, which the run is forwarded in.

label_version

label_version(backend: Backend) -> WesVersion | None

Get the WES version that the label wes.version of a backend states.

Parameters:

Name Type Description Default
backend Backend

Backend.

required

Returns:

Type Description
WesVersion | None

The version, if the label is set to a supported one (others stop the

WesVersion | None

app on startup, cf. :py:class:pro_wes.config_models.Wes).

read_service_info

read_service_info(backend: Backend, timeout: float = PROBE_TIMEOUT) -> tuple[int, Any]

Read the service info of a WES instance, without credentials.

Must be called in an app context.

Parameters:

Name Type Description Default
backend Backend

Backend.

required
timeout float

Time that reading the service info may take, in seconds.

PROBE_TIMEOUT

Returns:

Type Description
tuple[int, Any]

Status and JSON body of the response (None if it is no JSON).

Raises:

Type Description
EngineUnavailable

The request failed.

backend_version

backend_version(backend: Backend, probe: bool = True, timeout: float = PROBE_TIMEOUT) -> WesVersion

Get the WES version of a WES instance (cf. :py:class:BackendVersions).

Parameters:

Name Type Description Default
backend Backend

Backend.

required
probe bool

Whether its service info may be read now.

True
timeout float

Time that reading the service info may take, in seconds.

PROBE_TIMEOUT

Returns:

Type Description
WesVersion

The version; the oldest supported one if it is unknown.

eligible_backends

eligible_backends(request: Any, backends: list[Backend]) -> list[Backend]

Get the WES instances that can run a run request unchanged.

Runs that every supported version can express can run anywhere, and need no service info. For other runs, no further service info is read once PROBE_TIMEOUT seconds have passed, so that unavailable WES instances don't keep the request waiting; the remaining ones count with what is cached (cf. :py:meth:BackendVersions.confirmed). WES instances never read come first, so that an unavailable one can't keep them from being read.

Parameters:

Name Type Description Default
request Any

Run request of the canonical WES version (form fields).

required
backends list[Backend]

Backends, in order.

required

Returns:

Type Description
list[Backend]

The backends that can run the request, in order.

select_backend

select_backend(request: dict[str, Any]) -> SelectedBackend

Choose the WES instance that a new run is forwarded to.

The first backend of the list (configured WES instances, and those discovered in registries, in the order of custom.wes.backends) that can run the request unchanged. Must be called in an app context.

Parameters:

Name Type Description Default
request dict[str, Any]

Run request of the canonical WES version (form fields).

required

Returns:

Type Description
SelectedBackend

The WES instance, with its API path and WES version.

Raises:

Type Description
InvalidFieldsProblem

No WES instance can run the request unchanged, and all of them stated or reported their versions (400), naming the fields.

NoBackendAvailable

The list has no backend (e.g., none is configured, or the registries list none yet), or none that can run the request, but some didn't answer so far, or the versions of all eligible ones changed since they were found eligible (503, as retrying may help).

versions

WES versions, and adapters of runs between them.

proWES stores and serves runs in the newest WES version it supports (:py:data:CANONICAL), and forwards them to WES instances that may implement an older one. Adapters (:py:class:WesAdapter) convert between two adjacent versions, in both directions; they are registered in :py:data:ADAPTERS and applied in chains, so that supporting a new version needs its specification and one adapter (see docs/wes-versions.md). They work on run requests (form fields) and run logs as plain JSON objects, without the database, the tracking of runs or HTTP clients.

Going down, an adapter declares what the older version can't express without changing what the run does (:py:meth:WesAdapter.incompatibilities): such runs are forwarded only to WES instances that can run them. Everything else that the older version doesn't know is dropped.

Versions are compared by major and minor version only, as patch versions don't change the API (e.g., WES 1.0.0 and 1.0.1 are both 1.0).

ENGINE_FIELDS module-attribute

ENGINE_FIELDS = ('workflow_engine', 'workflow_engine_version')

Fields of run requests of WES 1.1 that choose the workflow engine.

WES_VERSION_LABEL module-attribute

WES_VERSION_LABEL = 'wes.version'

Label of backend entries that states the WES version of WES instances.

ADAPTERS module-attribute

ADAPTERS: tuple[WesAdapter, ...] = (Wes11To10(),)

Registered adapters, each between two adjacent versions.

CANONICAL module-attribute

CANONICAL: WesVersion = max(adapter.newer for adapter in ADAPTERS)

Version in which proWES stores and serves runs: the newest it supports.

OLDEST module-attribute

OLDEST: WesVersion = min(adapter.older for adapter in ADAPTERS)

Oldest supported version, assumed for WES instances of unknown versions.

SUPPORTED module-attribute

SUPPORTED: frozenset[WesVersion] = frozenset(version for adapter in ADAPTERS for version in (adapter.newer, adapter.older))

Versions that proWES can forward runs to.

WesVersion dataclass

WesVersion(major: int, minor: int)

Version of the WES API; patch versions don't change the API.

Attributes:

Name Type Description
major int

Major version.

minor int

Minor version.

parse classmethod

parse(value: object) -> Self | None

Parse a version leniently, as WES instances report them.

E.g., 1.1.0, v1.0.1 and 1.0 (also as a number).

Parameters:

Name Type Description Default
value object

Version.

required

Returns:

Type Description
Self | None

The version, or None if it is none.

Incompatibility dataclass

Incompatibility(field: str, reason: str)

Field of a run request that a version can't express.

Attributes:

Name Type Description
field str

Name of the field (form field of POST /runs).

reason str

Why dropping the field would change what the run does.

WesAdapter

Bases: ABC

Adapter of runs between two adjacent WES versions.

Attributes:

Name Type Description
newer WesVersion

The newer version.

older WesVersion

The older version.

incompatibilities abstractmethod

incompatibilities(request: dict[str, Any]) -> list[Incompatibility]

Get what the older version can't express without changing the run.

Parameters:

Name Type Description Default
request dict[str, Any]

Run request of the newer version (form fields); not changed.

required

Returns:

Type Description
list[Incompatibility]

The fields of the request that the older version can't express.

downgrade_run_request abstractmethod

downgrade_run_request(request: dict[str, Any]) -> dict[str, Any]

Convert a run request to the older version.

Parameters:

Name Type Description Default
request dict[str, Any]

Run request of the newer version (form fields); not changed.

required

Returns:

Type Description
dict[str, Any]

The run request, without what the older version doesn't know.

upgrade_run_log abstractmethod

upgrade_run_log(run_log: dict[str, Any]) -> dict[str, Any]

Convert a run log that a WES instance serves to the newer version.

Parameters:

Name Type Description Default
run_log dict[str, Any]

Run log of the older version; not changed.

required

Returns:

Type Description
dict[str, Any]

The run log.

Wes11To10

Bases: WesAdapter

Adapter between WES 1.1 (1.1.0) and WES 1.0 (1.0.0, 1.0.1).

WES 1.1.0 adds workflow_engine and workflow_engine_version to run requests; run logs, run states and run lists of WES 1.0 are valid in WES 1.1.0, which only adds optional fields, the state PREEMPTED, the task endpoints and RunSummary.

incompatibilities

incompatibilities(request: dict[str, Any]) -> list[Incompatibility]

Get what WES 1.0 can't express without changing the run.

Empty fields choose nothing, so they can be dropped.

Parameters:

Name Type Description Default
request dict[str, Any]

Run request of WES 1.1 (form fields); not changed.

required

Returns:

Type Description
list[Incompatibility]

The fields that choose the workflow engine or its version: the

list[Incompatibility]

WES instance would run the workflow with an engine of its own

list[Incompatibility]

choice.

downgrade_run_request

downgrade_run_request(request: dict[str, Any]) -> dict[str, Any]

Convert a run request to WES 1.0.

Parameters:

Name Type Description Default
request dict[str, Any]

Run request of WES 1.1, without incompatibilities; not changed.

required

Returns:

Type Description
dict[str, Any]

The run request, without the fields of WES 1.1, which WES

dict[str, Any]

instances of WES 1.0 may reject.

upgrade_run_log

upgrade_run_log(run_log: dict[str, Any]) -> dict[str, Any]

Convert a run log that a WES instance serves to WES 1.1.

Parameters:

Name Type Description Default
run_log dict[str, Any]

Run log of WES 1.0.

required

Returns:

Type Description
dict[str, Any]

The run log: all run logs of WES 1.0 are valid in WES 1.1 (Log

dict[str, Any]

objects in task_logs included).

parse_supported

parse_supported(value: object) -> WesVersion | None

Parse a version leniently, if proWES supports it.

Parameters:

Name Type Description Default
value object

Version (e.g., a label, or stored with a run).

required

Returns:

Type Description
WesVersion | None

The version, if it is one of SUPPORTED; otherwise None.

chain

chain(version: WesVersion) -> list[WesAdapter]

Get the adapters between the canonical version and a version.

Parameters:

Name Type Description Default
version WesVersion

A supported version.

required

Returns:

Type Description
list[WesAdapter]

The adapters, from the newest down to the version; none for the

list[WesAdapter]

canonical version.

Raises:

Type Description
ValueError

The version is not supported.

incompatibilities

incompatibilities(request: dict[str, Any], version: WesVersion = OLDEST) -> list[Incompatibility]

Get what a version can't express of a run request.

Each adapter sees the request as the adapters before it left it.

Parameters:

Name Type Description Default
request dict[str, Any]

Run request of the canonical version (form fields); not changed.

required
version WesVersion

Version.

OLDEST

Returns:

Type Description
list[Incompatibility]

The fields that keep the run from running unchanged in the version;

list[Incompatibility]

none if it can.

Raises:

Type Description
ValueError

The version is not supported.

downgrade_run_request

downgrade_run_request(request: dict[str, Any], version: WesVersion) -> dict[str, Any]

Convert a run request of the canonical version to a version.

Parameters:

Name Type Description Default
request dict[str, Any]

Run request of the canonical version (form fields), without incompatibilities; not changed.

required
version WesVersion

Version.

required

Returns:

Type Description
dict[str, Any]

The run request in the version (the same object for the canonical

dict[str, Any]

version).

Raises:

Type Description
ValueError

The version is not supported.

upgrade_run_log

upgrade_run_log(run_log: dict[str, Any], version: WesVersion) -> dict[str, Any]

Convert a run log that a WES instance serves to the canonical version.

Parameters:

Name Type Description Default
run_log dict[str, Any]

Run log of the version; not changed.

required
version WesVersion

Version.

required

Returns:

Type Description
dict[str, Any]

The run log in the canonical version.

Raises:

Type Description
ValueError

The version is not supported.

reported_version

reported_version(service_info: Any) -> WesVersion | None

Get the WES version that a service info reports, read leniently.

Parameters:

Name Type Description Default
service_info Any

Service info, as served by a WES instance.

required

Returns:

Type Description
WesVersion | None

The version of type.version, if type.group is org.ga4gh and

WesVersion | None

type.artifact is wes (ignoring case); None if it reports none

WesVersion | None

that proWES supports.

client_wes

WES client, sending requests with FOCA's guarded HTTP client.

Requests to WES instances go through FOCA's guarded HTTP client (:py:class:foca.utils.http.GuardedClient):

  • https only, unless the configured entry of the WES instance allows http (url_schemes); TLS certificates are always verified, with the public certificate authorities, or with those of the file or directory that the environment variable REQUESTS_CA_BUNDLE names (:py:data:CA_BUNDLE_ENV) instead;
  • configured WES instances may have private addresses (operators trust them); discovered ones only public ones, unless their registry entry has allow_private_addresses; WES instances that the backend list doesn't yield (e.g., of runs stored before it changed) only public ones, over https;
  • redirects are not followed: they fail the request;
  • each request ends within its timeout as a whole (name resolution, connecting, sending and reading), and responses are read up to custom.wes.max_response_size bytes;
  • proxy settings and .netrc files of the environment are ignored.

Failed requests raise :py:class:pro_wes.exceptions.EngineUnavailable: :py:class:pro_wes.exceptions.EngineRequestNotSent if the WES instance certainly didn't get the request, and :py:class:pro_wes.exceptions.EngineOutcomeUnknown if it may have got (and processed) it, e.g., after a read timeout, or after a redirect or a response that is no JSON.

CA_BUNDLE_ENV module-attribute

CA_BUNDLE_ENV = 'REQUESTS_CA_BUNDLE'

Environment variable with the path of the certificate authorities that WES instances are verified with, instead of the public ones (a file or a directory, as for requests).

WesClient

WesClient(host: str, base_path: str = '/ga4gh/wes/v1', token: str | None = None)

Client to communicate with GA4GH WES API.

Must be created in an app context (it reads the config and the backend list, cf. :py:mod:pro_wes.ga4gh.wes.client_wes). A client is not meant to be shared between threads.

Parameters:

Name Type Description Default
host str

Host at which the WES API is served; note that this should include the path information but not the base path path defined in the WES API specification; e.g., specify https://my.wes.com/api if the actual API is hosted at https://my.wes.com/api/ga4gh/wes/v1.

required
base_path str

Override the default path suffix defined in the WES API specification.

'/ga4gh/wes/v1'
token str | None

Bearer token to send along with any WES API requests. Set if required by WES instance. Alternatively, use set_token() method to set.

None

Attributes:

Name Type Description
url

URL to WES endpoints, built from url and base_path, e.g.,"https://wes.rahtiapp.fi/ga4gh/wes/v1".

token

Bearer token for gaining access to WES endpoints.

timeout float

Timeout of requests without one of their own, in seconds (custom.defaults.timeout).

http GuardedClient

Guarded HTTP client of the requests.

Class constructor.

get_service_info

get_service_info(timeout: float | None = None) -> ErrorResponse | ServiceInfo

Retrieve information about the WES instance.

Validated against WES 1.1.0 (ServiceInfo): the service info of WES 1.0.x instances (e.g., workflow_engine_versions as strings) is invalid; their versions are read with :py:meth:read_service_info.

Parameters:

Name Type Description Default
timeout float | None

Timeout of the request as a whole, in seconds; by default the client's (custom.defaults.timeout).

None

Returns:

Type Description
ErrorResponse | ServiceInfo

Response object according to WES API schema ServiceInfo. Cf. pro_wes/api/20230914.tag_1_1_0.workflow_execution_service.openapi.yaml

Raises:

Type Description
EngineUnavailable

The request failed.

ValueError

The response does not conform to any of the expected schemas.

read_service_info

read_service_info(timeout: float | None = None) -> tuple[int, Any]

Read the service info of the WES instance, as it is.

Not validated, as WES instances of other WES versions serve other forms (cf. :py:mod:pro_wes.ga4gh.wes.routing).

Parameters:

Name Type Description Default
timeout float | None

Timeout of the request as a whole, in seconds; by default the client's (custom.defaults.timeout).

None

Returns:

Type Description
int

Status of the response (any but a redirect), and its parsed JSON

Any

body (None if it is no JSON).

Raises:

Type Description
EngineUnavailable

The request failed.

post_run

post_run(form_data: dict[str, str], files: dict[str, tuple[str, bytes]] | None = None, timeout: float | None = None) -> ErrorResponse | RunId

Send workflow run request.

The run request is sent as multipart/form-data, as the WES API specifies.

Parameters:

Name Type Description Default
form_data dict[str, str]

Form data according to WES API schema RunRequest. Cf. pro_wes/api/20230914.tag_1_1_0.workflow_execution_service.openapi.yaml The following form fields are required: * workflow_params * workflow_type * workflow_type_version * workflow_url The following form fields are optional: * tags * workflow_engine_parameters * workflow_engine and workflow_engine_version (WES 1.1.0; left out for WES 1.0)

required
files dict[str, tuple[str, bytes]] | None

Files to be attached, by form field: file name and content.

None
timeout float | None

Timeout of the request as a whole, in seconds; by default the client's (custom.defaults.timeout).

None

Returns:

Type Description
ErrorResponse | RunId

WES API schema RunId. Cf. pro_wes/api/20230914.tag_1_1_0.workflow_execution_service.openapi.yaml

Raises:

Type Description
ValueError

The form data does not conform to the expected schema.

EngineUnavailable

The request failed.

ValueError

The response does not conform to any of the expected schemas.

get_runs

get_runs(timeout: float | None = None) -> ErrorResponse | RunListResponse

Retrieve list of workflow runs.

Parameters:

Name Type Description Default
timeout float | None

Timeout of the request as a whole, in seconds; by default the client's (custom.defaults.timeout).

None

Returns:

Type Description
ErrorResponse | RunListResponse

WES API schema RunListResponse. Cf. pro_wes/api/20230914.tag_1_1_0.workflow_execution_service.openapi.yaml

Raises:

Type Description
EngineUnavailable

The request failed.

ValueError

The response does not conform to any of the expected schemas.

get_run

get_run(run_id: str, timeout: float | None = None) -> dict[str, Any]

Retrieve detailed information about a workflow run.

The response is not validated against the WES API schema RunLog (workaround for cwl-WES, whose responses don't conform to it).

Parameters:

Name Type Description Default
run_id str

Workflow run identifier.

required
timeout float | None

Timeout of the request as a whole, in seconds; by default the client's (custom.defaults.timeout).

None

Returns:

Type Description
dict[str, Any]

Response object, as sent; according to WES API schema RunLog if the service conforms to it. Cf. pro_wes/api/20230914.tag_1_1_0.workflow_execution_service.openapi.yaml

Raises:

Type Description
EngineUnavailable

The request failed, or the response is no JSON object.

get_run_status

get_run_status(run_id: str, timeout: float | None = None) -> ErrorResponse | RunStatus

Retrieve status information about a workflow run.

Parameters:

Name Type Description Default
run_id str

Workflow run identifier.

required
timeout float | None

Timeout of the request as a whole, in seconds; by default the client's (custom.defaults.timeout).

None

Returns:

Type Description
ErrorResponse | RunStatus

WES API schema RunStatus. Cf. pro_wes/api/20230914.tag_1_1_0.workflow_execution_service.openapi.yaml

Raises:

Type Description
EngineUnavailable

The request failed.

ValueError

The response does not conform to any of the expected schemas.

cancel_run

cancel_run(run_id: str, timeout: float | None = None) -> ErrorResponse | RunId

Cancel workflow run.

Parameters:

Name Type Description Default
run_id str

Workflow run identifier.

required
timeout float | None

Timeout of the request as a whole, in seconds; by default the client's (custom.defaults.timeout).

None

Returns:

Type Description
ErrorResponse | RunId

WES API schema RunId if the WES instance accepted the

ErrorResponse | RunId

cancellation (a 2xx status), else ErrorResponse with the

ErrorResponse | RunId

HTTP status of the response, whatever its body (e.g., problem

ErrorResponse | RunId

details, or no JSON). Cf. pro_wes/api/20230914.tag_1_1_0.workflow_execution_service.openapi.yaml

Raises:

Type Description
EngineUnavailable

The request failed, or a response of 2xx status is no JSON.

ValueError

A response of 2xx status is no RunId.

set_token

set_token(token: str | None = None) -> None

Set access token for session.

Parameters:

Name Type Description Default
token str | None

Bearer token to send along with any WES API requests. Set if required by WES instance.

None

headers

headers(content_type: str | None = None) -> dict[str, str]

Get the headers of a request.

Each request gets its own headers, so that none sticks to later requests. Without a token (or with an empty one), no Authorization header is sent (no anonymous request carries Authorization: Bearer None).

Parameters:

Name Type Description Default
content_type str | None

Type of content sent with the request, if any.

None

Returns:

Name Type Description
Headers dict[str, str]

Accept (JSON), and Content-Type and Authorization

dict[str, str]

if given.

Run tracking

celery_worker

Celery worker entry point.

Start the worker with celery -A pro_wes.celery_worker worker. FOCA replaces the MongoDB client of the worker before it forks its pool processes, and in each of them after the fork, so that clients aren't shared across forks (cf. foca.Foca.create_celery_app()); tasks get their collections when they run (foca.get_collection()).

track_run_progress

Celery background task to track the progress of workflow runs.

task__track_run_progress

task__track_run_progress(self: Task[Any, Any], remote_host: str, remote_base_path: str, remote_run_id: str, jwt: str | None) -> str

Relay workflow run request to remote WES and track run progress.

The collection of the runs is taken from FOCA when the task runs, as FOCA replaces the MongoDB client of the worker after each fork (cf. :py:func:foca.get_collection). Run logs of the remote service are converted from the WES version that the run was forwarded in, as stored with the run (wes_endpoint.wes_version; the oldest supported version for runs stored without one, e.g., by earlier versions), so that the task's arguments are the same as before, and workers of earlier versions can track runs of later ones (e.g., in a rolling update).

Parameters:

Name Type Description Default
self Task[Any, Any]

The bound task (bind=True).

required
remote_host str

Host at which the WES API is served that is processing this request; note that this should include the path information but not the base path path defined in the WES API specification; e.g., specify https://my.wes.com/api if the actual API is hosted at https://my.wes.com/api/ga4gh/wes/v1.

required
remote_base_path str

Override the default path suffix defined in the WES API specification, i.e., /ga4gh/wes/v1.

required
remote_run_id str

Workflow run identifier on remote WES service.

required
jwt str | None

Ignored: the client's token is never passed on to WES instances (kept for tasks queued by earlier versions).

required

Returns:

Type Description
str

Task identifier.

Raises:

Type Description
ValueError

The task has no identifier.

EngineUnavailable

The remote service is unavailable or is not a valid WES service.

ValueError

The remote service sent too many invalid status responses.

EngineProblem

The remote service sent too many error responses.

WesEndpointProblem

The run document has no identifier of the run at the remote service; the run state is set to SYSTEM_ERROR.

SoftTimeLimitExceeded

Tracking took longer than custom.post_runs.timeout_job; the run state is set to SYSTEM_ERROR, unless the run has finished already.

utils

Utility functions for Celery background tasks.

set_run_state

set_run_state(collection: Collection[dict[str, Any]], run_id: str, task_id: str | None = None, state: str = 'UNKNOWN') -> None

Set/update state of run associated with Celery task.

Database errors are logged, not raised.

Parameters:

Name Type Description Default
collection Collection[dict[str, Any]]

Collection of the runs.

required
run_id str

Run identifier.

required
task_id str | None

Identifier of the Celery task of the run; looked up by run identifier if not given.

None
state str

New state of the run.

'UNKNOWN'

Raises:

Type Description
ValueError

No run with the identifier was found, or the state is unknown.

Database

db

Utility functions for MongoDB document insertion, updates and retrieval.

DbDocumentConnector

DbDocumentConnector(collection: Collection[dict[str, Any]], task_id: str)

MongoDB connector to a given pro_wes.ga4gh.wes.models.DbDocument document.

Parameters:

Name Type Description Default
collection Collection[dict[str, Any]]

Database collection.

required
task_id str

Celery task identifier.

required

Class constructor.

get_document

get_document(projection: Mapping[str, Any] | None = None) -> DbDocument

Get document associated with task.

Parameters:

Name Type Description Default
projection Mapping[str, Any] | None

A projection object indicating which fields of the document to return. By default, all fields except the MongoDB identifier _id are returned.

None

Returns:

Type Description
DbDocument

Instance of pro_wes.ga4gh.wes.models.DbDocument associated with the task.

Raise

ValueError: Returned document does not conform to schema.

update_run_state

update_run_state(state: str = 'UNKNOWN') -> None

Update run status.

For states of the run as known to proWES (e.g., reported by the WES instance); clears the mark of SYSTEM_ERRORs set by proWES itself (cf. set_system_error()).

Parameters:

Name Type Description Default
state str

New run status; one of pro_wes.ga4gh.wes.models.State.

'UNKNOWN'

Raises:

Type Description
ValueError

The state is not a known run state.

set_system_error

set_system_error() -> None

Set the run status to SYSTEM_ERROR, as set by proWES itself.

For runs that fail in proWES (e.g., the run request can't be sent) or that proWES loses track of, without knowing their state at the WES instance; such runs can still be canceled if they have a remote run.

upsert_fields_in_root_object

upsert_fields_in_root_object(root: str, **kwargs: Any) -> DbDocument

Insert or update fields in the same root object.

Parameters:

Name Type Description Default
root str

Root object of the fields.

required
**kwargs Any

Fields to insert or update, with their values.

{}

Returns:

Type Description
DbDocument

Updated document.

db_names

Names of the database and collections of proWES (db.dbs of config.yaml).

config

Readers of the service info of the app configuration.

Kept apart from the models (pro_wes.ga4gh.wes.models) and the service info (pro_wes.ga4gh.wes.service_info), so that both can use them without importing each other.

workflow_type_versions

workflow_type_versions() -> dict[str, Any]

Get the workflow types and versions of the service info.

Must be called in an app context.

Returns:

Type Description
dict[str, Any]

Workflow types and their versions, as configured

dict[str, Any]

(service_info.service.workflow_type_versions); empty if not set.

Raises:

Type Description
RuntimeError

No service info is configured (the app doesn't start without one, as FOCA serves GET /service-info from it).

Errors

exceptions

App exceptions and their problem details.

The app raises and maps the framework-neutral error classes of FOCA (:py:mod:foca.errors) rather than those of Werkzeug and Connexion. Errors are sent as problem details (RFC 9457: title, status and detail), with the media type application/json (cf. exceptions in config.yaml).

EngineProblem

Bases: InternalServerError

The external workflow engine appears to experience problems.

EngineUnavailable

Bases: EngineProblem

The external workflow engine is not available.

EngineRequestNotSent

EngineRequestNotSent(description: str | None = None, reason: str = '')

Bases: EngineUnavailable

A request certainly didn't reach the external workflow engine.

E.g., its host has no (allowed) address, connecting or the TLS handshake failed, or its timeout passed before it was sent (cf. :py:class:foca.utils.http.RequestNotSent).

Attributes:

Name Type Description
reason

Reason code of FOCA's guarded HTTP client, e.g., connect_error, not_public or tls_error.

Create the error.

Parameters:

Name Type Description Default
description str | None

Description, without credentials.

None
reason str

Reason code; connect_error if empty.

''

EngineOutcomeUnknown

EngineOutcomeUnknown(description: str | None = None, reason: str = '')

Bases: EngineUnavailable

The external workflow engine may have got, and processed, a request.

E.g., the response timed out, the connection was lost after sending, or the response was larger than allowed (cf. :py:class:foca.utils.http.RequestMaybeSent).

Attributes:

Name Type Description
reason

Reason code of FOCA's guarded HTTP client, e.g., read_timeout, connection_lost or response_too_large.

Create the error.

Parameters:

Name Type Description Default
description str | None

Description, without credentials.

None
reason str

Reason code; connection_lost if empty.

''

EngineRefused

Bases: EngineProblem

The external workflow engine answered a request with an error.

E.g., the remote run is unknown there, or has finished; errors that proWES passes on as its own (400, 401, 403) are raised as those.

EngineInvalidResponse

Bases: EngineProblem

The external workflow engine sent an invalid response.

E.g., a successful response that doesn't conform to the expected schema.

NoBackendAvailable

Bases: ServiceUnavailable

No WES instance is available for new runs.

None is configured (custom.wes.backends), or the service registries of the backend list list none (yet).

NoSuitableEngine

Bases: BadRequest

No suitable workflow engine known.

TasksNotServed

Bases: InternalServerError

The task endpoints of WES 1.1.0 are not served yet (#124).

501 Not Implemented (exceptions); FOCA has no error class for it, so it derives from the closest server-side one.

InvalidAttachmentName

Bases: BadRequest

A workflow attachment has no usable file name.

E.g., none, one longer than file systems allow, or one that another attachment of the run has, too (after making it safe).

TooManyAttachments

Bases: PayloadTooLarge

A run has more workflow attachments than allowed.

Cf. custom.post_runs.max_attachments.

AttachmentTooLarge

Bases: PayloadTooLarge

A workflow attachment is larger than allowed.

Cf. custom.post_runs.max_attachment_size.

UrlCredentials

Bases: BadRequest

A URL of a run request has credentials (user name or password).

Cf. custom.post_runs.url_credentials.

MalformedUrl

Bases: BadRequest

A URL of a run request is malformed, so its credentials can't be checked.

UnsupportedMediaType

Bases: BadRequest

A run request isn't a form (multipart/form-data or URL-encoded).

Mapped to 415 Unsupported Media Type in exceptions below; FOCA has no error class for it, so it derives from the closest client-side one (like TasksNotServed).

UrlEncodedAttachment

Bases: BadRequest

A URL-encoded run request has workflow attachments, which it can't carry.

MissingBoundary

Bases: BadRequest

A multipart/form-data run request has no boundary, so it can't be read.

RunNotFound

Bases: NotFound

Workflow run with given identifier not found.

RunNotCancelable

Bases: Conflict

Workflow run not cancelable in its current state.

E.g., a run that has finished or is being canceled (cf. :py:attr:pro_wes.ga4gh.wes.models.State.is_cancelable).

IdsUnavailableProblem

Bases: PyMongoError

No unique run identifier available.

StorageUnavailableProblem

Bases: OSError

Storage unavailable for OS operations.

WesEndpointProblem

Bases: InternalServerError

No or incomplete information on the external WES endpoint.