|
| 1 | +package gg.beemo.vanilla |
| 2 | + |
| 3 | +import gg.beemo.latte.logging.Log |
| 4 | +import gg.beemo.latte.proto.RatelimitGrpcKt |
| 5 | +import gg.beemo.latte.proto.RatelimitQuota |
| 6 | +import gg.beemo.latte.proto.ratelimitQuota |
| 7 | +import gg.beemo.latte.proto.RatelimitRequest |
| 8 | +import gg.beemo.latte.proto.RatelimitType |
| 9 | +import kotlinx.coroutines.sync.Mutex |
| 10 | +import kotlinx.coroutines.sync.withLock |
| 11 | +import java.util.LinkedList |
| 12 | +import java.util.concurrent.ConcurrentHashMap |
| 13 | +import kotlin.time.Duration |
| 14 | +import kotlin.time.Duration.Companion.seconds |
| 15 | + |
| 16 | +class GrpcRatelimitService : RatelimitGrpcKt.RatelimitCoroutineImplBase() { |
| 17 | + |
| 18 | + private val log by Log |
| 19 | + private val globalRatelimits = ClientRatelimits(50, 1.seconds) |
| 20 | + private val identifyRatelimits = ClientRatelimits(1, 5.seconds) |
| 21 | + |
| 22 | + override suspend fun reserveQuota(request: RatelimitRequest): RatelimitQuota { |
| 23 | + val clientRatelimits = when (request.type) { |
| 24 | + RatelimitType.GLOBAL -> globalRatelimits |
| 25 | + RatelimitType.IDENTIFY -> identifyRatelimits |
| 26 | + else -> throw IllegalArgumentException("Unknown ratelimit type ${request.type}") |
| 27 | + } |
| 28 | + |
| 29 | + val ratelimit = clientRatelimits.getClientRatelimit(request.clientId) |
| 30 | + val maxDelay = if (request.hasMaxDelay()) request.maxDelay.toLong() else null |
| 31 | + val (granted, at) = ratelimit.reserveQuota(request.probeOnly, maxDelay) |
| 32 | + val delay = (at - System.currentTimeMillis()).coerceAtLeast(0) |
| 33 | + |
| 34 | + if (request.probeOnly) { |
| 35 | + log.debug( |
| 36 | + "Probed {} quota slot for clientId {} is at {} (in {} ms)", |
| 37 | + request.type, |
| 38 | + request.clientId, |
| 39 | + at, |
| 40 | + delay |
| 41 | + ) |
| 42 | + } else if (granted) { |
| 43 | + log.debug( |
| 44 | + "Reserved {} quota slot for clientId {} at {} (in {} ms)", |
| 45 | + request.type, |
| 46 | + request.clientId, |
| 47 | + at, |
| 48 | + delay |
| 49 | + ) |
| 50 | + } else { |
| 51 | + val maxTimestamp = if (maxDelay != null) System.currentTimeMillis() + maxDelay else null |
| 52 | + log.debug( |
| 53 | + "Failed to reserve {} quota slot for clientId {}, next slot would be at {} (in {} ms), requested max delay was {} (-> {})", |
| 54 | + request.type, |
| 55 | + request.clientId, |
| 56 | + at, |
| 57 | + delay, |
| 58 | + maxDelay, |
| 59 | + maxTimestamp |
| 60 | + ) |
| 61 | + } |
| 62 | + |
| 63 | + return ratelimitQuota { |
| 64 | + this.granted = granted |
| 65 | + this.at = at |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | +} |
| 70 | + |
| 71 | +private class ClientRatelimits(private val burst: Int, private val duration: Duration) { |
| 72 | + |
| 73 | + private val limiters = ConcurrentHashMap<Long, RatelimitQueue>() |
| 74 | + |
| 75 | + fun getClientRatelimit(clientId: Long): RatelimitQueue = limiters.computeIfAbsent(clientId) { |
| 76 | + RatelimitQueue(burst, duration) |
| 77 | + } |
| 78 | + |
| 79 | +} |
| 80 | + |
| 81 | +data class RatelimitSlot( |
| 82 | + var usedQuota: Int, |
| 83 | + val startsAt: Long, |
| 84 | + val endsAt: Long, |
| 85 | +) |
| 86 | + |
| 87 | +private class RatelimitQueue(private val burst: Int, private val duration: Duration) { |
| 88 | + |
| 89 | + private val queue = LinkedList<RatelimitSlot>() |
| 90 | + private val lock = Mutex() |
| 91 | + |
| 92 | + suspend fun reserveQuota(probeOnly: Boolean = false, maxDelay: Long? = null): Pair<Boolean, Long> = |
| 93 | + lock.withLock { |
| 94 | + val now = System.currentTimeMillis() |
| 95 | + |
| 96 | + // Clean up expired slots |
| 97 | + while (queue.isNotEmpty() && now > queue.first.endsAt) { |
| 98 | + queue.removeFirst() |
| 99 | + } |
| 100 | + |
| 101 | + // Find free slot at the end of the queue |
| 102 | + val lastSlot = queue.lastOrNull() |
| 103 | + // No slots are used, so ratelimit is immediately available |
| 104 | + if (lastSlot == null) { |
| 105 | + // No timeout to check if we can immediately grant quota |
| 106 | + if (probeOnly) { |
| 107 | + return@withLock false to 0 |
| 108 | + } |
| 109 | + queue.add(RatelimitSlot(1, now, now + duration.inWholeMilliseconds)) |
| 110 | + return@withLock true to 0 |
| 111 | + } |
| 112 | + |
| 113 | + // Check if slot still has quota available |
| 114 | + if (lastSlot.usedQuota < burst) { |
| 115 | + val exceedsDelay = maxDelay != null && lastSlot.startsAt > now + maxDelay |
| 116 | + if (exceedsDelay || probeOnly) { |
| 117 | + return@withLock false to lastSlot.startsAt |
| 118 | + } |
| 119 | + lastSlot.usedQuota++ |
| 120 | + return@withLock true to lastSlot.startsAt |
| 121 | + } |
| 122 | + |
| 123 | + // Slot is full, create new slot |
| 124 | + val exceedsDelay = maxDelay != null && lastSlot.endsAt > now + maxDelay |
| 125 | + if (exceedsDelay || probeOnly) { |
| 126 | + return@withLock false to lastSlot.endsAt |
| 127 | + } |
| 128 | + val nextStart = lastSlot.endsAt |
| 129 | + val nextEnd = nextStart + duration.inWholeMilliseconds |
| 130 | + queue.add(RatelimitSlot(1, nextStart, nextEnd)) |
| 131 | + return@withLock true to nextStart |
| 132 | + } |
| 133 | + |
| 134 | +} |
0 commit comments