provider: a Remote magpie whose computer took another address is found on the network
luckymanjc (Discord) uses computer A's magpie from computer B over the
LAN. A's router hands it a new DHCP address after a boot, and B's Remote
magpie, saved at the old one, reached nothing until the address was
typed in again.
When B can't connect to a Remote magpie at all (a dial error, not an
answer), the list fetch (models.go) and the gateway's request (forward
in gateway.go) now call provider.SeekMoved (remote_moved.go). It dials
every address of the old one's /24 and of up to four of B's own private
/24s at A's port (500ms each, 128 at once). The first that lists
/v1/models 200 for the provider's key, and whose list this magpie didn't
make (magpie_via), is A: a LAN caller always needs a gateway key, so
another magpie answers 401. That address is saved as the provider's and
the request is made again there. 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
one look.
Run:
- mote-run go test -count=1 -run 'TestRemoteMagpie|TestLANNeighbours|TestDialable|TestRemoteSelf' ./internal/provider ./internal/gateway: ok
- mote-run go vet, GOOS=windows and GOOS=linux go vet of both packages: ok; gofmt -l clean
- Live: A was a real magpie on mote (10.0.0.121:3511), B a -tags nogui
build in WSL magpie-desktop (127.0.0.1:3522), sandbox HOMEs. B's
provider was saved at the dead 10.0.0.250:3511. B's start fetch found
A ("found at 10.0.0.121:3511, saved there") and a chat answered 200 in
4.2s. Then, with B running, the address was set dead again: a request
to office/group/rot found A and answered 200 in 4.4s, saved at .121.
Broken by hand, each red: the gateway hook off (502), the fetch hook off
(fetch error), the self check off (saved at this magpie itself).
Not tried: a real Windows A; a mDNS name (.local) that changed address
(left to the name); A on a different /24 than B. On Linux a dial to a
dead LAN address took ~54s (no route to host) before the look starts;
not changed here.
Reported-by: luckymanjc. (Discord)
This commit is contained in:
@@ -542,6 +542,13 @@ id to avoid a 403. Embeddings, rerank and speech-to-text requests use the remote
|
||||
APIs, and its exposed retrieval models are kept when fetching its list.
|
||||
These remain in agent model lists as on the remote; being listed does not
|
||||
mean an embedding or rerank model can hold a conversation.
|
||||
When the shared magpie's computer comes back at another address on the same
|
||||
network (a router handing it a new IP after a restart), the other computers
|
||||
find it by themselves: one that can't connect looks on its own networks for
|
||||
the magpie that answers its key, saves the new address and goes on. This
|
||||
needs an IP address on a private network; a name (`a-pc.local`) or a
|
||||
Tailscale address is followed as it is. Over the internet, use Tailscale's
|
||||
stable address or name, or a public URL in front of the shared magpie.
|
||||
The remote must serve the requested API and model, and allow the supplied
|
||||
key to use them. Responses uses HTTP, including SSE, rather than WebSocket.
|
||||
An older remote without decision-model discovery still serves its existing
|
||||
|
||||
@@ -61,6 +61,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. | [`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) |
|
||||
| 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), and the first that lists `/v1/models` 200 for the provider's key and whose list this magpie didn't make (`magpie_via`) is saved as the provider's address and asked again. 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 (`TestRemoteMagpieFoundMoved`, `TestRemoteMagpieNotFoundStays`, `TestRemoteMagpieMovedIsFound`). |
|
||||
| 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) |
|
||||
|
||||
@@ -5394,6 +5394,14 @@ func (s *Server) forward(ctx context.Context, p provider.Provider, to provider.P
|
||||
ctx = context.WithValue(ctx, dsSentKey{}, &dsSent{})
|
||||
}
|
||||
res, err = s.forwardOnce(ctx, p, to, path, body, in)
|
||||
if err != nil {
|
||||
// a Remote magpie whose computer came back at another address
|
||||
// is asked there (provider's remote_moved.go)
|
||||
if q, ok := provider.SeekMoved(ctx, p, err); ok {
|
||||
p = q
|
||||
res, err = s.forwardOnce(ctx, p, to, path, body, in)
|
||||
}
|
||||
}
|
||||
if err == nil && res.StatusCode >= 400 {
|
||||
// a file DeepSeek no longer holds: uploaded again, or the
|
||||
// images sent inline (deepseek_files.go)
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// A Remote magpie whose computer came back at another address
|
||||
// (luckymanjc on Discord: A's router gives it a new IP each boot): the
|
||||
// request that finds no one at the old one is answered from the address
|
||||
// that lists for the provider's key, and the provider is saved there.
|
||||
func TestRemoteMagpieMovedIsFound(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":"hi"},"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)
|
||||
}
|
||||
h := New().Handler()
|
||||
remote := httptest.NewServer(h)
|
||||
t.Cleanup(remote.Close)
|
||||
at := strings.TrimPrefix(remote.URL, "http://")
|
||||
id, err := provider.Add(provider.Provider{ID: "office", Name: "Office", Preset: provider.RemoteMagpiePreset, Key: "secret", Chat: at})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
office, err := provider.Find(id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := office.Fetch(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// A's old address now answers nobody (nothing listens on port 1)
|
||||
office, _ = provider.Find(id)
|
||||
office.Chat, office.Responses, office.Anthropic, office.Decide = "127.0.0.1:1", "", "", ""
|
||||
if err := provider.Save(*office); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(provider.SeekHere([]string{"127.0.0.1:1", at}))
|
||||
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 {
|
||||
t.Fatalf("status %d: %s", rec.Code, rec.Body)
|
||||
}
|
||||
office, _ = provider.Find(id)
|
||||
if office.Chat != remote.URL+"/v1" {
|
||||
t.Errorf("saved at %q, want %s/v1", office.Chat, remote.URL)
|
||||
}
|
||||
}
|
||||
@@ -428,6 +428,16 @@ func relistPicks(q *Provider, now map[string]bool) bool {
|
||||
// asked whether it serves its MCP router (noteRemoteHub).
|
||||
func (p Provider) fetch(ctx context.Context) ([]catalog.Model, error) {
|
||||
ms, err := p.fetchList(ctx)
|
||||
if err != nil && p.IsRemoteMagpie() {
|
||||
// one that took another address on its network is asked there
|
||||
// (remote_moved.go)
|
||||
sctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), seekFor)
|
||||
defer cancel()
|
||||
if q, ok := SeekMoved(sctx, p, err); ok {
|
||||
p, ctx = q, sctx
|
||||
ms, err = p.fetchList(ctx)
|
||||
}
|
||||
}
|
||||
if err == nil {
|
||||
noteSelf(p, ms)
|
||||
if len(ms) > 0 {
|
||||
|
||||
@@ -0,0 +1,289 @@
|
||||
package provider
|
||||
|
||||
// A Remote magpie whose computer came back at another address
|
||||
// (luckymanjc on Discord): computer A's router hands it a new IP now and
|
||||
// then, a boot often enough, and B's Remote magpie, saved at the old
|
||||
// one, reached nothing until the user typed the new one in. So when B
|
||||
// can't connect to it at all, B looks for it on the networks it shares
|
||||
// with it: every address of the old one's /24 and of each of B's own
|
||||
// private IPv4 networks, at the port A served on. An address that takes
|
||||
// the connection is A when it answers the model list 200 for the
|
||||
// provider's own key: a gateway key is A's secret, and another magpie,
|
||||
// or anything else, answers 401 or isn't a magpie at all. One whose list
|
||||
// this magpie made (its magpie_via ends with catalog.Self, remote_self.go)
|
||||
// is this magpie and is passed over. The address found is saved as the
|
||||
// provider's, as if the user had typed it, and the request or list that
|
||||
// failed is asked there.
|
||||
//
|
||||
// An address given by name (a-pc.local, a Tailscale name) is the name's
|
||||
// to follow, and a public address isn't looked around: neither is
|
||||
// looked for. A look is made at most once a minute for each provider.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
)
|
||||
|
||||
// seekDial is how long each address is given to take the connection.
|
||||
var seekDial = 500 * time.Millisecond
|
||||
|
||||
// seekAnswer is how long an address that took it is given to list.
|
||||
var seekAnswer = 5 * time.Second
|
||||
|
||||
// seekFor is how long a list that failed waits for a look and the list
|
||||
// asked again.
|
||||
var seekFor = 20 * time.Second
|
||||
|
||||
// seekEvery is how soon after one look another is made for a provider.
|
||||
var seekEvery = time.Minute
|
||||
|
||||
// seekWide is how many addresses are dialled at once.
|
||||
const seekWide = 128
|
||||
|
||||
// seekNets is how many /24 networks one look covers at most.
|
||||
const seekNets = 4
|
||||
|
||||
var seekMu sync.Mutex
|
||||
var seekLast = map[string]time.Time{}
|
||||
|
||||
// seekAt is the addresses (host:port) a Remote magpie last at host:port
|
||||
// may be at now, nearest first. Tests give their own.
|
||||
var seekAt = lanNeighbours
|
||||
|
||||
// SeekHere has every look made at ats alone, as if any look made before
|
||||
// were long ago, until restore: for the gateway's tests, whose Remote
|
||||
// magpie is on loopback.
|
||||
func SeekHere(ats []string) (restore func()) {
|
||||
seekMu.Lock()
|
||||
old := seekAt
|
||||
seekAt = func(string, string) []string { return ats }
|
||||
clear(seekLast)
|
||||
seekMu.Unlock()
|
||||
return func() {
|
||||
seekMu.Lock()
|
||||
seekAt = old
|
||||
clear(seekLast)
|
||||
seekMu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
// unconnected says err is a connection that was never made: what a
|
||||
// computer that moved, or is off, leaves behind.
|
||||
var unconnected = regexp.MustCompile(`dial tcp |connectex|no route to host|host is down|network is unreachable`)
|
||||
|
||||
// SeekMoved is p, a Remote magpie a request found no one at (err), at
|
||||
// the address it was found at on this computer's network, saved there:
|
||||
// the request is made again at it. Requests failing at once wait for one
|
||||
// look, and one is made at most every seekEvery.
|
||||
func SeekMoved(ctx context.Context, p Provider, err error) (Provider, bool) {
|
||||
if !p.IsRemoteMagpie() || err == nil || !unconnected.MatchString(err.Error()) {
|
||||
return p, false
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, seekFor)
|
||||
defer cancel()
|
||||
q := seekOnce(ctx, p.ID)
|
||||
if q == nil || strings.TrimSpace(q.Chat) == strings.TrimSpace(p.Chat) {
|
||||
return p, false
|
||||
}
|
||||
p.Chat, p.Responses, p.Anthropic, p.Decide = q.Chat, q.Responses, q.Anthropic, q.Decide
|
||||
return p, true
|
||||
}
|
||||
|
||||
// a look under way, for those who wait for it
|
||||
type seekRun struct {
|
||||
done chan struct{}
|
||||
found *Provider
|
||||
}
|
||||
|
||||
var seekRunning = map[string]*seekRun{}
|
||||
|
||||
// seekOnce is seekMoved, made once for those asking at once, and not
|
||||
// again within seekEvery.
|
||||
func seekOnce(ctx context.Context, id string) *Provider {
|
||||
seekMu.Lock()
|
||||
if r := seekRunning[id]; r != nil {
|
||||
seekMu.Unlock()
|
||||
select {
|
||||
case <-r.done:
|
||||
return r.found
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if time.Since(seekLast[id]) < seekEvery {
|
||||
seekMu.Unlock()
|
||||
return nil
|
||||
}
|
||||
r := &seekRun{done: make(chan struct{})}
|
||||
seekRunning[id], seekLast[id] = r, time.Now()
|
||||
seekMu.Unlock()
|
||||
r.found, _ = seekMoved(ctx, id)
|
||||
seekMu.Lock()
|
||||
delete(seekRunning, id)
|
||||
seekMu.Unlock()
|
||||
close(r.done)
|
||||
return r.found
|
||||
}
|
||||
|
||||
// seekMoved looks for provider id at another address, and is it as saved
|
||||
// at the address it was found at, if it was.
|
||||
func seekMoved(ctx context.Context, id string) (*Provider, bool) {
|
||||
p, err := Find(id)
|
||||
if err != nil || p.ID != id || !p.IsRemoteMagpie() {
|
||||
return nil, false
|
||||
}
|
||||
u, err := url.Parse(p.Chat)
|
||||
if err != nil || u.Port() == "" {
|
||||
return nil, false
|
||||
}
|
||||
if p.Key == "" {
|
||||
if on := p.KeysOn(); len(on) > 0 {
|
||||
p.Key = on[0].Key
|
||||
}
|
||||
}
|
||||
if p.Key == "" {
|
||||
return nil, false
|
||||
}
|
||||
seekMu.Lock()
|
||||
look := seekAt
|
||||
seekMu.Unlock()
|
||||
open := dialable(ctx, look(u.Hostname(), u.Port()))
|
||||
for _, at := range open {
|
||||
if ctx.Err() != nil {
|
||||
return nil, false
|
||||
}
|
||||
if !isRemote(ctx, *p, u.Scheme+"://"+at) {
|
||||
continue
|
||||
}
|
||||
q, err := Find(id)
|
||||
if err != nil || q.Chat != p.Chat {
|
||||
return nil, false // changed meanwhile: the user's word stands
|
||||
}
|
||||
was := q.Chat
|
||||
q.Chat, q.Responses, q.Anthropic, q.Decide = u.Scheme+"://"+at, "", "", ""
|
||||
if err := Save(*q); err != nil {
|
||||
log.Printf("%s: found at %s, not saved: %v", id, at, err)
|
||||
return nil, false
|
||||
}
|
||||
log.Printf("%s: %s didn't answer; found at %s, saved there", id, was, at)
|
||||
q, err = Find(id)
|
||||
return q, err == nil
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// isRemote says the magpie at root is p's: it lists for p's key, and
|
||||
// isn't this magpie.
|
||||
func isRemote(ctx context.Context, p Provider, root string) bool {
|
||||
p.Chat, p.Responses, p.Anthropic, p.Decide = root, "", "", ""
|
||||
p.remoteMagpieEndpoints()
|
||||
b, err := remoteBody(ctx, p, "GET", "/v1/models", seekAnswer)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
var list struct {
|
||||
Data []struct {
|
||||
Via []string `json:"magpie_via"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if json.Unmarshal(b, &list) != nil {
|
||||
return false
|
||||
}
|
||||
for _, m := range list.Data {
|
||||
if len(m.Via) > 0 {
|
||||
// a test's own gateway serves its Remote magpie (LeaveOutSelf)
|
||||
return !LeaveOutSelf || m.Via[len(m.Via)-1] != catalog.Self()
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// dialable is the addresses of ats that take a connection, in ats' order.
|
||||
func dialable(ctx context.Context, ats []string) []string {
|
||||
ok := make([]bool, len(ats))
|
||||
slots := make(chan struct{}, seekWide)
|
||||
var wg sync.WaitGroup
|
||||
d := net.Dialer{Timeout: seekDial}
|
||||
for i, at := range ats {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
select {
|
||||
case slots <- struct{}{}:
|
||||
case <-ctx.Done():
|
||||
return
|
||||
}
|
||||
defer func() { <-slots }()
|
||||
if c, err := d.DialContext(ctx, "tcp", at); err == nil {
|
||||
c.Close()
|
||||
ok[i] = true
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
var out []string
|
||||
for i, at := range ats {
|
||||
if ok[i] {
|
||||
out = append(out, at)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// lanNeighbours is every address at port of host's /24 and of each of
|
||||
// this computer's own private IPv4 networks' /24, this computer's own
|
||||
// addresses and host itself left out. A host that is a name, or not a
|
||||
// private IPv4 address, has none.
|
||||
func lanNeighbours(host, port string) []string {
|
||||
old := net.ParseIP(host).To4()
|
||||
if old == nil || !old.IsPrivate() {
|
||||
return nil
|
||||
}
|
||||
own := map[string]bool{old.String(): true}
|
||||
nets := []net.IP{old.Mask(net.CIDRMask(24, 32))}
|
||||
if addrs, err := net.InterfaceAddrs(); err == nil {
|
||||
for _, a := range addrs {
|
||||
n, ok := a.(*net.IPNet)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
ip := n.IP.To4()
|
||||
if ip == nil || !ip.IsPrivate() {
|
||||
continue
|
||||
}
|
||||
own[ip.String()] = true
|
||||
base := ip.Mask(net.CIDRMask(24, 32))
|
||||
if !containsIP(nets, base) && len(nets) < seekNets {
|
||||
nets = append(nets, base)
|
||||
}
|
||||
}
|
||||
}
|
||||
var out []string
|
||||
for _, base := range nets {
|
||||
for i := 1; i < 255; i++ {
|
||||
ip := net.IPv4(base[0], base[1], base[2], byte(i)).String()
|
||||
if !own[ip] {
|
||||
out = append(out, net.JoinHostPort(ip, port))
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func containsIP(ips []net.IP, ip net.IP) bool {
|
||||
for _, x := range ips {
|
||||
if x.Equal(ip) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
)
|
||||
|
||||
// a magpie on 127.0.0.1 that lists for key alone, its list made by lister
|
||||
func movedMagpie(t *testing.T, key, lister string, hits *atomic.Int32) string {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if hits != nil {
|
||||
hits.Add(1)
|
||||
}
|
||||
if r.Header.Get("x-api-key") != key {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
io.WriteString(w, `{"error":{"message":"send an enabled gateway key"}}`)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
io.WriteString(w, `{"object":"list","data":[{"id":"own/m1","object":"model","magpie_via":["`+lister+`"]}]}`)
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
return strings.TrimPrefix(srv.URL, "http://")
|
||||
}
|
||||
|
||||
// nobody listens on port 1
|
||||
const movedAway = "127.0.0.1:1"
|
||||
|
||||
func seekHere(t *testing.T, ats ...string) *atomic.Int32 {
|
||||
t.Helper()
|
||||
asked := new(atomic.Int32)
|
||||
t.Cleanup(SeekHere(nil))
|
||||
seekMu.Lock()
|
||||
seekAt = func(host, port string) []string { asked.Add(1); return ats }
|
||||
seekMu.Unlock()
|
||||
return asked
|
||||
}
|
||||
|
||||
// A Remote magpie whose computer came back at another address
|
||||
// (luckymanjc): its list, finding no one at the old one, is asked at the
|
||||
// address that lists for its key and isn't this magpie, and the
|
||||
// provider is saved there. A magpie that refuses the key, and this
|
||||
// magpie itself, are passed over.
|
||||
func TestRemoteMagpieFoundMoved(t *testing.T) {
|
||||
isolate(t)
|
||||
isolateFetchHome(t)
|
||||
other := movedMagpie(t, "someone-else", "c", nil)
|
||||
self := movedMagpie(t, "secret", catalog.Self(), nil)
|
||||
moved := movedMagpie(t, "secret", "a", nil)
|
||||
seekHere(t, movedAway, other, self, moved)
|
||||
id, err := Add(Provider{ID: "office", Name: "Office", Preset: RemoteMagpiePreset, Key: "secret", Chat: movedAway})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p, _ := Find(id)
|
||||
ms, err := p.Fetch(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("fetch: %v", err)
|
||||
}
|
||||
if len(ms) != 1 || ms[0].ID != "own/m1" {
|
||||
t.Errorf("listed %v, want own/m1", ms)
|
||||
}
|
||||
p, _ = Find(id)
|
||||
if p.Chat != "http://"+moved+"/v1" || p.Anthropic != "http://"+moved {
|
||||
t.Errorf("saved at %q / %q, want %s", p.Chat, p.Anthropic, moved)
|
||||
}
|
||||
}
|
||||
|
||||
// With no magpie of its key anywhere, nothing is saved and the list's
|
||||
// error stands; a look is made once a minute at most.
|
||||
func TestRemoteMagpieNotFoundStays(t *testing.T) {
|
||||
isolate(t)
|
||||
isolateFetchHome(t)
|
||||
other := movedMagpie(t, "someone-else", "c", nil)
|
||||
asked := seekHere(t, movedAway, other)
|
||||
id, err := Add(Provider{ID: "office", Name: "Office", Preset: RemoteMagpiePreset, Key: "secret", Chat: movedAway})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p, _ := Find(id)
|
||||
if _, err := p.Fetch(context.Background()); err == nil || !unconnected.MatchString(err.Error()) {
|
||||
t.Fatalf("fetch: %v, want the dial's error", err)
|
||||
}
|
||||
if _, err := p.Fetch(context.Background()); err == nil {
|
||||
t.Fatal("second fetch answered")
|
||||
}
|
||||
if n := asked.Load(); n != 1 {
|
||||
t.Errorf("looked %d times in a minute, want 1", n)
|
||||
}
|
||||
if q, _ := Find(id); q.Chat != "http://"+movedAway+"/v1" {
|
||||
t.Errorf("saved at %q", q.Chat)
|
||||
}
|
||||
}
|
||||
|
||||
// A remote that answers, however badly, is where it was: nobody looks.
|
||||
func TestRemoteMagpieAnsweringIsNotLookedFor(t *testing.T) {
|
||||
isolate(t)
|
||||
isolateFetchHome(t)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "boom", http.StatusInternalServerError)
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
asked := seekHere(t, movedMagpie(t, "secret", "a", nil))
|
||||
id, err := Add(Provider{ID: "office", Name: "Office", Preset: RemoteMagpiePreset, Key: "secret", Chat: strings.TrimPrefix(srv.URL, "http://")})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p, _ := Find(id)
|
||||
p.Fetch(context.Background())
|
||||
if n := asked.Load(); n != 0 {
|
||||
t.Errorf("looked %d times for a remote that answered", n)
|
||||
}
|
||||
}
|
||||
|
||||
// The addresses looked at: the old one's /24 at its port, itself left
|
||||
// out; none for a name or a public address.
|
||||
func TestLANNeighbours(t *testing.T) {
|
||||
got := lanNeighbours("192.168.77.20", "3425")
|
||||
for _, want := range []string{"192.168.77.1:3425", "192.168.77.21:3425", "192.168.77.254:3425"} {
|
||||
if !slices.Contains(got, want) {
|
||||
t.Errorf("missing %s", want)
|
||||
}
|
||||
}
|
||||
for _, not := range []string{"192.168.77.20:3425", "192.168.77.0:3425", "192.168.77.255:3425"} {
|
||||
if slices.Contains(got, not) {
|
||||
t.Errorf("has %s", not)
|
||||
}
|
||||
}
|
||||
if len(got) > seekNets*254 {
|
||||
t.Errorf("%d addresses", len(got))
|
||||
}
|
||||
for _, host := range []string{"a-pc.local", "8.8.8.8", "100.101.102.103", "::1"} {
|
||||
if got := lanNeighbours(host, "3425"); got != nil {
|
||||
t.Errorf("%s: looked at %d addresses", host, len(got))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The dial keeps what takes the connection.
|
||||
func TestDialable(t *testing.T) {
|
||||
up := movedMagpie(t, "k", "a", nil)
|
||||
got := dialable(context.Background(), []string{movedAway, up})
|
||||
if !slices.Equal(got, []string{up}) {
|
||||
t.Errorf("dialable = %v, want [%s]", got, up)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user