| 1 | package apperr |
| 2 | |
| 3 | import ( |
| 4 | "sort" |
| 5 | "time" |
| 6 | ) |
| 7 | |
| 8 | // Group is one row of the Errors tab: every record sharing a fingerprint |
| 9 | // in the window, summed (spec §3.6). |
| 10 | type Group struct { |
| 11 | FP string `json:"fp"` |
| 12 | Source string `json:"source"` |
| 13 | Kind string `json:"kind,omitempty"` |
| 14 | Name string `json:"name"` |
| 15 | Level string `json:"level,omitempty"` |
| 16 | Count int `json:"count"` |
| 17 | First time.Time `json:"first"` |
| 18 | Last time.Time `json:"last"` |
| 19 | Hosts []string `json:"hosts"` |
| 20 | Releases []string `json:"releases,omitempty"` |
| 21 | Sample Record `json:"sample"` |
| 22 | } |
| 23 | |
| 24 | // GroupRecords folds records into groups by FP, newest Last first. The |
| 25 | // sample is the earliest record of the group (its stack and fields are |
| 26 | // the first occurrence's). |
| 27 | func GroupRecords(recs []Record) []Group { |
| 28 | byFP := make(map[string]*Group) |
| 29 | var order []string |
| 30 | for _, r := range recs { |
| 31 | first, last := r.First, r.Last |
| 32 | if first.IsZero() { |
| 33 | first = r.TS |
| 34 | } |
| 35 | if last.IsZero() { |
| 36 | last = r.TS |
| 37 | } |
| 38 | count := r.Count |
| 39 | if count == 0 { |
| 40 | count = 1 |
| 41 | } |
| 42 | g := byFP[r.FP] |
| 43 | if g == nil { |
| 44 | g = &Group{FP: r.FP, Source: r.Source, Kind: r.Kind, Name: r.Name, Level: r.Level, First: first, Last: last, Sample: r} |
| 45 | byFP[r.FP] = g |
| 46 | order = append(order, r.FP) |
| 47 | } |
| 48 | g.Count += count |
| 49 | if first.Before(g.First) { |
| 50 | g.First = first |
| 51 | g.Sample = r |
| 52 | } |
| 53 | if last.After(g.Last) { |
| 54 | g.Last = last |
| 55 | } |
| 56 | g.Hosts = addUnique(g.Hosts, r.Host) |
| 57 | g.Releases = addUnique(g.Releases, r.Release) |
| 58 | } |
| 59 | out := make([]Group, 0, len(order)) |
| 60 | for _, fp := range order { |
| 61 | g := byFP[fp] |
| 62 | sort.Strings(g.Hosts) |
| 63 | sort.Strings(g.Releases) |
| 64 | out = append(out, *g) |
| 65 | } |
| 66 | sort.SliceStable(out, func(i, j int) bool { return out[i].Last.After(out[j].Last) }) |
| 67 | return out |
| 68 | } |
| 69 | |
| 70 | func addUnique(list []string, v string) []string { |
| 71 | if v == "" { |
| 72 | return list |
| 73 | } |
| 74 | for _, x := range list { |
| 75 | if x == v { |
| 76 | return list |
| 77 | } |
| 78 | } |
| 79 | return append(list, v) |
| 80 | } |
| 81 | |