diff --git a/certificate/peer_test.go b/certificate/peer_test.go index ef92f46ec..acc372942 100644 --- a/certificate/peer_test.go +++ b/certificate/peer_test.go @@ -104,7 +104,7 @@ func TestCertificateSigner_Sign_E2E(t *testing.T) { assert.Equal(t, clientIdent.CA.RawTBSCertificate, signedChain[0].RawTBSCertificate) assert.Equal(t, signer.Cert.Raw, signedChainBytes[1]) // TODO: test scenario with rest chain - //assert.Equal(t, signingCA.RawRestChain(), signedChainBytes[1:]) + // assert.Equal(t, signingCA.RawRestChain(), signedChainBytes[1:]) err = signedChain[0].CheckSignatureFrom(signer.Cert) require.NoError(t, err) @@ -187,7 +187,7 @@ func TestCertificateSigner_Sign(t *testing.T) { assert.Equal(t, ident.CA.RawTBSCertificate, signedChain[0].RawTBSCertificate) assert.Equal(t, ca.Cert.Raw, signedChain[1].Raw) // TODO: test scenario with rest chain - //assert.Equal(t, signingCA.RawRestChain(), res.Chain[1:]) + // assert.Equal(t, signingCA.RawRestChain(), res.Chain[1:]) err = signedChain[0].CheckSignatureFrom(ca.Cert) require.NoError(t, err) diff --git a/cmd/storagenode/main.go b/cmd/storagenode/main.go index 74107bba3..9df2c2875 100644 --- a/cmd/storagenode/main.go +++ b/cmd/storagenode/main.go @@ -265,7 +265,7 @@ func cmdConfig(cmd *cobra.Command, args []string) (err error) { if err != nil { return err } - //run setup if we can't access the config file + // run setup if we can't access the config file conf := filepath.Join(setupDir, "config.yaml") if _, err := os.Stat(conf); err != nil { return cmdSetup(cmd, args) diff --git a/cmd/storj-admin/main.go b/cmd/storj-admin/main.go index ad3adbf11..21e8ca045 100644 --- a/cmd/storj-admin/main.go +++ b/cmd/storj-admin/main.go @@ -31,7 +31,6 @@ var ( runCmd = &cobra.Command{ Use: "run", Short: "Run the storj-admin", - //RunE: cmdRun, } confDir string diff --git a/cmd/storj-sim/prefix.go b/cmd/storj-sim/prefix.go index b653f2216..7b77d74c1 100644 --- a/cmd/storj-sim/prefix.go +++ b/cmd/storj-sim/prefix.go @@ -100,7 +100,8 @@ func (writer *prefixWriter) Write(data []byte) (int, error) { // buffer everything that hasn't been written yet if len(writer.buffer) > 0 { - buffer = append(writer.buffer, data...) // nolint gocritic + buffer = writer.buffer + buffer = append(buffer, data...) defer func() { writer.buffer = buffer }() diff --git a/cmd/uplink/cmd/rb.go b/cmd/uplink/cmd/rb.go index 690601149..09ca69af2 100644 --- a/cmd/uplink/cmd/rb.go +++ b/cmd/uplink/cmd/rb.go @@ -61,7 +61,7 @@ func deleteBucket(cmd *cobra.Command, args []string) (err error) { }() if *rbForceFlag { - //TODO: Do we need to have retry here? + // TODO: Do we need to have retry here? if _, err := project.DeleteBucketWithObjects(ctx, dst.Bucket()); err != nil { return convertError(err, dst) } diff --git a/private/date/utils.go b/private/date/utils.go index f00607341..d1e29e224 100644 --- a/private/date/utils.go +++ b/private/date/utils.go @@ -43,7 +43,7 @@ func MonthsBetweenDates(from time.Time, to time.Time) int { y2, M2, _ := to.UTC().Date() months := ((y2 - y1) * 12) + int(M2) - int(M1) - //note that according to the tests, we ignore days of the month + // note that according to the tests, we ignore days of the month return months } diff --git a/private/migrate/versions_test.go b/private/migrate/versions_test.go index 647277c88..d5f841c1c 100644 --- a/private/migrate/versions_test.go +++ b/private/migrate/versions_test.go @@ -59,7 +59,7 @@ func TestBasicMigration(t *testing.T) { } func basicMigration(ctx *testcontext.Context, t *testing.T, db tagsql.DB, testDB tagsql.DB) { - dbName := strings.ToLower(`versions_` + strings.Replace(t.Name(), "/", "_", -1)) + dbName := strings.ToLower(`versions_` + strings.ReplaceAll(t.Name(), "/", "_")) defer func() { assert.NoError(t, dropTables(ctx, db, dbName, "users")) }() /* #nosec G306 */ // This is a test besides the file contains just test data. diff --git a/private/post/message.go b/private/post/message.go index c425b7657..2df803b1d 100644 --- a/private/post/message.go +++ b/private/post/message.go @@ -123,7 +123,7 @@ func (msg *Message) Bytes() (data []byte, err error) { } func tocrlf(data []byte) []byte { - lf := bytes.Replace(data, []byte("\r\n"), []byte("\n"), -1) - crlf := bytes.Replace(lf, []byte("\n"), []byte("\r\n"), -1) + lf := bytes.ReplaceAll(data, []byte("\r\n"), []byte("\n")) + crlf := bytes.ReplaceAll(lf, []byte("\n"), []byte("\r\n")) return crlf } diff --git a/private/web/ratelimiter.go b/private/web/ratelimiter.go index ac9439a19..1d5a468bc 100644 --- a/private/web/ratelimiter.go +++ b/private/web/ratelimiter.go @@ -14,27 +14,27 @@ import ( "golang.org/x/time/rate" ) -//IPRateLimiterConfig configures an IPRateLimiter. +// IPRateLimiterConfig configures an IPRateLimiter. type IPRateLimiterConfig struct { Duration time.Duration `help:"the rate at which request are allowed" default:"5m"` Burst int `help:"number of events before the limit kicks in" default:"5"` NumLimits int `help:"number of IPs whose rate limits we store" default:"1000"` } -//IPRateLimiter imposes a rate limit per HTTP user IP. +// IPRateLimiter imposes a rate limit per HTTP user IP. type IPRateLimiter struct { config IPRateLimiterConfig mu sync.Mutex ipLimits map[string]*userLimit } -//userLimit is the per-IP limiter. +// userLimit is the per-IP limiter. type userLimit struct { limiter *rate.Limiter lastSeen time.Time } -//NewIPRateLimiter constructs an IPRateLimiter. +// NewIPRateLimiter constructs an IPRateLimiter. func NewIPRateLimiter(config IPRateLimiterConfig) *IPRateLimiter { return &IPRateLimiter{ config: config, @@ -67,7 +67,7 @@ func (rl *IPRateLimiter) cleanupLimiters() { } } -//Limit applies a per IP rate limiting as an HTTP Handler. +// Limit applies a per IP rate limiting as an HTTP Handler. func (rl *IPRateLimiter) Limit(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ip, err := getRequestIP(r) @@ -84,7 +84,7 @@ func (rl *IPRateLimiter) Limit(next http.Handler) http.Handler { }) } -//getRequestIP gets the original IP address of the request by handling the request headers. +// getRequestIP gets the original IP address of the request by handling the request headers. func getRequestIP(r *http.Request) (ip string, err error) { realIP := r.Header.Get("X-REAL-IP") if realIP != "" { @@ -104,7 +104,7 @@ func getRequestIP(r *http.Request) (ip string, err error) { return ip, err } -//getUserLimit returns a rate limiter for an IP. +// getUserLimit returns a rate limiter for an IP. func (rl *IPRateLimiter) getUserLimit(ip string) *rate.Limiter { rl.mu.Lock() defer rl.mu.Unlock() @@ -128,7 +128,7 @@ func (rl *IPRateLimiter) getUserLimit(ip string) *rate.Limiter { oldestKey = ip } } - //only delete the oldest non-expired if there's still an issue + // only delete the oldest non-expired if there's still an issue if oldestKey != "" && len(rl.ipLimits) >= rl.config.NumLimits { delete(rl.ipLimits, oldestKey) } @@ -141,12 +141,12 @@ func (rl *IPRateLimiter) getUserLimit(ip string) *rate.Limiter { return v.limiter } -//Burst returns the number of events that happen before the rate limit. +// Burst returns the number of events that happen before the rate limit. func (rl *IPRateLimiter) Burst() int { return rl.config.Burst } -//Duration returns the amount of time required between events. +// Duration returns the amount of time required between events. func (rl *IPRateLimiter) Duration() time.Duration { return rl.config.Duration } diff --git a/private/web/ratelimiter_test.go b/private/web/ratelimiter_test.go index 065fd9b94..03e8ea144 100644 --- a/private/web/ratelimiter_test.go +++ b/private/web/ratelimiter_test.go @@ -19,12 +19,13 @@ import ( ) func TestNewIPRateLimiter(t *testing.T) { - //create a rate limiter with defaults except NumLimits = 2 + // create a rate limiter with defaults except NumLimits = 2 config := web.IPRateLimiterConfig{} cfgstruct.Bind(&pflag.FlagSet{}, &config, cfgstruct.UseDevDefaults()) config.NumLimits = 2 rateLimiter := web.NewIPRateLimiter(config) - //run ratelimiter cleanup until end of test + + // run ratelimiter cleanup until end of test ctx := testcontext.New(t) defer ctx.Cleanup() ctx2, cancel := context.WithCancel(ctx) @@ -33,32 +34,36 @@ func TestNewIPRateLimiter(t *testing.T) { rateLimiter.Run(ctx2) return nil }) - //make the default HTTP handler return StatusOK + + // make the default HTTP handler return StatusOK handler := rateLimiter.Limit(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })) - //expect burst number of successes + + // expect burst number of successes testWithAddress(t, "192.168.1.1:5000", rateLimiter.Burst(), handler) - //expect similar results for a different IP + // expect similar results for a different IP testWithAddress(t, "127.0.0.1:5000", rateLimiter.Burst(), handler) - //expect similar results for a different IP + // expect similar results for a different IP testWithAddress(t, "127.0.0.100:5000", rateLimiter.Burst(), handler) - //expect original IP to work again because numLimits == 2 + // expect original IP to work again because numLimits == 2 testWithAddress(t, "192.168.1.1:5000", rateLimiter.Burst(), handler) } func testWithAddress(t *testing.T, remoteAddress string, burst int, handler http.Handler) { - //create HTTP request + // create HTTP request req, err := http.NewRequest("GET", "", nil) require.NoError(t, err) req.RemoteAddr = remoteAddress - //expect burst number of successes + + // expect burst number of successes for x := 0; x < burst; x++ { rr := httptest.NewRecorder() handler.ServeHTTP(rr, req) assert.Equal(t, rr.Code, http.StatusOK, remoteAddress) } - //then expect failure + + // then expect failure rr := httptest.NewRecorder() handler.ServeHTTP(rr, req) assert.Equal(t, rr.Code, http.StatusTooManyRequests, remoteAddress) diff --git a/satellite/accounting/rollup/rollup.go b/satellite/accounting/rollup/rollup.go index e691683e6..c8c0f6aad 100644 --- a/satellite/accounting/rollup/rollup.go +++ b/satellite/accounting/rollup/rollup.go @@ -78,7 +78,7 @@ func (r *Service) Rollup(ctx context.Context) (err error) { return Error.Wrap(err) } - //remove the latest day (which we cannot know is complete), then push to DB + // remove the latest day (which we cannot know is complete), then push to DB latestTally = time.Date(latestTally.Year(), latestTally.Month(), latestTally.Day(), 0, 0, 0, 0, latestTally.Location()) delete(rollupStats, latestTally) if len(rollupStats) == 0 { @@ -113,7 +113,7 @@ func (r *Service) RollupStorage(ctx context.Context, lastRollup time.Time, rollu r.logger.Info("Rollup found no new tallies") return lastRollup, nil } - //loop through tallies and build Rollup + // loop through tallies and build Rollup for _, tallyRow := range tallies { node := tallyRow.NodeID // tallyEndTime is the time the at rest tally was saved @@ -121,7 +121,7 @@ func (r *Service) RollupStorage(ctx context.Context, lastRollup time.Time, rollu if tallyEndTime.After(latestTally) { latestTally = tallyEndTime } - //create or get AccoutingRollup day entry + // create or get AccoutingRollup day entry iDay := time.Date(tallyEndTime.Year(), tallyEndTime.Month(), tallyEndTime.Day(), 0, 0, 0, 0, tallyEndTime.Location()) if rollupStats[iDay] == nil { rollupStats[iDay] = make(map[storj.NodeID]*accounting.Rollup) @@ -129,7 +129,7 @@ func (r *Service) RollupStorage(ctx context.Context, lastRollup time.Time, rollu if rollupStats[iDay][node] == nil { rollupStats[iDay][node] = &accounting.Rollup{NodeID: node, StartTime: iDay} } - //increment data at rest sum + // increment data at rest sum rollupStats[iDay][node].AtRestTotal += tallyRow.DataTotal } diff --git a/satellite/admin.go b/satellite/admin.go index 882d02ea7..05afab9e8 100644 --- a/satellite/admin.go +++ b/satellite/admin.go @@ -144,7 +144,7 @@ func NewAdmin(log *zap.Logger, full *identity.FullIdentity, db DB, peer.Payments.Stripe = stripeClient peer.Payments.Accounts = peer.Payments.Service.Accounts() } - { //setup admin endpoint + { // setup admin endpoint var err error peer.Admin.Listener, err = net.Listen("tcp", config.Admin.Address) if err != nil { diff --git a/satellite/admin/project.go b/satellite/admin/project.go index ebd42f9ca..af9fa95cb 100644 --- a/satellite/admin/project.go +++ b/satellite/admin/project.go @@ -491,7 +491,7 @@ func (server *Server) checkUsage(ctx context.Context, w http.ResponseWriter, pro } if lastMonthUsage.Storage > 0 || lastMonthUsage.Egress > 0 || lastMonthUsage.ObjectCount > 0 { - //time passed into the check function need to be the UTC midnight dates of the first and last day of the month + // time passed into the check function need to be the UTC midnight dates of the first and last day of the month err := server.db.StripeCoinPayments().ProjectRecords().Check(ctx, projectID, firstOfMonth.AddDate(0, -1, 0), firstOfMonth.Add(-time.Hour*24)) switch err { case stripecoinpayments.ErrProjectRecordExists: diff --git a/satellite/admin/project_test.go b/satellite/admin/project_test.go index 5a7d50c3d..f2dc6addc 100644 --- a/satellite/admin/project_test.go +++ b/satellite/admin/project_test.go @@ -538,7 +538,7 @@ func TestDeleteProjectWithUsagePreviousMonth(t *testing.T) { err = planet.Satellites[0].DB.Console().APIKeys().Delete(ctx, apiKeys.APIKeys[0].ID) require.NoError(t, err) - //ToDo: Improve updating of DB entries + // TODO: Improve updating of DB entries now := time.Now().UTC() // set fixed day to avoid failures at the end of the month accTime := time.Date(now.Year(), now.Month()-1, 15, now.Hour(), now.Minute(), now.Second(), now.Nanosecond(), time.UTC) diff --git a/satellite/admin/user.go b/satellite/admin/user.go index 234d10350..1f5f980ad 100644 --- a/satellite/admin/user.go +++ b/satellite/admin/user.go @@ -108,7 +108,7 @@ func (server *Server) addUser(w http.ResponseWriter, r *http.Request) { return } - //Set User Status to be activated, as we manually created it + // Set User Status to be activated, as we manually created it newuser.Status = console.Active newuser.PasswordHash = nil err = server.db.Console().Users().Update(ctx, newuser) diff --git a/satellite/configlock_test.go b/satellite/configlock_test.go index c32154af0..47244005a 100644 --- a/satellite/configlock_test.go +++ b/satellite/configlock_test.go @@ -48,7 +48,7 @@ func TestConfigLock(t *testing.T) { assert.NoErrorf(t, err, "Error reading file for move") err = ioutil.WriteFile(lockPath, input, 0644) assert.NoErrorf(t, err, "Error writing file for move") - } else { //compare to satellite-config.yaml.lock + } else { // compare to satellite-config.yaml.lock configs1 := readLines(t, lockPath) configs2 := readLines(t, cleanedupConfig) if diff := cmp.Diff(configs1, configs2); diff != "" { @@ -84,11 +84,11 @@ func normalizeConfig(t *testing.T, configIn, configOut, tempDir string) { appDir := fpath.ApplicationDir() for scanner.Scan() { line := scanner.Text() - //fix metrics.app and tracing.app + // fix metrics.app and tracing.app line = strings.Replace(line, ".exe", "", 1) - //fix server.revocation-dburl + // fix server.revocation-dburl line = strings.Replace(line, tempDir, "testdata", 1) - //fix identity.cert-path and identity.key-path + // fix identity.cert-path and identity.key-path if strings.Contains(line, appDir) { line = strings.Replace(line, appDir, "/root/.local/share", 1) line = strings.ToLower(strings.ReplaceAll(line, "\\", "/")) diff --git a/satellite/console/auth.go b/satellite/console/auth.go index 08279c356..82eddc058 100644 --- a/satellite/console/auth.go +++ b/satellite/console/auth.go @@ -12,7 +12,7 @@ import ( "storj.io/storj/satellite/console/consoleauth" ) -//TODO: change to JWT or Macaroon based auth +// TODO: change to JWT or Macaroon based auth // Signer creates signature for provided data. type Signer interface { diff --git a/satellite/console/consoleauth/claims.go b/satellite/console/consoleauth/claims.go index 0f022d9a1..cd11f2555 100644 --- a/satellite/console/consoleauth/claims.go +++ b/satellite/console/consoleauth/claims.go @@ -11,7 +11,7 @@ import ( "storj.io/common/uuid" ) -//TODO: change to JWT or Macaroon based auth +// TODO: change to JWT or Macaroon based auth // Claims represents data signed by server and used for authentication. type Claims struct { diff --git a/satellite/console/consoleauth/hmac.go b/satellite/console/consoleauth/hmac.go index 6ff670cde..fb179d2da 100644 --- a/satellite/console/consoleauth/hmac.go +++ b/satellite/console/consoleauth/hmac.go @@ -8,7 +8,7 @@ import ( "crypto/sha256" ) -//TODO: change to JWT or Macaroon based auth +// TODO: change to JWT or Macaroon based auth // Hmac is hmac256 based Signer. type Hmac struct { diff --git a/satellite/console/consoleauth/token.go b/satellite/console/consoleauth/token.go index ab6e4589b..ed55aec29 100644 --- a/satellite/console/consoleauth/token.go +++ b/satellite/console/consoleauth/token.go @@ -12,7 +12,7 @@ import ( "github.com/zeebo/errs" ) -//TODO: change to JWT or Macaroon based auth +// TODO: change to JWT or Macaroon based auth // Token represents authentication data structure. type Token struct { diff --git a/satellite/console/projects_test.go b/satellite/console/projects_test.go index 232415fa8..163f5909f 100644 --- a/satellite/console/projects_test.go +++ b/satellite/console/projects_test.go @@ -21,7 +21,6 @@ import ( ) func TestProjectsRepository(t *testing.T) { - //testing constants const ( // for user shortName = "lastName" @@ -195,7 +194,7 @@ func TestProjectsList(t *testing.T) { projectsDB := db.Console().Projects() - //create projects + // Create projects var projects []console.Project for i := 0; i < length; i++ { proj, err := projectsDB.Insert(ctx, diff --git a/satellite/console/resetpasswordtoken_test.go b/satellite/console/resetpasswordtoken_test.go index fc3904903..10700bef3 100644 --- a/satellite/console/resetpasswordtoken_test.go +++ b/satellite/console/resetpasswordtoken_test.go @@ -16,9 +16,7 @@ import ( ) func TestNewRegistrationSecret(t *testing.T) { - // testing constants const ( - // for user shortName = "lastName" email = "email@mail.test" pass = "123456" diff --git a/satellite/console/service.go b/satellite/console/service.go index 22e7a6aee..e1d2005b0 100644 --- a/satellite/console/service.go +++ b/satellite/console/service.go @@ -227,7 +227,7 @@ func (paymentService PaymentsService) AddCreditCard(ctx context.Context, creditC return nil } - //ToDo: check if this is the right place + // TODO: check if this is the right place err = paymentService.AddPromotionalCoupon(ctx, auth.User.ID) if err != nil { paymentService.service.log.Warn(fmt.Sprintf("could not add promotional coupon for user %s", auth.User.ID.String()), zap.Error(err)) @@ -534,7 +534,7 @@ func (s *Service) CreateUser(ctx context.Context, user CreateUser, tokenSecret R offerType = rewards.Referral } - //TODO: Create a current offer cache to replace database call + // TODO: Create a current offer cache to replace database call offers, err := s.rewards.GetActiveOffersByType(ctx, offerType) if err != nil && !rewards.ErrOfferNotExist.Has(err) { s.log.Error("internal error", zap.Error(err)) @@ -641,7 +641,7 @@ func (s *Service) CreateUser(ctx context.Context, user CreateUser, tokenSecret R func (s *Service) GenerateActivationToken(ctx context.Context, id uuid.UUID, email string) (token string, err error) { defer mon.Task()(&ctx)(&err) - //TODO: activation token should differ from auth token + // TODO: activation token should differ from auth token claims := &consoleauth.Claims{ ID: id, Email: email, @@ -719,7 +719,7 @@ func (s *Service) ActivateAccount(ctx context.Context, activationToken string) ( return nil } - //ToDo: check if this is the right place + // TODO: check if this is the right place err = s.accounts.Coupons().AddPromotionalCoupon(ctx, user.ID) if err != nil { s.log.Debug(fmt.Sprintf("could not add promotional coupon for user %s", user.ID.String()), zap.Error(Error.Wrap(err))) diff --git a/satellite/console/usercredits_test.go b/satellite/console/usercredits_test.go index e2c2d3b93..ed19f7bda 100644 --- a/satellite/console/usercredits_test.go +++ b/satellite/console/usercredits_test.go @@ -298,7 +298,7 @@ func setupData(ctx context.Context, t *testing.T, db satellite.DB) (user *consol }) require.NoError(t, err) - //create an user as referrer + // create an user as referrer referrer, err = consoleDB.Users().Insert(ctx, &console.User{ ID: testrand.UUID(), FullName: "referrer", diff --git a/satellite/console/users_test.go b/satellite/console/users_test.go index ba50fa245..685b6f7c8 100644 --- a/satellite/console/users_test.go +++ b/satellite/console/users_test.go @@ -17,7 +17,6 @@ import ( "storj.io/storj/satellite/satellitedb/satellitedbtest" ) -//testing constants. const ( lastName = "lastName" email = "email@mail.test" diff --git a/satellite/mailservice/service.go b/satellite/mailservice/service.go index f406b12d6..577c519b8 100644 --- a/satellite/mailservice/service.go +++ b/satellite/mailservice/service.go @@ -57,7 +57,7 @@ type Service struct { html *htmltemplate.Template // TODO(yar): prepare plain text version - //text *texttemplate.Template + // text *texttemplate.Template sending sync.WaitGroup } @@ -68,10 +68,10 @@ func New(log *zap.Logger, sender Sender, templatePath string) (*Service, error) service := &Service{log: log, sender: sender} // TODO(yar): prepare plain text version - //service.text, err = texttemplate.ParseGlob(filepath.Join(templatePath, "*.txt")) - //if err != nil { - // return nil, err - //} + // service.text, err = texttemplate.ParseGlob(filepath.Join(templatePath, "*.txt")) + // if err != nil { + // return nil, err + // } service.html, err = htmltemplate.ParseGlob(filepath.Join(templatePath, "*.html")) if err != nil { @@ -126,9 +126,9 @@ func (service *Service) SendRendered(ctx context.Context, to []post.Address, msg var textBuffer bytes.Buffer // TODO(yar): prepare plain text version - //if err = service.text.ExecuteTemplate(&textBuffer, msg.Template() + ".txt", msg); err != nil { - // return - //} + // if err = service.text.ExecuteTemplate(&textBuffer, msg.Template() + ".txt", msg); err != nil { + // return + // } if err = service.html.ExecuteTemplate(&htmlBuffer, msg.Template()+".html", msg); err != nil { return diff --git a/satellite/marketingweb/server_test.go b/satellite/marketingweb/server_test.go index f65546522..494a26593 100644 --- a/satellite/marketingweb/server_test.go +++ b/satellite/marketingweb/server_test.go @@ -80,7 +80,7 @@ func TestCreateAndStopOffers(t *testing.T) { return err } require.Equal(t, http.StatusOK, req.StatusCode) - //reading out the rest of the connection + // reading out the rest of the connection _, err = io.Copy(ioutil.Discard, req.Body) if err != nil { return err diff --git a/satellite/metainfo/batch.go b/satellite/metainfo/batch.go index c2eeede27..ab0ef649b 100644 --- a/satellite/metainfo/batch.go +++ b/satellite/metainfo/batch.go @@ -72,7 +72,7 @@ func (endpoint *Endpoint) Batch(ctx context.Context, req *pb.BatchRequest) (resp }, }) - //OBJECT + // OBJECT case *pb.BatchRequestItem_ObjectBegin: singleRequest.ObjectBegin.Header = req.Header response, err := endpoint.BeginObject(ctx, singleRequest.ObjectBegin) diff --git a/satellite/metainfo/db_test.go b/satellite/metainfo/db_test.go index 04ad688a6..fa119e475 100644 --- a/satellite/metainfo/db_test.go +++ b/satellite/metainfo/db_test.go @@ -68,7 +68,7 @@ func TestBasicBucketOperations(t *testing.T) { require.Equal(t, expectedBucket.DefaultRedundancyScheme, bucket.DefaultRedundancyScheme) require.Equal(t, expectedBucket.DefaultEncryptionParameters, bucket.DefaultEncryptionParameters) - //CountBuckets + // CountBuckets count, err = bucketsDB.CountBuckets(ctx, project.ID) require.NoError(t, err) require.Equal(t, 1, count) diff --git a/satellite/metainfo/metainfo.go b/satellite/metainfo/metainfo.go index b0e76bda3..e5e3eb293 100644 --- a/satellite/metainfo/metainfo.go +++ b/satellite/metainfo/metainfo.go @@ -1361,7 +1361,7 @@ func (endpoint *Endpoint) commitSegment(ctx context.Context, req *pb.SegmentComm // ToDo: Replace with hash & signature validation // Ensure neither uplink or storage nodes are cheating on us if pointer.Type == pb.Pointer_REMOTE { - //We cannot have more redundancy than total/min + // We cannot have more redundancy than total/min if float64(totalStored) > (float64(pointer.SegmentSize)/float64(pointer.Remote.Redundancy.MinReq))*float64(pointer.Remote.Redundancy.Total) { endpoint.log.Debug("data size mismatch", zap.Int64("segment", pointer.SegmentSize), diff --git a/satellite/overlay/selection_test.go b/satellite/overlay/selection_test.go index 74714dfe3..a592df9e3 100644 --- a/satellite/overlay/selection_test.go +++ b/satellite/overlay/selection_test.go @@ -134,7 +134,7 @@ func TestOffline(t *testing.T) { result, err = service.KnownUnreliableOrOffline(ctx, []storj.NodeID{ planet.StorageNodes[0].ID(), - {1, 2, 3, 4}, //note that this succeeds by design + {1, 2, 3, 4}, // note that this succeeds by design planet.StorageNodes[2].ID(), }) require.NoError(t, err) diff --git a/satellite/overlay/service.go b/satellite/overlay/service.go index 1b04a91f2..312635e37 100644 --- a/satellite/overlay/service.go +++ b/satellite/overlay/service.go @@ -531,12 +531,12 @@ func ResolveIPAndNetwork(ctx context.Context, target string) (ipPort, network st // If addr can be converted to 4byte notation, it is an IPv4 address, else its an IPv6 address if ipv4 := ipAddr.IP.To4(); ipv4 != nil { - //Filter all IPv4 Addresses into /24 Subnet's + // Filter all IPv4 Addresses into /24 Subnet's mask := net.CIDRMask(24, 32) return net.JoinHostPort(ipAddr.String(), port), ipv4.Mask(mask).String(), nil } if ipv6 := ipAddr.IP.To16(); ipv6 != nil { - //Filter all IPv6 Addresses into /64 Subnet's + // Filter all IPv6 Addresses into /64 Subnet's mask := net.CIDRMask(64, 128) return net.JoinHostPort(ipAddr.String(), port), ipv6.Mask(mask).String(), nil } diff --git a/satellite/payments/coinpayments/transactions_test.go b/satellite/payments/coinpayments/transactions_test.go index 15ced557b..14e5a6993 100644 --- a/satellite/payments/coinpayments/transactions_test.go +++ b/satellite/payments/coinpayments/transactions_test.go @@ -13,7 +13,7 @@ import ( ) func TestListInfos(t *testing.T) { - //This test is deliberately skipped as it requires credentials to coinpayments.net + // This test is deliberately skipped as it requires credentials to coinpayments.net t.SkipNow() ctx := testcontext.New(t) defer ctx.Cleanup() @@ -23,12 +23,12 @@ func TestListInfos(t *testing.T) { PrivateKey: "ask-littleskunk-on-keybase", }).Transactions() - //verify that bad ids fail + // verify that bad ids fail infos, err := payments.ListInfos(ctx, TransactionIDList{"an_unlikely_id"}) assert.Error(t, err) assert.Len(t, infos, 0) - //verify that ListInfos can handle more than 25 good ids + // verify that ListInfos can handle more than 25 good ids ids := TransactionIDList{} for x := 0; x < 27; x++ { tx, err := payments.Create(ctx, diff --git a/satellite/payments/stripecoinpayments/accounts.go b/satellite/payments/stripecoinpayments/accounts.go index f762cf3a8..d42253a97 100644 --- a/satellite/payments/stripecoinpayments/accounts.go +++ b/satellite/payments/stripecoinpayments/accounts.go @@ -152,7 +152,7 @@ func (accounts *accounts) CheckProjectInvoicingStatus(ctx context.Context, proje } if lastMonthUsage.Storage > 0 || lastMonthUsage.Egress > 0 || lastMonthUsage.ObjectCount > 0 { - //time passed into the check function need to be the UTC midnight dates of the first and last day of the month + // time passed into the check function need to be the UTC midnight dates of the first and last day of the month err = accounts.service.db.ProjectRecords().Check(ctx, projectID, firstOfMonth.AddDate(0, -1, 0), firstOfMonth.Add(-time.Hour*24)) switch err { case ErrProjectRecordExists: @@ -236,7 +236,7 @@ func (accounts *accounts) PaywallEnabled(userID uuid.UUID) bool { return BytesAreWithinProportion(userID, accounts.service.PaywallProportion) } -//BytesAreWithinProportion returns true if first byte is less than the normalized proportion [0..1]. +// BytesAreWithinProportion returns true if first byte is less than the normalized proportion [0..1]. func BytesAreWithinProportion(uuidBytes [16]byte, proportion float64) bool { return int(uuidBytes[0]) < int(proportion*256) } diff --git a/satellite/payments/stripecoinpayments/service.go b/satellite/payments/stripecoinpayments/service.go index 6bf9da887..794ff9798 100644 --- a/satellite/payments/stripecoinpayments/service.go +++ b/satellite/payments/stripecoinpayments/service.go @@ -74,7 +74,7 @@ type Service struct { // Minimum CoinPayment to create a coupon MinCoinPayment int64 - //Stripe Extended Features + // Stripe Extended Features AutoAdvance bool mu sync.Mutex @@ -204,7 +204,7 @@ func (service *Service) updateTransactions(ctx context.Context, ids TransactionA // moment of CoinPayments receives funds, not when STORJ does // this was a business decision to not wait until StatusCompleted if info.Status >= coinpayments.StatusReceived { - //monkit currently does not have a DurationVal + // monkit currently does not have a DurationVal mon.IntVal("coinpayment_duration").Observe(int64(time.Since(creationTimes[id]))) applies = append(applies, id) } diff --git a/satellite/repair/checker/checker_test.go b/satellite/repair/checker/checker_test.go index 721a1df68..b133f14e8 100644 --- a/satellite/repair/checker/checker_test.go +++ b/satellite/repair/checker/checker_test.go @@ -154,7 +154,7 @@ func TestIdentifyIrreparableSegments(t *testing.T) { _, err = repairQueue.Select(ctx) require.True(t, storage.ErrEmptyQueue.Has(err)) - //check if the expected segments were added to the irreparable DB + // check if the expected segments were added to the irreparable DB irreparable := planet.Satellites[0].DB.Irreparable() remoteSegmentInfo, err := irreparable.Get(ctx, pointerKey) require.NoError(t, err) diff --git a/satellite/repair/irreparable/irreparable_test.go b/satellite/repair/irreparable/irreparable_test.go index da5c592a3..3b253071b 100644 --- a/satellite/repair/irreparable/irreparable_test.go +++ b/satellite/repair/irreparable/irreparable_test.go @@ -93,7 +93,7 @@ func TestIrreparable(t *testing.T) { require.Empty(t, cmp.Diff(segments[0], dbxInfo, cmp.Comparer(pb.Equal))) } - { //Delete existing entry + { // Delete existing entry err := irrdb.Delete(ctx, segments[0].Path) require.NoError(t, err) diff --git a/satellite/repair/repairer/segments.go b/satellite/repair/repairer/segments.go index 577a46aa5..15572079d 100644 --- a/satellite/repair/repairer/segments.go +++ b/satellite/repair/repairer/segments.go @@ -61,7 +61,7 @@ type SegmentRepairer struct { // repaired pieces multiplierOptimalThreshold float64 - //repairOverride is the value handed over from the checker to override the Repair Threshold + // repairOverride is the value handed over from the checker to override the Repair Threshold repairOverride int } diff --git a/satellite/satellitedb/apikeys.go b/satellite/satellitedb/apikeys.go index e5cf5deeb..0668fd446 100644 --- a/satellite/satellitedb/apikeys.go +++ b/satellite/satellitedb/apikeys.go @@ -28,7 +28,7 @@ type apikeys struct { func (keys *apikeys) GetPagedByProjectID(ctx context.Context, projectID uuid.UUID, cursor console.APIKeyCursor) (akp *console.APIKeyPage, err error) { defer mon.Task()(&ctx)(&err) - search := "%" + strings.Replace(cursor.Search, " ", "%", -1) + "%" + search := "%" + strings.ReplaceAll(cursor.Search, " ", "%") + "%" if cursor.Limit > 50 { cursor.Limit = 50 diff --git a/satellite/satellitedb/projectmembers.go b/satellite/satellitedb/projectmembers.go index eaea589cf..9cd13b460 100644 --- a/satellite/satellitedb/projectmembers.go +++ b/satellite/satellitedb/projectmembers.go @@ -38,7 +38,7 @@ func (pm *projectMembers) GetByMemberID(ctx context.Context, memberID uuid.UUID) func (pm *projectMembers) GetPagedByProjectID(ctx context.Context, projectID uuid.UUID, cursor console.ProjectMembersCursor) (_ *console.ProjectMembersPage, err error) { defer mon.Task()(&ctx)(&err) - search := "%" + strings.Replace(cursor.Search, " ", "%", -1) + "%" + search := "%" + strings.ReplaceAll(cursor.Search, " ", "%") + "%" if cursor.Limit > 50 { cursor.Limit = 50 diff --git a/satellite/satellitedb/repairqueue.go b/satellite/satellitedb/repairqueue.go index 4c44fa21d..e9ea76e17 100644 --- a/satellite/satellitedb/repairqueue.go +++ b/satellite/satellitedb/repairqueue.go @@ -120,7 +120,7 @@ func (r *repairQueue) SelectN(ctx context.Context, limit int) (segs []pb.Injured if limit <= 0 || limit > RepairQueueSelectLimit { limit = RepairQueueSelectLimit } - //todo: strictly enforce order-by or change tests + // TODO: strictly enforce order-by or change tests rows, err := r.db.QueryContext(ctx, r.db.Rebind(`SELECT data FROM injuredsegments LIMIT ?`), limit) if err != nil { return nil, Error.Wrap(err) diff --git a/storage/common.go b/storage/common.go index 937a2fe9c..4522248a8 100644 --- a/storage/common.go +++ b/storage/common.go @@ -16,7 +16,7 @@ var mon = monkit.Package() // Delimiter separates nested paths in storage. const Delimiter = '/' -//ErrKeyNotFound used when something doesn't exist. +// ErrKeyNotFound used when something doesn't exist. var ErrKeyNotFound = errs.Class("key not found") // ErrEmptyKey is returned when an empty key is used in Put or in CompareAndSwap. diff --git a/storage/testsuite/test_crud.go b/storage/testsuite/test_crud.go index 80035388f..7b26c168d 100644 --- a/storage/testsuite/test_crud.go +++ b/storage/testsuite/test_crud.go @@ -17,7 +17,7 @@ import ( func testCRUD(t *testing.T, ctx *testcontext.Context, store storage.KeyValueStore) { items := storage.Items{ - // newItem("0", "", false), //TODO: broken + // newItem("0", "", false), // TODO: broken newItem("\x00", "\x00", false), newItem("a/b", "\x01\x00", false), newItem("a\\b", "\xFF", false), diff --git a/storagenode/contact/contact_test.go b/storagenode/contact/contact_test.go index f8328e244..44eea8720 100644 --- a/storagenode/contact/contact_test.go +++ b/storagenode/contact/contact_test.go @@ -31,7 +31,7 @@ func TestStoragenodeContactEndpoint(t *testing.T) { firstPing := pingStats.WhenLastPinged() - time.Sleep(time.Second) //HACKFIX: windows has large time granularity + time.Sleep(time.Second) // HACKFIX: windows has large time granularity resp, err = pb.NewDRPCContactClient(conn).PingNode(ctx, &pb.ContactPingRequest{}) require.NotNil(t, resp) diff --git a/storagenode/peer.go b/storagenode/peer.go index 14aeab7f8..76f06e18c 100644 --- a/storagenode/peer.go +++ b/storagenode/peer.go @@ -456,7 +456,7 @@ func New(log *zap.Logger, full *identity.FullIdentity, db DB, revocationDB exten peer.Contact.Service, peer.DB.Bandwidth(), config.Storage.AllocatedDiskSpace.Int64(), - //TODO use config.Storage.Monitor.Interval, but for some reason is not set + // TODO: use config.Storage.Monitor.Interval, but for some reason is not set config.Storage.KBucketRefreshInterval, peer.Contact.Chore.Trigger, config.Storage2.Monitor, diff --git a/storagenode/pieces/cache.go b/storagenode/pieces/cache.go index d615114d1..86decbec4 100644 --- a/storagenode/pieces/cache.go +++ b/storagenode/pieces/cache.go @@ -199,8 +199,7 @@ func (blobs *BlobsUsageCache) SpaceUsedBySatellite(ctx context.Context, satellit return values.Total, values.ContentSize, nil } -// SpaceUsedForPieces returns the current total used space for -//// all pieces. +// SpaceUsedForPieces returns the current total used space for all pieces. func (blobs *BlobsUsageCache) SpaceUsedForPieces(ctx context.Context) (int64, int64, error) { blobs.mu.Lock() defer blobs.mu.Unlock() diff --git a/storagenode/piecestore/endpoint.go b/storagenode/piecestore/endpoint.go index e10c8970e..e5a29836a 100644 --- a/storagenode/piecestore/endpoint.go +++ b/storagenode/piecestore/endpoint.go @@ -122,7 +122,7 @@ var monLiveRequests = mon.TaskNamed("live-request") // Delete handles deleting a piece on piece store requested by uplink. // -// DEPRECATED in favor of DeletePieces. +// Deprecated: use DeletePieces instead. func (endpoint *Endpoint) Delete(ctx context.Context, delete *pb.PieceDeleteRequest) (_ *pb.PieceDeleteResponse, err error) { defer monLiveRequests(&ctx)(&err) defer mon.Task()(&ctx)(&err) diff --git a/storagenode/piecestore/verification_test.go b/storagenode/piecestore/verification_test.go index 9c8aebbf5..b60a117eb 100644 --- a/storagenode/piecestore/verification_test.go +++ b/storagenode/piecestore/verification_test.go @@ -259,8 +259,8 @@ func TestOrderLimitGetValidation(t *testing.T) { closeErr := downloader.Close() err = errs.Combine(readErr, closeErr) if tt.err != "" { - assert.Equal(t, 0, len(buffer)) //errors 10240 - require.Error(t, err) //nil + assert.Equal(t, 0, len(buffer)) + require.Error(t, err) require.Contains(t, err.Error(), tt.err) } else { require.NoError(t, err) diff --git a/storagenode/satellites/satellites.go b/storagenode/satellites/satellites.go index d12bfd477..0160fa762 100644 --- a/storagenode/satellites/satellites.go +++ b/storagenode/satellites/satellites.go @@ -14,15 +14,15 @@ import ( type Status = int const ( - //Unexpected status should not be used for sanity checking. + // Unexpected status should not be used for sanity checking. Unexpected Status = 0 - //Normal status reflects a lack of graceful exit. + // Normal status reflects a lack of graceful exit. Normal = 1 - //Exiting reflects an active graceful exit. + // Exiting reflects an active graceful exit. Exiting = 2 - //ExitSucceeded reflects a graceful exit that succeeded. + // ExitSucceeded reflects a graceful exit that succeeded. ExitSucceeded = 3 - //ExitFailed reflects a graceful exit that failed. + // ExitFailed reflects a graceful exit that failed. ExitFailed = 4 ) diff --git a/storagenode/storagenodedb/storagenodedbtest/run_test.go b/storagenode/storagenodedb/storagenodedbtest/run_test.go index dc0c3f453..7e42aa1af 100644 --- a/storagenode/storagenodedb/storagenodedbtest/run_test.go +++ b/storagenode/storagenodedb/storagenodedbtest/run_test.go @@ -128,7 +128,6 @@ func verifyOrders(t *testing.T, ctx *testcontext.Context, db *storagenodedb.DB, for _, order := range orders { for _, dbOrder := range dbOrders { if order.Order.SerialNumber == dbOrder.Order.SerialNumber { - //fmt.Printf("Found %v\n", order.Order.SerialNumber) found++ } } diff --git a/versioncontrol/peer.go b/versioncontrol/peer.go index 86a25ae14..4c6f240f8 100644 --- a/versioncontrol/peer.go +++ b/versioncontrol/peer.go @@ -39,7 +39,8 @@ type Config struct { } // OldVersionConfig provides a list of allowed Versions per process. -// NB: this will be deprecated in favor of `ProcessesConfig`. +// +// NB: use `ProcessesConfig` for newer code instead. type OldVersionConfig struct { Satellite string `user:"true" help:"Allowed Satellite Versions" default:"v0.0.1"` Storagenode string `user:"true" help:"Allowed Storagenode Versions" default:"v0.0.1"`