forked from apache/rocketmq-clients
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClientManagerImpl.cpp
More file actions
1466 lines (1261 loc) · 52.3 KB
/
ClientManagerImpl.cpp
File metadata and controls
1466 lines (1261 loc) · 52.3 KB
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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ClientManagerImpl.h"
#include <atomic>
#include <cassert>
#include <chrono>
#include <memory>
#include <system_error>
#include <utility>
#include <vector>
#include "InvocationContext.h"
#include "LogInterceptor.h"
#include "LogInterceptorFactory.h"
#include "MixAll.h"
#include "Protocol.h"
#include "ReceiveMessageContext.h"
#include "RpcClient.h"
#include "RpcClientImpl.h"
#include "Scheduler.h"
#include "SchedulerImpl.h"
#include "UtilAll.h"
#include "google/protobuf/util/time_util.h"
#include "grpcpp/create_channel.h"
#include "rocketmq/ErrorCode.h"
#include "spdlog/spdlog.h"
ROCKETMQ_NAMESPACE_BEGIN
ClientManagerImpl::ClientManagerImpl(std::string resource_namespace, bool with_ssl)
: scheduler_(std::make_shared<SchedulerImpl>()),
resource_namespace_(std::move(resource_namespace)),
state_(State::CREATED),
callback_thread_pool_(absl::make_unique<ThreadPoolImpl>(std::thread::hardware_concurrency())),
with_ssl_(with_ssl) {
certificate_verifier_ = grpc::experimental::ExternalCertificateVerifier::Create<InsecureCertificateVerifier>();
tls_channel_credential_options_.set_verify_server_certs(false);
tls_channel_credential_options_.set_check_call_host(false);
channel_credential_ = grpc::experimental::TlsCredentials(tls_channel_credential_options_);
// Use unlimited receive message size.
channel_arguments_.SetMaxReceiveMessageSize(-1);
int max_send_message_size = 1024 * 1024 * 16;
channel_arguments_.SetMaxSendMessageSize(max_send_message_size);
/*
* Keep-alive settings:
* https://github.com/grpc/grpc/blob/master/doc/keepalive.md
* Keep-alive ping timeout duration: 3s
* Keep-alive ping interval, 30s
*/
channel_arguments_.SetInt(GRPC_ARG_KEEPALIVE_TIME_MS, 60000);
channel_arguments_.SetInt(GRPC_ARG_KEEPALIVE_TIMEOUT_MS, 3000);
channel_arguments_.SetInt(GRPC_ARG_KEEPALIVE_PERMIT_WITHOUT_CALLS, 1);
channel_arguments_.SetInt(GRPC_ARG_HTTP2_MAX_PINGS_WITHOUT_DATA, 0);
/*
* If set to zero, disables retry behavior. Otherwise, transparent retries
* are enabled for all RPCs, and configurable retries are enabled when they
* are configured via the service config. For details, see:
* https://github.com/grpc/proposal/blob/master/A6-client-retries.md
*/
channel_arguments_.SetInt(GRPC_ARG_ENABLE_RETRIES, 0);
// channel_arguments_.SetSslTargetNameOverride("localhost");
SPDLOG_INFO("ClientManager[ResourceNamespace={}] created", resource_namespace_);
}
ClientManagerImpl::~ClientManagerImpl() {
shutdown();
SPDLOG_INFO("ClientManager[ResourceNamespace={}] destructed", resource_namespace_);
}
void ClientManagerImpl::start() {
if (State::CREATED != state_.load(std::memory_order_relaxed)) {
SPDLOG_WARN("Unexpected client instance state: {}", state_.load(std::memory_order_relaxed));
return;
}
state_.store(State::STARTING, std::memory_order_relaxed);
callback_thread_pool_->start();
scheduler_->start();
std::weak_ptr<ClientManagerImpl> client_instance_weak_ptr = shared_from_this();
auto heartbeat_functor = [client_instance_weak_ptr]() {
auto client_instance = client_instance_weak_ptr.lock();
if (client_instance) {
client_instance->doHeartbeat();
}
};
heartbeat_task_id_ =
scheduler_->schedule(heartbeat_functor, HEARTBEAT_TASK_NAME, std::chrono::seconds(1), std::chrono::seconds(10));
SPDLOG_DEBUG("Heartbeat task-id={}", heartbeat_task_id_);
state_.store(State::STARTED, std::memory_order_relaxed);
}
void ClientManagerImpl::shutdown() {
SPDLOG_INFO("Client manager shutdown");
if (State::STARTED != state_.load(std::memory_order_relaxed)) {
SPDLOG_WARN("Unexpected client instance state: {}", state_.load(std::memory_order_relaxed));
return;
}
state_.store(STOPPING, std::memory_order_relaxed);
callback_thread_pool_->shutdown();
if (heartbeat_task_id_) {
scheduler_->cancel(heartbeat_task_id_);
}
scheduler_->shutdown();
{
absl::MutexLock lk(&rpc_clients_mtx_);
rpc_clients_.clear();
SPDLOG_DEBUG("rpc_clients_ is clear");
}
state_.store(State::STOPPED, std::memory_order_relaxed);
SPDLOG_DEBUG("ClientManager stopped");
}
std::vector<std::string> ClientManagerImpl::cleanOfflineRpcClients() {
absl::flat_hash_set<std::string> hosts;
{
absl::MutexLock lk(&clients_mtx_);
for (const auto& item : clients_) {
std::shared_ptr<Client> client = item.lock();
if (!client) {
continue;
}
client->endpointsInUse(hosts);
}
}
std::vector<std::string> removed;
{
absl::MutexLock lk(&rpc_clients_mtx_);
for (auto it = rpc_clients_.begin(); it != rpc_clients_.end();) {
std::string host = it->first;
if (it->second->needHeartbeat() && !hosts.contains(host)) {
SPDLOG_INFO("Removed RPC client whose peer is offline. RemoteHost={}", host);
removed.push_back(host);
rpc_clients_.erase(it++);
} else {
it++;
}
}
}
return removed;
}
void ClientManagerImpl::heartbeat(const std::string& target_host,
const Metadata& metadata,
const HeartbeatRequest& request,
std::chrono::milliseconds timeout,
const std::function<void(const std::error_code&, const HeartbeatResponse&)>& cb) {
SPDLOG_DEBUG("Prepare to send heartbeat to {}. Request: {}", target_host, request.DebugString());
auto client = getRpcClient(target_host, true);
auto invocation_context = new InvocationContext<HeartbeatResponse>();
invocation_context->task_name = fmt::format("Heartbeat to {}", target_host);
invocation_context->remote_address = target_host;
for (const auto& item : metadata) {
invocation_context->context.AddMetadata(item.first, item.second);
}
auto callback = [cb](const InvocationContext<HeartbeatResponse>* invocation_context) {
if (!invocation_context->status.ok()) {
SPDLOG_WARN("Failed to send heartbeat to target_host={}. gRPC code: {}, message: {}",
invocation_context->remote_address, invocation_context->status.error_code(),
invocation_context->status.error_message());
std::error_code ec = ErrorCode::RequestTimeout;
cb(ec, invocation_context->response);
return;
}
auto&& status = invocation_context->response.status();
std::error_code ec;
switch (status.code()) {
case rmq::Code::OK: {
cb(ec, invocation_context->response);
break;
}
case rmq::Code::ILLEGAL_CONSUMER_GROUP: {
SPDLOG_ERROR("IllegalConsumerGroup: {}. Host={}", status.message(), invocation_context->remote_address);
ec = ErrorCode::IllegalConsumerGroup;
break;
}
case rmq::Code::TOO_MANY_REQUESTS: {
SPDLOG_WARN("TooManyRequest: {}. Host={}", status.message(), invocation_context->remote_address);
ec = ErrorCode::TooManyRequests;
cb(ec, invocation_context->response);
break;
}
case rmq::Code::UNAUTHORIZED: {
SPDLOG_WARN("Unauthorized: {}. Host={}", status.message(), invocation_context->remote_address);
ec = ErrorCode::Unauthorized;
cb(ec, invocation_context->response);
break;
}
case rmq::Code::UNRECOGNIZED_CLIENT_TYPE: {
SPDLOG_ERROR("UnsupportedClientType: {}. Host={}", status.message(), invocation_context->remote_address);
ec = ErrorCode::UnsupportedClientType;
cb(ec, invocation_context->response);
break;
}
case rmq::Code::CLIENT_ID_REQUIRED: {
SPDLOG_ERROR("ClientIdRequired: {}. Host={}", status.message(), invocation_context->remote_address);
ec = ErrorCode::InternalClientError;
cb(ec, invocation_context->response);
break;
}
case rmq::Code::INTERNAL_SERVER_ERROR: {
SPDLOG_WARN("InternalServerError: {}, host={}", status.message(), invocation_context->remote_address);
ec = ErrorCode::InternalServerError;
cb(ec, invocation_context->response);
break;
}
default: {
SPDLOG_WARN("NotSupported: Please upgrade SDK to latest release. Message={}, host={}", status.message(),
invocation_context->remote_address);
ec = ErrorCode::NotSupported;
cb(ec, invocation_context->response);
break;
}
}
};
invocation_context->callback = callback;
invocation_context->context.set_deadline(std::chrono::system_clock::now() + timeout);
client->asyncHeartbeat(request, invocation_context);
}
void ClientManagerImpl::doHeartbeat() {
if (State::STARTED != state_.load(std::memory_order_relaxed) &&
State::STARTING != state_.load(std::memory_order_relaxed)) {
SPDLOG_WARN("Unexpected client manager state={}.", state_.load(std::memory_order_relaxed));
return;
}
{
absl::MutexLock lk(&clients_mtx_);
for (const auto& item : clients_) {
auto client = item.lock();
if (client && client->active()) {
client->heartbeat();
}
}
}
}
bool ClientManagerImpl::send(const std::string& target_host,
const Metadata& metadata,
SendMessageRequest& request,
SendResultCallback cb) {
assert(cb);
SPDLOG_DEBUG("Prepare to send message to {} asynchronously. Request: {}", target_host, request.ShortDebugString());
RpcClientSharedPtr client = getRpcClient(target_host);
// Invocation context will be deleted in its onComplete() method.
auto invocation_context = new InvocationContext<SendMessageResponse>();
invocation_context->task_name = fmt::format("Send message to {}", target_host);
invocation_context->remote_address = target_host;
for (const auto& entry : metadata) {
invocation_context->context.AddMetadata(entry.first, entry.second);
}
const std::string& topic = request.messages().begin()->topic().name();
std::weak_ptr<ClientManager> client_manager(shared_from_this());
auto completion_callback = [topic, cb, client_manager,
target_host](const InvocationContext<SendMessageResponse>* invocation_context) {
ClientManagerPtr client_manager_ptr = client_manager.lock();
if (!client_manager_ptr) {
return;
}
if (State::STARTED != client_manager_ptr->state()) {
// TODO: Would this leak some memory?
return;
}
SendResult send_result = {};
send_result.target = target_host;
if (!invocation_context->status.ok()) {
SPDLOG_WARN("Failed to send message to {} due to gRPC error. gRPC code: {}, gRPC error message: {}",
invocation_context->remote_address, invocation_context->status.error_code(),
invocation_context->status.error_message());
send_result.ec = ErrorCode::RequestTimeout;
cb(send_result);
return;
}
auto&& status = invocation_context->response.status();
switch (invocation_context->response.status().code()) {
case rmq::Code::OK: {
if (!invocation_context->response.entries().empty()) {
auto first = invocation_context->response.entries().begin();
send_result.message_id = first->message_id();
send_result.transaction_id = first->transaction_id();
} else {
SPDLOG_ERROR("Unexpected send-message-response: {}", invocation_context->response.DebugString());
}
break;
}
case rmq::Code::ILLEGAL_TOPIC: {
SPDLOG_ERROR("IllegalTopic: {}. Host={}", status.message(), invocation_context->remote_address);
send_result.ec = ErrorCode::IllegalTopic;
break;
}
case rmq::Code::ILLEGAL_MESSAGE_TAG: {
SPDLOG_ERROR("IllegalMessageTag: {}. Host={}", status.message(), invocation_context->remote_address);
send_result.ec = ErrorCode::IllegalMessageTag;
break;
}
case rmq::Code::ILLEGAL_MESSAGE_KEY: {
SPDLOG_ERROR("IllegalMessageKey: {}. Host={}", status.message(), invocation_context->remote_address);
send_result.ec = ErrorCode::IllegalMessageKey;
break;
}
case rmq::Code::ILLEGAL_MESSAGE_GROUP: {
SPDLOG_ERROR("IllegalMessageGroup: {}. Host={}", status.message(), invocation_context->remote_address);
send_result.ec = ErrorCode::IllegalMessageGroup;
break;
}
case rmq::Code::ILLEGAL_MESSAGE_PROPERTY_KEY: {
SPDLOG_ERROR("IllegalMessageProperty: {}. Host={}", status.message(), invocation_context->remote_address);
send_result.ec = ErrorCode::IllegalMessageProperty;
break;
}
case rmq::Code::MESSAGE_PROPERTIES_TOO_LARGE: {
SPDLOG_ERROR("MessagePropertiesTooLarge: {}. Host={}", status.message(), invocation_context->remote_address);
send_result.ec = ErrorCode::MessagePropertiesTooLarge;
break;
}
case rmq::Code::MESSAGE_BODY_TOO_LARGE: {
SPDLOG_ERROR("MessageBodyTooLarge: {}. Host={}", status.message(), invocation_context->remote_address);
send_result.ec = ErrorCode::MessageBodyTooLarge;
break;
}
case rmq::Code::TOPIC_NOT_FOUND: {
SPDLOG_WARN("TopicNotFound: {}. Host={}", status.message(), invocation_context->remote_address);
send_result.ec = ErrorCode::TopicNotFound;
break;
}
case rmq::Code::NOT_FOUND: {
SPDLOG_WARN("NotFound: {}. Host={}", status.message(), invocation_context->remote_address);
send_result.ec = ErrorCode::NotFound;
break;
}
case rmq::Code::UNAUTHORIZED: {
SPDLOG_WARN("Unauthenticated: {}. Host={}", status.message(), invocation_context->remote_address);
send_result.ec = ErrorCode::Unauthorized;
break;
}
case rmq::Code::FORBIDDEN: {
SPDLOG_WARN("Forbidden: {}. Host={}", status.message(), invocation_context->remote_address);
send_result.ec = ErrorCode::Forbidden;
break;
}
case rmq::Code::MESSAGE_CORRUPTED: {
SPDLOG_WARN("MessageCorrupted: {}. Host={}", status.message(), invocation_context->remote_address);
send_result.ec = ErrorCode::MessageCorrupted;
break;
}
case rmq::Code::TOO_MANY_REQUESTS: {
SPDLOG_WARN("TooManyRequest: {}. Host={}", status.message(), invocation_context->remote_address);
send_result.ec = ErrorCode::TooManyRequests;
break;
}
case rmq::Code::INTERNAL_SERVER_ERROR: {
SPDLOG_WARN("InternalServerError: {}. Host={}", status.message(), invocation_context->remote_address);
send_result.ec = ErrorCode::InternalServerError;
break;
}
case rmq::Code::HA_NOT_AVAILABLE: {
SPDLOG_WARN("InternalServerError: {}. Host={}", status.message(), invocation_context->remote_address);
send_result.ec = ErrorCode::InternalServerError;
break;
}
case rmq::Code::PROXY_TIMEOUT: {
SPDLOG_WARN("GatewayTimeout: {}. Host={}", status.message(), invocation_context->remote_address);
send_result.ec = ErrorCode::GatewayTimeout;
break;
}
case rmq::Code::MASTER_PERSISTENCE_TIMEOUT: {
SPDLOG_WARN("GatewayTimeout: {}. Host={}", status.message(), invocation_context->remote_address);
send_result.ec = ErrorCode::GatewayTimeout;
break;
}
case rmq::Code::SLAVE_PERSISTENCE_TIMEOUT: {
SPDLOG_WARN("GatewayTimeout: {}. Host={}", status.message(), invocation_context->remote_address);
send_result.ec = ErrorCode::GatewayTimeout;
break;
}
case rmq::Code::MESSAGE_PROPERTY_CONFLICT_WITH_TYPE: {
SPDLOG_WARN("Message-property-conflict-with-type: Host={}, Response={}", invocation_context->remote_address,
invocation_context->response.ShortDebugString());
send_result.ec = ErrorCode::MessagePropertyConflictWithType;
break;
}
default: {
SPDLOG_WARN("NotSupported: Check and upgrade SDK to the latest. Host={}", invocation_context->remote_address);
send_result.ec = ErrorCode::NotSupported;
break;
}
}
cb(send_result);
};
invocation_context->callback = completion_callback;
client->asyncSend(request, invocation_context);
return true;
}
/**
* @brief Create a gRPC channel to target host.
*
* @param target_host
* @return std::shared_ptr<grpc::Channel>
*/
std::shared_ptr<grpc::Channel> ClientManagerImpl::createChannel(const std::string& target_host) {
std::vector<std::unique_ptr<grpc::experimental::ClientInterceptorFactoryInterface>> interceptor_factories;
interceptor_factories.emplace_back(absl::make_unique<LogInterceptorFactory>());
auto channel = grpc::experimental::CreateCustomChannelWithInterceptors(
target_host, with_ssl_ ? channel_credential_ : grpc::InsecureChannelCredentials(), channel_arguments_,
std::move(interceptor_factories));
return channel;
}
RpcClientSharedPtr ClientManagerImpl::getRpcClient(const std::string& target_host, bool need_heartbeat) {
std::shared_ptr<RpcClient> client;
{
absl::MutexLock lock(&rpc_clients_mtx_);
auto search = rpc_clients_.find(target_host);
if (search == rpc_clients_.end() || !search->second->ok()) {
if (search == rpc_clients_.end()) {
SPDLOG_INFO("Create a RPC client to [{}]", target_host.data());
} else if (!search->second->ok()) {
SPDLOG_INFO("Prior RPC client to {} is not OK. Re-create one", target_host);
}
auto channel = createChannel(target_host);
std::weak_ptr<ClientManager> client_manager(shared_from_this());
client = std::make_shared<RpcClientImpl>(client_manager, channel, target_host, need_heartbeat);
rpc_clients_.insert_or_assign(target_host, client);
} else {
client = search->second;
}
}
if (need_heartbeat && !client->needHeartbeat()) {
client->needHeartbeat(need_heartbeat);
}
return client;
}
void ClientManagerImpl::addRpcClient(const std::string& target_host, const RpcClientSharedPtr& client) {
{
absl::MutexLock lock(&rpc_clients_mtx_);
rpc_clients_.insert_or_assign(target_host, client);
}
}
void ClientManagerImpl::cleanRpcClients() {
absl::MutexLock lk(&rpc_clients_mtx_);
rpc_clients_.clear();
}
SendResult ClientManagerImpl::processSendResponse(const rmq::MessageQueue& message_queue,
const SendMessageResponse& response,
std::error_code& ec) {
SendResult send_result;
switch (response.status().code()) {
case rmq::Code::OK: {
assert(response.entries_size() > 0);
send_result.message_id = response.entries().begin()->message_id();
send_result.transaction_id = response.entries().begin()->transaction_id();
return send_result;
}
case rmq::Code::ILLEGAL_TOPIC: {
ec = ErrorCode::BadRequest;
return send_result;
}
default: {
// TODO: handle other cases.
break;
}
}
return send_result;
}
void ClientManagerImpl::addClientObserver(std::weak_ptr<Client> client) {
absl::MutexLock lk(&clients_mtx_);
clients_.emplace_back(std::move(client));
}
void ClientManagerImpl::resolveRoute(const std::string& target_host,
const Metadata& metadata,
const QueryRouteRequest& request,
std::chrono::milliseconds timeout,
const std::function<void(const std::error_code&, const TopicRouteDataPtr&)>& cb) {
SPDLOG_DEBUG("Name server connection URL: {}", target_host);
SPDLOG_DEBUG("Query route request: {}", request.ShortDebugString());
RpcClientSharedPtr client = getRpcClient(target_host, false);
if (!client) {
SPDLOG_WARN("Failed to create RPC client for name server[host={}]", target_host);
std::error_code ec = ErrorCode::RequestTimeout;
cb(ec, nullptr);
return;
}
auto invocation_context = new InvocationContext<QueryRouteResponse>();
invocation_context->task_name = fmt::format("Query route of topic={} from {}", request.topic().name(), target_host);
invocation_context->remote_address = target_host;
invocation_context->context.set_deadline(std::chrono::system_clock::now() + timeout);
for (const auto& item : metadata) {
invocation_context->context.AddMetadata(item.first, item.second);
}
auto callback = [cb](const InvocationContext<QueryRouteResponse>* invocation_context) {
if (!invocation_context->status.ok()) {
SPDLOG_WARN("Failed to send query route request to server[host={}]. Reason: {}",
invocation_context->remote_address, invocation_context->status.error_message());
std::error_code ec = ErrorCode::RequestTimeout;
cb(ec, nullptr);
return;
}
std::error_code ec;
auto&& status = invocation_context->response.status();
switch (status.code()) {
case rmq::Code::OK: {
std::vector<rmq::MessageQueue> message_queues;
for (const auto& item : invocation_context->response.message_queues()) {
message_queues.push_back(item);
}
auto ptr = std::make_shared<TopicRouteData>(std::move(message_queues));
cb(ec, ptr);
break;
}
case rmq::Code::ILLEGAL_ACCESS_POINT: {
SPDLOG_WARN("IllegalAccessPoint: {}. Host={}", status.message(), invocation_context->remote_address);
ec = ErrorCode::IllegalAccessPoint;
cb(ec, nullptr);
break;
}
case rmq::Code::UNAUTHORIZED: {
SPDLOG_WARN("Unauthorized: {}. Host={}", status.message(), invocation_context->remote_address);
ec = ErrorCode::Unauthorized;
cb(ec, nullptr);
break;
}
case rmq::Code::TOPIC_NOT_FOUND: {
SPDLOG_WARN("TopicNotFound: {}. Host={}", status.message(), invocation_context->remote_address);
ec = ErrorCode::NotFound;
cb(ec, nullptr);
break;
}
case rmq::Code::TOO_MANY_REQUESTS: {
SPDLOG_WARN("TooManyRequest: {}. Host={}", status.message(), invocation_context->remote_address);
ec = ErrorCode::TooManyRequests;
cb(ec, nullptr);
break;
}
case rmq::Code::CLIENT_ID_REQUIRED: {
SPDLOG_ERROR("ClientIdRequired: {}. Host={}", status.message(), invocation_context->remote_address);
ec = ErrorCode::InternalClientError;
cb(ec, nullptr);
break;
}
case rmq::Code::INTERNAL_SERVER_ERROR: {
SPDLOG_WARN("InternalServerError: {}. Host={}", status.message(), invocation_context->remote_address);
ec = ErrorCode::InternalServerError;
cb(ec, nullptr);
break;
}
case rmq::Code::PROXY_TIMEOUT: {
SPDLOG_WARN("GatewayTimeout: {}. Host={}", status.message(), invocation_context->remote_address);
ec = ErrorCode::GatewayTimeout;
cb(ec, nullptr);
break;
}
default: {
SPDLOG_WARN("NotImplement: Please upgrade to latest SDK release. Host={}", invocation_context->remote_address);
ec = ErrorCode::NotImplemented;
cb(ec, nullptr);
break;
}
}
};
invocation_context->callback = callback;
client->asyncQueryRoute(request, invocation_context);
}
void ClientManagerImpl::queryAssignment(
const std::string& target,
const Metadata& metadata,
const QueryAssignmentRequest& request,
std::chrono::milliseconds timeout,
const std::function<void(const std::error_code&, const QueryAssignmentResponse&)>& cb) {
SPDLOG_DEBUG("Prepare to send query assignment request to broker[address={}]", target);
std::shared_ptr<RpcClient> client = getRpcClient(target);
auto callback = [&, cb](const InvocationContext<QueryAssignmentResponse>* invocation_context) {
if (!invocation_context->status.ok()) {
SPDLOG_WARN("Failed to query assignment. Reason: {}", invocation_context->status.error_message());
std::error_code ec = ErrorCode::RequestTimeout;
cb(ec, invocation_context->response);
return;
}
auto&& status = invocation_context->response.status();
std::error_code ec;
switch (status.code()) {
case rmq::Code::OK: {
SPDLOG_DEBUG("Query assignment OK. Host={}", invocation_context->remote_address);
break;
}
case rmq::Code::ILLEGAL_ACCESS_POINT: {
SPDLOG_WARN("IllegalAccessPoint: {}, host={}", status.message(), invocation_context->remote_address);
ec = ErrorCode::IllegalAccessPoint;
break;
}
case rmq::Code::ILLEGAL_TOPIC: {
SPDLOG_WARN("IllegalAccessPoint: {}. Host={}", status.message(), invocation_context->remote_address);
ec = ErrorCode::IllegalTopic;
break;
}
case rmq::Code::ILLEGAL_CONSUMER_GROUP: {
SPDLOG_WARN("IllegalConsumerGroup: {}. Host={}", status.message(), invocation_context->remote_address);
ec = ErrorCode::IllegalConsumerGroup;
break;
}
case rmq::Code::CLIENT_ID_REQUIRED: {
SPDLOG_WARN("ClientIdRequired: {}. Host={}", status.message(), invocation_context->remote_address);
ec = ErrorCode::InternalClientError;
break;
}
case rmq::Code::UNAUTHORIZED: {
SPDLOG_WARN("Unauthorized: {}, host={}", status.message(), invocation_context->remote_address);
ec = ErrorCode::Unauthorized;
break;
}
case rmq::Code::FORBIDDEN: {
SPDLOG_WARN("Forbidden: {}, host={}", status.message(), invocation_context->remote_address);
ec = ErrorCode::Forbidden;
break;
}
case rmq::Code::TOPIC_NOT_FOUND: {
SPDLOG_WARN("TopicNotFound: {}, host={}", status.message(), invocation_context->remote_address);
ec = ErrorCode::TopicNotFound;
break;
}
case rmq::Code::CONSUMER_GROUP_NOT_FOUND: {
SPDLOG_WARN("ConsumerGroupNotFound: {}, host={}", status.message(), invocation_context->remote_address);
ec = ErrorCode::ConsumerGroupNotFound;
break;
}
case rmq::Code::INTERNAL_SERVER_ERROR: {
SPDLOG_WARN("InternalServerError: {}, host={}", status.message(), invocation_context->remote_address);
ec = ErrorCode::InternalServerError;
break;
}
case rmq::Code::PROXY_TIMEOUT: {
SPDLOG_WARN("GatewayTimeout: {}. Host={}", status.message(), invocation_context->remote_address);
ec = ErrorCode::GatewayTimeout;
break;
}
default: {
SPDLOG_WARN("NotSupported: please upgrade SDK to latest release. Host={}", invocation_context->remote_address);
ec = ErrorCode::NotSupported;
break;
}
}
cb(ec, invocation_context->response);
};
auto invocation_context = new InvocationContext<QueryAssignmentResponse>();
invocation_context->task_name = fmt::format("QueryAssignment from {}", target);
invocation_context->remote_address = target;
for (const auto& item : metadata) {
invocation_context->context.AddMetadata(item.first, item.second);
}
invocation_context->context.set_deadline(std::chrono::system_clock::now() + timeout);
invocation_context->callback = callback;
client->asyncQueryAssignment(request, invocation_context);
}
void ClientManagerImpl::receiveMessage(const std::string& target_host,
const Metadata& metadata,
const ReceiveMessageRequest& request,
std::chrono::milliseconds timeout,
ReceiveMessageCallback cb) {
SPDLOG_DEBUG("Prepare to receive message from {} asynchronously. Request: {}", target_host, request.DebugString());
RpcClientSharedPtr client = getRpcClient(target_host);
auto context = absl::make_unique<ReceiveMessageContext>();
context->callback = std::move(cb);
context->metadata = metadata;
context->timeout = timeout;
client->asyncReceive(request, std::move(context));
}
State ClientManagerImpl::state() const {
return state_.load(std::memory_order_relaxed);
}
MessageConstSharedPtr ClientManagerImpl::wrapMessage(const rmq::Message& item) {
auto builder = Message::newBuilder();
// base
builder.withTopic(item.topic().name());
const auto& system_properties = item.system_properties();
// Tag
if (system_properties.has_tag()) {
builder.withTag(system_properties.tag());
}
// Keys
std::vector<std::string> keys;
for (const auto& key : system_properties.keys()) {
keys.push_back(key);
}
if (!keys.empty()) {
builder.withKeys(std::move(keys));
}
// Message-Id
const auto& message_id = system_properties.message_id();
builder.withId(message_id);
// Validate body digest
const rmq::Digest& digest = system_properties.body_digest();
bool body_digest_match = false;
if (item.body().empty()) {
SPDLOG_WARN("Body of message[topic={}, msgId={}] is empty", item.topic().name(),
item.system_properties().message_id());
body_digest_match = true;
} else {
switch (digest.type()) {
case rmq::DigestType::CRC32: {
std::string checksum;
bool success = MixAll::crc32(item.body(), checksum);
if (success) {
body_digest_match = (digest.checksum() == checksum);
if (body_digest_match) {
SPDLOG_DEBUG("Message body CRC32 checksum validation passed.");
} else {
SPDLOG_WARN("Body CRC32 checksum validation failed. Actual: {}, expect: {}", checksum, digest.checksum());
}
} else {
SPDLOG_WARN("Failed to calculate CRC32 checksum. Skip.");
}
break;
}
case rmq::DigestType::MD5: {
std::string checksum;
bool success = MixAll::md5(item.body(), checksum);
if (success) {
body_digest_match = (digest.checksum() == checksum);
if (body_digest_match) {
SPDLOG_DEBUG("Body of message[{}] MD5 checksum validation passed.", message_id);
} else {
SPDLOG_WARN("Body of message[{}] MD5 checksum validation failed. Expect: {}, Actual: {}", message_id,
digest.checksum(), checksum);
}
} else {
SPDLOG_WARN("Failed to calculate MD5 digest. Skip.");
body_digest_match = true;
}
break;
}
case rmq::DigestType::SHA1: {
std::string checksum;
bool success = MixAll::sha1(item.body(), checksum);
if (success) {
body_digest_match = (checksum == digest.checksum());
if (body_digest_match) {
SPDLOG_DEBUG("Body of message[{}] SHA1 checksum validation passed", message_id);
} else {
SPDLOG_WARN("Body of message[{}] SHA1 checksum validation failed. Expect: {}, Actual: {}", message_id,
digest.checksum(), checksum);
}
} else {
SPDLOG_WARN("Failed to calculate SHA1 digest for message[{}]. Skip.", message_id);
}
break;
}
default: {
SPDLOG_WARN("Unsupported message body digest algorithm");
body_digest_match = true;
break;
}
}
}
if (!body_digest_match) {
SPDLOG_WARN("Message body checksum failed. MsgId={}", system_properties.message_id());
// TODO: NACK it immediately
return nullptr;
}
// Body encoding
switch (system_properties.body_encoding()) {
case rmq::Encoding::GZIP: {
std::string uncompressed;
UtilAll::uncompress(item.body(), uncompressed);
builder.withBody(uncompressed);
break;
}
case rmq::Encoding::IDENTITY: {
builder.withBody(item.body());
break;
}
default: {
SPDLOG_WARN("Unsupported encoding algorithm");
break;
}
}
// User-properties
std::unordered_map<std::string, std::string> properties;
for (const auto& it : item.user_properties()) {
properties.insert(std::make_pair(it.first, it.second));
}
if (!properties.empty()) {
builder.withProperties(properties);
}
// Born-timestamp
if (system_properties.has_born_timestamp()) {
auto born_timestamp = google::protobuf::util::TimeUtil::TimestampToMilliseconds(system_properties.born_timestamp());
builder.withBornTime(absl::ToChronoTime(absl::FromUnixMillis(born_timestamp)));
}
// Born-host
builder.withBornHost(system_properties.born_host());
// Trace-context
if (system_properties.has_trace_context()) {
builder.withTraceContext(system_properties.trace_context());
}
auto message = builder.build();
const Message* raw = message.release();
Message* msg = const_cast<Message*>(raw);
Extension& extension = msg->mutableExtension();
// Receipt-handle
extension.receipt_handle = system_properties.receipt_handle();
// Store-timestamp
if (system_properties.has_store_timestamp()) {
auto store_timestamp =
google::protobuf::util::TimeUtil::TimestampToMilliseconds(system_properties.store_timestamp());
extension.store_time = absl::ToChronoTime(absl::FromUnixMillis(store_timestamp));
}
// Store-host
extension.store_host = system_properties.store_host();
// Process one-of: delivery-timestamp and delay-level.
if (system_properties.has_delivery_timestamp()) {
auto delivery_timestamp_ms =
google::protobuf::util::TimeUtil::TimestampToMilliseconds(system_properties.delivery_timestamp());
extension.delivery_timepoint = absl::ToChronoTime(absl::FromUnixMillis(delivery_timestamp_ms));
}
// Queue-id
extension.queue_id = system_properties.queue_id();
// Queue-offset
extension.offset = system_properties.queue_offset();
// Invisible-period
if (system_properties.has_invisible_duration()) {
auto invisible_period = std::chrono::seconds(system_properties.invisible_duration().seconds()) +
std::chrono::nanoseconds(system_properties.invisible_duration().nanos());
extension.invisible_period = invisible_period;
}
// Delivery attempt
extension.delivery_attempt = system_properties.delivery_attempt();
// Decoded Time-Point
extension.decode_time = std::chrono::system_clock::now();
return MessageConstSharedPtr(raw);
}
SchedulerSharedPtr ClientManagerImpl::getScheduler() {
return scheduler_;
}
void ClientManagerImpl::ack(const std::string& target,
const Metadata& metadata,
const AckMessageRequest& request,
std::chrono::milliseconds timeout,
const std::function<void(const std::error_code&)>& cb) {
std::string target_host(target.data(), target.length());
SPDLOG_DEBUG("Prepare to ack message against {} asynchronously. AckMessageRequest: {}", target_host,
request.DebugString());
RpcClientSharedPtr client = getRpcClient(target_host);
auto invocation_context = new InvocationContext<AckMessageResponse>();
invocation_context->task_name = fmt::format("Ack messages against {}", target);
invocation_context->remote_address = target_host;
invocation_context->context.set_deadline(std::chrono::system_clock::now() + timeout);
for (const auto& item : metadata) {
invocation_context->context.AddMetadata(item.first, item.second);
}
// TODO: Use capture by move and pass-by-value paradigm when C++ 14 is available.
auto callback = [request, cb](const InvocationContext<AckMessageResponse>* invocation_context) {
std::error_code ec;
if (!invocation_context->status.ok()) {
ec = ErrorCode::RequestTimeout;
cb(ec);
return;
}
auto&& status = invocation_context->response.status();
switch (status.code()) {
case rmq::Code::OK: {
SPDLOG_DEBUG("Ack OK. host={}", invocation_context->remote_address);
break;
}