-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathAPITest.cpp
1458 lines (1264 loc) · 52.5 KB
/
APITest.cpp
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
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
#include "mat/config.h"
#ifdef _MSC_VER
#pragma warning (disable : 4389)
#endif
//#include "gtest/gtest.h"
#include "common/Common.hpp"
#include "CsProtocol_types.hpp"
#include <atomic>
#include <cassert>
#include <LogManager.hpp>
#include "PayloadDecoder.hpp"
#include "mat.h"
#include "IDecorator.hpp"
#ifdef HAVE_MAT_JSONHPP
#include <nlohmann/json.hpp>
#endif
#include "CorrelationVector.hpp"
#include "http/HttpClientFactory.hpp"
#include <list>
using namespace MAT;
LOGMANAGER_INSTANCE
// 1DSCppSdkTest sandbox key
#define TEST_TOKEN "7c8b1796cbc44bd5a03803c01c2b9d61-b6e370dd-28d9-4a52-9556-762543cf7aa7-6991"
#define KILLED_TOKEN "deadbeefdeadbeefdeadbeefdeadbeef-c2d379e0-4408-4325-9b4d-2a7d78131e14-7322"
#define TEST_TOKEN2 "0ae6cd22d8264818933f4857dd3c1472-eea5f30e-e0ed-4ab0-8ed0-4dc0f5e156e0-7385"
class TestDebugEventListener : public DebugEventListener {
public:
std::atomic<bool> netChanged;
std::atomic<unsigned> eps;
std::atomic<unsigned> numLogged0;
std::atomic<unsigned> numLogged;
std::atomic<unsigned> numSent;
std::atomic<unsigned> numDropped;
std::atomic<unsigned> numReject;
std::atomic<unsigned> numHttpError;
std::atomic<unsigned> numHttpOK;
std::atomic<unsigned> numCached;
std::atomic<unsigned> numFiltered;
std::atomic<unsigned> logLatMin;
std::atomic<unsigned> logLatMax;
std::atomic<unsigned> storageFullPct;
std::atomic<bool> storageFailed;
std::function<void(::CsProtocol::Record&)> OnLogX;
TestDebugEventListener() :
netChanged(false),
eps(0),
numLogged0(0),
numLogged(0),
numSent(0),
numDropped(0),
numReject(0),
numHttpError(0),
numHttpOK(0),
numCached(0),
numFiltered(0),
logLatMin(100),
logLatMax(0),
storageFullPct(0),
storageFailed(false)
{
resetOnLogX();
}
void reset()
{
netChanged = false;
eps = 0;
numLogged0 = 0;
numLogged = 0;
numSent = 0;
numDropped = 0;
numReject = 0;
numHttpError = 0;
numHttpOK = 0;
numCached = 0;
numFiltered = 0;
logLatMin = 100;
logLatMax = 0;
storageFullPct = 0;
storageFailed = false;
resetOnLogX();
}
virtual void OnLogXDefault(::CsProtocol::Record&)
{
};
void resetOnLogX()
{
OnLogX = [this](::CsProtocol::Record& record)
{
OnLogXDefault(record);
};
}
virtual void OnDebugEvent(DebugEvent& evt)
{
switch (evt.type) {
case EVT_LOG_EVENT:
case EVT_LOG_LIFECYCLE:
case EVT_LOG_FAILURE:
case EVT_LOG_PAGEVIEW:
case EVT_LOG_PAGEACTION:
case EVT_LOG_SAMPLEMETR:
case EVT_LOG_AGGRMETR:
case EVT_LOG_TRACE:
case EVT_LOG_USERSTATE:
case EVT_LOG_SESSION:
{
/* Test-only code */
::CsProtocol::Record& record = *static_cast<::CsProtocol::Record *>(evt.data);
numLogged++;
OnLogX(record);
}
break;
case EVT_REJECTED:
numReject++;
break;
case EVT_ADDED:
break;
/* Event counts below would never overflow the size of unsigned int */
case EVT_CACHED:
numCached += (unsigned int)evt.param1;
break;
case EVT_DROPPED:
numDropped += (unsigned int)evt.param1;
break;
case EVT_SENT:
numSent += (unsigned int)evt.param1;
break;
case EVT_STORAGE_FULL:
storageFullPct = (unsigned int)evt.param1;
break;
case EVT_STORAGE_FAILED:
storageFailed = true;
break;
case EVT_CONN_FAILURE:
case EVT_HTTP_FAILURE:
case EVT_COMPRESS_FAILED:
case EVT_UNKNOWN_HOST:
case EVT_SEND_FAILED:
case EVT_HTTP_ERROR:
numHttpError++;
break;
case EVT_HTTP_OK:
numHttpOK++;
break;
case EVT_FILTERED:
numFiltered++;
break;
case EVT_SEND_RETRY:
case EVT_SEND_RETRY_DROPPED:
break;
case EVT_NET_CHANGED:
netChanged = true;
break;
case EVT_UNKNOWN:
default:
break;
};
};
void printStats()
{
std::cerr << "[ ] netChanged = " << netChanged << std::endl;
std::cerr << "[ ] numLogged0 = " << numLogged0 << std::endl;
std::cerr << "[ ] numLogged = " << numLogged << std::endl;
std::cerr << "[ ] numSent = " << numSent << std::endl;
std::cerr << "[ ] numDropped = " << numDropped << std::endl;
std::cerr << "[ ] numReject = " << numReject << std::endl;
std::cerr << "[ ] numCached = " << numCached << std::endl;
std::cerr << "[ ] numFiltered = " << numFiltered << std::endl;
}
};
/// <summary>
/// Add all event listeners
/// </summary>
/// <param name="listener"></param>
void addAllListeners(DebugEventListener& listener)
{
LogManager::AddEventListener(DebugEventType::EVT_LOG_EVENT, listener);
LogManager::AddEventListener(DebugEventType::EVT_LOG_SESSION, listener);
LogManager::AddEventListener(DebugEventType::EVT_REJECTED, listener);
LogManager::AddEventListener(DebugEventType::EVT_SEND_FAILED, listener);
LogManager::AddEventListener(DebugEventType::EVT_SENT, listener);
LogManager::AddEventListener(DebugEventType::EVT_DROPPED, listener);
LogManager::AddEventListener(DebugEventType::EVT_HTTP_OK, listener);
LogManager::AddEventListener(DebugEventType::EVT_HTTP_ERROR, listener);
LogManager::AddEventListener(DebugEventType::EVT_SEND_RETRY, listener);
LogManager::AddEventListener(DebugEventType::EVT_SEND_RETRY_DROPPED, listener);
LogManager::AddEventListener(DebugEventType::EVT_CACHED, listener);
LogManager::AddEventListener(DebugEventType::EVT_NET_CHANGED, listener);
LogManager::AddEventListener(DebugEventType::EVT_STORAGE_FULL, listener);
LogManager::AddEventListener(DebugEventType::EVT_FILTERED, listener);
}
/// <summary>
/// Remove all event listeners
/// </summary>
/// <param name="listener"></param>
void removeAllListeners(DebugEventListener& listener)
{
LogManager::RemoveEventListener(DebugEventType::EVT_LOG_EVENT, listener);
LogManager::RemoveEventListener(DebugEventType::EVT_LOG_SESSION, listener);
LogManager::RemoveEventListener(DebugEventType::EVT_REJECTED, listener);
LogManager::RemoveEventListener(DebugEventType::EVT_SEND_FAILED, listener);
LogManager::RemoveEventListener(DebugEventType::EVT_SENT, listener);
LogManager::RemoveEventListener(DebugEventType::EVT_DROPPED, listener);
LogManager::RemoveEventListener(DebugEventType::EVT_HTTP_OK, listener);
LogManager::RemoveEventListener(DebugEventType::EVT_HTTP_ERROR, listener);
LogManager::RemoveEventListener(DebugEventType::EVT_SEND_RETRY, listener);
LogManager::RemoveEventListener(DebugEventType::EVT_SEND_RETRY_DROPPED, listener);
LogManager::RemoveEventListener(DebugEventType::EVT_CACHED, listener);
LogManager::RemoveEventListener(DebugEventType::EVT_NET_CHANGED, listener);
LogManager::RemoveEventListener(DebugEventType::EVT_STORAGE_FULL, listener);
LogManager::RemoveEventListener(DebugEventType::EVT_FILTERED, listener);
}
#ifdef HAVE_MAT_DEFAULT_HTTP_CLIENT
/// <summary>
/// Perform simple Initialize and FlushAndTeardown
/// </summary>
/// <param name=""></param>
/// <param name=""></param>
/// <returns></returns>
TEST(APITest, LogManager_Initialize_Default_Test)
{
ILogger *result = LogManager::Initialize(TEST_TOKEN);
EXPECT_EQ(true, (result != NULL));
LogManager::FlushAndTeardown();
}
/// <summary>
/// Perform Initialize and FlushAndTeardown with some options
/// </summary>
/// <param name=""></param>
/// <param name=""></param>
/// <returns></returns>
TEST(APITest, LogManager_Initialize_Custom)
{
auto& configuration = LogManager::GetLogConfiguration();
configuration[CFG_INT_TRACE_LEVEL_MASK] = 0xFFFFFFFF ^ 128; // API calls + Global mask for general messages - less SQL
configuration[CFG_INT_TRACE_LEVEL_MIN] = ACTTraceLevel_Trace;
configuration[CFG_STR_COLLECTOR_URL] = "https://127.0.0.1/";
ILogger *result = LogManager::Initialize(TEST_TOKEN, configuration);
EXPECT_EQ(true, (result != NULL));
LogManager::FlushAndTeardown();
}
#define TEST_STORAGE_FILENAME "offlinestorage.db"
static std::string GetStoragePath()
{
std::string fileName = MAT::GetTempDirectory();
#ifdef _WIN32
fileName += "\\";
#else
fileName += "/";
#endif
fileName += TEST_STORAGE_FILENAME;
return fileName;
}
static void CleanStorage()
{
std::remove(GetStoragePath().c_str());
}
#if 0
/* TODO: [maxgolov] - Issue #150: test needs to be reworked. Invalid tokens might noe get sporadically 'black-holed' with 200 OK */
TEST(APITest, LogManager_KilledEventsAreDropped)
{
constexpr static unsigned MAX_ITERATIONS = 100;
TestDebugEventListener debugListener;
auto& configuration = LogManager::GetLogConfiguration();
configuration[CFG_INT_TRACE_LEVEL_MASK] = 0xFFFFFFFF ^ 128; // API calls + Global mask for general messages - less SQL
configuration[CFG_INT_TRACE_LEVEL_MIN] = ACTTraceLevel_Info;
configuration[CFG_STR_COLLECTOR_URL] = COLLECTOR_URL_PROD;
configuration[CFG_MAP_METASTATS_CONFIG][CFG_INT_METASTATS_INTERVAL] = 0; // avoid sending stats for this test
configuration[CFG_STR_CACHE_FILE_PATH] = GetStoragePath();
configuration[CFG_INT_MAX_TEARDOWN_TIME] = 5;
CleanStorage();
ILogger *result = LogManager::Initialize(KILLED_TOKEN, configuration);
addAllListeners(debugListener);
for (int i = 0; i < 2; i++)
{
// Log some foo
size_t numIterations = MAX_ITERATIONS;
EventProperties eventToLog{ "foo1" };
eventToLog.SetLevel(DIAG_LEVEL_REQUIRED);
while (numIterations--)
result->LogEvent(eventToLog);
LogManager::UploadNow(); // Try to upload whatever we got
PAL::sleep(2000); // Give enough time to upload at least one event
if (i == 0)
{
EXPECT_EQ(MAX_ITERATIONS, debugListener.numLogged);
// TODO: it is possible that collector would return 503 here, in that case we may not get the 'kill-tokens' hint.
// If it ever happens, the test would fail because the second iteration might try to upload.
EXPECT_EQ(1u, debugListener.numHttpError);
debugListener.numCached = 0;
}
if (i == 1)
{
// At this point we should get the error response from collector because we ingested with invalid tokens.
// Collector should have also asked us to ban that token... Check the counts
EXPECT_EQ(2 * MAX_ITERATIONS, debugListener.numLogged);
EXPECT_EQ(0u, debugListener.numCached);
EXPECT_EQ(MAX_ITERATIONS, debugListener.numDropped);
}
}
LogManager::FlushAndTeardown();
EXPECT_EQ(0u, debugListener.numCached);
debugListener.printStats();
removeAllListeners(debugListener);
}
#endif
TEST(APITest, LogManager_Initialize_DebugEventListener)
{
constexpr static unsigned MAX_ITERATIONS = 100;
TestDebugEventListener debugListener;
auto& configuration = LogManager::GetLogConfiguration();
configuration[CFG_INT_TRACE_LEVEL_MASK] = 0xFFFFFFFF ^ 128; // API calls + Global mask for general messages - less SQL
configuration[CFG_INT_TRACE_LEVEL_MIN] = ACTTraceLevel_Warn; // Don't log too much on a slow machine
configuration[CFG_STR_COLLECTOR_URL] = COLLECTOR_URL_PROD;
configuration[CFG_MAP_METASTATS_CONFIG][CFG_INT_METASTATS_INTERVAL] = 0; // avoid sending stats for this test
configuration[CFG_STR_CACHE_FILE_PATH] = GetStoragePath();
configuration[CFG_INT_MAX_TEARDOWN_TIME] = 5;
configuration[CFG_INT_CACHE_FILE_SIZE] = 1024000; // 1MB
configuration[CFG_INT_STORAGE_FULL_PCT] = 1; // 1%
configuration[CFG_INT_STORAGE_FULL_CHECK_TIME] = 0; // 0ms
configuration[CFG_INT_RAM_QUEUE_SIZE] = 524288; // Requires default ram queue size otherwise skips events
EventProperties eventToLog{ "foo1" };
eventToLog.SetLevel(DIAG_LEVEL_REQUIRED);
CleanStorage();
addAllListeners(debugListener);
{
LogManager::Initialize(TEST_TOKEN, configuration);
LogManager::PauseTransmission();
size_t numIterations = MAX_ITERATIONS * 1000; // 100K events
while (numIterations--)
{
LogManager::GetLogger()->LogEvent(eventToLog);
}
LogManager::Flush();
EXPECT_GE(debugListener.storageFullPct.load(), (unsigned)100);
LogManager::FlushAndTeardown();
debugListener.storageFullPct = 0;
LogManager::Initialize(TEST_TOKEN, configuration);
LogManager::FlushAndTeardown();
EXPECT_EQ(debugListener.storageFullPct.load(), 0u);
}
debugListener.numCached = 0;
debugListener.numSent = 0;
debugListener.numLogged = 0;
CleanStorage();
ILogger *result = LogManager::Initialize(TEST_TOKEN, configuration);
// Log some foo
size_t numIterations = MAX_ITERATIONS;
while (numIterations--)
result->LogEvent(eventToLog);
// Check the counts
EXPECT_EQ(MAX_ITERATIONS, debugListener.numLogged);
EXPECT_EQ(0u, debugListener.numDropped);
EXPECT_EQ(0u, debugListener.numReject);
LogManager::UploadNow(); // Try to upload whatever we got
PAL::sleep(1000); // Give enough time to upload at least one event
EXPECT_NE(0u, debugListener.numSent); // Some posts must succeed within 500ms
LogManager::PauseTransmission(); // There could still be some pending at this point
LogManager::Flush(); // Save all pending to disk
numIterations = MAX_ITERATIONS;
debugListener.numLogged = 0; // Reset the logged counter
debugListener.numCached = 0; // Reset the flush counter
EventProperties eventToStore{ "bar2" };
eventToStore.SetLevel(DIAG_LEVEL_REQUIRED);
while (numIterations--)
result->LogEvent(eventToStore); // New events go straight to offline storage
EXPECT_EQ(MAX_ITERATIONS, debugListener.numLogged);
LogManager::Flush();
EXPECT_EQ(MAX_ITERATIONS, debugListener.numCached);
LogManager::SetTransmitProfile(TransmitProfile_RealTime);
LogManager::ResumeTransmission();
LogManager::FlushAndTeardown();
// Check that we sent all of logged + whatever left overs
// prior to PauseTransmission
EXPECT_GE(debugListener.numSent, debugListener.numLogged);
debugListener.printStats();
removeAllListeners(debugListener);
}
#ifdef _WIN32
TEST(APITest, LogManager_UTCSingleEventSent) {
auto& configuration = LogManager::GetLogConfiguration();
configuration[CFG_INT_TRACE_LEVEL_MASK] = 0xFFFFFFFF ^ 128; // API calls + Global mask for general messages - less SQL
configuration[CFG_INT_TRACE_LEVEL_MIN] = ACTTraceLevel_Info;
configuration[CFG_INT_SDK_MODE] = SdkModeTypes::SdkModeTypes_UTCCommonSchema;
configuration[CFG_STR_COLLECTOR_URL] = COLLECTOR_URL_PROD;
configuration[CFG_MAP_METASTATS_CONFIG][CFG_INT_METASTATS_INTERVAL] = 0; // avoid sending stats for this test
configuration[CFG_INT_MAX_TEARDOWN_TIME] = 5;
EventProperties event;
std::string evtType = "My.Record.BaseType"; // default v1 legacy behaviour: custom.my_record_basetype
event.SetName("MyProduct.TaggedEvent");
event.SetType(evtType);
event.SetProperty("result", "Success");
event.SetProperty("random", rand());
event.SetProperty("secret", 5.6872);
event.SetProperty(COMMONFIELDS_EVENT_PRIVTAGS, PDT_BrowsingHistory);
event.SetLatency(EventLatency_Normal);
event.SetLevel(DIAG_LEVEL_REQUIRED);
ILogger *logger = LogManager::Initialize(TEST_TOKEN, configuration);
logger->LogEvent(event);
LogManager::FlushAndTeardown();
}
#endif
TEST(APITest, LogManager_SemanticAPI)
{
bool failed = false;
try
{
ILogger *result = LogManager::Initialize(TEST_TOKEN);
// ISemanticContext *context = result->GetSemanticContext();
{
AggregatedMetricData data("agg_metric_1", 10, 10);
for (size_t i = 0; i < 10; i++)
data.aggregates[AggregateType_Sum] = 0;
EventProperties props("agg_metric_props");
result->LogAggregatedMetric(data, props);
}
{
EventProperties props("lifecycle_props");
result->LogAppLifecycle(AppLifecycleState_Suspend, props);
result->LogAppLifecycle(AppLifecycleState_Resume, props);
}
{
EventProperties props("failure_props");
result->LogFailure("failure", "unknown", props);
}
{
EventProperties props("page_action_props");
PageActionData data("page_action", ActionType_Unknown);
result->LogPageAction(data, props);
}
LogManager::FlushAndTeardown();
}
catch (...)
{
failed = true;
}
/* gtest on Linux internally casts boolean to int, which results in a compiler warning with gcc */
EXPECT_EQ(0, static_cast<int>(failed));
}
constexpr static unsigned MAX_ITERATIONS = 2000;
unsigned StressSingleThreaded(ILogConfiguration& config)
{
TestDebugEventListener debugListener;
addAllListeners(debugListener);
ILogger *result = LogManager::Initialize(TEST_TOKEN, config);
size_t numIterations = MAX_ITERATIONS;
while (numIterations--)
{
EventProperties props = testing::CreateSampleEvent("event_name", EventPriority_Normal);
result->LogEvent(props);
}
LogManager::FlushAndTeardown();
unsigned retVal = debugListener.numLogged;
removeAllListeners(debugListener);
return retVal;
}
TEST(APITest, LogManager_Stress_SingleThreaded)
{
auto& config = LogManager::GetLogConfiguration();
EXPECT_GE(StressSingleThreaded(config), MAX_ITERATIONS);
}
constexpr static unsigned MAX_ITERATIONS_MT = 100;
constexpr static unsigned MAX_THREADS = 25;
/// <summary>
/// Stresses the Upload vs Teardown multi-threaded.
/// </summary>
/// <param name="config">The configuration.</param>
void StressUploadLockMultiThreaded(ILogConfiguration& config)
{
std::srand(static_cast<unsigned int>(std::time(nullptr)));
TestDebugEventListener debugListener;
addAllListeners(debugListener);
size_t numIterations = MAX_ITERATIONS_MT;
std::mutex m_threads_mtx;
std::atomic<unsigned> threadCount(0);
while (numIterations--)
{
ILogger *result = LogManager::Initialize(TEST_TOKEN, config);
// Keep spawning UploadNow threads while the main thread is trying to perform
// Initialize and Teardown, but no more than MAX_THREADS at a time.
for (size_t i = 0; i < MAX_THREADS; i++)
{
if (threadCount++ < MAX_THREADS)
{
auto t = std::thread([&]()
{
std::this_thread::yield();
LogManager::UploadNow();
const auto randTimeSub2ms = std::rand() % 2;
PAL::sleep(randTimeSub2ms);
threadCount--;
});
t.detach();
}
};
EventProperties props = testing::CreateSampleEvent("event_name", EventPriority_Normal);
result->LogEvent(props);
LogManager::FlushAndTeardown();
}
removeAllListeners(debugListener);
}
TEST(APITest, LogManager_StressUploadLock_MultiThreaded)
{
auto& config = LogManager::GetLogConfiguration();
config[CFG_INT_MAX_TEARDOWN_TIME] = 0;
StressUploadLockMultiThreaded(config);
// Basic expectation here is just that we do not crash..
// We can add memory utilization metric in here as well.
}
TEST(APITest, LogManager_Reinitialize_Test)
{
size_t numIterations = 5;
while (numIterations--)
{
ILogger *result = LogManager::Initialize(TEST_TOKEN);
EXPECT_EQ(true, (result != NULL));
LogManager::FlushAndTeardown();
}
}
#define EVENT_NAME_PURE_C "Event.Name.Pure.C"
#define JSON_CONFIG(...) #__VA_ARGS__
TEST(APITest, C_API_Test)
{
TestDebugEventListener debugListener;
// Using some cool macro-magic trick to populate well-formed JSON in a neat way.
// Unfortunately that trick does not allow to use variables or other macros in
// config, but generally well-suited for illustrative purposes, to create easy-
// to-read JSON config file. Note __VA_ARGS__ substitution is a C++11 feature
// that isn't avail in C99
const char* config = JSON_CONFIG(
{
"cacheFilePath": "MyOfflineStorage.db",
"config" : {
"host": "*"
},
"stats" : {
"interval": 0
},
"name" : "C-API-Client-0",
"version" : "1.0.0",
"primaryToken" : "7c8b1796cbc44bd5a03803c01c2b9d61-b6e370dd-28d9-4a52-9556-762543cf7aa7-6991",
"maxTeardownUploadTimeInSec" : 5,
"hostMode" : false,
"minimumTraceLevel" : 0,
"sdkmode" : 0
}
);
std::time_t now = time(0);
MAT::time_ticks_t ticks(&now);
evt_prop event[] = TELEMETRY_EVENT
(
// Part A/B fields
_STR(COMMONFIELDS_EVENT_NAME, EVENT_NAME_PURE_C), // Event name
_INT(COMMONFIELDS_EVENT_TIME, static_cast<int64_t>(now * 1000L)), // Epoch time in millis, ms since Jan 01 1970. (UTC)
_DBL("popSample", 100.0), // Effective sample rate
_STR(COMMONFIELDS_IKEY, TEST_TOKEN), // iKey to send this event to
_INT(COMMONFIELDS_EVENT_POLICYFLAGS, 0xffffffff), // UTC policy bitflags (optional)
_INT(COMMONFIELDS_EVENT_PRIORITY, static_cast<int64_t>(EventPriority_Immediate)),
_INT(COMMONFIELDS_EVENT_LATENCY, static_cast<int64_t>(EventLatency_Max)),
_INT(COMMONFIELDS_EVENT_LEVEL, DIAG_LEVEL_REQUIRED),
// Customer Data fields go as part of userdata
_STR("strKey", "value1"),
_INT("intKey", 12345),
_DBL("dblKey", 3.14),
_BOOL("boolKey", true),
_GUID("guidKey", "{01020304-0506-0708-090a-0b0c0d0e0f00}" ),
_TIME("timeKey", ticks.ticks), // .NET ticks
// All Pii types get treated as strings by the backend
PII_STR("piiKey", "secret", (int)PiiKind_Identity)
);
// event[2].value.as_double = 100.0f;
unsigned totalEvents = 0;
debugListener.OnLogX = [&](::CsProtocol::Record& record)
{
totalEvents++;
// Verify event name
EXPECT_EQ(record.name, EVENT_NAME_PURE_C);
// Verify event time
auto recordTimeTicks = MAT::time_ticks_t(record.time);
EXPECT_EQ(record.time, int64_t(recordTimeTicks.ticks) );
// Verify event iKey
std::string iToken_o = "o:";
iToken_o += TEST_TOKEN;
EXPECT_THAT(iToken_o, testing::HasSubstr(record.iKey));
// Verify string
ASSERT_STREQ(record.data[0].properties["strKey"].stringValue.c_str(), "value1");
// Verify integer
ASSERT_EQ(record.data[0].properties["intKey"].longValue, 12345);
// Verify double
ASSERT_EQ(record.data[0].properties["dblKey"].doubleValue, 3.14);
// Verify boolean
ASSERT_EQ(record.data[0].properties["boolKey"].longValue, 1);
// Verify GUID
auto guid = record.data[0].properties["guidKey"].guidValue[0].data();
auto guidStr = GUID_t(guid).to_string();
std::string guidStr2 = "01020304-0506-0708-090a-0b0c0d0e0f00";
ASSERT_STRCASEEQ(guidStr.c_str(), guidStr2.c_str());
// Verify time
ASSERT_EQ(record.data[0].properties["timeKey"].longValue, (int64_t)ticks.ticks);
};
evt_handle_t handle = evt_open(config);
ASSERT_NE(handle, 0);
capi_client *client = capi_get_client(handle);
ASSERT_NE(client, nullptr);
ASSERT_NE(client->logmanager, nullptr);
// Bind from C API LogManager instance to C++ DebugEventListener
// to verify event contents. Currently we do not support registering
// debug callbacks via C API, so we obtain the ILogManager first,
// then register event listener on it.
client->logmanager->AddEventListener(EVT_LOG_EVENT, debugListener);
// Ingest 5 events via C API
for (size_t i = 0; i < 5; i++)
{
evt_log(handle, event);
}
EXPECT_EQ(totalEvents, 5u);
evt_flush(handle);
evt_upload(handle);
// Must remove event listener befor closing the handle!
client->logmanager->RemoveEventListener(EVT_LOG_EVENT, debugListener);
evt_flushAndTeardown(handle);
evt_close(handle);
ASSERT_EQ(capi_get_client(handle), nullptr);
// Re-open with the same configuration
handle = evt_open(config);
ASSERT_NE(handle, 0);
client = capi_get_client(handle);
ASSERT_NE(client, nullptr);
ASSERT_NE(client->logmanager, nullptr);
// Re-close
evt_close(handle);
ASSERT_EQ(capi_get_client(handle), nullptr);
}
#ifdef HAVE_MAT_JSONHPP
#if defined(_WIN32)
TEST(APITest, UTC_Callback_Test)
{
TestDebugEventListener debugListener;
auto& configuration = LogManager::GetLogConfiguration();
configuration[CFG_INT_SDK_MODE] = SdkModeTypes::SdkModeTypes_UTCCommonSchema;
std::time_t now = time(0);
MAT::time_ticks_t ticks(&now);
LogManager::AddEventListener(EVT_LOG_EVENT, debugListener);
auto logger = LogManager::Initialize(TEST_TOKEN);
unsigned totalEvents = 0;
debugListener.OnLogX = [&](::CsProtocol::Record& record)
{
totalEvents++;
// Verify event name
EXPECT_EQ(record.name, "MyProduct.UtcEvent");
// Verify event time
auto recordTimeTicks = MAT::time_ticks_t(record.time);
EXPECT_EQ(record.time, int64_t(recordTimeTicks.ticks));
// Verify event iKey
std::string iToken_o = "o:";
iToken_o += TEST_TOKEN;
EXPECT_THAT(iToken_o, testing::HasSubstr(record.iKey));
// Verify string
ASSERT_STREQ(record.data[0].properties["strKey"].stringValue.c_str(), "value1");
// Verify integer
ASSERT_EQ(record.data[0].properties["intKey"].longValue, 12345);
// Verify double
ASSERT_EQ(record.data[0].properties["dblKey"].doubleValue, 3.14);
// Verify boolean
ASSERT_EQ(record.data[0].properties["boolKey"].longValue, 1);
// Verify GUID
auto guid = record.data[0].properties["guidKey"].guidValue[0].data();
auto guidStr = GUID_t(guid).to_string();
std::string guidStr2 = "01020304-0506-0708-090a-0b0c0d0e0f00";
ASSERT_STRCASEEQ(guidStr.c_str(), guidStr2.c_str());
// Verify time
ASSERT_EQ(record.data[0].properties["timeKey"].longValue, (int64_t)ticks.ticks);
// Transform to JSON and print
std::string s;
exporters::DecodeRecord(record, s);
printf(
"*************************************** Event %u ***************************************\n%s\n",
totalEvents,
s.c_str()
);
};
// Ingest 3 events via C++ API in UTC mode. Callback function above intercepts
// these events as CsRecord, then invokes PayloadDecoder to represent as JSON.
for (size_t i = 0; i < 3; i++)
{
EventProperties event("MyProduct.UtcEvent",
{
{ "strKey", "value1" },
{ "intKey", 12345 },
{ "dblKey", 3.14 },
{ "boolKey", true },
{ "guidKey", GUID_t("{01020304-0506-0708-090a-0b0c0d0e0f00}") },
{ "timeKey", ticks }
});
event.SetTimestamp((int64_t)(now * 1000L));
logger->LogEvent(event);
}
LogManager::FlushAndTeardown();
LogManager::RemoveEventListener(EVT_LOG_EVENT, debugListener);
}
#endif
TEST(APITest, Pii_DROP_Test)
{
TestDebugEventListener debugListener;
auto& config = LogManager::GetLogConfiguration();
config[CFG_INT_SDK_MODE] = SdkModeTypes::SdkModeTypes_CS;
config[CFG_MAP_METASTATS_CONFIG][CFG_INT_METASTATS_INTERVAL] = 0; // avoid sending stats for this test
config[CFG_INT_MAX_TEARDOWN_TIME] = 1; // give enough time to upload
// register a listener
LogManager::AddEventListener(EVT_LOG_EVENT, debugListener);
auto logger = LogManager::Initialize(TEST_TOKEN);
unsigned totalEvents = 0;
std::string realDeviceId;
// verify that we get one regular event with real device id,
// as well as more events with anonymous random device id.
debugListener.OnLogX = [&](::CsProtocol::Record& record)
{
totalEvents++;
if (record.name == "Regular.Event")
{
// usual event with proper SDK-obtained localId
realDeviceId = record.extDevice[0].localId;
EXPECT_STREQ(record.extUser[0].localId.c_str(), "c:1234567890");
return;
}
ASSERT_EQ(record.extProtocol[0].ticketKeys.size(), 0ul);
// more events with random device id
EXPECT_STRNE(record.extDevice[0].localId.c_str(), realDeviceId.c_str());
EXPECT_STREQ(record.extDevice[0].authId.c_str(), "");
EXPECT_STREQ(record.extDevice[0].authSecId.c_str(), "");
EXPECT_STREQ(record.extDevice[0].id.c_str(), "");
// ext.user.localId stripped
EXPECT_STREQ(record.extUser[0].localId.c_str(), "");
EXPECT_STREQ(record.extUser[0].authId.c_str(), "");
EXPECT_STREQ(record.extUser[0].id.c_str(), "");
// SDK tracking cookies stripped
EXPECT_EQ(record.extSdk[0].seq, 0);
EXPECT_STREQ(record.extSdk[0].epoch.c_str(), "");
EXPECT_STREQ(record.extSdk[0].installId.c_str(), "");
// cV stripped
EXPECT_STREQ(record.cV.c_str(), "");
};
auto context = logger->GetSemanticContext();
context->SetUserId("c:1234567890");
// Set some random cV
CorrelationVector m_appCV;
m_appCV.SetValue("jj9XLhDw7EuXoC2L");
// Extend that value.
m_appCV.Extend();
// Get the next value, log it and/or pass it to your downstream dependency.
std::string curCV = m_appCV.GetNextValue();
logger->LogEvent("Regular.Event");
for (size_t i = 0; i < 3; i++)
{
EventProperties event("PiiDrop.Event",
{
{ "strKey", "some string" }
});
event.SetPolicyBitFlags(MICROSOFT_EVENTTAG_DROP_PII);
event.SetProperty(CorrelationVector::PropertyName, curCV);
logger->LogEvent(event);
}
LogManager::FlushAndTeardown();
ASSERT_EQ(totalEvents, 4u);
LogManager::RemoveEventListener(EVT_LOG_EVENT, debugListener);
}
#endif
TEST(APITest, SemanticContext_Test)
{
TestDebugEventListener debugListener;
auto& config = LogManager::GetLogConfiguration();
config[CFG_INT_SDK_MODE] = SdkModeTypes::SdkModeTypes_CS;
config[CFG_MAP_METASTATS_CONFIG][CFG_INT_METASTATS_INTERVAL] = 0; // avoid sending stats for this test
config[CFG_INT_MAX_TEARDOWN_TIME] = 1; // give enough time to upload
// register a listener
LogManager::AddEventListener(EVT_LOG_EVENT, debugListener);
CleanStorage();
auto logger = LogManager::Initialize(TEST_TOKEN);
unsigned totalEvents = 0;
// Verify that semantic context fields have been set on record
debugListener.OnLogX = [&](::CsProtocol::Record& record) {
totalEvents++;
if (record.name == "LoggerContext.Event")
{
// App extension
EXPECT_STREQ(record.extApp[0].env.c_str(), "dev");
EXPECT_STREQ(record.extApp[0].id.c_str(), "myAppId");
EXPECT_STREQ(record.extApp[0].locale.c_str(), "en-US");
EXPECT_STREQ(record.extApp[0].name.c_str(), "myAppName");
EXPECT_STREQ(record.extApp[0].ver.c_str(), "1.2.3");
// Device extension
EXPECT_STREQ(record.extDevice[0].deviceClass.c_str(), "Custom.Desktop");
EXPECT_STREQ(record.extDevice[0].localId.c_str(), "c:1234567890");
// Legacy schema quirk that forces SDK to send devMake and devModel under protocol extension
EXPECT_STREQ(record.extProtocol[0].devMake.c_str(), "Make");
EXPECT_STREQ(record.extProtocol[0].devModel.c_str(), "Model");
// Commercial Id
EXPECT_STREQ(record.extM365a[0].enrolledTenantId.c_str(), "1-2-3-4-5");
// Network extension
EXPECT_STREQ(record.extNet[0].cost.c_str(), "Unmetered");
EXPECT_STREQ(record.extNet[0].provider.c_str(), "Provider");
EXPECT_STREQ(record.extNet[0].type.c_str(), "Wifi");
// OS extension. 1DS SDK maps OS Build semantic context field to ext.os.ver
EXPECT_STREQ(record.extOs[0].ver.c_str(), "os-build");
EXPECT_STREQ(record.extOs[0].name.c_str(), "os-name");
// User extension
EXPECT_STREQ(record.extUser[0].localId.c_str(), "localUserId");
EXPECT_STREQ(record.extUser[0].locale.c_str(), "en-US");
EXPECT_STREQ(record.extLoc[0].timezone.c_str(), "+01:00");
}
};
auto context = logger->GetSemanticContext();
// App extension
context->SetAppEnv("dev");
context->SetAppId("myAppId");
context->SetAppLanguage("en-US");
context->SetAppName("myAppName");
context->SetAppVersion("1.2.3");
// Device extension
context->SetDeviceClass("Custom.Desktop");
context->SetDeviceId("c:1234567890");
context->SetDeviceMake("Make");
context->SetDeviceModel("Model");
// Commercial Id aka. Office Enrolled Tenant Id
context->SetCommercialId("1-2-3-4-5");
// Network extension
context->SetNetworkCost(NetworkCost_Unmetered);
context->SetNetworkProvider("Provider");
context->SetNetworkType(NetworkType_Wifi);
// OS extension
context->SetOsBuild("os-build");
context->SetOsName("os-name");
context->SetOsVersion("1.0.0");
// User extension
context->SetUserId("localUserId");
context->SetUserLanguage("en-US");
context->SetUserTimeZone("+01:00");
logger->LogEvent("LoggerContext.Event");
LogManager::FlushAndTeardown();
ASSERT_EQ(totalEvents, 1u);
LogManager::RemoveEventListener(EVT_LOG_EVENT, debugListener);
}
TEST(APITest, SetType_Test)
{
TestDebugEventListener debugListener;
for (auto customPrefix : {EVENTRECORD_TYPE_CUSTOM_EVENT, ""})
{
auto& config = LogManager::GetLogConfiguration();
config[CFG_INT_SDK_MODE] = SdkModeTypes::SdkModeTypes_CS;
config[CFG_MAP_METASTATS_CONFIG][CFG_INT_METASTATS_INTERVAL] = 0; // avoid sending stats for this test
config[CFG_INT_MAX_TEARDOWN_TIME] = 0;
// Iterate over default ("custom") and empty prefix.
config[CFG_MAP_COMPAT][CFG_STR_COMPAT_PREFIX] = customPrefix;
// Register a listener.
LogManager::AddEventListener(EVT_LOG_EVENT, debugListener);
// Clean storage to avoid polluting our test callback by unwanted events.
CleanStorage();
auto logger = LogManager::Initialize(TEST_TOKEN);
unsigned totalEvents = 0;
// We don't need to upload for this test.
LogManager::PauseTransmission();
// Verify that record.baseType have been properly decorated.
debugListener.OnLogX = [&](::CsProtocol::Record& record) {
totalEvents++;
const std::string& prefix = config[CFG_MAP_COMPAT][CFG_STR_COMPAT_PREFIX];
if (prefix == EVENTRECORD_TYPE_CUSTOM_EVENT)