Skip to content

Commit

Permalink
Merge pull request #175 from Tibz-Dankan/switch/sqlite
Browse files Browse the repository at this point in the history
Switch/sqlite
  • Loading branch information
Tibz-Dankan authored Sep 13, 2024
2 parents 74a1fac + 3218702 commit e853924
Show file tree
Hide file tree
Showing 3 changed files with 103 additions and 32 deletions.
2 changes: 0 additions & 2 deletions internal/routes/request/getLiveRequests.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ type AppRequestProgress = services.AppRequestProgress
func sendMessage(message, userId string, clientManager *services.ClientManager) error {
w, ok := clientManager.GetClient(userId)
if !ok {
log.Println("Client not found")
return nil
}

Expand All @@ -45,7 +44,6 @@ func sendMessage(message, userId string, clientManager *services.ClientManager)
func sendAppToClient(appRequestProgress AppRequestProgress, clientManager *services.ClientManager) error {
client, ok := clientManager.GetClient(appRequestProgress.UserID)
if !ok {
log.Println("Client not found")
return nil
}

Expand Down
93 changes: 79 additions & 14 deletions internal/routes/request/makeRequest.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,24 +13,34 @@ import (

// Makes request for the app
func MakeAppRequest(app models.App) {
ok, err := validateApp(app)
isValid, requiresExternalRequest, err := validateApp(app)
if err != nil {
log.Println("Error validating the app: ", err)
}
if !ok {
if !isValid {
log.Println("Couldn't make request: ", app.Name)
return
}

response := services.Response{}
appRequestProgress := services.AppRequestProgress{App: app, InProgress: true}
services.UserAppMem.Add(app.UserID, appRequestProgress)

events.EB.Publish("appRequestProgress", appRequestProgress)

response, err := services.MakeHTTPRequest(app.URL)
if err != nil {
log.Println("Request error:", err)
return
if !requiresExternalRequest {
response, err = services.MakeHTTPRequest(app.URL)
if err != nil {
log.Println("Request error:", err)
return
}
}

if requiresExternalRequest {
response, err = services.MakeExternalHTTPRequest(app.URL)
if err != nil {
log.Println("Request error:", err)
return
}
}

request := models.Request{
Expand All @@ -54,17 +64,23 @@ func MakeAppRequest(app models.App) {
}

// Validates the app's eligibility for making requests
func validateApp(app models.App) (bool, error) {
// It returns isValid, requiresExternalRequest and error
func validateApp(app models.App) (bool, bool, error) {
if app.IsDisabled {
return false, nil
return false, false, nil
}

requiresExternal, err := appRequiresExternalRequest(app)
if err != nil {
log.Println("Error getting the external determination", err)
}

hasLastRequest := len(app.Request) > 0

// Check and validate requestInterval
if len(app.RequestTime) == 0 {
if !hasLastRequest {
return true, nil
return true, requiresExternal, nil
}
log.Println("App doesn't have requestTime")
currentTime := time.Now()
Expand All @@ -80,9 +96,9 @@ func validateApp(app models.App) (bool, error) {
}

if int(timeDiff) >= requestInterval {
return true, nil
return true, requiresExternal, nil
}
return false, nil
return false, requiresExternal, nil
}

for _, rt := range app.RequestTime {
Expand Down Expand Up @@ -112,7 +128,7 @@ func validateApp(app models.App) (bool, error) {
// Check and validate requestInterval
log.Println("App time frame is correct")
if !hasLastRequest {
return true, nil
return true, requiresExternal, nil
}
lastRequestStartedAt, _ := appDateStart.ISOTime()
timeDiff := currentTimeStart.Sub(lastRequestStartedAt).Minutes()
Expand All @@ -122,10 +138,59 @@ func validateApp(app models.App) (bool, error) {
}

if int(timeDiff) >= requestInterval {
return true, nil
return true, requiresExternal, nil
}
}
}

return false, requiresExternal, nil
}

func appRequiresExternalRequest(app models.App) (bool, error) {
hasLastRequest := len(app.Request) > 0
hasRequestTime := len(app.RequestTime) > 0

if !hasLastRequest {
return true, nil
}

if !hasRequestTime {
currentTime := time.Now()
location := currentTime.Location().String()
appDate := services.Date{TimeZone: location, ISOStringDate: app.Request[0].StartedAt.String()}

currentAppTime, _ := appDate.CurrentTime()
lastRequestStartedAt, _ := appDate.ISOTime()
timeDiff := currentAppTime.Sub(lastRequestStartedAt).Minutes()

if int(timeDiff) > 15 {
return true, nil
}

if app.Request[0].StatusCode == 503 && app.Request[0].Duration < 15*1000 {
return true, nil
}
}

for _, rt := range app.RequestTime {
lastReqStartedAtStr := time.Now().String()
if hasLastRequest {
lastReqStartedAtStr = app.Request[0].StartedAt.String()
}

appDate := services.Date{TimeZone: rt.TimeZone, ISOStringDate: lastReqStartedAtStr, HourMinSec: rt.Start}
currentAppTime, _ := appDate.CurrentTime()
lastRequestStartedAt, _ := appDate.ISOTime()
timeDiff := currentAppTime.Sub(lastRequestStartedAt).Minutes()

if int(timeDiff) > 15 {
return true, nil
}

if app.Request[0].StatusCode == 503 && app.Request[0].Duration < 15*1000 {
return true, nil
}
}

return false, nil
}
40 changes: 24 additions & 16 deletions internal/services/httpRequest.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package services

import (
"fmt"
"io"
"log"
"net"
"net/http"
Expand Down Expand Up @@ -49,12 +48,6 @@ func MakeHTTPRequest(URL string) (Response, error) {
if err != nil {
log.Printf("Error making request: %v", err)
if isTimeoutError(err) {
retryBaseURL := os.Getenv("APPCRONS_RETRY_URL")
retryURL := fmt.Sprintf("%s?url=%s", retryBaseURL, URL)

if err := MakeHTTPRetryRequest(retryURL); err != nil {
return response, err
}
response.StatusCode = 503
response.RequestTimeMS = requestTimeMS
response.StartedAt = startTime
Expand All @@ -71,11 +64,16 @@ func MakeHTTPRequest(URL string) (Response, error) {
return response, nil
}

func MakeHTTPRetryRequest(URL string) error {
req, err := http.NewRequest(http.MethodGet, URL, nil)
func MakeExternalHTTPRequest(URL string) (Response, error) {
response := Response{}
startTime := time.Now()

externalURL := fmt.Sprintf("%s?url=%s", os.Getenv("APPCRONS_EXTERNAL_URL"), URL)

req, err := http.NewRequest(http.MethodGet, externalURL, nil)
if err != nil {
log.Printf("Error creating request: %v", err)
return err
return response, err
}
req.Header.Set("Content-Type", "application/json")

Expand All @@ -89,20 +87,30 @@ func MakeHTTPRetryRequest(URL string) error {

client := &http.Client{
Transport: transport,
Timeout: time.Second * 35,
Timeout: time.Minute * 4,
}

res, err := client.Do(req)
duration := time.Since(startTime)
requestTimeMS := int(duration.Milliseconds())

if err != nil {
return err
log.Printf("Error making request: %v", err)
if isTimeoutError(err) {
response.StatusCode = 503
response.RequestTimeMS = requestTimeMS
response.StartedAt = startTime
response.Message = "Request timeout"
return response, nil
}
return response, err
}
defer res.Body.Close()

body, _ := io.ReadAll(res.Body)
log.Printf("Response Body: %s", string(body))
response.StatusCode = res.StatusCode
response.RequestTimeMS = requestTimeMS
response.StartedAt = startTime

return nil
return response, nil
}

func isTimeoutError(err error) bool {
Expand Down

0 comments on commit e853924

Please sign in to comment.