From 2c3f8a319e01af73d57c0b83bde1545c82bec885 Mon Sep 17 00:00:00 2001 From: Max Kuznetsov Date: Thu, 24 Aug 2023 13:28:35 -0400 Subject: [PATCH] fix linter warnings and add GH lint workflow --- .github/workflows/golangci-lint.yml | 25 +++ .golangci.yml | 15 ++ CHANGELOG.md | 2 + flags/flags.go | 204 +++++++++++------------ internal/skiplist/skiplist_test.go | 3 +- server/api_authenticate.go | 2 +- server/api_rpc.go | 4 +- server/config.go | 4 +- server/console.go | 5 +- server/console_authenticate.go | 2 +- server/core_leaderboard.go | 2 +- server/core_purchase.go | 8 +- server/core_storage.go | 3 +- server/core_subscription.go | 11 +- server/match_common_test.go | 8 +- server/match_registry_test.go | 11 +- server/matchmaker.go | 2 +- server/matchmaker_process.go | 4 +- server/matchmaker_test.go | 50 +++--- server/metrics_grpc_handler.go | 5 +- server/party_handler_test.go | 2 +- server/party_presence.go | 8 +- server/pipeline.go | 10 +- server/pipeline_channel.go | 48 +++--- server/pipeline_match.go | 36 ++-- server/pipeline_matchmaker.go | 22 +-- server/pipeline_party.go | 106 ++++++------ server/pipeline_ping.go | 2 +- server/pipeline_rpc.go | 8 +- server/pipeline_status.go | 30 ++-- server/runtime.go | 24 +-- server/runtime_go_context.go | 3 + server/runtime_go_match_core.go | 11 +- server/runtime_go_nakama.go | 9 +- server/runtime_javascript.go | 133 +++++++-------- server/runtime_javascript_context.go | 34 ++-- server/runtime_javascript_init.go | 4 +- server/runtime_javascript_logger.go | 18 +- server/runtime_javascript_logger_test.go | 12 +- server/runtime_javascript_match_core.go | 74 ++++---- server/runtime_javascript_nakama.go | 29 ++-- server/runtime_lua_nakama.go | 3 +- server/runtime_lua_oslib.go | 2 +- server/status_registry.go | 6 +- server/storage_index.go | 4 +- server/tracker.go | 2 +- social/social.go | 34 ++-- 47 files changed, 541 insertions(+), 503 deletions(-) create mode 100644 .github/workflows/golangci-lint.yml create mode 100644 .golangci.yml diff --git a/.github/workflows/golangci-lint.yml b/.github/workflows/golangci-lint.yml new file mode 100644 index 0000000000..0c8f70eeaf --- /dev/null +++ b/.github/workflows/golangci-lint.yml @@ -0,0 +1,25 @@ +name: golangci-lint +on: + workflow_dispatch: + pull_request: + +permissions: + contents: read + pull-requests: read + +jobs: + golangci: + name: lint + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-go@v4 + with: + go-version: "stable" + cache: false + - name: golangci-lint + uses: golangci/golangci-lint-action@v3 + with: + version: v1.54 + only-new-issues: true + args: --timeout=10m diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000000..ddc25ffddc --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,15 @@ +run: + # Enables skipping of directories: + # - vendor$, third_party$, testdata$, examples$, Godeps$, builtin$ + skip-dirs-use-default: true + skip-dirs: + - internal/gopher-lua + - internal/cronexpr + +linters: + enable: + - gofmt + +linters-settings: + gofmt: + simplify: false diff --git a/CHANGELOG.md b/CHANGELOG.md index b1b466d731..429e06b3d7 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ All notable changes to this project are documented below. The format is based on [keep a changelog](http://keepachangelog.com) and this project uses [semantic versioning](http://semver.org). ## [Unreleased] +### Fixed +- Fixed multiple issues found by linter. ### [3.17.1] - 2023-08-23 ### Added diff --git a/flags/flags.go b/flags/flags.go index 3f29be47a6..62275343db 100644 --- a/flags/flags.go +++ b/flags/flags.go @@ -30,14 +30,14 @@ // application we load from the yaml file to get the necessary parameters to // create the connection. Our base.yaml looks like this // -// base.yaml -// --- -// mysql: -// user: 'foo' -// password: 'xxxxxx' -// mysql_defaults_file: ./mysql_defaults.ini -// mysql_socket_path: /var/run/mysqld/mysqld.sock -// ... more config options ... +// base.yaml +// --- +// mysql: +// user: 'foo' +// password: 'xxxxxx' +// mysql_defaults_file: ./mysql_defaults.ini +// mysql_socket_path: /var/run/mysqld/mysqld.sock +// ... more config options ... // // we want to load all the configs from it but we want to provide some // flexibility for the program to connect via a different db user. We could @@ -56,125 +56,125 @@ // // Let's say we have our configration object as the following. // -// type logging struct { -// Interval int -// Path string -// } +// type logging struct { +// Interval int +// Path string +// } // -// type socket struct { -// ReadTimeout time.Duration -// WriteTimeout time.Duration -// } +// type socket struct { +// ReadTimeout time.Duration +// WriteTimeout time.Duration +// } // -// type tcp struct { -// ReadTimeout time.Duration -// socket -// } +// type tcp struct { +// ReadTimeout time.Duration +// socket +// } // -// type network struct { -// ReadTimeout time.Duration -// WriteTimeout time.Duration -// tcp -// } +// type network struct { +// ReadTimeout time.Duration +// WriteTimeout time.Duration +// tcp +// } // -// type Cfg struct { -// logging -// network -// } +// type Cfg struct { +// logging +// network +// } // // The following code // -// func main() { -// c := &Cfg{} -// flags.ParseArgs(c, os.Args[1:]) -// } +// func main() { +// c := &Cfg{} +// flags.ParseArgs(c, os.Args[1:]) +// } // // will create the following flags // -// -logging.interval int -// logging.interval -// -logging.path string -// logging.path -// -network.readtimeout duration -// network.readtimeout -// -network.tcp.readtimeout duration -// network.tcp.readtimeout -// -network.tcp.socket.readtimeout duration -// network.tcp.socket.readtimeout -// -network.tcp.socket.writetimeout duration -// network.tcp.socket.writetimeout -// -network.writetimeout duration -// network.writetimeout +// -logging.interval int +// logging.interval +// -logging.path string +// logging.path +// -network.readtimeout duration +// network.readtimeout +// -network.tcp.readtimeout duration +// network.tcp.readtimeout +// -network.tcp.socket.readtimeout duration +// network.tcp.socket.readtimeout +// -network.tcp.socket.writetimeout duration +// network.tcp.socket.writetimeout +// -network.writetimeout duration +// network.writetimeout // // flags to subcommands are naturally suported. // -// func main() { -// cmd := os.Args[1] -// switch cmd { -// case "new" -// c1 := &Cfg1{} -// ParseArgs(c1, os.Args[2:]) -// case "update": -// c2 := &Cfg2{} -// ParseArgs(c2, os.Args[2:]) +// func main() { +// cmd := os.Args[1] +// switch cmd { +// case "new" +// c1 := &Cfg1{} +// ParseArgs(c1, os.Args[2:]) +// case "update": +// c2 := &Cfg2{} +// ParseArgs(c2, os.Args[2:]) // -// ... more sub commands ... -// } -// } +// ... more sub commands ... +// } +// } // // One can set Flatten to true when calling NewFlagMakerAdv, in which case, // flags are created without namespacing. For example, // -// type auth struct { -// Token string -// Tag float64 -// } -// -// type credentials struct { -// User string -// Password string -// auth -// } -// -// type database struct { -// DBName string -// TableName string -// credentials -// } -// -// type Cfg struct { -// logging -// database -// } -// -// func main() { -// c := &Cfg{} -// flags.ParseArgs(c, os.Args[1:]) -// } +// type auth struct { +// Token string +// Tag float64 +// } +// +// type credentials struct { +// User string +// Password string +// auth +// } +// +// type database struct { +// DBName string +// TableName string +// credentials +// } +// +// type Cfg struct { +// logging +// database +// } +// +// func main() { +// c := &Cfg{} +// flags.ParseArgs(c, os.Args[1:]) +// } // // will create the following flags -// -dbname string -// dbname -// -interval int -// interval -// -password string -// password -// -path string -// path -// -tablename string -// tablename -// -tag float -// tag -// -token string -// token -// -user string -// user +// +// -dbname string +// dbname +// -interval int +// interval +// -password string +// password +// -path string +// path +// -tablename string +// tablename +// -tag float +// tag +// -token string +// token +// -user string +// user // // Please be aware that usual GoLang flag creation rules apply, i.e., if there are // duplication in flag names (in the flattened case it's more likely to happen // unless the caller make due dilligence to create the struct properly), it panics. // -// // Note that not all types can have command line flags created for. map, channel // and function type will not defien a flag corresponding to the field. Pointer // types are properly handled and slice type will create multi-value command diff --git a/internal/skiplist/skiplist_test.go b/internal/skiplist/skiplist_test.go index fda2ca6cc1..55855df5cc 100644 --- a/internal/skiplist/skiplist_test.go +++ b/internal/skiplist/skiplist_test.go @@ -73,8 +73,6 @@ func TestInt(t *testing.T) { sl.Delete(Int(888)) sl.Delete(Int(1000)) - expect = []Int{Int(-999), Int(-888), Int(1), Int(3), Int(999)} - if sl.Front().Value.(Int) != -999 { t.Fatal() } @@ -283,6 +281,7 @@ func BenchmarkIntRankRandom(b *testing.B) { } } +// nolint:unused func output(sl *SkipList) { var x *Element for i := 0; i < SKIPLIST_MAXLEVEL; i++ { diff --git a/server/api_authenticate.go b/server/api_authenticate.go index 18fbc96041..cac58cd46b 100644 --- a/server/api_authenticate.go +++ b/server/api_authenticate.go @@ -33,7 +33,7 @@ import ( var ( invalidUsernameRegex = regexp.MustCompilePOSIX("([[:cntrl:]]|[[\t\n\r\f\v]])+") invalidCharsRegex = regexp.MustCompilePOSIX("([[:cntrl:]]|[[:space:]])+") - emailRegex = regexp.MustCompile("^.+@.+\\..+$") + emailRegex = regexp.MustCompile(`^.+@.+\..+$`) ) type SessionTokenClaims struct { diff --git a/server/api_rpc.go b/server/api_rpc.go index 650cae5d25..cdce638d5c 100644 --- a/server/api_rpc.go +++ b/server/api_rpc.go @@ -189,9 +189,7 @@ func (s *ApiServer) RpcFuncHttp(w http.ResponseWriter, r *http.Request) { continue } headers[k] = make([]string, 0, len(v)) - for _, h := range v { - headers[k] = append(headers[k], h) - } + headers[k] = append(headers[k], v...) } // Execute the function. diff --git a/server/config.go b/server/config.go index 46711ca01d..dc15f8ad96 100644 --- a/server/config.go +++ b/server/config.go @@ -365,7 +365,7 @@ func CheckConfig(logger *zap.Logger, config Config) map[string]string { logger.Warn("WARNING: deprecated configuration parameter", zap.String("deprecated", "runtime.registry_size"), zap.String("param", "runtime.lua_registry_size")) configWarnings["runtime.registry_size"] = "Deprecated configuration parameter" } - if config.GetRuntime().ReadOnlyGlobals != true { + if !config.GetRuntime().ReadOnlyGlobals { logger.Warn("WARNING: deprecated configuration parameter", zap.String("deprecated", "runtime.read_only_globals"), zap.String("param", "runtime.lua_read_only_globals")) configWarnings["runtime.read_only_globals"] = "Deprecated configuration parameter" } @@ -862,7 +862,7 @@ func (r *RuntimeConfig) GetLuaRegistrySize() int { // Function to allow backwards compatibility for LuaReadOnlyGlobals config func (r *RuntimeConfig) GetLuaReadOnlyGlobals() bool { - if r.ReadOnlyGlobals != true { + if !r.ReadOnlyGlobals { return r.ReadOnlyGlobals } return r.LuaReadOnlyGlobals diff --git a/server/console.go b/server/console.go index 0019730426..c9ddb18a6a 100644 --- a/server/console.go +++ b/server/console.go @@ -364,7 +364,7 @@ SELECT collection FROM t WHERE collection IS NOT NULL` sort.Strings(collections) collectionSetCache.Store(collections) - elapsed := time.Now().Sub(startAt) + elapsed := time.Since(startAt) elapsed *= 20 if elapsed < time.Minute { elapsed = time.Minute @@ -410,8 +410,7 @@ func registerDashboardHandlers(logger *zap.Logger, router *mux.Router) { w.Header().Add("Cache-Control", "no-cache") w.Header().Set("X-Frame-Options", "deny") - w.Write(indexBytes) - return + _, _ = w.Write(indexBytes) } router.Path("/").HandlerFunc(indexFn) diff --git a/server/console_authenticate.go b/server/console_authenticate.go index a5fb78f495..7116f6aafa 100644 --- a/server/console_authenticate.go +++ b/server/console_authenticate.go @@ -76,7 +76,7 @@ func (s *ConsoleServer) Authenticate(ctx context.Context, in *console.Authentica return nil, status.Error(codes.ResourceExhausted, "Try again later.") } - role := console.UserRole_USER_ROLE_UNKNOWN + var role console.UserRole var uname string var email string var id uuid.UUID diff --git a/server/core_leaderboard.go b/server/core_leaderboard.go index f6d328d25c..880c43bb17 100644 --- a/server/core_leaderboard.go +++ b/server/core_leaderboard.go @@ -285,7 +285,7 @@ func LeaderboardRecordsList(ctx context.Context, logger *zap.Logger, db *sql.DB, } } - if ownerIds != nil && len(ownerIds) != 0 { + if len(ownerIds) != 0 { params := make([]interface{}, 0, len(ownerIds)+2) params = append(params, leaderboardId, time.Unix(expiryTime, 0).UTC()) statements := make([]string, len(ownerIds)) diff --git a/server/core_purchase.go b/server/core_purchase.go index ca2ff410ad..9b4d4478a0 100644 --- a/server/core_purchase.go +++ b/server/core_purchase.go @@ -57,7 +57,7 @@ func ValidatePurchasesApple(ctx context.Context, logger *zap.Logger, db *sql.DB, } if validation.Status != iap.AppleReceiptIsValid { - if validation.IsRetryable == true { + if validation.IsRetryable { return nil, status.Error(codes.Unavailable, "Apple IAP verification is currently unavailable. Try again later.") } return nil, status.Error(codes.FailedPrecondition, fmt.Sprintf("Invalid Receipt. Status: %d", validation.Status)) @@ -617,10 +617,10 @@ RETURNING var updateTime pgtype.Timestamptz var refundTime pgtype.Timestamptz if err = rows.Scan(&dbUserID, &transactionId, &createTime, &updateTime, &refundTime); err != nil { - rows.Close() + _ = rows.Close() return nil, err } - storedPurchase, _ := transactionIDsToPurchase[transactionId] + storedPurchase := transactionIDsToPurchase[transactionId] storedPurchase.createTime = createTime.Time storedPurchase.updateTime = updateTime.Time storedPurchase.seenBefore = updateTime.Time.After(createTime.Time) @@ -628,7 +628,7 @@ RETURNING storedPurchase.refundTime = refundTime.Time } } - rows.Close() + _ = rows.Close() if err := rows.Err(); err != nil { return nil, err } diff --git a/server/core_storage.go b/server/core_storage.go index 945dfe6a7e..3364954c9b 100644 --- a/server/core_storage.go +++ b/server/core_storage.go @@ -23,7 +23,6 @@ import ( "encoding/gob" "encoding/hex" "errors" - "fmt" "sort" "github.com/gofrs/uuid/v5" @@ -711,7 +710,7 @@ func StorageDeleteObjects(ctx context.Context, logger *zap.Logger, db *sql.DB, s if op.ObjectID.GetVersion() != "" { // Conditional delete. params = append(params, op.ObjectID.Version) - query += fmt.Sprintf(" AND version = $4") + query += " AND version = $4" } result, err := tx.ExecContext(ctx, query, params...) diff --git a/server/core_subscription.go b/server/core_subscription.go index 219c06c62f..8abcc018d3 100644 --- a/server/core_subscription.go +++ b/server/core_subscription.go @@ -258,7 +258,7 @@ func ValidateSubscriptionApple(ctx context.Context, logger *zap.Logger, db *sql. } if validation.Status != iap.AppleReceiptIsValid { - if validation.IsRetryable == true { + if validation.IsRetryable { return nil, status.Error(codes.Unavailable, "Apple IAP verification is currently unavailable. Try again later.") } return nil, status.Error(codes.FailedPrecondition, fmt.Sprintf("Invalid Receipt. Status: %d", validation.Status)) @@ -685,6 +685,7 @@ type appleNotificationTransactionInfo struct { PurchaseDateMs int64 `json:"purchaseDate"` } +//nolint:unused func extractApplePublicKeyFromToken(tokenStr string) (*ecdsa.PublicKey, error) { tokenArr := strings.Split(tokenStr, ".") headerByte, err := base64.RawStdEncoding.DecodeString(tokenArr[0]) @@ -1021,7 +1022,6 @@ func appleNotificationHandler(logger *zap.Logger, db *sql.DB, purchaseNotificati } w.WriteHeader(http.StatusOK) - return } } @@ -1117,7 +1117,7 @@ func googleNotificationHandler(logger *zap.Logger, db *sql.DB, config *IAPGoogle logger.Debug("Google IAP subscription notification received", zap.String("notification_payload", string(jsonData)), zap.Any("api_response", gResponse)) - uid := uuid.Nil + var uid uuid.UUID if gResponse.ObfuscatedExternalAccountId != "" { extUID, err := uuid.FromString(gResponse.ObfuscatedExternalAccountId) if err != nil { @@ -1135,7 +1135,7 @@ func googleNotificationHandler(logger *zap.Logger, db *sql.DB, config *IAPGoogle } else if gResponse.ProfileId != "" { var dbUID uuid.UUID if err = db.QueryRowContext(context.Background(), "SELECT id FROM users WHERE google_id = $1", gResponse.ProfileId).Scan(&dbUID); err != nil { - if err == sql.ErrNoRows { + if errors.Is(err, sql.ErrNoRows) { logger.Warn("Google Play Billing subscription notification user not found", zap.String("profile_id", gResponse.ProfileId), zap.String("payload", string(body))) w.WriteHeader(http.StatusOK) // Subscription could not be assigned to a user ID, ack and ignore it. return @@ -1148,7 +1148,7 @@ func googleNotificationHandler(logger *zap.Logger, db *sql.DB, config *IAPGoogle // Get user id by existing validated subscription. sub, err := getSubscriptionByOriginalTransactionId(context.Background(), db, googleNotification.SubscriptionNotification.PurchaseToken) if err != nil { - if err != sql.ErrNoRows { + if !errors.Is(err, sql.ErrNoRows) { logger.Error("Failed to get subscription by original transaction id", zap.Error(err)) } w.WriteHeader(http.StatusInternalServerError) @@ -1206,6 +1206,5 @@ func googleNotificationHandler(logger *zap.Logger, db *sql.DB, config *IAPGoogle } w.WriteHeader(http.StatusOK) - return } } diff --git a/server/match_common_test.go b/server/match_common_test.go index a222237fa6..91689eea70 100644 --- a/server/match_common_test.go +++ b/server/match_common_test.go @@ -138,7 +138,9 @@ func (m *testMatch) MatchLoop(ctx context.Context, logger runtime.Logger, db *sq for _, message := range messages { logger.Info("Received %v from %v", string(message.GetData()), message.GetUserId()) reliable := true - dispatcher.BroadcastMessage(1, message.GetData(), []runtime.Presence{message}, nil, reliable) + if err := dispatcher.BroadcastMessage(1, message.GetData(), []runtime.Presence{message}, nil, reliable); err != nil { + logger.Error("Failed to broadcast message: %w", err) + } } return mState } @@ -147,7 +149,9 @@ func (m *testMatch) MatchTerminate(ctx context.Context, logger runtime.Logger, d dispatcher runtime.MatchDispatcher, tick int64, state interface{}, graceSeconds int) interface{} { message := "Server shutting down in " + strconv.Itoa(graceSeconds) + " seconds." reliable := true - dispatcher.BroadcastMessage(2, []byte(message), []runtime.Presence{}, nil, reliable) + if err := dispatcher.BroadcastMessage(2, []byte(message), []runtime.Presence{}, nil, reliable); err != nil { + logger.Error("Failed to broadcast message: %w", err) + } return state } diff --git a/server/match_registry_test.go b/server/match_registry_test.go index c960002d77..bc95546bf8 100644 --- a/server/match_registry_test.go +++ b/server/match_registry_test.go @@ -22,6 +22,7 @@ import ( "github.com/blugelabs/bluge" "github.com/gofrs/uuid/v5" "github.com/heroiclabs/nakama-common/runtime" + "github.com/stretchr/testify/require" "go.uber.org/atomic" "go.uber.org/zap" "google.golang.org/protobuf/types/known/wrapperspb" @@ -158,6 +159,7 @@ func TestMatchRegistryAuthoritativeMatchAndListMatches(t *testing.T) { matches, _, err := matchRegistry.ListMatches(context.Background(), 2, wrapperspb.Bool(true), wrapperspb.String("label"), wrapperspb.Int32(0), wrapperspb.Int32(5), nil, nil) + require.NoError(t, err) if len(matches) != 1 { t.Fatalf("expected one match, got %d", len(matches)) } @@ -193,6 +195,7 @@ func TestMatchRegistryAuthoritativeMatchAndListMatchesWithTokenizableLabel(t *te matches, _, err := matchRegistry.ListMatches(context.Background(), 2, wrapperspb.Bool(true), wrapperspb.String("label-part2"), wrapperspb.Int32(0), wrapperspb.Int32(5), nil, nil) + require.NoError(t, err) if len(matches) != 1 { t.Fatalf("expected one match, got %d", len(matches)) } @@ -227,6 +230,7 @@ func TestMatchRegistryAuthoritativeMatchAndListMatchesWithQuerying(t *testing.T) matches, _, err := matchRegistry.ListMatches(context.Background(), 2, wrapperspb.Bool(true), wrapperspb.String("label"), wrapperspb.Int32(0), wrapperspb.Int32(5), wrapperspb.String("+label.skill:>=50"), nil) + require.NoError(t, err) if len(matches) != 1 { t.Fatalf("expected one match, got %d", len(matches)) } @@ -261,6 +265,7 @@ func TestMatchRegistryAuthoritativeMatchAndListAllMatchesWithQueryStar(t *testin matches, _, err := matchRegistry.ListMatches(context.Background(), 2, wrapperspb.Bool(true), wrapperspb.String("label"), wrapperspb.Int32(0), wrapperspb.Int32(5), wrapperspb.String("*"), nil) + require.NoError(t, err) if len(matches) != 1 { t.Fatalf("expected one match, got %d", len(matches)) } @@ -299,6 +304,7 @@ func TestMatchRegistryAuthoritativeMatchAndListMatchesWithQueryingArrays(t *test matches, _, err := matchRegistry.ListMatches(context.Background(), 2, wrapperspb.Bool(true), wrapperspb.String("label"), wrapperspb.Int32(0), wrapperspb.Int32(5), wrapperspb.String(fmt.Sprintf("+label.convo_ids:%s", convoID2)), nil) + require.NoError(t, err) if len(matches) != 1 { t.Fatalf("expected one match, got %d", len(matches)) } @@ -336,12 +342,15 @@ func TestMatchRegistryListMatchesAfterLabelsUpdate(t *testing.T) { t.Fatal(err) } - rgmc.MatchLabelUpdate(`{"updated_label": 1}`) + err = rgmc.MatchLabelUpdate(`{"updated_label": 1}`) + require.NoError(t, err) + matchRegistry.processLabelUpdates(bluge.NewBatch()) matches, _, err := matchRegistry.ListMatches(context.Background(), 2, wrapperspb.Bool(true), nil, wrapperspb.Int32(0), wrapperspb.Int32(5), wrapperspb.String(`label.updated_label:1`), nil) + require.NoError(t, err) if len(matches) != 1 { t.Fatalf("expected one match, got %d", len(matches)) } diff --git a/server/matchmaker.go b/server/matchmaker.go index 10ad140a8d..f1b19d995e 100644 --- a/server/matchmaker.go +++ b/server/matchmaker.go @@ -283,7 +283,7 @@ func (m *LocalMatchmaker) Process() { startTime := time.Now() var activeIndexCount, indexCount int defer func() { - m.metrics.Matchmaker(float64(indexCount), float64(activeIndexCount), time.Now().Sub(startTime)) + m.metrics.Matchmaker(float64(indexCount), float64(activeIndexCount), time.Since(startTime)) }() m.Lock() diff --git a/server/matchmaker_process.go b/server/matchmaker_process.go index 1998fa86d4..020a3cf973 100644 --- a/server/matchmaker_process.go +++ b/server/matchmaker_process.go @@ -299,7 +299,7 @@ func (m *LocalMatchmaker) processDefault(activeIndexCount int, activeIndexesCopy currentMatchedEntries := append(foundCombo, activeIndex.Entries...) // Remove the found combos from currently tracked list. - entryCombos = append(entryCombos[:foundComboIdx], entryCombos[foundComboIdx+1:]...) + entryCombos = append(entryCombos[:foundComboIdx], entryCombos[foundComboIdx+1:]...) //nolint:staticcheck matchedEntries = append(matchedEntries, currentMatchedEntries) @@ -507,7 +507,7 @@ func (m *LocalMatchmaker) processCustom(activeIndexesCopy map[string]*Matchmaker sessionIDs := make(map[string]struct{}, index.MaxCount-index.Count) parsedQueries := make(map[string]bluge.Query, index.MaxCount-index.Count) for _, hitIndex := range hitIndexes { - for sessionID, _ := range hitIndex.SessionIDs { + for sessionID := range hitIndex.SessionIDs { // Check for session ID conflicts. if _, found := sessionIDs[sessionID]; found { sessionIdConflict = true diff --git a/server/matchmaker_test.go b/server/matchmaker_test.go index 84d7b298cb..07f9f508d5 100644 --- a/server/matchmaker_test.go +++ b/server/matchmaker_test.go @@ -39,7 +39,7 @@ func TestMatchmakerAddOnly(t *testing.T) { if err != nil { t.Fatalf("error creating test matchmaker: %v", err) } - defer cleanup() + defer cleanup() //nolint:errcheck sessionID, _ := uuid.NewV4() ticket, _, err := matchMaker.Add(context.Background(), []*MatchmakerPresence{ @@ -67,7 +67,7 @@ func TestMatchmakerAddRemoveRepeated(t *testing.T) { if err != nil { t.Fatalf("error creating test matchmaker: %v", err) } - defer cleanup() + defer cleanup() //nolint:errcheck sessionID, _ := uuid.NewV4() ticket, _, err := matchMaker.Add(context.Background(), []*MatchmakerPresence{ @@ -165,7 +165,7 @@ func TestMatchmakerPropertyRegexSubmatch(t *testing.T) { if err != nil { t.Fatalf("error creating test matchmaker: %v", err) } - defer cleanup() + defer cleanup() //nolint:errcheck matchmakerIndexDoc1, err := MapMatchmakerIndex("ticket1", &MatchmakerIndex{ Ticket: "ticket1", @@ -291,7 +291,7 @@ func TestMatchmakerPropertyRegexSubmatchMultiple(t *testing.T) { if err != nil { t.Fatalf("error creating test matchmaker: %v", err) } - defer cleanup() + defer cleanup() //nolint:errcheck matchmakerIndexDoc1, err := MapMatchmakerIndex("ticket1", &MatchmakerIndex{ Ticket: "ticket1", @@ -384,7 +384,7 @@ func TestMatchmakerAddAndRemove(t *testing.T) { if err != nil { t.Fatalf("error creating test matchmaker: %v", err) } - defer cleanup() + defer cleanup() //nolint:errcheck sessionID, _ := uuid.NewV4() ticket, _, err := matchMaker.Add(context.Background(), []*MatchmakerPresence{ @@ -423,7 +423,7 @@ func TestMatchmakerAddWithBasicMatch(t *testing.T) { if err != nil { t.Fatalf("error creating test matchmaker: %v", err) } - defer cleanup() + defer cleanup() //nolint:errcheck sessionID, _ := uuid.NewV4() ticket1, _, err := matchMaker.Add(context.Background(), []*MatchmakerPresence{ @@ -534,7 +534,7 @@ func TestMatchmakerAddWithMatchOnStar(t *testing.T) { if err != nil { t.Fatalf("error creating test matchmaker: %v", err) } - defer cleanup() + defer cleanup() //nolint:errcheck sessionID, _ := uuid.NewV4() ticket1, _, err := matchMaker.Add(context.Background(), []*MatchmakerPresence{ @@ -651,7 +651,7 @@ func TestMatchmakerAddWithMatchOnRange(t *testing.T) { if err != nil { t.Fatalf("error creating test matchmaker: %v", err) } - defer cleanup() + defer cleanup() //nolint:errcheck sessionID, _ := uuid.NewV4() ticket1, _, err := matchMaker.Add(context.Background(), []*MatchmakerPresence{ @@ -768,7 +768,7 @@ func TestMatchmakerAddWithMatchOnRangeAndValue(t *testing.T) { if err != nil { t.Fatalf("error creating test matchmaker: %v", err) } - defer cleanup() + defer cleanup() //nolint:errcheck sessionID, _ := uuid.NewV4() ticket1, _, err := matchMaker.Add(context.Background(), []*MatchmakerPresence{ @@ -894,7 +894,7 @@ func TestMatchmakerAddRemoveNotMatch(t *testing.T) { if err != nil { t.Fatalf("error creating test matchmaker: %v", err) } - defer cleanup() + defer cleanup() //nolint:errcheck sessionID, _ := uuid.NewV4() ticket1, _, err := matchMaker.Add(context.Background(), []*MatchmakerPresence{ @@ -941,7 +941,7 @@ func TestMatchmakerAddButNotMatch(t *testing.T) { if err != nil { t.Fatalf("error creating test matchmaker: %v", err) } - defer cleanup() + defer cleanup() //nolint:errcheck sessionID, _ := uuid.NewV4() ticket1, _, err := matchMaker.Add(context.Background(), []*MatchmakerPresence{ @@ -1011,7 +1011,7 @@ func TestMatchmakerAddButNotMatchOnRange(t *testing.T) { if err != nil { t.Fatalf("error creating test matchmaker: %v", err) } - defer cleanup() + defer cleanup() //nolint:errcheck testID, _ := uuid.NewV4() @@ -1087,7 +1087,7 @@ func TestMatchmakerAddButNotMatchOnRangeAndValue(t *testing.T) { if err != nil { t.Fatalf("error creating test matchmaker: %v", err) } - defer cleanup() + defer cleanup() //nolint:errcheck testID, _ := uuid.NewV4() @@ -1162,7 +1162,7 @@ func TestMatchmakerAddMultipleAndSomeMatch(t *testing.T) { if err != nil { t.Fatalf("error creating test matchmaker: %v", err) } - defer cleanup() + defer cleanup() //nolint:errcheck testID, _ := uuid.NewV4() @@ -1264,7 +1264,7 @@ func TestMatchmakerAddMultipleAndSomeMatchWithBoost(t *testing.T) { if err != nil { t.Fatalf("error creating test matchmaker: %v", err) } - defer cleanup() + defer cleanup() //nolint:errcheck testID, _ := uuid.NewV4() @@ -1382,7 +1382,7 @@ func TestMatchmakerAddMultipleAndSomeMatchOptionalTextAlteringScore(t *testing.T if err != nil { t.Fatalf("error creating test matchmaker: %v", err) } - defer cleanup() + defer cleanup() //nolint:errcheck testID, _ := uuid.NewV4() @@ -1484,7 +1484,7 @@ func TestMatchmakerAddAndMatchAuthoritative(t *testing.T) { if err != nil { t.Fatalf("error creating test matchmaker: %v", err) } - defer cleanup() + defer cleanup() //nolint:errcheck sessionID, _ := uuid.NewV4() ticket1, _, err := matchMaker.Add(context.Background(), []*MatchmakerPresence{ @@ -1754,7 +1754,7 @@ func TestMatchmakerRequireMutualMatch(t *testing.T) { if err != nil { t.Fatalf("error creating test matchmaker: %v", err) } - defer cleanup() + defer cleanup() //nolint:errcheck sessionID, _ := uuid.NewV4() ticket1, _, err := matchMaker.Add(context.Background(), []*MatchmakerPresence{ @@ -1836,7 +1836,7 @@ func TestMatchmakerRequireMutualMatchLarger(t *testing.T) { if err != nil { t.Fatalf("error creating test matchmaker: %v", err) } - defer cleanup() + defer cleanup() //nolint:errcheck sessionID, _ := uuid.NewV4() _, _, err = matchMaker.Add(context.Background(), []*MatchmakerPresence{ @@ -1938,7 +1938,7 @@ func TestMatchmakerRequireMutualMatchLargerReversed(t *testing.T) { if err != nil { t.Fatalf("error creating test matchmaker: %v", err) } - defer cleanup() + defer cleanup() //nolint:errcheck sessionID, _ := uuid.NewV4() _, _, err = matchMaker.Add(context.Background(), []*MatchmakerPresence{ @@ -2133,7 +2133,7 @@ func benchmarkMatchmakerHelper(b *testing.B, activeCount, minCount, maxCount, co if err != nil { b.Fatalf("error creating test matchmaker: %v", err) } - defer cleanup() + defer cleanup() //nolint:errcheck var matchMakerAdded int b.ResetTimer() @@ -2195,7 +2195,7 @@ func TestMatchmakerMaxPartyTracking(t *testing.T) { if err != nil { t.Fatalf("error creating test matchmaker: %v", err) } - defer cleanup() + defer cleanup() //nolint:errcheck createTicketFunc := func(party string) error { sessionID, _ := uuid.NewV4() @@ -2276,7 +2276,7 @@ func TestMatchmakerMaxSessionTracking(t *testing.T) { if err != nil { t.Fatalf("error creating test matchmaker: %v", err) } - defer cleanup() + defer cleanup() //nolint:errcheck createTicketFunc := func(sessionID uuid.UUID) error { _, _, err = matchMaker.Add(context.Background(), []*MatchmakerPresence{ @@ -2364,7 +2364,7 @@ func benchmarkMatchmakerProcessTickets(ticketsMax int32, unmatchable int, minCou if err != nil { b.Fatalf("error creating test matchmaker: %v", err) } - defer cleanup() + defer cleanup() //nolint:errcheck for i := 0; i < unmatchable; i++ { sessionID, _ := uuid.NewV4() @@ -2430,6 +2430,8 @@ func benchmarkMatchmakerProcessTickets(ticketsMax int32, unmatchable int, minCou processedTicketsCount.Store(0) ctx, cancel = context.WithCancel(context.Background()) } + + cancel() } func BenchmarkMatchmakerProcessTickets100_min2_max2(b *testing.B) { diff --git a/server/metrics_grpc_handler.go b/server/metrics_grpc_handler.go index 9443fed7e4..63b77d37e4 100644 --- a/server/metrics_grpc_handler.go +++ b/server/metrics_grpc_handler.go @@ -61,9 +61,10 @@ func (m *MetricsGrpcHandler) HandleRPC(ctx context.Context, rs stats.RPCStats) { // For conn stats handling, the context used in HandleConn for this // connection will be derived from the context returned. // For RPC stats handling, -// - On server side, the context used in HandleRPC for all RPCs on this +// - On server side, the context used in HandleRPC for all RPCs on this +// // connection will be derived from the context returned. -// - On client side, the context is not derived from the context returned. +// - On client side, the context is not derived from the context returned. func (m *MetricsGrpcHandler) TagConn(ctx context.Context, _ *stats.ConnTagInfo) context.Context { return ctx } diff --git a/server/party_handler_test.go b/server/party_handler_test.go index bb0258e638..63399ed716 100644 --- a/server/party_handler_test.go +++ b/server/party_handler_test.go @@ -25,7 +25,7 @@ import ( func TestPartyMatchmakerAddAndRemove(t *testing.T) { consoleLogger := loggerForTest(t) partyHandler, cleanup := createTestPartyHandler(t, consoleLogger) - defer cleanup() + defer cleanup() //nolint:errcheck sessionID, _ := uuid.NewV4() userID, _ := uuid.NewV4() diff --git a/server/party_presence.go b/server/party_presence.go index 2996d1f3db..311a12a3ea 100644 --- a/server/party_presence.go +++ b/server/party_presence.go @@ -107,9 +107,7 @@ func (m *PartyPresenceList) Join(joins []*Presence) ([]*Presence, error) { } if len(processed) > 0 { presencesRead := make([]*PartyPresenceListItem, 0, len(m.presences)) - for _, presence := range m.presences { - presencesRead = append(presencesRead, presence) - } + presencesRead = append(presencesRead, m.presences...) m.presencesRead.Store(presencesRead) } m.Unlock() @@ -140,9 +138,7 @@ func (m *PartyPresenceList) Leave(leaves []*Presence) ([]*Presence, []*Presence) } if len(processed) > 0 { presencesRead := make([]*PartyPresenceListItem, 0, len(m.presences)) - for _, presence := range m.presences { - presencesRead = append(presencesRead, presence) - } + presencesRead = append(presencesRead, m.presences...) m.presencesRead.Store(presencesRead) } m.Unlock() diff --git a/server/pipeline.go b/server/pipeline.go index 523c8a3530..b0569f8e0b 100644 --- a/server/pipeline.go +++ b/server/pipeline.go @@ -66,7 +66,7 @@ func (p *Pipeline) ProcessRequest(logger *zap.Logger, session Session, in *rtapi } if in.Message == nil { - session.Send(&rtapi.Envelope{Cid: in.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: in.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_MISSING_PAYLOAD), Message: "Missing message.", }}}, true) @@ -136,7 +136,7 @@ func (p *Pipeline) ProcessRequest(logger *zap.Logger, session Session, in *rtapi // If we reached this point the envelope was valid but the contents are missing or unknown. // Usually caused by a version mismatch, and should cause the session making this pipeline request to close. logger.Error("Unrecognizable payload received.", zap.Any("payload", in)) - session.Send(&rtapi.Envelope{Cid: in.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: in.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_UNRECOGNIZED_PAYLOAD), Message: "Unrecognized message.", }}}, true) @@ -157,7 +157,7 @@ func (p *Pipeline) ProcessRequest(logger *zap.Logger, session Session, in *rtapi if hookErr != nil { // Errors from before hooks do not close the session. - session.Send(&rtapi.Envelope{Cid: in.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: in.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_RUNTIME_FUNCTION_EXCEPTION), Message: hookErr.Error(), }}}, true) @@ -165,7 +165,7 @@ func (p *Pipeline) ProcessRequest(logger *zap.Logger, session Session, in *rtapi } else if hookResult == nil { // If result is nil, requested resource is disabled. Sessions calling disabled resources will be closed. logger.Warn("Intercepted a disabled resource.", zap.String("resource", messageName)) - session.Send(&rtapi.Envelope{Cid: in.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: in.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_UNRECOGNIZED_PAYLOAD), Message: "Requested resource was not found.", }}}, true) @@ -181,7 +181,7 @@ func (p *Pipeline) ProcessRequest(logger *zap.Logger, session Session, in *rtapi if success && messageName != "" { // Unsuccessful operations do not trigger after hooks. if fn := p.runtime.AfterRt(messageNameID); fn != nil { - fn(session.Context(), logger, session.UserID().String(), session.Username(), session.Vars(), session.Expiry(), session.ID().String(), session.ClientIP(), session.ClientPort(), session.Lang(), out, in) + _ = fn(session.Context(), logger, session.UserID().String(), session.Username(), session.Vars(), session.Expiry(), session.ID().String(), session.ClientIP(), session.ClientPort(), session.Lang(), out, in) } } diff --git a/server/pipeline_channel.go b/server/pipeline_channel.go index 65edafb128..2f09bff873 100644 --- a/server/pipeline_channel.go +++ b/server/pipeline_channel.go @@ -51,13 +51,13 @@ func (p *Pipeline) channelJoin(logger *zap.Logger, session Session, envelope *rt channelID, stream, err := BuildChannelId(session.Context(), logger, p.db, session.UserID(), incoming.Target, rtapi.ChannelJoin_Type(incoming.Type)) if err != nil { if errors.Is(err, runtime.ErrInvalidChannelTarget) || errors.Is(err, runtime.ErrInvalidChannelType) { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: err.Error(), }}}, true) return false, nil } else { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_RUNTIME_EXCEPTION), Message: err.Error(), }}}, true) @@ -73,7 +73,7 @@ func (p *Pipeline) channelJoin(logger *zap.Logger, session Session, envelope *rt } success, isNew := p.tracker.Track(session.Context(), session.ID(), stream, session.UserID(), meta, false) if !success { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_RUNTIME_EXCEPTION), Message: "Error joining channel", }}}, true) @@ -161,7 +161,7 @@ func (p *Pipeline) channelJoin(logger *zap.Logger, session Session, envelope *rt } out := &rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Channel{Channel: channel}} - session.Send(out, true) + _ = session.Send(out, true) return true, out } @@ -171,7 +171,7 @@ func (p *Pipeline) channelLeave(logger *zap.Logger, session Session, envelope *r streamConversionResult, err := ChannelIdToStream(incoming.ChannelId) if err != nil { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid channel identifier", }}}, true) @@ -181,7 +181,7 @@ func (p *Pipeline) channelLeave(logger *zap.Logger, session Session, envelope *r p.tracker.Untrack(session.ID(), streamConversionResult.Stream, session.UserID()) out := &rtapi.Envelope{Cid: envelope.Cid} - session.Send(out, true) + _ = session.Send(out, true) return true, out } @@ -191,7 +191,7 @@ func (p *Pipeline) channelMessageSend(logger *zap.Logger, session Session, envel streamConversionResult, err := ChannelIdToStream(incoming.ChannelId) if err != nil { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid channel identifier", }}}, true) @@ -199,7 +199,7 @@ func (p *Pipeline) channelMessageSend(logger *zap.Logger, session Session, envel } if maybeJSON := []byte(incoming.Content); !json.Valid(maybeJSON) || bytes.TrimSpace(maybeJSON)[0] != byteBracket { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Message content must be a valid JSON object", }}}, true) @@ -208,7 +208,7 @@ func (p *Pipeline) channelMessageSend(logger *zap.Logger, session Session, envel meta := p.tracker.GetLocalBySessionIDStreamUserID(session.ID(), streamConversionResult.Stream, session.UserID()) if meta == nil { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Must join channel before sending messages", }}}, true) @@ -218,7 +218,7 @@ func (p *Pipeline) channelMessageSend(logger *zap.Logger, session Session, envel ack, err := ChannelMessageSend(session.Context(), p.logger, p.db, p.router, streamConversionResult.Stream, incoming.ChannelId, incoming.Content, session.UserID().String(), session.Username(), meta.Persistence) switch err { case errChannelMessagePersist: - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = 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 to channel history", }}}, true) @@ -226,7 +226,7 @@ func (p *Pipeline) channelMessageSend(logger *zap.Logger, session Session, envel } out := &rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_ChannelMessageAck{ChannelMessageAck: ack}} - session.Send(out, true) + _ = session.Send(out, true) return true, out } @@ -235,7 +235,7 @@ func (p *Pipeline) channelMessageUpdate(logger *zap.Logger, session Session, env incoming := envelope.GetChannelMessageUpdate() if _, err := uuid.FromString(incoming.MessageId); err != nil { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid message identifier", }}}, true) @@ -244,7 +244,7 @@ func (p *Pipeline) channelMessageUpdate(logger *zap.Logger, session Session, env streamConversionResult, err := ChannelIdToStream(incoming.ChannelId) if err != nil { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid channel identifier", }}}, true) @@ -252,7 +252,7 @@ func (p *Pipeline) channelMessageUpdate(logger *zap.Logger, session Session, env } if maybeJSON := []byte(incoming.Content); !json.Valid(maybeJSON) || bytes.TrimSpace(maybeJSON)[0] != byteBracket { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Message content must be a valid JSON object", }}}, true) @@ -261,7 +261,7 @@ func (p *Pipeline) channelMessageUpdate(logger *zap.Logger, session Session, env meta := p.tracker.GetLocalBySessionIDStreamUserID(session.ID(), streamConversionResult.Stream, session.UserID()) if meta == nil { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Must join channel before updating messages", }}}, true) @@ -271,20 +271,20 @@ func (p *Pipeline) channelMessageUpdate(logger *zap.Logger, session Session, env ack, err := ChannelMessageUpdate(session.Context(), p.logger, p.db, p.router, streamConversionResult.Stream, incoming.ChannelId, incoming.MessageId, incoming.Content, session.UserID().String(), session.Username(), meta.Persistence) switch err { case errChannelMessageNotFound: - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Could not find message to update in channel history", }}}, true) return false, nil case errChannelMessagePersist: - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = 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) } out := &rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_ChannelMessageAck{ChannelMessageAck: ack}} - session.Send(out, true) + _ = session.Send(out, true) return true, out } @@ -293,7 +293,7 @@ func (p *Pipeline) channelMessageRemove(logger *zap.Logger, session Session, env incoming := envelope.GetChannelMessageRemove() if _, err := uuid.FromString(incoming.MessageId); err != nil { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid message identifier", }}}, true) @@ -302,7 +302,7 @@ func (p *Pipeline) channelMessageRemove(logger *zap.Logger, session Session, env streamConversionResult, err := ChannelIdToStream(incoming.ChannelId) if err != nil { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid channel identifier", }}}, true) @@ -311,7 +311,7 @@ func (p *Pipeline) channelMessageRemove(logger *zap.Logger, session Session, env meta := p.tracker.GetLocalBySessionIDStreamUserID(session.ID(), streamConversionResult.Stream, session.UserID()) if meta == nil { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Must join channel before removing messages", }}}, true) @@ -321,20 +321,20 @@ func (p *Pipeline) channelMessageRemove(logger *zap.Logger, session Session, env ack, err := ChannelMessageRemove(session.Context(), p.logger, p.db, p.router, streamConversionResult.Stream, incoming.ChannelId, incoming.MessageId, session.UserID().String(), session.Username(), meta.Persistence) switch err { case errChannelMessageNotFound: - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Could not find message to remove in channel history", }}}, true) return false, nil case errChannelMessagePersist: - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = 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) } out := &rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_ChannelMessageAck{ChannelMessageAck: ack}} - session.Send(out, true) + _ = session.Send(out, true) return true, out } diff --git a/server/pipeline_match.go b/server/pipeline_match.go index 8e25548226..02d7dfbc4b 100644 --- a/server/pipeline_match.go +++ b/server/pipeline_match.go @@ -87,7 +87,7 @@ func (p *Pipeline) matchCreate(logger *zap.Logger, session Session, envelope *rt Username: username, }, }}} - session.Send(out, true) + _ = session.Send(out, true) return true, out } @@ -106,7 +106,7 @@ func (p *Pipeline) matchJoin(logger *zap.Logger, session Session, envelope *rtap // Validate the match ID. matchIDComponents := strings.SplitN(matchIDString, ".", 2) if len(matchIDComponents) != 2 { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid match ID", }}}, true) @@ -114,7 +114,7 @@ func (p *Pipeline) matchJoin(logger *zap.Logger, session Session, envelope *rtap } matchID, err = uuid.FromString(matchIDComponents[0]) if err != nil { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid match ID", }}}, true) @@ -129,7 +129,7 @@ func (p *Pipeline) matchJoin(logger *zap.Logger, session Session, envelope *rtap return []byte(p.config.GetSession().EncryptionKey), nil }) if err != nil { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid match token", }}}, true) @@ -137,7 +137,7 @@ func (p *Pipeline) matchJoin(logger *zap.Logger, session Session, envelope *rtap } claims, ok := token.Claims.(jwt.MapClaims) if !ok || !token.Valid { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid match token", }}}, true) @@ -147,7 +147,7 @@ func (p *Pipeline) matchJoin(logger *zap.Logger, session Session, envelope *rtap // Validate the match ID. matchIDComponents := strings.SplitN(matchIDString, ".", 2) if len(matchIDComponents) != 2 { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid match token", }}}, true) @@ -155,7 +155,7 @@ func (p *Pipeline) matchJoin(logger *zap.Logger, session Session, envelope *rtap } matchID, err = uuid.FromString(matchIDComponents[0]) if err != nil { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid match token", }}}, true) @@ -164,13 +164,13 @@ func (p *Pipeline) matchJoin(logger *zap.Logger, session Session, envelope *rtap node = matchIDComponents[1] allowEmpty = true case nil: - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "No match ID or token found", }}}, true) return false, nil default: - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Unrecognized match ID or token", }}}, true) @@ -187,7 +187,7 @@ func (p *Pipeline) matchJoin(logger *zap.Logger, session Session, envelope *rtap stream := PresenceStream{Mode: mode, Subject: matchID, Label: node} if !allowEmpty && !p.tracker.StreamExists(stream) { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_MATCH_NOT_FOUND), Message: "Match not found", }}}, true) @@ -233,7 +233,7 @@ func (p *Pipeline) matchJoin(logger *zap.Logger, session Session, envelope *rtap found, allow, isNew, reason, l, ps := p.matchRegistry.JoinAttempt(session.Context(), matchID, node, session.UserID(), session.ID(), username, session.Expiry(), session.Vars(), session.ClientIP(), session.ClientPort(), p.node, incoming.Metadata) if !found { // Match did not exist. - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_MATCH_NOT_FOUND), Message: "Match not found", }}}, true) @@ -245,7 +245,7 @@ func (p *Pipeline) matchJoin(logger *zap.Logger, session Session, envelope *rtap reason = "Match join rejected" } // Match exists, but rejected the join. - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_MATCH_JOIN_REJECTED), Message: reason, }}}, true) @@ -294,7 +294,7 @@ func (p *Pipeline) matchJoin(logger *zap.Logger, session Session, envelope *rtap Username: username, }, }}} - session.Send(out, true) + _ = session.Send(out, true) return true, out } @@ -303,7 +303,7 @@ func (p *Pipeline) matchLeave(logger *zap.Logger, session Session, envelope *rta // Validate the match ID. matchIDComponents := strings.SplitN(envelope.GetMatchLeave().MatchId, ".", 2) if len(matchIDComponents) != 2 { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid match ID", }}}, true) @@ -311,7 +311,7 @@ func (p *Pipeline) matchLeave(logger *zap.Logger, session Session, envelope *rta } matchID, err := uuid.FromString(matchIDComponents[0]) if err != nil { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid match ID", }}}, true) @@ -330,7 +330,7 @@ func (p *Pipeline) matchLeave(logger *zap.Logger, session Session, envelope *rta p.tracker.Untrack(session.ID(), stream, session.UserID()) out := &rtapi.Envelope{Cid: envelope.Cid} - session.Send(out, true) + _ = session.Send(out, true) return true, out } @@ -341,7 +341,7 @@ func (p *Pipeline) matchDataSend(logger *zap.Logger, session Session, envelope * // Validate the match ID. matchIDComponents := strings.SplitN(incoming.MatchId, ".", 2) if len(matchIDComponents) != 2 { - session.Send(&rtapi.Envelope{Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid match ID", }}}, true) @@ -349,7 +349,7 @@ func (p *Pipeline) matchDataSend(logger *zap.Logger, session Session, envelope * } matchID, err := uuid.FromString(matchIDComponents[0]) if err != nil { - session.Send(&rtapi.Envelope{Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid match ID", }}}, true) diff --git a/server/pipeline_matchmaker.go b/server/pipeline_matchmaker.go index fc1741c120..7b4e7c31df 100644 --- a/server/pipeline_matchmaker.go +++ b/server/pipeline_matchmaker.go @@ -26,7 +26,7 @@ func (p *Pipeline) matchmakerAdd(logger *zap.Logger, session Session, envelope * // Minimum count. minCount := int(incoming.MinCount) if minCount < 2 { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid minimum count, must be >= 2", }}}, true) @@ -36,7 +36,7 @@ func (p *Pipeline) matchmakerAdd(logger *zap.Logger, session Session, envelope * // Maximum count, must be at least minimum count. maxCount := int(incoming.MaxCount) if maxCount < minCount { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid maximum count, must be >= minimum count", }}}, true) @@ -48,21 +48,21 @@ func (p *Pipeline) matchmakerAdd(logger *zap.Logger, session Session, envelope * if incoming.CountMultiple != nil { countMultiple = int(incoming.CountMultiple.GetValue()) if countMultiple < 1 { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid count multiple, must be >= 1", }}}, true) return false, nil } if minCount%countMultiple != 0 { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid count multiple for minimum count, must divide", }}}, true) return false, nil } if maxCount%countMultiple != 0 { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid count multiple for maximum count, must divide", }}}, true) @@ -87,7 +87,7 @@ func (p *Pipeline) matchmakerAdd(logger *zap.Logger, session Session, envelope * ticket, _, err := p.matchmaker.Add(session.Context(), presences, session.ID().String(), "", query, minCount, maxCount, countMultiple, incoming.StringProperties, incoming.NumericProperties) if err != nil { logger.Error("Error adding to matchmaker", zap.Error(err)) - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_RUNTIME_EXCEPTION), Message: "Error adding to matchmaker", }}}, true) @@ -98,7 +98,7 @@ func (p *Pipeline) matchmakerAdd(logger *zap.Logger, session Session, envelope * out := &rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_MatchmakerTicket{MatchmakerTicket: &rtapi.MatchmakerTicket{ Ticket: ticket, }}} - session.Send(out, true) + _ = session.Send(out, true) return true, out } @@ -108,7 +108,7 @@ func (p *Pipeline) matchmakerRemove(logger *zap.Logger, session Session, envelop // Ticket is required. if incoming.Ticket == "" { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid matchmaker ticket", }}}, true) @@ -118,7 +118,7 @@ func (p *Pipeline) matchmakerRemove(logger *zap.Logger, session Session, envelop // Run matchmaker remove. if err := p.matchmaker.RemoveSession(session.ID().String(), incoming.Ticket); err != nil { if err == runtime.ErrMatchmakerTicketNotFound { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Matchmaker ticket not found", }}}, true) @@ -126,7 +126,7 @@ func (p *Pipeline) matchmakerRemove(logger *zap.Logger, session Session, envelop } logger.Error("Error removing matchmaker ticket", zap.Error(err)) - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_RUNTIME_EXCEPTION), Message: "Error removing matchmaker ticket", }}}, true) @@ -134,7 +134,7 @@ func (p *Pipeline) matchmakerRemove(logger *zap.Logger, session Session, envelop } out := &rtapi.Envelope{Cid: envelope.Cid} - session.Send(out, true) + _ = session.Send(out, true) return true, out } diff --git a/server/pipeline_party.go b/server/pipeline_party.go index 0ec6e724d0..991bebe5a0 100644 --- a/server/pipeline_party.go +++ b/server/pipeline_party.go @@ -28,7 +28,7 @@ func (p *Pipeline) partyCreate(logger *zap.Logger, session Session, envelope *rt // Validate party creation parameters. if incoming.MaxSize < 0 || incoming.MaxSize > 256 { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid party max size, must be 1-256", }}}, true) @@ -44,7 +44,7 @@ func (p *Pipeline) partyCreate(logger *zap.Logger, session Session, envelope *rt // Handle through the party registry. ph := p.partyRegistry.Create(incoming.Open, int(incoming.MaxSize), presence) if ph == nil { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_RUNTIME_EXCEPTION), Message: "Failed to create party", }}}, true) @@ -58,7 +58,7 @@ func (p *Pipeline) partyCreate(logger *zap.Logger, session Session, envelope *rt Status: "", }, false) if !success { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_RUNTIME_EXCEPTION), Message: "Error tracking party creation", }}}, true) @@ -73,7 +73,7 @@ func (p *Pipeline) partyCreate(logger *zap.Logger, session Session, envelope *rt Leader: presence, Presences: []*rtapi.UserPresence{presence}, }}} - session.Send(out, true) + _ = session.Send(out, true) return true, out } @@ -84,7 +84,7 @@ func (p *Pipeline) partyJoin(logger *zap.Logger, session Session, envelope *rtap // Validate the party ID. partyIDComponents := strings.SplitN(incoming.PartyId, ".", 2) if len(partyIDComponents) != 2 { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid party ID", }}}, true) @@ -92,7 +92,7 @@ func (p *Pipeline) partyJoin(logger *zap.Logger, session Session, envelope *rtap } partyID, err := uuid.FromString(partyIDComponents[0]) if err != nil { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid party ID", }}}, true) @@ -114,7 +114,7 @@ func (p *Pipeline) partyJoin(logger *zap.Logger, session Session, envelope *rtap }, }) if err != nil { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: fmt.Sprintf("Error joining party: %s", err.Error()), }}}, true) @@ -129,7 +129,7 @@ func (p *Pipeline) partyJoin(logger *zap.Logger, session Session, envelope *rtap Status: "", }, false) if !success { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_RUNTIME_EXCEPTION), Message: "Error tracking party join", }}}, true) @@ -138,7 +138,7 @@ func (p *Pipeline) partyJoin(logger *zap.Logger, session Session, envelope *rtap } out := &rtapi.Envelope{Cid: envelope.Cid} - session.Send(out, true) + _ = session.Send(out, true) return true, out } @@ -149,7 +149,7 @@ func (p *Pipeline) partyLeave(logger *zap.Logger, session Session, envelope *rta // Validate the party ID. partyIDComponents := strings.SplitN(incoming.PartyId, ".", 2) if len(partyIDComponents) != 2 { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid party ID", }}}, true) @@ -157,7 +157,7 @@ func (p *Pipeline) partyLeave(logger *zap.Logger, session Session, envelope *rta } partyID, err := uuid.FromString(partyIDComponents[0]) if err != nil { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid party ID", }}}, true) @@ -169,7 +169,7 @@ func (p *Pipeline) partyLeave(logger *zap.Logger, session Session, envelope *rta p.tracker.Untrack(session.ID(), PresenceStream{Mode: StreamModeParty, Subject: partyID, Label: node}, session.UserID()) out := &rtapi.Envelope{Cid: envelope.Cid} - session.Send(out, true) + _ = session.Send(out, true) return true, nil } @@ -179,7 +179,7 @@ func (p *Pipeline) partyPromote(logger *zap.Logger, session Session, envelope *r // Validate presence info. if incoming.Presence == nil || incoming.Presence.UserId == "" || incoming.Presence.SessionId == "" || incoming.Presence.Username == "" { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid presence", }}}, true) @@ -189,7 +189,7 @@ func (p *Pipeline) partyPromote(logger *zap.Logger, session Session, envelope *r // Validate the party ID. partyIDComponents := strings.SplitN(incoming.PartyId, ".", 2) if len(partyIDComponents) != 2 { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid party ID", }}}, true) @@ -197,7 +197,7 @@ func (p *Pipeline) partyPromote(logger *zap.Logger, session Session, envelope *r } partyID, err := uuid.FromString(partyIDComponents[0]) if err != nil { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid party ID", }}}, true) @@ -208,7 +208,7 @@ func (p *Pipeline) partyPromote(logger *zap.Logger, session Session, envelope *r // Handle through the party registry. err = p.partyRegistry.PartyPromote(session.Context(), partyID, node, session.ID().String(), p.node, incoming.Presence) if err != nil { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: fmt.Sprintf("Error promoting new party leader: %s", err.Error()), }}}, true) @@ -216,7 +216,7 @@ func (p *Pipeline) partyPromote(logger *zap.Logger, session Session, envelope *r } out := &rtapi.Envelope{Cid: envelope.Cid} - session.Send(out, true) + _ = session.Send(out, true) return true, out } @@ -226,7 +226,7 @@ func (p *Pipeline) partyAccept(logger *zap.Logger, session Session, envelope *rt // Validate presence info. if incoming.Presence == nil || incoming.Presence.UserId == "" || incoming.Presence.SessionId == "" || incoming.Presence.Username == "" { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid presence", }}}, true) @@ -236,7 +236,7 @@ func (p *Pipeline) partyAccept(logger *zap.Logger, session Session, envelope *rt // Validate the party ID. partyIDComponents := strings.SplitN(incoming.PartyId, ".", 2) if len(partyIDComponents) != 2 { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid party ID", }}}, true) @@ -244,7 +244,7 @@ func (p *Pipeline) partyAccept(logger *zap.Logger, session Session, envelope *rt } partyID, err := uuid.FromString(partyIDComponents[0]) if err != nil { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid party ID", }}}, true) @@ -255,7 +255,7 @@ func (p *Pipeline) partyAccept(logger *zap.Logger, session Session, envelope *rt // Handle through the party registry. err = p.partyRegistry.PartyAccept(session.Context(), partyID, node, session.ID().String(), p.node, incoming.Presence) if err != nil { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: fmt.Sprintf("Error accepting party join request: %s", err.Error()), }}}, true) @@ -263,7 +263,7 @@ func (p *Pipeline) partyAccept(logger *zap.Logger, session Session, envelope *rt } out := &rtapi.Envelope{Cid: envelope.Cid} - session.Send(out, true) + _ = session.Send(out, true) return true, out } @@ -273,7 +273,7 @@ func (p *Pipeline) partyRemove(logger *zap.Logger, session Session, envelope *rt // Validate presence info. if incoming.Presence == nil || incoming.Presence.UserId == "" || incoming.Presence.SessionId == "" || incoming.Presence.Username == "" { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid presence", }}}, true) @@ -283,7 +283,7 @@ func (p *Pipeline) partyRemove(logger *zap.Logger, session Session, envelope *rt // Validate the party ID. partyIDComponents := strings.SplitN(incoming.PartyId, ".", 2) if len(partyIDComponents) != 2 { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid party ID", }}}, true) @@ -291,7 +291,7 @@ func (p *Pipeline) partyRemove(logger *zap.Logger, session Session, envelope *rt } partyID, err := uuid.FromString(partyIDComponents[0]) if err != nil { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid party ID", }}}, true) @@ -302,7 +302,7 @@ func (p *Pipeline) partyRemove(logger *zap.Logger, session Session, envelope *rt // Handle through the party registry. err = p.partyRegistry.PartyRemove(session.Context(), partyID, node, session.ID().String(), p.node, incoming.Presence) if err != nil { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: fmt.Sprintf("Error removing party member or join request: %s", err.Error()), }}}, true) @@ -310,7 +310,7 @@ func (p *Pipeline) partyRemove(logger *zap.Logger, session Session, envelope *rt } out := &rtapi.Envelope{Cid: envelope.Cid} - session.Send(out, true) + _ = session.Send(out, true) return true, out } @@ -321,7 +321,7 @@ func (p *Pipeline) partyClose(logger *zap.Logger, session Session, envelope *rta // Validate the party ID. partyIDComponents := strings.SplitN(incoming.PartyId, ".", 2) if len(partyIDComponents) != 2 { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid party ID", }}}, true) @@ -329,7 +329,7 @@ func (p *Pipeline) partyClose(logger *zap.Logger, session Session, envelope *rta } partyID, err := uuid.FromString(partyIDComponents[0]) if err != nil { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid party ID", }}}, true) @@ -340,7 +340,7 @@ func (p *Pipeline) partyClose(logger *zap.Logger, session Session, envelope *rta // Handle through the party registry. err = p.partyRegistry.PartyClose(session.Context(), partyID, node, session.ID().String(), p.node) if err != nil { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: fmt.Sprintf("Error closing party: %s", err.Error()), }}}, true) @@ -348,7 +348,7 @@ func (p *Pipeline) partyClose(logger *zap.Logger, session Session, envelope *rta } out := &rtapi.Envelope{Cid: envelope.Cid} - session.Send(out, true) + _ = session.Send(out, true) return true, out } @@ -359,7 +359,7 @@ func (p *Pipeline) partyJoinRequestList(logger *zap.Logger, session Session, env // Validate the party ID. partyIDComponents := strings.SplitN(incoming.PartyId, ".", 2) if len(partyIDComponents) != 2 { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid party ID", }}}, true) @@ -367,7 +367,7 @@ func (p *Pipeline) partyJoinRequestList(logger *zap.Logger, session Session, env } partyID, err := uuid.FromString(partyIDComponents[0]) if err != nil { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid party ID", }}}, true) @@ -378,7 +378,7 @@ func (p *Pipeline) partyJoinRequestList(logger *zap.Logger, session Session, env // Handle through the party registry. presences, err := p.partyRegistry.PartyJoinRequestList(session.Context(), partyID, node, session.ID().String(), p.node) if err != nil { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: fmt.Sprintf("Error listing party join requests: %s", err.Error()), }}}, true) @@ -389,7 +389,7 @@ func (p *Pipeline) partyJoinRequestList(logger *zap.Logger, session Session, env PartyId: incoming.PartyId, Presences: presences, }}} - session.Send(out, true) + _ = session.Send(out, true) return true, out } @@ -400,7 +400,7 @@ func (p *Pipeline) partyMatchmakerAdd(logger *zap.Logger, session Session, envel // Minimum count. minCount := int(incoming.MinCount) if minCount < 2 { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid minimum count, must be >= 2", }}}, true) @@ -410,7 +410,7 @@ func (p *Pipeline) partyMatchmakerAdd(logger *zap.Logger, session Session, envel // Maximum count, must be at least minimum count. maxCount := int(incoming.MaxCount) if maxCount < minCount { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid maximum count, must be >= minimum count", }}}, true) @@ -422,21 +422,21 @@ func (p *Pipeline) partyMatchmakerAdd(logger *zap.Logger, session Session, envel if incoming.CountMultiple != nil { countMultiple = int(incoming.CountMultiple.GetValue()) if countMultiple < 1 { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid count multiple, must be >= 1", }}}, true) return false, nil } if minCount%countMultiple != 0 { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid count multiple for minimum count, must divide", }}}, true) return false, nil } if maxCount%countMultiple != 0 { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid count multiple for maximum count, must divide", }}}, true) @@ -452,7 +452,7 @@ func (p *Pipeline) partyMatchmakerAdd(logger *zap.Logger, session Session, envel // Validate the party ID. partyIDComponents := strings.SplitN(incoming.PartyId, ".", 2) if len(partyIDComponents) != 2 { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid party ID", }}}, true) @@ -460,7 +460,7 @@ func (p *Pipeline) partyMatchmakerAdd(logger *zap.Logger, session Session, envel } partyID, err := uuid.FromString(partyIDComponents[0]) if err != nil { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid party ID", }}}, true) @@ -471,7 +471,7 @@ func (p *Pipeline) partyMatchmakerAdd(logger *zap.Logger, session Session, envel // Handle through the party registry. ticket, memberPresenceIDs, err := p.partyRegistry.PartyMatchmakerAdd(session.Context(), partyID, node, session.ID().String(), p.node, query, minCount, maxCount, countMultiple, incoming.StringProperties, incoming.NumericProperties) if err != nil { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: fmt.Sprintf("Error adding party to matchmaker: %s", err.Error()), }}}, true) @@ -483,7 +483,7 @@ func (p *Pipeline) partyMatchmakerAdd(logger *zap.Logger, session Session, envel PartyId: incoming.PartyId, Ticket: ticket, }}} - session.Send(out, true) + _ = session.Send(out, true) if len(memberPresenceIDs) != 0 { // Notify all other party members. @@ -506,7 +506,7 @@ func (p *Pipeline) partyMatchmakerRemove(logger *zap.Logger, session Session, en // Ticket is required. if incoming.Ticket == "" { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid matchmaker ticket", }}}, true) @@ -516,7 +516,7 @@ func (p *Pipeline) partyMatchmakerRemove(logger *zap.Logger, session Session, en // Validate the party ID. partyIDComponents := strings.SplitN(incoming.PartyId, ".", 2) if len(partyIDComponents) != 2 { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid party ID", }}}, true) @@ -524,7 +524,7 @@ func (p *Pipeline) partyMatchmakerRemove(logger *zap.Logger, session Session, en } partyID, err := uuid.FromString(partyIDComponents[0]) if err != nil { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid party ID", }}}, true) @@ -535,7 +535,7 @@ func (p *Pipeline) partyMatchmakerRemove(logger *zap.Logger, session Session, en // Handle through the party registry. err = p.partyRegistry.PartyMatchmakerRemove(session.Context(), partyID, node, session.ID().String(), p.node, incoming.Ticket) if err != nil { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: fmt.Sprintf("Error closing party: %s", err.Error()), }}}, true) @@ -543,7 +543,7 @@ func (p *Pipeline) partyMatchmakerRemove(logger *zap.Logger, session Session, en } out := &rtapi.Envelope{Cid: envelope.Cid} - session.Send(out, true) + _ = session.Send(out, true) return true, out } @@ -554,7 +554,7 @@ func (p *Pipeline) partyDataSend(logger *zap.Logger, session Session, envelope * // Validate the party ID. partyIDComponents := strings.SplitN(incoming.PartyId, ".", 2) if len(partyIDComponents) != 2 { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid party ID", }}}, true) @@ -562,7 +562,7 @@ func (p *Pipeline) partyDataSend(logger *zap.Logger, session Session, envelope * } partyID, err := uuid.FromString(partyIDComponents[0]) if err != nil { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid party ID", }}}, true) @@ -573,7 +573,7 @@ func (p *Pipeline) partyDataSend(logger *zap.Logger, session Session, envelope * // Handle through the party registry. err = p.partyRegistry.PartyDataSend(session.Context(), partyID, node, session.ID().String(), p.node, incoming.OpCode, incoming.Data) if err != nil { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: fmt.Sprintf("Error sending party data: %s", err.Error()), }}}, true) @@ -581,7 +581,7 @@ func (p *Pipeline) partyDataSend(logger *zap.Logger, session Session, envelope * } out := &rtapi.Envelope{Cid: envelope.Cid} - session.Send(out, true) + _ = session.Send(out, true) return true, out } diff --git a/server/pipeline_ping.go b/server/pipeline_ping.go index 0ea644d95b..727f376376 100644 --- a/server/pipeline_ping.go +++ b/server/pipeline_ping.go @@ -21,7 +21,7 @@ import ( func (p *Pipeline) ping(logger *zap.Logger, session Session, envelope *rtapi.Envelope) (bool, *rtapi.Envelope) { out := &rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Pong{Pong: &rtapi.Pong{}}} - session.Send(out, true) + _ = session.Send(out, true) return true, out } diff --git a/server/pipeline_rpc.go b/server/pipeline_rpc.go index 3255a5fa1a..2c02659192 100644 --- a/server/pipeline_rpc.go +++ b/server/pipeline_rpc.go @@ -25,7 +25,7 @@ import ( func (p *Pipeline) rpc(logger *zap.Logger, session Session, envelope *rtapi.Envelope) (bool, *rtapi.Envelope) { rpcMessage := envelope.GetRpc() if rpcMessage.Id == "" { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "RPC ID must be set", }}}, true) @@ -36,7 +36,7 @@ func (p *Pipeline) rpc(logger *zap.Logger, session Session, envelope *rtapi.Enve fn := p.runtime.Rpc(id) if fn == nil { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_RUNTIME_FUNCTION_NOT_FOUND), Message: "RPC function not found", }}}, true) @@ -45,7 +45,7 @@ func (p *Pipeline) rpc(logger *zap.Logger, session Session, envelope *rtapi.Enve result, fnErr, _ := fn(session.Context(), nil, nil, session.UserID().String(), session.Username(), session.Vars(), session.Expiry(), session.ID().String(), session.ClientIP(), session.ClientPort(), session.Lang(), rpcMessage.Payload) if fnErr != nil { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_RUNTIME_FUNCTION_EXCEPTION), Message: fnErr.Error(), }}}, true) @@ -56,7 +56,7 @@ func (p *Pipeline) rpc(logger *zap.Logger, session Session, envelope *rtapi.Enve Id: rpcMessage.Id, Payload: result, }}} - session.Send(out, true) + _ = session.Send(out, true) return true, out } diff --git a/server/pipeline_status.go b/server/pipeline_status.go index 117478acd2..7ece03a814 100644 --- a/server/pipeline_status.go +++ b/server/pipeline_status.go @@ -31,7 +31,7 @@ func (p *Pipeline) statusFollow(logger *zap.Logger, session Session, envelope *r out := &rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Status{Status: &rtapi.Status{ Presences: make([]*rtapi.UserPresence, 0), }}} - session.Send(out, true) + _ = session.Send(out, true) return true, nil } @@ -41,7 +41,7 @@ func (p *Pipeline) statusFollow(logger *zap.Logger, session Session, envelope *r for _, uid := range incoming.UserIds { userID, err := uuid.FromString(uid) if err != nil { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid user identifier", }}}, true) @@ -60,7 +60,7 @@ func (p *Pipeline) statusFollow(logger *zap.Logger, session Session, envelope *r uniqueUsernames := make(map[string]struct{}, len(incoming.Usernames)) for _, username := range incoming.Usernames { if username == "" { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid username", }}}, true) @@ -78,7 +78,7 @@ func (p *Pipeline) statusFollow(logger *zap.Logger, session Session, envelope *r out := &rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Status{Status: &rtapi.Status{ Presences: make([]*rtapi.UserPresence, 0), }}} - session.Send(out, true) + _ = session.Send(out, true) return true, out } @@ -98,7 +98,7 @@ func (p *Pipeline) statusFollow(logger *zap.Logger, session Session, envelope *r rows, err := p.db.QueryContext(session.Context(), query, params...) if err != nil { logger.Error("Error checking users in status follow", zap.Error(err)) - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_RUNTIME_EXCEPTION), Message: "Could not check users", }}}, true) @@ -146,7 +146,7 @@ func (p *Pipeline) statusFollow(logger *zap.Logger, session Session, envelope *r rows, err := p.db.QueryContext(session.Context(), query, params...) if err != nil { logger.Error("Error checking users in status follow", zap.Error(err)) - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_RUNTIME_EXCEPTION), Message: "Could not check users", }}}, true) @@ -158,7 +158,7 @@ func (p *Pipeline) statusFollow(logger *zap.Logger, session Session, envelope *r if err := rows.Scan(&id, &username); err != nil { _ = rows.Close() logger.Error("Error scanning users in status follow", zap.Error(err)) - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_RUNTIME_EXCEPTION), Message: "Could not check users", }}}, true) @@ -217,7 +217,7 @@ func (p *Pipeline) statusFollow(logger *zap.Logger, session Session, envelope *r out := &rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Status{Status: &rtapi.Status{ Presences: presences, }}} - session.Send(out, true) + _ = session.Send(out, true) return true, out } @@ -227,7 +227,7 @@ func (p *Pipeline) statusUnfollow(logger *zap.Logger, session Session, envelope if len(incoming.UserIds) == 0 { out := &rtapi.Envelope{Cid: envelope.Cid} - session.Send(out, true) + _ = session.Send(out, true) return true, out } @@ -236,7 +236,7 @@ func (p *Pipeline) statusUnfollow(logger *zap.Logger, session Session, envelope for _, uid := range incoming.UserIds { userID, err := uuid.FromString(uid) if err != nil { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Invalid user identifier", }}}, true) @@ -252,7 +252,7 @@ func (p *Pipeline) statusUnfollow(logger *zap.Logger, session Session, envelope p.statusRegistry.Unfollow(session.ID(), userIDs) out := &rtapi.Envelope{Cid: envelope.Cid} - session.Send(out, true) + _ = session.Send(out, true) return true, out } @@ -264,13 +264,13 @@ func (p *Pipeline) statusUpdate(logger *zap.Logger, session Session, envelope *r p.tracker.Untrack(session.ID(), PresenceStream{Mode: StreamModeStatus, Subject: session.UserID()}, session.UserID()) out := &rtapi.Envelope{Cid: envelope.Cid} - session.Send(out, true) + _ = session.Send(out, true) return true, out } if len(incoming.Status.Value) > 2048 { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_BAD_INPUT), Message: "Status must be 2048 characters or less", }}}, true) @@ -284,7 +284,7 @@ func (p *Pipeline) statusUpdate(logger *zap.Logger, session Session, envelope *r }, false) if !success { - session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ + _ = session.Send(&rtapi.Envelope{Cid: envelope.Cid, Message: &rtapi.Envelope_Error{Error: &rtapi.Error{ Code: int32(rtapi.Error_RUNTIME_EXCEPTION), Message: "Error tracking status update", }}}, true) @@ -292,7 +292,7 @@ func (p *Pipeline) statusUpdate(logger *zap.Logger, session Session, envelope *r } out := &rtapi.Envelope{Cid: envelope.Cid} - session.Send(out, true) + _ = session.Send(out, true) return true, out } diff --git a/server/runtime.go b/server/runtime.go index 5eba95e439..ada2b62efe 100644 --- a/server/runtime.go +++ b/server/runtime.go @@ -521,8 +521,6 @@ type Runtime struct { leaderboardResetFunction RuntimeLeaderboardResetFunction eventFunctions *RuntimeEventFunctions - - consoleInfo *RuntimeInfo } type MatchNamesListFunction func() []string @@ -535,12 +533,12 @@ type MatchProvider struct { func (mp *MatchProvider) RegisterCreateFn(name string, fn RuntimeMatchCreateFunction) { mp.Lock() - newProviders := make([]RuntimeMatchCreateFunction, len(mp.providers)+1, len(mp.providers)+1) + newProviders := make([]RuntimeMatchCreateFunction, len(mp.providers)+1) copy(newProviders, mp.providers) newProviders[len(mp.providers)] = fn mp.providers = newProviders - newProviderNames := make([]string, len(mp.providerNames)+1, len(mp.providerNames)+1) + newProviderNames := make([]string, len(mp.providerNames)+1) copy(newProviderNames, mp.providerNames) newProviderNames[len(mp.providerNames)] = name mp.providerNames = newProviderNames @@ -657,15 +655,9 @@ func NewRuntime(ctx context.Context, logger, startupLogger *zap.Logger, db *sql. } allModules := make([]string, 0, len(jsModules)+len(luaModules)+len(goModules)) - for _, module := range jsModules { - allModules = append(allModules, module) - } - for _, module := range luaModules { - allModules = append(allModules, module) - } - for _, module := range goModules { - allModules = append(allModules, module) - } + allModules = append(allModules, jsModules...) + allModules = append(allModules, luaModules...) + allModules = append(allModules, goModules...) startupLogger.Info("Found runtime modules", zap.Int("count", len(allModules)), zap.Strings("modules", allModules)) @@ -2620,15 +2612,15 @@ func NewRuntime(ctx context.Context, logger, startupLogger *zap.Logger, db *sql. func runtimeInfo(paths []string, jsRpcIDs, luaRpcIDs, goRpcIDs map[string]bool, jsModules, luaModules, goModules []string) (*RuntimeInfo, error) { jsRpcs := make([]string, 0, len(jsRpcIDs)) - for id, _ := range jsRpcIDs { + for id := range jsRpcIDs { jsRpcs = append(jsRpcs, id) } luaRpcs := make([]string, 0, len(luaRpcIDs)) - for id, _ := range luaRpcIDs { + for id := range luaRpcIDs { luaRpcs = append(luaRpcs, id) } goRpcs := make([]string, 0, len(goRpcIDs)) - for id, _ := range goRpcIDs { + for id := range goRpcIDs { goRpcs = append(goRpcs, id) } diff --git a/server/runtime_go_context.go b/server/runtime_go_context.go index 6d91db10a5..6ed6a6d88c 100644 --- a/server/runtime_go_context.go +++ b/server/runtime_go_context.go @@ -20,6 +20,9 @@ import ( "github.com/heroiclabs/nakama-common/runtime" ) +// ignore warnings about strings being used as ctx keys +// +//nolint:staticcheck func NewRuntimeGoContext(ctx context.Context, node, version string, env map[string]string, mode RuntimeExecutionMode, headers, queryParams map[string][]string, sessionExpiry int64, userID, username string, vars map[string]string, sessionID, clientIP, clientPort, lang string) context.Context { ctx = context.WithValue(ctx, runtime.RUNTIME_CTX_ENV, env) ctx = context.WithValue(ctx, runtime.RUNTIME_CTX_MODE, mode.String()) diff --git a/server/runtime_go_match_core.go b/server/runtime_go_match_core.go index d0c520a48f..b9b17e332a 100644 --- a/server/runtime_go_match_core.go +++ b/server/runtime_go_match_core.go @@ -61,8 +61,8 @@ type RuntimeGoMatchCore struct { func NewRuntimeGoMatchCore(logger *zap.Logger, module string, matchRegistry MatchRegistry, router MessageRouter, id uuid.UUID, node, version string, stopped *atomic.Bool, db *sql.DB, env map[string]string, nk runtime.NakamaModule, match runtime.Match) (RuntimeMatchCore, error) { ctx, ctxCancelFn := context.WithCancel(context.Background()) ctx = NewRuntimeGoContext(ctx, node, version, env, RuntimeExecutionModeMatch, nil, nil, 0, "", "", nil, "", "", "", "") - ctx = context.WithValue(ctx, runtime.RUNTIME_CTX_MATCH_ID, fmt.Sprintf("%v.%v", id.String(), node)) - ctx = context.WithValue(ctx, runtime.RUNTIME_CTX_MATCH_NODE, node) + ctx = context.WithValue(ctx, runtime.RUNTIME_CTX_MATCH_ID, fmt.Sprintf("%v.%v", id.String(), node)) //nolint:staticcheck + ctx = context.WithValue(ctx, runtime.RUNTIME_CTX_MATCH_NODE, node) //nolint:staticcheck return &RuntimeGoMatchCore{ logger: logger, @@ -116,8 +116,8 @@ func (r *RuntimeGoMatchCore) MatchInit(presenceList *MatchPresenceList, deferMes } r.label.Store(label) - r.ctx = context.WithValue(r.ctx, runtime.RUNTIME_CTX_MATCH_TICK_RATE, tickRate) - r.ctx = context.WithValue(r.ctx, runtime.RUNTIME_CTX_MATCH_LABEL, label) + r.ctx = context.WithValue(r.ctx, runtime.RUNTIME_CTX_MATCH_TICK_RATE, tickRate) //nolint:staticcheck + r.ctx = context.WithValue(r.ctx, runtime.RUNTIME_CTX_MATCH_LABEL, label) //nolint:staticcheck r.deferMessageFn = deferMessageFn r.presenceList = presenceList @@ -125,6 +125,7 @@ func (r *RuntimeGoMatchCore) MatchInit(presenceList *MatchPresenceList, deferMes return state, tickRate, nil } +//nolint:staticcheck func (r *RuntimeGoMatchCore) MatchJoinAttempt(tick int64, state interface{}, userID, sessionID uuid.UUID, username string, sessionExpiry int64, vars map[string]string, clientIP, clientPort, node string, metadata map[string]string) (interface{}, bool, string, error) { presence := &MatchPresence{ Node: node, @@ -391,6 +392,6 @@ func (r *RuntimeGoMatchCore) MatchLabelUpdate(label string) error { r.label.Store(label) // This must be executed from inside a match call so safe to update here. - r.ctx = context.WithValue(r.ctx, runtime.RUNTIME_CTX_MATCH_LABEL, label) + r.ctx = context.WithValue(r.ctx, runtime.RUNTIME_CTX_MATCH_LABEL, label) //nolint:staticcheck return nil } diff --git a/server/runtime_go_nakama.go b/server/runtime_go_nakama.go index bb2aa34b67..e22f42e586 100644 --- a/server/runtime_go_nakama.go +++ b/server/runtime_go_nakama.go @@ -46,7 +46,6 @@ type RuntimeGoNakamaModule struct { logger *zap.Logger db *sql.DB protojsonMarshaler *protojson.MarshalOptions - protojsonUnmarshaler *protojson.UnmarshalOptions config Config socialClient *social.Client leaderboardCache LeaderboardCache @@ -2202,7 +2201,7 @@ func (n *RuntimeGoNakamaModule) LeaderboardCreate(ctx context.Context, id string return errors.New("expects a leaderboard ID string") } - sort := LeaderboardSortOrderDescending + var sort int switch sortOrder { case "desc", "descending": sort = LeaderboardSortOrderDescending @@ -2212,7 +2211,7 @@ func (n *RuntimeGoNakamaModule) LeaderboardCreate(ctx context.Context, id string return errors.New("expects sort order to be 'asc' or 'desc'") } - oper := LeaderboardOperatorBest + var oper int switch operator { case "best": oper = LeaderboardOperatorBest @@ -2473,7 +2472,7 @@ func (n *RuntimeGoNakamaModule) TournamentCreate(ctx context.Context, id string, return errors.New("expects a tournament ID string") } - sort := LeaderboardSortOrderDescending + var sort int switch sortOrder { case "desc", "descending": sort = LeaderboardSortOrderDescending @@ -2483,7 +2482,7 @@ func (n *RuntimeGoNakamaModule) TournamentCreate(ctx context.Context, id string, return errors.New("expects sort order to be 'asc' or 'desc'") } - oper := LeaderboardOperatorBest + var oper int switch operator { case "best": oper = LeaderboardOperatorBest diff --git a/server/runtime_javascript.go b/server/runtime_javascript.go index ab0bf67e05..7d691906a7 100644 --- a/server/runtime_javascript.go +++ b/server/runtime_javascript.go @@ -1683,7 +1683,10 @@ func NewRuntimeProviderJS(logger, startupLogger *zap.Logger, db *sql.DB, protojs runtimeProviderJS.newFn = func() *RuntimeJS { runtime := goja.New() - runtime.RunProgram(modCache.Modules[modCache.Names[0]].Program) + _, err := runtime.RunProgram(modCache.Modules[modCache.Names[0]].Program) + if err != nil { + logger.Fatal("Failed to initialize JavaScript runtime", zap.Error(err)) + } freezeGlobalObject(config, runtime) jsLoggerInst, err := NewJsLogger(runtime, logger) @@ -1778,7 +1781,7 @@ func cacheJavascriptModules(logger *zap.Logger, path, entrypoint string) (*Runti } else { modName = filepath.Base(entrypoint) } - ast, _ := goja.Parse(modName, string(content)) + modAst, _ := goja.Parse(modName, string(content)) prg, err := goja.Compile(modName, string(content), true) if err != nil { logger.Error("Could not compile JavaScript module", zap.String("module", modName), zap.Error(err)) @@ -1789,7 +1792,7 @@ func cacheJavascriptModules(logger *zap.Logger, path, entrypoint string) (*Runti Name: modName, Path: absEntrypoint, Program: prg, - Ast: ast, + Ast: modAst, }) return moduleCache, nil @@ -1809,25 +1812,25 @@ func (rp *RuntimeProviderJS) MatchmakerMatched(ctx context.Context, entries []*M entriesSlice := make([]interface{}, 0, len(entries)) for _, e := range entries { presenceObj := r.vm.NewObject() - presenceObj.Set("userId", e.Presence.UserId) - presenceObj.Set("sessionId", e.Presence.SessionId) - presenceObj.Set("username", e.Presence.Username) - presenceObj.Set("node", e.Presence.Node) + _ = presenceObj.Set("userId", e.Presence.UserId) + _ = presenceObj.Set("sessionId", e.Presence.SessionId) + _ = presenceObj.Set("username", e.Presence.Username) + _ = presenceObj.Set("node", e.Presence.Node) propertiesObj := r.vm.NewObject() for k, v := range e.StringProperties { - propertiesObj.Set(k, v) + _ = propertiesObj.Set(k, v) } for k, v := range e.NumericProperties { - propertiesObj.Set(k, v) + _ = propertiesObj.Set(k, v) } entry := r.vm.NewObject() - entry.Set("presence", presenceObj) - entry.Set("properties", propertiesObj) + _ = entry.Set("presence", presenceObj) + _ = entry.Set("properties", propertiesObj) if e.PartyId != "" { - entry.Set("partyId", e.PartyId) + _ = entry.Set("partyId", e.PartyId) } entriesSlice = append(entriesSlice, entry) @@ -1889,25 +1892,25 @@ func (rp *RuntimeProviderJS) TournamentEnd(ctx context.Context, tournament *api. } tournamentObj := r.vm.NewObject() - tournamentObj.Set("id", tournament.Id) - tournamentObj.Set("title", tournament.Title) - tournamentObj.Set("description", tournament.Description) - tournamentObj.Set("category", tournament.Category) - tournamentObj.Set("sortOrder", tournament.SortOrder) - tournamentObj.Set("size", tournament.Size) - tournamentObj.Set("maxSize", tournament.MaxSize) - tournamentObj.Set("maxNumScore", tournament.MaxNumScore) - tournamentObj.Set("duration", tournament.Duration) - tournamentObj.Set("startActive", tournament.StartActive) - tournamentObj.Set("endActive", tournament.EndActive) - tournamentObj.Set("canEnter", tournament.CanEnter) + _ = tournamentObj.Set("id", tournament.Id) + _ = tournamentObj.Set("title", tournament.Title) + _ = tournamentObj.Set("description", tournament.Description) + _ = tournamentObj.Set("category", tournament.Category) + _ = tournamentObj.Set("sortOrder", tournament.SortOrder) + _ = tournamentObj.Set("size", tournament.Size) + _ = tournamentObj.Set("maxSize", tournament.MaxSize) + _ = tournamentObj.Set("maxNumScore", tournament.MaxNumScore) + _ = tournamentObj.Set("duration", tournament.Duration) + _ = tournamentObj.Set("startActive", tournament.StartActive) + _ = tournamentObj.Set("endActive", tournament.EndActive) + _ = tournamentObj.Set("canEnter", tournament.CanEnter) if tournament.PrevReset != 0 { - tournamentObj.Set("prevReset", tournament.PrevReset) + _ = tournamentObj.Set("prevReset", tournament.PrevReset) } if tournament.NextReset != 0 { - tournamentObj.Set("nextReset", tournament.NextReset) + _ = tournamentObj.Set("nextReset", tournament.NextReset) } - tournamentObj.Set("operator", strings.ToLower(tournament.Operator.String())) + _ = tournamentObj.Set("operator", strings.ToLower(tournament.Operator.String())) metadataMap := make(map[string]interface{}) err = json.Unmarshal([]byte(tournament.Metadata), &metadataMap) if err != nil { @@ -1915,13 +1918,13 @@ func (rp *RuntimeProviderJS) TournamentEnd(ctx context.Context, tournament *api. return fmt.Errorf("failed to convert metadata to json: %s", err.Error()) } pointerizeSlices(metadataMap) - tournamentObj.Set("metadata", metadataMap) - tournamentObj.Set("createTime", tournament.CreateTime.Seconds) - tournamentObj.Set("startTime", tournament.StartTime.Seconds) + _ = tournamentObj.Set("metadata", metadataMap) + _ = tournamentObj.Set("createTime", tournament.CreateTime.Seconds) + _ = tournamentObj.Set("startTime", tournament.StartTime.Seconds) if tournament.EndTime == nil { - tournamentObj.Set("endTime", goja.Null()) + _ = tournamentObj.Set("endTime", goja.Null()) } else { - tournamentObj.Set("endTime", tournament.EndTime.Seconds) + _ = tournamentObj.Set("endTime", tournament.EndTime.Seconds) } fn, ok := goja.AssertFunction(r.vm.Get(jsFn)) @@ -1965,25 +1968,25 @@ func (rp *RuntimeProviderJS) TournamentReset(ctx context.Context, tournament *ap } tournamentObj := r.vm.NewObject() - tournamentObj.Set("id", tournament.Id) - tournamentObj.Set("title", tournament.Title) - tournamentObj.Set("description", tournament.Description) - tournamentObj.Set("category", tournament.Category) - tournamentObj.Set("sortOrder", tournament.SortOrder) - tournamentObj.Set("size", tournament.Size) - tournamentObj.Set("maxSize", tournament.MaxSize) - tournamentObj.Set("maxNumScore", tournament.MaxNumScore) - tournamentObj.Set("duration", tournament.Duration) - tournamentObj.Set("startActive", tournament.StartActive) - tournamentObj.Set("endActive", tournament.EndActive) - tournamentObj.Set("canEnter", tournament.CanEnter) + _ = tournamentObj.Set("id", tournament.Id) + _ = tournamentObj.Set("title", tournament.Title) + _ = tournamentObj.Set("description", tournament.Description) + _ = tournamentObj.Set("category", tournament.Category) + _ = tournamentObj.Set("sortOrder", tournament.SortOrder) + _ = tournamentObj.Set("size", tournament.Size) + _ = tournamentObj.Set("maxSize", tournament.MaxSize) + _ = tournamentObj.Set("maxNumScore", tournament.MaxNumScore) + _ = tournamentObj.Set("duration", tournament.Duration) + _ = tournamentObj.Set("startActive", tournament.StartActive) + _ = tournamentObj.Set("endActive", tournament.EndActive) + _ = tournamentObj.Set("canEnter", tournament.CanEnter) if tournament.PrevReset != 0 { - tournamentObj.Set("prevReset", tournament.PrevReset) + _ = tournamentObj.Set("prevReset", tournament.PrevReset) } if tournament.NextReset != 0 { - tournamentObj.Set("nextReset", tournament.NextReset) + _ = tournamentObj.Set("nextReset", tournament.NextReset) } - tournamentObj.Set("operator", strings.ToLower(tournament.Operator.String())) + _ = tournamentObj.Set("operator", strings.ToLower(tournament.Operator.String())) metadataMap := make(map[string]interface{}) err = json.Unmarshal([]byte(tournament.Metadata), &metadataMap) if err != nil { @@ -1991,13 +1994,13 @@ func (rp *RuntimeProviderJS) TournamentReset(ctx context.Context, tournament *ap return fmt.Errorf("failed to convert metadata to json: %s", err.Error()) } pointerizeSlices(metadataMap) - tournamentObj.Set("metadata", metadataMap) - tournamentObj.Set("createTime", tournament.CreateTime.Seconds) - tournamentObj.Set("startTime", tournament.StartTime.Seconds) + _ = tournamentObj.Set("metadata", metadataMap) + _ = tournamentObj.Set("createTime", tournament.CreateTime.Seconds) + _ = tournamentObj.Set("startTime", tournament.StartTime.Seconds) if tournament.EndTime == nil { - tournamentObj.Set("endTime", goja.Null()) + _ = tournamentObj.Set("endTime", goja.Null()) } else { - tournamentObj.Set("endTime", tournament.EndTime.Seconds) + _ = tournamentObj.Set("endTime", tournament.EndTime.Seconds) } fn, ok := goja.AssertFunction(r.vm.Get(jsFn)) @@ -2041,15 +2044,15 @@ func (rp *RuntimeProviderJS) LeaderboardReset(ctx context.Context, leaderboard * } leaderboardObj := r.vm.NewObject() - leaderboardObj.Set("id", leaderboard.Id) - leaderboardObj.Set("authoritative", leaderboard.Authoritative) - leaderboardObj.Set("sortOrder", leaderboard.SortOrder) - leaderboardObj.Set("operator", strings.ToLower(leaderboard.Operator.String())) + _ = leaderboardObj.Set("id", leaderboard.Id) + _ = leaderboardObj.Set("authoritative", leaderboard.Authoritative) + _ = leaderboardObj.Set("sortOrder", leaderboard.SortOrder) + _ = leaderboardObj.Set("operator", strings.ToLower(leaderboard.Operator.String())) if leaderboard.PrevReset != 0 { - leaderboardObj.Set("prevReset", leaderboard.PrevReset) + _ = leaderboardObj.Set("prevReset", leaderboard.PrevReset) } if leaderboard.NextReset != 0 { - leaderboardObj.Set("nextReset", leaderboard.NextReset) + _ = leaderboardObj.Set("nextReset", leaderboard.NextReset) } metadataMap := make(map[string]interface{}) err = json.Unmarshal([]byte(leaderboard.Metadata), &metadataMap) @@ -2058,8 +2061,8 @@ func (rp *RuntimeProviderJS) LeaderboardReset(ctx context.Context, leaderboard * return fmt.Errorf("failed to convert metadata to json: %s", err.Error()) } pointerizeSlices(metadataMap) - leaderboardObj.Set("metadata", metadataMap) - leaderboardObj.Set("createTime", leaderboard.CreateTime) + _ = leaderboardObj.Set("metadata", metadataMap) + _ = leaderboardObj.Set("createTime", leaderboard.CreateTime) fn, ok := goja.AssertFunction(r.vm.Get(jsFn)) if !ok { @@ -2130,8 +2133,6 @@ func (rp *RuntimeProviderJS) PurchaseNotificationApple(ctx context.Context, purc } return errors.New("Unexpected return type from runtime Purchase Notification Apple hook, must be nil.") - - return nil } func (rp *RuntimeProviderJS) SubscriptionNotificationApple(ctx context.Context, subscription *api.ValidatedSubscription, providerPayload string) error { @@ -2174,8 +2175,6 @@ func (rp *RuntimeProviderJS) SubscriptionNotificationApple(ctx context.Context, } return errors.New("Unexpected return type from runtime Subscription Notification Apple hook, must be nil.") - - return nil } func (rp *RuntimeProviderJS) PurchaseNotificationGoogle(ctx context.Context, purchase *api.ValidatedPurchase, providerPayload string) error { @@ -2218,8 +2217,6 @@ func (rp *RuntimeProviderJS) PurchaseNotificationGoogle(ctx context.Context, pur } return errors.New("Unexpected return type from runtime Purchase Notification Google hook, must be nil.") - - return nil } func (rp *RuntimeProviderJS) SubscriptionNotificationGoogle(ctx context.Context, subscription *api.ValidatedSubscription, providerPayload string) error { @@ -2262,8 +2259,6 @@ func (rp *RuntimeProviderJS) SubscriptionNotificationGoogle(ctx context.Context, } return errors.New("Unexpected return type from runtime Subscription Notification Google hook, must be nil.") - - return nil } func (rp *RuntimeProviderJS) StorageIndexFilter(ctx context.Context, indexName string, storageWrite *StorageOpWrite) (bool, error) { @@ -2403,7 +2398,7 @@ func freezeGlobalObject(config Config, r *goja.Runtime) { if !config.GetRuntime().JsReadOnlyGlobals { return } - r.RunString(` + _, _ = r.RunString(` for (const k of Reflect.ownKeys(globalThis)) { const v = globalThis[k]; if (v) { diff --git a/server/runtime_javascript_context.go b/server/runtime_javascript_context.go index c6339cf2d6..75d70c4362 100644 --- a/server/runtime_javascript_context.go +++ b/server/runtime_javascript_context.go @@ -43,38 +43,38 @@ const ( func NewRuntimeJsContext(r *goja.Runtime, node, version string, env goja.Value, mode RuntimeExecutionMode, httpHeaders, queryParams map[string][]string, sessionExpiry int64, userID, username string, vars map[string]string, sessionID, clientIP, clientPort, lang string) *goja.Object { ctxObj := r.NewObject() - ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_NODE, node) - ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_VERSION, version) - ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_ENV, env) - ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_MODE, mode.String()) + _ = ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_NODE, node) + _ = ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_VERSION, version) + _ = ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_ENV, env) + _ = ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_MODE, mode.String()) if httpHeaders != nil { - ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_HTTP_HEADERS, httpHeaders) + _ = ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_HTTP_HEADERS, httpHeaders) } if queryParams != nil { - ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_QUERY_PARAMS, queryParams) + _ = ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_QUERY_PARAMS, queryParams) } if sessionExpiry != 0 { - ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_USER_SESSION_EXP, sessionExpiry) + _ = ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_USER_SESSION_EXP, sessionExpiry) } if userID != "" { - ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_USER_ID, userID) + _ = ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_USER_ID, userID) } if username != "" { - ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_USERNAME, username) + _ = ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_USERNAME, username) } if vars != nil { - ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_VARS, vars) + _ = ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_VARS, vars) } if sessionID != "" { - ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_SESSION_ID, sessionID) + _ = ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_SESSION_ID, sessionID) // Lang is never reported without session ID. - ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_LANG, lang) + _ = ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_LANG, lang) } if clientIP != "" { - ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_CLIENT_IP, clientIP) + _ = ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_CLIENT_IP, clientIP) } if clientPort != "" { - ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_CLIENT_PORT, clientPort) + _ = ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_CLIENT_PORT, clientPort) } return ctxObj @@ -82,9 +82,9 @@ func NewRuntimeJsContext(r *goja.Runtime, node, version string, env goja.Value, func NewRuntimeJsInitContext(r *goja.Runtime, node, version string, env map[string]string) *goja.Object { ctxObj := r.NewObject() - ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_NODE, node) - ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_VERSION, version) - ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_ENV, env) + _ = ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_NODE, node) + _ = ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_VERSION, version) + _ = ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_ENV, env) return ctxObj } diff --git a/server/runtime_javascript_init.go b/server/runtime_javascript_init.go index 052b2d93d6..55b4f577ce 100644 --- a/server/runtime_javascript_init.go +++ b/server/runtime_javascript_init.go @@ -27,8 +27,6 @@ import ( const INIT_MODULE_FN_NAME = "InitModule" -var inlinedFunctionError = errors.New("function literal found: javascript functions cannot be inlined") - type RuntimeJavascriptMatchHandlers struct { sync.RWMutex mapping map[string]*jsMatchHandlers @@ -266,7 +264,7 @@ func (im *RuntimeJavascriptInitModule) mappings(r *goja.Runtime) map[string]func func (im *RuntimeJavascriptInitModule) Constructor(r *goja.Runtime) (*goja.Object, error) { constructor := func(call goja.ConstructorCall) *goja.Object { for key, fn := range im.mappings(r) { - call.This.Set(key, fn) + _ = call.This.Set(key, fn) } return nil diff --git a/server/runtime_javascript_logger.go b/server/runtime_javascript_logger.go index 198a5e1d0b..1f1ec73151 100644 --- a/server/runtime_javascript_logger.go +++ b/server/runtime_javascript_logger.go @@ -63,9 +63,9 @@ func (l *jsLogger) Constructor(r *goja.Runtime) (*goja.Object, error) { } else { argFields = r.NewObject() } - call.This.Set("fields", argFields) + _ = call.This.Set("fields", argFields) - call.This.Set("info", func(f goja.FunctionCall) goja.Value { + _ = call.This.Set("info", func(f goja.FunctionCall) goja.Value { format, a, err := getArgs(f.Arguments) if err != nil { panic(r.NewTypeError(err.Error())) @@ -75,7 +75,7 @@ func (l *jsLogger) Constructor(r *goja.Runtime) (*goja.Object, error) { return nil }) - call.This.Set("warn", func(f goja.FunctionCall) goja.Value { + _ = call.This.Set("warn", func(f goja.FunctionCall) goja.Value { format, a, err := getArgs(f.Arguments) if err != nil { panic(r.NewTypeError(err.Error())) @@ -85,7 +85,7 @@ func (l *jsLogger) Constructor(r *goja.Runtime) (*goja.Object, error) { return nil }) - call.This.Set("error", func(f goja.FunctionCall) goja.Value { + _ = call.This.Set("error", func(f goja.FunctionCall) goja.Value { format, a, err := getArgs(f.Arguments) if err != nil { panic(r.NewTypeError(err.Error())) @@ -95,7 +95,7 @@ func (l *jsLogger) Constructor(r *goja.Runtime) (*goja.Object, error) { return nil }) - call.This.Set("debug", func(f goja.FunctionCall) goja.Value { + _ = call.This.Set("debug", func(f goja.FunctionCall) goja.Value { format, a, err := getArgs(f.Arguments) if err != nil { panic(r.NewTypeError(err.Error())) @@ -105,7 +105,7 @@ func (l *jsLogger) Constructor(r *goja.Runtime) (*goja.Object, error) { return nil }) - call.This.Set("withField", func(f goja.FunctionCall) goja.Value { + _ = call.This.Set("withField", func(f goja.FunctionCall) goja.Value { key, ok := f.Arguments[0].Export().(string) if !ok { panic(r.NewTypeError("key argument must be a string")) @@ -127,7 +127,7 @@ func (l *jsLogger) Constructor(r *goja.Runtime) (*goja.Object, error) { return objInst }) - call.This.Set("withFields", func(f goja.FunctionCall) goja.Value { + _ = call.This.Set("withFields", func(f goja.FunctionCall) goja.Value { argMap, ok := f.Arguments[0].Export().(map[string]interface{}) if !ok { panic(r.NewTypeError("argument must be a map")) @@ -146,7 +146,7 @@ func (l *jsLogger) Constructor(r *goja.Runtime) (*goja.Object, error) { return objInst }) - call.This.Set("getFields", func(f goja.FunctionCall) goja.Value { + _ = call.This.Set("getFields", func(f goja.FunctionCall) goja.Value { return call.This.Get("fields") }) @@ -161,6 +161,6 @@ func (l *jsLogger) Constructor(r *goja.Runtime) (*goja.Object, error) { // Disallows resetting or changing the properties of the object func freeze(o *goja.Object) { for _, key := range o.Keys() { - o.DefineDataProperty(key, o.Get(key), goja.FLAG_FALSE, goja.FLAG_FALSE, goja.FLAG_TRUE) + _ = o.DefineDataProperty(key, o.Get(key), goja.FLAG_FALSE, goja.FLAG_FALSE, goja.FLAG_TRUE) } } diff --git a/server/runtime_javascript_logger_test.go b/server/runtime_javascript_logger_test.go index a9d73e9855..8d415efcb9 100644 --- a/server/runtime_javascript_logger_test.go +++ b/server/runtime_javascript_logger_test.go @@ -33,7 +33,7 @@ func TestJsLoggerInfo(t *testing.T) { if err != nil { t.Error("Failed to instantiate jsLogger") } - r.Set("logger", jsLoggerInst) + _ = r.Set("logger", jsLoggerInst) SCRIPT := ` var s = 'info'; @@ -59,7 +59,7 @@ func TestJsLoggerWarn(t *testing.T) { if err != nil { t.Error("Failed to instantiate jsLogger") } - r.Set("logger", jsLoggerInst) + _ = r.Set("logger", jsLoggerInst) SCRIPT := ` var s = 'warn'; @@ -85,7 +85,7 @@ func TestJsLoggerError(t *testing.T) { if err != nil { t.Error("Failed to instantiate jsLogger") } - r.Set("logger", jsLoggerInst) + _ = r.Set("logger", jsLoggerInst) SCRIPT := ` var s = 'error'; @@ -111,7 +111,7 @@ func TestJsLoggerDebug(t *testing.T) { if err != nil { t.Error("Failed to instantiate jsLogger") } - r.Set("logger", jsLoggerInst) + _ = r.Set("logger", jsLoggerInst) SCRIPT := ` var s = 'debug'; @@ -137,7 +137,7 @@ func TestJsLoggerWithField(t *testing.T) { if err != nil { t.Error("Failed to instantiate jsLogger") } - r.Set("logger", jsLoggerInst) + _ = r.Set("logger", jsLoggerInst) SCRIPT := ` var s = 'info'; @@ -164,7 +164,7 @@ func TestJsLoggerWithFields(t *testing.T) { if err != nil { t.Error("Failed to instantiate jsLogger") } - r.Set("logger", jsLoggerInst) + _ = r.Set("logger", jsLoggerInst) SCRIPT := ` var s = 'info'; diff --git a/server/runtime_javascript_match_core.go b/server/runtime_javascript_match_core.go index bad2574df5..88b2738492 100644 --- a/server/runtime_javascript_match_core.go +++ b/server/runtime_javascript_match_core.go @@ -63,7 +63,6 @@ type RuntimeJavaScriptMatchCore struct { dispatcher goja.Value nakamaModule goja.Value loggerModule goja.Value - program *goja.Program ctxCancelFn context.CancelFunc } @@ -84,13 +83,16 @@ func NewRuntimeJavascriptMatchCore(logger *zap.Logger, module string, db *sql.DB goCtx, ctxCancelFn := context.WithCancel(context.Background()) nakamaModule.ctx = goCtx - runtime.RunProgram(modCache.Modules[modCache.Names[0]].Program) + _, err = runtime.RunProgram(modCache.Modules[modCache.Names[0]].Program) + if err != nil { + logger.Fatal("Failed to initialize JavaScript runtime", zap.Error(err)) + } freezeGlobalObject(config, runtime) ctx := NewRuntimeJsInitContext(runtime, node, version, config.GetRuntime().Environment) - ctx.Set(__RUNTIME_JAVASCRIPT_CTX_MODE, RuntimeExecutionModeMatch) - ctx.Set(__RUNTIME_JAVASCRIPT_CTX_MATCH_ID, fmt.Sprintf("%v.%v", id.String(), node)) - ctx.Set(__RUNTIME_JAVASCRIPT_CTX_MATCH_NODE, node) + _ = ctx.Set(__RUNTIME_JAVASCRIPT_CTX_MODE, RuntimeExecutionModeMatch) + _ = ctx.Set(__RUNTIME_JAVASCRIPT_CTX_MATCH_ID, fmt.Sprintf("%v.%v", id.String(), node)) + _ = ctx.Set(__RUNTIME_JAVASCRIPT_CTX_MATCH_NODE, node) // TODO: goja runtime does not currently support passing a context to the vm // goCtx, ctxCancelFn := context.WithCancel(context.Background()) @@ -170,10 +172,10 @@ func NewRuntimeJavascriptMatchCore(logger *zap.Logger, module string, db *sql.DB dispatcher := runtime.ToValue( func(call goja.ConstructorCall) *goja.Object { - call.This.Set("broadcastMessage", core.broadcastMessage(runtime)) - call.This.Set("broadcastMessageDeferred", core.broadcastMessageDeferred(runtime)) - call.This.Set("matchKick", core.matchKick(runtime)) - call.This.Set("matchLabelUpdate", core.matchLabelUpdate(runtime)) + _ = call.This.Set("broadcastMessage", core.broadcastMessage(runtime)) + _ = call.This.Set("broadcastMessageDeferred", core.broadcastMessageDeferred(runtime)) + _ = call.This.Set("matchKick", core.matchKick(runtime)) + _ = call.This.Set("matchLabelUpdate", core.matchLabelUpdate(runtime)) freeze(call.This) @@ -238,8 +240,8 @@ func (rm *RuntimeJavaScriptMatchCore) MatchInit(presenceList *MatchPresenceList, } rm.label.Store(label) - rm.ctx.Set(__RUNTIME_JAVASCRIPT_CTX_MATCH_LABEL, label) - rm.ctx.Set(__RUNTIME_JAVASCRIPT_CTX_MATCH_TICK_RATE, rate) + _ = rm.ctx.Set(__RUNTIME_JAVASCRIPT_CTX_MATCH_LABEL, label) + _ = rm.ctx.Set(__RUNTIME_JAVASCRIPT_CTX_MATCH_TICK_RATE, rate) rm.deferMessageFn = deferMessageFn rm.presenceList = presenceList @@ -250,28 +252,28 @@ func (rm *RuntimeJavaScriptMatchCore) MatchInit(presenceList *MatchPresenceList, func (rm *RuntimeJavaScriptMatchCore) MatchJoinAttempt(tick int64, state interface{}, userID, sessionID uuid.UUID, username string, sessionExpiry int64, vars map[string]string, clientIP, clientPort, node string, metadata map[string]string) (interface{}, bool, string, error) { // Setup presence presenceObj := rm.vm.NewObject() - presenceObj.Set("userId", userID.String()) - presenceObj.Set("sessionId", sessionID.String()) - presenceObj.Set("username", username) - presenceObj.Set("node", node) + _ = presenceObj.Set("userId", userID.String()) + _ = presenceObj.Set("sessionId", sessionID.String()) + _ = presenceObj.Set("username", username) + _ = presenceObj.Set("node", node) // Setup ctx ctxObj := rm.vm.NewObject() for _, key := range rm.ctx.Keys() { - ctxObj.Set(key, rm.ctx.Get(key)) + _ = ctxObj.Set(key, rm.ctx.Get(key)) } - ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_USER_ID, userID.String()) - ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_USERNAME, username) + _ = ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_USER_ID, userID.String()) + _ = ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_USERNAME, username) if vars != nil { - ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_VARS, vars) + _ = ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_VARS, vars) } - ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_USER_SESSION_EXP, sessionExpiry) - ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_SESSION_ID, sessionID.String()) + _ = ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_USER_SESSION_EXP, sessionExpiry) + _ = ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_SESSION_ID, sessionID.String()) if clientIP != "" { - ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_CLIENT_IP, clientIP) + _ = ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_CLIENT_IP, clientIP) } if clientPort != "" { - ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_CLIENT_PORT, clientPort) + _ = ctxObj.Set(__RUNTIME_JAVASCRIPT_CTX_CLIENT_PORT, clientPort) } pointerizeSlices(state) @@ -300,7 +302,7 @@ func (rm *RuntimeJavaScriptMatchCore) MatchJoinAttempt(tick int64, state interfa } var rejectMsg string - if allow == false { + if !allow { rejectMsgRet, ok := retMap["rejectMessage"] if ok { rejectMsg, ok = rejectMsgRet.(string) @@ -574,11 +576,11 @@ func (rm *RuntimeJavaScriptMatchCore) validateBroadcast(r *goja.Runtime, f goja. data := f.Argument(1) if !goja.IsUndefined(data) && !goja.IsNull(data) { dataExport := data.Export() - switch dataExport.(type) { + switch val := dataExport.(type) { case string: - dataBytes = []byte(dataExport.(string)) + dataBytes = []byte(val) case goja.ArrayBuffer: - dataBytes = dataExport.(goja.ArrayBuffer).Bytes() + dataBytes = val.Bytes() default: panic(r.NewTypeError("expects data to be an ArrayBuffer, a string or nil")) } @@ -601,7 +603,7 @@ func (rm *RuntimeJavaScriptMatchCore) validateBroadcast(r *goja.Runtime, f goja. presenceID := &PresenceID{} - sidVal, _ := pMap["sessionId"] + sidVal := pMap["sessionId"] if sidVal == nil { panic(r.NewTypeError("presence is expected to contain a 'sessionId'")) } @@ -614,7 +616,7 @@ func (rm *RuntimeJavaScriptMatchCore) validateBroadcast(r *goja.Runtime, f goja. panic(r.NewTypeError("expects a valid 'sessionId'")) } - nodeVal, _ := pMap["node"] + nodeVal := pMap["node"] if nodeVal == nil { panic(r.NewTypeError("expects presence to contain a 'node'")) } @@ -645,7 +647,7 @@ func (rm *RuntimeJavaScriptMatchCore) validateBroadcast(r *goja.Runtime, f goja. if !ok { panic(r.NewTypeError("expects sender to be an object")) } - userIdVal, _ := senderMap["userId"] + userIdVal := senderMap["userId"] if userIdVal == nil { panic(r.NewTypeError("expects presence to contain 'userId'")) } @@ -659,7 +661,7 @@ func (rm *RuntimeJavaScriptMatchCore) validateBroadcast(r *goja.Runtime, f goja. } presence.UserId = userIDStr - sidVal, _ := senderMap["sessionId"] + sidVal := senderMap["sessionId"] if sidVal == nil { panic(r.NewTypeError("presence is expected to contain a 'sessionId'")) } @@ -673,7 +675,7 @@ func (rm *RuntimeJavaScriptMatchCore) validateBroadcast(r *goja.Runtime, f goja. } presence.SessionId = sidStr - usernameVal, _ := senderMap["username"] + usernameVal := senderMap["username"] if usernameVal == nil { panic(r.NewTypeError("presence is expected to contain a 'username'")) } @@ -744,7 +746,7 @@ func (rm *RuntimeJavaScriptMatchCore) matchKick(r *goja.Runtime) func(goja.Funct } presence := &MatchPresence{} - userIdVal, _ := pMap["userId"] + userIdVal := pMap["userId"] if userIdVal == nil { panic(r.NewTypeError("expects presence to contain 'userId'")) } @@ -758,7 +760,7 @@ func (rm *RuntimeJavaScriptMatchCore) matchKick(r *goja.Runtime) func(goja.Funct } presence.UserID = uid - sidVal, _ := pMap["sessionId"] + sidVal := pMap["sessionId"] if sidVal == nil { panic(r.NewTypeError("presence is expected to contain a 'sessionId'")) } @@ -772,7 +774,7 @@ func (rm *RuntimeJavaScriptMatchCore) matchKick(r *goja.Runtime) func(goja.Funct } presence.SessionID = sid - nodeVal, _ := pMap["node"] + nodeVal := pMap["node"] if nodeVal == nil { panic(r.NewTypeError("expects presence to contain a 'node'")) } @@ -805,7 +807,7 @@ func (rm *RuntimeJavaScriptMatchCore) matchLabelUpdate(r *goja.Runtime) func(goj rm.label.Store(input) // This must be executed from inside a match call so safe to update here. - rm.ctx.Set(__RUNTIME_JAVASCRIPT_CTX_MATCH_LABEL, input) + _ = rm.ctx.Set(__RUNTIME_JAVASCRIPT_CTX_MATCH_LABEL, input) return goja.Undefined() } diff --git a/server/runtime_javascript_nakama.go b/server/runtime_javascript_nakama.go index 3692560319..233ae271b1 100644 --- a/server/runtime_javascript_nakama.go +++ b/server/runtime_javascript_nakama.go @@ -129,10 +129,10 @@ func (n *runtimeJavascriptNakamaModule) Constructor(r *goja.Runtime) (*goja.Obje constructor := func(call goja.ConstructorCall) *goja.Object { for fnName, fn := range n.mappings(r) { - call.This.Set(fnName, fn) + _ = call.This.Set(fnName, fn) } - call.This.Set("getSatori", n.getSatori(satoriJsObj)) + _ = call.This.Set("getSatori", n.getSatori(satoriJsObj)) return nil } @@ -1051,7 +1051,7 @@ func (n *runtimeJavascriptNakamaModule) aes256Decrypt(r *goja.Runtime) func(goja // @return error(error) An optional error value if an error occurred. func (n *runtimeJavascriptNakamaModule) aesEncrypt(keySize int, input, key string) (string, error) { if len(key) != keySize { - return "", errors.New(fmt.Sprintf("expects key %v bytes long", keySize)) + return "", fmt.Errorf("expects key %v bytes long", keySize) } // Pad string up to length multiple of 4 if needed. @@ -1061,13 +1061,13 @@ func (n *runtimeJavascriptNakamaModule) aesEncrypt(keySize int, input, key strin block, err := aes.NewCipher([]byte(key)) if err != nil { - return "", errors.New(fmt.Sprintf("error creating cipher block: %v", err.Error())) + return "", fmt.Errorf("error creating cipher block: %v", err.Error()) } cipherText := make([]byte, aes.BlockSize+len(input)) iv := cipherText[:aes.BlockSize] if _, err = io.ReadFull(rand.Reader, iv); err != nil { - return "", errors.New(fmt.Sprintf("error getting iv: %v", err.Error())) + return "", fmt.Errorf("error getting iv: %v", err.Error()) } stream := cipher.NewCFBEncrypter(block, iv) @@ -1085,17 +1085,17 @@ func (n *runtimeJavascriptNakamaModule) aesEncrypt(keySize int, input, key strin // @return error(error) An optional error value if an error occurred. func (n *runtimeJavascriptNakamaModule) aesDecrypt(keySize int, input, key string) (string, error) { if len(key) != keySize { - return "", errors.New(fmt.Sprintf("expects key %v bytes long", keySize)) + return "", fmt.Errorf("expects key %v bytes long", keySize) } block, err := aes.NewCipher([]byte(key)) if err != nil { - return "", errors.New(fmt.Sprintf("error creating cipher block: %v", err.Error())) + return "", fmt.Errorf("error creating cipher block: %v", err.Error()) } decodedtText, err := base64.StdEncoding.DecodeString(input) if err != nil { - return "", errors.New(fmt.Sprintf("error decoding cipher text: %v", err.Error())) + return "", fmt.Errorf("error decoding cipher text: %v", err.Error()) } cipherText := decodedtText iv := cipherText[:aes.BlockSize] @@ -2060,7 +2060,7 @@ func (n *runtimeJavascriptNakamaModule) usersGetId(r *goja.Runtime) func(goja.Fu } if userIds == nil && facebookIds == nil { - return r.ToValue(make([]string, 0, 0)) + return r.ToValue(make([]string, 0)) } users, err := GetUsers(n.ctx, n.logger, n.db, n.statusRegistry, userIds, nil, facebookIds) @@ -4127,12 +4127,11 @@ func (n *runtimeJavascriptNakamaModule) walletLedgerUpdate(r *goja.Runtime) func panic(r.NewTypeError("expects a valid id")) } - metadataBytes := []byte("{}") metadataMap, ok := f.Argument(1).Export().(map[string]interface{}) if !ok { panic(r.NewTypeError("expects metadata object")) } - metadataBytes, err = json.Marshal(metadataMap) + metadataBytes, err := json.Marshal(metadataMap) if err != nil { panic(r.NewGoError(fmt.Errorf("failed to convert metadata: %s", err.Error()))) } @@ -4463,7 +4462,7 @@ func jsArrayToStorageOpWrites(r *goja.Runtime, dataSlice []any) (StorageOpWrites writeOp.Collection = collection } - keyIn, ok := dataMap["key"] + keyIn := dataMap["key"] key, ok := keyIn.(string) if !ok { return nil, errors.New("expects 'key' value to be a string") @@ -4473,7 +4472,7 @@ func jsArrayToStorageOpWrites(r *goja.Runtime, dataSlice []any) (StorageOpWrites } writeOp.Key = key - userIDIn, ok := dataMap["userId"] + userIDIn := dataMap["userId"] if userIDIn == nil { userID = uuid.Nil } else { @@ -4488,7 +4487,7 @@ func jsArrayToStorageOpWrites(r *goja.Runtime, dataSlice []any) (StorageOpWrites } } - valueIn, ok := dataMap["value"] + valueIn := dataMap["value"] valueMap, ok := valueIn.(map[string]interface{}) if !ok { return nil, errors.New("expects 'value' value to be an object") @@ -8210,7 +8209,7 @@ func (n *runtimeJavascriptNakamaModule) satoriConstructor(r *goja.Runtime) (*goj constructor := func(call goja.ConstructorCall) *goja.Object { for k, f := range mappings { - call.This.Set(k, f) + _ = call.This.Set(k, f) } return nil diff --git a/server/runtime_lua_nakama.go b/server/runtime_lua_nakama.go index 8b16e8f926..40547d2526 100644 --- a/server/runtime_lua_nakama.go +++ b/server/runtime_lua_nakama.go @@ -5934,6 +5934,7 @@ func tableToStorageWrites(l *lua.LState, dataTable *lua.LTable) (StorageOpWrites return ops, nil } +//nolint:unused func storageOpWritesToTable(l *lua.LState, ops StorageOpWrites) (*lua.LTable, error) { lv := l.CreateTable(len(ops), 0) for i, v := range ops { @@ -7966,7 +7967,7 @@ func (n *RuntimeLuaNakamaModule) tournamentRecordWrite(l *lua.LState) int { } overrideOperatorString := l.OptString(7, api.Operator_NO_OVERRIDE.String()) - overrideOperator := int32(api.Operator_NO_OVERRIDE) + var overrideOperator int32 var ok bool if overrideOperator, ok = api.Operator_value[strings.ToUpper(overrideOperatorString)]; !ok { l.ArgError(7, ErrInvalidOperator.Error()) diff --git a/server/runtime_lua_oslib.go b/server/runtime_lua_oslib.go index 934704470f..95a0f7650f 100644 --- a/server/runtime_lua_oslib.go +++ b/server/runtime_lua_oslib.go @@ -65,7 +65,7 @@ var osFuncs = map[string]lua.LGFunction{ } func osClock(L *lua.LState) int { - L.Push(lua.LNumber(float64(time.Now().Sub(startedAt)) / float64(time.Second))) + L.Push(lua.LNumber(float64(time.Since(startedAt)) / float64(time.Second))) return 1 } diff --git a/server/status_registry.go b/server/status_registry.go index 8848a22093..38898220a9 100644 --- a/server/status_registry.go +++ b/server/status_registry.go @@ -104,7 +104,7 @@ func NewStatusRegistry(logger *zap.Logger, config Config, sessionRegistry Sessio continue } sessionIDs := make([]uuid.UUID, 0, len(ids)) - for id, _ := range ids { + for id := range ids { sessionIDs = append(sessionIDs, id) } s.RUnlock() @@ -178,7 +178,7 @@ func (s *StatusRegistry) Follow(sessionID uuid.UUID, userIDs map[uuid.UUID]struc sessionFollows = make(map[uuid.UUID]struct{}) s.bySession[sessionID] = sessionFollows } - for userID, _ := range userIDs { + for userID := range userIDs { if _, alreadyFollowing := sessionFollows[userID]; alreadyFollowing { continue } @@ -246,7 +246,7 @@ func (s *StatusRegistry) UnfollowAll(sessionID uuid.UUID) { s.Unlock() return } - for userID, _ := range sessionFollows { + for userID := range sessionFollows { if userFollowers := s.byUser[userID]; len(userFollowers) == 1 { delete(s.byUser, userID) } else { diff --git a/server/storage_index.go b/server/storage_index.go index 5606a9467b..29e3875eb5 100644 --- a/server/storage_index.go +++ b/server/storage_index.go @@ -476,7 +476,7 @@ func (si *LocalStorageIndex) queryMatchesToDocumentIds(dmi search.DocumentMatchI next, err := dmi.Next() ids := make([]string, 0) for err == nil && next != nil { - next.VisitStoredFields(func(field string, value []byte) bool { + _ = next.VisitStoredFields(func(field string, value []byte) bool { if field == "_id" { ids = append(ids, string(value)) return false @@ -546,7 +546,7 @@ func (si *LocalStorageIndex) CreateIndex(ctx context.Context, name, collection, } func (si *LocalStorageIndex) RegisterFilters(runtime *Runtime) { - for name, _ := range si.indexByName { + for name := range si.indexByName { fn := runtime.StorageIndexFilterFunction(name) if fn != nil { si.customFilterFunctions[name] = fn diff --git a/server/tracker.go b/server/tracker.go index e1f9d3d71c..8906538def 100644 --- a/server/tracker.go +++ b/server/tracker.go @@ -901,7 +901,7 @@ func (t *LocalTracker) queueEvent(joins, leaves []*Presence) { func (t *LocalTracker) processEvent(e *PresenceEvent) { dequeueTime := time.Now() defer func() { - t.metrics.PresenceEvent(dequeueTime.Sub(e.QueueTime), time.Now().Sub(dequeueTime)) + t.metrics.PresenceEvent(dequeueTime.Sub(e.QueueTime), time.Since(dequeueTime)) }() t.logger.Debug("Processing presence event", zap.Int("joins", len(e.Joins)), zap.Int("leaves", len(e.Leaves))) diff --git a/social/social.go b/social/social.go index 978b9fa435..b8c9174e07 100644 --- a/social/social.go +++ b/social/social.go @@ -26,7 +26,7 @@ import ( "encoding/pem" "errors" "fmt" - "io/ioutil" + "io" "math/big" "net/http" "net/url" @@ -297,7 +297,7 @@ func (c *Client) ExtractFacebookInstantGameID(signedPlayerInfo string, appSecret signatureBase64 := parts[0] payloadBase64 := parts[1] - payloadRaw, err := jwt.DecodeSegment(payloadBase64) + payloadRaw, err := jwt.DecodeSegment(payloadBase64) //nolint:staticcheck if err != nil { return "", err } @@ -481,33 +481,33 @@ func (c *Client) CheckGoogleToken(ctx context.Context, idToken string) (GooglePr return nil, errors.New("google id token aud field missing") } if v, ok := claims["iat"]; ok { - switch v.(type) { + switch val := v.(type) { case string: - vi, err := strconv.Atoi(v.(string)) + vi, err := strconv.Atoi(val) if err != nil { return nil, errors.New("google id token iat field invalid") } profile.Iat = int64(vi) case float64: - profile.Iat = int64(v.(float64)) + profile.Iat = int64(val) case int64: - profile.Iat = v.(int64) + profile.Iat = val default: return nil, errors.New("google id token iat field unknown") } } if v, ok := claims["exp"]; ok { - switch v.(type) { + switch val := v.(type) { case string: - vi, err := strconv.Atoi(v.(string)) + vi, err := strconv.Atoi(val) if err != nil { return nil, errors.New("google id token exp field invalid") } profile.Exp = int64(vi) case float64: - profile.Exp = int64(v.(float64)) + profile.Exp = int64(val) case int64: - profile.Exp = v.(int64) + profile.Exp = val default: return nil, errors.New("google id token exp field unknown") } @@ -518,11 +518,11 @@ func (c *Client) CheckGoogleToken(ctx context.Context, idToken string) (GooglePr } } if v, ok := claims["email_verified"]; ok { - switch v.(type) { + switch val := v.(type) { case bool: - profile.EmailVerified = v.(bool) + profile.EmailVerified = val case string: - vb, err := strconv.ParseBool(v.(string)) + vb, err := strconv.ParseBool(val) if err != nil { return nil, errors.New("google id token email_verified field invalid") } @@ -766,11 +766,11 @@ func (c *Client) CheckAppleToken(ctx context.Context, bundleId string, idToken s } } if v, ok := claims["email_verified"]; ok { - switch v.(type) { + switch val := v.(type) { case bool: - profile.EmailVerified = v.(bool) + profile.EmailVerified = val case string: - vb, err := strconv.ParseBool(v.(string)) + vb, err := strconv.ParseBool(val) if err != nil { return nil, errors.New("apple id token email_verified field invalid") } @@ -956,7 +956,7 @@ func (c *Client) requestRaw(ctx context.Context, provider, path string, headers c.logger.Warn("error executing social request", zap.String("provider", provider), zap.Error(err)) return nil, err } - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) _ = resp.Body.Close() if err != nil { c.logger.Warn("error reading social response", zap.String("provider", provider), zap.Error(err))