1// Per-connection token buckets with the retry hint clients understand:2// "rate-limited: quota exceeded; retry in Ns".34export class Bucket {5 private tokens: number;6 private last = Date.now();78 constructor(private perMinute: number) {9 this.tokens = perMinute;10 }1112 // take returns "" if allowed, else the NIP-01 reason with a retry hint.13 take(perMinute = this.perMinute): string {14 this.perMinute = perMinute;15 const now = Date.now();16 this.tokens = Math.min(perMinute, this.tokens + ((now - this.last) / 60_000) * perMinute);17 this.last = now;18 if (this.tokens >= 1) {19 this.tokens -= 1;20 return "";21 }22 const wait = Math.ceil(((1 - this.tokens) / perMinute) * 60);23 return `rate-limited: quota exceeded; retry in ${Math.max(wait, 1)}s`;24 }25}