Chris@63: // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors Chris@63: // Licensed under the MIT License: Chris@63: // Chris@63: // Permission is hereby granted, free of charge, to any person obtaining a copy Chris@63: // of this software and associated documentation files (the "Software"), to deal Chris@63: // in the Software without restriction, including without limitation the rights Chris@63: // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell Chris@63: // copies of the Software, and to permit persons to whom the Software is Chris@63: // furnished to do so, subject to the following conditions: Chris@63: // Chris@63: // The above copyright notice and this permission notice shall be included in Chris@63: // all copies or substantial portions of the Software. Chris@63: // Chris@63: // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR Chris@63: // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, Chris@63: // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE Chris@63: // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER Chris@63: // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, Chris@63: // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN Chris@63: // THE SOFTWARE. Chris@63: Chris@63: #ifndef KJ_ASYNC_IO_H_ Chris@63: #define KJ_ASYNC_IO_H_ Chris@63: Chris@63: #if defined(__GNUC__) && !KJ_HEADER_WARNINGS Chris@63: #pragma GCC system_header Chris@63: #endif Chris@63: Chris@63: #include "async.h" Chris@63: #include "function.h" Chris@63: #include "thread.h" Chris@63: #include "time.h" Chris@63: Chris@63: struct sockaddr; Chris@63: Chris@63: namespace kj { Chris@63: Chris@63: #if _WIN32 Chris@63: class Win32EventPort; Chris@63: #else Chris@63: class UnixEventPort; Chris@63: #endif Chris@63: Chris@63: class NetworkAddress; Chris@63: class AsyncOutputStream; Chris@63: Chris@63: // ======================================================================================= Chris@63: // Streaming I/O Chris@63: Chris@63: class AsyncInputStream { Chris@63: // Asynchronous equivalent of InputStream (from io.h). Chris@63: Chris@63: public: Chris@63: virtual Promise read(void* buffer, size_t minBytes, size_t maxBytes); Chris@63: virtual Promise tryRead(void* buffer, size_t minBytes, size_t maxBytes) = 0; Chris@63: Chris@63: Promise read(void* buffer, size_t bytes); Chris@63: Chris@63: virtual Maybe tryGetLength(); Chris@63: // Get the remaining number of bytes that will be produced by this stream, if known. Chris@63: // Chris@63: // This is used e.g. to fill in the Content-Length header of an HTTP message. If unknown, the Chris@63: // HTTP implementation may need to fall back to Transfer-Encoding: chunked. Chris@63: // Chris@63: // The default implementation always returns null. Chris@63: Chris@63: virtual Promise pumpTo( Chris@63: AsyncOutputStream& output, uint64_t amount = kj::maxValue); Chris@63: // Read `amount` bytes from this stream (or to EOF) and write them to `output`, returning the Chris@63: // total bytes actually pumped (which is only less than `amount` if EOF was reached). Chris@63: // Chris@63: // Override this if your stream type knows how to pump itself to certain kinds of output Chris@63: // streams more efficiently than via the naive approach. You can use Chris@63: // kj::dynamicDowncastIfAvailable() to test for stream types you recognize, and if none match, Chris@63: // delegate to the default implementation. Chris@63: // Chris@63: // The default implementation first tries calling output.tryPumpFrom(), but if that fails, it Chris@63: // performs a naive pump by allocating a buffer and reading to it / writing from it in a loop. Chris@63: Chris@63: Promise> readAllBytes(); Chris@63: Promise readAllText(); Chris@63: // Read until EOF and return as one big byte array or string. Chris@63: }; Chris@63: Chris@63: class AsyncOutputStream { Chris@63: // Asynchronous equivalent of OutputStream (from io.h). Chris@63: Chris@63: public: Chris@63: virtual Promise write(const void* buffer, size_t size) = 0; Chris@63: virtual Promise write(ArrayPtr> pieces) = 0; Chris@63: Chris@63: virtual Maybe> tryPumpFrom( Chris@63: AsyncInputStream& input, uint64_t amount = kj::maxValue); Chris@63: // Implements double-dispatch for AsyncInputStream::pumpTo(). Chris@63: // Chris@63: // This method should only be called from within an implementation of pumpTo(). Chris@63: // Chris@63: // This method examines the type of `input` to find optimized ways to pump data from it to this Chris@63: // output stream. If it finds one, it performs the pump. Otherwise, it returns null. Chris@63: // Chris@63: // The default implementation always returns null. Chris@63: }; Chris@63: Chris@63: class AsyncIoStream: public AsyncInputStream, public AsyncOutputStream { Chris@63: // A combination input and output stream. Chris@63: Chris@63: public: Chris@63: virtual void shutdownWrite() = 0; Chris@63: // Cleanly shut down just the write end of the stream, while keeping the read end open. Chris@63: Chris@63: virtual void abortRead() {} Chris@63: // Similar to shutdownWrite, but this will shut down the read end of the stream, and should only Chris@63: // be called when an error has occurred. Chris@63: Chris@63: virtual void getsockopt(int level, int option, void* value, uint* length); Chris@63: virtual void setsockopt(int level, int option, const void* value, uint length); Chris@63: // Corresponds to getsockopt() and setsockopt() syscalls. Will throw an "unimplemented" exception Chris@63: // if the stream is not a socket or the option is not appropriate for the socket type. The Chris@63: // default implementations always throw "unimplemented". Chris@63: Chris@63: virtual void getsockname(struct sockaddr* addr, uint* length); Chris@63: virtual void getpeername(struct sockaddr* addr, uint* length); Chris@63: // Corresponds to getsockname() and getpeername() syscalls. Will throw an "unimplemented" Chris@63: // exception if the stream is not a socket. The default implementations always throw Chris@63: // "unimplemented". Chris@63: // Chris@63: // Note that we don't provide methods that return NetworkAddress because it usually wouldn't Chris@63: // be useful. You can't connect() to or listen() on these addresses, obviously, because they are Chris@63: // ephemeral addresses for a single connection. Chris@63: }; Chris@63: Chris@63: struct OneWayPipe { Chris@63: // A data pipe with an input end and an output end. (Typically backed by pipe() system call.) Chris@63: Chris@63: Own in; Chris@63: Own out; Chris@63: }; Chris@63: Chris@63: struct TwoWayPipe { Chris@63: // A data pipe that supports sending in both directions. Each end's output sends data to the Chris@63: // other end's input. (Typically backed by socketpair() system call.) Chris@63: Chris@63: Own ends[2]; Chris@63: }; Chris@63: Chris@63: class ConnectionReceiver { Chris@63: // Represents a server socket listening on a port. Chris@63: Chris@63: public: Chris@63: virtual Promise> accept() = 0; Chris@63: // Accept the next incoming connection. Chris@63: Chris@63: virtual uint getPort() = 0; Chris@63: // Gets the port number, if applicable (i.e. if listening on IP). This is useful if you didn't Chris@63: // specify a port when constructing the NetworkAddress -- one will have been assigned Chris@63: // automatically. Chris@63: Chris@63: virtual void getsockopt(int level, int option, void* value, uint* length); Chris@63: virtual void setsockopt(int level, int option, const void* value, uint length); Chris@63: // Same as the methods of AsyncIoStream. Chris@63: }; Chris@63: Chris@63: // ======================================================================================= Chris@63: // Datagram I/O Chris@63: Chris@63: class AncillaryMessage { Chris@63: // Represents an ancillary message (aka control message) received using the recvmsg() system Chris@63: // call (or equivalent). Most apps will not use this. Chris@63: Chris@63: public: Chris@63: inline AncillaryMessage(int level, int type, ArrayPtr data); Chris@63: AncillaryMessage() = default; Chris@63: Chris@63: inline int getLevel() const; Chris@63: // Originating protocol / socket level. Chris@63: Chris@63: inline int getType() const; Chris@63: // Protocol-specific message type. Chris@63: Chris@63: template Chris@63: inline Maybe as(); Chris@63: // Interpret the ancillary message as the given struct type. Most ancillary messages are some Chris@63: // sort of struct, so this is a convenient way to access it. Returns nullptr if the message Chris@63: // is smaller than the struct -- this can happen if the message was truncated due to Chris@63: // insufficient ancillary buffer space. Chris@63: Chris@63: template Chris@63: inline ArrayPtr asArray(); Chris@63: // Interpret the ancillary message as an array of items. If the message size does not evenly Chris@63: // divide into elements of type T, the remainder is discarded -- this can happen if the message Chris@63: // was truncated due to insufficient ancillary buffer space. Chris@63: Chris@63: private: Chris@63: int level; Chris@63: int type; Chris@63: ArrayPtr data; Chris@63: // Message data. In most cases you should use `as()` or `asArray()`. Chris@63: }; Chris@63: Chris@63: class DatagramReceiver { Chris@63: // Class encapsulating the recvmsg() system call. You must specify the DatagramReceiver's Chris@63: // capacity in advance; if a received packet is larger than the capacity, it will be truncated. Chris@63: Chris@63: public: Chris@63: virtual Promise receive() = 0; Chris@63: // Receive a new message, overwriting this object's content. Chris@63: // Chris@63: // receive() may reuse the same buffers for content and ancillary data with each call. Chris@63: Chris@63: template Chris@63: struct MaybeTruncated { Chris@63: T value; Chris@63: Chris@63: bool isTruncated; Chris@63: // True if the Receiver's capacity was insufficient to receive the value and therefore the Chris@63: // value is truncated. Chris@63: }; Chris@63: Chris@63: virtual MaybeTruncated> getContent() = 0; Chris@63: // Get the content of the datagram. Chris@63: Chris@63: virtual MaybeTruncated> getAncillary() = 0; Chris@63: // Ancilarry messages received with the datagram. See the recvmsg() system call and the cmsghdr Chris@63: // struct. Most apps don't need this. Chris@63: // Chris@63: // If the returned value is truncated, then the last message in the array may itself be Chris@63: // truncated, meaning its as() method will return nullptr or its asArray() method will Chris@63: // return fewer elements than expected. Truncation can also mean that additional messages were Chris@63: // available but discarded. Chris@63: Chris@63: virtual NetworkAddress& getSource() = 0; Chris@63: // Get the datagram sender's address. Chris@63: Chris@63: struct Capacity { Chris@63: size_t content = 8192; Chris@63: // How much space to allocate for the datagram content. If a datagram is received that is Chris@63: // larger than this, it will be truncated, with no way to recover the tail. Chris@63: Chris@63: size_t ancillary = 0; Chris@63: // How much space to allocate for ancillary messages. As with content, if the ancillary data Chris@63: // is larger than this, it will be truncated. Chris@63: }; Chris@63: }; Chris@63: Chris@63: class DatagramPort { Chris@63: public: Chris@63: virtual Promise send(const void* buffer, size_t size, NetworkAddress& destination) = 0; Chris@63: virtual Promise send(ArrayPtr> pieces, Chris@63: NetworkAddress& destination) = 0; Chris@63: Chris@63: virtual Own makeReceiver( Chris@63: DatagramReceiver::Capacity capacity = DatagramReceiver::Capacity()) = 0; Chris@63: // Create a new `Receiver` that can be used to receive datagrams. `capacity` specifies how much Chris@63: // space to allocate for the received message. The `DatagramPort` must outlive the `Receiver`. Chris@63: Chris@63: virtual uint getPort() = 0; Chris@63: // Gets the port number, if applicable (i.e. if listening on IP). This is useful if you didn't Chris@63: // specify a port when constructing the NetworkAddress -- one will have been assigned Chris@63: // automatically. Chris@63: Chris@63: virtual void getsockopt(int level, int option, void* value, uint* length); Chris@63: virtual void setsockopt(int level, int option, const void* value, uint length); Chris@63: // Same as the methods of AsyncIoStream. Chris@63: }; Chris@63: Chris@63: // ======================================================================================= Chris@63: // Networks Chris@63: Chris@63: class NetworkAddress { Chris@63: // Represents a remote address to which the application can connect. Chris@63: Chris@63: public: Chris@63: virtual Promise> connect() = 0; Chris@63: // Make a new connection to this address. Chris@63: // Chris@63: // The address must not be a wildcard ("*"). If it is an IP address, it must have a port number. Chris@63: Chris@63: virtual Own listen() = 0; Chris@63: // Listen for incoming connections on this address. Chris@63: // Chris@63: // The address must be local. Chris@63: Chris@63: virtual Own bindDatagramPort(); Chris@63: // Open this address as a datagram (e.g. UDP) port. Chris@63: // Chris@63: // The address must be local. Chris@63: Chris@63: virtual Own clone() = 0; Chris@63: // Returns an equivalent copy of this NetworkAddress. Chris@63: Chris@63: virtual String toString() = 0; Chris@63: // Produce a human-readable string which hopefully can be passed to Network::parseAddress() Chris@63: // to reproduce this address, although whether or not that works of course depends on the Network Chris@63: // implementation. This should be called only to display the address to human users, who will Chris@63: // hopefully know what they are able to do with it. Chris@63: }; Chris@63: Chris@63: class Network { Chris@63: // Factory for NetworkAddress instances, representing the network services offered by the Chris@63: // operating system. Chris@63: // Chris@63: // This interface typically represents broad authority, and well-designed code should limit its Chris@63: // use to high-level startup code and user interaction. Low-level APIs should accept Chris@63: // NetworkAddress instances directly and work from there, if at all possible. Chris@63: Chris@63: public: Chris@63: virtual Promise> parseAddress(StringPtr addr, uint portHint = 0) = 0; Chris@63: // Construct a network address from a user-provided string. The format of the address Chris@63: // strings is not specified at the API level, and application code should make no assumptions Chris@63: // about them. These strings should always be provided by humans, and said humans will know Chris@63: // what format to use in their particular context. Chris@63: // Chris@63: // `portHint`, if provided, specifies the "standard" IP port number for the application-level Chris@63: // service in play. If the address turns out to be an IP address (v4 or v6), and it lacks a Chris@63: // port number, this port will be used. If `addr` lacks a port number *and* `portHint` is Chris@63: // omitted, then the returned address will only support listen() and bindDatagramPort() Chris@63: // (not connect()), and an unused port will be chosen each time one of those methods is called. Chris@63: Chris@63: virtual Own getSockaddr(const void* sockaddr, uint len) = 0; Chris@63: // Construct a network address from a legacy struct sockaddr. Chris@63: }; Chris@63: Chris@63: // ======================================================================================= Chris@63: // I/O Provider Chris@63: Chris@63: class AsyncIoProvider { Chris@63: // Class which constructs asynchronous wrappers around the operating system's I/O facilities. Chris@63: // Chris@63: // Generally, the implementation of this interface must integrate closely with a particular Chris@63: // `EventLoop` implementation. Typically, the EventLoop implementation itself will provide Chris@63: // an AsyncIoProvider. Chris@63: Chris@63: public: Chris@63: virtual OneWayPipe newOneWayPipe() = 0; Chris@63: // Creates an input/output stream pair representing the ends of a one-way pipe (e.g. created with Chris@63: // the pipe(2) system call). Chris@63: Chris@63: virtual TwoWayPipe newTwoWayPipe() = 0; Chris@63: // Creates two AsyncIoStreams representing the two ends of a two-way pipe (e.g. created with Chris@63: // socketpair(2) system call). Data written to one end can be read from the other. Chris@63: Chris@63: virtual Network& getNetwork() = 0; Chris@63: // Creates a new `Network` instance representing the networks exposed by the operating system. Chris@63: // Chris@63: // DO NOT CALL THIS except at the highest levels of your code, ideally in the main() function. If Chris@63: // you call this from low-level code, then you are preventing higher-level code from injecting an Chris@63: // alternative implementation. Instead, if your code needs to use network functionality, it Chris@63: // should ask for a `Network` as a constructor or method parameter, so that higher-level code can Chris@63: // chose what implementation to use. The system network is essentially a singleton. See: Chris@63: // http://www.object-oriented-security.org/lets-argue/singletons Chris@63: // Chris@63: // Code that uses the system network should not make any assumptions about what kinds of Chris@63: // addresses it will parse, as this could differ across platforms. String addresses should come Chris@63: // strictly from the user, who will know how to write them correctly for their system. Chris@63: // Chris@63: // With that said, KJ currently supports the following string address formats: Chris@63: // - IPv4: "1.2.3.4", "1.2.3.4:80" Chris@63: // - IPv6: "1234:5678::abcd", "[1234:5678::abcd]:80" Chris@63: // - Local IP wildcard (covers both v4 and v6): "*", "*:80" Chris@63: // - Symbolic names: "example.com", "example.com:80", "example.com:http", "1.2.3.4:http" Chris@63: // - Unix domain: "unix:/path/to/socket" Chris@63: Chris@63: struct PipeThread { Chris@63: // A combination of a thread and a two-way pipe that communicates with that thread. Chris@63: // Chris@63: // The fields are intentionally ordered so that the pipe will be destroyed (and therefore Chris@63: // disconnected) before the thread is destroyed (and therefore joined). Thus if the thread Chris@63: // arranges to exit when it detects disconnect, destruction should be clean. Chris@63: Chris@63: Own thread; Chris@63: Own pipe; Chris@63: }; Chris@63: Chris@63: virtual PipeThread newPipeThread( Chris@63: Function startFunc) = 0; Chris@63: // Create a new thread and set up a two-way pipe (socketpair) which can be used to communicate Chris@63: // with it. One end of the pipe is passed to the thread's start function and the other end of Chris@63: // the pipe is returned. The new thread also gets its own `AsyncIoProvider` instance and will Chris@63: // already have an active `EventLoop` when `startFunc` is called. Chris@63: // Chris@63: // TODO(someday): I'm not entirely comfortable with this interface. It seems to be doing too Chris@63: // much at once but I'm not sure how to cleanly break it down. Chris@63: Chris@63: virtual Timer& getTimer() = 0; Chris@63: // Returns a `Timer` based on real time. Time does not pass while event handlers are running -- Chris@63: // it only updates when the event loop polls for system events. This means that calling `now()` Chris@63: // on this timer does not require a system call. Chris@63: // Chris@63: // This timer is not affected by changes to the system date. It is unspecified whether the timer Chris@63: // continues to count while the system is suspended. Chris@63: }; Chris@63: Chris@63: class LowLevelAsyncIoProvider { Chris@63: // Similar to `AsyncIoProvider`, but represents a lower-level interface that may differ on Chris@63: // different operating systems. You should prefer to use `AsyncIoProvider` over this interface Chris@63: // whenever possible, as `AsyncIoProvider` is portable and friendlier to dependency-injection. Chris@63: // Chris@63: // On Unix, this interface can be used to import native file descriptors into the async framework. Chris@63: // Different implementations of this interface might work on top of different event handling Chris@63: // primitives, such as poll vs. epoll vs. kqueue vs. some higher-level event library. Chris@63: // Chris@63: // On Windows, this interface can be used to import native HANDLEs into the async framework. Chris@63: // Different implementations of this interface might work on top of different event handling Chris@63: // primitives, such as I/O completion ports vs. completion routines. Chris@63: // Chris@63: // TODO(port): Actually implement Windows support. Chris@63: Chris@63: public: Chris@63: // --------------------------------------------------------------------------- Chris@63: // Unix-specific stuff Chris@63: Chris@63: enum Flags { Chris@63: // Flags controlling how to wrap a file descriptor. Chris@63: Chris@63: TAKE_OWNERSHIP = 1 << 0, Chris@63: // The returned object should own the file descriptor, automatically closing it when destroyed. Chris@63: // The close-on-exec flag will be set on the descriptor if it is not already. Chris@63: // Chris@63: // If this flag is not used, then the file descriptor is not automatically closed and the Chris@63: // close-on-exec flag is not modified. Chris@63: Chris@63: #if !_WIN32 Chris@63: ALREADY_CLOEXEC = 1 << 1, Chris@63: // Indicates that the close-on-exec flag is known already to be set, so need not be set again. Chris@63: // Only relevant when combined with TAKE_OWNERSHIP. Chris@63: // Chris@63: // On Linux, all system calls which yield new file descriptors have flags or variants which Chris@63: // set the close-on-exec flag immediately. Unfortunately, other OS's do not. Chris@63: Chris@63: ALREADY_NONBLOCK = 1 << 2 Chris@63: // Indicates that the file descriptor is known already to be in non-blocking mode, so the flag Chris@63: // need not be set again. Otherwise, all wrap*Fd() methods will enable non-blocking mode Chris@63: // automatically. Chris@63: // Chris@63: // On Linux, all system calls which yield new file descriptors have flags or variants which Chris@63: // enable non-blocking mode immediately. Unfortunately, other OS's do not. Chris@63: #endif Chris@63: }; Chris@63: Chris@63: #if _WIN32 Chris@63: typedef uintptr_t Fd; Chris@63: // On Windows, the `fd` parameter to each of these methods must be a SOCKET, and must have the Chris@63: // flag WSA_FLAG_OVERLAPPED (which socket() uses by default, but WSASocket() wants you to specify Chris@63: // explicitly). Chris@63: #else Chris@63: typedef int Fd; Chris@63: // On Unix, any arbitrary file descriptor is supported. Chris@63: #endif Chris@63: Chris@63: virtual Own wrapInputFd(Fd fd, uint flags = 0) = 0; Chris@63: // Create an AsyncInputStream wrapping a file descriptor. Chris@63: // Chris@63: // `flags` is a bitwise-OR of the values of the `Flags` enum. Chris@63: Chris@63: virtual Own wrapOutputFd(Fd fd, uint flags = 0) = 0; Chris@63: // Create an AsyncOutputStream wrapping a file descriptor. Chris@63: // Chris@63: // `flags` is a bitwise-OR of the values of the `Flags` enum. Chris@63: Chris@63: virtual Own wrapSocketFd(Fd fd, uint flags = 0) = 0; Chris@63: // Create an AsyncIoStream wrapping a socket file descriptor. Chris@63: // Chris@63: // `flags` is a bitwise-OR of the values of the `Flags` enum. Chris@63: Chris@63: virtual Promise> wrapConnectingSocketFd( Chris@63: Fd fd, const struct sockaddr* addr, uint addrlen, uint flags = 0) = 0; Chris@63: // Create an AsyncIoStream wrapping a socket and initiate a connection to the given address. Chris@63: // The returned promise does not resolve until connection has completed. Chris@63: // Chris@63: // `flags` is a bitwise-OR of the values of the `Flags` enum. Chris@63: Chris@63: virtual Own wrapListenSocketFd(Fd fd, uint flags = 0) = 0; Chris@63: // Create an AsyncIoStream wrapping a listen socket file descriptor. This socket should already Chris@63: // have had `bind()` and `listen()` called on it, so it's ready for `accept()`. Chris@63: // Chris@63: // `flags` is a bitwise-OR of the values of the `Flags` enum. Chris@63: Chris@63: virtual Own wrapDatagramSocketFd(Fd fd, uint flags = 0); Chris@63: Chris@63: virtual Timer& getTimer() = 0; Chris@63: // Returns a `Timer` based on real time. Time does not pass while event handlers are running -- Chris@63: // it only updates when the event loop polls for system events. This means that calling `now()` Chris@63: // on this timer does not require a system call. Chris@63: // Chris@63: // This timer is not affected by changes to the system date. It is unspecified whether the timer Chris@63: // continues to count while the system is suspended. Chris@63: }; Chris@63: Chris@63: Own newAsyncIoProvider(LowLevelAsyncIoProvider& lowLevel); Chris@63: // Make a new AsyncIoProvider wrapping a `LowLevelAsyncIoProvider`. Chris@63: Chris@63: struct AsyncIoContext { Chris@63: Own lowLevelProvider; Chris@63: Own provider; Chris@63: WaitScope& waitScope; Chris@63: Chris@63: #if _WIN32 Chris@63: Win32EventPort& win32EventPort; Chris@63: #else Chris@63: UnixEventPort& unixEventPort; Chris@63: // TEMPORARY: Direct access to underlying UnixEventPort, mainly for waiting on signals. This Chris@63: // field will go away at some point when we have a chance to improve these interfaces. Chris@63: #endif Chris@63: }; Chris@63: Chris@63: AsyncIoContext setupAsyncIo(); Chris@63: // Convenience method which sets up the current thread with everything it needs to do async I/O. Chris@63: // The returned objects contain an `EventLoop` which is wrapping an appropriate `EventPort` for Chris@63: // doing I/O on the host system, so everything is ready for the thread to start making async calls Chris@63: // and waiting on promises. Chris@63: // Chris@63: // You would typically call this in your main() loop or in the start function of a thread. Chris@63: // Example: Chris@63: // Chris@63: // int main() { Chris@63: // auto ioContext = kj::setupAsyncIo(); Chris@63: // Chris@63: // // Now we can call an async function. Chris@63: // Promise textPromise = getHttp(*ioContext.provider, "http://example.com"); Chris@63: // Chris@63: // // And we can wait for the promise to complete. Note that you can only use `wait()` Chris@63: // // from the top level, not from inside a promise callback. Chris@63: // String text = textPromise.wait(ioContext.waitScope); Chris@63: // print(text); Chris@63: // return 0; Chris@63: // } Chris@63: // Chris@63: // WARNING: An AsyncIoContext can only be used in the thread and process that created it. In Chris@63: // particular, note that after a fork(), an AsyncIoContext created in the parent process will Chris@63: // not work correctly in the child, even if the parent ceases to use its copy. In particular Chris@63: // note that this means that server processes which daemonize themselves at startup must wait Chris@63: // until after daemonization to create an AsyncIoContext. Chris@63: Chris@63: // ======================================================================================= Chris@63: // inline implementation details Chris@63: Chris@63: inline AncillaryMessage::AncillaryMessage( Chris@63: int level, int type, ArrayPtr data) Chris@63: : level(level), type(type), data(data) {} Chris@63: Chris@63: inline int AncillaryMessage::getLevel() const { return level; } Chris@63: inline int AncillaryMessage::getType() const { return type; } Chris@63: Chris@63: template Chris@63: inline Maybe AncillaryMessage::as() { Chris@63: if (data.size() >= sizeof(T)) { Chris@63: return *reinterpret_cast(data.begin()); Chris@63: } else { Chris@63: return nullptr; Chris@63: } Chris@63: } Chris@63: Chris@63: template Chris@63: inline ArrayPtr AncillaryMessage::asArray() { Chris@63: return arrayPtr(reinterpret_cast(data.begin()), data.size() / sizeof(T)); Chris@63: } Chris@63: Chris@63: } // namespace kj Chris@63: Chris@63: #endif // KJ_ASYNC_IO_H_