PocketMine-MP 5.21.2 git-a6534ecbbbcf369264567d27e5ed70f7f5be9816
Loading...
Searching...
No Matches
PacketRateLimiter.php
1<?php
2
3/*
4 *
5 * ____ _ _ __ __ _ __ __ ____
6 * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
7 * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
8 * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
9 * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
10 *
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU Lesser General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * @author PocketMine Team
17 * @link http://www.pocketmine.net/
18 *
19 *
20 */
21
22declare(strict_types=1);
23
24namespace pocketmine\network\mcpe;
25
27use function hrtime;
28use function intdiv;
29use function min;
30
37 private int $budget;
38 private int $lastUpdateTimeNs;
39 private int $maxBudget;
40
41 public function __construct(
42 private string $name,
43 private int $averagePerTick,
44 int $maxBufferTicks,
45 private int $updateFrequencyNs = 50_000_000,
46 ){
47 $this->maxBudget = $this->averagePerTick * $maxBufferTicks;
48 $this->budget = $this->maxBudget;
49 $this->lastUpdateTimeNs = hrtime(true);
50 }
51
55 public function decrement(int $amount = 1) : void{
56 if($this->budget <= 0){
57 $this->update();
58 if($this->budget <= 0){
59 throw new PacketHandlingException("Exceeded rate limit for \"$this->name\"");
60 }
61 }
62 $this->budget -= $amount;
63 }
64
65 public function update() : void{
66 $nowNs = hrtime(true);
67 $timeSinceLastUpdateNs = $nowNs - $this->lastUpdateTimeNs;
68 if($timeSinceLastUpdateNs > $this->updateFrequencyNs){
69 $ticksSinceLastUpdate = intdiv($timeSinceLastUpdateNs, $this->updateFrequencyNs);
70 /*
71 * If the server takes an abnormally long time to process a tick, add the budget for time difference to
72 * compensate. This extra budget may be very large, but it will disappear the next time a normal update
73 * occurs. This ensures that backlogs during a large lag spike don't cause everyone to get kicked.
74 * As long as all the backlogged packets are processed before the next tick, everything should be OK for
75 * clients behaving normally.
76 */
77 $this->budget = min($this->budget, $this->maxBudget) + ($this->averagePerTick * 2 * $ticksSinceLastUpdate);
78 $this->lastUpdateTimeNs = $nowNs;
79 }
80 }
81}