Sane C++ Libraries
C++ Platform Abstraction Libraries
Loading...
Searching...
No Matches
Async.h
1// Copyright (c) Stefano Cristiano
2// SPDX-License-Identifier: MIT
3#pragma once
4
5#include "../Common/CompilerMacrosExport.h"
6#ifndef SC_EXPORT_LIBRARY_ASYNC
7#define SC_EXPORT_LIBRARY_ASYNC 0
8#endif
9#define SC_ASYNC_EXPORT SC_COMPILER_LIBRARY_EXPORT(SC_EXPORT_LIBRARY_ASYNC)
10
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"
20#include "AsyncError.h"
21
22namespace SC
23{
24SC_DECLARE_ASSERT_PROVIDER(AsyncAssert, SC_ASYNC_EXPORT);
25
26#define SC_ASYNC_ASSERT_RELEASE(e) SC_ASSERT_PROVIDER_RELEASE(SC::AsyncAssert, e)
27#define SC_ASYNC_ASSERT_DEBUG(e) SC_ASSERT_PROVIDER_DEBUG(SC::AsyncAssert, e)
28#define SC_ASYNC_TRUST_RESULT(expression) SC_ASYNC_ASSERT_RELEASE(expression)
29
30struct ThreadPool;
31struct ThreadPoolTask;
32struct EventObject;
33} // namespace SC
59
62namespace SC
63{
64struct AsyncEventLoop;
65struct AsyncResult;
66struct AsyncSequence;
67struct AsyncTaskSequence;
68
70enum class AsyncThreadPoolMode : uint8_t
71{
72 NativePreferred,
73 ForceThreadPool,
74};
75
76namespace detail
77{
78struct AsyncWinOverlapped;
79struct AsyncWinOverlappedDefinition
80{
81 static constexpr int Windows = sizeof(void*) * 4 + sizeof(uint64_t);
82 static constexpr size_t Alignment = alignof(void*);
83
84 using Object = AsyncWinOverlapped;
85};
86using WinOverlappedOpaque = OpaqueObject<AsyncWinOverlappedDefinition>;
87
88struct AsyncWinWaitDefinition
89{
90 using Handle = FileDescriptor::Handle; // fd
91 static constexpr Handle Invalid = FileDescriptor::Invalid; // invalid fd
92
93 static Result releaseHandle(Handle& waitHandle);
94};
95struct SC_ASYNC_EXPORT WinWaitHandle : public UniqueHandle<AsyncWinWaitDefinition>
96{
97};
98} // namespace detail
99
138struct SC_ASYNC_EXPORT AsyncRequest
139{
140 AsyncRequest* next = nullptr;
141 AsyncRequest* prev = nullptr;
142
143 void setDebugName(const char* newDebugName);
144
146 void executeOn(AsyncSequence& sequence);
147
152 AsyncThreadPoolMode mode = AsyncThreadPoolMode::NativePreferred);
153
156
158 enum class Type : uint8_t
159 {
160 LoopTimeout,
161 LoopWakeUp,
162 LoopWork,
163 ProcessExit,
164 Signal,
165 SocketAccept,
166 SocketConnect,
167 SocketSend,
168 SocketSendTo,
169 SocketReceive,
170 SocketReceiveFrom,
171 FileRead,
172 FileWrite,
173 FileSend,
174 FileReadiness,
175 ExternalCompletion,
176 FileSystemOperation,
177 };
178
181 AsyncRequest(Type type) : state(State::Free), type(type), flags(0), unused(0), userFlags(0) {}
182
190 Result stop(AsyncEventLoop& eventLoop, Function<void(AsyncResult&)>* afterStopped = nullptr);
191
193 [[nodiscard]] bool isFree() const;
194
196 [[nodiscard]] bool isCancelling() const;
197
199 [[nodiscard]] bool isActive() const;
200
202 [[nodiscard]] Type getType() const { return type; }
203
205 Result start(AsyncEventLoop& eventLoop);
206
208 void setUserFlags(uint16_t externalFlags) { userFlags = externalFlags; }
209
211 uint16_t getUserFlags() const { return userFlags; }
212
214 [[nodiscard]] Function<void(AsyncResult&)>* getCloseCallback() { return closeCallback; }
215
216 [[nodiscard]] const Function<void(AsyncResult&)>* getCloseCallback() const { return closeCallback; }
217
218 protected:
219 Result checkState();
220
221 void queueSubmission(AsyncEventLoop& eventLoop);
222
223 AsyncSequence* sequence = nullptr;
224
225 AsyncTaskSequence* getTask();
226
227 [[nodiscard]] bool isThreadPoolForced() const;
228
229 private:
230 Function<void(AsyncResult&)>* closeCallback = nullptr;
231
232 friend struct AsyncEventLoop;
233 friend struct AsyncResult;
234
235 void markAsFree();
236
237 [[nodiscard]] static const char* TypeToString(Type type);
238 enum class State : uint8_t
239 {
240 Free, // not in any queue, this can be started with an async.start(...)
241 Setup, // when in submission queue waiting to be setup (after an async.start(...))
242 Submitting, // when in submission queue waiting to be activated or re-activated
243 Active, // when monitored by OS syscall or in activeLoopWakeUps / activeTimeouts queues
244 Reactivate, // when flagged for reactivation inside the callback (after a result.reactivateRequest(true))
245 Cancelling, // when in cancellation queue waiting for a cancelAsync (on active async)
246 };
247
248#if SC_ASYNC_ENABLE_LOG
249 const char* debugName = "None";
250#endif
251 State state; // 1 byte
252 Type type; // 1 byte
253 int16_t flags; // 2 bytes
254
255 uint16_t unused; // 2 bytes
256 uint16_t userFlags; // 2 bytes
257};
258
263struct SC_ASYNC_EXPORT AsyncSequence
264{
265 AsyncSequence* next = nullptr;
266 AsyncSequence* prev = nullptr;
267
268 bool clearSequenceOnCancel = true;
269 bool clearSequenceOnError = true;
270 private:
271 friend struct AsyncEventLoop;
272 bool runningAsync = false; // true if an async from this sequence is being run
273 bool tracked = false;
274
275 AsyncRequest* runningRequest = nullptr;
276
277 IntrusiveDoubleLinkedList<AsyncRequest> submissions;
278};
279
281struct SC_ASYNC_EXPORT AsyncCompletionData
282{
283};
284
287struct SC_ASYNC_EXPORT AsyncResult
288{
290 AsyncResult(AsyncEventLoop& eventLoop, AsyncRequest& request, SC::Result& res, bool* hasBeenReactivated = nullptr)
291 : eventLoop(eventLoop), async(request), hasBeenReactivated(hasBeenReactivated), returnCode(res)
292 {}
293
296 void reactivateRequest(bool shouldBeReactivated);
297
299 [[nodiscard]] const SC::Result& isValid() const { return returnCode; }
300
301 AsyncEventLoop& eventLoop;
302 AsyncRequest& async;
303
304 protected:
305 friend struct AsyncEventLoop;
306
307 bool shouldCallCallback = true;
308 bool* hasBeenReactivated = nullptr;
309
310 SC::Result& returnCode;
311};
312
316template <typename T, typename C>
318{
319 T& getAsync() { return static_cast<T&>(AsyncResult::async); }
320 const T& getAsync() const { return static_cast<const T&>(AsyncResult::async); }
321
323
324 C completionData;
325 int32_t eventIndex = 0;
326};
327
332struct SC_ASYNC_EXPORT AsyncLoopTimeout : public AsyncRequest
333{
334 AsyncLoopTimeout() : AsyncRequest(Type::LoopTimeout) {}
335
338 using AsyncRequest::start;
339
341 SC::Result start(AsyncEventLoop& eventLoop, TimeMs relativeTimeout);
342
346 SC::Result unschedule(AsyncEventLoop& eventLoop);
347
348 Function<void(Result&)> callback;
349
351
353 TimeMs getExpirationTime() const { return expirationTime; }
354
355 private:
356 SC::Result validate(AsyncEventLoop&);
357 friend struct AsyncEventLoop;
358 TimeMs expirationTime;
359};
360
363{
366 bool coalesce = true;
367};
368
389struct SC_ASYNC_EXPORT AsyncLoopWakeUp : public AsyncRequest
390{
391 AsyncLoopWakeUp() : AsyncRequest(Type::LoopWakeUp) {}
392
394 {
395 uint32_t deliveryCount = 1;
396 };
397
399
401 SC::Result start(AsyncEventLoop& eventLoop, AsyncLoopWakeUpOptions options = {});
402
404 SC::Result start(AsyncEventLoop& eventLoop, EventObject& eventObject, AsyncLoopWakeUpOptions options = {});
405
407 SC::Result wakeUp(AsyncEventLoop& eventLoop);
408
409 Function<void(Result&)> callback;
410 EventObject* eventObject = nullptr;
411
412 private:
413 friend struct AsyncEventLoop;
414 SC::Result validate(AsyncEventLoop&);
415 int32_t consumePendingWakeUps();
416 int32_t getPendingWakeUps() const;
417
418 AsyncLoopWakeUpOptions wakeUpOptions;
419 Atomic<int32_t> pendingWakeUps = 0;
420};
421
430struct SC_ASYNC_EXPORT AsyncProcessExit : public AsyncRequest
431{
432 AsyncProcessExit() : AsyncRequest(Type::ProcessExit) {}
433
435 {
436 int exitStatus;
437 };
438
439 struct Result : public AsyncResultOf<AsyncProcessExit, CompletionData>
440 {
441 using AsyncResultOf<AsyncProcessExit, CompletionData>::AsyncResultOf;
442
443 SC::Result get(int& status)
444 {
445 status = completionData.exitStatus;
446 return returnCode;
447 }
448 };
449 using AsyncRequest::start;
450
454 SC::Result start(AsyncEventLoop& eventLoop, FileDescriptor::Handle process);
455
456 Function<void(Result&)> callback;
457
458 private:
459 friend struct AsyncEventLoop;
460 SC::Result validate(AsyncEventLoop&);
461
462 FileDescriptor::Handle handle = FileDescriptor::Invalid;
463#if SC_PLATFORM_WINDOWS
464 detail::WinOverlappedOpaque overlapped;
465 detail::WinWaitHandle waitHandle;
466 AsyncEventLoop* eventLoop = nullptr;
467#elif SC_PLATFORM_LINUX
468 FileDescriptor pidFd;
469#endif
470};
471
474{
479 enum class Mode : uint8_t
480 {
481 Persistent,
482 OneShot
483 };
485 bool coalesce = true;
486};
487
507struct SC_ASYNC_EXPORT AsyncSignal : public AsyncRequest
508{
509 AsyncSignal() : AsyncRequest(Type::Signal) {}
510
512 {
513 int signalNumber = 0;
514 uint32_t deliveryCount = 1;
515 };
516
517 struct Result : public AsyncResultOf<AsyncSignal, CompletionData>
518 {
519 using AsyncResultOf<AsyncSignal, CompletionData>::AsyncResultOf;
520 };
521 using AsyncRequest::start;
522
524 SC::Result start(AsyncEventLoop& eventLoop, int num, AsyncSignalOptions options = {});
525
526 Function<void(Result&)> callback;
527
528 private:
529 friend struct AsyncEventLoop;
530 SC::Result validate(AsyncEventLoop&);
531
532 int signalNumber = 0;
533 AsyncSignalOptions signalOptions;
534#if SC_PLATFORM_WINDOWS
535 detail::WinOverlappedOpaque overlapped;
536 AsyncEventLoop* eventLoop = nullptr;
537#elif SC_PLATFORM_LINUX
538 FileDescriptor signalFd;
539 FileDescriptor::Handle signalFdHandle = FileDescriptor::Invalid;
540#endif
541};
542
543struct AsyncSocketAccept;
544namespace detail
545{
548struct SC_ASYNC_EXPORT AsyncSocketAcceptData
549{
550#if SC_PLATFORM_WINDOWS
551 void (*pAcceptEx)() = nullptr;
552 detail::WinOverlappedOpaque overlapped;
553 SocketDescriptor clientSocket;
554 uint8_t acceptBuffer[288] = {0};
555#elif SC_PLATFORM_LINUX
556 AlignedStorage<128> sockAddrHandle;
557 uint32_t sockAddrLen;
558#endif
559};
560
562struct SC_ASYNC_EXPORT AsyncSocketAcceptBase : public AsyncRequest
563{
564 AsyncSocketAcceptBase() : AsyncRequest(Type::SocketAccept) {}
565
566 struct CompletionData : public AsyncCompletionData
567 {
568 SocketDescriptor acceptedClient;
569 };
570
571 struct Result : public AsyncResultOf<AsyncSocketAccept, CompletionData>
572 {
573 using AsyncResultOf<AsyncSocketAccept, CompletionData>::AsyncResultOf;
574
575 SC::Result moveTo(SocketDescriptor& client)
576 {
577 SC_TRY(returnCode);
578 return SC::Result(client.assign(move(completionData.acceptedClient)));
579 }
580 };
581 using AsyncRequest::start;
582
584 SC::Result start(AsyncEventLoop& eventLoop, const SocketDescriptor& socketDescriptor, AsyncSocketAcceptData& data);
585 SC::Result validate(AsyncEventLoop&);
586
587 Function<void(Result&)> callback;
588 SocketDescriptor::Handle handle = SocketDescriptor::Invalid;
589 SocketFlags::AddressFamily addressFamily = SocketFlags::AddressFamilyIPV4;
590 AsyncSocketAcceptData* acceptData = nullptr;
591};
592
593} // namespace detail
594
604struct SC_ASYNC_EXPORT AsyncSocketAccept : public detail::AsyncSocketAcceptBase
605{
606 AsyncSocketAccept() { AsyncSocketAcceptBase::acceptData = &data; }
607 using AsyncSocketAcceptBase::start;
608
610 SC::Result start(AsyncEventLoop& eventLoop, const SocketDescriptor& socketDescriptor);
611
612 private:
613 detail::AsyncSocketAcceptData data;
614};
615
624struct SC_ASYNC_EXPORT AsyncSocketConnect : public AsyncRequest
625{
626 AsyncSocketConnect() : AsyncRequest(Type::SocketConnect) {}
627
630 using AsyncRequest::start;
631
633 SC::Result start(AsyncEventLoop& eventLoop, const SocketDescriptor& descriptor, SocketIPAddress address);
634 SC::Result start(AsyncEventLoop& eventLoop, const SocketDescriptor& descriptor, SocketAddress address);
635
636 Function<void(Result&)> callback;
637
638 SocketDescriptor::Handle handle = SocketDescriptor::Invalid;
639 SocketAddress address;
640
641 private:
642 friend struct AsyncEventLoop;
643 SC::Result validate(AsyncEventLoop&);
644
645#if SC_PLATFORM_WINDOWS
646 void (*pConnectEx)() = nullptr;
647 detail::WinOverlappedOpaque overlapped;
648#else
649 SC::Result immediateConnectResult{true};
650#endif
651};
652
661struct SC_ASYNC_EXPORT AsyncSocketSend : public AsyncRequest
662{
663 AsyncSocketSend() : AsyncRequest(Type::SocketSend) {}
665 {
666 size_t numBytes = 0;
667 };
669 using AsyncRequest::start;
670
672 SC::Result start(AsyncEventLoop& eventLoop, const SocketDescriptor& descriptor, Span<const char> data);
673
675 SC::Result start(AsyncEventLoop& eventLoop, const SocketDescriptor& descriptor, Span<Span<const char>> data);
676
677 Function<void(Result&)> callback;
678
679 SocketDescriptor::Handle handle = SocketDescriptor::Invalid;
680
681 SC::Result closeHandle() { return detail::SocketDescriptorDefinition::releaseHandle(handle); }
682
683 Span<const char> buffer;
684 Span<Span<const char>> buffers;
685 bool singleBuffer = true;
686
687 protected:
688 AsyncSocketSend(Type type) : AsyncRequest(type) {}
689 friend struct AsyncEventLoop;
690 SC::Result validate(AsyncEventLoop&);
691
692 size_t totalBytesWritten = 0;
693#if SC_PLATFORM_WINDOWS
694 detail::WinOverlappedOpaque overlapped;
695#endif
696};
697
707struct SC_ASYNC_EXPORT AsyncSocketSendTo : public AsyncSocketSend
708{
709 AsyncSocketSendTo() : AsyncSocketSend(Type::SocketSendTo) {}
710
711 SocketAddress address;
712
713 SC::Result start(AsyncEventLoop& eventLoop, const SocketDescriptor& descriptor, SocketIPAddress ipAddress,
714 Span<const char> data);
715
716 SC::Result start(AsyncEventLoop& eventLoop, const SocketDescriptor& descriptor, SocketIPAddress ipAddress,
717 Span<Span<const char>> data);
718
719 SC::Result start(AsyncEventLoop& eventLoop, const SocketDescriptor& descriptor, SocketAddress socketAddress,
720 Span<const char> data);
721
722 SC::Result start(AsyncEventLoop& eventLoop, const SocketDescriptor& descriptor, SocketAddress socketAddress,
723 Span<Span<const char>> data);
724
725 private:
726 using AsyncSocketSend::start;
727 friend struct AsyncEventLoop;
728 SC::Result validate(AsyncEventLoop&);
729#if SC_PLATFORM_LINUX
730 AlignedStorage<56> typeErasedMsgHdr;
731#endif
732};
733
745struct SC_ASYNC_EXPORT AsyncSocketReceive : public AsyncRequest
746{
747 AsyncSocketReceive() : AsyncRequest(Type::SocketReceive) {}
748
750 {
751 size_t numBytes = 0;
752 bool disconnected = false;
753 bool truncated = false;
754 };
755
756 struct Result : public AsyncResultOf<AsyncSocketReceive, CompletionData>
757 {
758 using AsyncResultOf<AsyncSocketReceive, CompletionData>::AsyncResultOf;
759
760 bool isEnded() const { return completionData.disconnected; }
761
762 bool isTruncated() const { return completionData.truncated; }
763
767 SC::Result get(Span<char>& outData)
768 {
769 SC_TRY(getAsync().buffer.sliceStartLength(0, completionData.numBytes, outData));
770 return returnCode;
771 }
772
776
779 };
780 using AsyncRequest::start;
781
783 SC::Result start(AsyncEventLoop& eventLoop, const SocketDescriptor& descriptor, Span<char> data);
784
785 Function<void(Result&)> callback;
786
787 Span<char> buffer;
788 SocketDescriptor::Handle handle = SocketDescriptor::Invalid;
789
790 SC::Result closeHandle() { return detail::SocketDescriptorDefinition::releaseHandle(handle); }
791
792 protected:
793 AsyncSocketReceive(Type type) : AsyncRequest(type) {}
794 friend struct AsyncEventLoop;
795 SC::Result validate(AsyncEventLoop&);
796#if SC_PLATFORM_WINDOWS
797 detail::WinOverlappedOpaque overlapped;
798#endif
799};
800
810struct SC_ASYNC_EXPORT AsyncSocketReceiveFrom : public AsyncSocketReceive
811{
812 AsyncSocketReceiveFrom() : AsyncSocketReceive(Type::SocketReceiveFrom) {}
813 using AsyncSocketReceive::start;
814
815 private:
816 SocketAddress address;
817 friend struct AsyncSocketReceive;
818 friend struct AsyncEventLoop;
819#if SC_PLATFORM_LINUX
820 AlignedStorage<56> typeErasedMsgHdr;
821#elif SC_PLATFORM_WINDOWS
822 unsigned long receiveFlags = 0;
823 int addressSize = 0;
824 bool truncatedSync = false;
825#endif
826};
827
850struct SC_ASYNC_EXPORT AsyncFileRead : public AsyncRequest
851{
852 AsyncFileRead() : AsyncRequest(Type::FileRead) { handle = FileDescriptor::Invalid; }
853
855 {
856 size_t numBytes = 0;
857 bool endOfFile = false;
858 };
859
860 struct Result : public AsyncResultOf<AsyncFileRead, CompletionData>
861 {
862 using AsyncResultOf<AsyncFileRead, CompletionData>::AsyncResultOf;
863
864 bool isEnded() const { return completionData.endOfFile; }
865
866 SC::Result get(Span<char>& data)
867 {
868 SC_TRY(getAsync().buffer.sliceStartLength(0, completionData.numBytes, data));
869 return returnCode;
870 }
871 };
872 using AsyncRequest::start;
873
875 SC::Result start(AsyncEventLoop& eventLoop, const FileDescriptor& descriptor, Span<char> data);
876
877 Function<void(Result&)> callback;
878 Span<char> buffer;
879 FileDescriptor::Handle handle;
881
882 SC::Result closeHandle() { return detail::FileDescriptorDefinition::releaseHandle(handle); }
883
885 uint64_t getOffset() const { return offset; }
886
889 void setOffset(uint64_t fileOffset)
890 {
891 useOffset = true;
892 offset = fileOffset;
893 }
894
895 private:
896 friend struct AsyncEventLoop;
897 SC::Result validate(AsyncEventLoop&);
898
899 bool useOffset = false;
900 bool endedSync = false;
901
902 uint64_t offset = 0;
903#if SC_PLATFORM_WINDOWS
904 uint64_t readCursor = 0;
905 detail::WinOverlappedOpaque overlapped;
906#endif
907};
908
930struct SC_ASYNC_EXPORT AsyncFileWrite : public AsyncRequest
931{
932 AsyncFileWrite() : AsyncRequest(Type::FileWrite) { handle = FileDescriptor::Invalid; }
933
935 {
936 size_t numBytes = 0;
937 };
938
939 struct Result : public AsyncResultOf<AsyncFileWrite, CompletionData>
940 {
941 using AsyncResultOf<AsyncFileWrite, CompletionData>::AsyncResultOf;
942
943 SC::Result get(size_t& writtenSizeInBytes)
944 {
945 writtenSizeInBytes = completionData.numBytes;
946 return returnCode;
947 }
948 };
949
950 using AsyncRequest::start;
951
953 SC::Result start(AsyncEventLoop& eventLoop, const FileDescriptor& descriptor, Span<Span<const char>> data);
954
956 SC::Result start(AsyncEventLoop& eventLoop, Span<Span<const char>> data);
957
959 SC::Result start(AsyncEventLoop& eventLoop, const FileDescriptor& descriptor, Span<const char> data);
960
962 SC::Result start(AsyncEventLoop& eventLoop, Span<const char> data);
963
964 Function<void(Result&)> callback;
965
966 FileDescriptor::Handle handle;
968
969 SC::Result closeHandle() { return detail::FileDescriptorDefinition::releaseHandle(handle); }
970
971 Span<const char> buffer;
972 Span<Span<const char>> buffers;
973 bool singleBuffer = true;
974
976 uint64_t getOffset() const { return offset; }
977
980 void setOffset(uint64_t fileOffset)
981 {
982 useOffset = true;
983 offset = fileOffset;
984 }
985
986 private:
987 friend struct AsyncEventLoop;
988 SC::Result validate(AsyncEventLoop&);
989
990#if SC_PLATFORM_WINDOWS
991 bool endedSync = false;
992#else
993 bool isWatchable = false;
994#endif
995 bool useOffset = false;
996 uint64_t offset = 0xffffffffffffffff;
997
998 size_t totalBytesWritten = 0;
999#if SC_PLATFORM_WINDOWS
1000 detail::WinOverlappedOpaque overlapped;
1001#endif
1002};
1003
1007struct SC_ASYNC_EXPORT AsyncFileReadiness : public AsyncRequest
1008{
1009 AsyncFileReadiness() : AsyncRequest(Type::FileReadiness) {}
1010
1013
1015 SC::Result start(AsyncEventLoop& eventLoop, FileDescriptor::Handle fileDescriptor);
1016
1017 Function<void(Result&)> callback;
1018
1019 private:
1020 friend struct AsyncEventLoop;
1021 SC::Result validate(AsyncEventLoop&);
1022
1023 FileDescriptor::Handle handle = FileDescriptor::Invalid;
1024};
1025
1029struct SC_ASYNC_EXPORT AsyncExternalCompletion : public AsyncRequest
1030{
1032 {
1033 size_t bytesTransferred = 0;
1034 };
1036
1037 AsyncExternalCompletion() : AsyncRequest(Type::ExternalCompletion) {}
1038
1040 SC::Result start(AsyncEventLoop& eventLoop);
1041
1042#if SC_PLATFORM_WINDOWS
1046 SC::Result start(AsyncEventLoop& eventLoop, FileDescriptor::Handle fileDescriptor);
1047
1049 [[nodiscard]] void* getWindowsOverlapped();
1050#endif
1051
1054
1057
1058 [[nodiscard]] bool hasSubmissionPending() const { return submissionPending; }
1059
1060 Function<void(Result&)> callback;
1061
1062 private:
1063 friend struct AsyncEventLoop;
1064 SC::Result validate(AsyncEventLoop&);
1065
1066 FileDescriptor::Handle handle = FileDescriptor::Invalid;
1067 size_t bytesTransferred = 0;
1068 bool manualMode = true;
1069 bool submissionPending = false;
1070 bool completionPosted = false;
1071#if SC_PLATFORM_WINDOWS
1072 detail::WinOverlappedOpaque overlapped;
1073#endif
1074};
1075
1100struct SC_ASYNC_EXPORT AsyncFileSend : public AsyncRequest
1101{
1102 AsyncFileSend() : AsyncRequest(Type::FileSend) {}
1103
1105 {
1106 size_t bytesTransferred = 0;
1107 bool usedZeroCopy = false;
1108 };
1109
1110 struct Result : public AsyncResultOf<AsyncFileSend, CompletionData>
1111 {
1112 using AsyncResultOf<AsyncFileSend, CompletionData>::AsyncResultOf;
1113
1115 [[nodiscard]] size_t getBytesTransferred() const { return completionData.bytesTransferred; }
1116
1118 [[nodiscard]] bool usedZeroCopy() const { return completionData.usedZeroCopy; }
1119
1121 [[nodiscard]] bool isComplete() const
1122 {
1123 return returnCode && completionData.bytesTransferred == getAsync().length;
1124 }
1125 };
1126
1127 using AsyncRequest::start;
1128
1138 SC::Result start(AsyncEventLoop& eventLoop, const FileDescriptor& file, const SocketDescriptor& socket,
1139 int64_t offset = 0, size_t length = 0, size_t pipeSize = 0);
1140
1141 Function<void(Result&)> callback;
1142
1143 // Internal handles (set by start())
1144 FileDescriptor::Handle fileHandle = FileDescriptor::Invalid;
1145 SocketDescriptor::Handle socketHandle = SocketDescriptor::Invalid;
1146
1147 int64_t offset = 0;
1148 size_t length = 0;
1149 size_t bytesSent = 0;
1150 private:
1151 friend struct AsyncEventLoop;
1152 SC::Result validate(AsyncEventLoop&);
1153
1154#if SC_PLATFORM_WINDOWS
1155 detail::WinOverlappedOpaque overlapped;
1156#elif SC_PLATFORM_LINUX
1157 size_t pipeBufferSize = 0;
1158 PipeDescriptor splicePipe;
1159 size_t spliceBytesPending = 0;
1160#endif
1161};
1162
1163// forward declared because it must be defined after AsyncTaskSequence
1164struct AsyncLoopWork;
1166
1168{
1169 FileDescriptor::Handle handle = FileDescriptor::Invalid; // for open
1170
1171 int code = 0; // for open/close
1172 size_t numBytes = 0; // for read
1173};
1174
1175namespace detail
1176{
1177// A simple hand-made variant of all completion types
1178struct SC_ASYNC_EXPORT AsyncCompletionVariant
1179{
1180 AsyncCompletionVariant() {}
1181 ~AsyncCompletionVariant() { destroy(); }
1182
1183 AsyncCompletionVariant(const AsyncCompletionVariant&) = delete;
1184 AsyncCompletionVariant(AsyncCompletionVariant&&) = delete;
1185 AsyncCompletionVariant& operator=(const AsyncCompletionVariant&) = delete;
1186 AsyncCompletionVariant& operator=(AsyncCompletionVariant&&) = delete;
1187
1188 bool inited = false;
1189
1190 AsyncRequest::Type type;
1191 union
1192 {
1193 AsyncCompletionData completionDataLoopWork; // Defined after AsyncCompletionVariant / AsyncTaskSequence
1194 AsyncLoopTimeout::CompletionData completionDataLoopTimeout;
1195 AsyncLoopWakeUp::CompletionData completionDataLoopWakeUp;
1196 AsyncProcessExit::CompletionData completionDataProcessExit;
1197 AsyncSignal::CompletionData completionDataSignal;
1198 AsyncSocketAccept::CompletionData completionDataSocketAccept;
1199 AsyncSocketConnect::CompletionData completionDataSocketConnect;
1200 AsyncSocketSend::CompletionData completionDataSocketSend;
1201 AsyncSocketSendTo::CompletionData completionDataSocketSendTo;
1202 AsyncSocketReceive::CompletionData completionDataSocketReceive;
1203 AsyncSocketReceiveFrom::CompletionData completionDataSocketReceiveFrom;
1204 AsyncFileRead::CompletionData completionDataFileRead;
1205 AsyncFileWrite::CompletionData completionDataFileWrite;
1206 AsyncFileSend::CompletionData completionDataFileSend;
1207 AsyncFileReadiness::CompletionData completionDataFileReadiness;
1208 AsyncExternalCompletion::CompletionData completionDataExternalCompletion;
1209
1210 AsyncFileSystemOperationCompletionData completionDataFileSystemOperation;
1211 };
1212
1213 auto& getCompletion(AsyncLoopWork&) { return completionDataLoopWork; }
1214 auto& getCompletion(AsyncLoopTimeout&) { return completionDataLoopTimeout; }
1215 auto& getCompletion(AsyncLoopWakeUp&) { return completionDataLoopWakeUp; }
1216 auto& getCompletion(AsyncProcessExit&) { return completionDataProcessExit; }
1217 auto& getCompletion(AsyncSignal&) { return completionDataSignal; }
1218 auto& getCompletion(AsyncSocketAccept&) { return completionDataSocketAccept; }
1219 auto& getCompletion(AsyncSocketConnect&) { return completionDataSocketConnect; }
1220 auto& getCompletion(AsyncSocketSend&) { return completionDataSocketSend; }
1221 auto& getCompletion(AsyncSocketReceive&) { return completionDataSocketReceive; }
1222 auto& getCompletion(AsyncFileRead&) { return completionDataFileRead; }
1223 auto& getCompletion(AsyncFileWrite&) { return completionDataFileWrite; }
1224 auto& getCompletion(AsyncFileSend&) { return completionDataFileSend; }
1225 auto& getCompletion(AsyncFileReadiness&) { return completionDataFileReadiness; }
1226 auto& getCompletion(AsyncExternalCompletion&) { return completionDataExternalCompletion; }
1227 auto& getCompletion(AsyncFileSystemOperation&) { return completionDataFileSystemOperation; }
1228
1229 template <typename T>
1230 auto& construct(T& t)
1231 {
1232 destroy();
1233 placementNew(getCompletion(t));
1234 inited = true;
1235 type = t.getType();
1236 return getCompletion(t);
1237 }
1238 void destroy();
1239};
1240} // namespace detail
1241
1245struct SC_ASYNC_EXPORT AsyncTaskSequence : public AsyncSequence
1246{
1247 protected:
1248 ThreadPoolTask task;
1249 ThreadPool* threadPool = nullptr;
1250
1251 friend struct AsyncEventLoop;
1252 friend struct AsyncRequest;
1253
1254 detail::AsyncCompletionVariant completion;
1255
1256 SC::Result returnCode = SC::Result(true);
1257};
1258
1264struct SC_ASYNC_EXPORT AsyncLoopWork : public AsyncRequest
1265{
1266 AsyncLoopWork() : AsyncRequest(Type::LoopWork) {}
1267
1270
1273 SC::Result setThreadPool(ThreadPool& threadPool, AsyncThreadPoolMode mode = AsyncThreadPoolMode::NativePreferred);
1274
1275 Function<SC::Result()> work;
1276 Function<void(Result&)> callback;
1277
1278 private:
1279 friend struct AsyncEventLoop;
1280 SC::Result validate(AsyncEventLoop&);
1281 AsyncTaskSequence task;
1282};
1283
1317struct SC_ASYNC_EXPORT AsyncFileSystemOperation : public AsyncRequest
1318{
1319 AsyncFileSystemOperation() : AsyncRequest(Type::FileSystemOperation) {}
1320 ~AsyncFileSystemOperation() { destroy(); }
1321#ifdef CopyFile
1322#undef CopyFile
1323#endif
1324#ifdef RemoveDirectory
1325#undef RemoveDirectory
1326#endif
1327 enum class Operation
1328 {
1329 None = 0,
1330 Open,
1331 Close,
1332 Read,
1333 Write,
1334 CopyFile,
1335 CopyDirectory,
1336 Rename,
1337 RemoveDirectory,
1338 RemoveFile,
1339 };
1340
1343
1345 SC::Result setThreadPool(ThreadPool& threadPool, AsyncThreadPoolMode mode = AsyncThreadPoolMode::NativePreferred);
1346
1348 SC::Result stop(AsyncEventLoop& eventLoop, Function<void(AsyncResult&)>* afterStopped = nullptr);
1349
1350 Function<void(Result&)> callback;
1351
1357 SC::Result open(AsyncEventLoop& eventLoop, StringSpan path, FileOpen mode);
1358
1363 SC::Result close(AsyncEventLoop& eventLoop, FileDescriptor::Handle handle);
1364
1371 SC::Result read(AsyncEventLoop& eventLoop, FileDescriptor::Handle handle, Span<char> buffer, uint64_t offset);
1372
1379 SC::Result write(AsyncEventLoop& eventLoop, FileDescriptor::Handle handle, Span<const char> buffer,
1380 uint64_t offset);
1381
1388 SC::Result copyFile(AsyncEventLoop& eventLoop, StringSpan path, StringSpan destinationPath,
1390
1397 SC::Result copyDirectory(AsyncEventLoop& eventLoop, StringSpan path, StringSpan destinationPath,
1399
1405 SC::Result rename(AsyncEventLoop& eventLoop, StringSpan path, StringSpan newPath);
1406
1412 SC::Result removeEmptyDirectory(AsyncEventLoop& eventLoop, StringSpan path);
1413
1418 SC::Result removeFile(AsyncEventLoop& eventLoop, StringSpan path);
1419
1420 private:
1421 friend struct AsyncEventLoop;
1422 Operation operation = Operation::None;
1423 AsyncThreadPoolMode threadPoolMode = AsyncThreadPoolMode::NativePreferred;
1424 AsyncLoopWork loopWork;
1425 CompletionData completionData;
1426
1427 void onOperationCompleted(AsyncLoopWork::Result& res);
1428
1429 struct FileDescriptorData
1430 {
1431 FileDescriptor::Handle handle;
1432 };
1433
1434 struct OpenData
1435 {
1436 StringSpan path;
1437 FileOpen mode;
1438 };
1439
1440 struct ReadData
1441 {
1442 FileDescriptor::Handle handle;
1443 Span<char> buffer;
1444 uint64_t offset;
1445 };
1446
1447 struct WriteData
1448 {
1449 FileDescriptor::Handle handle;
1450 Span<const char> buffer;
1451 uint64_t offset;
1452 };
1453
1454 struct CopyFileData
1455 {
1456 StringSpan path;
1457 StringSpan destinationPath;
1458 FileSystemCopyFlags copyFlags;
1459 };
1460
1461 using CopyDirectoryData = CopyFileData;
1462
1463 using CloseData = FileDescriptorData;
1464
1465 struct RenameData
1466 {
1467 StringSpan path;
1468 StringSpan newPath;
1469 };
1470
1471 struct RemoveData
1472 {
1473 StringSpan path;
1474 };
1475
1476 union
1477 {
1478 OpenData openData;
1479 CloseData closeData;
1480 ReadData readData;
1481 WriteData writeData;
1482 CopyFileData copyFileData;
1483 CopyDirectoryData copyDirectoryData;
1484 RenameData renameData;
1485 RemoveData removeData;
1486 };
1487
1488 void destroy();
1489
1490 SC::Result start(AsyncEventLoop& eventLoop, FileDescriptor::Handle fileDescriptor);
1491 SC::Result validate(AsyncEventLoop&);
1492};
1493
1497struct SC_ASYNC_EXPORT AsyncKernelEvents
1498{
1499 Span<uint8_t> eventsMemory;
1500
1501 private:
1502 int numberOfEvents = 0;
1503 friend struct AsyncEventLoop;
1504 friend struct AsyncEventLoopMonitor;
1505};
1506
1508struct SC_ASYNC_EXPORT AsyncEventLoopListeners
1509{
1510 Function<void(AsyncEventLoop&)> beforeBlockingPoll;
1511 Function<void(AsyncEventLoop&)> afterBlockingPoll;
1512};
1513
1520struct SC_ASYNC_EXPORT AsyncEventLoop
1521{
1523 struct Options
1524 {
1525 enum class ApiType : uint8_t
1526 {
1527 Automatic = 0,
1528 ForceUseIoUring,
1529 ForceUseEpoll,
1530 };
1532
1533 Options() { apiType = ApiType::Automatic; }
1534 };
1535
1537
1538 AsyncEventLoop(const AsyncEventLoop&) = delete;
1539 AsyncEventLoop(AsyncEventLoop&&) = delete;
1540 AsyncEventLoop& operator=(AsyncEventLoop&&) = delete;
1541 AsyncEventLoop& operator=(const AsyncEventLoop&) = delete;
1542
1544 Result create(Options options = Options());
1545
1547 Result close();
1548
1551 Result start(AsyncRequest& async);
1552
1554 Result postExternalCompletion(AsyncExternalCompletion& async, size_t bytesTransferred = 0);
1555
1559
1561 [[nodiscard]] bool isInitialized() const;
1562
1564 [[nodiscard]] bool needsThreadPoolForFileOperations() const;
1565
1573 Result run();
1574
1584 Result runOnce();
1585
1591 Result runNoWait();
1592
1597 Result submitRequests(AsyncKernelEvents& kernelEvents);
1598
1619 Result blockingPoll(AsyncKernelEvents& kernelEvents);
1620
1628
1632
1635
1638
1641
1644 SocketFlags::ProtocolType protocol, SocketDescriptor& outDescriptor);
1645
1648
1650 Result associateExternallyCreatedSocketHandle(SocketDescriptor::Handle handle);
1651
1654
1656 Result associateExternallyCreatedFileDescriptorHandle(FileDescriptor::Handle handle);
1657
1659 static Result removeAllAssociationsFor(SocketDescriptor& outDescriptor);
1660
1662 static Result removeAllAssociationsForSocketHandle(SocketDescriptor::Handle handle);
1663
1665 static Result removeAllAssociationsFor(FileDescriptor& outDescriptor);
1666
1668 static Result removeAllAssociationsForFileDescriptorHandle(FileDescriptor::Handle handle);
1669
1672
1674 [[nodiscard]] TimeMs getLoopTime() const;
1675
1677 [[nodiscard]] int getNumberOfActiveRequests() const;
1678
1680 [[nodiscard]] int getNumberOfSubmittedRequests() const;
1681
1685
1690
1693
1698 void enumerateRequests(Function<void(AsyncRequest&)> enumerationCallback);
1699
1703
1705 [[nodiscard]] static bool isExcludedFromActiveCount(const AsyncRequest& async);
1706
1709 [[nodiscard]] static bool tryProbingIOUring();
1710
1713
1714 struct Internal;
1715
1717 using LoopWork = AsyncLoopWork;
1720 using Signal = AsyncSignal;
1727 using FileRead = AsyncFileRead;
1728 using FileWrite = AsyncFileWrite;
1729 using FileSend = AsyncFileSend;
1734 using ResultType = AsyncResult;
1735
1736 public:
1737 struct SC_ASYNC_EXPORT InternalDefinition
1738 {
1739 static constexpr int Windows = 584;
1740 static constexpr int Apple = 552;
1741 static constexpr int Linux = 816;
1742 static constexpr int Default = Linux;
1743
1744 static constexpr size_t Alignment = 8;
1745
1746 using Object = Internal;
1747 };
1748
1749 using InternalOpaque = OpaqueObject<InternalDefinition>;
1750
1751 private:
1752 InternalOpaque internalOpaque;
1753 Internal& internal;
1754
1755 friend struct AsyncRequest;
1756 friend struct AsyncLoopTimeout;
1757 friend struct AsyncFileWrite;
1758 friend struct AsyncFileRead;
1759 friend struct AsyncFileSystemOperation;
1760 friend struct AsyncResult;
1761};
1762
1766struct SC_ASYNC_EXPORT AsyncEventLoopMonitor
1767{
1768 Function<void(void)> onNewEventsAvailable;
1769
1772 Result create(AsyncEventLoop& eventLoop);
1773
1775 Result close();
1776
1784
1790
1791 private:
1792#if SC_COMPILER_MSVC
1793#pragma warning(push)
1794#pragma warning(disable : 4324) // useless warning on 32 bit... (structure was padded due to __declspec(align()))
1795#endif
1796 alignas(uint64_t) uint8_t eventsMemory[8 * 1024]; // 8 Kb of kernel events
1797#if SC_COMPILER_MSVC
1798#pragma warning(pop)
1799#endif
1800
1801 AsyncKernelEvents asyncKernelEvents;
1802 AsyncEventLoop* eventLoop = nullptr;
1803 AsyncLoopWakeUp eventLoopWakeUp;
1804
1805 Thread eventLoopThread;
1806 EventObject eventObjectEnterBlockingMode;
1807 EventObject eventObjectExitBlockingMode;
1808
1809 Atomic<bool> finished = false;
1810 Atomic<bool> needsWakeUp = true;
1811
1812 bool wakeUpHasBeenCalled = false;
1813
1814 Result monitoringLoopThread(Thread& thread);
1815};
1816
1817} // namespace SC
Empty base struct for all AsyncRequest-derived CompletionData (internal) structs.
Definition Async.h:282
Allow library user to provide callbacks signaling different phases of async event loop cycle.
Definition Async.h:1509
Monitors Async I/O events from a background thread using a blocking kernel function (no CPU usage on ...
Definition Async.h:1767
Function< void(void)> onNewEventsAvailable
Informs to call dispatchCompletions on GUI Event Loop.
Definition Async.h:1768
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:1524
ApiType apiType
Criteria to choose Async IO API.
Definition Async.h:1531
ApiType
Definition Async.h:1526
Asynchronous I/O (files, sockets, timers, processes, fs events, threads wake-up) (see Async) AsyncEve...
Definition Async.h:1521
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 ready requests if any, dispatching their completions, or returns immediately without blocking...
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 without running user callbacks.
void enumerateRequests(Function< void(AsyncRequest &)> enumerationCallback)
Enumerates user-visible request objects associated with this loop.
Result postExternalCompletion(AsyncExternalCompletion &async, size_t bytesTransferred=0)
Posts completion for an AsyncExternalCompletion started in manual mode.
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.
Result createAsyncSocket(SocketFlags::AddressFamily family, SocketFlags::SocketType socketType, SocketFlags::ProtocolType protocol, SocketDescriptor &outDescriptor)
Creates a non-blocking socket registered with the event loop.
AsyncLoopTimeout * findEarliestLoopTimeout() const
Returns the next AsyncLoopTimeout that will be executed (shortest relativeTimeout)
void setListeners(AsyncEventLoopListeners *listeners)
Sets listeners invoked around AsyncEventLoop::blockingPoll.
Result dispatchCompletions(AsyncKernelEvents &kernelEvents)
Invokes completions for the AsyncKernelEvents collected by a call to AsyncEventLoop::blockingPoll.
void interrupt()
Interrupts AsyncEventLoop::run, causing it to return even if counted active work remains.
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 ready completions.
void excludeFromActiveCount(AsyncRequest &async)
Excludes the request from active handles count so it does not keep AsyncEventLoop::run alive.
Result run()
Blocks until there are no more counted active, submitted, or cancelling requests, dispatching complet...
void includeInActiveCount(AsyncRequest &async)
Reverses the effect of excludeFromActiveCount for the request.
int getNumberOfActiveRequests() const
Obtain the total number of active requests.
Integrates externally-submitted completion based operations with AsyncEventLoop.
Definition Async.h:1030
SC::Result clearSubmissionPending()
Clears a pending submission after an external submission failed synchronously.
SC::Result start(AsyncEventLoop &eventLoop)
Starts a manual external completion. The request remains active until postExternalCompletion() or sto...
SC::Result markSubmissionPending()
Marks that a native/manual external operation has been submitted and must complete before reuse.
Definition Async.h:855
Definition Async.h:861
Starts a file read operation, reading bytes from a file (or pipe).
Definition Async.h:851
FileDescriptor::Handle handle
The writeable span of memory where to data will be written.
Definition Async.h:879
Span< char > buffer
Callback called when some data has been read from the file into the buffer.
Definition Async.h:878
SC::Result closeHandle()
The file/pipe descriptor handle to read data from.
Definition Async.h:882
void setOffset(uint64_t fileOffset)
Sets the offset in bytes at which start reading.
Definition Async.h:889
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:885
Starts a file descriptor readiness operation.
Definition Async.h:1008
SC::Result start(AsyncEventLoop &eventLoop, FileDescriptor::Handle fileDescriptor)
Starts a file descriptor poll operation, monitoring its readiness with appropriate OS API.
Definition Async.h:1105
Definition Async.h:1111
size_t getBytesTransferred() const
Get the number of bytes transferred.
Definition Async.h:1115
bool usedZeroCopy() const
Check if zero-copy was used for this transfer.
Definition Async.h:1118
bool isComplete() const
Check if the entire requested range was sent.
Definition Async.h:1121
Sends file contents to a socket using zero-copy when available (sendfile, TransmitFile).
Definition Async.h:1101
Function< void(Result &)> callback
Called when send completes or fails.
Definition Async.h:1141
SC::Result start(AsyncEventLoop &eventLoop, const FileDescriptor &file, const SocketDescriptor &socket, int64_t offset=0, size_t length=0, size_t pipeSize=0)
Start file send.
Starts an asynchronous file system operation (open, close, read, write, sendFile, stat,...
Definition Async.h:1318
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 setThreadPool(ThreadPool &threadPool, AsyncThreadPoolMode mode=AsyncThreadPoolMode::NativePreferred)
Sets the thread pool to use for the operation.
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 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:1350
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.
Definition Async.h:940
Starts a file write operation, writing bytes to a file (or pipe).
Definition Async.h:931
uint64_t getOffset() const
Returns the last offset set with AsyncFileWrite::setOffset.
Definition Async.h:976
FileDescriptor::Handle handle
The file/pipe descriptor to write data to.
Definition Async.h:966
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:980
Function< void(Result &)> callback
Callback called when descriptor is ready to be written with more data.
Definition Async.h:964
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:972
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:971
Allows user to supply a block of memory that will store kernel I/O events retrieved from AsyncEventLo...
Definition Async.h:1498
Span< uint8_t > eventsMemory
User supplied block of memory used to store kernel I/O events.
Definition Async.h:1499
Starts a Timeout that is invoked only once after expiration (relative) time has passed.
Definition Async.h:333
TimeMs getExpirationTime() const
Gets computed absolute expiration time that determines when this timeout get executed.
Definition Async.h:353
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:350
Function< void(Result &)> callback
Called after given expiration time since AsyncLoopTimeout::start has passed.
Definition Async.h:348
SC::Result unschedule(AsyncEventLoop &eventLoop)
Synchronously removes an unsequenced timeout from the event loop schedule without invoking its callba...
Options for AsyncLoopWakeUp configuration.
Definition Async.h:363
bool coalesce
Merge repeated pending wakeUp() calls into a single callback (default true, matching libuv uv_async_t...
Definition Async.h:366
Starts a wake-up operation, allowing threads to execute callbacks on loop thread.
Definition Async.h:390
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:409
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:1265
Function< void(Result &)> callback
Called to execute the work in a background threadpool thread.
Definition Async.h:1276
SC::Result setThreadPool(ThreadPool &threadPool, AsyncThreadPoolMode mode=AsyncThreadPoolMode::NativePreferred)
Sets the ThreadPool that will supply the thread to run the async work on.
Definition Async.h:440
Waits for a child process to exit and reports its exit status.
Definition Async.h:431
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:456
Base class for all async requests, holding state and type.
Definition Async.h:139
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:181
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:211
Function< void(AsyncResult &)> * getCloseCallback()
Returns currently set close callback (if any) passed to AsyncRequest::stop.
Definition Async.h:214
bool isActive() const
Returns true if this request is active or being reactivated.
Result executeOn(AsyncTaskSequence &task, ThreadPool &pool, AsyncThreadPoolMode mode=AsyncThreadPoolMode::NativePreferred)
Adds the request to be executed on a specific AsyncTaskSequence.
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:202
void setUserFlags(uint16_t externalFlags)
Sets user flags, holding some meaningful data for the caller.
Definition Async.h:208
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:159
Helper holding CompletionData for a specific AsyncRequest-derived class.
Definition Async.h:318
Base class for all async results (argument of completion callbacks).
Definition Async.h:288
const SC::Result & isValid() const
Check if the returnCode of this result is valid.
Definition Async.h:299
AsyncResult(AsyncEventLoop &eventLoop, AsyncRequest &request, SC::Result &res, bool *hasBeenReactivated=nullptr)
Constructs an async result from a request and a result.
Definition Async.h:290
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:264
Options for AsyncSignal request configuration.
Definition Async.h:474
Mode
Reserved signal watching policy.
Definition Async.h:480
@ Persistent
Default policy; future backend parity work may use it for automatic persistence.
@ OneShot
Future policy for explicit one-shot watchers.
Mode mode
Currently does not bypass the AsyncRequest reactivation contract.
Definition Async.h:484
bool coalesce
Backend hint; portable code should inspect CompletionData::deliveryCount.
Definition Async.h:485
Definition Async.h:512
Definition Async.h:518
Starts monitoring a signal, notifying about its reception.
Definition Async.h:508
Function< void(Result &)> callback
Called when the signal is raised.
Definition Async.h:526
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:605
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:625
Function< void(Result &)> callback
Called after socket is finally connected to endpoint.
Definition Async.h:636
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:811
Definition Async.h:757
SC::Result get(Span< char > &outData)
Get a Span of the actually read data.
Definition Async.h:767
SocketIPAddress getSourceAddress() const
Returns the source when it is an IPv4 or IPv6 address.
SocketAddress getSourceSocketAddress() const
Returns the family-neutral source address for receive-from operations.
Starts a socket receive operation, receiving bytes from a remote endpoint.
Definition Async.h:746
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:790
Span< char > buffer
The writeable span of memory where to data will be written.
Definition Async.h:787
Function< void(Result &)> callback
Called after data has been received.
Definition Async.h:785
Starts an unconnected socket send to operation, sending bytes to a remote endpoint.
Definition Async.h:708
Starts a socket send operation, sending bytes to a remote endpoint.
Definition Async.h:662
Function< void(Result &)> callback
Called when socket is ready to send more data.
Definition Async.h:677
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:684
Span< const char > buffer
Span of bytes to send (singleBuffer == true)
Definition Async.h:683
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:1246
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:77
Read / Write pipe (Process stdin/stdout and IPC communication)
Definition File.h:302
Family-neutral native socket address.
Definition Socket.h:168
Low-level OS socket handle.
Definition Socket.h:207
SocketType
Sets the socket type to datagram or stream.
Definition Socket.h:82
AddressFamily
Sets the socket address family.
Definition Socket.h:74
ProtocolType
Sets the socket protocol type.
Definition Socket.h:89
Native representation of an IP Address.
Definition Socket.h:117
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:45
A native OS thread.
Definition Threading.h:127