From 56220bf53a2f61cf9e5fda219413154564186a12 Mon Sep 17 00:00:00 2001 From: Ross Savage Date: Mon, 2 Jan 2023 21:05:16 +0100 Subject: [PATCH 1/6] Remove verification key --- go.mod | 2 +- go.sum | 2 + internal/rpc/command/rpc.go | 11 +-- internal/tokenauthorization/v2.1.1/process.go | 15 ---- ocpirpc/command.pb.go | 75 ++++++++----------- ocpirpc/command.proto | 1 - pkg/ocpi/command/message.go | 4 +- pkg/ocpi/tokenauthorization/util.go | 13 ---- 8 files changed, 38 insertions(+), 85 deletions(-) delete mode 100644 pkg/ocpi/tokenauthorization/util.go diff --git a/go.mod b/go.mod index 0e9d9b74..d7b93fdc 100644 --- a/go.mod +++ b/go.mod @@ -13,7 +13,7 @@ require ( github.com/joho/godotenv v1.4.0 github.com/nsf/jsondiff v0.0.0-20210926074059-1e845ec5d249 github.com/prometheus/client_golang v1.13.1 - github.com/satimoto/go-datastore v0.3.1-0.20221215215552-467363aef4a9 + github.com/satimoto/go-datastore v0.3.1-0.20230102194740-a5839718733c google.golang.org/grpc v1.47.0 ) diff --git a/go.sum b/go.sum index 128d4302..4c9f3b60 100644 --- a/go.sum +++ b/go.sum @@ -402,6 +402,8 @@ github.com/satimoto/go-datastore v0.3.1-0.20221211215042-d5318660b0e1 h1:j8SMRJQ github.com/satimoto/go-datastore v0.3.1-0.20221211215042-d5318660b0e1/go.mod h1:SvM8losYPwH6hJgUKLkjNtQwVv06lZgCMWl8cGdllCM= github.com/satimoto/go-datastore v0.3.1-0.20221215215552-467363aef4a9 h1:vmWEl6/uFLQND2y0IE47Ym8iBDRhfF/z8AdFH9ls8LI= github.com/satimoto/go-datastore v0.3.1-0.20221215215552-467363aef4a9/go.mod h1:SvM8losYPwH6hJgUKLkjNtQwVv06lZgCMWl8cGdllCM= +github.com/satimoto/go-datastore v0.3.1-0.20230102194740-a5839718733c h1:pFctByHq4fH9RKHDdHTcyfFRspAI6WJUuBZNVMkzZGg= +github.com/satimoto/go-datastore v0.3.1-0.20230102194740-a5839718733c/go.mod h1:SvM8losYPwH6hJgUKLkjNtQwVv06lZgCMWl8cGdllCM= github.com/satimoto/go-lsp v0.2.1-0.20221115190646-b981e98c7ba4 h1:3QKFoeOVSDU8bvrVfj/zAMDq+hg3KJBLaMgEgutJExk= github.com/satimoto/go-lsp v0.2.1-0.20221115190646-b981e98c7ba4/go.mod h1:bleUpVumUC8QAFi0CZdnbtDRGWRFKETMH5JWcLAolBs= github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0= diff --git a/internal/rpc/command/rpc.go b/internal/rpc/command/rpc.go index a07a4556..5ec612f9 100644 --- a/internal/rpc/command/rpc.go +++ b/internal/rpc/command/rpc.go @@ -12,7 +12,6 @@ import ( metrics "github.com/satimoto/go-ocpi/internal/metric" "github.com/satimoto/go-ocpi/ocpirpc" ocpiCommand "github.com/satimoto/go-ocpi/pkg/ocpi/command" - ocpiTokenAuthorization "github.com/satimoto/go-ocpi/pkg/ocpi/tokenauthorization" ) func (r *RpcCommandResolver) ReserveNow(ctx context.Context, input *ocpirpc.ReserveNowRequest) (*ocpirpc.ReserveNowResponse, error) { @@ -130,14 +129,6 @@ func (r *RpcCommandResolver) StartSession(ctx context.Context, input *ocpirpc.St return nil, errors.New("error starting session") } - verificationKey, err := ocpiTokenAuthorization.CreateVerificationKey(*tokenAuthorization) - - if err != nil { - metrics.RecordError("OCPI282", "Error creating verification key", err) - log.Printf("OCPI282: TokenAuthorization=%#v", tokenAuthorization) - return nil, errors.New("error starting session") - } - command, err := r.CommandResolver.StartSession(ctx, credential, *tokenAuthorization, &input.EvseUid) if err != nil { @@ -146,7 +137,7 @@ func (r *RpcCommandResolver) StartSession(ctx context.Context, input *ocpirpc.St return nil, err } - startResponse := ocpiCommand.NewCommandStartResponse(*command, verificationKey) + startResponse := ocpiCommand.NewCommandStartResponse(*command) return startResponse, nil } diff --git a/internal/tokenauthorization/v2.1.1/process.go b/internal/tokenauthorization/v2.1.1/process.go index 75b97b5d..ea17cde0 100644 --- a/internal/tokenauthorization/v2.1.1/process.go +++ b/internal/tokenauthorization/v2.1.1/process.go @@ -6,7 +6,6 @@ import ( "log" "time" - secp "github.com/decred/dcrd/dcrec/secp256k1/v4" "github.com/satimoto/go-datastore/pkg/db" "github.com/satimoto/go-datastore/pkg/param" "github.com/satimoto/go-datastore/pkg/util" @@ -40,7 +39,6 @@ func (r *TokenAuthorizationResolver) CreateTokenAuthorization(ctx context.Contex tokenAuthorizationParams := param.NewCreateTokenAuthorizationParams(token.ID) tokenAuthorizationParams.Authorized = token.Type == db.TokenTypeOTHER - tokenAuthorizationParams.SigningKey = r.createTokenAuthorizationSigningKey() if locationReferencesDto != nil { tokenAuthorizationParams.LocationID = util.SqlNullString(locationReferencesDto.LocationID) @@ -150,19 +148,6 @@ func (r *TokenAuthorizationResolver) createTokenAuthorizationRelations(ctx conte } } -func (r *TokenAuthorizationResolver) createTokenAuthorizationSigningKey() []byte { - var privateKey *secp.PrivateKey - var err error - - for { - if privateKey, err = secp.GeneratePrivateKey(); err == nil { - break - } - } - - return privateKey.Serialize() -} - func (r *TokenAuthorizationResolver) waitForEvsesStatus(credential db.Credential, token db.Token, tokenAuthorization db.TokenAuthorization, locationReferencesDto *dto.LocationReferencesDto, evseStatus db.EvseStatus, timeoutSeconds int) { if locationReferencesDto != nil && locationReferencesDto.LocationID != nil && len(locationReferencesDto.EvseUids) > 0 { cancelCtx, cancel := context.WithCancel(context.Background()) diff --git a/ocpirpc/command.pb.go b/ocpirpc/command.pb.go index b6d60c18..a3ea872c 100644 --- a/ocpirpc/command.pb.go +++ b/ocpirpc/command.pb.go @@ -225,7 +225,6 @@ type StartSessionResponse struct { Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` Status string `protobuf:"bytes,2,opt,name=status,proto3" json:"status,omitempty"` AuthorizationId string `protobuf:"bytes,3,opt,name=authorizationId,proto3" json:"authorizationId,omitempty"` - VerificationKey string `protobuf:"bytes,4,opt,name=verificationKey,proto3" json:"verificationKey,omitempty"` LocationUid string `protobuf:"bytes,5,opt,name=location_uid,json=locationUid,proto3" json:"location_uid,omitempty"` EvseUid string `protobuf:"bytes,6,opt,name=evse_uid,json=evseUid,proto3" json:"evse_uid,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` @@ -279,13 +278,6 @@ func (m *StartSessionResponse) GetAuthorizationId() string { return "" } -func (m *StartSessionResponse) GetVerificationKey() string { - if m != nil { - return m.VerificationKey - } - return "" -} - func (m *StartSessionResponse) GetLocationUid() string { if m != nil { return m.LocationUid @@ -542,40 +534,39 @@ func init() { func init() { proto.RegisterFile("ocpirpc/command.proto", fileDescriptor_6c9ab853259f9e2c) } var fileDescriptor_6c9ab853259f9e2c = []byte{ - // 515 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x55, 0xcd, 0x6e, 0xd3, 0x40, - 0x10, 0xd6, 0x3a, 0x6d, 0x42, 0x27, 0x69, 0x2b, 0x16, 0x68, 0x83, 0x5b, 0x94, 0x90, 0x82, 0x94, - 0x0b, 0x8d, 0x04, 0x77, 0x0e, 0x14, 0x24, 0xaa, 0x4a, 0x1c, 0x1c, 0x72, 0xe1, 0x12, 0xb9, 0xf6, - 0xd0, 0xae, 0x48, 0x3c, 0x66, 0x77, 0x1d, 0x28, 0xbc, 0x00, 0x12, 0xaf, 0xc1, 0x8b, 0x20, 0xf1, - 0x00, 0x3c, 0x12, 0xb2, 0xbd, 0x09, 0xf6, 0xc6, 0x4d, 0x55, 0x55, 0x3d, 0xce, 0xcf, 0xce, 0xf7, - 0xcd, 0xb7, 0xb3, 0xb3, 0xf0, 0x80, 0x82, 0x58, 0xc8, 0x38, 0x18, 0x04, 0x34, 0x9d, 0xfa, 0x51, - 0x78, 0x18, 0x4b, 0xd2, 0xc4, 0x1b, 0xc6, 0xec, 0xfd, 0x64, 0x70, 0xd7, 0x43,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, 0x67, 0x42, 0x9f, 0x27, 0xa7, 0x69, - 0xe6, 0x40, 0xf9, 0x5a, 0x4c, 0x49, 0xd3, 0xe0, 0x8c, 0x9e, 0xa5, 0x3f, 0xc0, 0xc0, 0x7c, 0x03, - 0xa7, 0xf5, 0x6c, 0xff, 0xbf, 0xf8, 0x17, 0x00, 0x00, 0xff, 0xff, 0x6f, 0x3b, 0xa8, 0xef, 0x18, - 0x06, 0x00, 0x00, + // 497 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x54, 0xcd, 0x6e, 0xd3, 0x40, + 0x10, 0xd6, 0x3a, 0x6d, 0x42, 0x27, 0x69, 0x2b, 0x06, 0x68, 0x83, 0x5b, 0x94, 0x90, 0x82, 0x94, + 0x0b, 0x8d, 0x04, 0x77, 0x0e, 0x14, 0x24, 0x2a, 0x24, 0x0e, 0x0e, 0xb9, 0x70, 0x89, 0x5c, 0x7b, + 0xd4, 0xae, 0x48, 0x3c, 0x66, 0x77, 0x1d, 0xfe, 0x5e, 0x00, 0x89, 0xd7, 0x40, 0xbc, 0x07, 0x12, + 0x0f, 0x86, 0xfc, 0x93, 0xe0, 0xbf, 0xa6, 0xaa, 0x2a, 0x8e, 0xf3, 0xb3, 0xf3, 0xcd, 0xf7, 0xed, + 0xcc, 0xc0, 0x3d, 0xf6, 0x42, 0xa9, 0x42, 0x6f, 0xe4, 0xf1, 0x7c, 0xee, 0x06, 0xfe, 0x71, 0xa8, + 0xd8, 0x30, 0xb6, 0x32, 0x73, 0xf0, 0x43, 0xc0, 0x6d, 0x87, 0x34, 0xa9, 0x05, 0xbd, 0xe5, 0x4f, + 0x0e, 0x7d, 0x8c, 0x48, 0x1b, 0xdc, 0x87, 0x56, 0xa4, 0x49, 0x4d, 0xa5, 0xdf, 0x15, 0x7d, 0x31, + 0x6c, 0x38, 0xcd, 0xd8, 0x3c, 0xf5, 0xb1, 0x07, 0x6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x7c, + 0x83, 0xbd, 0x49, 0x30, 0x63, 0xef, 0xc3, 0x09, 0x07, 0x01, 0x79, 0x86, 0xd5, 0x92, 0x4e, 0x59, + 0x22, 0xb1, 0x5e, 0x22, 0xab, 0x20, 0x11, 0x1e, 0xc1, 0xb6, 0xb7, 0xac, 0x98, 0xfb, 0xeb, 0xce, + 0xca, 0x19, 0x83, 0xff, 0x14, 0xb0, 0x5f, 0x41, 0xbf, 0xa6, 0x16, 0x37, 0x5a, 0xd2, 0x6a, 0x9b, + 0x9b, 0xd5, 0x36, 0x9f, 0xfe, 0xb1, 0x60, 0xe7, 0x24, 0xbd, 0x31, 0x63, 0x52, 0x0b, 0xe9, 0x11, + 0xbe, 0x02, 0xf8, 0xb7, 0xdb, 0x68, 0x1f, 0x2f, 0x2f, 0x52, 0xe5, 0xfc, 0xd8, 0x07, 0xb5, 0xb1, + 0x8c, 0xe4, 0x1b, 0xe8, 0xe4, 0x07, 0x1e, 0x0f, 0x57, 0xc9, 0x35, 0x6b, 0x67, 0x3f, 0xb8, 0x24, + 0x9a, 0x15, 0x7b, 0x0d, 0xed, 0xdc, 0x50, 0xe1, 0x41, 0x2e, 0xbb, 0x3c, 0xab, 0xf6, 0x61, 0x7d, + 0x30, 0xab, 0xf4, 0x0e, 0x76, 0x4b, 0xdf, 0x82, 0xbd, 0xd5, 0x83, 0xfa, 0x71, 0xb1, 0xfb, 0x97, + 0x27, 0xa4, 0x55, 0x5f, 0x3c, 0x7e, 0x7f, 0x74, 0x2e, 0xcd, 0x45, 0x74, 0x16, 0x67, 0x8e, 0xb4, + 0x6b, 0xe4, 0x9c, 0x0d, 0x8f, 0xce, 0xf9, 0x49, 0x7c, 0xd7, 0x47, 0xd9, 0x71, 0x3f, 0x6b, 0x26, + 0x57, 0xfd, 0xd9, 0xdf, 0x00, 0x00, 0x00, 0xff, 0xff, 0x1c, 0x90, 0x0d, 0x9c, 0xee, 0x05, 0x00, + 0x00, } // Reference imports to suppress errors if they are not otherwise used. diff --git a/ocpirpc/command.proto b/ocpirpc/command.proto index aa4cb7d5..702c445f 100644 --- a/ocpirpc/command.proto +++ b/ocpirpc/command.proto @@ -37,7 +37,6 @@ message StartSessionResponse { int64 id = 1; string status = 2; string authorizationId = 3; - string verificationKey = 4; string location_uid = 5; string evse_uid = 6; }; diff --git a/pkg/ocpi/command/message.go b/pkg/ocpi/command/message.go index af669174..7afaebf9 100644 --- a/pkg/ocpi/command/message.go +++ b/pkg/ocpi/command/message.go @@ -1,7 +1,6 @@ package command import ( - "encoding/hex" "time" "github.com/satimoto/go-datastore/pkg/db" @@ -19,12 +18,11 @@ func NewCommandReservationResponse(command db.CommandReservation) *ocpirpc.Reser } } -func NewCommandStartResponse(command db.CommandStart, verificationKey []byte) *ocpirpc.StartSessionResponse { +func NewCommandStartResponse(command db.CommandStart) *ocpirpc.StartSessionResponse { return &ocpirpc.StartSessionResponse{ Id: command.ID, Status: string(command.Status), AuthorizationId: command.AuthorizationID.String, - VerificationKey: hex.EncodeToString(verificationKey), LocationUid: command.LocationID, EvseUid: command.EvseUid.String, } diff --git a/pkg/ocpi/tokenauthorization/util.go b/pkg/ocpi/tokenauthorization/util.go deleted file mode 100644 index 34b966a7..00000000 --- a/pkg/ocpi/tokenauthorization/util.go +++ /dev/null @@ -1,13 +0,0 @@ -package tokenauthorization - -import ( - secp "github.com/decred/dcrd/dcrec/secp256k1/v4" - "github.com/satimoto/go-datastore/pkg/db" -) - -func CreateVerificationKey(tokenAuthorization db.TokenAuthorization) ([]byte, error) { - privateKey := secp.PrivKeyFromBytes(tokenAuthorization.SigningKey) - publicKey := privateKey.PubKey() - - return publicKey.SerializeCompressed(), nil -} From d1bba69184262fb14a7c7a2f78552f909444faca Mon Sep 17 00:00:00 2001 From: Ross Savage Date: Wed, 11 Jan 2023 13:13:17 +0100 Subject: [PATCH 2/6] Set last token authorization to unauthorised if no session is yet created, add WAIT_FOR_EVSE_STATUS_TIMEOUT environment variable --- internal/session/v2.1.1/process.go | 4 +- internal/tokenauthorization/v2.1.1/process.go | 37 +++++++++----- internal/tokenauthorization/v2.1.1/push.go | 5 +- terraform/environments/mainnet/main.tf | 49 ++++++++++--------- terraform/environments/mainnet/variables.tf | 4 ++ terraform/environments/testnet/main.tf | 47 +++++++++--------- terraform/environments/testnet/variables.tf | 4 ++ .../resources/task-container-definitions.json | 4 ++ 8 files changed, 93 insertions(+), 61 deletions(-) diff --git a/internal/session/v2.1.1/process.go b/internal/session/v2.1.1/process.go index 4f4c18d1..9ceb90b6 100644 --- a/internal/session/v2.1.1/process.go +++ b/internal/session/v2.1.1/process.go @@ -185,7 +185,9 @@ func (r *SessionResolver) ReplaceSessionByIdentifier(ctx context.Context, creden } if sessionCreated && session.Status == db.SessionStatusTypePENDING { - go r.waitForEvseStatus(credential, session.LocationID, session.EvseID, db.EvseStatusCHARGING, session, session.Status, db.SessionStatusTypeACTIVE, 150) + timeout := int(util.GetEnvInt32("WAIT_FOR_EVSE_STATUS_TIMEOUT", 180)) + + go r.waitForEvseStatus(credential, session.LocationID, session.EvseID, db.EvseStatusCHARGING, session, session.Status, db.SessionStatusTypeACTIVE, timeout) } return &session diff --git a/internal/tokenauthorization/v2.1.1/process.go b/internal/tokenauthorization/v2.1.1/process.go index ea17cde0..b87cdb54 100644 --- a/internal/tokenauthorization/v2.1.1/process.go +++ b/internal/tokenauthorization/v2.1.1/process.go @@ -37,24 +37,37 @@ func (r *TokenAuthorizationResolver) CreateTokenAuthorization(ctx context.Contex } } - tokenAuthorizationParams := param.NewCreateTokenAuthorizationParams(token.ID) - tokenAuthorizationParams.Authorized = token.Type == db.TokenTypeOTHER + if lastTokenAuthorization, err := r.Repository.GetLastTokenAuthorizationByTokenID(ctx, token.ID); err == nil { + // Last token authorization for this token has no session, unauthorise the token authorization + updateTokenAuthorizationParams := param.NewUpdateTokenAuthorizationParams(lastTokenAuthorization) + updateTokenAuthorizationParams.Authorized = false + + _, err = r.Repository.UpdateTokenAuthorizationByAuthorizationID(ctx, updateTokenAuthorizationParams) + + if err != nil { + metrics.RecordError("OCPI332", "Error updating token authorization", err) + log.Printf("OCPI332: Params=%#v", updateTokenAuthorizationParams) + } + } + + createTokenAuthorizationParams := param.NewCreateTokenAuthorizationParams(token.ID) + createTokenAuthorizationParams.Authorized = token.Type == db.TokenTypeOTHER if locationReferencesDto != nil { - tokenAuthorizationParams.LocationID = util.SqlNullString(locationReferencesDto.LocationID) + createTokenAuthorizationParams.LocationID = util.SqlNullString(locationReferencesDto.LocationID) } - tokenAuthorization, err := r.Repository.CreateTokenAuthorization(ctx, tokenAuthorizationParams) + tokenAuthorization, err := r.Repository.CreateTokenAuthorization(ctx, createTokenAuthorizationParams) if err != nil { metrics.RecordError("OCPI206", "Error creating token authorization", err) - log.Printf("OCPI206: Params=%#v", tokenAuthorizationParams) + log.Printf("OCPI206: Params=%#v", createTokenAuthorizationParams) return nil, errors.New("Authorization error") } r.createTokenAuthorizationRelations(ctx, tokenAuthorization.ID, locationReferencesDto) - if !tokenAuthorizationParams.Authorized { + if !createTokenAuthorizationParams.Authorized { // Token authentication is not authorized because its initiated // by an RFID card. The request needs to be forwarded to the user's // device, which then responds if it is authorized or not. @@ -72,21 +85,21 @@ func (r *TokenAuthorizationResolver) CreateTokenAuthorization(ctx context.Contex return nil, errors.New("Please enable notifications in your Satimoto application") } - asyncChan := r.AsyncService.Add(tokenAuthorizationParams.AuthorizationID) - r.SendNotification(user, tokenAuthorizationParams.AuthorizationID) + asyncChan := r.AsyncService.Add(createTokenAuthorizationParams.AuthorizationID) + r.SendNotification(user, createTokenAuthorizationParams.AuthorizationID) timeout := util.GetEnvInt32("TOKEN_AUTHORIZATION_TIMEOUT", 5) select { case asyncResult := <-asyncChan: - log.Printf("Token authorization received: %v", tokenAuthorizationParams.AuthorizationID) - r.AsyncService.Remove(tokenAuthorizationParams.AuthorizationID) + log.Printf("Token authorization received: %v", createTokenAuthorizationParams.AuthorizationID) + r.AsyncService.Remove(createTokenAuthorizationParams.AuthorizationID) if !asyncResult.Bool { return nil, errors.New("Please fund your Satimoto application and try again") } case <-time.After(time.Duration(timeout) * time.Second): - log.Printf("Token authorization timeout: %v", tokenAuthorizationParams.AuthorizationID) - r.AsyncService.Remove(tokenAuthorizationParams.AuthorizationID) + log.Printf("Token authorization timeout: %v", createTokenAuthorizationParams.AuthorizationID) + r.AsyncService.Remove(createTokenAuthorizationParams.AuthorizationID) return nil, errors.New("Authorization timeout") } diff --git a/internal/tokenauthorization/v2.1.1/push.go b/internal/tokenauthorization/v2.1.1/push.go index 4034a6f8..144ad38e 100644 --- a/internal/tokenauthorization/v2.1.1/push.go +++ b/internal/tokenauthorization/v2.1.1/push.go @@ -6,6 +6,7 @@ import ( "github.com/go-chi/render" "github.com/satimoto/go-datastore/pkg/db" + "github.com/satimoto/go-datastore/pkg/util" coreDto "github.com/satimoto/go-ocpi/internal/dto" dto "github.com/satimoto/go-ocpi/internal/dto/v2.1.1" "github.com/satimoto/go-ocpi/internal/middleware" @@ -40,7 +41,9 @@ func (r *TokenAuthorizationResolver) AuthorizeToken(rw http.ResponseWriter, requ authorizationInfoDto = r.CreateAuthorizationInfoDto(ctx, token, tokenAuthorization, locationReferencesDto, displayText) if tokenAuthorization != nil && tokenAuthorization.Authorized { - go r.waitForEvsesStatus(*cred, token, *tokenAuthorization, locationReferencesDto, db.EvseStatusCHARGING, 150) + timeout := int(util.GetEnvInt32("WAIT_FOR_EVSE_STATUS_TIMEOUT", 180)) + + go r.waitForEvsesStatus(*cred, token, *tokenAuthorization, locationReferencesDto, db.EvseStatusCHARGING, timeout) } } diff --git a/terraform/environments/mainnet/main.tf b/terraform/environments/mainnet/main.tf index 0df2f4be..15bc048d 100644 --- a/terraform/environments/mainnet/main.tf +++ b/terraform/environments/mainnet/main.tf @@ -96,29 +96,30 @@ module "service-ocpi" { service_discovery_namespace_id = data.terraform_remote_state.infrastructure.outputs.ecs_service_discovery_namespace_id task_container_definitions = templatefile("../../resources/task-container-definitions.json", { - account_id = data.aws_caller_identity.current.account_id - image_tag = "mainnet" - region = var.region - service_name = var.service_name - service_container_port = var.service_container_port - service_metric_port = var.service_metric_port - rpc_container_port = var.env_rpc_port - task_network_mode = var.task_network_mode - env_api_domain = "https://${var.subdomain_name}.${data.terraform_remote_state.infrastructure.outputs.route53_zone_name}" - env_web_domain = "https://${data.terraform_remote_state.infrastructure.outputs.route53_zone_name}" - env_country_code = var.env_country_code - env_party_id = var.env_party_id - env_issuer = var.env_issuer - env_db_user = "satimoto" - env_db_pass = data.aws_ssm_parameter.satimoto_db_password.value - env_db_host = "${data.terraform_remote_state.infrastructure.outputs.rds_cluster_endpoint}:${data.terraform_remote_state.infrastructure.outputs.rds_cluster_port}" - env_db_name = "satimoto" - env_fcm_api_key = var.env_fcm_api_key - env_metric_port = var.service_metric_port - env_rest_port = var.service_container_port - env_rpc_port = var.env_rpc_port - env_record_evse_status_periods = var.env_record_evse_status_periods - env_shutdown_timeout = var.env_shutdown_timeout - env_token_authorization_timeout = var.env_token_authorization_timeout + account_id = data.aws_caller_identity.current.account_id + image_tag = "mainnet" + region = var.region + service_name = var.service_name + service_container_port = var.service_container_port + service_metric_port = var.service_metric_port + rpc_container_port = var.env_rpc_port + task_network_mode = var.task_network_mode + env_api_domain = "https://${var.subdomain_name}.${data.terraform_remote_state.infrastructure.outputs.route53_zone_name}" + env_web_domain = "https://${data.terraform_remote_state.infrastructure.outputs.route53_zone_name}" + env_country_code = var.env_country_code + env_party_id = var.env_party_id + env_issuer = var.env_issuer + env_db_user = "satimoto" + env_db_pass = data.aws_ssm_parameter.satimoto_db_password.value + env_db_host = "${data.terraform_remote_state.infrastructure.outputs.rds_cluster_endpoint}:${data.terraform_remote_state.infrastructure.outputs.rds_cluster_port}" + env_db_name = "satimoto" + env_fcm_api_key = var.env_fcm_api_key + env_metric_port = var.service_metric_port + env_rest_port = var.service_container_port + env_rpc_port = var.env_rpc_port + env_record_evse_status_periods = var.env_record_evse_status_periods + env_shutdown_timeout = var.env_shutdown_timeout + env_token_authorization_timeout = var.env_token_authorization_timeout + env_wait_for_evse_status_timeout = var.env_wait_for_evse_status_timeout }) } diff --git a/terraform/environments/mainnet/variables.tf b/terraform/environments/mainnet/variables.tf index b696b59b..83f40124 100644 --- a/terraform/environments/mainnet/variables.tf +++ b/terraform/environments/mainnet/variables.tf @@ -106,3 +106,7 @@ variable "env_shutdown_timeout" { variable "env_token_authorization_timeout" { description = "The environment variable to set the token authorization timeout" } + +variable "env_wait_for_evse_status_timeout" { + description = "The environment variable to set the wait for evse status timeout" +} diff --git a/terraform/environments/testnet/main.tf b/terraform/environments/testnet/main.tf index b63a2d4c..7130b38d 100644 --- a/terraform/environments/testnet/main.tf +++ b/terraform/environments/testnet/main.tf @@ -83,28 +83,29 @@ module "service-ocpi" { service_discovery_namespace_id = data.terraform_remote_state.infrastructure.outputs.ecs_service_discovery_namespace_id task_container_definitions = templatefile("../../resources/task-container-definitions.json", { - account_id = data.aws_caller_identity.current.account_id - image_tag = "testnet" - region = var.region - service_name = var.service_name - service_container_port = var.service_container_port - service_metric_port = var.service_metric_port - rpc_container_port = var.env_rpc_port - task_network_mode = var.task_network_mode - env_api_domain = "https://${var.subdomain_name}.${data.terraform_remote_state.infrastructure.outputs.route53_zone_name}" - env_web_domain = "https://${data.terraform_remote_state.infrastructure.outputs.route53_zone_name}" - env_country_code = var.env_country_code - env_party_id = var.env_party_id - env_issuer = var.env_issuer - env_db_user = "satimoto" - env_db_pass = data.aws_ssm_parameter.satimoto_db_password.value - env_db_host = "${data.terraform_remote_state.infrastructure.outputs.rds_cluster_endpoint}:${data.terraform_remote_state.infrastructure.outputs.rds_cluster_port}" - env_db_name = "satimoto" - env_fcm_api_key = var.env_fcm_api_key - env_rest_port = var.service_container_port - env_rpc_port = var.env_rpc_port - env_record_evse_status_periods = var.env_record_evse_status_periods - env_shutdown_timeout = var.env_shutdown_timeout - env_token_authorization_timeout = var.env_token_authorization_timeout + account_id = data.aws_caller_identity.current.account_id + image_tag = "testnet" + region = var.region + service_name = var.service_name + service_container_port = var.service_container_port + service_metric_port = var.service_metric_port + rpc_container_port = var.env_rpc_port + task_network_mode = var.task_network_mode + env_api_domain = "https://${var.subdomain_name}.${data.terraform_remote_state.infrastructure.outputs.route53_zone_name}" + env_web_domain = "https://${data.terraform_remote_state.infrastructure.outputs.route53_zone_name}" + env_country_code = var.env_country_code + env_party_id = var.env_party_id + env_issuer = var.env_issuer + env_db_user = "satimoto" + env_db_pass = data.aws_ssm_parameter.satimoto_db_password.value + env_db_host = "${data.terraform_remote_state.infrastructure.outputs.rds_cluster_endpoint}:${data.terraform_remote_state.infrastructure.outputs.rds_cluster_port}" + env_db_name = "satimoto" + env_fcm_api_key = var.env_fcm_api_key + env_rest_port = var.service_container_port + env_rpc_port = var.env_rpc_port + env_record_evse_status_periods = var.env_record_evse_status_periods + env_shutdown_timeout = var.env_shutdown_timeout + env_token_authorization_timeout = var.env_token_authorization_timeout + env_wait_for_evse_status_timeout = var.env_wait_for_evse_status_timeout }) } diff --git a/terraform/environments/testnet/variables.tf b/terraform/environments/testnet/variables.tf index f6329972..6c227661 100644 --- a/terraform/environments/testnet/variables.tf +++ b/terraform/environments/testnet/variables.tf @@ -105,3 +105,7 @@ variable "env_shutdown_timeout" { variable "env_token_authorization_timeout" { description = "The environment variable to set the token authorization timeout" } + +variable "env_wait_for_evse_status_timeout" { + description = "The environment variable to set the wait for evse status timeout" +} diff --git a/terraform/resources/task-container-definitions.json b/terraform/resources/task-container-definitions.json index 45fe8d85..c4af8fa8 100644 --- a/terraform/resources/task-container-definitions.json +++ b/terraform/resources/task-container-definitions.json @@ -93,6 +93,10 @@ { "name": "TOKEN_AUTHORIZATION_TIMEOUT", "value": "${env_token_authorization_timeout}" + }, + { + "name": "WAIT_FOR_EVSE_STATUS_TIMEOUT", + "value": "${env_wait_for_evse_status_timeout}" } ] } From 4e6e3ee80fd8108fb50e853a6579fd34cd06cf06 Mon Sep 17 00:00:00 2001 From: Ross Savage Date: Thu, 12 Jan 2023 16:19:28 +0100 Subject: [PATCH 3/6] Send a notification if there is an issue authorising a token --- .../tokenauthorization/v2.1.1/notification.go | 45 ++++++++++++++----- internal/tokenauthorization/v2.1.1/process.go | 7 ++- 2 files changed, 38 insertions(+), 14 deletions(-) diff --git a/internal/tokenauthorization/v2.1.1/notification.go b/internal/tokenauthorization/v2.1.1/notification.go index 7e3de062..8a2b0e79 100644 --- a/internal/tokenauthorization/v2.1.1/notification.go +++ b/internal/tokenauthorization/v2.1.1/notification.go @@ -9,25 +9,46 @@ import ( "github.com/satimoto/go-ocpi/internal/notification" ) -func (r *TokenAuthorizationResolver) SendNotification(user db.User, authorizationID string) { +func (r *TokenAuthorizationResolver) SendContentNotification(user db.User, title, body string) { + if user.DeviceToken.Valid { + message := &fcm.Message{ + To: user.DeviceToken.String, + Notification: &fcm.Notification{ + Title: title, + Body: body, + }, + } + + _, err := r.NotificationService.SendNotificationWithRetry(message, 10) + + if err != nil { + metrics.RecordError("OCPI333", "Error sending notification", err) + log.Printf("OCPI333: Message=%v", message) + } + } +} + +func (r *TokenAuthorizationResolver) SendDataNotification(user db.User, authorizationID string) { dto := notification.CreateTokenAuthorizeNotificationDto(authorizationID) r.sendNotification(user, dto) } func (r *TokenAuthorizationResolver) sendNotification(user db.User, data notification.NotificationDto) { - message := &fcm.Message{ - To: user.DeviceToken.String, - ContentAvailable: true, - Priority: "high", - Data: data, - } + if user.DeviceToken.Valid { + message := &fcm.Message{ + To: user.DeviceToken.String, + ContentAvailable: true, + Priority: "high", + Data: data, + } - _, err := r.NotificationService.SendNotificationWithRetry(message, 10) + _, err := r.NotificationService.SendNotificationWithRetry(message, 10) - if err != nil { - // TODO: Cancel session? - metrics.RecordError("OCPI286", "Error sending notification", err) - log.Printf("OCPI286: Message=%v", message) + if err != nil { + // TODO: Cancel session? + metrics.RecordError("OCPI286", "Error sending notification", err) + log.Printf("OCPI286: Message=%v", message) + } } } diff --git a/internal/tokenauthorization/v2.1.1/process.go b/internal/tokenauthorization/v2.1.1/process.go index b87cdb54..de96825a 100644 --- a/internal/tokenauthorization/v2.1.1/process.go +++ b/internal/tokenauthorization/v2.1.1/process.go @@ -25,6 +25,8 @@ func (r *TokenAuthorizationResolver) CreateTokenAuthorization(ctx context.Contex } if user.IsRestricted || !user.NodeID.Valid || !user.LastActiveDate.Valid { + r.SendContentNotification(user, "Card Authorization Failed", "Please fund your Satimoto application and try again") + return nil, errors.New("Please fund your Satimoto application and try again") } @@ -32,7 +34,8 @@ func (r *TokenAuthorizationResolver) CreateTokenAuthorization(ctx context.Contex fiveDaysAgo := time.Now().Add(time.Hour * 24 * -5) if fiveDaysAgo.After(user.LastActiveDate.Time) { - // TODO: Send a notification + r.SendContentNotification(user, "Card Authorization Failed", "Please open your Satimoto application and try again") + return nil, errors.New("Please open your Satimoto application and try again") } } @@ -86,7 +89,7 @@ func (r *TokenAuthorizationResolver) CreateTokenAuthorization(ctx context.Contex } asyncChan := r.AsyncService.Add(createTokenAuthorizationParams.AuthorizationID) - r.SendNotification(user, createTokenAuthorizationParams.AuthorizationID) + r.SendDataNotification(user, createTokenAuthorizationParams.AuthorizationID) timeout := util.GetEnvInt32("TOKEN_AUTHORIZATION_TIMEOUT", 5) select { From bf84c92e32cca3f8b4fd93196b1a001c6a7b7bb6 Mon Sep 17 00:00:00 2001 From: Ross Savage Date: Fri, 13 Jan 2023 16:29:11 +0100 Subject: [PATCH 4/6] Check if there are unsettled invoices before issuing token authorization --- internal/tokenauthorization/v2.1.1/process.go | 47 +++++++++++-------- 1 file changed, 27 insertions(+), 20 deletions(-) diff --git a/internal/tokenauthorization/v2.1.1/process.go b/internal/tokenauthorization/v2.1.1/process.go index de96825a..3216d6db 100644 --- a/internal/tokenauthorization/v2.1.1/process.go +++ b/internal/tokenauthorization/v2.1.1/process.go @@ -14,16 +14,33 @@ import ( ) func (r *TokenAuthorizationResolver) CreateTokenAuthorization(ctx context.Context, credential db.Credential, token db.Token, locationReferencesDto *dto.LocationReferencesDto) (*db.TokenAuthorization, error) { - if token.Type == db.TokenTypeRFID { - // Check if user is restricted, has a node and has been active - user, err := r.UserRepository.GetUserByTokenID(ctx, token.ID) + user, err := r.UserRepository.GetUser(ctx, token.UserID) - if err != nil { - metrics.RecordError("OCPI288", "Error retrieving user", err) - log.Printf("OCPI288: UserID=%v", token.UserID) - return nil, nil - } + if err != nil { + metrics.RecordError("OCPI288", "Error retrieving user", err) + log.Printf("OCPI288: UserID=%v", token.UserID) + return nil, errors.New("Authorization error") + } + + if !user.DeviceToken.Valid { + return nil, errors.New("Please enable notifications in your Satimoto application") + } + + listSessionInvoicesParams := db.ListSessionInvoicesByUserIDParams{ + ID: user.ID, + IsSettled: false, + IsExpired: false, + } + + // Check if there are unsettled invoices from a previous session + if sessionInvoices, err := r.SessionRepository.ListSessionInvoicesByUserID(ctx, listSessionInvoicesParams); err == nil && len(sessionInvoices) > 0 { + r.SendContentNotification(user, "Authorization Failed", "Please fund your Satimoto application and try again") + return nil, errors.New("Please fund your Satimoto application and try again") + } + + if token.Type == db.TokenTypeRFID { + // Check if user is restricted, has a node and has been active if user.IsRestricted || !user.NodeID.Valid || !user.LastActiveDate.Valid { r.SendContentNotification(user, "Card Authorization Failed", "Please fund your Satimoto application and try again") @@ -76,18 +93,6 @@ func (r *TokenAuthorizationResolver) CreateTokenAuthorization(ctx context.Contex // device, which then responds if it is authorized or not. // If there is a timeout in waiting for the response, the token // authorize request is rejected. - user, err := r.UserRepository.GetUser(ctx, token.UserID) - - if err != nil { - metrics.RecordError("OCPI285", "Error retrieving user", err) - log.Printf("OCPI285: UserID=%v", token.UserID) - return nil, nil - } - - if !user.DeviceToken.Valid { - return nil, errors.New("Please enable notifications in your Satimoto application") - } - asyncChan := r.AsyncService.Add(createTokenAuthorizationParams.AuthorizationID) r.SendDataNotification(user, createTokenAuthorizationParams.AuthorizationID) timeout := util.GetEnvInt32("TOKEN_AUTHORIZATION_TIMEOUT", 5) @@ -104,6 +109,8 @@ func (r *TokenAuthorizationResolver) CreateTokenAuthorization(ctx context.Contex log.Printf("Token authorization timeout: %v", createTokenAuthorizationParams.AuthorizationID) r.AsyncService.Remove(createTokenAuthorizationParams.AuthorizationID) + r.SendContentNotification(user, "Card Authorization Failed", "Please open your Satimoto application and try again") + return nil, errors.New("Authorization timeout") } From f0531d5ba15798b41839832b3701018534966882 Mon Sep 17 00:00:00 2001 From: Ross Savage Date: Fri, 20 Jan 2023 20:54:40 +0100 Subject: [PATCH 5/6] Move sync request to separate func to allow correct response body closing --- internal/cdr/v2.1.1/sync.go | 66 ++++++++++++++++++------------- internal/location/v2.1.1/sync.go | 67 +++++++++++++++++++------------- internal/session/v2.1.1/sync.go | 67 +++++++++++++++++++------------- internal/tariff/v2.1.1/sync.go | 67 +++++++++++++++++++------------- 4 files changed, 156 insertions(+), 111 deletions(-) diff --git a/internal/cdr/v2.1.1/sync.go b/internal/cdr/v2.1.1/sync.go index 9965cc60..382681af 100644 --- a/internal/cdr/v2.1.1/sync.go +++ b/internal/cdr/v2.1.1/sync.go @@ -11,6 +11,7 @@ import ( "github.com/satimoto/go-datastore/pkg/db" "github.com/satimoto/go-datastore/pkg/util" coreCdr "github.com/satimoto/go-ocpi/internal/cdr" + dto "github.com/satimoto/go-ocpi/internal/dto/v2.1.1" metrics "github.com/satimoto/go-ocpi/internal/metric" "github.com/satimoto/go-ocpi/internal/transportation" ) @@ -59,42 +60,21 @@ func (r *CdrResolver) SyncByIdentifier(ctx context.Context, credential db.Creden } for { + if retries >= 5 { + break + } + query.Set("limit", fmt.Sprintf("%d", limit)) query.Set("offset", fmt.Sprintf("%d", offset)) requestUrl.RawQuery = query.Encode() - response, err := r.OcpiService.Do(http.MethodGet, requestUrl.String(), header, nil) + dto, limit := r.sendRequest(requestUrl.String(), header, limit) - if err != nil { - metrics.RecordError("OCPI030", "Error making request", err) - log.Printf("OCPI030: Method=%v, Url=%v, Header=%#v", http.MethodGet, requestUrl.String(), header) + if dto == nil { retries++ - - if retries >= 5 { - break - } - continue } - dto, err := r.UnmarshalPullDto(response.Body) - defer response.Body.Close() - - if err != nil { - metrics.RecordError("OCPI031", "Error unmarshaling response", err) - util.LogHttpResponse("OCPI031", requestUrl.String(), response, true) - break - } - - limit = transportation.GetXLimitHeader(response, limit) - - if dto.StatusCode != transportation.STATUS_CODE_OK { - metrics.RecordError("OCPI032", "Error response failure", err) - util.LogHttpRequest("OCPI032", requestUrl.String(), response.Request, true) - util.LogHttpResponse("OCPI032", requestUrl.String(), response, true) - break - } - retries = 0 if dto.StatusCode == transportation.STATUS_CODE_OK { @@ -110,3 +90,35 @@ func (r *CdrResolver) SyncByIdentifier(ctx context.Context, credential db.Creden } } } + +func (r *CdrResolver) sendRequest(url string, header transportation.OcpiRequestHeader, limit int) (*dto.OcpiCdrsDto, int) { + response, err := r.OcpiService.Do(http.MethodGet, url, header, nil) + + if err != nil { + metrics.RecordError("OCPI030", "Error making request", err) + log.Printf("OCPI030: Method=%v, Url=%v, Header=%#v", http.MethodGet, url, header) + + return nil, limit + } + + dto, err := r.UnmarshalPullDto(response.Body) + defer response.Body.Close() + + if err != nil { + metrics.RecordError("OCPI031", "Error unmarshaling response", err) + util.LogHttpResponse("OCPI031", url, response, true) + + return nil, limit + } + + if dto.StatusCode != transportation.STATUS_CODE_OK { + metrics.RecordError("OCPI032", "Error response failure", err) + util.LogHttpRequest("OCPI032", url, response.Request, true) + util.LogHttpResponse("OCPI032", url, response, true) + log.Printf("OCPI032: StatusCode=%v, StatusMessage=%v", dto.StatusCode, dto.StatusMessage) + + return nil, limit + } + + return dto, transportation.GetXLimitHeader(response, limit) +} diff --git a/internal/location/v2.1.1/sync.go b/internal/location/v2.1.1/sync.go index 869eb05b..4c074d23 100644 --- a/internal/location/v2.1.1/sync.go +++ b/internal/location/v2.1.1/sync.go @@ -10,6 +10,7 @@ import ( "github.com/satimoto/go-datastore/pkg/db" "github.com/satimoto/go-datastore/pkg/util" + dto "github.com/satimoto/go-ocpi/internal/dto/v2.1.1" coreLocation "github.com/satimoto/go-ocpi/internal/location" metrics "github.com/satimoto/go-ocpi/internal/metric" "github.com/satimoto/go-ocpi/internal/transportation" @@ -64,43 +65,21 @@ func (r *LocationResolver) SyncByIdentifier(ctx context.Context, credential db.C } for { + if retries >= 5 { + break + } + query.Set("limit", fmt.Sprintf("%d", limit)) query.Set("offset", fmt.Sprintf("%d", offset)) requestUrl.RawQuery = query.Encode() - response, err := r.OcpiService.Do(http.MethodGet, requestUrl.String(), header, nil) + dto, limit := r.sendRequest(requestUrl.String(), header, limit) - if err != nil { - metrics.RecordError("OCPI127", "Error making request", err) - log.Printf("OCPI127: Method=%v, Url=%v, Header=%#v", http.MethodGet, requestUrl.String(), header) + if dto == nil { retries++ - - if retries >= 5 { - break - } - continue } - dto, err := r.UnmarshalPullDto(response.Body) - defer response.Body.Close() - - if err != nil { - metrics.RecordError("OCPI128", "Error unmarshaling response", err) - util.LogHttpResponse("OCPI128", requestUrl.String(), response, true) - break - } - - limit = transportation.GetXLimitHeader(response, limit) - - if dto.StatusCode != transportation.STATUS_CODE_OK { - metrics.RecordError("OCPI129", "Error response failure", err) - util.LogHttpRequest("OCPI129", versionEndpoint.Url, response.Request, true) - util.LogHttpResponse("OCPI129", requestUrl.String(), response, true) - log.Printf("OCPI129: StatusCode=%v, StatusMessage=%v", dto.StatusCode, dto.StatusMessage) - break - } - retries = 0 if dto.StatusCode == transportation.STATUS_CODE_OK { @@ -116,3 +95,35 @@ func (r *LocationResolver) SyncByIdentifier(ctx context.Context, credential db.C } } } + +func (r *LocationResolver) sendRequest(url string, header transportation.OcpiRequestHeader, limit int) (*dto.OcpiLocationsDto, int) { + response, err := r.OcpiService.Do(http.MethodGet, url, header, nil) + + if err != nil { + metrics.RecordError("OCPI127", "Error making request", err) + log.Printf("OCPI127: Method=%v, Url=%v, Header=%#v", http.MethodGet, url, header) + + return nil, limit + } + + dto, err := r.UnmarshalPullDto(response.Body) + defer response.Body.Close() + + if err != nil { + metrics.RecordError("OCPI128", "Error unmarshaling response", err) + util.LogHttpResponse("OCPI128", url, response, true) + + return nil, limit + } + + if dto.StatusCode != transportation.STATUS_CODE_OK { + metrics.RecordError("OCPI129", "Error response failure", err) + util.LogHttpRequest("OCPI129", url, response.Request, true) + util.LogHttpResponse("OCPI129", url, response, true) + log.Printf("OCPI129: StatusCode=%v, StatusMessage=%v", dto.StatusCode, dto.StatusMessage) + + return nil, limit + } + + return dto, transportation.GetXLimitHeader(response, limit) +} diff --git a/internal/session/v2.1.1/sync.go b/internal/session/v2.1.1/sync.go index d2157777..2d6f223e 100644 --- a/internal/session/v2.1.1/sync.go +++ b/internal/session/v2.1.1/sync.go @@ -10,6 +10,7 @@ import ( "github.com/satimoto/go-datastore/pkg/db" "github.com/satimoto/go-datastore/pkg/util" + dto "github.com/satimoto/go-ocpi/internal/dto/v2.1.1" metrics "github.com/satimoto/go-ocpi/internal/metric" coreSession "github.com/satimoto/go-ocpi/internal/session" "github.com/satimoto/go-ocpi/internal/transportation" @@ -59,43 +60,21 @@ func (r *SessionResolver) SyncByIdentifier(ctx context.Context, credential db.Cr } for { + if retries >= 5 { + break + } + query.Set("limit", fmt.Sprintf("%d", limit)) query.Set("offset", fmt.Sprintf("%d", offset)) requestUrl.RawQuery = query.Encode() - response, err := r.OcpiService.Do(http.MethodGet, requestUrl.String(), header, nil) + dto, limit := r.sendRequest(requestUrl.String(), header, limit) - if err != nil { - metrics.RecordError("OCPI172", "Error making request", err) - log.Printf("OCPI172: Method=%v, Url=%v, Header=%#v", http.MethodGet, requestUrl.String(), header) + if dto == nil { retries++ - - if retries >= 5 { - break - } - continue } - dto, err := r.UnmarshalPullDto(response.Body) - defer response.Body.Close() - - if err != nil { - metrics.RecordError("OCPI173", "Error unmarshaling response", err) - util.LogHttpResponse("OCPI173", requestUrl.String(), response, true) - break - } - - limit = transportation.GetXLimitHeader(response, limit) - - if dto.StatusCode != transportation.STATUS_CODE_OK { - metrics.RecordError("OCPI174", "Error response failure", err) - util.LogHttpRequest("OCPI174", requestUrl.String(), response.Request, true) - util.LogHttpResponse("OCPI174", requestUrl.String(), response, true) - log.Printf("OCPI174: StatusCode=%v, StatusMessage=%v", dto.StatusCode, dto.StatusMessage) - break - } - retries = 0 if dto.StatusCode == transportation.STATUS_CODE_OK { @@ -111,3 +90,35 @@ func (r *SessionResolver) SyncByIdentifier(ctx context.Context, credential db.Cr } } } + +func (r *SessionResolver) sendRequest(url string, header transportation.OcpiRequestHeader, limit int) (*dto.OcpiSessionsDto, int) { + response, err := r.OcpiService.Do(http.MethodGet, url, header, nil) + + if err != nil { + metrics.RecordError("OCPI172", "Error making request", err) + log.Printf("OCPI172: Method=%v, Url=%v, Header=%#v", http.MethodGet, url, header) + + return nil, limit + } + + dto, err := r.UnmarshalPullDto(response.Body) + defer response.Body.Close() + + if err != nil { + metrics.RecordError("OCPI173", "Error unmarshaling response", err) + util.LogHttpResponse("OCPI173", url, response, true) + + return nil, limit + } + + if dto.StatusCode != transportation.STATUS_CODE_OK { + metrics.RecordError("OCPI174", "Error response failure", err) + util.LogHttpRequest("OCPI174", url, response.Request, true) + util.LogHttpResponse("OCPI174", url, response, true) + log.Printf("OCPI174: StatusCode=%v, StatusMessage=%v", dto.StatusCode, dto.StatusMessage) + + return nil, limit + } + + return dto, transportation.GetXLimitHeader(response, limit) +} diff --git a/internal/tariff/v2.1.1/sync.go b/internal/tariff/v2.1.1/sync.go index 378c56f4..659b469e 100644 --- a/internal/tariff/v2.1.1/sync.go +++ b/internal/tariff/v2.1.1/sync.go @@ -10,6 +10,7 @@ import ( "github.com/satimoto/go-datastore/pkg/db" "github.com/satimoto/go-datastore/pkg/util" + dto "github.com/satimoto/go-ocpi/internal/dto/v2.1.1" metrics "github.com/satimoto/go-ocpi/internal/metric" coreTariff "github.com/satimoto/go-ocpi/internal/tariff" "github.com/satimoto/go-ocpi/internal/transportation" @@ -48,43 +49,21 @@ func (r *TariffResolver) SyncByIdentifier(ctx context.Context, credential db.Cre } for { + if retries >= 5 { + break + } + query.Set("limit", fmt.Sprintf("%d", limit)) query.Set("offset", fmt.Sprintf("%d", offset)) requestUrl.RawQuery = query.Encode() - response, err := r.OcpiService.Do(http.MethodGet, requestUrl.String(), header, nil) + dto, limit := r.sendRequest(requestUrl.String(), header, limit) - if err != nil { - metrics.RecordError("OCPI184", "Error making request", err) - log.Printf("OCPI184: Method=%v, Url=%v, Header=%#v", http.MethodGet, requestUrl.String(), header) + if dto == nil { retries++ - - if retries >= 5 { - break - } - continue } - dto, err := r.UnmarshalPullDto(response.Body) - response.Body.Close() - - if err != nil { - metrics.RecordError("OCPI185", "Error unmarshaling response", err) - util.LogHttpResponse("OCPI185", requestUrl.String(), response, true) - break - } - - limit = transportation.GetXLimitHeader(response, limit) - - if dto.StatusCode != transportation.STATUS_CODE_OK { - metrics.RecordError("OCPI186", "Error response failure", err) - util.LogHttpRequest("OCPI186", requestUrl.String(), response.Request, true) - util.LogHttpResponse("OCPI186", requestUrl.String(), response, true) - log.Printf("OCPI186: StatusCode=%v, StatusMessage=%v", dto.StatusCode, dto.StatusMessage) - break - } - retries = 0 if dto.StatusCode == transportation.STATUS_CODE_OK { @@ -100,3 +79,35 @@ func (r *TariffResolver) SyncByIdentifier(ctx context.Context, credential db.Cre } } } + +func (r *TariffResolver) sendRequest(url string, header transportation.OcpiRequestHeader, limit int) (*dto.OcpiTariffsDto, int) { + response, err := r.OcpiService.Do(http.MethodGet, url, header, nil) + + if err != nil { + metrics.RecordError("OCPI184", "Error making request", err) + log.Printf("OCPI184: Method=%v, Url=%v, Header=%#v", http.MethodGet, url, header) + + return nil, limit + } + + dto, err := r.UnmarshalPullDto(response.Body) + defer response.Body.Close() + + if err != nil { + metrics.RecordError("OCPI185", "Error unmarshaling response", err) + util.LogHttpResponse("OCPI185", url, response, true) + + return nil, limit + } + + if dto.StatusCode != transportation.STATUS_CODE_OK { + metrics.RecordError("OCPI186", "Error response failure", err) + util.LogHttpRequest("OCPI186", url, response.Request, true) + util.LogHttpResponse("OCPI186", url, response, true) + log.Printf("OCPI186: StatusCode=%v, StatusMessage=%v", dto.StatusCode, dto.StatusMessage) + + return nil, limit + } + + return dto, transportation.GetXLimitHeader(response, limit) +} From 74fbd48fd1da746d8059b8ddad6fa3062242040a Mon Sep 17 00:00:00 2001 From: Ross Savage Date: Sun, 22 Jan 2023 20:24:05 +0100 Subject: [PATCH 6/6] Add logging to async service --- internal/async/service.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/internal/async/service.go b/internal/async/service.go index 0fe3704c..c1a1c3f5 100644 --- a/internal/async/service.go +++ b/internal/async/service.go @@ -1,5 +1,7 @@ package async +import "log" + type AsyncResult struct { String string Bool bool @@ -16,11 +18,13 @@ func NewService() *AsyncService { } func (r *AsyncService) Add(key string) <-chan AsyncResult { + log.Printf("Async: Add key=%v", key) r.channels[key] = make(chan AsyncResult) return r.channels[key] } func (r *AsyncService) Remove(key string) { + log.Printf("Async: Remove key=%v", key) if _, ok := r.channels[key]; ok { close(r.channels[key]) delete(r.channels, key) @@ -29,9 +33,11 @@ func (r *AsyncService) Remove(key string) { func (r *AsyncService) Set(key string, result AsyncResult) bool { if _, ok := r.channels[key]; ok { + log.Printf("Async: Set key=%v", key) r.channels[key] <-result return true } + log.Printf("Async: Invalid key=%v", key) return false } \ No newline at end of file