http/internal/host_worker/module.protos

Repository
guillermomolina/protos
Commit
2723a55555e7beecee0816bf99d16e3c8c1ae635
Tree
c36054e4e5abd7fc29a039b4e096cac2e8706492
Blob
cc8f45831d1bd18ce4b1d6d87e247ade2c9fe575
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 Worker Actor bootstrap of std:http/host (D216, HTTP.md §§15.3 to
//! 15.6). This module is an unpublished implementation artifact, not an
//! approved Standard Library API.
//!
//! `start` is the `Actor.spawn` bootstrap binding of `Host.owning`. Its only
//! initialization arguments are the delegated TcpAcceptor, the handler module
//! specifier and binding name, the Worker's fixed quotas and the captured
//! limits; no listener, connection, Closure, Future or module instance crosses
//! into the Worker. A String is resolved inside this Actor; a genuine reference
//! preserves the application's selected target. This Actor owns its own instance.
//!
//! `startWithFactory` is the bootstrap binding of `Host.owningWithFactory`
//! (D225-A, HTTP.md §15.13). It receives the same arguments with a factory
//! module and binding in place of the handler ones and resolves the factory
//! exactly like a handler. The application initialization is not a spawn
//! argument: it arrives as the argument of the host's "serve" request, so it
//! crosses under the ordinary Actor transfer rules, never under the
//! spawn-only TcpAcceptor delegation. The Worker calls the factory exactly
//! once in its lifetime with its own copy; the result, which must itself be
//! callable, is the handler of every session of this Worker. The Worker Actor
//! is READY before it receives the initialization; it enters its acceptance
//! service, and answers "ready" with true, only after that construction
//! succeeded and before any shutdown cutover.
//!
//! The Worker accepts by itself and services each accepted connection exactly
//! once through `Server.serveOne.owning`, inside this Actor, with custody kept
//! by HostConnection. Acceptance runs in lanes: a lane holds at most one
//! accepted connection or one pending accept, so live lanes bound accepted
//! plus pending connections. A lane is added only when every live lane is
//! serving, never beyond the connection quota, so lanes follow concurrent
//! demand. Each lane belongs to one of `pendingQuota` groups and a group has at
//! most one pending accept, which bounds outstanding accepts. Whenever a lane
//! is not serving, its group has a pending accept, so freed capacity resumes
//! acceptance. Lanes started while serving are structured children of the
//! lane that started them, so the acceptance service ends only after all of
//! them.
//!
//! Shutdown arrives as control messages: "drain" stops admission, and "abort"
//! also requests cancellation of the outstanding accepts and admitted
//! sessions. An unexpected accept failure is a fatal listener failure: the
//! Worker applies the same abort to itself at once, instead of waiting for
//! another pending accept or for a client. Cancellation stays cooperative
//! (FUTURES_AND_TASKS.md §23): it wakes suspended accepts, reads and writes,
//! but handler code that runs without reaching a cancellation boundary still
//! runs to its end, and every session completes its owning cleanup before the
//! acceptance service replies. The host stops this Actor only after that
//! reply, so every owning cleanup runs while the Worker is still READY.

Server: import("std:http/server").Server
HostConnection: import("../HostConnection.protos")

// Waits for a Future of this Actor, discarding its outcome.
settle: (future) => {
    Error.handle(
        () => {
            future.value()
        },
        (error) => {
            error
        }
    )
}

// Requests cancellation of every Future held in futures.
cancelEach: (futures) => {
    for(future in futures) {
        if(future !== null) {
            future.cancel()
        }
    }
}

/// The acceptance service of one Worker, answered as its behavior: `serve`,
/// `ready`, `drain` and `abort`. acceptor answers accept Futures;
/// admitConnection(connection) admits a delivered connection to its session
/// and answers its HostConnection custody. A connection delivered after the
/// admission cutover is released by this Worker without admitConnection.
acceptance: (acceptor, connectionQuota, pendingQuota, admitConnection) => {
    admitting: true
    serving: false
    // The worst fatal outcome of this Worker: "listener" or "cleanup".
    failure: null
    lanes: 0
    busy: 0
    // The pending accept of each group, or null.
    groups: Array()
    while(groups.size() < pendingQuota) {
        groups = Array(...groups, null)
    }
    // The service Future of the session each lane serves, or null.
    sessions: Array()
    while(sessions.size() < connectionQuota) {
        sessions = Array(...sessions, null)
    }

    // Stops admission and requests cooperative cancellation of the
    // outstanding accepts and admitted sessions; each session still runs its
    // owning cleanup before its Future becomes terminal. Repeating it cancels
    // nothing twice: cancel() of a terminal Future is a no-op.
    abortAll: () => {
        admitting = false
        cancelEach(groups)
        cancelEach(sessions)
    }

    // A fatal outcome is recorded and aborts this Worker at once: admission stops and its accepts and sessions are cancelled, so the
    // acceptance service replies without any external drain or abort. A
    // connection cleanup failure supersedes a listener failure, as the host's
    // mandatory cleanup failures do.
    record: (kind) => {
        if((failure === null) || (kind == "cleanup")) {
            failure = kind
        }
        abortAll()
    }

    // The listener close cutover (IOLifecycleError) or a cancellation
    // requested by this Worker is the ordinary end of acceptance; any other
    // accept failure is a fatal listener failure (HTTP.md §15.10).
    stopAccepting: (error) => {
        if((error.parent() === IOLifecycleError) || (error.parent() === Cancelled)) {
            admitting = false
        } else {
            record("listener")
        }
    }

    lane: null
    // A lane's number indexes the session slot of the connection it serves.
    startLane: (group) => {
        slot: lanes
        lanes = lanes + 1
        (() => {
            lane(group, slot)
        }).future()
    }

    // Request, handler and ordinary client failures are retired by the
    // owning session and stay local to this Worker; a failed mandatory close
    // is a cleanup failure (HTTP.md §§15.6, 15.10). The quota unit is released
    // on every exit, including cancellation.
    admit: (connection, slot) => {
        failed: false
        if(admitting) {
            busy = busy + 1
            (() => {
                if((busy == lanes) && (lanes < connectionQuota)) {
                    startLane(lanes % pendingQuota)
                }
                custody: admitConnection(connection)
                sessions[slot] = custody.service
                failed = custody.retire()
            }).ensure(() => {
                sessions[slot] = null
                busy = busy - 1
            })
        } else {
            failed = HostConnection.release(connection)
        }
        if(failed) {
            record("cleanup")
        }
    }

    lane = (group, slot) => {
        while(admitting) {
            current: groups[group]
            if(current !== null) {
                settle(current)
                // The issuing lane may not have run yet; a settled accept no
                // longer occupies the group.
                if(groups[group] === current) {
                    groups[group] = null
                }
            } else {
                pending: acceptor.accept()
                groups[group] = pending
                connection: null
                error: null
                Error.handle(
                    () => {
                        connection = pending.value()
                    },
                    (signalled) => {
                        error = signalled
                        signalled
                    }
                )
                if(groups[group] === pending) {
                    groups[group] = null
                }
                if(error !== null) {
                    stopAccepting(error)
                } else {
                    admit(connection, slot)
                }
            }
        }
    }

    service: {
        // Runs the acceptance service until admission ends and every
        // admitted session has retired; answers "drained", "listener" or
        // "cleanup". Lanes started while serving are structured children of
        // the initial lanes, which therefore end after them.
        serve: () => {
            serving = true
            initial: Array()
            while(initial.size() < pendingQuota) {
                initial = Array(...initial, startLane(initial.size()))
            }
            for(started in initial) {
                settle(started)
            }
            outcome: "drained"
            if(failure !== null) {
                outcome = failure
            }
            outcome
        }
        // Answers whether the acceptance service has been entered.
        ready: () => {
            serving
        }
        // Stops admission: connections delivered from now on are released
        // unserved; admitted sessions continue to completion.
        drain: () => {
            admitting = false
            null
        }
        // Stops admission and requests cancellation of the outstanding
        // accepts and admitted sessions while this Worker can still run
        // their owning cleanup (HTTP.md §15.8).
        abort: () => {
            abortAll()
            null
        }
    }
    service
}

// Answers whether value is callable (CALLABLES.md, "Callability
// inspection"); nothing is invoked.
callable: ((facility) => {
    (value) => {
        facility.provides(value, "call")
    }
})(_httpAsyncFacility)

// Answers a gate: its future stays pending until open() and then answers
// null; opening twice is a no-op. The blocker waits for this Actor's own
// termination, which cancels it at the latest, so the gate never outlives
// the Actor and no polling is involved.
gate: () => {
    blocker: (() => {
        Actor.current().termination().value()
    }).future()
    opened: (() => {
        settle(blocker)
        null
    }).future()
    result: {
        future: opened
        open: () => {
            blocker.cancel()
        }
    }
    result
}

// Answers the callable own top-level binding bindingName of this Actor's
// instance of moduleSpecifier. A missing module, missing own binding, or
// non-invokable binding signals, failing this Actor's initialization (HTTP.md
// §15.4). A String is resolved relative to this module (MODULES.md); a genuine
// reference retains its acquired canonical target through ordinary import.
ownCallable: (moduleSpecifier, bindingName) => {
    module: import(moduleSpecifier)
    if(!module.hasSlot(bindingName)) {
        Error().signal()
    }
    binding: module.slotValue(bindingName)
    if(!callable(binding)) {
        Error().signal()
    }
    binding
}

/// Worker bootstrap of `Host.owning`: answers the acceptance service as the
/// Worker behavior, serving every admitted session with the binding
/// handlerBinding of handlerModule.
this.start: (acceptor, handlerModule, handlerBinding, connectionQuota, pendingQuota, limits) => {
    handler: ownCallable(handlerModule, handlerBinding)
    acceptance(acceptor, connectionQuota, pendingQuota, (connection) => {
        HostConnection.admit(Server, connection, handler, limits)
    })
}

/// Worker bootstrap of `Host.owningWithFactory` (HTTP.md §15.13): resolves
/// the binding factoryBinding of factoryModule and answers the Worker
/// behavior. This Actor is READY before it holds any initialization; the
/// handler is built later, by the first "serve" request, and readiness is
/// the hosting readiness of HTTP.md §15.7, not Actor READY.
///
/// `serve(initialization)` receives this Worker's own copy through the
/// ordinary request transfer, calls the factory at most once in this
/// Worker's lifetime, and only then enters the acceptance service, serving
/// every admitted session with the factory result. `ready` answers true only
/// once that handler is built and validated and no shutdown has reached this
/// Worker. `drain` and `abort` are those of the acceptance service; both are
/// also a cutover after which acceptance is never entered, and `abort`
/// requests cooperative cancellation of a construction still in progress.
this.startWithFactory: (acceptor, factoryModule, factoryBinding, connectionQuota, pendingQuota, limits) => {
    factory: ownCallable(factoryModule, factoryBinding)
    handler: null
    // Opened once "serve" has entered the acceptance service or ended
    // without entering it. "ready" waits for it rather than for the
    // construction: two waiters of one Future resume in no specified order,
    // so "ready" could otherwise answer before "serve" entered.
    entered: gate()
    // Set by "drain" or "abort": acceptance is never entered afterwards.
    cutover: false
    // The Future of the one construction. It is set synchronously by the
    // first "serve", before any suspension, so it also guards against a
    // second construction or acceptance.
    construction: null
    service: acceptance(acceptor, connectionQuota, pendingQuota, (connection) => {
        HostConnection.admit(Server, connection, handler, limits)
    })
    behavior: {
        // A factory Error or a non-callable result escapes this turn and is
        // fatal to the Worker, which the host classifies as a startup
        // failure. The construction Task answers null, so a Future result is
        // never adopted: it is checked like any other value. A cancellation
        // requested by "abort" is the ordinary end of a construction; any
        // other cancellation of it is fatal. Every later "serve" answers null
        // at once and changes nothing.
        serve: (initialization) => {
            outcome: null
            if(construction === null) {
                (() => {
                    construction = (() => {
                        if(!cutover) {
                            built: factory(initialization)
                            if(!callable(built)) {
                                Error().signal()
                            }
                            handler = built
                        }
                        null
                    }).future()
                    Cancelled.handle(
                        () => {
                            construction.value()
                        },
                        (cancelled) => {
                            if(!cutover) {
                                Error().signal()
                            }
                            cancelled
                        }
                    )
                    outcome = "drained"
                    if(!cutover) {
                        // Turns are not preempted (ACTORS.md §24D): "ready"
                        // resumes only after this turn suspends, which happens
                        // inside the acceptance service, after it was entered.
                        entered.open()
                        outcome = service.serve()
                    }
                }).ensure(() => {
                    entered.open()
                })
            }
            outcome
        }
        // Same-sender FIFO: "ready" is dispatched only after "serve" started.
        // It answers true only once "serve" has entered the acceptance
        // service after a successful construction and no cutover happened.
        ready: () => {
            settle(entered.future)
            service.ready() && !cutover
        }
        drain: () => {
            cutover = true
            service.drain()
        }
        abort: () => {
            cutover = true
            if(construction !== null) {
                construction.cancel()
            }
            service.abort()
        }
    }
    behavior
}

this.acceptance: acceptance

// The runtime-provisioned facility is captured privately above; it is not
// module surface.
context.removeSlot("_httpAsyncFacility")