diff --git a/README.md b/README.md index fe7a2dd..3c048db 100644 --- a/README.md +++ b/README.md @@ -97,11 +97,14 @@ multipart_threshold: 52428800 # 50 MiB multipart_part_size: 16777216 # 16 MiB (allowed: 5 MiB..5 GiB) multipart_concurrency: 4 # Parallel parts per large object (1..64; product <= 4096) rate_limit: 0 # Aggregate source-read cap (e.g. 20M or 20MiB; 0 = unlimited) +list_max_keys: 100 # ListObjectsV2 page size (1..1000; 0/omitted = 100) +response_header_timeout: "60s" # HTTP response-header timeout (0/omitted = 60s, max 1h) +max_attempts: 5 # Per-request S3 attempt budget (1..100; 0/omitted = 5) ``` - **Strict parsing**: Unknown YAML keys and multi-document YAML files fail fast at startup. Endpoint URLs must be plain `http://` or `https://` URLs without embedded credentials, query strings, or `#` fragments. - **Precedence**: `CLI flags > Environment variables > YAML > Built-in defaults`. -- **Environment variables**: `OLD_ENDPOINT`, `OLD_AK`, `OLD_SK`, `OLD_REGION`, `OLD_SESSION_TOKEN`, `NEW_ENDPOINT`, `NEW_AK`, `NEW_SK`, `NEW_REGION`, `NEW_SESSION_TOKEN`, `REGION`, `BUCKET`, `DB_PATH`, `CONFLICT_LOG`, `SPOOL_DIR`, `WORKERS`, `MULTIPART_CONCURRENCY`, `RATE_LIMIT`, `SOURCE_FROZEN`. +- **Environment variables**: `OLD_ENDPOINT`, `OLD_AK`, `OLD_SK`, `OLD_REGION`, `OLD_SESSION_TOKEN`, `NEW_ENDPOINT`, `NEW_AK`, `NEW_SK`, `NEW_REGION`, `NEW_SESSION_TOKEN`, `REGION`, `BUCKET`, `DB_PATH`, `CONFLICT_LOG`, `SPOOL_DIR`, `WORKERS`, `MULTIPART_CONCURRENCY`, `RATE_LIMIT`, `LIST_MAX_KEYS`, `RESPONSE_HEADER_TIMEOUT`, `MAX_ATTEMPTS` (or `AWS_MAX_ATTEMPTS`), `SOURCE_FROZEN`, `AWS_CA_BUNDLE`. See the [User Manual](docs/MANUAL.md) for detailed `0`-value rules, unit conversions (`20M` decimal vs `20MiB` binary), and disk/bandwidth sizing. diff --git a/README_ZH.md b/README_ZH.md index 90d47bc..492310d 100644 --- a/README_ZH.md +++ b/README_ZH.md @@ -97,11 +97,14 @@ multipart_threshold: 52428800 # 分片阈值(默认 50 MiB) multipart_part_size: 16777216 # 分片大小(默认 16 MiB,范围 5 MiB ~ 5 GiB) multipart_concurrency: 4 # 单对象分片并发(1~64;与 workers 乘积 <= 4096) rate_limit: 0 # 源端读取总带宽上限(如 20M、20MiB;0 = 不限速) +list_max_keys: 100 # ListObjectsV2 每页条数上限(1~1000;0 或省略取 100) +response_header_timeout: "60s" # 等待 HTTP 响应头超时(0 或省略取 60s,上限 1h) +max_attempts: 5 # 单次 S3 请求最大尝试次数(1~100;0 或省略取 5) ``` - **严格校验**:配置包含未知字段或多份 YAML 文档会立即报错退出;端点 URL 仅接受纯 `http://` 或 `https://`,不可带账密、查询参数或 `#` 锚点。 - **生效优先级**:`命令行参数 > 环境变量 > YAML 配置 > 内置默认值`。 -- **环境变量**:`OLD_ENDPOINT`、`OLD_AK`、`OLD_SK`、`OLD_REGION`、`OLD_SESSION_TOKEN`、`NEW_ENDPOINT`、`NEW_AK`、`NEW_SK`、`NEW_REGION`、`NEW_SESSION_TOKEN`、`REGION`、`BUCKET`、`DB_PATH`、`CONFLICT_LOG`、`SPOOL_DIR`、`WORKERS`、`MULTIPART_CONCURRENCY`、`RATE_LIMIT`、`SOURCE_FROZEN`。 +- **环境变量**:`OLD_ENDPOINT`、`OLD_AK`、`OLD_SK`、`OLD_REGION`、`OLD_SESSION_TOKEN`、`NEW_ENDPOINT`、`NEW_AK`、`NEW_SK`、`NEW_REGION`、`NEW_SESSION_TOKEN`、`REGION`、`BUCKET`、`DB_PATH`、`CONFLICT_LOG`、`SPOOL_DIR`、`WORKERS`、`MULTIPART_CONCURRENCY`、`RATE_LIMIT`、`LIST_MAX_KEYS`、`RESPONSE_HEADER_TIMEOUT`、`MAX_ATTEMPTS`(兼容 `AWS_MAX_ATTEMPTS`)、`SOURCE_FROZEN`、`AWS_CA_BUNDLE`。 关于 `0` 值在不同层级的含义、十进制 `MB` 与二进制 `MiB` 换算、磁盘预算和排障说明,请阅读 [完整中文使用手册](docs/MANUAL_ZH.md)。 diff --git a/cmd/cli_regression_test.go b/cmd/cli_regression_test.go index 3bdb6e2..8242e23 100644 --- a/cmd/cli_regression_test.go +++ b/cmd/cli_regression_test.go @@ -304,3 +304,139 @@ func TestDiffCLIExportsIssuesJSONLWithoutOverwriting(t *testing.T) { t.Fatalf("report overwritten: %v", err) } } + +func TestCLIScanRunAndDiffPaginateAndRecoverFromSlowListing(t *testing.T) { + lm := time.Date(2026, 12, 1, 2, 45, 0, 0, time.UTC) + oldBackend := fakes3.New(t) + defer oldBackend.Close() + for _, bkt := range []string{"dossier", "thunisoft", "writ"} { + for i := 0; i < 5; i++ { + key := "11/方案/" + bkt + "-" + string(rune('a'+i)) + ".docx" + oldBackend.Put(bkt, key, []byte(bkt+"-"+key), lm, fakes3.Metadata{ContentType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"}) + } + } + + var listCalls atomic.Int32 + var stallWritPage2 atomic.Int32 + var badMaxKeys atomic.Bool + oldSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet && r.URL.Query().Get("list-type") == "2" { + listCalls.Add(1) + if r.URL.Query().Get("max-keys") != "2" { + badMaxKeys.Store(true) + } + // On bucket "writ" continuation page, stall the first 2 attempts past + // the 100ms response-header timeout, then succeed on attempt 3. + if strings.HasPrefix(r.URL.Path, "/writ") && r.URL.Query().Get("continuation-token") != "" { + if stallWritPage2.Add(1) <= 2 { + select { + case <-time.After(300 * time.Millisecond): + case <-r.Context().Done(): + return + } + } + } + } + oldBackend.Config.Handler.ServeHTTP(w, r) + })) + defer oldSrv.Close() + + newS3 := fakes3.New(t) + defer newS3.Close() + + dir := t.TempDir() + cfgPath := filepath.Join(dir, "config.yaml") + writeClusterConfig(t, cfgPath, oldSrv.URL, newS3.URL, filepath.Join(dir, "migration.db"), filepath.Join(dir, "conflict.log"), dir, ` +workers: 2 +multipart_concurrency: 1 +`) + + out, err := execRoot(t, + "run", "-c", cfgPath, + "--strict", + "--list-max-keys", "2", + "--response-header-timeout", "100ms", + "--max-attempts", "4", + ) + if err != nil { + t.Fatalf("run with paginated listing and transient header timeouts failed: %v\n%s", err, out) + } + if badMaxKeys.Load() { + t.Fatal("expected every ListObjectsV2 request to carry max-keys=2") + } + if stallWritPage2.Load() < 3 { + t.Fatalf("expected writ continuation page to retry after header timeout, attempts=%d", stallWritPage2.Load()) + } + // 3 buckets * 3 pages (2+2+1) + 2 retried stalls = at least 11 list calls. + if listCalls.Load() < 11 { + t.Fatalf("expected paginated list calls >= 11, got %d", listCalls.Load()) + } + + diffOut, err := execRootStdout(t, + "diff", "-c", cfgPath, + "--strict", + "--list-max-keys", "2", + ) + if err != nil { + t.Fatalf("diff --strict failed: %v\n%s", err, diffOut) + } + if got := strings.Count(diffOut, "ok=5"); got != 3 { + t.Fatalf("expected all 3 buckets to verify ok=5, got %d:\n%s", got, diffOut) + } +} + +func TestCLIDefaultListPageSizeIs100WithoutFlags(t *testing.T) { + lm := time.Date(2026, 12, 1, 3, 0, 0, 0, time.UTC) + oldBackend := fakes3.New(t) + defer oldBackend.Close() + for i := 0; i < 250; i++ { + key := "writ/item-" + string([]byte{ + byte('0' + (i/100)%10), + byte('0' + (i/10)%10), + byte('0' + i%10), + }) + ".docx" + oldBackend.Put("writ", key, []byte(key), lm, fakes3.Metadata{ContentType: "application/octet-stream"}) + } + + var listPages atomic.Int32 + var badMaxKeys atomic.Bool + oldSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet && r.URL.Query().Get("list-type") == "2" { + listPages.Add(1) + if r.URL.Query().Get("max-keys") != "100" { + badMaxKeys.Store(true) + } + } + oldBackend.Config.Handler.ServeHTTP(w, r) + })) + defer oldSrv.Close() + + newS3 := fakes3.New(t) + defer newS3.Close() + + dir := t.TempDir() + cfgPath := filepath.Join(dir, "config.yaml") + writeClusterConfig(t, cfgPath, oldSrv.URL, newS3.URL, filepath.Join(dir, "migration.db"), filepath.Join(dir, "conflict.log"), dir, ` +bucket: writ +workers: 8 +`) + + if out, err := execRoot(t, "run", "-c", cfgPath, "--strict"); err != nil { + t.Fatalf("default run failed: %v\n%s", err, out) + } + if badMaxKeys.Load() { + t.Fatal("default scan/run did not send max-keys=100 on every ListObjectsV2 request") + } + if got := listPages.Load(); got != 3 { + t.Fatalf("expected 3 pages (100+100+50) for 250 objects during scan, got %d", got) + } + + listPages.Store(0) + diffOut, err := execRootStdout(t, "diff", "-c", cfgPath, "--strict") + if err != nil { + t.Fatalf("default diff failed: %v\n%s", err, diffOut) + } + if badMaxKeys.Load() || listPages.Load() != 3 || !strings.Contains(diffOut, "ok=250") { + t.Fatalf("default diff unexpected state: badMaxKeys=%v pages=%d\n%s", badMaxKeys.Load(), listPages.Load(), diffOut) + } +} diff --git a/cmd/help_test.go b/cmd/help_test.go index c339869..49576a3 100644 --- a/cmd/help_test.go +++ b/cmd/help_test.go @@ -30,6 +30,12 @@ func TestRootHelpBilingual(t *testing.T) { "--workers", "--multipart-concurrency", "--rate-limit", + "--list-max-keys", + "--response-header-timeout", + "--max-attempts", + "LIST_MAX_KEYS", + "RESPONSE_HEADER_TIMEOUT", + "MAX_ATTEMPTS", "RATE_LIMIT", "20M", "20MiB", diff --git a/cmd/helptext.go b/cmd/helptext.go index 20ff386..0dbf5d6 100644 --- a/cmd/helptext.go +++ b/cmd/helptext.go @@ -147,12 +147,19 @@ Concurrency / 并发: --multipart-concurrency N parts in parallel inside one large object (default 4) 单个大对象的分片并发,默认 4 Scan is single-threaded / 扫描(scan)始终单线程,不受 --workers 影响 -Bandwidth / 带宽: + Bandwidth / 带宽: --rate-limit SIZE shared source-read cap for run/migrate (default unlimited) run/migrate 从源读取的合计上限,默认不限速 20M/30M/50M = decimal MB/s (×1000×1000) 20MiB = binary MiB/s (×1024×1024); 0 = unlimited 20M 是十进制 MB/s;20MiB 才是 1024 进制;0 = 不限速 + Timeouts & Listing / 超时与列举: + --list-max-keys N ListObjectsV2 page size (1..1000, default 100) + ListObjectsV2 每页条数上限(1..1000,默认 100) + --response-header-timeout D HTTP response-header timeout (default 60s, e.g. 2m, 5m) + 等待 HTTP 响应头超时(默认 60s,慢盘可调大如 2m、5m) + --max-attempts N max S3 attempts per request (1..100, default 5) + 单次 S3 请求最大尝试次数(1..100,默认 5) Priority / 优先级: CLI > env > YAML > default 命令行 > 环境变量 > 配置文件 > 默认值 Env overrides / 环境变量覆盖: @@ -160,4 +167,5 @@ Env overrides / 环境变量覆盖: NEW_ENDPOINT NEW_AK NEW_SK NEW_REGION BUCKET DB_PATH CONFLICT_LOG SPOOL_DIR REGION WORKERS MULTIPART_CONCURRENCY RATE_LIMIT SOURCE_FROZEN + LIST_MAX_KEYS RESPONSE_HEADER_TIMEOUT MAX_ATTEMPTS AWS_MAX_ATTEMPTS OLD_SESSION_TOKEN NEW_SESSION_TOKEN` diff --git a/cmd/root.go b/cmd/root.go index a2f5dfe..041ee2b 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -46,6 +46,9 @@ func NewRoot() *cobra.Command { root.PersistentFlags().Int("workers", 0, "concurrent objects for run/migrate/diff, overrides YAML (must be >= 1) / 对象并发数,覆盖配置,须 >= 1") root.PersistentFlags().Int("multipart-concurrency", 0, "parallel parts per large object, overrides YAML (must be >= 1) / 单个大对象的分片并发,覆盖配置,须 >= 1") root.PersistentFlags().String("rate-limit", "", "aggregate source-read cap for run/migrate, e.g. 20M or 20MiB; 0 = unlimited / 所有 worker 从源读取的合计上限,例如 20M 或 20MiB;0 表示不限速") + root.PersistentFlags().Int("list-max-keys", 0, "ListObjectsV2 page size for scan/run/diff (1..1000, default 100) / 列举每页最大对象数(1..1000,默认 100)") + root.PersistentFlags().String("response-header-timeout", "", "HTTP response-header timeout (e.g. 60s, 5m; default 60s) / 等待 HTTP 响应头超时(如 60s、5m,默认 60s)") + root.PersistentFlags().Int("max-attempts", 0, "max S3 attempts per request (1..100, default 5) / 每次 S3 请求最大尝试次数(1..100,默认 5)") root.PersistentFlags().Bool("source-frozen", false, "confirm source writes and deletes are externally frozen for run/migrate / 确认来源的写入和删除已在外部冻结") root.CompletionOptions.DisableDefaultCmd = true @@ -96,15 +99,24 @@ func loadConfig(cmd *cobra.Command) (*config.Config, error) { workersFlag, _ := flags.GetInt("workers") multipartConcFlag, _ := flags.GetInt("multipart-concurrency") rateLimitFlag, _ := flags.GetString("rate-limit") + listMaxKeysFlag, _ := flags.GetInt("list-max-keys") + headerTimeoutFlag, _ := flags.GetString("response-header-timeout") + maxAttemptsFlag, _ := flags.GetInt("max-attempts") workersSet := flags.Changed("workers") multipartSet := flags.Changed("multipart-concurrency") rateLimitSet := flags.Changed("rate-limit") + listMaxKeysSet := flags.Changed("list-max-keys") + headerTimeoutSet := flags.Changed("response-header-timeout") + maxAttemptsSet := flags.Changed("max-attempts") sourceFrozenSet := flags.Changed("source-frozen") cfg, err := config.LoadForCLI(cfgPath, config.CLIReadOptions{ - SkipWorkersEnv: workersSet, - SkipMultipartConcurrencyEnv: multipartSet, - SkipRateLimitEnv: rateLimitSet, - SkipSourceFrozenEnv: sourceFrozenSet, + SkipWorkersEnv: workersSet, + SkipMultipartConcurrencyEnv: multipartSet, + SkipRateLimitEnv: rateLimitSet, + SkipSourceFrozenEnv: sourceFrozenSet, + SkipListMaxKeysEnv: listMaxKeysSet, + SkipResponseHeaderTimeoutEnv: headerTimeoutSet, + SkipMaxAttemptsEnv: maxAttemptsSet, }) if err != nil { return nil, err @@ -127,12 +139,27 @@ func loadConfig(cmd *cobra.Command) (*config.Config, error) { if err := cfg.ApplyRateLimitOverride(rateLimitFlag, rateLimitSet); err != nil { return nil, err } + if err := cfg.ApplyTransportOverrides( + listMaxKeysFlag, listMaxKeysSet, + headerTimeoutFlag, headerTimeoutSet, + maxAttemptsFlag, maxAttemptsSet, + ); err != nil { + return nil, err + } if sourceFrozenSet { cfg.SourceFrozen, _ = flags.GetBool("source-frozen") } return cfg, nil } +func clientOptions(cfg *config.Config, idlePerHost int) s3client.ClientOptions { + return s3client.ClientOptions{ + IdlePerHost: idlePerHost, + ResponseHeaderTimeout: cfg.ResponseHeaderTimeout.Duration(), + MaxAttempts: cfg.MaxAttempts, + } +} + func listCmd() *cobra.Command { return &cobra.Command{ Use: "list", @@ -149,7 +176,7 @@ func listCmd() *cobra.Command { } ctx, cancel := signalCtx(cmd.Context()) defer cancel() - oldCli, err := s3client.NewWithPool(ctx, cfg.Old, cfg.MaxInFlight()) + oldCli, err := s3client.NewWithOptions(ctx, cfg.Old, clientOptions(cfg, cfg.MaxInFlight())) if err != nil { return err } @@ -211,7 +238,7 @@ func scanCmd() *cobra.Command { } ctx, cancel := signalCtx(cmd.Context()) defer cancel() - oldCli, err := s3client.NewWithPool(ctx, cfg.Old, cfg.MaxInFlight()) + oldCli, err := s3client.NewWithOptions(ctx, cfg.Old, clientOptions(cfg, cfg.MaxInFlight())) if err != nil { return err } @@ -294,11 +321,11 @@ func runDiffBuckets(cmd *cobra.Command, diffExtra, strict bool, jsonlPath string ctx, cancel := signalCtx(cmd.Context()) defer cancel() pool := cfg.MaxInFlight() - oldCli, err := s3client.NewWithPool(ctx, cfg.Old, pool) + oldCli, err := s3client.NewWithOptions(ctx, cfg.Old, clientOptions(cfg, pool)) if err != nil { return err } - newCli, err := s3client.NewWithPool(ctx, cfg.New, pool) + newCli, err := s3client.NewWithOptions(ctx, cfg.New, clientOptions(cfg, pool)) if err != nil { return err } @@ -337,6 +364,7 @@ func runDiffBuckets(cmd *cobra.Command, diffExtra, strict bool, jsonlPath string } res, err := differ.Run(ctx, oldCli, newCli, name, differ.Options{ Workers: cfg.Workers, + ListMaxKeys: cfg.ListMaxKeys, ReportExtra: reportExtra, TempDir: cfg.SpoolDir, Writer: os.Stdout, @@ -360,6 +388,7 @@ func runDiffBuckets(cmd *cobra.Command, diffExtra, strict bool, jsonlPath string } res, err := differ.RunExtraBucket(ctx, newCli, name, differ.Options{ Workers: cfg.Workers, + ListMaxKeys: cfg.ListMaxKeys, ReportExtra: true, TempDir: cfg.SpoolDir, Writer: os.Stdout, @@ -461,13 +490,13 @@ func forEachBucket(cmd *cobra.Command, needTarget bool, fn func(ctx context.Cont ctx, cancel := signalCtx(cmd.Context()) defer cancel() pool := cfg.MaxInFlight() - oldCli, err := s3client.NewWithPool(ctx, cfg.Old, pool) + oldCli, err := s3client.NewWithOptions(ctx, cfg.Old, clientOptions(cfg, pool)) if err != nil { return err } var newCli *s3.Client if needTarget { - newCli, err = s3client.NewWithPool(ctx, cfg.New, pool) + newCli, err = s3client.NewWithOptions(ctx, cfg.New, clientOptions(cfg, pool)) if err != nil { return err } @@ -523,8 +552,8 @@ func scanOne(ctx context.Context, cfg *config.Config, oldCli *s3.Client, bucket if err := st.BindMigration(cfg.Old.Endpoint, cfg.New.Endpoint); err != nil { return err } - log.Printf("scan: bucket=%s db=%s (single-threaded list; --workers applies to copy and diff)", bucket, cfg.DBPathFor(bucket)) - _, err = scanner.Run(ctx, oldCli, bucket, st) + log.Printf("scan: bucket=%s db=%s list_max_keys=%d (single-threaded list; --workers applies to copy and diff)", bucket, cfg.DBPathFor(bucket), cfg.ListMaxKeys) + _, err = scanner.RunWithOptions(ctx, oldCli, bucket, st, scanner.Options{ListMaxKeys: cfg.ListMaxKeys}) return err } diff --git a/config.example.yaml b/config.example.yaml index d409517..d0a1035 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -9,6 +9,7 @@ # NEW_ENDPOINT NEW_AK NEW_SK NEW_REGION NEW_SESSION_TOKEN REGION # BUCKET DB_PATH CONFLICT_LOG SPOOL_DIR # WORKERS MULTIPART_CONCURRENCY RATE_LIMIT SOURCE_FROZEN +# LIST_MAX_KEYS RESPONSE_HEADER_TIMEOUT MAX_ATTEMPTS AWS_MAX_ATTEMPTS old: endpoint: "http://10.0.0.1:9000" # source / 来源(只读) @@ -77,6 +78,20 @@ multipart_concurrency: 4 # 生产时段示例:rate_limit: 20M 。确认不影响业务后再调到 30M 或 50M。 rate_limit: 0 +# ListObjectsV2 每页条数上限(1..1000;省略或 0 = 默认 100)。 +# 默认 100 兼顾机械硬盘(HDD)海量小文件深分页性能,避免单页扫盘过久触发响应头超时;全闪存集群可调大至 1000。 +# 命令行:--list-max-keys 100 。环境变量:LIST_MAX_KEYS。 +list_max_keys: 100 + +# 等待 HTTP 响应头超时(省略或 0 = 默认 60s;须 > 0 且 <= 1h,需带单位如 60s、2m、5m)。 +# 源端深分页列举(timeout awaiting response headers)或大分片合并较慢时可调大,如 2m、5m。 +# 命令行:--response-header-timeout 60s 。环境变量:RESPONSE_HEADER_TIMEOUT。 +response_header_timeout: "60s" + +# 单次 S3 请求最大尝试次数,含首次请求(1..100;省略或 0 = 默认 5)。 +# 命令行:--max-attempts 10 。环境变量:MAX_ATTEMPTS(未设置时也兼容 AWS_MAX_ATTEMPTS)。 +max_attempts: 5 + # 在应用/存储层冻结源写入及删除后才设 true;本参数不自动冻结 S3。 # 迁移和最终验收期间必须保持冻结;涉及清单对象的业务删除(包括目标端)也必须暂停或有墓碑协调。 # 也可使用 --source-frozen。 diff --git a/docs/DESIGN.md b/docs/DESIGN.md index dd1c722..3097cb8 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -38,7 +38,7 @@ Workers and producer share cancellation; a fatal HEAD/GET error stops all produc Object workers, part concurrency and job queues are bounded. Multipart bodies spool to disk instead of io.ReadAll; range reads are limited to expected bytes plus one. Temporary disk remains a capacity requirement. A shared limiter covers all source body reads in migration, including the extra digest pass. Destination reads/writes and diff are not throttled by this setting. -HTTP/1 connection pools follow worker fan-out. Response headers have a 30-second timeout; each blocked body Read and connection Write has a 90-second deadline. The body watchdog is inactive between reads, so low configured bandwidth does not cause false idle timeouts. Optional SDK checksum extensions are disabled unless required; application SHA-256 validation remains mandatory. +HTTP/1 connection pools follow worker fan-out. `ListObjectsV2` bounds every page with an explicit `max-keys` (default 100 for HDD-friendly pagination, configurable `1..1000` via `list_max_keys`). Response headers default to a 60-second timeout (`response_header_timeout`), and each blocked body Read and connection Write has a `max(90s, response_header_timeout)` deadline. S3 CLI operations default to 5 attempts (`max_attempts`) with the SDK's client-wide retry token quota disabled so transient storage stalls do not exhaust retry tokens across workers or long scans, and `AWS_CA_BUNDLE` custom RootCAs are preserved on the pooled transport. The body watchdog is inactive between reads, so low configured bandwidth does not cause false idle timeouts. Optional SDK checksum extensions are disabled unless required; application SHA-256 validation remains mandatory. ## Scope and testing diff --git a/docs/MANUAL.md b/docs/MANUAL.md index 9bc8417..3382d08 100644 --- a/docs/MANUAL.md +++ b/docs/MANUAL.md @@ -243,6 +243,11 @@ multipart_concurrency: 4 # Parallel parts per large obj # Aggregate source-read bandwidth cap: 0 or omitted = unlimited; supports 20M (decimal) or 20MiB (binary) rate_limit: 0 + +# Listing pagination, HTTP response-header timeout, and per-request S3 attempt budget +list_max_keys: 100 # ListObjectsV2 page size (1..1000; 0 or omitted = 100) +response_header_timeout: "60s" # HTTP response-header timeout (0 or omitted = 60s; max 1h) +max_attempts: 5 # Max S3 attempts per request (1..100; 0 or omitted = 5) ``` ### Precedence Order @@ -262,6 +267,9 @@ To guard against accidental typos in automation scripts, `0` behaves differently | `workers` | Default (`16`) | **Error** (must be integer `>= 1`) | **Error** (`--workers 0` rejected) | | `multipart_concurrency` | Default (`4`) | **Error** (must be integer `>= 1`) | **Error** | | `rate_limit` | **Unlimited** | **Unlimited** (overrides YAML cap) | **Unlimited** (`--rate-limit 0`) | +| `list_max_keys` | Default (`100`) | **Error** (must be `1..1000`) | **Error** | +| `response_header_timeout` | Default (`60s`) | **Error** (must be `> 0` and `<= 1h`) | **Error** | +| `max_attempts` | Default (`5`) | **Error** (must be `1..100`) | **Error** | | `multipart_threshold` | Default (`50 MiB`) | No env var | No CLI flag | | `multipart_part_size` | Default (`16 MiB`) | No env var | No CLI flag | | `spool_max_bytes` | Default (`1 GiB`) | No env var | No CLI flag | @@ -279,6 +287,10 @@ Leave secrets empty in `config.yaml` and inject them via environment variables w | `DB_PATH`, `CONFLICT_LOG`, `SPOOL_DIR` | Local state database, conflict log, and spool paths | | `WORKERS`, `MULTIPART_CONCURRENCY` | Concurrency integers (`>= 1`, plain digits without units) | | `RATE_LIMIT` | Aggregate source-read cap (e.g., `20M`, `50MiB`, `0`) | +| `LIST_MAX_KEYS` | `ListObjectsV2` page size (`1..1000`, default `100`) | +| `RESPONSE_HEADER_TIMEOUT` | HTTP response-header timeout (e.g., `60s`, `5m`; max `1h`) | +| `MAX_ATTEMPTS` (or `AWS_MAX_ATTEMPTS`) | Per-request S3 attempt budget (`1..100`, default `5`) | +| `AWS_CA_BUNDLE` | Custom PEM Root CA bundle for self-hosted HTTPS S3 endpoints | | `SOURCE_FROZEN` | `true` or `false`, equivalent to `source_frozen` | --- @@ -343,7 +355,7 @@ While `migration` is not a live replication daemon, large clusters often run a p ### Concurrency Model & Limits -Peak in-flight HTTP requests toward a single cluster are roughly **`workers × multipart_concurrency`** (hard caps: `workers <= 1024`, `multipart_concurrency <= 64`, and `workers × multipart_concurrency <= 4096`). The transport enforces HTTP/1.1 with connection pooling, a 30-second response-header timeout, and a 90-second blocked read/write timeout (rate-limiter sleep intervals between reads do not trip this timeout). +Peak in-flight HTTP requests toward a single cluster are roughly **`workers × multipart_concurrency`** (hard caps: `workers <= 1024`, `multipart_concurrency <= 64`, and `workers × multipart_concurrency <= 4096`). The transport enforces HTTP/1.1 with connection pooling, a configurable 60-second default response-header timeout (`response_header_timeout`), a `max(90s, response_header_timeout)` blocked read/write timeout (rate-limiter sleep intervals between reads do not trip this timeout), and 5 default S3 attempts per request (`max_attempts`) with bounded `ListObjectsV2` pages (`list_max_keys`, default `100`). | Workload / Symptom | Recommended Tuning | | :--- | :--- | @@ -450,5 +462,6 @@ stateDiagram-v2 | `multipart_part_size must be >= 5242880 (5 MiB)` | S3 rejects non-final parts smaller than 5 MiB. Use the default `16777216` (16 MiB) or higher. | | Object fails on `spool_max_bytes` budget | A single unsplit object or part exceeds `spool_max_bytes` (default 1 GiB). Increase `spool_max_bytes` or reduce `multipart_part_size` / `multipart_threshold`. | | Raising `--workers` does not speed up `scan` | Expected: `ListObjectsV2` pagination is inherently sequential. `--workers` accelerates copying and `diff`. | +| `ListObjectsV2 ... net/http: timeout awaiting response headers` | Deep listing over slow HDDs, millions of small keys/delete markers, or a proxy exceeded `response_header_timeout`. Lower `--list-max-keys` (e.g., `20`–`50`), raise `--response-header-timeout` (e.g., `5m`), raise `--max-attempts` (e.g., `10`), and connect directly to a healthy source storage node. | | High bandwidth during `diff` despite `--rate-limit` | Expected: `rate_limit` throttles only source reads in `run` / `migrate`; `diff` reads both full bodies at full speed. Schedule `diff` during off-peak hours. | | `create diff JSONL: ... file exists` | `--issues-jsonl` refuses to overwrite existing audit files. Specify a new output path. | diff --git a/docs/MANUAL_DE.md b/docs/MANUAL_DE.md index f9945c7..962fba5 100644 --- a/docs/MANUAL_DE.md +++ b/docs/MANUAL_DE.md @@ -343,7 +343,7 @@ Obwohl `migration` kein Live-Replikations-Daemon ist, führen große Cluster hä ### Parallelitätsmodell & Grenzwerte -Die Spitzenzahl gleichzeitiger HTTP-Anfragen an einen einzelnen Cluster beträgt näherungsweise **`workers × multipart_concurrency`** (harte Obergrenzen: `workers <= 1024`, `multipart_concurrency <= 64` sowie `workers × multipart_concurrency <= 4096`). Der HTTP-Transport nutzt HTTP/1.1 mit Connection-Pooling, einem 30-Sekunden-Timeout für Antwort-Header und einem 90-Sekunden-Timeout für blockierte Lese-/Schreibvorgänge (Wartepausen des Rate-Limiters zwischen Lesevorgängen lösen dieses Timeout nicht aus). +Die Spitzenzahl gleichzeitiger HTTP-Anfragen an einen einzelnen Cluster beträgt näherungsweise **`workers × multipart_concurrency`** (harte Obergrenzen: `workers <= 1024`, `multipart_concurrency <= 64` sowie `workers × multipart_concurrency <= 4096`). Der HTTP-Transport nutzt HTTP/1.1 mit Connection-Pooling, einem konfigurierbaren Standard-Timeout von 60 Sekunden für Antwort-Header (`response_header_timeout`), einem `max(90s, response_header_timeout)`-Timeout für blockierte Lese-/Schreibvorgänge (Wartepausen des Rate-Limiters zwischen Lesevorgängen lösen dieses Timeout nicht aus) sowie standardmäßig 5 S3-Versuchen pro Anfrage (`max_attempts`) und begrenzter `ListObjectsV2`-Seitengröße (`list_max_keys`, Standard `100`). | Arbeitslast / Symptom | Empfohlene Einstellung | | :--- | :--- | diff --git a/docs/MANUAL_ES.md b/docs/MANUAL_ES.md index 2859389..dfa73bb 100644 --- a/docs/MANUAL_ES.md +++ b/docs/MANUAL_ES.md @@ -343,7 +343,7 @@ Aunque `migration` no es un demonio de replicación en vivo, en clústeres de gr ### Modelo de concurrencia y límites -El pico de peticiones HTTP simultáneas contra un mismo clúster es aproximadamente **`workers × multipart_concurrency`** (límites estrictos: `workers <= 1024`, `multipart_concurrency <= 64` y `workers × multipart_concurrency <= 4096`). La capa de transporte fuerza HTTP/1.1 con reutilización de conexiones (*connection pooling*), un tiempo de espera de 30 segundos para cabeceras de respuesta y un tiempo de espera de 90 segundos para lecturas/escrituras bloqueadas (las pausas del limitador de velocidad entre lecturas no disparan este tiempo de espera). +El pico de peticiones HTTP simultáneas contra un mismo clúster es aproximadamente **`workers × multipart_concurrency`** (límites estrictos: `workers <= 1024`, `multipart_concurrency <= 64` y `workers × multipart_concurrency <= 4096`). La capa de transporte fuerza HTTP/1.1 con reutilización de conexiones (*connection pooling*), un tiempo de espera predeterminado y configurable de 60 segundos para cabeceras de respuesta (`response_header_timeout`), un tiempo de espera de `max(90s, response_header_timeout)` para lecturas/escrituras bloqueadas (las pausas del limitador de velocidad entre lecturas no disparan este tiempo de espera), 5 intentos S3 por petición de forma predeterminada (`max_attempts`) y páginas `ListObjectsV2` acotadas (`list_max_keys`, predeterminado `100`). | Carga de trabajo / Síntoma | Ajuste recomendado | | :--- | :--- | diff --git a/docs/MANUAL_FR.md b/docs/MANUAL_FR.md index 0c061a1..3f3360d 100644 --- a/docs/MANUAL_FR.md +++ b/docs/MANUAL_FR.md @@ -343,7 +343,7 @@ Bien que `migration` ne soit pas un démon de réplication temps réel, les clus ### Modèle de concurrence et limites -Le pic de requêtes HTTP simultanées vers un même cluster correspond approximativement à **`workers × multipart_concurrency`** (plafonds stricts : `workers <= 1024`, `multipart_concurrency <= 64` et `workers × multipart_concurrency <= 4096`). La couche transport impose HTTP/1.1 avec réutilisation des connexions, un délai maximal de 30 secondes pour les en-têtes de réponse et un délai maximal de 90 secondes en cas de blocage lecture/écriture (les pauses introduites par le limiteur de débit entre deux lectures ne déclenchent pas ce délai d'expiration). +Le pic de requêtes HTTP simultanées vers un même cluster correspond approximativement à **`workers × multipart_concurrency`** (plafonds stricts : `workers <= 1024`, `multipart_concurrency <= 64` et `workers × multipart_concurrency <= 4096`). La couche transport impose HTTP/1.1 avec réutilisation des connexions, un délai maximal configurable de 60 secondes par défaut pour les en-têtes de réponse (`response_header_timeout`), un délai maximal `max(90s, response_header_timeout)` en cas de blocage lecture/écriture (les pauses introduites par le limiteur de débit entre deux lectures ne déclenchent pas ce délai d'expiration), 5 tentatives S3 par requête par défaut (`max_attempts`) et des pages `ListObjectsV2` bornées (`list_max_keys`, défaut `100`). | Profil de charge / Symptôme | Réglage recommandé | | :--- | :--- | diff --git a/docs/MANUAL_IT.md b/docs/MANUAL_IT.md index aa94a56..e071acc 100644 --- a/docs/MANUAL_IT.md +++ b/docs/MANUAL_IT.md @@ -343,7 +343,7 @@ Sebbene `migration` non sia un demone di replica continua, sui cluster di grandi ### Modello di concorrenza e limiti -Il picco di richieste HTTP simultanee verso un singolo cluster è approssimativamente **`workers × multipart_concurrency`** (limiti rigidi: `workers <= 1024`, `multipart_concurrency <= 64` e `workers × multipart_concurrency <= 4096`). Il livello di trasporto utilizza HTTP/1.1 con connection pooling, un timeout di 30 secondi sugli header di risposta e un timeout di 90 secondi su letture/scritture bloccate (le pause introdotte dal rate limiter tra una lettura e l'altra non fanno scattare questo timeout). +Il picco di richieste HTTP simultanee verso un singolo cluster è approssimativamente **`workers × multipart_concurrency`** (limiti rigidi: `workers <= 1024`, `multipart_concurrency <= 64` e `workers × multipart_concurrency <= 4096`). Il livello di trasporto utilizza HTTP/1.1 con connection pooling, un timeout configurabile di 60 secondi per impostazione predefinita sugli header di risposta (`response_header_timeout`), un timeout `max(90s, response_header_timeout)` su letture/scritture bloccate (le pause introdotte dal rate limiter tra una lettura e l'altra non fanno scattare questo timeout), 5 tentativi S3 predefiniti per richiesta (`max_attempts`) e pagine `ListObjectsV2` limitate (`list_max_keys`, predefinito `100`). | Carico di lavoro / Sintomo | Tuning consigliato | | :--- | :--- | diff --git a/docs/MANUAL_JA.md b/docs/MANUAL_JA.md index 095afce..f4b3fbc 100644 --- a/docs/MANUAL_JA.md +++ b/docs/MANUAL_JA.md @@ -343,7 +343,7 @@ migration diff -c config.yaml --strict --issues-jsonl ./audit/diff-report.jsonl ### 並列モデルと上限値 -単一クラスタに対するピーク時の同時インフライト HTTP リクエスト数は、おおよそ **`workers × multipart_concurrency`** となります(ハードリミット:`workers <= 1024`、`multipart_concurrency <= 64`、かつ `workers × multipart_concurrency <= 4096`)。HTTP トランスポートはコネクションプーリング付きの HTTP/1.1 を使用し、レスポンスヘッダータイムアウトは 30 秒、読み書きブロックタイムアウトは 90 秒に設定されています(読み取り間のレート制限スリープ時間はタイムアウトとしてカウントされません)。 +単一クラスタに対するピーク時の同時インフライト HTTP リクエスト数は、おおよそ **`workers × multipart_concurrency`** となります(ハードリミット:`workers <= 1024`、`multipart_concurrency <= 64`、かつ `workers × multipart_concurrency <= 4096`)。HTTP トランスポートはコネクションプーリング付きの HTTP/1.1 を使用し、レスポンスヘッダータイムアウトはデフォルト 60 秒(`response_header_timeout` で変更可)、読み書きブロックタイムアウトは `max(90s, response_header_timeout)`(読み取り間のレート制限スリープ時間はタイムアウトとしてカウントされません)、リクエストごとの S3 最大試行回数はデフォルト 5 回(`max_attempts`)、`ListObjectsV2` ページ上限はデフォルト `100`(`list_max_keys`)に設定されています。 | ワークロード / 現象 | 推奨チューニング | | :--- | :--- | diff --git a/docs/MANUAL_KO.md b/docs/MANUAL_KO.md index fa2f24d..8c06b61 100644 --- a/docs/MANUAL_KO.md +++ b/docs/MANUAL_KO.md @@ -343,7 +343,7 @@ migration diff -c config.yaml --strict --issues-jsonl ./audit/diff-report.jsonl ### 동시성 모델 및 한도 -단일 클러스터로 동시에 전송되는 최대 HTTP 요청 수는 대략 **`workers × multipart_concurrency`** 수준입니다(하드 상한: `workers <= 1024`, `multipart_concurrency <= 64`, `workers × multipart_concurrency <= 4096`). 전송 계층은 커넥션 풀링을 사용하는 HTTP/1.1로 고정되어 있으며, 응답 헤더 타임아웃은 30초, 읽기/쓰기 블로킹 타임아웃은 90초입니다(대역폭 제한기 대기 시간은 블로킹 타임아웃에 포함되지 않습니다). +단일 클러스터로 동시에 전송되는 최대 HTTP 요청 수는 대략 **`workers × multipart_concurrency`** 수준입니다(하드 상한: `workers <= 1024`, `multipart_concurrency <= 64`, `workers × multipart_concurrency <= 4096`). 전송 계층은 커넥션 풀링을 사용하는 HTTP/1.1로 고정되어 있으며, 응답 헤더 타임아웃은 기본 60초(`response_header_timeout`으로 조정 가능), 읽기/쓰기 블로킹 타임아웃은 `max(90s, response_header_timeout)`(대역폭 제한기 대기 시간은 블로킹 타임아웃에 포함되지 않습니다), 요청당 기본 S3 최대 시도 횟수는 5회(`max_attempts`), `ListObjectsV2` 페이지 크기는 기본 `100`(`list_max_keys`)입니다. | 워크로드 / 증상 | 권장 튜닝 설정 | | :--- | :--- | diff --git a/docs/MANUAL_ZH.md b/docs/MANUAL_ZH.md index 56a4bac..ea7b4ef 100644 --- a/docs/MANUAL_ZH.md +++ b/docs/MANUAL_ZH.md @@ -242,6 +242,11 @@ multipart_concurrency: 4 # 单个大对象内部并发 # 源端读取合计带宽上限:0 或省略表示不限速;支持 20M(十进制)或 20MiB(1024 进制) rate_limit: 0 + +# 列举分页、等待 HTTP 响应头超时与单次请求重试上限 +list_max_keys: 100 # ListObjectsV2 每页最大条数(1~1000,0 或省略取默认 100) +response_header_timeout: "60s" # 等待 HTTP 响应头超时(0 或省略取默认 60s,上限 1h) +max_attempts: 5 # 单次 S3 请求最大尝试次数(1~100,0 或省略取默认 5) ``` ### 2. 参数覆盖优先级 @@ -261,6 +266,9 @@ rate_limit: 0 | `workers` | 取默认值 `16` | **启动报错**(须为 `>= 1` 的纯整数) | **启动报错**(`--workers 0` 非法) | | `multipart_concurrency` | 取默认值 `4` | **启动报错**(须为 `>= 1` 的纯整数) | **启动报错** | | `rate_limit` | **不限速** | **不限速**(可覆盖 YAML 中的限速) | **不限速**(`--rate-limit 0`) | +| `list_max_keys` | 取默认值 `100` | **启动报错**(须在 `1~1000` 之间) | **启动报错** | +| `response_header_timeout` | 取默认值 `60s` | **启动报错**(须 `> 0` 且 `<= 1h`) | **启动报错** | +| `max_attempts` | 取默认值 `5` | **启动报错**(须在 `1~100` 之间) | **启动报错** | | `multipart_threshold` | 取默认值 `50 MiB` | 无对应环境变量 | 无对应命令行参数 | | `multipart_part_size` | 取默认值 `16 MiB` | 无对应环境变量 | 无对应命令行参数 | | `spool_max_bytes` | 取默认值 `1 GiB` | 无对应环境变量 | 无对应命令行参数 | @@ -278,6 +286,10 @@ rate_limit: 0 | `DB_PATH` / `CONFLICT_LOG` / `SPOOL_DIR` | 覆盖本地数据库、冲突日志与临时落盘目录 | | `WORKERS` / `MULTIPART_CONCURRENCY` | 覆盖并发数(仅接受 `>= 1` 的纯整数,不可带单位) | | `RATE_LIMIT` | 覆盖源端读取带宽上限(如 `20M`、`50MiB`、`0`) | +| `LIST_MAX_KEYS` | 覆盖 `ListObjectsV2` 每页条数上限(`1~1000`,默认 `100`) | +| `RESPONSE_HEADER_TIMEOUT` | 覆盖等待 HTTP 响应头超时(如 `60s`、`5m`,上限 `1h`) | +| `MAX_ATTEMPTS`(或 `AWS_MAX_ATTEMPTS`) | 覆盖单次 S3 请求最大尝试次数(`1~100`,默认 `5`) | +| `AWS_CA_BUNDLE` | 自建 HTTPS S3 集群的自定义 PEM 根证书路径 | | `SOURCE_FROZEN` | 填写 `true` 或 `false`,等同于 `source_frozen` | --- @@ -349,7 +361,7 @@ migration diff -c config.yaml --strict --issues-jsonl ./audit/diff-report.jsonl ### 1. 并发模型与调优参考 -打向单个存储集群的峰值并发 HTTP 请求数约为 **`workers × multipart_concurrency`**(系统内置安全上限:`workers <= 1024`,`multipart_concurrency <= 64`,且乘积 `<= 4096`)。HTTP 客户端底层采用 HTTP/1.1 连接池(响应头超时 30 秒,单次读写阻塞超时 90 秒;限速等待期间不计入阻塞超时)。 +打向单个存储集群的峰值并发 HTTP 请求数约为 **`workers × multipart_concurrency`**(系统内置安全上限:`workers <= 1024`,`multipart_concurrency <= 64`,且乘积 `<= 4096`)。HTTP 客户端底层采用 HTTP/1.1 连接池,默认等待响应头超时为 60 秒(`response_header_timeout`),单次读写阻塞超时为 `max(90s, response_header_timeout)`(限速等待期间不计入阻塞超时),单次请求默认最多尝试 5 次(`max_attempts`),且 `ListObjectsV2` 显式限制每页条数(`list_max_keys`,默认 `100`)。 | 业务对象分布 / 现场表现 | 调参建议 | | :--- | :--- | @@ -458,5 +470,6 @@ stateDiagram-v2 | `multipart_part_size must be >= 5242880 (5 MiB)` | S3 协议要求除最后一片外每片不得小于 `5 MiB`(`5242880` 字节)。请改为默认值 `16777216`(16 MiB)或以上。 | | 报错提示超过 `spool_max_bytes` 预算 | 单个未分片对象或单个分片大于 `spool_max_bytes`(默认 1 GiB)。请调大 `spool_max_bytes`,或减小 `multipart_part_size` / `multipart_threshold`。 | | 调大 `--workers` 后 `scan` 阶段依然没有变快 | 正常现象。S3 `ListObjectsV2` 分页列举必须串行等待上一页返回的 `ContinuationToken`,`--workers` 从复制与 `diff` 阶段开始生效。 | +| `ListObjectsV2 ... net/http: timeout awaiting response headers` | 源端在机械盘海量小文件/深层目录或反代下,单页列举耗时超过了等待响应头超时。可进一步调小分页(如 `--list-max-keys 20` 或 `50`)、调大 `--response-header-timeout 5m` 与 `--max-attempts 10`,并尽量将 `old.endpoint` 直连健康的源存储节点。 | | 设置了 `--rate-limit` 但执行 `diff` 时带宽跑满 | 正常现象。`rate_limit` 只限制 `run` / `migrate` 对源端正文的读取;`diff` 会并发全速读取双端完整正文校验 SHA-256,请安排在低峰窗口执行。 | | `create diff JSONL: ... file exists` | `--issues-jsonl` 为避免覆盖已有审计证据,要求目标文件必须不存在。请更换一个新的 `.jsonl` 文件路径。 | diff --git a/internal/cluster/objects.go b/internal/cluster/objects.go index 585fda8..e58b84e 100644 --- a/internal/cluster/objects.go +++ b/internal/cluster/objects.go @@ -10,10 +10,35 @@ import ( "github.com/aws/aws-sdk-go-v2/service/s3/types" ) -// WalkObjects passes one decoded listing page at a time to visit. Request URL -// encoding so even keys containing characters forbidden in XML can be listed. +const ( + // DefaultListMaxKeys is the default S3 ListObjectsV2 page size. Keeping pages + // at 100 keys prevents slow HDD metadata scans or oversized default pages + // (such as 10,000 keys) from stalling HTTP response headers. + DefaultListMaxKeys = 100 + maxListMaxKeys = 1000 +) + +// WalkObjects passes one decoded listing page at a time to visit using the +// default 100-key page size. Request URL encoding so even keys containing +// characters forbidden in XML can be listed. func WalkObjects(ctx context.Context, cli *s3.Client, bucket string, visit func([]types.Object) error) error { - input := &s3.ListObjectsV2Input{Bucket: aws.String(bucket), EncodingType: types.EncodingTypeUrl} + return WalkObjectsWithMaxKeys(ctx, cli, bucket, DefaultListMaxKeys, visit) +} + +// WalkObjectsWithMaxKeys is WalkObjects with an explicit ListObjectsV2 MaxKeys +// cap (1..1000; values <= 0 use DefaultListMaxKeys). +func WalkObjectsWithMaxKeys(ctx context.Context, cli *s3.Client, bucket string, maxKeys int, visit func([]types.Object) error) error { + if maxKeys <= 0 { + maxKeys = DefaultListMaxKeys + } + if maxKeys > maxListMaxKeys { + maxKeys = maxListMaxKeys + } + input := &s3.ListObjectsV2Input{ + Bucket: aws.String(bucket), + EncodingType: types.EncodingTypeUrl, + MaxKeys: aws.Int32(int32(maxKeys)), + } seenTokens := make(map[string]struct{}) for { if err := ctx.Err(); err != nil { diff --git a/internal/cluster/objects_test.go b/internal/cluster/objects_test.go index 1cf9238..519647e 100644 --- a/internal/cluster/objects_test.go +++ b/internal/cluster/objects_test.go @@ -31,6 +31,9 @@ func TestWalkObjectsDecodesKeysOnceAndPreservesOpaqueTokens(t *testing.T) { if query.Get("encoding-type") != "url" { t.Error("missing URL encoding request") } + if query.Get("max-keys") != "100" { + t.Errorf("expected explicit max-keys=100, got %q", query.Get("max-keys")) + } page := "" switch query.Get("continuation-token") { case "": @@ -95,3 +98,30 @@ func TestWalkObjectsRejectsAlternatingTokens(t *testing.T) { t.Fatalf("requests=%d err=%v", requests, err) } } + +func TestWalkObjectsWithMaxKeysBoundsEveryPage(t *testing.T) { + var seenMaxKeys []string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + seenMaxKeys = append(seenMaxKeys, r.URL.Query().Get("max-keys")) + if r.URL.Query().Get("continuation-token") == "" { + fmt.Fprint(w, `photostruep2a1`) + return + } + fmt.Fprint(w, `photosfalseb2`) + })) + defer server.Close() + + var keys []string + err := WalkObjectsWithMaxKeys(context.Background(), clientFor(t, server.URL), "photos", 250, func(objs []types.Object) error { + for _, o := range objs { + keys = append(keys, *o.Key) + } + return nil + }) + if err != nil { + t.Fatalf("WalkObjectsWithMaxKeys: %v", err) + } + if !slices.Equal(seenMaxKeys, []string{"250", "250"}) || !slices.Equal(keys, []string{"a", "b"}) { + t.Fatalf("seenMaxKeys=%v keys=%v", seenMaxKeys, keys) + } +} diff --git a/internal/config/config.go b/internal/config/config.go index b439bbc..1a0ed44 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -9,6 +9,7 @@ import ( "path/filepath" "strconv" "strings" + "time" "unicode" "gopkg.in/yaml.v3" @@ -23,6 +24,17 @@ const ( DefaultMultipartConcurrency = 4 // DefaultSpoolMaxBytes bounds temporary copy data for one migration. DefaultSpoolMaxBytes int64 = 1 << 30 + // DefaultListMaxKeys bounds each ListObjectsV2 page to 100 keys so HDD-backed + // S3-compatible clusters return pages quickly without header timeouts. + DefaultListMaxKeys = 100 + MaxListMaxKeys = 1000 + // DefaultResponseHeaderTimeout bounds how long the HTTP transport waits + // for response headers on slow listings or multipart commits. + DefaultResponseHeaderTimeout = 60 * time.Second + MaxResponseHeaderTimeout = time.Hour + // DefaultMaxAttempts is the per-request S3 attempt budget (1 initial + 4 retries). + DefaultMaxAttempts = 5 + MaxMaxAttempts = 100 ) type Endpoint struct { @@ -57,6 +69,14 @@ type Config struct { // YAML 0 and a missing field both stay unlimited; this is not rewritten // to a default the way workers is. RateLimit ByteRate `yaml:"rate_limit"` + + // ListMaxKeys caps each ListObjectsV2 page (1..1000; 0 or omitted = 100). + ListMaxKeys int `yaml:"list_max_keys"` + // ResponseHeaderTimeout bounds waiting for HTTP response headers on slow + // listings or multipart commits (0 or omitted = 60s). + ResponseHeaderTimeout Duration `yaml:"response_header_timeout"` + // MaxAttempts is the per-request S3 attempt budget (1..100; 0 or omitted = 5). + MaxAttempts int `yaml:"max_attempts"` } // MinMultipartPartSize is the S3 minimum for every part except the last @@ -72,10 +92,13 @@ const MinMultipartPartSize int64 = 5 * 1024 * 1024 const MaxMultipartPartSize int64 = 5 * 1024 * 1024 * 1024 type CLIReadOptions struct { - SkipWorkersEnv bool - SkipMultipartConcurrencyEnv bool - SkipRateLimitEnv bool - SkipSourceFrozenEnv bool + SkipWorkersEnv bool + SkipMultipartConcurrencyEnv bool + SkipRateLimitEnv bool + SkipSourceFrozenEnv bool + SkipListMaxKeysEnv bool + SkipResponseHeaderTimeoutEnv bool + SkipMaxAttemptsEnv bool } // Load parses YAML, applies env overrides and defaults. It does not require @@ -97,6 +120,9 @@ func Load(path string) (*Config, error) { if err := c.ValidateRateLimit(); err != nil { return nil, err } + if err := c.ValidateTransport(); err != nil { + return nil, err + } return c, nil } @@ -179,6 +205,25 @@ func (c *Config) applyEnvWithOptions(opt CLIReadOptions) error { return err } } + if !opt.SkipListMaxKeysEnv { + if err := applyBoundedIntEnv(&c.ListMaxKeys, "LIST_MAX_KEYS", 1, MaxListMaxKeys); err != nil { + return err + } + } + if !opt.SkipResponseHeaderTimeoutEnv { + if err := applyPositiveDurationEnv(&c.ResponseHeaderTimeout, "RESPONSE_HEADER_TIMEOUT"); err != nil { + return err + } + } + if !opt.SkipMaxAttemptsEnv { + if strings.TrimSpace(os.Getenv("MAX_ATTEMPTS")) != "" { + if err := applyBoundedIntEnv(&c.MaxAttempts, "MAX_ATTEMPTS", 1, MaxMaxAttempts); err != nil { + return err + } + } else if err := applyBoundedIntEnv(&c.MaxAttempts, "AWS_MAX_ATTEMPTS", 1, MaxMaxAttempts); err != nil { + return err + } + } return nil } @@ -201,6 +246,38 @@ func applyPositiveIntEnv(dst *int, key string) error { return nil } +func applyBoundedIntEnv(dst *int, key string, minVal, maxVal int) error { + raw := strings.TrimSpace(os.Getenv(key)) + if raw == "" { + return nil + } + n, err := strconv.Atoi(raw) + if err != nil { + return fmt.Errorf("env %s=%q is not an integer", key, raw) + } + if n < minVal || n > maxVal { + return fmt.Errorf("env %s must be between %d and %d, got %d", key, minVal, maxVal, n) + } + *dst = n + return nil +} + +func applyPositiveDurationEnv(dst *Duration, key string) error { + raw := strings.TrimSpace(os.Getenv(key)) + if raw == "" { + return nil + } + d, err := ParseDuration(raw) + if err != nil { + return fmt.Errorf("env %s: %w", key, err) + } + if d <= 0 || d > MaxResponseHeaderTimeout { + return fmt.Errorf("env %s must be > 0 and <= %s, got %s", key, MaxResponseHeaderTimeout, d) + } + *dst = Duration(d) + return nil +} + // applyByteRateEnv overrides dst when key is set. Empty means "leave YAML". // 0 is a real value (unlimited) and replaces a YAML cap. Negative values and // unknown suffixes are rejected. @@ -232,7 +309,7 @@ func (c *Config) applyDefaults() { c.ConflictLog = "./conflict.log" } // 0 (omitted) means "use the default". Negatives are left in place so - // ValidateConcurrency can reject them instead of silently rewriting a typo. + // ValidateConcurrency / ValidateTransport can reject them instead of silently rewriting a typo. if c.Workers == 0 { c.Workers = DefaultWorkers } @@ -245,6 +322,15 @@ func (c *Config) applyDefaults() { if c.MultipartConcurrency == 0 { c.MultipartConcurrency = DefaultMultipartConcurrency } + if c.ListMaxKeys == 0 { + c.ListMaxKeys = DefaultListMaxKeys + } + if c.ResponseHeaderTimeout == 0 { + c.ResponseHeaderTimeout = Duration(DefaultResponseHeaderTimeout) + } + if c.MaxAttempts == 0 { + c.MaxAttempts = DefaultMaxAttempts + } // RateLimit 0 (omitted) stays 0: unlimited. Do not invent a default cap. if c.SpoolMaxBytes == 0 { c.SpoolMaxBytes = DefaultSpoolMaxBytes @@ -452,6 +538,53 @@ func (c *Config) ApplyRateLimitOverride(raw string, set bool) error { return c.ValidateRateLimit() } +// ValidateTransport validates S3 listing page size, HTTP response-header +// timeout, and per-request S3 attempt limits. +func (c *Config) ValidateTransport() error { + if c.ListMaxKeys < 1 || c.ListMaxKeys > MaxListMaxKeys { + return fmt.Errorf("list_max_keys must be between 1 and %d, got %d", MaxListMaxKeys, c.ListMaxKeys) + } + if c.ResponseHeaderTimeout <= 0 || c.ResponseHeaderTimeout.Duration() > MaxResponseHeaderTimeout { + return fmt.Errorf("response_header_timeout must be > 0 and <= %s, got %s", MaxResponseHeaderTimeout, c.ResponseHeaderTimeout) + } + if c.MaxAttempts < 1 || c.MaxAttempts > MaxMaxAttempts { + return fmt.Errorf("max_attempts must be between 1 and %d, got %d", MaxMaxAttempts, c.MaxAttempts) + } + return nil +} + +// ApplyTransportOverrides applies CLI overrides for listing page size, +// response-header timeout, and retry attempts. Priority is CLI > env > YAML > default. +func (c *Config) ApplyTransportOverrides( + listMaxKeys int, listMaxKeysSet bool, + headerTimeoutRaw string, headerTimeoutSet bool, + maxAttempts int, maxAttemptsSet bool, +) error { + if listMaxKeysSet { + if listMaxKeys < 1 || listMaxKeys > MaxListMaxKeys { + return fmt.Errorf("list_max_keys must be between 1 and %d, got %d", MaxListMaxKeys, listMaxKeys) + } + c.ListMaxKeys = listMaxKeys + } + if headerTimeoutSet { + d, err := ParseDuration(headerTimeoutRaw) + if err != nil { + return fmt.Errorf("response_header_timeout: %w", err) + } + if d <= 0 || d > MaxResponseHeaderTimeout { + return fmt.Errorf("response_header_timeout must be > 0 and <= %s, got %s", MaxResponseHeaderTimeout, d) + } + c.ResponseHeaderTimeout = Duration(d) + } + if maxAttemptsSet { + if maxAttempts < 1 || maxAttempts > MaxMaxAttempts { + return fmt.Errorf("max_attempts must be between 1 and %d, got %d", MaxMaxAttempts, maxAttempts) + } + c.MaxAttempts = maxAttempts + } + return c.ValidateTransport() +} + // MaxInFlight estimates per-host request fan-out: each worker may have // MultipartConcurrency parts in flight. It sizes HTTP idle pools and is not a hard cap. func (c *Config) MaxInFlight() int { diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 7cd0946..6406dbe 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -404,3 +404,112 @@ func TestMultipartPartSizeMaximum(t *testing.T) { t.Fatal("part size above 5 GiB accepted") } } + +func TestTransportTuningDefaultsEnvAndCLIPrecedence(t *testing.T) { + const base = "old: {endpoint: \"http://a:1\", access_key: a, secret_key: b}\n" + + t.Run("defaults when omitted or zero", func(t *testing.T) { + for _, yamlBody := range []string{ + base, + base + "list_max_keys: 0\nresponse_header_timeout: 0\nmax_attempts: 0\n", + base + "response_header_timeout: 0s\n", + } { + cfg := loadPartSizeYAML(t, yamlBody) + if cfg.ListMaxKeys != DefaultListMaxKeys { + t.Fatalf("ListMaxKeys = %d, want %d", cfg.ListMaxKeys, DefaultListMaxKeys) + } + if cfg.ResponseHeaderTimeout.Duration() != DefaultResponseHeaderTimeout { + t.Fatalf("ResponseHeaderTimeout = %s, want %s", cfg.ResponseHeaderTimeout, DefaultResponseHeaderTimeout) + } + if cfg.MaxAttempts != DefaultMaxAttempts { + t.Fatalf("MaxAttempts = %d, want %d", cfg.MaxAttempts, DefaultMaxAttempts) + } + } + }) + + t.Run("yaml env aws_max_attempts and cli precedence", func(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.yaml") + body := base + "list_max_keys: 250\nresponse_header_timeout: 3m\nmax_attempts: 6\n" + if err := os.WriteFile(path, []byte(body), 0o600); err != nil { + t.Fatal(err) + } + + // Whitespace env vars must preserve YAML. + t.Setenv("LIST_MAX_KEYS", " ") + t.Setenv("RESPONSE_HEADER_TIMEOUT", "\t") + t.Setenv("MAX_ATTEMPTS", " ") + t.Setenv("AWS_MAX_ATTEMPTS", "12") + cfg, err := Load(path) + if err != nil { + t.Fatal(err) + } + if cfg.ListMaxKeys != 250 || cfg.ResponseHeaderTimeout.String() != "3m0s" || cfg.MaxAttempts != 12 { + t.Fatalf("AWS_MAX_ATTEMPTS fallback or YAML preservation failed: keys=%d timeout=%s attempts=%d", + cfg.ListMaxKeys, cfg.ResponseHeaderTimeout, cfg.MaxAttempts) + } + + // Explicit MAX_ATTEMPTS beats AWS_MAX_ATTEMPTS. + t.Setenv("LIST_MAX_KEYS", "500") + t.Setenv("RESPONSE_HEADER_TIMEOUT", "4m30s") + t.Setenv("MAX_ATTEMPTS", "9") + cfg, err = Load(path) + if err != nil { + t.Fatal(err) + } + if cfg.ListMaxKeys != 500 || cfg.ResponseHeaderTimeout.String() != "4m30s" || cfg.MaxAttempts != 9 { + t.Fatalf("env override failed: keys=%d timeout=%s attempts=%d", + cfg.ListMaxKeys, cfg.ResponseHeaderTimeout, cfg.MaxAttempts) + } + + // CLI overrides beat env and YAML. + if err := cfg.ApplyTransportOverrides(100, true, "5m", true, 15, true); err != nil { + t.Fatal(err) + } + if cfg.ListMaxKeys != 100 || cfg.ResponseHeaderTimeout.String() != "5m0s" || cfg.MaxAttempts != 15 { + t.Fatalf("CLI override failed: keys=%d timeout=%s attempts=%d", + cfg.ListMaxKeys, cfg.ResponseHeaderTimeout, cfg.MaxAttempts) + } + }) + + t.Run("rejects invalid values", func(t *testing.T) { + badYAML := []string{ + "list_max_keys: -1\n", + "list_max_keys: 1001\n", + "response_header_timeout: -5s\n", + "response_header_timeout: 2h\n", + "response_header_timeout: 120\n", + "max_attempts: -1\n", + "max_attempts: 101\n", + } + for _, extra := range badYAML { + path := filepath.Join(t.TempDir(), "config.yaml") + if err := os.WriteFile(path, []byte(base+extra), 0o600); err != nil { + t.Fatal(err) + } + if _, err := Load(path); err == nil { + t.Fatalf("expected error for YAML %q", extra) + } + } + + cfg := loadPartSizeYAML(t, base) + if err := cfg.ApplyTransportOverrides(0, true, "", false, 0, false); err == nil { + t.Fatal("expected CLI list_max_keys=0 to fail") + } + if err := cfg.ApplyTransportOverrides(0, false, "0s", true, 0, false); err == nil { + t.Fatal("expected CLI response_header_timeout=0s to fail") + } + if err := cfg.ApplyTransportOverrides(0, false, "", false, 0, true); err == nil { + t.Fatal("expected CLI max_attempts=0 to fail") + } + }) + + t.Run("config.example.yaml parses cleanly", func(t *testing.T) { + cfg, err := Load(filepath.Join("..", "..", "config.example.yaml")) + if err != nil { + t.Fatalf("config.example.yaml failed to load: %v", err) + } + if cfg.ListMaxKeys != DefaultListMaxKeys || cfg.ResponseHeaderTimeout.Duration() != DefaultResponseHeaderTimeout || cfg.MaxAttempts != DefaultMaxAttempts { + t.Fatalf("unexpected defaults in config.example.yaml: %+v", cfg) + } + }) +} diff --git a/internal/config/duration.go b/internal/config/duration.go new file mode 100644 index 0000000..60c31b4 --- /dev/null +++ b/internal/config/duration.go @@ -0,0 +1,56 @@ +package config + +import ( + "fmt" + "strings" + "time" + + "gopkg.in/yaml.v3" +) + +// Duration wraps time.Duration for YAML unmarshaling and CLI/env parsing. +// In YAML, 0 or an empty/omitted value means "use the built-in default". +type Duration time.Duration + +func (d Duration) Duration() time.Duration { + return time.Duration(d) +} + +func (d Duration) String() string { + return time.Duration(d).String() +} + +func (d *Duration) UnmarshalYAML(node *yaml.Node) error { + if node == nil || node.Tag == "!!null" { + *d = 0 + return nil + } + if node.Kind != yaml.ScalarNode { + return fmt.Errorf("duration must be a string such as 30s, 2m, or 5m") + } + raw := strings.TrimSpace(node.Value) + if raw == "" || raw == "0" { + *d = 0 + return nil + } + parsed, err := ParseDuration(raw) + if err != nil { + return err + } + *d = Duration(parsed) + return nil +} + +// ParseDuration parses a Go duration string (e.g. 30s, 2m, 5m) and rejects +// bare non-zero integers whose unit would be ambiguous. +func ParseDuration(raw string) (time.Duration, error) { + s := strings.TrimSpace(raw) + if s == "" { + return 0, fmt.Errorf("duration is empty") + } + d, err := time.ParseDuration(s) + if err != nil { + return 0, fmt.Errorf("invalid duration %q (use units like 30s, 2m, 5m): %w", raw, err) + } + return d, nil +} diff --git a/internal/differ/differ.go b/internal/differ/differ.go index b50cb1c..25a1fc2 100644 --- a/internal/differ/differ.go +++ b/internal/differ/differ.go @@ -48,7 +48,9 @@ func (r Result) HasGaps() bool { } type Options struct { - Workers int + Workers int + // ListMaxKeys caps each ListObjectsV2 page (1..1000; <= 0 uses default 100). + ListMaxKeys int ReportExtra bool // TempDir overrides the directory for the temporary SQLite index used when // ReportExtra is true (e.g. spool_dir). Empty uses the OS temp directory. @@ -231,7 +233,7 @@ func Run(ctx context.Context, oldCli, newCli *s3.Client, bucket string, opt Opti }() } - walkErr := cluster.WalkObjects(ctx, oldCli, bucket, func(contents []types.Object) error { + walkErr := cluster.WalkObjectsWithMaxKeys(ctx, oldCli, bucket, opt.ListMaxKeys, func(contents []types.Object) error { for _, obj := range contents { key := awsv2.ToString(obj.Key) item := listed{key: key, size: *obj.Size, etag: awsv2.ToString(obj.ETag)} @@ -268,7 +270,7 @@ func Run(ctx context.Context, oldCli, newCli *s3.Client, bucket string, opt Opti } if opt.ReportExtra { - err := cluster.WalkObjects(ctx, newCli, bucket, func(contents []types.Object) error { + err := cluster.WalkObjectsWithMaxKeys(ctx, newCli, bucket, opt.ListMaxKeys, func(contents []types.Object) error { for _, obj := range contents { key := awsv2.ToString(obj.Key) var n int @@ -301,7 +303,7 @@ func RunExtraBucket(ctx context.Context, newCli *s3.Client, bucket string, opt O return res, fmt.Errorf("head target bucket %q: %w", bucket, err) } var mu sync.Mutex - err := cluster.WalkObjects(ctx, newCli, bucket, func(contents []types.Object) error { + err := cluster.WalkObjectsWithMaxKeys(ctx, newCli, bucket, opt.ListMaxKeys, func(contents []types.Object) error { for _, obj := range contents { key := awsv2.ToString(obj.Key) if err := record(&mu, &res, opt.IssuesJSONL, Issue{Key: key, Kind: "extra", Detail: "only on target (bucket missing on source)"}); err != nil { diff --git a/internal/fakes3/fakes3.go b/internal/fakes3/fakes3.go index 2648564..a20a618 100644 --- a/internal/fakes3/fakes3.go +++ b/internal/fakes3/fakes3.go @@ -378,17 +378,48 @@ func (s *Server) listObjects(w http.ResponseWriter, r *http.Request, bucket stri } sort.Strings(keys) + q := r.URL.Query() + maxKeys := 1000 + if rawMax := q.Get("max-keys"); rawMax != "" { + if parsed, err := strconv.Atoi(rawMax); err == nil && parsed >= 0 { + maxKeys = parsed + } + } + startIdx := 0 + if tok := q.Get("continuation-token"); tok != "" { + afterKey, err := url.QueryUnescape(strings.TrimPrefix(tok, "tok:")) + if err != nil { + http.Error(w, "invalid continuation-token", http.StatusBadRequest) + return + } + startIdx = sort.Search(len(keys), func(i int) bool { return keys[i] > afterKey }) + } + + pageKeys := keys[startIdx:] + isTruncated := false + nextToken := "" + if len(pageKeys) > maxKeys { + isTruncated = true + pageKeys = pageKeys[:maxKeys] + if len(pageKeys) > 0 { + nextToken = "tok:" + url.QueryEscape(pageKeys[len(pageKeys)-1]) + } + } + var b strings.Builder b.WriteString(``) b.WriteString(``) - b.WriteString(`` + xmlEscape(bucket) + `` + strconv.Itoa(len(keys)) + `1000false`) - if r.URL.Query().Get("encoding-type") == "url" { + b.WriteString(`` + xmlEscape(bucket) + `` + strconv.Itoa(len(pageKeys)) + `` + strconv.Itoa(maxKeys) + `` + strconv.FormatBool(isTruncated) + ``) + if isTruncated { + b.WriteString(`` + xmlEscape(nextToken) + ``) + } + if q.Get("encoding-type") == "url" { b.WriteString(`url`) } - for _, key := range keys { + for _, key := range pageKeys { obj := bkt[key] encodedKey := key - if r.URL.Query().Get("encoding-type") == "url" { + if q.Get("encoding-type") == "url" { encodedKey = url.PathEscape(key) } b.WriteString(`` + xmlEscape(encodedKey) + ``) diff --git a/internal/s3client/client.go b/internal/s3client/client.go index 6b50c2b..7e592e8 100644 --- a/internal/s3client/client.go +++ b/internal/s3client/client.go @@ -8,6 +8,9 @@ import ( "time" awsv2 "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/aws/ratelimit" + "github.com/aws/aws-sdk-go-v2/aws/retry" + awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http" awsconfig "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/credentials" "github.com/aws/aws-sdk-go-v2/feature/ec2/imds" @@ -16,11 +19,21 @@ import ( "github.com/rustfs/migration/internal/config" ) +const defaultIOTimeout = 90 * time.Second + +// ClientOptions configures connection pooling, HTTP timeouts, and S3 retries. +// Zero values select safe defaults. +type ClientOptions struct { + IdlePerHost int + ResponseHeaderTimeout time.Duration + MaxAttempts int +} + // New builds an S3 client for a self-hosted, S3-compatible endpoint // (RustFS / MinIO style). Path-style addressing is forced on. // The HTTP idle pool is sized for the default worker fan-out. func New(ctx context.Context, ep config.Endpoint) (*s3.Client, error) { - return NewWithPool(ctx, ep, 0) + return NewWithOptions(ctx, ep, ClientOptions{}) } // NewWithPool is New with an explicit per-host idle-connection hint. @@ -30,23 +43,61 @@ func New(ctx context.Context, ep config.Endpoint) (*s3.Client, error) { // reconnecting on every object when MaxIdleConnsPerHost would otherwise // stay at the Go default of 2. func NewWithPool(ctx context.Context, ep config.Endpoint, idlePerHost int) (*s3.Client, error) { + return NewWithOptions(ctx, ep, ClientOptions{IdlePerHost: idlePerHost}) +} + +// NewWithOptions builds an S3 client with explicit pool, timeout, and retry settings. +func NewWithOptions(ctx context.Context, ep config.Endpoint, opts ClientOptions) (*s3.Client, error) { + headerTimeout := opts.ResponseHeaderTimeout + if headerTimeout <= 0 { + headerTimeout = config.DefaultResponseHeaderTimeout + } + ioTimeout := max(defaultIOTimeout, headerTimeout) + // Self-hosted clusters have no EC2 IMDS; disable it on the config loader // without mutating process-wide environment variables across goroutines. + // Pass a BuildableClient so AWS_CA_BUNDLE / ca_bundle custom RootCAs can be + // attached by LoadDefaultConfig before we clone and tune the transport. cfg, err := awsconfig.LoadDefaultConfig(ctx, awsconfig.WithRegion(ep.Region), awsconfig.WithEC2IMDSClientEnableState(imds.ClientDisabled), awsconfig.WithCredentialsProvider( credentials.NewStaticCredentialsProvider(ep.AccessKey, ep.SecretKey, ep.SessionToken), ), - awsconfig.WithHTTPClient(&http.Client{Transport: idleTimeoutTransport{base: pooledTransport(idlePerHost), timeout: 90 * time.Second}}), + awsconfig.WithHTTPClient(awshttp.NewBuildableClient()), ) if err != nil { return nil, fmt.Errorf("aws config: %w", err) } + var baseTransport *http.Transport + if bc, ok := cfg.HTTPClient.(*awshttp.BuildableClient); ok { + baseTransport = bc.GetTransport() + } + tr := pooledTransportFrom(baseTransport, opts.IdlePerHost, headerTimeout, ioTimeout) + httpClient := &http.Client{ + Transport: idleTimeoutTransport{base: tr, timeout: ioTimeout}, + } + + maxAttempts := opts.MaxAttempts + if maxAttempts <= 0 { + maxAttempts = cfg.RetryMaxAttempts + } + if maxAttempts <= 0 { + maxAttempts = retry.DefaultMaxAttempts + } + client := s3.NewFromConfig(cfg, func(o *s3.Options) { o.BaseEndpoint = awsv2.String(ep.Endpoint) o.UsePathStyle = true + o.HTTPClient = httpClient + // Disable the SDK's shared 500-token client retry quota so transient + // cluster stalls across concurrent workers or multi-hour scans do not + // exhaust tokens and silently stop retrying later pages/objects. + o.Retryer = retry.NewStandard(func(ro *retry.StandardOptions) { + ro.MaxAttempts = maxAttempts + ro.RateLimiter = ratelimit.None + }) // Avoid assuming optional checksum extensions on S3-compatible servers. // Migration and diff verify full SHA-256 content independently. o.RequestChecksumCalculation = awsv2.RequestChecksumCalculationWhenRequired @@ -56,6 +107,10 @@ func NewWithPool(ctx context.Context, ep config.Endpoint, idlePerHost int) (*s3. } func pooledTransport(idlePerHost int) *http.Transport { + return pooledTransportFrom(nil, idlePerHost, config.DefaultResponseHeaderTimeout, max(defaultIOTimeout, config.DefaultResponseHeaderTimeout)) +} + +func pooledTransportFrom(base *http.Transport, idlePerHost int, headerTimeout, writeTimeout time.Duration) *http.Transport { if idlePerHost <= 0 { idlePerHost = config.DefaultWorkers * config.DefaultMultipartConcurrency } @@ -66,13 +121,20 @@ func pooledTransport(idlePerHost int) *http.Transport { idlePerHost = 1024 } var tr *http.Transport - if base, ok := http.DefaultTransport.(*http.Transport); ok { + switch { + case base != nil: tr = base.Clone() - } else { + case http.DefaultTransport != nil: + if def, ok := http.DefaultTransport.(*http.Transport); ok { + tr = def.Clone() + } else { + tr = &http.Transport{} + } + default: tr = &http.Transport{} } tr.MaxIdleConnsPerHost = idlePerHost - tr.ResponseHeaderTimeout = 30 * time.Second + tr.ResponseHeaderTimeout = headerTimeout // HTTP/1 gives each upload its own connection write deadline. HTTP/2 // stream flow-control waits cannot be bounded by a socket WriteDeadline. tr.ForceAttemptHTTP2 = false @@ -87,7 +149,7 @@ func pooledTransport(idlePerHost int) *http.Transport { if err != nil { return nil, err } - return &writeTimeoutConn{Conn: conn, timeout: 90 * time.Second}, nil + return &writeTimeoutConn{Conn: conn, timeout: writeTimeout}, nil } if tr.MaxIdleConns < idlePerHost*2 { tr.MaxIdleConns = idlePerHost * 2 diff --git a/internal/s3client/timeout_test.go b/internal/s3client/timeout_test.go index 08b57cf..55fb1cc 100644 --- a/internal/s3client/timeout_test.go +++ b/internal/s3client/timeout_test.go @@ -2,13 +2,26 @@ package s3client import ( "context" + "encoding/pem" "errors" + "fmt" "io" "net" "net/http" "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "sync/atomic" "testing" "time" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/aws/retry" + "github.com/aws/aws-sdk-go-v2/service/s3" + + "github.com/rustfs/migration/internal/config" ) func TestStalledUploadWriteTimesOut(t *testing.T) { @@ -64,3 +77,189 @@ func TestBandwidthPacingBetweenReadsDoesNotTimeOut(t *testing.T) { t.Fatal("wrong body") } } + +func TestListObjectsResponseHeaderTimeoutAndRetryRecovery(t *testing.T) { + var attempts atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + n := attempts.Add(1) + // Simulate a cold HDD bucket listing whose first 3 attempts exceed an 80ms + // header timeout while warming directory metadata, then succeed on attempt 4. + if n <= 3 { + select { + case <-time.After(250 * time.Millisecond): + case <-r.Context().Done(): + return + } + } + w.Header().Set("Content-Type", "application/xml") + _, _ = io.WriteString(w, `writfalsedoc.docx12`) + })) + defer srv.Close() + + ctx := context.Background() + ep := config.Endpoint{Endpoint: srv.URL, Region: "us-east-1", AccessKey: "a", SecretKey: "b"} + + // With only 3 attempts and a tight header timeout, all 3 attempts time out. + shortCli, err := NewWithOptions(ctx, ep, ClientOptions{ + ResponseHeaderTimeout: 80 * time.Millisecond, + MaxAttempts: 3, + }) + if err != nil { + t.Fatal(err) + } + shortCli = s3.New(shortCli.Options(), func(o *s3.Options) { + o.Retryer = retry.NewStandard(func(ro *retry.StandardOptions) { + ro.MaxAttempts = 3 + ro.MaxBackoff = 5 * time.Millisecond + }) + }) + _, err = shortCli.ListObjectsV2(ctx, &s3.ListObjectsV2Input{Bucket: aws.String("writ")}) + if err == nil || !strings.Contains(err.Error(), "timeout awaiting response headers") { + t.Fatalf("expected response header timeout with 3 attempts, got %v", err) + } + + // With MaxAttempts=5 (the new CLI default), attempt 4 succeeds after the 3 stalls. + attempts.Store(0) + recoverCli, err := NewWithOptions(ctx, ep, ClientOptions{ + ResponseHeaderTimeout: 80 * time.Millisecond, + MaxAttempts: 5, + }) + if err != nil { + t.Fatal(err) + } + recoverCli = s3.New(recoverCli.Options(), func(o *s3.Options) { + o.Retryer = retry.NewStandard(func(ro *retry.StandardOptions) { + ro.MaxAttempts = 5 + ro.MaxBackoff = 5 * time.Millisecond + }) + }) + out, err := recoverCli.ListObjectsV2(ctx, &s3.ListObjectsV2Input{Bucket: aws.String("writ")}) + if err != nil { + t.Fatalf("expected recovery on attempt 4, got %v", err) + } + if len(out.Contents) != 1 || aws.ToString(out.Contents[0].Key) != "doc.docx" || attempts.Load() != 4 { + t.Fatalf("unexpected output: attempts=%d contents=%+v", attempts.Load(), out.Contents) + } + + // Raising ResponseHeaderTimeout lets even the slow 250ms first page succeed on attempt 1. + attempts.Store(0) + patientCli, err := NewWithOptions(ctx, ep, ClientOptions{ + ResponseHeaderTimeout: time.Second, + MaxAttempts: 1, + }) + if err != nil { + t.Fatal(err) + } + out, err = patientCli.ListObjectsV2(ctx, &s3.ListObjectsV2Input{Bucket: aws.String("writ")}) + if err != nil || len(out.Contents) != 1 || attempts.Load() != 1 { + t.Fatalf("patient header timeout should succeed on attempt 1: attempts=%d err=%v", attempts.Load(), err) + } +} + +func TestRetryQuotaDoesNotExhaustAcrossSustainedTransientTimeouts(t *testing.T) { + var mu sync.Mutex + seen := map[string]bool{} + markFirst := func(k string) bool { + mu.Lock() + defer mu.Unlock() + if seen[k] { + return false + } + seen[k] = true + return true + } + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // Stall the first attempt of every distinct prefix past the 100ms header + // timeout, and answer the retry immediately. Over 64 logical operations + // (64 * 10 = 640 timeout cost > 500 default SDK quota, 0 refunded), the + // SDK's default retry rate limiter would fail later operations. + prefix := r.URL.Query().Get("prefix") + if markFirst(prefix) { + select { + case <-time.After(300 * time.Millisecond): + case <-r.Context().Done(): + return + } + } + w.Header().Set("Content-Type", "application/xml") + _, _ = io.WriteString(w, `writfalse`) + })) + defer srv.Close() + + cli, err := NewWithOptions(context.Background(), config.Endpoint{ + Endpoint: srv.URL, Region: "us-east-1", AccessKey: "a", SecretKey: "b", + }, ClientOptions{ + IdlePerHost: 16, + ResponseHeaderTimeout: 100 * time.Millisecond, + MaxAttempts: 2, + }) + if err != nil { + t.Fatal(err) + } + + const workers = 16 + const perWorker = 4 + errCh := make(chan error, workers*perWorker) + doneCh := make(chan struct{}, workers) + for w := 0; w < workers; w++ { + w := w + go func() { + defer func() { doneCh <- struct{}{} }() + for i := 0; i < perWorker; i++ { + pfx := fmt.Sprintf("w%d-i%d", w, i) + _, err := cli.ListObjectsV2(context.Background(), &s3.ListObjectsV2Input{ + Bucket: aws.String("writ"), + Prefix: aws.String(pfx), + }) + if err != nil { + errCh <- fmt.Errorf("%s: %w", pfx, err) + return + } + } + }() + } + for w := 0; w < workers; w++ { + <-doneCh + } + close(errCh) + for err := range errCh { + t.Fatalf("transient timeout was not retried (retry quota exhausted?): %v", err) + } +} + +func TestCustomCABundleEnvWorksWithPooledTransport(t *testing.T) { + tlsSrv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodHead && r.URL.Path == "/secure-bucket" { + w.WriteHeader(http.StatusOK) + return + } + w.Header().Set("Content-Type", "application/xml") + fmt.Fprint(w, `secure-bucketfalse`) + })) + defer tlsSrv.Close() + + caFile := filepath.Join(t.TempDir(), "ca.pem") + pemBytes := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: tlsSrv.Certificate().Raw}) + if err := os.WriteFile(caFile, pemBytes, 0o600); err != nil { + t.Fatal(err) + } + t.Setenv("AWS_CA_BUNDLE", caFile) + + cli, err := NewWithOptions(context.Background(), config.Endpoint{ + Endpoint: tlsSrv.URL, Region: "us-east-1", AccessKey: "a", SecretKey: "b", + }, ClientOptions{MaxAttempts: 2}) + if err != nil { + t.Fatalf("NewWithOptions failed with AWS_CA_BUNDLE set: %v", err) + } + if _, err := cli.HeadBucket(context.Background(), &s3.HeadBucketInput{Bucket: aws.String("secure-bucket")}); err != nil { + t.Fatalf("HeadBucket over custom-CA TLS failed: %v", err) + } +} + +func TestDefaultTransportTimeouts(t *testing.T) { + tr := pooledTransport(0) + if tr.ResponseHeaderTimeout != 60*time.Second { + t.Fatalf("default ResponseHeaderTimeout = %s, want 60s", tr.ResponseHeaderTimeout) + } +} diff --git a/internal/scanner/scanner.go b/internal/scanner/scanner.go index 8fde573..e32a8c8 100644 --- a/internal/scanner/scanner.go +++ b/internal/scanner/scanner.go @@ -16,6 +16,12 @@ import ( const batchSize = 500 +// Options tunes how source buckets are listed during scan. +type Options struct { + // ListMaxKeys caps each ListObjectsV2 page (1..1000; <= 0 uses default 100). + ListMaxKeys int +} + // Run lists every object in bucket on the source cluster and persists // metadata into the store. Full ListObjectsV2 (S3 has no LastModified // server filter); changes invalidate previous completion for that key. @@ -25,6 +31,11 @@ const batchSize = 500 // concurrency (workers) applies to copy and diff, not to scan. // rate_limit applies to copy body reads only. func Run(ctx context.Context, cli *s3.Client, bucket string, st *store.Store) (int64, error) { + return RunWithOptions(ctx, cli, bucket, st, Options{}) +} + +// RunWithOptions is Run with explicit listing options. +func RunWithOptions(ctx context.Context, cli *s3.Client, bucket string, st *store.Store, opt Options) (int64, error) { bound, err := st.BoundBucket() if err != nil { return 0, err @@ -58,7 +69,7 @@ func Run(ctx context.Context, cli *s3.Client, bucket string, st *store.Store) (i return nil } - walkErr := cluster.WalkObjects(ctx, cli, bucket, func(contents []s3types.Object) error { + walkErr := cluster.WalkObjectsWithMaxKeys(ctx, cli, bucket, opt.ListMaxKeys, func(contents []s3types.Object) error { for _, obj := range contents { o := store.Object{ Key: awsv2.ToString(obj.Key),