|
| 1 | +// SPDX-License-Identifier: MIT |
| 2 | + |
| 3 | +package backend |
| 4 | + |
| 5 | +import ( |
| 6 | + "fmt" |
| 7 | + "sync" |
| 8 | + "time" |
| 9 | + |
| 10 | + "github.com/mudler/LocalAI/core/config" |
| 11 | +) |
| 12 | + |
| 13 | +// BackendAdmissionError reports that the process-wide backend execution |
| 14 | +// ceiling is full. HTTP callers map it to 503; internal callers receive the |
| 15 | +// same typed error instead of silently queueing and growing in-flight state. |
| 16 | +type BackendAdmissionError struct { |
| 17 | + Limit int |
| 18 | + RetryAfter time.Duration |
| 19 | +} |
| 20 | + |
| 21 | +func (e *BackendAdmissionError) Error() string { |
| 22 | + return fmt.Sprintf("backend inference capacity reached (max_concurrent=%d); retry after %s", e.Limit, e.RetryAfter) |
| 23 | +} |
| 24 | + |
| 25 | +var backendAdmission = struct { |
| 26 | + sync.RWMutex |
| 27 | + limit int |
| 28 | + slots chan struct{} |
| 29 | +}{} |
| 30 | + |
| 31 | +// ConfigureGlobalBackendAdmission sets the process-wide ceiling. It is called |
| 32 | +// during application construction, before backend work can begin. |
| 33 | +func ConfigureGlobalBackendAdmission(limit int) { |
| 34 | + if limit <= 0 { |
| 35 | + limit = config.DefaultMaxConcurrentBackendRequests |
| 36 | + } |
| 37 | + backendAdmission.Lock() |
| 38 | + backendAdmission.limit = limit |
| 39 | + backendAdmission.slots = make(chan struct{}, limit) |
| 40 | + backendAdmission.Unlock() |
| 41 | +} |
| 42 | + |
| 43 | +// AcquireGlobalBackendSlot admits one backend operation without queueing. |
| 44 | +// Callers must invoke release on every completion path. |
| 45 | +func AcquireGlobalBackendSlot() (release func(), err error) { |
| 46 | + backendAdmission.RLock() |
| 47 | + limit, slots := backendAdmission.limit, backendAdmission.slots |
| 48 | + backendAdmission.RUnlock() |
| 49 | + if slots == nil { |
| 50 | + backendAdmission.Lock() |
| 51 | + if backendAdmission.slots == nil { |
| 52 | + backendAdmission.limit = config.DefaultMaxConcurrentBackendRequests |
| 53 | + backendAdmission.slots = make(chan struct{}, backendAdmission.limit) |
| 54 | + } |
| 55 | + limit, slots = backendAdmission.limit, backendAdmission.slots |
| 56 | + backendAdmission.Unlock() |
| 57 | + } |
| 58 | + select { |
| 59 | + case slots <- struct{}{}: |
| 60 | + var once sync.Once |
| 61 | + return func() { once.Do(func() { <-slots }) }, nil |
| 62 | + default: |
| 63 | + return nil, &BackendAdmissionError{Limit: limit, RetryAfter: time.Second} |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +// GlobalBackendInFlight is the current number of admitted backend operations. |
| 68 | +func GlobalBackendInFlight() int { |
| 69 | + backendAdmission.RLock() |
| 70 | + defer backendAdmission.RUnlock() |
| 71 | + return len(backendAdmission.slots) |
| 72 | +} |
0 commit comments