The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

353 lines
11KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. namespace juce
  18. {
  19. ThreadedAnalyticsDestination::ThreadedAnalyticsDestination (const String& threadName)
  20. : dispatcher (threadName, *this)
  21. {}
  22. ThreadedAnalyticsDestination::~ThreadedAnalyticsDestination()
  23. {
  24. // If you hit this assertion then the analytics thread has not been shut down
  25. // before this class is destroyed. Call stopAnalyticsThread() in your destructor!
  26. jassert (! dispatcher.isThreadRunning());
  27. }
  28. void ThreadedAnalyticsDestination::setBatchPeriod (int newBatchPeriodMilliseconds)
  29. {
  30. dispatcher.batchPeriodMilliseconds = newBatchPeriodMilliseconds;
  31. }
  32. void ThreadedAnalyticsDestination::logEvent (const AnalyticsEvent& event)
  33. {
  34. dispatcher.addToQueue (event);
  35. }
  36. void ThreadedAnalyticsDestination::startAnalyticsThread (int initialBatchPeriodMilliseconds)
  37. {
  38. setBatchPeriod (initialBatchPeriodMilliseconds);
  39. dispatcher.startThread();
  40. }
  41. void ThreadedAnalyticsDestination::stopAnalyticsThread (int timeout)
  42. {
  43. dispatcher.signalThreadShouldExit();
  44. stopLoggingEvents();
  45. dispatcher.stopThread (timeout);
  46. if (dispatcher.eventQueue.size() > 0)
  47. saveUnloggedEvents (dispatcher.eventQueue);
  48. }
  49. ThreadedAnalyticsDestination::EventDispatcher::EventDispatcher (const String& threadName,
  50. ThreadedAnalyticsDestination& destination)
  51. : Thread (threadName),
  52. parent (destination)
  53. {}
  54. void ThreadedAnalyticsDestination::EventDispatcher::run()
  55. {
  56. // We may have inserted some events into the queue (on the message thread)
  57. // before this thread has started, so make sure the old events are at the
  58. // front of the queue.
  59. {
  60. std::deque<AnalyticsEvent> restoredEventQueue;
  61. parent.restoreUnloggedEvents (restoredEventQueue);
  62. const ScopedLock lock (queueAccess);
  63. for (auto rit = restoredEventQueue.rbegin(); rit != restoredEventQueue.rend(); ++rit)
  64. eventQueue.push_front (*rit);
  65. }
  66. const int maxBatchSize = parent.getMaximumBatchSize();
  67. while (! threadShouldExit())
  68. {
  69. auto eventsToSendCapacity = maxBatchSize - eventsToSend.size();
  70. if (eventsToSendCapacity > 0)
  71. {
  72. const ScopedLock lock (queueAccess);
  73. const auto numEventsInQueue = (int) eventQueue.size();
  74. if (numEventsInQueue > 0)
  75. {
  76. const auto numEventsToAdd = jmin (eventsToSendCapacity, numEventsInQueue);
  77. for (size_t i = 0; i < (size_t) numEventsToAdd; ++i)
  78. eventsToSend.add (eventQueue[i]);
  79. }
  80. }
  81. const auto submissionTime = Time::getMillisecondCounter();
  82. if (! eventsToSend.isEmpty())
  83. {
  84. if (parent.logBatchedEvents (eventsToSend))
  85. {
  86. const ScopedLock lock (queueAccess);
  87. for (auto i = 0; i < eventsToSend.size(); ++i)
  88. eventQueue.pop_front();
  89. eventsToSend.clearQuick();
  90. }
  91. }
  92. while (Time::getMillisecondCounter() - submissionTime < (uint32) batchPeriodMilliseconds.get())
  93. {
  94. if (threadShouldExit())
  95. return;
  96. Thread::sleep (100);
  97. }
  98. }
  99. }
  100. void ThreadedAnalyticsDestination::EventDispatcher::addToQueue (const AnalyticsEvent& event)
  101. {
  102. const ScopedLock lock (queueAccess);
  103. eventQueue.push_back (event);
  104. }
  105. //==============================================================================
  106. #if JUCE_UNIT_TESTS
  107. namespace DestinationTestHelpers
  108. {
  109. //==============================================================================
  110. struct TestDestination : public ThreadedAnalyticsDestination
  111. {
  112. TestDestination (std::deque<AnalyticsEvent>& loggedEvents,
  113. std::deque<AnalyticsEvent>& unloggedEvents)
  114. : ThreadedAnalyticsDestination ("ThreadedAnalyticsDestinationTest"),
  115. loggedEventQueue (loggedEvents),
  116. unloggedEventStore (unloggedEvents)
  117. {}
  118. virtual ~TestDestination() {}
  119. int getMaximumBatchSize() override
  120. {
  121. return 5;
  122. }
  123. void saveUnloggedEvents (const std::deque<AnalyticsEvent>& eventsToSave) override
  124. {
  125. unloggedEventStore = eventsToSave;
  126. }
  127. void restoreUnloggedEvents (std::deque<AnalyticsEvent>& restoredEventQueue) override
  128. {
  129. restoredEventQueue = unloggedEventStore;
  130. }
  131. std::deque<AnalyticsEvent>& loggedEventQueue;
  132. std::deque<AnalyticsEvent>& unloggedEventStore;
  133. };
  134. //==============================================================================
  135. struct BasicDestination : public TestDestination
  136. {
  137. BasicDestination (std::deque<AnalyticsEvent>& loggedEvents,
  138. std::deque<AnalyticsEvent>& unloggedEvents)
  139. : TestDestination (loggedEvents, unloggedEvents)
  140. {
  141. startAnalyticsThread (20);
  142. }
  143. virtual ~BasicDestination()
  144. {
  145. stopAnalyticsThread (1000);
  146. }
  147. bool logBatchedEvents (const Array<AnalyticsEvent>& events) override
  148. {
  149. jassert (events.size() <= getMaximumBatchSize());
  150. for (auto& event : events)
  151. loggedEventQueue.push_back (event);
  152. return true;
  153. }
  154. void stopLoggingEvents() override {}
  155. };
  156. //==============================================================================
  157. struct SlowWebDestination : public TestDestination
  158. {
  159. SlowWebDestination (std::deque<AnalyticsEvent>& loggedEvents,
  160. std::deque<AnalyticsEvent>& unloggedEvents)
  161. : TestDestination (loggedEvents, unloggedEvents)
  162. {
  163. startAnalyticsThread (initialPeriod);
  164. }
  165. virtual ~SlowWebDestination()
  166. {
  167. stopAnalyticsThread (1000);
  168. }
  169. bool logBatchedEvents (const Array<AnalyticsEvent>& events) override
  170. {
  171. threadHasStarted.signal();
  172. jassert (events.size() <= getMaximumBatchSize());
  173. {
  174. const ScopedLock lock (webStreamCreation);
  175. if (shouldExit)
  176. return false;
  177. // An attempt to connect to an unroutable IP address will hang
  178. // indefinitely, which simulates a very slow server
  179. webStream = new WebInputStream (URL ("http://1.192.0.0"), true);
  180. }
  181. String data;
  182. for (auto& event : events)
  183. data << event.name;
  184. webStream->withExtraHeaders (data);
  185. const auto success = webStream->connect (nullptr);
  186. // Exponential backoff on failure
  187. if (success)
  188. period = initialPeriod;
  189. else
  190. period *= 2;
  191. setBatchPeriod (period);
  192. return success;
  193. }
  194. void stopLoggingEvents() override
  195. {
  196. const ScopedLock lock (webStreamCreation);
  197. shouldExit = true;
  198. if (webStream != nullptr)
  199. webStream->cancel();
  200. }
  201. const int initialPeriod = 100;
  202. int period = initialPeriod;
  203. CriticalSection webStreamCreation;
  204. bool shouldExit = false;
  205. ScopedPointer<WebInputStream> webStream;
  206. WaitableEvent threadHasStarted;
  207. };
  208. }
  209. //==============================================================================
  210. struct ThreadedAnalyticsDestinationTests : public UnitTest
  211. {
  212. ThreadedAnalyticsDestinationTests()
  213. : UnitTest ("ThreadedAnalyticsDestination")
  214. {}
  215. void compareEventQueues (const std::deque<AnalyticsDestination::AnalyticsEvent>& a,
  216. const std::deque<AnalyticsDestination::AnalyticsEvent>& b)
  217. {
  218. const auto numEntries = a.size();
  219. expectEquals (b.size(), numEntries);
  220. for (size_t i = 0; i < numEntries; ++i)
  221. {
  222. expectEquals (a[i].name, b[i].name);
  223. expect (a[i].timestamp == b[i].timestamp);
  224. }
  225. }
  226. void runTest() override
  227. {
  228. std::deque<AnalyticsDestination::AnalyticsEvent> testEvents;
  229. for (int i = 0; i < 7; ++i)
  230. testEvents.push_back ({ String (i), 0, Time::getMillisecondCounter(), {}, "TestUser", {} });
  231. std::deque<AnalyticsDestination::AnalyticsEvent> loggedEvents, unloggedEvents;
  232. beginTest ("Basic");
  233. {
  234. {
  235. DestinationTestHelpers::BasicDestination destination (loggedEvents, unloggedEvents);
  236. for (auto& event : testEvents)
  237. destination.logEvent (event);
  238. Thread::sleep (400);
  239. }
  240. compareEventQueues (loggedEvents, testEvents);
  241. expect (unloggedEvents.size() == 0);
  242. loggedEvents.clear();
  243. }
  244. beginTest ("Web");
  245. {
  246. {
  247. DestinationTestHelpers::SlowWebDestination destination (loggedEvents, unloggedEvents);
  248. for (auto& event : testEvents)
  249. destination.logEvent (event);
  250. }
  251. expect (loggedEvents.size() == 0);
  252. compareEventQueues (unloggedEvents, testEvents);
  253. {
  254. DestinationTestHelpers::SlowWebDestination destination (loggedEvents, unloggedEvents);
  255. destination.threadHasStarted.wait();
  256. unloggedEvents.clear();
  257. }
  258. expect (loggedEvents.size() == 0);
  259. compareEventQueues (unloggedEvents, testEvents);
  260. unloggedEvents.clear();
  261. }
  262. }
  263. };
  264. static ThreadedAnalyticsDestinationTests threadedAnalyticsDestinationTests;
  265. #endif
  266. } // namespace juce