diff --git a/atproto/atcrypto/keys_test.go b/atproto/atcrypto/keys_test.go index 80909041..92791edf 100644 --- a/atproto/atcrypto/keys_test.go +++ b/atproto/atcrypto/keys_test.go @@ -93,7 +93,7 @@ func TestLowSMany(t *testing.T) { msg := make([]byte, 1024) - for i := 0; i < 128; i++ { + for range 128 { privP256, err := GeneratePrivateKeyP256() assert.NoError(err) privK256, err := GeneratePrivateKeyK256() diff --git a/atproto/atdata/basic_test.go b/atproto/atdata/basic_test.go index bae3d88f..fa8b133e 100644 --- a/atproto/atdata/basic_test.go +++ b/atproto/atdata/basic_test.go @@ -14,21 +14,21 @@ func TestSimpleValidation(t *testing.T) { assert := assert.New(t) s := "a string" - assert.NoError(Validate(map[string]interface{}{ + assert.NoError(Validate(map[string]any{ "a": 5, "b": 123, "c": s, "d": &s, })) - assert.NoError(Validate(map[string]interface{}{ + assert.NoError(Validate(map[string]any{ "$type": "com.example.thing", "a": 5, })) - assert.Error(Validate(map[string]interface{}{ + assert.Error(Validate(map[string]any{ "$type": 123, "a": 5, })) - assert.Error(Validate(map[string]interface{}{ + assert.Error(Validate(map[string]any{ "$type": "", "a": 5, })) @@ -39,7 +39,7 @@ func TestSyntaxSerialize(t *testing.T) { atid, err := syntax.ParseAtIdentifier("did:web:example.com") assert.NoError(err) - obj := map[string]interface{}{ + obj := map[string]any{ "at-identifier": atid, "at-uri": syntax.ATURI("at://did:abc:123/io.nsid.someFunc/record-key"), "cid-string": syntax.CID("bafyreidfayvfuwqa7qlnopdjiqrxzs6blmoeu4rujcjtnci5beludirz2a"), @@ -63,17 +63,17 @@ func TestExtractBlobs(t *testing.T) { assert := assert.New(t) cid1, _ := cid.Parse("bafkreiccldh766hwcnuxnf2wh6jgzepf2nlu2lvcllt63eww5p6chi4ity") - obj := map[string]interface{}{ + obj := map[string]any{ "a": 5, "b": 123, - "c": map[string]interface{}{ + "c": map[string]any{ "blb": Blob{ Size: 567, MimeType: "image/jpeg", Ref: CIDLink(cid1), }, }, - "d": []interface{}{ + "d": []any{ 123, Blob{ Size: 123, diff --git a/atproto/atdata/data.go b/atproto/atdata/data.go index 1d824c4b..0ee380d3 100644 --- a/atproto/atdata/data.go +++ b/atproto/atdata/data.go @@ -95,7 +95,7 @@ func forCBOR(obj map[string]any) map[string]any { case Bytes: out[k] = []byte(v) case Blob: - out[k] = map[string]interface{}{ + out[k] = map[string]any{ "$type": "blob", "mimeType": v.MimeType, "ref": cid.Cid(v.Ref), @@ -127,7 +127,7 @@ func forCBORArray(arr []any) []any { case Bytes: out[i] = []byte(v) case Blob: - out[i] = map[string]interface{}{ + out[i] = map[string]any{ "$type": "blob", "mimeType": v.MimeType, "ref": cid.Cid(v.Ref), diff --git a/atproto/auth/jwt_signing.go b/atproto/auth/jwt_signing.go index d7007d57..29cf1bc8 100644 --- a/atproto/auth/jwt_signing.go +++ b/atproto/auth/jwt_signing.go @@ -48,7 +48,7 @@ func init() { supportedAlgs = []string{signingMethodES256K.Alg(), signingMethodES256.Alg()} } -func (sm *signingMethodAtproto) Verify(signingString string, sig []byte, key interface{}) error { +func (sm *signingMethodAtproto) Verify(signingString string, sig []byte, key any) error { pub, ok := key.(atcrypto.PublicKey) if !ok { return jwt.ErrInvalidKeyType @@ -66,7 +66,7 @@ func (sm *signingMethodAtproto) Verify(signingString string, sig []byte, key int return pub.HashAndVerifyLenient([]byte(signingString), sig) } -func (sm *signingMethodAtproto) Sign(signingString string, key interface{}) ([]byte, error) { +func (sm *signingMethodAtproto) Sign(signingString string, key any) ([]byte, error) { priv, ok := key.(atcrypto.PrivateKey) if !ok { return nil, jwt.ErrInvalidKeyType diff --git a/atproto/auth/oauth/jwt_signing.go b/atproto/auth/oauth/jwt_signing.go index 4981189d..1155d940 100644 --- a/atproto/auth/oauth/jwt_signing.go +++ b/atproto/auth/oauth/jwt_signing.go @@ -41,7 +41,7 @@ func init() { supportedAlgs = []string{signingMethodES256.Alg()} } -func (sm *signingMethodAtproto) Verify(signingString string, sig []byte, key interface{}) error { +func (sm *signingMethodAtproto) Verify(signingString string, sig []byte, key any) error { pub, ok := key.(atcrypto.PublicKey) if !ok { return jwt.ErrInvalidKeyType @@ -59,7 +59,7 @@ func (sm *signingMethodAtproto) Verify(signingString string, sig []byte, key int return pub.HashAndVerifyLenient([]byte(signingString), sig) } -func (sm *signingMethodAtproto) Sign(signingString string, key interface{}) ([]byte, error) { +func (sm *signingMethodAtproto) Sign(signingString string, key any) ([]byte, error) { priv, ok := key.(atcrypto.PrivateKey) if !ok { return nil, jwt.ErrInvalidKeyType diff --git a/atproto/auth/oauth/session.go b/atproto/auth/oauth/session.go index f78fe0ec..8c258119 100644 --- a/atproto/auth/oauth/session.go +++ b/atproto/auth/oauth/session.go @@ -85,7 +85,7 @@ type ClientSession struct { // body object will be url-encoded (expected to be either RefreshTokenRequest or RevocationRequest) // expects sess.lk to be held by caller // if a non-nil *http.Response is returned, the caller is responsible for closing the response body -func (sess *ClientSession) postToAuthServer(ctx context.Context, url string, body interface{}) (*http.Response, error) { +func (sess *ClientSession) postToAuthServer(ctx context.Context, url string, body any) (*http.Response, error) { vals, err := query.Values(body) if err != nil { return nil, err diff --git a/atproto/identity/live_test.go b/atproto/identity/live_test.go index 589cd3db..9efb807e 100644 --- a/atproto/identity/live_test.go +++ b/atproto/identity/live_test.go @@ -95,10 +95,8 @@ func TestCacheCoalesce(t *testing.T) { // Cancel the context after 2 seconds, if we're coalescing correctly, we should only make 1 request ctx, cancel := context.WithTimeout(context.Background(), time.Second*2) defer cancel() - for i := 0; i < routines; i++ { - wg.Add(1) - go func() { - defer wg.Done() + for range routines { + wg.Go(func() { ident, err := dir.LookupDID(ctx, did) if err != nil { slog.Error("Failed lookup", "error", err) @@ -112,7 +110,7 @@ func TestCacheCoalesce(t *testing.T) { } assert.NoError(err) assert.Equal(did, ident.DID) - }() + }) } wg.Wait() } diff --git a/atproto/identity/redisdir/live_test.go b/atproto/identity/redisdir/live_test.go index 433c45b8..1a42d9c3 100644 --- a/atproto/identity/redisdir/live_test.go +++ b/atproto/identity/redisdir/live_test.go @@ -113,10 +113,8 @@ func TestRedisCoalesce(t *testing.T) { // Cancel the context after 2 seconds, if we're coalescing correctly, we should only make 1 request ctx, cancel := context.WithTimeout(context.Background(), time.Second*2) defer cancel() - for i := 0; i < routines; i++ { - wg.Add(1) - go func() { - defer wg.Done() + for range routines { + wg.Go(func() { ident, err := dir.LookupDID(ctx, did) if err != nil { slog.Error("Failed lookup", "error", err) @@ -130,7 +128,7 @@ func TestRedisCoalesce(t *testing.T) { } assert.NoError(err) assert.Equal(did, ident.DID) - }() + }) } wg.Wait() } diff --git a/atproto/lexicon/language.go b/atproto/lexicon/language.go index 82f2836f..3e8b000d 100644 --- a/atproto/lexicon/language.go +++ b/atproto/lexicon/language.go @@ -4,6 +4,7 @@ import ( "encoding/json" "fmt" "reflect" + "slices" "strings" "github.com/bluesky-social/indigo/atproto/atdata" @@ -663,13 +664,7 @@ func (s *SchemaInteger) Validate(d any) error { return fmt.Errorf("integer val outside specified range: %d", v) } if len(s.Enum) != 0 { - inEnum := false - for _, e := range s.Enum { - if e == v { - inEnum = true - break - } - } + inEnum := slices.Contains(s.Enum, v) if !inEnum { return fmt.Errorf("integer val not in required enum: %d", v) } @@ -735,13 +730,7 @@ func (s *SchemaString) Validate(d any, flags ValidateFlags) error { return fmt.Errorf("string length outside specified range: %d", len(v)) } if len(s.Enum) != 0 { - inEnum := false - for _, e := range s.Enum { - if e == v { - inEnum = true - break - } - } + inEnum := slices.Contains(s.Enum, v) if !inEnum { return fmt.Errorf("string val not in required enum: %s", v) } @@ -927,12 +916,7 @@ func (s *SchemaObject) CheckSchema() error { // Checks if a field name 'k' is one of the Nullable fields for this object func (s *SchemaObject) IsNullable(k string) bool { - for _, el := range s.Nullable { - if el == k { - return true - } - } - return false + return slices.Contains(s.Nullable, k) } type SchemaBlob struct { diff --git a/atproto/syntax/tid.go b/atproto/syntax/tid.go index bebb8467..3cf5ad06 100644 --- a/atproto/syntax/tid.go +++ b/atproto/syntax/tid.go @@ -49,7 +49,7 @@ func NewTIDNow(clockId uint) TID { func NewTIDFromInteger(v uint64) TID { v = (0x7FFF_FFFF_FFFF_FFFF & v) s := "" - for i := 0; i < 13; i++ { + for range 13 { s = string(Base32SortAlphabet[v&0x1F]) + s v = v >> 5 } @@ -74,7 +74,7 @@ func (t TID) Integer() uint64 { return 0 } var v uint64 - for i := 0; i < 13; i++ { + for i := range 13 { c := strings.IndexByte(Base32SortAlphabet, s[i]) if c < 0 { return 0 diff --git a/atproto/syntax/tid_test.go b/atproto/syntax/tid_test.go index ed0d94be..86de5c3d 100644 --- a/atproto/syntax/tid_test.go +++ b/atproto/syntax/tid_test.go @@ -123,7 +123,7 @@ func TestTIDClock(t *testing.T) { clk := NewTIDClock(0) last := NewTID(0, 0) - for i := 0; i < 100; i++ { + for range 100 { next := clk.Next() assert.Greater(next, last) last = next diff --git a/automod/countstore/countstore_test.go b/automod/countstore/countstore_test.go index e9d1d566..8961ece8 100644 --- a/automod/countstore/countstore_test.go +++ b/automod/countstore/countstore_test.go @@ -64,7 +64,7 @@ func TestMemCountStoreConcurrent(t *testing.T) { // and reads are interleaved with writes. var wg sync.WaitGroup fnInc := func(name, val string, times int) { - for i := 0; i < times; i++ { + for range times { assert.NoError(cs.Increment(ctx, name, val)) assert.NoError(cs.IncrementDistinct(ctx, name, name, val)) time.Sleep(time.Nanosecond) @@ -72,7 +72,7 @@ func TestMemCountStoreConcurrent(t *testing.T) { wg.Done() } fnRead := func(name, val string, times int) { - for i := 0; i < times; i++ { + for range times { _, err := cs.GetCount(ctx, name, val, PeriodTotal) assert.NoError(err) time.Sleep(time.Nanosecond) diff --git a/automod/engine/action_dedupe_test.go b/automod/engine/action_dedupe_test.go index b07a2a43..d292c7db 100644 --- a/automod/engine/action_dedupe_test.go +++ b/automod/engine/action_dedupe_test.go @@ -48,7 +48,7 @@ func TestAccountReportDedupe(t *testing.T) { CID: &cid1, RecordCBOR: p1cbor, } - for i := 0; i < 5; i++ { + for range 5 { assert.NoError(eng.ProcessRecordOp(ctx, op)) } diff --git a/automod/engine/effects.go b/automod/engine/effects.go index 44c6ae22..2408a138 100644 --- a/automod/engine/effects.go +++ b/automod/engine/effects.go @@ -1,6 +1,7 @@ package engine import ( + "slices" "sync" ) @@ -94,10 +95,8 @@ func (e *Effects) IncrementDistinct(name, bucket, val string) { func (e *Effects) AddAccountLabel(val string) { e.mu.Lock() defer e.mu.Unlock() - for _, v := range e.AccountLabels { - if v == val { - return - } + if slices.Contains(e.AccountLabels, val) { + return } e.AccountLabels = append(e.AccountLabels, val) } @@ -106,10 +105,8 @@ func (e *Effects) AddAccountLabel(val string) { func (e *Effects) RemoveAccountLabel(val string) { e.mu.Lock() defer e.mu.Unlock() - for _, v := range e.RemovedAccountLabels { - if v == val { - return - } + if slices.Contains(e.RemovedAccountLabels, val) { + return } e.RemovedAccountLabels = append(e.RemovedAccountLabels, val) } @@ -118,10 +115,8 @@ func (e *Effects) RemoveAccountLabel(val string) { func (e *Effects) AddAccountTag(val string) { e.mu.Lock() defer e.mu.Unlock() - for _, v := range e.AccountTags { - if v == val { - return - } + if slices.Contains(e.AccountTags, val) { + return } e.AccountTags = append(e.AccountTags, val) } @@ -130,10 +125,8 @@ func (e *Effects) AddAccountTag(val string) { func (e *Effects) AddAccountFlag(val string) { e.mu.Lock() defer e.mu.Unlock() - for _, v := range e.AccountFlags { - if v == val { - return - } + if slices.Contains(e.AccountFlags, val) { + return } e.AccountFlags = append(e.AccountFlags, val) } @@ -172,10 +165,8 @@ func (e *Effects) AcknowledgeAccount() { func (e *Effects) AddRecordLabel(val string) { e.mu.Lock() defer e.mu.Unlock() - for _, v := range e.RecordLabels { - if v == val { - return - } + if slices.Contains(e.RecordLabels, val) { + return } e.RecordLabels = append(e.RecordLabels, val) } @@ -184,10 +175,8 @@ func (e *Effects) AddRecordLabel(val string) { func (e *Effects) RemoveRecordLabel(val string) { e.mu.Lock() defer e.mu.Unlock() - for _, v := range e.RemovedRecordLabels { - if v == val { - return - } + if slices.Contains(e.RemovedRecordLabels, val) { + return } e.RemovedRecordLabels = append(e.RemovedRecordLabels, val) } @@ -196,10 +185,8 @@ func (e *Effects) RemoveRecordLabel(val string) { func (e *Effects) AddRecordTag(val string) { e.mu.Lock() defer e.mu.Unlock() - for _, v := range e.RecordTags { - if v == val { - return - } + if slices.Contains(e.RecordTags, val) { + return } e.RecordTags = append(e.RecordTags, val) } @@ -208,10 +195,8 @@ func (e *Effects) AddRecordTag(val string) { func (e *Effects) AddRecordFlag(val string) { e.mu.Lock() defer e.mu.Unlock() - for _, v := range e.RecordFlags { - if v == val { - return - } + if slices.Contains(e.RecordFlags, val) { + return } e.RecordFlags = append(e.RecordFlags, val) } @@ -250,10 +235,8 @@ func (e *Effects) AcknowledgeRecord() { func (e *Effects) TakedownBlob(cid string) { e.mu.Lock() defer e.mu.Unlock() - for _, v := range e.BlobTakedowns { - if v == cid { - return - } + if slices.Contains(e.BlobTakedowns, cid) { + return } e.BlobTakedowns = append(e.BlobTakedowns, cid) } @@ -262,10 +245,8 @@ func (e *Effects) TakedownBlob(cid string) { func (e *Effects) Notify(srv string) { e.mu.Lock() defer e.mu.Unlock() - for _, v := range e.NotifyServices { - if v == srv { - return - } + if slices.Contains(e.NotifyServices, srv) { + return } e.NotifyServices = append(e.NotifyServices, srv) } diff --git a/automod/engine/persisthelpers.go b/automod/engine/persisthelpers.go index 5642312b..d356e8ff 100644 --- a/automod/engine/persisthelpers.go +++ b/automod/engine/persisthelpers.go @@ -3,6 +3,7 @@ package engine import ( "context" "fmt" + "slices" "time" comatproto "github.com/bluesky-social/indigo/api/atproto" @@ -15,18 +16,9 @@ import ( func dedupeLabelActions(labels, existing, existingNegated []string) []string { newLabels := []string{} for _, val := range dedupeStrings(labels) { - exists := false - for _, e := range existingNegated { - if val == e { - exists = true - break - } - } - for _, e := range existing { - if val == e { - exists = true - break - } + exists := slices.Contains(existingNegated, val) + if slices.Contains(existing, val) { + exists = true } if !exists { newLabels = append(newLabels, val) @@ -38,13 +30,7 @@ func dedupeLabelActions(labels, existing, existingNegated []string) []string { func dedupeTagActions(tags, existing []string) []string { newTags := []string{} for _, val := range dedupeStrings(tags) { - exists := false - for _, e := range existing { - if val == e { - exists = true - break - } - } + exists := slices.Contains(existing, val) if !exists { newTags = append(newTags, val) } @@ -55,13 +41,7 @@ func dedupeTagActions(tags, existing []string) []string { func dedupeFlagActions(flags, existing []string) []string { newFlags := []string{} for _, val := range dedupeStrings(flags) { - exists := false - for _, e := range existing { - if val == e { - exists = true - break - } - } + exists := slices.Contains(existing, val) if !exists { newFlags = append(newFlags, val) } diff --git a/automod/flagstore/flagstore_redis.go b/automod/flagstore/flagstore_redis.go index ac1ee111..ccbee1ec 100644 --- a/automod/flagstore/flagstore_redis.go +++ b/automod/flagstore/flagstore_redis.go @@ -45,7 +45,7 @@ func (s *RedisFlagStore) Add(ctx context.Context, key string, flags []string) er if len(flags) == 0 { return nil } - l := []interface{}{} + l := []any{} for _, v := range flags { l = append(l, v) } @@ -57,7 +57,7 @@ func (s *RedisFlagStore) Remove(ctx context.Context, key string, flags []string) if len(flags) == 0 { return nil } - l := []interface{}{} + l := []any{} for _, v := range flags { l = append(l, v) } diff --git a/automod/keyword/keyword.go b/automod/keyword/keyword.go index dde62a69..392e2974 100644 --- a/automod/keyword/keyword.go +++ b/automod/keyword/keyword.go @@ -1,11 +1,8 @@ package keyword +import "slices" + // Helper to check a single token against a list of tokens func TokenInSet(tok string, set []string) bool { - for _, v := range set { - if tok == v { - return true - } - } - return false + return slices.Contains(set, tok) } diff --git a/automod/rules/harassment.go b/automod/rules/harassment.go index e38e7c44..bd251d21 100644 --- a/automod/rules/harassment.go +++ b/automod/rules/harassment.go @@ -2,6 +2,7 @@ package rules import ( "fmt" + "slices" "time" appbsky "github.com/bluesky-social/indigo/api/bsky" @@ -78,11 +79,8 @@ func HarassmentTargetInteractionPostRule(c *automod.RecordContext, post *appbsky continue } if targetAccount.Private != nil { - for _, t := range targetAccount.Private.AccountTags { - if t == "harassment-protection" { - targetIsProtected = true - break - } + if slices.Contains(targetAccount.Private.AccountTags, "harassment-protection") { + targetIsProtected = true } } } @@ -145,14 +143,10 @@ func HarassmentProtectionOzoneEventRule(c *automod.OzoneEventContext) error { return nil } - for _, t := range c.Event.Event.ModerationDefs_ModEventTag.Add { - if t == "harassment-protection" { - c.Logger.Info("adding harassment protection to account", "ozoneComment", c.Event.Event.ModerationDefs_ModEventTag.Comment, "did", c.Account.Identity.DID, "handle", c.Account.Identity.Handle) - // to make slack message clearer; bluring flags and tags is a bit weird - c.AddAccountFlag("harassment-protection") - //c.Notify("slack") - break - } + if slices.Contains(c.Event.Event.ModerationDefs_ModEventTag.Add, "harassment-protection") { + c.Logger.Info("adding harassment protection to account", "ozoneComment", c.Event.Event.ModerationDefs_ModEventTag.Comment, "did", c.Account.Identity.DID, "handle", c.Account.Identity.Handle) + // to make slack message clearer; bluring flags and tags is a bit weird + c.AddAccountFlag("harassment-protection") } return nil } diff --git a/backfill/backfill.go b/backfill/backfill.go index 06683b11..85377cb8 100644 --- a/backfill/backfill.go +++ b/backfill/backfill.go @@ -395,7 +395,7 @@ func (b *Backfiller) fetchRepo(ctx context.Context, did, since, host string) (io maxAttempts := len(retryDelays) + 1 var lastErr error - for attempt := 0; attempt < maxAttempts; attempt++ { + for attempt := range maxAttempts { if attempt > 0 { select { case <-ctx.Done(): @@ -547,10 +547,8 @@ func (b *Backfiller) BackfillRepo(ctx context.Context, job Job) (string, error) // Consumer routines wg := sync.WaitGroup{} - for i := 0; i < numRoutines; i++ { - wg.Add(1) - go func() { - defer wg.Done() + for range numRoutines { + wg.Go(func() { for item := range recordQueue { raw := item.data @@ -564,20 +562,18 @@ func (b *Backfiller) BackfillRepo(ctx context.Context, job Job) (string, error) backfillRecordsProcessed.WithLabelValues(b.Name).Inc() recordResults <- recordResult{recordPath: item.recordPath, err: err} } - }() + }) } resultWG := sync.WaitGroup{} - resultWG.Add(1) // Handle results - go func() { - defer resultWG.Done() + resultWG.Go(func() { for result := range recordResults { if result.err != nil { log.Error("Error processing record", "record", result.recordPath, "error", result.err) } } - }() + }) wg.Wait() close(recordResults) diff --git a/carstore/bs.go b/carstore/bs.go index aacbc1c8..310efb21 100644 --- a/carstore/bs.go +++ b/carstore/bs.go @@ -639,7 +639,7 @@ func (cs *FileCarStore) writeNewShard(ctx context.Context, root cid.Cid, rev str offset := hnw //brefs := make([]*blockRef, 0, len(ds.blks)) - brefs := make([]map[string]interface{}, 0, len(blks)) + brefs := make([]map[string]any, 0, len(blks)) for k, blk := range blks { nw, err := LdWrite(buf, k.Bytes(), blk.RawData()) if err != nil { @@ -655,7 +655,7 @@ func (cs *FileCarStore) writeNewShard(ctx context.Context, root cid.Cid, rev str */ // adding things to the db by map is the only way to get gorm to not // add the 'returning' clause, which costs a lot of time - brefs = append(brefs, map[string]interface{}{ + brefs = append(brefs, map[string]any{ "cid": models.DbCID{CID: k}, "offset": offset, }) @@ -1356,7 +1356,7 @@ func (cs *FileCarStore) compactBucket(ctx context.Context, user models.Uid, b *c return fmt.Errorf("failed to write block: %w", err) } - nbrefs = append(nbrefs, map[string]interface{}{ + nbrefs = append(nbrefs, map[string]any{ "cid": models.DbCID{CID: blk.Cid()}, "offset": offset, }) diff --git a/carstore/repo_test.go b/carstore/repo_test.go index 86982ebb..58cec59f 100644 --- a/carstore/repo_test.go +++ b/carstore/repo_test.go @@ -124,7 +124,7 @@ func TestBasicOperation(ot *testing.T) { var recs []cid.Cid head := ncid - for i := 0; i < 10; i++ { + for range 10 { ds, err := cs.NewDeltaSession(ctx, 1, &rev) if err != nil { t.Fatal(err) @@ -210,8 +210,8 @@ func TestRepeatedCompactions(t *testing.T) { var lastRec string - for loop := 0; loop < 50; loop++ { - for i := 0; i < 20; i++ { + for loop := range 50 { + for i := range 20 { ds, err := cs.NewDeltaSession(ctx, 1, &rev) if err != nil { t.Fatal(err) @@ -537,7 +537,7 @@ func TestDuplicateBlockAcrossShards(ot *testing.T) { var recs []cid.Cid head := cids[1] rev := revs[1] - for i := 0; i < 10; i++ { + for range 10 { ds, err := cs.NewDeltaSession(ctx, 2, &rev) if err != nil { t.Fatal(err) diff --git a/cmd/beemo/notify_mentions.go b/cmd/beemo/notify_mentions.go index f1cba426..19d3886a 100644 --- a/cmd/beemo/notify_mentions.go +++ b/cmd/beemo/notify_mentions.go @@ -67,7 +67,7 @@ func notifyMentions(ctx context.Context, cmd *cli.Command) error { minimumWords := cmd.Int("minimum-words") mentionDIDs := []syntax.DID{} - for _, raw := range strings.Split(cmd.String("mention-dids"), ",") { + for raw := range strings.SplitSeq(cmd.String("mention-dids"), ",") { did, err := syntax.ParseDID(raw) if err != nil { return err diff --git a/cmd/collectiondir/collectiondir.go b/cmd/collectiondir/collectiondir.go index cbf533dc..6d7dc9d4 100644 --- a/cmd/collectiondir/collectiondir.go +++ b/cmd/collectiondir/collectiondir.go @@ -321,7 +321,7 @@ var adminCrawlCmd = &cli.Command{ reqBlob, err := json.Marshal(postReqeust) reqReader := bytes.NewReader(reqBlob) - for try := 0; try < 3; try++ { + for try := range 3 { req, err := http.NewRequest("POST", requestCrawlUrl.String(), reqReader) if err != nil { return fmt.Errorf("could not create request, %w", err) diff --git a/cmd/fakermaker/main.go b/cmd/fakermaker/main.go index 5dca3c96..5eadb2cb 100644 --- a/cmd/fakermaker/main.go +++ b/cmd/fakermaker/main.go @@ -245,7 +245,7 @@ func genAccounts(ctx context.Context, cmd *cli.Command) error { var usr *fakedata.AccountContext var line []byte t1 := fakedata.MeasureIterations("register celebrity accounts") - for i := 0; i < countCelebrities; i++ { + for i := range countCelebrities { if usr, err = fakedata.GenAccount(xrpcc, i, "celebrity", domainSuffix, inviteCode); err != nil { return err } @@ -258,7 +258,7 @@ func genAccounts(ctx context.Context, cmd *cli.Command) error { t1(countCelebrities) t2 := fakedata.MeasureIterations("register regular accounts") - for i := 0; i < countRegulars; i++ { + for i := range countRegulars { if usr, err = fakedata.GenAccount(xrpcc, i, "regular", domainSuffix, inviteCode); err != nil { return err } @@ -285,7 +285,7 @@ func genProfiles(ctx context.Context, cmd *cli.Command) error { accChan := make(chan fakedata.AccountContext, len(catalog.Celebs)+len(catalog.Regulars)) eg := new(errgroup.Group) - for i := 0; i < jobs; i++ { + for range jobs { eg.Go(func() error { for acc := range accChan { xrpcc, err := fakedata.AccountXrpcClient(pdsHost, &acc) @@ -320,7 +320,7 @@ func genGraph(ctx context.Context, cmd *cli.Command) error { accChan := make(chan fakedata.AccountContext, len(catalog.Celebs)+len(catalog.Regulars)) eg := new(errgroup.Group) - for i := 0; i < jobs; i++ { + for range jobs { eg.Go(func() error { for acc := range accChan { xrpcc, err := fakedata.AccountXrpcClient(pdsHost, &acc) @@ -356,7 +356,7 @@ func genPosts(ctx context.Context, cmd *cli.Command) error { accChan := make(chan fakedata.AccountContext, len(catalog.Celebs)+len(catalog.Regulars)) eg := new(errgroup.Group) - for i := 0; i < jobs; i++ { + for range jobs { eg.Go(func() error { for acc := range accChan { xrpcc, err := fakedata.AccountXrpcClient(pdsHost, &acc) @@ -392,7 +392,7 @@ func genInteractions(ctx context.Context, cmd *cli.Command) error { accChan := make(chan fakedata.AccountContext, len(catalog.Celebs)+len(catalog.Regulars)) eg := new(errgroup.Group) - for i := 0; i < jobs; i++ { + for range jobs { eg.Go(func() error { for acc := range accChan { xrpcc, err := fakedata.AccountXrpcClient(pdsHost, &acc) @@ -427,7 +427,7 @@ func runBrowsing(ctx context.Context, cmd *cli.Command) error { accChan := make(chan fakedata.AccountContext, len(catalog.Celebs)+len(catalog.Regulars)) eg := new(errgroup.Group) - for i := 0; i < jobs; i++ { + for range jobs { eg.Go(func() error { for acc := range accChan { xrpcc, err := fakedata.AccountXrpcClient(pdsHost, &acc) diff --git a/cmd/netsync/main.go b/cmd/netsync/main.go index 85209f96..b372c05a 100644 --- a/cmd/netsync/main.go +++ b/cmd/netsync/main.go @@ -343,15 +343,13 @@ func Netsync(ctx context.Context, cmd *cli.Command) error { Handler: mux, } - state.wg.Add(1) - go func() { - defer state.wg.Done() + state.wg.Go(func() { if err := metricsServer.ListenAndServe(); err != http.ErrServerClosed { logger.Error("failed to start metrics server", "err", err) os.Exit(1) } logger.Info("metrics server shut down successfully") - }() + }) // Start workers for i := 0; i < state.workerCount; i++ { @@ -366,9 +364,7 @@ func Netsync(ctx context.Context, cmd *cli.Command) error { } // Check for empty queue - state.wg.Add(1) - go func() { - defer state.wg.Done() + state.wg.Go(func() { t := time.NewTicker(30 * time.Second) for { select { @@ -392,7 +388,7 @@ func Netsync(ctx context.Context, cmd *cli.Command) error { state.lk.RUnlock() } } - }() + }) // Trap SIGINT to trigger a shutdown. logger.Info("listening for signals") diff --git a/cmd/relay/stream/persist/diskpersist/diskpersist.go b/cmd/relay/stream/persist/diskpersist/diskpersist.go index b8dc097b..5df864a4 100644 --- a/cmd/relay/stream/persist/diskpersist/diskpersist.go +++ b/cmd/relay/stream/persist/diskpersist/diskpersist.go @@ -705,7 +705,7 @@ func (dp *DiskPersistence) Playback(ctx context.Context, since int64, cb func(*s // playback data from all the log files we found, then check the db to see if more were written during playback. // repeat a few times but not unboundedly. // don't decrease '10' below 2 because we should always do two passes through this if the above before-chunk query was used. - for i := 0; i < 10; i++ { + for range 10 { if needslogs { if err := dp.meta.Order("seq_start asc").Find(&logs, "seq_start >= ?", since).Error; err != nil { return err diff --git a/cmd/relay/stream/schedulers/parallel/parallel.go b/cmd/relay/stream/schedulers/parallel/parallel.go index 0786dcf8..254373f4 100644 --- a/cmd/relay/stream/schedulers/parallel/parallel.go +++ b/cmd/relay/stream/schedulers/parallel/parallel.go @@ -62,7 +62,7 @@ func NewScheduler(maxC, maxQ int, ident string, do func(context.Context, *stream log: slog.Default().With("system", "parallel-scheduler"), } - for i := 0; i < maxC; i++ { + for range maxC { go p.worker() } diff --git a/cmd/sonar/main.go b/cmd/sonar/main.go index 85980285..baa76a25 100644 --- a/cmd/sonar/main.go +++ b/cmd/sonar/main.go @@ -102,9 +102,7 @@ func runSonar(ctx context.Context, cmd *cli.Command) error { pool := sequential.NewScheduler(u.Host, s.HandleStreamEvent) // Start a goroutine to manage the cursor file, saving the current cursor every 5 seconds. - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { ticker := time.NewTicker(5 * time.Second) logger := logger.With("source", "cursor_file_manager") @@ -125,12 +123,10 @@ func runSonar(ctx context.Context, cmd *cli.Command) error { } } } - }() + }) // Start a goroutine to manage the liveness checker, shutting down if no events are received for 15 seconds - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { ticker := time.NewTicker(15 * time.Second) lastSeq := int64(0) @@ -154,7 +150,7 @@ func runSonar(ctx context.Context, cmd *cli.Command) error { } } } - }() + }) mux := http.NewServeMux() mux.Handle("/metrics", promhttp.Handler()) @@ -165,9 +161,7 @@ func runSonar(ctx context.Context, cmd *cli.Command) error { } // Startup metrics server - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { logger = logger.With("source", "metrics_server") logger.Info("metrics server listening", "port", cmd.Int("port")) @@ -176,7 +170,7 @@ func runSonar(ctx context.Context, cmd *cli.Command) error { log.Fatalf("failed to start metrics server: %+v", err) } logger.Info("metrics server shut down successfully") - }() + }) if s.Progress.LastSeq >= 0 { u.RawQuery = fmt.Sprintf("cursor=%d", s.Progress.LastSeq) @@ -192,13 +186,11 @@ func runSonar(ctx context.Context, cmd *cli.Command) error { } defer c.Close() - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { err = events.HandleRepoStream(ctx, c, pool, logger) logger.Info("HandleRepoStream returned unexpectedly", "err", err) cancel() - }() + }) select { case <-signals: diff --git a/cmd/stress/main.go b/cmd/stress/main.go index 70a62a45..2e42010a 100644 --- a/cmd/stress/main.go +++ b/cmd/stress/main.go @@ -123,11 +123,11 @@ var postingCmd = &cli.Command{ } var wg sync.WaitGroup - for con := 0; con < concurrent; con++ { + for con := range concurrent { wg.Add(1) go func(worker int) { defer wg.Done() - for i := 0; i < count; i++ { + for i := range count { buf := make([]byte, 100) rand.Read(buf) diff --git a/cmd/tap/event_manager.go b/cmd/tap/event_manager.go index 9058145b..4c9d4e02 100644 --- a/cmd/tap/event_manager.go +++ b/cmd/tap/event_manager.go @@ -192,7 +192,7 @@ func (em *EventManager) AddCommit(ctx context.Context, commit *Commit, dbCallbac func updateRepoCommitMeta(dbOrTx *gorm.DB, commit *Commit) error { return dbOrTx.Model(&models.Repo{}). Where("did = ?", commit.Did). - Updates(map[string]interface{}{ + Updates(map[string]any{ "rev": commit.Rev, "prev_data": commit.DataCid, }).Error diff --git a/cmd/tap/resyncer.go b/cmd/tap/resyncer.go index 5b25fae1..1a548742 100644 --- a/cmd/tap/resyncer.go +++ b/cmd/tap/resyncer.go @@ -332,7 +332,7 @@ func (r *Resyncer) doResync(ctx context.Context, did string) (bool, error) { if err := r.db.WithContext(ctx).Model(&models.Repo{}). Where("did = ?", did). - Updates(map[string]interface{}{ + Updates(map[string]any{ "state": models.RepoStateActive, "rev": rev, "prev_data": commit.Data.String(), @@ -368,7 +368,7 @@ func (r *Resyncer) handleResyncError(ctx context.Context, did string, resyncErr if err := r.db.WithContext(ctx).Model(&models.Repo{}). Where("did = ?", did). - Updates(map[string]interface{}{ + Updates(map[string]any{ "state": state, "error_msg": errMsg, "retry_count": repo.RetryCount + 1, diff --git a/cmd/tap/resyncer_test.go b/cmd/tap/resyncer_test.go index 97bf6b06..397e2f10 100644 --- a/cmd/tap/resyncer_test.go +++ b/cmd/tap/resyncer_test.go @@ -169,7 +169,7 @@ func TestHandleResyncError_ExponentialBackoff(t *testing.T) { var prevRetryAfter int64 - for i := 0; i < 4; i++ { + for i := range 4 { // Reset state to active so GetRepoState works for handleResyncError te.db.Model(&models.Repo{}).Where("did = ?", did).Update("state", models.RepoStateActive) diff --git a/cmd/tap/tap_test_helpers_test.go b/cmd/tap/tap_test_helpers_test.go index 4a04cda5..0a796516 100644 --- a/cmd/tap/tap_test_helpers_test.go +++ b/cmd/tap/tap_test_helpers_test.go @@ -167,7 +167,7 @@ func (te *testEnv) pushRecordEvents(did string, count int, live bool) []uint { te.t.Helper() evts := make([]*RecordEvt, count) - for i := 0; i < count; i++ { + for i := range count { evts[i] = &RecordEvt{ Live: live, Did: did, @@ -175,7 +175,7 @@ func (te *testEnv) pushRecordEvents(did string, count int, live bool) []uint { Collection: "app.bsky.feed.post", Rkey: fmt.Sprintf("rkey-%d-%d", time.Now().UnixNano(), i), Action: "create", - Record: map[string]interface{}{"text": fmt.Sprintf("test post %d", i)}, + Record: map[string]any{"text": fmt.Sprintf("test post %d", i)}, Cid: fmt.Sprintf("cid-%d-%d", time.Now().UnixNano(), i), } } @@ -190,7 +190,7 @@ func (te *testEnv) pushRecordEvents(did string, count int, live bool) []uint { } ids := make([]uint, count) - for i := 0; i < count; i++ { + for i := range count { ids[i] = startID + uint(i) + 1 } return ids diff --git a/cmd/tap/types.go b/cmd/tap/types.go index e49541cf..07741189 100644 --- a/cmd/tap/types.go +++ b/cmd/tap/types.go @@ -23,22 +23,22 @@ type Commit struct { } type CommitOp struct { - Collection string `json:"collection"` - Rkey string `json:"rkey"` - Action string `json:"action"` - Record map[string]interface{} `json:"record,omitempty"` - Cid string `json:"cid,omitempty"` + Collection string `json:"collection"` + Rkey string `json:"rkey"` + Action string `json:"action"` + Record map[string]any `json:"record,omitempty"` + Cid string `json:"cid,omitempty"` } type RecordEvt struct { - Live bool `json:"live"` - Did string `json:"did"` - Rev string `json:"rev"` - Collection string `json:"collection"` - Rkey string `json:"rkey"` - Action string `json:"action"` - Record map[string]interface{} `json:"record,omitempty"` - Cid string `json:"cid,omitempty"` + Live bool `json:"live"` + Did string `json:"did"` + Rev string `json:"rev"` + Collection string `json:"collection"` + Rkey string `json:"rkey"` + Action string `json:"action"` + Record map[string]any `json:"record,omitempty"` + Cid string `json:"cid,omitempty"` } func (e *RecordEvt) MarshalWithId(id uint) ([]byte, error) { diff --git a/events/dbpersist/dbpersist_test.go b/events/dbpersist/dbpersist_test.go index 5c21ea64..34fe38cc 100644 --- a/events/dbpersist/dbpersist_test.go +++ b/events/dbpersist/dbpersist_test.go @@ -97,17 +97,15 @@ func BenchmarkDBPersist(b *testing.B) { errChan := make(chan error, numRoutines) // Add events in parallel - for i := 0; i < numRoutines; i++ { - wg.Add(1) - go func() { - defer wg.Done() + for range numRoutines { + wg.Go(func() { for i := 0; i < b.N; i++ { err = evtman.AddEvent(ctx, inEvts[i]) if err != nil { errChan <- err } } - }() + }) } wg.Wait() @@ -192,7 +190,7 @@ func BenchmarkPlayback(b *testing.B) { } inEvts := make([]*events.XRPCStreamEvent, n) - for i := 0; i < n; i++ { + for i := range n { cidLink := lexutil.LexLink(cid) headLink := lexutil.LexLink(userRepoHead) inEvts[i] = &events.XRPCStreamEvent{ @@ -217,17 +215,15 @@ func BenchmarkPlayback(b *testing.B) { errChan := make(chan error, numRoutines) // Add events in parallel - for i := 0; i < numRoutines; i++ { - wg.Add(1) - go func() { - defer wg.Done() - for i := 0; i < n; i++ { + for range numRoutines { + wg.Go(func() { + for i := range n { err = evtman.AddEvent(ctx, inEvts[i]) if err != nil { errChan <- err } } - }() + }) } wg.Wait() diff --git a/events/diskpersist/diskpersist.go b/events/diskpersist/diskpersist.go index 04695d1d..814ba76f 100644 --- a/events/diskpersist/diskpersist.go +++ b/events/diskpersist/diskpersist.go @@ -635,7 +635,7 @@ func (dp *DiskPersistence) Playback(ctx context.Context, since int64, cb func(*e return err } - for i := 0; i < 10; i++ { + for range 10 { lastSeq, err := dp.PlaybackLogfiles(ctx, since, cb, logs) if err != nil { return err diff --git a/events/diskpersist/diskpersist_test.go b/events/diskpersist/diskpersist_test.go index bc1ef8bf..27768ec2 100644 --- a/events/diskpersist/diskpersist_test.go +++ b/events/diskpersist/diskpersist_test.go @@ -74,7 +74,7 @@ func testPersister(t *testing.T, perisistenceFactory func(path string, db *gorm. n := 100 inEvts := make([]*events.XRPCStreamEvent, n) - for i := 0; i < n; i++ { + for i := range n { cidLink := lexutil.LexLink(cid) headLink := lexutil.LexLink(userRepoHead) inEvts[i] = &events.XRPCStreamEvent{ @@ -95,7 +95,7 @@ func testPersister(t *testing.T, perisistenceFactory func(path string, db *gorm. } // Add events in parallel - for i := 0; i < n; i++ { + for i := range n { err = evtman.AddEvent(ctx, inEvts[i]) if err != nil { t.Fatal(err) @@ -134,7 +134,7 @@ func testPersister(t *testing.T, perisistenceFactory func(path string, db *gorm. evtman2 := events.NewEventManager(dp2) inEvts = make([]*events.XRPCStreamEvent, n) - for i := 0; i < n; i++ { + for i := range n { cidLink := lexutil.LexLink(cid) headLink := lexutil.LexLink(userRepoHead) inEvts[i] = &events.XRPCStreamEvent{ @@ -153,7 +153,7 @@ func testPersister(t *testing.T, perisistenceFactory func(path string, db *gorm. } } - for i := 0; i < n; i++ { + for i := range n { err = evtman2.AddEvent(ctx, inEvts[i]) if err != nil { t.Fatal(err) @@ -257,17 +257,15 @@ func runPersisterBenchmark(b *testing.B, cs carstore.CarStore, db *gorm.DB, p ev errChan := make(chan error, numRoutines) // Add events in parallel - for i := 0; i < numRoutines; i++ { - wg.Add(1) - go func() { - defer wg.Done() + for range numRoutines { + wg.Go(func() { for i := 0; i < b.N; i++ { err = evtman.AddEvent(ctx, inEvts[i]) if err != nil { errChan <- err } } - }() + }) } wg.Wait() @@ -345,7 +343,7 @@ func runEventManagerTest(t *testing.T, cs carstore.CarStore, db *gorm.DB, p even testSize := 100 // you can adjust this number as needed inEvts := make([]*events.XRPCStreamEvent, testSize) - for i := 0; i < testSize; i++ { + for i := range testSize { cidLink := lexutil.LexLink(cid) headLink := lexutil.LexLink(userRepoHead) inEvts[i] = &events.XRPCStreamEvent{ diff --git a/events/pebblepersist/pebblepersist_test.go b/events/pebblepersist/pebblepersist_test.go index 47c4bb9f..07ac71ab 100644 --- a/events/pebblepersist/pebblepersist_test.go +++ b/events/pebblepersist/pebblepersist_test.go @@ -81,7 +81,7 @@ func testPersister(t *testing.T, perisistenceFactory func(path string, db *gorm. n := 100 inEvts := make([]*events.XRPCStreamEvent, n) - for i := 0; i < n; i++ { + for i := range n { cidLink := lexutil.LexLink(cid) headLink := lexutil.LexLink(userRepoHead) inEvts[i] = &events.XRPCStreamEvent{ @@ -102,7 +102,7 @@ func testPersister(t *testing.T, perisistenceFactory func(path string, db *gorm. } // Add events in parallel - for i := 0; i < n; i++ { + for i := range n { err = evtman.AddEvent(ctx, inEvts[i]) if err != nil { t.Fatal(err) @@ -141,7 +141,7 @@ func testPersister(t *testing.T, perisistenceFactory func(path string, db *gorm. evtman2 := events.NewEventManager(dp2) inEvts = make([]*events.XRPCStreamEvent, n) - for i := 0; i < n; i++ { + for i := range n { cidLink := lexutil.LexLink(cid) headLink := lexutil.LexLink(userRepoHead) inEvts[i] = &events.XRPCStreamEvent{ @@ -160,7 +160,7 @@ func testPersister(t *testing.T, perisistenceFactory func(path string, db *gorm. } } - for i := 0; i < n; i++ { + for i := range n { err = evtman2.AddEvent(ctx, inEvts[i]) if err != nil { t.Fatal(err) diff --git a/events/schedulers/parallel/parallel.go b/events/schedulers/parallel/parallel.go index 25ba4716..7d1aec57 100644 --- a/events/schedulers/parallel/parallel.go +++ b/events/schedulers/parallel/parallel.go @@ -58,7 +58,7 @@ func NewScheduler(maxC, maxQ int, ident string, do func(context.Context, *events log: slog.Default().With("system", "parallel-scheduler"), } - for i := 0; i < maxC; i++ { + for range maxC { go p.worker() } diff --git a/lex/lexgen/codegen.go b/lex/lexgen/codegen.go index 999778f0..f93273fd 100644 --- a/lex/lexgen/codegen.go +++ b/lex/lexgen/codegen.go @@ -4,6 +4,7 @@ import ( "fmt" "io" "log/slog" + "slices" "sort" "strings" @@ -172,12 +173,7 @@ func (gen *CodeGenerator) WriteType(ft *FlatType) error { } func isRequired(required []string, fname string) bool { - for _, k := range required { - if k == fname { - return true - } - } - return false + return slices.Contains(required, fname) } func (gen *CodeGenerator) fieldType(fname string, def *lexicon.SchemaDef, optional bool) (string, error) { diff --git a/lex/util/decoder.go b/lex/util/decoder.go index 38512a1f..77fb3449 100644 --- a/lex/util/decoder.go +++ b/lex/util/decoder.go @@ -31,7 +31,7 @@ func RegisterType(id string, val cbg.CBORMarshaler) { lexTypesMap[id] = t } -func NewFromType(typ string) (interface{}, error) { +func NewFromType(typ string) (any, error) { t, ok := lexTypesMap[typ] if !ok { return nil, fmt.Errorf("%w: %q", ErrUnrecognizedType, typ) diff --git a/lex/util/lex_interop_old_test.go b/lex/util/lex_interop_old_test.go index 9fac95d2..cc2d3a7f 100644 --- a/lex/util/lex_interop_old_test.go +++ b/lex/util/lex_interop_old_test.go @@ -97,11 +97,11 @@ func TestInteropBasicOldSchema(t *testing.T) { assert.Equal(cidStr, goCborCid.String()) // reproduce JSON serialization - var jsonAll interface{} + var jsonAll any assert.NoError(json.Unmarshal([]byte(jsonStr), &jsonAll)) goJsonBytes, err := json.Marshal(goObj) assert.NoError(err) - var goJsonAll interface{} + var goJsonAll any assert.NoError(json.Unmarshal(goJsonBytes, &goJsonAll)) assert.Equal(jsonAll, goJsonAll) } @@ -162,11 +162,11 @@ func TestInteropIpldOldSchema(t *testing.T) { assert.Equal(cidStr, goCborCid.String()) // reproduce JSON serialization - var jsonAll interface{} + var jsonAll any assert.NoError(json.Unmarshal([]byte(jsonStr), &jsonAll)) goJsonBytes, err := json.Marshal(goObj) assert.NoError(err) - var goJsonAll interface{} + var goJsonAll any assert.NoError(json.Unmarshal(goJsonBytes, &goJsonAll)) assert.Equal(jsonAll, goJsonAll) } diff --git a/lex/util/lex_interop_test.go b/lex/util/lex_interop_test.go index 9fc8a500..188ed051 100644 --- a/lex/util/lex_interop_test.go +++ b/lex/util/lex_interop_test.go @@ -128,11 +128,11 @@ func TestInteropBasicSchema(t *testing.T) { assert.Equal(cidStr, goCborCid.String()) // reproduce JSON serialization - var jsonAll interface{} + var jsonAll any assert.NoError(json.Unmarshal([]byte(jsonStr), &jsonAll)) goJsonBytes, err := json.Marshal(goObj) assert.NoError(err) - var goJsonAll interface{} + var goJsonAll any assert.NoError(json.Unmarshal(goJsonBytes, &goJsonAll)) assert.Equal(jsonAll, goJsonAll) } @@ -214,11 +214,11 @@ func TestInteropIpldSchema(t *testing.T) { assert.Equal(cidStr, goCborCid.String()) // reproduce JSON serialization - var jsonAll interface{} + var jsonAll any assert.NoError(json.Unmarshal([]byte(jsonStr), &jsonAll)) goJsonBytes, err := json.Marshal(goObj) assert.NoError(err) - var goJsonAll interface{} + var goJsonAll any assert.NoError(json.Unmarshal(goJsonBytes, &goJsonAll)) assert.Equal(jsonAll, goJsonAll) } @@ -297,11 +297,11 @@ func TestInteropIpldNestedSchema(t *testing.T) { assert.Equal(goObj, jsonObj) // reproduce JSON serialization - var jsonAll interface{} + var jsonAll any assert.NoError(json.Unmarshal([]byte(jsonStr), &jsonAll)) goJsonBytes, err := json.Marshal(goObj) assert.NoError(err) - var goJsonAll interface{} + var goJsonAll any assert.NoError(json.Unmarshal(goJsonBytes, &goJsonAll)) assert.Equal(jsonAll, goJsonAll) diff --git a/lex/util/lex_types_test.go b/lex/util/lex_types_test.go index 173ea9b2..c5c86ebc 100644 --- a/lex/util/lex_types_test.go +++ b/lex/util/lex_types_test.go @@ -62,19 +62,19 @@ func TestBlobParse(t *testing.T) { assert.Equal(goObjLegacy, jsonObjLegacy) // reproduce JSON serialization - var jsonAll interface{} + var jsonAll any assert.NoError(json.Unmarshal([]byte(jsonStr), &jsonAll)) goJsonBytes, err := json.Marshal(goObj) assert.NoError(err) - var goJsonAll interface{} + var goJsonAll any assert.NoError(json.Unmarshal(goJsonBytes, &goJsonAll)) assert.Equal(jsonAll, goJsonAll) - var jsonAllLegacy interface{} + var jsonAllLegacy any assert.NoError(json.Unmarshal([]byte(jsonStrLegacy), &jsonAllLegacy)) goJsonBytesLegacy, err := json.Marshal(goObjLegacy) assert.NoError(err) - var goJsonAllLegacy interface{} + var goJsonAllLegacy any assert.NoError(json.Unmarshal(goJsonBytesLegacy, &goJsonAllLegacy)) assert.Equal(jsonAllLegacy, goJsonAllLegacy) } diff --git a/models/dbcid.go b/models/dbcid.go index 56cee3d2..a31d6a25 100644 --- a/models/dbcid.go +++ b/models/dbcid.go @@ -13,7 +13,7 @@ type DbCID struct { CID cid.Cid } -func (dbc *DbCID) Scan(v interface{}) error { +func (dbc *DbCID) Scan(v any) error { b, ok := v.([]byte) if !ok { return fmt.Errorf("dbcids must get bytes!") diff --git a/mst/mst_test.go b/mst/mst_test.go index d38223a0..cf53aefe 100644 --- a/mst/mst_test.go +++ b/mst/mst_test.go @@ -206,12 +206,12 @@ func randKey(s int64) string { func TestDiffInsertionsLarge(t *testing.T) { a := map[string]string{} - for i := int64(0); i < 1000; i++ { + for i := range int64(1000) { a[randKey(i)] = randStr(72385739 - i) } b := maps.Clone(a) - for i := int64(0); i < 30; i++ { + for i := range int64(30) { b[randKey(5000+i)] = randStr(2293825 - i) } @@ -221,12 +221,12 @@ func TestDiffInsertionsLarge(t *testing.T) { func TestDiffNoOverlap(t *testing.T) { a := map[string]string{} - for i := int64(0); i < 10; i++ { + for i := range int64(10) { a[randKey(i)] = randStr(72385739 - i) } b := map[string]string{} - for i := int64(0); i < 10; i++ { + for i := range int64(10) { b[randKey(5000+i)] = randStr(2293825 - i) } @@ -236,17 +236,17 @@ func TestDiffNoOverlap(t *testing.T) { func TestDiffSmallOverlap(t *testing.T) { a := map[string]string{} - for i := int64(0); i < 10; i++ { + for i := range int64(10) { a[randKey(i)] = randStr(72385739 - i) } b := maps.Clone(a) - for i := int64(0); i < 1000; i++ { + for i := range int64(1000) { a[randKey(i)] = randStr(682823 - i) } - for i := int64(0); i < 1000; i++ { + for i := range int64(1000) { b[randKey(5000+i)] = randStr(2293825 - i) } @@ -256,17 +256,17 @@ func TestDiffSmallOverlap(t *testing.T) { func TestDiffSmallOverlapSmall(t *testing.T) { a := map[string]string{} - for i := int64(0); i < 4; i++ { + for i := range int64(4) { a[randKey(i)] = randStr(72385739 - i) } b := maps.Clone(a) - for i := int64(0); i < 20; i++ { + for i := range int64(20) { a[randKey(i)] = randStr(682823 - i) } - for i := int64(0); i < 20; i++ { + for i := range int64(20) { b[randKey(5000+i)] = randStr(2293825 - i) } @@ -479,7 +479,7 @@ func compareDiffs(a, b []*DiffOp) bool { return false } - for i := 0; i < len(a); i++ { + for i := range a { aa := a[i] bb := b[i] @@ -529,7 +529,7 @@ func FuzzKeyHasAllValidChars(f *testing.F) { for _, seed := range [][]byte{{}} { f.Add(seed) } - for i := 0; i < 256; i++ { + for i := range 256 { f.Add([]byte{byte(i)}) } rx := regexp.MustCompile("^[a-zA-Z0-9_:.~-]+$") @@ -552,12 +552,12 @@ func BenchmarkDiffTrees(b *testing.B) { b.ReportAllocs() const size = 10000 ma := map[string]string{} - for i := 0; i < size; i++ { + for i := range size { ma[fmt.Sprintf("num/%02d", i)] = fmt.Sprint(i) } // And then mess with half of the items of the first half of it. mb := maps.Clone(ma) - for i := 0; i < size/2; i++ { + for i := range size / 2 { switch i % 4 { case 0, 1: case 2: diff --git a/repo/carutil/reader.go b/repo/carutil/reader.go index 7c9f9508..4267f129 100644 --- a/repo/carutil/reader.go +++ b/repo/carutil/reader.go @@ -122,8 +122,8 @@ func (b *BasicBlock) String() string { } // Loggable returns a go-log loggable item. -func (b *BasicBlock) Loggable() map[string]interface{} { - return map[string]interface{}{ +func (b *BasicBlock) Loggable() map[string]any { + return map[string]any{ "block": b.Cid().String(), } } diff --git a/repomgr/ingest_test.go b/repomgr/ingest_test.go index 602a06c3..dfbba7c1 100644 --- a/repomgr/ingest_test.go +++ b/repomgr/ingest_test.go @@ -126,7 +126,7 @@ func TestIngestWithGap(t *testing.T) { var since *string ctx := context.TODO() - for i := 0; i < 5; i++ { + for i := range 5 { slice, _, nrev, tid := doPost(t, cs2, did, since, i) ops := []*atproto.SyncSubscribeRepos_RepoOp{ @@ -144,7 +144,7 @@ func TestIngestWithGap(t *testing.T) { } // now do a few outside of the standard event stream flow - for i := 0; i < 5; i++ { + for i := range 5 { _, _, nrev, _ := doPost(t, cs2, did, since, i) since = &nrev } diff --git a/search/bulk.go b/search/bulk.go index 65c42f2b..bb58e0b6 100644 --- a/search/bulk.go +++ b/search/bulk.go @@ -32,7 +32,7 @@ func (idx *Indexer) BulkIndexPageranks(ctx context.Context, pagerankFile string) defer f.Close() // Run 5 pagerank indexers in parallel - for i := 0; i < 5; i++ { + for range 5 { go idx.runPagerankIndexer(ctx) } @@ -41,16 +41,14 @@ func (idx *Indexer) BulkIndexPageranks(ctx context.Context, pagerankFile string) queue := make(chan string, 20_000) wg := &sync.WaitGroup{} workerCount := 20 - for i := 0; i < workerCount; i++ { - wg.Add(1) - go func() { - defer wg.Done() + for range workerCount { + wg.Go(func() { for line := range queue { if err := idx.processPagerankCSVLine(line); err != nil { logger.Error("failed to process line", "err", err) } } - }() + }) } // Create a scanner to read the file line by line @@ -95,7 +93,7 @@ func (idx *Indexer) BulkIndexPosts(ctx context.Context, postsFile string) error defer f.Close() // Run 5 post indexers in parallel - for i := 0; i < 5; i++ { + for range 5 { go idx.runPostIndexer(ctx) } @@ -104,16 +102,14 @@ func (idx *Indexer) BulkIndexPosts(ctx context.Context, postsFile string) error queue := make(chan string, 20_000) wg := &sync.WaitGroup{} workerCount := 20 - for i := 0; i < workerCount; i++ { - wg.Add(1) - go func() { - defer wg.Done() + for range workerCount { + wg.Go(func() { for line := range queue { if err := idx.processPostCSVLine(line); err != nil { logger.Error("failed to process line", "err", err) } } - }() + }) } // Create a scanner to read the file line by line @@ -157,7 +153,7 @@ func (idx *Indexer) BulkIndexProfiles(ctx context.Context, profilesFile string) } defer f.Close() - for i := 0; i < 5; i++ { + for range 5 { go idx.runProfileIndexer(ctx) } @@ -166,16 +162,14 @@ func (idx *Indexer) BulkIndexProfiles(ctx context.Context, profilesFile string) queue := make(chan string, 20_000) wg := &sync.WaitGroup{} workerCount := 20 - for i := 0; i < workerCount; i++ { - wg.Add(1) - go func() { - defer wg.Done() + for range workerCount { + wg.Go(func() { for line := range queue { if err := idx.processProfileCSVLine(line); err != nil { logger.Error("failed to process line", "err", err) } } - }() + }) } // Create a scanner to read the file line by line diff --git a/search/query.go b/search/query.go index 14d6aef7..52ac9b25 100644 --- a/search/query.go +++ b/search/query.go @@ -105,12 +105,12 @@ func (p *PostSearchParams) Update(other *PostSearchParams) { } // Filters turns search params in to actual elasticsearch/opensearch filter DSL -func (p *PostSearchParams) Filters() []map[string]interface{} { - var filters []map[string]interface{} +func (p *PostSearchParams) Filters() []map[string]any { + var filters []map[string]any if p.Author != nil { - filters = append(filters, map[string]interface{}{ - "term": map[string]interface{}{"did": map[string]interface{}{ + filters = append(filters, map[string]any{ + "term": map[string]any{"did": map[string]any{ "value": p.Author.String(), "case_insensitive": true, }}, @@ -118,8 +118,8 @@ func (p *PostSearchParams) Filters() []map[string]interface{} { } if p.Mentions != nil { - filters = append(filters, map[string]interface{}{ - "term": map[string]interface{}{"mention_did": map[string]interface{}{ + filters = append(filters, map[string]any{ + "term": map[string]any{"mention_did": map[string]any{ "value": p.Mentions.String(), "case_insensitive": true, }}, @@ -128,8 +128,8 @@ func (p *PostSearchParams) Filters() []map[string]interface{} { if p.Lang != nil { // TODO: extracting just the 2-char code would be good - filters = append(filters, map[string]interface{}{ - "term": map[string]interface{}{"lang_code_iso2": map[string]interface{}{ + filters = append(filters, map[string]any{ + "term": map[string]any{"lang_code_iso2": map[string]any{ "value": p.Lang.String(), "case_insensitive": true, }}, @@ -137,9 +137,9 @@ func (p *PostSearchParams) Filters() []map[string]interface{} { } if p.Since != nil { - filters = append(filters, map[string]interface{}{ - "range": map[string]interface{}{ - "created_at": map[string]interface{}{ + filters = append(filters, map[string]any{ + "range": map[string]any{ + "created_at": map[string]any{ "gte": p.Since.String(), }, }, @@ -147,9 +147,9 @@ func (p *PostSearchParams) Filters() []map[string]interface{} { } if p.Until != nil { - filters = append(filters, map[string]interface{}{ - "range": map[string]interface{}{ - "created_at": map[string]interface{}{ + filters = append(filters, map[string]any{ + "range": map[string]any{ + "created_at": map[string]any{ "lt": p.Until.String(), }, }, @@ -157,8 +157,8 @@ func (p *PostSearchParams) Filters() []map[string]interface{} { } if p.URL != "" { - filters = append(filters, map[string]interface{}{ - "term": map[string]interface{}{"url": map[string]interface{}{ + filters = append(filters, map[string]any{ + "term": map[string]any{"url": map[string]any{ "value": NormalizeLossyURL(p.URL), "case_insensitive": true, }}, @@ -166,8 +166,8 @@ func (p *PostSearchParams) Filters() []map[string]interface{} { } if p.Domain != "" { - filters = append(filters, map[string]interface{}{ - "term": map[string]interface{}{"domain": map[string]interface{}{ + filters = append(filters, map[string]any{ + "term": map[string]any{"domain": map[string]any{ "value": p.Domain, "case_insensitive": true, }}, @@ -175,9 +175,9 @@ func (p *PostSearchParams) Filters() []map[string]interface{} { } for _, tag := range p.Tags { - filters = append(filters, map[string]interface{}{ - "term": map[string]interface{}{ - "tag": map[string]interface{}{ + filters = append(filters, map[string]any{ + "term": map[string]any{ + "tag": map[string]any{ "value": tag, "case_insensitive": true, }, @@ -189,16 +189,16 @@ func (p *PostSearchParams) Filters() []map[string]interface{} { } // Filters turns search params in to actual elasticsearch/opensearch filter DSL -func (p *ActorSearchParams) Filters() []map[string]interface{} { - var filters []map[string]interface{} +func (p *ActorSearchParams) Filters() []map[string]any { + var filters []map[string]any if p.Follows != nil && len(p.Follows) > 0 { follows := make([]string, len(p.Follows)) for i, did := range p.Follows { follows[i] = did.String() } - filters = append(filters, map[string]interface{}{ - "terms": map[string]interface{}{ + filters = append(filters, map[string]any{ + "terms": map[string]any{ "did": follows, }, }) @@ -227,8 +227,8 @@ func DoSearchPosts(ctx context.Context, dir identity.Directory, escli *es.Client if containsJapanese(params.Query) { idx = "everything_ja" } - basic := map[string]interface{}{ - "simple_query_string": map[string]interface{}{ + basic := map[string]any{ + "simple_query_string": map[string]any{ "query": params.Query, "fields": []string{idx}, "flags": "AND|NOT|OR|PHRASE|PRECEDENCE|WHITESPACE", @@ -240,16 +240,16 @@ func DoSearchPosts(ctx context.Context, dir identity.Directory, escli *es.Client filters := params.Filters() // filter out future posts (TODO: temporary hack) now := syntax.DatetimeNow() - filters = append(filters, map[string]interface{}{ - "range": map[string]interface{}{ - "created_at": map[string]interface{}{ + filters = append(filters, map[string]any{ + "range": map[string]any{ + "created_at": map[string]any{ "lte": now, }, }, }) - query := map[string]interface{}{ - "query": map[string]interface{}{ - "bool": map[string]interface{}{ + query := map[string]any{ + "query": map[string]any{ + "bool": map[string]any{ "must": basic, "filter": filters, }, @@ -276,8 +276,8 @@ func DoSearchProfiles(ctx context.Context, dir identity.Directory, escli *es.Cli filters := params.Filters() - fulltext := map[string]interface{}{ - "simple_query_string": map[string]interface{}{ + fulltext := map[string]any{ + "simple_query_string": map[string]any{ "query": params.Query, "fields": []string{"everything"}, "flags": "AND|NOT|OR|PHRASE|PRECEDENCE|WHITESPACE", @@ -292,8 +292,8 @@ func DoSearchProfiles(ctx context.Context, dir identity.Directory, escli *es.Cli // syntax), then have the primary query be an "OR" of the basic fulltext // query and the typeahead query if len(strings.Split(params.Query, " ")) == 1 { - typeahead := map[string]interface{}{ - "multi_match": map[string]interface{}{ + typeahead := map[string]any{ + "multi_match": map[string]any{ "query": params.Query, "type": "bool_prefix", "operator": "and", @@ -304,9 +304,9 @@ func DoSearchProfiles(ctx context.Context, dir identity.Directory, escli *es.Cli }, }, } - primary = map[string]interface{}{ - "bool": map[string]interface{}{ - "should": []interface{}{ + primary = map[string]any{ + "bool": map[string]any{ + "should": []any{ fulltext, typeahead, }, @@ -314,13 +314,13 @@ func DoSearchProfiles(ctx context.Context, dir identity.Directory, escli *es.Cli } } - query := map[string]interface{}{ - "query": map[string]interface{}{ - "bool": map[string]interface{}{ + query := map[string]any{ + "query": map[string]any{ + "bool": map[string]any{ "must": primary, - "should": []interface{}{ - map[string]interface{}{"term": map[string]interface{}{"has_avatar": true}}, - map[string]interface{}{"term": map[string]interface{}{"has_banner": true}}, + "should": []any{ + map[string]any{"term": map[string]any{"has_avatar": true}}, + map[string]any{"term": map[string]any{"has_banner": true}}, }, "minimum_should_match": 0, "boost": 0.5, @@ -331,7 +331,7 @@ func DoSearchProfiles(ctx context.Context, dir identity.Directory, escli *es.Cli } if len(filters) > 0 { - query["query"].(map[string]interface{})["bool"].(map[string]interface{})["filter"] = filters + query["query"].(map[string]any)["bool"].(map[string]any)["filter"] = filters } return doSearch(ctx, escli, index, query) @@ -347,11 +347,11 @@ func DoSearchProfilesTypeahead(ctx context.Context, escli *es.Client, index stri filters := params.Filters() - query := map[string]interface{}{ - "query": map[string]interface{}{ - "bool": map[string]interface{}{ - "must": map[string]interface{}{ - "multi_match": map[string]interface{}{ + query := map[string]any{ + "query": map[string]any{ + "bool": map[string]any{ + "must": map[string]any{ + "multi_match": map[string]any{ "query": params.Query, "type": "bool_prefix", "operator": "and", @@ -369,7 +369,7 @@ func DoSearchProfilesTypeahead(ctx context.Context, escli *es.Client, index stri } if len(filters) > 0 { - query["query"].(map[string]interface{})["bool"].(map[string]interface{})["filter"] = filters + query["query"].(map[string]any)["bool"].(map[string]any)["filter"] = filters } return doSearch(ctx, escli, index, query) @@ -380,9 +380,9 @@ func DoSearchGeneric(ctx context.Context, escli *es.Client, index, q string) (*E ctx, span := tracer.Start(ctx, "DoSearchGeneric") defer span.End() - query := map[string]interface{}{ - "query": map[string]interface{}{ - "query_string": map[string]interface{}{ + query := map[string]any{ + "query": map[string]any{ + "query_string": map[string]any{ "query": q, "default_operator": "and", "analyze_wildcard": true, @@ -396,7 +396,7 @@ func DoSearchGeneric(ctx context.Context, escli *es.Client, index, q string) (*E return doSearch(ctx, escli, index, query) } -func doSearch(ctx context.Context, escli *es.Client, index string, query interface{}) (*EsSearchResponse, error) { +func doSearch(ctx context.Context, escli *es.Client, index string, query any) (*EsSearchResponse, error) { ctx, span := tracer.Start(ctx, "doSearch") defer span.End() diff --git a/splitter/ringbuf.go b/splitter/ringbuf.go index a212259c..f0109902 100644 --- a/splitter/ringbuf.go +++ b/splitter/ringbuf.go @@ -70,7 +70,7 @@ func (er *EventRingBuffer) Flush(context.Context) error { func (er *EventRingBuffer) Playback(ctx context.Context, since int64, cb func(*events.XRPCStreamEvent) error) error { // run playback a few times to get as close to 'live' as possible before returning - for i := 0; i < 10; i++ { + for range 10 { n, err := er.playbackRound(ctx, since, cb) if err != nil { return err diff --git a/testing/feedpost_test.go b/testing/feedpost_test.go index a42cf708..e00e5dd0 100644 --- a/testing/feedpost_test.go +++ b/testing/feedpost_test.go @@ -119,9 +119,9 @@ func TestFeedPostParse(t *testing.T) { outJsonBytes, err := json.Marshal(fp) assert.NoError(err) fmt.Println(string(outJsonBytes)) - var outJsonObj map[string]interface{} + var outJsonObj map[string]any assert.NoError(json.Unmarshal(outJsonBytes, &outJsonObj)) - var expectedJsonObj map[string]interface{} + var expectedJsonObj map[string]any assert.NoError(json.Unmarshal([]byte(expectedJson), &expectedJsonObj)) assert.Equal(expectedJsonObj, outJsonObj) } diff --git a/testing/utils.go b/testing/utils.go index 61f85755..1dd38f12 100644 --- a/testing/utils.go +++ b/testing/utils.go @@ -40,7 +40,7 @@ var words = []string{ func MakeRandomPost() string { var out []string - for i := 0; i < 20; i++ { + for range 20 { out = append(out, words[mathrand.Intn(len(words))]) } @@ -145,7 +145,7 @@ func GenerateFakeRepo(r *repo.Repo, size int) (cid.Cid, error) { ctx := context.TODO() var root cid.Cid - for i := 0; i < size; i++ { + for range size { switch RandAction() { case "post": _, _, err := r.CreateRecord(ctx, "app.bsky.feed.post", &bsky.FeedPost{ diff --git a/util/http.go b/util/http.go index e4d4a8d9..d54a4ed0 100644 --- a/util/http.go +++ b/util/http.go @@ -16,19 +16,19 @@ type LeveledSlog struct { } // re-writes HTTP client ERROR to WARN level (because of retries) -func (l LeveledSlog) Error(msg string, keysAndValues ...interface{}) { +func (l LeveledSlog) Error(msg string, keysAndValues ...any) { l.inner.Warn(msg, keysAndValues...) } -func (l LeveledSlog) Warn(msg string, keysAndValues ...interface{}) { +func (l LeveledSlog) Warn(msg string, keysAndValues ...any) { l.inner.Warn(msg, keysAndValues...) } -func (l LeveledSlog) Info(msg string, keysAndValues ...interface{}) { +func (l LeveledSlog) Info(msg string, keysAndValues ...any) { l.inner.Info(msg, keysAndValues...) } -func (l LeveledSlog) Debug(msg string, keysAndValues ...interface{}) { +func (l LeveledSlog) Debug(msg string, keysAndValues ...any) { l.inner.Debug(msg, keysAndValues...) } diff --git a/xrpc/xrpc.go b/xrpc/xrpc.go index 0df0f149..30c4b86e 100644 --- a/xrpc/xrpc.go +++ b/xrpc/xrpc.go @@ -132,7 +132,7 @@ func makeParams(p map[string]any) string { return params.Encode() } -func (c *Client) Do(ctx context.Context, kind string, inpenc string, method string, params map[string]interface{}, bodyobj interface{}, out interface{}) error { +func (c *Client) Do(ctx context.Context, kind string, inpenc string, method string, params map[string]any, bodyobj any, out any) error { var body io.Reader if bodyobj != nil { if rr, ok := bodyobj.(io.Reader); ok { diff --git a/xrpc/xrpc_test.go b/xrpc/xrpc_test.go index 0ea822c5..97dc1b2c 100644 --- a/xrpc/xrpc_test.go +++ b/xrpc/xrpc_test.go @@ -8,24 +8,24 @@ import ( func TestMakeParams(t *testing.T) { testCases := []struct { name string - input map[string]interface{} + input map[string]any expected string }{ { name: "Empty input", - input: map[string]interface{}{}, + input: map[string]any{}, expected: "", }, { name: "Single value", - input: map[string]interface{}{ + input: map[string]any{ "key": "value", }, expected: "key=value", }, { name: "Multiple values", - input: map[string]interface{}{ + input: map[string]any{ "key1": "value1", "key2": "value2", }, @@ -33,14 +33,14 @@ func TestMakeParams(t *testing.T) { }, { name: "Slice of strings", - input: map[string]interface{}{ + input: map[string]any{ "key": []string{"value1", "value2", "value3"}, }, expected: "key=value1&key=value2&key=value3", }, { name: "Mixed values", - input: map[string]interface{}{ + input: map[string]any{ "key1": "value1", "key2": []string{"value2", "value3"}, },