aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/actors/examples/02_discovery/replica.cpp
blob: 96a6f5f475a3dc6d67ff7d15db8e2307a7dbf598 (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
#include "services.h"
#include <library/cpp/actors/core/actorsystem.h>
#include <library/cpp/actors/core/hfunc.h>
#include <library/cpp/actors/core/interconnect.h>
#include <util/generic/set.h>
#include <util/generic/hash_set.h>
#include <util/generic/vector.h>

class TExampleReplicaActor : public TActor<TExampleReplicaActor> {
    using TOwnerIndex = TMap<TActorId, ui32, TActorId::TOrderedCmp>;
    using TKeyIndex = THashMap<TString, TSet<ui32>>;

    struct TEntry {
        TString Payload;
        TActorId Owner;
        TOwnerIndex::iterator OwnerIt;
        TKeyIndex::iterator KeyIt;
    };

    TVector<TEntry> Entries;
    TVector<ui32> AvailableEntries;

    TOwnerIndex IndexOwner;
    TKeyIndex IndexKey;

    ui32 AllocateEntry() {
        ui32 ret;
        if (AvailableEntries) {
            ret = AvailableEntries.back();
            AvailableEntries.pop_back();
        }
        else {
            ret = Entries.size();
            Entries.emplace_back();
        }

        return ret;
    }

    bool IsLastEntryOnNode(TOwnerIndex::iterator ownerIt) {
        const ui32 ownerNodeId = ownerIt->first.NodeId();
        if (ownerIt != IndexOwner.begin()) {
            auto x = ownerIt;
            --x;
            if (x->first.NodeId() == ownerNodeId)
                return false;
        }

        ++ownerIt;
        if (ownerIt != IndexOwner.end()) {
            if (ownerIt->first.NodeId() == ownerNodeId)
                return false;
        }

        return true;
    }

    void CleanupEntry(ui32 entryIndex) {
        TEntry &entry = Entries[entryIndex];
        entry.KeyIt->second.erase(entryIndex);
        if (entry.KeyIt->second.empty())
            IndexKey.erase(entry.KeyIt);

        if (IsLastEntryOnNode(entry.OwnerIt))
            Send(TlsActivationContext->ExecutorThread.ActorSystem->InterconnectProxy(entry.OwnerIt->first.NodeId()), new TEvents::TEvUnsubscribe());

        IndexOwner.erase(entry.OwnerIt);

        TString().swap(entry.Payload);
        entry.Owner = TActorId();
        entry.KeyIt = IndexKey.end();
        entry.OwnerIt = IndexOwner.end();

        AvailableEntries.emplace_back(entryIndex);
    }

    void Handle(TEvExample::TEvReplicaLookup::TPtr &ev) {
        auto &record = ev->Get()->Record;
        const auto &key = record.GetKey();

        auto keyIt = IndexKey.find(key);
        if (keyIt == IndexKey.end()) {
            Send(ev->Sender, new TEvExample::TEvReplicaInfo(key), 0, ev->Cookie);
            return;
        }

        auto reply = MakeHolder<TEvExample::TEvReplicaInfo>(key);
        reply->Record.MutablePayload()->Reserve(keyIt->second.size());
        for (ui32 entryIndex : keyIt->second) {
            const TEntry &entry = Entries[entryIndex];
            reply->Record.AddPayload(entry.Payload);
        }

        Send(ev->Sender, std::move(reply), 0, ev->Cookie);
    }

    void Handle(TEvExample::TEvReplicaPublish::TPtr &ev) {
        auto &record = ev->Get()->Record;
        const TString &key = record.GetKey();
        const TString &payload = record.GetPayload();
        const TActorId &owner = ev->Sender;

        auto ownerIt = IndexOwner.find(owner);
        if (ownerIt != IndexOwner.end()) {
            const ui32 entryIndex = ownerIt->second;
            TEntry &entry = Entries[entryIndex];
            if (entry.KeyIt->first != key) {
                // reply nothing, request suspicious
                return;
            }

            entry.Payload = payload;
        }
        else {
            const ui32 entryIndex = AllocateEntry();
            TEntry &entry = Entries[entryIndex];

            entry.Payload = payload;
            entry.Owner = owner;

            entry.OwnerIt = IndexOwner.emplace(owner, entryIndex).first;
            entry.KeyIt = IndexKey.emplace(std::make_pair(key, TSet<ui32>())).first;
            entry.KeyIt->second.emplace(entryIndex);

            Send(owner, new TEvExample::TEvReplicaPublishAck(), IEventHandle::FlagTrackDelivery | IEventHandle::FlagSubscribeOnSession, ev->Cookie);
        }
    }

    void Handle(TEvents::TEvUndelivered::TPtr &ev) {
        auto ownerIt = IndexOwner.find(ev->Sender);
        if (ownerIt == IndexOwner.end())
            return;

        CleanupEntry(ownerIt->second);
    }

    void Handle(TEvInterconnect::TEvNodeDisconnected::TPtr &ev) {
        auto *msg = ev->Get();
        const ui32 nodeId = msg->NodeId;
        auto ownerIt = IndexOwner.lower_bound(TActorId(nodeId, 0, 0, 0));
        while (ownerIt != IndexOwner.end() && ownerIt->first.NodeId() == nodeId) {
            const ui32 idx = ownerIt->second;
            ++ownerIt;
            CleanupEntry(idx);
        }
    }

public:
    static constexpr IActor::EActivityType ActorActivityType() {
        // define app-specific activity tag to track elapsed cpu | handled events | actor count in Solomon
        return EActorActivity::ACTORLIB_COMMON;
    }

    TExampleReplicaActor()
        : TActor(&TThis::StateWork)
    {}

    STFUNC(StateWork) {
        switch (ev->GetTypeRewrite()) {
            hFunc(TEvExample::TEvReplicaLookup, Handle);
            hFunc(TEvExample::TEvReplicaPublish, Handle);
            hFunc(TEvents::TEvUndelivered, Handle);
            hFunc(TEvInterconnect::TEvNodeDisconnected, Handle);

            IgnoreFunc(TEvInterconnect::TEvNodeConnected);
        default:
            // here is place to spam some log message on unknown events
            break;
        }
    }
};

IActor* CreateReplica() {
    return new TExampleReplicaActor();
}

TActorId MakeReplicaId(ui32 nodeid) {
    char x[12] = { 'r', 'p', 'l' };
    memcpy(x + 5, &nodeid, sizeof(ui32));
    return TActorId(nodeid, TStringBuf(x, 12));
}