-
Notifications
You must be signed in to change notification settings - Fork 1
/
twirp.go
101 lines (80 loc) · 2.07 KB
/
twirp.go
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
package elephantine
import (
"context"
"errors"
"log/slog"
"net/http"
"github.com/twitchtv/twirp"
)
// IsTwirpErrorCode checks if any error in the tree is a twirp.Error with the
// given error code.
func IsTwirpErrorCode(err error, code twirp.ErrorCode) bool {
if err == nil {
return false
}
var te twirp.Error
if errors.As(err, &te) {
return te.Code() == code
}
return false
}
// TwirpErrorToHTTPStatusCode returns the HTTP status code for the given
// error. If the error is nil 200 will be returned, if the error isn't a
// twirp.Error 500 will be returned.
func TwirpErrorToHTTPStatusCode(err error) int {
if err == nil {
return http.StatusOK
}
var te twirp.Error
if errors.As(err, &te) {
return twirp.ServerHTTPStatusFromErrorCode(te.Code())
}
return http.StatusInternalServerError
}
// LoggingHooks creaes a twirp.ServerHooks that will set log metadata for the
// twirp service and method name, and log error responses.
func LoggingHooks(
logger *slog.Logger, scopesFunc func(context.Context) string,
) *twirp.ServerHooks {
hooks := twirp.ServerHooks{
RequestRouted: func(ctx context.Context) (context.Context, error) {
service, ok := twirp.ServiceName(ctx)
if ok {
SetLogMetadata(ctx, LogKeyService, service)
}
method, ok := twirp.MethodName(ctx)
if ok {
SetLogMetadata(ctx, LogKeyMethod, method)
}
return ctx, nil
},
Error: func(ctx context.Context, err twirp.Error) context.Context {
code := err.Code()
status := twirp.ServerHTTPStatusFromErrorCode(err.Code())
args := []any{
LogKeyErrorCode, code,
LogKeyError, err.Msg(),
LogKeyStatusCode, status,
}
meta := err.MetaMap()
if meta != nil {
args = append(args,
LogKeyErrorMeta, err.MetaMap())
}
if code == twirp.PermissionDenied {
args = append(args,
LogKeyScopes, scopesFunc(ctx))
}
level := slog.LevelWarn
switch {
case status == 400:
level = slog.LevelInfo
case status >= 500:
level = slog.LevelError
}
logger.Log(ctx, level, "error response", args...)
return ctx
},
}
return &hooks
}