aboutsummaryrefslogtreecommitdiff
path: root/network/receivepack/hooks/chain.go
blob: f98c06f86a51dd70a419fb1516430233ad6b2d16 (about) (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package hooks

import (
	"context"
	"fmt"

	receivepack "codeberg.org/lindenii/furgit/network/receivepack"
)

// Chain combines hooks by running them in order and intersecting their
// decisions. The first rejecting message for each update is preserved.
func Chain(hooks ...receivepack.Hook) receivepack.Hook {
	return func(
		ctx context.Context,
		req receivepack.HookRequest,
	) ([]receivepack.UpdateDecision, error) {
		decisions := make([]receivepack.UpdateDecision, len(req.Updates))
		for i := range decisions {
			decisions[i].Accept = true
		}

		for _, hook := range hooks {
			if hook == nil {
				continue
			}

			hookDecisions, err := hook(ctx, req)
			if err != nil {
				return nil, err
			}

			if len(hookDecisions) != len(req.Updates) {
				return nil, fmt.Errorf("hook returned %d decisions for %d updates", len(hookDecisions), len(req.Updates))
			}

			for i, decision := range hookDecisions {
				if decision.Accept {
					continue
				}

				if decisions[i].Accept {
					decisions[i].Message = decision.Message
				}

				decisions[i].Accept = false
			}
		}

		return decisions, nil
	}
}