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