github.com/TrueBlocks/trueblocks-core/src/apps/chifra@v0.0.0-20241022031540-b362680128f7/pkg/manifest/remove_chunk.go (about) 1 package manifest 2 3 import ( 4 "os" 5 6 "github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/base" 7 "github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/config" 8 "github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/file" 9 "github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/types" 10 ) 11 12 // RemoveChunk must remove the underlying chunk (both Bloom filter and the chunk itself) and 13 // update the manifest by removing all chunks at or after the given path. Note that if this 14 // function aborts due to error and the backup files still exist, the function will attempt 15 // to restore the backup files before returning. 16 func RemoveChunk(chain string, publisher base.Address, bloomFn, indexFn string) (err error) { 17 manifestFn := config.PathToManifest(chain) 18 19 manifestBackup := manifestFn + ".backup" 20 indexBackup := indexFn + ".backup" 21 bloomBackup := bloomFn + ".backup" 22 23 defer func() { 24 if err != nil { 25 // If the backup files still exist when the function ends, something went wrong, reset everything 26 if file.FileExists(manifestBackup) { 27 _, _ = file.Copy(manifestFn, manifestBackup) 28 _ = os.Remove(manifestBackup) 29 } 30 if file.FileExists(indexBackup) { 31 _, _ = file.Copy(indexFn, indexBackup) 32 _ = os.Remove(indexBackup) 33 } 34 if file.FileExists(bloomBackup) { 35 _, _ = file.Copy(bloomFn, bloomBackup) 36 _ = os.Remove(bloomBackup) 37 } 38 } 39 }() 40 41 var man *Manifest 42 man, err = LoadManifest(chain, publisher, LocalCache) 43 if err != nil { 44 return err 45 } 46 47 if _, err = file.Copy(manifestBackup, manifestFn); err != nil { 48 return err 49 } 50 51 if _, err = file.Copy(indexBackup, indexFn); err != nil { 52 return err 53 } 54 55 if _, err = file.Copy(bloomBackup, bloomFn); err != nil { 56 return err 57 } 58 59 if err := os.Remove(indexFn); err != nil { 60 return err 61 } 62 63 if err := os.Remove(bloomFn); err != nil { 64 return err 65 } 66 67 removedRange, err1 := base.RangeFromFilenameE(bloomFn) 68 if err1 != nil { 69 err = err1 70 return err 71 } 72 73 newChunks := []types.ChunkRecord{} 74 for _, chunk := range man.Chunks { 75 chunkRange := base.RangeFromRangeString(chunk.Range) 76 if chunkRange.EarlierThan(removedRange) { 77 newChunks = append(newChunks, chunk) 78 // fmt.Println(colors.Green, "Keeping", chunk.Range, colors.Off) 79 // } else { 80 // fmt.Println(colors.Red, "Removing", chunk.Range, colors.Off) 81 } 82 } 83 man.Chunks = newChunks 84 if err = man.SaveManifest(chain, config.PathToManifest(chain)); err != nil { 85 return err 86 } 87 88 os.Remove(manifestBackup) 89 os.Remove(indexBackup) 90 os.Remove(bloomBackup) 91 92 return nil 93 }