~evanj/cms

ref: f4362a4175b569eb2b18199a45525b0022b41478 cms/internal/s/hook/hook.go -rw-r--r-- 2.2 KiB
f4362a41Evan M Jones Fix(db/content.go): Quickfix for broken content search (accidently 4 months 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
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"
	"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(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(space space.Space, content content.Content, ht HookType) {
	var (
		hooks  hook.HookList
		before int
		err    error
		eg     errgroup.Group
		ctx, _ = context.WithTimeout(
			context.Background(),
			10*time.Second, // TODO: May want to lower?
		)
	)

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

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

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

	h.log.Println("webhooks performed successfully for space", space.ID(), space.Name())
}