Match returns matched stage.
(ctx context.Context, event *Event)
| 124 | |
| 125 | // Match returns matched stage. |
| 126 | func (s Lifecycle) Match(ctx context.Context, event *Event) (*Stage, error) { |
| 127 | stages, err := s.match(ctx, event) |
| 128 | if err != nil { |
| 129 | return nil, err |
| 130 | } |
| 131 | if len(stages) == 0 { |
| 132 | return nil, nil |
| 133 | } |
| 134 | if len(stages) == 1 { |
| 135 | return stages[0], nil |
| 136 | } |
| 137 | |
| 138 | var weights = make([]int64, 0, len(stages)) |
| 139 | var totalWeights int64 |
| 140 | var countError int |
| 141 | for _, stage := range stages { |
| 142 | w, ok, err := stage.Weight(ctx, event) |
| 143 | if err != nil { |
| 144 | return nil, err |
| 145 | } |
| 146 | if ok { |
| 147 | totalWeights += w |
| 148 | weights = append(weights, w) |
| 149 | } else { |
| 150 | weights = append(weights, -1) |
| 151 | countError++ |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | if countError == len(stages) { |
| 156 | //nolint:gosec |
| 157 | return stages[rand.Intn(len(stages))], nil |
| 158 | } |
| 159 | |
| 160 | if totalWeights == 0 { |
| 161 | if countError == 0 { |
| 162 | //nolint:gosec |
| 163 | return stages[rand.Intn(len(stages))], nil |
| 164 | } |
| 165 | |
| 166 | stagesWithWeights := make([]*Stage, 0, len(stages)) |
| 167 | for i, stage := range stages { |
| 168 | if weights[i] < 0 { |
| 169 | continue |
| 170 | } |
| 171 | stagesWithWeights = append(stagesWithWeights, stage) |
| 172 | } |
| 173 | |
| 174 | //nolint:gosec |
| 175 | off := rand.Intn(len(stagesWithWeights)) |
| 176 | return stagesWithWeights[off], nil |
| 177 | } |
| 178 | |
| 179 | //nolint:gosec |
| 180 | off := rand.Int63n(totalWeights) |
| 181 | for i, stage := range stages { |
| 182 | if weights[i] <= 0 { |
| 183 | continue |