|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "flag" |
| 6 | + "log" |
| 7 | + chpkg "go-backfill/clickhouse" |
| 8 | + "go-backfill/config" |
| 9 | + "go-backfill/repository" |
| 10 | +) |
| 11 | + |
| 12 | +func main() { |
| 13 | + envFile := flag.String("env", ".env", "Path to the .env file") |
| 14 | + batch := flag.Int("batch", 5000, "Batch size") |
| 15 | + flag.Parse() |
| 16 | + |
| 17 | + config.InitEnv(*envFile) |
| 18 | + chpkg.LoadCHEnv(*envFile) |
| 19 | + |
| 20 | + env := config.GetConfig() |
| 21 | + if chpkg.GetCHConfig().ClickHouseURL == "" { |
| 22 | + log.Fatal("CLICKHOUSE_URL not set; aborting repair") |
| 23 | + } |
| 24 | + |
| 25 | + pool := config.InitDatabase() |
| 26 | + defer pool.Close() |
| 27 | + |
| 28 | + ch, err := chpkg.NewClient(chpkg.GetCHConfig()) |
| 29 | + if err != nil { |
| 30 | + log.Fatalf("clickhouse connect: %v", err) |
| 31 | + } |
| 32 | + if err := chpkg.EnsureDDL(context.Background(), ch); err != nil { |
| 33 | + log.Fatalf("clickhouse DDL: %v", err) |
| 34 | + } |
| 35 | + |
| 36 | + var lastTdID int64 = 0 |
| 37 | + for { |
| 38 | + rows, err := repository.FetchUnindexedBatch(pool, lastTdID, *batch) |
| 39 | + if err != nil { |
| 40 | + log.Fatalf("fetch batch: %v", err) |
| 41 | + } |
| 42 | + if len(rows) == 0 { |
| 43 | + log.Println("repair complete") |
| 44 | + return |
| 45 | + } |
| 46 | + |
| 47 | + payload := make([]chpkg.TxCodeRow, 0, len(rows)) |
| 48 | + tdIDs := make([]int64, 0, len(rows)) |
| 49 | + for _, r := range rows { |
| 50 | + code, _ := chpkg.MarshalCode(r.Code) |
| 51 | + payload = append(payload, chpkg.TxCodeRow{ |
| 52 | + ID: uint64(r.TxID), |
| 53 | + RequestKey: r.RequestKey, |
| 54 | + ChainID: uint16(r.ChainID), |
| 55 | + CreationTime: uint64(parseUint64(r.CreationTime)), |
| 56 | + Height: uint64(r.Height), |
| 57 | + Canonical: boolToUint8(r.Canonical), |
| 58 | + Sender: r.Sender, |
| 59 | + Gas: r.Gas, |
| 60 | + GasLimit: r.GasLimit, |
| 61 | + GasPrice: r.GasPrice, |
| 62 | + Code: code, |
| 63 | + }) |
| 64 | + tdIDs = append(tdIDs, r.TdID) |
| 65 | + lastTdID = r.TdID |
| 66 | + } |
| 67 | + |
| 68 | + if err := chpkg.BulkInsert(context.Background(), ch, payload); err != nil { |
| 69 | + log.Printf("[CH][INSERT][ERROR] %v", err) |
| 70 | + continue |
| 71 | + } |
| 72 | + if err := repository.MarkIndexedByTdIDs(pool, tdIDs); err != nil { |
| 73 | + log.Printf("[PG][FLAG][ERROR] %v", err) |
| 74 | + } |
| 75 | + log.Printf("indexed %d rows up to td.id=%d", len(rows), lastTdID) |
| 76 | + if env.IsSingleChain { |
| 77 | + break |
| 78 | + } |
| 79 | + } |
| 80 | +} |
| 81 | + |
| 82 | +func parseUint64(s string) uint64 { |
| 83 | + var out uint64 |
| 84 | + for i := 0; i < len(s); i++ { |
| 85 | + out = out*10 + uint64(s[i]-'0') |
| 86 | + } |
| 87 | + return out |
| 88 | +} |
| 89 | + |
| 90 | +func boolToUint8(b bool) uint8 { if b { return 1 }; return 0 } |
| 91 | + |
| 92 | + |
0 commit comments