DownloadManager.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. <?php
  2. /*
  3. * This file is part of Packagist.
  4. *
  5. * (c) Jordi Boggiano <j.boggiano@seld.be>
  6. * Nils Adermann <naderman@naderman.de>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Packagist\WebBundle\Model;
  12. use Doctrine\Common\Persistence\ManagerRegistry;
  13. use Doctrine\DBAL\Connection;
  14. use Packagist\WebBundle\Entity\Package;
  15. use Packagist\WebBundle\Entity\Version;
  16. use Packagist\WebBundle\Entity\Download;
  17. use Predis\Client;
  18. use DateTimeImmutable;
  19. /**
  20. * Manages the download counts for packages.
  21. */
  22. class DownloadManager
  23. {
  24. protected $redis;
  25. protected $doctrine;
  26. protected $redisCommandLoaded = false;
  27. public function __construct(Client $redis, ManagerRegistry $doctrine)
  28. {
  29. $this->redis = $redis;
  30. $this->doctrine = $doctrine;
  31. }
  32. /**
  33. * Gets the total, monthly, and daily download counts for an entire package or optionally a version.
  34. *
  35. * @param \Packagist\WebBundle\Entity\Package|int $package
  36. * @param \Packagist\WebBundle\Entity\Version|int|null $version
  37. * @return array
  38. */
  39. public function getDownloads($package, $version = null)
  40. {
  41. if ($package instanceof Package) {
  42. $package = $package->getId();
  43. }
  44. if ($version instanceof Version) {
  45. $version = $version->getId();
  46. }
  47. $type = Download::TYPE_PACKAGE;
  48. $id = $package;
  49. $keyBase = 'dl:'.$package;
  50. if ($version !== null) {
  51. $id = $version;
  52. $type = Download::TYPE_VERSION;
  53. $keyBase .= '-'.$version;
  54. }
  55. $record = $this->doctrine->getRepository(Download::class)->findOneBy(['id' => $id, 'type' => $type]);
  56. $dlData = $record ? $record->getData() : [];
  57. $keyBase .= ':';
  58. $date = new \DateTime();
  59. $todayDate = $date->format('Ymd');
  60. $yesterdayDate = date('Ymd', $date->format('U') - 86400);
  61. // fetch today, yesterday and the latest total from redis
  62. $redisData = $this->redis->mget([$keyBase.$todayDate, $keyBase.$yesterdayDate, 'dl:'.$package]);
  63. $monthly = 0;
  64. for ($i = 0; $i < 30; $i++) {
  65. // current day and previous day might not be in db yet or incomplete, so we take the data from redis if there is still data there
  66. if ($i <= 1) {
  67. $monthly += $redisData[$i] ?? $dlData[$date->format('Ymd')] ?? 0;
  68. } else {
  69. $monthly += $dlData[$date->format('Ymd')] ?? 0;
  70. }
  71. $date->modify('-1 day');
  72. }
  73. $total = (int) $redisData[2];
  74. if ($version) {
  75. $total = $record ? $record->getTotal() : 0;
  76. }
  77. // how much of yesterday to add to today to make it a whole day (sort of..)
  78. $dayRatio = (2400 - (int) date('Hi')) / 2400;
  79. return [
  80. 'total' => $total,
  81. 'monthly' => $monthly,
  82. 'daily' => round(($redisData[0] ?? $dlData[$todayDate] ?? 0) + (($redisData[1] ?? $dlData[$yesterdayDate] ?? 0) * $dayRatio)),
  83. 'views' => $this->redis->incr('views:'.$package),
  84. ];
  85. }
  86. /**
  87. * Gets the total download count for a package.
  88. *
  89. * @param \Packagist\WebBundle\Entity\Package|int $package
  90. * @return int
  91. */
  92. public function getTotalDownloads($package)
  93. {
  94. if ($package instanceof Package) {
  95. $package = $package->getId();
  96. }
  97. return (int) $this->redis->get('dl:' . $package) ?: 0;
  98. }
  99. /**
  100. * Gets total download counts for multiple package IDs.
  101. *
  102. * @param array $packageIds
  103. * @return array a map of package ID to download count
  104. */
  105. public function getPackagesDownloads(array $packageIds)
  106. {
  107. $keys = array();
  108. foreach ($packageIds as $id) {
  109. if (ctype_digit((string) $id)) {
  110. $keys[$id] = 'dl:'.$id;
  111. }
  112. }
  113. if (!$keys) {
  114. return array();
  115. }
  116. $res = array_map('intval', $this->redis->mget(array_values($keys)));
  117. return array_combine(array_keys($keys), $res);
  118. }
  119. /**
  120. * Tracks downloads by updating the relevant keys.
  121. *
  122. * @param array[] an array of arrays containing id (package id), vid (version id) and ip keys
  123. */
  124. public function addDownloads(array $jobs)
  125. {
  126. $day = date('Ymd');
  127. $month = date('Ym');
  128. if (!$this->redisCommandLoaded) {
  129. $this->redis->getProfile()->defineCommand('downloadsIncr', 'Packagist\Redis\DownloadsIncr');
  130. $this->redisCommandLoaded = true;
  131. }
  132. $args = ['downloads', 'downloads:'.$day, 'downloads:'.$month];
  133. foreach ($jobs as $job) {
  134. $package = $job['id'];
  135. $version = $job['vid'];
  136. // throttle key
  137. $args[] = 'throttle:'.$package.':'.$day;
  138. // stats keys
  139. $args[] = 'dl:'.$package;
  140. $args[] = 'dl:'.$package.':'.$day;
  141. $args[] = 'dl:'.$package.'-'.$version.':'.$day;
  142. }
  143. $args[] = $job['ip'];
  144. $this->redis->downloadsIncr(...$args);
  145. }
  146. public function transferDownloadsToDb(int $packageId, array $keys, DateTimeImmutable $now)
  147. {
  148. $package = $this->doctrine->getRepository(Package::class)->findOneById($packageId);
  149. // package was deleted in the meantime, abort
  150. if (!$package) {
  151. $this->redis->del($keys);
  152. return;
  153. }
  154. $versionsWithDownloads = [];
  155. foreach ($keys as $key) {
  156. if (preg_match('{^dl:'.$packageId.'-(\d+):\d+$}', $key, $match)) {
  157. $versionsWithDownloads[(int) $match[1]] = true;
  158. }
  159. }
  160. $rows = $this->doctrine->getManager()->getConnection()->fetchAll(
  161. 'SELECT id FROM package_version WHERE id IN (:ids)',
  162. ['ids' => array_keys($versionsWithDownloads)],
  163. ['ids' => Connection::PARAM_INT_ARRAY]
  164. );
  165. $versionIds = [];
  166. foreach ($rows as $row) {
  167. $versionIds[] = (int) $row['id'];
  168. }
  169. unset($versionsWithDownloads, $rows, $row);
  170. sort($keys);
  171. $values = $this->redis->mget($keys);
  172. $buffer = [];
  173. $lastPrefix = null;
  174. foreach ($keys as $index => $key) {
  175. $prefix = preg_replace('{:\d+$}', ':', $key);
  176. if ($lastPrefix && $prefix !== $lastPrefix && $buffer) {
  177. $this->createDbRecordsForKeys($package, $buffer, $versionIds, $now);
  178. $buffer = [];
  179. }
  180. $buffer[$key] = (int) $values[$index];
  181. $lastPrefix = $prefix;
  182. }
  183. if ($buffer) {
  184. $this->createDbRecordsForKeys($package, $buffer, $versionIds, $now);
  185. }
  186. $this->doctrine->getManager()->flush();
  187. $this->redis->del($keys);
  188. }
  189. private function createDbRecordsForKeys(Package $package, array $keys, array $validVersionIds, DateTimeImmutable $now)
  190. {
  191. reset($keys);
  192. list($id, $type) = $this->getKeyInfo(key($keys));
  193. // skip if the version was deleted in the meantime
  194. if ($type === Download::TYPE_VERSION && !in_array($id, $validVersionIds, true)) {
  195. return;
  196. }
  197. $record = $this->doctrine->getRepository(Download::class)->findOneBy(['id' => $id, 'type' => $type]);
  198. $isNewRecord = false;
  199. if (!$record) {
  200. $record = new Download();
  201. $record->setId($id);
  202. $record->setType($type);
  203. $record->setPackage($package);
  204. $isNewRecord = true;
  205. }
  206. $record->setLastUpdated($now);
  207. foreach ($keys as $key => $val) {
  208. $date = preg_replace('{^.*?:(\d+)$}', '$1', $key);
  209. if ($val) {
  210. $record->setDataPoint($date, $val);
  211. }
  212. }
  213. // only store records for packages or for versions that have had downloads to avoid storing empty records
  214. if ($isNewRecord && ($type === Download::TYPE_PACKAGE || count($record->getData()) > 0)) {
  215. $this->doctrine->getManager()->persist($record);
  216. }
  217. $record->computeSum();
  218. }
  219. private function getKeyInfo(string $key): array
  220. {
  221. if (preg_match('{^dl:(\d+):}', $key, $match)) {
  222. return [(int) $match[1], Download::TYPE_PACKAGE];
  223. }
  224. if (preg_match('{^dl:\d+-(\d+):}', $key, $match)) {
  225. return [(int) $match[1], Download::TYPE_VERSION];
  226. }
  227. throw new \LogicException('Invalid key given: '.$key);
  228. }
  229. }