~bigbes/core-go

ref: bdf079e6a8893909e73c6183c0e8a066ab368e45 core-go/server/email.go -rw-r--r-- 2.2 KiB
bdf079e6 — Conrad Hoffmann auth: grant scoped access to anon internal auth 1 year, 8 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
package server

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"log"
	"runtime/debug"
	"strings"

	"github.com/99designs/gqlgen/graphql"
	"github.com/emersion/go-message/mail"

	"git.sr.ht/~sircmpwn/core-go/auth"
	"git.sr.ht/~sircmpwn/core-go/config"
	"git.sr.ht/~sircmpwn/core-go/email"
)

// Provides a graphql.RecoverFunc which will print the stack trace, and if
// debug mode is not enabled, email it to the administrator.
func EmailRecover(ctx context.Context, _origErr interface{}) error {
	origErr, ok := _origErr.(error)
	if !ok {
		log.Printf("Unexpected error in recover: %v\n", origErr)
		return fmt.Errorf("internal system error")
	}

	log.Println(origErr)

	if errors.Is(origErr, context.Canceled) {
		return origErr
	}

	if errors.Is(origErr, context.DeadlineExceeded) {
		return origErr
	}

	if origErr.Error() == "pq: canceling statement due to user request" {
		return origErr
	}

	stack := string(debug.Stack())
	log.Println(stack)
	if config.Debug {
		return fmt.Errorf("internal system error")
	}

	var header mail.Header
	header.SetSubject(fmt.Sprintf("[%s] GraphQL query error: %v",
		config.ServiceName(ctx), origErr))

	conf := config.ForContext(ctx)
	to, _ := conf.Get("mail", "error-to")
	if to == "" {
		log.Println("Warning: mail::error-to is not set")
		return fmt.Errorf("internal system error")
	}
	rcpt, err := mail.ParseAddress(to)
	if err != nil {
		log.Printf("Warning: mail::error-to is invalid: %v", err)
		return fmt.Errorf("internal system error")
	}
	header.SetAddressList("To", []*mail.Address{rcpt})

	var reader io.Reader
	func() {
		defer func() {
			if err := recover(); err != nil {
				reader = strings.NewReader(fmt.Sprintf(`An error occured outside of the GraphQL context:

				%s`, stack))
			}
		}()
		quser := auth.ForContext(ctx)
		octx := graphql.GetOperationContext(ctx)
		vars, _ := json.Marshal(octx.Variables)
		reader = strings.NewReader(
			fmt.Sprintf(`Error occured processing GraphQL request:

%v

When running the following query on behalf of %s <%s>:

%s

With these variables:

%s

The following stack trace was produced:

%s`, origErr, quser.Username, quser.Email, octx.RawQuery,
				string(vars), stack))
	}()

	email.EnqueueStd(ctx, header, reader, nil)
	return fmt.Errorf("internal system error")
}