返回 DeepSeek-Reasonix
compaction_gate.go
根目录 / internal / agent / compaction_gate.go
1 package agent
2
3 import (
4 "context"
5 "sync"
6 )
7
8 // compactionGate is a zero-value, cancellation-aware single-flight latch.
9 type compactionGate struct {
10 once sync.Once
11 token chan struct{}
12 }
13
14 func (g *compactionGate) acquire(ctx context.Context) error {
15 g.once.Do(func() { g.token = make(chan struct{}, 1) })
16 if err := ctx.Err(); err != nil {
17 return err
18 }
19 select {
20 case g.token <- struct{}{}:
21 return g.acquired(ctx)
22 case <-ctx.Done():
23 return ctx.Err()
24 }
25 }
26
27 func (g *compactionGate) acquired(ctx context.Context) error {
28 if err := ctx.Err(); err != nil {
29 g.Unlock()
30 return err
31 }
32 return nil
33 }
34
35 func (g *compactionGate) Lock() { _ = g.acquire(context.Background()) }
36 func (g *compactionGate) Unlock() { <-g.token }
37
37 lines GO