-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecution_manager.go
More file actions
404 lines (322 loc) · 9.72 KB
/
Copy pathexecution_manager.go
File metadata and controls
404 lines (322 loc) · 9.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
package sdk
import (
"context"
"sync"
"time"
"github.com/google/uuid"
logger "github.com/xraph/go-utils/log"
"github.com/xraph/go-utils/metrics"
)
// ExecutionState represents the state of a stream execution.
type ExecutionState string
const (
ExecutionStatePending ExecutionState = "pending"
ExecutionStateRunning ExecutionState = "running"
ExecutionStateCompleted ExecutionState = "completed"
ExecutionStateCancelled ExecutionState = "cancelled"
ExecutionStateError ExecutionState = "error"
)
// ExecutionInfo contains information about an active stream execution.
type ExecutionInfo struct {
// ExecutionID uniquely identifies this execution
ExecutionID string `json:"executionId"`
// State is the current execution state
State ExecutionState `json:"state"`
// Model being used
Model string `json:"model,omitempty"`
// Provider being used
Provider string `json:"provider,omitempty"`
// StartTime when the execution started
StartTime time.Time `json:"startTime"`
// EndTime when the execution ended (zero if still running)
EndTime time.Time `json:"endTime,omitempty"`
// TokensGenerated counts tokens generated so far
TokensGenerated int64 `json:"tokensGenerated"`
// LastActivity timestamp of last event
LastActivity time.Time `json:"lastActivity"`
// Error message if state is error
Error string `json:"error,omitempty"`
// Metadata for custom data
Metadata map[string]any `json:"metadata,omitempty"`
// cancel function for cancellation
cancel context.CancelFunc
ctx context.Context
}
// ExecutionManager tracks and manages active stream executions.
// It provides:
// - Active stream tracking by executionId
// - Cancellation support
// - Cleanup of stale executions
// - Metrics and observability.
type ExecutionManager struct {
// executions maps executionId to ExecutionInfo
executions map[string]*ExecutionInfo
// mu protects the executions map
mu sync.RWMutex
// logger for logging
logger logger.Logger
// metrics for observability
metrics metrics.Metrics
// config for the manager
config ExecutionManagerConfig
// cleanupTicker for periodic cleanup
cleanupTicker *time.Ticker
cleanupDone chan struct{}
}
// ExecutionManagerConfig configures the execution manager.
type ExecutionManagerConfig struct {
// MaxActiveExecutions is the maximum number of concurrent executions
// 0 means unlimited
MaxActiveExecutions int
// ExecutionTimeout is the maximum duration for a single execution
// 0 means no timeout (not recommended)
ExecutionTimeout time.Duration
// StaleExecutionAge is the age after which completed executions are cleaned up
StaleExecutionAge time.Duration
// CleanupInterval is how often to run cleanup
CleanupInterval time.Duration
}
// DefaultExecutionManagerConfig returns sensible defaults.
func DefaultExecutionManagerConfig() ExecutionManagerConfig {
return ExecutionManagerConfig{
MaxActiveExecutions: 100,
ExecutionTimeout: 5 * time.Minute,
StaleExecutionAge: 10 * time.Minute,
CleanupInterval: 1 * time.Minute,
}
}
// NewExecutionManager creates a new execution manager.
func NewExecutionManager(logger logger.Logger, metrics metrics.Metrics, config ExecutionManagerConfig) *ExecutionManager {
em := &ExecutionManager{
executions: make(map[string]*ExecutionInfo),
logger: logger,
metrics: metrics,
config: config,
cleanupDone: make(chan struct{}),
}
// Start cleanup goroutine
if config.CleanupInterval > 0 {
em.cleanupTicker = time.NewTicker(config.CleanupInterval)
go em.cleanupLoop()
}
return em
}
// StartExecution creates and tracks a new execution.
// Returns the execution info and a context that will be cancelled when the execution
// is cancelled or times out.
func (em *ExecutionManager) StartExecution(ctx context.Context, model, provider string) (*ExecutionInfo, context.Context, error) {
em.mu.Lock()
defer em.mu.Unlock()
// Check max executions
if em.config.MaxActiveExecutions > 0 {
activeCount := 0
for _, info := range em.executions {
if info.State == ExecutionStateRunning {
activeCount++
}
}
if activeCount >= em.config.MaxActiveExecutions {
if em.metrics != nil {
em.metrics.Counter("forge.ai.sdk.execution.rejected", metrics.WithLabel("reason", "max_executions")).Inc()
}
return nil, nil, ErrMaxExecutionsReached{}
}
}
// Create execution context with timeout
var cancel context.CancelFunc
var execCtx context.Context
if em.config.ExecutionTimeout > 0 {
execCtx, cancel = context.WithTimeout(ctx, em.config.ExecutionTimeout)
} else {
execCtx, cancel = context.WithCancel(ctx)
}
// Create execution info
execID := uuid.New().String()
now := time.Now()
info := &ExecutionInfo{
ExecutionID: execID,
State: ExecutionStateRunning,
Model: model,
Provider: provider,
StartTime: now,
LastActivity: now,
Metadata: make(map[string]any),
cancel: cancel,
ctx: execCtx,
}
em.executions[execID] = info
if em.logger != nil {
em.logger.Debug("Execution started",
F("execution_id", execID),
F("model", model),
F("provider", provider),
)
}
if em.metrics != nil {
em.metrics.Counter("forge.ai.sdk.execution.started").Inc()
em.metrics.Gauge("forge.ai.sdk.execution.active").Inc()
}
return info, execCtx, nil
}
// GetExecution returns the execution info for the given ID.
func (em *ExecutionManager) GetExecution(executionID string) (*ExecutionInfo, bool) {
em.mu.RLock()
defer em.mu.RUnlock()
info, exists := em.executions[executionID]
return info, exists
}
// UpdateActivity updates the last activity time for an execution.
func (em *ExecutionManager) UpdateActivity(executionID string, tokensGenerated int64) {
em.mu.Lock()
defer em.mu.Unlock()
if info, exists := em.executions[executionID]; exists {
info.LastActivity = time.Now()
info.TokensGenerated = tokensGenerated
}
}
// CompleteExecution marks an execution as completed.
func (em *ExecutionManager) CompleteExecution(executionID string, err error) {
em.mu.Lock()
defer em.mu.Unlock()
info, exists := em.executions[executionID]
if !exists {
return
}
info.EndTime = time.Now()
if err != nil {
info.State = ExecutionStateError
info.Error = err.Error()
} else {
info.State = ExecutionStateCompleted
}
if em.logger != nil {
em.logger.Debug("Execution completed",
F("execution_id", executionID),
F("state", info.State),
F("duration", info.EndTime.Sub(info.StartTime)),
F("tokens", info.TokensGenerated),
)
}
if em.metrics != nil {
em.metrics.Counter("forge.ai.sdk.execution.completed", metrics.WithLabel("state", string(info.State))).Inc()
em.metrics.Gauge("forge.ai.sdk.execution.active").Dec()
em.metrics.Histogram("forge.ai.sdk.execution.duration").Observe(info.EndTime.Sub(info.StartTime).Seconds())
}
}
// CancelExecution cancels an execution by ID.
func (em *ExecutionManager) CancelExecution(executionID string) bool {
em.mu.Lock()
defer em.mu.Unlock()
info, exists := em.executions[executionID]
if !exists {
return false
}
if info.State != ExecutionStateRunning {
return false
}
// Call cancel function
if info.cancel != nil {
info.cancel()
}
info.State = ExecutionStateCancelled
info.EndTime = time.Now()
if em.logger != nil {
em.logger.Info("Execution cancelled",
F("execution_id", executionID),
)
}
if em.metrics != nil {
em.metrics.Counter("forge.ai.sdk.execution.cancelled").Inc()
em.metrics.Gauge("forge.ai.sdk.execution.active").Dec()
}
return true
}
// ListExecutions returns all executions, optionally filtered by state.
func (em *ExecutionManager) ListExecutions(state *ExecutionState) []*ExecutionInfo {
em.mu.RLock()
defer em.mu.RUnlock()
results := make([]*ExecutionInfo, 0)
for _, info := range em.executions {
if state == nil || info.State == *state {
results = append(results, info)
}
}
return results
}
// ActiveCount returns the number of active executions.
func (em *ExecutionManager) ActiveCount() int {
em.mu.RLock()
defer em.mu.RUnlock()
count := 0
for _, info := range em.executions {
if info.State == ExecutionStateRunning {
count++
}
}
return count
}
// cleanupLoop periodically cleans up stale executions.
func (em *ExecutionManager) cleanupLoop() {
for {
select {
case <-em.cleanupTicker.C:
em.cleanup()
case <-em.cleanupDone:
return
}
}
}
// cleanup removes stale completed executions.
func (em *ExecutionManager) cleanup() {
em.mu.Lock()
defer em.mu.Unlock()
now := time.Now()
cutoff := now.Add(-em.config.StaleExecutionAge)
toDelete := make([]string, 0)
for id, info := range em.executions {
// Skip running executions
if info.State == ExecutionStateRunning {
continue
}
// Check if stale
if !info.EndTime.IsZero() && info.EndTime.Before(cutoff) {
toDelete = append(toDelete, id)
}
}
for _, id := range toDelete {
delete(em.executions, id)
}
if len(toDelete) > 0 && em.logger != nil {
em.logger.Debug("Cleaned up stale executions",
F("count", len(toDelete)),
)
}
}
// Stop stops the execution manager and cancels all active executions.
func (em *ExecutionManager) Stop() {
// Stop cleanup goroutine
if em.cleanupTicker != nil {
em.cleanupTicker.Stop()
close(em.cleanupDone)
}
// Cancel all active executions
em.mu.Lock()
defer em.mu.Unlock()
for _, info := range em.executions {
if info.State == ExecutionStateRunning && info.cancel != nil {
info.cancel()
info.State = ExecutionStateCancelled
info.EndTime = time.Now()
}
}
if em.logger != nil {
em.logger.Info("Execution manager stopped")
}
}
// ErrMaxExecutionsReached is returned when the maximum number of concurrent
// executions has been reached.
type ErrMaxExecutionsReached struct{}
func (e ErrMaxExecutionsReached) Error() string {
return "maximum number of concurrent executions reached"
}
var _ error = ErrMaxExecutionsReached{}