Skip to content

API reference

Everything public is re-exported from the top-level zarr_http_server namespace; the private _serve and _keys modules are implementation detail and carry no compatibility guarantee.

Building an app

zarr_http_server.store_app

store_app(
    store: Store,
    *,
    methods: Set[HTTPMethod] | None = None,
    cors_options: CorsOptions | None = None,
    max_body_size: int | None = DEFAULT_MAX_BODY_SIZE,
) -> Starlette

Create a Starlette ASGI app that serves every key in a zarr Store.

Parameters:

  • store (Store) –

    The zarr store to serve.

  • methods (set of HTTPMethod, default: None ) –

    The HTTP methods to accept: any of "GET", "HEAD", and "PUT". Defaults to {"GET"}, which also serves HEAD. Passing any other method raises ValueError.

  • cors_options (CorsOptions, default: None ) –

    If provided, CORS middleware will be added with the given options.

  • max_body_size (int or None, default: DEFAULT_MAX_BODY_SIZE ) –

    Largest PUT body to accept, in bytes; larger requests get a 413. Store.set takes a whole Buffer, so bodies cannot be streamed and are held in memory in full. Defaults to DEFAULT_MAX_BODY_SIZE; pass None to lift the cap.

Returns:

  • Starlette –

    An ASGI application.

Source code in src/zarr_http_server/_serve.py
def store_app(
    store: Store,
    *,
    methods: AbstractSet[HTTPMethod] | None = None,
    cors_options: CorsOptions | None = None,
    max_body_size: int | None = DEFAULT_MAX_BODY_SIZE,
) -> Starlette:
    """Create a Starlette ASGI app that serves every key in a zarr ``Store``.

    Parameters
    ----------
    store : Store
        The zarr store to serve.
    methods : set of HTTPMethod, optional
        The HTTP methods to accept: any of `"GET"`, `"HEAD"`, and `"PUT"`.
        Defaults to `{"GET"}`, which also serves `HEAD`. Passing any other
        method raises `ValueError`.
    cors_options : CorsOptions, optional
        If provided, CORS middleware will be added with the given options.
    max_body_size : int or None, optional
        Largest `PUT` body to accept, in bytes; larger requests get a 413.
        `Store.set` takes a whole `Buffer`, so bodies cannot be streamed and
        are held in memory in full. Defaults to `DEFAULT_MAX_BODY_SIZE`;
        pass `None` to lift the cap.

    Returns
    -------
    Starlette
        An ASGI application.
    """
    _reject_writes_to_a_read_only_store(store, methods)
    app = _make_starlette_app(methods=methods, cors_options=cors_options)
    app.state.store = store
    app.state.node = None
    app.state.prefix = ""
    app.state.max_body_size = max_body_size
    return app

zarr_http_server.node_app

node_app(
    node: Array[Any] | Group,
    *,
    methods: Set[HTTPMethod] | None = None,
    cors_options: CorsOptions | None = None,
    max_body_size: int | None = DEFAULT_MAX_BODY_SIZE,
) -> Starlette

Create a Starlette ASGI app that serves only the keys belonging to a zarr Array or Group.

For an Array, the served keys are the metadata document(s) and all chunk (or shard) keys whose coordinates fall within the array's grid.

For a Group, the served keys are the group's own metadata plus any path that resolves through the group's members to a valid array metadata document or chunk key.

Requests for keys outside this set receive a 404 response, even if the underlying store contains data at that path.

Parameters:

  • node (Array or Group) –

    The zarr array or group to serve.

  • methods (set of HTTPMethod, default: None ) –

    The HTTP methods to accept: any of "GET", "HEAD", and "PUT". Defaults to {"GET"}, which also serves HEAD. Passing any other method raises ValueError.

  • cors_options (CorsOptions, default: None ) –

    If provided, CORS middleware will be added with the given options.

  • max_body_size (int or None, default: DEFAULT_MAX_BODY_SIZE ) –

    Largest PUT body to accept, in bytes; larger requests get a 413. Store.set takes a whole Buffer, so bodies cannot be streamed and are held in memory in full. Defaults to DEFAULT_MAX_BODY_SIZE; pass None to lift the cap.

Returns:

  • Starlette –

    An ASGI application.

Source code in src/zarr_http_server/_serve.py
def node_app(
    node: Array[Any] | Group,
    *,
    methods: AbstractSet[HTTPMethod] | None = None,
    cors_options: CorsOptions | None = None,
    max_body_size: int | None = DEFAULT_MAX_BODY_SIZE,
) -> Starlette:
    """Create a Starlette ASGI app that serves only the keys belonging to a
    zarr ``Array`` or ``Group``.

    For an ``Array``, the served keys are the metadata document(s) and all
    chunk (or shard) keys whose coordinates fall within the array's grid.

    For a ``Group``, the served keys are the group's own metadata plus any
    path that resolves through the group's members to a valid array metadata
    document or chunk key.

    Requests for keys outside this set receive a 404 response, even if the
    underlying store contains data at that path.

    Parameters
    ----------
    node : Array or Group
        The zarr array or group to serve.
    methods : set of HTTPMethod, optional
        The HTTP methods to accept: any of `"GET"`, `"HEAD"`, and `"PUT"`.
        Defaults to `{"GET"}`, which also serves `HEAD`. Passing any other
        method raises `ValueError`.
    cors_options : CorsOptions, optional
        If provided, CORS middleware will be added with the given options.
    max_body_size : int or None, optional
        Largest `PUT` body to accept, in bytes; larger requests get a 413.
        `Store.set` takes a whole `Buffer`, so bodies cannot be streamed and
        are held in memory in full. Defaults to `DEFAULT_MAX_BODY_SIZE`;
        pass `None` to lift the cap.

    Returns
    -------
    Starlette
        An ASGI application.
    """
    _reject_writes_to_a_read_only_store(node.store_path.store, methods)
    app = _make_starlette_app(methods=methods, cors_options=cors_options)
    app.state.store = node.store_path.store
    app.state.node = node
    app.state.prefix = node.store_path.path
    app.state.max_body_size = max_body_size
    return app

Running a server

zarr_http_server.serve

serve(
    app: Starlette,
    *,
    host: str = "127.0.0.1",
    port: int | Literal["auto"] = AUTO_PORT,
    shutdown_timeout: int = 5,
    uvicorn_options: Mapping[str, object] | None = None,
) -> None

Run an ASGI app under Uvicorn, blocking until it is stopped.

Returns only when the server stops, so this is the shape for a process whose job is to serve -- a script, a container entrypoint. Use :func:serve_background when the caller has more to do.

Build the app first with :func:store_app or :func:node_app, or compose several of them; what an app serves is settled when it is built, and this only decides how it runs.

.. code-block:: python

serve(store_app(store), host="0.0.0.0", port=8000)

Parameters:

  • app (Starlette) –

    The ASGI app to run.

  • host (str, default: '127.0.0.1' ) –

    The host to bind to. Defaults to "127.0.0.1".

  • port (int, default: AUTO_PORT ) –

    The port to bind to. Defaults to 8000.

  • shutdown_timeout (int, default: 5 ) –

    Seconds to wait for in-flight requests to finish gracefully when the server is shut down, via uvicorn's timeout_graceful_shutdown. Defaults to 5.

  • uvicorn_options (Mapping[str, object], default: None ) –

    Extra options passed straight to uvicorn.Config, merged over the ones set here (host, port, timeout_graceful_shutdown), so a caller key wins. This is the escape hatch for anything uvicorn can do that this signature does not name -- TLS via ssl_keyfile / ssl_certfile, proxy_headers and forwarded_allow_ips behind a reverse proxy, root_path when mounted under a prefix, log_level, limit_concurrency, or a uds / fd bind.

Source code in src/zarr_http_server/_serve.py
def serve(
    app: Starlette,
    *,
    host: str = "127.0.0.1",
    port: int | Literal["auto"] = AUTO_PORT,
    shutdown_timeout: int = 5,
    uvicorn_options: Mapping[str, object] | None = None,
) -> None:
    """Run an ASGI app under Uvicorn, blocking until it is stopped.

    Returns only when the server stops, so this is the shape for a process
    whose job is to serve -- a script, a container entrypoint. Use
    :func:`serve_background` when the caller has more to do.

    Build the app first with :func:`store_app` or :func:`node_app`, or compose
    several of them; what an app serves is settled when it is built, and this
    only decides how it runs.

    .. code-block:: python

        serve(store_app(store), host="0.0.0.0", port=8000)

    Parameters
    ----------
    app : Starlette
        The ASGI app to run.
    host : str, optional
        The host to bind to. Defaults to ``"127.0.0.1"``.
    port : int, optional
        The port to bind to. Defaults to ``8000``.
    shutdown_timeout : int, optional
        Seconds to wait for in-flight requests to finish gracefully when the
        server is shut down, via uvicorn's ``timeout_graceful_shutdown``.
        Defaults to ``5``.
    uvicorn_options : Mapping[str, object], optional
        Extra options passed straight to `uvicorn.Config`, merged over the
        ones set here (`host`, `port`, `timeout_graceful_shutdown`), so a
        caller key wins. This is the escape hatch for anything uvicorn can do
        that this signature does not name -- TLS via `ssl_keyfile` /
        `ssl_certfile`, `proxy_headers` and `forwarded_allow_ips` behind a
        reverse proxy, `root_path` when mounted under a prefix, `log_level`,
        `limit_concurrency`, or a `uds` / `fd` bind.
    """
    server, _, sock = _build_server(
        app,
        host=host,
        port=port,
        shutdown_timeout=shutdown_timeout,
        uvicorn_options=uvicorn_options,
    )
    server.run(sockets=[sock] if sock is not None else None)

zarr_http_server.serve_background

serve_background(
    app: Starlette,
    *,
    host: str = "127.0.0.1",
    port: int | Literal["auto"] = AUTO_PORT,
    shutdown_timeout: int = 5,
    uvicorn_options: Mapping[str, object] | None = None,
) -> BackgroundServer

Start an ASGI app under Uvicorn in a daemon thread and return at once.

Returns once the socket is listening, so the next statement can use the server. The returned handle is also a context manager:

.. code-block:: python

with serve_background(node_app(array)) as server:
    httpx.get(f"{server.url}/zarr.json")

In a notebook, where the server must outlive the cell that started it, keep the handle instead and call :meth:BackgroundServer.shutdown later.

Parameters:

  • app (Starlette) –

    The ASGI app to run.

  • host (str, default: '127.0.0.1' ) –

    The host to bind to. Defaults to "127.0.0.1".

  • port (int, default: AUTO_PORT ) –

    The port to bind to. Defaults to 0, which asks the OS for a free one -- unlike :func:serve, whose caller usually needs a port others already know. A background server is normally reached through :attr:BackgroundServer.url, and a fixed default would make starting a second one, or re-running a notebook cell, fail on a port collision.

  • shutdown_timeout (int, default: 5 ) –

    Seconds to wait for in-flight requests to finish gracefully, both for uvicorn's timeout_graceful_shutdown and for the wait :meth:BackgroundServer.shutdown uses before forcing the thread closed. Defaults to 5.

  • uvicorn_options (Mapping[str, object], default: None ) –

    Extra options passed straight to uvicorn.Config, merged over the ones set here so a caller key wins. See :func:serve. Binding somewhere other than a TCP host and port leaves :attr:BackgroundServer.url as None.

Returns:

Raises:

  • RuntimeError –

    If the server does not start -- most often because the port is already in use.

Source code in src/zarr_http_server/_serve.py
def serve_background(
    app: Starlette,
    *,
    host: str = "127.0.0.1",
    port: int | Literal["auto"] = AUTO_PORT,
    shutdown_timeout: int = 5,
    uvicorn_options: Mapping[str, object] | None = None,
) -> BackgroundServer:
    """Start an ASGI app under Uvicorn in a daemon thread and return at once.

    Returns once the socket is listening, so the next statement can use the
    server. The returned handle is also a context manager:

    .. code-block:: python

        with serve_background(node_app(array)) as server:
            httpx.get(f"{server.url}/zarr.json")

    In a notebook, where the server must outlive the cell that started it,
    keep the handle instead and call :meth:`BackgroundServer.shutdown` later.

    Parameters
    ----------
    app : Starlette
        The ASGI app to run.
    host : str, optional
        The host to bind to. Defaults to ``"127.0.0.1"``.
    port : int, optional
        The port to bind to. Defaults to ``0``, which asks the OS for a free
        one -- unlike :func:`serve`, whose caller usually needs a port others
        already know. A background server is normally reached through
        :attr:`BackgroundServer.url`, and a fixed default would make starting
        a second one, or re-running a notebook cell, fail on a port collision.
    shutdown_timeout : int, optional
        Seconds to wait for in-flight requests to finish gracefully, both for
        uvicorn's ``timeout_graceful_shutdown`` and for the wait
        :meth:`BackgroundServer.shutdown` uses before forcing the thread
        closed. Defaults to ``5``.
    uvicorn_options : Mapping[str, object], optional
        Extra options passed straight to `uvicorn.Config`, merged over the
        ones set here so a caller key wins. See :func:`serve`. Binding
        somewhere other than a TCP host and port leaves
        :attr:`BackgroundServer.url` as ``None``.

    Returns
    -------
    BackgroundServer
        A handle for the running server.

    Raises
    ------
    RuntimeError
        If the server does not start -- most often because the port is
        already in use.
    """
    server, options, sock = _build_server(
        app,
        host=host,
        port=port,
        shutdown_timeout=shutdown_timeout,
        uvicorn_options=uvicorn_options,
    )

    # uvicorn skips signal-handler installation off the main thread
    # (Server.capture_signals), so no workaround is needed here.
    thread = threading.Thread(
        target=partial(server.run, sockets=[sock] if sock is not None else None), daemon=True
    )
    thread.start()

    deadline = time.monotonic() + _STARTUP_TIMEOUT
    while not server.started:
        if not thread.is_alive():
            # uvicorn logs the underlying error and calls sys.exit, which in a
            # thread ends it without surfacing anything to the caller. The
            # overwhelmingly common cause is a port already in use.
            raise RuntimeError(
                f"Server thread exited before startup completed; {host}:{port} "
                "may already be in use. See the server log for the cause."
            )
        if time.monotonic() > deadline:
            # The thread is still alive here, unlike the branch above, and it
            # is about to finish starting. Raising without stopping it would
            # leave a server bound to the port with no handle to shut it down
            # -- a daemon thread serving for the rest of the process, and a
            # retry on the same port failing with the other error above.
            server.should_exit = True
            server.force_exit = True
            thread.join(timeout=_STARTUP_ABANDON_TIMEOUT)
            raise RuntimeError(
                f"Server failed to start within {_STARTUP_TIMEOUT:g} seconds; "
                "it has been signalled to stop."
            )
        time.sleep(0.01)

    # Report the port the socket actually bound rather than the one asked for,
    # so `port=0` ("pick a free port") yields a usable `url`. A unix-socket or
    # file-descriptor bind has no host and port at all, so both stay None and
    # `url` reports None rather than naming an address nothing is listening on.
    bound_port: int | None = None
    for bound in server.servers:
        for sock in bound.sockets:
            sockname = sock.getsockname()
            if isinstance(sockname, tuple) and len(sockname) >= 2:
                bound_port = int(sockname[1])
            break
        break

    # The host is taken from the request rather than the socket: a wildcard
    # bind reports "0.0.0.0", which is not an address a client can connect to.
    requested_host = options.get("host")
    bound_host = (
        str(requested_host) if bound_port is not None and requested_host is not None else None
    )

    return BackgroundServer(
        server,
        thread,
        host=bound_host,
        port=bound_port,
        scheme="https" if server.config.is_ssl else "http",
        shutdown_timeout=shutdown_timeout,
    )

zarr_http_server.BackgroundServer

A running background HTTP server that can be used as a context manager.

Wraps a uvicorn.Server running in a daemon thread. When used as a context manager the server is shut down automatically on exit.

Parameters:

  • server (Server) –

    The running uvicorn server instance.

  • thread (Thread) –

    The daemon thread running the server.

  • host (str or None) –

    The host the server was asked to bind, or None when it is not listening on a TCP socket.

  • port (int or None) –

    The port actually bound, or None when the server is not listening on a TCP socket.

  • scheme (str, default: 'http' ) –

    URL scheme the server is reachable over. Defaults to "http".

  • shutdown_timeout (int, default: 5 ) –

    Seconds to wait for in-flight requests to finish gracefully during :meth:shutdown before forcing the server closed. Defaults to 5.

Examples:

>>> with serve_background(node_app(arr)) as server:
...     print(f"Listening on {server.host}:{server.port}")
...     # server is shut down when the block exits
Source code in src/zarr_http_server/_serve.py
class BackgroundServer:
    """A running background HTTP server that can be used as a context manager.

    Wraps a ``uvicorn.Server`` running in a daemon thread.  When used as a
    context manager the server is shut down automatically on exit.

    Parameters
    ----------
    server : uvicorn.Server
        The running uvicorn server instance.
    thread : threading.Thread
        The daemon thread running the server.
    host : str or None
        The host the server was asked to bind, or ``None`` when it is not
        listening on a TCP socket.
    port : int or None
        The port actually bound, or ``None`` when the server is not listening
        on a TCP socket.
    scheme : str, optional
        URL scheme the server is reachable over. Defaults to ``"http"``.
    shutdown_timeout : int, optional
        Seconds to wait for in-flight requests to finish gracefully during
        :meth:`shutdown` before forcing the server closed. Defaults to ``5``.

    Examples
    --------
    >>> with serve_background(node_app(arr)) as server:  # doctest: +SKIP
    ...     print(f"Listening on {server.host}:{server.port}")
    ...     # server is shut down when the block exits
    """

    def __init__(
        self,
        server: uvicorn.Server,
        thread: threading.Thread,
        *,
        host: str | None,
        port: int | None,
        scheme: str = "http",
        shutdown_timeout: int = 5,
    ) -> None:
        self._server = server
        self._thread = thread
        self.host = host
        self.port = port
        self.scheme = scheme
        self._shutdown_timeout = shutdown_timeout

    @property
    def url(self) -> str | None:
        """The base URL of the running server.

        ``None`` when the server is not listening on a TCP socket -- a unix
        socket or an inherited file descriptor has no host and port, and
        inventing one would be a URL that connects to nothing.
        """
        if self.host is None or self.port is None:
            return None
        return f"{self.scheme}://{self.host}:{self.port}"

    def shutdown(self) -> None:
        """Signal the server to shut down and wait for it to stop.

        Waits for the server thread to exit on its own, then escalates to
        ``force_exit`` if it has not, so a request wedged outside uvicorn's
        loop cannot block here forever.

        Raises
        ------
        RuntimeError
            If the thread is still running after both waits. Returning
            normally would report success for a server that is still bound to
            its port and still serving, which the caller cannot detect any
            other way.
        """
        self._server.should_exit = True
        # Outlast uvicorn's own graceful wait rather than matching it. uvicorn
        # spends roughly 0.2s on teardown (a 0.1s loop tick plus a 0.1s sleep)
        # *before* its `timeout_graceful_shutdown` wait even begins, so an
        # equal bound here always expires first -- escalating to force_exit on
        # the path that is supposed to be the orderly one, which makes uvicorn
        # skip ASGI lifespan shutdown entirely.
        self._thread.join(timeout=self._graceful_timeout + _SHUTDOWN_JOIN_MARGIN)
        if self._thread.is_alive():
            self._server.force_exit = True
            self._thread.join(timeout=self._shutdown_timeout)

        if self._thread.is_alive():
            raise RuntimeError(
                "Server thread did not stop within "
                f"{self._graceful_timeout + _SHUTDOWN_JOIN_MARGIN + self._shutdown_timeout:.1f}s, "
                "even after force_exit. The server may still be serving and "
                "holding its port; a request blocked in a store call cannot be "
                "cancelled from here."
            )

    @property
    def _graceful_timeout(self) -> float:
        """uvicorn's own graceful-shutdown bound, whoever configured it."""
        configured = self._server.config.timeout_graceful_shutdown
        return float(configured) if configured is not None else float(self._shutdown_timeout)

    def __enter__(self) -> Self:
        return self

    def __exit__(self, *args: object) -> None:
        self.shutdown()

host instance-attribute

host = host

port instance-attribute

port = port

scheme instance-attribute

scheme = scheme

url property

url: str | None

The base URL of the running server.

None when the server is not listening on a TCP socket -- a unix socket or an inherited file descriptor has no host and port, and inventing one would be a URL that connects to nothing.

__enter__

__enter__() -> Self
Source code in src/zarr_http_server/_serve.py
def __enter__(self) -> Self:
    return self

__exit__

__exit__(*args: object) -> None
Source code in src/zarr_http_server/_serve.py
def __exit__(self, *args: object) -> None:
    self.shutdown()

__init__

__init__(
    server: Server,
    thread: Thread,
    *,
    host: str | None,
    port: int | None,
    scheme: str = "http",
    shutdown_timeout: int = 5,
) -> None
Source code in src/zarr_http_server/_serve.py
def __init__(
    self,
    server: uvicorn.Server,
    thread: threading.Thread,
    *,
    host: str | None,
    port: int | None,
    scheme: str = "http",
    shutdown_timeout: int = 5,
) -> None:
    self._server = server
    self._thread = thread
    self.host = host
    self.port = port
    self.scheme = scheme
    self._shutdown_timeout = shutdown_timeout

shutdown

shutdown() -> None

Signal the server to shut down and wait for it to stop.

Waits for the server thread to exit on its own, then escalates to force_exit if it has not, so a request wedged outside uvicorn's loop cannot block here forever.

Raises:

  • RuntimeError –

    If the thread is still running after both waits. Returning normally would report success for a server that is still bound to its port and still serving, which the caller cannot detect any other way.

Source code in src/zarr_http_server/_serve.py
def shutdown(self) -> None:
    """Signal the server to shut down and wait for it to stop.

    Waits for the server thread to exit on its own, then escalates to
    ``force_exit`` if it has not, so a request wedged outside uvicorn's
    loop cannot block here forever.

    Raises
    ------
    RuntimeError
        If the thread is still running after both waits. Returning
        normally would report success for a server that is still bound to
        its port and still serving, which the caller cannot detect any
        other way.
    """
    self._server.should_exit = True
    # Outlast uvicorn's own graceful wait rather than matching it. uvicorn
    # spends roughly 0.2s on teardown (a 0.1s loop tick plus a 0.1s sleep)
    # *before* its `timeout_graceful_shutdown` wait even begins, so an
    # equal bound here always expires first -- escalating to force_exit on
    # the path that is supposed to be the orderly one, which makes uvicorn
    # skip ASGI lifespan shutdown entirely.
    self._thread.join(timeout=self._graceful_timeout + _SHUTDOWN_JOIN_MARGIN)
    if self._thread.is_alive():
        self._server.force_exit = True
        self._thread.join(timeout=self._shutdown_timeout)

    if self._thread.is_alive():
        raise RuntimeError(
            "Server thread did not stop within "
            f"{self._graceful_timeout + _SHUTDOWN_JOIN_MARGIN + self._shutdown_timeout:.1f}s, "
            "even after force_exit. The server may still be serving and "
            "holding its port; a request blocked in a store call cannot be "
            "cancelled from here."
        )

Configuration

zarr_http_server.CorsOptions

Bases: TypedDict

Options forwarded to Starlette's CORSMiddleware.

Every parameter the middleware accepts appears here, so configuring CORS never requires reaching around this package. Keys left out fall back to the defaults described below; a key that is present is used verbatim, including an empty list.

Two defaults differ from Starlette's own, because this server knows something its caller should not have to. It emits Content-Range on every ranged response, which is not a CORS-safelisted response header -- with Starlette's empty expose_headers a browser client can read the bytes but not learn which bytes it got. And it accepts a Range request header, which Starlette's empty allow_headers would reject at preflight.

  • expose_headers defaults to ["Content-Range"]
  • allow_headers defaults to ["Range"]

Everything else defaults to the middleware's own value: no origins, GET only, no credentials, no origin regex, no private-network access, and a 600-second preflight cache.

Source code in src/zarr_http_server/_serve.py
class CorsOptions(TypedDict, total=False):
    """Options forwarded to Starlette's `CORSMiddleware`.

    Every parameter the middleware accepts appears here, so configuring CORS
    never requires reaching around this package. Keys left out fall back to
    the defaults described below; a key that is present is used verbatim,
    including an empty list.

    Two defaults differ from Starlette's own, because this server knows
    something its caller should not have to. It emits `Content-Range` on
    every ranged response, which is *not* a CORS-safelisted response header --
    with Starlette's empty `expose_headers` a browser client can read the
    bytes but not learn which bytes it got. And it accepts a `Range` request
    header, which Starlette's empty `allow_headers` would reject at preflight.

    * `expose_headers` defaults to `["Content-Range"]`
    * `allow_headers` defaults to `["Range"]`

    Everything else defaults to the middleware's own value: no origins, `GET`
    only, no credentials, no origin regex, no private-network access, and a
    600-second preflight cache.
    """

    allow_origins: list[str]
    allow_methods: list[str]
    allow_headers: list[str]
    allow_credentials: bool
    allow_origin_regex: str | None
    allow_private_network: bool
    expose_headers: list[str]
    max_age: int

allow_credentials instance-attribute

allow_credentials: bool

allow_headers instance-attribute

allow_headers: list[str]

allow_methods instance-attribute

allow_methods: list[str]

allow_origin_regex instance-attribute

allow_origin_regex: str | None

allow_origins instance-attribute

allow_origins: list[str]

allow_private_network instance-attribute

allow_private_network: bool

expose_headers instance-attribute

expose_headers: list[str]

max_age instance-attribute

max_age: int

zarr_http_server.HTTPMethod module-attribute

HTTPMethod = ReadOnlyHTTPMethod | _WriteHTTPMethod

An HTTP method this server implements.

GET and HEAD read a key; PUT writes one. Other verbs are not accepted: the handler has no behavior for them, so serving them would silently answer as if they were GET.

zarr_http_server.ReadOnlyHTTPMethod module-attribute

ReadOnlyHTTPMethod = Literal['GET', 'HEAD']

An HTTP method that cannot modify the store.

Distinguished from HTTPMethod in the type domain, not only at runtime, so a read-only interface can be declared rather than merely configured: a parameter annotated AbstractSet[ReadOnlyHTTPMethod] cannot be handed "PUT" without a type error, whatever the value turns out to be at runtime.

HEAD belongs here because Starlette routes it wherever GET goes, which is what RFC 9110 §9.3.2 asks of an origin server. It is answered from the value's size rather than by building and discarding a body.

zarr_http_server.READ_ONLY_HTTP_METHODS module-attribute

Methods that only read. The default for every app in this package.

Naming the set makes a read-only deployment say so at the call site, rather than being the absence of an argument:

store_app(store, methods=READ_ONLY_HTTP_METHODS)

Typed as a set of ReadOnlyHTTPMethod, so a caller building on it keeps the static guarantee: adding "PUT" to a frozenset[ReadOnlyHTTPMethod] is a type error, not a runtime surprise.

The stronger guarantee is a read-only store, which holds however methods is configured -- see store.with_read_only(True).

zarr_http_server.READ_WRITE_HTTP_METHODS module-attribute

READ_WRITE_HTTP_METHODS: frozenset[HTTPMethod] = frozenset(
    get_args(ReadOnlyHTTPMethod)
    + get_args(_WriteHTTPMethod)
)

Methods that read and write. Serving these grants clients write access.

Every writable app must name a method set, so this constant is also what makes writable deployments findable: grepping for READ_WRITE_HTTP_METHODS (or for methods= generally) turns up every place that opts in.

zarr_http_server.AUTO_PORT module-attribute

AUTO_PORT: Literal['auto'] = 'auto'

Sentinel for port: prefer DEFAULT_PORT, but settle for any free port.

An explicit port is a requirement -- it binds that port or fails -- because a caller who names one usually has something else expecting the server there. "auto" says the opposite: no particular port is needed, so a collision should not stop the server from starting. port=0 keeps its usual meaning of "any free port", with no preference.

zarr_http_server.DEFAULT_PORT module-attribute

DEFAULT_PORT = 8000

Port tried first when port="auto".

zarr_http_server.DEFAULT_MAX_BODY_SIZE module-attribute

DEFAULT_MAX_BODY_SIZE = 256 * 1024 * 1024

Default cap on a PUT body, in bytes.

Store.set takes a whole Buffer, so an accepted body is held in memory in full; the body is read incrementally and abandoned once it passes this cap, so one request cannot size the server's memory use. Pass max_body_size=None to lift the cap and read the body whole.