From b72fa0f11dfdf0106f2f62c46cf708f002a55dbb Mon Sep 17 00:00:00 2001 From: Semyon Novikov Date: Mon, 15 Jul 2024 17:48:24 +0300 Subject: [PATCH] replace interface{} to any, fix tests --- config/blockchain_network_config.go | 12 +++--- config/blockchain_network_config_test.go | 4 +- config/config.go | 3 +- config/config_test.go | 4 +- config/configuration_schema.go | 2 +- config/version_test.go | 14 +++--- escrow/free_call_storage.go | 2 +- escrow/payment_channel_storage.go | 6 +-- escrow/prepaid_service.go | 14 +++--- escrow/prepaid_storage.go | 10 ++--- etcddb/etcddb_client.go | 2 +- etcddb/etcddb_conf.go | 4 ++ handler/grpc.go | 36 ++++++++-------- handler/interceptors.go | 12 +++--- handler/interceptors_test.go | 10 ++--- license_server/license_service.go | 2 +- license_server/license_storage.go | 12 +++--- logger/logger_test.go | 12 +++--- metrics/utils.go | 4 +- storage/atomic_storage.go | 54 ++++++++++++------------ token/jwttoken.go | 2 +- token/token_service_api.go | 4 +- training/storage.go | 4 +- utils/common.go | 4 +- 24 files changed, 121 insertions(+), 112 deletions(-) diff --git a/config/blockchain_network_config.go b/config/blockchain_network_config.go index 34aba753..cd2f37d7 100644 --- a/config/blockchain_network_config.go +++ b/config/blockchain_network_config.go @@ -29,7 +29,7 @@ var networkSelected = &NetworkSelected{} var networkIdNameMapping string func determineNetworkSelected(data []byte) (err error) { - dynamicBinding := map[string]interface{}{} + dynamicBinding := map[string]any{} networkName := GetString(BlockChainNetworkSelected) if err = json.Unmarshal(data, &dynamicBinding); err != nil { return err @@ -37,16 +37,16 @@ func determineNetworkSelected(data []byte) (err error) { //Get the Network Name selected in config ( snetd.config.json) , Based on this retrieve the Registry address , //Ethereum End point and Network ID mapped to networkSelected.NetworkName = networkName - networkSelected.RegistryAddressKey = getDetailsFromJsonOrConfig(dynamicBinding[networkName].(map[string]interface{})[RegistryAddressKey], RegistryAddressKey) - networkSelected.EthereumJSONRPCEndpoint = getDetailsFromJsonOrConfig(dynamicBinding[networkName].(map[string]interface{})[EthereumJsonRpcEndpointKey], EthereumJsonRpcEndpointKey) - networkSelected.NetworkId = fmt.Sprintf("%v", dynamicBinding[networkName].(map[string]interface{})[NetworkId]) + networkSelected.RegistryAddressKey = getDetailsFromJsonOrConfig(dynamicBinding[networkName].(map[string]any)[RegistryAddressKey], RegistryAddressKey) + networkSelected.EthereumJSONRPCEndpoint = getDetailsFromJsonOrConfig(dynamicBinding[networkName].(map[string]any)[EthereumJsonRpcEndpointKey], EthereumJsonRpcEndpointKey) + networkSelected.NetworkId = fmt.Sprintf("%v", dynamicBinding[networkName].(map[string]any)[NetworkId]) return err } // Check if the value set in the config file, if yes, then we use it as is // else we derive the value from the JSON parsed -func getDetailsFromJsonOrConfig(details interface{}, configName string) string { +func getDetailsFromJsonOrConfig(details any, configName string) string { if len(GetString(configName)) > 0 { return GetString(configName) } @@ -107,7 +107,7 @@ func deriveDatafromJSON(data []byte) (err error) { return errors.New("cannot find registry address from JSON for the selected network") } - networkSelected.RegistryAddressKey = fmt.Sprintf("%v", m[GetNetworkId()].(map[string]interface{})["address"]) + networkSelected.RegistryAddressKey = fmt.Sprintf("%v", m[GetNetworkId()].(map[string]any)["address"]) zap.L().Info("Derive data from JSON", zap.String("Network", GetString(BlockChainNetworkSelected)), zap.String("NetwrokId", GetNetworkId()), diff --git a/config/blockchain_network_config_test.go b/config/blockchain_network_config_test.go index 802e9379..9f6771c0 100644 --- a/config/blockchain_network_config_test.go +++ b/config/blockchain_network_config_test.go @@ -83,7 +83,7 @@ func Test_SetBlockChainNetworkDetails(t *testing.T) { func Test_GetDetailsFromJsonOrConfig(t *testing.T) { - dynamicBinding := map[string]interface{}{} + dynamicBinding := map[string]any{} data := []byte(defaultBlockChainNetworkConfig) json.Unmarshal(data, &dynamicBinding) @@ -97,7 +97,7 @@ func Test_GetDetailsFromJsonOrConfig(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - if got := getDetailsFromJsonOrConfig(dynamicBinding[tt.network].(map[string]interface{})[tt.name], tt.name); got != tt.want { + if got := getDetailsFromJsonOrConfig(dynamicBinding[tt.network].(map[string]any)[tt.name], tt.name); got != tt.want { t.Errorf("getDetailsFromJsonOrConfig() = %v, want %v", got, tt.want) } }) diff --git a/config/config.go b/config/config.go index 65c53b6d..c88942dc 100644 --- a/config/config.go +++ b/config/config.go @@ -221,9 +221,10 @@ func Validate() error { // Check if the Daemon is on the latest version or not if message, err := CheckVersionOfDaemon(); err != nil { - //In case of any error on version check, just log it + // In case of any error on version check, just log it zap.L().Warn(err.Error()) } else { + // Print current version of daemon zap.L().Info(message) } diff --git a/config/config_test.go b/config/config_test.go index e17ac995..8fb9eb89 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -78,9 +78,9 @@ const jsonConfigString = ` }` func assertConfigIsEqualToJsonConfigString(t *testing.T, config *viper.Viper) { - assert.Equal(t, map[string]interface{}{"field": "value"}, config.Get("object")) + assert.Equal(t, map[string]any{"field": "value"}, config.Get("object")) assert.Equal(t, "value", config.Get("object.field")) - assert.Equal(t, []interface{}{"item-1", "item-2"}, config.Get("array")) + assert.Equal(t, []any{"item-1", "item-2"}, config.Get("array")) assert.Equal(t, "string-value", config.Get("string-key")) assert.Equal(t, 42, config.GetInt("int-key")) } diff --git a/config/configuration_schema.go b/config/configuration_schema.go index cbac244a..505dcf1c 100644 --- a/config/configuration_schema.go +++ b/config/configuration_schema.go @@ -93,7 +93,7 @@ func GetConfigurationSchema() ([]ConfigurationDetails, error) { } // ConvertStructToJSON converts the passed datastructure to a JSON -func ConvertStructToJSON(payLoad interface{}) ([]byte, error) { +func ConvertStructToJSON(payLoad any) ([]byte, error) { b, err := json.Marshal(&payLoad) if err != nil { return nil, err diff --git a/config/version_test.go b/config/version_test.go index 5724a5e9..19088051 100644 --- a/config/version_test.go +++ b/config/version_test.go @@ -54,9 +54,13 @@ func Test_getBuildTime(t *testing.T) { } func TestCheckVersionOfDaemon(t *testing.T) { - versionTag = "v0.1.9" - message ,err := CheckVersionOfDaemon() - assert.Nil(t, err) - assert.Contains(t,message,"There is a newer version of the Daemon") + versionTag = "v5.1.2" + message, err := CheckVersionOfDaemon() + assert.NotNil(t, err) + assert.Contains(t, err.Error(), "There is a newer version of the Daemon") -} \ No newline at end of file + versionTag, _ = GetLatestDaemonVersion() + message, err = CheckVersionOfDaemon() + assert.Nil(t, err) + assert.Contains(t, message, "Daemon version is "+versionTag) +} diff --git a/escrow/free_call_storage.go b/escrow/free_call_storage.go index 1bc56207..3afe9181 100644 --- a/escrow/free_call_storage.go +++ b/escrow/free_call_storage.go @@ -31,7 +31,7 @@ func NewFreeCallUserStorage(atomicStorage storage.AtomicStorage) *FreeCallUserSt }*/ } -func serializeFreeCallKey(key interface{}) (serialized string, err error) { +func serializeFreeCallKey(key any) (serialized string, err error) { myKey := key.(*FreeCallUserKey) return myKey.String(), nil } diff --git a/escrow/payment_channel_storage.go b/escrow/payment_channel_storage.go index 5cc913da..e402e9e2 100644 --- a/escrow/payment_channel_storage.go +++ b/escrow/payment_channel_storage.go @@ -33,10 +33,10 @@ func NewPaymentChannelStorage(atomicStorage storage.AtomicStorage) *PaymentChann } -func serializeKey(key interface{}) (slice string, err error) { +func serializeKey(key any) (slice string, err error) { return fmt.Sprintf("%v", key), nil } -func serialize(value interface{}) (slice string, err error) { +func serialize(value any) (slice string, err error) { var b bytes.Buffer e := gob.NewEncoder(&b) err = e.Encode(value) @@ -48,7 +48,7 @@ func serialize(value interface{}) (slice string, err error) { return } -func deserialize(slice string, value interface{}) (err error) { +func deserialize(slice string, value any) (err error) { b := bytes.NewBuffer([]byte(slice)) d := gob.NewDecoder(b) err = d.Decode(value) diff --git a/escrow/prepaid_service.go b/escrow/prepaid_service.go index 67c745fa..45722e3e 100644 --- a/escrow/prepaid_service.go +++ b/escrow/prepaid_service.go @@ -33,9 +33,9 @@ func (h *lockingPrepaidService) GetUsage(key PrePaidDataKey) (data *PrePaidData, } -//Defines the condition that needs to be met, it generates the respective typed Data when -//conditions are satisfied, you define your own validations in here -//It takes in the latest typed values read. +// Defines the condition that needs to be met, it generates the respective typed Data when +// conditions are satisfied, you define your own validations in here +// It takes in the latest typed values read. type ConditionFunc func(conditionValues []storage.TypedKeyValueData, revisedAmount *big.Int, channelId *big.Int) ([]storage.TypedKeyValueData, error) func (h *lockingPrepaidService) UpdateUsage(channelId *big.Int, revisedAmount *big.Int, updateUsageType string) (err error) { @@ -78,16 +78,16 @@ func (h *lockingPrepaidService) UpdateUsage(channelId *big.Int, revisedAmount *b } return nil } -func getAllKeys(channelId *big.Int) []interface{} { - keys := make([]interface{}, 3) +func getAllKeys(channelId *big.Int) []any { + keys := make([]any, 3) for i, usageType := range []string{REFUND_AMOUNT, PLANNED_AMOUNT, USED_AMOUNT} { keys[i] = PrePaidDataKey{ChannelID: channelId, UsageType: usageType} } return keys } -//this function will be used to read typed data ,convert it in to a business structure -//on which validations can be easily performed and return back the business structure. +// this function will be used to read typed data ,convert it in to a business structure +// on which validations can be easily performed and return back the business structure. func convertTypedDataToPrePaidUsage(data []storage.TypedKeyValueData) (new *PrePaidUsageData, err error) { usageData := &PrePaidUsageData{PlannedAmount: big.NewInt(0), UsedAmount: big.NewInt(0), RefundAmount: big.NewInt(0)} diff --git a/escrow/prepaid_storage.go b/escrow/prepaid_storage.go index f6a8609b..1fa530ba 100644 --- a/escrow/prepaid_storage.go +++ b/escrow/prepaid_storage.go @@ -15,13 +15,13 @@ type PrePaidPayment struct { AuthToken string } -//Used when the Request comes in +// Used when the Request comes in func (payment *PrePaidPayment) String() string { return fmt.Sprintf("{ID:%v/%v/%v}", payment.ChannelID, payment.OrganizationId, payment.GroupId) } -//Kept the bare minimum here , other details like group and sender address of this channel can -//always be retrieved from BlockChain +// Kept the bare minimum here , other details like group and sender address of this channel can +// always be retrieved from BlockChain type PrePaidData struct { Amount *big.Int } @@ -44,7 +44,7 @@ const ( REFUND_AMOUNT string = "R" ) -//This will ony be used for doing any business checks +// This will ony be used for doing any business checks type PrePaidUsageData struct { ChannelID *big.Int PlannedAmount *big.Int @@ -80,7 +80,7 @@ func (data PrePaidUsageData) Clone() *PrePaidUsageData { } } -func serializePrePaidKey(key interface{}) (serialized string, err error) { +func serializePrePaidKey(key any) (serialized string, err error) { myKey := key.(PrePaidDataKey) return myKey.String(), nil } diff --git a/etcddb/etcddb_client.go b/etcddb/etcddb_client.go index 709b07b7..529f9ea4 100644 --- a/etcddb/etcddb_client.go +++ b/etcddb/etcddb_client.go @@ -407,7 +407,7 @@ func (client *EtcdClient) checkTxnResponse(keys []string, txnResp *clientv3.TxnR } latestStateArray = append(latestStateArray, latestValues...) } - keySet.Do(func(elem interface{}) { + keySet.Do(func(elem any) { latestStateArray = append(latestStateArray, keyValueVersion{ Key: elem.(string), Present: false, diff --git a/etcddb/etcddb_conf.go b/etcddb/etcddb_conf.go index 92600271..1414385a 100644 --- a/etcddb/etcddb_conf.go +++ b/etcddb/etcddb_conf.go @@ -31,6 +31,10 @@ func GetEtcdClientConf(vip *viper.Viper, metaData *blockchain.OrganizationMetaDa Endpoints: metaData.GetPaymentStorageEndPoints(), } + if vip == nil { + return + } + confFromVip := &EtcdClientConf{} subVip := config.SubWithDefault(vip, config.PaymentChannelStorageClientKey) err = subVip.Unmarshal(confFromVip) diff --git a/handler/grpc.go b/handler/grpc.go index acc77ae2..b36591d9 100644 --- a/handler/grpc.go +++ b/handler/grpc.go @@ -115,7 +115,7 @@ Modified from https://github.com/mwitkow/grpc-proxy/blob/67591eb23c48346a480470e Original Copyright 2017 Michal Witkowski. All Rights Reserved. See LICENSE-GRPC-PROXY for licensing terms. Modifications Copyright 2018 SingularityNET Foundation. All Rights Reserved. See LICENSE for licensing terms. */ -func (g grpcHandler) grpcToGRPC(srv interface{}, inStream grpc.ServerStream) error { +func (g grpcHandler) grpcToGRPC(srv any, inStream grpc.ServerStream) error { method, ok := grpc.MethodFromServerStream(inStream) if !ok { @@ -266,7 +266,7 @@ func (g grpcHandler) grpcToHTTP(srv any, inStream grpc.ServerStream) error { methodSegs := strings.Split(method, "/") method = methodSegs[len(methodSegs)-1] - zap.L().Debug("Calling method", zap.String("method", method)) + zap.L().Info("Calling method", zap.String("method", method)) f := &codec.GrpcFrame{} if err := inStream.RecvMsg(f); err != nil { @@ -340,7 +340,7 @@ func (g grpcHandler) grpcToHTTP(srv any, inStream grpc.ServerStream) error { if err != nil { return status.Errorf(codes.Internal, "error reading response; error: %+cred", err) } - zap.L().Info("Getting response", zap.String("response", string(resp))) + zap.L().Debug("Getting response", zap.String("response", string(resp))) protoMessage := jsonToProto(g.serviceMetaData.ProtoFile, resp, method) if err = inStream.SendMsg(protoMessage); err != nil { @@ -356,19 +356,19 @@ func jsonToProto(protoFile protoreflect.FileDescriptor, json []byte, methodName zap.L().Debug("Count services: ", zap.Int("value", protoFile.Services().Len())) if protoFile.Services().Len() == 0 { - zap.L().Info("service in proto not found") + zap.L().Warn("service in proto not found") return proto } service := protoFile.Services().Get(0) if service == nil { - zap.L().Info("service in proto not found") + zap.L().Warn("service in proto not found") return proto } method := service.Methods().ByName(protoreflect.Name(methodName)) if method == nil { - zap.L().Info("method not found") + zap.L().Warn("method not found in proto") return proto } output := method.Output() @@ -385,19 +385,19 @@ func jsonToProto(protoFile protoreflect.FileDescriptor, json []byte, methodName func protoToJson(protoFile protoreflect.FileDescriptor, in []byte, methodName string) (json []byte) { if protoFile.Services().Len() == 0 { - zap.L().Info("service in proto not found") + zap.L().Warn("service in proto not found") return []byte("error, invalid proto file") } service := protoFile.Services().Get(0) if service == nil { - zap.L().Info("service in proto not found") + zap.L().Warn("service in proto not found") return []byte("error, invalid proto file") } method := service.Methods().ByName(protoreflect.Name(methodName)) if method == nil { - zap.L().Info("method not found") + zap.L().Warn("method not found in proto") return []byte("error, invalid proto file or input request") } @@ -406,12 +406,12 @@ func protoToJson(protoFile protoreflect.FileDescriptor, in []byte, methodName st msg := dynamicpb.NewMessage(input) err := proto.Unmarshal(in, msg) if err != nil { - zap.L().Error("Errog in unmarshaling", zap.Error(err)) + zap.L().Error("Error in unmarshalling", zap.Error(err)) return []byte("error, invalid proto file or input request") } json, err = protojson.MarshalOptions{UseProtoNames: true}.Marshal(msg) if err != nil { - zap.L().Error("Errog in marshaling", zap.Error(err)) + zap.L().Error("Error in marshaling", zap.Error(err)) return []byte("error, invalid proto file or input request") } zap.L().Debug("Getting json", zap.String("json", string(json))) @@ -419,7 +419,7 @@ func protoToJson(protoFile protoreflect.FileDescriptor, in []byte, methodName st return json } -func (g grpcHandler) grpcToJSONRPC(srv interface{}, inStream grpc.ServerStream) error { +func (g grpcHandler) grpcToJSONRPC(srv any, inStream grpc.ServerStream) error { method, ok := grpc.MethodFromServerStream(inStream) if !ok { @@ -438,7 +438,7 @@ func (g grpcHandler) grpcToJSONRPC(srv interface{}, inStream grpc.ServerStream) return status.Errorf(codes.Internal, "error receiving request; error: %+v", err) } - params := new(interface{}) + params := new(any) if err := json.Unmarshal(f.Data, params); err != nil { return status.Errorf(codes.Internal, "error unmarshaling request; error: %+v", err) @@ -525,19 +525,19 @@ func (f *WrapperServerStream) Context() context.Context { return f.stream.Context() } -func (f *WrapperServerStream) SendMsg(m interface{}) error { +func (f *WrapperServerStream) SendMsg(m any) error { return f.stream.SendMsg(m) } -func (f *WrapperServerStream) RecvMsg(m interface{}) error { +func (f *WrapperServerStream) RecvMsg(m any) error { return f.stream.RecvMsg(m) } -func (f *WrapperServerStream) OriginalRecvMsg() interface{} { +func (f *WrapperServerStream) OriginalRecvMsg() any { return f.recvMessage } -func (g grpcHandler) grpcToProcess(srv interface{}, inStream grpc.ServerStream) error { +func (g grpcHandler) grpcToProcess(srv any, inStream grpc.ServerStream) error { method, ok := grpc.MethodFromServerStream(inStream) if !ok { @@ -579,7 +579,7 @@ func (g grpcHandler) grpcToProcess(srv interface{}, inStream grpc.ServerStream) return nil } -func grpcLoopback(srv interface{}, inStream grpc.ServerStream) error { +func grpcLoopback(srv any, inStream grpc.ServerStream) error { f := &codec.GrpcFrame{} if err := inStream.RecvMsg(f); err != nil { return status.Errorf(codes.Internal, "error receiving request; error: %+v", err) diff --git a/handler/interceptors.go b/handler/interceptors.go index 5d22bc73..5633eaac 100644 --- a/handler/interceptors.go +++ b/handler/interceptors.go @@ -88,7 +88,7 @@ func (context *GrpcStreamContext) String() string { // Payment represents payment handler specific data which is validated // and used to complete payment. -type Payment interface{} +type Payment any // Custom gRPC codes to return to the client const ( @@ -128,7 +128,7 @@ func NewGrpcError(code codes.Code, message string) *GrpcError { // NewGrpcErrorf returns new error which contains gRPC status with provided // code and message formed from format string and args. -func NewGrpcErrorf(code codes.Code, format string, args ...interface{}) *GrpcError { +func NewGrpcErrorf(code codes.Code, format string, args ...any) *GrpcError { return &GrpcError{ Status: status.Newf(code, format, args...), } @@ -181,7 +181,7 @@ func GrpcMeteringInterceptor() grpc.StreamServerInterceptor { } // Monitor requests arrived and responses sent and publish these stats for Reporting -func interceptMetering(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { +func interceptMetering(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { var err error var start time.Time start = time.Now() @@ -206,7 +206,7 @@ func interceptMetering(srv interface{}, ss grpc.ServerStream, info *grpc.StreamS return nil } -func (interceptor *rateLimitInterceptor) intercept(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { +func (interceptor *rateLimitInterceptor) intercept(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { if interceptor.processRequest == configuration_service.STOP_PROCESING_ANY_REQUEST { return status.New(codes.Unavailable, "No requests are currently being processed, please try again later").Err() @@ -249,7 +249,7 @@ type paymentValidationInterceptor struct { paymentHandlers map[string]PaymentHandler } -func (interceptor *paymentValidationInterceptor) intercept(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (e error) { +func (interceptor *paymentValidationInterceptor) intercept(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (e error) { var err *GrpcError wrapperStream := ss // check we need to have dynamic pricing here @@ -397,7 +397,7 @@ func GetSingleValue(md metadata.MD, key string) (value string, err *GrpcError) { } // NoOpInterceptor is a gRPC interceptor which doesn't do payment checking. -func NoOpInterceptor(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, +func NoOpInterceptor(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { return handler(srv, ss) } diff --git a/handler/interceptors_test.go b/handler/interceptors_test.go index afe6f0d7..54ea93d5 100644 --- a/handler/interceptors_test.go +++ b/handler/interceptors_test.go @@ -34,11 +34,11 @@ func (m *serverStreamMock) SendHeader(metadata.MD) error { func (m *serverStreamMock) SetTrailer(metadata.MD) { } -func (m *serverStreamMock) SendMsg(interface{}) error { +func (m *serverStreamMock) SendMsg(any) error { return errors.New("not implemented in mock") } -func (m *serverStreamMock) RecvMsg(interface{}) error { +func (m *serverStreamMock) RecvMsg(any) error { return errors.New("not implemented in mock") } @@ -110,13 +110,13 @@ type InterceptorsSuite struct { } func (suite *InterceptorsSuite) SetupSuite() { - suite.successHandler = func(srv interface{}, stream grpc.ServerStream) error { + suite.successHandler = func(srv any, stream grpc.ServerStream) error { return nil } - suite.returnErrorHandler = func(srv interface{}, stream grpc.ServerStream) error { + suite.returnErrorHandler = func(srv any, stream grpc.ServerStream) error { return errors.New("some error") } - suite.panicHandler = func(srv interface{}, stream grpc.ServerStream) error { + suite.panicHandler = func(srv any, stream grpc.ServerStream) error { panic("some panic") } suite.defaultPaymentHandler = &paymentHandlerMock{typ: defaultPaymentHandlerType} diff --git a/license_server/license_service.go b/license_server/license_service.go index ff0fc370..2e156032 100644 --- a/license_server/license_service.go +++ b/license_server/license_service.go @@ -119,7 +119,7 @@ func (h *LockingLicenseService) UpdateLicenseUsage(channelId *big.Int, serviceId } return nil } -func getAllLicenseKeys(channelId *big.Int, serviceId string) []interface{} { +func getAllLicenseKeys(channelId *big.Int, serviceId string) []any { keys := make([]interface{}, 3) for i, usageType := range []string{REFUND, PLANNED, USED} { keys[i] = LicenseUsageTrackerKey{ChannelID: channelId, ServiceID: serviceId, UsageType: usageType} diff --git a/license_server/license_storage.go b/license_server/license_storage.go index 546fe089..ba31c41a 100644 --- a/license_server/license_storage.go +++ b/license_server/license_storage.go @@ -55,7 +55,7 @@ func (key *LicenseDetailsKey) String() string { return fmt.Sprintf("{ID:%v/%v}", key.ChannelID, key.ServiceID) } -func serializeLicenseDetailsKey(key interface{}) (serialized string, err error) { +func serializeLicenseDetailsKey(key any) (serialized string, err error) { myKey := key.(LicenseDetailsKey) return myKey.String(), nil } @@ -74,7 +74,7 @@ type LicenseUsageTrackerKey struct { UsageType string } -func serializeLicenseUsageTrackerKey(key interface{}) (serialized string, err error) { +func serializeLicenseUsageTrackerKey(key any) (serialized string, err error) { myKey := key.(LicenseUsageTrackerKey) return myKey.String(), nil } @@ -343,7 +343,7 @@ func NewLicenseDetailsStorage(atomicStorage storage.AtomicStorage) storage.Typed reflect.TypeOf(LicenseDetailsData{})) } -func serializeLicenseDetailsData(value interface{}) (slice string, err error) { +func serializeLicenseDetailsData(value any) (slice string, err error) { var b bytes.Buffer e := gob.NewEncoder(&b) gob.Register(&Subscription{}) @@ -362,7 +362,7 @@ func serializeLicenseDetailsData(value interface{}) (slice string, err error) { slice = string(b.Bytes()) return } -func deserializeLicenseDetailsData(slice string, value interface{}) (err error) { +func deserializeLicenseDetailsData(slice string, value any) (err error) { b := bytes.NewBuffer([]byte(slice)) gob.Register(&Subscription{}) gob.Register(&ValidityPeriod{}) @@ -376,7 +376,7 @@ func deserializeLicenseDetailsData(slice string, value interface{}) (err error) return } -func serializeLicenseTrackerData(value interface{}) (slice string, err error) { +func serializeLicenseTrackerData(value any) (slice string, err error) { var b bytes.Buffer e := gob.NewEncoder(&b) gob.Register(&UsageInCalls{}) @@ -390,7 +390,7 @@ func serializeLicenseTrackerData(value interface{}) (slice string, err error) { return } -func deserializeLicenseTrackerData(slice string, value interface{}) (err error) { +func deserializeLicenseTrackerData(slice string, value any) (err error) { b := bytes.NewBuffer([]byte(slice)) d := gob.NewDecoder(b) gob.Register(&UsageInCalls{}) diff --git a/logger/logger_test.go b/logger/logger_test.go index 67711a95..78c44b04 100644 --- a/logger/logger_test.go +++ b/logger/logger_test.go @@ -316,7 +316,7 @@ func TestFormatFileName(t *testing.T) { type createWriterSyncerTestCases struct { name string - outputType interface{} + outputType any filePatternName string expectedError string } @@ -381,7 +381,7 @@ func TestCreateWriterSyncer(t *testing.T) { type configTestCase struct { name string - config map[string]interface{} + config map[string]any expectPanic bool expectedLog *zap.Logger } @@ -393,7 +393,7 @@ func TestInitialize(t *testing.T) { testCases := []configTestCase{ { name: "Valid config", - config: map[string]interface{}{ + config: map[string]any{ "log.level": "info", "log.timezone": "UTC", "log.formatter.type": "json", @@ -410,7 +410,7 @@ func TestInitialize(t *testing.T) { }, { name: "Invalid config - invalid level", - config: map[string]interface{}{ + config: map[string]any{ "log.level": "INVALID", "log.timezone": "UTC", "log.formatter.type": "json", @@ -426,7 +426,7 @@ func TestInitialize(t *testing.T) { }, { name: "Invalid config - invalid formatter type", - config: map[string]interface{}{ + config: map[string]any{ "log.level": "info", "log.timezone": "UTC", "log.formatter.type": "INVALID", @@ -442,7 +442,7 @@ func TestInitialize(t *testing.T) { }, { name: "Invalid config - invalid output type", - config: map[string]interface{}{ + config: map[string]any{ "log.level": "info", "log.timezone": "UTC", "log.formatter.type": "json", diff --git a/metrics/utils.go b/metrics/utils.go index 619ed889..f69c5b39 100644 --- a/metrics/utils.go +++ b/metrics/utils.go @@ -55,7 +55,7 @@ func GenXid() string { } // convert the payload to JSON and publish it to the serviceUrl passed -func Publish(payload interface{}, serviceUrl string, commonStats *CommonStats) bool { +func Publish(payload any, serviceUrl string, commonStats *CommonStats) bool { jsonBytes, err := ConvertStructToJSON(payload) if err != nil { return false @@ -195,7 +195,7 @@ func getTokenFromResponse(response *http.Response) (string, bool) { } // Generic utility to determine the size of the srtuct passed -func GetSize(v interface{}) uint64 { +func GetSize(v any) uint64 { return memory.Sizeof(v) } diff --git a/storage/atomic_storage.go b/storage/atomic_storage.go index f535bbdd..e72dc9dc 100644 --- a/storage/atomic_storage.go +++ b/storage/atomic_storage.go @@ -35,7 +35,7 @@ type Transaction interface { GetConditionValues() ([]KeyValueData, error) } -//Best to change this to KeyValueData , will do this in the next commit +// Best to change this to KeyValueData , will do this in the next commit type UpdateFunc func(conditionValues []KeyValueData) (update []KeyValueData, ok bool, err error) type CASRequest struct { @@ -57,7 +57,7 @@ type PrefixedAtomicStorage struct { keyPrefix string } -//It is recommended to use this function to create a PrefixedAtomicStorage +// It is recommended to use this function to create a PrefixedAtomicStorage func NewPrefixedAtomicStorage(atomicStorage AtomicStorage, prefix string) *PrefixedAtomicStorage { return &PrefixedAtomicStorage{ delegate: atomicStorage, @@ -169,18 +169,18 @@ func (storage *PrefixedAtomicStorage) ExecuteTransaction(request CASRequest) (ok // serializes/deserializes values and keys type TypedAtomicStorage interface { // Get returns value by key - Get(key interface{}) (value interface{}, ok bool, err error) + Get(key any) (value any, ok bool, err error) // GetAll returns an array which contains all values from storage - GetAll() (array interface{}, err error) + GetAll() (array any, err error) // Put puts value by key unconditionally - Put(key interface{}, value interface{}) (err error) + Put(key any, value any) (err error) // PutIfAbsent puts value by key if and only if key is absent in storage - PutIfAbsent(key interface{}, value interface{}) (ok bool, err error) + PutIfAbsent(key any, value any) (ok bool, err error) // CompareAndSwap puts newValue by key if and only if previous value is equal // to prevValue - CompareAndSwap(key interface{}, prevValue interface{}, newValue interface{}) (ok bool, err error) + CompareAndSwap(key any, prevValue any, newValue any) (ok bool, err error) // Delete removes value by key - Delete(key interface{}) (err error) + Delete(key any) (err error) ExecuteTransaction(request TypedCASRequest) (ok bool, err error) } @@ -188,34 +188,34 @@ type TypedTransaction interface { GetConditionValues() ([]TypedKeyValueData, error) } -//Best to change this to KeyValueData , will do this in the next commit +// Best to change this to KeyValueData , will do this in the next commit type TypedUpdateFunc func(conditionValues []TypedKeyValueData) (update []TypedKeyValueData, ok bool, err error) type TypedCASRequest struct { RetryTillSuccessOrError bool Update TypedUpdateFunc - ConditionKeys []interface{} //Typed Keys + ConditionKeys []any //Typed Keys } type TypedKeyValueData struct { - Key interface{} - Value interface{} + Key any + Value any Present bool } // TypedAtomicStorageImpl is an implementation of TypedAtomicStorage interface type TypedAtomicStorageImpl struct { atomicStorage AtomicStorage - keySerializer func(key interface{}) (serialized string, err error) + keySerializer func(key any) (serialized string, err error) keyType reflect.Type - valueSerializer func(value interface{}) (serialized string, err error) - valueDeserializer func(serialized string, value interface{}) (err error) + valueSerializer func(value any) (serialized string, err error) + valueDeserializer func(serialized string, value any) (err error) valueType reflect.Type } -func NewTypedAtomicStorageImpl(storage AtomicStorage, keySerializer func(key interface{}) (serialized string, err error), - keyType reflect.Type, valueSerializer func(value interface{}) (serialized string, err error), - valueDeserializer func(serialized string, value interface{}) (err error), +func NewTypedAtomicStorageImpl(storage AtomicStorage, keySerializer func(key any) (serialized string, err error), + keyType reflect.Type, valueSerializer func(value any) (serialized string, err error), + valueDeserializer func(serialized string, value any) (err error), valueType reflect.Type) TypedAtomicStorage { return &TypedAtomicStorageImpl{ @@ -230,7 +230,7 @@ func NewTypedAtomicStorageImpl(storage AtomicStorage, keySerializer func(key int } // Get implements TypedAtomicStorage.Get -func (storage *TypedAtomicStorageImpl) Get(key interface{}) (value interface{}, ok bool, err error) { +func (storage *TypedAtomicStorageImpl) Get(key any) (value any, ok bool, err error) { keyString, err := storage.keySerializer(key) if err != nil { return @@ -252,7 +252,7 @@ func (storage *TypedAtomicStorageImpl) Get(key interface{}) (value interface{}, return value, true, nil } -func (storage *TypedAtomicStorageImpl) deserializeValue(valueString string) (value interface{}, err error) { +func (storage *TypedAtomicStorageImpl) deserializeValue(valueString string) (value any, err error) { value = reflect.New(storage.valueType).Interface() err = storage.valueDeserializer(valueString, value) if err != nil { @@ -261,7 +261,7 @@ func (storage *TypedAtomicStorageImpl) deserializeValue(valueString string) (val return value, err } -func (storage *TypedAtomicStorageImpl) GetAll() (array interface{}, err error) { +func (storage *TypedAtomicStorageImpl) GetAll() (array any, err error) { stringValues, err := storage.atomicStorage.GetByKeyPrefix("") if err != nil { return @@ -284,7 +284,7 @@ func (storage *TypedAtomicStorageImpl) GetAll() (array interface{}, err error) { } // Put implementor TypedAtomicStorage.Put -func (storage *TypedAtomicStorageImpl) Put(key interface{}, value interface{}) (err error) { +func (storage *TypedAtomicStorageImpl) Put(key any, value any) (err error) { keyString, err := storage.keySerializer(key) if err != nil { return @@ -299,7 +299,7 @@ func (storage *TypedAtomicStorageImpl) Put(key interface{}, value interface{}) ( } // PutIfAbsent implements TypedAtomicStorage.PutIfAbsent -func (storage *TypedAtomicStorageImpl) PutIfAbsent(key interface{}, value interface{}) (ok bool, err error) { +func (storage *TypedAtomicStorageImpl) PutIfAbsent(key any, value any) (ok bool, err error) { keyString, err := storage.keySerializer(key) if err != nil { return @@ -314,7 +314,7 @@ func (storage *TypedAtomicStorageImpl) PutIfAbsent(key interface{}, value interf } // CompareAndSwap implements TypedAtomicStorage.CompareAndSwap -func (storage *TypedAtomicStorageImpl) CompareAndSwap(key interface{}, prevValue interface{}, newValue interface{}) (ok bool, err error) { +func (storage *TypedAtomicStorageImpl) CompareAndSwap(key any, prevValue any, newValue any) (ok bool, err error) { keyString, err := storage.keySerializer(key) if err != nil { return @@ -333,7 +333,7 @@ func (storage *TypedAtomicStorageImpl) CompareAndSwap(key interface{}, prevValue return storage.atomicStorage.CompareAndSwap(keyString, prevValueString, newValueString) } -func (storage *TypedAtomicStorageImpl) Delete(key interface{}) (err error) { +func (storage *TypedAtomicStorageImpl) Delete(key any) (err error) { keyString, err := storage.keySerializer(key) if err != nil { return @@ -342,7 +342,7 @@ func (storage *TypedAtomicStorageImpl) Delete(key interface{}) (err error) { return storage.atomicStorage.Delete(keyString) } -func (storage *TypedAtomicStorageImpl) convertKeyValueDataToTyped(conditionKeys []interface{}, keyValueData []KeyValueData) (result []TypedKeyValueData, err error) { +func (storage *TypedAtomicStorageImpl) convertKeyValueDataToTyped(conditionKeys []any, keyValueData []KeyValueData) (result []TypedKeyValueData, err error) { result = make([]TypedKeyValueData, len(conditionKeys)) for i, conditionKey := range conditionKeys { conditionKeyString, err := storage.keySerializer(conditionKey) @@ -405,7 +405,7 @@ func (storage *TypedAtomicStorageImpl) ExecuteTransaction(request TypedCASReques return storage.atomicStorage.ExecuteTransaction(storageRequest) } -func (storage *TypedAtomicStorageImpl) convertTypedKeyToString(typedKeys []interface{}) (stringKeys []string, err error) { +func (storage *TypedAtomicStorageImpl) convertTypedKeyToString(typedKeys []any) (stringKeys []string, err error) { stringKeys = make([]string, len(typedKeys)) for i, key := range typedKeys { stringKeys[i], err = storage.keySerializer(key) diff --git a/token/jwttoken.go b/token/jwttoken.go index 7c2f0056..5a77d0af 100644 --- a/token/jwttoken.go +++ b/token/jwttoken.go @@ -36,7 +36,7 @@ func (service customJWTokenServiceImpl) CreateToken(payLoad PayLoad) (CustomToke func (service customJWTokenServiceImpl) VerifyToken(receivedToken CustomToken, payLoad PayLoad) (err error) { tokenString := fmt.Sprintf("%v", receivedToken) - token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { + token, err := jwt.Parse(tokenString, func(token *jwt.Token) (any, error) { if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf("unexpected signing method : %v", token.Header["alg"]) } diff --git a/token/token_service_api.go b/token/token_service_api.go index f1fa68a4..c7d59622 100644 --- a/token/token_service_api.go +++ b/token/token_service_api.go @@ -1,7 +1,7 @@ package token -type PayLoad interface{} -type CustomToken interface{} +type PayLoad any +type CustomToken any // Token.Manager interface is an API for creating and verifying tokens type Manager interface { diff --git a/training/storage.go b/training/storage.go index f04e2415..18cad925 100644 --- a/training/storage.go +++ b/training/storage.go @@ -104,7 +104,7 @@ type ModelData struct { UpdatedDate string } -func serializeModelKey(key interface{}) (serialized string, err error) { +func serializeModelKey(key any) (serialized string, err error) { myKey := key.(*ModelKey) return myKey.String(), nil } @@ -137,7 +137,7 @@ func (storage *ModelStorage) CompareAndSwap(key *ModelKey, prevState *ModelData, newState *ModelData) (ok bool, err error) { return storage.delegate.CompareAndSwap(key, prevState, newState) } -func serializeModelUserKey(key interface{}) (serialized string, err error) { +func serializeModelUserKey(key any) (serialized string, err error) { myKey := key.(*ModelUserKey) return myKey.String(), nil } diff --git a/utils/common.go b/utils/common.go index 6cecf3d6..a62c6e7d 100644 --- a/utils/common.go +++ b/utils/common.go @@ -10,7 +10,7 @@ import ( "go.uber.org/zap" ) -func Serialize(value interface{}) (slice string, err error) { +func Serialize(value any) (slice string, err error) { var b bytes.Buffer e := gob.NewEncoder(&b) err = e.Encode(value) @@ -22,7 +22,7 @@ func Serialize(value interface{}) (slice string, err error) { return } -func Deserialize(slice string, value interface{}) (err error) { +func Deserialize(slice string, value any) (err error) { b := bytes.NewBuffer([]byte(slice)) d := gob.NewDecoder(b) return d.Decode(value)