~sircmpwn/meta.sr.ht

ref: 0.56.17 meta.sr.ht/api/graph/model/webhooks.go -rw-r--r-- 5.4 KiB
b1deacf0Nicolas Schodet Fix field name when validating the PGP key in RegisterAccount 11 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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
package model

import (
	"context"
	"database/sql"
	"fmt"
	"strconv"
	"time"

	"github.com/lib/pq"
	sq "github.com/Masterminds/squirrel"

	"git.sr.ht/~sircmpwn/core-go/database"
	"git.sr.ht/~sircmpwn/core-go/model"
)

type WebhookDelivery struct {
	UUID            string              `json:"uuid"`
	Date            time.Time           `json:"date"`
	Event           WebhookEvent        `json:"event"`
	RequestBody     string              `json:"requestBody"`
	ResponseBody    *string             `json:"responseBody"`
	ResponseHeaders *string             `json:"responseHeaders"`
	ResponseStatus  *int                `json:"responseStatus"`

	ID             int
	SubscriptionID int
	Name           string

	alias  string
	fields *database.ModelFields
}

func (whd *WebhookDelivery) WithName(name string) *WebhookDelivery {
	whd.Name = name
	return whd
}

func (whd *WebhookDelivery) As(alias string) *WebhookDelivery {
	whd.alias = alias
	return whd
}

func (whd *WebhookDelivery) Alias() string {
	return whd.alias
}

func (whd *WebhookDelivery) Table() string {
	return "gql_"+whd.Name+"_wh_delivery"
}

func (whd *WebhookDelivery) Fields() *database.ModelFields {
	if whd.fields != nil {
		return whd.fields
	}
	whd.fields = &database.ModelFields{
		Fields: []*database.FieldMap{
			{ "uuid", "uuid", &whd.UUID },
			{ "date", "date", &whd.Date },
			{ "event", "event", &whd.Event },
			{ "request_body", "requestBody", &whd.RequestBody },
			{ "response_body", "responseBody", &whd.ResponseBody },
			{ "response_headers", "responseHeaders", &whd.ResponseHeaders },
			{ "response_status", "responseStatus", &whd.ResponseStatus },

			// Always fetch:
			{ "id", "", &whd.ID },
			{ "subscription_id", "", &whd.SubscriptionID },
		},
	}
	return whd.fields
}

func (whd *WebhookDelivery) QueryWithCursor(ctx context.Context,
	runner sq.BaseRunner, q sq.SelectBuilder,
	cur *model.Cursor) ([]*WebhookDelivery, *model.Cursor) {
	var (
		err  error
		rows *sql.Rows
	)

	if cur.Next != "" {
		next, _ := strconv.ParseInt(cur.Next, 10, 64)
		q = q.Where(database.WithAlias(whd.alias, "id")+"<= ?", next)
	}
	q = q.
		OrderBy(database.WithAlias(whd.alias, "id") + " DESC").
		Limit(uint64(cur.Count + 1))

	if rows, err = q.RunWith(runner).QueryContext(ctx); err != nil {
		panic(err)
	}
	defer rows.Close()

	var deliveries []*WebhookDelivery
	for rows.Next() {
		var delivery WebhookDelivery
		if err := rows.Scan(database.Scan(ctx, &delivery)...); err != nil {
			panic(err)
		}
		delivery.Name = whd.Name
		deliveries = append(deliveries, &delivery)
	}

	if len(deliveries) > cur.Count {
		cur = &model.Cursor{
			Count:  cur.Count,
			Next:   strconv.Itoa(deliveries[len(deliveries)-1].ID),
			Search: cur.Search,
		}
		deliveries = deliveries[:cur.Count]
	} else {
		cur = nil
	}

	return deliveries, cur
}

type ProfileWebhookSubscription struct {
	ID     int            `json:"id"`
	Events []WebhookEvent `json:"events"`
	Query  string         `json:"query"`
	URL    string         `json:"url"`

	UserID     int
	AuthMethod string
	ClientID   *string
	TokenHash  *string
	Expires    *time.Time
	Grants     *string
	NodeID     *string

	alias  string
	fields *database.ModelFields
}

func (we *WebhookEvent) Scan(src interface{}) error {
	bytes, ok := src.([]uint8)
	if !ok {
		return fmt.Errorf("Unable to scan from %T into WebhookEvent", src)
	}
	*we = WebhookEvent(string(bytes))
	if !we.IsValid() {
		return fmt.Errorf("%s is not a valid WebhookEvent", string(bytes))
	}
	return nil
}

func (ProfileWebhookSubscription) IsWebhookSubscription() {}

func (sub *ProfileWebhookSubscription) As(alias string) *ProfileWebhookSubscription {
	sub.alias = alias
	return sub
}

func (sub *ProfileWebhookSubscription) Alias() string {
	return sub.alias
}

func (sub *ProfileWebhookSubscription) Table() string {
	return "gql_profile_wh_sub"
}

func (sub *ProfileWebhookSubscription) Fields() *database.ModelFields {
	if sub.fields != nil {
		return sub.fields
	}
	sub.fields = &database.ModelFields{
		Fields: []*database.FieldMap{
			{ "events", "events", pq.Array(&sub.Events) },
			{ "url", "url", &sub.URL },

			// Always fetch:
			{ "id", "", &sub.ID },
			{ "query", "", &sub.Query },
			{ "user_id", "", &sub.UserID },
			{ "auth_method", "", &sub.AuthMethod },
			{ "token_hash", "", &sub.TokenHash },
			{ "client_id", "", &sub.ClientID },
			{ "grants", "", &sub.Grants },
			{ "expires", "", &sub.Expires },
			{ "node_id", "", &sub.NodeID },
		},
	}
	return sub.fields
}

func (sub *ProfileWebhookSubscription) QueryWithCursor(ctx context.Context,
	runner sq.BaseRunner, q sq.SelectBuilder,
	cur *model.Cursor) ([]WebhookSubscription, *model.Cursor) {
	var (
		err  error
		rows *sql.Rows
	)

	if cur.Next != "" {
		next, _ := strconv.ParseInt(cur.Next, 10, 64)
		q = q.Where(database.WithAlias(sub.alias, "id")+"<= ?", next)
	}
	q = q.
		OrderBy(database.WithAlias(sub.alias, "id")).
		Limit(uint64(cur.Count + 1))

	if rows, err = q.RunWith(runner).QueryContext(ctx); err != nil {
		panic(err)
	}
	defer rows.Close()

	var (
		subs   []WebhookSubscription
		lastID int
	)
	for rows.Next() {
		var sub ProfileWebhookSubscription
		if err := rows.Scan(database.Scan(ctx, &sub)...); err != nil {
			panic(err)
		}
		subs = append(subs, &sub)
		lastID = sub.ID
	}

	if len(subs) > cur.Count {
		cur = &model.Cursor{
			Count:  cur.Count,
			Next:   strconv.Itoa(lastID),
			Search: cur.Search,
		}
		subs = subs[:cur.Count]
	} else {
		cur = nil
	}

	return subs, cur
}