Repository navigation
Expand file tree
/
Copy pathgmailapi.go
More file actions
308 lines (281 loc) · 11.1 KB
/
Copy pathgmailapi.go
File metadata and controls
308 lines (281 loc) · 11.1 KB
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
// Package gmailapi is the Gmail REST API client the Gmail-API-mode backend is
// built on (GMAIL_API_PLAN.md, D-API-2/D-API-7). It wraps the official
// google.golang.org/api/gmail/v1 generated client with the pieces that client
// lacks: a quota pacer, an error taxonomy that speaks the backend-neutral
// mailbackend vocabulary, and a hand-rolled batch endpoint (google-api-go-client
// #179). OAuth2 is not re-implemented here — TokenSourceFromManager bridges the
// project's existing internal/oauth.Manager into golang.org/x/oauth2.
//
// Generated *gmail.* types never leave this package: the thin operations below
// are unexported so the M10 adapter (also in this package) can use them while no
// caller can name a google type. All calls are context-aware and every network
// call is classified and paced.
package gmailapi
import (
"context"
"errors"
"net/http"
"strings"
"time"
"golang.org/x/oauth2"
"google.golang.org/api/gmail/v1"
"google.golang.org/api/googleapi"
"google.golang.org/api/option"
"github.com/CaffeinatedTech/jmap-bridge/internal/mailbackend"
)
// userMe is Gmail's alias for the authenticated user; API mode is one account,
// one token, so "me" is always the right principal.
const userMe = "me"
// Options configures a Client. Exactly one of TokenSource or HTTPClient is
// required; TokenSource is the production path (see TokenSourceFromManager).
type Options struct {
// TokenSource authenticates every request. It is wrapped in an
// oauth2-authenticated http.Client.
TokenSource oauth2.TokenSource
// Reauthorize forces a fresh access token after a 401. When set, the
// client retries the refused call exactly once with the new token
// (FR-A.7); when nil (static/fixture bearers), a 401 is final. This is
// what lets a merely-stale cached token self-heal instead of looking
// like a dead refresh token until the process restarts.
Reauthorize func(ctx context.Context) error
// HTTPClient is a pre-authenticated client, used by tests that inject a
// static bearer token. It wins when both are set.
HTTPClient *http.Client
// Endpoint overrides the API base URL; empty means Google's default. Only
// the fixture tests set it (GMAIL_API_PLAN §4.1 keeps the endpoint
// non-configurable in production).
Endpoint string
// QuotaUnitsPerSecond paces requests; 0 selects DefaultQuotaUnitsPerSecond.
// Negative disables pacing.
QuotaUnitsPerSecond int
// MaxRetries bounds retries of a retryable failure; 0 selects
// DefaultMaxRetries.
MaxRetries int
// Clock overrides the time source for pacing and backoff; tests inject a
// fake to stay deterministic. Nil selects the real clock.
Clock Clock
}
// Client is one account's Gmail API client. It is safe for concurrent use by
// net/http's transport, but the engine serialises calls per account (PLAN §10).
type Client struct {
svc *gmail.Service
httpClient *http.Client
base string
pacer *Pacer
maxRetries int
reauthorize func(context.Context) error
clock Clock
}
// New builds a client. It fails closed on missing credentials or a bad endpoint
// rather than making an unauthenticated request.
func New(ctx context.Context, opts Options) (*Client, error) {
hc := opts.HTTPClient
if hc == nil {
if opts.TokenSource == nil {
return nil, errors.New("gmailapi: Options needs TokenSource or HTTPClient")
}
// Deliberately not oauth2.NewClient: that wraps the source in a
// ReuseTokenSource which caches the first bearer. Our source returns a
// token with no Expiry, which oauth2.Token.Valid treats as valid
// forever, so the cache pinned a stale token past the point Google
// rejected it and a forced refresh (Reauthorize) never reached the
// wire — the account stayed wedged on 401s until restart. A bare
// oauth2.Transport consults the manager on every request, so refresh
// is governed by internal/oauth and the 401 retry sees the new token.
hc = &http.Client{Transport: &oauth2.Transport{Source: opts.TokenSource}}
}
clientOpts := []option.ClientOption{option.WithHTTPClient(hc)}
if opts.Endpoint != "" {
clientOpts = append(clientOpts, option.WithEndpoint(strings.TrimRight(opts.Endpoint, "/")+"/"))
}
svc, err := gmail.NewService(ctx, clientOpts...)
if err != nil {
return nil, err
}
rate := opts.QuotaUnitsPerSecond
if rate == 0 {
rate = DefaultQuotaUnitsPerSecond
}
retries := opts.MaxRetries
if retries == 0 {
retries = DefaultMaxRetries
}
clock := opts.Clock
if clock == nil {
clock = realClock{}
}
return &Client{
svc: svc,
httpClient: hc,
base: svc.BasePath,
pacer: NewPacer(rate, clock),
maxRetries: retries,
reauthorize: opts.Reauthorize,
clock: clock,
}, nil
}
// Close releases idle connections the client opened.
func (c *Client) Close() error {
c.httpClient.CloseIdleConnections()
return nil
}
// BasePath returns the API base URL the client targets (Google's default, or
// the fixture endpoint in tests).
func (c *Client) BasePath() string { return c.base }
// batchURL is the Gmail batch endpoint on the same origin as the API (D-13).
func (c *Client) batchURL() string {
return strings.TrimRight(c.base, "/") + "/batch/gmail/v1"
}
// apiCall is the shape every generated method call shares: a Do that returns
// the typed response and a Header accessor. It lets one generic helper pace,
// retry and classify every call.
type apiCall[T any] interface {
Do(...googleapi.CallOption) (T, error)
Header() http.Header
}
// invoke runs one generated call under the pacer, retrying throttles and
// transient failures with backoff and returning the classified error otherwise.
// A 401 gets exactly one extra attempt after a forced token refresh (FR-A.7):
// the cached access token may have been invalidated before its nominal expiry.
func invoke[T any, C apiCall[T]](ctx context.Context, c *Client, cost int, call C) (T, error) {
var zero T
reauthorized := false
for attempt := 0; ; attempt++ {
if err := c.pacer.Wait(ctx, cost); err != nil {
return zero, err
}
v, err := call.Do()
if err == nil {
return v, nil
}
classified := classify(err)
if errors.Is(classified, mailbackend.ErrAuth) && !reauthorized && c.reauthorize != nil {
reauthorized = true
if rerr := c.reauthorize(ctx); rerr != nil {
return zero, rerr
}
continue
}
if attempt >= c.maxRetries || !retryable(classified) {
return zero, classified
}
if serr := c.clock.Sleep(ctx, backoffDelay(err, attempt, c.clock.Now())); serr != nil {
return zero, serr
}
}
}
// invokeOnce paces and classifies one call without retrying. Send uses it:
// a retried send can duplicate a message whose response was lost, so an
// ambiguous outcome is reconciled by Message-ID instead (GMAIL_API_PLAN
// §8.1). A 401 is exempt: the provider never processed an unauthenticated
// request, so one retry after a forced refresh is safe and keeps a stale
// cached token from failing sends.
func invokeOnce[T any, C apiCall[T]](ctx context.Context, c *Client, cost int, call C) (T, error) {
var zero T
if err := c.pacer.Wait(ctx, cost); err != nil {
return zero, err
}
v, err := call.Do()
if err == nil {
return v, nil
}
classified := classify(err)
if errors.Is(classified, mailbackend.ErrAuth) && c.reauthorize != nil {
if rerr := c.reauthorize(ctx); rerr != nil {
return zero, rerr
}
if err := c.pacer.Wait(ctx, cost); err != nil {
return zero, err
}
v, err = call.Do()
if err == nil {
return v, nil
}
classified = classify(err)
}
return zero, classified
}
// --- thin typed operations (unexported: generated types stay in this package) ---
func (c *Client) profile(ctx context.Context) (*gmail.Profile, error) {
return invoke(ctx, c, CostGetProfile, c.svc.Users.GetProfile(userMe).Context(ctx))
}
func (c *Client) listLabels(ctx context.Context) (*gmail.ListLabelsResponse, error) {
return invoke(ctx, c, CostLabelsList, c.svc.Users.Labels.List(userMe).Context(ctx))
}
func (c *Client) listMessages(ctx context.Context, query string, labelIDs []string, max int64, pageToken string) (*gmail.ListMessagesResponse, error) {
return c.listMessagesPage(ctx, listOpts{
Query: query, LabelIDs: labelIDs, Max: max, PageToken: pageToken,
})
}
// listOpts is the full messages.list parameter set; the adapter uses
// IncludeSpamTrash so the synthetic All Mail container is truthful.
type listOpts struct {
Query string
LabelIDs []string
Max int64
PageToken string
IncludeSpamTrash bool
}
func (c *Client) listMessagesPage(ctx context.Context, o listOpts) (*gmail.ListMessagesResponse, error) {
call := c.svc.Users.Messages.List(userMe).Context(ctx)
if o.Query != "" {
call = call.Q(o.Query)
}
if len(o.LabelIDs) > 0 {
call = call.LabelIds(o.LabelIDs...)
}
if o.Max > 0 {
call = call.MaxResults(o.Max)
}
if o.PageToken != "" {
call = call.PageToken(o.PageToken)
}
if o.IncludeSpamTrash {
call = call.IncludeSpamTrash(true)
}
return invoke(ctx, c, CostMessagesList, call)
}
// messageFormat is the subset of gmail's format parameter API mode uses.
type messageFormat string
const (
formatMetadata messageFormat = "metadata"
formatRaw messageFormat = "raw"
)
func (c *Client) getMessage(ctx context.Context, id string, format messageFormat, metadataHeaders ...string) (*gmail.Message, error) {
call := c.svc.Users.Messages.Get(userMe, id).Format(string(format)).Context(ctx)
if len(metadataHeaders) > 0 {
call = call.MetadataHeaders(metadataHeaders...)
}
return invoke(ctx, c, CostMessagesGet, call)
}
func (c *Client) modifyMessage(ctx context.Context, id string, add, remove []string) (*gmail.Message, error) {
req := &gmail.ModifyMessageRequest{AddLabelIds: add, RemoveLabelIds: remove}
return invoke(ctx, c, CostMessagesModify, c.svc.Users.Messages.Modify(userMe, id, req).Context(ctx))
}
func (c *Client) listHistory(ctx context.Context, startHistoryID uint64, pageToken string) (*gmail.ListHistoryResponse, error) {
call := c.svc.Users.History.List(userMe).StartHistoryId(startHistoryID).MaxResults(500).Context(ctx)
if pageToken != "" {
call = call.PageToken(pageToken)
}
return invoke(ctx, c, CostHistoryList, call)
}
// watch registers a Cloud Pub/Sub push for the account (M13, FR-S.14). The
// topic must already exist and grant gmail-api-push@system.gserviceaccount.com
// publish; the response carries the watch's expiration, which the adapter
// renews against.
func (c *Client) watch(ctx context.Context, topic string) (*gmail.WatchResponse, error) {
req := &gmail.WatchRequest{TopicName: topic}
return invoke(ctx, c, CostWatch, c.svc.Users.Watch(userMe, req).Context(ctx))
}
// stop cancels the account's push watch (users.stop). It is called on
// graceful shutdown; Google also expires the watch on its own. It is a
// best-effort shutdown call, so it paces and classifies but does not retry.
func (c *Client) stop(ctx context.Context) error {
if err := c.pacer.Wait(ctx, CostStop); err != nil {
return err
}
return classify(c.svc.Users.Stop(userMe).Context(ctx).Do())
}
// now returns the client's current time (the injected clock in tests), so
// renewal scheduling is deterministic where the clock is faked.
func (c *Client) now() time.Time { return c.clock.Now() }