Skip to content

Commit 438e0c1

Browse files
committed
Enhance page handling with mutex management and index rotation
- Implemented mutexes for page index tracking per instance to ensure thread safety. - Added logic for rotating and reordering pages starting from the last used index for improved page availability. - Refactored `handlers.go` to include new synchronization mechanisms.
1 parent d94e5fa commit 438e0c1

File tree

1 file changed

+30
-3
lines changed

1 file changed

+30
-3
lines changed

internal/api/handlers.go

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,12 @@ import (
2222
"github.com/google/uuid"
2323
)
2424

25-
var ScreenshotMutex sync.Mutex
25+
var (
26+
lastUsedPageIndex = make(map[string]int)
27+
pageIndexMutexes = make(map[string]*sync.Mutex)
28+
mutexMapLock = &sync.Mutex{}
29+
ScreenshotMutex sync.Mutex
30+
)
2631

2732
// APIHandlers contains the handlers for API endpoints
2833
type APIHandlers struct {
@@ -215,9 +220,31 @@ func (h *APIHandlers) ChatCompletions(c *gin.Context) {
215220
}()
216221

217222
if pages, ok := h.pages[instanceName]; ok {
218-
locked := false
223+
// Get the mutex for the instance
224+
mutex, exists := pageIndexMutexes[instanceName]
225+
if !exists {
226+
mutexMapLock.Lock()
227+
mutex = &sync.Mutex{}
228+
pageIndexMutexes[instanceName] = mutex
229+
mutexMapLock.Unlock()
230+
}
231+
232+
// Lock the mutex to update the last used page index
233+
mutex.Lock()
234+
startIndex := lastUsedPageIndex[instanceName]
235+
currentIndex := (startIndex + 1) % len(pages)
236+
lastUsedPageIndex[instanceName] = currentIndex
237+
mutex.Unlock()
238+
239+
// Reorder the pages to start from the last used index
240+
reorderedPages := make([]*chrome.Page, len(pages))
219241
for i := 0; i < len(pages); i++ {
220-
page = pages[i]
242+
reorderedPages[i] = pages[(startIndex+1+i)%len(pages)]
243+
}
244+
245+
locked := false
246+
for i := 0; i < len(reorderedPages); i++ {
247+
page = reorderedPages[i]
221248
if page.RequestMutex.TryLock() {
222249
locked = true
223250
break

0 commit comments

Comments
 (0)