5#include "../Common/CompilerMacrosExport.h"
6#ifndef SC_EXPORT_LIBRARY_ASYNC
7#define SC_EXPORT_LIBRARY_ASYNC 0
9#define SC_ASYNC_EXPORT SC_COMPILER_LIBRARY_EXPORT(SC_EXPORT_LIBRARY_ASYNC)
11#include "../Async/Internal/IntrusiveDoubleLinkedList.h"
12#include "../Common/Assert.h"
13#include "../Common/Function.h"
14#include "../Common/OpaqueObject.h"
15#include "../File/File.h"
16#include "../FileSystem/FileSystem.h"
17#include "../Socket/Socket.h"
18#include "../Threading/Atomic.h"
19#include "../Threading/ThreadPool.h"
23SC_DECLARE_ASSERT_PROVIDER(AsyncAssert, SC_ASYNC_EXPORT);
25#define SC_ASYNC_ASSERT_RELEASE(e) SC_ASSERT_PROVIDER_RELEASE(SC::AsyncAssert, e)
26#define SC_ASYNC_ASSERT_DEBUG(e) SC_ASSERT_PROVIDER_DEBUG(SC::AsyncAssert, e)
27#define SC_ASYNC_TRUST_RESULT(expression) SC_ASYNC_ASSERT_RELEASE(expression)
65struct AsyncTaskSequence;
69struct AsyncWinOverlapped;
70struct AsyncWinOverlappedDefinition
72 static constexpr int Windows =
sizeof(
void*) * 4 +
sizeof(uint64_t);
73 static constexpr size_t Alignment =
alignof(
void*);
75 using Object = AsyncWinOverlapped;
77using WinOverlappedOpaque = OpaqueObject<AsyncWinOverlappedDefinition>;
79struct AsyncWinWaitDefinition
81 using Handle = FileDescriptor::Handle;
82 static constexpr Handle Invalid = FileDescriptor::Invalid;
84 static Result releaseHandle(Handle& waitHandle);
86struct SC_ASYNC_EXPORT WinWaitHandle :
public UniqueHandle<AsyncWinWaitDefinition>
134 void setDebugName(
const char* newDebugName);
170 AsyncRequest(
Type type) : state(State::Free), type(type), flags(0), unused(0), userFlags(0) {}
196 void setUserFlags(uint16_t externalFlags) { userFlags = externalFlags; }
204 [[nodiscard]]
const Function<void(
AsyncResult&)>* getCloseCallback()
const {
return closeCallback; }
209 void queueSubmission(AsyncEventLoop& eventLoop);
211 AsyncSequence* sequence =
nullptr;
213 AsyncTaskSequence* getTask();
216 Function<void(AsyncResult&)>* closeCallback =
nullptr;
218 friend struct AsyncEventLoop;
219 friend struct AsyncResult;
223 [[nodiscard]]
static const char* TypeToString(Type type);
224 enum class State : uint8_t
234#if SC_ASYNC_ENABLE_LOG
235 const char* debugName =
"None";
254 bool clearSequenceOnCancel =
true;
255 bool clearSequenceOnError =
true;
258 bool runningAsync =
false;
259 bool tracked =
false;
261 IntrusiveDoubleLinkedList<AsyncRequest> submissions;
275 : eventLoop(eventLoop), async(request), hasBeenReactivated(hasBeenReactivated), returnCode(res)
283 [[nodiscard]]
const SC::Result&
isValid()
const {
return returnCode; }
291 bool shouldCallCallback =
true;
292 bool* hasBeenReactivated =
nullptr;
294 SC::Result& returnCode;
300template <
typename T,
typename C>
303 T& getAsync() {
return static_cast<T&
>(AsyncResult::async); }
304 const T& getAsync()
const {
return static_cast<const T&
>(AsyncResult::async); }
309 int32_t eventIndex = 0;
322 using AsyncRequest::start;
337 TimeMs expirationTime;
370 uint32_t deliveryCount = 1;
390 int32_t consumePendingWakeUps();
391 int32_t getPendingWakeUps()
const;
414 SC::Result get(
int& status)
416 status = completionData.exitStatus;
420 using AsyncRequest::start;
433 FileDescriptor::Handle handle = FileDescriptor::Invalid;
434#if SC_PLATFORM_WINDOWS
435 detail::WinOverlappedOpaque overlapped;
436 detail::WinWaitHandle waitHandle;
438#elif SC_PLATFORM_LINUX
469 int signalNumber = 0;
470 uint32_t deliveryCount = 1;
477 using AsyncRequest::start;
488 int signalNumber = 0;
490#if SC_PLATFORM_WINDOWS
491 detail::WinOverlappedOpaque overlapped;
493#elif SC_PLATFORM_LINUX
495 FileDescriptor::Handle signalFdHandle = FileDescriptor::Invalid;
504struct SC_ASYNC_EXPORT AsyncSocketAcceptData
506#if SC_PLATFORM_WINDOWS
507 void (*pAcceptEx)() =
nullptr;
508 detail::WinOverlappedOpaque overlapped;
510 uint8_t acceptBuffer[288] = {0};
511#elif SC_PLATFORM_LINUX
512 AlignedStorage<28> sockAddrHandle;
513 uint32_t sockAddrLen;
518struct SC_ASYNC_EXPORT AsyncSocketAcceptBase :
public AsyncRequest
520 AsyncSocketAcceptBase() : AsyncRequest(Type::SocketAccept) {}
522 struct CompletionData :
public AsyncCompletionData
524 SocketDescriptor acceptedClient;
527 struct Result :
public AsyncResultOf<AsyncSocketAccept, CompletionData>
529 using AsyncResultOf<AsyncSocketAccept, CompletionData>::AsyncResultOf;
531 SC::Result moveTo(SocketDescriptor& client)
534 return SC::Result(client.assign(move(completionData.acceptedClient)));
537 using AsyncRequest::start;
540 SC::Result start(AsyncEventLoop& eventLoop,
const SocketDescriptor& socketDescriptor, AsyncSocketAcceptData& data);
541 SC::Result validate(AsyncEventLoop&);
543 Function<void(Result&)> callback;
544 SocketDescriptor::Handle handle = SocketDescriptor::Invalid;
545 SocketFlags::AddressFamily addressFamily = SocketFlags::AddressFamilyIPV4;
546 AsyncSocketAcceptData* acceptData =
nullptr;
563 using AsyncSocketAcceptBase::start;
569 detail::AsyncSocketAcceptData data;
586 using AsyncRequest::start;
593 SocketDescriptor::Handle handle = SocketDescriptor::Invalid;
600#if SC_PLATFORM_WINDOWS
601 void (*pConnectEx)() =
nullptr;
602 detail::WinOverlappedOpaque overlapped;
622 using AsyncRequest::start;
632 SocketDescriptor::Handle handle = SocketDescriptor::Invalid;
634 SC::Result closeHandle() {
return detail::SocketDescriptorDefinition::releaseHandle(handle); }
638 bool singleBuffer =
true;
645 size_t totalBytesWritten = 0;
646#if SC_PLATFORM_WINDOWS
647 detail::WinOverlappedOpaque overlapped;
667 Span<const char> data);
670 Span<Span<const char>> data);
673 using AsyncSocketSend::start;
677 AlignedStorage<56> typeErasedMsgHdr;
699 bool disconnected =
false;
706 bool isEnded()
const {
return completionData.disconnected; }
711 SC::Result
get(Span<char>& outData)
713 SC_TRY(getAsync().buffer.sliceStartLength(0, completionData.numBytes, outData));
719 using AsyncRequest::start;
727 SocketDescriptor::Handle handle = SocketDescriptor::Invalid;
729 SC::Result
closeHandle() {
return detail::SocketDescriptorDefinition::releaseHandle(handle); }
733 friend struct AsyncEventLoop;
734 SC::Result validate(AsyncEventLoop&);
735#if SC_PLATFORM_WINDOWS
736 detail::WinOverlappedOpaque overlapped;
752 using AsyncSocketReceive::start;
759 AlignedStorage<56> typeErasedMsgHdr;
791 bool endOfFile =
false;
798 bool isEnded()
const {
return completionData.endOfFile; }
800 SC::Result get(Span<char>& data)
802 SC_TRY(getAsync().buffer.sliceStartLength(0, completionData.numBytes, data));
806 using AsyncRequest::start;
811 Function<void(
Result&)> callback;
816 SC::Result
closeHandle() {
return detail::FileDescriptorDefinition::releaseHandle(handle); }
833 bool useOffset =
false;
834 bool endedSync =
false;
837#if SC_PLATFORM_WINDOWS
838 uint64_t readCursor = 0;
839 detail::WinOverlappedOpaque overlapped;
873 SC::Result get(
size_t& writtenSizeInBytes)
875 writtenSizeInBytes = completionData.numBytes;
880 using AsyncRequest::start;
899 SC::Result closeHandle() {
return detail::FileDescriptorDefinition::releaseHandle(handle); }
903 bool singleBuffer =
true;
920#if SC_PLATFORM_WINDOWS
921 bool endedSync =
false;
923 bool isWatchable =
false;
925 bool useOffset =
false;
926 uint64_t offset = 0xffffffffffffffff;
928 size_t totalBytesWritten = 0;
929#if SC_PLATFORM_WINDOWS
930 detail::WinOverlappedOpaque overlapped;
948#if SC_PLATFORM_WINDOWS
949 [[nodiscard]]
void* getOverlappedPtr();
952 Function<void(
Result&)> callback;
958 FileDescriptor::Handle handle = FileDescriptor::Invalid;
959#if SC_PLATFORM_WINDOWS
960 detail::WinOverlappedOpaque overlapped;
994 size_t bytesTransferred = 0;
995 bool usedZeroCopy =
false;
1006 [[nodiscard]]
bool usedZeroCopy()
const {
return completionData.usedZeroCopy; }
1011 return returnCode && completionData.bytesTransferred == getAsync().length;
1015 using AsyncRequest::start;
1027 int64_t offset = 0,
size_t length = 0,
size_t pipeSize = 0);
1032 FileDescriptor::Handle fileHandle = FileDescriptor::Invalid;
1033 SocketDescriptor::Handle socketHandle = SocketDescriptor::Invalid;
1037 size_t bytesSent = 0;
1042#if SC_PLATFORM_WINDOWS
1043 detail::WinOverlappedOpaque overlapped;
1044#elif SC_PLATFORM_LINUX
1045 size_t pipeBufferSize = 0;
1056 FileDescriptor::Handle handle = FileDescriptor::Invalid;
1059 size_t numBytes = 0;
1065struct SC_ASYNC_EXPORT AsyncCompletionVariant
1067 AsyncCompletionVariant() {}
1068 ~AsyncCompletionVariant() { destroy(); }
1070 AsyncCompletionVariant(
const AsyncCompletionVariant&) =
delete;
1071 AsyncCompletionVariant(AsyncCompletionVariant&&) =
delete;
1072 AsyncCompletionVariant& operator=(
const AsyncCompletionVariant&) =
delete;
1073 AsyncCompletionVariant& operator=(AsyncCompletionVariant&&) =
delete;
1075 bool inited =
false;
1077 AsyncRequest::Type type;
1080 AsyncCompletionData completionDataLoopWork;
1081 AsyncLoopTimeout::CompletionData completionDataLoopTimeout;
1082 AsyncLoopWakeUp::CompletionData completionDataLoopWakeUp;
1083 AsyncProcessExit::CompletionData completionDataProcessExit;
1084 AsyncSignal::CompletionData completionDataSignal;
1085 AsyncSocketAccept::CompletionData completionDataSocketAccept;
1086 AsyncSocketConnect::CompletionData completionDataSocketConnect;
1087 AsyncSocketSend::CompletionData completionDataSocketSend;
1088 AsyncSocketSendTo::CompletionData completionDataSocketSendTo;
1089 AsyncSocketReceive::CompletionData completionDataSocketReceive;
1090 AsyncSocketReceiveFrom::CompletionData completionDataSocketReceiveFrom;
1091 AsyncFileRead::CompletionData completionDataFileRead;
1092 AsyncFileWrite::CompletionData completionDataFileWrite;
1093 AsyncFileSend::CompletionData completionDataFileSend;
1094 AsyncFilePoll::CompletionData completionDataFilePoll;
1096 AsyncFileSystemOperationCompletionData completionDataFileSystemOperation;
1099 auto& getCompletion(AsyncLoopWork&) {
return completionDataLoopWork; }
1100 auto& getCompletion(AsyncLoopTimeout&) {
return completionDataLoopTimeout; }
1101 auto& getCompletion(AsyncLoopWakeUp&) {
return completionDataLoopWakeUp; }
1102 auto& getCompletion(AsyncProcessExit&) {
return completionDataProcessExit; }
1103 auto& getCompletion(AsyncSignal&) {
return completionDataSignal; }
1104 auto& getCompletion(AsyncSocketAccept&) {
return completionDataSocketAccept; }
1105 auto& getCompletion(AsyncSocketConnect&) {
return completionDataSocketConnect; }
1106 auto& getCompletion(AsyncSocketSend&) {
return completionDataSocketSend; }
1107 auto& getCompletion(AsyncSocketReceive&) {
return completionDataSocketReceive; }
1108 auto& getCompletion(AsyncFileRead&) {
return completionDataFileRead; }
1109 auto& getCompletion(AsyncFileWrite&) {
return completionDataFileWrite; }
1110 auto& getCompletion(AsyncFileSend&) {
return completionDataFileSend; }
1111 auto& getCompletion(AsyncFilePoll&) {
return completionDataFilePoll; }
1112 auto& getCompletion(AsyncFileSystemOperation&) {
return completionDataFileSystemOperation; }
1114 template <
typename T>
1115 auto& construct(T& t)
1118 placementNew(getCompletion(t));
1121 return getCompletion(t);
1139 detail::AsyncCompletionVariant completion;
1141 SC::Result returnCode = SC::Result(
true);
1160 Function<SC::Result()> work;
1209#ifdef RemoveDirectory
1210#undef RemoveDirectory
1212 enum class Operation
1256 SC::Result
read(
AsyncEventLoop& eventLoop, FileDescriptor::Handle handle, Span<char> buffer, uint64_t offset);
1307 Operation operation = Operation::None;
1313 struct FileDescriptorData
1315 FileDescriptor::Handle handle;
1326 FileDescriptor::Handle handle;
1333 FileDescriptor::Handle handle;
1334 Span<const char> buffer;
1341 StringSpan destinationPath;
1342 FileSystemCopyFlags copyFlags;
1345 using CopyDirectoryData = CopyFileData;
1347 using CloseData = FileDescriptorData;
1363 CloseData closeData;
1365 WriteData writeData;
1366 CopyFileData copyFileData;
1367 CopyDirectoryData copyDirectoryData;
1368 RenameData renameData;
1369 RemoveData removeData;
1374 SC::Result start(AsyncEventLoop& eventLoop, FileDescriptor::Handle fileDescriptor);
1375 SC::Result validate(AsyncEventLoop&);
1386 int numberOfEvents = 0;
1416 Options() { apiType = ApiType::Automatic; }
1603 static constexpr int Windows = 552;
1604 static constexpr int Apple = 520;
1605 static constexpr int Linux = 784;
1606 static constexpr int Default = Linux;
1608 static constexpr size_t Alignment = 8;
1610 using Object = Internal;
1613 using InternalOpaque = OpaqueObject<InternalDefinition>;
1616 InternalOpaque internalOpaque;
1656#pragma warning(push)
1657#pragma warning(disable : 4324)
1659 alignas(uint64_t) uint8_t eventsMemory[8 * 1024];
1675 bool wakeUpHasBeenCalled =
false;
1677 Result monitoringLoopThread(
Thread& thread);
Empty base struct for all AsyncRequest-derived CompletionData (internal) structs.
Definition Async.h:266
Allow library user to provide callbacks signaling different phases of async event loop cycle.
Definition Async.h:1392
Monitors Async I/O events from a background thread using a blocking kernel function (no CPU usage on ...
Definition Async.h:1630
Function< void(void)> onNewEventsAvailable
Informs to call dispatchCompletions on GUI Event Loop.
Definition Async.h:1631
Result startMonitoring()
Queue all async requests submissions and start monitoring loop events on a background thread.
Result close()
Stop monitoring the AsyncEventLoop, disposing all resources.
Result stopMonitoringAndDispatchCompletions()
Stops monitoring events on the background thread and dispatches callbacks for completed requests.
Result create(AsyncEventLoop &eventLoop)
Create the monitoring thread for an AsyncEventLoop.
Options given to AsyncEventLoop::create.
Definition Async.h:1407
ApiType apiType
Criteria to choose Async IO API.
Definition Async.h:1414
ApiType
Definition Async.h:1409
Asynchronous I/O (files, sockets, timers, processes, fs events, threads wake-up) (see Async) AsyncEve...
Definition Async.h:1404
bool needsThreadPoolForFileOperations() const
Returns true if backend needs a thread pool for non-blocking fs operations (anything but io_uring bas...
Result associateExternallyCreatedFileDescriptor(FileDescriptor &outDescriptor)
Associates a previously created File Descriptor with the eventLoop.
Result wakeUpFromExternalThread()
Wake up the event loop from a thread different than the one where run() is called (and potentially bl...
Result runNoWait()
Process active requests if any, dispatching their completions, or returns immediately without blockin...
static Result removeAllAssociationsFor(SocketDescriptor &outDescriptor)
Removes association of a TCP Socket with any event loop.
void updateTime()
Updates loop time to "now".
static bool tryProbingIOUring()
Check if io_uring can be created directly (only on Linux)
static bool isExcludedFromActiveCount(const AsyncRequest &async)
Checks if excludeFromActiveCount() has been called on the given request.
Result associateExternallyCreatedSocket(SocketDescriptor &outDescriptor)
Associates a previously created TCP / UDP socket with the eventLoop.
Result associateExternallyCreatedFileDescriptorHandle(FileDescriptor::Handle handle)
Associates a previously created File Descriptor handle with the eventLoop.
Result blockingPoll(AsyncKernelEvents &kernelEvents)
Blocks until at least one event happens, ensuring forward progress, without executing completions.
void clearSequence(AsyncSequence &sequence)
Clears the sequence.
int getNumberOfSubmittedRequests() const
Obtain the total number of submitted requests.
Result submitRequests(AsyncKernelEvents &kernelEvents)
Submits all queued async requests.
void enumerateRequests(Function< void(AsyncRequest &)> enumerationCallback)
Enumerates all requests objects associated with this loop.
TimeMs getLoopTime() const
Get Loop time (monotonic)
Result associateExternallyCreatedSocketHandle(SocketDescriptor::Handle handle)
Associates a previously created TCP / UDP socket handle with the eventLoop.
Result start(AsyncRequest &async)
Queues an async request request that has been correctly setup.
AsyncLoopTimeout * findEarliestLoopTimeout() const
Returns the next AsyncLoopTimeout that will be executed (shortest relativeTimeout)
void setListeners(AsyncEventLoopListeners *listeners)
Sets reference to listeners that will signal different events in loop lifetime.
Result dispatchCompletions(AsyncKernelEvents &kernelEvents)
Invokes completions for the AsyncKernelEvents collected by a call to AsyncEventLoop::blockingPoll.
void interrupt()
Interrupts the event loop even if it has active request on it.
Result wakeUpFromExternalThread(AsyncLoopWakeUp &wakeUp)
Wake up the event loop from a thread different than the one where run() is called (and potentially bl...
bool isInitialized() const
Returns true if create has been already called (successfully)
static Result removeAllAssociationsForSocketHandle(SocketDescriptor::Handle handle)
Removes association of a TCP Socket handle with any event loop.
Result create(Options options=Options())
Creates the event loop kernel object.
Result createAsyncTCPSocket(SocketFlags::AddressFamily family, SocketDescriptor &outDescriptor)
Creates an async TCP (IPV4 / IPV6) socket registered with the eventLoop.
Result close()
Closes the event loop kernel object.
static Result removeAllAssociationsForFileDescriptorHandle(FileDescriptor::Handle handle)
Removes association of a File Descriptor handle with any event loop.
Result createAsyncUDPSocket(SocketFlags::AddressFamily family, SocketDescriptor &outDescriptor)
Creates an async UCP (IPV4 / IPV6) socket registered with the eventLoop.
static Result removeAllAssociationsFor(FileDescriptor &outDescriptor)
Removes association of a File Descriptor with any event loop.
Result runOnce()
Blocks until at least one request proceeds, ensuring forward progress, dispatching all completions.
void excludeFromActiveCount(AsyncRequest &async)
Excludes the request from active handles count (to avoid it keeping event loop alive)
Result run()
Blocks until there are no more active queued requests, dispatching all completions.
void includeInActiveCount(AsyncRequest &async)
Reverses the effect of excludeFromActiveCount for the request.
int getNumberOfActiveRequests() const
Obtain the total number of active requests.
Starts an handle polling operation.
Definition Async.h:939
SC::Result start(AsyncEventLoop &eventLoop, FileDescriptor::Handle fileDescriptor)
Starts a file descriptor poll operation, monitoring its readiness with appropriate OS API.
Starts a file read operation, reading bytes from a file (or pipe).
Definition Async.h:785
FileDescriptor::Handle handle
The writeable span of memory where to data will be written.
Definition Async.h:813
Span< char > buffer
Callback called when some data has been read from the file into the buffer.
Definition Async.h:812
SC::Result closeHandle()
The file/pipe descriptor handle to read data from.
Definition Async.h:816
void setOffset(uint64_t fileOffset)
Sets the offset in bytes at which start reading.
Definition Async.h:823
SC::Result start(AsyncEventLoop &eventLoop, const FileDescriptor &descriptor, Span< char > data)
Sets async request members and calls AsyncEventLoop::start.
uint64_t getOffset() const
Returns the last offset set with AsyncFileRead::setOffset.
Definition Async.h:819
size_t getBytesTransferred() const
Get the number of bytes transferred.
Definition Async.h:1003
bool usedZeroCopy() const
Check if zero-copy was used for this transfer.
Definition Async.h:1006
bool isComplete() const
Check if the entire requested range was sent.
Definition Async.h:1009
Sends file contents to a socket using zero-copy when available (sendfile, TransmitFile).
Definition Async.h:989
Function< void(Result &)> callback
Called when send completes or fails.
Definition Async.h:1029
SC::Result start(AsyncEventLoop &eventLoop, const FileDescriptor &file, const SocketDescriptor &socket, int64_t offset=0, size_t length=0, size_t pipeSize=0)
Start the file send operation.
Starts an asynchronous file system operation (open, close, read, write, sendFile, stat,...
Definition Async.h:1203
SC::Result stop(AsyncEventLoop &eventLoop, Function< void(AsyncResult &)> *afterStopped=nullptr)
Stops the operation, including the internal thread-pool work item when used.
SC::Result copyDirectory(AsyncEventLoop &eventLoop, StringSpan path, StringSpan destinationPath, FileSystemCopyFlags copyFlags=FileSystemCopyFlags())
Copies a directory from one location to another.
SC::Result removeEmptyDirectory(AsyncEventLoop &eventLoop, StringSpan path)
Removes a directory asynchronously.
SC::Result rename(AsyncEventLoop &eventLoop, StringSpan path, StringSpan newPath)
Renames a file.
SC::Result removeFile(AsyncEventLoop &eventLoop, StringSpan path)
Removes a file asynchronously.
SC::Result setThreadPool(ThreadPool &threadPool)
Sets the thread pool to use for the operation.
SC::Result read(AsyncEventLoop &eventLoop, FileDescriptor::Handle handle, Span< char > buffer, uint64_t offset)
Reads data from a file descriptor at a given offset.
SC::Result write(AsyncEventLoop &eventLoop, FileDescriptor::Handle handle, Span< const char > buffer, uint64_t offset)
Writes data to a file descriptor at a given offset.
SC::Result close(AsyncEventLoop &eventLoop, FileDescriptor::Handle handle)
Closes a file descriptor asynchronously.
Function< void(Result &)> callback
Called after the operation is completed, on the event loop thread.
Definition Async.h:1235
SC::Result copyFile(AsyncEventLoop &eventLoop, StringSpan path, StringSpan destinationPath, FileSystemCopyFlags copyFlags=FileSystemCopyFlags())
Copies a file from one location to another.
SC::Result open(AsyncEventLoop &eventLoop, StringSpan path, FileOpen mode)
Opens a file asynchronously and returns its corresponding file descriptor.
Starts a file write operation, writing bytes to a file (or pipe).
Definition Async.h:861
uint64_t getOffset() const
Returns the last offset set with AsyncFileWrite::setOffset.
Definition Async.h:906
FileDescriptor::Handle handle
The file/pipe descriptor to write data to.
Definition Async.h:896
SC::Result start(AsyncEventLoop &eventLoop, Span< const char > data)
Sets async request members and calls AsyncEventLoop::start.
SC::Result start(AsyncEventLoop &eventLoop, const FileDescriptor &descriptor, Span< Span< const char > > data)
Sets async request members and calls AsyncEventLoop::start.
void setOffset(uint64_t fileOffset)
Sets the offset in bytes at which start writing.
Definition Async.h:910
Function< void(Result &)> callback
Callback called when descriptor is ready to be written with more data.
Definition Async.h:894
SC::Result start(AsyncEventLoop &eventLoop, const FileDescriptor &descriptor, Span< const char > data)
Sets async request members and calls AsyncEventLoop::start.
Span< Span< const char > > buffers
The read-only spans of memory where to read the data from.
Definition Async.h:902
SC::Result start(AsyncEventLoop &eventLoop, Span< Span< const char > > data)
Sets async request members and calls AsyncEventLoop::start.
Span< const char > buffer
The read-only span of memory where to read the data from.
Definition Async.h:901
Allows user to supply a block of memory that will store kernel I/O events retrieved from AsyncEventLo...
Definition Async.h:1382
Span< uint8_t > eventsMemory
User supplied block of memory used to store kernel I/O events.
Definition Async.h:1383
Starts a Timeout that is invoked only once after expiration (relative) time has passed.
Definition Async.h:317
TimeMs getExpirationTime() const
Gets computed absolute expiration time that determines when this timeout get executed.
Definition Async.h:332
SC::Result start(AsyncEventLoop &eventLoop, TimeMs relativeTimeout)
Sets async request members and calls AsyncEventLoop::start.
TimeMs relativeTimeout
First timer expiration (relative) time in milliseconds.
Definition Async.h:329
Function< void(Result &)> callback
Called after given expiration time since AsyncLoopTimeout::start has passed.
Definition Async.h:327
Options for AsyncLoopWakeUp configuration.
Definition Async.h:342
bool coalesce
Merge repeated pending wakeUp() calls into a single callback (default true, matching libuv uv_async_t...
Definition Async.h:345
Starts a wake-up operation, allowing threads to execute callbacks on loop thread.
Definition Async.h:365
SC::Result start(AsyncEventLoop &eventLoop, EventObject &eventObject, AsyncLoopWakeUpOptions options={})
Sets async request members and calls AsyncEventLoop::start.
Function< void(Result &)> callback
Callback called by SC::AsyncEventLoop::run after SC::AsyncLoopWakeUp::wakeUp.
Definition Async.h:384
SC::Result wakeUp(AsyncEventLoop &eventLoop)
Wakes up event loop, scheduling AsyncLoopWakeUp::callback on next AsyncEventLoop::run (or its variati...
SC::Result start(AsyncEventLoop &eventLoop, AsyncLoopWakeUpOptions options={})
Sets async request members and calls AsyncEventLoop::start.
Executes work in a thread pool and then invokes a callback on the event loop thread.
Definition Async.h:1150
Function< void(Result &)> callback
Called to execute the work in a background threadpool thread.
Definition Async.h:1161
SC::Result setThreadPool(ThreadPool &threadPool)
Sets the ThreadPool that will supply the thread to run the async work on.
Starts monitoring a process, notifying about its termination.
Definition Async.h:402
SC::Result start(AsyncEventLoop &eventLoop, FileDescriptor::Handle process)
Sets async request members and calls AsyncEventLoop::start.
Function< void(Result &)> callback
Called when process has exited.
Definition Async.h:427
Base class for all async requests, holding state and type.
Definition Async.h:130
bool isCancelling() const
Returns true if this request is being cancelled.
AsyncRequest(Type type)
Constructs a free async request of given type.
Definition Async.h:170
Result start(AsyncEventLoop &eventLoop)
Shortcut for AsyncEventLoop::start.
uint16_t getUserFlags() const
Gets user flags, holding some meaningful data for the caller.
Definition Async.h:199
Function< void(AsyncResult &)> * getCloseCallback()
Returns currently set close callback (if any) passed to AsyncRequest::stop.
Definition Async.h:202
bool isActive() const
Returns true if this request is active or being reactivated.
bool isFree() const
Returns true if this request is free.
void disableThreadPool()
Disables the thread-pool usage for this request.
Type getType() const
Returns request type.
Definition Async.h:190
void setUserFlags(uint16_t externalFlags)
Sets user flags, holding some meaningful data for the caller.
Definition Async.h:196
Result executeOn(AsyncTaskSequence &task, ThreadPool &pool)
Adds the request to be executed on a specific AsyncTaskSequence.
Result stop(AsyncEventLoop &eventLoop, Function< void(AsyncResult &)> *afterStopped=nullptr)
Ask to stop current async operation.
void executeOn(AsyncSequence &sequence)
Adds the request to be executed on a specific AsyncSequence.
Type
Type of async request.
Definition Async.h:149
Helper holding CompletionData for a specific AsyncRequest-derived class.
Definition Async.h:302
Base class for all async results (argument of completion callbacks).
Definition Async.h:272
const SC::Result & isValid() const
Check if the returnCode of this result is valid.
Definition Async.h:283
AsyncResult(AsyncEventLoop &eventLoop, AsyncRequest &request, SC::Result &res, bool *hasBeenReactivated=nullptr)
Constructs an async result from a request and a result.
Definition Async.h:274
void reactivateRequest(bool shouldBeReactivated)
Ask the event loop to re-activate this request after it was already completed.
Execute AsyncRequests serially, by submitting the next one after the previous one is completed.
Definition Async.h:250
Options for AsyncSignal request configuration.
Definition Async.h:445
Mode
Mode of signal watching.
Definition Async.h:448
@ Persistent
Callback runs on every delivery until stopped (default)
@ OneShot
Request auto-stops after first successful callback dispatch.
Mode mode
Default mode is Persistent.
Definition Async.h:452
bool coalesce
Merge repeated pending deliveries (default true)
Definition Async.h:453
Starts monitoring a signal, notifying about its reception.
Definition Async.h:464
Function< void(Result &)> callback
Called when the signal is raised.
Definition Async.h:482
SC::Result start(AsyncEventLoop &eventLoop, int num, AsyncSignalOptions options={})
Sets async request members and calls AsyncEventLoop::start.
Starts a socket accept operation, obtaining a new socket from a listening socket.
Definition Async.h:561
SC::Result start(AsyncEventLoop &eventLoop, const SocketDescriptor &socketDescriptor)
Sets async request members and calls AsyncEventLoop::start.
Starts a socket connect operation, connecting to a remote endpoint.
Definition Async.h:581
Function< void(Result &)> callback
Called after socket is finally connected to endpoint.
Definition Async.h:591
SC::Result start(AsyncEventLoop &eventLoop, const SocketDescriptor &descriptor, SocketIPAddress address)
Sets async request members and calls AsyncEventLoop::start.
Starts an unconnected socket receive from operation, receiving bytes from a remote endpoint.
Definition Async.h:750
SC::Result get(Span< char > &outData)
Get a Span of the actually read data.
Definition Async.h:711
Starts a socket receive operation, receiving bytes from a remote endpoint.
Definition Async.h:693
SC::Result start(AsyncEventLoop &eventLoop, const SocketDescriptor &descriptor, Span< char > data)
Sets async request members and calls AsyncEventLoop::start.
SC::Result closeHandle()
The Socket Descriptor handle to read data from.
Definition Async.h:729
Span< char > buffer
The writeable span of memory where to data will be written.
Definition Async.h:726
Function< void(Result &)> callback
Called after data has been received.
Definition Async.h:724
Starts an unconnected socket send to operation, sending bytes to a remote endpoint.
Definition Async.h:661
Starts a socket send operation, sending bytes to a remote endpoint.
Definition Async.h:615
Function< void(Result &)> callback
Called when socket is ready to send more data.
Definition Async.h:630
SC::Result start(AsyncEventLoop &eventLoop, const SocketDescriptor &descriptor, Span< const char > data)
Sets async request members and calls AsyncEventLoop::start.
Span< Span< const char > > buffers
Spans of bytes to send (singleBuffer == false)
Definition Async.h:637
Span< const char > buffer
Span of bytes to send (singleBuffer == true)
Definition Async.h:636
SC::Result start(AsyncEventLoop &eventLoop, const SocketDescriptor &descriptor, Span< Span< const char > > data)
Sets async request members and calls AsyncEventLoop::start.
An AsyncSequence using a SC::ThreadPool to execute one or more SC::AsyncRequest in a background threa...
Definition Async.h:1131
Atomic variables (only for int and bool for now).
Definition Atomic.h:42
An automatically reset event object to synchronize two threads.
Definition Threading.h:243
[UniqueHandleDeclaration2Snippet]
Definition File.h:130
Options used to open a file descriptor.
Definition File.h:101
A structure to describe copy flags.
Definition FileSystem.h:76
Read / Write pipe (Process stdin/stdout and IPC communication)
Definition File.h:302
Low-level OS socket handle.
Definition Socket.h:167
AddressFamily
Sets the address family of an IP Address (IPv4 or IPV6)
Definition Socket.h:74
Native representation of an IP Address.
Definition Socket.h:114
A small task containing a function to execute that can be queued in the thread pool.
Definition ThreadPool.h:16
Simple thread pool that executes tasks in a fixed number of worker threads.
Definition ThreadPool.h:38
A native OS thread.
Definition Threading.h:127