From 190f1f88cbcc261dbc87c90eaf499155968decdc Mon Sep 17 00:00:00 2001 From: Samuel Pua Date: Thu, 27 Oct 2022 01:02:45 +0800 Subject: [PATCH] Fix(booking-job): Ensures triggerFuturePageRefresh is cancelled --- .../ktmtrainbot/backgroundbookingjob.go | 23 +++++++++++-------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/backend/internal/ktmtrainbot/backgroundbookingjob.go b/backend/internal/ktmtrainbot/backgroundbookingjob.go index 2117227..4a17dc5 100644 --- a/backend/internal/ktmtrainbot/backgroundbookingjob.go +++ b/backend/internal/ktmtrainbot/backgroundbookingjob.go @@ -106,13 +106,13 @@ func (env *Env) BackgroundJobRunner() { if success { jobToDo.Status = "success" env.DB.Save(&jobToDo) - fmt.Println("Successfully made a booking.") + log.Println("Successfully made a booking.") } else { // Sleep for 10 minutes before setting status to pending time.Sleep(10 * time.Minute) jobToDo.Status = "pending" env.DB.Save(&jobToDo) - fmt.Println("Failed to make a booking.") + log.Println("Failed to make a booking.") } }() jobToDo.Status = "running" @@ -296,13 +296,6 @@ func (env *Env) startBooking(job *Booking, username string, password string, cre } func chooseAndMakePayment(timerCtx context.Context, creditCardType, creditCard, creditCardCVV, creditCardExpiry string, browser *rod.Browser, page *rod.Page) bool { - defer func() { - if r := recover(); r != nil { - log.Println("Recovering from chooseAndMakePayment panic...") - chooseAndMakePayment(timerCtx, creditCardType, creditCard, creditCardCVV, creditCardExpiry, browser, page) - } - }() - // Exits if context cancelled select { case <-timerCtx.Done(): @@ -311,7 +304,15 @@ func chooseAndMakePayment(timerCtx context.Context, creditCardType, creditCard, default: } - go triggerFuturePageRefresh(page) + cancelRefresh := triggerFuturePageRefresh(page) + + defer func() { + if r := recover(); r != nil { + log.Println("Recovering from chooseAndMakePayment panic...") + cancelRefresh() + chooseAndMakePayment(timerCtx, creditCardType, creditCard, creditCardCVV, creditCardExpiry, browser, page) + } + }() if strings.ToUpper(creditCardType) == "VISA" || strings.ToUpper(creditCardType) == "MASTERCARD" { log.Println("Credit card payment method chosen.") @@ -356,6 +357,7 @@ func chooseAndMakePayment(timerCtx context.Context, creditCardType, creditCard, log.Println("KTM wallet payment made.") } + cancelRefresh() return true } @@ -629,6 +631,7 @@ func triggerFuturePageRefresh(page *rod.Page) func() { return // Reload page after 9 minutes case <-time.After(540 * time.Second): + log.Println("Reloading page") page.MustReload() } }()