|
| 1 | +package decorator |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "strings" |
| 7 | + "time" |
| 8 | +) |
| 9 | + |
| 10 | +type MetricsClient interface { |
| 11 | + Inc(key string, value int) |
| 12 | +} |
| 13 | + |
| 14 | +type commandMetricsDecorator[C any] struct { |
| 15 | + base CommandHandler[C] |
| 16 | + client MetricsClient |
| 17 | +} |
| 18 | + |
| 19 | +func (d commandMetricsDecorator[C]) Handle(ctx context.Context, cmd C) (err error) { |
| 20 | + start := time.Now() |
| 21 | + |
| 22 | + actionName := strings.ToLower(generateActionName(cmd)) |
| 23 | + |
| 24 | + defer func() { |
| 25 | + end := time.Since(start) |
| 26 | + |
| 27 | + d.client.Inc(fmt.Sprintf("commands.%s.duration", actionName), int(end.Seconds())) |
| 28 | + |
| 29 | + if err == nil { |
| 30 | + d.client.Inc(fmt.Sprintf("commands.%s.success", actionName), 1) |
| 31 | + } else { |
| 32 | + d.client.Inc(fmt.Sprintf("commands.%s.failure", actionName), 1) |
| 33 | + } |
| 34 | + }() |
| 35 | + |
| 36 | + return d.base.Handle(ctx, cmd) |
| 37 | +} |
| 38 | + |
| 39 | +type queryMetricsDecorator[C any, R any] struct { |
| 40 | + base QueryHandler[C, R] |
| 41 | + client MetricsClient |
| 42 | +} |
| 43 | + |
| 44 | +func (d queryMetricsDecorator[C, R]) Handle(ctx context.Context, query C) (result R, err error) { |
| 45 | + start := time.Now() |
| 46 | + |
| 47 | + actionName := strings.ToLower(generateActionName(query)) |
| 48 | + |
| 49 | + defer func() { |
| 50 | + end := time.Since(start) |
| 51 | + |
| 52 | + d.client.Inc(fmt.Sprintf("querys.%s.duration", actionName), int(end.Seconds())) |
| 53 | + |
| 54 | + if err == nil { |
| 55 | + d.client.Inc(fmt.Sprintf("querys.%s.success", actionName), 1) |
| 56 | + } else { |
| 57 | + d.client.Inc(fmt.Sprintf("querys.%s.failure", actionName), 1) |
| 58 | + } |
| 59 | + }() |
| 60 | + |
| 61 | + return d.base.Handle(ctx, query) |
| 62 | +} |
0 commit comments