### ----------------------------------------------------
### -- P6W
### -- Licenses: Artistic-2.0
### -- Authors: Sterling Hanenkamp <hanenkamp@cpan.org>
### -- File: RakuWAPI.pod
### ----------------------------------------------------
### -- Chunk 1 of 2
=NAME Web API for Raku (RakuWAPI)

=begin pod

=head1 STATUS

This is a Proposed Draft.

Version 0.9.Draft

=head1 0 INTRODUCTION

This document standardizes an API for web application and server framework developers in Raku. It provides a standard protocol by which web applications and application servers may communicate with each other.

This standard has the following goals:

=item Standardize the interface between server and application so that web developers may focus on application development rather than the nuances of supporting different server platforms.

=item Keep the interface simple so that a web application or middleware requires no additional tools or libraries other than what exists in a standard Raku environment, and no module installations are required.

=item Keep the interface simple so that servers and middleware are simple to implement.

=item Allow the interface to be flexible enough to accommodate a variety of common use-cases and simple optimzations as well as supporting unanticipated use-cases and future extensions.

Aside from that is the underlying assumption that this is a simple interface and ought to at least somewhat resemble work in the standards it is derived from, including [Rack](http://www.rubydoc.info/github/rack/rack/master/file/SPEC), [WSGI](https://www.python.org/dev/peps/pep-0333/), [PSGI](https://metacpan.com/pod/PSGI), [CGI](http://www.w3.org/CGI/), and others.

=head1 1 TERMINOLOGY

=head2 1.0 Glossary

A D<RakuWAPI application> is a Raku routine that expects to receive an environment from an I<application server> and returns a response each time it is called by the server.

A D<Web Server> is an application that processes requests and responses according to a web-related protocol, such as HTTP or WebSockets or similar protocol.

The D<origin> is the external entity that makes a given request and/or expects a response from the application server. This can be thought of generically as a web browser, bot, or other user agent.

An D<application server> is a program that is able to provide an environment to a I<RakuWAPI application> and process the value returned from such an application.

The I<application server> might be associated with a I<web server>, might itself be a I<web server>, might process a protocol used to communicate with a I<web server> (such as CGI or FastCGI), or may be something else entirely not related to a I<web server> (such as a tool for testing I<RakuWAPI applications>).

D<Middleware> is a I<RakuWAPI application> that wraps another I<RakuWAPI application> for the purpose of performing some auxiliary task such as preprocessing request environments, logging, postprocessing responses, etc.

A D<framework developer> is a developer who writes an I<application server>.

An D<application developer> is a developer who writes a I<RakuWAPI application>.

A D<sane Supply> is a Supply object that follows the emit*-done/quit protocol, i.e., it will emit 0 or more objects followed by a call to the done or quit handler. See L<Supply> for details.

=head2 1.1 Type Constraints

The following type constraints are defined for use with this document.

    subset NonEmptyStr of Str where { !.defined || .chars > 0 };
    subset PathStr of Str where { !.defined || $_ ~~ any('', m{ ^ "/" }) };
    subset PositiveInt of Int where { !.defined || $_ > 0 };
    subset Supplierish of Any where { !.defined || ?.can('emit').grep(*.arity == 2) };

Any place a type is used in this document, the implementation is free to use any subtype (either subset or sub-class) of that type in place of the named type so long as the type constraint is guaranteed to hold for the subtype. For example, if an C<Int> is required, it would be permissible to use an C<IntStr> instead.

=head1 2 SPECIFICATION

This specification is divided into three layers:

=item Layer 0: Server

=item Layer 1: Middleware

=item Layer 2: Application

Each layer has a specific role related to the other layers. The server layer is responsible for managing the application lifecycle and performing communication with the origin. The application layer is responsible for receiving metadata and content from the server and delivering metadata and content back to the server. The middleware layer is responsible for enhancing the application or server by providing additional services and utilities.

This specification goes through each layer in order. In the process, each section only specifies the requirements and recommendations for the layer that section describes. When other layers a mentioned outside of its section, the specification is deliberately vague to keep all specifics in the appropriate section. 

To aid in reading this specification, the numbering subsections of 2.0, 2.1, and 2.2 are matched so that you can navigate between them to compare the requirements of each layer. For example, 2.0.1 describes the environment the server provides, 2.1.1 describes how the application interacts with that environment, and 2.1.1 describes how middleware may manipulate that environment.

=head2 2.0 Layer 0: Server

A RakuWAPI application server is a program capable of running RakuWAPI applications as defined by this specification.

A RakuWAPI application server implements some kind of web service. For example, this may mean implementing an HTTP or WebSocket service or a related protocol such as CGI, FastCGI, SCGI, etc. An application server also manages the application lifecycle and executes the application, providing it with a complete environment, and processing the response from the application to determine how to respond to the origin.

One important aspect of this specification that is not defined is the meaning of a server error. At times it is suggested that certain states be treated as a server error, but what that actually means to a given implementation is deliberatly undefined. That is a complex topic which varies by implementation and by the state the server is in when such a state is discovered. The server SHOULD log such events and SHOULD use the appropriate means of communication provided to notify the application that a server error has occurred while responding.

=head3 2.0.0 Application Definition

A RakuWAPI application is defined as a class or object, which must be implemented according to a particular interface. The application server MUST provide a means by which an application is loaded. The application server SHOULD be able to load them by executing a RakuWAPI script file.

For example, here is a simple application:

    use v6;
    sub app(%env) {
        start {
            200, [ Content-Type => 'text/plain' ], [ 'Hello World!' ]
        }
    }

For full details on how an application is defined, see Section 2.2.0. For details on how a server interacts with the application, see Section 2.0.4.

=head3 2.0.1 The Environment

The environment is delivered to the application via hashes, they MUST be L<Associative>. The application server makes the environment available to the application at runtime. The environment is used to:

=item Communicate server capabilities to the application,
=item Allow the application to communicate with the server, and
=item Allow the application to respond to calls to the application.

Each variable or key in the environment is described as belonging to one of two roles:

=item A D<configuration environment variable> describes global capabilities and configuration information to application.

=item A D<runtime environment variable> describes per-call information related to the particular request.

Calls to the runtime routine MUST be provided with all required environment variables belonging to either of these roles in the passed environment hash. However, calls to the configuration routine (see 2.0.4) MUST include the configuration envrionment and SHOULD NOT include runtime environment in the passed environment hash.

The server MAY provide variables in the environment in either role in addition to the ones defined here, but they MUST contain a period and SHOULD be given a unique prefix to avoid name clashes.

The following prefixes are reserved and SHOULD NOT be used unless defined by this specification and only according to the definition given here.

=item C<wapi.> is for RakuWAPI core standard environment.

=item C<wapix.> is for RakuWAPI standard extensions to the environment.

In the tables below, a type constraint is given for each variable. The application server MUST provide each key as the named type. All variables given in the tables with 2.0.1.0 and 2.0.1.1 MUST be provided.

=head4 2.0.1.0 Configuration Environment

The configuration environment MUST be made available to the application during every call made to the application, both to the configuration routine and the runtime routine.

=begin table :allow<C L>

    Variable                 | Constraint           | Description
    =========================|======================|======================================
    C<wapi.version>          | C<< Version:D >>     | This is the version of this
                             |                      | specification, C<v0.9.Draft>.
    
    C<wapi.errors>           | C<< Supplierish:D >> | The error stream for logging.
    
    C<wapi.multithread>      | C<< Bool:D >>        | True if the app may be
                             |                      | simultaneously invoked in another
                             |                      | thread in the same
                             |                      | process.
    
    C<wapi.multiprocess>     | C<< Bool:D >>        | True if the app may be simultaneously
                             |                      | invoked in another process.
    
    C<wapi.run-once>         | C<< Bool:D >>        | True if the server expects the app
                             |                      | to be invoked only once during the
                             |                      | life of the process. This is not a
                             |                      | guarantee.
    
    C<wapi.protocol.support> | C<< Set:D >>         | This is a L<Set> of strings naming the
                             |                      | protocols supported by the application 
                             |                      | server.
    
    C<wapi.protocol.enabled> | C<< SetHash:D >>     | This is the set of enabled protocols. 
                             |                      | The application may modify this set 
                             |                      | with those found in 
                             |                      | C<wapi.protocol.support> to 
                             |                      | enable/disable protocols the server 
                             |                      | is permitted to use.

=end table

=head4 2.0.1.1 Runtime Environment

Many of the runtime environment variables are derived from the old Common Gateway Interface (CGI). This environment MUST be given when the application is being called, i.e., whenever the runtime routine is called.

=begin table :allow<C L>

    Variable                 | Constraint           | Description
    =========================|======================|======================================
    C<REQUEST_METHOD>        | C<< NonEmptyStr:D >> | The HTTP request method, such as
                             |                      | "GET" or "POST".

    C<SCRIPT_NAME>           | C<< PathStr:D >>     | This is the initial portion of the
                             |                      | URI path that refers to the
                             |                      | application.

    C<PATH_INFO>             | C<< PathStr:D >>     | This is the remainder of the request
                             |                      | URI path within the application.
                             |                      | This value SHOULD be URI decoded by
                             |                      | the application server according to
                             |                      | L<RFC 3875|http://www.ietf.org/rfc/rfc3875>

    C<REQUEST_URI>           | C<< Str:D >>         | This is the exact URI sent by the
                             |                      | client in the request line of the
                             |                      | HTTP request. The application server
                             |                      | SHOULD NOT perform any decoding on
                             |                      | it.

    C<QUERY_STRING>          | C<< Str:D >>         | This is the portion of the requested
                             |                      | URL following the C<?>, if any.

    C<SERVER_NAME>           | C<< NonEmptyStr:D >> | This is the name of the web server.

    C<SERVER_PORT>           | C<< PositiveInt:D >> | This is the port number of the web
                             |                      | server.

    C<SERVER_PROTOCOL>       | C<< NonEmptyStr:D >> | This is the server protocol sent by
                             |                      | the client, e.g. "HTTP/1.0"
                             |                      | or "HTTP/1.1".

    C<CONTENT_LENGTH>        | C<< Int:_ >>         | This corresponds to the
                             |                      | Content-Length header sent by the
                             |                      | client. If no such header was sent
                             |                      | the application server MUST set
                             |                      | this key to the L<Int> type value.

    C<CONTENT_TYPE>          | C<< Str:_ >>         | This corresponds to the Content-Type
                             |                      | header sent by the client. If no
                             |                      | such header was sent the application
                             |                      | server MUST set this key to the
                             |                      | L<Str> type value.

    C<HTTP_*>                | C<< Str:_ >>         | The remaining request headers are
                             |                      | placed here. The names are prefixed
                             |                      | with C<HTTP_>, in ALL CAPS with the
                             |                      | hyphens ("-") turned to underscores
                             |                      | ("_"). Multiple incoming headers
                             |                      | with the same name MUST have their 
                             |                      | values joined with a comma (", ") as
                             |                      | described in
                             |                      | L<RFC 2616|http://www.ietf.org/rfc/rfc2616>.
                             |                      | The C<HTTP_CONTENT_LENGTH> and
                             |                      | C<HTTP_CONTENT_TYPE> headers MUST
                             |                      | NOT be set.

    Other CGI Keys           | C<< Str:_ >>         | The server MUST attempt to provide
                             |                      | as many other CGI variables as
                             |                      | possible, but no others are required
                             |                      | or formally specified.

    C<wapi.url-scheme>       | C<< Str:D >>         | Either "http" or "https".

    C<wapi.input>            | C<< Supply:D >>      | The input stream for reading the
                             |                      | body of the request, if any.

    C<wapi.ready>            | C<< Promise:D >>     | This is a vowed Promise that MUST be
                             |                      | kept by the server as soon as the
                             |                      | server has tapped the application's
                             |                      | output Supply and is ready to
                             |                      | receive emitted messages. The value
                             |                      | of the kept Promise is irrelevent.
                             |                      | The server SHOULD NOT break this
                             |                      | Promise.

    C<wapi.body.encoding>    | C<< Str:D >>         | Name of the encoding the server will
                             |                      | use for any strings it is sent.

    C<wapi.protocol>         | C<< Str:D >>         | This is a string naming the
                             |                      | response protocols the server is 
                             |                      | expecting from the application for 
                             |                      | call.

=end table

In the environment, either C<SCRIPT_NAME> or C<PATH_INFO> must be set to a non-empty string. When C<REQUEST_URI> is "/", the C<PATH_INFO> SHOULD be "/" and C<SCRIPT_NAME> SHOULD be the empty string. C<SCRIPT_NAME> MUST NOT be set to "/".

=head3 2.0.2 The Input Stream

The input stream is set in the C<wapi.input> key of the runtime environment. This represents the request payload sent from the origin. Unless otherwise indicated as part of the protocol definition, the server MUST provide a I<sane> L<Supply> that emits L<Blob> objects containing the content of the request payload. It MAY emit nothing and just signal C<done> if the request payload is empty.

=head3 2.0.3 The Error Stream

The error stream MUST be given in the configuration environment via C<wapi.errors>. This MUST be a L<Supplierish> (see Section 1.1) object the server provides for emitting errors. This is a defined object that has an C<emit> method that has the same signature as C<Supplier.emit>. 

The application MAY call C<emit> on this object zero or more times, passing any object that may be stringified. The server SHOULD write these log entries to a suitable log file or to C<$*ERR> or wherever appropriate. If written to a typical file handle, it should automatically append a newline to each emitted message.

=head3 2.0.4 Application Lifecycle

After the application has been defined, it will be called each time the application server needs to respond to the origin. What that means will vary depending on which protocol is needed to appropriately respond to the origin.

These requirements, however, are in held in common regardless of protocol, the application server requirements are as follows:

=item The application server MUST check the type of the return value of the application routine. If the application return value is L<Callable>, the application has returned a configuration routine. Otherwise, the application has returned a runtime routine.

=item If the application returned a configuration routine, as detected by the previous requirement, the application server MUST call this routine and pass the configuration environment in a hash as the first argument to the routine. The return value of this routine is the runtime routine for the application.

=item Prior to each call to runtime routine, the application server MUST set the C<wapi.protocol> variable to the name of the protocol the server will use to communicate with the application.

=item The server MUST receive the return value of runtime routine and process it according to the application protocol in use for this call, the protocol matching the one set in the previous requirement.

=item The server MUST pass a L<Hash> containing all variables of both the configuration environment and runtime environments as the first argument to the runtime routine.

The server MUST NOT call the application with C<wapi.protocol> set to a protocol that has been previously disabled by the application via the C<wapi.protocol.enabled> setting.

For details on how each protocol handles the application call, see section 4.

=head2 2.1 Layer 1: Middleware

RakuWAPI middleware is simply an application that wraps another application. Middleware is used to perform any kind of pre-processing, post-processing, or side-effects that might be added onto an application. Possible uses include logging, encoding, validation, security, debugging, routing, interface adaptation, and header manipulation.

For example, in the following snippet, C<mw> is a middleware application that adds a custom header:

    sub app(%env) { start { 200, [ Content-Type => 'text/plain' ], [ 'Hello World' ] } }
    sub mw(&wrappee is copy, %config) returns Callable {
        &wrappee = wrappee(%config) if &wrappee.returns ~~ Callable;
        sub (%env) {
            wrappee(%env).then(
                -> $p {
                    my @r = $p.result;
                    @r[1].push: 'WAPI-Used' => 'True';
                    @r
                }
            );
        }
    }
    my &mw-app = &mw.assuming(&app);

=head3 2.1.0 Middleware Definition

The way in which middleware is defined and applied is left up to the middleware author. The example in the previous section uses a combination of priming and defining a closure. This is, by no means, the only way to define RakuWAPI middleware in Raku.

What is important in middleware definition is the following:

=item A middleware application MUST be a RakuWAPI application, viz., it MUST be a configuration routine or runtime routine as defined in section 2.2.0.

=item Middleware SHOULD check to see if the application being wrapped returns a configuration routine or a runtime routine by testing whether the return value of the routine is L<Callable>.

=item A middleware configuration routine SHOULD run the wrapped configuration application at configuration time with the configuration environment.

=item A middleware runtime routine SHOULD fail if the wrapped configuration application is a configuration routine.

Any general purpose middleware should be defined as a configuration routine.

Otherwise, There Is More Than One Way To Do It.

=head3 2.1.1 The Environment

Middleware applications MAY set or modify the environment (both configuration and runtime environment) as needed. Middleware applications MUST maintain the typing required for the server in Sections 2.0.1.0 and 2.0.1.1 above, as modified by extensions and the application protocol in use. 

Whenever setting new variables in the environment, the variables MUST contain a period and SHOULD use a unique prefix to avoid name clashes with servers, other middleware, and applications.

=head3 2.1.2 The Input Stream

An application server is required to provide the input stream as a L<Supply> emitting L<Blob>s. Middleware MUST provide the same. 

However, it is possible that the middleware will consume the data in C<wapi.input> for the purpose of parsing or providing the data contained in another form. In such a case, the middleware SHOULD provide an empty, already closed, L<Supply>. The middleware should provide the data in another environment variable.

=head3 2.1.3 The Error Stream

See sections 2.0.3 and 2.2.3.

=head3 2.1.4 Application Lifecycle

Middleware MUST return a valid response to the server according to the value set in C<wapi.protocol> by the server (or whatever middleware came before it).

See sections 2.0.4 and 2.2.4. Middleware MUST adhere to all requirements of the application as respects the server (2.2.4) and all requirements of the server as respects the application (2.0.4).

See section 4 for details on protocol handling.

=head2 2.2 Layer 2: Application

A RakuWAPI application is a Raku routine. The application MUST be L<Callable>. An application may be defined as either a runtime routine or a configuration routine. A configuration routine receives a RakuWAPI configuration environment and returns a runtime routine. A runtime routine receives a RakuWAPI runtime environment and responds to it by returning a response.

As an example, a simple Hello World RakuWAPI application defined with a runtime routine could be implemented as follows:

    sub app(%env) {
        start {
            200, [ Content-Type => 'text/plain' ], [ 'Hello World' ]
        }
    }

Or, a slightly more complex Hello World application could be implemented using a configuration routine instead like so:

    sub app-config(%config) returns Callable {
        %config<wapi.protocol.enabled> ∩= set('request-response');
        sub app(%env) {
            start {
                200, [ Content-Type => 'text/plain' ], [ 'Hello World' ]
            }
        }
    }

This second application makes sure that only the request-response protocol is enabled before returning an application only capable of responding that way (see Section 4).

=head3 2.2.0 Defining an Application

An application is defined in one of two mechanisms, as mentioned in the previous section:

=item A D<runtime routine> defines just the part of the application that reacts to incoming calls from the application server. (See Section 2.2.0.0.)

=item A D<configuration routine> defines a special routine that is called prior to handling any incoming calls from the application server to give the application a chance to communicate with the server. (See Section 2.2.0.1.)

During application defintion, the application MAY also instantiate and apply middleware to be used by the application.

=head3 2.2.0.0 Runtime Routine

To define an application as a runtime routine, the application is defined as a L<Callable> (typically a L<Routine>). This application MUST accept a single parameter as its argument. When the application server handles a request, the server will set this parameter to the runtime environment for the request. The application MUST NOT have a return type set to a L<Callable>.

The application SHOULD respond to the caller, i.e., the application server or outer middleware, according to the C<wapi.protocol> string set in the passed environment.

Here, for example, is a RakuWAPI application that calculates and prints the Nth Lucas number depending on the value passed in the query string. This assumes a C<request-response> protocol (see Section 4.0).

    sub lucas-runtime(%env) {
        start {
            my $n = %env<QUERY_STRING>.Int;
            my $lucas-number := 2, 1, * + * ... *;
            200, [ Content-Type => 'text/plain' ], [ $lucas-number[$n] ];
        }
    }

This application is vulnerable, however, to problems if the server might call the application with a different protocol.

=head3 2.2.0.1 Configuration Routine

An application SHOULD return a configuration routine, which is defined just like the runtime routine, but it must constrain its return type to something L<Callable>. This application MUST accept a single parameter as its argument, just like the runtime routine. This single parameter will be set to the configuration environment when called by the application server. This routine will also be called prior to any request or other contact from an origin has occurred, which gives the application the opportunity to communicate with the server early.

The application SHOULD modify the configuration environment to suit the needs of the application. The application SHOULD end the routine by returning a runtime routine (see the previous section).

Here is the example from the previous section, but using a configuration routine to guarantee that the only protocol the application can use to contact it is the request-response protocol (see Section 4.0). It ends by returning the C<&lucas-app> subroutine defined in the previous section:

    sub lucas-config(%config) returns Callable {
        # Only permit the request-response protocol
        %config<wapi.protocol.enabled> ∩= set('request-response');

        &lucas-runtime;
    }

=head3 2.2.1 The Environment

Calls to the configuration routine of the application (if defined) will receive the configuration environment as defined in Section 2.0.1.0. Calls to the runtime routine of the application will receive the combination of the runtime environment and configuration environment as defined in Sections 2.0.1.0 and 2.0.1.1. Additional variables may be provided by your application server and middleware in either environment hash.

The application itself MAY store additional values in the environment as it sees fit. This allows the application to communicate with a server or middleware or even with itself. When the application modifies the environment, the variables set MUST contain a period and SHOULD start with a unique name that is not C<wapi.> or C<wapix.> as these are reserved.

=head3 2.2.2 The Input Stream

Some calls to your application may be accompanied by a request payload. For example, a POST or PUT request sent by an origin using HTTP will typically include such a payload. The application MAY choose to read the payload using the sane L<Supply> provided in the C<wapi.input> variable of the runtime environment. This will provide a stream lf L<Blob>s.

=head3 2.2.3 The Error Stream

The application server is required to provide a C<wapi.errors> variable in the environment with a L<Supplierish> object (see Section 1.1). The application MAY emit any errors or messages here using any object that stringifies. The application SHOULD NOT terminate such messages with a newline as the server will do so if necessary.

=head3 2.2.4 Application Call

To handle requests from the origin, the application server will make calls to the application routine. The application SHOULD return a valid response to the server. The response required will depend on what string is set in C<wapi.protocol> within the runtime environment, so the application SHOULD check that on every call if it may vary.

The application SHOULD attempt to return a value as quickly as possible via the runtime routine. For protocols that require the application to return a L<Promise>, the application SHOULD wrap the entire body of the call in a C<start> block to minimize the time the server will be waiting on the application.

See section 4 on how different application protocols are handled.

=head1 3 Extensions

In addition to the standard specification, there are a number of extensions that servers or middleware MAY choose to implement. They are completely optional and applications and middleware SHOULD check for their presence before using them. Such checks SHOULD be performed as early as possible.

Unless stated otherwise, all environment variables described here are set in the runtime environment, which is passed as the single argument with each call to the runtime routine.

=head2 3.0 Header Done

The C<wapix.header.done> environment variable, if provided, MUST be a vowed L<Promise>. This Promise MUST be kept when the server is done sending or processing the response header. The Promise MUST be broken if the server is unable or unwilling to send the application provided headers.

This is not an exhaustive list, but here are a few possible reasons why this Promise MAY be broken:

=item The headers are invalid and the application server will not send them.

=item An internal error occurred in the application server.

=item The client hungup the connection before the headers could be sent.

When broken, this Promise SHOULD be broken with a helpful diagnostic exception.

=head2 3.1 Body Done

The C<wapix.body.done> environment variable, if provided, MUST be a vowed L<Promise>. This Promise MUST be kept when the server is done sending or processing the response body. The Promise MUST be broken if the server is unable or unwilling to send the complete application body.

This is not an exhaustive list, but here are a few possible reasons why this Promise MAY be broken:

=item The application server has already transmitted C<Content-Length>, but the application continued to send bytes after that point.

=item The client hungup the connection before it finished sending the response.

=item An application initiated an HTTP/2 push-promise, which the server had begun to fulfill when it received a cancel message from the client.

In particular, C<wapix.body.done> MUST be broken if C<wapix.header.done> is broken (assuming both extensions are implemented).

When broken, the Promise SHOULD be broken with a helpful diagnostic exception.

=head2 3.2 Raw Socket

The C<wapix.io> environment variable, if provided, SHOULD be the socket object used to communicate to the client. This is the interface of last resort as it sidesteps the entire RakuWAPI interface. It may be useful in cases where an application wishes to control details of the socket itself.

If your application requires the use of this socket, please file an issue describing the nature of your application in detail. You may have a use-case that a future revision to RakuWAPI can improve.

This variable MAY be made available as part of the configuration environment.

=head2 3.3 Logger

The C<wapix.logger> environment variable, if provided, MUST be a L<Routine> defined with a signature as follows:

    sub (Str:D $message, Str:D :$level = 'info');

When called application MUST provide a C<$level> that is one of: C<"debug">, C<"info">, C<"warn">, C<"error">, C<"fatal">.

Te C<wapix.logger> environment variable SHOULD be provided in the configuration environment.

=head2 3.4 Sessions

This extension implements basic session handling that allows certain data to persist across requests. Session data SHOULD be associated with a particular origin.

The C<wapix.session> environment variable, if provided, MUST be an L<Associative>. This hash maps arbitrary keys and values that may be read and written to by an application. The application SHOULD only use L<Str> keys and values. The details of persisting this data is up to the application server or middleware implementing the session extension.

The C<wapix.session.options> environment variable, if provided, MUST be an L<Associative>. This variable uses implementation-specific keys and values to communicate between the application and the extension implementation. This allows the application a channel by which to instruct the session handler how to operate.

=head2 3.5 Harakiri Mode

The C<wapix.harakiri> environment variable, if provided, MUST be a L<Bool>. If set to C<True> it signals to the application that the server supports harakiri mode, which allows the application to ask the server to terminate the current work when the request is complete. This variable SHOULD be set in the configuration environment.

The C<wapix.harakiri.commit> environment variable MAY be set to a C<True> value by the application to signal to the server that the current worker should be killed after the current request has been processed.

=head2 3.6 Cleanup Handlers

The C<wapix.cleanup> environment variable, if provided, MUST be a L<Bool>. If set to C<True> it tells the application that the server supports running cleanup handlers after the request is complete. This variable SHOULD be set in the configuration environment.

The C<wapix.cleanup.handlers> environment variable MUST be provided if the C<wapix.cleanup> flag is set. This MUST an L<Array>. The application adds cleanup handlers to the array by putting L<Callable>s into the Array (usually by C<push>ing). Each handler will be given a copy of the C<%env> as the first argument. The server MUST run these handlers, but only after the application has completely finished returning the response and any response payload.

If the server supports the harakiri extension, it SHOULD allow the cleanup handlers to invoke harakiri mode by setting C<wapix.harakiri.commit> (see 3.5).

=head2 3.7 Output Block Detection

The C<wapix.body.backpressure> environment variable, if provided, MUST be a L<Bool> flag. It is set to C<True> to indicate that the RakuWAPI server provide response backpressure detection by polling for non-blocking I/O problems. In this case, the server MUST provide the other two environment variables. If C<False> or not defined, the server does not provide these two environment variables. This variable SHOULD be defined in the configuration environment.

The C<wapix.body.backpressure.supply> environment variable MUST be provided if C<wapix.body.backpressure> is C<True>. When provided, it MUST be a live L<Supply> that periodically emits C<True> and C<False> values. C<True> is emitted when the server polls for backpressure and detects a blocked output socket. C<False> is emitted when the server polls for backpressure and detects the previously blocked socket is no longer blocked.

The C<wapix.body.backpressure.test> environment variable MUST be provided if C<wapix.body.backpressure> is C<True>. When provided, it MUST be a L<Bool> that is C<True> while output has last been detected as blocked and C<False> otherwise. This can be useful for detecting the initial state before the backpressure supply has emitted any value or just as a way to poll the last known status of the socket.

=head2 3.8 Protocol Upgrade

The C<wapix.net-protocol.upgrade> environment variable MUST be provided in the configuration environment, if the server implements the protocol upgrade extension. It MUST be the L<Set> of names of protocols the server supports for upgrade.

When the client makes a protocol upgrade request using an C<Upgrade> header, the application MAY request that the server negotiate the upgrade to one of these supported protocols by sending a C<WAPIx-Upgrade> header back to the server with the named protocol. The application MAY send any other headers related to the Upgrade and MAY send a message payload if the upgrade allows it. These SHOULD override any server supplied values or headers.

The server MUST negotiate the new protocol and enable any environment variables required for interacting through that protocol. After the handshake or upgrade negoatiation is complete, the server MUST make a new call to the application with a new environment to process the remainder of the network request with the origin.

=head3 3.8.0 HTTP/2 Protocol Upgrade

The workings of HTTP/2 are similar enough to HTTP/1.0 and HTTP/1.1 that use of a protocol upgrade may not be necessary in most or all use-cases. However, servers MAY choose to delegate this to the application using the protocol upgrade extension.

Servers that support this protocol upgrade MUST place the name "h2c" and/or "h2" into the C<wapix.net-protocol.upgrade> set, for support of HTTP/2 over cleartext connections and HTTP/2 over TLS, respectively.

The application MUST NOT request an upgrade using the C<WAPIx-Upgrade> header for "h2c" unless the C<wapi.url-scheme> is "http". Similarly, the application MUST NOT request an upgrade for "h2" unless the C<wapi.url-scheme> is "https". The application server SHOULD enforce this requirement for security reasons.

The application MUST NOT tap the C<wapi.input> stream when performing this upgrade. The application SHOULD NOT return a message payload aside from an empty L<Supply>.

=head3 3.8.1 WebSocket Protocol Upgrade

Servers that support the WebSocket protocol upgrade MUST place the name "ws" into the C<wapix.net-protocol.upgrade> set.

The application MUST NOT tap the C<wapi.input> stream when performing this upgrade. The application SHOULD NOT return a message payload aside from an empty L<Supply>.

=head2 3.9 Transfer Encoding

This extension is only for HTTP/1.1 protocol connections. When the server supports this extension, it MUST provide a C<wapix.http11.transfer-encoding> variable containing a C<Set> naming the transfer encodings the server supports as strings. This SHOULD be set in the configuration environment.

When the application returns a header named C<WAPIx-Transfer-Encoding> with the name of one of the supported transfer encoding strings, the server MUST apply that transfer encoding to the message payload. If the connection is not HTTP/1.1, the server SHOULD ignore this header.

=head3