aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/actors/core/event_pb.h
blob: f88519e1083d8ebcd2bb11cc727f39b853fff412 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
#pragma once

#include "event.h"
#include "event_load.h"

#include <google/protobuf/io/zero_copy_stream.h>
#include <google/protobuf/arena.h>
#include <library/cpp/actors/protos/actors.pb.h>
#include <util/generic/deque.h>
#include <util/system/context.h>
#include <util/system/filemap.h>
#include <array>

namespace NActors {
 
    class TRopeStream : public NProtoBuf::io::ZeroCopyInputStream { 
        TRope::TConstIterator Iter; 
        const size_t Size; 
 
    public:
        TRopeStream(TRope::TConstIterator iter, size_t size) 
            : Iter(iter) 
            , Size(size) 
        {} 

        bool Next(const void** data, int* size) override; 
        void BackUp(int count) override; 
        bool Skip(int count) override; 
        int64_t ByteCount() const override {
            return TotalByteCount;
        }

    private: 
        int64_t TotalByteCount = 0;
    };

    class TChunkSerializer : public NProtoBuf::io::ZeroCopyOutputStream { 
    public:
        TChunkSerializer() = default; 
        virtual ~TChunkSerializer() = default; 
 
        virtual bool WriteRope(const TRope *rope) = 0; 
        virtual bool WriteString(const TString *s) = 0; 
    };

    class TAllocChunkSerializer final : public TChunkSerializer { 
    public:
        bool Next(void** data, int* size) override; 
        void BackUp(int count) override; 
        int64_t ByteCount() const override {
            return Buffers->GetSize();
        }
        bool WriteAliasedRaw(const void* data, int size) override; 

        // WARNING: these methods require owner to retain ownership and immutability of passed objects 
        bool WriteRope(const TRope *rope) override; 
        bool WriteString(const TString *s) override; 
 
        inline TIntrusivePtr<TEventSerializedData> Release(bool extendedFormat) { 
            if (extendedFormat) { 
                Buffers->SetExtendedFormat(); 
            } 
            return std::move(Buffers); 
        }

    protected:
        TIntrusivePtr<TEventSerializedData> Buffers = new TEventSerializedData; 
        TRope Backup; 
    };

    class TCoroutineChunkSerializer final : public TChunkSerializer, protected ITrampoLine { 
    public:
        using TChunk = std::pair<const char*, size_t>; 
 
        TCoroutineChunkSerializer();
        ~TCoroutineChunkSerializer();

        void SetSerializingEvent(const IEventBase *event); 
        void Abort(); 
        std::pair<TChunk*, TChunk*> FeedBuf(void* data, size_t size); 
        bool IsComplete() const {
            return !Event; 
        }
        bool IsSuccessfull() const {
            return SerializationSuccess;
        }
        const IEventBase *GetCurrentEvent() const { 
            return Event; 
        } 

        bool Next(void** data, int* size) override;
        void BackUp(int count) override;
        int64_t ByteCount() const override {
            return TotalSerializedDataSize;
        }
        bool WriteAliasedRaw(const void* data, int size) override;
        bool AllowsAliasing() const override;

        bool WriteRope(const TRope *rope) override; 
        bool WriteString(const TString *s) override; 
 
    protected:
        void DoRun() override;
        void Resume();
        bool Produce(const void *data, size_t size); 

        i64 TotalSerializedDataSize;
        TMappedAllocation Stack;
        TContClosure SelfClosure;
        TContMachineContext InnerContext;
        TContMachineContext *BufFeedContext = nullptr; 
        char *BufferPtr; 
        size_t SizeRemain; 
        static constexpr size_t MaxChunks = 16; 
        TChunk Chunks[MaxChunks]; 
        size_t NumChunks = 0; 
        const IEventBase *Event = nullptr; 
        bool CancelFlag = false; 
        bool AbortFlag; 
        bool SerializationSuccess; 
        bool Finished = false; 
    };

#ifdef ACTORLIB_HUGE_PB_SIZE 
    static const size_t EventMaxByteSize = 140 << 20; // (140MB) 
#else 
    static const size_t EventMaxByteSize = 67108000; 
#endif 
 
    template <typename TEv, typename TRecord /*protobuf record*/, ui32 TEventType, typename TRecHolder>
    class TEventPBBase: public TEventBase<TEv, TEventType> , public TRecHolder {
        // a vector of data buffers referenced by record; if filled, then extended serialization mechanism applies 
        TVector<TRope> Payload; 
 
    public:
        using TRecHolder::Record;

    public:
        using ProtoRecordType = TRecord;

        TEventPBBase() = default;

        explicit TEventPBBase(const TRecord& rec)
        {
            Record = rec;
        }

        explicit TEventPBBase(TRecord&& rec)
        {
            Record = std::move(rec);
        }

        TString ToStringHeader() const override {
            return Record.GetTypeName();
        }

        TString ToString() const override {
            return Record.ShortDebugString(); 
        }

        bool IsSerializable() const override { 
            return true; 
        } 
 
        bool IsExtendedFormat() const override { 
            return static_cast<bool>(Payload); 
        } 
 
        bool SerializeToArcadiaStream(TChunkSerializer* chunker) const override {
            // serialize payload first 
            if (Payload) { 
                void *data; 
                int size = 0; 
                auto append = [&](const char *p, size_t len) { 
                    while (len) { 
                        if (size) { 
                            const size_t numBytesToCopy = std::min<size_t>(size, len); 
                            memcpy(data, p, numBytesToCopy); 
                            data = static_cast<char*>(data) + numBytesToCopy; 
                            size -= numBytesToCopy; 
                            p += numBytesToCopy; 
                            len -= numBytesToCopy; 
                        } else if (!chunker->Next(&data, &size)) { 
                            return false; 
                        } 
                    } 
                    return true; 
                }; 
                auto appendNumber = [&](size_t number) { 
                    char buf[MaxNumberBytes]; 
                    return append(buf, SerializeNumber(number, buf)); 
                }; 
                char marker = PayloadMarker; 
                append(&marker, 1); 
                if (!appendNumber(Payload.size())) { 
                    return false; 
                } 
                for (const TRope& rope : Payload) { 
                    if (!appendNumber(rope.GetSize())) { 
                        return false; 
                    } 
                    if (rope) { 
                        if (size) { 
                            chunker->BackUp(std::exchange(size, 0)); 
                        } 
                        if (!chunker->WriteRope(&rope)) { 
                            return false; 
                        } 
                    } 
                } 
                if (size) { 
                    chunker->BackUp(size); 
                } 
            } 
 
            return Record.SerializeToZeroCopyStream(chunker);
        }

        ui32 CalculateSerializedSize() const override {
            ssize_t result = Record.ByteSize(); 
            if (result >= 0 && Payload) { 
                ++result; // marker 
                char buf[MaxNumberBytes]; 
                result += SerializeNumber(Payload.size(), buf); 
                for (const TRope& rope : Payload) { 
                    result += SerializeNumber(rope.GetSize(), buf); 
                    result += rope.GetSize(); 
                } 
            } 
            return result;
        }

        static IEventBase* Load(TIntrusivePtr<TEventSerializedData> input) {
            THolder<TEventPBBase> ev(new TEv());
            if (!input->GetSize()) { 
                Y_PROTOBUF_SUPPRESS_NODISCARD ev->Record.ParseFromString(TString());
            } else { 
                TRope::TConstIterator iter = input->GetBeginIter(); 
                ui64 size = input->GetSize(); 
 
                if (input->IsExtendedFormat()) { 
                    // check marker 
                    if (!iter.Valid() || *iter.ContiguousData() != PayloadMarker) { 
                        Y_FAIL("invalid event"); 
                    } 
                    // skip marker 
                    iter += 1; 
                    --size; 
                    // parse number of payload ropes 
                    size_t numRopes = DeserializeNumber(iter, size); 
                    if (numRopes == Max<size_t>()) { 
                        Y_FAIL("invalid event"); 
                    } 
                    while (numRopes--) { 
                        // parse length of the rope 
                        const size_t len = DeserializeNumber(iter, size); 
                        if (len == Max<size_t>() || size < len) { 
                            Y_FAIL("invalid event len# %zu size# %" PRIu64, len, size); 
                        } 
                        // extract the rope 
                        TRope::TConstIterator begin = iter; 
                        iter += len; 
                        size -= len; 
                        ev->Payload.emplace_back(begin, iter); 
                    } 
                } 
 
                // parse the protobuf 
                TRopeStream stream(iter, size); 
                if (!ev->Record.ParseFromZeroCopyStream(&stream)) { 
                    Y_FAIL("Failed to parse protobuf event type %" PRIu32 " class %s", TEventType, TypeName(ev->Record).data());
                } 
            }
            ev->CachedByteSize = input->GetSize(); 
            return ev.Release(); 
        }

        size_t GetCachedByteSize() const { 
            if (CachedByteSize == 0) { 
                CachedByteSize = CalculateSerializedSize(); 
            }
            return CachedByteSize;
        }

        ui32 CalculateSerializedSizeCached() const override { 
            return GetCachedByteSize(); 
        } 
 
        void InvalidateCachedByteSize() {
            CachedByteSize = 0;
        }

    public: 
        void ReservePayload(size_t size) {
            Payload.reserve(size);
        }

        ui32 AddPayload(TRope&& rope) { 
            const ui32 id = Payload.size(); 
            Payload.push_back(std::move(rope)); 
            InvalidateCachedByteSize(); 
            return id; 
        } 
 
        const TRope& GetPayload(ui32 id) const { 
            Y_VERIFY(id < Payload.size()); 
            return Payload[id]; 
        } 
 
        ui32 GetPayloadCount() const { 
            return Payload.size(); 
        } 
 
        void StripPayload() { 
            Payload.clear(); 
        } 
 
    protected: 
        mutable size_t CachedByteSize = 0;
 
        static constexpr char PayloadMarker = 0x07; 
        static constexpr size_t MaxNumberBytes = (sizeof(size_t) * CHAR_BIT + 6) / 7; 
 
        static size_t SerializeNumber(size_t num, char *buffer) { 
            char *begin = buffer; 
            do { 
                *buffer++ = (num & 0x7F) | (num >= 128 ? 0x80 : 0x00); 
                num >>= 7; 
            } while (num); 
            return buffer - begin; 
        } 
 
        static size_t DeserializeNumber(const char **ptr, const char *end) { 
            const char *p = *ptr; 
            size_t res = 0; 
            size_t offset = 0; 
            for (;;) { 
                if (p == end) { 
                    return Max<size_t>(); 
                } 
                const char byte = *p++; 
                res |= (static_cast<size_t>(byte) & 0x7F) << offset; 
                offset += 7; 
                if (!(byte & 0x80)) { 
                    break; 
                } 
            } 
            *ptr = p; 
            return res; 
        } 
 
        static size_t DeserializeNumber(TRope::TConstIterator& iter, ui64& size) { 
            size_t res = 0; 
            size_t offset = 0; 
            for (;;) { 
                if (!iter.Valid()) { 
                    return Max<size_t>(); 
                } 
                const char byte = *iter.ContiguousData(); 
                iter += 1; 
                --size; 
                res |= (static_cast<size_t>(byte) & 0x7F) << offset; 
                offset += 7; 
                if (!(byte & 0x80)) { 
                    break; 
                } 
            } 
            return res; 
        } 
    };

    // Protobuf record not using arena
    template <typename TRecord>
    struct TRecordHolder {
        TRecord Record;
    };

    // Protobuf arena and a record allocated on it
    template <typename TRecord, size_t InitialBlockSize, size_t MaxBlockSize>
    struct TArenaRecordHolder {
        google::protobuf::Arena PbArena;
        TRecord& Record;

        static const google::protobuf::ArenaOptions GetArenaOptions() {
            google::protobuf::ArenaOptions opts;
            opts.initial_block_size = InitialBlockSize;
            opts.max_block_size = MaxBlockSize;
            return opts;
        }

        TArenaRecordHolder()
            : PbArena(GetArenaOptions())
            , Record(*google::protobuf::Arena::CreateMessage<TRecord>(&PbArena))
        {}
    };

    template <typename TEv, typename TRecord, ui32 TEventType>
    class TEventPB : public TEventPBBase<TEv, TRecord, TEventType, TRecordHolder<TRecord> > {
        typedef TEventPBBase<TEv, TRecord, TEventType, TRecordHolder<TRecord> > TPbBase;
        // NOTE: No extra fields allowed: TEventPB must be a "template typedef"
    public:
        using TPbBase::TPbBase;
    };

    template <typename TEv, typename TRecord, ui32 TEventType, size_t InitialBlockSize = 512, size_t MaxBlockSize = 16*1024>
    using TEventPBWithArena = TEventPBBase<TEv, TRecord, TEventType, TArenaRecordHolder<TRecord, InitialBlockSize, MaxBlockSize> >;

    template <typename TEv, typename TRecord, ui32 TEventType>
    class TEventShortDebugPB: public TEventPB<TEv, TRecord, TEventType> {
    public:
        using TBase = TEventPB<TEv, TRecord, TEventType>;
        TEventShortDebugPB() = default;
        explicit TEventShortDebugPB(const TRecord& rec)
            : TBase(rec)
        {
        }
        explicit TEventShortDebugPB(TRecord&& rec)
            : TBase(std::move(rec))
        {
        }
        TString ToString() const override {
            return TypeName<TEv>() + " { " + TBase::Record.ShortDebugString() + " }";
        }
    };

    template <typename TEv, typename TRecord, ui32 TEventType>
    class TEventPreSerializedPB: public TEventPB<TEv, TRecord, TEventType> {
    protected:
        using TBase = TEventPB<TEv, TRecord, TEventType>;
        using TSelf = TEventPreSerializedPB<TEv, TRecord, TEventType>;
        using TBase::Record;

    public:
        TString PreSerializedData; // already serialized PB data (using message::SerializeToString)

        TEventPreSerializedPB() = default;

        explicit TEventPreSerializedPB(const TRecord& rec)
            : TBase(rec)
        {
        }

        explicit TEventPreSerializedPB(TRecord&& rec)
            : TBase(std::move(rec))
        {
        }

        // when remote event received locally this method will merge preserialized data
        const TRecord& GetRecord() {
            TRecord& base(TBase::Record);
            if (!PreSerializedData.empty()) {
                TRecord copy;
                Y_PROTOBUF_SUPPRESS_NODISCARD copy.ParseFromString(PreSerializedData);
                copy.MergeFrom(base);
                base.Swap(&copy);
                PreSerializedData.clear();
            }
            return TBase::Record;
        }

        const TRecord& GetRecord() const {
            return const_cast<TSelf*>(this)->GetRecord();
        }

        TRecord* MutableRecord() {
            GetRecord(); // Make sure PreSerializedData is parsed
            return &(TBase::Record);
        }

        TString ToString() const override {
            return GetRecord().ShortDebugString(); 
        }

        bool SerializeToArcadiaStream(TChunkSerializer* chunker) const override {
            return chunker->WriteString(&PreSerializedData) && TBase::SerializeToArcadiaStream(chunker);
        }

        ui32 CalculateSerializedSize() const override {
            return PreSerializedData.size() + TBase::CalculateSerializedSize();
        }

        size_t GetCachedByteSize() const {
            return PreSerializedData.size() + TBase::GetCachedByteSize();
        }
 
        ui32 CalculateSerializedSizeCached() const override { 
            return GetCachedByteSize(); 
        } 
    };

    inline TActorId ActorIdFromProto(const NActorsProto::TActorId& actorId) {
        return TActorId(actorId.GetRawX1(), actorId.GetRawX2());
    }

    inline void ActorIdToProto(const TActorId& src, NActorsProto::TActorId* dest) {
        Y_VERIFY_DEBUG(dest);
        dest->SetRawX1(src.RawX1());
        dest->SetRawX2(src.RawX2());
    }
}