5#include "../Foundation/Compiler.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 "../File/File.h"
13#include "../FileSystem/FileSystem.h"
14#include "../Foundation/Function.h"
15#include "../Foundation/OpaqueObject.h"
16#include "../Socket/Socket.h"
17#include "../Threading/Atomic.h"
18#include "../Threading/ThreadPool.h"
58struct AsyncTaskSequence;
62struct AsyncWinOverlapped;
63struct AsyncWinOverlappedDefinition
65 static constexpr int Windows =
sizeof(
void*) * 4 +
sizeof(
uint64_t);
66 static constexpr size_t Alignment =
alignof(
void*);
68 using Object = AsyncWinOverlapped;
70using WinOverlappedOpaque = OpaqueObject<AsyncWinOverlappedDefinition>;
72struct AsyncWinWaitDefinition
74 using Handle = FileDescriptor::Handle;
75 static constexpr Handle Invalid = FileDescriptor::Invalid;
77 static Result releaseHandle(Handle& waitHandle);
79struct SC_ASYNC_EXPORT WinWaitHandle :
public UniqueHandle<AsyncWinWaitDefinition>
127 void setDebugName(
const char* newDebugName);
163 AsyncRequest(
Type type) : state(State::Free), type(type), flags(0), unused(0), userFlags(0) {}
197 [[nodiscard]]
const Function<void(
AsyncResult&)>* getCloseCallback()
const {
return closeCallback; }
202 void queueSubmission(AsyncEventLoop& eventLoop);
204 AsyncSequence* sequence =
nullptr;
206 AsyncTaskSequence* getTask();
209 Function<void(AsyncResult&)>* closeCallback =
nullptr;
211 friend struct AsyncEventLoop;
212 friend struct AsyncResult;
216 [[nodiscard]]
static const char* TypeToString(Type type);
217 enum class State : uint8_t
227#if SC_ASYNC_ENABLE_LOG
228 const char* debugName =
"None";
247 bool clearSequenceOnCancel =
true;
248 bool clearSequenceOnError =
true;
251 bool runningAsync =
false;
252 bool tracked =
false;
254 IntrusiveDoubleLinkedList<AsyncRequest> submissions;
268 : eventLoop(eventLoop), async(request), hasBeenReactivated(hasBeenReactivated), returnCode(res)
284 bool shouldCallCallback =
true;
285 bool* hasBeenReactivated =
nullptr;
293template <
typename T,
typename C>
296 T& getAsync() {
return static_cast<T&
>(AsyncResult::async); }
297 const T& getAsync()
const {
return static_cast<const T&
>(AsyncResult::async); }
315 using AsyncRequest::start;
383 int32_t consumePendingWakeUps();
384 int32_t getPendingWakeUps()
const;
409 status = completionData.exitStatus;
413 using AsyncRequest::start;
426 FileDescriptor::Handle handle = FileDescriptor::Invalid;
427#if SC_PLATFORM_WINDOWS
429 detail::WinWaitHandle waitHandle;
431#elif SC_PLATFORM_LINUX
462 int signalNumber = 0;
470 using AsyncRequest::start;
481 int signalNumber = 0;
483#if SC_PLATFORM_WINDOWS
486#elif SC_PLATFORM_LINUX
488 FileDescriptor::Handle signalFdHandle = FileDescriptor::Invalid;
497struct SC_ASYNC_EXPORT AsyncSocketAcceptData
499#if SC_PLATFORM_WINDOWS
500 void (*pAcceptEx)() =
nullptr;
503 uint8_t acceptBuffer[288] = {0};
504#elif SC_PLATFORM_LINUX
505 AlignedStorage<28> sockAddrHandle;
506 uint32_t sockAddrLen;
511struct SC_ASYNC_EXPORT AsyncSocketAcceptBase :
public AsyncRequest
513 AsyncSocketAcceptBase() : AsyncRequest(Type::SocketAccept) {}
515 struct CompletionData :
public AsyncCompletionData
517 SocketDescriptor acceptedClient;
520 struct Result :
public AsyncResultOf<AsyncSocketAccept, CompletionData>
522 using AsyncResultOf<AsyncSocketAccept, CompletionData>::AsyncResultOf;
527 return client.assign(
move(completionData.acceptedClient));
530 using AsyncRequest::start;
533 SC::Result start(AsyncEventLoop& eventLoop,
const SocketDescriptor& socketDescriptor, AsyncSocketAcceptData& data);
537 SocketDescriptor::Handle handle = SocketDescriptor::Invalid;
538 SocketFlags::AddressFamily addressFamily = SocketFlags::AddressFamilyIPV4;
539 AsyncSocketAcceptData* acceptData =
nullptr;
556 using AsyncSocketAcceptBase::start;
562 detail::AsyncSocketAcceptData data;
579 using AsyncRequest::start;
586 SocketDescriptor::Handle handle = SocketDescriptor::Invalid;
593#if SC_PLATFORM_WINDOWS
594 void (*pConnectEx)() =
nullptr;
615 using AsyncRequest::start;
625 SocketDescriptor::Handle handle = SocketDescriptor::Invalid;
627 SC::Result closeHandle() {
return detail::SocketDescriptorDefinition::releaseHandle(handle); }
631 bool singleBuffer =
true;
638 size_t totalBytesWritten = 0;
639#if SC_PLATFORM_WINDOWS
666 using AsyncSocketSend::start;
692 bool disconnected =
false;
699 bool isEnded()
const {
return completionData.disconnected; }
706 SC_TRY(getAsync().buffer.sliceStartLength(0, completionData.numBytes, outData));
712 using AsyncRequest::start;
720 SocketDescriptor::Handle handle = SocketDescriptor::Invalid;
726 friend struct AsyncEventLoop;
728#if SC_PLATFORM_WINDOWS
729 detail::WinOverlappedOpaque overlapped;
745 using AsyncSocketReceive::start;
784 bool endOfFile =
false;
791 bool isEnded()
const {
return completionData.endOfFile; }
795 SC_TRY(getAsync().buffer.sliceStartLength(0, completionData.numBytes, data));
799 using AsyncRequest::start;
826 bool useOffset =
false;
827 bool endedSync =
false;
830#if SC_PLATFORM_WINDOWS
868 writtenSizeInBytes = completionData.numBytes;
873 using AsyncRequest::start;
892 SC::Result closeHandle() {
return detail::FileDescriptorDefinition::releaseHandle(handle); }
896 bool singleBuffer =
true;
913#if SC_PLATFORM_WINDOWS
914 bool endedSync =
false;
916 bool isWatchable =
false;
918 bool useOffset =
false;
919 uint64_t offset = 0xffffffffffffffff;
921 size_t totalBytesWritten = 0;
922#if SC_PLATFORM_WINDOWS
941#if SC_PLATFORM_WINDOWS
942 [[nodiscard]]
void* getOverlappedPtr();
951 FileDescriptor::Handle handle = FileDescriptor::Invalid;
952#if SC_PLATFORM_WINDOWS
987 size_t bytesTransferred = 0;
988 bool usedZeroCopy =
false;
999 [[nodiscard]]
bool usedZeroCopy()
const {
return completionData.usedZeroCopy; }
1004 return returnCode && completionData.bytesTransferred == getAsync().length;
1008 using AsyncRequest::start;
1020 int64_t offset = 0,
size_t length = 0,
size_t pipeSize = 0);
1025 FileDescriptor::Handle fileHandle = FileDescriptor::Invalid;
1026 SocketDescriptor::Handle socketHandle = SocketDescriptor::Invalid;
1030 size_t bytesSent = 0;
1035#if SC_PLATFORM_WINDOWS
1037#elif SC_PLATFORM_LINUX
1038 size_t pipeBufferSize = 0;
1049 FileDescriptor::Handle handle = FileDescriptor::Invalid;
1052 size_t numBytes = 0;
1058struct SC_ASYNC_EXPORT AsyncCompletionVariant
1060 AsyncCompletionVariant() {}
1061 ~AsyncCompletionVariant() { destroy(); }
1063 AsyncCompletionVariant(
const AsyncCompletionVariant&) =
delete;
1064 AsyncCompletionVariant(AsyncCompletionVariant&&) =
delete;
1065 AsyncCompletionVariant& operator=(
const AsyncCompletionVariant&) =
delete;
1066 AsyncCompletionVariant& operator=(AsyncCompletionVariant&&) =
delete;
1068 bool inited =
false;
1070 AsyncRequest::Type type;
1073 AsyncCompletionData completionDataLoopWork;
1074 AsyncLoopTimeout::CompletionData completionDataLoopTimeout;
1075 AsyncLoopWakeUp::CompletionData completionDataLoopWakeUp;
1076 AsyncProcessExit::CompletionData completionDataProcessExit;
1077 AsyncSignal::CompletionData completionDataSignal;
1078 AsyncSocketAccept::CompletionData completionDataSocketAccept;
1079 AsyncSocketConnect::CompletionData completionDataSocketConnect;
1080 AsyncSocketSend::CompletionData completionDataSocketSend;
1081 AsyncSocketSendTo::CompletionData completionDataSocketSendTo;
1082 AsyncSocketReceive::CompletionData completionDataSocketReceive;
1083 AsyncSocketReceiveFrom::CompletionData completionDataSocketReceiveFrom;
1084 AsyncFileRead::CompletionData completionDataFileRead;
1085 AsyncFileWrite::CompletionData completionDataFileWrite;
1086 AsyncFileSend::CompletionData completionDataFileSend;
1087 AsyncFilePoll::CompletionData completionDataFilePoll;
1089 AsyncFileSystemOperationCompletionData completionDataFileSystemOperation;
1092 auto& getCompletion(AsyncLoopWork&) {
return completionDataLoopWork; }
1093 auto& getCompletion(AsyncLoopTimeout&) {
return completionDataLoopTimeout; }
1094 auto& getCompletion(AsyncLoopWakeUp&) {
return completionDataLoopWakeUp; }
1095 auto& getCompletion(AsyncProcessExit&) {
return completionDataProcessExit; }
1096 auto& getCompletion(AsyncSignal&) {
return completionDataSignal; }
1097 auto& getCompletion(AsyncSocketAccept&) {
return completionDataSocketAccept; }
1098 auto& getCompletion(AsyncSocketConnect&) {
return completionDataSocketConnect; }
1099 auto& getCompletion(AsyncSocketSend&) {
return completionDataSocketSend; }
1100 auto& getCompletion(AsyncSocketReceive&) {
return completionDataSocketReceive; }
1101 auto& getCompletion(AsyncFileRead&) {
return completionDataFileRead; }
1102 auto& getCompletion(AsyncFileWrite&) {
return completionDataFileWrite; }
1103 auto& getCompletion(AsyncFileSend&) {
return completionDataFileSend; }
1104 auto& getCompletion(AsyncFilePoll&) {
return completionDataFilePoll; }
1105 auto& getCompletion(AsyncFileSystemOperation&) {
return completionDataFileSystemOperation; }
1107 template <
typename T>
1108 auto& construct(T& t)
1111 placementNew(getCompletion(t));
1114 return getCompletion(t);
1132 detail::AsyncCompletionVariant completion;
1202#ifdef RemoveDirectory
1203#undef RemoveDirectory
1205 enum class Operation
1297 Operation operation = Operation::None;
1303 struct FileDescriptorData
1305 FileDescriptor::Handle handle;
1316 FileDescriptor::Handle handle;
1323 FileDescriptor::Handle handle;
1324 Span<const char> buffer;
1331 StringSpan destinationPath;
1332 FileSystemCopyFlags copyFlags;
1335 using CopyDirectoryData = CopyFileData;
1337 using CloseData = FileDescriptorData;
1353 CloseData closeData;
1355 WriteData writeData;
1356 CopyFileData copyFileData;
1357 CopyDirectoryData copyDirectoryData;
1358 RenameData renameData;
1359 RemoveData removeData;
1364 SC::Result start(AsyncEventLoop& eventLoop, FileDescriptor::Handle fileDescriptor);
1376 int numberOfEvents = 0;
1406 Options() { apiType = ApiType::Automatic; }
1593 static constexpr int Windows = 552;
1594 static constexpr int Apple = 520;
1595 static constexpr int Linux = 736;
1596 static constexpr int Default = Linux;
1598 static constexpr size_t Alignment = 8;
1600 using Object = Internal;
1646#pragma warning(push)
1647#pragma warning(disable : 4324)
1665 bool wakeUpHasBeenCalled =
false;
@ Write
Check if path is writable.
@ Read
Check if path is readable.
unsigned short uint16_t
Platform independent (2) bytes unsigned int.
Definition PrimitiveTypes.h:37
constexpr T && move(T &value)
Converts an lvalue to an rvalue reference.
Definition Compiler.h:274
struct SC_FOUNDATION_EXPORT Function
Wraps function pointers, member functions and lambdas without ever allocating.
Definition Function.h:19
unsigned char uint8_t
Platform independent (1) byte unsigned int.
Definition PrimitiveTypes.h:36
unsigned long long uint64_t
Platform independent (8) bytes unsigned int.
Definition PrimitiveTypes.h:42
unsigned int uint32_t
Platform independent (4) bytes unsigned int.
Definition PrimitiveTypes.h:38
short int16_t
Platform independent (2) bytes signed int.
Definition PrimitiveTypes.h:45
long long int64_t
Platform independent (8) bytes signed int.
Definition PrimitiveTypes.h:50
int int32_t
Platform independent (4) bytes signed int.
Definition PrimitiveTypes.h:46
#define SC_TRY(expression)
Checks the value of the given expression and if failed, returns this value to caller.
Definition Result.h:49
A buffer of bytes with given alignment.
Definition AlignedStorage.h:29
Empty base struct for all AsyncRequest-derived CompletionData (internal) structs.
Definition Async.h:259
Allow library user to provide callbacks signaling different phases of async event loop cycle.
Definition Async.h:1382
Monitors Async I/O events from a background thread using a blocking kernel function (no CPU usage on ...
Definition Async.h:1620
Function< void(void)> onNewEventsAvailable
Informs to call dispatchCompletions on GUI Event Loop.
Definition Async.h:1621
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:1397
ApiType apiType
Criteria to choose Async IO API.
Definition Async.h:1404
ApiType
Definition Async.h:1399
Asynchronous I/O (files, sockets, timers, processes, fs events, threads wake-up) (see Async) AsyncEve...
Definition Async.h:1394
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 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.
static bool tryLoadingLiburing()
Check if liburing is loadable (only on Linux)
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:932
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:778
FileDescriptor::Handle handle
The writeable span of memory where to data will be written.
Definition Async.h:806
Span< char > buffer
Callback called when some data has been read from the file into the buffer.
Definition Async.h:805
SC::Result closeHandle()
The file/pipe descriptor handle to read data from.
Definition Async.h:809
void setOffset(uint64_t fileOffset)
Sets the offset in bytes at which start reading.
Definition Async.h:816
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:812
size_t getBytesTransferred() const
Get the number of bytes transferred.
Definition Async.h:996
bool usedZeroCopy() const
Check if zero-copy was used for this transfer.
Definition Async.h:999
bool isComplete() const
Check if the entire requested range was sent.
Definition Async.h:1002
Sends file contents to a socket using zero-copy when available (sendfile, TransmitFile).
Definition Async.h:982
Function< void(Result &)> callback
Called when send completes or fails.
Definition Async.h:1022
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:1196
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:1225
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:854
uint64_t getOffset() const
Returns the last offset set with AsyncFileWrite::setOffset.
Definition Async.h:899
FileDescriptor::Handle handle
The file/pipe descriptor to write data to.
Definition Async.h:889
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:903
Function< void(Result &)> callback
Callback called when descriptor is ready to be written with more data.
Definition Async.h:887
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:895
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:894
Allows user to supply a block of memory that will store kernel I/O events retrieved from AsyncEventLo...
Definition Async.h:1372
Span< uint8_t > eventsMemory
User supplied block of memory used to store kernel I/O events.
Definition Async.h:1373
Starts a Timeout that is invoked only once after expiration (relative) time has passed.
Definition Async.h:310
TimeMs getExpirationTime() const
Gets computed absolute expiration time that determines when this timeout get executed.
Definition Async.h:325
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:322
Function< void(Result &)> callback
Called after given expiration time since AsyncLoopTimeout::start has passed.
Definition Async.h:320
Options for AsyncLoopWakeUp configuration.
Definition Async.h:335
bool coalesce
Merge repeated pending wakeUp() calls into a single callback (default true, matching libuv uv_async_t...
Definition Async.h:338
Starts a wake-up operation, allowing threads to execute callbacks on loop thread.
Definition Async.h:358
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:377
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:1143
Function< void(Result &)> callback
Called to execute the work in a background threadpool thread.
Definition Async.h:1154
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:395
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:420
Base class for all async requests, holding state and type.
Definition Async.h:123
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:163
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:192
Function< void(AsyncResult &)> * getCloseCallback()
Returns currently set close callback (if any) passed to AsyncRequest::stop.
Definition Async.h:195
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:183
void setUserFlags(uint16_t externalFlags)
Sets user flags, holding some meaningful data for the caller.
Definition Async.h:189
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:142
Helper holding CompletionData for a specific AsyncRequest-derived class.
Definition Async.h:295
Base class for all async results (argument of completion callbacks).
Definition Async.h:265
const SC::Result & isValid() const
Check if the returnCode of this result is valid.
Definition Async.h:276
AsyncResult(AsyncEventLoop &eventLoop, AsyncRequest &request, SC::Result &res, bool *hasBeenReactivated=nullptr)
Constructs an async result from a request and a result.
Definition Async.h:267
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:243
Options for AsyncSignal request configuration.
Definition Async.h:438
Mode
Mode of signal watching.
Definition Async.h:441
@ 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:445
bool coalesce
Merge repeated pending deliveries (default true)
Definition Async.h:446
Starts monitoring a signal, notifying about its reception.
Definition Async.h:457
Function< void(Result &)> callback
Called when the signal is raised.
Definition Async.h:475
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:554
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:574
Function< void(Result &)> callback
Called after socket is finally connected to endpoint.
Definition Async.h:584
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:743
SC::Result get(Span< char > &outData)
Get a Span of the actually read data.
Definition Async.h:704
Starts a socket receive operation, receiving bytes from a remote endpoint.
Definition Async.h:686
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:722
Span< char > buffer
The writeable span of memory where to data will be written.
Definition Async.h:719
Function< void(Result &)> callback
Called after data has been received.
Definition Async.h:717
Starts an unconnected socket send to operation, sending bytes to a remote endpoint.
Definition Async.h:654
Starts a socket send operation, sending bytes to a remote endpoint.
Definition Async.h:608
Function< void(Result &)> callback
Called when socket is ready to send more data.
Definition Async.h:623
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:630
Span< const char > buffer
Span of bytes to send (singleBuffer == true)
Definition Async.h:629
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:1124
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:235
[UniqueHandleDeclaration2Snippet]
Definition File.h:128
Options used to open a file descriptor.
Definition File.h:99
A structure to describe copy flags.
Definition FileSystem.h:76
Hides implementation details from public headers (static PIMPL).
Definition OpaqueObject.h:31
Read / Write pipe (Process stdin/stdout and IPC communication)
Definition File.h:300
An ascii string used as boolean result. SC_TRY macro forwards errors to caller.
Definition Result.h:13
Low-level OS socket handle.
Definition Socket.h:159
AddressFamily
Sets the address family of an IP Address (IPv4 or IPV6)
Definition Socket.h:66
Native representation of an IP Address.
Definition Socket.h:106
View over a contiguous sequence of items (pointer + size in elements).
Definition Span.h:29
An read-only view over a string (to avoid including Strings library when parsing is not needed).
Definition StringSpan.h:37
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:119
A vocabulary type representing a time interval in milliseconds since epoch.
Definition PrimitiveTypes.h:63