Skip to content

madbot_cli.client

A client of the madbot REST API, authenticated by a personal access token.

The client knows the conventions of the API: the token, the workspace header, the pages of a list and the background tasks. It knows nothing of nodes or submissions: madbot_cli.operations builds the steps of a deposit on it.

Every request goes through a transport, a function that sends one HTTP request and returns the status and the body of the answer. The default one uses the standard library; another one can be given, for a proxy or tests.

A request that can be sent again without effect (a read, a PUT, the values of a metadata object) is sent again when the network drops or a gateway gives up, after a growing pause: see RETRY_DELAYS. A request that creates is never sent twice.

Attributes

NameDescription
GATEWAY_GAVE_UPStatuses of a proxy or gateway that did not reach madbot: worth a new attempt.
LIST_READSTimes a list whose length changes while it is read is read again from its first page.
MAX_PAGE_SIZEThe largest page the API serves.
MIN_API_VERSIONThe oldest version of the madbot API this release works with.
OnRetryTold of a new attempt: (reason, seconds before it, attempt number).
REDIRECTION_MAXThe first HTTP status after those of a redirection.
REDIRECTION_MINThe first HTTP status of a redirection, which the client never follows.
REPLAYABLE_METHODSMethods whose repetition has no further effect: they are sent again on a network drop.
RETRY_DELAYSSeconds to wait before each new attempt of a request that can be repeated: 31 s of pauses in all, each attempt waiting up to the timeout of the transport.
TASK_DONEStates of a task over in success.
TASK_FAILEDStates of a task over in failure.
TransportA transport sends one request: (method, url, headers, body) -> (status, body).

Classes

NameDescription
ClientA client of the madbot REST API.

Functions

NameDescription
urllib_transportMake the default transport, built on urllib.request.

GATEWAY_GAVE_UPattributemodule attribute#

GATEWAY_GAVE_UP = {502, 503, 504}

Statuses of a proxy or gateway that did not reach madbot: worth a new attempt.

LIST_READSattributemodule attribute#

LIST_READS = 3

Times a list whose length changes while it is read is read again from its first page.

MAX_PAGE_SIZEattributemodule attribute#

MAX_PAGE_SIZE = 500

The largest page the API serves.

MIN_API_VERSIONattributemodule attribute#

MIN_API_VERSION = (2, 2, 0)

The oldest version of the madbot API this release works with.

OnRetryattributemodule attribute#

OnRetry = Callable[[str, float, int], None]

Told of a new attempt: (reason, seconds before it, attempt number).

REDIRECTION_MAXattributemodule attribute#

REDIRECTION_MAX = 400

The first HTTP status after those of a redirection.

REDIRECTION_MINattributemodule attribute#

REDIRECTION_MIN = 300

The first HTTP status of a redirection, which the client never follows.

REPLAYABLE_METHODSattributemodule attribute#

REPLAYABLE_METHODS = {'GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE'}

Methods whose repetition has no further effect: they are sent again on a network drop.

RETRY_DELAYSattributemodule attribute#

RETRY_DELAYS = (1, 2, 4, 8, 16)

Seconds to wait before each new attempt of a request that can be repeated: 31 s of pauses in all, each attempt waiting up to the timeout of the transport.

TASK_DONEattributemodule attribute#

TASK_DONE = {'SUCCESS'}

States of a task over in success.

TASK_FAILEDattributemodule attribute#

TASK_FAILED = {'FAILURE', 'REVOKED'}

States of a task over in failure.

Transportattributemodule attribute#

Transport = Callable[[str, str, Mapping[str, str], 'bytes | None'], 'tuple[int, bytes]']

A transport sends one request: (method, url, headers, body) -> (status, body).

Clientclass#

class Client(api_url: str, token: str, *, workspace: str | None = None, transport: Transport | None = None, sleep: Callable[[float], None] = time.sleep, clock: Callable[[], float] = time.monotonic, retry_delays: Sequence[float] = RETRY_DELAYS, on_retry: OnRetry | None = None)

A client of the madbot REST API.

Parameters

NameTypeDefaultDescription
api_urlstrrequiredThe address of the API, such as https://api.madbot.example.org. It is often not the address of the web application.
tokenstrrequiredA personal access token of that instance, with the read and write scopes.
workspacestrNoneThe identifier of the workspace the requests act in, sent in the X-Workspace header. use_workspace sets it later.
transportTransportNoneSends the requests; urllib_transport() by default.
sleepcallabletime.sleepWaits between two reads of a background task; time.sleep by default.
clockcallabletime.monotonicMeasures how long a wait lasts; time.monotonic by default.
retry_delayssequence of floatRETRY_DELAYSSeconds to wait before each new attempt of a request that can be repeated, when the network drops; RETRY_DELAYS by default, empty for none.
on_retrycallableNoneTold of each new attempt, to show it: (reason, seconds before it, attempt number).

Examples

>>> client = Client.from_env()
>>> client.use_workspace("my-workspace")
>>> nodes = client.list("/api/nodes")

api_urlattributeinstance attribute#

api_url = api_url.rstrip('/')

clockattributeinstance attribute#

clock = clock

on_retryattributeinstance attribute#

on_retry = on_retry

retry_delaysattributeinstance attribute#

retry_delays = tuple(retry_delays)

sleepattributeinstance attribute#

sleep = sleep

tokenattributeinstance attribute#

token = token

transportattributeinstance attribute#

transport = transport or urllib_transport()

workspaceattributeinstance attribute#

workspace = workspace

attemptmethod#

def attempt(method: str, url: str, headers: Mapping[str, str], body: bytes | None, replayable: bool) -> tuple[int, bytes]

Send a request through the transport, again after a pause when it can be repeated.

Parameters

NameTypeDescription
methodstrThe HTTP method.
urlstrThe URL.
headersmappingThe headers.
bodybytes or NoneThe body.
replayableboolWhether the request can be sent again: on no answer, or when a gateway gave up (GATEWAY_GAVE_UP).

Returns

tuple
The status and the body of the answer.

Raises

ApiUnreachable
When no answer came, after the last attempt.

check_versionmethod#

def check_version() -> dict

Read the version of the API and tell whether this release works with it.

Returns

dict
version of madbot, and compatible: False for a version older than MIN_API_VERSION, None when it cannot be read.

from_envmethodclassmethod#

def from_env(api_url: str | None = None, token: str | None = None, environ: Mapping[str, str] | None = None, **options: Any) -> Client

Make a client from the MADBOT_API and MADBOT_TOKEN environment variables.

Parameters

NameTypeDefaultDescription
api_urlstrNoneThe address of the API; MADBOT_API when not given.
tokenstrNoneThe personal access token; MADBOT_TOKEN when not given.
environmappingNoneThe environment to read; os.environ by default.
**optionsAny{}Passed to the client: workspace, transport, sleep, clock, retry_delays, on_retry.

Returns

Client
The client.

Raises

MadbotError
When the address or the token is missing, or the address is not http(s). There is no default address, so that nothing is written to an instance by mistake.

getmethod#

def get(path: str, **params: Any) -> Any

Read one object.

Parameters

NameTypeDefaultDescription
pathstrrequiredThe path of the object.
**paramsAny{}Query parameters.

Returns

Any
The decoded answer.

listmethod#

def list(path: str, *, must_settle: bool = False, **params: Any) -> list[Any]

Read every page of a list.

The API makes each page anew: a list that changes between two pages, such as a folder a source lists differently from one request to the next, would come back cut or with an item twice. Each page gives the length of the whole list; when it changes, the list is read again from its first page.

Parameters

NameTypeDefaultDescription
pathstrrequiredThe path of the list.
must_settleboolFalseTrue for a list that must be read whole, such as a folder of a source where a name is sought: when its length still changes after LIST_READS reads, the command stops. Otherwise the last read is kept, as for the data madbot still links while it is read.
**paramsAny{}Query parameters, such as filters.

Returns

list
All the items of the list.

Raises

MadbotError
With must_settle, when the length of the list still changes after LIST_READS reads.

postmethod#

def post(path: str, payload: Any = None, *, replayable: bool = False) -> Any

Create an object or run an action.

Parameters

NameTypeDefaultDescription
pathstrrequiredThe path of the collection or action.
payloadAnyNoneThe body of the request.
replayableboolFalseTrue when sending it twice has no further effect, such as values that replace those there: it is sent again when the network drops.

Returns

Any
The decoded answer.

read_pagesmethod#

def read_pages(path: str, params: Mapping[str, Any]) -> tuple[list[Any], bool]

Read a list once, page after page.

Parameters

NameTypeDescription
pathstrThe path of the list.
paramsmappingQuery parameters, such as filters.

Returns

tuple
The items read, and whether every page gave the same length of the list.

requestmethod#

def request(method: str, path: str, payload: Any = None, *, params: Mapping[str, Any] | None = None, replayable: bool | None = None) -> Any

Send a request and return the decoded answer.

Parameters

NameTypeDefaultDescription
methodstrrequiredThe HTTP method.
pathstrrequiredA path under the API address, or a full URL.
payloadAnyNoneThe body of the request, sent as JSON.
paramsmappingNoneQuery parameters.
replayableboolNoneWhether the request can be sent again without effect; see send.

Returns

Any
The decoded JSON answer, None when empty.

same_originmethod#

def same_origin(url: str) -> str

Put a link of the API back on the address of the client.

Behind a proxy, the API may build its links on another scheme or host (http:// behind TLS): the token must only go to api_url.

Parameters

NameTypeDescription
urlstrA full URL given by the API, such as the next page of a list.

Returns

str
The same path and query, on the scheme and host of api_url.

sendmethod#

def send(method: str, path: str, payload: Any = None, *, params: Mapping[str, Any] | None = None, replayable: bool | None = None) -> tuple[int, Any]

Send a request and return the status with the decoded answer.

Parameters

NameTypeDefaultDescription
methodstrrequiredThe HTTP method.
pathstrrequiredA path under the API address, or a full URL.
payloadAnyNoneThe body of the request, sent as JSON.
paramsmappingNoneQuery parameters.
replayableboolNoneWhether the request can be sent again without effect, when the network drops; by default, for the methods of REPLAYABLE_METHODS. Never for a request that creates.

Returns

tuple
The HTTP status and the decoded JSON answer (None when empty).

Raises

ApiError
A subclass matching the status of an error answer; ApiUnreachable without an answer, once the new attempts are spent; NotJson when the answer is not JSON.

urlmethod#

def url(path: str, params: Mapping[str, Any] | None = None) -> str

Build the URL of a request.

Parameters

NameTypeDefaultDescription
pathstrrequiredA path under the API address (/api/...), or a full URL such as the next page of a list.
paramsmappingNoneQuery parameters; those set to None are left out.

Returns

str
The URL.

use_workspacemethod#

def use_workspace(name_slug_or_id: str) -> dict

Send the following requests in a workspace of the account.

Parameters

NameTypeDescription
name_slug_or_idstrThe name, the slug (after /w/ in the address of the web application) or the identifier of the workspace.

Returns

dict
The workspace.

Raises

NotFound
When the account has no such workspace.

versionmethod#

def version() -> dict

Read the version of the API.

Returns

dict
version of madbot and plugins_api_version.

wait_taskmethod#

def wait_task(task_id: str, *, timeout: float = 1800, interval: float = 2, pending_grace: float = 60, on_wait: Callable[[float], None] | None = None) -> dict

Wait for a background task of madbot to end.

A task is read with GET /api/tasks/{task_id}. Right after it is queued the API may not know it yet, then reports it PENDING until a worker starts it: both are waited for.

Parameters

NameTypeDefaultDescription
task_idstrrequiredThe identifier of the task, as an answer of the API gives it.
timeoutfloat1800Seconds to wait in all.
intervalfloat2Seconds between two reads.
pending_gracefloat60Seconds during which an unknown task is taken for one not recorded yet.
on_waitcallableNoneCalled with the seconds waited so far, before each pause: shows the progress.

Returns

dict
The task, ended in success, with its result.

Raises

TaskFailed
When the task failed or was revoked.
WaitTimeout
When the task is not over after timeout seconds.

urllib_transportfunction#

def urllib_transport(timeout: float = 120) -> Transport

Make the default transport, built on urllib.request.

Parameters

NameTypeDefaultDescription
timeoutfloat120Seconds to wait for an answer.

Returns

Transport
A function that sends a request and returns its status and body. An HTTP error is returned like any answer; only the absence of an answer raises ApiUnreachable. A redirection is not followed: it raises Redirected, with the address the API sends to.