http/internal/ClientSession.protos

Repository
guillermomolina/protos
Commit
379c6fa63685c39a5954cfbd577bfda3b4df8e75
Tree
8cd4f4afe29ae4c3866381f38c1858108e9799f6
Blob
8fe78dcb734617734597c1d326af6e7d254ce513
Source
View exact source on GitHub
// THE LICENSED WORK IS PROVIDED UNDER THE TERMS OF THE ADAPTIVE PUBLIC LICENSE
// ("LICENSE") AS FIRST COMPLETED BY: Guillermo Adrián Molina. ANY USE, PUBLIC
// DISPLAY, PUBLIC PERFORMANCE, REPRODUCTION OR DISTRIBUTION OF, OR PREPARATION OF
// DERIVATIVE WORKS BASED ON, THE LICENSED WORK CONSTITUTES RECIPIENT'S ACCEPTANCE
// OF THIS LICENSE AND ITS TERMS, WHETHER OR NOT SUCH RECIPIENT READS THE TERMS OF
// THE LICENSE. "LICENSED WORK" AND "RECIPIENT" ARE DEFINED IN THE LICENSE. A COPY
// OF THE LICENSE IS LOCATED IN THE TEXT FILE ENTITLED "LICENSE.TXT" ACCOMPANYING
// THE CONTENTS OF THIS FILE. IF A COPY OF THE LICENSE DOES NOT ACCOMPANY THIS
// FILE, A COPY OF THE LICENSE MAY ALSO BE OBTAINED AT THE FOLLOWING WEB SITE:
// https://github.com/guillermomolina/protos
//
// Software distributed under the License is distributed on an "AS IS" basis,
// WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
// the specific language governing rights and limitations under the License.

//! Internal HTTP/1.1 single-exchange session of std:http/client (D218-B,
//! HTTP.md §16). This module is an unpublished implementation artifact, not an
//! approved Standard Library API. It coordinates one admitted exchange over
//! ClientHead and MessageBody; it owns no authority beyond the duplex it is
//! given and never acquires a connection, resolves a name, or retries.

ClientHead: import("./ClientHead.protos")
MessageBody: import("./MessageBody.protos")
MessageSyntax: import("./MessageSyntax.protos")
BufferedReader: import("std:io/buffered_reader").BufferedReader

/// Establishes the private state of one admitted exchange and answers its
/// zero-argument service body, to be run as the one service Task. prepared is
/// the already validated request snapshot of ClientHead.prepareRequest;
/// limits is the captured ClientLimits snapshot; facility is the private
/// asynchronous bridge of std:http/Client. The body answers the callback's
/// ordinary result, which the service Future adopts.
serviceBody: (facility, ClientError, duplex, prepared, onResponse, limits, owning) => {
    // HTTP-managed read-ahead never exceeds one lower read of this size.
    readSize: limits.ioChunkBytes
    if(limits.maxPrefetchBytes < readSize) {
        readSize = limits.maxPrefetchBytes
    }

    // ------------------------------------------------------------ session state

    // Private state decides every framing and lifecycle question; the
    // callback's response object is never consulted.
    retired: false
    lateFailure: null
    // Lower reads provide independent Bytes; this block never escapes the session.
    emptyInput: Encoding.UTF8.encode("")
    leftover: emptyInput
    leftoverOffset: 0
    leftoverEnd: 0
    physicalEof: false
    pendingLower: null
    framer: null
    informationalCount: 0

    // ------------------------------------------------------------ helpers

    // Every ClientError is a fresh occurrence without an HTTP status.
    clientError: (errorKind) => {
        occurrence: ClientError {
            kind: errorKind
        }
        occurrence
    }

    writeAll: (bytes) => {
        duplex.write(bytes).value()
    }

    // Awaits a pending Future; a cancellation delivered meanwhile still waits
    // for its completion as cleanup of that cancellation unwind.
    awaitThroughCancellation: (future) => {
        (() => {
            future.value()
        }).ensure(() => {
            future.value()
        })
    }

    // ------------------------------------------------------------ response heads

    // Answers the parser's terminal result for one response head. Octets after
    // the head stay in leftover for the next head or the body framer; physical
    // EOF before an accepted head is a malformed (incomplete) response.
    readHead: () => {
        parser: ClientHead.responseHeadParser(limits)
        outcome: null
        while(outcome === null) {
            if(leftoverOffset == leftoverEnd) {
                received: null
                if(!physicalEof) {
                    received = duplex.read(readSize).value()
                }
                if(received === null) {
                    physicalEof = true
                    outcome = {
                        state: "REJECTED"
                        head: null
                        failure: {
                            kind: "malformedResponse"
                        }
                    }
                } else {
                    leftover = received
                    leftoverOffset = 0
                    leftoverEnd = received.size()
                }
            }
            if((outcome === null) && (leftoverOffset < leftoverEnd)) {
                result: parser.feed(leftover, leftoverOffset, leftoverEnd - leftoverOffset)
                leftoverOffset = leftoverOffset + result.consumed
                if(leftoverOffset == leftoverEnd) {
                    leftover = emptyInput
                }
                if(result.state != "NEED_MORE") {
                    outcome = result
                }
            }
        }
        outcome
    }

    // Consumes every informational head (HTTP.md §16.6) and answers the first
    // final head. Nothing after the final head is parsed as another response.
    receiveFinalHead: () => {
        finalHead: null
        while(finalHead === null) {
            outcome: readHead()
            if(outcome.state == "REJECTED") {
                clientError(outcome.failure.kind).signal()
            }
            if(outcome.head.informational) {
                if(informationalCount >= limits.maxInformationalResponses) {
                    clientError("responseLimit").signal()
                }
                informationalCount = informationalCount + 1
            } else {
                finalHead = outcome.head
            }
        }
        finalHead
    }

    // ------------------------------------------------------------ response body

    // Answers the next decoded content (at most maxBytes octets) or null at
    // the logical end of the body. A framer rejection terminalizes the session
    // and signals the recorded ClientError. A pending lower read stays
    // recorded until it is consumed, so a cancelled logical read loses no
    // octet obtained from the duplex.
    nextContent: (maxBytes) => {
        content: null
        done: false
        while(!done) {
            result: null
            if(leftoverOffset < leftoverEnd) {
                result = framer.feed(leftover, leftoverOffset, leftoverEnd - leftoverOffset, maxBytes)
                leftoverOffset = leftoverOffset + result.consumed
                if(leftoverOffset == leftoverEnd) {
                    leftover = emptyInput
                }
            } else {
                if(framer.state() != "OPEN") {
                    result = framer.feed(emptyInput, 0, 0, maxBytes)
                } else {
                    if(physicalEof) {
                        result = framer.endOfInput()
                    } else {
                        if(pendingLower === null) {
                            pendingLower = duplex.read(readSize)
                        }
                        lower: pendingLower
                        received: null
                        Error.handle(
                            () => {
                                received = lower.value()
                            },
                            (error) => {
                                // A failed lower read is reported once and
                                // never replayed by a later logical read.
                                pendingLower = null
                                error.signal()
                            }
                        )
                        pendingLower = null
                        if(received === null) {
                            physicalEof = true
                        } else {
                            leftover = received
                            leftoverOffset = 0
                            leftoverEnd = received.size()
                        }
                    }
                }
            }
            if(result !== null) {
                if(result.state == "CONTENT") {
                    content = result.content
                    done = true
                }
                if(result.state == "COMPLETE") {
                    done = true
                }
                if(result.state == "REJECTED") {
                    failure: clientError(result.failure.kind)
                    lateFailure = failure
                    failure.signal()
                }
            }
        }
        content
    }

    // The private ByteReadable under the response body. Each read answers an
    // already terminal Future; the standard BufferedReader above it supplies
    // the per-read Futures, ordering, and cancellation without a Task.
    framedSource: {
        read: (maxBytes) => {
            answer: null
            if(retired || (lateFailure !== null)) {
                answer = facility.failed(IOLifecycleError {})
            } else {
                Error.handle(
                    () => {
                        answer = facility.resolved(nextContent(maxBytes))
                    },
                    (error) => {
                        answer = facility.failed(error)
                        error
                    }
                )
            }
            answer
        }
    }

    // ------------------------------------------------------------ exchange

    process: () => {
        // The request is written completely before any response octet is read.
        writeAll(prepared.headBytes)
        if((prepared.bodyBytes !== null) && (prepared.bodyBytes.size() > 0)) {
            writeAll(prepared.bodyBytes)
        }

        head: receiveFinalHead()
        framing: head.framing
        if(prepared.isHead) {
            framing = "NONE"
        }
        // The declared-size budget applies only when Content-Length frames an
        // actual body: HEAD, 1xx, 204, 205, and 304 already selected NONE.
        if((framing == "CONTENT_LENGTH") && (head.contentLength > limits.maxResponseBodyBytes)) {
            clientError("responseLimit").signal()
        }
        bodyHead: {
            framing: framing
            contentLength: head.contentLength
        }
        framer = MessageBody.responseBodyFramer(bodyHead, limits)

        bodyReader: BufferedReader(framedSource)
        responseHeaders: []
        for(pair in head.headers) {
            responseHeaders = Array(...responseHeaders, [pair[0], MessageSyntax.copyRange(pair[1], 0, pair[1].size())])
        }
        publicBody: {
            read: (maxBytes) => {
                answer: null
                if(retired) {
                    answer = facility.failed(IOLifecycleError {})
                } else {
                    answer = bodyReader.read(maxBytes)
                }
                answer
            }
        }
        response: {
            version: "1.1"
            status: head.status
            headers: responseHeaders
            body: publicBody
        }

        // The callback runs once; its result is not awaited here.
        outcome: null
        callbackFailure: null
        Error.handle(
            () => {
                outcome = onResponse(response)
            },
            (error) => {
                callbackFailure = error
                error
            }
        )

        // Provenance comes from session state, not from what escaped: a
        // reached framing failure governs even when the callback handled it.
        if(lateFailure !== null) {
            lateFailure.signal()
        }
        if(callbackFailure !== null) {
            callbackFailure.signal()
        }
        outcome
    }

    run: () => {
        answer: null
        (() => {
            // First instruction: a cancellation requested before the service
            // started unwinds from here, through the cleanup below.
            facility.enterService()
            answer = process()
        }).ensure(() => {
            // Retirement precedes cleanup, so a Future the callback returned
            // never extends the life of response.body.
            retired = true
            if(owning) {
                awaitThroughCancellation(duplex.close())
            }
        })
        answer
    }

    run
}