Files
rclone/backend/protondrive/events.go
StereotypicalCatandClaude Opus 5.5 c0bdbcde6b
build / windows (push) Skipped
build / other_os (push) Skipped
build / mac_amd64 (push) Skipped
build / mac_arm64 (push) Skipped
build / linux (push) Skipped
build / go1.26 (push) Skipped
build / linux_386 (push) Skipped
build / lint (push) Skipped
build / android-all (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/386 (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/amd64 (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/arm/v6 (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/arm/v7 (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/arm64 (push) Skipped
Build & Push Docker Images / Merge & Push Final Docker Image (push) Waiting for needed jobs
protondrive: rewrite the backend as a native Go client of the Proton Drive API
Replace Proton-API-Bridge and go-proton-api with a client in
backend/protondrive written against Proton's current Drive API, following
the behaviour of Proton's official Drive SDK:

- volume-based and v2 routes only
- upload block verification, signed manifests and extended attributes
- current content encryption (v4 node keys, v6 PKESK, SEIPDv2)
- browser (session fork) sign-in, with username and password still
  supported
- the volume's change events, used to keep the metadata cache current and
  for ChangeNotify, polled at most every 30 s
- an in-memory fake Proton server (protontest) so the tests run without
  an account

Uses ProtonMail/gopenpgp/v3 and ProtonMail/go-srp directly; no cgo.

Written with heavy AI assistance (Claude Code).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 23:22:46 +01:00

575 lines
18 KiB
Go

package protondrive
import (
"context"
"errors"
"fmt"
"math/rand/v2"
"slices"
"sync"
"time"
"github.com/rclone/rclone/backend/protondrive/api"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/lib/pacer"
"github.com/rclone/rclone/lib/rest"
)
const (
// minEventsInterval is the shortest time between polls of Proton's
// endpoint for events: the SDK's for the user's own volume.
minEventsInterval = 30 * time.Second
// eventsJitter is the most random time added to each wait between
// polls, as in the SDK.
eventsJitter = time.Second
// maxEventsBackoff is the longest wait between polls which fail.
maxEventsBackoff = 10 * time.Minute
// maxPendingNodes is the most nodes the poller waits to name.
maxPendingNodes = 1000
// pendingPolls is the number of polls after its change in which a
// node not cached then is named if it is cached by then.
pendingPolls = 2
// cacheIdleTime is how long the cache may go unused, with nothing
// subscribed, before the poller clears it and so stops polling.
cacheIdleTime = 10 * time.Minute
)
// errVolumeGone is returned by the events calls when the volume no
// longer exists or can't be reached: no later poll can succeed.
var errVolumeGone = errors.New("volume gone")
// eventChange is a change to a node the volume events report. Events
// name the node and its parent but not its name or type, and report its
// parent and trash state as they are when read, which may be after
// later changes.
type eventChange struct {
linkID string
parentID string // parent when read; empty if not reported
kind int // api.EventDelete etc
trashed bool // whether the node was in the trash when read
}
// staleNode is what the cache knew of a changed node before the change
// was applied.
type staleNode struct {
id string
parentID string // the cached parent; empty unless known
name string // empty unless known
isDir bool
known bool // whether the node was cached
newParentID string // the parent the change reports; empty if not reported
gone bool // whether the change deleted or trashed the node
late bool // whether the node changed in an earlier poll, before it was cached; see subscribe
}
// latestEventID returns the ID of the newest event of the volume, from
// which pollEvents reports the changes made after now. It wraps
// errVolumeGone if the volume is gone.
func (c *client) latestEventID(ctx context.Context) (string, error) {
opts := &rest.Opts{
Method: "GET",
Path: c.volumePath("/drive/volumes", "events", "latest"),
}
var resp api.LatestEventResponse
if err := c.eventsCall(ctx, opts, &resp); err != nil {
return "", eventsError("get latest event", err)
}
if resp.EventID == "" {
return "", errors.New("get latest event: no event ID in the response")
}
return resp.EventID, nil
}
// maxEventPages is the most pages of events one poll reads; the rest
// are read by the next poll.
const maxEventPages = 100
// pollEvents returns the changes after event cursor, oldest first, and
// the event ID to poll from next, reading up to maxEventPages pages.
//
// If the server no longer knows cursor it returns refresh set, no
// changes and the newest event ID: anything cached may be out of date.
// On error it returns no changes, and the poll should be retried from
// cursor. It wraps errVolumeGone if the volume is gone.
func (c *client) pollEvents(ctx context.Context, cursor string) (changes []eventChange, next string, refresh bool, err error) {
for pages := 1; ; pages++ {
opts := &rest.Opts{
Method: "GET",
Path: c.volumePath("/drive/v2/volumes", "events", cursor),
}
var page api.EventsResponse
if err := c.eventsCall(ctx, opts, &page); err != nil {
return nil, "", false, eventsError("list events", err)
}
if page.EventID == "" {
return nil, "", false, errors.New("list events: no event ID in the response")
}
if page.Refresh {
fs.Debugf(nil, "protondrive: events: event %s is no longer known: refreshing", cursor)
return nil, page.EventID, true, nil
}
fs.Debugf(nil, "protondrive: events: %d after %s (more %v)", len(page.Events), cursor, page.More)
changes = append(changes, eventChanges(page.Events)...)
// As in the SDK, a page without events ends the poll whatever
// More says, and so does one which doesn't advance.
if page.More && len(page.Events) > 0 && page.EventID == cursor {
fs.Debugf(nil, "protondrive: events: page after %s doesn't advance: its events will be read again", cursor)
}
if !page.More || len(page.Events) == 0 || page.EventID == cursor || pages >= maxEventPages {
return changes, page.EventID, false, nil
}
cursor = page.EventID
}
}
// eventsCall makes the events API call opts as apiCall does, but
// tries it only once and doesn't wait out a Retry-After: the poller
// backs off itself, and the returned error carries the Retry-After for
// pacer.IsRetryAfter.
func (c *client) eventsCall(ctx context.Context, opts *rest.Opts, response any) error {
var retryAfter time.Duration
err := c.apiPacer.CallNoRetry(func() (bool, error) {
resp, err := c.s.call(ctx, opts, nil, response)
retry, err := c.shouldRetry(ctx, resp, err)
if wait, ok := pacer.IsRetryAfter(err); ok {
// Kept from the pacer, which would hold every call of the
// client for it.
retryAfter = wait
err = errors.Unwrap(err)
}
return retry, err
})
if retryAfter > 0 {
return pacer.RetryAfterError(err, retryAfter)
}
return err
}
// eventsError returns err of the events call what, wrapping
// errVolumeGone for API code 2501.
func eventsError(what string, err error) error {
if apiErrorCode(err) == api.CodeNotExists {
return fmt.Errorf("%s: %w: %w", what, errVolumeGone, err)
}
return fmt.Errorf("%s: %w", what, err)
}
// eventChanges returns the changes events report, leaving out any
// which name no node.
func eventChanges(events []api.Event) []eventChange {
changes := make([]eventChange, 0, len(events))
for _, e := range events {
if e.Link.LinkID == "" {
fs.Debugf(nil, "protondrive: events: ignoring event %q naming no node", e.EventID)
continue
}
changes = append(changes, eventChange{
linkID: e.Link.LinkID,
parentID: e.Link.ParentLinkID,
kind: e.EventType,
trashed: e.Link.IsTrashed,
})
}
return changes
}
// applyEvents drops from the cache what changes make out of date, in
// order, and returns what it knew of each changed node before: stale[i]
// is for changes[i].
//
// A deleted node, and a folder moved or trashed, goes with everything
// cached below it. Another changed node goes with its own listing. The
// listings of the node's parents before and after the change go too.
func (c *client) applyEvents(changes []eventChange) (stale []staleNode) {
stale = make([]staleNode, 0, len(changes))
for _, ch := range changes {
s := staleNode{id: ch.linkID}
n := c.cache.peek(ch.linkID)
if n == nil && c.root != nil && ch.linkID == c.root.ID {
n = c.root
}
if n != nil {
s = staleNode{id: n.ID, parentID: n.ParentID, name: n.Name, isDir: n.IsFolder, known: true}
}
s.newParentID = ch.parentID
s.gone = ch.kind == api.EventDelete || ch.trashed
stale = append(stale, s)
// The root, the only node without a parent, can't be moved, so
// a parent reported for it leaves its descendants' paths alone.
moved := s.known && s.parentID != "" && ch.parentID != "" && ch.parentID != s.parentID
switch {
case ch.kind == api.EventDelete, s.isDir && (moved || ch.trashed):
c.cache.invalidateTree(ch.linkID)
default:
c.cache.invalidate(ch.linkID)
}
if ch.parentID != "" {
c.cache.invalidateChildren(ch.parentID)
}
}
return stale
}
// eventPoller polls the events of a client's volume and applies them
// to its cache, while the cache holds anything or anything subscribes.
//
// It polls from a timer, so no goroutine is left while it waits, and
// never more often than its interval. Polls which fail are retried
// after Fibonacci multiples of the interval, up to maxEventsBackoff.
type eventPoller struct {
c *client
floor time.Duration // shortest time between polls; 0 disables polling
jitter time.Duration // most random time added to each wait: eventsJitter, unless a test lowers it
idle time.Duration // how long the cache may go unused before it is cleared: cacheIdleTime, unless a test lowers it
runMu sync.Mutex // held by the timer's polls and by notifications, so they never overlap
pollMu sync.Mutex // held by every poll until it has updated the poller, for stop to wait for
mu sync.Mutex
interval time.Duration // time between polls asked for by setInterval
cursor string // event to poll from; empty until the start cursor is fetched
failures int // polls failed in a row
notBefore time.Time // no poll before this, as the server's Retry-After asked
timer *time.Timer // the next poll; nil if none is scheduled
running bool // whether a poll of gen is running
gen uint64 // polls of an earlier gen, from before stop, do nothing
ctx context.Context // context of the polls of gen
cancel context.CancelFunc // cancels ctx
closed bool // whether polling has stopped for good
subs map[int]func(stale []staleNode, refresh bool)
nextSub int
observer func(stale []staleNode, refresh bool) // called after subs; see observe
pending []pendingNode // nodes changed while not cached, oldest first; see subscribe
}
// pendingNode is a node which changed while it wasn't cached.
type pendingNode struct {
id string
polls int // polls left in which to look for it in the cache
}
// newEventPoller returns an idle poller of the events of c, polling no
// more often than every floor, or never if floor is 0.
func newEventPoller(c *client, floor time.Duration) *eventPoller {
return &eventPoller{
c: c,
floor: floor,
jitter: eventsJitter,
idle: cacheIdleTime,
subs: make(map[int]func([]staleNode, bool)),
}
}
// subscribe calls fn after each poll which changed anything, with what
// the cache knew of each changed node, or with refresh set if anything
// cached may have been out of date and the cache was cleared. Calls are
// made one at a time, on a goroutine of the poller's own, never on one
// which called wake or filled the cache, and fn must not call the
// poller.
//
// A node which changed while it wasn't cached, in a folder reported,
// as one being uploaded may be, is looked for in the cache in each of
// the next pendingPolls polls. If it is found it is passed again with
// late set, whether or not the poll changed anything.
//
// It keeps polling going until unsubscribe is called, once wake starts
// it. A call already started may still be made, or be running, after
// unsubscribe returns.
func (p *eventPoller) subscribe(fn func(stale []staleNode, refresh bool)) (unsubscribe func()) {
p.mu.Lock()
defer p.mu.Unlock()
id := p.nextSub
p.nextSub++
p.subs[id] = fn
return func() {
p.mu.Lock()
defer p.mu.Unlock()
delete(p.subs, id)
if len(p.subs) == 0 {
p.pending = nil
}
}
}
// addPendingLocked adds to the nodes to look for in the cache those in
// stale which weren't cached, if anything subscribes. It forgets the
// oldest beyond maxPendingNodes. p.mu must be held.
func (p *eventPoller) addPendingLocked(stale []staleNode) {
if len(p.subs) == 0 {
return
}
for _, s := range stale {
if s.known || s.gone || s.newParentID == "" {
continue
}
p.pending = slices.DeleteFunc(p.pending, func(pn pendingNode) bool { return pn.id == s.id })
p.pending = append(p.pending, pendingNode{id: s.id, polls: pendingPolls})
}
if n := len(p.pending) - maxPendingNodes; n > 0 {
p.pending = slices.Delete(p.pending, 0, n)
}
}
// resolvePendingLocked returns, with late set, the pending nodes now
// cached, and forgets them and those looked for in pendingPolls polls.
// p.mu must be held.
func (p *eventPoller) resolvePendingLocked() (late []staleNode) {
kept := p.pending[:0]
for _, pn := range p.pending {
if n := p.c.cache.peek(pn.id); n != nil {
late = append(late, staleNode{id: n.ID, parentID: n.ParentID, name: n.Name, isDir: n.IsFolder, known: true, late: true})
} else if pn.polls > 1 {
pn.polls--
kept = append(kept, pn)
}
}
clear(p.pending[len(kept):])
p.pending = kept
return late
}
// observe makes fn be called after each poll which changed anything,
// as subscribe does, after the subscribers. Unlike subscribe it doesn't
// keep polling going. It replaces any earlier fn; nil removes it.
func (p *eventPoller) observe(fn func(stale []staleNode, refresh bool)) {
p.mu.Lock()
defer p.mu.Unlock()
p.observer = fn
}
// setInterval sets the time between polls to d, if it is longer than
// the shortest the poller allows, from the next poll scheduled.
func (p *eventPoller) setInterval(d time.Duration) {
p.mu.Lock()
defer p.mu.Unlock()
p.interval = d
}
// wake starts polling if it isn't running and the cache holds anything
// or anything subscribes. The first wake fetches the start cursor
// before it returns, so every change made afterwards is seen, unless
// fetching it failed before, when it is fetched after a backoff. It
// doesn't wait for a poll or a notification.
func (p *eventPoller) wake() {
p.mu.Lock()
if p.closed || p.floor <= 0 || p.timer != nil || p.running || !p.wantedLocked() {
p.mu.Unlock()
return
}
if p.ctx == nil {
p.ctx, p.cancel = context.WithCancel(context.Background())
}
if p.cursor != "" || p.failures > 0 {
p.scheduleLocked()
p.mu.Unlock()
return
}
p.running = true
gen, ctx := p.gen, p.ctx
p.mu.Unlock()
p.poll(ctx, gen, true)
}
// stop stops polling, cancelling a poll in flight and waiting for it to
// end, but not for any notification it makes. A later wake starts
// polling again, from the cursor, after an interval.
func (p *eventPoller) stop() {
p.mu.Lock()
p.stopLocked()
p.mu.Unlock()
p.pollMu.Lock()
defer p.pollMu.Unlock()
}
// stopLocked is stop with p.mu held.
func (p *eventPoller) stopLocked() {
p.gen++
if p.timer != nil {
p.timer.Stop()
p.timer = nil
}
if p.cancel != nil {
p.cancel()
p.ctx, p.cancel = nil, nil
}
p.running = false
p.pending = nil
}
// close stops polling for good, as stop does.
func (p *eventPoller) close() {
p.mu.Lock()
p.closed = true
p.stopLocked()
p.mu.Unlock()
p.pollMu.Lock()
defer p.pollMu.Unlock()
}
// wantedLocked reports whether polling is wanted: the cache holds
// anything or anything subscribes. p.mu must be held.
func (p *eventPoller) wantedLocked() bool {
return len(p.subs) > 0 || !p.c.cache.empty()
}
// scheduleLocked schedules the next poll of the current gen and returns
// the wait. p.mu must be held.
func (p *eventPoller) scheduleLocked() time.Duration {
base := max(p.floor, p.interval)
// Fibonacci multiples of base for 1, 2, 3... failures: 1, 1, 2...
limit := max(base, maxEventsBackoff)
wait := base
for a, b, i := base, base, 1; i < p.failures && wait < limit; i++ {
a, b = b, a+b
wait = a
}
wait = min(wait, limit)
if p.jitter > 0 {
wait += rand.N(p.jitter + 1)
}
wait = max(wait, time.Until(p.notBefore))
gen := p.gen
p.timer = time.AfterFunc(wait, func() { p.run(gen) })
return wait
}
// run is the timer function of a poll scheduled in gen.
func (p *eventPoller) run(gen uint64) {
p.mu.Lock()
if gen != p.gen {
p.mu.Unlock()
return
}
p.timer = nil
if len(p.subs) == 0 && p.c.cache.unusedFor() >= p.idle {
fs.Debugf(nil, "protondrive: events: cache unused for %v: clearing it", p.idle)
p.c.cache.clear()
}
if !p.wantedLocked() {
// Idle: the cursor is kept for the next wake.
p.mu.Unlock()
return
}
p.running = true
ctx := p.ctx
p.mu.Unlock()
p.poll(ctx, gen, false)
}
// poll fetches the start cursor if there is none, else applies the
// events since the cursor, and then schedules the next poll if polling
// is still wanted. p.running must have been set in gen.
//
// From wake, inline is set: the caller may hold locks of its own (the
// dircache's, VFS's) which subscribers take, so it doesn't wait for
// runMu and leaves any notification to a goroutine of its own. Only
// the start cursor is fetched then, and no other poll of gen can run.
func (p *eventPoller) poll(ctx context.Context, gen uint64, inline bool) {
if !inline {
p.runMu.Lock()
defer p.runMu.Unlock()
}
p.pollMu.Lock()
pollDone := sync.OnceFunc(p.pollMu.Unlock)
defer pollDone()
p.mu.Lock()
cursor := p.cursor
p.mu.Unlock()
var (
changes []eventChange
next string
refresh bool
err error
)
if cursor == "" {
next, err = p.c.latestEventID(ctx)
} else {
changes, next, refresh, err = p.c.pollEvents(ctx, cursor)
}
p.mu.Lock()
if gen != p.gen {
// Stopped while polling.
p.mu.Unlock()
return
}
p.running = false
var stale []staleNode
gone := errors.Is(err, errVolumeGone)
switch {
case gone:
p.closed = true
refresh = true
p.c.cache.clear()
p.pending = nil
case err != nil:
p.failures++
if wait, ok := pacer.IsRetryAfter(err); ok {
p.notBefore = time.Now().Add(wait)
}
stale = p.resolvePendingLocked()
default:
p.failures = 0
p.cursor = next
if refresh {
p.c.cache.clear()
p.pending = nil
break
}
// Before applying changes, which may drop the nodes again.
stale = p.resolvePendingLocked()
if len(changes) > 0 {
applied := p.c.applyEvents(changes)
p.addPendingLocked(applied)
stale = append(stale, applied...)
}
}
var wait time.Duration
if !p.closed && p.wantedLocked() {
wait = p.scheduleLocked()
}
var subs []func([]staleNode, bool)
if refresh || len(stale) > 0 {
for _, fn := range p.subs {
subs = append(subs, fn)
}
if p.observer != nil {
subs = append(subs, p.observer)
}
}
p.mu.Unlock()
switch {
case gone:
fs.Errorf(nil, "protondrive: events: %v: no longer watching for changes", err)
case err != nil:
fs.Debugf(nil, "protondrive: events: %v: trying again in %v", err, wait)
}
pollDone()
notify := func() {
for _, fn := range subs {
fn(stale, refresh)
}
}
switch {
case len(subs) == 0:
case inline:
time.AfterFunc(0, func() {
p.runMu.Lock()
defer p.runMu.Unlock()
notify()
})
default:
notify()
}
}