diff --git a/cronexpr/cronexpr.go b/cronexpr/cronexpr.go index dc049a6b832414cf24eb8d530a9bd0fc4656ef2b..41534bd0ecebd3f27ef8bc3fab4a6d2f11bcd1e0 100644 --- a/cronexpr/cronexpr.go +++ b/cronexpr/cronexpr.go @@ -90,7 +90,7 @@ func Parse(cronLine string) (*Expression, error) { if err != nil { return nil, err } - field += 1 + field++ } else { expr.secondList = []int{0} } @@ -100,35 +100,35 @@ func Parse(cronLine string) (*Expression, error) { if err != nil { return nil, err } - field += 1 + field++ // hour field err = expr.hourFieldHandler(cron[indices[field][0]:indices[field][1]]) if err != nil { return nil, err } - field += 1 + field++ // day of month field err = expr.domFieldHandler(cron[indices[field][0]:indices[field][1]]) if err != nil { return nil, err } - field += 1 + field++ // month field err = expr.monthFieldHandler(cron[indices[field][0]:indices[field][1]]) if err != nil { return nil, err } - field += 1 + field++ // day of week field err = expr.dowFieldHandler(cron[indices[field][0]:indices[field][1]]) if err != nil { return nil, err } - field += 1 + field++ // year field if field < fieldCount { diff --git a/cronexpr/cronexpr_next.go b/cronexpr/cronexpr_next.go index 0472b0ceaab3019408401ebed6cd099310a5bd0a..2da92861472a3d6b35b68deb71103c98b6df460f 100644 --- a/cronexpr/cronexpr_next.go +++ b/cronexpr/cronexpr_next.go @@ -277,13 +277,13 @@ func workdayOfMonth(targetDom, lastDom time.Time) int { dow := targetDom.Weekday() if dow == time.Saturday { if dom > 1 { - dom -= 1 + dom-- } else { dom += 2 } } else if dow == time.Sunday { if dom < lastDom.Day() { - dom += 1 + dom++ } else { dom -= 2 } diff --git a/cronexpr/cronexpr_parse.go b/cronexpr/cronexpr_parse.go index a9fe74646cf935054dff93498357a31a2b4c234a..49af45fc64a31471012e04926b940ab210c1a845 100644 --- a/cronexpr/cronexpr_parse.go +++ b/cronexpr/cronexpr_parse.go @@ -391,7 +391,7 @@ func toList(set map[int]bool) []int { i := 0 for k := range set { list[i] = k - i += 1 + i++ } sort.Ints(list) return list diff --git a/main.go b/main.go index b4ce2fb208ba125ab59444c6d2ec908bfafd830c..9b4c51dfa6622a8bc30019270f6a6c13b00444d6 100644 --- a/main.go +++ b/main.go @@ -211,26 +211,26 @@ func main() { } func dbConnect(multiLogger *zap.Logger, config server.Config) (*sql.DB, string) { - rawUrl := fmt.Sprintf("postgresql://%s", config.GetDatabase().Addresses[0]) - parsedUrl, err := url.Parse(rawUrl) + rawURL := fmt.Sprintf("postgresql://%s", config.GetDatabase().Addresses[0]) + parsedURL, err := url.Parse(rawURL) if err != nil { multiLogger.Fatal("Bad database connection URL", zap.Error(err)) } - query := parsedUrl.Query() + query := parsedURL.Query() if len(query.Get("sslmode")) == 0 { query.Set("sslmode", "disable") - parsedUrl.RawQuery = query.Encode() + parsedURL.RawQuery = query.Encode() } - if len(parsedUrl.User.Username()) < 1 { - parsedUrl.User = url.User("root") + if len(parsedURL.User.Username()) < 1 { + parsedURL.User = url.User("root") } - if len(parsedUrl.Path) < 1 { - parsedUrl.Path = "/nakama" + if len(parsedURL.Path) < 1 { + parsedURL.Path = "/nakama" } - multiLogger.Debug("Complete database connection URL", zap.String("raw_url", parsedUrl.String())) - db, err := sql.Open("pgx", parsedUrl.String()) + multiLogger.Debug("Complete database connection URL", zap.String("raw_url", parsedURL.String())) + db, err := sql.Open("pgx", parsedURL.String()) if err != nil { multiLogger.Fatal("Error connecting to database", zap.Error(err)) } diff --git a/migrate/migrate.go b/migrate/migrate.go index f0e94cf4a9dced81cd1270056b0d4f401ca7c234..8957fdb4424fac66fcc071d10b3e9c452bd64e1c 100644 --- a/migrate/migrate.go +++ b/migrate/migrate.go @@ -27,7 +27,7 @@ import ( "github.com/gobuffalo/packr" "github.com/heroiclabs/nakama/v2/server" "github.com/jackc/pgx" - _ "github.com/jackc/pgx/stdlib" + _ "github.com/jackc/pgx/stdlib" // Blank import to register SQL driver "github.com/rubenv/sql-migrate" "go.uber.org/zap" "go.uber.org/zap/zapcore" @@ -117,29 +117,29 @@ func Parse(args []string, tmpLogger *zap.Logger) { ms.parseSubcommand(args[1:], tmpLogger) logger := server.NewJSONLogger(os.Stdout, zapcore.InfoLevel, ms.loggerFormat) - rawUrl := fmt.Sprintf("postgresql://%s", ms.dbAddress) - parsedUrl, err := url.Parse(rawUrl) + rawURL := fmt.Sprintf("postgresql://%s", ms.dbAddress) + parsedURL, err := url.Parse(rawURL) if err != nil { logger.Fatal("Bad connection URL", zap.Error(err)) } - query := parsedUrl.Query() + query := parsedURL.Query() if len(query.Get("sslmode")) == 0 { query.Set("sslmode", "disable") - parsedUrl.RawQuery = query.Encode() + parsedURL.RawQuery = query.Encode() } - if len(parsedUrl.User.Username()) < 1 { - parsedUrl.User = url.User("root") + if len(parsedURL.User.Username()) < 1 { + parsedURL.User = url.User("root") } dbname := "nakama" - if len(parsedUrl.Path) > 1 { - dbname = parsedUrl.Path[1:] + if len(parsedURL.Path) > 1 { + dbname = parsedURL.Path[1:] } logger.Info("Database connection", zap.String("dsn", ms.dbAddress)) - parsedUrl.Path = "" - db, err := sql.Open("pgx", parsedUrl.String()) + parsedURL.Path = "" + db, err := sql.Open("pgx", parsedURL.String()) if err != nil { logger.Fatal("Failed to open database", zap.Error(err)) } @@ -165,8 +165,8 @@ func Parse(args []string, tmpLogger *zap.Logger) { _ = db.Close() // Append dbname to data source name. - parsedUrl.Path = fmt.Sprintf("/%s", dbname) - db, err = sql.Open("pgx", parsedUrl.String()) + parsedURL.Path = fmt.Sprintf("/%s", dbname) + db, err = sql.Open("pgx", parsedURL.String()) if err != nil { logger.Fatal("Failed to open database", zap.Error(err)) } diff --git a/server/api.go b/server/api.go index 128946e548579c6ef5a9720a6bdde01c2c363926..d244d16a56d87a46a901b5e72aa5a5281e799f89 100644 --- a/server/api.go +++ b/server/api.go @@ -522,7 +522,7 @@ func traceApiBefore(ctx context.Context, logger *zap.Logger, fullMethodName stri err = fn(clientIP, clientPort) span.End() - stats.Record(statsCtx, MetricsApiTimeSpentMsec.M(float64(time.Now().UTC().UnixNano()-startNanos)/1000), MetricsApiCount.M(1)) + stats.Record(statsCtx, MetricsAPITimeSpentMsec.M(float64(time.Now().UTC().UnixNano()-startNanos)/1000), MetricsAPICount.M(1)) return err } @@ -543,5 +543,5 @@ func traceApiAfter(ctx context.Context, logger *zap.Logger, fullMethodName strin fn(clientIP, clientPort) span.End() - stats.Record(statsCtx, MetricsApiTimeSpentMsec.M(float64(time.Now().UTC().UnixNano()-startNanos)/1000), MetricsApiCount.M(1)) + stats.Record(statsCtx, MetricsAPITimeSpentMsec.M(float64(time.Now().UTC().UnixNano()-startNanos)/1000), MetricsAPICount.M(1)) } diff --git a/server/api_leaderboard.go b/server/api_leaderboard.go index ed788a11d079fba2b270ff31273d062bba3541ce..34912d9938f6c0f1b5c4208744572b7ba114134a 100644 --- a/server/api_leaderboard.go +++ b/server/api_leaderboard.go @@ -118,8 +118,8 @@ func (s *ApiServer) ListLeaderboardRecords(ctx context.Context, in *api.ListLead } if len(in.GetOwnerIds()) != 0 { - for _, ownerId := range in.OwnerIds { - if _, err := uuid.FromString(ownerId); err != nil { + for _, ownerID := range in.OwnerIds { + if _, err := uuid.FromString(ownerID); err != nil { return nil, status.Error(codes.InvalidArgument, "One or more owner IDs are invalid.") } } @@ -252,7 +252,7 @@ func (s *ApiServer) ListLeaderboardRecordsAroundOwner(ctx context.Context, in *a return nil, status.Error(codes.InvalidArgument, "Owner ID must be provided for a haystack query.") } - ownerId, err := uuid.FromString(in.GetOwnerId()) + ownerID, err := uuid.FromString(in.GetOwnerId()) if err != nil { return nil, status.Error(codes.InvalidArgument, "Invalid owner ID provided.") } @@ -262,7 +262,7 @@ func (s *ApiServer) ListLeaderboardRecordsAroundOwner(ctx context.Context, in *a overrideExpiry = in.Expiry.Value } - records, err := LeaderboardRecordsHaystack(ctx, s.logger, s.db, s.leaderboardCache, s.leaderboardRankCache, in.GetLeaderboardId(), ownerId, limit, overrideExpiry) + records, err := LeaderboardRecordsHaystack(ctx, s.logger, s.db, s.leaderboardCache, s.leaderboardRankCache, in.GetLeaderboardId(), ownerID, limit, overrideExpiry) if err == ErrLeaderboardNotFound { return nil, status.Error(codes.NotFound, "Leaderboard not found.") } else if err != nil { diff --git a/server/api_link.go b/server/api_link.go index cbb961f046737af462627f000f9f8eeb1999a3d0..d8c8b693a1f2d1f2e87ddb9cce171a0ba5c3ec9f 100644 --- a/server/api_link.go +++ b/server/api_link.go @@ -137,14 +137,14 @@ func (s *ApiServer) LinkDevice(ctx context.Context, in *api.AccountDevice) (*emp } err = ExecuteInTx(ctx, tx, func() error { - var dbDeviceIdLinkedUser int64 - err := tx.QueryRowContext(ctx, "SELECT COUNT(id) FROM user_device WHERE id = $1 AND user_id = $2 LIMIT 1", deviceID, userID).Scan(&dbDeviceIdLinkedUser) + var dbDeviceIDLinkedUser int64 + err := tx.QueryRowContext(ctx, "SELECT COUNT(id) FROM user_device WHERE id = $1 AND user_id = $2 LIMIT 1", deviceID, userID).Scan(&dbDeviceIDLinkedUser) if err != nil { s.logger.Debug("Cannot link device ID.", zap.Error(err), zap.Any("input", in)) return err } - if dbDeviceIdLinkedUser == 0 { + if dbDeviceIDLinkedUser == 0 { _, err = tx.ExecContext(ctx, "INSERT INTO user_device (id, user_id) VALUES ($1, $2)", deviceID, userID) if err != nil { if e, ok := err.(pgx.PgError); ok && e.Code == dbErrorUniqueViolation { @@ -449,11 +449,11 @@ func (s *ApiServer) LinkGoogle(ctx context.Context, in *api.AccountGoogle) (*emp displayName = "" } - avatarUrl := googleProfile.Picture - if len(avatarUrl) > 512 { + avatarURL := googleProfile.Picture + if len(avatarURL) > 512 { // Ignore the url in case it is longer than db can store - s.logger.Warn("Skipping updating avatar_url: value received from Google longer than max length of 512 chars.", zap.String("avatar_url", avatarUrl)) - avatarUrl = "" + s.logger.Warn("Skipping updating avatar_url: value received from Google longer than max length of 512 chars.", zap.String("avatar_url", avatarURL)) + avatarURL = "" } res, err := s.db.ExecContext(ctx, ` @@ -465,7 +465,7 @@ AND (NOT EXISTS FROM users WHERE google_id = $2 AND NOT id = $1))`, userID, - googleProfile.Sub, displayName, avatarUrl) + googleProfile.Sub, displayName, avatarURL) if err != nil { s.logger.Error("Could not link Google ID.", zap.Error(err), zap.Any("input", in)) diff --git a/server/api_notification.go b/server/api_notification.go index f28fffbc9e5b5db9716e7163a3c08d341bdbe06c..509acbaf53519be5f86f1af1ed9604fc842da6aa 100644 --- a/server/api_notification.go +++ b/server/api_notification.go @@ -63,17 +63,17 @@ func (s *ApiServer) ListNotifications(ctx context.Context, in *api.ListNotificat } cursor := in.GetCacheableCursor() - var nc *notificationCacheableCursor = nil + var nc *notificationCacheableCursor if cursor != "" { - nc = ¬ificationCacheableCursor{} - if cb, err := base64.RawURLEncoding.DecodeString(cursor); err != nil { + nc := ¬ificationCacheableCursor{} + cb, err := base64.RawURLEncoding.DecodeString(cursor) + if err != nil { s.logger.Warn("Could not base64 decode notification cursor.", zap.String("cursor", cursor)) return nil, status.Error(codes.InvalidArgument, "Malformed cursor was used.") - } else { - if err := gob.NewDecoder(bytes.NewReader(cb)).Decode(nc); err != nil { - s.logger.Warn("Could not decode notification cursor.", zap.String("cursor", cursor)) - return nil, status.Error(codes.InvalidArgument, "Malformed cursor was used.") - } + } + if err := gob.NewDecoder(bytes.NewReader(cb)).Decode(nc); err != nil { + s.logger.Warn("Could not decode notification cursor.", zap.String("cursor", cursor)) + return nil, status.Error(codes.InvalidArgument, "Malformed cursor was used.") } } diff --git a/server/api_rpc.go b/server/api_rpc.go index d47de58696ec7e92ca0d2e7cf421d46bac1fcef6..7975aad8a8cce4abc75b92f46e5f9f7656e0d113 100644 --- a/server/api_rpc.go +++ b/server/api_rpc.go @@ -35,10 +35,10 @@ var ( authTokenInvalidBytes = []byte(`{"error":"Auth token invalid","message":"Auth token invalid","code":16}`) httpKeyInvalidBytes = []byte(`{"error":"HTTP key invalid","message":"HTTP key invalid","code":16}`) noAuthBytes = []byte(`{"error":"Auth token or HTTP key required","message":"Auth token or HTTP key required","code":16}`) - rpcIdMustBeSetBytes = []byte(`{"error":"RPC ID must be set","message":"RPC ID must be set","code":3}`) + rpcIDMustBeSetBytes = []byte(`{"error":"RPC ID must be set","message":"RPC ID must be set","code":3}`) rpcFunctionNotFoundBytes = []byte(`{"error":"RPC function not found","message":"RPC function not found","code":5}`) internalServerErrorBytes = []byte(`{"error":"Internal Server Error","message":"Internal Server Error","code":13}`) - badJsonBytes = []byte(`{"error":"json: cannot unmarshal object into Go value of type string","message":"json: cannot unmarshal object into Go value of type string","code":3}`) + badJSONBytes = []byte(`{"error":"json: cannot unmarshal object into Go value of type string","message":"json: cannot unmarshal object into Go value of type string","code":3}`) ) func (s *ApiServer) RpcFuncHttp(w http.ResponseWriter, r *http.Request) { @@ -84,18 +84,18 @@ func (s *ApiServer) RpcFuncHttp(w http.ResponseWriter, r *http.Request) { } // Check the RPC function ID. - maybeId, ok := mux.Vars(r)["id"] - if !ok || maybeId == "" { + maybeID, ok := mux.Vars(r)["id"] + if !ok || maybeID == "" { // Missing RPC function ID. w.WriteHeader(http.StatusBadRequest) w.Header().Set("content-type", "application/json") - _, err := w.Write(rpcIdMustBeSetBytes) + _, err := w.Write(rpcIDMustBeSetBytes) if err != nil { s.logger.Debug("Error writing response to client", zap.Error(err)) } return } - id := strings.ToLower(maybeId) + id := strings.ToLower(maybeID) // Find the correct RPC function. fn := s.runtime.Rpc(id) @@ -136,7 +136,7 @@ func (s *ApiServer) RpcFuncHttp(w http.ResponseWriter, r *http.Request) { if err != nil { w.WriteHeader(http.StatusBadRequest) w.Header().Set("content-type", "application/json") - _, err := w.Write(badJsonBytes) + _, err := w.Write(badJSONBytes) if err != nil { s.logger.Debug("Error writing response to client", zap.Error(err)) } @@ -210,14 +210,14 @@ func (s *ApiServer) RpcFunc(ctx context.Context, in *api.Rpc) (*api.Rpc, error) } queryParams := make(map[string][]string, 0) - if md, ok := metadata.FromIncomingContext(ctx); !ok { + md, ok := metadata.FromIncomingContext(ctx) + if !ok { return nil, status.Error(codes.Internal, "RPC function could not get incoming context") - } else { - for k, vs := range md { - // Only process the keys representing custom query parameters. - if strings.HasPrefix(k, "q_") { - queryParams[k[2:]] = vs - } + } + for k, vs := range md { + // Only process the keys representing custom query parameters. + if strings.HasPrefix(k, "q_") { + queryParams[k[2:]] = vs } } diff --git a/server/api_tournament.go b/server/api_tournament.go index 117bef050ee0b015081e9913b7ac9d3098f5d553..5284af3ab304026b0c9b080cafe4db047b8fd5c0 100644 --- a/server/api_tournament.go +++ b/server/api_tournament.go @@ -59,9 +59,9 @@ func (s *ApiServer) JoinTournament(ctx context.Context, in *api.JoinTournamentRe } } - tournamentId := in.GetTournamentId() + tournamentID := in.GetTournamentId() - if err := TournamentJoin(ctx, s.logger, s.db, s.leaderboardCache, userID.String(), username, tournamentId); err != nil { + if err := TournamentJoin(ctx, s.logger, s.db, s.leaderboardCache, userID.String(), username, tournamentID); err != nil { if err == ErrTournamentNotFound { return nil, status.Error(codes.NotFound, "Tournament not found.") } else if err == ErrTournamentMaxSizeReached { @@ -138,8 +138,8 @@ func (s *ApiServer) ListTournamentRecords(ctx context.Context, in *api.ListTourn } if len(in.GetOwnerIds()) != 0 { - for _, ownerId := range in.OwnerIds { - if _, err := uuid.FromString(ownerId); err != nil { + for _, ownerID := range in.OwnerIds { + if _, err := uuid.FromString(ownerID); err != nil { return nil, status.Error(codes.InvalidArgument, "One or more owner IDs are invalid.") } } @@ -202,13 +202,13 @@ func (s *ApiServer) ListTournaments(ctx context.Context, in *api.ListTournaments var incomingCursor *tournamentListCursor if in.GetCursor() != "" { - if cb, err := base64.StdEncoding.DecodeString(in.GetCursor()); err != nil { + cb, err := base64.StdEncoding.DecodeString(in.GetCursor()) + if err != nil { + return nil, ErrLeaderboardInvalidCursor + } + incomingCursor = &tournamentListCursor{} + if err := gob.NewDecoder(bytes.NewReader(cb)).Decode(incomingCursor); err != nil { return nil, ErrLeaderboardInvalidCursor - } else { - incomingCursor = &tournamentListCursor{} - if err := gob.NewDecoder(bytes.NewReader(cb)).Decode(incomingCursor); err != nil { - return nil, ErrLeaderboardInvalidCursor - } } } @@ -386,7 +386,7 @@ func (s *ApiServer) ListTournamentRecordsAroundOwner(ctx context.Context, in *ap return nil, status.Error(codes.InvalidArgument, "Owner ID must be provided for a haystack query.") } - ownerId, err := uuid.FromString(in.GetOwnerId()) + ownerID, err := uuid.FromString(in.GetOwnerId()) if err != nil { return nil, status.Error(codes.InvalidArgument, "Invalid owner ID provided.") } @@ -396,7 +396,7 @@ func (s *ApiServer) ListTournamentRecordsAroundOwner(ctx context.Context, in *ap overrideExpiry = in.Expiry.Value } - records, err := TournamentRecordsHaystack(ctx, s.logger, s.db, s.leaderboardCache, s.leaderboardRankCache, in.GetTournamentId(), ownerId, limit, overrideExpiry) + records, err := TournamentRecordsHaystack(ctx, s.logger, s.db, s.leaderboardCache, s.leaderboardRankCache, in.GetTournamentId(), ownerID, limit, overrideExpiry) if err == ErrLeaderboardNotFound { return nil, status.Error(codes.NotFound, "Tournament not found.") } else if err != nil { diff --git a/server/config.go b/server/config.go index 79638fbb1387be7ee69cec6d66222c0ae075288b..067288f29a6c407bff78df3e364a21eedf9f8ad2 100644 --- a/server/config.go +++ b/server/config.go @@ -168,8 +168,8 @@ func CheckConfig(logger *zap.Logger, config Config) map[string]string { logger.Fatal("At least one database address must be specified", zap.Strings("database.address", config.GetDatabase().Addresses)) } for _, address := range config.GetDatabase().Addresses { - rawUrl := fmt.Sprintf("postgresql://%s", address) - if _, err := url.Parse(rawUrl); err != nil { + rawURL := fmt.Sprintf("postgresql://%s", address) + if _, err := url.Parse(rawURL); err != nil { logger.Fatal("Bad database connection URL", zap.String("database.address", address), zap.Error(err)) } } @@ -374,11 +374,11 @@ func (c *config) Clone() (Config, error) { nc.Socket.KeyPEMBlock = make([]byte, len(c.Socket.KeyPEMBlock)) copy(nc.Socket.KeyPEMBlock, c.Socket.KeyPEMBlock) if len(c.Socket.TLSCert) != 0 { - if cert, err := tls.X509KeyPair(nc.Socket.CertPEMBlock, nc.Socket.KeyPEMBlock); err != nil { + cert, err := tls.X509KeyPair(nc.Socket.CertPEMBlock, nc.Socket.KeyPEMBlock) + if err != nil { return nil, err - } else { - nc.Socket.TLSCert = []tls.Certificate{cert} } + nc.Socket.TLSCert = []tls.Certificate{cert} } nc.Database.Addresses = make([]string, len(c.Database.Addresses)) copy(nc.Database.Addresses, c.Database.Addresses) diff --git a/server/console_account.go b/server/console_account.go index f021a73e2ca51d9d15174ea2997576e7c5906775..d7515a9243597e5e93ea93e03c7caf5c6a28d72e 100644 --- a/server/console_account.go +++ b/server/console_account.go @@ -287,10 +287,10 @@ func (s *ConsoleServer) UpdateAccount(ctx context.Context, in *console.UpdateAcc } } - var removeCustomId bool + var removeCustomID bool if v := in.CustomId; v != nil { if c := v.Value; c == "" { - removeCustomId = true + removeCustomID = true } else { if invalidCharsRegex.MatchString(c) { return nil, status.Error(codes.InvalidArgument, "Custom ID invalid, no spaces or control characters allowed.") @@ -350,7 +350,7 @@ func (s *ConsoleServer) UpdateAccount(ctx context.Context, in *console.UpdateAcc } } - if len(statements) == 0 && !removeCustomId && !removeEmail && len(in.DeviceIds) == 0 { + if len(statements) == 0 && !removeCustomID && !removeEmail && len(in.DeviceIds) == 0 { // Nothing to update. return &empty.Empty{}, nil } @@ -404,7 +404,7 @@ AND (EXISTS (SELECT id FROM users WHERE id = $1 AND } } - if removeCustomId && removeEmail { + if removeCustomID && removeEmail { query := `UPDATE users SET custom_id = NULL, email = NULL, update_time = now() WHERE id = $1 AND ((facebook_id IS NOT NULL @@ -421,7 +421,7 @@ AND ((facebook_id IS NOT NULL if rowsAffected, _ := res.RowsAffected(); rowsAffected == 0 { return StatusError(codes.InvalidArgument, "Cannot unlink both custom ID and email address when there are no other identifiers.", ErrRowsAffectedCount) } - } else if removeCustomId { + } else if removeCustomID { query := `UPDATE users SET custom_id = NULL, update_time = now() WHERE id = $1 AND ((facebook_id IS NOT NULL @@ -459,7 +459,7 @@ AND ((facebook_id IS NOT NULL } } - if len(in.DeviceIds) != 0 && len(statements) == 0 && !removeCustomId && !removeEmail { + if len(in.DeviceIds) != 0 && len(statements) == 0 && !removeCustomID && !removeEmail { // Ensure the user account update time is touched if the device IDs have changed but no other updates were applied to the core user record. _, err := tx.ExecContext(ctx, "UPDATE users SET update_time = now() WHERE id = $1", userID) if err != nil { diff --git a/server/console_config.go b/server/console_config.go index a7d0eae7c1aadee41aed94c6ad8912ce3c7f9010..8f4df9735bcca745ac2b289cdbccdfcc617a905d 100644 --- a/server/console_config.go +++ b/server/console_config.go @@ -39,15 +39,15 @@ func (s *ConsoleServer) GetConfig(ctx context.Context, in *empty.Empty) (*consol cfg.GetConsole().Password = ObfuscationString for i, address := range cfg.GetDatabase().Addresses { - rawUrl := fmt.Sprintf("postgresql://%s", address) - parsedUrl, err := url.Parse(rawUrl) + rawURL := fmt.Sprintf("postgresql://%s", address) + parsedURL, err := url.Parse(rawURL) if err != nil { s.logger.Error("Error parsing database address in config.", zap.Error(err)) return nil, status.Error(codes.Internal, "Error processing config.") } - if parsedUrl.User != nil { - if password, isSet := parsedUrl.User.Password(); isSet { - cfg.GetDatabase().Addresses[i] = strings.ReplaceAll(address, parsedUrl.User.Username()+":"+password, parsedUrl.User.Username()+":"+ObfuscationString) + if parsedURL.User != nil { + if password, isSet := parsedURL.User.Password(); isSet { + cfg.GetDatabase().Addresses[i] = strings.ReplaceAll(address, parsedURL.User.Username()+":"+password, parsedURL.User.Username()+":"+ObfuscationString) } } } diff --git a/server/console_storage_import.go b/server/console_storage_import.go index b7b3292c17a5f1c5edf31ed1667bcc74c0fab7a3..244bf1a5f1e72933d36a0b02b38f03841722fc6e 100644 --- a/server/console_storage_import.go +++ b/server/console_storage_import.go @@ -74,7 +74,7 @@ func (s *ConsoleServer) importStorage(w http.ResponseWriter, r *http.Request) { // Find the name of the uploaded file. var filename string - for n, _ := range r.MultipartForm.File { + for n := range r.MultipartForm.File { // If there are 2 or more files only use the first one. filename = n break @@ -144,24 +144,24 @@ func importStorageJSON(ctx context.Context, logger *zap.Logger, db *sql.DB, file for i, d := range importedData { if _, err := uuid.FromString(d.UserID); err != nil { - return errors.New(fmt.Sprintf("invalid user ID on object #%d", i)) + return fmt.Errorf("invalid user ID on object #%d", i) } if d.Collection == "" || d.Key == "" || d.Value == "" { - return errors.New(fmt.Sprintf("invalid collection, key or value supplied on object #%d", i)) + return fmt.Errorf("invalid collection, key or value supplied on object #%d", i) } if d.PermissionRead < 0 || d.PermissionRead > 2 { - return errors.New(fmt.Sprintf("invalid Read permission supplied on object #%d. It must be either 0, 1 or 2", i)) + return fmt.Errorf("invalid Read permission supplied on object #%d. It must be either 0, 1 or 2", i) } if d.PermissionWrite < 0 || d.PermissionWrite > 1 { - return errors.New(fmt.Sprintf("invalid Write permission supplied on object #%d. It must be either 0 or 1", i)) + return fmt.Errorf("invalid Write permission supplied on object #%d. It must be either 0 or 1", i) } var maybeJSON map[string]interface{} if json.Unmarshal([]byte(d.Value), &maybeJSON) != nil { - return errors.New(fmt.Sprintf("value must be a JSON object on object #%d", i)) + return fmt.Errorf("value must be a JSON object on object #%d", i) } ops = append(ops, &StorageOpWrite{ @@ -237,7 +237,7 @@ func importStorageCSV(ctx context.Context, logger *zap.Logger, db *sql.DB, fileB } else { user := record[columnIndexes["user_id"]] if _, err := uuid.FromString(user); err != nil { - return errors.New(fmt.Sprintf("invalid user ID on row #%d", len(ops)+1)) + return fmt.Errorf("invalid user ID on row #%d", len(ops)+1) } collection := record[columnIndexes["collection"]] key := record[columnIndexes["key"]] @@ -246,22 +246,22 @@ func importStorageCSV(ctx context.Context, logger *zap.Logger, db *sql.DB, fileB permissionWrite := record[columnIndexes["permission_write"]] if collection == "" || key == "" || value == "" { - return errors.New(fmt.Sprintf("invalid collection, key or value supplied on row #%d", len(ops)+1)) + return fmt.Errorf("invalid collection, key or value supplied on row #%d", len(ops)+1) } pr, err := strconv.Atoi(permissionRead) if permissionRead == "" || err != nil || pr < 0 || pr > 2 { - return errors.New(fmt.Sprintf("invalid read permission supplied on row #%d. It must be either 0, 1 or 2", len(ops)+1)) + return fmt.Errorf("invalid read permission supplied on row #%d. It must be either 0, 1 or 2", len(ops)+1) } pw, err := strconv.Atoi(permissionWrite) if permissionWrite == "" || err != nil || pw < 0 || pw > 1 { - return errors.New(fmt.Sprintf("invalid write permission supplied on row #%d. It must be either 0 or 1", len(ops)+1)) + return fmt.Errorf("invalid write permission supplied on row #%d. It must be either 0 or 1", len(ops)+1) } var maybeJSON map[string]interface{} if json.Unmarshal([]byte(value), &maybeJSON) != nil { - return errors.New(fmt.Sprintf("value must be a JSON object on row #%d", len(ops)+1)) + return fmt.Errorf("value must be a JSON object on row #%d", len(ops)+1) } ops = append(ops, &StorageOpWrite{ diff --git a/server/console_user.go b/server/console_user.go index 86d801d390412d11383cb356f6b9cc2c0aaaac94..80ddebb23210bfad6200401d37f33255d4509829 100644 --- a/server/console_user.go +++ b/server/console_user.go @@ -104,7 +104,7 @@ func (s *ConsoleServer) ListUsers(ctx context.Context, in *console.ListUsersRequ return &console.UserList{ Users: []*api.User{ - &api.User{ + { Id: in.Filter, UpdateTime: ×tamp.Timestamp{Seconds: createTime.Time.Unix()}, }, diff --git a/server/core_account.go b/server/core_account.go index e31e58d2a13a5ab0f781f58911181281f35e9478..bbf768d88d3fa1cbf9f5cf1ef41f1630df1bb0c6 100644 --- a/server/core_account.go +++ b/server/core_account.go @@ -79,7 +79,7 @@ WHERE u.id = $1` devices = append(devices, &api.AccountDevice{Id: deviceID.String}) } - var verifyTimestamp *timestamp.Timestamp = nil + var verifyTimestamp *timestamp.Timestamp if verifyTime.Status == pgtype.Present && verifyTime.Time.Unix() != 0 { verifyTimestamp = ×tamp.Timestamp{Seconds: verifyTime.Time.Unix()} } diff --git a/server/core_authenticate.go b/server/core_authenticate.go index 36ddd3d8357d401d4e9252de4eaf0f4bc2d58fbd..106bebdd0a0930205b5199f700da55d949f9d338 100644 --- a/server/core_authenticate.go +++ b/server/core_authenticate.go @@ -288,10 +288,9 @@ func AuthenticateUsername(ctx context.Context, logger *zap.Logger, db *sql.DB, u if err == sql.ErrNoRows { // Account not found and creation is never allowed for this type. return "", status.Error(codes.NotFound, "User account not found.") - } else { - logger.Error("Error looking up user by username.", zap.Error(err), zap.String("username", username)) - return "", status.Error(codes.Internal, "Error finding user account.") } + logger.Error("Error looking up user by username.", zap.Error(err), zap.String("username", username)) + return "", status.Error(codes.Internal, "Error finding user account.") } // Check if it's disabled. @@ -461,8 +460,8 @@ func AuthenticateGoogle(ctx context.Context, logger *zap.Logger, db *sql.DB, cli var dbUsername string var dbDisableTime pgtype.Timestamptz var dbDisplayName sql.NullString - var dbAvatarUrl sql.NullString - err = db.QueryRowContext(ctx, query, googleProfile.Sub).Scan(&dbUserID, &dbUsername, &dbDisableTime, &dbDisplayName, &dbAvatarUrl) + var dbAvatarURL sql.NullString + err = db.QueryRowContext(ctx, query, googleProfile.Sub).Scan(&dbUserID, &dbUsername, &dbDisableTime, &dbDisplayName, &dbAvatarURL) if err != nil { if err == sql.ErrNoRows { found = false @@ -479,11 +478,11 @@ func AuthenticateGoogle(ctx context.Context, logger *zap.Logger, db *sql.DB, cli logger.Warn("Skipping updating display_name: value received from Google longer than max length of 255 chars.", zap.String("display_name", googleProfile.Name)) } - var avatarUrl string + var avatarURL string if len(googleProfile.Picture) <= 512 { - avatarUrl = googleProfile.Picture + avatarURL = googleProfile.Picture } else { - logger.Warn("Skipping updating avatar_url: value received from Google longer than max length of 512 chars.", zap.String("avatar_url", avatarUrl)) + logger.Warn("Skipping updating avatar_url: value received from Google longer than max length of 512 chars.", zap.String("avatar_url", avatarURL)) } // Existing account found. @@ -495,7 +494,7 @@ func AuthenticateGoogle(ctx context.Context, logger *zap.Logger, db *sql.DB, cli } // Check if the display name or avatar received from Google have values but the DB does not. - if (dbDisplayName.String == "" && displayName != "") || (dbAvatarUrl.String == "" && avatarUrl != "") { + if (dbDisplayName.String == "" && displayName != "") || (dbAvatarURL.String == "" && avatarURL != "") { // At least one valid change found, update the DB to reflect changes. params := make([]interface{}, 0, 3) params = append(params, dbUserID) @@ -506,8 +505,8 @@ func AuthenticateGoogle(ctx context.Context, logger *zap.Logger, db *sql.DB, cli params = append(params, displayName) statements = append(statements, "display_name = $"+strconv.Itoa(len(params))) } - if dbAvatarUrl.String == "" && avatarUrl != "" { - params = append(params, avatarUrl) + if dbAvatarURL.String == "" && avatarURL != "" { + params = append(params, avatarURL) statements = append(statements, "avatar_url = $"+strconv.Itoa(len(params))) } @@ -530,7 +529,7 @@ func AuthenticateGoogle(ctx context.Context, logger *zap.Logger, db *sql.DB, cli // Create a new account. userID := uuid.Must(uuid.NewV4()).String() query = "INSERT INTO users (id, username, google_id, display_name, avatar_url, create_time, update_time) VALUES ($1, $2, $3, $4, $5, now(), now())" - result, err := db.ExecContext(ctx, query, userID, username, googleProfile.Sub, displayName, avatarUrl) + result, err := db.ExecContext(ctx, query, userID, username, googleProfile.Sub, displayName, avatarURL) if err != nil { if e, ok := err.(pgx.PgError); ok && e.Code == dbErrorUniqueViolation { if strings.Contains(e.Message, "users_username_key") { @@ -812,7 +811,7 @@ AND EXISTS subject := "Your friend has just joined the game" createTime := time.Now().UTC().Unix() for _, friendUserID := range friendUserIDs { - notifications[friendUserID] = []*api.Notification{&api.Notification{ + notifications[friendUserID] = []*api.Notification{{ Id: uuid.Must(uuid.NewV4()).String(), Subject: subject, Content: string(content), diff --git a/server/core_channel.go b/server/core_channel.go index adf65a3b0070b102477587d51471d0d55ed97e6a..744046166141a979f0b29a59d3e0becce5ebd78e 100644 --- a/server/core_channel.go +++ b/server/core_channel.go @@ -34,7 +34,7 @@ import ( ) var ( - ErrChannelIdInvalid = errors.New("invalid channel id") + ErrChannelIDInvalid = errors.New("invalid channel id") ErrChannelCursorInvalid = errors.New("invalid channel cursor") ErrChannelGroupNotFound = errors.New("group not found") ) @@ -55,16 +55,16 @@ type channelMessageListCursor struct { IsNext bool } -func ChannelMessagesList(ctx context.Context, logger *zap.Logger, db *sql.DB, caller uuid.UUID, stream PresenceStream, channelId string, limit int, forward bool, cursor string) (*api.ChannelMessageList, error) { +func ChannelMessagesList(ctx context.Context, logger *zap.Logger, db *sql.DB, caller uuid.UUID, stream PresenceStream, channelID string, limit int, forward bool, cursor string) (*api.ChannelMessageList, error) { var incomingCursor *channelMessageListCursor if cursor != "" { - if cb, err := base64.StdEncoding.DecodeString(cursor); err != nil { + cb, err := base64.StdEncoding.DecodeString(cursor) + if err != nil { + return nil, ErrChannelCursorInvalid + } + incomingCursor = &channelMessageListCursor{} + if err := gob.NewDecoder(bytes.NewReader(cb)).Decode(incomingCursor); err != nil { return nil, ErrChannelCursorInvalid - } else { - incomingCursor = &channelMessageListCursor{} - if err := gob.NewDecoder(bytes.NewReader(cb)).Decode(incomingCursor); err != nil { - return nil, ErrChannelCursorInvalid - } } if forward != incomingCursor.Forward { @@ -125,15 +125,15 @@ WHERE stream_mode = $1 AND stream_subject = $2::UUID AND stream_descriptor = $3: return nil, err } - groupId := stream.Subject.String() - userIdOne := stream.Subject.String() - userIdTwo := stream.Subcontext.String() + groupID := stream.Subject.String() + userIDOne := stream.Subject.String() + userIDTwo := stream.Subcontext.String() messages := make([]*api.ChannelMessage, 0, limit) var nextCursor, prevCursor *channelMessageListCursor - var dbId string + var dbID string var dbCode int32 - var dbSenderId string + var dbSenderID string var dbUsername string var dbContent string var dbCreateTime pgtype.Timestamptz @@ -146,14 +146,14 @@ WHERE stream_mode = $1 AND stream_subject = $2::UUID AND stream_descriptor = $3: StreamSubcontext: stream.Subcontext.String(), StreamLabel: stream.Label, CreateTime: dbCreateTime.Time.Unix(), - Id: dbId, + Id: dbID, Forward: forward, IsNext: true, } break } - err = rows.Scan(&dbId, &dbCode, &dbSenderId, &dbUsername, &dbContent, &dbCreateTime, &dbUpdateTime) + err = rows.Scan(&dbID, &dbCode, &dbSenderID, &dbUsername, &dbContent, &dbCreateTime, &dbUpdateTime) if err != nil { _ = rows.Close() logger.Error("Error parsing listed channel messages", zap.Error(err)) @@ -161,10 +161,10 @@ WHERE stream_mode = $1 AND stream_subject = $2::UUID AND stream_descriptor = $3: } message := &api.ChannelMessage{ - ChannelId: channelId, - MessageId: dbId, + ChannelId: channelID, + MessageId: dbID, Code: &wrappers.Int32Value{Value: dbCode}, - SenderId: dbSenderId, + SenderId: dbSenderID, Username: dbUsername, Content: dbContent, CreateTime: ×tamp.Timestamp{Seconds: dbCreateTime.Time.Unix()}, @@ -175,10 +175,10 @@ WHERE stream_mode = $1 AND stream_subject = $2::UUID AND stream_descriptor = $3: case StreamModeChannel: message.RoomName = stream.Label case StreamModeGroup: - message.GroupId = groupId + message.GroupId = groupID case StreamModeDM: - message.UserIdOne = userIdOne - message.UserIdTwo = userIdTwo + message.UserIdOne = userIDOne + message.UserIdTwo = userIDTwo } messages = append(messages, message) @@ -191,7 +191,7 @@ WHERE stream_mode = $1 AND stream_subject = $2::UUID AND stream_descriptor = $3: StreamSubcontext: stream.Subcontext.String(), StreamLabel: stream.Label, CreateTime: dbCreateTime.Time.Unix(), - Id: dbId, + Id: dbID, Forward: forward, IsNext: false, } @@ -250,7 +250,7 @@ func GetChannelMessages(ctx context.Context, logger *zap.Logger, db *sql.DB, use defer rows.Close() messages := make([]*api.ChannelMessage, 0, 100) - var dbId string + var dbID string var dbCode int32 var dbUsername string var dbStreamMode uint8 @@ -261,13 +261,13 @@ func GetChannelMessages(ctx context.Context, logger *zap.Logger, db *sql.DB, use var dbCreateTime pgtype.Timestamptz var dbUpdateTime pgtype.Timestamptz for rows.Next() { - err = rows.Scan(&dbId, &dbCode, &dbUsername, &dbStreamMode, &dbStreamSubject, &dbStreamSubcontext, &dbStreamLabel, &dbContent, &dbCreateTime, &dbUpdateTime) + err = rows.Scan(&dbID, &dbCode, &dbUsername, &dbStreamMode, &dbStreamSubject, &dbStreamSubcontext, &dbStreamLabel, &dbContent, &dbCreateTime, &dbUpdateTime) if err != nil { logger.Error("Error parsing listed channel messages for user", zap.String("user_id", userID.String()), zap.Error(err)) return nil, err } - channelId, err := StreamToChannelId(PresenceStream{ + channelID, err := StreamToChannelId(PresenceStream{ Mode: dbStreamMode, Subject: uuid.FromStringOrNil(dbStreamSubject), Subcontext: uuid.FromStringOrNil(dbStreamSubcontext), @@ -279,8 +279,8 @@ func GetChannelMessages(ctx context.Context, logger *zap.Logger, db *sql.DB, use } messages = append(messages, &api.ChannelMessage{ - ChannelId: channelId, - MessageId: dbId, + ChannelId: channelID, + MessageId: dbID, Code: &wrappers.Int32Value{Value: dbCode}, SenderId: userID.String(), Username: dbUsername, @@ -294,14 +294,14 @@ func GetChannelMessages(ctx context.Context, logger *zap.Logger, db *sql.DB, use return messages, nil } -func ChannelIdToStream(channelId string) (*ChannelIdToStreamResult, error) { - if channelId == "" { - return nil, ErrChannelIdInvalid +func ChannelIdToStream(channelID string) (*ChannelIdToStreamResult, error) { + if channelID == "" { + return nil, ErrChannelIDInvalid } - components := strings.SplitN(channelId, ".", 4) + components := strings.SplitN(channelID, ".", 4) if len(components) != 4 { - return nil, ErrChannelIdInvalid + return nil, ErrChannelIDInvalid } stream := PresenceStream{ @@ -314,23 +314,23 @@ func ChannelIdToStream(channelId string) (*ChannelIdToStreamResult, error) { // StreamModeChannel. // Expect no subject or subcontext. if components[1] != "" || components[2] != "" { - return nil, ErrChannelIdInvalid + return nil, ErrChannelIDInvalid } // Label. if l := len(components[3]); l < 1 || l > 64 { - return nil, ErrChannelIdInvalid + return nil, ErrChannelIDInvalid } stream.Label = components[3] case "3": // Expect no subcontext or label. if components[2] != "" || components[3] != "" { - return nil, ErrChannelIdInvalid + return nil, ErrChannelIDInvalid } // Subject. var err error if components[1] != "" { if stream.Subject, err = uuid.FromString(components[1]); err != nil { - return nil, ErrChannelIdInvalid + return nil, ErrChannelIDInvalid } } // Mode. @@ -338,25 +338,25 @@ func ChannelIdToStream(channelId string) (*ChannelIdToStreamResult, error) { case "4": // Expect lo label. if components[3] != "" { - return nil, ErrChannelIdInvalid + return nil, ErrChannelIDInvalid } // Subject. var err error if components[1] != "" { if stream.Subject, err = uuid.FromString(components[1]); err != nil { - return nil, ErrChannelIdInvalid + return nil, ErrChannelIDInvalid } } // Subcontext. if components[2] != "" { if stream.Subcontext, err = uuid.FromString(components[2]); err != nil { - return nil, ErrChannelIdInvalid + return nil, ErrChannelIDInvalid } } // Mode. stream.Mode = StreamModeDM default: - return nil, ErrChannelIdInvalid + return nil, ErrChannelIDInvalid } return &ChannelIdToStreamResult{Stream: stream}, nil @@ -364,7 +364,7 @@ func ChannelIdToStream(channelId string) (*ChannelIdToStreamResult, error) { func StreamToChannelId(stream PresenceStream) (string, error) { if stream.Mode != StreamModeChannel && stream.Mode != StreamModeGroup && stream.Mode != StreamModeDM { - return "", ErrChannelIdInvalid + return "", ErrChannelIDInvalid } subject := "" diff --git a/server/core_friend.go b/server/core_friend.go index 2de0739c6e19daa23c0d1a929c4c728e89800380..281177243752bea03a7dc9bae2c34c93ec254388 100644 --- a/server/core_friend.go +++ b/server/core_friend.go @@ -91,13 +91,13 @@ FROM users, user_edge WHERE id = destination_id AND source_id = $1` func ListFriends(ctx context.Context, logger *zap.Logger, db *sql.DB, tracker Tracker, userID uuid.UUID, limit int, state *wrappers.Int32Value, cursor string) (*api.FriendList, error) { var incomingCursor *edgeListCursor if cursor != "" { - if cb, err := base64.StdEncoding.DecodeString(cursor); err != nil { + cb, err := base64.StdEncoding.DecodeString(cursor) + if err != nil { + return nil, ErrFriendInvalidCursor + } + incomingCursor = &edgeListCursor{} + if err := gob.NewDecoder(bytes.NewReader(cb)).Decode(incomingCursor); err != nil { return nil, ErrFriendInvalidCursor - } else { - incomingCursor = &edgeListCursor{} - if err := gob.NewDecoder(bytes.NewReader(cb)).Decode(incomingCursor); err != nil { - return nil, ErrFriendInvalidCursor - } } // Cursor and filter mismatch. Perhaps the caller has sent an old cursor with a changed filter. diff --git a/server/core_group.go b/server/core_group.go index 475a6012fef4b13b61db061a7f662414805c9749..f560419cfa9354a0535226746aeee32998948e35 100644 --- a/server/core_group.go +++ b/server/core_group.go @@ -233,16 +233,15 @@ func UpdateGroup(ctx context.Context, logger *zap.Logger, db *sql.DB, groupID uu return err } - if rowsAffected, err := res.RowsAffected(); err != nil { + rowsAffected, err := res.RowsAffected() + if err != nil { logger.Error("Could not get rows affected after group update query.", zap.Error(err)) return err - } else { - if rowsAffected == 0 { - return ErrGroupNotUpdated - } - - return nil } + if rowsAffected == 0 { + return ErrGroupNotUpdated + } + return nil } func DeleteGroup(ctx context.Context, logger *zap.Logger, db *sql.DB, groupID uuid.UUID, userID uuid.UUID) error { @@ -344,7 +343,7 @@ WHERE (id = $1) AND (disable_time = '1970-01-01 00:00:00 UTC')` adminID := uuid.FromStringOrNil(id) notifications[adminID] = []*api.Notification{ - &api.Notification{ + { Id: uuid.Must(uuid.NewV4()).String(), Subject: notificationSubject, Content: notificationContent, @@ -373,14 +372,14 @@ WHERE (id = $1) AND (disable_time = '1970-01-01 00:00:00 UTC')` Mode: StreamModeGroup, Subject: groupID, } - channelId, err := StreamToChannelId(stream) + channelID, err := StreamToChannelId(stream) if err != nil { logger.Error("Could not create channel ID.", zap.Error(err)) return err } ts := time.Now().Unix() message := &api.ChannelMessage{ - ChannelId: channelId, + ChannelId: channelID, MessageId: uuid.Must(uuid.NewV4()).String(), Code: &wrappers.Int32Value{Value: ChannelMessageTypeGroupJoin}, SenderId: userID.String(), @@ -471,14 +470,14 @@ func LeaveGroup(ctx context.Context, logger *zap.Logger, db *sql.DB, router Mess Mode: StreamModeGroup, Subject: groupID, } - channelId, err := StreamToChannelId(stream) + channelID, err := StreamToChannelId(stream) if err != nil { logger.Error("Could not create channel ID.", zap.Error(err)) return err } ts := time.Now().Unix() message := &api.ChannelMessage{ - ChannelId: channelId, + ChannelId: channelID, MessageId: uuid.Must(uuid.NewV4()).String(), Code: &wrappers.Int32Value{Value: ChannelMessageTypeGroupLeave}, SenderId: userID.String(), @@ -595,7 +594,7 @@ func AddGroupUsers(ctx context.Context, logger *zap.Logger, db *sql.DB, router M Mode: StreamModeGroup, Subject: groupID, } - channelId, err := StreamToChannelId(stream) + channelID, err := StreamToChannelId(stream) if err != nil { logger.Error("Could not create channel ID.", zap.Error(err)) return err @@ -667,7 +666,7 @@ func AddGroupUsers(ctx context.Context, logger *zap.Logger, db *sql.DB, router M } message := &api.ChannelMessage{ - ChannelId: channelId, + ChannelId: channelID, MessageId: uuid.Must(uuid.NewV4()).String(), Code: &wrappers.Int32Value{Value: ChannelMessageTypeGroupAdd}, SenderId: uid.String(), @@ -689,7 +688,7 @@ VALUES ($1, $2, $3, $4, $5, $6::UUID, $7::UUID, $8, $9, $10, $10)` messages = append(messages, message) notifications[uid] = []*api.Notification{ - &api.Notification{ + { Id: uuid.Must(uuid.NewV4()).String(), Subject: notificationSubject, Content: notificationContent, @@ -743,7 +742,7 @@ func KickGroupUsers(ctx context.Context, logger *zap.Logger, db *sql.DB, router Mode: StreamModeGroup, Subject: groupID, } - channelId, err := StreamToChannelId(stream) + channelID, err := StreamToChannelId(stream) if err != nil { logger.Error("Could not create channel ID.", zap.Error(err)) return err @@ -837,7 +836,7 @@ RETURNING state` } message := &api.ChannelMessage{ - ChannelId: channelId, + ChannelId: channelID, MessageId: uuid.Must(uuid.NewV4()).String(), Code: &wrappers.Int32Value{Value: ChannelMessageTypeGroupKick}, SenderId: uid.String(), @@ -910,7 +909,7 @@ func PromoteGroupUsers(ctx context.Context, logger *zap.Logger, db *sql.DB, rout Mode: StreamModeGroup, Subject: groupID, } - channelId, err := StreamToChannelId(stream) + channelID, err := StreamToChannelId(stream) if err != nil { logger.Error("Could not create channel ID.", zap.Error(err)) return err @@ -979,7 +978,7 @@ RETURNING state` } message := &api.ChannelMessage{ - ChannelId: channelId, + ChannelId: channelID, MessageId: uuid.Must(uuid.NewV4()).String(), Code: &wrappers.Int32Value{Value: ChannelMessageTypeGroupPromote}, SenderId: uid.String(), @@ -1016,13 +1015,13 @@ VALUES ($1, $2, $3, $4, $5, $6::UUID, $7::UUID, $8, $9, $10, $10)` func ListGroupUsers(ctx context.Context, logger *zap.Logger, db *sql.DB, tracker Tracker, groupID uuid.UUID, limit int, state *wrappers.Int32Value, cursor string) (*api.GroupUserList, error) { var incomingCursor *edgeListCursor if cursor != "" { - if cb, err := base64.StdEncoding.DecodeString(cursor); err != nil { + cb, err := base64.StdEncoding.DecodeString(cursor) + if err != nil { + return nil, ErrGroupUserInvalidCursor + } + incomingCursor = &edgeListCursor{} + if err := gob.NewDecoder(bytes.NewReader(cb)).Decode(incomingCursor); err != nil { return nil, ErrGroupUserInvalidCursor - } else { - incomingCursor = &edgeListCursor{} - if err := gob.NewDecoder(bytes.NewReader(cb)).Decode(incomingCursor); err != nil { - return nil, ErrGroupUserInvalidCursor - } } // Cursor and filter mismatch. Perhaps the caller has sent an old cursor with a changed filter. @@ -1150,13 +1149,13 @@ WHERE u.id = ge.destination_id AND ge.source_id = $1` func ListUserGroups(ctx context.Context, logger *zap.Logger, db *sql.DB, userID uuid.UUID, limit int, state *wrappers.Int32Value, cursor string) (*api.UserGroupList, error) { var incomingCursor *edgeListCursor if cursor != "" { - if cb, err := base64.StdEncoding.DecodeString(cursor); err != nil { + cb, err := base64.StdEncoding.DecodeString(cursor) + if err != nil { + return nil, ErrUserGroupInvalidCursor + } + incomingCursor = &edgeListCursor{} + if err := gob.NewDecoder(bytes.NewReader(cb)).Decode(incomingCursor); err != nil { return nil, ErrUserGroupInvalidCursor - } else { - incomingCursor = &edgeListCursor{} - if err := gob.NewDecoder(bytes.NewReader(cb)).Decode(incomingCursor); err != nil { - return nil, ErrUserGroupInvalidCursor - } } // Cursor and filter mismatch. Perhaps the caller has sent an old cursor with a changed filter. @@ -1315,17 +1314,17 @@ AND id IN (` + strings.Join(statements, ",") + `)` } func ListGroups(ctx context.Context, logger *zap.Logger, db *sql.DB, name string, limit int, cursorStr string) (*api.GroupList, error) { - var cursor *groupListCursor = nil + var cursor *groupListCursor if cursorStr != "" { cursor = &groupListCursor{} - if cb, err := base64.RawURLEncoding.DecodeString(cursorStr); err != nil { + cb, err := base64.RawURLEncoding.DecodeString(cursorStr) + if err != nil { logger.Warn("Could not base64 decode group listing cursor.", zap.String("cursor", cursorStr)) return nil, status.Error(codes.InvalidArgument, "Malformed cursor was used.") - } else { - if err := gob.NewDecoder(bytes.NewReader(cb)).Decode(cursor); err != nil { - logger.Warn("Could not decode group listing cursor.", zap.String("cursor", cursorStr)) - return nil, status.Error(codes.InvalidArgument, "Malformed cursor was used.") - } + } + if err = gob.NewDecoder(bytes.NewReader(cb)).Decode(cursor); err != nil { + logger.Warn("Could not decode group listing cursor.", zap.String("cursor", cursorStr)) + return nil, status.Error(codes.InvalidArgument, "Malformed cursor was used.") } } @@ -1486,11 +1485,11 @@ VALUES return 0, err } - if rowsAffected, err := res.RowsAffected(); err != nil { + rowsAffected, err := res.RowsAffected() + if err != nil { return 0, err - } else { - return rowsAffected, nil } + return rowsAffected, nil } func groupUpdateUserState(ctx context.Context, db *sql.DB, tx *sql.Tx, groupID uuid.UUID, userID uuid.UUID, fromState int, toState int) (int64, error) { @@ -1514,11 +1513,11 @@ OR return 0, err } - if rowsAffected, err := res.RowsAffected(); err != nil { + rowsAffected, err := res.RowsAffected() + if err != nil { return 0, err - } else { - return rowsAffected, nil } + return rowsAffected, nil } func groupCheckUserPermission(ctx context.Context, logger *zap.Logger, db *sql.DB, groupID, userID uuid.UUID, state int) (bool, error) { diff --git a/server/core_leaderboard.go b/server/core_leaderboard.go index c2cffc1eedb07ee254c76b18777dd1a50213021e..3199b30703935cf66b095accfe1922dfb3eb304a 100644 --- a/server/core_leaderboard.go +++ b/server/core_leaderboard.go @@ -71,13 +71,13 @@ func LeaderboardRecordsList(ctx context.Context, logger *zap.Logger, db *sql.DB, limitNumber := int(limit.Value) var incomingCursor *leaderboardRecordListCursor if cursor != "" { - if cb, err := base64.StdEncoding.DecodeString(cursor); err != nil { + cb, err := base64.StdEncoding.DecodeString(cursor) + if err != nil { + return nil, ErrLeaderboardInvalidCursor + } + incomingCursor = &leaderboardRecordListCursor{} + if err := gob.NewDecoder(bytes.NewReader(cb)).Decode(incomingCursor); err != nil { return nil, ErrLeaderboardInvalidCursor - } else { - incomingCursor = &leaderboardRecordListCursor{} - if err := gob.NewDecoder(bytes.NewReader(cb)).Decode(incomingCursor); err != nil { - return nil, ErrLeaderboardInvalidCursor - } } if leaderboardId != incomingCursor.LeaderboardId { @@ -126,7 +126,7 @@ func LeaderboardRecordsList(ctx context.Context, logger *zap.Logger, db *sql.DB, records = make([]*api.LeaderboardRecord, 0, limitNumber) var nextCursor, prevCursor *leaderboardRecordListCursor - var dbOwnerId string + var dbOwnerID string var dbUsername sql.NullString var dbScore int64 var dbSubscore int64 @@ -143,13 +143,13 @@ func LeaderboardRecordsList(ctx context.Context, logger *zap.Logger, db *sql.DB, ExpiryTime: expiryTime, Score: dbScore, Subscore: dbSubscore, - OwnerId: dbOwnerId, + OwnerId: dbOwnerID, Rank: rank, } break } - err = rows.Scan(&dbOwnerId, &dbUsername, &dbScore, &dbSubscore, &dbNumScore, &dbMaxNumScore, &dbMetadata, &dbCreateTime, &dbUpdateTime) + err = rows.Scan(&dbOwnerID, &dbUsername, &dbScore, &dbSubscore, &dbNumScore, &dbMaxNumScore, &dbMetadata, &dbCreateTime, &dbUpdateTime) if err != nil { _ = rows.Close() logger.Error("Error parsing listed leaderboard records", zap.Error(err)) @@ -164,7 +164,7 @@ func LeaderboardRecordsList(ctx context.Context, logger *zap.Logger, db *sql.DB, record := &api.LeaderboardRecord{ LeaderboardId: leaderboardId, - OwnerId: dbOwnerId, + OwnerId: dbOwnerID, Score: dbScore, Subscore: dbSubscore, NumScore: dbNumScore, @@ -191,7 +191,7 @@ func LeaderboardRecordsList(ctx context.Context, logger *zap.Logger, db *sql.DB, ExpiryTime: expiryTime, Score: dbScore, Subscore: dbSubscore, - OwnerId: dbOwnerId, + OwnerId: dbOwnerID, Rank: rank, } } @@ -237,8 +237,8 @@ func LeaderboardRecordsList(ctx context.Context, logger *zap.Logger, db *sql.DB, params := make([]interface{}, 0, len(ownerIds)+2) params = append(params, leaderboardId, time.Unix(expiryTime, 0).UTC()) statements := make([]string, len(ownerIds)) - for i, ownerId := range ownerIds { - params = append(params, ownerId) + for i, ownerID := range ownerIds { + params = append(params, ownerID) statements[i] = "$" + strconv.Itoa(i+3) } @@ -251,7 +251,7 @@ func LeaderboardRecordsList(ctx context.Context, logger *zap.Logger, db *sql.DB, ownerRecords = make([]*api.LeaderboardRecord, 0, len(ownerIds)) - var dbOwnerId string + var dbOwnerID string var dbUsername sql.NullString var dbScore int64 var dbSubscore int64 @@ -261,7 +261,7 @@ func LeaderboardRecordsList(ctx context.Context, logger *zap.Logger, db *sql.DB, var dbCreateTime pgtype.Timestamptz var dbUpdateTime pgtype.Timestamptz for rows.Next() { - err = rows.Scan(&dbOwnerId, &dbUsername, &dbScore, &dbSubscore, &dbNumScore, &dbMaxNumScore, &dbMetadata, &dbCreateTime, &dbUpdateTime) + err = rows.Scan(&dbOwnerID, &dbUsername, &dbScore, &dbSubscore, &dbNumScore, &dbMaxNumScore, &dbMetadata, &dbCreateTime, &dbUpdateTime) if err != nil { _ = rows.Close() logger.Error("Error parsing read leaderboard records", zap.Error(err)) @@ -271,7 +271,7 @@ func LeaderboardRecordsList(ctx context.Context, logger *zap.Logger, db *sql.DB, record := &api.LeaderboardRecord{ // Rank filled in in bulk below. LeaderboardId: leaderboardId, - OwnerId: dbOwnerId, + OwnerId: dbOwnerID, Score: dbScore, Subscore: dbSubscore, NumScore: dbNumScore, @@ -303,7 +303,7 @@ func LeaderboardRecordsList(ctx context.Context, logger *zap.Logger, db *sql.DB, }, nil } -func LeaderboardRecordWrite(ctx context.Context, logger *zap.Logger, db *sql.DB, leaderboardCache LeaderboardCache, rankCache LeaderboardRankCache, caller uuid.UUID, leaderboardId, ownerId, username string, score, subscore int64, metadata string) (*api.LeaderboardRecord, error) { +func LeaderboardRecordWrite(ctx context.Context, logger *zap.Logger, db *sql.DB, leaderboardCache LeaderboardCache, rankCache LeaderboardRankCache, caller uuid.UUID, leaderboardId, ownerID, username string, score, subscore int64, metadata string) (*api.LeaderboardRecord, error) { leaderboard := leaderboardCache.Get(leaderboardId) if leaderboard == nil { return nil, ErrLeaderboardNotFound @@ -318,21 +318,21 @@ func LeaderboardRecordWrite(ctx context.Context, logger *zap.Logger, db *sql.DB, expiryTime = leaderboard.ResetSchedule.Next(time.Now().UTC()).UTC().Unix() } - var opSql string - var filterSql string + var opSQL string + var filterSQL string var scoreDelta int64 var subscoreDelta int64 var scoreAbs int64 var subscoreAbs int64 switch leaderboard.Operator { case LeaderboardOperatorIncrement: - opSql = "score = leaderboard_record.score + $8, subscore = leaderboard_record.subscore + $9" + opSQL = "score = leaderboard_record.score + $8, subscore = leaderboard_record.subscore + $9" scoreDelta = score subscoreDelta = subscore scoreAbs = score subscoreAbs = subscore case LeaderboardOperatorSet: - opSql = "score = $8, subscore = $9" + opSQL = "score = $8, subscore = $9" scoreDelta = score subscoreDelta = subscore scoreAbs = score @@ -342,12 +342,12 @@ func LeaderboardRecordWrite(ctx context.Context, logger *zap.Logger, db *sql.DB, default: if leaderboard.SortOrder == LeaderboardSortOrderAscending { // Lower score is better. - opSql = "score = div((leaderboard_record.score + $8 - abs(leaderboard_record.score - $8)), 2), subscore = div((leaderboard_record.subscore + $9 - abs(leaderboard_record.subscore - $9)), 2)" - filterSql = " WHERE leaderboard_record.score > $8 OR leaderboard_record.subscore > $9" + opSQL = "score = div((leaderboard_record.score + $8 - abs(leaderboard_record.score - $8)), 2), subscore = div((leaderboard_record.subscore + $9 - abs(leaderboard_record.subscore - $9)), 2)" + filterSQL = " WHERE leaderboard_record.score > $8 OR leaderboard_record.subscore > $9" } else { // Higher score is better. - opSql = "score = div((leaderboard_record.score + $8 + abs(leaderboard_record.score - $8)), 2), subscore = div((leaderboard_record.subscore + $9 + abs(leaderboard_record.subscore - $9)), 2)" - filterSql = " WHERE leaderboard_record.score < $8 OR leaderboard_record.subscore < $9" + opSQL = "score = div((leaderboard_record.score + $8 + abs(leaderboard_record.score - $8)), 2), subscore = div((leaderboard_record.subscore + $9 + abs(leaderboard_record.subscore - $9)), 2)" + filterSQL = " WHERE leaderboard_record.score < $8 OR leaderboard_record.subscore < $9" } scoreDelta = score subscoreDelta = subscore @@ -358,9 +358,9 @@ func LeaderboardRecordWrite(ctx context.Context, logger *zap.Logger, db *sql.DB, query := `INSERT INTO leaderboard_record (leaderboard_id, owner_id, username, score, subscore, metadata, expiry_time) VALUES ($1, $2, $3, $4, $5, COALESCE($6, '{}'::JSONB), $7) ON CONFLICT (owner_id, leaderboard_id, expiry_time) - DO UPDATE SET ` + opSql + `, num_score = leaderboard_record.num_score + 1, metadata = COALESCE($6, leaderboard_record.metadata), update_time = now()` + filterSql + DO UPDATE SET ` + opSQL + `, num_score = leaderboard_record.num_score + 1, metadata = COALESCE($6, leaderboard_record.metadata), update_time = now()` + filterSQL params := make([]interface{}, 0, 9) - params = append(params, leaderboardId, ownerId) + params = append(params, leaderboardId, ownerID) if username == "" { params = append(params, nil) } else { @@ -389,19 +389,19 @@ func LeaderboardRecordWrite(ctx context.Context, logger *zap.Logger, db *sql.DB, var dbCreateTime pgtype.Timestamptz var dbUpdateTime pgtype.Timestamptz query = "SELECT username, score, subscore, num_score, max_num_score, metadata, create_time, update_time FROM leaderboard_record WHERE leaderboard_id = $1 AND owner_id = $2 AND expiry_time = $3" - err = db.QueryRowContext(ctx, query, leaderboardId, ownerId, time.Unix(expiryTime, 0).UTC()).Scan(&dbUsername, &dbScore, &dbSubscore, &dbNumScore, &dbMaxNumScore, &dbMetadata, &dbCreateTime, &dbUpdateTime) + err = db.QueryRowContext(ctx, query, leaderboardId, ownerID, time.Unix(expiryTime, 0).UTC()).Scan(&dbUsername, &dbScore, &dbSubscore, &dbNumScore, &dbMaxNumScore, &dbMetadata, &dbCreateTime, &dbUpdateTime) if err != nil { logger.Error("Error after writing leaderboard record", zap.Error(err)) return nil, err } // ensure we have the latest dbscore, dbsubscore - newRank := rankCache.Insert(leaderboardId, expiryTime, leaderboard.SortOrder, uuid.Must(uuid.FromString(ownerId)), dbScore, dbSubscore) + newRank := rankCache.Insert(leaderboardId, expiryTime, leaderboard.SortOrder, uuid.Must(uuid.FromString(ownerID)), dbScore, dbSubscore) record := &api.LeaderboardRecord{ Rank: newRank, LeaderboardId: leaderboardId, - OwnerId: ownerId, + OwnerId: ownerID, Score: dbScore, Subscore: dbSubscore, NumScore: dbNumScore, @@ -420,7 +420,7 @@ func LeaderboardRecordWrite(ctx context.Context, logger *zap.Logger, db *sql.DB, return record, nil } -func LeaderboardRecordDelete(ctx context.Context, logger *zap.Logger, db *sql.DB, leaderboardCache LeaderboardCache, rankCache LeaderboardRankCache, caller uuid.UUID, leaderboardId, ownerId string) error { +func LeaderboardRecordDelete(ctx context.Context, logger *zap.Logger, db *sql.DB, leaderboardCache LeaderboardCache, rankCache LeaderboardRankCache, caller uuid.UUID, leaderboardId, ownerID string) error { leaderboard := leaderboardCache.Get(leaderboardId) if leaderboard == nil { return nil @@ -436,13 +436,13 @@ func LeaderboardRecordDelete(ctx context.Context, logger *zap.Logger, db *sql.DB } query := "DELETE FROM leaderboard_record WHERE leaderboard_id = $1 AND owner_id = $2 AND expiry_time = $3" - _, err := db.ExecContext(ctx, query, leaderboardId, ownerId, time.Unix(expiryTime, 0).UTC()) + _, err := db.ExecContext(ctx, query, leaderboardId, ownerID, time.Unix(expiryTime, 0).UTC()) if err != nil { logger.Error("Error deleting leaderboard record", zap.Error(err)) return err } - rankCache.Delete(leaderboardId, expiryTime, uuid.Must(uuid.FromString(ownerId))) + rankCache.Delete(leaderboardId, expiryTime, uuid.Must(uuid.FromString(ownerID))) return nil } @@ -468,7 +468,7 @@ func LeaderboardRecordsDeleteAll(ctx context.Context, logger *zap.Logger, tx *sq return nil } -func LeaderboardRecordsHaystack(ctx context.Context, logger *zap.Logger, db *sql.DB, leaderboardCache LeaderboardCache, rankCache LeaderboardRankCache, leaderboardId string, ownerId uuid.UUID, limit int, overrideExpiry int64) ([]*api.LeaderboardRecord, error) { +func LeaderboardRecordsHaystack(ctx context.Context, logger *zap.Logger, db *sql.DB, leaderboardCache LeaderboardCache, rankCache LeaderboardRankCache, leaderboardId string, ownerID uuid.UUID, limit int, overrideExpiry int64) ([]*api.LeaderboardRecord, error) { leaderboard := leaderboardCache.Get(leaderboardId) if leaderboard == nil { return nil, ErrLeaderboardNotFound @@ -480,12 +480,12 @@ func LeaderboardRecordsHaystack(ctx context.Context, logger *zap.Logger, db *sql return make([]*api.LeaderboardRecord, 0), nil } - return getLeaderboardRecordsHaystack(ctx, logger, db, rankCache, ownerId, limit, leaderboard.Id, leaderboard.SortOrder, time.Unix(expiryTime, 0).UTC()) + return getLeaderboardRecordsHaystack(ctx, logger, db, rankCache, ownerID, limit, leaderboard.Id, leaderboard.SortOrder, time.Unix(expiryTime, 0).UTC()) } -func getLeaderboardRecordsHaystack(ctx context.Context, logger *zap.Logger, db *sql.DB, rankCache LeaderboardRankCache, ownerId uuid.UUID, limit int, leaderboardId string, sortOrder int, expiryTime time.Time) ([]*api.LeaderboardRecord, error) { - var dbLeaderboardId string - var dbOwnerId string +func getLeaderboardRecordsHaystack(ctx context.Context, logger *zap.Logger, db *sql.DB, rankCache LeaderboardRankCache, ownerID uuid.UUID, limit int, leaderboardId string, sortOrder int, expiryTime time.Time) ([]*api.LeaderboardRecord, error) { + var dbLeaderboardID string + var dbOwnerID string var dbUsername sql.NullString var dbScore int64 var dbSubscore int64 @@ -502,18 +502,18 @@ func getLeaderboardRecordsHaystack(ctx context.Context, logger *zap.Logger, db * AND leaderboard_id = $2 AND expiry_time = $3` logger.Debug("Leaderboard haystack lookup", zap.String("query", findQuery)) - err := db.QueryRowContext(ctx, findQuery, ownerId, leaderboardId, expiryTime).Scan(&dbLeaderboardId, &dbOwnerId, &dbUsername, &dbScore, &dbSubscore, &dbNumScore, &dbMaxNumScore, &dbMetadata, &dbCreateTime, &dbUpdateTime, &dbExpiryTime) + err := db.QueryRowContext(ctx, findQuery, ownerID, leaderboardId, expiryTime).Scan(&dbLeaderboardID, &dbOwnerID, &dbUsername, &dbScore, &dbSubscore, &dbNumScore, &dbMaxNumScore, &dbMetadata, &dbCreateTime, &dbUpdateTime, &dbExpiryTime) if err == sql.ErrNoRows { return []*api.LeaderboardRecord{}, nil } else if err != nil { - logger.Error("Could not load owner record in leaderboard records list haystack", zap.Error(err), zap.String("leaderboard_id", leaderboardId), zap.String("owner_id", ownerId.String())) + logger.Error("Could not load owner record in leaderboard records list haystack", zap.Error(err), zap.String("leaderboard_id", leaderboardId), zap.String("owner_id", ownerID.String())) return nil, err } ownerRecord := &api.LeaderboardRecord{ // Record populated later. - LeaderboardId: dbLeaderboardId, - OwnerId: dbOwnerId, + LeaderboardId: dbLeaderboardID, + OwnerId: dbOwnerID, Score: dbScore, Subscore: dbSubscore, NumScore: dbNumScore, @@ -530,7 +530,7 @@ func getLeaderboardRecordsHaystack(ctx context.Context, logger *zap.Logger, db * } if limit == 1 { - ownerRecord.Rank = rankCache.Get(leaderboardId, expiryTime.Unix(), ownerId) + ownerRecord.Rank = rankCache.Get(leaderboardId, expiryTime.Unix(), ownerID) return []*api.LeaderboardRecord{ownerRecord}, nil } @@ -540,7 +540,7 @@ func getLeaderboardRecordsHaystack(ctx context.Context, logger *zap.Logger, db * AND expiry_time = $2` // First half. - params := []interface{}{leaderboardId, expiryTime, ownerRecord.Score, ownerRecord.Subscore, ownerId} + params := []interface{}{leaderboardId, expiryTime, ownerRecord.Score, ownerRecord.Subscore, ownerID} firstQuery := query if sortOrder == LeaderboardSortOrderAscending { // Lower score is better, but get in reverse order from current user to get those immediately above. @@ -614,8 +614,8 @@ func parseLeaderboardRecords(logger *zap.Logger, rows *sql.Rows) ([]*api.Leaderb defer rows.Close() records := make([]*api.LeaderboardRecord, 0, 10) - var dbLeaderboardId string - var dbOwnerId string + var dbLeaderboardID string + var dbOwnerID string var dbUsername sql.NullString var dbScore int64 var dbSubscore int64 @@ -626,14 +626,14 @@ func parseLeaderboardRecords(logger *zap.Logger, rows *sql.Rows) ([]*api.Leaderb var dbUpdateTime pgtype.Timestamptz var dbExpiryTime pgtype.Timestamptz for rows.Next() { - if err := rows.Scan(&dbLeaderboardId, &dbOwnerId, &dbUsername, &dbScore, &dbSubscore, &dbNumScore, &dbMaxNumScore, &dbMetadata, &dbCreateTime, &dbUpdateTime, &dbExpiryTime); err != nil { + if err := rows.Scan(&dbLeaderboardID, &dbOwnerID, &dbUsername, &dbScore, &dbSubscore, &dbNumScore, &dbMaxNumScore, &dbMetadata, &dbCreateTime, &dbUpdateTime, &dbExpiryTime); err != nil { logger.Error("Could not execute leaderboard records list query", zap.Error(err)) return nil, err } record := &api.LeaderboardRecord{ - LeaderboardId: dbLeaderboardId, - OwnerId: dbOwnerId, + LeaderboardId: dbLeaderboardID, + OwnerId: dbOwnerID, Score: dbScore, Subscore: dbSubscore, NumScore: dbNumScore, diff --git a/server/core_storage.go b/server/core_storage.go index 356183b47aa62573cdf3b7a491bca6403fac629c..15919da71e4f8bf2d267d80b0201afdd16f9dc40 100644 --- a/server/core_storage.go +++ b/server/core_storage.go @@ -97,17 +97,17 @@ func (s StorageOpDeletes) Less(i, j int) bool { } func StorageListObjects(ctx context.Context, logger *zap.Logger, db *sql.DB, caller uuid.UUID, ownerID *uuid.UUID, collection string, limit int, cursor string) (*api.StorageObjectList, codes.Code, error) { - var sc *storageCursor = nil + var sc *storageCursor if cursor != "" { sc = &storageCursor{} - if cb, err := base64.RawURLEncoding.DecodeString(cursor); err != nil { + cb, err := base64.RawURLEncoding.DecodeString(cursor) + if err != nil { logger.Warn("Could not base64 decode storage cursor.", zap.String("cursor", cursor)) return nil, codes.InvalidArgument, errors.New("Malformed cursor was used.") - } else { - if err := gob.NewDecoder(bytes.NewReader(cb)).Decode(sc); err != nil { - logger.Warn("Could not decode storage cursor.", zap.String("cursor", cursor)) - return nil, codes.InvalidArgument, errors.New("Malformed cursor was used.") - } + } + if err := gob.NewDecoder(bytes.NewReader(cb)).Decode(sc); err != nil { + logger.Warn("Could not decode storage cursor.", zap.String("cursor", cursor)) + return nil, codes.InvalidArgument, errors.New("Malformed cursor was used.") } } @@ -184,10 +184,9 @@ LIMIT $2` if err == sql.ErrNoRows { objects = &api.StorageObjectList{Objects: make([]*api.StorageObject, 0)} return nil - } else { - logger.Error("Could not list storage.", zap.Error(err), zap.String("collection", collection), zap.Int("limit", limit), zap.String("cursor", cursor)) - return err } + logger.Error("Could not list storage.", zap.Error(err), zap.String("collection", collection), zap.Int("limit", limit), zap.String("cursor", cursor)) + return err } // rows.Close() called in storageListObjects @@ -225,10 +224,9 @@ LIMIT $3` if err == sql.ErrNoRows { objects = &api.StorageObjectList{Objects: make([]*api.StorageObject, 0)} return nil - } else { - logger.Error("Could not list storage.", zap.Error(err), zap.String("collection", collection), zap.Int("limit", limit), zap.String("cursor", cursor)) - return err } + logger.Error("Could not list storage.", zap.Error(err), zap.String("collection", collection), zap.Int("limit", limit), zap.String("cursor", cursor)) + return err } // rows.Close() called in storageListObjects @@ -275,10 +273,9 @@ LIMIT $3` if err == sql.ErrNoRows { objects = &api.StorageObjectList{Objects: make([]*api.StorageObject, 0)} return nil - } else { - logger.Error("Could not list storage.", zap.Error(err), zap.String("collection", collection), zap.Int("limit", limit), zap.String("cursor", cursor)) - return err } + logger.Error("Could not list storage.", zap.Error(err), zap.String("collection", collection), zap.Int("limit", limit), zap.String("cursor", cursor)) + return err } // rows.Close() called in storageListObjects @@ -306,10 +303,9 @@ WHERE user_id = $1` if err == sql.ErrNoRows { objects = make([]*api.StorageObject, 0) return nil - } else { - logger.Error("Could not read storage objects.", zap.Error(err), zap.String("user_id", userID.String())) - return err } + logger.Error("Could not read storage objects.", zap.Error(err), zap.String("user_id", userID.String())) + return err } defer rows.Close() @@ -434,10 +430,9 @@ WHERE if err == sql.ErrNoRows { objects = &api.StorageObjects{Objects: make([]*api.StorageObject, 0)} return nil - } else { - logger.Error("Could not read storage objects.", zap.Error(err)) - return err } + logger.Error("Could not read storage objects.", zap.Error(err)) + return err } defer rows.Close() diff --git a/server/core_tournament.go b/server/core_tournament.go index 188536f87596065cc747813bdbca3a062f58056a..4d9db7c2deba877a93be8c54e1f2b1cfc6c9324f 100644 --- a/server/core_tournament.go +++ b/server/core_tournament.go @@ -186,10 +186,9 @@ ON CONFLICT(owner_id, leaderboard_id, expiry_time) DO NOTHING` if err == ErrTournamentMaxSizeReached { logger.Info("Failed to join tournament, reached max size allowed.", zap.String("tournament_id", tournamentId), zap.String("owner", owner), zap.String("username", username)) return err - } else { - logger.Error("Could not join tournament.", zap.Error(err)) - return err } + logger.Error("Could not join tournament.", zap.Error(err)) + return err } logger.Info("Joined tournament.", zap.String("tournament_id", tournamentId), zap.String("owner", owner), zap.String("username", username)) @@ -303,20 +302,20 @@ func TournamentRecordWrite(ctx context.Context, logger *zap.Logger, db *sql.DB, expiryTime := time.Unix(expiryUnix, 0).UTC() - var opSql string + var opSQL string var scoreDelta int64 var subscoreDelta int64 var scoreAbs int64 var subscoreAbs int64 switch leaderboard.Operator { case LeaderboardOperatorIncrement: - opSql = "score = leaderboard_record.score + $5, subscore = leaderboard_record.subscore + $6" + opSQL = "score = leaderboard_record.score + $5, subscore = leaderboard_record.subscore + $6" scoreDelta = score subscoreDelta = subscore scoreAbs = score subscoreAbs = subscore case LeaderboardOperatorSet: - opSql = "score = $5, subscore = $6" + opSQL = "score = $5, subscore = $6" scoreDelta = score subscoreDelta = subscore scoreAbs = score @@ -326,10 +325,10 @@ func TournamentRecordWrite(ctx context.Context, logger *zap.Logger, db *sql.DB, default: if leaderboard.SortOrder == LeaderboardSortOrderAscending { // Lower score is better. - opSql = "score = div((leaderboard_record.score + $5 - abs(leaderboard_record.score - $5)), 2), subscore = div((leaderboard_record.subscore + $6 - abs(leaderboard_record.subscore - $6)), 2)" + opSQL = "score = div((leaderboard_record.score + $5 - abs(leaderboard_record.score - $5)), 2), subscore = div((leaderboard_record.subscore + $6 - abs(leaderboard_record.subscore - $6)), 2)" } else { // Higher score is better. - opSql = "score = div((leaderboard_record.score + $5 + abs(leaderboard_record.score - $5)), 2), subscore = div((leaderboard_record.subscore + $6 + abs(leaderboard_record.subscore - $6)), 2)" + opSQL = "score = div((leaderboard_record.score + $5 + abs(leaderboard_record.score - $5)), 2), subscore = div((leaderboard_record.subscore + $6 + abs(leaderboard_record.subscore - $6)), 2)" } scoreDelta = score subscoreDelta = subscore @@ -356,7 +355,7 @@ func TournamentRecordWrite(ctx context.Context, logger *zap.Logger, db *sql.DB, // There's also no need to increment the number of records tracked for this tournament. query := `UPDATE leaderboard_record - SET ` + opSql + `, num_score = leaderboard_record.num_score + 1, metadata = COALESCE($7, leaderboard_record.metadata), username = COALESCE($3, leaderboard_record.username), update_time = now() + SET ` + opSQL + `, num_score = leaderboard_record.num_score + 1, metadata = COALESCE($7, leaderboard_record.metadata), username = COALESCE($3, leaderboard_record.username), update_time = now() WHERE leaderboard_id = $1 AND owner_id = $2 AND expiry_time = $4 AND (max_num_score = 0 OR num_score < max_num_score)` logger.Debug("Tournament update query", zap.String("query", query), zap.Any("params", params)) res, err := db.ExecContext(ctx, query, params...) @@ -375,7 +374,7 @@ func TournamentRecordWrite(ctx context.Context, logger *zap.Logger, db *sql.DB, query := `INSERT INTO leaderboard_record (leaderboard_id, owner_id, username, score, subscore, metadata, expiry_time, max_num_score) VALUES ($1, $2, $3, $8, $9, COALESCE($7, '{}'::JSONB), $4, $10) ON CONFLICT (owner_id, leaderboard_id, expiry_time) - DO UPDATE SET ` + opSql + `, num_score = leaderboard_record.num_score + 1, metadata = COALESCE($7, leaderboard_record.metadata), update_time = now() + DO UPDATE SET ` + opSQL + `, num_score = leaderboard_record.num_score + 1, metadata = COALESCE($7, leaderboard_record.metadata), update_time = now() RETURNING num_score, max_num_score` params = append(params, scoreAbs, subscoreAbs, leaderboard.MaxNumScore) @@ -514,18 +513,17 @@ func calculateTournamentDeadlines(startTime, endTime, duration int64, resetSched } return startActiveUnix, endActiveUnix, expiryUnix - } else { - endActiveUnix := int64(0) - if startTime <= t.Unix() { - endActiveUnix = startTime + duration - } - expiryUnix := endTime - return startTime, endActiveUnix, expiryUnix } + endActiveUnix := int64(0) + if startTime <= t.Unix() { + endActiveUnix = startTime + duration + } + expiryUnix := endTime + return startTime, endActiveUnix, expiryUnix } func parseTournament(scannable Scannable, now time.Time) (*api.Tournament, error) { - var dbId string + var dbID string var dbSortOrder int var dbResetSchedule sql.NullString var dbMetadata string @@ -539,7 +537,7 @@ func parseTournament(scannable Scannable, now time.Time) (*api.Tournament, error var dbTitle string var dbSize int var dbStartTime pgtype.Timestamptz - err := scannable.Scan(&dbId, &dbSortOrder, &dbResetSchedule, &dbMetadata, &dbCreateTime, + err := scannable.Scan(&dbID, &dbSortOrder, &dbResetSchedule, &dbMetadata, &dbCreateTime, &dbCategory, &dbDescription, &dbDuration, &dbEndTime, &dbMaxSize, &dbMaxNumScore, &dbTitle, &dbSize, &dbStartTime) if err != nil { return nil, err @@ -564,7 +562,7 @@ func parseTournament(scannable Scannable, now time.Time) (*api.Tournament, error } tournament := &api.Tournament{ - Id: dbId, + Id: dbID, Title: dbTitle, Description: dbDescription, Category: uint32(dbCategory), diff --git a/server/core_user.go b/server/core_user.go index 4cd60b69d94a2d1a06198dffad7f917f30b223d9..417dc4fc2f958358250c451cc62598a636dfded5 100644 --- a/server/core_user.go +++ b/server/core_user.go @@ -39,7 +39,7 @@ WHERE` facebookStatements := make([]string, 0, len(fbIDs)) params := make([]interface{}, 0) counter := 1 - useSqlOr := false + useSQLOr := false if len(ids) > 0 { for _, id := range ids { @@ -49,7 +49,7 @@ WHERE` counter++ } query = query + " id IN (" + strings.Join(idStatements, ", ") + ")" - useSqlOr = true + useSQLOr = true } if len(usernames) > 0 { @@ -59,11 +59,11 @@ WHERE` usernameStatements = append(usernameStatements, statement) counter++ } - if useSqlOr { + if useSQLOr { query = query + " OR" } query = query + " username IN (" + strings.Join(usernameStatements, ", ") + ")" - useSqlOr = true + useSQLOr = true } if len(fbIDs) > 0 { @@ -73,7 +73,7 @@ WHERE` facebookStatements = append(facebookStatements, statement) counter++ } - if useSqlOr { + if useSQLOr { query = query + " OR" } query = query + " facebook_id IN (" + strings.Join(facebookStatements, ", ") + ")" diff --git a/server/core_wallet.go b/server/core_wallet.go index 427ae6b2ccdf29d7bcf7b7c03e0d40310c5cc551..1814e8780af70dc6b44b60b18b790df8151f330c 100644 --- a/server/core_wallet.go +++ b/server/core_wallet.go @@ -201,12 +201,12 @@ func UpdateWallets(ctx context.Context, logger *zap.Logger, db *sql.DB, updates func UpdateWalletLedger(ctx context.Context, logger *zap.Logger, db *sql.DB, id uuid.UUID, metadata string) (*walletLedger, error) { // Metadata is expected to already be a valid JSON string. - var userId string + var userID string var changeset sql.NullString var createTime pgtype.Timestamptz var updateTime pgtype.Timestamptz query := "UPDATE wallet_ledger SET update_time = now(), metadata = metadata || $2 WHERE id = $1::UUID RETURNING user_id, changeset, create_time, update_time" - err := db.QueryRowContext(ctx, query, id, metadata).Scan(&userId, &changeset, &createTime, &updateTime) + err := db.QueryRowContext(ctx, query, id, metadata).Scan(&userID, &changeset, &createTime, &updateTime) if err != nil { logger.Error("Error updating user wallet ledger.", zap.String("id", id.String()), zap.Error(err)) return nil, err @@ -220,7 +220,7 @@ func UpdateWalletLedger(ctx context.Context, logger *zap.Logger, db *sql.DB, id } return &walletLedger{ - UserID: userId, + UserID: userID, Changeset: changesetMap, CreateTime: createTime.Time.Unix(), UpdateTime: updateTime.Time.Unix(), diff --git a/server/leaderboard_cache.go b/server/leaderboard_cache.go index d5d3dc5efb75a8bc2835fa853fe1b4ee5fde05f1..623a5acf98808c8df6dc4b857416503890027460 100644 --- a/server/leaderboard_cache.go +++ b/server/leaderboard_cache.go @@ -342,10 +342,9 @@ func (l *LocalLeaderboardCache) CreateTournament(ctx context.Context, id string, if leaderboard.Duration > 0 { // Creation is an idempotent operation. return nil, nil // return nil for leaderboard to indicate no new creation - } else { - l.logger.Error("Cannot create tournament as leaderboard is already in use.", zap.String("leaderboard_id", id)) - return nil, fmt.Errorf("cannot create tournament as leaderboard is already in use") } + l.logger.Error("Cannot create tournament as leaderboard is already in use.", zap.String("leaderboard_id", id)) + return nil, fmt.Errorf("cannot create tournament as leaderboard is already in use") } params := make([]interface{}, 0) diff --git a/server/leaderboard_rank_cache.go b/server/leaderboard_rank_cache.go index 5c64426470086dd83a9b62adf2141744eb4dcd09..70ef9ba84df4a0c1d3cadc56c5945afcfc833a27 100644 --- a/server/leaderboard_rank_cache.go +++ b/server/leaderboard_rank_cache.go @@ -27,10 +27,10 @@ import ( ) type LeaderboardRankCache interface { - Get(leaderboardId string, expiryUnix int64, ownerId uuid.UUID) int64 + Get(leaderboardId string, expiryUnix int64, ownerID uuid.UUID) int64 Fill(leaderboardId string, expiryUnix int64, records []*api.LeaderboardRecord) - Insert(leaderboardId string, expiryUnix int64, sortOrder int, ownerId uuid.UUID, score, subscore int64) int64 - Delete(leaderboardId string, expiryUnix int64, ownerId uuid.UUID) bool + Insert(leaderboardId string, expiryUnix int64, sortOrder int, ownerID uuid.UUID, score, subscore int64) int64 + Delete(leaderboardId string, expiryUnix int64, ownerID uuid.UUID) bool DeleteLeaderboard(leaderboardId string, expiryUnix int64) bool TrimExpired(nowUnix int64) bool } @@ -151,15 +151,15 @@ WHERE leaderboard_id = $1 AND expiry_time = $2` // Process the records. for rows.Next() { - var ownerId string + var ownerID string rankData := &RankData{Rank: int64(len(rankEntries.Ranks) + 1)} - if err = rows.Scan(&ownerId, &rankData.Score, &rankData.Subscore); err != nil { + if err = rows.Scan(&ownerID, &rankData.Score, &rankData.Subscore); err != nil { startupLogger.Fatal("Failed to scan leaderboard rank data", zap.String("leaderboard_id", leaderboard.Id), zap.Error(err)) return nil } - rankData.OwnerId = uuid.Must(uuid.FromString(ownerId)) + rankData.OwnerId = uuid.Must(uuid.FromString(ownerID)) rankEntries.Ranks = append(rankEntries.Ranks, rankData) rankEntries.Haystack[rankData.OwnerId] = rankData @@ -176,7 +176,7 @@ WHERE leaderboard_id = $1 AND expiry_time = $2` return cache } -func (l *LocalLeaderboardRankCache) Get(leaderboardId string, expiryUnix int64, ownerId uuid.UUID) int64 { +func (l *LocalLeaderboardRankCache) Get(leaderboardId string, expiryUnix int64, ownerID uuid.UUID) int64 { if l.blacklistAll { // If all rank caching is disabled. return 0 @@ -197,7 +197,7 @@ func (l *LocalLeaderboardRankCache) Get(leaderboardId string, expiryUnix int64, // Find rank data for this owner. rankMap.RLock() - rankData, ok := rankMap.Haystack[ownerId] + rankData, ok := rankMap.Haystack[ownerID] if !ok { rankMap.RUnlock() return 0 @@ -242,7 +242,7 @@ func (l *LocalLeaderboardRankCache) Fill(leaderboardId string, expiryUnix int64, rankMap.RUnlock() } -func (l *LocalLeaderboardRankCache) Insert(leaderboardId string, expiryUnix int64, sortOrder int, ownerId uuid.UUID, score, subscore int64) int64 { +func (l *LocalLeaderboardRankCache) Insert(leaderboardId string, expiryUnix int64, sortOrder int, ownerID uuid.UUID, score, subscore int64) int64 { if l.blacklistAll { // If all rank caching is disabled. return 0 @@ -276,15 +276,15 @@ func (l *LocalLeaderboardRankCache) Insert(leaderboardId string, expiryUnix int6 // Insert or update the score. rankMap.Lock() - rankData, ok := rankMap.Haystack[ownerId] + rankData, ok := rankMap.Haystack[ownerID] if !ok { rankData = &RankData{ - OwnerId: ownerId, + OwnerId: ownerID, Score: score, Subscore: subscore, Rank: int64(len(rankMap.Ranks) + 1), } - rankMap.Haystack[ownerId] = rankData + rankMap.Haystack[ownerID] = rankData rankMap.Ranks = append(rankMap.Ranks, rankData) } else { rankData.Score = score @@ -299,7 +299,7 @@ func (l *LocalLeaderboardRankCache) Insert(leaderboardId string, expiryUnix int6 return rank } -func (l *LocalLeaderboardRankCache) Delete(leaderboardId string, expiryUnix int64, ownerId uuid.UUID) bool { +func (l *LocalLeaderboardRankCache) Delete(leaderboardId string, expiryUnix int64, ownerID uuid.UUID) bool { if l.blacklistAll { // If all rank caching is disabled. return false @@ -322,14 +322,14 @@ func (l *LocalLeaderboardRankCache) Delete(leaderboardId string, expiryUnix int6 // Delete rank data for this owner. rankMap.Lock() - rankData, ok := rankMap.Haystack[ownerId] + rankData, ok := rankMap.Haystack[ownerID] if !ok { // No rank data. rankMap.Unlock() return true } - delete(rankMap.Haystack, ownerId) + delete(rankMap.Haystack, ownerID) rank := rankData.Rank totalRanks := len(rankMap.Ranks) @@ -387,7 +387,7 @@ func (l *LocalLeaderboardRankCache) TrimExpired(nowUnix int64) bool { // Used for the timer. l.Lock() - for k, _ := range l.cache { + for k := range l.cache { if k.Expiry <= nowUnix { delete(l.cache, k) } diff --git a/server/logger.go b/server/logger.go index f9e9639443c88ba2e158b0215c629f0f6afd690c..71ad83bef46dde7058f73035aa909b306691c8ea 100644 --- a/server/logger.go +++ b/server/logger.go @@ -75,10 +75,9 @@ func SetupLogging(tmpLogger *zap.Logger, config Config) (*zap.Logger, *zap.Logge if config.GetLogger().Stdout { zap.RedirectStdLog(multiLogger) return multiLogger, multiLogger - } else { - zap.RedirectStdLog(fileLogger) - return fileLogger, multiLogger } + zap.RedirectStdLog(fileLogger) + return fileLogger, multiLogger } zap.RedirectStdLog(consoleLogger) diff --git a/server/message_router.go b/server/message_router.go index 181d604454e85c6f55ee743d8d4e840cdcb765fc..d857be8a87b0c7668e9af98d2c7f553f45704bbe 100644 --- a/server/message_router.go +++ b/server/message_router.go @@ -58,7 +58,7 @@ func (r *LocalMessageRouter) SendToPresenceIDs(logger *zap.Logger, presenceIDs [ // Prepare payload variables but do not initialize until we hit a session that needs them to avoid unnecessary work. var payloadProtobuf []byte - var payloadJson []byte + var payloadJSON []byte for _, presenceID := range presenceIDs { session := r.sessionRegistry.Get(presenceID.SessionID) @@ -82,17 +82,17 @@ func (r *LocalMessageRouter) SendToPresenceIDs(logger *zap.Logger, presenceIDs [ case SessionFormatJson: fallthrough default: - if payloadJson == nil { + if payloadJSON == nil { // Marshal the payload now that we know this format is needed. var buf bytes.Buffer if err = r.jsonpbMarshaler.Marshal(&buf, envelope); err == nil { - payloadJson = buf.Bytes() + payloadJSON = buf.Bytes() } else { logger.Error("Could not marshal message", zap.Error(err)) return } } - err = session.SendBytes(payloadJson, reliable) + err = session.SendBytes(payloadJSON, reliable) } if err != nil { logger.Error("Failed to route message", zap.String("sid", presenceID.SessionID.String()), zap.Error(err)) diff --git a/server/metrics.go b/server/metrics.go index bd471342957882d5db7a9b64c72f9d6d49777e56..06b3bb34b029b000bc393a640abf8c57a042b119 100644 --- a/server/metrics.go +++ b/server/metrics.go @@ -37,8 +37,8 @@ var ( MetricsSocketWsTimeSpentMsec = stats.Float64("nakama.socket/ws/server_elapsed_time", "Elapsed time in msecs spent in WebSocket connections", stats.UnitMilliseconds) MetricsSocketWsOpenCount = stats.Int64("nakama.socket/ws/open_count", "Number of opened WebSocket connections", stats.UnitDimensionless) MetricsSocketWsCloseCount = stats.Int64("nakama.socket/ws/close_count", "Number of closed WebSocket connections", stats.UnitDimensionless) - MetricsApiTimeSpentMsec = stats.Float64("nakama.api/server/server_elapsed_time", "Elapsed time in msecs spent in API functions", stats.UnitMilliseconds) - MetricsApiCount = stats.Int64("nakama.api/server/request_count", "Number of calls to API functions", stats.UnitDimensionless) + MetricsAPITimeSpentMsec = stats.Float64("nakama.api/server/server_elapsed_time", "Elapsed time in msecs spent in API functions", stats.UnitMilliseconds) + MetricsAPICount = stats.Int64("nakama.api/server/request_count", "Number of calls to API functions", stats.UnitDimensionless) MetricsRtapiTimeSpentMsec = stats.Float64("nakama.rtapi/server/server_elapsed_time", "Elapsed time in msecs spent in realtime socket functions", stats.UnitMilliseconds) MetricsRtapiCount = stats.Int64("nakama.rtapi/server/request_count", "Number of calls to realtime socket functions", stats.UnitDimensionless) @@ -99,7 +99,7 @@ func NewMetrics(logger, startupLogger *zap.Logger, config Config, metricsExporte Name: "nakama.api/server/server_elapsed_time", Description: "Elapsed time in msecs spent in API functions", TagKeys: []tag.Key{MetricsFunction}, - Measure: MetricsApiTimeSpentMsec, + Measure: MetricsAPITimeSpentMsec, Aggregation: ocgrpc.DefaultMillisecondsDistribution, }); err != nil { startupLogger.Fatal("Error subscribing api elapsed time metrics view", zap.Error(err)) @@ -108,7 +108,7 @@ func NewMetrics(logger, startupLogger *zap.Logger, config Config, metricsExporte Name: "nakama.api/server/request_count", Description: "Number of calls to API functions", TagKeys: []tag.Key{MetricsFunction}, - Measure: MetricsApiCount, + Measure: MetricsAPICount, Aggregation: view.Count(), }); err != nil { startupLogger.Fatal("Error subscribing api request count metrics view", zap.Error(err)) diff --git a/server/pipeline_channel.go b/server/pipeline_channel.go index dde9ba9eb4f79689b5893400482e3e480f2e2032..8b12b666d08935a0e0d48c0a2fa784736aa9ca2b 100644 --- a/server/pipeline_channel.go +++ b/server/pipeline_channel.go @@ -179,7 +179,7 @@ func (p *Pipeline) channelJoin(logger *zap.Logger, session Session, envelope *rt return } - channelId, err := StreamToChannelId(stream) + channelID, err := StreamToChannelId(stream) if err != nil { // Should not happen after the input validation above, but guard just in case. logger.Error("Error converting stream to channel identifier", zap.Error(err), zap.Any("stream", stream)) @@ -231,8 +231,8 @@ func (p *Pipeline) channelJoin(logger *zap.Logger, session Session, envelope *rt logger.Warn("Failed to send channel direct message notification", zap.Error(e)) } else { notifications := map[uuid.UUID][]*api.Notification{ - otherUserID: []*api.Notification{ - &api.Notification{ + otherUserID: { + { Id: uuid.Must(uuid.NewV4()).String(), Subject: fmt.Sprintf("%v wants to chat", session.Username()), Content: string(content), @@ -266,7 +266,7 @@ func (p *Pipeline) channelJoin(logger *zap.Logger, session Session, envelope *rt } channel := &rtapi.Channel{ - Id: channelId, + Id: channelID, Presences: userPresences, Self: &rtapi.UserPresence{ UserId: session.UserID().String(), @@ -467,14 +467,13 @@ func (p *Pipeline) channelMessageUpdate(logger *zap.Logger, session Session, env Message: "Could not find message to update in channel history", }}}, true) return - } else { - logger.Error("Error persisting channel message update", zap.Error(err)) - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ - Code: int32(rtapi.Error_RUNTIME_EXCEPTION), - Message: "Could not persist message update to channel history", - }}}, true) - return } + logger.Error("Error persisting channel message update", zap.Error(err)) + session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + Code: int32(rtapi.Error_RUNTIME_EXCEPTION), + Message: "Could not persist message update to channel history", + }}}, true) + return } // Replace the message create time with the real one from DB. message.CreateTime = ×tamp.Timestamp{Seconds: dbCreateTime.Time.Unix()} @@ -567,14 +566,13 @@ func (p *Pipeline) channelMessageRemove(logger *zap.Logger, session Session, env Message: "Could not find message to remove in channel history", }}}, true) return - } else { - logger.Error("Error persisting channel message remove", zap.Error(err)) - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ - Code: int32(rtapi.Error_RUNTIME_EXCEPTION), - Message: "Could not persist message remove to channel history", - }}}, true) - return } + logger.Error("Error persisting channel message remove", zap.Error(err)) + session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + Code: int32(rtapi.Error_RUNTIME_EXCEPTION), + Message: "Could not persist message remove to channel history", + }}}, true) + return } // Replace the message create time with the real one from DB. message.CreateTime = ×tamp.Timestamp{Seconds: dbCreateTime.Time.Unix()} diff --git a/server/pipeline_matchmaker.go b/server/pipeline_matchmaker.go index 1682ce9494ad0d1509785f92f5255f61accfdcc4..7d45a3cf42c32a3e1c4a844cea08c4d38da01c40 100644 --- a/server/pipeline_matchmaker.go +++ b/server/pipeline_matchmaker.go @@ -125,7 +125,7 @@ func (p *Pipeline) matchmakerAdd(logger *zap.Logger, session Session, envelope * outgoing.GetMatchmakerMatched().Ticket = entry.Ticket // Route outgoing message. - p.router.SendToPresenceIDs(logger, []*PresenceID{&PresenceID{Node: entry.Presence.Node, SessionID: entry.SessionID}}, outgoing, true) + p.router.SendToPresenceIDs(logger, []*PresenceID{{Node: entry.Presence.Node, SessionID: entry.SessionID}}, outgoing, true) } } diff --git a/server/pipeline_status.go b/server/pipeline_status.go index e74db3675fc5482877e1363f6af10765d0ac6d88..018dc7dee7134e748d153ff862e3779a3af249f0 100644 --- a/server/pipeline_status.go +++ b/server/pipeline_status.go @@ -67,7 +67,7 @@ func (p *Pipeline) statusFollow(logger *zap.Logger, session Session, envelope *r if len(uniqueUsernames) == 0 { params := make([]interface{}, 0, len(uniqueUserIDs)) statements := make([]string, 0, len(uniqueUserIDs)) - for userID, _ := range uniqueUserIDs { + for userID := range uniqueUserIDs { params = append(params, userID) statements = append(statements, "$"+strconv.Itoa(len(params))+"::UUID") } @@ -100,7 +100,7 @@ func (p *Pipeline) statusFollow(logger *zap.Logger, session Session, envelope *r params := make([]interface{}, 0, len(uniqueUserIDs)) statements := make([]string, 0, len(uniqueUserIDs)) - for userID, _ := range uniqueUserIDs { + for userID := range uniqueUserIDs { params = append(params, userID) statements = append(statements, "$"+strconv.Itoa(len(params))+"::UUID") } @@ -109,7 +109,7 @@ func (p *Pipeline) statusFollow(logger *zap.Logger, session Session, envelope *r statements = make([]string, 0, len(uniqueUsernames)) } - for username, _ := range uniqueUsernames { + for username := range uniqueUsernames { params = append(params, username) statements = append(statements, "$"+strconv.Itoa(len(params))) } @@ -170,7 +170,7 @@ func (p *Pipeline) statusFollow(logger *zap.Logger, session Session, envelope *r // Follow all of the validated user IDs, and prepare a list of current presences to return. presences := make([]*rtapi.UserPresence, 0, len(followUserIDs)) - for userID, _ := range followUserIDs { + for userID := range followUserIDs { stream := PresenceStream{Mode: StreamModeStatus, Subject: userID} success, _ := p.tracker.Track(session.ID(), stream, session.UserID(), PresenceMeta{Format: session.Format(), Username: session.Username(), Hidden: true}, false) if !success { diff --git a/server/runtime.go b/server/runtime.go index 22d38e8c5351d37061e4a9e1a5c8ec7efd14ca6b..4ea70bc6af7524428716c90b34b352c8abab5f7c 100644 --- a/server/runtime.go +++ b/server/runtime.go @@ -439,13 +439,13 @@ func NewRuntime(logger, startupLogger *zap.Logger, db *sql.DB, jsonpbMarshaler * eventQueue := NewRuntimeEventQueue(logger, config) startupLogger.Info("Runtime event queue processor started", zap.Int("size", config.GetRuntime().EventQueueSize), zap.Int("workers", config.GetRuntime().EventQueueWorkers)) - goModules, goRpcFunctions, goBeforeRtFunctions, goAfterRtFunctions, goBeforeReqFunctions, goAfterReqFunctions, goMatchmakerMatchedFunction, goMatchCreateFn, goTournamentEndFunction, goTournamentResetFunction, goLeaderboardResetFunction, allEventFunctions, goSetMatchCreateFn, goMatchNamesListFn, err := NewRuntimeProviderGo(logger, startupLogger, db, jsonpbMarshaler, config, socialClient, leaderboardCache, leaderboardRankCache, leaderboardScheduler, sessionRegistry, matchRegistry, tracker, streamManager, router, runtimeConfig.Path, paths, eventQueue) + goModules, goRPCFunctions, goBeforeRtFunctions, goAfterRtFunctions, goBeforeReqFunctions, goAfterReqFunctions, goMatchmakerMatchedFunction, goMatchCreateFn, goTournamentEndFunction, goTournamentResetFunction, goLeaderboardResetFunction, allEventFunctions, goSetMatchCreateFn, goMatchNamesListFn, err := NewRuntimeProviderGo(logger, startupLogger, db, jsonpbMarshaler, config, socialClient, leaderboardCache, leaderboardRankCache, leaderboardScheduler, sessionRegistry, matchRegistry, tracker, streamManager, router, runtimeConfig.Path, paths, eventQueue) if err != nil { startupLogger.Error("Error initialising Go runtime provider", zap.Error(err)) return nil, err } - luaModules, luaRpcFunctions, luaBeforeRtFunctions, luaAfterRtFunctions, luaBeforeReqFunctions, luaAfterReqFunctions, luaMatchmakerMatchedFunction, allMatchCreateFn, luaTournamentEndFunction, luaTournamentResetFunction, luaLeaderboardResetFunction, err := NewRuntimeProviderLua(logger, startupLogger, db, jsonpbMarshaler, jsonpbUnmarshaler, config, socialClient, leaderboardCache, leaderboardRankCache, leaderboardScheduler, sessionRegistry, matchRegistry, tracker, streamManager, router, goMatchCreateFn, runtimeConfig.Path, paths) + luaModules, luaRPCFunctions, luaBeforeRtFunctions, luaAfterRtFunctions, luaBeforeReqFunctions, luaAfterReqFunctions, luaMatchmakerMatchedFunction, allMatchCreateFn, luaTournamentEndFunction, luaTournamentResetFunction, luaLeaderboardResetFunction, err := NewRuntimeProviderLua(logger, startupLogger, db, jsonpbMarshaler, jsonpbUnmarshaler, config, socialClient, leaderboardCache, leaderboardRankCache, leaderboardScheduler, sessionRegistry, matchRegistry, tracker, streamManager, router, goMatchCreateFn, runtimeConfig.Path, paths) if err != nil { startupLogger.Error("Error initialising Lua runtime provider", zap.Error(err)) return nil, err @@ -470,13 +470,13 @@ func NewRuntime(logger, startupLogger *zap.Logger, db *sql.DB, jsonpbMarshaler * startupLogger.Info("Registered event function invocation", zap.String("id", "session_end")) } - allRpcFunctions := make(map[string]RuntimeRpcFunction, len(goRpcFunctions)+len(luaRpcFunctions)) - for id, fn := range luaRpcFunctions { - allRpcFunctions[id] = fn + allRPCFunctions := make(map[string]RuntimeRpcFunction, len(goRPCFunctions)+len(luaRPCFunctions)) + for id, fn := range luaRPCFunctions { + allRPCFunctions[id] = fn startupLogger.Info("Registered Lua runtime RPC function invocation", zap.String("id", id)) } - for id, fn := range goRpcFunctions { - allRpcFunctions[id] = fn + for id, fn := range goRPCFunctions { + allRPCFunctions[id] = fn startupLogger.Info("Registered Go runtime RPC function invocation", zap.String("id", id)) } @@ -1350,7 +1350,7 @@ func NewRuntime(logger, startupLogger *zap.Logger, db *sql.DB, jsonpbMarshaler * return &Runtime{ matchCreateFunction: allMatchCreateFn, - rpcFunctions: allRpcFunctions, + rpcFunctions: allRPCFunctions, beforeRtFunctions: allBeforeRtFunctions, afterRtFunctions: allAfterRtFunctions, beforeReqFunctions: allBeforeReqFunctions, diff --git a/server/runtime_go.go b/server/runtime_go.go index 8d13df366bf8bf97219c39be8c47a34d8d8e2d3f..ee53f44266d12543e3da97b994c9e25de7283a49 100644 --- a/server/runtime_go.go +++ b/server/runtime_go.go @@ -1779,7 +1779,7 @@ func NewRuntimeProviderGo(logger, startupLogger *zap.Logger, db *sql.DB, jsonpbM matchNamesListFn := func() []string { matchLock.RLock() matchNames := make([]string, 0, len(match)) - for name, _ := range match { + for name := range match { matchNames = append(matchNames, name) } matchLock.RUnlock() diff --git a/server/runtime_go_nakama.go b/server/runtime_go_nakama.go index 4222b1e53411e6a7d835d6be81dcabcebe886b23..4ed1fe69db460f3d6616e8b31d5b38749fb2ec49 100644 --- a/server/runtime_go_nakama.go +++ b/server/runtime_go_nakama.go @@ -969,7 +969,7 @@ func (n *RuntimeGoNakamaModule) WalletUpdate(ctx context.Context, userID string, } } - return UpdateWallets(ctx, n.logger, n.db, []*walletUpdate{&walletUpdate{ + return UpdateWallets(ctx, n.logger, n.db, []*walletUpdate{{ UserID: uid, Changeset: changeset, Metadata: string(metadataBytes), @@ -1264,9 +1264,8 @@ func (n *RuntimeGoNakamaModule) LeaderboardRecordsList(ctx context.Context, id s var limitWrapper *wrappers.Int32Value if limit < 0 || limit > 10000 { return nil, nil, "", "", errors.New("expects limit to be 0-10000") - } else { - limitWrapper = &wrappers.Int32Value{Value: int32(limit)} } + limitWrapper = &wrappers.Int32Value{Value: int32(limit)} if expiry < 0 { return nil, nil, "", "", errors.New("expects expiry to equal or greater than 0") @@ -1457,13 +1456,13 @@ func (n *RuntimeGoNakamaModule) TournamentList(ctx context.Context, categoryStar var cursorPtr *tournamentListCursor if cursor != "" { - if cb, err := base64.StdEncoding.DecodeString(cursor); err != nil { + cb, err := base64.StdEncoding.DecodeString(cursor) + if err != nil { + return nil, errors.New("expects cursor to be valid when provided") + } + cursorPtr = &tournamentListCursor{} + if err := gob.NewDecoder(bytes.NewReader(cb)).Decode(cursorPtr); err != nil { return nil, errors.New("expects cursor to be valid when provided") - } else { - cursorPtr = &tournamentListCursor{} - if err := gob.NewDecoder(bytes.NewReader(cb)).Decode(cursorPtr); err != nil { - return nil, errors.New("expects cursor to be valid when provided") - } } } @@ -1598,9 +1597,9 @@ func (n *RuntimeGoNakamaModule) GroupUpdate(ctx context.Context, id, name, creat descriptionWrapper = &wrappers.StringValue{Value: description} } - var avatarUrlWrapper *wrappers.StringValue + var avatarURLWrapper *wrappers.StringValue if avatarUrl != "" { - avatarUrlWrapper = &wrappers.StringValue{Value: avatarUrl} + avatarURLWrapper = &wrappers.StringValue{Value: avatarUrl} } openWrapper := &wrappers.BoolValue{Value: open} @@ -1619,7 +1618,7 @@ func (n *RuntimeGoNakamaModule) GroupUpdate(ctx context.Context, id, name, creat maxCountValue = maxCount } - return UpdateGroup(ctx, n.logger, n.db, groupID, uuid.Nil, creator, nameWrapper, langTagWrapper, descriptionWrapper, avatarUrlWrapper, metadataWrapper, openWrapper, maxCountValue) + return UpdateGroup(ctx, n.logger, n.db, groupID, uuid.Nil, creator, nameWrapper, langTagWrapper, descriptionWrapper, avatarURLWrapper, metadataWrapper, openWrapper, maxCountValue) } func (n *RuntimeGoNakamaModule) GroupDelete(ctx context.Context, id string) error { diff --git a/server/runtime_lua.go b/server/runtime_lua.go index 21a24520fc5a4c15645f233f9fcbd4945b3c821e..64404f277c46c3357354c74c48497cfbd8df367f 100644 --- a/server/runtime_lua.go +++ b/server/runtime_lua.go @@ -184,8 +184,8 @@ func NewRuntimeProviderLua(logger, startupLogger *zap.Logger, db *sql.DB, jsonpb return runtimeProviderLua.BeforeRt(ctx, id, logger, userID, username, vars, expiry, sessionID, clientIP, clientPort, envelope) } } else if strings.HasPrefix(id, strings.ToLower(API_PREFIX)) { - shortId := strings.TrimPrefix(id, strings.ToLower(API_PREFIX)) - switch shortId { + shortID := strings.TrimPrefix(id, strings.ToLower(API_PREFIX)) + switch shortID { case "getaccount": beforeReqFunctions.beforeGetAccountFunction = func(ctx context.Context, logger *zap.Logger, userID, username string, vars map[string]string, expiry int64, clientIP, clientPort string) (error, codes.Code) { _, err, code := runtimeProviderLua.BeforeReq(ctx, id, logger, userID, username, vars, expiry, clientIP, clientPort, nil) @@ -650,8 +650,8 @@ func NewRuntimeProviderLua(logger, startupLogger *zap.Logger, db *sql.DB, jsonpb return runtimeProviderLua.AfterRt(ctx, id, logger, userID, username, vars, expiry, sessionID, clientIP, clientPort, envelope) } } else if strings.HasPrefix(id, strings.ToLower(API_PREFIX)) { - shortId := strings.TrimPrefix(id, strings.ToLower(API_PREFIX)) - switch shortId { + shortID := strings.TrimPrefix(id, strings.ToLower(API_PREFIX)) + switch shortID { case "getaccount": afterReqFunctions.afterGetAccountFunction = func(ctx context.Context, logger *zap.Logger, userID, username string, vars map[string]string, expiry int64, clientIP, clientPort string, out *api.Account) error { return runtimeProviderLua.AfterReq(ctx, id, logger, userID, username, vars, expiry, clientIP, clientPort, out, nil) @@ -1029,21 +1029,20 @@ func (rp *RuntimeProviderLua) Rpc(ctx context.Context, id string, queryParams ma } } return "", errors.New(msg), code - } else { - return "", fnErr, code } + return "", fnErr, code } if result == nil { return "", nil, 0 } - if payload, ok := result.(string); !ok { + payload, ok := result.(string) + if !ok { rp.logger.Warn("Lua runtime function returned invalid data", zap.Any("result", result)) return "", errors.New("Runtime function returned invalid data - only allowed one return value of type String/Byte."), codes.Internal - } else { - return payload, nil, 0 } + return payload, nil, 0 } func (rp *RuntimeProviderLua) BeforeRt(ctx context.Context, id string, logger *zap.Logger, userID, username string, vars map[string]string, expiry int64, sessionID, clientIP, clientPort string, envelope *rtapi.Envelope) (*rtapi.Envelope, error) { @@ -1089,9 +1088,8 @@ func (rp *RuntimeProviderLua) BeforeRt(ctx context.Context, id string, logger *z } } return nil, errors.New(msg) - } else { - return nil, fnErr } + return nil, fnErr } if result == nil { @@ -1155,9 +1153,8 @@ func (rp *RuntimeProviderLua) AfterRt(ctx context.Context, id string, logger *za } } return errors.New(msg) - } else { - return fnErr } + return fnErr } return nil @@ -1217,9 +1214,8 @@ func (rp *RuntimeProviderLua) BeforeReq(ctx context.Context, id string, logger * } } return nil, errors.New(msg), code - } else { - return nil, fnErr, code } + return nil, fnErr, code } if result == nil || reqMap == nil { @@ -1317,9 +1313,8 @@ func (rp *RuntimeProviderLua) AfterReq(ctx context.Context, id string, logger *z } } return errors.New(msg) - } else { - return fnErr } + return fnErr } return nil @@ -1646,10 +1641,9 @@ func (r *RuntimeLua) loadModules(moduleCache *RuntimeLuaModuleCache) error { if err != nil { r.logger.Error("Could not load module", zap.String("name", module.Path), zap.Error(err)) return err - } else { - r.vm.SetField(preload, module.Name, f) - fns[module.Name] = f } + r.vm.SetField(preload, module.Name, f) + fns[module.Name] = f } for _, name := range moduleCache.Names { @@ -1810,9 +1804,8 @@ func checkRuntimeLuaVM(logger *zap.Logger, config Config, stdLibs map[string]lua if err != nil { logger.Error("Could not load module", zap.String("name", module.Path), zap.Error(err)) return err - } else { - vm.SetField(preload, module.Name, f) } + vm.SetField(preload, module.Name, f) } return nil diff --git a/server/runtime_lua_context.go b/server/runtime_lua_context.go index 382fca497f8ec2c5a9125af9ee33ad81173a71f5..1f9966d8ba283549ae7a2b70e779c407092c781f 100644 --- a/server/runtime_lua_context.go +++ b/server/runtime_lua_context.go @@ -203,14 +203,13 @@ func RuntimeLuaConvertLuaValue(lv lua.LValue) interface{} { ret[keyStr] = RuntimeLuaConvertLuaValue(value) }) return ret - } else { - // Array. - ret := make([]interface{}, 0, maxn) - for i := 1; i <= maxn; i++ { - ret = append(ret, RuntimeLuaConvertLuaValue(v.RawGetInt(i))) - } - return ret } + // Array. + ret := make([]interface{}, 0, maxn) + for i := 1; i <= maxn; i++ { + ret = append(ret, RuntimeLuaConvertLuaValue(v.RawGetInt(i))) + } + return ret default: return v } diff --git a/server/runtime_lua_match_core.go b/server/runtime_lua_match_core.go index 0d072d76488e06913ad471d652f78e4153b745f8..2ba8c04651bf7cb1698ee898385f653ae07df642 100644 --- a/server/runtime_lua_match_core.go +++ b/server/runtime_lua_match_core.go @@ -104,12 +104,12 @@ func NewRuntimeLuaMatchCore(logger *zap.Logger, db *sql.DB, jsonpbMarshaler *jso // Extract the expected function references. var tab *lua.LTable - if t := vm.Get(-1); t.Type() != lua.LTTable { + t := vm.Get(-1) + if t.Type() != lua.LTTable { ctxCancelFn() return nil, errors.New("match module must return a table containing the match callback functions") - } else { - tab = t.(*lua.LTable) } + tab = t.(*lua.LTable) initFn := tab.RawGet(lua.LString("match_init")) if initFn.Type() != lua.LTFunction { ctxCancelFn() diff --git a/server/runtime_lua_nakama.go b/server/runtime_lua_nakama.go index 277beee6bfbb50a58364d99b39f08b0233a68cec..5df70bc768c99aaa422098e9bcf0ee80c42902df 100644 --- a/server/runtime_lua_nakama.go +++ b/server/runtime_lua_nakama.go @@ -580,7 +580,7 @@ func (n *RuntimeLuaNakamaModule) sqlQuery(l *lua.LState) int { for rows.Next() { resultRowValues := make([]interface{}, resultColumnCount) resultRowPointers := make([]interface{}, resultColumnCount) - for i, _ := range resultRowValues { + for i := range resultRowValues { resultRowPointers[i] = &resultRowValues[i] } if err = rows.Scan(resultRowPointers...); err != nil { @@ -673,12 +673,12 @@ func (n *RuntimeLuaNakamaModule) httpRequest(l *lua.LState) int { // Apply any request headers. httpHeaders := RuntimeLuaConvertLuaTable(headers) for k, v := range httpHeaders { - if vs, ok := v.(string); !ok { + vs, ok := v.(string) + if !ok { l.RaiseError("HTTP header values must be strings") return 0 - } else { - req.Header.Add(k, vs) } + req.Header.Add(k, vs) } // Execute the request. resp, err := n.client.Do(req) @@ -1348,8 +1348,8 @@ func (n *RuntimeLuaNakamaModule) authenticateGameCenter(l *lua.LState) int { l.ArgError(5, "expects signature string") return 0 } - publicKeyUrl := l.CheckString(6) - if publicKeyUrl == "" { + publicKeyURL := l.CheckString(6) + if publicKeyURL == "" { l.ArgError(6, "expects public key URL string") return 0 } @@ -1369,7 +1369,7 @@ func (n *RuntimeLuaNakamaModule) authenticateGameCenter(l *lua.LState) int { // Parse create flag, if any. create := l.OptBool(8, true) - dbUserID, dbUsername, created, err := AuthenticateGameCenter(l.Context(), n.logger, n.db, n.socialClient, playerID, bundleID, ts, salt, signature, publicKeyUrl, username, create) + dbUserID, dbUsername, created, err := AuthenticateGameCenter(l.Context(), n.logger, n.db, n.socialClient, playerID, bundleID, ts, salt, signature, publicKeyURL, username, create) if err != nil { l.RaiseError("error authenticating: %v", err.Error()) return 0 @@ -1856,12 +1856,12 @@ func (n *RuntimeLuaNakamaModule) usersGetUsername(l *lua.LState) int { // Input individual ID validation. usernameStrings := make([]string, 0, len(usernames)) for _, u := range usernames { - if us, ok := u.(string); !ok || us == "" { + us, ok := u.(string) + if !ok || us == "" { l.ArgError(1, "each username must be a string") return 0 - } else { - usernameStrings = append(usernameStrings, us) } + usernameStrings = append(usernameStrings, us) } // Get the user accounts. @@ -3426,7 +3426,7 @@ func (n *RuntimeLuaNakamaModule) walletUpdate(l *lua.LState) int { updateLedger := l.OptBool(4, true) - if err = UpdateWallets(l.Context(), n.logger, n.db, []*walletUpdate{&walletUpdate{ + if err = UpdateWallets(l.Context(), n.logger, n.db, []*walletUpdate{{ UserID: userID, Changeset: changesetMap, Metadata: string(metadataBytes), @@ -4338,8 +4338,8 @@ func (n *RuntimeLuaNakamaModule) leaderboardRecordWrite(l *lua.LState) int { return 0 } - ownerId := l.CheckString(2) - if _, err := uuid.FromString(ownerId); err != nil { + ownerID := l.CheckString(2) + if _, err := uuid.FromString(ownerID); err != nil { l.ArgError(2, "expects owner ID to be a valid identifier") return 0 } @@ -4370,7 +4370,7 @@ func (n *RuntimeLuaNakamaModule) leaderboardRecordWrite(l *lua.LState) int { metadataStr = string(metadataBytes) } - record, err := LeaderboardRecordWrite(l.Context(), n.logger, n.db, n.leaderboardCache, n.rankCache, uuid.Nil, id, ownerId, username, score, subscore, metadataStr) + record, err := LeaderboardRecordWrite(l.Context(), n.logger, n.db, n.leaderboardCache, n.rankCache, uuid.Nil, id, ownerID, username, score, subscore, metadataStr) if err != nil { l.RaiseError("error writing leaderboard record: %v", err.Error()) return 0 @@ -4416,13 +4416,13 @@ func (n *RuntimeLuaNakamaModule) leaderboardRecordDelete(l *lua.LState) int { return 0 } - ownerId := l.CheckString(2) - if _, err := uuid.FromString(ownerId); err != nil { + ownerID := l.CheckString(2) + if _, err := uuid.FromString(ownerID); err != nil { l.ArgError(2, "expects owner ID to be a valid identifier") return 0 } - if err := LeaderboardRecordDelete(l.Context(), n.logger, n.db, n.leaderboardCache, n.rankCache, uuid.Nil, id, ownerId); err != nil { + if err := LeaderboardRecordDelete(l.Context(), n.logger, n.db, n.leaderboardCache, n.rankCache, uuid.Nil, id, ownerID); err != nil { l.RaiseError("error deleting leaderboard record: %v", err.Error()) } return 0 @@ -4630,15 +4630,15 @@ func (n *RuntimeLuaNakamaModule) tournamentList(l *lua.LState) int { var cursor *tournamentListCursor cursorStr := l.OptString(6, "") if cursorStr != "" { - if cb, err := base64.StdEncoding.DecodeString(cursorStr); err != nil { + cb, err := base64.StdEncoding.DecodeString(cursorStr) + if err != nil { + l.ArgError(6, "expects cursor to be valid when provided") + return 0 + } + cursor = &tournamentListCursor{} + if err := gob.NewDecoder(bytes.NewReader(cb)).Decode(cursor); err != nil { l.ArgError(6, "expects cursor to be valid when provided") return 0 - } else { - cursor = &tournamentListCursor{} - if err := gob.NewDecoder(bytes.NewReader(cb)).Decode(cursor); err != nil { - l.ArgError(6, "expects cursor to be valid when provided") - return 0 - } } } diff --git a/server/runtime_lua_utils.go b/server/runtime_lua_utils.go index 2a984595b678bb778dca182ee489fa82d6ebd2e6..80ad7b9a7940fcef157ec42904081d03b5dd4c4f 100644 --- a/server/runtime_lua_utils.go +++ b/server/runtime_lua_utils.go @@ -57,22 +57,21 @@ func (fs *flagScanner) Next() (byte, bool) { fs.AppendString(fs.end) } return c, true - } else { - c = fs.str[fs.Pos] - if c == fs.flag { - if fs.Pos < (fs.Length-1) && fs.str[fs.Pos+1] == fs.flag { - fs.HasFlag = false - fs.AppendChar(fs.flag) - fs.Pos += 2 - return fs.Next() - } else if fs.Pos != fs.Length-1 { - if fs.HasFlag { - fs.AppendString(fs.end) - } - fs.AppendString(fs.start) - fs.ChangeFlag = true - fs.HasFlag = true + } + c = fs.str[fs.Pos] + if c == fs.flag { + if fs.Pos < (fs.Length-1) && fs.str[fs.Pos+1] == fs.flag { + fs.HasFlag = false + fs.AppendChar(fs.flag) + fs.Pos += 2 + return fs.Next() + } else if fs.Pos != fs.Length-1 { + if fs.HasFlag { + fs.AppendString(fs.end) } + fs.AppendString(fs.start) + fs.ChangeFlag = true + fs.HasFlag = true } } fs.Pos++ diff --git a/server/status_handler.go b/server/status_handler.go index 38414ab94a671134b51be92008455666e17d9502..94d56349aaa10e8845c45f688b313a2337dc95f4 100644 --- a/server/status_handler.go +++ b/server/status_handler.go @@ -47,7 +47,7 @@ func NewLocalStatusHandler(logger *zap.Logger, sessionRegistry SessionRegistry, func (s *LocalStatusHandler) GetStatus(ctx context.Context) ([]*console.StatusList_Status, error) { return []*console.StatusList_Status{ - &console.StatusList_Status{ + { Name: s.node, Health: 0, SessionCount: int32(s.sessionRegistry.Count()), diff --git a/server/tracker.go b/server/tracker.go index c09ff14faf12f82b1306c8c44702c444fac60ccd..76ba7a055c06487fd1417dd2f453dc7ca913fa42 100644 --- a/server/tracker.go +++ b/server/tracker.go @@ -258,7 +258,7 @@ func (t *LocalTracker) Track(sessionID uuid.UUID, stream PresenceStream, userID if !meta.Hidden { t.queueEvent( []Presence{ - Presence{ID: pc.ID, Stream: stream, UserID: userID, Meta: meta}, + {ID: pc.ID, Stream: stream, UserID: userID, Meta: meta}, }, nil, ) @@ -318,7 +318,7 @@ func (t *LocalTracker) Untrack(sessionID uuid.UUID, stream PresenceStream, userI t.queueEvent( nil, []Presence{ - Presence{ID: pc.ID, Stream: stream, UserID: userID, Meta: meta}, + {ID: pc.ID, Stream: stream, UserID: userID, Meta: meta}, }, ) } @@ -415,13 +415,13 @@ func (t *LocalTracker) Update(sessionID uuid.UUID, stream PresenceStream, userID var joins []Presence if !meta.Hidden { joins = []Presence{ - Presence{ID: pc.ID, Stream: stream, UserID: userID, Meta: meta}, + {ID: pc.ID, Stream: stream, UserID: userID, Meta: meta}, } } var leaves []Presence if alreadyTracked && !previousMeta.Hidden { leaves = []Presence{ - Presence{ID: pc.ID, Stream: stream, UserID: userID, Meta: previousMeta}, + {ID: pc.ID, Stream: stream, UserID: userID, Meta: previousMeta}, } } // Guaranteed joins and/or leaves are not empty or we wouldn't be inside this block. @@ -445,7 +445,7 @@ func (t *LocalTracker) UntrackLocalByStream(stream PresenceStream) { } // Drop the presences from tracking for each session. - for pc, _ := range byStream { + for pc := range byStream { if bySession := t.presencesBySession[pc.ID.SessionID]; len(bySession) == 1 { // This is the only presence for that session, discard the whole list. delete(t.presencesBySession, pc.ID.SessionID) @@ -479,7 +479,7 @@ func (t *LocalTracker) UntrackByStream(stream PresenceStream) { } // Drop the presences from tracking for each session. - for pc, _ := range byStream { + for pc := range byStream { if bySession := t.presencesBySession[pc.ID.SessionID]; len(bySession) == 1 { // This is the only presence for that session, discard the whole list. delete(t.presencesBySession, pc.ID.SessionID) @@ -507,7 +507,7 @@ func (t *LocalTracker) ListNodesForStream(stream PresenceStream) map[string]stru t.RUnlock() if anyTracked { // For the local tracker having any presences for this stream is enough. - return map[string]struct{}{t.name: struct{}{}} + return map[string]struct{}{t.name: {}} } return map[string]struct{}{} } @@ -617,7 +617,7 @@ func (t *LocalTracker) ListLocalSessionIDByStream(stream PresenceStream) []uuid. return []uuid.UUID{} } ps := make([]uuid.UUID, 0, len(byStream)) - for pc, _ := range byStream { + for pc := range byStream { ps = append(ps, pc.ID.SessionID) } t.RUnlock() @@ -632,7 +632,7 @@ func (t *LocalTracker) ListPresenceIDByStream(stream PresenceStream) []*Presence return []*PresenceID{} } ps := make([]*PresenceID, 0, len(byStream)) - for pc, _ := range byStream { + for pc := range byStream { pid := pc.ID ps = append(ps, &pid) } @@ -782,14 +782,14 @@ func (t *LocalTracker) processEvent(e *PresenceEvent) { case StreamModeGroup: fallthrough case StreamModeDM: - channelId, err := StreamToChannelId(stream) + channelID, err := StreamToChannelId(stream) if err != nil { // Should not happen thanks to previous validation, but guard just in case. t.logger.Error("Error converting stream to channel identifier in presence event", zap.Error(err), zap.Any("stream", stream)) continue } envelope = &rtapi.Envelope{Message: &rtapi.Envelope_ChannelPresenceEvent{ChannelPresenceEvent: &rtapi.ChannelPresenceEvent{ - ChannelId: channelId, + ChannelId: channelID, Joins: joins, Leaves: leaves, }}} @@ -811,7 +811,7 @@ func (t *LocalTracker) processEvent(e *PresenceEvent) { // Prepare payload variables but do not initialize until we hit a session that needs them to avoid unnecessary work. var payloadProtobuf []byte - var payloadJson []byte + var payloadJSON []byte // Deliver event. for _, sessionID := range sessionIDs { @@ -836,17 +836,17 @@ func (t *LocalTracker) processEvent(e *PresenceEvent) { case SessionFormatJson: fallthrough default: - if payloadJson == nil { + if payloadJSON == nil { // Marshal the payload now that we know this format is needed. var buf bytes.Buffer if err = t.jsonpbMarshaler.Marshal(&buf, envelope); err == nil { - payloadJson = buf.Bytes() + payloadJSON = buf.Bytes() } else { t.logger.Error("Could not marshal presence event", zap.Error(err)) return } } - err = session.SendBytes(payloadJson, true) + err = session.SendBytes(payloadJSON, true) } if err != nil { t.logger.Error("Failed to deliver presence event", zap.String("sid", sessionID.String()), zap.Error(err)) @@ -887,14 +887,14 @@ func (t *LocalTracker) processEvent(e *PresenceEvent) { case StreamModeGroup: fallthrough case StreamModeDM: - channelId, err := StreamToChannelId(stream) + channelID, err := StreamToChannelId(stream) if err != nil { // Should not happen thanks to previous validation, but guard just in case. t.logger.Error("Error converting stream to channel identifier in presence event", zap.Error(err), zap.Any("stream", stream)) continue } envelope = &rtapi.Envelope{Message: &rtapi.Envelope_ChannelPresenceEvent{ChannelPresenceEvent: &rtapi.ChannelPresenceEvent{ - ChannelId: channelId, + ChannelId: channelID, // No joins. Leaves: leaves, }}} @@ -916,7 +916,7 @@ func (t *LocalTracker) processEvent(e *PresenceEvent) { // Prepare payload variables but do not initialize until we hit a session that needs them to avoid unnecessary work. var payloadProtobuf []byte - var payloadJson []byte + var payloadJSON []byte // Deliver event. for _, sessionID := range sessionIDs { @@ -941,17 +941,17 @@ func (t *LocalTracker) processEvent(e *PresenceEvent) { case SessionFormatJson: fallthrough default: - if payloadJson == nil { + if payloadJSON == nil { // Marshal the payload now that we know this format is needed. var buf bytes.Buffer if err = t.jsonpbMarshaler.Marshal(&buf, envelope); err == nil { - payloadJson = buf.Bytes() + payloadJSON = buf.Bytes() } else { t.logger.Error("Could not marshal presence event", zap.Error(err)) return } } - err = session.SendBytes(payloadJson, true) + err = session.SendBytes(payloadJSON, true) } if err != nil { t.logger.Error("Failed to deliver presence event", zap.String("sid", sessionID.String()), zap.Error(err)) diff --git a/social/social.go b/social/social.go index e7c401dac2ffd223161c586500c45d251a097092..e0cfd84798b9dcea9b4a26ec0a35aab13548bbfe 100644 --- a/social/social.go +++ b/social/social.go @@ -308,11 +308,11 @@ func (c *Client) CheckGoogleToken(ctx context.Context, idToken string) (*GoogleP if v, ok := claims["iat"]; ok { switch v.(type) { case string: - if vi, err := strconv.Atoi(v.(string)); err != nil { + vi, err := strconv.Atoi(v.(string)) + if err != nil { return nil, errors.New("google id token iat field invalid") - } else { - profile.Iat = int64(vi) } + profile.Iat = int64(vi) case float64: profile.Iat = int64(v.(float64)) case int64: @@ -324,11 +324,11 @@ func (c *Client) CheckGoogleToken(ctx context.Context, idToken string) (*GoogleP if v, ok := claims["exp"]; ok { switch v.(type) { case string: - if vi, err := strconv.Atoi(v.(string)); err != nil { + vi, err := strconv.Atoi(v.(string)) + if err != nil { return nil, errors.New("google id token exp field invalid") - } else { - profile.Exp = int64(vi) } + profile.Exp = int64(vi) case float64: profile.Exp = int64(v.(float64)) case int64: @@ -347,11 +347,11 @@ func (c *Client) CheckGoogleToken(ctx context.Context, idToken string) (*GoogleP case bool: profile.EmailVerified = v.(bool) case string: - if vb, err := strconv.ParseBool(v.(string)); err != nil { + vb, err := strconv.ParseBool(v.(string)) + if err != nil { return nil, errors.New("google id token email_verified field invalid") - } else { - profile.EmailVerified = vb } + profile.EmailVerified = vb default: return nil, errors.New("google id token email_verified field unknown") } diff --git a/tests/core_wallet_test.go b/tests/core_wallet_test.go index 4deffb540076a1a29e6c08e4d333ce856dd7065d..b8ec380f619c0507b5031a67c16a0a039361976f 100644 --- a/tests/core_wallet_test.go +++ b/tests/core_wallet_test.go @@ -487,15 +487,15 @@ func TestUpdateWalletsSingleUser(t *testing.T) { } updates := []*runtime.WalletUpdate{ - &runtime.WalletUpdate{ + { UserID: userID, Changeset: map[string]interface{}{"value": float64(1)}, }, - &runtime.WalletUpdate{ + { UserID: userID, Changeset: map[string]interface{}{"value": float64(2)}, }, - &runtime.WalletUpdate{ + { UserID: userID, Changeset: map[string]interface{}{"value": float64(3)}, },