# x/time

`golang.org/x/time/rate` 提供以「權杖桶（token bucket）」演算法實作的限流器，用來控制每秒最多做幾次事。

- Module：`golang.org/x/time`
- 本書使用版本：v0.16.0（需要 Go 1.26 以上）

## 這個庫做什麼

呼叫第三方 API 常有「每秒最多 10 次」的限制；自己的伺服器也需要擋下同一個用戶端的大量請求。這類「限流（rate limiting）」需求，標準庫只有 `time.Ticker` 可以湊合，但它無法處理「平常慢慢來、偶爾允許一小波突發」的情況，也不能搭配 context 取消。

`x/time` 目前只有一個常用子套件 `rate`，核心是 `rate.Limiter`。它的模型是一個桶子：

| 名詞 | 意思 | 比喻 |
| --- | --- | --- |
| 速率（limit） | 每秒往桶裡補幾個權杖 | 水龍頭的流速 |
| 突發量（burst） | 桶子最多裝幾個權杖 | 桶子的容量 |
| 權杖（token） | 每做一件事要花掉一個 | 一杯水 |

桶子一開始是滿的。每次請求拿走權杖；桶空了就要等補充，或直接拒絕。

## 安裝

```bash
go get golang.org/x/time@v0.16.0
```

```go
import "golang.org/x/time/rate"
```

## 建立限流器

### NewLimiter、Every、Limit 與 Burst

`rate.Limit` 是 `float64`，單位是「每秒幾個權杖」。`rate.Every(d)` 把「每隔多久一個」換算成 `Limit`，讀起來比較直覺。`rate.Inf` 表示不限速。

簽名：

```go
func NewLimiter(r Limit, b int) *Limiter
func Every(interval time.Duration) Limit
func (lim *Limiter) Limit() Limit
func (lim *Limiter) Burst() int
```

範例：

```go
package main

import (
	"fmt"
	"time"

	"golang.org/x/time/rate"
)

func main() {
	a := rate.NewLimiter(rate.Limit(5), 10)
	b := rate.NewLimiter(rate.Every(200*time.Millisecond), 1)
	c := rate.NewLimiter(rate.Inf, 0)

	fmt.Println("a:", a.Limit(), "tokens/s, burst", a.Burst())
	fmt.Println("b:", b.Limit(), "tokens/s, burst", b.Burst())
	fmt.Println("c is Inf:", c.Limit() == rate.Inf)
}
```

輸出：

```text
a: 5 tokens/s, burst 10
b: 5 tokens/s, burst 1
c is Inf: true
```

`rate.Every(200*time.Millisecond)` 就是每秒 5 個。`Limiter` 可以被多個 goroutine 同時使用，通常整個程式（或每個用戶端）共用一個。

注意：burst 為 0 時，除非速率是 `rate.Inf`，否則任何請求都不會被允許。

## 三種取用方式

`Limiter` 提供三組方法，差別在「權杖不夠時怎麼辦」：

| 方法 | 權杖不夠時 | 適合 |
| --- | --- | --- |
| `Allow` / `AllowN` | 立刻回傳 `false`，不扣權杖 | HTTP 伺服器回 429 |
| `Wait` / `WaitN` | 阻塞等到有權杖，或 context 結束 | 背景工作、呼叫外部 API |
| `Reserve` / `ReserveN` | 先預約，告訴你要等多久 | 需要自己決定等或不等 |

帶 `N` 的版本一次取 n 個權杖；`AllowN`、`ReserveN` 另外接受一個 `time.Time` 參數，代表「以這個時間點計算」，方便測試時固定時間。

### AllowN：以固定時間檢查

範例把時間固定在 `t0`，所以輸出每次都一樣。速率每 100 毫秒一個、桶容量 3：

- 在 `t0` 連續取 5 次：前 3 次用光滿桶，後 2 次被拒
- 過 100 毫秒只補回 1 個
- 過 1 秒最多補到 3 個（不會超過 burst）

簽名：

```go
func (lim *Limiter) AllowN(t time.Time, n int) bool
func (lim *Limiter) TokensAt(t time.Time) float64
```

範例：

```go
package main

import (
	"fmt"
	"time"

	"golang.org/x/time/rate"
)

func main() {
	lim := rate.NewLimiter(rate.Every(100*time.Millisecond), 3)
	t0 := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)

	for i := 1; i <= 5; i++ {
		fmt.Printf("t0 request %d: %v\n", i, lim.AllowN(t0, 1))
	}

	t1 := t0.Add(100 * time.Millisecond)
	fmt.Println("t0+100ms:", lim.AllowN(t1, 1), lim.AllowN(t1, 1))

	t2 := t0.Add(time.Second)
	fmt.Printf("t0+1s tokens: %.1f\n", lim.TokensAt(t2))
	fmt.Println("t0+1s take 3:", lim.AllowN(t2, 3))
	fmt.Println("take 4 > burst:", lim.AllowN(t2.Add(time.Hour), 4))
}
```

輸出：

```text
t0 request 1: true
t0 request 2: true
t0 request 3: true
t0 request 4: false
t0 request 5: false
t0+100ms: true false
t0+1s tokens: 3.0
t0+1s take 3: true
take 4 > burst: false
```

注意：`n` 大於 burst 時永遠回傳 `false`，等多久都一樣。傳入的時間應該遞增，傳入比上次更早的時間不會「退回」權杖。

### Allow：拒絕超量請求

`Allow()` 等於 `AllowN(time.Now(), 1)`，是 HTTP 伺服器限流最常見的寫法：拿不到權杖就回 `429 Too Many Requests`。

簽名：

```go
func (lim *Limiter) Allow() bool
```

範例中每秒補 1 個、桶容量 2，瞬間來了 4 個請求：

```go
package main

import (
	"fmt"
	"time"

	"golang.org/x/time/rate"
)

func main() {
	lim := rate.NewLimiter(rate.Every(time.Second), 2)

	for i := 1; i <= 4; i++ {
		if lim.Allow() {
			fmt.Printf("request %d: served\n", i)
		} else {
			fmt.Printf("request %d: 429 Too Many Requests\n", i)
		}
	}
}
```

輸出：

```text
request 1: served
request 2: served
request 3: 429 Too Many Requests
request 4: 429 Too Many Requests
```

實際的伺服器通常為每個 IP 或 API key 各存一個 `Limiter`（例如放在加鎖的 map 中），在 middleware 裡呼叫 `Allow`。

### Wait：排隊等權杖

`Wait(ctx)` 會阻塞到拿到權杖為止，適合「慢慢做，但不要超速」的工作，例如爬蟲或批次呼叫外部 API。

- 成功：回傳 nil
- context 被取消：回傳錯誤
- 預估要等的時間會超過 context 的期限：**立刻**回傳錯誤，不會白等

簽名：

```go
func (lim *Limiter) Wait(ctx context.Context) error
func (lim *Limiter) WaitN(ctx context.Context, n int) error
```

範例：

```go
package main

import (
	"context"
	"fmt"
	"time"

	"golang.org/x/time/rate"
)

func main() {
	lim := rate.NewLimiter(rate.Every(50*time.Millisecond), 1)
	ctx := context.Background()

	start := time.Now()
	for i := 1; i <= 3; i++ {
		if err := lim.Wait(ctx); err != nil {
			fmt.Println("wait:", err)
			return
		}
		fmt.Printf("job %d started\n", i)
	}
	fmt.Println("took at least 100ms:", time.Since(start) >= 100*time.Millisecond)

	slow := rate.NewLimiter(rate.Every(time.Minute), 1)
	slow.Allow()
	timeoutCtx, cancel := context.WithTimeout(ctx, time.Second)
	defer cancel()
	fmt.Println("wait:", slow.Wait(timeoutCtx))
}
```

輸出：

```text
job 1 started
job 2 started
job 3 started
took at least 100ms: true
wait: rate: Wait(n=1) would exceed context deadline
```

第一個工作用掉滿桶的權杖，後兩個各等 50 毫秒。第二段的限流器每分鐘才補一個，而 context 只給 1 秒，`Wait` 判斷等不到就馬上回報。

### ReserveN：先預約再決定

`Reserve` 不會阻塞，也不會拒絕，而是回傳一張 `*Reservation`（預約單），告訴你「要等多久才輪到你」。你可以自己 `time.Sleep(r.Delay())` 後再做事，也可以覺得太久而 `Cancel()` 把權杖還回去。

簽名：

```go
func (lim *Limiter) Reserve() *Reservation
func (lim *Limiter) ReserveN(t time.Time, n int) *Reservation
func (r *Reservation) OK() bool
func (r *Reservation) DelayFrom(t time.Time) time.Duration
func (r *Reservation) CancelAt(t time.Time)
```

`Reserve()`、`Delay()`、`Cancel()` 是以 `time.Now()` 為準的對應版本。範例用固定時間 `t0`，每次預約都排在前一張的後面：

```go
package main

import (
	"fmt"
	"time"

	"golang.org/x/time/rate"
)

func main() {
	lim := rate.NewLimiter(rate.Every(100*time.Millisecond), 1)
	t0 := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)

	for i := 1; i <= 3; i++ {
		r := lim.ReserveN(t0, 1)
		fmt.Printf("reservation %d: ok=%v delay=%v\n", i, r.OK(), r.DelayFrom(t0))
	}

	r := lim.ReserveN(t0, 1)
	fmt.Println("reservation 4 delay:", r.DelayFrom(t0))
	r.CancelAt(t0)
	fmt.Println("after cancel, next delay:", lim.ReserveN(t0, 1).DelayFrom(t0))

	tooBig := lim.ReserveN(t0, 2)
	fmt.Println("n > burst ok:", tooBig.OK())
}
```

輸出：

```text
reservation 1: ok=true delay=0s
reservation 2: ok=true delay=100ms
reservation 3: ok=true delay=200ms
reservation 4 delay: 300ms
after cancel, next delay: 300ms
n > burst ok: false
```

取消第 4 張後，權杖被歸還，下一張預約又回到 300ms。

注意：`n` 大於 burst 時 `OK()` 為 `false`，這張預約不能使用，也不需要取消。

## 執行中調整

### SetLimitAt 與 SetBurstAt

服務降級或尖峰時段可能要即時調整速率。`SetLimit`、`SetBurst` 立即生效；帶 `At` 的版本以指定時間計算，方便寫出確定的範例。

簽名：

```go
func (lim *Limiter) SetLimitAt(t time.Time, newLimit Limit)
func (lim *Limiter) SetBurstAt(t time.Time, newBurst int)
```

範例：

```go
package main

import (
	"fmt"
	"time"

	"golang.org/x/time/rate"
)

func main() {
	lim := rate.NewLimiter(rate.Limit(1), 1)
	t0 := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)

	fmt.Println("before:", lim.AllowN(t0, 1), lim.AllowN(t0, 1))

	lim.SetBurstAt(t0, 5)
	lim.SetLimitAt(t0, rate.Limit(10))
	fmt.Println("limit:", lim.Limit(), "burst:", lim.Burst())

	t1 := t0.Add(500 * time.Millisecond)
	fmt.Printf("tokens at t0+500ms: %.1f\n", lim.TokensAt(t1))
	fmt.Println("take 5:", lim.AllowN(t1, 5))
}
```

輸出：

```text
before: true false
limit: 10 burst: 5
tokens at t0+500ms: 5.0
take 5: true
```

調整前每秒 1 個、容量 1，第二次就被拒。調成每秒 10 個、容量 5 後，經過 0.5 秒補滿 5 個。

## 偶爾做一次

### Sometimes

`rate.Sometimes` 不是權杖桶，而是「呼叫很多次，只偶爾真的執行」的小工具，常用在避免日誌洗版。三個欄位可以組合：

- `First`：前 N 次一定執行
- `Every`：每第 N 次執行一次
- `Interval`：距離上次執行超過這段時間就執行

零值的 `Sometimes` 只會執行一次。

簽名：

```go
func (s *Sometimes) Do(f func())
```

範例：

```go
package main

import (
	"fmt"

	"golang.org/x/time/rate"
)

func main() {
	s := rate.Sometimes{First: 2, Every: 3}
	for i := 1; i <= 10; i++ {
		s.Do(func() { fmt.Println("log at call", i) })
	}
}
```

輸出：

```text
log at call 1
log at call 2
log at call 4
log at call 7
log at call 10
```

前 2 次因 `First` 執行；之後第 4、7、10 次因 `Every: 3` 執行（以總呼叫次數 1、4、7、10 計算，第 1 次已被 `First` 涵蓋）。

## 重點整理

- `rate.Limiter` 用權杖桶限流：limit 是每秒補充量，burst 是桶容量，一開始桶是滿的
- 拿不到權杖時：`Allow` 立即拒絕、`Wait` 阻塞排隊、`Reserve` 告訴你要等多久
- `Wait` 發現等不到 context 期限就立刻回錯誤；`n` 大於 burst 永遠無法成功
- `AllowN`、`ReserveN`、`TokensAt` 等帶時間參數的方法讓測試與範例輸出可重現
- `Limiter` 可多 goroutine 共用；依用戶端分流時每個用戶端各存一個

## 資料來源

- [pkg.go.dev：golang.org/x/time](https://pkg.go.dev/golang.org/x/time)
