~evanj/cms

ref: 4e6befbb576c2e14bcbb5b05e127ae40c9c6073e cms/internal/s/hook/hook.go -rw-r--r-- 2.3 KiB
4e6befbbEvan J Fix(hook service): Hook service was broke for list of hooks. Encapsulate 1 year, 22 days ago
                                                                                
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package hook

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"strings"
	"time"

	"git.sr.ht/~evanj/cms/internal/m/content"
	"git.sr.ht/~evanj/cms/internal/m/hook"
	"git.sr.ht/~evanj/cms/internal/m/space"
	"git.sr.ht/~evanj/cms/internal/m/user"
	"golang.org/x/sync/errgroup"
)

type HookType string

const (
	HookNew    HookType = "created"
	HookUpdate HookType = "modified"
	HookDelete HookType = "removed"
)

type Hook struct {
	log    *log.Logger
	db     dber
	client *http.Client
}

type dber interface {
	HooksPerSpace(user user.User, space space.Space, before int) (hook.HookList, error)
}

func New(log *log.Logger, db dber) *Hook {
	return &Hook{log, db, http.DefaultClient}
}

func (h *Hook) do(ctx context.Context, content content.Content, hook hook.Hook, ht HookType) error {
	var bod bytes.Buffer

	data := make(map[string]interface{})
	data["Type"] = string(ht)
	data["Content"] = content

	bytes, err := json.Marshal(data)
	if err != nil {
		return err
	}
	bod.Write(bytes)

	req, err := http.NewRequestWithContext(ctx, "POST", hook.URL(), &bod)
	if err != nil {
		return err
	}
	req.Header.Set("Content-Type", "application/json")

	resp, err := h.client.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	bytes, err = ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}

	res := strings.TrimSpace(string(bytes))
	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("%s", res)
	}

	return nil
}

func (h *Hook) Do(user user.User, space space.Space, content content.Content, ht HookType) {
	var (
		hooks       hook.HookList
		before      int
		err         error
		eg          errgroup.Group
		ctx, cancel = context.WithTimeout(
			context.Background(),
			10*time.Second, // TODO: May want to lower?
		)
	)
	defer cancel()

	for i := 0; i == 0 || hooks.More(); i++ {
		hooks, err = h.db.HooksPerSpace(user, space, before)
		if err != nil {
			h.log.Println("failed to find webhooks for", space.ID(), space.Name(), err)
			return
		}
		before = hooks.Before()

		for _, item := range hooks.List() {
			func(hook hook.Hook) {
				eg.Go(func() error {
					return h.do(ctx, content, hook, ht)
				})
			}(item)
		}

		if err := eg.Wait(); err != nil {
			h.log.Println("webhooks failed for", space.ID(), space.Name(), err)
			return
		}
	}
}