Files
Agent-Native/exec/limiter.go
weichenandCursor fedf671a48
ci / vet-and-test (push) Successful in 5s
ci / docker-checkout-hostgateway (push) Successful in 3s
Import the current agent-native module as a fresh history.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-29 12:29:04 +00:00

47 lines
939 B
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package exec
import (
"context"
"fmt"
)
// LimitingBackend 用有界信号量限制底层 agent 并发,保护 GPU/API 资源。
type LimitingBackend struct {
inner Backend
sem chan struct{}
}
// WrapWithConcurrencyLimit 包装 backend;max<=0 时默认 8。
func WrapWithConcurrencyLimit(inner Backend, max int) Backend {
if inner == nil {
return nil
}
if max <= 0 {
max = 8
}
return &LimitingBackend{
inner: inner,
sem: make(chan struct{}, max),
}
}
func (l *LimitingBackend) Name() string {
if l.inner == nil {
return "limiting"
}
return l.inner.Name()
}
func (l *LimitingBackend) Execute(ctx context.Context, req Request) (*Result, error) {
select {
case l.sem <- struct{}{}:
defer func() { <-l.sem }()
case <-ctx.Done():
return &Result{
Success: false,
ErrorReason: fmt.Sprintf("agent concurrency wait canceled: %v", ctx.Err()),
}, ctx.Err()
}
return l.inner.Execute(ctx, req)
}