| 1 | package sessioncatalog |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "slices" |
| 7 | "sort" |
| 8 | "strings" |
| 9 | |
| 10 | "reasonix/internal/agent" |
| 11 | ) |
| 12 | |
| 13 | type repairBatchGeneration struct { |
| 14 | contentFingerprint string |
| 15 | metaFingerprint string |
| 16 | locked bool |
| 17 | } |
| 18 | |
| 19 | func lockRepairBatchGenerations(ctx context.Context, outcomes []repairOutcome) ([]repairBatchGeneration, func(), error) { |
| 20 | generations := make([]repairBatchGeneration, len(outcomes)) |
| 21 | order := make([]int, 0, len(outcomes)) |
| 22 | for index := range outcomes { |
| 23 | if outcomes[index].result.ContentFingerprint != "" || outcomes[index].result.MetaFingerprint != "" { |
| 24 | order = append(order, index) |
| 25 | } |
| 26 | } |
| 27 | sort.Slice(order, func(i, j int) bool { |
| 28 | return agent.CanonicalSessionPath(outcomes[order[i]].item.path) < agent.CanonicalSessionPath(outcomes[order[j]].item.path) |
| 29 | }) |
| 30 | |
| 31 | unlocks := make([]func(), 0, len(order)) |
| 32 | release := func() { |
| 33 | for _, unlock := range slices.Backward(unlocks) { |
| 34 | unlock() |
| 35 | } |
| 36 | } |
| 37 | for _, index := range order { |
| 38 | if err := ctx.Err(); err != nil { |
| 39 | release() |
| 40 | return nil, func() {}, err |
| 41 | } |
| 42 | generation, unlock, err := agent.TryLockSessionListingGeneration(outcomes[index].item.path) |
| 43 | if err != nil { |
| 44 | outcomes[index].err = errors.Join(outcomes[index].err, err) |
| 45 | continue |
| 46 | } |
| 47 | generations[index] = repairBatchGeneration{ |
| 48 | contentFingerprint: generation.ContentFingerprint, |
| 49 | metaFingerprint: generation.MetaFingerprint, |
| 50 | locked: true, |
| 51 | } |
| 52 | unlocks = append(unlocks, unlock) |
| 53 | } |
| 54 | return generations, release, nil |
| 55 | } |
| 56 | |
| 57 | func repairBatchFingerprints(outcome repairOutcome, generation repairBatchGeneration) (string, string) { |
| 58 | if generation.locked { |
| 59 | return generation.contentFingerprint, generation.metaFingerprint |
| 60 | } |
| 61 | contentFingerprint, metaFingerprint, _ := strings.Cut(outcome.item.sourceFingerprint, "\x00") |
| 62 | return contentFingerprint, metaFingerprint |
| 63 | } |
| 64 |