29 type = chanType->getInner();
31 if (translationType) {
32 this->type = translationType->getIntoType();
33 this->
translationInfo = std::make_unique<TranslationInfo>(translationType);
46 throw std::runtime_error(
"Channel '" + name +
"' not found");
49 throw std::runtime_error(
"Channel '" + name +
"' is not a write channel");
56 throw std::runtime_error(
"Channel '" + name +
"' not found");
59 throw std::runtime_error(
"Channel '" + name +
"' is not a read channel");
89 std::unique_ptr<SegmentedMessageData> &msg) {
99 assert(
callback &&
"Callback should be set in non-disconnected mode");
109 auto finish = [
this]() {
125 if (msg &&
type &&
type->getBitWidth() == 0) {
126 size_t size = msg->totalSize();
128 msg = std::make_unique<MessageData>();
130 throw std::runtime_error(
"zero-width message must be empty or use a "
131 "single-byte placeholder payload");
134 bool consumed = activeCallback(msg);
146 throw std::runtime_error(
"Channel already connected");
155 this->callback = [
this, cb = std::move(
callback)](
156 std::unique_ptr<SegmentedMessageData> &data) {
181 [cb = std::move(
callback)](std::unique_ptr<SegmentedMessageData> &data)
182 ->
bool {
return cb(data->toMessageData()); },
188 throw std::runtime_error(
"Channel already connected");
203 translate](std::unique_ptr<SegmentedMessageData> &msg) {
215 data = msg->toMessageData();
230 throw std::runtime_error(
231 "Cannot read from a callback channel. Call `connect()` without a "
232 "callback specified to use polling mode.");
234 throw std::runtime_error(
235 "Cannot read from a disconnected channel. `connect()` the channel "
236 "without a callback before calling `readAsync()`.");
253 for (
const auto &frame :
windowType->getFrames()) {
254 for (
const auto &field : frame.fields) {
255 if (field.bulkCountWidth > 0)
256 throw std::runtime_error(
257 "Window translation for serial (bulk) list encoding is not "
258 "implemented (window '" +
259 windowType->getName() +
"', frame '" + frame.name +
"', field '" +
261 "'). Connect the port with ConnectOptions{translateMessage=false} "
262 "and decode the frames manually.");
272 throw std::runtime_error(
273 "Window intoType must be a struct for translation");
275 const auto &intoFields = intoStruct->
getFields();
284 const Type *listElementType;
285 size_t listElementSize;
287 std::map<std::string, FieldInfo> fieldMap;
288 size_t currentOffset = 0;
291 auto processField = [&](
const std::string &name,
const Type *fieldType) {
292 auto *listType =
dynamic_cast<const ListType *
>(fieldType);
298 const Type *elemType = listType->getElementType();
301 throw std::runtime_error(
302 "Cannot translate list with dynamically-sized element type: " +
305 throw std::runtime_error(
306 "Cannot translate list with zero-width element type: " + name);
307 if (elemBits % 8 != 0)
308 throw std::runtime_error(
309 "Cannot translate list element with non-byte-aligned size: " +
311 size_t elemBytes = (
static_cast<size_t>(elemBits) + 7) / 8;
312 fieldMap[name] = {currentOffset, fieldType,
true, elemType, elemBytes};
316 currentOffset +=
sizeof(size_t);
319 std::ptrdiff_t fieldBits = fieldType->getBitWidth();
321 throw std::runtime_error(
"Cannot translate field with dynamic size: " +
323 if (fieldBits % 8 != 0)
324 throw std::runtime_error(
325 "Cannot translate field with non-byte-aligned size: " + name);
326 size_t fieldBytes = (
static_cast<size_t>(fieldBits) + 7) / 8;
327 fieldMap[name] = {currentOffset, fieldType,
false,
nullptr, 0};
328 currentOffset += fieldBytes;
333 for (
auto it = intoFields.rbegin(); it != intoFields.rend(); ++it)
334 processField(it->first, it->second);
336 for (
const auto &[name, fieldType] : intoFields)
337 processField(name, fieldType);
344 const auto &windowFrames =
windowType->getFrames();
346 frames.reserve(windowFrames.size());
348 for (
const auto &frame : windowFrames) {
350 size_t frameOffset = 0;
367 struct FrameFieldLayout {
373 size_t listElementSize;
375 const Type *listElementType;
377 std::vector<FrameFieldLayout> fieldLayouts;
379 for (
auto fieldIt = frame.fields.rbegin(); fieldIt != frame.fields.rend();
382 auto it = fieldMap.find(field.
name);
383 if (it == fieldMap.end())
384 throw std::runtime_error(
"Frame field '" + field.
name +
385 "' not found in intoType");
387 const FieldInfo &fieldInfo = it->second;
388 FrameFieldLayout layout;
389 layout.name = field.
name;
390 layout.bufferOffset = fieldInfo.offset;
391 layout.isList = fieldInfo.isList;
393 layout.listElementType = fieldInfo.listElementType;
394 layout.listElementSize = fieldInfo.listElementSize;
396 if (fieldInfo.isList) {
403 throw std::runtime_error(
404 "List translation with numItems > 1 is not yet supported. "
406 field.
name +
"' has numItems=" + std::to_string(numItems));
409 size_t lastOffset = frameOffset;
413 layout.frameOffset = frameOffset;
414 layout.size = fieldInfo.listElementSize;
415 fieldLayouts.push_back(layout);
416 frameOffset += layout.size;
429 std::ptrdiff_t fieldBits = fieldInfo.type->getBitWidth();
430 layout.frameOffset = frameOffset;
431 layout.size = (
static_cast<size_t>(fieldBits) + 7) / 8;
432 fieldLayouts.push_back(layout);
433 frameOffset += layout.size;
440 for (
const auto &layout : fieldLayouts) {
441 if (!layout.isList) {
444 {layout.frameOffset, layout.bufferOffset, layout.size});
453 return a.frameOffset < b.frameOffset;
457 if (!frameInfo.
copyOps.empty()) {
458 std::vector<CopyOp> mergedOps;
459 mergedOps.push_back(frameInfo.
copyOps[0]);
461 for (
size_t i = 1; i < frameInfo.
copyOps.size(); ++i) {
462 CopyOp &last = mergedOps.back();
469 mergedOps.push_back(current);
473 frameInfo.
copyOps = std::move(mergedOps);
476 frames.push_back(std::move(frameInfo));
482 std::ptrdiff_t loweredBits =
windowType->getLoweredType()->getBitWidth();
483 if (loweredBits > 0) {
487 for (
const auto &f :
frames)
494 "Translation type must be set for window translation.");
497 const uint8_t *frameData = data.getBytes();
498 size_t frameDataSize = data.size();
504 if (frameDataSize < frameInfo.expectedSize)
505 throw std::runtime_error(
"Frame data too small: expected at least " +
506 std::to_string(frameInfo.expectedSize) +
507 " bytes, got " + std::to_string(frameDataSize) +
524 for (
const auto &op : frameInfo.copyOps)
526 frameData + op.frameOffset, op.size);
529 if (frameInfo.listField.has_value()) {
530 const auto &listInfo = frameInfo.listField.value();
533 size_t bytesToCopy = listInfo.elementSize;
535 if (listInfo.dataOffset > frameDataSize)
536 throw std::runtime_error(
"List data offset is beyond frame bounds");
538 if (listInfo.dataOffset + bytesToCopy > frameDataSize)
539 throw std::runtime_error(
"List data extends beyond frame bounds");
543 frameData + listInfo.dataOffset, bytesToCopy);
546 uint8_t lastFlag = frameData[listInfo.lastFieldOffset];
552 size_t *listLengthPtr =
reinterpret_cast<size_t *
>(
554 *listLengthPtr = listLength;
591 "Translation type must be set for window translation.");
593 const uint8_t *srcData = data.getBytes();
594 size_t srcDataSize = data.size();
596 if (srcDataSize < translationInfo->intoTypeBytes)
597 throw std::runtime_error(
"Source data too small: expected at least " +
599 " bytes, got " + std::to_string(srcDataSize) +
606 std::vector<uint8_t> frameBuffer(frameInfo.expectedSize, 0);
607 for (
const auto &op : frameInfo.copyOps)
608 std::memcpy(frameBuffer.data() + op.frameOffset,
609 srcData + op.bufferOffset, op.size);
617 if (!frameInfo.listField.has_value()) {
619 std::vector<uint8_t> frameBuffer(frameInfo.expectedSize, 0);
620 for (
const auto &op : frameInfo.copyOps)
621 std::memcpy(frameBuffer.data() + op.frameOffset,
622 srcData + op.bufferOffset, op.size);
626 const auto &listInfo = frameInfo.listField.value();
629 size_t listLength = 0;
630 std::memcpy(&listLength, srcData + listInfo.listLengthBufferOffset,
634 if (
translationInfo->intoTypeBytes + (listLength * listInfo.elementSize) >
636 throw std::runtime_error(
637 "Source buffer too small for list data: possible corrupted or "
638 "inconsistent list length field");
644 size_t itemsRemaining = listLength;
645 size_t listDataOffset = 0;
649 throw std::runtime_error(
650 "Cannot send empty lists - parallel ESI list encoding requires at "
651 "least one frame to be sent, and each frame must contain at least "
654 while (itemsRemaining > 0) {
655 std::vector<uint8_t> frameBuffer(frameInfo.expectedSize, 0);
658 for (
const auto &op : frameInfo.copyOps)
659 std::memcpy(frameBuffer.data() + op.frameOffset,
660 srcData + op.bufferOffset, op.size);
663 size_t bytesInThisFrame = listInfo.elementSize;
666 std::memcpy(frameBuffer.data() + listInfo.dataOffset,
667 listData + listDataOffset, bytesInThisFrame);
671 listDataOffset += bytesInThisFrame;
674 frameBuffer[listInfo.lastFieldOffset] = (itemsRemaining == 0) ? 1 : 0;
682std::vector<MessageData>
685 assert(frameBytes > 0 &&
"Frame size must be greater than 0");
686 if (data.getSize() % frameBytes != 0)
687 throw std::runtime_error(
688 "write message size (" + std::to_string(data.getSize()) +
689 ") is not a multiple of frame size (" + std::to_string(frameBytes) +
690 ") on type " +
type->toString());
691 std::vector<MessageData> frames;
692 size_t numFrames = data.getSize() / frameBytes;
693 const uint8_t *ptr = data.getBytes();
694 for (
size_t i = 0; i < numFrames; ++i) {
695 frames.emplace_back(ptr, frameBytes);
716 std::lock_guard<std::recursive_mutex> lock(
mutex);
772 std::unique_lock<std::recursive_mutex> lock(
mutex, std::try_to_lock);
797 return DrainResult::Yielded;
805 return port.flushInternal() ? DrainResult::Idle
806 : DrainResult::Blocked;
808 port.discardPendingFrames();
809 onError(std::current_exception());
813 std::exception_ptr fetchError;
817 fetchError = std::current_exception();
836 return DrainResult::Blocked;
840 port.discardPendingFrames();
841 onError(std::current_exception());
844 return DrainResult::Stopped;
851 throw std::runtime_error(
852 std::string(
"Cannot call `") + method +
853 "()` on a write channel connected in callback mode. Use "
854 "`connect()` without callbacks.");
869 throw std::runtime_error(
"Channel already connected in callback mode");
876 throw std::runtime_error(
"Channel already connected");
878 throw std::runtime_error(
879 "Cannot connect in callback mode while a windowed message written in "
880 "sync mode has unsent frames. Reconnect in sync mode and flush() "
890 throw std::invalid_argument(
891 "WriteChannelPort::connect: null data fetch callback");
893 throw std::invalid_argument(
894 "WriteChannelPort::connect: null error callback");
895 auto writer = std::make_shared<DefaultAsyncWriter>(*
this, std::move(fetch),
912std::shared_ptr<WriteChannelPort::DefaultAsyncWriter>
919 std::shared_ptr<DefaultAsyncWriter> writer;
930 if (std::shared_ptr<DefaultAsyncWriter> writer =
getAsyncWriter())
939 std::shared_ptr<DefaultAsyncWriter> writer =
942 throw std::runtime_error(
943 "Cannot call `notifyAsyncDataAvailable()` on a write channel which "
944 "is not connected in callback mode.");
951 "Cannot call write() with pending translated messages");
967 "Translation buffer should be empty after successful flush");
assert(baseType &&"element must be base type")
ReadChannelPort & getRawRead(const std::string &name) const
WriteChannelPort & getRawWrite(const std::string &name) const
Get access to the raw byte streams of a channel.
BundlePort(AppID id, const BundleType *type, PortMap channels)
Construct a port.
Bundles represent a collection of channels.
size_t getFrameSizeBytes() const
Get the size of each frame in bytes.
virtual void connectImpl(const ConnectOptions &options)
Called by all connect methods to let backends initiate the underlying connections.
ChannelPort(const Type *type)
std::unique_ptr< TranslationInfo > translationInfo
bool poll()
Poll for incoming data.
virtual bool isConnected() const =0
Channels are the basic communication primitives.
Lists represent variable-length sequences of elements of a single type.
A concrete flat message backed by a single vector of bytes.
MessageData toMessageData() const override
Flatten all segments into a standard MessageData.
A ChannelPort which reads data from the accelerator.
std::mutex callbackMutex
Synchronizes callback revocation during disconnect.
virtual void connect(ReadCallback callback, const ConnectOptions &options={})
virtual std::future< MessageData > readAsync()
Asynchronous polling read.
size_t nextFrameIndex
Index of the next expected frame (for multi-frame windows).
std::vector< uint8_t > translationBuffer
Window translation support.
bool accumulatingListData
Flag to track whether we're in the middle of accumulating list data.
void resetTranslationState()
Reset translation state buffers and indices.
std::function< bool(std::unique_ptr< SegmentedMessageData > &)> ReadCallback
Primary callback API for raw reads.
std::optional< detail::PollingBuffer< MessageData > > pollingState
bool translateIncoming(MessageData &data)
Translate incoming data if the port type is a window type.
virtual void disconnect() override
Disconnect the channel.
std::unique_ptr< SegmentedMessageData > translatedMessage
If a translated message has been assembled but not yet consumed, retain ownership here so retries pre...
uint64_t maxDataQueueMsgs
std::function< bool(MessageData)> FlatReadCallback
Compatibility callback API for callers which want flattened message bytes instead of the owning segme...
ReadCallback callback
Backends should not call this directly.
std::vector< uint8_t > listDataBuffer
For list fields: accumulated list data across frames.
bool invokeCallback(std::unique_ptr< SegmentedMessageData > &msg)
Invoke the currently registered callback.
std::condition_variable callbackCv
Structs are an ordered collection of fields, each with a name and a type.
const FieldVector & getFields() const
Root class of the ESI type system.
virtual std::ptrdiff_t getBitWidth() const
Windows represent a fixed-size sliding window over a stream of data.
A ChannelPort which sends data to the accelerator.
void stopAsyncWriter()
Detach and stop the default implementation's current connection, if any.
std::mutex asyncWriterMutex
Protects asyncWriter.
std::shared_ptr< DefaultAsyncWriter > asyncWriter
The default implementation's current connection, if in use.
void connectCallbackMode(const ConnectOptions &options)
For backends which override connect(DataFetchCallback, ...): check that the port is disconnected,...
void writeInternal(const MessageData &data)
write(), tryWrite() and flush() without the mode check.
size_t translationBufferIdx
Index of the next message to write in translationBuffer.
virtual void disconnect() override
Disconnect the port.
virtual bool tryWriteImpl(const MessageData &data)=0
Implementation for tryWrite(). Subclasses must implement this.
void connectCommon(const ConnectOptions &options)
Set up translation and call connectImpl(). Shared by both modes.
bool translateMessages
Whether to translate outgoing data if the port type is a window type.
void requireNotCallbackMode(const char *method) const
Throw if the port is connected in callback mode.
virtual void notifyAsyncDataAvailable()
Notify the port that the DataFetchCallback has data again.
bool tryWriteInternal(const MessageData &data)
virtual void connect(const ConnectOptions &options={}) override
Connect in sync mode. Throws if connected in callback mode.
virtual bool pollWriteImpl()
Backend-specific polling.
const MessageData & maybePadEmptyMessage(const MessageData &data)
Pad an empty payload with a single zero byte if the port type has a zero-width logical width (e....
bool pollImpl() final
If the default callback mode implementation is in use, write fetched data (see connect()).
bool hasPendingFrames() const
Whether a windowed message's frames are partially written.
void discardPendingFrames()
Drop the frames of a partially written (windowed) message.
std::function< void(std::exception_ptr)> WriteErrorCallback
Callback mode error handler.
std::shared_ptr< DefaultAsyncWriter > getAsyncWriter()
Return the default implementation's current connection, if any.
void translateOutgoing(const MessageData &data)
Translate outgoing data if the port type is a window type.
std::vector< MessageData > getMessageFrames(const MessageData &data)
Break a message into its frames.
static constexpr size_t kMaxAsyncWritesPerCall
The most messages the default callback mode implementation writes per call to notifyAsyncDataAvailabl...
std::vector< MessageData > translationBuffer
If tryWrite cannot write all the messages of a windowed type at once, it stores them here and writes ...
std::function< std::unique_ptr< SegmentedMessageData >()> DataFetchCallback
Callback mode data source.
~WriteChannelPort() override
Stops the default callback mode implementation, if in use, dropping a fetched message which hasn't be...
virtual void writeImpl(const MessageData &)=0
Implementation for write(). Subclasses must implement this.
std::map< std::string, ChannelPort & > PortMap
std::atomic< bool > stopped
Set when the port is disconnected (or reconnected) or destroyed.
bool draining
Set by the thread holding mutex while in drain(), so callbacks don't start another one.
void notify()
Mark that the DataFetchCallback may have data, then poll().
void poll()
Write fetched data (fetching more as needed) until the DataFetchCallback has none,...
void stop()
Stop this connection: after this returns, it doesn't touch the port again.
DrainResult drain()
The body of poll(). Requires mutex.
DefaultAsyncWriter(WriteChannelPort &port, DataFetchCallback fetch, WriteErrorCallback onError)
std::recursive_mutex mutex
Held while writing, including while calling the callbacks.
std::atomic< bool > dataAvailable
False once fetch returns nullptr (or throws), until notify() is called.
std::unique_ptr< SegmentedMessageData > pendingMsg
A fetched message which the port hasn't accepted yet.
const WriteErrorCallback onError
const DataFetchCallback fetch
std::optional< unsigned > bufferSize
The buffer size is optional and should be considered merely a hint.
bool translateMessage
If the type of this port is a window, translate the incoming/outgoing data into its underlying ('into...
A copy operation for translating between frame data and the translation.
size_t bufferOffset
Offset in the translation buffer.
size_t frameOffset
Offset in the incoming/outgoing frame data.
size_t size
Number of bytes to copy.
Information about each frame in the windowed type.
std::vector< CopyOp > copyOps
Precomputed copy operations for translating this frame (non-list fields).
std::optional< ListFieldInfo > listField
Information about list fields in this frame (parallel encoding).
size_t expectedSize
The total size of a frame in bytes.
Information about a list field within a frame (for parallel encoding).
size_t listLengthBufferOffset
Offset in the translation buffer where list length is stored.
size_t dataOffset
Offset of the list data array in the frame.
std::string fieldName
Name of the list field.
size_t lastFieldOffset
Offset of the 'last' field in the frame.
size_t elementSize
Size of each list element in bytes.
size_t listDataBufferOffset
Offset in the translation buffer where list data starts.
void precomputeFrameInfo()
Precompute and optimize the copy operations for translating frames.
void requireTranslationSupported() const
Throw if this window cannot be translated by the runtime translator (e.g.
bool hasListField
True if the window contains a list field (variable-size message).
const WindowType * windowType
The window type being translated.
size_t intoTypeBytes
Size of the 'into' type in bytes (for fixed-size types).
size_t frameBytes
Number of bytes per wire frame (from the lowered type's bit width).
std::vector< FrameInfo > frames
Precomputed information about each frame.
Field information describing a field within a frame.