mirror of
https://github.com/warmbly/warmbly.git
synced 2026-11-28 08:05:45 +00:00
* feat: run a narrow check (Graph inbox and junk delta, IMAP INBOX and junk from their cursors, Gmail history only) on a push or IDLE wake at most every 30 seconds while the full sync pass keeps its own timer, and resolve each Graph delta page and Gmail history page through one batched message-map lookup including the immutable-id regular fallback * feat: give every mailbox without a live push channel or IMAP IDLE watch a jittered 5-minute narrow check (Graph inbox and junk, IMAP INBOX and junk, Gmail history) that starts the moment IDLE drops or a push channel lapses and stops when the signal is back * feat: run every mailbox's full sync check every 15 to 60 minutes scaled by mailboxes held against the plan allowance (operator-editable sync.full_check_min_minutes and full_check_max_minutes, shipped as SyncPolicy.full_check_seconds with seeds and pool-linked mailboxes kept at one minute), give errors their own backoff in nextSyncDelay, retire SYNC_PUSH_FALLBACK_INTERVAL, and widen the sync_stale monitor and provider hold recovery freshness windows to match * feat: document that mailboxes without push or IDLE see new mail within about 5 minutes through the narrow check while every folder gets the 15 to 60 minute full check, in the mailboxes guide, realtime mailbox sync, configuration and architecture pages, and list the narrow poll interval under effective limits * feat: keep the full sync pass on a one-minute catch-up cadence while an import or Graph, Gmail or IMAP recovery is unfinished and pull it forward when a narrow check meets such work, add a 15-minute safety narrow check behind live push channels, treat a zero mailbox allowance with mailboxes held as the slowest full check, widen the stale backfill monitor to the full check window, and correct the IMAP_IDLE admin text
229 lines
8.1 KiB
Go
229 lines
8.1 KiB
Go
// Package msgraph is a thin Microsoft Graph mail client for Warmbly's
|
|
// Outlook/Microsoft 365 mailboxes. It mirrors the shape of internal/client/goog
|
|
// (the Gmail API client): a per-mailbox Client with OnMessage* callbacks, an
|
|
// OAuth2 token source that persists refreshes, RAW MIME sending, delta-based
|
|
// inbound sync, and warmup mailbox actions. It deliberately hand-rolls a small
|
|
// REST surface (~a dozen endpoints) instead of pulling in the very large
|
|
// official SDK, which would bloat the disposable worker binary and slow CI.
|
|
package msgraph
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"net/url"
|
|
"sync"
|
|
|
|
"github.com/rs/zerolog/log"
|
|
"github.com/warmbly/warmbly/internal/errx"
|
|
"github.com/warmbly/warmbly/internal/infrastructure/cache"
|
|
"github.com/warmbly/warmbly/internal/pkg/mailauth"
|
|
"github.com/warmbly/warmbly/internal/pkg/stoken"
|
|
"golang.org/x/oauth2"
|
|
)
|
|
|
|
const (
|
|
// graphBase is the Microsoft Graph v1.0 root. Mail calls go through root().
|
|
graphBase = "https://graph.microsoft.com/v1.0"
|
|
|
|
// Well-known mail folder ids Graph accepts directly in a path or as a
|
|
// move destinationId, so we never have to resolve them to opaque ids.
|
|
FolderInbox = "inbox"
|
|
FolderJunk = "junkemail"
|
|
FolderSent = "sentitems"
|
|
FolderArchive = "archive"
|
|
FolderDrafts = "drafts"
|
|
// FolderDeletedItems is where Outlook's Delete puts a message.
|
|
FolderDeletedItems = "deleteditems"
|
|
)
|
|
|
|
// Client is a single Microsoft 365 mailbox reached over Graph.
|
|
type Client struct {
|
|
Email string
|
|
FirstName string
|
|
LastName string
|
|
|
|
// User is the Graph user id an application token acts for; "" is the
|
|
// signed-in user of a delegated token (/me).
|
|
User string
|
|
|
|
hc *http.Client
|
|
Cache *cache.Cache
|
|
|
|
// DeltaLinks holds the opaque per-folder delta cursor (well-known folder
|
|
// name -> deltaLink URL). Seeded from persisted state on init and advanced
|
|
// as sync runs; OnDelta persists each new value off the disposable worker.
|
|
DeltaLinks map[string]string
|
|
ImmutableIDs bool
|
|
idMu sync.RWMutex
|
|
|
|
// folderIDs caches resolved folder ids (e.g. the created "Warmbly" folder)
|
|
// so we don't re-list on every warmup action.
|
|
folderIDs map[string]string
|
|
mu sync.Mutex
|
|
|
|
// OnMessageSeen is offered every live delta item with only its id and
|
|
// read state: the caller dedupes, hydrates (FetchMessage) and stores as
|
|
// budget allows, and returns false for a message it left on the server,
|
|
// which pins the folder cursor before that page.
|
|
OnMessageSeen func(ctx context.Context, folder, providerID string, seen bool) (stored bool, err error)
|
|
OnMessageRemove func(ctx context.Context, providerID string) error
|
|
// OnPage is told every id on a delta page before its items are offered, so lookups can be batched.
|
|
OnPage func(ctx context.Context, ids []string)
|
|
OnDelta func(ctx context.Context, folder, deltaLink string) error
|
|
OnTokenRefresh func(ctx context.Context, token *oauth2.Token) error
|
|
OnFolderReconcile func(ctx context.Context, folder string) (bool, error)
|
|
OnRecoveryStart func(ctx context.Context, folder string) error
|
|
OnRecoveryCheckpoint func(ctx context.Context, folder, link string) error
|
|
OnRecoveryBaseline func(ctx context.Context, folder, link string) error
|
|
PendingRecoveryLink func(folder string) (string, error)
|
|
Recovering func(folder string) bool
|
|
}
|
|
|
|
// Init builds the auto-refreshing OAuth2 HTTP client. It mirrors goog.Client.Init:
|
|
// the token source reuses the current token until expiry, then refreshes through
|
|
// cfg and persists the new token via OnTokenRefresh (the worker relays it back to
|
|
// the control plane, which owns the encrypted credential store).
|
|
func (c *Client) Init(ctx context.Context, token *oauth2.Token, cfg oauth2.Config) *errx.MailError {
|
|
ctx = stoken.BoundedContext(ctx)
|
|
ts := cfg.TokenSource(ctx, token)
|
|
ts = oauth2.ReuseTokenSource(token, ts)
|
|
// Same guard as goog.Init: a nil OnTokenRefresh would panic per request.
|
|
if c.OnTokenRefresh != nil {
|
|
ts = stoken.New(ts, func(t *oauth2.Token) error {
|
|
return c.OnTokenRefresh(context.Background(), t)
|
|
})
|
|
}
|
|
return c.InitWithSource(ctx, ts)
|
|
}
|
|
|
|
// InitWithSource builds the client on a caller-owned token source (brokered
|
|
// tokens from Warmbly Cloud); nothing is persisted from it.
|
|
func (c *Client) InitWithSource(ctx context.Context, ts oauth2.TokenSource) *errx.MailError {
|
|
c.hc = stoken.HTTPClient(ctx, ts)
|
|
if c.DeltaLinks == nil {
|
|
c.DeltaLinks = map[string]string{}
|
|
}
|
|
c.folderIDs = map[string]string{}
|
|
return nil
|
|
}
|
|
|
|
// root is the mailbox's Graph path: /me for a delegated token, /users/{id} for an application one.
|
|
func (c *Client) root() string {
|
|
if c.User == "" {
|
|
return graphBase + "/me"
|
|
}
|
|
return graphBase + "/users/" + url.PathEscape(c.User)
|
|
}
|
|
|
|
// do issues a single authenticated request. body may be nil.
|
|
func (c *Client) do(ctx context.Context, method, url, contentType string, body []byte) (*http.Response, error) {
|
|
var r io.Reader
|
|
if body != nil {
|
|
r = bytes.NewReader(body)
|
|
}
|
|
req, err := http.NewRequestWithContext(ctx, method, url, r)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if contentType != "" {
|
|
req.Header.Set("Content-Type", contentType)
|
|
}
|
|
if c.ImmutableIDMode() {
|
|
req.Header.Set("Prefer", `IdType="ImmutableId", odata.maxpagesize=50`)
|
|
}
|
|
return c.hc.Do(req)
|
|
}
|
|
|
|
// doJSON marshals in (if non-nil), issues the request, maps any non-2xx status to
|
|
// a MailError, and decodes the response into out (if non-nil).
|
|
func (c *Client) doJSON(ctx context.Context, method, url string, in, out any) error {
|
|
var body []byte
|
|
contentType := ""
|
|
if in != nil {
|
|
b, err := json.Marshal(in)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
body = b
|
|
contentType = "application/json"
|
|
}
|
|
|
|
resp, err := c.do(ctx, method, url, contentType, body)
|
|
if err != nil {
|
|
return transportError(err)
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
|
return HandleError(resp)
|
|
}
|
|
if out != nil {
|
|
decoder := json.NewDecoder(resp.Body)
|
|
if err := decoder.Decode(out); err != nil {
|
|
var networkError net.Error
|
|
if errors.As(err, &networkError) || errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
|
|
return transportError(err)
|
|
}
|
|
return unreadableResponse(resp, err)
|
|
}
|
|
var trailing json.RawMessage
|
|
if err := decoder.Decode(&trailing); err != io.EOF {
|
|
var networkError net.Error
|
|
if errors.As(err, &networkError) || errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
|
|
return transportError(err)
|
|
}
|
|
return errGraphTrailingJSON
|
|
}
|
|
return nil
|
|
}
|
|
if _, err := io.Copy(io.Discard, resp.Body); err != nil {
|
|
return transportError(err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
var errGraphTrailingJSON = errors.New("graph: response contains extra JSON data")
|
|
|
|
// ErrUnreadableResponse is a success status whose body is not the JSON Graph
|
|
// promised. It says nothing about the mailbox or reachability, so the pass
|
|
// retries without reporting either.
|
|
var ErrUnreadableResponse = errors.New("graph: success response could not be decoded")
|
|
|
|
// unreadableResponse logs the response shape and decoder error type, never text that can quote mail content.
|
|
func unreadableResponse(resp *http.Response, err error) error {
|
|
log.Warn().
|
|
Str("decode_error", fmt.Sprintf("%T", err)).
|
|
Int("status", resp.StatusCode).
|
|
Str("content_type", resp.Header.Get("Content-Type")).
|
|
Str("content_encoding", resp.Header.Get("Content-Encoding")).
|
|
Msg("graph: success response could not be decoded")
|
|
return fmt.Errorf("%w (%T)", ErrUnreadableResponse, err)
|
|
}
|
|
|
|
// transportError classifies a failure of the HTTP call itself. The client's
|
|
// token source runs inside it, so a grant the provider has revoked arrives
|
|
// here rather than as a status code, and reporting that as "the mail server
|
|
// could not be established" points the operator at the network and promises a
|
|
// retry that can never succeed.
|
|
func transportError(err error) *errx.MailError {
|
|
f := mailauth.ClassifyTokenError(err)
|
|
if f.Refused() {
|
|
log.Debug().
|
|
Str("oauth_error", f.ErrorCode).
|
|
Str("oauth_description", f.Description).
|
|
Int("status", f.Status).
|
|
Bool("revoked", f.Revoked()).
|
|
Msg("Graph token refresh refused")
|
|
}
|
|
if f.Revoked() {
|
|
return errx.ErrMailAuthenticationFailed
|
|
}
|
|
return errx.ErrMailServerUnreachable
|
|
}
|