aboutsummaryrefslogtreecommitdiffstats
path: root/ydb/public/lib/deprecated/client/msgbus_client.cpp
blob: 1364c4dde6626986ec77ccef94eaf3f47bee5a9b (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
#include "msgbus_client.h"
#include <util/system/event.h>

namespace NKikimr {
namespace NMsgBusProxy {

void TMsgBusClientConfig::CrackAddress(const TString& address, TString& hostname, ui32& port) { 
    size_t first_colon_pos = address.find(':');
    if (first_colon_pos != TString::npos) { 
        size_t last_colon_pos = address.rfind(':');
        if (last_colon_pos == first_colon_pos) {
            // only one colon, simple case
            port = FromString<ui32>(address.substr(first_colon_pos + 1));
            hostname = address.substr(0, first_colon_pos);
        } else {
            // ipv6?
            size_t closing_bracket_pos = address.rfind(']');
            if (closing_bracket_pos == TString::npos || closing_bracket_pos > last_colon_pos) { 
                // whole address is ipv6 host
                hostname = address;
            } else {
                port = FromString<ui32>(address.substr(last_colon_pos + 1));
                hostname = address.substr(0, last_colon_pos);
            }
            if (hostname.StartsWith('[') && hostname.EndsWith(']')) {
                hostname = hostname.substr(1, hostname.size() - 2);
            }
        }
    } else {
        hostname = address;
    }
}



struct TMessageCookie
{
    virtual void Signal(TAutoPtr<NBus::TBusMessage>& msg, NBus::EMessageStatus errorStatus, TAutoPtr<NBus::TBusMessage> reply) = 0;
    virtual ~TMessageCookie()
    {
    }
};

struct TSyncMessageCookie : public TMessageCookie {
    TAutoPtr<NBus::TBusMessage> Reply;
    NBus::EMessageStatus ErrorStatus = NBus::MESSAGE_UNKNOWN;
    TManualEvent Ev;

    TSyncMessageCookie()
        : Ev()
    {}

    void Wait() {
        Ev.Wait();
    }

    virtual void Signal(TAutoPtr<NBus::TBusMessage>& msg, NBus::EMessageStatus errorStatus, TAutoPtr<NBus::TBusMessage> reply) {
        Y_UNUSED(msg.Release());
        ErrorStatus = errorStatus;
        Reply = reply;
        Ev.Signal();
    }
};


template <typename CallbackType>
struct TAsyncMessageCookie : public TMessageCookie {
    CallbackType Callback;
    void* Data;

    explicit TAsyncMessageCookie(CallbackType callback, void* data)
        : Callback(callback)
        , Data(data)
    {}

    void Signal(TAutoPtr<NBus::TBusMessage>& msg, NBus::EMessageStatus errorStatus, TAutoPtr<NBus::TBusMessage> reply) override;
};

template <>
void TAsyncMessageCookie<TMsgBusClient::TOnCall>::Signal(TAutoPtr<NBus::TBusMessage>& msg, NBus::EMessageStatus errorStatus, TAutoPtr<NBus::TBusMessage> reply) {
    msg->Data = Data;
    Callback(errorStatus, reply);
    delete this; // we must cleanup cookie after use
}

template <>
void TAsyncMessageCookie<TMsgBusClient::TOnCallWithRequest>::Signal(TAutoPtr<NBus::TBusMessage>& msg, NBus::EMessageStatus errorStatus, TAutoPtr<NBus::TBusMessage> reply) {
    msg->Data = Data;
    Callback(errorStatus, msg, reply);
    delete this; // we must cleanup cookie after use
}


TMsgBusClientConfig::TMsgBusClientConfig()
    : Ip("localhost")
    , Port(NMsgBusProxy::TProtocol::DefaultPort)
    , UseCompression(false)
{}

void TMsgBusClientConfig::ConfigureLastGetopt(NLastGetopt::TOpts &opts, const TString& prefix) { 
    BusSessionConfig.ConfigureLastGetopt(opts, prefix);
    BusQueueConfig.ConfigureLastGetopt(opts, prefix);
}

TMsgBusClient::TMsgBusClient(const TMsgBusClientConfig &config)
    : Config(config)
    , Protocol(NMsgBusProxy::TProtocol::DefaultPort)
{}

TMsgBusClient::~TMsgBusClient() {
    Shutdown();
}

void TMsgBusClient::Init() {
    NetAddr = new NBus::TNetAddr(Config.Ip, Config.Port); // could throw
    Bus = NBus::CreateMessageQueue(Config.BusQueueConfig);
    Session = NBus::TBusClientSession::Create(&Protocol, this, Config.BusSessionConfig, Bus);
}

void TMsgBusClient::Shutdown() {
    if (Bus) {
        if (Session) {
            Session->Shutdown();
        }

        Session.Drop();
        Bus.Drop();
    }
}

NBus::EMessageStatus TMsgBusClient::SyncCall(TAutoPtr<NBus::TBusMessage> msg, TAutoPtr<NBus::TBusMessage> &reply) {
    Y_VERIFY(!msg->Data);
    TAutoPtr<TSyncMessageCookie> cookie(new TSyncMessageCookie());
    msg->Data = cookie.Get();

    // msgbus would recreate second TAutoPtr for our msg pointer (wut?!) Second copy terminates in OnRelease/OnError where we release it.
    NBus::EMessageStatus status = Session->SendMessage(msg.Get(), NetAddr.Get(), true);

    if (status == NBus::MESSAGE_OK) {
        cookie->Wait();
        reply = cookie->Reply;
        return cookie->ErrorStatus;
    } else {
        return status;
    }
}

NBus::EMessageStatus TMsgBusClient::AsyncCall(TAutoPtr<NBus::TBusMessage> msg, TOnCall callback) {
    TAutoPtr<TMessageCookie> cookie(new TAsyncMessageCookie<TOnCall>(callback, msg->Data));
    msg->Data = cookie.Get();

    if (Config.UseCompression) {
        msg->SetCompressed(true);
        msg->SetCompressedResponse(true);
    }

    NBus::EMessageStatus status = Session->SendMessage(msg.Get(), NetAddr.Get(), false);

    if (status == NBus::MESSAGE_OK) {
        // would be destructed in onresult/onerror
        Y_UNUSED(cookie.Release());
        Y_UNUSED(msg.Release());
    }

    return status;
}

NBus::EMessageStatus TMsgBusClient::AsyncCall(TAutoPtr<NBus::TBusMessage> msg, TOnCallWithRequest callback) {
    TAutoPtr<TMessageCookie> cookie(new TAsyncMessageCookie<TOnCallWithRequest>(callback, msg->Data));
    msg->Data = cookie.Get();

    if (Config.UseCompression) {
        msg->SetCompressed(true);
        msg->SetCompressedResponse(true);
    }

    NBus::EMessageStatus status = Session->SendMessage(msg.Get(), NetAddr.Get(), false);

    if (status == NBus::MESSAGE_OK) {
        // would be destructed in onresult/onerror
        Y_UNUSED(cookie.Release());
        Y_UNUSED(msg.Release());
    }

    return status;
}

void TMsgBusClient::OnResult(TAutoPtr<NBus::TBusMessage> pMessage, NBus::EMessageStatus status, TAutoPtr<NBus::TBusMessage> pReply) {
    static_cast<TMessageCookie*>(pMessage->Data)->Signal(pMessage, status, pReply);
}

void TMsgBusClient::OnReply(TAutoPtr<NBus::TBusMessage> pMessage, TAutoPtr<NBus::TBusMessage> pReply) {
    OnResult(pMessage, NBus::MESSAGE_OK, pReply);
}

void TMsgBusClient::OnError(TAutoPtr<NBus::TBusMessage> pMessage, NBus::EMessageStatus status) {
    if (status == NBus::MESSAGE_UNKNOWN) // timeouted request
        return;

    OnResult(pMessage, status, TAutoPtr<NBus::TBusMessage>());
}

const TMsgBusClientConfig& TMsgBusClient::GetConfig() {
    return Config;
}

EDataReqStatusExcerpt ExtractDataRequestStatus(const NKikimrClient::TResponse *record) {
    if (!record)
        return EDataReqStatusExcerpt::Unknown;

    switch (record->GetStatus()) {
    case MSTATUS_OK:
        return EDataReqStatusExcerpt::Complete;
    case MSTATUS_INPROGRESS:
        return EDataReqStatusExcerpt::InProgress;
    case MSTATUS_ERROR:
        return EDataReqStatusExcerpt::Error;
    case MSTATUS_TIMEOUT:
        return EDataReqStatusExcerpt::LostInSpaceAndTime;
    case MSTATUS_NOTREADY:
    case MSTATUS_REJECTED:
        return EDataReqStatusExcerpt::RejectedForNow;
    case MSTATUS_INTERNALERROR:
        return EDataReqStatusExcerpt::InternalError;
    default:
        return EDataReqStatusExcerpt::Unknown;
    }
}

}

void SetMsgBusDefaults(NBus::TBusSessionConfig& sessionConfig,
                              NBus::TBusQueueConfig& queueConfig) {
   size_t memorySize = NSystemInfo::TotalMemorySize();
   if (!memorySize) {
       memorySize = 1 << 30;
   }
   sessionConfig.MaxInFlightBySize =
           (memorySize / 20);
   sessionConfig.MaxInFlight =
           sessionConfig.MaxInFlightBySize / 1024;
   queueConfig.NumWorkers =
           ((NSystemInfo::CachedNumberOfCpus() - 1) / 4 + 1);
   sessionConfig.TotalTimeout = TDuration::Minutes(5).MilliSeconds();
   sessionConfig.ConnectTimeout = TDuration::Seconds(15).MilliSeconds();
}

}