remote magpie: a request under way takes the address saved now
le13ure on X: after the LAN address of a magpie used as a Remote magpie provider changed and the user edited it in the provider, requests already under way kept retrying the old address instead of switching. Each request held the Provider it started with, and its retries (the same-one pauses up to 8s, a group's and a provider's patience up to 30s) asked that copy's address again. The look for a moved magpie (SeekMoved, v0.1.3177) ran at most once a minute, so other requests within the minute got nothing from it and kept the stale address. And a dial to a LAN address no one holds now waited on the OS (~75s macOS, ~127s Linux) per try. - provider.Readdressed: a Remote magpie copy moved onto the address saved now. The gateway's try loop asks it before each try; SeekMoved returns it when another look or the user saved one. - provider.Edited: store() signals every save; a pause between tries (pauseAlive, new pauseUntilReaddressed) ends when the waiting Remote magpie's address changed, so the next try goes at once. - netproxy: Dispatch's transports give a dial to a private or link-local IP literal 5s (lanDialCap). Names, public, CGNAT/Tailscale untouched. - docs: providers-accounts "A remote magpie that moved". Run (mote, nogui, at this tree): go test ./internal/netproxy ./internal/provider ./internal/gateway -run 'TestLANDial|TestLAN|TestDispatch|TestRemoteMagpie|TestPauseEnds|Patience|Replan' ok; go vet of the three packages for darwin, linux and windows ok; gofmt -l clean. mote was at load ~28 over its 18 cores (mica's disk is full), so timings ran slow. Broken by hand, each red: lanDialCap off (TestLANDialGivesUp, "no deadline"); Readdressed out of SeekMoved (TestRemoteMagpieSavedElsewhereIsTaken); the loop-head Readdressed off (TestRemoteMagpieRetryGoesToTheSavedAddress, 503 from the old address); the Edited wake out of pauseUntilReaddressed (TestPauseEndsWhenReaddressed, the pause ran its full 30s). Not tried: a real two-computer LAN move; the full suite before the push (started after it).
This commit is contained in:
@@ -69,7 +69,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
|
||||
| A remote magpie's prices | A local magpie asks a remote magpie's `/v1/models` with `X-Magpie-Prices` (`PricesHeader`, sent by `listHeaders`). The remote answers each model's `magpie_price`: what its own Usage page counts the model at (`EntryPriceIn`: the price its user set, else its provider's list price at its price rate; a routing group only when every member costs the same). It tells it only to a request from its own computer or one let in with a gateway key (`local` or `sharedWith`); a list that didn't ask gets no `magpie_price` (a remote request without a valid key never reaches the list: `lanGuard` refuses it); every list told to those callers also carries the same price as OpenRouter's `pricing`, for agents ([gateway routing](gateway-routing.md)). The local keeps the price with the fetched list (`catalog.Model.Price`; a value that isn't a price, or has a negative part, is dropped, the model kept) and uses it as that provider's list price (`ListPrice` → `remotePrice`). A price the local user set (`provider/model`, `provider/*`, `*/model`) still comes first, and the local provider's own price rate still applies on top. A remote from before this sends no field and the models stay priced as before; an older local sends no header and is sent nothing new. The model editor says the greyed price is the other magpie's (`remoteList`). | [`remote_magpie.go`](../../internal/provider/remote_magpie.go), [`models.go`](../../internal/provider/models.go), [`gateway.go`](../../internal/gateway/gateway.go) (`models`), [`live.go`](../../internal/catalog/live.go) |
|
||||
| A remote magpie's service tiers | A remote magpie's `/v1/models` gives each model the `service_tiers` its own Codex is offered on it (`codexTiers` → `codexcat.ServiceTiers`, from the same `CodexCatalog` and `codexcat.Entries` as its `/v1/codex/models`: Fast on a ChatGPT account's GPT model, the tiers of Codex's own entry on a relay's, none on a model it offers none). The local keeps the ids (`catalog.Model.Tiers` → `Entry.Tiers`), `codexListed` hands them on for the remote's models, and `codexcat.Entries` offers them to the local Codex with Codex's own names (`namedTiers`). The gateway sends the tier Codex asks for to a remote magpie as it was asked (`Request.OwnTier`, as for a provider added by its address; dropped and not sent again if refused), and the remote serves it as its own Codex's turn (#1234). An agent's picker offers the bolt on a remote's model whose tiers hold `priority` (`provider.CanFast` reads them with `RemoteTiers`; Ultrafast too where they hold `ultrafast`, `UltraOn`), and a fast pick of one goes on with `service_tier` `priority` on the remote's Chat or Responses: an agent on Messages, whose fast is Claude's `speed`, has it turned into the tier the remote offers (`forwardTranslated`), so Claude Code's pick reaches the remote's vendor too (littlekk88 on Discord; `TestRemoteMagpieFastPick`, red without either half). A remote from before this sends no tiers, and its models are offered none, as before. The list gives every client the tiers, not only a magpie asking with `X-Magpie-Drawers`: Cindy shows its Fast switch on a model whose `service_tiers` hold `priority` (#1914, `TestModelsListTiersForEveryClient`). | [`codexcat.go`](../../internal/codexcat/codexcat.go), [`codex_models.go`](../../internal/provider/codex_models.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`gateway.go`](../../internal/gateway/gateway.go), [`live.go`](../../internal/catalog/live.go) |
|
||||
| Two magpies each the other's remote | The list a magpie gives another magpie (`X-Magpie-Drawers`) names, as `magpie_via`, the magpies each model passes through to its vendor, itself last (`catalog.ViaHere`, `viaOf`; a routing group's are its members' together, so a group with the other magpie's own group of the model in it is left out there too). Each process has a random id (`catalog.Self`). A fetched list leaves out a model whose `magpie_via` has this magpie and another one (it went out of here and came back), or more than `MaxVia` (8), so two magpies that are each other's remote no longer list each other's models back one level deeper on every 10-minute fetch, without end, each level another member of the found `auto/` group and another trip round the two (cdredfox on Discord, 100-200% CPU). A remote that is this magpie itself (sync carries a Remote magpie provider to the computer it names, hanslin1666) has its models through this id alone, taken once; one through this id twice or more is left out. Such a remote is found by its own list: a fetch whose models' `magpie_via` ends with this magpie's own `Self` is kept, by provider id and the address it answered at, in `remote-self.json` (`noteSelf`; another lister, or a list with no via, takes it away; an empty list or a failed fetch changes nothing; this computer's own file, never in a backup or a sync). The provider is then left out (`SelfLeftOut` in `On`, `SwitchedOff`, `remoteMagpies`): its models are not listed beside this magpie's own nor in a found group, and a request naming one, an agent's pick sync brought from the other computer, is served here with the remote's id taken off the front (`ThroughSelf` in `Resolve` and `ResolveRoute`), not passed through the gateway again. The Providers row says *This magpie* (greyed while left out) and its editor says why, with **Use it anyway** (`KeepSelf`, `provider/keepself`, `SetKeepSelf`), the user's to set (hanslin1666): kept, it is served as any remote, each request twice through this magpie. `KeepSelf` is this computer's own like `KeepLogin` (`Mirror`, `Restore`, blanked in davsync's `hashes`), since the other computer's copy points at this one, which is not itself (`TestRemoteMagpieThatIsThisOneIsLeftOut`, `TestRemoteSelfRecord`, `remote-self.test.cjs`). Each request passed on to a Remote magpie says how many magpies it went through (`X-Magpie-Hops`, `passOnCaller`); one that arrives having passed `MaxVia` is answered 508 Loop Detected (`withCaller`), read only from a magpie's request and taken off every request as it arrives. A magpie older than the field sends none, and its models are taken as they were. The quota cards a Remote passes on follow the same ways (X on 0.1.3678: A → B → C → A told Kiro and Codex by `remote-B/kiro` and `remote-B/remote-C/remote-A/remote-B/remote-C/kiro`, hours apart, to a Remote enabled for one local model): a card's `via` that names any magpie twice is a loop too, so one that came round after this magpie restarted (its old `Self` is no longer this one's) is left out (`catalog.Loops`), and isn't kept in `remoteCardCache` (`keepRemoteCards`). A Remote's cards are shown, and passed on, only for the providers it is enabled for: the card's provider id must be the provider path of an exposed model there (its id less the last part, or a parent of it, whole parts only: relay/strata enabled tells relay/strata, never relay/kiro; `remoteCardWanted`, `cardWantedFor`, `TestRemoteCardWantedByWholePath`, 748975219 on X), unknown, so all shown, while its list isn't read, and all shown for a Remote set to Select none (it serves no model, its usage is still read; a user on X, 0.1.3929, `TestRemoteSelectNoneStillShowsItsCards`). One subscription account's copies (same provider, same `user`) are one card, the newest complete reading, then the shorter way (`oneCardPerAccount`, in `RemoteCards` and `CachedCards`; a key's cards, whose `user` is a name two keys may share, are not merged) (`TestRemoteCardsFollowEnabledModelsAndDedupe`, `TestLoopsOnARepeatedMagpie`). | [`magpie_via.go`](../../internal/catalog/magpie_via.go), [`live.go`](../../internal/catalog/live.go), [`gateway.go`](../../internal/gateway/gateway.go), [`remote_magpie.go`](../../internal/provider/remote_magpie.go), [`remote_self.go`](../../internal/provider/remote_self.go), [`remote_quotas_scope.go`](../../internal/provider/remote_quotas_scope.go) |
|
||||
| A remote magpie that moved | Computer A's router hands it a new address now and then (luckymanjc on Discord), and B's Remote magpie, saved at the old one, reached nothing. When B can't connect to it at all (a dial error, `unconnected`), its list fetch (`fetch` in [`models.go`](../../internal/provider/models.go)) and the gateway's request (`forward` in [`gateway.go`](../../internal/gateway/gateway.go)) call `SeekMoved` ([`remote_moved.go`](../../internal/provider/remote_moved.go)): every address of the old one's /24 and of up to four of B's own private /24s is dialled at A's port (500ms each, 128 at once, `lanNeighbours`). Whatever takes the connection there may be anyone's (a café's network, A switched off), so it is sent neither the key nor the provider's headers until it proves it holds the key (`proves`): B POSTs a nonce of its own and `RemoteKeyID` (the key's sha256, hex) to `RemoteProvePath` (`/v1/magpie/prove`) with no key and no proxy, and checks with `hmac.Equal` that the answer is `RemoteProof`: HMAC-SHA256 under the key of the nonce and the address B dialled. A answers it ([`remote_prove.go`](../../internal/gateway/remote_prove.go)) for an enabled gateway key of that id (`access.ProveSecret`: constant-time compares over every key, then `Check`) at the address the connection reached it on (`http.LocalAddrContextKey`), so a host passing B's nonce on to A elsewhere hands back a proof for A's address, not its own; 404 for a key it hasn't or has turned off. Only an address that proved is asked `/v1/models` with the key, and the first that lists 200 and whose list this magpie didn't make (`magpie_via`) is saved as the provider's address and asked again. A magpie from before the route, one behind a port forward or NAT (it is reached at another address than its own), or one behind a proxy that needs the provider's headers, is not found, and the user types the new address. A name or a public address is never looked around, an address the user changed meanwhile stands, and a provider is looked for once a minute at most, callers at once sharing the look (`TestRemoteMagpieKeyGoesToNoNeighbour`: an impostor that lists 200 for anything, one with a proof under another key, one with a garbled proof and one relaying to the real magpie are sent no key or header and not saved, and the real one is; `TestRemoteProof`, `TestRemoteMagpieFoundMoved`, `TestRemoteMagpieNotFoundStays`, `TestRemoteMagpieMovedIsFound`, `TestRemoteProveAnswersOnlyTheKeysHolder`). |
|
||||
| A remote magpie that moved | Computer A's router hands it a new address now and then (luckymanjc on Discord), and B's Remote magpie, saved at the old one, reached nothing. When B can't connect to it at all (a dial error, `unconnected`), its list fetch (`fetch` in [`models.go`](../../internal/provider/models.go)) and the gateway's request (`forward` in [`gateway.go`](../../internal/gateway/gateway.go)) call `SeekMoved` ([`remote_moved.go`](../../internal/provider/remote_moved.go)): every address of the old one's /24 and of up to four of B's own private /24s is dialled at A's port (500ms each, 128 at once, `lanNeighbours`). Whatever takes the connection there may be anyone's (a café's network, A switched off), so it is sent neither the key nor the provider's headers until it proves it holds the key (`proves`): B POSTs a nonce of its own and `RemoteKeyID` (the key's sha256, hex) to `RemoteProvePath` (`/v1/magpie/prove`) with no key and no proxy, and checks with `hmac.Equal` that the answer is `RemoteProof`: HMAC-SHA256 under the key of the nonce and the address B dialled. A answers it ([`remote_prove.go`](../../internal/gateway/remote_prove.go)) for an enabled gateway key of that id (`access.ProveSecret`: constant-time compares over every key, then `Check`) at the address the connection reached it on (`http.LocalAddrContextKey`), so a host passing B's nonce on to A elsewhere hands back a proof for A's address, not its own; 404 for a key it hasn't or has turned off. Only an address that proved is asked `/v1/models` with the key, and the first that lists 200 and whose list this magpie didn't make (`magpie_via`) is saved as the provider's address and asked again. A magpie from before the route, one behind a port forward or NAT (it is reached at another address than its own), or one behind a proxy that needs the provider's headers, is not found, and the user types the new address. An address saved, by that look or by the user's edit, is taken at once by a request already under way (le13ure on X: requests kept trying the old address after the edit): the gateway's try loop asks `Readdressed` before each try and moves the candidate onto the saved address, `SeekMoved` hands back the saved address when another caller's look (or the user) saved one within the minute, and a pause between tries (`pauseAlive`, `pauseUntilReaddressed` in [`patience.go`](../../internal/gateway/patience.go)) ends when `store` signals `Edited` and the provider's address changed. Dialling a private or link-local IP literal gives up after 5s (`lanDialCap` in [`lan.go`](../../internal/netproxy/lan.go), through `Dispatch`), where the OS would wait over a minute on an address no one holds (`TestRemoteMagpieSavedElsewhereIsTaken`, `TestRemoteMagpieRetryGoesToTheSavedAddress`, `TestPauseEndsWhenReaddressed`, `TestLANDialGivesUp`). A name or a public address is never looked around, an address the user changed meanwhile stands, and a provider is looked for once a minute at most, callers at once sharing the look (`TestRemoteMagpieKeyGoesToNoNeighbour`: an impostor that lists 200 for anything, one with a proof under another key, one with a garbled proof and one relaying to the real magpie are sent no key or header and not saved, and the real one is; `TestRemoteProof`, `TestRemoteMagpieFoundMoved`, `TestRemoteMagpieNotFoundStays`, `TestRemoteMagpieMovedIsFound`, `TestRemoteProveAnswersOnlyTheKeysHolder`). |
|
||||
| A relay's Codex entries | A provider the user added by its address with a Responses URL may list its models in Codex's own shape (`slug`, `supported_reasoning_levels`, `shell_type`, `base_instructions`: `catalog.CodexEntry`), plainly or when asked with Codex's `client_version`, as sub2api does (ctopsc on Discord: GPT-6.1 Terra was handed models.dev's 922000 window where the relay said 272000). `fetchOne` keeps such a row whole (`catalog.Model.Codex`, with its window, max window and inputs read off it), and when the plain list has none it asks the same URL once more with `client_version` (`codexEntries`): only where the list is fetched (add, key change, Refresh), never per Codex poll. The answer only adds entries to models the plain list has; one that fails or can't be read keeps the last list's entries (failed read = unknown), one that answers plainly says there are none. `codexcat.listedEntry` hands Codex the relay's entry as given, `base_instructions` included, with magpie's slug, name, priority and " via magpie" description; the user's window, compaction, levels and image setting still win (levels keep the relay's descriptions). A saved list from before is enriched at its next Refresh. `TestCodexListedEntry`, `TestCodexListedEntryInPlainList`. | [`codex_entries.go`](../../internal/provider/codex_entries.go), [`live.go`](../../internal/catalog/live.go), [`codexcat.go`](../../internal/codexcat/codexcat.go) |
|
||||
| An endpoint's catalog | A key's provider with no catalog of its own (none named, none from a preset) is priced from the models.dev catalog whose `api` is one of its endpoints (`EndpointCatalog`, `catalog.AtEndpoint`; a trailing slash and case don't count, and an Anthropic base, kept as its root, is also matched with its `/v1`). Only when exactly one catalog is at that address, and it isn't a plan's (an id with `-plan`, or a `membershipCatalogs` one): a plan lists its membership's $0, and two catalogs at one address can't be told apart. A subscription's account never gets one. A provider at AMD's own endpoint is priced from `amd`, which lists Qwen3.8-27B at $0, a price, where its maker sells no such model and it had none (#2052); a relay's endpoint matches nothing and its model stays unpriced, never priced at a reseller's guess. `magpie model price` names the catalog, and says how to give a price when none is known. | [`models.go`](../../internal/provider/models.go), [`catalog.go`](../../internal/catalog/catalog.go) |
|
||||
| The maker's own price | A model priced at its maker (`MakerPrice`, a provider's `ListPrice` after its own catalog, `PricedName`; through `makerListPrice`) is priced at a models.dev provider that lists it as its own (`catalog.MakerPriced`): one whose entry's `canonical_model_id` names it as the maker, or whose id is the maker's with a region (`alibaba-cn`), never a plan's (`-plan`) and never at $0. A maker preset that is such an API is asked first, in preset order, then the other owners by id; only then the maker presets as before (`PricedBy`). A maker preset that resells another lab's model no longer prices it: Mistral's `deepseek-v4-1-flash-1017` at $0.30/$1.20 gave way to DeepSeek's $0.15/$0.60, and a lab that isn't a preset (Meta's `muse-spark`) is priced at all. So a subscription's model (Command Code's, bestony on Discord) is estimated at what its maker charges (`TestMakerPriceIsTheMakersOwn`). A model no maker lists (Kimi K2.5, GLM-5.2 Fast) stays unpriced; the user gives it a price or a same-as model. | [`models.go`](../../internal/provider/models.go), [`catalog.go`](../../internal/catalog/catalog.go) |
|
||||
|
||||
@@ -1222,7 +1222,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
|
||||
askAgain := func(status int, msg string, wait time.Duration) bool {
|
||||
handOn(status, msg, wait)
|
||||
busyAgain++
|
||||
if !pauseAlive(r.Context(), w, kept, streams, start, wait) {
|
||||
if !pauseAlive(r.Context(), w, kept, streams, start, wait, nil) {
|
||||
s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1].Gone = true })
|
||||
end(status, msg, 0, 0)
|
||||
return false
|
||||
|
||||
+15
-13
@@ -3583,6 +3583,12 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
nearDone = nil
|
||||
}
|
||||
c := cands[i]
|
||||
if q, ok := provider.Readdressed(c.p); ok {
|
||||
// a Remote magpie saved at another address since the
|
||||
// request read it is asked there, a retry of it too
|
||||
// (le13ure on X)
|
||||
c.p = q
|
||||
}
|
||||
if handed.release != nil && handed.who != c.who() {
|
||||
handed.release()
|
||||
handed.release = nil
|
||||
@@ -4938,15 +4944,13 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1] = try })
|
||||
skipped = append(skipped, c.label()+": "+call.Error)
|
||||
again++
|
||||
select {
|
||||
case <-time.After(wait):
|
||||
if pauseUntilReaddressed(r.Context(), wait, readdressedOf([]candidate{c})) {
|
||||
i--
|
||||
continue
|
||||
case <-r.Context().Done():
|
||||
call.Status, call.Error = canceled(r.Context())
|
||||
try.Gone = true
|
||||
s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1] = try })
|
||||
}
|
||||
call.Status, call.Error = canceled(r.Context())
|
||||
try.Gone = true
|
||||
s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1] = try })
|
||||
break
|
||||
}
|
||||
if !last && hw.failed() && codexReset(hw.code(), hw.errBody()) {
|
||||
@@ -5230,7 +5234,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1] = try })
|
||||
skipped = append(skipped, c.label()+": "+call.Error)
|
||||
rounds, busyNow = rounds+1, nil
|
||||
if pauseAlive(r.Context(), w, kept, streams, start, wait) {
|
||||
if pauseAlive(r.Context(), w, kept, streams, start, wait, readdressedOf(next)) {
|
||||
cands = append(cands[:i+1:i+1], next...)
|
||||
continue
|
||||
}
|
||||
@@ -5248,15 +5252,13 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1] = try })
|
||||
skipped = append(skipped, c.label()+": "+call.Error)
|
||||
again++
|
||||
select {
|
||||
case <-time.After(wait):
|
||||
if pauseUntilReaddressed(r.Context(), wait, readdressedOf([]candidate{c})) {
|
||||
i--
|
||||
continue
|
||||
case <-r.Context().Done():
|
||||
call.Status, call.Error = canceled(r.Context())
|
||||
try.Gone = true
|
||||
s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1] = try })
|
||||
}
|
||||
call.Status, call.Error = canceled(r.Context())
|
||||
try.Gone = true
|
||||
s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1] = try })
|
||||
break
|
||||
}
|
||||
// (not for one account pinned: the others weren't asked)
|
||||
|
||||
@@ -217,10 +217,16 @@ func minTime(a, b time.Time) time.Time {
|
||||
|
||||
// pauseAlive waits d, keeping a streaming agent alive as a held stream
|
||||
// does once the request has gone keepHeldAfter without a word. false: the
|
||||
// agent went away first.
|
||||
func pauseAlive(ctx context.Context, w http.ResponseWriter, kept *keptAlive, streams bool, start time.Time, d time.Duration) bool {
|
||||
// agent went away first. A pause ends early once moved (when given) says
|
||||
// a provider about to be asked again was saved at another address
|
||||
// (readdressedOf).
|
||||
func pauseAlive(ctx context.Context, w http.ResponseWriter, kept *keptAlive, streams bool, start time.Time, d time.Duration, moved func() bool) bool {
|
||||
t := time.NewTimer(d)
|
||||
defer t.Stop()
|
||||
edits := editsOf(moved)
|
||||
if moved != nil && moved() {
|
||||
return true // saved elsewhere while it was asked
|
||||
}
|
||||
var hw *holdWriter
|
||||
if streams && kept != nil && kept.proto != provider.Gemini {
|
||||
hw = newHoldWriter(w, true)
|
||||
@@ -238,6 +244,61 @@ func pauseAlive(ctx context.Context, w http.ResponseWriter, kept *keptAlive, str
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
case <-tick.C:
|
||||
case <-edits:
|
||||
if moved() {
|
||||
return true
|
||||
}
|
||||
edits = provider.Edited()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// pauseUntilReaddressed waits d, or until moved (when given) says a
|
||||
// provider about to be asked again was saved at another address. false:
|
||||
// ctx ended first.
|
||||
func pauseUntilReaddressed(ctx context.Context, d time.Duration, moved func() bool) bool {
|
||||
t := time.NewTimer(d)
|
||||
defer t.Stop()
|
||||
edits := editsOf(moved)
|
||||
if moved != nil && moved() {
|
||||
return true // saved elsewhere while it was asked
|
||||
}
|
||||
for {
|
||||
select {
|
||||
case <-t.C:
|
||||
return true
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
case <-edits:
|
||||
if moved() {
|
||||
return true
|
||||
}
|
||||
edits = provider.Edited()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// editsOf is provider.Edited when there is a moved to ask, else a channel
|
||||
// that never fires.
|
||||
func editsOf(moved func() bool) <-chan struct{} {
|
||||
if moved == nil {
|
||||
return nil
|
||||
}
|
||||
return provider.Edited()
|
||||
}
|
||||
|
||||
// readdressedOf says whether any of cs is a Remote magpie saved at another
|
||||
// address since the request read it: the user typed its new address in
|
||||
// while the request paused before asking it again (le13ure on X). nil
|
||||
// when none of cs is a Remote magpie, for a pause that never wakes early.
|
||||
func readdressedOf(cs []candidate) func() bool {
|
||||
if !slices.ContainsFunc(cs, func(c candidate) bool { return c.p.IsRemoteMagpie() }) {
|
||||
return nil
|
||||
}
|
||||
return func() bool {
|
||||
return slices.ContainsFunc(cs, func(c candidate) bool {
|
||||
_, ok := provider.Readdressed(c.p)
|
||||
return ok
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,7 +9,9 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/access"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
@@ -132,3 +134,116 @@ func TestRemoteProveAnswersOnlyTheKeysHolder(t *testing.T) {
|
||||
t.Errorf("not shared: %d %s", w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
|
||||
// A Remote magpie's new address, saved while a request to it is being
|
||||
// retried (le13ure on X: "实时的请求却不会立刻改变而是反复重试"), is where
|
||||
// the retry goes: the old one is asked no more.
|
||||
func TestRemoteMagpieRetryGoesToTheSavedAddress(t *testing.T) {
|
||||
fresh(t)
|
||||
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
io.WriteString(w, `{"id":"c1","object":"chat.completion","model":"sol","choices":[{"index":0,"message":{"role":"assistant","content":"from the new address"},"finish_reason":"stop"}],"usage":{"prompt_tokens":5,"completion_tokens":2}}`)
|
||||
}))
|
||||
t.Cleanup(up.Close)
|
||||
if err := provider.Save(provider.Provider{ID: "fake", Name: "Fake", Key: "k", Models: []string{"sol"}, Chat: up.URL + "/v1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, secrets := newCaller(t, "B")
|
||||
h := New().Handler()
|
||||
remote := httptest.NewServer(h)
|
||||
t.Cleanup(remote.Close)
|
||||
id, err := provider.Add(provider.Provider{ID: "office", Name: "Office", Preset: provider.RemoteMagpiePreset, Key: secrets[0], Chat: strings.TrimPrefix(remote.URL, "http://")})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
office, _ := provider.Find(id)
|
||||
if _, err := office.Fetch(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// the old address answers busy, and the user types the new one in
|
||||
// before the retry
|
||||
var oldHits atomic.Int32
|
||||
old := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if oldHits.Add(1) == 1 {
|
||||
q, _ := provider.Find(id)
|
||||
q.Chat, q.Responses, q.Anthropic, q.Decide = remote.URL, "", "", ""
|
||||
if err := provider.Save(*q); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
w.Header().Set("Retry-After", "1")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
io.WriteString(w, `{"error":{"message":"overloaded"}}`)
|
||||
}))
|
||||
t.Cleanup(old.Close)
|
||||
office, _ = provider.Find(id)
|
||||
office.Chat, office.Responses, office.Anthropic, office.Decide = old.URL, "", "", ""
|
||||
if err := provider.Save(*office); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"office/fake/sol","messages":[{"role":"user","content":"hi"}]}`)))
|
||||
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "from the new address") {
|
||||
t.Fatalf("status %d: %s", rec.Code, rec.Body)
|
||||
}
|
||||
if n := oldHits.Load(); n != 1 {
|
||||
t.Errorf("the old address was asked %d times, want once", n)
|
||||
}
|
||||
}
|
||||
|
||||
// A pause before a Remote magpie is asked again ends when its new address
|
||||
// is saved, or at once when it was saved before the pause began; a pause
|
||||
// for nobody that moved runs its course.
|
||||
func TestPauseEndsWhenReaddressed(t *testing.T) {
|
||||
fresh(t)
|
||||
id, err := provider.Add(provider.Provider{ID: "office", Name: "Office", Preset: provider.RemoteMagpiePreset, Key: "k", Chat: "127.0.0.1:1"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
held, _ := provider.Find(id)
|
||||
cs := []candidate{{p: *held, model: "m", rest: held.ID}}
|
||||
if readdressedOf([]candidate{{p: provider.Provider{ID: "x", Chat: "http://h/v1"}}}) != nil {
|
||||
t.Error("a pause for no Remote magpie wakes for edits")
|
||||
}
|
||||
done := make(chan bool, 1)
|
||||
go func() { done <- pauseUntilReaddressed(context.Background(), time.Hour, readdressedOf(cs)) }()
|
||||
// an edit that moves nothing doesn't end it
|
||||
other, _ := provider.Find(id)
|
||||
other.Name = "Office 2"
|
||||
if err := provider.Save(*other); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case <-done:
|
||||
t.Fatal("ended by an edit that kept the address")
|
||||
case <-time.After(50 * time.Millisecond):
|
||||
}
|
||||
moved, _ := provider.Find(id)
|
||||
moved.Chat, moved.Responses, moved.Anthropic, moved.Decide = "127.0.0.1:2", "", "", ""
|
||||
if err := provider.Save(*moved); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case ok := <-done:
|
||||
if !ok {
|
||||
t.Fatal("ended as if the agent went away")
|
||||
}
|
||||
case <-time.After(30 * time.Second):
|
||||
t.Fatal("the pause went on after the address was saved")
|
||||
}
|
||||
// saved before the pause began
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go func() {
|
||||
done <- pauseAlive(ctx, httptest.NewRecorder(), nil, false, time.Now(), time.Hour, readdressedOf(cs))
|
||||
}()
|
||||
select {
|
||||
case ok := <-done:
|
||||
if !ok {
|
||||
t.Fatal("ended as if the agent went away")
|
||||
}
|
||||
case <-time.After(30 * time.Second):
|
||||
t.Fatal("a pause for one saved elsewhere already waited")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package netproxy
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -86,3 +87,33 @@ var cgnat = &net.IPNet{IP: net.IPv4(100, 64, 0, 0), Mask: net.CIDRMask(10, 32)}
|
||||
func lanIP(ip net.IP) bool {
|
||||
return ip.IsPrivate() || ip.IsLinkLocalUnicast() || ip.IsLoopback() || cgnat.Contains(ip)
|
||||
}
|
||||
|
||||
// lanDial is how long a connection to an address on the user's own
|
||||
// network is waited for: one there is taken within milliseconds, while
|
||||
// one nobody holds any more (a Remote magpie whose computer's router
|
||||
// handed it another address, le13ure on X) went unanswered until the
|
||||
// system gave up, over a minute on macOS and two on Linux, each try of a
|
||||
// request, before its retries, or the look for where it went
|
||||
// (provider's SeekMoved), could begin.
|
||||
var lanDial = 5 * time.Second
|
||||
|
||||
// lanDialCap has t give up on connecting to a private or link-local
|
||||
// address after lanDial. A name is left to the system's wait: it may
|
||||
// stand for an address outside, and Tailscale's (100.64/10), relayed on
|
||||
// its first packets, may take longer.
|
||||
func lanDialCap(t *http.Transport) {
|
||||
dial := t.DialContext
|
||||
if dial == nil {
|
||||
dial = (&net.Dialer{}).DialContext
|
||||
}
|
||||
t.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
if h, _, err := net.SplitHostPort(addr); err == nil {
|
||||
if ip := net.ParseIP(h); ip != nil && (ip.IsPrivate() || ip.IsLinkLocalUnicast()) {
|
||||
ctx, cancel := context.WithTimeout(ctx, lanDial)
|
||||
defer cancel()
|
||||
return dial(ctx, network, addr)
|
||||
}
|
||||
}
|
||||
return dial(ctx, network, addr)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package netproxy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A connection to an address on the user's own network that nobody holds
|
||||
// any more (le13ure on X: a Remote magpie whose computer was given
|
||||
// another address) is given up on after lanDial, not after the system's
|
||||
// minute or two; a name, a public address and Tailscale's are left to
|
||||
// the request's own context.
|
||||
func TestLANDialGivesUp(t *testing.T) {
|
||||
old := lanDial
|
||||
lanDial = 20 * time.Millisecond
|
||||
t.Cleanup(func() { lanDial = old })
|
||||
tr := &http.Transport{DialContext: func(ctx context.Context, _, addr string) (net.Conn, error) {
|
||||
if _, ok := ctx.Deadline(); !ok {
|
||||
return nil, errors.New("no deadline: " + addr)
|
||||
}
|
||||
<-ctx.Done() // an address that never answers
|
||||
return nil, ctx.Err()
|
||||
}}
|
||||
lanDialCap(tr)
|
||||
for _, addr := range []string{"192.168.1.20:3425", "10.0.0.5:3425", "172.16.3.4:3425", "169.254.1.1:3425"} {
|
||||
if _, err := tr.DialContext(context.Background(), "tcp", addr); !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Errorf("%s: %v, want given up on", addr, err)
|
||||
}
|
||||
}
|
||||
for _, addr := range []string{"a-pc.local:3425", "8.8.8.8:443", "100.100.1.2:3425", "api.example.com:443"} {
|
||||
if _, err := tr.DialContext(context.Background(), "tcp", addr); err == nil || errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Errorf("%s: %v, want left to the request's context", addr, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -218,8 +218,10 @@ var HTTP1 func(u *url.URL) bool
|
||||
// said not to check (WithUncheckedTLS) through a clone kept for that
|
||||
// host alone (uncheckTLS), and one made with a provider's own TLS
|
||||
// identity (WithClientCert) through a clone kept for it (clientTLS). A host whose IPv6 is taken but goes nowhere
|
||||
// is dialed over IPv4 (v4Fallback).
|
||||
// is dialed over IPv4 (v4Fallback), and one on the user's own network
|
||||
// is given lanDial to connect (lanDialCap).
|
||||
func Dispatch(base *http.Transport) http.RoundTripper {
|
||||
lanDialCap(base)
|
||||
v4Fallback(base)
|
||||
return &dispatch{base: base, own: map[route]*http.Transport{}, moved: Watch()}
|
||||
}
|
||||
|
||||
@@ -934,6 +934,8 @@ func store(f file) error {
|
||||
pruneIcons(f)
|
||||
// what agents were handed of the catalog may be out of date now
|
||||
catalog.Touched()
|
||||
// and a request waiting to ask a provider again asks it as saved now
|
||||
editedNow()
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -108,6 +108,12 @@ func SeekMoved(ctx context.Context, p Provider, err error) (Provider, bool) {
|
||||
if !p.IsRemoteMagpie() || err == nil || !unconnected.MatchString(err.Error()) {
|
||||
return p, false
|
||||
}
|
||||
if q, ok := Readdressed(p); ok {
|
||||
// saved at another address since the request read it: typed in,
|
||||
// or found by a look within seekEvery, which a request still
|
||||
// asking the old one met as no look at all (le13ure on X)
|
||||
return q, true
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, seekFor)
|
||||
defer cancel()
|
||||
q := seekOnce(ctx, p.ID)
|
||||
@@ -118,6 +124,45 @@ func SeekMoved(ctx context.Context, p Provider, err error) (Provider, bool) {
|
||||
return p, true
|
||||
}
|
||||
|
||||
// Readdressed is p, a Remote magpie, at the address it is saved at now,
|
||||
// when that is another than p's: the user typed the new one in, or a look
|
||||
// (seekMoved) found it there, while a request held p as it read it (le13ure
|
||||
// on X: a request asked the old address again and again, through its
|
||||
// retries and its patience, after the new one was saved). Only the
|
||||
// addresses are taken; a key's view of p stays as it was.
|
||||
func Readdressed(p Provider) (Provider, bool) {
|
||||
if !p.IsRemoteMagpie() {
|
||||
return p, false
|
||||
}
|
||||
q := lookIn(sharedAll(), p.ID)
|
||||
if q == nil || q.ID != p.ID || !q.IsRemoteMagpie() || q.Chat == "" || q.Chat == p.Chat {
|
||||
return p, false
|
||||
}
|
||||
p.Chat, p.Responses, p.Anthropic, p.Decide = q.Chat, q.Responses, q.Anthropic, q.Decide
|
||||
return p, true
|
||||
}
|
||||
|
||||
// edited is closed, and made anew, each time providers.json is written
|
||||
// here (store): a request pausing before it asks again wakes for it.
|
||||
var edited = struct {
|
||||
sync.Mutex
|
||||
ch chan struct{}
|
||||
}{ch: make(chan struct{})}
|
||||
|
||||
// Edited is closed when this magpie next writes the providers.
|
||||
func Edited() <-chan struct{} {
|
||||
edited.Lock()
|
||||
defer edited.Unlock()
|
||||
return edited.ch
|
||||
}
|
||||
|
||||
func editedNow() {
|
||||
edited.Lock()
|
||||
close(edited.ch)
|
||||
edited.ch = make(chan struct{})
|
||||
edited.Unlock()
|
||||
}
|
||||
|
||||
// a look under way, for those who wait for it
|
||||
type seekRun struct {
|
||||
done chan struct{}
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"crypto/hmac"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
@@ -321,3 +322,38 @@ func TestRemoteProof(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A request that read a Remote magpie at its old address, whose new one
|
||||
// was saved since (typed in by the user, or found by a look within
|
||||
// seekEvery), finds no one there: it is asked at the saved one, with no
|
||||
// look made (le13ure on X: a request asked the old address again and
|
||||
// again after the new one was saved).
|
||||
func TestRemoteMagpieSavedElsewhereIsTaken(t *testing.T) {
|
||||
isolate(t)
|
||||
isolateFetchHome(t)
|
||||
asked := seekHere(t)
|
||||
id, err := Add(Provider{ID: "office", Name: "Office", Preset: RemoteMagpiePreset, Key: "secret", Chat: movedAway})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
held, _ := Find(id)
|
||||
if _, ok := Readdressed(*held); ok {
|
||||
t.Fatal("readdressed while saved where it was read")
|
||||
}
|
||||
now := movedMagpie(t, "secret", "a", nil)
|
||||
saved, _ := Find(id)
|
||||
saved.Chat, saved.Responses, saved.Anthropic, saved.Decide = now, "", "", ""
|
||||
if err := Save(*saved); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
q, ok := SeekMoved(context.Background(), *held, errors.New("dial tcp 127.0.0.1:1: connect: connection refused"))
|
||||
if !ok || q.Chat != "http://"+now+"/v1" || q.Anthropic != "http://"+now {
|
||||
t.Fatalf("SeekMoved = %q %q %v, want the saved address", q.Chat, q.Anthropic, ok)
|
||||
}
|
||||
if q.Key != held.Key {
|
||||
t.Errorf("key %q, want the held one's", q.Key)
|
||||
}
|
||||
if n := asked.Load(); n != 0 {
|
||||
t.Errorf("looked around %d times for a provider saved elsewhere", n)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user