系统列表

Distributed Systems in Go:生产级分布式平台 SDK 与微服务实战

distributed-systems-in-goGo架构: Platform SDK / Microservices Monorepo·

专栏《分布式 Go 系统工程》配套完整代码实战工程,涵盖并发模型、消息队列适配、Saga 编排、弹性容错与可观测性等生产级模式。

README.mdSYSTEM.mdcmd/auth/main.gocmd/gateway/main.gocmd/orders/main.goconfig/grafana/datasources/datasources.yamlconfig/prometheus.yamlconfig/tempo.yamldeploy/kube/orderflow-infra.yamldocker-compose.ymlgo.modgo.suminternal/auth/handler.gointernal/auth/service.gointernal/domain/events.gointernal/inventory/handler.gointernal/inventory/service.gointernal/notifications/service.gointernal/orders/handler.gointernal/orders/service.gointernal/payment/service.gomigrations/000001_init_schema.up.sqlpkg/platform/auth/auth_test.gopkg/platform/auth/claims.gopkg/platform/auth/jwks.gopkg/platform/auth/middleware.gopkg/platform/auth/password.gopkg/platform/auth/token.gopkg/platform/cli/cli_test.gopkg/platform/cli/health.gopkg/platform/concurrency/context.gopkg/platform/concurrency/shutdown.gopkg/platform/concurrency/shutdown_test.gopkg/platform/concurrency/workerpool.gopkg/platform/concurrency/workerpool_test.gopkg/platform/config/config_test.gopkg/platform/config/loader.gopkg/platform/consistency/consistency_test.gopkg/platform/consistency/idempotency.gopkg/platform/consistency/optimistic.gopkg/platform/consistency/saga.gopkg/platform/ctxutil/context.gopkg/platform/ctxutil/context_test.gopkg/platform/ctxutil/keys.gopkg/platform/database/database_test.gopkg/platform/database/errors.gopkg/platform/database/migrate.gopkg/platform/database/pool.gopkg/platform/database/retry.gopkg/platform/database/tx.gopkg/platform/messaging/fake.gopkg/platform/messaging/fake_test.gopkg/platform/messaging/interfaces.gopkg/platform/messaging/kafka/consumer.gopkg/platform/messaging/kafka/producer.gopkg/platform/messaging/nats/publisher.gopkg/platform/messaging/nats/subscriber.gopkg/platform/messaging/schema.gopkg/platform/middleware/bodyclose.gopkg/platform/middleware/chain.gopkg/platform/middleware/cors.gopkg/platform/middleware/errors.gopkg/platform/middleware/health.gopkg/platform/middleware/logging.gopkg/platform/middleware/middleware_test.gopkg/platform/middleware/recover.gopkg/platform/middleware/requestid.gopkg/platform/middleware/timeout.gopkg/platform/observability/context.gopkg/platform/observability/logger.gopkg/platform/observability/metrics.gopkg/platform/observability/observability_test.gopkg/platform/observability/tracing.gopkg/platform/orchestration/budget.gopkg/platform/orchestration/degrade.gopkg/platform/orchestration/fanout.gopkg/platform/orchestration/orchestration_test.gopkg/platform/resilience/circuit.gopkg/platform/resilience/resilience_test.gopkg/platform/resilience/retry.gotests/live_infra_test.gotests/orderflow_integration_test.go
pkg/platform/database/migrate.go
pkg/platform/database/migrate.go
package database
import (
"context"
"fmt"
"log/slog"
"os"
"path/filepath"
"sort"
"strings"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
// MigrationRunner executes SQL migrations against PostgreSQL.
type MigrationRunner struct {
pool *pgxpool.Pool
}
// NewMigrationRunner creates a MigrationRunner.
func NewMigrationRunner(pool *pgxpool.Pool) *MigrationRunner {
return &MigrationRunner{pool: pool}
}
// Run executes all unapplied `*.up.sql` files from the specified directory in lexicographical order.
func (m *MigrationRunner) Run(ctx context.Context, dir string) error {
// 1. Ensure migrations tracking table exists
initSQL := `
CREATE TABLE IF NOT EXISTS schema_migrations (
version VARCHAR(255) PRIMARY KEY,
applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);`
if _, err := m.pool.Exec(ctx, initSQL); err != nil {
return fmt.Errorf("init schema_migrations table: %w", err)
}
// 2. Query already applied migrations
rows, err := m.pool.Query(ctx, `SELECT version FROM schema_migrations;`)
if err != nil {
return fmt.Errorf("query applied migrations: %w", err)
}
defer rows.Close()
applied := make(map[string]bool)
for rows.Next() {
var v string
if err := rows.Scan(&v); err != nil {
return err
}
applied[v] = true
}
// 3. Scan directory for *.up.sql files
files, err := os.ReadDir(dir)
if err != nil {
return fmt.Errorf("read migration dir: %w", err)
}
var upFiles []string
for _, f := range files {
if !f.IsDir() && strings.HasSuffix(f.Name(), ".up.sql") {
upFiles = append(upFiles, f.Name())
}
}
sort.Strings(upFiles)
// 4. Execute pending migrations in transaction
for _, fileName := range upFiles {
version := strings.TrimSuffix(fileName, ".up.sql")
if applied[version] {
continue
}
filePath := filepath.Join(dir, fileName)
content, err := os.ReadFile(filePath)
if err != nil {
return fmt.Errorf("read migration file %s: %w", fileName, err)
}
slog.InfoContext(ctx, "applying database migration", "version", version)
err = InTransaction(ctx, m.pool, func(tx pgx.Tx) error {
if _, err := tx.Exec(ctx, string(content)); err != nil {
return fmt.Errorf("execute %s: %w", fileName, err)
}
if _, err := tx.Exec(ctx, "INSERT INTO schema_migrations (version) VALUES ($1);", version); err != nil {
return fmt.Errorf("record migration %s: %w", version, err)
}
return nil
})
if err != nil {
return err
}
}
slog.InfoContext(ctx, "database migrations up to date")
return nil
}