Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
# Lib-commons Changelog

## [5.3.0]

- **Changes:**
- **mongo**: Migrated from `go.mongodb.org/mongo-driver` v1 to `go.mongodb.org/mongo-driver/v2` (v2.6.0) in-place across `commons/mongo/`, `commons/outbox/mongo/`, `commons/tenant-manager/core/`, and `commons/tenant-manager/mongo/`. Public function signatures are unchanged, but the concrete `*mongo.Database`/`*mongo.Client` types now resolve to v2. Consumers updating to v5.3.0 must adapt their own MongoDB query code for the following v2 API changes:
- `options.UpdateOne()`, `options.Find()`, and `options.Index()` now return builder types (`*XxxOptionsBuilder`). Fluent `.SetX()` chains are unchanged.
- `primitive.ObjectID` → `bson.ObjectID`, `primitive.DateTime` → `bson.DateTime`, `primitive.NewObjectID()` → `bson.NewObjectID()` (the `primitive` package was merged into `bson` in v2).
- `mongo.Connect` no longer accepts a `context.Context` parameter **and no longer pings the server to validate reachability**. If you relied on `Connect` to fail on unreachable deployments, call `client.Ping(ctx, nil)` explicitly after connecting.
- `Collection.Distinct` returns `*DistinctResult` instead of `([]any, error)` — use `result.Err()` followed by `result.Decode(&values)`.
- `WithTransaction` callbacks receive `context.Context` instead of `mongo.SessionContext`. Use `mongo.SessionFromContext(ctx)` if you need the session.

## [5.2.0](https://github.com/LerianStudio/lib-commons/releases/tag/v5.2.0)

- **Features:**
Expand Down
10 changes: 5 additions & 5 deletions commons/mongo/mongo.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ import (
"github.com/LerianStudio/lib-observability/log"
"github.com/LerianStudio/lib-observability/metrics"
libOpentelemetry "github.com/LerianStudio/lib-observability/tracing"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
)
Expand Down Expand Up @@ -143,8 +143,8 @@ type clientDeps struct {

func defaultDeps() clientDeps {
return clientDeps{
connect: func(ctx context.Context, clientOptions *options.ClientOptions) (*mongo.Client, error) {
return mongo.Connect(ctx, clientOptions)
connect: func(_ context.Context, clientOptions *options.ClientOptions) (*mongo.Client, error) {
return mongo.Connect(clientOptions)
},
ping: func(ctx context.Context, client *mongo.Client) error {
return client.Ping(ctx, nil)
Expand Down
4 changes: 2 additions & 2 deletions commons/mongo/mongo_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ import (
"github.com/testcontainers/testcontainers-go"
tcmongo "github.com/testcontainers/testcontainers-go/modules/mongodb"
"github.com/testcontainers/testcontainers-go/wait"
"go.mongodb.org/mongo-driver/bson"
mongodriver "go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/v2/bson"
mongodriver "go.mongodb.org/mongo-driver/v2/mongo"
)

const (
Expand Down
6 changes: 3 additions & 3 deletions commons/mongo/mongo_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@ import (
"github.com/LerianStudio/lib-observability/log"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)

// ---------------------------------------------------------------------------
Expand Down
6 changes: 3 additions & 3 deletions commons/outbox/mongo/claim.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ import (
"github.com/LerianStudio/lib-commons/v5/commons/outbox"
libOpentelemetry "github.com/LerianStudio/lib-observability/tracing"
"github.com/google/uuid"
"go.mongodb.org/mongo-driver/bson"
mongodriver "go.mongodb.org/mongo-driver/mongo"
mongooptions "go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/v2/bson"
mongodriver "go.mongodb.org/mongo-driver/v2/mongo"
mongooptions "go.mongodb.org/mongo-driver/v2/mongo/options"
)

func (repo *Repository) claimPending(ctx context.Context, limit int, eventType string, spanName string) ([]*outbox.OutboxEvent, error) {
Expand Down
7 changes: 3 additions & 4 deletions commons/outbox/mongo/coverage_boost_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@ import (
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/v2/bson"
)

// -------------------------------------------------------------------
Expand Down Expand Up @@ -131,7 +130,7 @@ func TestTimeField_PrimitiveDateTime(t *testing.T) {
t.Parallel()

now := time.Now().UTC().Truncate(time.Millisecond)
raw := bson.M{"ts": primitive.NewDateTimeFromTime(now)}
raw := bson.M{"ts": bson.NewDateTimeFromTime(now)}
val, err := timeField(raw, "ts")
require.NoError(t, err)
assert.WithinDuration(t, now, val, time.Millisecond)
Expand Down Expand Up @@ -183,7 +182,7 @@ func TestOptionalTimeField_PrimitiveDateTime(t *testing.T) {
t.Parallel()

now := time.Now().UTC().Truncate(time.Millisecond)
raw := bson.M{"ts": primitive.NewDateTimeFromTime(now)}
raw := bson.M{"ts": bson.NewDateTimeFromTime(now)}
val, err := optionalTimeField(raw, "ts")
require.NoError(t, err)
require.NotNil(t, val)
Expand Down
9 changes: 4 additions & 5 deletions commons/outbox/mongo/document.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,8 @@ import (

"github.com/LerianStudio/lib-commons/v5/commons/outbox"
"github.com/google/uuid"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
mongodriver "go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/v2/bson"
mongodriver "go.mongodb.org/mongo-driver/v2/mongo"
)

func (doc document) toBSON(tenantField string) bson.M {
Expand Down Expand Up @@ -418,7 +417,7 @@ func timeField(raw bson.M, key string) (time.Time, error) {
switch typed := value.(type) {
case time.Time:
return typed, nil
case primitive.DateTime:
case bson.DateTime:
return typed.Time(), nil
default:
return time.Time{}, fmt.Errorf("field %q must be time", key)
Expand All @@ -434,7 +433,7 @@ func optionalTimeField(raw bson.M, key string) (*time.Time, error) {
switch typed := value.(type) {
case time.Time:
return &typed, nil
case primitive.DateTime:
case bson.DateTime:
timeValue := typed.Time()
return &timeValue, nil
default:
Expand Down
2 changes: 1 addition & 1 deletion commons/outbox/mongo/extra_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
libMongo "github.com/LerianStudio/lib-commons/v5/commons/mongo"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/v2/bson"
)

// TestWithLogger covers the WithLogger option.
Expand Down
2 changes: 1 addition & 1 deletion commons/outbox/mongo/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"maps"
"regexp"

"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/v2/bson"
)

var mongoIdentifierPattern = regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_]*$`)
Expand Down
6 changes: 3 additions & 3 deletions commons/outbox/mongo/indexes.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package mongo

import (
"go.mongodb.org/mongo-driver/bson"
mongodriver "go.mongodb.org/mongo-driver/mongo"
mongooptions "go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/v2/bson"
mongodriver "go.mongodb.org/mongo-driver/v2/mongo"
mongooptions "go.mongodb.org/mongo-driver/v2/mongo/options"
)

func buildIndexes(tenantField string) []mongodriver.IndexModel {
Expand Down
2 changes: 1 addition & 1 deletion commons/outbox/mongo/pure_functions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/v2/bson"
)

// ---------------------------------------------------------------------------
Expand Down
15 changes: 11 additions & 4 deletions commons/outbox/mongo/repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ import (
libLog "github.com/LerianStudio/lib-observability/log"
libOpentelemetry "github.com/LerianStudio/lib-observability/tracing"
"github.com/google/uuid"
"go.mongodb.org/mongo-driver/bson"
mongodriver "go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/v2/bson"
mongodriver "go.mongodb.org/mongo-driver/v2/mongo"
"go.opentelemetry.io/otel/trace"
"go.opentelemetry.io/otel/trace/noop"
)
Expand Down Expand Up @@ -345,16 +345,23 @@ func (repo *Repository) ListTenants(ctx context.Context) ([]string, error) {
return nil, err
}

values, err := collection.Distinct(ctx, repo.tenantField, bson.M{
distinctResult := collection.Distinct(ctx, repo.tenantField, bson.M{
mongoFieldStatus: bson.M{"$in": bson.A{outbox.OutboxStatusPending, outbox.OutboxStatusFailed, outbox.OutboxStatusProcessing}},
repo.tenantField: bson.M{"$ne": defaultScopeTenantID},
})
if err != nil {
if err := distinctResult.Err(); err != nil {
libOpentelemetry.HandleSpanError(span, "failed to list tenants", err)

return nil, fmt.Errorf("listing tenants: %w", err)
}

var values []any
if err := distinctResult.Decode(&values); err != nil {
libOpentelemetry.HandleSpanError(span, "failed to decode tenants", err)

return nil, fmt.Errorf("listing tenants: %w", err)
}

tenants := make([]string, 0, len(values))
for _, value := range values {
tenantID, ok := value.(string)
Expand Down
12 changes: 6 additions & 6 deletions commons/outbox/mongo/repository_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ import (
"github.com/testcontainers/testcontainers-go"
tcmongo "github.com/testcontainers/testcontainers-go/modules/mongodb"
"github.com/testcontainers/testcontainers-go/wait"
"go.mongodb.org/mongo-driver/bson"
mongodriver "go.mongodb.org/mongo-driver/mongo"
mongooptions "go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/v2/bson"
mongodriver "go.mongodb.org/mongo-driver/v2/mongo"
mongooptions "go.mongodb.org/mongo-driver/v2/mongo/options"
"go.opentelemetry.io/otel/trace/noop"
)

Expand Down Expand Up @@ -115,7 +115,7 @@ func waitForMongoPrimary(t *testing.T, uri string) {

for time.Now().Before(deadline) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
client, err := mongodriver.Connect(ctx, mongooptions.Client().ApplyURI(uri))
client, err := mongodriver.Connect(mongooptions.Client().ApplyURI(uri))
if err == nil {
err = client.Ping(ctx, nil)
}
Expand Down Expand Up @@ -294,7 +294,7 @@ func TestIntegration_Repository_CreateJoinsMongoTransactionContext(t *testing.T)

tenantCtx := outbox.ContextWithTenantID(suite.ctx, "tenant-a")
var committedID uuid.UUID
_, err = commitSession.WithTransaction(tenantCtx, func(sessionCtx mongodriver.SessionContext) (any, error) {
_, err = commitSession.WithTransaction(tenantCtx, func(sessionCtx context.Context) (any, error) {
event, eventErr := outbox.NewOutboxEvent(sessionCtx, "payment.tx.commit", uuid.New(), []byte(`{"ok":true}`))
if eventErr != nil {
return nil, eventErr
Expand Down Expand Up @@ -322,7 +322,7 @@ func TestIntegration_Repository_CreateJoinsMongoTransactionContext(t *testing.T)

var rolledBackID uuid.UUID
rollbackErr := errors.New("rollback sentinel")
_, err = rollbackSession.WithTransaction(tenantCtx, func(sessionCtx mongodriver.SessionContext) (any, error) {
_, err = rollbackSession.WithTransaction(tenantCtx, func(sessionCtx context.Context) (any, error) {
event, eventErr := outbox.NewOutboxEvent(sessionCtx, "payment.tx.rollback", uuid.New(), []byte(`{"ok":true}`))
if eventErr != nil {
return nil, eventErr
Expand Down
2 changes: 1 addition & 1 deletion commons/outbox/mongo/repository_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (
tmcore "github.com/LerianStudio/lib-commons/v5/commons/tenant-manager/core"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/v2/bson"
)

func TestNewRepository_Validation(t *testing.T) {
Expand Down
2 changes: 1 addition & 1 deletion commons/tenant-manager/core/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"context"

"github.com/bxcodec/dbresolver/v2"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/v2/mongo"
)

// nonNilContext returns ctx if non-nil, otherwise context.Background().
Expand Down
2 changes: 1 addition & 1 deletion commons/tenant-manager/core/context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (

"github.com/bxcodec/dbresolver/v2"
"github.com/stretchr/testify/assert"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/v2/mongo"
)

func TestContextWithTenantID(t *testing.T) {
Expand Down
13 changes: 10 additions & 3 deletions commons/tenant-manager/mongo/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@
observability "github.com/LerianStudio/lib-observability"
"github.com/LerianStudio/lib-observability/log"
libOpentelemetry "github.com/LerianStudio/lib-observability/tracing"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
"go.opentelemetry.io/otel/trace"
)

Expand Down Expand Up @@ -153,11 +153,18 @@

clientOptions.SetTLSConfig(c.tlsConfig)

mongoClient, err := mongo.Connect(ctx, clientOptions)
mongoClient, err := mongo.Connect(clientOptions)
if err != nil {
return fmt.Errorf("mongo connect with TLS failed: %w", err)
}

if err := mongoClient.Ping(ctx, nil); err != nil {
disconnectCtx, disconnectCancel := context.WithTimeout(context.Background(), mongoPingTimeout)
_ = mongoClient.Disconnect(disconnectCtx)
disconnectCancel()

Check failure on line 164 in commons/tenant-manager/mongo/manager.go

View workflow job for this annotation

GitHub Actions / Go Analysis / Lint (app)

missing whitespace above this line (no shared variables above expr) (wsl_v5)

Check failure on line 164 in commons/tenant-manager/mongo/manager.go

View workflow job for this annotation

GitHub Actions / Go Analysis / Lint (app)

missing whitespace above this line (no shared variables above expr) (wsl_v5)
return fmt.Errorf("mongo connect with TLS failed: %w", err)

Check failure on line 165 in commons/tenant-manager/mongo/manager.go

View workflow job for this annotation

GitHub Actions / Go Analysis / Lint (app)

missing whitespace above this line (too many lines above return) (wsl_v5)

Check failure on line 165 in commons/tenant-manager/mongo/manager.go

View workflow job for this annotation

GitHub Actions / Go Analysis / Lint (app)

missing whitespace above this line (too many lines above return) (wsl_v5)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
}

c.DB = mongoClient

return nil
Expand Down
15 changes: 10 additions & 5 deletions commons/tenant-manager/mongo/manager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ import (
"github.com/LerianStudio/lib-commons/v5/commons/tenant-manager/internal/testutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
"go.uber.org/goleak"
)

Expand All @@ -41,6 +41,11 @@ func TestMain(m *testing.M) {
goleak.IgnoreTopFunction("internal/poll.runtime_pollWait"),
goleak.IgnoreTopFunction("net/http.(*persistConn).writeLoop"),
goleak.IgnoreTopFunction("net/http.(*persistConn).readLoop"),
// v2 driver spawns topology goroutines that wind down asynchronously
// after Disconnect; ignore the known shutdown/monitor stacks.
goleak.IgnoreAnyFunction("go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology.(*Server).Disconnect"),
goleak.IgnoreAnyFunction("go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology.(*rttMonitor).runHellos"),
goleak.IgnoreAnyFunction("go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology.(*contextDoneListener).Listen"),
)
}

Expand All @@ -66,9 +71,9 @@ func startFakeMongoServer(t *testing.T) (*mongo.Client, func()) {

addr := ln.Addr().String()

mongoClient, err := mongo.Connect(ctx, options.Client().
mongoClient, err := mongo.Connect(options.Client().
ApplyURI(fmt.Sprintf("mongodb://%s/?directConnection=true", addr)).
SetServerSelectionTimeout(2*time.Second))
SetServerSelectionTimeout(2 * time.Second))
require.NoError(t, err)

require.NoError(t, mongoClient.Ping(ctx, nil))
Expand Down
5 changes: 1 addition & 4 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ require (
github.com/testcontainers/testcontainers-go/modules/postgres v0.42.0
github.com/testcontainers/testcontainers-go/modules/rabbitmq v0.42.0
github.com/testcontainers/testcontainers-go/modules/redis v0.42.0
go.mongodb.org/mongo-driver v1.17.9
go.mongodb.org/mongo-driver/v2 v2.6.0
go.opentelemetry.io/otel v1.43.0
go.opentelemetry.io/otel/metric v1.43.0
go.opentelemetry.io/otel/sdk v1.43.0
Expand Down Expand Up @@ -77,7 +77,6 @@ require (
github.com/go-ole/go-ole v1.3.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/golang/snappy v1.0.0 // indirect
github.com/google/s2a-go v0.1.9 // indirect
github.com/googleapis/enterprise-certificate-proxy v0.3.15 // indirect
github.com/googleapis/gax-go/v2 v2.22.0 // indirect
Expand Down Expand Up @@ -105,7 +104,6 @@ require (
github.com/moby/sys/user v0.4.0 // indirect
github.com/moby/sys/userns v0.1.0 // indirect
github.com/moby/term v0.5.2 // indirect
github.com/montanaflynn/stats v0.9.0 // indirect
github.com/opencontainers/go-digest v1.0.0 // indirect
github.com/opencontainers/image-spec v1.1.1 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
Expand All @@ -122,7 +120,6 @@ require (
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect
github.com/yuin/gopher-lua v1.1.2 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
go.mongodb.org/mongo-driver/v2 v2.6.0 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.68.0 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0 // indirect
Expand Down
Loading
Loading