-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
717 lines (636 loc) · 23.5 KB
/
main.go
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
package main
import (
"context"
"encoding/base64"
"fmt"
"github.com/go-redis/redis"
"github.com/joho/godotenv"
"github.com/rojolang/GOaiCrossTab/stats"
"github.com/sashabaranov/go-openai"
"golang.org/x/oauth2/google"
"golang.org/x/time/rate"
"google.golang.org/api/option"
"google.golang.org/api/sheets/v4"
"log"
"os"
"strconv"
"strings"
"sync"
"time"
)
type ColumnVariable struct {
ColumnNumber int
VariableName string
}
type ChunkSettings struct {
Name string
TriggerColumn []string
SystemMessage string
UserMessage string
Temperature float32
MaxTokens int
PromptColTo string
}
var allSettings map[string]map[string]interface{}
var _ map[string]ChunkSettings
var gptSettingsByName map[string]ChunkSettings
var _ map[int]ColumnVariable
var columnNameByIndex map[int]string
var columnIndexByName map[string]int
var columnLetterByName map[string]string
var currentRow map[string]interface{}
var redisClient *redis.Client
var srv *sheets.Service
var prevState [][]interface{}
var sheetsLimiter = rate.NewLimiter(rate.Every(time.Minute/29), 29)
var gptLimiter = rate.NewLimiter(rate.Every(time.Minute/10), 10)
var gptSemaphore = make(chan struct{}, 10)
var sheetsSemaphore = make(chan struct{}, 29)
var cellMutexes map[string]*sync.Mutex
var cellMutexesMutex = &sync.Mutex{} // Mutex to protect access to cellMutexes map
var spreadsheetID string
var errorCount int
var successfulCompletions int
var lastError string
var wg sync.WaitGroup // WaitGroup to ensure all goroutines finish
var su *stats.StatsUpdater // Define global variable for stats updater
// setupEnvironment loads environment variables, creates the Google Sheets and Redis services,
// and initializes a map of mutexes for each cell in the Google Sheets.
// It also creates a stats updater, creates the "Stats" sheet, and writes the stat names.
// It handles any errors that occur during these operations by calling the handleError function,
// which increments the "Errors" counter and updates the "Errors" and "Last Error" stats.
// It returns an error if an error occurred while creating the mutexes.
func setupEnvironment() error {
// Load environment variables
err := godotenv.Load()
if err != nil {
handleError(err) // Call handleError function instead of returning the error directly
return nil
}
// Get spreadsheet ID from environment variable
spreadsheetID = os.Getenv("SPREADSHEET_ID")
// Decode service account key
b, err := base64.StdEncoding.DecodeString(os.Getenv("GOOGLE_APPLICATION_CREDENTIALS"))
if err != nil {
handleError(err) // Call handleError function instead of returning the error directly
return nil
}
// Create JWT config from service account key
conf, err := google.JWTConfigFromJSON(b, "https://www.googleapis.com/auth/spreadsheets")
if err != nil {
handleError(err) // Call handleError function instead of returning the error directly
return nil
}
// Create new Sheets service
tmpSrv, err := sheets.NewService(context.Background(), option.WithHTTPClient(conf.Client(context.Background())))
if err != nil {
handleError(err) // Call handleError function instead of returning the error directly
return nil
}
srv = tmpSrv
// Create new StatsUpdater
su, err = stats.NewStatsUpdater(spreadsheetID, os.Getenv("GOOGLE_APPLICATION_CREDENTIALS"), []string{"Total Rows Processed", "Errors", "Successful Completions", "Last Error"})
if err != nil {
handleError(err) // Call handleError function instead of returning the error directly
return nil
}
// Get Redis configuration from environment variables
redisAddr := os.Getenv("REDIS_ADDR")
redisPassword := os.Getenv("REDIS_PASSWORD")
redisDB, err := strconv.Atoi(os.Getenv("REDIS_DB"))
if err != nil {
handleError(err) // Call handleError function instead of returning the error directly
return nil
}
// Create new Redis client
redisClient = redis.NewClient(&redis.Options{
Addr: redisAddr,
Password: redisPassword,
DB: redisDB,
})
// Test Redis connection
_, err = redisClient.Ping().Result()
if err != nil {
handleError(err) // Call handleError function instead of returning the error directly
return nil
}
// Fetch the entire sheet's data
resp, err := srv.Spreadsheets.Get(spreadsheetID).Do()
if err != nil {
handleError(err) // Call handleError function instead of returning the error directly
return nil
}
// Get the number of rows and columns from the sheet's grid data
numRows := int(resp.Sheets[0].Properties.GridProperties.RowCount)
numCols := int(resp.Sheets[0].Properties.GridProperties.ColumnCount)
// Initialize the cellMutexes map with a mutex for each cell in the sheet
cellMutexes = make(map[string]*sync.Mutex)
for i := 0; i < numRows; i++ {
for j := 0; j < numCols; j++ {
cellKey := fmt.Sprintf("%d:%d", i, j)
cellMutexes[cellKey] = &sync.Mutex{}
}
}
return nil
}
// handleError function increments the "Errors" counter and updates the "Errors" and "Last Error" stats.
func handleError(err error) {
// Increment the "Errors" counter
errorCount++
// Set the last error
lastError = err.Error()
// If STATS is true, update the "Errors" and "Last Error" stats
if statsEnabled, ok := allSettings["GLOBAL"]["STATS"].(bool); ok && statsEnabled {
// Assume su is an instance of StatsUpdater from the stats.go file
errUpdate := su.UpdateStats("Errors", errorCount)
if errUpdate != nil {
log.Printf("Error updating stats: %v", errUpdate)
}
errUpdate = su.UpdateStats("Last Error", lastError)
if errUpdate != nil {
log.Printf("Error updating stats: %v", errUpdate)
}
}
}
// readSettings reads settings from the Google Sheet and updates the global settings variables.
// It returns an error if an error occurred while reading the settings.
func readSettings() error {
resp, err := readFromSheetWithRateLimit(spreadsheetID, "Settings!A1:B1000")
if err != nil {
return fmt.Errorf("unable to retrieve data from sheet: %v", err)
}
allSettings = make(map[string]map[string]interface{})
allSettings["GLOBAL"] = make(map[string]interface{})
gptSettingsByName = make(map[string]ChunkSettings)
_ = make(map[int]ColumnVariable)
for _, row := range resp.Values {
if len(row) < 2 {
continue
}
key, ok := row[0].(string)
if !ok {
return fmt.Errorf("error: key is not a string. It is a %T", row[0])
}
value := row[1]
if !strings.HasPrefix(key, "VAR") {
switch key {
case "SHEET_REFRESH_FREQUENCY":
if s, err := strconv.ParseFloat(value.(string), 64); err == nil {
allSettings["GLOBAL"]["SHEET_REFRESH_FREQUENCY"] = s
} else {
log.Printf("Error: SHEET_REFRESH_FREQUENCY is not a float64. It is a %s", value)
}
case "SHEET_NEW_COLUMNS_FREQUENCY":
if s, err := strconv.ParseFloat(value.(string), 64); err == nil {
allSettings["GLOBAL"]["SHEET_NEW_COLUMNS_FREQUENCY"] = s
} else {
log.Printf("Error: SHEET_NEW_COLUMNS_FREQUENCY is not a float64. It is a %s", value)
}
case "GPT_RATE_LIMIT":
if s, err := strconv.Atoi(value.(string)); err == nil {
gptLimiter = rate.NewLimiter(rate.Every(time.Minute/time.Duration(s)), s)
} else {
log.Printf("Error: GPT_RATE_LIMIT is not an int. It is a %s", value)
}
case "SHEETS_RATE_LIMIT":
if s, err := strconv.Atoi(value.(string)); err == nil {
sheetsLimiter = rate.NewLimiter(rate.Every(time.Minute/time.Duration(s)), s)
} else {
log.Printf("Error: SHEETS_RATE_LIMIT is not an int. It is a %s", value)
}
case "STATS":
if s, err := strconv.ParseBool(value.(string)); err == nil {
allSettings["GLOBAL"]["STATS"] = s
} else {
log.Printf("Error: STATS is not a bool. It is a %s", value)
}
default:
allSettings["GLOBAL"][key] = value
}
} else {
splitIndex := strings.Index(key, "_")
currentSettingsName := key[:splitIndex]
varProp := key[splitIndex+1:]
varValue, ok := value.(string)
if !ok {
return fmt.Errorf("error: varValue is not a string. It is a %T", value)
}
currentSettings, exists := gptSettingsByName[currentSettingsName]
if !exists {
currentSettings = ChunkSettings{Name: currentSettingsName}
}
switch varProp {
case "TRIGGER_COL":
splitValues := strings.Split(varValue, ",")
for i, val := range splitValues {
splitValues[i] = strings.TrimSpace(val)
}
currentSettings.TriggerColumn = splitValues
case "SYSTEM_MESSAGE":
currentSettings.SystemMessage = varValue
case "USER_MESSAGE":
currentSettings.UserMessage = varValue
case "TEMP":
if temp, err := strconv.ParseFloat(varValue, 32); err == nil {
currentSettings.Temperature = float32(temp)
} else {
return fmt.Errorf("error: TEMP is not a float32. It is a %s", varValue)
}
case "MAX_TOKENS":
if maxTokens, err := strconv.Atoi(varValue); err == nil {
currentSettings.MaxTokens = maxTokens
} else {
return fmt.Errorf("error: MAX_TOKENS is not an int. It is a %s", varValue)
}
case "PROMPT_COL_TO":
currentSettings.PromptColTo = varValue
}
gptSettingsByName[currentSettingsName] = currentSettings
}
}
return nil
}
// detectChanges compares the current state with the previous state and logs any changes.
// It updates the previous state in Redis and processes any detected changes.
// It returns an error if an error occurred.
func detectChanges(currentRows [][]interface{}, shouldCheckForNewColumns bool) error {
columnNameByIndex = make(map[int]string)
columnIndexByName = make(map[string]int)
columnLetterByName = make(map[string]string)
for i := range currentRows[0] {
columnName, ok := currentRows[0][i].(string)
if !ok {
log.Printf("Error: columnName is not a string. It is a %T", currentRows[0][i])
continue
}
columnNameByIndex[i] = columnName
columnIndexByName[columnName] = i
columnLetterByName[columnName] = getExcelColumnName(i + 1)
}
for rowIndex := range currentRows {
if rowIndex == 0 {
continue
}
currentRow = make(map[string]interface{})
for columnIndex := range currentRows[rowIndex] {
currentRow["RowIndex"] = rowIndex
currentRow[columnNameByIndex[columnIndex]] = currentRows[rowIndex][columnIndex]
}
for _, columnName := range columnNameByIndex {
if _, ok := currentRow[columnName]; !ok {
currentRow[columnName] = ""
}
}
for _, gptSettings := range gptSettingsByName {
if len(gptSettings.UserMessage) == 0 || len(gptSettings.SystemMessage) == 0 {
continue
}
if gptSettings.Temperature == 0 || gptSettings.MaxTokens == 0 {
continue
}
if len(gptSettings.PromptColTo) == 0 {
continue
}
if len(gptSettings.TriggerColumn) == 0 {
continue
}
rowHadTriggerColumnValues := true
rowHadChangedTriggerColumnsCount := 0
rowMissingNewColumns := false
for _, triggerColumn := range gptSettings.TriggerColumn {
if currentRow[triggerColumn] == nil || currentRow[triggerColumn] == "" {
rowHadTriggerColumnValues = false
break
}
if checkIfValueChangedInCache(currentRow, triggerColumn) {
rowHadChangedTriggerColumnsCount++
}
}
if shouldCheckForNewColumns {
newColumnValue := currentRow[gptSettings.PromptColTo]
if newColumnValue == nil || newColumnValue == "" {
if rowHadTriggerColumnValues {
rowMissingNewColumns = true
}
}
}
if rowMissingNewColumns || (rowHadTriggerColumnValues && rowHadChangedTriggerColumnsCount == len(gptSettings.TriggerColumn)) {
if rowMissingNewColumns {
log.Printf("Row #%d is missing value in new column '%s'\n", currentRow["RowIndex"], gptSettings.PromptColTo)
} else {
log.Printf("Row #%d change triggered gptSettings '%s'\n", currentRow["RowIndex"], gptSettings.Name)
}
err := runGptSettingsOnRowWithSemaphore(currentRow, gptSettings)
if err != nil {
log.Printf("Error running GPT settings on row: %v", err)
continue
}
}
}
}
return nil
}
// getExcelColumnName function converts a column number to an Excel column name.
// It returns the Excel column name.
func getExcelColumnName(columnNumber int) string {
columnName := ""
for columnNumber > 0 {
columnNumber--
columnName = string(rune('A'+columnNumber%26)) + columnName
columnNumber /= 26
}
return columnName
}
// checkIfValueChangedInCache function checks if a value has changed in the Redis cache.
// It returns true if the value has changed, false otherwise.
func checkIfValueChangedInCache(row map[string]interface{}, columnName string) bool {
if row[columnName] == nil || row[columnName] == "" {
return false
}
redisKey := fmt.Sprintf("cell:%d:%d", row["RowIndex"], columnIndexByName[columnName])
prevValue, err := redisClient.Get(redisKey).Result()
if err == redis.Nil {
// The key does not exist in Redis, which means the cell's value has not been cached yet.
// Cache the value and return true to indicate that the value has "changed".
err = redisClient.Set(redisKey, row[columnName], 0).Err()
if err != nil {
log.Printf("Error setting value in Redis: %v", err)
}
return true
} else if err != nil {
log.Printf("Error getting value from Redis: %v", err)
return false
}
if prevValue == row[columnName] {
return false
}
log.Printf("Row #%d (%v) has changed from %v to %v\n", row["RowIndex"], columnName, prevValue, row[columnName])
err = redisClient.Set(redisKey, row[columnName], 0).Err()
if err != nil {
log.Printf("Error setting value in Redis: %v", err)
}
return true
}
// replaceTokens function replaces tokens in a message with their corresponding values from a row.
// It returns the message with tokens replaced.
func replaceTokens(message string, currentRow map[string]interface{}) string {
for key, value := range currentRow {
token := "{" + key + "}"
if strings.Contains(message, token) {
message = strings.Replace(message, token, fmt.Sprint(value), -1)
}
}
return message
}
// runGptSettingsOnRow processes the GPT settings on a row.
// It fetches the GPT response,
// updates the Google Sheet with the response using rate-limited function, and logs any errors.
// It returns an error if an error occurred.
func runGptSettingsOnRow(row map[string]interface{}, gptSettings ChunkSettings) error {
if err := gptLimiter.Wait(context.Background()); err != nil {
log.Printf("[GPT] rate limit error: %v", err)
return err
}
destinationColumnName := gptSettings.PromptColTo
destinationColumnLetter := columnLetterByName[destinationColumnName]
rowIndex, ok := row["RowIndex"].(int)
if !ok {
log.Printf("Error: RowIndex is not an integer")
return fmt.Errorf("error: RowIndex is not an integer")
}
destinationRange := fmt.Sprintf("%v%d", destinationColumnLetter, rowIndex+1)
vr := &sheets.ValueRange{
Values: [][]interface{}{{""}},
}
_, err := writeToSheetWithRateLimit(spreadsheetID, destinationRange, vr)
if err != nil {
log.Printf("Error updating Google Sheet: %v", err)
return err
}
systemMessage := replaceTokens(gptSettings.SystemMessage, row)
userMessage := replaceTokens(gptSettings.UserMessage, row)
client := openai.NewClient(os.Getenv("OPENAI_SECRET_KEY"))
resp, err := client.CreateChatCompletion(
context.Background(),
openai.ChatCompletionRequest{
Model: openai.GPT4,
Messages: []openai.ChatCompletionMessage{
{
Role: openai.ChatMessageRoleSystem,
Content: systemMessage,
},
{
Role: openai.ChatMessageRoleUser,
Content: userMessage,
},
},
MaxTokens: gptSettings.MaxTokens,
Temperature: float32(gptSettings.Temperature),
},
)
if err != nil {
log.Printf("[ERROR] getting GPT response: %v", err)
return err
}
if len(resp.Choices) <= 0 {
log.Printf("No choices in the response")
return fmt.Errorf("no choices in the response")
}
output := resp.Choices[0].Message.Content
vr = &sheets.ValueRange{
Values: [][]interface{}{{output}},
}
_, err = writeToSheetWithRateLimit(spreadsheetID, destinationRange, vr)
if err != nil {
log.Printf("Error updating Google Sheet: %v", err)
return err
}
log.Printf("Updated row #%v (%s) with value %s\n", rowIndex, destinationColumnName, output)
// If the STATS are true, update the "Successful Completions" stat
if statsEnabled, ok := allSettings["GLOBAL"]["STATS"].(bool); ok && statsEnabled {
// Assume su is an instance of StatsUpdater from the stats.go file
// Assumes successfulCompletions is a counter for the number of successful completions
successfulCompletions++
err := su.UpdateStats("Successful Completions", successfulCompletions)
if err != nil {
log.Printf("Error updating stats: %v", err)
}
}
return nil
}
// runGptSettingsOnRowWithSemaphore is a function that runs the GPT settings on a row with a semaphore for rate limiting.
// It first acquires a token from the gptSemaphore, then launches a goroutine to run the GPT settings on the row.
// The goroutine first checks if a mutex exists for the cell. If it doesn't, it creates a new mutex and stores it in the map.
// It then locks the mutex for the cell to ensure exclusive access to the cell.
// It then calls the runGptSettingsOnRow function to process the GPT settings on the row.
// After the GPT settings have been processed, it unlocks the mutex for the cell to allow other goroutines to access the cell.
// If an error occurs while processing the GPT settings, it logs the error.
// Finally, it releases the token back to the gptSemaphore.
func runGptSettingsOnRowWithSemaphore(row map[string]interface{}, gptSettings ChunkSettings) error {
gptSemaphore <- struct{}{}
wg.Add(1) // Increment WaitGroup counter
go func() {
defer wg.Done() // Decrement WaitGroup counter when goroutine finishes
defer func() { <-gptSemaphore }()
cellMutexesMutex.Lock()
cellKey := fmt.Sprintf("%d:%d", row["RowIndex"], columnIndexByName[gptSettings.PromptColTo])
mutex, ok := cellMutexes[cellKey]
if !ok {
mutex = &sync.Mutex{}
cellMutexes[cellKey] = mutex
}
cellMutexesMutex.Unlock()
mutex.Lock()
err := runGptSettingsOnRow(row, gptSettings)
mutex.Unlock()
if err != nil {
log.Printf("Error running GPT settings on row: %v", err)
}
}()
return nil
}
// readFromSheetWithRateLimit waits for a token from the rate limiter, then reads values from a Google Sheet.
// It returns the values read and any error encountered.
func readFromSheetWithRateLimit(spreadsheetID, range_ string) (*sheets.ValueRange, error) {
// Wait for a token from the rate limiter
if err := sheetsLimiter.Wait(context.Background()); err != nil {
return nil, err
}
// Proceed with the read operation
return srv.Spreadsheets.Values.Get(spreadsheetID, range_).Do()
}
// writeToSheetWithRateLimit waits for a token from the rate limiter, then writes values to a Google Sheet.
// It returns the response from the write operation and any error encountered.
func writeToSheetWithRateLimit(spreadsheetID, range_ string, vr *sheets.ValueRange) (*sheets.UpdateValuesResponse, error) {
// Wait for a token from the rate limiter
if err := sheetsLimiter.Wait(context.Background()); err != nil {
return nil, err
}
// Proceed with the write operation
return srv.Spreadsheets.Values.Update(spreadsheetID, range_, vr).ValueInputOption("USER_ENTERED").Do()
}
// runMainLoop runs the main loop of the program. It fetches the values from the Google Sheet,
// detects any changes, updates the previous state, and sleeps for the specified refresh frequency
// before fetching the values again. It also updates the "Total Rows Processed" stat if the STATS setting is true.
// It handles any errors that occur during these operations by calling the handleError function,
// which increments the "Errors" counter and updates the "Errors" and "Last Error" stats.
// It returns an error if an error occurred while sleeping.
func runMainLoop() error {
lastColumnCheck := time.Now().Add(-1 * time.Hour)
lastReadSettings := time.Now().Add(-1 * time.Hour)
// Define a counter for the total number of rows processed
totalRowsProcessed := 0
// Initialize prevState as nil
var prevState [][]interface{} = nil
for {
if time.Since(lastReadSettings).Seconds() >= 15 {
err := readSettings()
if err != nil {
log.Printf("Error reading settings: %v", err)
continue
}
lastReadSettings = time.Now()
}
resp, err := getSheetValuesWithSemaphore(spreadsheetID, allSettings["GLOBAL"]["SHEET_NAME"].(string))
if err != nil {
handleError(err) // Call handleError function instead of logging the error directly
continue
}
// Increment the total number of rows processed by the number of rows
totalRowsProcessed += len(resp.Values)
// If STATS is true, update the "Total Rows Processed" stat
if statsEnabled, ok := allSettings["GLOBAL"]["STATS"].(bool); ok && statsEnabled {
err := su.UpdateStats("Total Rows Processed", totalRowsProcessed)
if err != nil {
handleError(err) // Call handleError function instead of logging the error directly
}
}
// If prevState is nil, write the initial state to Redis
if prevState == nil {
for i := range resp.Values {
for j := range resp.Values[i] {
value, ok := resp.Values[i][j].(string)
if !ok {
handleError(fmt.Errorf("error: value is not a string. It is a %T", resp.Values[i][j])) // Call handleError function instead of logging the error directly
continue
}
err := redisClient.Set(fmt.Sprintf("cell:%d:%d", i, j), value, 0).Err()
if err != nil {
handleError(err) // Call handleError function instead of logging the error directly
continue
}
}
}
prevState = resp.Values
continue
}
shouldCheckForNewColumns := false
newColumnsFreq, ok := allSettings["GLOBAL"]["SHEET_NEW_COLUMNS_FREQUENCY"].(float64)
if !ok {
handleError(fmt.Errorf("error: SHEET_NEW_COLUMNS_FREQUENCY in allSettings is not a float value")) // Call handleError function instead of logging the error directly
continue
}
if time.Since(lastColumnCheck).Seconds() >= newColumnsFreq {
shouldCheckForNewColumns = true
lastColumnCheck = time.Now()
}
err = detectChanges(resp.Values, shouldCheckForNewColumns)
if err != nil {
handleError(err) // Call handleError function instead of logging the error directly
continue
}
prevState = resp.Values
sleepFreq, ok := allSettings["GLOBAL"]["SHEET_REFRESH_FREQUENCY"].(float64)
if !ok {
handleError(fmt.Errorf("error: SHEET_REFRESH_FREQUENCY in allSettings is not a float value")) // Call handleError function instead of logging the error directly
continue
}
time.Sleep(time.Duration(sleepFreq * float64(time.Second)))
}
return nil
}
// getSheetValuesWithSemaphore is a wrapper function for readFromSheetWithRateLimit
// that uses a semaphore for rate limiting.
func getSheetValuesWithSemaphore(spreadsheetID, sheetName string) (*sheets.ValueRange, error) {
sheetsSemaphore <- struct{}{}
respCh := make(chan *sheets.ValueRange, 1)
errCh := make(chan error, 1)
wg.Add(1) // Increment WaitGroup counter
go func() {
defer wg.Done() // Decrement WaitGroup counter when goroutine finishes
defer func() { <-sheetsSemaphore }()
resp, err := readFromSheetWithRateLimit(spreadsheetID, sheetName)
if err != nil {
errCh <- fmt.Errorf("error getting sheet values: %v", err)
return
}
respCh <- resp
close(respCh)
close(errCh)
}()
resp := <-respCh
err := <-errCh
if err != nil {
return nil, err
}
return resp, nil
}
// the main function is the entry point of the program.
// it loads the environment variables, creates the Google Sheets and Redis services,
// fetches the settings from the Google Sheet, stores the prompt settings,
// and runs the main loop of the program.
func main() {
err := setupEnvironment()
if err != nil {
log.Fatalf("Error setting up environment: %v", err)
}
err = readSettings()
if err != nil {
log.Fatalf("Error reading settings: %v", err)
}
err = runMainLoop()
if err != nil {
log.Fatalf("Error running main loop: %v", err)
}
wg.Wait() // Wait for all goroutines to finish before exiting
}