zhangmeng
2021-12-16 cb6e8a6831613006603c14337291174fa29d2f57
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
#include "nng_wrap.h"
#include "common.h"
 
#include <nng/protocol/reqrep0/rep.h>
#include <nng/supplemental/util/platform.h>
 
#include <vector>
using namespace std;
 
namespace nng_wrap {
//////////////////////////////////////////////
// reply for request
 
int request2(const std::string &ipc, const void* r, const int r_len,
    void** reply, int* reply_len, const int to_ms, void* arg/*=NULL*/)
{
    const auto suc = simple_request(ipc, r, r_len, reply, reply_len, to_ms);
    if (suc){
        const size_t sl = rr_unblocking_msg_.size();
        const size_t rl = *reply_len;
        if (sl != rl) return true;
 
        const auto& s = rr_unblocking_msg_;
        auto r = (const char*)(*reply);
        if (s.compare(0, sl, r, rl) == 0){
            free(*reply);
            *reply = NULL;
            *reply_len = 0;
            return false;
        }
    }
    return suc;
}
 
static void server_cb(void *arg)
{
    if (!arg) return;
 
    struct work *work = (struct work*)arg;
    nng_msg *    msg;
    int          rv;
    // uint32_t     when{0};
 
    switch (work->state) {
    case INIT:
        work->state = RECV;
        nng_ctx_recv(work->ctx, work->aio);
        break;
    case RECV:
        if ((rv = nng_aio_result(work->aio)) != 0) {
            break;
        }
        msg = nng_aio_get_msg(work->aio);
 
        work->msg   = msg;
        work->state = WAIT;
        if (work->cb_recv) work->cb_recv(work);
        // nng_sleep_aio(when, work->aio);
        break;
    case WAIT:
        // We could add more data to the message here.
        nng_aio_set_msg(work->aio, work->msg);
        work->msg   = NULL;
        work->state = SEND;
        nng_ctx_send(work->ctx, work->aio);
        break;
    case SEND:
        if ((rv = nng_aio_result(work->aio)) != 0) {
            nng_msg_free(work->msg);
        }
        work->state = RECV;
        nng_ctx_recv(work->ctx, work->aio);
        break;
    default:
        break;
    }
}
 
static void cb_recv_for_aio(work* w){
    nng_msg *om = w->msg;
    if (!om) return;
 
    _rr* rep = (_rr*)w->user_data;
 
    string msg{(const char*)nng_msg_body(om), nng_msg_len(om)};
    nng_msg_free(om);
 
    lock_guard<mutex> l{rep->mtx_msg_};
    rep->works_.emplace(rep->work_index_, w);
    rep->msg_.emplace(rep->work_index_, move(msg));
    // rep->works_.insert({rep->work_index_, w});
    // rep->msg_.insert({rep->work_index_, msg});
    // rep->works_[rep->work_index_] = w;
    // rep->msg_[rep->work_index_] = msg;
    rep->work_index_++;
    rep->cv_msg_.notify_all();
}
 
static struct work *alloc_work(nng_socket sock, _rr* rep)
{
    struct work *w;
    int          rv;
 
    if ((w = (struct work*)nng_alloc(sizeof(*w))) == NULL) {
        return NULL;;
    }
    w->cb_recv = cb_recv_for_aio;
    w->user_data = rep;
 
    if ((rv = nng_aio_alloc(&w->aio, server_cb, w)) != 0) {
        return NULL;
    }
    if ((rv = nng_ctx_open(&w->ctx, sock)) != 0) {
        return NULL;
    }
    w->state = INIT;
    return (w);
}
 
static int create_server(nng_socket* sock, const string& url, const int count, _rr* rep){
    TAG;
    if (sock->id > 0) return 0;
 
    int rv = nng_rep0_open(sock);
    if (rv < 0){
        PRNTVITAG("create_server nng_rep0_open faild");
        PRNTVITAG(url);
        return rv;
    }
 
    work** works = (work**)malloc(sizeof(work*) * count);
    for (int i = 0; i < count; i++) {
        works[i] = alloc_work(*sock, rep);
    }
 
    remove_exist(url);
    rv = nng_listen(*sock, url.c_str(), NULL, 0);
    if (rv < 0){
        free(works);
        PRNTVITAG("create_server nng_listen failed");
        PRNTVITAG(url);
        return rv;
    }
 
    for (int i = 0; i < count; i++) {
        server_cb(works[i]); // this starts them going (INIT state)
    }
 
    free(works);
    return 0;
}
 
static void aio_unblock(work* w, const void* msg, const int msg_len){
    nng_msg_alloc(&w->msg, 0);
    nng_msg_append(w->msg, msg, msg_len);
 
    nng_sleep_aio(0, w->aio);
}
 
int start_reply(const std::string& url, const int port, void* arg/*=NULL*/){
    _rr* rep = (_rr*)arg;
    if (!rep) rep = singleton<_rr>();
 
    string ipc = "ipc:///tmp/" + url;
    if (url.find("ipc://") == 0){
        ipc = url;
    }
    rep->url_ = ipc;
    if(create_server(&rep->sock_local_, ipc, 62, rep) != 0) return -1;
 
    if (port > 0){
        rep->port_ = port;
        ipc = "tcp://0.0.0.0:" + to_string(port);
        if(create_server(&rep->sock_remote_, ipc, 62, rep) != 0) return -1;
    }else {
        rep->sock_remote_.id = numeric_limits<int32_t>::max();
    }
 
    if (!rep->t_unblock_){
        rep->t_unblock_.reset(new thread([rep]{
            constexpr int idle = 10;
            const auto data = rr_unblocking_msg_.data();
            const auto data_size = rr_unblocking_msg_.size();
            while (!rep->t_quit_.load()) {
                this_thread::sleep_for(chrono::milliseconds{10});
                vector<struct work*> tmp{};
                {
                    lock_guard<mutex> l{rep->mtx_msg_};
                    for(auto iter = rep->works_.begin(); iter != rep->works_.end();){
                        if ((iter->second+=idle) > timeout_req_rep){
                            tmp.push_back(iter->second.w_);
                            iter = rep->works_.erase(iter);
                        }else {
                            ++iter;
                        }
                    }
                }
                for(auto && w : tmp){
                    aio_unblock(w, data, data_size);
                }
            }
        }));
    }
 
    return 0;
}
 
int read_request(void** src, std::string* msg, const int to_ms, void* arg/*=NULL*/){
    _rr* rep = (_rr*)arg;
    if (!rep) rep = singleton<_rr>();
 
    if (rep->sock_local_.id == 0 || rep->sock_remote_.id == 0)
        if (start_reply(rep->url_, rep->port_) != 0)
            return -1;
 
    int tm = to_ms > 0 ? to_ms : 30;
 
    uint64_t key{};
    {
        unique_lock<mutex> l(rep->mtx_msg_);
        auto status = rep->cv_msg_.wait_for(l, chrono::milliseconds{tm}, [rep]{
            return !rep->msg_.empty();
        });
        if (!status){
            PRNTVITAG("subscribe_read timeout");
            return -1;
        }
        auto iter = rep->msg_.begin();
        key = iter->first;
        *msg = move(iter->second);
        rep->msg_.erase(iter);
    }
 
    *src = malloc(sizeof(uint64_t));
    *(uint64_t*)(*src) = key;
 
    return 0;
}
 
int send_reply(const void* src, const void* msg, const int msg_len, void* arg/*=NULL*/){
    _rr* rep = (_rr*)arg;
    if (!rep) rep = singleton<_rr>();
 
    struct work* w{};
    {
        auto key = *(static_cast<uint64_t*>(const_cast<void*>(src)));
 
        lock_guard<mutex> l{rep->mtx_msg_};
        auto iter = rep->works_.find(key);
        if (iter == rep->works_.end()) return -1;
        w = iter->second;
        rep->works_.erase(iter);
    }
 
    aio_unblock(w, msg, msg_len);
 
    return 0;
}
 
}