annotate osx/include/kj/async-io.h @ 169:223a55898ab9 tip default

Add null config files
author Chris Cannam <cannam@all-day-breakfast.com>
date Mon, 02 Mar 2020 14:03:47 +0000
parents 45360b968bf4
children
rev   line source
cannam@147 1 // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
cannam@147 2 // Licensed under the MIT License:
cannam@147 3 //
cannam@147 4 // Permission is hereby granted, free of charge, to any person obtaining a copy
cannam@147 5 // of this software and associated documentation files (the "Software"), to deal
cannam@147 6 // in the Software without restriction, including without limitation the rights
cannam@147 7 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
cannam@147 8 // copies of the Software, and to permit persons to whom the Software is
cannam@147 9 // furnished to do so, subject to the following conditions:
cannam@147 10 //
cannam@147 11 // The above copyright notice and this permission notice shall be included in
cannam@147 12 // all copies or substantial portions of the Software.
cannam@147 13 //
cannam@147 14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
cannam@147 15 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
cannam@147 16 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
cannam@147 17 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
cannam@147 18 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
cannam@147 19 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
cannam@147 20 // THE SOFTWARE.
cannam@147 21
cannam@147 22 #ifndef KJ_ASYNC_IO_H_
cannam@147 23 #define KJ_ASYNC_IO_H_
cannam@147 24
cannam@147 25 #if defined(__GNUC__) && !KJ_HEADER_WARNINGS
cannam@147 26 #pragma GCC system_header
cannam@147 27 #endif
cannam@147 28
cannam@147 29 #include "async.h"
cannam@147 30 #include "function.h"
cannam@147 31 #include "thread.h"
cannam@147 32 #include "time.h"
cannam@147 33
cannam@147 34 struct sockaddr;
cannam@147 35
cannam@147 36 namespace kj {
cannam@147 37
cannam@147 38 #if _WIN32
cannam@147 39 class Win32EventPort;
cannam@147 40 #else
cannam@147 41 class UnixEventPort;
cannam@147 42 #endif
cannam@147 43
cannam@147 44 class NetworkAddress;
cannam@147 45 class AsyncOutputStream;
cannam@147 46
cannam@147 47 // =======================================================================================
cannam@147 48 // Streaming I/O
cannam@147 49
cannam@147 50 class AsyncInputStream {
cannam@147 51 // Asynchronous equivalent of InputStream (from io.h).
cannam@147 52
cannam@147 53 public:
cannam@147 54 virtual Promise<size_t> read(void* buffer, size_t minBytes, size_t maxBytes);
cannam@147 55 virtual Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) = 0;
cannam@147 56
cannam@147 57 Promise<void> read(void* buffer, size_t bytes);
cannam@147 58
cannam@147 59 virtual Maybe<uint64_t> tryGetLength();
cannam@147 60 // Get the remaining number of bytes that will be produced by this stream, if known.
cannam@147 61 //
cannam@147 62 // This is used e.g. to fill in the Content-Length header of an HTTP message. If unknown, the
cannam@147 63 // HTTP implementation may need to fall back to Transfer-Encoding: chunked.
cannam@147 64 //
cannam@147 65 // The default implementation always returns null.
cannam@147 66
cannam@147 67 virtual Promise<uint64_t> pumpTo(
cannam@147 68 AsyncOutputStream& output, uint64_t amount = kj::maxValue);
cannam@147 69 // Read `amount` bytes from this stream (or to EOF) and write them to `output`, returning the
cannam@147 70 // total bytes actually pumped (which is only less than `amount` if EOF was reached).
cannam@147 71 //
cannam@147 72 // Override this if your stream type knows how to pump itself to certain kinds of output
cannam@147 73 // streams more efficiently than via the naive approach. You can use
cannam@147 74 // kj::dynamicDowncastIfAvailable() to test for stream types you recognize, and if none match,
cannam@147 75 // delegate to the default implementation.
cannam@147 76 //
cannam@147 77 // The default implementation first tries calling output.tryPumpFrom(), but if that fails, it
cannam@147 78 // performs a naive pump by allocating a buffer and reading to it / writing from it in a loop.
cannam@147 79
cannam@147 80 Promise<Array<byte>> readAllBytes();
cannam@147 81 Promise<String> readAllText();
cannam@147 82 // Read until EOF and return as one big byte array or string.
cannam@147 83 };
cannam@147 84
cannam@147 85 class AsyncOutputStream {
cannam@147 86 // Asynchronous equivalent of OutputStream (from io.h).
cannam@147 87
cannam@147 88 public:
cannam@147 89 virtual Promise<void> write(const void* buffer, size_t size) = 0;
cannam@147 90 virtual Promise<void> write(ArrayPtr<const ArrayPtr<const byte>> pieces) = 0;
cannam@147 91
cannam@147 92 virtual Maybe<Promise<uint64_t>> tryPumpFrom(
cannam@147 93 AsyncInputStream& input, uint64_t amount = kj::maxValue);
cannam@147 94 // Implements double-dispatch for AsyncInputStream::pumpTo().
cannam@147 95 //
cannam@147 96 // This method should only be called from within an implementation of pumpTo().
cannam@147 97 //
cannam@147 98 // This method examines the type of `input` to find optimized ways to pump data from it to this
cannam@147 99 // output stream. If it finds one, it performs the pump. Otherwise, it returns null.
cannam@147 100 //
cannam@147 101 // The default implementation always returns null.
cannam@147 102 };
cannam@147 103
cannam@147 104 class AsyncIoStream: public AsyncInputStream, public AsyncOutputStream {
cannam@147 105 // A combination input and output stream.
cannam@147 106
cannam@147 107 public:
cannam@147 108 virtual void shutdownWrite() = 0;
cannam@147 109 // Cleanly shut down just the write end of the stream, while keeping the read end open.
cannam@147 110
cannam@147 111 virtual void abortRead() {}
cannam@147 112 // Similar to shutdownWrite, but this will shut down the read end of the stream, and should only
cannam@147 113 // be called when an error has occurred.
cannam@147 114
cannam@147 115 virtual void getsockopt(int level, int option, void* value, uint* length);
cannam@147 116 virtual void setsockopt(int level, int option, const void* value, uint length);
cannam@147 117 // Corresponds to getsockopt() and setsockopt() syscalls. Will throw an "unimplemented" exception
cannam@147 118 // if the stream is not a socket or the option is not appropriate for the socket type. The
cannam@147 119 // default implementations always throw "unimplemented".
cannam@147 120
cannam@147 121 virtual void getsockname(struct sockaddr* addr, uint* length);
cannam@147 122 virtual void getpeername(struct sockaddr* addr, uint* length);
cannam@147 123 // Corresponds to getsockname() and getpeername() syscalls. Will throw an "unimplemented"
cannam@147 124 // exception if the stream is not a socket. The default implementations always throw
cannam@147 125 // "unimplemented".
cannam@147 126 //
cannam@147 127 // Note that we don't provide methods that return NetworkAddress because it usually wouldn't
cannam@147 128 // be useful. You can't connect() to or listen() on these addresses, obviously, because they are
cannam@147 129 // ephemeral addresses for a single connection.
cannam@147 130 };
cannam@147 131
cannam@147 132 struct OneWayPipe {
cannam@147 133 // A data pipe with an input end and an output end. (Typically backed by pipe() system call.)
cannam@147 134
cannam@147 135 Own<AsyncInputStream> in;
cannam@147 136 Own<AsyncOutputStream> out;
cannam@147 137 };
cannam@147 138
cannam@147 139 struct TwoWayPipe {
cannam@147 140 // A data pipe that supports sending in both directions. Each end's output sends data to the
cannam@147 141 // other end's input. (Typically backed by socketpair() system call.)
cannam@147 142
cannam@147 143 Own<AsyncIoStream> ends[2];
cannam@147 144 };
cannam@147 145
cannam@147 146 class ConnectionReceiver {
cannam@147 147 // Represents a server socket listening on a port.
cannam@147 148
cannam@147 149 public:
cannam@147 150 virtual Promise<Own<AsyncIoStream>> accept() = 0;
cannam@147 151 // Accept the next incoming connection.
cannam@147 152
cannam@147 153 virtual uint getPort() = 0;
cannam@147 154 // Gets the port number, if applicable (i.e. if listening on IP). This is useful if you didn't
cannam@147 155 // specify a port when constructing the NetworkAddress -- one will have been assigned
cannam@147 156 // automatically.
cannam@147 157
cannam@147 158 virtual void getsockopt(int level, int option, void* value, uint* length);
cannam@147 159 virtual void setsockopt(int level, int option, const void* value, uint length);
cannam@147 160 // Same as the methods of AsyncIoStream.
cannam@147 161 };
cannam@147 162
cannam@147 163 // =======================================================================================
cannam@147 164 // Datagram I/O
cannam@147 165
cannam@147 166 class AncillaryMessage {
cannam@147 167 // Represents an ancillary message (aka control message) received using the recvmsg() system
cannam@147 168 // call (or equivalent). Most apps will not use this.
cannam@147 169
cannam@147 170 public:
cannam@147 171 inline AncillaryMessage(int level, int type, ArrayPtr<const byte> data);
cannam@147 172 AncillaryMessage() = default;
cannam@147 173
cannam@147 174 inline int getLevel() const;
cannam@147 175 // Originating protocol / socket level.
cannam@147 176
cannam@147 177 inline int getType() const;
cannam@147 178 // Protocol-specific message type.
cannam@147 179
cannam@147 180 template <typename T>
cannam@147 181 inline Maybe<const T&> as();
cannam@147 182 // Interpret the ancillary message as the given struct type. Most ancillary messages are some
cannam@147 183 // sort of struct, so this is a convenient way to access it. Returns nullptr if the message
cannam@147 184 // is smaller than the struct -- this can happen if the message was truncated due to
cannam@147 185 // insufficient ancillary buffer space.
cannam@147 186
cannam@147 187 template <typename T>
cannam@147 188 inline ArrayPtr<const T> asArray();
cannam@147 189 // Interpret the ancillary message as an array of items. If the message size does not evenly
cannam@147 190 // divide into elements of type T, the remainder is discarded -- this can happen if the message
cannam@147 191 // was truncated due to insufficient ancillary buffer space.
cannam@147 192
cannam@147 193 private:
cannam@147 194 int level;
cannam@147 195 int type;
cannam@147 196 ArrayPtr<const byte> data;
cannam@147 197 // Message data. In most cases you should use `as()` or `asArray()`.
cannam@147 198 };
cannam@147 199
cannam@147 200 class DatagramReceiver {
cannam@147 201 // Class encapsulating the recvmsg() system call. You must specify the DatagramReceiver's
cannam@147 202 // capacity in advance; if a received packet is larger than the capacity, it will be truncated.
cannam@147 203
cannam@147 204 public:
cannam@147 205 virtual Promise<void> receive() = 0;
cannam@147 206 // Receive a new message, overwriting this object's content.
cannam@147 207 //
cannam@147 208 // receive() may reuse the same buffers for content and ancillary data with each call.
cannam@147 209
cannam@147 210 template <typename T>
cannam@147 211 struct MaybeTruncated {
cannam@147 212 T value;
cannam@147 213
cannam@147 214 bool isTruncated;
cannam@147 215 // True if the Receiver's capacity was insufficient to receive the value and therefore the
cannam@147 216 // value is truncated.
cannam@147 217 };
cannam@147 218
cannam@147 219 virtual MaybeTruncated<ArrayPtr<const byte>> getContent() = 0;
cannam@147 220 // Get the content of the datagram.
cannam@147 221
cannam@147 222 virtual MaybeTruncated<ArrayPtr<const AncillaryMessage>> getAncillary() = 0;
cannam@147 223 // Ancilarry messages received with the datagram. See the recvmsg() system call and the cmsghdr
cannam@147 224 // struct. Most apps don't need this.
cannam@147 225 //
cannam@147 226 // If the returned value is truncated, then the last message in the array may itself be
cannam@147 227 // truncated, meaning its as<T>() method will return nullptr or its asArray<T>() method will
cannam@147 228 // return fewer elements than expected. Truncation can also mean that additional messages were
cannam@147 229 // available but discarded.
cannam@147 230
cannam@147 231 virtual NetworkAddress& getSource() = 0;
cannam@147 232 // Get the datagram sender's address.
cannam@147 233
cannam@147 234 struct Capacity {
cannam@147 235 size_t content = 8192;
cannam@147 236 // How much space to allocate for the datagram content. If a datagram is received that is
cannam@147 237 // larger than this, it will be truncated, with no way to recover the tail.
cannam@147 238
cannam@147 239 size_t ancillary = 0;
cannam@147 240 // How much space to allocate for ancillary messages. As with content, if the ancillary data
cannam@147 241 // is larger than this, it will be truncated.
cannam@147 242 };
cannam@147 243 };
cannam@147 244
cannam@147 245 class DatagramPort {
cannam@147 246 public:
cannam@147 247 virtual Promise<size_t> send(const void* buffer, size_t size, NetworkAddress& destination) = 0;
cannam@147 248 virtual Promise<size_t> send(ArrayPtr<const ArrayPtr<const byte>> pieces,
cannam@147 249 NetworkAddress& destination) = 0;
cannam@147 250
cannam@147 251 virtual Own<DatagramReceiver> makeReceiver(
cannam@147 252 DatagramReceiver::Capacity capacity = DatagramReceiver::Capacity()) = 0;
cannam@147 253 // Create a new `Receiver` that can be used to receive datagrams. `capacity` specifies how much
cannam@147 254 // space to allocate for the received message. The `DatagramPort` must outlive the `Receiver`.
cannam@147 255
cannam@147 256 virtual uint getPort() = 0;
cannam@147 257 // Gets the port number, if applicable (i.e. if listening on IP). This is useful if you didn't
cannam@147 258 // specify a port when constructing the NetworkAddress -- one will have been assigned
cannam@147 259 // automatically.
cannam@147 260
cannam@147 261 virtual void getsockopt(int level, int option, void* value, uint* length);
cannam@147 262 virtual void setsockopt(int level, int option, const void* value, uint length);
cannam@147 263 // Same as the methods of AsyncIoStream.
cannam@147 264 };
cannam@147 265
cannam@147 266 // =======================================================================================
cannam@147 267 // Networks
cannam@147 268
cannam@147 269 class NetworkAddress {
cannam@147 270 // Represents a remote address to which the application can connect.
cannam@147 271
cannam@147 272 public:
cannam@147 273 virtual Promise<Own<AsyncIoStream>> connect() = 0;
cannam@147 274 // Make a new connection to this address.
cannam@147 275 //
cannam@147 276 // The address must not be a wildcard ("*"). If it is an IP address, it must have a port number.
cannam@147 277
cannam@147 278 virtual Own<ConnectionReceiver> listen() = 0;
cannam@147 279 // Listen for incoming connections on this address.
cannam@147 280 //
cannam@147 281 // The address must be local.
cannam@147 282
cannam@147 283 virtual Own<DatagramPort> bindDatagramPort();
cannam@147 284 // Open this address as a datagram (e.g. UDP) port.
cannam@147 285 //
cannam@147 286 // The address must be local.
cannam@147 287
cannam@147 288 virtual Own<NetworkAddress> clone() = 0;
cannam@147 289 // Returns an equivalent copy of this NetworkAddress.
cannam@147 290
cannam@147 291 virtual String toString() = 0;
cannam@147 292 // Produce a human-readable string which hopefully can be passed to Network::parseAddress()
cannam@147 293 // to reproduce this address, although whether or not that works of course depends on the Network
cannam@147 294 // implementation. This should be called only to display the address to human users, who will
cannam@147 295 // hopefully know what they are able to do with it.
cannam@147 296 };
cannam@147 297
cannam@147 298 class Network {
cannam@147 299 // Factory for NetworkAddress instances, representing the network services offered by the
cannam@147 300 // operating system.
cannam@147 301 //
cannam@147 302 // This interface typically represents broad authority, and well-designed code should limit its
cannam@147 303 // use to high-level startup code and user interaction. Low-level APIs should accept
cannam@147 304 // NetworkAddress instances directly and work from there, if at all possible.
cannam@147 305
cannam@147 306 public:
cannam@147 307 virtual Promise<Own<NetworkAddress>> parseAddress(StringPtr addr, uint portHint = 0) = 0;
cannam@147 308 // Construct a network address from a user-provided string. The format of the address
cannam@147 309 // strings is not specified at the API level, and application code should make no assumptions
cannam@147 310 // about them. These strings should always be provided by humans, and said humans will know
cannam@147 311 // what format to use in their particular context.
cannam@147 312 //
cannam@147 313 // `portHint`, if provided, specifies the "standard" IP port number for the application-level
cannam@147 314 // service in play. If the address turns out to be an IP address (v4 or v6), and it lacks a
cannam@147 315 // port number, this port will be used. If `addr` lacks a port number *and* `portHint` is
cannam@147 316 // omitted, then the returned address will only support listen() and bindDatagramPort()
cannam@147 317 // (not connect()), and an unused port will be chosen each time one of those methods is called.
cannam@147 318
cannam@147 319 virtual Own<NetworkAddress> getSockaddr(const void* sockaddr, uint len) = 0;
cannam@147 320 // Construct a network address from a legacy struct sockaddr.
cannam@147 321 };
cannam@147 322
cannam@147 323 // =======================================================================================
cannam@147 324 // I/O Provider
cannam@147 325
cannam@147 326 class AsyncIoProvider {
cannam@147 327 // Class which constructs asynchronous wrappers around the operating system's I/O facilities.
cannam@147 328 //
cannam@147 329 // Generally, the implementation of this interface must integrate closely with a particular
cannam@147 330 // `EventLoop` implementation. Typically, the EventLoop implementation itself will provide
cannam@147 331 // an AsyncIoProvider.
cannam@147 332
cannam@147 333 public:
cannam@147 334 virtual OneWayPipe newOneWayPipe() = 0;
cannam@147 335 // Creates an input/output stream pair representing the ends of a one-way pipe (e.g. created with
cannam@147 336 // the pipe(2) system call).
cannam@147 337
cannam@147 338 virtual TwoWayPipe newTwoWayPipe() = 0;
cannam@147 339 // Creates two AsyncIoStreams representing the two ends of a two-way pipe (e.g. created with
cannam@147 340 // socketpair(2) system call). Data written to one end can be read from the other.
cannam@147 341
cannam@147 342 virtual Network& getNetwork() = 0;
cannam@147 343 // Creates a new `Network` instance representing the networks exposed by the operating system.
cannam@147 344 //
cannam@147 345 // DO NOT CALL THIS except at the highest levels of your code, ideally in the main() function. If
cannam@147 346 // you call this from low-level code, then you are preventing higher-level code from injecting an
cannam@147 347 // alternative implementation. Instead, if your code needs to use network functionality, it
cannam@147 348 // should ask for a `Network` as a constructor or method parameter, so that higher-level code can
cannam@147 349 // chose what implementation to use. The system network is essentially a singleton. See:
cannam@147 350 // http://www.object-oriented-security.org/lets-argue/singletons
cannam@147 351 //
cannam@147 352 // Code that uses the system network should not make any assumptions about what kinds of
cannam@147 353 // addresses it will parse, as this could differ across platforms. String addresses should come
cannam@147 354 // strictly from the user, who will know how to write them correctly for their system.
cannam@147 355 //
cannam@147 356 // With that said, KJ currently supports the following string address formats:
cannam@147 357 // - IPv4: "1.2.3.4", "1.2.3.4:80"
cannam@147 358 // - IPv6: "1234:5678::abcd", "[1234:5678::abcd]:80"
cannam@147 359 // - Local IP wildcard (covers both v4 and v6): "*", "*:80"
cannam@147 360 // - Symbolic names: "example.com", "example.com:80", "example.com:http", "1.2.3.4:http"
cannam@147 361 // - Unix domain: "unix:/path/to/socket"
cannam@147 362
cannam@147 363 struct PipeThread {
cannam@147 364 // A combination of a thread and a two-way pipe that communicates with that thread.
cannam@147 365 //
cannam@147 366 // The fields are intentionally ordered so that the pipe will be destroyed (and therefore
cannam@147 367 // disconnected) before the thread is destroyed (and therefore joined). Thus if the thread
cannam@147 368 // arranges to exit when it detects disconnect, destruction should be clean.
cannam@147 369
cannam@147 370 Own<Thread> thread;
cannam@147 371 Own<AsyncIoStream> pipe;
cannam@147 372 };
cannam@147 373
cannam@147 374 virtual PipeThread newPipeThread(
cannam@147 375 Function<void(AsyncIoProvider&, AsyncIoStream&, WaitScope&)> startFunc) = 0;
cannam@147 376 // Create a new thread and set up a two-way pipe (socketpair) which can be used to communicate
cannam@147 377 // with it. One end of the pipe is passed to the thread's start function and the other end of
cannam@147 378 // the pipe is returned. The new thread also gets its own `AsyncIoProvider` instance and will
cannam@147 379 // already have an active `EventLoop` when `startFunc` is called.
cannam@147 380 //
cannam@147 381 // TODO(someday): I'm not entirely comfortable with this interface. It seems to be doing too
cannam@147 382 // much at once but I'm not sure how to cleanly break it down.
cannam@147 383
cannam@147 384 virtual Timer& getTimer() = 0;
cannam@147 385 // Returns a `Timer` based on real time. Time does not pass while event handlers are running --
cannam@147 386 // it only updates when the event loop polls for system events. This means that calling `now()`
cannam@147 387 // on this timer does not require a system call.
cannam@147 388 //
cannam@147 389 // This timer is not affected by changes to the system date. It is unspecified whether the timer
cannam@147 390 // continues to count while the system is suspended.
cannam@147 391 };
cannam@147 392
cannam@147 393 class LowLevelAsyncIoProvider {
cannam@147 394 // Similar to `AsyncIoProvider`, but represents a lower-level interface that may differ on
cannam@147 395 // different operating systems. You should prefer to use `AsyncIoProvider` over this interface
cannam@147 396 // whenever possible, as `AsyncIoProvider` is portable and friendlier to dependency-injection.
cannam@147 397 //
cannam@147 398 // On Unix, this interface can be used to import native file descriptors into the async framework.
cannam@147 399 // Different implementations of this interface might work on top of different event handling
cannam@147 400 // primitives, such as poll vs. epoll vs. kqueue vs. some higher-level event library.
cannam@147 401 //
cannam@147 402 // On Windows, this interface can be used to import native HANDLEs into the async framework.
cannam@147 403 // Different implementations of this interface might work on top of different event handling
cannam@147 404 // primitives, such as I/O completion ports vs. completion routines.
cannam@147 405 //
cannam@147 406 // TODO(port): Actually implement Windows support.
cannam@147 407
cannam@147 408 public:
cannam@147 409 // ---------------------------------------------------------------------------
cannam@147 410 // Unix-specific stuff
cannam@147 411
cannam@147 412 enum Flags {
cannam@147 413 // Flags controlling how to wrap a file descriptor.
cannam@147 414
cannam@147 415 TAKE_OWNERSHIP = 1 << 0,
cannam@147 416 // The returned object should own the file descriptor, automatically closing it when destroyed.
cannam@147 417 // The close-on-exec flag will be set on the descriptor if it is not already.
cannam@147 418 //
cannam@147 419 // If this flag is not used, then the file descriptor is not automatically closed and the
cannam@147 420 // close-on-exec flag is not modified.
cannam@147 421
cannam@147 422 #if !_WIN32
cannam@147 423 ALREADY_CLOEXEC = 1 << 1,
cannam@147 424 // Indicates that the close-on-exec flag is known already to be set, so need not be set again.
cannam@147 425 // Only relevant when combined with TAKE_OWNERSHIP.
cannam@147 426 //
cannam@147 427 // On Linux, all system calls which yield new file descriptors have flags or variants which
cannam@147 428 // set the close-on-exec flag immediately. Unfortunately, other OS's do not.
cannam@147 429
cannam@147 430 ALREADY_NONBLOCK = 1 << 2
cannam@147 431 // Indicates that the file descriptor is known already to be in non-blocking mode, so the flag
cannam@147 432 // need not be set again. Otherwise, all wrap*Fd() methods will enable non-blocking mode
cannam@147 433 // automatically.
cannam@147 434 //
cannam@147 435 // On Linux, all system calls which yield new file descriptors have flags or variants which
cannam@147 436 // enable non-blocking mode immediately. Unfortunately, other OS's do not.
cannam@147 437 #endif
cannam@147 438 };
cannam@147 439
cannam@147 440 #if _WIN32
cannam@147 441 typedef uintptr_t Fd;
cannam@147 442 // On Windows, the `fd` parameter to each of these methods must be a SOCKET, and must have the
cannam@147 443 // flag WSA_FLAG_OVERLAPPED (which socket() uses by default, but WSASocket() wants you to specify
cannam@147 444 // explicitly).
cannam@147 445 #else
cannam@147 446 typedef int Fd;
cannam@147 447 // On Unix, any arbitrary file descriptor is supported.
cannam@147 448 #endif
cannam@147 449
cannam@147 450 virtual Own<AsyncInputStream> wrapInputFd(Fd fd, uint flags = 0) = 0;
cannam@147 451 // Create an AsyncInputStream wrapping a file descriptor.
cannam@147 452 //
cannam@147 453 // `flags` is a bitwise-OR of the values of the `Flags` enum.
cannam@147 454
cannam@147 455 virtual Own<AsyncOutputStream> wrapOutputFd(Fd fd, uint flags = 0) = 0;
cannam@147 456 // Create an AsyncOutputStream wrapping a file descriptor.
cannam@147 457 //
cannam@147 458 // `flags` is a bitwise-OR of the values of the `Flags` enum.
cannam@147 459
cannam@147 460 virtual Own<AsyncIoStream> wrapSocketFd(Fd fd, uint flags = 0) = 0;
cannam@147 461 // Create an AsyncIoStream wrapping a socket file descriptor.
cannam@147 462 //
cannam@147 463 // `flags` is a bitwise-OR of the values of the `Flags` enum.
cannam@147 464
cannam@147 465 virtual Promise<Own<AsyncIoStream>> wrapConnectingSocketFd(
cannam@147 466 Fd fd, const struct sockaddr* addr, uint addrlen, uint flags = 0) = 0;
cannam@147 467 // Create an AsyncIoStream wrapping a socket and initiate a connection to the given address.
cannam@147 468 // The returned promise does not resolve until connection has completed.
cannam@147 469 //
cannam@147 470 // `flags` is a bitwise-OR of the values of the `Flags` enum.
cannam@147 471
cannam@147 472 virtual Own<ConnectionReceiver> wrapListenSocketFd(Fd fd, uint flags = 0) = 0;
cannam@147 473 // Create an AsyncIoStream wrapping a listen socket file descriptor. This socket should already
cannam@147 474 // have had `bind()` and `listen()` called on it, so it's ready for `accept()`.
cannam@147 475 //
cannam@147 476 // `flags` is a bitwise-OR of the values of the `Flags` enum.
cannam@147 477
cannam@147 478 virtual Own<DatagramPort> wrapDatagramSocketFd(Fd fd, uint flags = 0);
cannam@147 479
cannam@147 480 virtual Timer& getTimer() = 0;
cannam@147 481 // Returns a `Timer` based on real time. Time does not pass while event handlers are running --
cannam@147 482 // it only updates when the event loop polls for system events. This means that calling `now()`
cannam@147 483 // on this timer does not require a system call.
cannam@147 484 //
cannam@147 485 // This timer is not affected by changes to the system date. It is unspecified whether the timer
cannam@147 486 // continues to count while the system is suspended.
cannam@147 487 };
cannam@147 488
cannam@147 489 Own<AsyncIoProvider> newAsyncIoProvider(LowLevelAsyncIoProvider& lowLevel);
cannam@147 490 // Make a new AsyncIoProvider wrapping a `LowLevelAsyncIoProvider`.
cannam@147 491
cannam@147 492 struct AsyncIoContext {
cannam@147 493 Own<LowLevelAsyncIoProvider> lowLevelProvider;
cannam@147 494 Own<AsyncIoProvider> provider;
cannam@147 495 WaitScope& waitScope;
cannam@147 496
cannam@147 497 #if _WIN32
cannam@147 498 Win32EventPort& win32EventPort;
cannam@147 499 #else
cannam@147 500 UnixEventPort& unixEventPort;
cannam@147 501 // TEMPORARY: Direct access to underlying UnixEventPort, mainly for waiting on signals. This
cannam@147 502 // field will go away at some point when we have a chance to improve these interfaces.
cannam@147 503 #endif
cannam@147 504 };
cannam@147 505
cannam@147 506 AsyncIoContext setupAsyncIo();
cannam@147 507 // Convenience method which sets up the current thread with everything it needs to do async I/O.
cannam@147 508 // The returned objects contain an `EventLoop` which is wrapping an appropriate `EventPort` for
cannam@147 509 // doing I/O on the host system, so everything is ready for the thread to start making async calls
cannam@147 510 // and waiting on promises.
cannam@147 511 //
cannam@147 512 // You would typically call this in your main() loop or in the start function of a thread.
cannam@147 513 // Example:
cannam@147 514 //
cannam@147 515 // int main() {
cannam@147 516 // auto ioContext = kj::setupAsyncIo();
cannam@147 517 //
cannam@147 518 // // Now we can call an async function.
cannam@147 519 // Promise<String> textPromise = getHttp(*ioContext.provider, "http://example.com");
cannam@147 520 //
cannam@147 521 // // And we can wait for the promise to complete. Note that you can only use `wait()`
cannam@147 522 // // from the top level, not from inside a promise callback.
cannam@147 523 // String text = textPromise.wait(ioContext.waitScope);
cannam@147 524 // print(text);
cannam@147 525 // return 0;
cannam@147 526 // }
cannam@147 527 //
cannam@147 528 // WARNING: An AsyncIoContext can only be used in the thread and process that created it. In
cannam@147 529 // particular, note that after a fork(), an AsyncIoContext created in the parent process will
cannam@147 530 // not work correctly in the child, even if the parent ceases to use its copy. In particular
cannam@147 531 // note that this means that server processes which daemonize themselves at startup must wait
cannam@147 532 // until after daemonization to create an AsyncIoContext.
cannam@147 533
cannam@147 534 // =======================================================================================
cannam@147 535 // inline implementation details
cannam@147 536
cannam@147 537 inline AncillaryMessage::AncillaryMessage(
cannam@147 538 int level, int type, ArrayPtr<const byte> data)
cannam@147 539 : level(level), type(type), data(data) {}
cannam@147 540
cannam@147 541 inline int AncillaryMessage::getLevel() const { return level; }
cannam@147 542 inline int AncillaryMessage::getType() const { return type; }
cannam@147 543
cannam@147 544 template <typename T>
cannam@147 545 inline Maybe<const T&> AncillaryMessage::as() {
cannam@147 546 if (data.size() >= sizeof(T)) {
cannam@147 547 return *reinterpret_cast<const T*>(data.begin());
cannam@147 548 } else {
cannam@147 549 return nullptr;
cannam@147 550 }
cannam@147 551 }
cannam@147 552
cannam@147 553 template <typename T>
cannam@147 554 inline ArrayPtr<const T> AncillaryMessage::asArray() {
cannam@147 555 return arrayPtr(reinterpret_cast<const T*>(data.begin()), data.size() / sizeof(T));
cannam@147 556 }
cannam@147 557
cannam@147 558 } // namespace kj
cannam@147 559
cannam@147 560 #endif // KJ_ASYNC_IO_H_