plugin: keep idle plugin sign-ins alive in the background (#5080)
A plugin with auth.refresh had a sign-in renewed only when something used the account (a request, its models, usage or check-in) within its refreshLead of expiry. An account left idle past its token's life lapsed. OrcaTerm's WeChat token lives two hours, and after that its refresh answers SESSION_EXPIRED for good, so the user had to sign in again (orinsid, magpie-community/plugins#675). The gateway now renews each such sign-in as it comes due (provider.KeepPluginsSignedIn, started beside KeepPluginsListed): - Due times come from plugin-auth.json through filememo (plugin.RenewAt: expires less the lead the host reckons, now listed as Provider.Renews/RenewLead). Nothing is asked, and no host started, until an account is due. The loop sleeps until the next one, at most 5 minutes, and renews them one after another. - A due sign-in goes through the host's own renewal (host.js keepSignedIn, which shares renewal() with fresh()). It is one at a time per account whoever asks: a request arriving meanwhile waits for the same promise, under the cross-process lock file, through the account's proxy. - Kept: accounts switched on and not marked, of a plugin provider not switched off, hidden (leftAlone) or being moved. - A failed renewal marks nothing. It is held back for 1m, doubling to at most 30m, for that sign-in only. Only the plugin's signIn:"expired" marks it, as at a request. - A plugin can opt out with auth.keepAlive: false. None in the plugins repo needs to: no refresh costs quota, the ones rotating single-use refresh tokens (Cline, Factory, Nous, SenseNova, CodeArts, Qoder, MiniMax) rotate at use already, and kimi-work's reference accounts and Raccoon's desktop reuse never refresh another app's token. Docs: provider-plugins.md "A sign-in nothing uses"; leftAlone list in providers-accounts.md. Run at the pushed head, on mote (mote-run), -tags nogui: - go test -count=1 -timeout 45m ./internal/plugin ./internal/provider ./internal/gateway: ok (109s, 119s, 637s), rebased on origin/main6cfe78635. Rebased again onb088fd0f0(gateway.go, prompt.go changed): go build ./..., go vet of the three packages and the new tests plus TestLivePrompt*: ok. - the new tests on Windows (win-run) and Linux (wsl-run): ok. - GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./..., go vet ./...: ok. gofmt -l: clean. Broken by hand, each red, then restored: - keepSignedIn refreshing by itself, not through renewal()/the lock: TestKeepSignedInRenewsIdleSignIns red (r-ok-busy renewed twice beside concurrent requests). - keepAlive:false ignored: red (stayco listed as renewed). - a network failure reported as gone: red (down: Gone true). - Go backoff removed: TestKeeperBacksOffAFailedRenewal red. - the On, Lapsed and leftAlone filters each dropped: TestKeptSignInsAreTheOnesSwitchedOn red. The new tests don't compile on the old code (no KeepSignedIn). Not tried: a real OrcaTerm account idling past its 2h token with the gateway running; Windows/Linux runs of the new tests (vet only); a magpie with many plugin accounts beyond the unit test's look.
This commit is contained in:
@@ -199,6 +199,10 @@ A 401 marks the account's sign-in by default (`notePluginSignIn` in [`plugins.go
|
||||
|
||||
An OAuth account keeps a short-lived access token beside its refresh token, and its plugin's loader (or magpie's `auth.refresh`) renews the access token when its stored `expires` comes. A vendor can turn an access token away before that: Copilot's API dropped the inference token of a slot that had carried no traffic, while its GitHub OAuth token still traded at `/copilot_internal/v2/token`, and the bare 401 marked the account "sign-in has expired — sign in again", whose row then offered only a new device flow ([magpie-community/plugins#618](https://github.com/magpie-community/plugins/issues/618), jinpy666). The host now judges a 401 its plugin said nothing of (no `X-Magpie-Sign-In`) against the sign-in as the request found it (`staleAccess` in [`host.js`](../../internal/plugin/host.js)): an OAuth sign-in with a refresh token whose access token is still the stored one and not due yet is made due (`expires` 1, under the auth lock, only while the access token is unchanged) and said `kept`, so the next request renews it and goes through, and the gateway fails this one over as it fails any 401. The account is still marked when the access token was renewed for this request and turned away, when it was due already and the plugin didn't renew it, when the account has no refresh token, and when the plugin says so (an error with `signIn: "expired"`, a refresh `auth.refresh` was refused). A sign-in that can't be read when the 401 comes (`readAuthState`'s `known` false) is unknown: `kept`, never marked. A marked account is still routed to (`pluginAlsoOn` leaves no account on out for its mark), so a slot marked before is renewed on its next request and cleared by the success. Copilot's plugin 0.1.1 says `expired` only for the token exchange's own 401 and `renewed` for a quota read GitHub answers, which clears a mark left from before. `TestPluginStaleAccessRenewsNotLapses` in [`plugin_stale_access_test.go`](../../internal/provider/plugin_stale_access_test.go) covers the idle account renewed, a renewed token turned away, a refused refresh, an unreadable sign-in and the marked account still routed.
|
||||
|
||||
## A sign-in nothing uses
|
||||
|
||||
A plugin's `auth.refresh` renews a sign-in only when something uses the account (a request, its models, its usage, its check-in) within its `refreshLead` of `expires`. An account left idle past its token's life lapsed, and for a vendor whose session dies with its token the user had to sign in again: OrcaTerm's WeChat token lives two hours, and its refresh after that answers `SESSION_EXPIRED` for good (#5080, orinsid, [magpie-community/plugins#675](https://github.com/magpie-community/plugins/issues/675)). So the magpie serving the gateway renews each such sign-in as it comes due (`KeepPluginsSignedIn` in [`plugin_keepalive.go`](../../internal/provider/plugin_keepalive.go), started beside `KeepPluginsListed`). It reads the due times from plugin-auth.json (`plugin.RenewAt`: `expires` less the lead the host reckons, `Provider.RenewLead`, listed with `Renews`), asks nothing and starts no host until one is due, and sleeps until the next, at most five minutes. A due sign-in is renewed through the host's own renewal (`keepSignedIn` → `renewal` in [`host.js`](../../internal/plugin/host.js)), the one a request makes: one at a time per account whoever asks, a request arriving meanwhile waiting for the same one, under the lock file every magpie process renews under, through the account's proxy. Only accounts switched on and not marked, of a plugin provider not switched off, hidden (`leftAlone`) or being moved, are kept. A renewal that fails marks nothing: it is held back a minute, doubled each time to half an hour, for that sign-in only; only the plugin's `signIn: "expired"` marks the account, as at a request. A plugin whose renewal costs the account something, or whose refresh token another client holds too, says `auth.keepAlive: false` and is renewed only when used. No plugin in magpie-community/plugins says so as of this change: their refreshes cost no quota, those that rotate a refresh token (Cline, Factory, Nous, SenseNova, CodeArts, Qoder, MiniMax) already rotate it at use, and the ones reading another app's sign-in (kimi-work's reference accounts, Raccoon's desktop) never refresh it. `TestKeepSignedInRenewsIdleSignIns` in [`plugin_keepalive_test.go`](../../internal/plugin/plugin_keepalive_test.go) runs the renewal fixture in a real host; `TestKeeperAsksOnlyWhatIsDue`, `TestKeeperBacksOffAFailedRenewal`, `TestKeeperHoldsWhatTheHostFindsNotDue` and `TestKeptSignInsAreTheOnesSwitchedOn` in [`plugin_keepalive_test.go`](../../internal/provider/plugin_keepalive_test.go) cover the loop and which accounts it keeps.
|
||||
|
||||
## A model's free and rate
|
||||
|
||||
magpie never reads `free` from `rate`: `rate` 0 is none given (`plugin.Model.Rate` in [`providers.go`](../../internal/plugin/providers.go)), and a model is free only by its own `free: true`, a $0 list price or the user counting its whole provider free (`Provider.CountFree`) (`FreeModel` in [`models.go`](../../internal/provider/models.go)). A plugin sets `free` from the vendor's word; the guide says so ([magpie-community/plugins#468](https://github.com/magpie-community/plugins/issues/468)).
|
||||
|
||||
@@ -323,7 +323,7 @@ and `TestHistoricalWindowHoldsUsesEachWindowsOwnReading`.
|
||||
- The gateway and a magpie run from a terminal change the same files (#1674). `loginsMu` is a [`filelock.Mutex`](../../internal/filelock/filelock.go): besides the mutex it holds an OS lock on `logins.json.lock` (flock, `LockFileEx` on Windows), and taking it has `logins.json` read afresh (`filememo.Look`), so every read a change is made from sees what another magpie wrote, and a refresh the gateway wrote is never written back over. `savedTokenMu` holds `logins.json.renew.lock` the same way, so two magpies never spend one refresh token. `caller-keys.json` (`access`) and `mcp-signins.json` (`mcpauth`, with `mcp-signins.json.renew.lock` around a renewal) are changed under such locks too; `plugin-auth.json` already was, under `plugin-auth.json.lock`, which `host.js` takes too. A lock another magpie holds is waited for up to `filelock.Wait` (10s), then gone on without, as before there was one. `rememberLogins` writes nothing when only `Seen` would move on and the saved one is less than `seenEvery` (10 minutes) old, so a run that only lists accounts (`magpie ls`, `providers`, `sessions`, `usage`) leaves `logins.json` as it is. [`logins_lock_test.go`](../../internal/provider/logins_lock_test.go) covers both, the second with another test process writing between this one's read and write.
|
||||
- The account Codex or Claude Code is signed in to can be paused (`SetLoginOn` off, #263) only while another of its accounts is on. The gateway then sends it nothing: Codex's own-model turns go through routing, which passes over it (`OwnPaused`), and a native compaction (`/responses/compact`) goes to the first account on that isn't resting, signed as that account (`compactOn` in [codex_backend.go](../../internal/gateway/codex_backend.go)). The last other account off, the paused one is used again. A switched-off Codex provider is not a pause: Codex's own-model requests still relay on its sign-in as they came.
|
||||
- A switched-off provider (`Off`, #163) stays saved. The gateway says it is off instead of saying the model is unknown.
|
||||
- A subscription switched off (`Off`) or whose account was removed from magpie (`Hidden`) is left alone in the background (`leftAlone` in [`left_alone.go`](../../internal/provider/left_alone.go); Riko on Discord, whose Claude switched off still ran `claude auth status --json` every minute). No CLI is asked who is signed in (`claudeIdentity`, `cliIdentity.get` for Cursor and Devin): what it said last, in memory or `cli-identity.json`, is served, so the account stays listed to switch on again. Nor is its allowance read (`fetchSubscriptionUsage`, `loginUsageAt`), a saved ChatGPT sign-in renewed (`RenewLogins`), the agent's account switched (`NextLogin`), a window warmed (`keepWarm`), its model list fetched (`newDue`), a daily check-in made by the loop (`checkinNow` with `soon` false; a press still checks in), or a Codex reset about to run out read and spent (`SpendExpiringCodexResets`, #2226; `TestExpiringResetLeftAlone`). A Cursor switched off that was never asked who is signed in isn't listed until it is switched on. `TestLeftAloneRunsNoCLI` runs those paths with fake `claude`, `cursor-agent` and `devin` CLIs on PATH and checks none ran. Plugins' model lists (`KeepPluginsListed`, and every listing after a sign-in or a plugin changes) are asked of the plugin host all at once, and a plugin provider switched off in magpie is named in the call (`plugin.ListingOff`, `pluginsOff` in [`plugins.go`](../../internal/provider/plugins.go)): `host.js` runs no models hook for it, nor the sign-in renewal before one, and tells its list as fallen back, so the list told last is kept (ChangQiu on Discord: `TestOffPluginProviderAskedNoModels`, `TestPluginsOffNamesThePluginsOwnIDs`). Refreshing every list (the window's Refresh, `POST /api/sync`, and `magpie sync`) goes through `RefreshLists`, which asks no provider switched off, and a key added to one isn't given its own list (`PrefillNewKeys`), nor is a provider switched off asked for its list when it is saved or a key is switched on in its editor (`TestRefreshListsAsksNoProviderSwitchedOff`, `TestPrefillAsksNoProviderSwitchedOff`).
|
||||
- A subscription switched off (`Off`) or whose account was removed from magpie (`Hidden`) is left alone in the background (`leftAlone` in [`left_alone.go`](../../internal/provider/left_alone.go); Riko on Discord, whose Claude switched off still ran `claude auth status --json` every minute). No CLI is asked who is signed in (`claudeIdentity`, `cliIdentity.get` for Cursor and Devin): what it said last, in memory or `cli-identity.json`, is served, so the account stays listed to switch on again. Nor is its allowance read (`fetchSubscriptionUsage`, `loginUsageAt`), a saved ChatGPT sign-in renewed (`RenewLogins`), the agent's account switched (`NextLogin`), a window warmed (`keepWarm`), its model list fetched (`newDue`), a daily check-in made by the loop (`checkinNow` with `soon` false; a press still checks in), a plugin's idle sign-in renewed (`KeepPluginsSignedIn`, #5080), or a Codex reset about to run out read and spent (`SpendExpiringCodexResets`, #2226; `TestExpiringResetLeftAlone`). A Cursor switched off that was never asked who is signed in isn't listed until it is switched on. `TestLeftAloneRunsNoCLI` runs those paths with fake `claude`, `cursor-agent` and `devin` CLIs on PATH and checks none ran. Plugins' model lists (`KeepPluginsListed`, and every listing after a sign-in or a plugin changes) are asked of the plugin host all at once, and a plugin provider switched off in magpie is named in the call (`plugin.ListingOff`, `pluginsOff` in [`plugins.go`](../../internal/provider/plugins.go)): `host.js` runs no models hook for it, nor the sign-in renewal before one, and tells its list as fallen back, so the list told last is kept (ChangQiu on Discord: `TestOffPluginProviderAskedNoModels`, `TestPluginsOffNamesThePluginsOwnIDs`). Refreshing every list (the window's Refresh, `POST /api/sync`, and `magpie sync`) goes through `RefreshLists`, which asks no provider switched off, and a key added to one isn't given its own list (`PrefillNewKeys`), nor is a provider switched off asked for its list when it is saved or a key is switched on in its editor (`TestRefreshListsAsksNoProviderSwitchedOff`, `TestPrefillAsksNoProviderSwitchedOff`).
|
||||
- *Warm up now*, the last row of Settings › Usage's Codex and Claude Code warm-up tabs (`renderWarmNow` in `app.js`, `POST /api/warm-now`), sends one account the request the scheduled warm-up sends, whatever the warm-up settings say ([`warm_now.go`](../../internal/provider/warm_now.go)): `warmCodexLogin` for a ChatGPT account, then `StaleAllowance`; for a Claude account Claude Code's own run, `warmClaudeLogin` over the gateway's `warmClaude` (`WarmClaudeVia`), in the saved account's directory, then `claudeWarmedNow`. With several accounts the press opens the app's menu of them. An account whose sign-in lapsed is sent nothing and says so, and the vendor's refusal comes back as the row's line, in red. The scheduled warm-up's file (`codex-warmup.json`) isn't written: its next look reads the window as started. `TestWarmNowSendsTheScheduledWarmUp` checks the body and headers equal the scheduled warm-up's; `warm-now.test.cjs` covers the GUI.
|
||||
- An Antigravity subscription offers the union of its On accounts' models (`antigravityPoolModels` in [`antigravity_pool.go`](../../internal/provider/antigravity_pool.go)), each account's own list kept beside it (`accountModels`, read by `Account.Lists` for routing). The lists are fetched at the first listing, a probe, a sync or a Refetch, and also at each account's quota reading, which asks `fetchAvailableModels` anyway: a reading whose models differ from the account's saved list saves it and merges the pooled list again from every On account's own (`noteAntigravityList`), so a model Google gives one account of several later (01huadalang on Discord: Gemini 4) is offered, routed to and given its bar without that account made preferred or probed. A switched-off account's reading changes nothing. `TestAntigravityQuotaReadingListsNewModels`. Each `fetchAvailableModels` names the account's paid and current tier first (`entitlement.userTier`, `askTiers`), then none; a tier Google answers 400 (a Google AI Pro account's g1-pro-tier, #1553) is left out of that account's lists and quota readings for `tierRefusedFor` (a day), and the refused request is no row of the request log.
|
||||
- A provider removed or switched off takes its models out of the catalog. [Agent wiring](agent-wiring.md)'s `Reseat` moves agents off them.
|
||||
|
||||
@@ -814,6 +814,8 @@ func (s *Server) ListenAndServe(ctx context.Context) error {
|
||||
// and fetches the partner list every hour, asked for or not
|
||||
go provider.KeepPartnersFresh(ctx)
|
||||
go provider.KeepPluginsListed(ctx) // models a plugin's vendor drops or adds, while magpie runs
|
||||
// and renews the plugins' sign-ins as they come due, used or not (#5080)
|
||||
go provider.KeepPluginsSignedIn(ctx)
|
||||
// and those a signed-in account's vendor adds (a ChatGPT plan's new GPT)
|
||||
go provider.KeepAccountsListed(ctx)
|
||||
// and fetches the lists of the providers the user asked to keep fresh (#2135)
|
||||
|
||||
+75
-20
@@ -340,7 +340,7 @@ function forgetAccount(key) {
|
||||
const sessions = new Map() // oauth sign-in in progress → its authorize result
|
||||
const inflight = new Map() // fetch id → its lifecycle and owned resources
|
||||
const renewing = new Map() // account → its sign-in's renewal under way
|
||||
const unrenewed = new Map() // account → its last renewal that failed: {at, secret, gone}
|
||||
const unrenewed = new Map() // account → its last renewal that failed: {at, secret, gone, error}
|
||||
let config = { provider: {} } // what the plugins' config hooks made of it
|
||||
|
||||
// loadWait bounds one plugin's load (its import and its plugin function)
|
||||
@@ -2181,6 +2181,10 @@ function rowOf(id, a, keys, stored, p, own) {
|
||||
icon: iconOf(a),
|
||||
usage: typeof a.auth.usage === "function",
|
||||
checkin: typeof a.auth.checkin === "function",
|
||||
// its sign-ins are renewed in the background as they come due, so
|
||||
// long before expires (keepSignedIn)
|
||||
renews: keepsAlive(a.auth),
|
||||
renewLead: keepsAlive(a.auth) ? leadOf(a.auth) : 0,
|
||||
options: optionsOf(a.auth),
|
||||
decide: p.decide === true,
|
||||
searches: p.searches === true,
|
||||
@@ -2403,6 +2407,9 @@ async function apiKey({ provider, method, inputs, key, account, proxy }, signal)
|
||||
// for good, and the account is marked.
|
||||
// auth.refreshLead: how long (ms) before expires a token is renewed,
|
||||
// 5 minutes when not said.
|
||||
// auth.keepAlive: false leaves an account nothing uses to lapse; any
|
||||
// other value has the magpie serving the gateway renew it in the
|
||||
// background as it comes due too (keepSignedIn, #5080).
|
||||
// An OAuth sign-in whose expires is that close is renewed before its
|
||||
// loader, models, usage or a request runs, once at a time per account: the
|
||||
// requests that find it due wait for the one renewal (a vendor that spends
|
||||
@@ -2428,33 +2435,80 @@ function renewAt(a, stored) {
|
||||
return Number.isFinite(exp) && exp > 0 ? Math.max(1, exp - leadOf(a)) : 0
|
||||
}
|
||||
|
||||
// renewal is the renewal of the sign-in at key under way, started now if
|
||||
// it is due and none is: null when it isn't due, or its last renewal
|
||||
// failed less than RENEW_RETRY ago (or for good). A request and the
|
||||
// background keep-alive (keepSignedIn) share it, so an account is renewed
|
||||
// once at a time whoever asks.
|
||||
function renewal(provider, key) {
|
||||
const a = auths().get(provider)?.auth
|
||||
const stored = readAuth()[key]
|
||||
const at = renewAt(a, stored)
|
||||
if (!at || Date.now() < at) return null
|
||||
let r = renewing.get(key)
|
||||
if (r) return r
|
||||
const f = unrenewed.get(key)
|
||||
if (f && f.secret === secretOf(stored) && (f.gone || Date.now() - f.at < RENEW_RETRY)) return null
|
||||
pending++ // the host doesn't leave in the middle of it
|
||||
r = renew(provider, key, a).finally(() => {
|
||||
renewing.delete(key)
|
||||
// nor does magpie stop it in the middle of one (host.go's stop)
|
||||
send({ event: "renewing", count: renewing.size })
|
||||
done()
|
||||
})
|
||||
renewing.set(key, r)
|
||||
send({ event: "renewing", count: renewing.size })
|
||||
return r
|
||||
}
|
||||
|
||||
// fresh renews the sign-in at key when it is due, waiting at most
|
||||
// RENEW_WAIT for it: a renewal that takes longer goes on, and is kept when
|
||||
// it ends, but what waits for it goes on with the sign-in as it is.
|
||||
async function fresh(provider, key) {
|
||||
const a = auths().get(provider)?.auth
|
||||
const stored = readAuth()[key]
|
||||
const at = renewAt(a, stored)
|
||||
if (!at || Date.now() < at) return
|
||||
const f = unrenewed.get(key)
|
||||
if (f && f.secret === secretOf(stored) && (f.gone || Date.now() - f.at < RENEW_RETRY)) return
|
||||
let r = renewing.get(key)
|
||||
if (!r) {
|
||||
pending++ // the host doesn't leave in the middle of it
|
||||
r = renew(provider, key, a).finally(() => {
|
||||
renewing.delete(key)
|
||||
// nor does magpie stop it in the middle of one (host.go's stop)
|
||||
send({ event: "renewing", count: renewing.size })
|
||||
done()
|
||||
})
|
||||
renewing.set(key, r)
|
||||
send({ event: "renewing", count: renewing.size })
|
||||
}
|
||||
const r = renewal(provider, key)
|
||||
if (!r) return
|
||||
let t
|
||||
await Promise.race([r, new Promise((ok) => (t = setTimeout(ok, RENEW_WAIT)))])
|
||||
clearTimeout(t)
|
||||
}
|
||||
|
||||
// keepSignedIn renews the sign-in at key if it is due, as a request would
|
||||
// (renewal), with nothing waiting on the account: the gateway's
|
||||
// keep-alive asks it of each account whose token comes due while nothing
|
||||
// uses it (#5080: OrcaTerm's WeChat token lives two hours and can't be
|
||||
// renewed once it ends). It waits for the renewal to end and says what
|
||||
// came of it: due false, it wasn't due (renewed meanwhile, no expiry, a
|
||||
// plugin that doesn't renew through magpie or said keepAlive false);
|
||||
// renewed, the sign-in is a new one; error, why it couldn't be, and gone
|
||||
// whether the vendor turned it away for good (the account is marked, as a
|
||||
// request's renewal marks it). A renewal that failed lately isn't tried
|
||||
// again here either: waiting says so.
|
||||
async function keepSignedIn({ provider, account, proxy }) {
|
||||
return via.run(proxy ?? "", async () => {
|
||||
const key = accountKey(provider, account)
|
||||
const a = auths().get(provider)?.auth
|
||||
const was = readAuth()[key]
|
||||
if (!was) throw new Error("not signed in")
|
||||
const at = keepsAlive(a) ? renewAt(a, was) : 0
|
||||
if (!at || Date.now() < at) return { due: false, renewed: false, waiting: false, gone: false, error: "" }
|
||||
const r = renewal(provider, key)
|
||||
if (r) await r
|
||||
const now = readAuthState().all[key]
|
||||
if (now && changed(now, was)) return { due: true, renewed: true, waiting: false, gone: false, error: "" }
|
||||
const f = unrenewed.get(key)
|
||||
const failed = !!f && f.secret === secretOf(was)
|
||||
return { due: true, renewed: false, waiting: !r && failed, gone: failed && !!f.gone, error: failed ? f.error ?? "" : "" }
|
||||
})
|
||||
}
|
||||
|
||||
// keepsAlive says the plugin's sign-ins are renewed in the background as
|
||||
// they come due (keepSignedIn): any that renews through magpie, unless
|
||||
// its auth hook says keepAlive: false (a renewal that costs the account
|
||||
// something, or a refresh token another client holds too).
|
||||
function keepsAlive(a) {
|
||||
return typeof a?.refresh === "function" && a?.keepAlive !== false
|
||||
}
|
||||
|
||||
// Each magpie process runs a host of its own (the gateway, a CLI's quota
|
||||
// or usage, a host restarting), and each renews the same sign-in when it
|
||||
// comes due: a vendor that spends a refresh token once turned the second
|
||||
@@ -2552,7 +2606,7 @@ async function renewLocked(provider, key, a, was) {
|
||||
forgetAccount(key)
|
||||
return
|
||||
}
|
||||
unrenewed.set(key, { at: Date.now(), secret: secretOf(was), gone: e?.signIn === "expired" })
|
||||
unrenewed.set(key, { at: Date.now(), secret: secretOf(was), gone: e?.signIn === "expired", error: String(e?.message ?? e) })
|
||||
if (e?.signIn === "expired") send({ event: "signIn", provider, account: key, said: "expired" })
|
||||
send({ event: "log", level: "error", message: `${auths().get(provider)?.spec ?? provider}: auth.refresh: ${e?.message ?? e}` })
|
||||
return
|
||||
@@ -2937,6 +2991,7 @@ const handlers = {
|
||||
load,
|
||||
usage,
|
||||
checkin,
|
||||
keepSignedIn,
|
||||
// setOptions takes the user's option values over, as init did: the
|
||||
// plugin reads them when it next asks (#2038)
|
||||
setProviderOptions(p) {
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/testenv"
|
||||
)
|
||||
|
||||
// A sign-in nothing uses is renewed by KeepSignedIn as it comes due, as a
|
||||
// request would renew it (#5080: OrcaTerm's two-hour WeChat token lapsed
|
||||
// for good on an idle gateway): through the same renewal, so a request
|
||||
// arriving meanwhile waits for it and the vendor is asked once; one with
|
||||
// time left isn't renewed; one the vendor can't be reached for says why,
|
||||
// isn't marked and isn't tried again at once; one the vendor turned away
|
||||
// is marked as a request's renewal marks it. The providers say which
|
||||
// plugins keep alive and how early, as the host reckons it, and a plugin
|
||||
// that says keepAlive: false is left alone.
|
||||
func TestKeepSignedInRenewsIdleSignIns(t *testing.T) {
|
||||
sandbox(t)
|
||||
var mu sync.Mutex
|
||||
var seen []string
|
||||
srv := testenv.FakeVendor(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
mu.Lock()
|
||||
seen = append(seen, r.Header.Get("Authorization"))
|
||||
mu.Unlock()
|
||||
io.WriteString(w, "ok")
|
||||
}))
|
||||
defer srv.Close()
|
||||
logf := filepath.Join(t.TempDir(), "renewals")
|
||||
t.Setenv("RENEW_LOG", logf)
|
||||
said := make(chan string, 16)
|
||||
OnSignIn(func(provider, account, s string) { said <- provider + " " + account + " " + s })
|
||||
t.Cleanup(func() { OnSignIn(nil) })
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
||||
defer cancel()
|
||||
|
||||
for _, f := range []string{"testdata/renew/index.js", "testdata/renew-nokeep/index.js"} {
|
||||
abs, _ := filepath.Abs(f)
|
||||
if _, err := Add(ctx, abs); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
soon := time.Now().Add(time.Minute).UnixMilli() // inside the 5 minutes
|
||||
later := time.Now().Add(time.Hour).UnixMilli()
|
||||
account := func(provider, who, refresh string, expires int64) string {
|
||||
t.Helper()
|
||||
k, err := Import(ctx, provider, map[string]any{"type": "oauth", "refresh": refresh, "access": "old-" + who, "expires": expires, "accountId": who})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return k
|
||||
}
|
||||
due := account("renewco", "due@renew", "r-ok", soon)
|
||||
busy := account("renewco", "busy@renew", "r-ok-busy", soon)
|
||||
notYet := account("renewco", "later@renew", "r-ok-later", later)
|
||||
never := account("renewco", "never@renew", "r-ok-never", 0)
|
||||
down := account("renewco", "down@renew", "r-down", soon)
|
||||
gone := account("renewco", "gone@renew", "r-gone", soon)
|
||||
stay := account("stayco", "stay@renew", "s-1", soon)
|
||||
renewals := func() []string {
|
||||
b, _ := os.ReadFile(logf)
|
||||
return strings.Fields(string(b))
|
||||
}
|
||||
stored := func(key string) map[string]any {
|
||||
var all map[string]map[string]any
|
||||
b, _ := os.ReadFile(AuthPath())
|
||||
json.Unmarshal(b, &all)
|
||||
return all[key]
|
||||
}
|
||||
keep := func(provider, key string) KeptSignedIn {
|
||||
t.Helper()
|
||||
k, err := KeepSignedIn(ctx, provider, key)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", key, err)
|
||||
}
|
||||
return k
|
||||
}
|
||||
|
||||
// what the providers say of renewing
|
||||
ps, err := Providers(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
byID := map[string]Provider{}
|
||||
for _, p := range ps {
|
||||
byID[p.ID] = p
|
||||
}
|
||||
if p := byID["renewco"]; !p.Renews || p.RenewLead != 5*60*1000 {
|
||||
t.Fatalf("renewco: renews %v, lead %d; want true, 5 minutes", p.Renews, p.RenewLead)
|
||||
}
|
||||
if p := byID["stayco"]; p.Renews {
|
||||
t.Fatal("stayco said keepAlive false and is listed as renewed in the background")
|
||||
}
|
||||
if at, ok := RenewAt(byID["renewco"], due); !ok || at.UnixMilli() != soon-5*60*1000 {
|
||||
t.Fatalf("RenewAt(due) = %v, %v; want %v", at, ok, time.UnixMilli(soon-5*60*1000))
|
||||
}
|
||||
if at, ok := RenewAt(byID["renewco"], notYet); !ok || !at.After(time.Now()) {
|
||||
t.Fatalf("RenewAt(later) = %v, %v", at, ok)
|
||||
}
|
||||
if at, ok := RenewAt(byID["renewco"], never); ok {
|
||||
t.Fatalf("RenewAt(never) = %v: a sign-in with no expiry is due", at)
|
||||
}
|
||||
if _, ok := RenewAt(byID["stayco"], stay); ok {
|
||||
t.Fatal("RenewAt(stay): a plugin that keeps nothing alive has a due time")
|
||||
}
|
||||
|
||||
// due: renewed with nothing using it, and kept
|
||||
if k := keep("renewco", due); !k.Due || !k.Renewed || k.Err != "" {
|
||||
t.Fatalf("due: %+v", k)
|
||||
}
|
||||
if got := renewals(); strings.Join(got, " ") != "r-ok" {
|
||||
t.Fatalf("renewals = %v, want r-ok", got)
|
||||
}
|
||||
if a := stored(due); a["access"] != "a-1" || a["refresh"] != "r-ok+" || a["accountId"] != "due@renew" {
|
||||
t.Fatalf("kept %v", a)
|
||||
}
|
||||
if s := waitSaid(t, said); s != "renewco "+due+" renewed" {
|
||||
t.Fatalf("said %q", s)
|
||||
}
|
||||
// renewed already: not due
|
||||
if k := keep("renewco", due); k.Due || k.Renewed {
|
||||
t.Fatalf("due again: %+v", k)
|
||||
}
|
||||
|
||||
// the keep-alive and requests at once: one renewal, the requests sent
|
||||
// with what it gave
|
||||
var wg sync.WaitGroup
|
||||
var kept KeptSignedIn
|
||||
wg.Add(1)
|
||||
go func() { defer wg.Done(); kept = keep("renewco", busy) }()
|
||||
for range 3 {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
res, err := Fetch(ctx, FetchRequest{Provider: "renewco", Account: busy, Model: "renew-1", NPM: "@ai-sdk/openai-compatible",
|
||||
URL: srv.URL + "/v1/chat/completions", Method: "POST", Body: []byte(`{}`)})
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
io.ReadAll(res.Body)
|
||||
res.Body.Close()
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
if got := renewals(); strings.Join(got, " ") != "r-ok r-ok-busy" {
|
||||
t.Fatalf("renewals = %v, want r-ok-busy once", got)
|
||||
}
|
||||
if !kept.Due || !kept.Renewed || stored(busy)["refresh"] != "r-ok-busy+" {
|
||||
t.Fatalf("busy: %+v, kept %v", kept, stored(busy))
|
||||
}
|
||||
mu.Lock()
|
||||
for _, h := range seen {
|
||||
if h != "Bearer a-2" {
|
||||
t.Errorf("a request went with %q, not the renewed token", h)
|
||||
}
|
||||
}
|
||||
mu.Unlock()
|
||||
if s := waitSaid(t, said); s != "renewco "+busy+" renewed" {
|
||||
t.Fatalf("said %q", s)
|
||||
}
|
||||
|
||||
// time left: not renewed
|
||||
if k := keep("renewco", notYet); k.Due || k.Renewed {
|
||||
t.Fatalf("later: %+v", k)
|
||||
}
|
||||
if k := keep("renewco", never); k.Due || k.Renewed {
|
||||
t.Fatalf("never: %+v", k)
|
||||
}
|
||||
// keepAlive false: not renewed, though due
|
||||
if k := keep("stayco", stay); k.Due || k.Renewed {
|
||||
t.Fatalf("stay: %+v", k)
|
||||
}
|
||||
|
||||
// can't be reached: why, not marked, kept as it was, not tried again
|
||||
// at once
|
||||
k := keep("renewco", down)
|
||||
if !k.Due || k.Renewed || k.Gone || !strings.Contains(k.Err, "can't be reached") {
|
||||
t.Fatalf("down: %+v", k)
|
||||
}
|
||||
if k := keep("renewco", down); !k.Waiting || k.Renewed || k.Gone {
|
||||
t.Fatalf("down again: %+v", k)
|
||||
}
|
||||
if a := stored(down); a["access"] != "old-down@renew" {
|
||||
t.Fatalf("an account that couldn't renew was changed: %v", a)
|
||||
}
|
||||
|
||||
// turned away for good: gone, and marked
|
||||
if k := keep("renewco", gone); !k.Due || k.Renewed || !k.Gone {
|
||||
t.Fatalf("gone: %+v", k)
|
||||
}
|
||||
if s := waitSaid(t, said); s != "renewco "+gone+" expired" {
|
||||
t.Fatalf("said %q", s)
|
||||
}
|
||||
select {
|
||||
case s := <-said:
|
||||
t.Fatalf("said %q: the account that couldn't be reached was marked", s)
|
||||
default:
|
||||
}
|
||||
if got := renewals(); strings.Join(got, " ") != "r-ok r-ok-busy r-down r-gone" {
|
||||
t.Fatalf("renewals = %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// An expires the host reads as a number is read so by RenewAt too: a
|
||||
// number, or a string of one.
|
||||
func TestExpiresOf(t *testing.T) {
|
||||
for raw, want := range map[string]int64{
|
||||
`1800000000000`: 1800000000000,
|
||||
`"1800000000000"`: 1800000000000,
|
||||
`" 1800000000000 "`: 1800000000000,
|
||||
`1.8e12`: 1800000000000,
|
||||
`0`: 0,
|
||||
`-5`: 0,
|
||||
`""`: 0,
|
||||
`null`: 0,
|
||||
`"soon"`: 0,
|
||||
``: 0,
|
||||
} {
|
||||
got, ok := expiresOf(json.RawMessage(raw))
|
||||
if got != want || ok != (want > 0) {
|
||||
t.Errorf("expiresOf(%s) = %d, %v; want %d", raw, got, ok, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,9 +7,11 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"math"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
@@ -141,6 +143,13 @@ type Provider struct {
|
||||
// Checkin says the plugin presses its vendor's daily check-in for each
|
||||
// account (auth.checkin)
|
||||
Checkin bool `json:"checkin,omitempty"`
|
||||
// Renews says the plugin renews its accounts' sign-ins through magpie
|
||||
// (auth.refresh) and lets the gateway's magpie do it in the background
|
||||
// as each comes due (auth.keepAlive not false); RenewLead is how long
|
||||
// before a token expires it is due, in milliseconds (auth.refreshLead,
|
||||
// 5 minutes when not said), as the host reckons it (RenewAt).
|
||||
Renews bool `json:"renews,omitempty"`
|
||||
RenewLead int64 `json:"renewLead,omitempty"`
|
||||
// Options are the switches the plugin declares for the provider
|
||||
// (auth.options, #2038), as the host checked them
|
||||
Options []Option `json:"options,omitempty"`
|
||||
@@ -717,15 +726,74 @@ func Cached() []Provider {
|
||||
}
|
||||
|
||||
type storedAuth struct {
|
||||
Type string `json:"type"`
|
||||
AccountID string `json:"accountId"`
|
||||
Email string `json:"email"`
|
||||
Key string `json:"key"`
|
||||
Type string `json:"type"`
|
||||
// Expires is when an OAuth sign-in's token ends, in epoch
|
||||
// milliseconds, as the host reads it (a number, or a string of one)
|
||||
Expires json.RawMessage `json:"expires"`
|
||||
AccountID string `json:"accountId"`
|
||||
Email string `json:"email"`
|
||||
Key string `json:"key"`
|
||||
Metadata struct {
|
||||
Email string `json:"email"`
|
||||
} `json:"metadata"`
|
||||
}
|
||||
|
||||
// RenewAt is when the sign-in kept under key, an account of p, comes due
|
||||
// to be renewed in the background, as host.js's renewAt reckons it: an
|
||||
// OAuth sign-in's expires less p.RenewLead. False when it never does: p
|
||||
// doesn't renew in the background, the sign-in isn't OAuth, has no
|
||||
// expiry or isn't kept.
|
||||
func RenewAt(p Provider, key string) (time.Time, bool) {
|
||||
if !p.Renews {
|
||||
return time.Time{}, false
|
||||
}
|
||||
a, ok := readAuth()[key]
|
||||
if !ok || a.Type != "oauth" {
|
||||
return time.Time{}, false
|
||||
}
|
||||
exp, ok := expiresOf(a.Expires)
|
||||
if !ok {
|
||||
return time.Time{}, false
|
||||
}
|
||||
return time.UnixMilli(max(1, exp-p.RenewLead)), true
|
||||
}
|
||||
|
||||
// expiresOf is a sign-in's expires as JavaScript's Number reads it, when
|
||||
// it is a time after the epoch.
|
||||
func expiresOf(raw json.RawMessage) (int64, bool) {
|
||||
v := strings.TrimSpace(string(raw))
|
||||
if s, err := strconv.Unquote(v); err == nil {
|
||||
v = strings.TrimSpace(s)
|
||||
}
|
||||
f, err := strconv.ParseFloat(v, 64)
|
||||
if err != nil || math.IsNaN(f) || math.IsInf(f, 0) || f <= 0 || f > math.MaxInt64/2 {
|
||||
return 0, false
|
||||
}
|
||||
return int64(f), true
|
||||
}
|
||||
|
||||
// KeptSignedIn is what came of KeepSignedIn: Due false, the sign-in
|
||||
// wasn't due (renewed meanwhile); Renewed, it is a new one; else Err is
|
||||
// why it couldn't be, Gone whether the vendor turned it away for good
|
||||
// (the host marks the account, as OnSignIn tells), and Waiting that a
|
||||
// renewal failed lately and isn't tried again yet.
|
||||
type KeptSignedIn struct {
|
||||
Due bool `json:"due"`
|
||||
Renewed bool `json:"renewed"`
|
||||
Waiting bool `json:"waiting"`
|
||||
Gone bool `json:"gone"`
|
||||
Err string `json:"error"`
|
||||
}
|
||||
|
||||
// KeepSignedIn renews account's sign-in of provider if it is due, as a
|
||||
// request on it would, under the same once-at-a-time renewal and lock,
|
||||
// and waits for it.
|
||||
func KeepSignedIn(ctx context.Context, provider, account string) (KeptSignedIn, error) {
|
||||
var k KeptSignedIn
|
||||
err := Call(ctx, "keepSignedIn", map[string]any{"provider": provider, "account": account, "proxy": proxyOf(ctx)}, &k)
|
||||
return k, err
|
||||
}
|
||||
|
||||
// ProviderOf is the provider an account key is one of.
|
||||
func ProviderOf(key string) string {
|
||||
id, _, _ := strings.Cut(key, "#")
|
||||
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
// A plugin that renews its sign-ins through magpie (auth.refresh) but
|
||||
// says keepAlive: false: an account nothing uses is left to lapse. Each
|
||||
// renewal is written to $RENEW_LOG as "stay:" and the refresh token.
|
||||
import fs from "node:fs"
|
||||
|
||||
export const StayPlugin = async () => ({
|
||||
config: async (cfg) => {
|
||||
cfg.provider = cfg.provider ?? {}
|
||||
cfg.provider.stayco = {
|
||||
name: "StayCo",
|
||||
npm: "@ai-sdk/openai-compatible",
|
||||
api: "https://stay.invalid/v1",
|
||||
models: { "stay-1": { name: "Stay One", limit: { context: 1000, output: 100 } } },
|
||||
}
|
||||
},
|
||||
auth: {
|
||||
provider: "stayco",
|
||||
methods: [{ type: "api", label: "API key" }],
|
||||
keepAlive: false,
|
||||
refreshLead: 60_000,
|
||||
async refresh(auth) {
|
||||
fs.appendFileSync(process.env.RENEW_LOG, "stay:" + auth.refresh + "\n")
|
||||
return { access: "stay-new", refresh: auth.refresh + "+", expires: Date.now() + 3600e3 }
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,209 @@
|
||||
package provider
|
||||
|
||||
// Keeping the plugins' sign-ins alive while nothing uses them (#5080). A
|
||||
// plugin that renews its sign-ins through magpie (auth.refresh) had each
|
||||
// renewed only when something used the account: a request, its models,
|
||||
// its usage or its check-in, within the plugin's refreshLead of expiry.
|
||||
// An account left idle past its token's life lapsed, and for a vendor
|
||||
// whose session dies with its token the user had to sign in again:
|
||||
// OrcaTerm's WeChat token lives two hours, and its refresh after that
|
||||
// answers SESSION_EXPIRED for good (orinsid, plugins#675).
|
||||
//
|
||||
// So the magpie serving the gateway renews each such sign-in as it comes
|
||||
// due, on a timer, through the host's own renewal (plugin.KeepSignedIn):
|
||||
// the one a request would make, once at a time per account whoever asks
|
||||
// (a request arriving meanwhile waits for the same one) and under the
|
||||
// lock file every magpie process renews under. Only the accounts switched
|
||||
// on are kept, of a plugin provider not switched off, not hidden and not
|
||||
// being moved; one the vendor turned away (Lapsed) waits for the user to
|
||||
// sign in again. A plugin that would rather not (a renewal that costs the
|
||||
// account something, or a refresh token another client holds too) says
|
||||
// auth.keepAlive: false.
|
||||
//
|
||||
// Nothing is asked until an account is due: a look reads plugin-auth.json
|
||||
// (parsed once per change, filememo) and sleeps until the next account
|
||||
// comes due, no longer than keepAliveLookMost, so an idle magpie with no
|
||||
// account due starts no plugin host. A renewal that fails is tried again
|
||||
// later and later (keepAliveBackoff), for that sign-in only, and never
|
||||
// marks the account: a renewal that couldn't reach its vendor says
|
||||
// nothing about the sign-in. Only the plugin saying the vendor turned it
|
||||
// away for good marks it, as a request's renewal does.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/plugin"
|
||||
)
|
||||
|
||||
var (
|
||||
// keepAliveLookFirst is how long after the gateway starts the first
|
||||
// look is made, once its start has listed the plugins
|
||||
keepAliveLookFirst = 30 * time.Second
|
||||
// keepAliveLookMost is the longest a look waits for the next: a
|
||||
// sign-in made meanwhile is seen by then (the shortest refreshLead a
|
||||
// plugin says is a minute, and its token is due a lead early)
|
||||
keepAliveLookMost = 5 * time.Minute
|
||||
// keepAliveLookLeast is the shortest: a token due already but held
|
||||
// back (keepAliveBackoff) isn't looked at in a busy loop
|
||||
keepAliveLookLeast = 15 * time.Second
|
||||
// keepAliveRenewWait bounds one renewal: the host's own lock is held
|
||||
// at most a minute (RENEW_LOCK_STALE) before another takes it over
|
||||
keepAliveRenewWait = 2 * time.Minute
|
||||
)
|
||||
|
||||
// keepAliveBackoff is how long a sign-in whose renewal failed n times in
|
||||
// a row waits before it is tried again: a minute, doubled each time, at
|
||||
// most half an hour. An outage of the vendor's isn't asked every look,
|
||||
// and its accounts are renewed soon after it ends.
|
||||
func keepAliveBackoff(n int) time.Duration {
|
||||
d := time.Minute
|
||||
for i := 1; i < n && d < 30*time.Minute; i++ {
|
||||
d *= 2
|
||||
}
|
||||
return min(d, 30*time.Minute)
|
||||
}
|
||||
|
||||
// pluginSignIn is a plugin account kept alive: its provider, its key in
|
||||
// plugin-auth.json, the account as magpie lists it (for its proxy) and
|
||||
// when it comes due.
|
||||
type pluginSignIn struct {
|
||||
ID, Key, User string
|
||||
At time.Time
|
||||
}
|
||||
|
||||
// pluginSignInsKept are the plugins' sign-ins kept alive in the
|
||||
// background, each with when it is next due: of the plugins that renew
|
||||
// through magpie and keep alive (plugin.Provider.Renews), the accounts
|
||||
// switched on and not refused, of a provider neither switched off, hidden
|
||||
// nor being moved. Tests replace it.
|
||||
var pluginSignInsKept = func() []pluginSignIn {
|
||||
var out []pluginSignIn
|
||||
for _, pp := range heldPlugins() {
|
||||
if !pp.Renews || movingNow(pp.ID) || leftAlone(PluginID(pp.ID)) {
|
||||
continue
|
||||
}
|
||||
for _, l := range pluginLogins(pp) {
|
||||
if !l.On || l.Lapsed != "" {
|
||||
continue
|
||||
}
|
||||
if at, ok := plugin.RenewAt(pp, l.acct.Key); ok {
|
||||
out = append(out, pluginSignIn{ID: pp.ID, Key: l.acct.Key, User: l.User, At: at})
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// keepPluginSignedIn renews one sign-in if it is due; tests replace it.
|
||||
var keepPluginSignedIn = func(ctx context.Context, s pluginSignIn) (plugin.KeptSignedIn, error) {
|
||||
if !plugin.Running() && !plugin.HasBun() {
|
||||
return plugin.KeptSignedIn{}, errNoBun
|
||||
}
|
||||
return plugin.KeepSignedIn(ViaLogin(ctx, PluginID(s.ID), s.User), s.ID, s.Key)
|
||||
}
|
||||
|
||||
var errNoBun = errors.New("no Bun to run the plugins on")
|
||||
|
||||
// signInKeeper keeps the plugins' sign-ins alive, a look at a time, from
|
||||
// one goroutine.
|
||||
type signInKeeper struct {
|
||||
// held is each sign-in held back, by its key and the time it was due
|
||||
// (a sign-in renewed or made again since has another due time, and
|
||||
// starts afresh): its renewal failed n times in a row, or, n 0, the
|
||||
// host found it not due yet
|
||||
held map[signInDue]keptFailure
|
||||
}
|
||||
|
||||
type signInDue struct {
|
||||
key string
|
||||
at int64
|
||||
}
|
||||
|
||||
type keptFailure struct {
|
||||
n int
|
||||
until time.Time
|
||||
}
|
||||
|
||||
// look renews each sign-in due at now, one after another, but those held
|
||||
// back after a failure, and says how long until the next look.
|
||||
func (k *signInKeeper) look(ctx context.Context, now time.Time) time.Duration {
|
||||
next := now.Add(keepAliveLookMost)
|
||||
soon := func(t time.Time) {
|
||||
if t.Before(next) {
|
||||
next = t
|
||||
}
|
||||
}
|
||||
due := map[signInDue]bool{}
|
||||
for _, s := range pluginSignInsKept() {
|
||||
if ctx.Err() != nil {
|
||||
break
|
||||
}
|
||||
d := signInDue{s.Key, s.At.UnixMilli()}
|
||||
due[d] = true
|
||||
if s.At.After(now) {
|
||||
soon(s.At)
|
||||
continue
|
||||
}
|
||||
if f, ok := k.held[d]; ok && now.Before(f.until) {
|
||||
soon(f.until)
|
||||
continue
|
||||
}
|
||||
c, cancel := context.WithTimeout(ctx, keepAliveRenewWait)
|
||||
r, err := keepPluginSignedIn(c, s)
|
||||
cancel()
|
||||
if err == nil && r.Err != "" {
|
||||
err = errors.New(r.Err)
|
||||
}
|
||||
hold := func(f keptFailure, d2 time.Duration) {
|
||||
f.until = now.Add(d2)
|
||||
if k.held == nil {
|
||||
k.held = map[signInDue]keptFailure{}
|
||||
}
|
||||
k.held[d] = f
|
||||
soon(f.until)
|
||||
}
|
||||
switch {
|
||||
case err != nil && ctx.Err() != nil:
|
||||
// magpie is stopping: nothing is known of the sign-in
|
||||
case err != nil || r.Due && !r.Renewed:
|
||||
f := k.held[d]
|
||||
f.n++
|
||||
hold(f, keepAliveBackoff(f.n))
|
||||
if err != nil && !r.Waiting {
|
||||
log.Printf("%s: renewing a sign-in nothing used: %v (tried again in %s)", s.ID, err, keepAliveBackoff(f.n))
|
||||
}
|
||||
case !r.Due:
|
||||
// the host reckons it otherwise (a plugin updated to another
|
||||
// lead, not listed again yet): not asked again every look
|
||||
hold(keptFailure{}, keepAliveLookMost)
|
||||
default:
|
||||
delete(k.held, d)
|
||||
}
|
||||
}
|
||||
// a sign-in renewed, made again or gone is forgotten
|
||||
for d := range k.held {
|
||||
if !due[d] {
|
||||
delete(k.held, d)
|
||||
}
|
||||
}
|
||||
return min(max(next.Sub(now), keepAliveLookLeast), keepAliveLookMost)
|
||||
}
|
||||
|
||||
// KeepPluginsSignedIn renews the plugins' sign-ins as they come due, in
|
||||
// the magpie serving the gateway, while nothing uses them (#5080).
|
||||
func KeepPluginsSignedIn(ctx context.Context) {
|
||||
var k signInKeeper
|
||||
t := time.NewTimer(keepAliveLookFirst)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
}
|
||||
t.Reset(k.look(ctx, time.Now()))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/plugin"
|
||||
"github.com/yetone/magpie/internal/testenv"
|
||||
)
|
||||
|
||||
// fakeSignIns replaces what the keeper sees and does: the sign-ins kept
|
||||
// alive, and the host's answer for each, counting what it was asked.
|
||||
func fakeSignIns(t *testing.T, ins *[]pluginSignIn, answer func(pluginSignIn) (plugin.KeptSignedIn, error)) map[string]int {
|
||||
t.Helper()
|
||||
asked := map[string]int{}
|
||||
wasIns, wasKeep := pluginSignInsKept, keepPluginSignedIn
|
||||
t.Cleanup(func() { pluginSignInsKept, keepPluginSignedIn = wasIns, wasKeep })
|
||||
pluginSignInsKept = func() []pluginSignIn { return *ins }
|
||||
keepPluginSignedIn = func(_ context.Context, s pluginSignIn) (plugin.KeptSignedIn, error) {
|
||||
asked[s.Key]++
|
||||
return answer(s)
|
||||
}
|
||||
return asked
|
||||
}
|
||||
|
||||
// The keeper asks the host of a sign-in only once it is due, and sleeps
|
||||
// until the next comes due (no longer than keepAliveLookMost, no shorter
|
||||
// than keepAliveLookLeast): an idle magpie with nothing due asks nothing
|
||||
// (#5080).
|
||||
func TestKeeperAsksOnlyWhatIsDue(t *testing.T) {
|
||||
now := time.Date(2026, 11, 3, 12, 0, 0, 0, time.UTC)
|
||||
ins := []pluginSignIn{
|
||||
{ID: "orcaterm", Key: "orcaterm:a", At: now.Add(-time.Second)},
|
||||
{ID: "orcaterm", Key: "orcaterm:b", At: now.Add(90 * time.Second)},
|
||||
{ID: "kiro", Key: "kiro:c", At: now.Add(time.Hour)},
|
||||
}
|
||||
asked := fakeSignIns(t, &ins, func(pluginSignIn) (plugin.KeptSignedIn, error) {
|
||||
return plugin.KeptSignedIn{Due: true, Renewed: true}, nil
|
||||
})
|
||||
var k signInKeeper
|
||||
if d := k.look(context.Background(), now); d != 90*time.Second {
|
||||
t.Fatalf("next look in %v, want 90s (b comes due)", d)
|
||||
}
|
||||
if asked["orcaterm:a"] != 1 || asked["orcaterm:b"] != 0 || asked["kiro:c"] != 0 {
|
||||
t.Fatalf("asked %v, want a only", asked)
|
||||
}
|
||||
if len(k.held) != 0 {
|
||||
t.Fatalf("a renewed sign-in is held: %v", k.held)
|
||||
}
|
||||
ins = ins[2:]
|
||||
if d := k.look(context.Background(), now); d != keepAliveLookMost {
|
||||
t.Fatalf("nothing due for an hour: next look in %v, want %v", d, keepAliveLookMost)
|
||||
}
|
||||
ins = nil
|
||||
if d := k.look(context.Background(), now); d != keepAliveLookMost || len(asked) != 1 {
|
||||
t.Fatalf("no sign-ins: next look in %v, asked %v", d, asked)
|
||||
}
|
||||
}
|
||||
|
||||
// A renewal that fails is tried again later and later, for that sign-in
|
||||
// only, while the others are renewed as they come due; once it is
|
||||
// renewed (or the sign-in made again, with another due time) it starts
|
||||
// afresh. A renewal that is due, but the host found waiting on an earlier
|
||||
// failure, is held as one.
|
||||
func TestKeeperBacksOffAFailedRenewal(t *testing.T) {
|
||||
now := time.Date(2026, 11, 3, 12, 0, 0, 0, time.UTC)
|
||||
due := now.Add(-time.Minute)
|
||||
ins := []pluginSignIn{{ID: "orcaterm", Key: "orcaterm:a", At: due}, {ID: "orcaterm", Key: "orcaterm:b", At: due}}
|
||||
down := true
|
||||
asked := fakeSignIns(t, &ins, func(s pluginSignIn) (plugin.KeptSignedIn, error) {
|
||||
if s.Key == "orcaterm:a" && down {
|
||||
return plugin.KeptSignedIn{Due: true, Err: "OrcaTerm can't be reached"}, nil
|
||||
}
|
||||
return plugin.KeptSignedIn{Due: true, Renewed: true}, nil
|
||||
})
|
||||
var k signInKeeper
|
||||
ctx := context.Background()
|
||||
at := now
|
||||
look := func(want time.Duration) {
|
||||
t.Helper()
|
||||
if d := k.look(ctx, at); d != want {
|
||||
t.Fatalf("at +%v: next look in %v, want %v", at.Sub(now), d, want)
|
||||
}
|
||||
}
|
||||
look(time.Minute) // a failed once: a minute
|
||||
if asked["orcaterm:a"] != 1 || asked["orcaterm:b"] != 1 {
|
||||
t.Fatalf("asked %v", asked)
|
||||
}
|
||||
ins[1].At = now.Add(time.Hour) // b renewed
|
||||
at = now.Add(30 * time.Second)
|
||||
look(30 * time.Second) // held: not asked
|
||||
if asked["orcaterm:a"] != 1 {
|
||||
t.Fatalf("asked again inside its backoff: %v", asked)
|
||||
}
|
||||
at = now.Add(time.Minute)
|
||||
look(2 * time.Minute) // failed twice: two minutes
|
||||
at = at.Add(2 * time.Minute)
|
||||
look(4 * time.Minute) // three times: four
|
||||
if asked["orcaterm:a"] != 3 || asked["orcaterm:b"] != 1 {
|
||||
t.Fatalf("asked %v", asked)
|
||||
}
|
||||
for range 10 {
|
||||
at = at.Add(30 * time.Minute)
|
||||
k.look(ctx, at)
|
||||
}
|
||||
if f := k.held[signInDue{"orcaterm:a", due.UnixMilli()}]; f.until.Sub(at) != 30*time.Minute {
|
||||
t.Fatalf("held %v after many failures, want at most 30m", f.until.Sub(at))
|
||||
}
|
||||
|
||||
// signed in again: another due time, and it starts afresh
|
||||
ins[0].At = at.Add(-time.Second)
|
||||
look(time.Minute)
|
||||
if len(k.held) != 1 {
|
||||
t.Fatalf("the old due time's hold was kept: %v", k.held)
|
||||
}
|
||||
|
||||
// the vendor is back
|
||||
down = false
|
||||
at = at.Add(time.Minute)
|
||||
n := asked["orcaterm:a"]
|
||||
k.look(ctx, at)
|
||||
if asked["orcaterm:a"] != n+1 || len(k.held) != 0 {
|
||||
t.Fatalf("renewed, still held: %v, asked %v", k.held, asked)
|
||||
}
|
||||
|
||||
// an error of the call, or due and not renewed with no word why, is
|
||||
// a failure too
|
||||
ins = ins[:1]
|
||||
ins[0].At = due
|
||||
fails := []plugin.KeptSignedIn{{Due: true}, {Due: true, Waiting: true}}
|
||||
for _, f := range fails {
|
||||
keepPluginSignedIn = func(context.Context, pluginSignIn) (plugin.KeptSignedIn, error) { return f, nil }
|
||||
k = signInKeeper{}
|
||||
if d := k.look(ctx, now); d != time.Minute {
|
||||
t.Fatalf("%+v: next look in %v, want held a minute", f, d)
|
||||
}
|
||||
}
|
||||
keepPluginSignedIn = func(context.Context, pluginSignIn) (plugin.KeptSignedIn, error) {
|
||||
return plugin.KeptSignedIn{}, errNoBun
|
||||
}
|
||||
k = signInKeeper{}
|
||||
if d := k.look(ctx, now); d != time.Minute {
|
||||
t.Fatalf("no Bun: next look in %v, want held a minute", d)
|
||||
}
|
||||
}
|
||||
|
||||
// A sign-in the host finds not due (it reckons the lead otherwise) is
|
||||
// held keepAliveLookMost, not asked every look; and a look made as magpie
|
||||
// stops records nothing of the sign-in it was renewing.
|
||||
func TestKeeperHoldsWhatTheHostFindsNotDue(t *testing.T) {
|
||||
now := time.Date(2026, 11, 3, 12, 0, 0, 0, time.UTC)
|
||||
ins := []pluginSignIn{{ID: "kiro", Key: "kiro:a", At: now.Add(-time.Second)}}
|
||||
asked := fakeSignIns(t, &ins, func(pluginSignIn) (plugin.KeptSignedIn, error) {
|
||||
return plugin.KeptSignedIn{}, nil
|
||||
})
|
||||
var k signInKeeper
|
||||
if d := k.look(context.Background(), now); d != keepAliveLookMost {
|
||||
t.Fatalf("next look in %v, want %v", d, keepAliveLookMost)
|
||||
}
|
||||
k.look(context.Background(), now.Add(time.Minute))
|
||||
k.look(context.Background(), now.Add(2*time.Minute))
|
||||
if asked["kiro:a"] != 1 {
|
||||
t.Fatalf("asked %d times inside the hold", asked["kiro:a"])
|
||||
}
|
||||
k.look(context.Background(), now.Add(keepAliveLookMost))
|
||||
if asked["kiro:a"] != 2 {
|
||||
t.Fatalf("asked %d times after the hold", asked["kiro:a"])
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
keepPluginSignedIn = func(c context.Context, s pluginSignIn) (plugin.KeptSignedIn, error) {
|
||||
cancel()
|
||||
<-c.Done()
|
||||
return plugin.KeptSignedIn{}, c.Err()
|
||||
}
|
||||
k = signInKeeper{}
|
||||
k.look(ctx, now)
|
||||
if len(k.held) != 0 {
|
||||
t.Fatalf("a renewal cut short by magpie stopping was held: %v", k.held)
|
||||
}
|
||||
if !errors.Is(ctx.Err(), context.Canceled) {
|
||||
t.Fatal(ctx.Err())
|
||||
}
|
||||
}
|
||||
|
||||
func TestKeepAliveBackoff(t *testing.T) {
|
||||
for n, want := range map[int]time.Duration{1: time.Minute, 2: 2 * time.Minute, 3: 4 * time.Minute, 5: 16 * time.Minute, 6: 30 * time.Minute, 50: 30 * time.Minute} {
|
||||
if got := keepAliveBackoff(n); got != want {
|
||||
t.Errorf("keepAliveBackoff(%d) = %v, want %v", n, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Only the sign-ins switched on and not marked, of a plugin provider not
|
||||
// switched off, are kept alive: an account switched off, one the vendor
|
||||
// turned away and every account of a provider switched off are left as
|
||||
// they are (#5080).
|
||||
func TestKeptSignInsAreTheOnesSwitchedOn(t *testing.T) {
|
||||
bun := testenv.Bun(t)
|
||||
claudeHome(t)
|
||||
t.Setenv("MAGPIE_BUN", bun)
|
||||
t.Setenv("RENEW_LOG", filepath.Join(t.TempDir(), "renewals"))
|
||||
t.Cleanup(plugin.Settle)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
||||
defer cancel()
|
||||
abs, _ := filepath.Abs("../plugin/testdata/renew/index.js")
|
||||
if _, err := plugin.Add(ctx, abs); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
soon := time.Now().Add(time.Minute).UnixMilli()
|
||||
keys := map[string]string{}
|
||||
for _, who := range []string{"on@renew", "off@renew", "lapsed@renew"} {
|
||||
k, err := plugin.Import(ctx, "renewco", map[string]any{"type": "oauth", "refresh": "r-ok-" + who, "access": "old", "expires": soon, "accountId": who})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
keys[who] = k
|
||||
}
|
||||
if _, err := plugin.Providers(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
plugin.Refreshed()
|
||||
kept := func() map[string]bool {
|
||||
t.Helper()
|
||||
got := map[string]bool{}
|
||||
for _, s := range pluginSignInsKept() {
|
||||
if s.ID != "renewco" || s.At.UnixMilli() != soon-5*60*1000 {
|
||||
t.Fatalf("kept %+v", s)
|
||||
}
|
||||
got[s.Key] = true
|
||||
}
|
||||
return got
|
||||
}
|
||||
if got := kept(); len(got) != 3 {
|
||||
t.Fatalf("kept %v, want all three", got)
|
||||
}
|
||||
var pp plugin.Provider
|
||||
for _, p := range heldPlugins() {
|
||||
if p.ID == "renewco" {
|
||||
pp = p
|
||||
}
|
||||
}
|
||||
users := map[string]string{}
|
||||
for _, l := range pluginLogins(pp) {
|
||||
users[l.acct.Key] = l.User
|
||||
}
|
||||
if err := setPluginLoginOn(pp, users[keys["off@renew"]], false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
notePluginLapse(pp, keys["lapsed@renew"], http.StatusUnauthorized)
|
||||
if got := kept(); len(got) != 1 || !got[keys["on@renew"]] {
|
||||
t.Fatalf("kept %v, want on@renew alone", got)
|
||||
}
|
||||
if err := SetOff(PluginID("renewco"), true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := kept(); len(got) != 0 {
|
||||
t.Fatalf("a provider switched off: kept %v", got)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user