GitHub

platform

API reference for platform.

What a server platform provides responses with (Effect's HttpPlatform): file responses with an ETag and last-modified, and response compression.

layer serves files through FileSystem and compresses with the standard library: gzip and deflate (zlib), and zstd where compression.zstd exists (Python 3.14). layer_live adds brotli with the brotli extra.

Re-exports

Values

AttributeTypeDescription
compression_stdlibCompression

gzip and deflate, and zstd on Python 3.14.

compression_liveCompression

What a live server offers (Node's NodeHttpCompression): compression_stdlib's and brotli with the brotli extra, one-shot bodies compressed whole off the fiber's thread.

layerLayer[HttpPlatform, Never, FileSystem]

Files streamed from FileSystem; the standard library's compression; weak ETags.

layer_strongLayer[HttpPlatform, Never, FileSystem]

layer with strong ETags.

layer_liveLayer[HttpPlatform]

The platform of the live server (Effect's NodeHttpPlatform.layer): layer_strong over the host's file system, compressing bytes bodies whole.

Types

TypeDefinitionDescription
CompressionAlgorithmtype CompressionAlgorithm = Literal['gzip', 'deflate', 'br', 'zstd']
PlatformNametype PlatformName = Literal['deno', 'node', 'bun', 'web']
Transformtype Transform = Callable[[CompressionAlgorithm, int | None, Stream[bytes, Any]], Stream[bytes, Any]]

Classes

Functions

wrap_compression

wrap_compression(impl) -> Compression

impl, setting content-encoding and vary on what it compressed, and weakening a strong ETag.

ParameterTypeDescription
implCompression

Returns Compression

def wrap_compression(impl: Compression) -> Compression:
    """``impl``, setting ``content-encoding`` and ``vary`` on what it
    compressed, and weakening a strong ETag."""

    def compress(
        response: HttpServerResponse, algorithm: CompressionAlgorithm, level: int | None
    ) -> Effect[HttpServerResponse]:
        return impl.compress_response(response, algorithm, level).map(
            lambda compressed: _with_encoding(response, compressed, algorithm)
        )

    return Compression(impl.algorithms, compress)

make_compression_stream

make_compression_stream(algorithms, transform) -> Compression

A compression transforming the bytes of bytes, stream and raw (bytes, str, async iterable or WebResponse) bodies; it leaves other bodies alone (Effect's makeCompressionWeb).

ParameterTypeDescription
algorithmsIterable[CompressionAlgorithm]
transformTransform

Returns Compression

def make_compression_stream(
    algorithms: Iterable[CompressionAlgorithm], transform: Transform
) -> Compression:
    """A compression transforming the bytes of bytes, stream and raw
    (``bytes``, ``str``, async iterable or ``WebResponse``) bodies; it
    leaves other bodies alone (Effect's ``makeCompressionWeb``)."""
    from pyfect.http.web import WebResponse

    def compressed(
        response: HttpServerResponse,
        chunks: Stream[bytes, Any],
        content_type: str | None,
        algorithm: CompressionAlgorithm,
        level: int | None,
    ) -> HttpServerResponse:
        body = _body.stream(transform(algorithm, level, chunks), content_type)
        return response.set_body(body).remove_header("content-length")

    def compress(
        response: HttpServerResponse, algorithm: CompressionAlgorithm, level: int | None
    ) -> Effect[HttpServerResponse]:
        body = response.body
        content_type = response.headers.get("content-type", body.content_type)
        match body:
            case _body.Bytes():
                chunks: Stream[bytes, Any] = stream_succeed(body.body)
            case _body.Stream():
                chunks = body.stream
            case _body.Raw():
                raw = body.body
                if isinstance(raw, WebResponse):
                    raw = raw.body
                if raw is None:
                    return succeed(response)
                if isinstance(raw, str):
                    raw = text_encode(raw)
                if isinstance(raw, (bytes, bytearray)):
                    chunks = stream_succeed(bytes(raw))
                elif hasattr(raw, "__aiter__"):
                    chunks = from_async_iterable(cast("Any", raw), lambda error: error)
                else:
                    return succeed(response)
            case _:
                return succeed(response)
        return succeed(compressed(response, chunks, content_type, algorithm, level))

    return Compression(frozenset(algorithms), compress)

compression_one_shot

compression_one_shot(fallback) -> Compression

Bytes bodies compressed whole, off the fiber's thread, with an exact content-length; other bodies by fallback (Node's NodeHttpCompression.make).

ParameterTypeDescription
fallbackCompression

Returns Compression

def compression_one_shot(fallback: Compression) -> Compression:
    """Bytes bodies compressed whole, off the fiber's thread, with an exact
    ``content-length``; other bodies by ``fallback`` (Node's
    ``NodeHttpCompression.make``)."""

    def compress(
        response: HttpServerResponse, algorithm: CompressionAlgorithm, level: int | None
    ) -> Effect[HttpServerResponse]:
        body = response.body
        if not isinstance(body, _body.Bytes):
            return fallback.compress_response(response, algorithm, level)
        content_type = response.headers.get("content-type", body.content_type)
        data = body.body

        def compressed(result: bytes) -> HttpServerResponse:
            return response.set_body(_body.bytes_(result, content_type)).set_header(
                "content-length", str(len(result))
            )

        return blocking(lambda: _compress_whole(data, algorithm, level)).map(compressed)

    return Compression(fallback.algorithms, compress)

make

make(*, platform, compression, file_response, file_web_response) -> Effect[HttpPlatformService, Never, Generator | FileSystem]

A platform from its file responses (given the clamped range and the ETag and last-modified headers) and its compression.

ParameterTypeDescription
platformPlatformName
compressionCompression
file_responseFileResponseImpl
file_web_responseFileWebResponseImpl

Returns Effect[HttpPlatformService, Never, Generator | FileSystem]

def make(
    *,
    platform: PlatformName,
    compression: Compression,
    file_response: FileResponseImpl,
    file_web_response: FileWebResponseImpl,
) -> Effect[HttpPlatformService, Never, Generator | FileSystem]:
    """A platform from its file responses (given the clamped range and the
    ETag and ``last-modified`` headers) and its compression."""

    @fn_untraced
    def build():
        fs = yield from FileSystem()
        etags = yield from Generator()

        @fn_untraced
        def respond_file(path: str, **options: Unpack[FileOptions]):
            info = yield from fs.stat(path)
            etag = yield from etags.from_file_info(info)
            given_offset = options.get("offset")
            requested = 0 if given_offset is None else (yield from _size(given_offset, "offset"))
            offset = min(requested, info.size)
            available = info.size - offset
            given_count = options.get("bytes_to_read")
            count = None if given_count is None else (yield from _size(given_count, "bytesToRead"))
            content_length = available if count is None or count > available else count
            limit = None if count is None else offset + content_length
            start = yield from _safe(offset, "offset")
            end = None if limit is None else (yield from _safe(limit, "end"))
            headers = _option_headers(options).set("etag", etag_to_string(etag))
            if info.mtime is not None:
                headers = headers.set("last-modified", format_http_date(info.mtime))
            return file_response(
                path,
                options.get("status", 200),
                options.get("status_text"),
                headers,
                start,
                end,
                content_length,
            )

        def respond_file_web(
            file: FileLike, **options: Unpack[FileWebOptions]
        ) -> Effect[HttpServerResponse]:
            def respond(etag: Any) -> HttpServerResponse:
                headers = _option_headers(options).merge(
                    Headers(
                        {
                            "etag": etag_to_string(etag),
                            "last-modified": format_http_date(file.last_modified),
                        }
                    )
                )
                return file_web_response(
                    file, options.get("status", 200), options.get("status_text"), headers, options
                )

            return etags.from_file_web(file).map(respond)

        return HttpPlatformService(
            platform, wrap_compression(compression), respond_file, respond_file_web
        )

    return build()