-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathclient_impl.cpp
More file actions
434 lines (369 loc) · 15.5 KB
/
client_impl.cpp
File metadata and controls
434 lines (369 loc) · 15.5 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
#include "client_impl.hpp"
#include "data_sources/null_data_source.hpp"
#include "data_sources/polling_data_source.hpp"
#include "data_sources/streaming_data_source.hpp"
#include <launchdarkly/events/asio_event_processor.hpp>
#include <launchdarkly/events/null_event_processor.hpp>
#include <launchdarkly/detail/c_binding_helpers.hpp>
#include <launchdarkly/encoding/sha_256.hpp>
#include <launchdarkly/logging/console_backend.hpp>
#include <launchdarkly/logging/null_logger.hpp>
#include <chrono>
#include <optional>
#include <utility>
namespace launchdarkly::client_side {
// The ASIO implementation assumes that the io_context will be run from a
// single thread, and applies several optimisations based on this
// assumption.
auto const kAsioConcurrencyHint = 1;
// Client's destructor attempts to gracefully shut down the datasource
// connection in this amount of time.
auto const kDataSourceShutdownWait = std::chrono::milliseconds(100);
using config::shared::ClientSDK;
using launchdarkly::client_side::data_sources::DataSourceStatus;
using launchdarkly::config::shared::built::DataSourceConfig;
using launchdarkly::config::shared::built::HttpProperties;
static std::shared_ptr<data_sources::IDataSource> MakeDataSource(
HttpProperties const& http_properties,
Config const& config,
Context const& context,
boost::asio::any_io_executor const& executor,
IDataSourceUpdateSink& flag_updater,
data_sources::DataSourceStatusManager& status_manager,
Logger& logger) {
if (config.Offline()) {
return std::make_shared<data_sources::NullDataSource>(executor,
status_manager);
}
auto builder = HttpPropertiesBuilder(http_properties);
auto data_source_properties = builder.Build();
if (config.DataSourceConfig().method.index() == 0) {
return std::make_shared<
launchdarkly::client_side::data_sources::StreamingDataSource>(
config.ServiceEndpoints(), config.DataSourceConfig(),
data_source_properties, executor, context, flag_updater,
status_manager, logger);
}
return std::make_shared<
launchdarkly::client_side::data_sources::PollingDataSource>(
config.ServiceEndpoints(), config.DataSourceConfig(),
data_source_properties, executor, context, flag_updater, status_manager,
logger);
}
static Logger MakeLogger(config::shared::built::Logging const& config) {
if (config.disable_logging) {
return {std::make_shared<logging::NullLoggerBackend>()};
}
if (config.backend) {
return {config.backend};
}
return {
std::make_shared<logging::ConsoleBackend>(config.level, config.tag)};
}
static std::shared_ptr<IPersistence> MakePersistence(Config const& config) {
auto persistence = config.Persistence();
if (persistence.disable_persistence) {
return nullptr;
}
return persistence.implementation;
}
ClientImpl::ClientImpl(Config in_cfg,
Context context,
std::string const& version)
: config_(std::move(in_cfg)), /* caution: do not use in_cfg (moved from!) */
http_properties_(
HttpPropertiesBuilder(config_.HttpProperties())
.Header("user-agent", "CPPClient/" + version)
.Header("authorization", config_.SdkKey())
.Header("x-launchdarkly-tags", config_.ApplicationTag())
.Build()),
logger_(MakeLogger(config_.Logging())),
ioc_(kAsioConcurrencyHint),
work_(boost::asio::make_work_guard(ioc_)),
context_(std::move(context)),
flag_manager_(config_.SdkKey(),
logger_,
config_.Persistence().max_contexts_,
MakePersistence(config_)),
data_source_factory_([this]() {
return MakeDataSource(http_properties_, config_, context_,
ioc_.get_executor(), flag_manager_.Updater(),
status_manager_, logger_);
}),
data_source_(nullptr),
event_processor_(nullptr),
eval_reasons_available_(config_.DataSourceConfig().with_reasons) {
flag_manager_.LoadCache(context_);
if (auto custom_ca = http_properties_.Tls().CustomCAFile()) {
LD_LOG(logger_, LogLevel::kInfo)
<< "TLS peer verification configured with custom CA file: "
<< *custom_ca;
}
if (http_properties_.Tls().PeerVerifyMode() ==
config::shared::built::TlsOptions::VerifyMode::kVerifyNone) {
LD_LOG(logger_, LogLevel::kInfo) << "TLS peer verification disabled";
}
if (config_.Events().Enabled() && !config_.Offline()) {
event_processor_ =
std::make_unique<events::AsioEventProcessor<ClientSDK>>(
ioc_.get_executor(), config_.ServiceEndpoints(),
config_.Events(), http_properties_, logger_);
} else {
event_processor_ = std::make_unique<events::NullEventProcessor>();
}
event_processor_->SendAsync(events::IdentifyEventParams{
std::chrono::system_clock::now(), context_});
run_thread_ = std::move(std::thread([&]() { ioc_.run(); }));
}
// Returns true if the SDK can be considered initialized. We have defined
// explicit configuration of offline mode as initialized.
//
// When online, we're initialized if we've obtained a payload and are healthy
// (kValid) or obtained a payload and are unhealthy (kInterrupted).
//
// The purpose of this concept is to enable:
//
// (1) Resolving the StartAsync() promise. Once the SDK is no longer
// initializing, this promise needs to indicate if the process was successful
// or not.
//
// (2) Providing a getter for (1), if the user didn't check the promise or
// otherwise need to poll the state. That's the Initialized() method.
//
// (3) As a diagnostic during evaluation, to log a message warning that a
// cached (if persistence is being used) or default (if not) value will be
// returned because the SDK is not yet initialized.
static bool IsInitializedSuccessfully(DataSourceStatus::DataSourceState state) {
return (state == DataSourceStatus::DataSourceState::kValid ||
state == DataSourceStatus::DataSourceState::kSetOffline ||
state == DataSourceStatus::DataSourceState::kInterrupted);
}
std::future<bool> ClientImpl::IdentifyAsync(Context context) {
UpdateContextSynchronized(context);
flag_manager_.LoadCache(context);
event_processor_->SendAsync(events::IdentifyEventParams{
std::chrono::system_clock::now(), std::move(context)});
return StartAsyncInternal();
}
void ClientImpl::RestartDataSource() {
auto start_op = [this]() {
data_source_ = data_source_factory_();
data_source_->Start();
};
if (!data_source_) {
return start_op();
}
data_source_->ShutdownAsync(start_op);
}
std::future<bool> ClientImpl::StartAsyncInternal() {
auto init_promise = std::make_shared<std::promise<bool>>();
auto init_future = init_promise->get_future();
status_manager_.OnDataSourceStatusChangeEx(
[init_promise](data_sources::DataSourceStatus const& status) {
if (auto const state = status.State();
state != DataSourceStatus::DataSourceState::kInitializing) {
init_promise->set_value(
IsInitializedSuccessfully(status.State()));
return true; /* delete this change listener since the desired
state was reached */
}
return false; /* keep the change listener */
});
RestartDataSource();
return init_future;
}
std::future<bool> ClientImpl::StartAsync() {
return StartAsyncInternal();
}
bool ClientImpl::Initialized() const {
return IsInitializedSuccessfully(status_manager_.Status().State());
}
std::unordered_map<Client::FlagKey, Value> ClientImpl::AllFlags() const {
std::unordered_map<Client::FlagKey, Value> result;
for (auto& [key, descriptor] : flag_manager_.Store().GetAll()) {
if (descriptor->item) {
result.try_emplace(key, descriptor->item->Detail().Value());
}
}
return result;
}
void ClientImpl::TrackInternal(std::string event_name,
std::optional<Value> data,
std::optional<double> metric_value) {
event_processor_->SendAsync(events::TrackEventParams{
std::chrono::system_clock::now(), std::move(event_name),
ReadContextSynchronized(
[](Context const& c) { return c.KindsToKeys(); }),
std::move(data), metric_value});
}
void ClientImpl::Track(std::string event_name,
Value data,
double metric_value) {
this->TrackInternal(std::move(event_name), std::move(data), metric_value);
}
void ClientImpl::Track(std::string event_name, Value data) {
this->TrackInternal(std::move(event_name), std::move(data), std::nullopt);
}
void ClientImpl::Track(std::string event_name) {
this->TrackInternal(std::move(event_name), std::nullopt, std::nullopt);
}
void ClientImpl::FlushAsync() {
event_processor_->FlushAsync();
}
template <typename T>
EvaluationDetail<T> ClientImpl::VariationInternal(FlagKey const& key,
Value default_value,
bool check_type,
bool detailed) {
auto desc = flag_manager_.Store().Get(key);
events::FeatureEventParams event = {
std::chrono::system_clock::now(),
key,
ReadContextSynchronized([](Context const& c) { return c; }),
default_value,
default_value,
std::nullopt,
std::nullopt,
std::nullopt,
false,
std::nullopt,
};
if (!desc || !desc->item) {
if (!Initialized()) {
LD_LOG(logger_, LogLevel::kWarn)
<< "LaunchDarkly client has not yet been initialized. "
"Returning default value";
auto error_reason =
EvaluationReason(EvaluationReason::ErrorKind::kClientNotReady);
if (eval_reasons_available_) {
event.reason = error_reason;
}
event_processor_->SendAsync(std::move(event));
return EvaluationDetail<T>(default_value, std::nullopt,
std::move(error_reason));
}
LD_LOG(logger_, LogLevel::kInfo)
<< "Unknown feature flag " << key << "; returning default value";
auto error_reason =
EvaluationReason(EvaluationReason::ErrorKind::kFlagNotFound);
if (eval_reasons_available_) {
event.reason = error_reason;
}
event_processor_->SendAsync(std::move(event));
return EvaluationDetail<T>(default_value, std::nullopt,
std::move(error_reason));
}
if (!Initialized()) {
LD_LOG(logger_, LogLevel::kInfo)
<< "LaunchDarkly client has not yet been initialized. "
"Returning cached value";
}
LD_ASSERT(desc->item);
auto const& flag = *(desc->item);
auto const& detail = flag.Detail();
// The Prerequisites vector represents the evaluated prerequisites of
// this flag. We need to generate events for both this flag and its
// prerequisites (recursively), which is necessary to ensure LaunchDarkly
// analytics functions properly.
//
// We're using JsonVariation because the type of the
// prerequisite is both unknown and irrelevant to emitting the events.
//
// We're passing Value::Null() to match a server-side SDK's behavior when
// evaluating prerequisites.
//
// NOTE: if "hooks" functionality is implemented into this SDK, take care
// that evaluating prerequisites does not trigger hooks. This may require
// refactoring the code below to not use JsonVariation.
if (auto const prereqs = flag.Prerequisites()) {
for (auto const& prereq : *prereqs) {
JsonVariation(prereq, Value::Null());
}
}
if (check_type && default_value.Type() != Value::Type::kNull &&
detail.Value().Type() != default_value.Type()) {
auto error_reason =
EvaluationReason(EvaluationReason::ErrorKind::kWrongType);
if (eval_reasons_available_) {
event.reason = error_reason;
}
event_processor_->SendAsync(std::move(event));
return EvaluationDetail<T>(default_value, std::nullopt, error_reason);
}
event.value = detail.Value();
event.variation = detail.VariationIndex();
if (detailed || flag.TrackReason()) {
event.reason = detail.Reason();
}
event.version = flag.FlagVersion().value_or(flag.Version());
event.require_full_event = flag.TrackEvents();
if (auto date = flag.DebugEventsUntilDate()) {
event.debug_events_until_date = events::Date{*date};
}
event_processor_->SendAsync(std::move(event));
return EvaluationDetail<T>(detail.Value(), detail.VariationIndex(),
detail.Reason());
}
EvaluationDetail<bool> ClientImpl::BoolVariationDetail(
IClient::FlagKey const& key,
bool default_value) {
return VariationInternal<bool>(key, default_value, true, true);
}
bool ClientImpl::BoolVariation(IClient::FlagKey const& key,
bool default_value) {
return *VariationInternal<bool>(key, default_value, true, false);
}
EvaluationDetail<std::string> ClientImpl::StringVariationDetail(
ClientImpl::FlagKey const& key,
std::string default_value) {
return VariationInternal<std::string>(key, std::move(default_value), true,
true);
}
std::string ClientImpl::StringVariation(IClient::FlagKey const& key,
std::string default_value) {
return *VariationInternal<std::string>(key, std::move(default_value), true,
false);
}
EvaluationDetail<double> ClientImpl::DoubleVariationDetail(
ClientImpl::FlagKey const& key,
double default_value) {
return VariationInternal<double>(key, default_value, true, true);
}
double ClientImpl::DoubleVariation(IClient::FlagKey const& key,
double default_value) {
return *VariationInternal<double>(key, default_value, true, false);
}
EvaluationDetail<int> ClientImpl::IntVariationDetail(
IClient::FlagKey const& key,
int default_value) {
return VariationInternal<int>(key, default_value, true, true);
}
int ClientImpl::IntVariation(IClient::FlagKey const& key, int default_value) {
return *VariationInternal<int>(key, default_value, true, false);
}
EvaluationDetail<Value> ClientImpl::JsonVariationDetail(
IClient::FlagKey const& key,
Value default_value) {
return VariationInternal<Value>(key, std::move(default_value), false, true);
}
Value ClientImpl::JsonVariation(IClient::FlagKey const& key,
Value default_value) {
return *VariationInternal<Value>(key, std::move(default_value), false,
false);
}
data_sources::IDataSourceStatusProvider& ClientImpl::DataSourceStatus() {
return status_manager_;
}
flag_manager::IFlagNotifier& ClientImpl::FlagNotifier() {
return flag_manager_.Notifier();
}
void ClientImpl::UpdateContextSynchronized(Context context) {
std::unique_lock lock(context_mutex_);
context_ = std::move(context);
}
ClientImpl::~ClientImpl() {
ioc_.stop();
// TODO(SC-219101)
run_thread_.join();
}
} // namespace launchdarkly::client_side