remote magpie: a list changed on the other magpie reaches this one's agents at once
KaCli (Discord) runs two magpies: the server's is the gateway, and the
local one has it as a Remote magpie and writes its models into dsh. A
route or group changed on the server reached the local dsh only on the
next 10-minute fetch (#2135's RemoteMagpieEvery). The server knows when
its list changes (filememo), so it now says so.
- Server: GET /v1/models with X-Magpie-List-Wait: <secs> and
If-None-Match answers the list with an ETag once it differs from that
tag. It answers 304 at the end of the wait (at most 50s, under a
proxy's 60s) or as the gateway stops. The list is looked at again on
each magpie write and on each change another process makes to its
files (filememo.Written). It is the list's own route, so the key,
lanGuard, corsGuard and a key's models judge it as before. The wait is
exempt from holdCatalog, and each look holds the catalog for itself.
Without the header the answer is the same as before, with no ETag.
- Client: KeepRemoteListsFollowed (started beside KeepListsFresh) keeps
one long-poll per Remote magpie. On a new tag it fetches the list
through the same RefetchTaking, so catalog.Touched rewrites the
agents' configs. A magpie from before answers at once with no ETag; it
is left to the 10m schedule and asked again after an hour. A Remote
magpie whose user set its list to "off" is not followed. The schedule
stays as the fallback.
Run (on mote, through mote-run):
- gofmt -l clean; go vet ./...; GOOS=linux go vet -tags nogui ./...;
GOOS=windows go vet ./...; go build ./..., GOOS=linux -tags nogui and
GOOS=windows builds: all ok.
- go test -tags nogui -count=1 ./internal/gateway ./internal/provider
./internal/catalog ./internal/filememo: all ok (gateway 863s, provider 152s, catalog, filememo).
- After the rebase on 650bf8412 (11 files changed under gateway and
provider since): go vet of both, go build ./..., and -run
"ModelsWait|RemoteMagpie|ListsFresh|HoldCatalog|Models" of both: ok.
- Two real magpies (this build, `serve`, sandbox HOMEs, 127.0.0.1:3561
server and :3562 local, a gateway key, dsh profile web wired to
office/up/m1). `magpie group add kacli-fast` on the server put
office/group/kacli-fast in the local cordis.patch.yml in 1.14s
(log: "office: its list changed there, fetched again: 3 models"). 130s
idle after it: no further fetch.
Control: origin/main on both, nothing in 37s. origin/main server, this
local: nothing in 37s, logged once "doesn't wait ... fetched on its
schedule", asked once.
Broken by hand, each red:
- Without the dispatch to the wait: TestModelsWaitTagged,
AnswersAChange, EndsWithTheGateway.
- Without the filememo.Written wake: TestModelsWaitAnswersAChange
(answered after 5.0s, at the others timer).
- Without RefetchTaking in the follower: TestRemoteMagpieListFollowed.
- Without the RefreshInterval > 0 check: TestRemoteMagpieOffNotFollowed
(asked 3 times).
- Removing the holdCatalog exemption is caught by no test: a held
catalog is still dropped on a write (heldFreshLocked), so the change is
seen. It is kept so a 50s hold doesn't pin the build, as with a
WebSocket.
Not tried: across two real computers on a LAN, or behind a reverse
proxy (only loopback with a key, and the LAN/no-key, foreign Origin and
Origin null refusals in TestModelsWaitGuardedAsTheList). Not tried on
Windows or Linux. Agents other than dsh weren't checked, though they go
through the same catalog.Touched sync.
Reported-by: KaCli (Discord)
This commit is contained in:
@@ -534,6 +534,21 @@ request alone. `Server.gatewayTrace` in
|
||||
`TestHeldKeyToldNoAccounts` in
|
||||
[`quotas_held_key_test.go`](../../internal/gateway/quotas_held_key_test.go).
|
||||
|
||||
`GET /v1/models` with `X-Magpie-List-Wait: <seconds>` is another magpie
|
||||
waiting for this one's list to change (KaCli on Discord). It is answered
|
||||
with an `ETag` once the list it would be answered is other than the one
|
||||
`If-None-Match` names, and 304 at the end of the wait (at most 50s,
|
||||
`listWaitMost`) or as the gateway stops (`streamsEnding`). The list is
|
||||
looked at again on each of magpie's writes and on each change another
|
||||
process makes to its files (`filememo.Written`), each look holding the
|
||||
catalog for itself, so the wait is exempt from `holdCatalog`. It is the
|
||||
list's own route, so the key, `lanGuard`, `corsGuard` and a key's models
|
||||
judge it exactly as the list. A list asked without the header is answered
|
||||
as before, with no ETag. `modelsOnceChanged` in
|
||||
[`models_wait.go`](../../internal/gateway/models_wait.go), and
|
||||
`TestModelsWaitGuardedAsTheList` in
|
||||
[`models_wait_test.go`](../../internal/gateway/models_wait_test.go).
|
||||
|
||||
A read-only gateway key (`access.Key.ReadOnly`, set by `add-key` or
|
||||
`access-key`; `magpie gateway-key add <name> --read-only`, `gateway-key
|
||||
access <id> read-only|full`, or the key's menu in Gateway → Gateway keys)
|
||||
|
||||
@@ -897,7 +897,8 @@ for: `provider_test`, `api_detect` or `model_list`
|
||||
all leaves them out.
|
||||
- **A model list answered is no row:** magpie fetches lists by itself
|
||||
(start-up's `FetchNew`, the panel's and the Providers page's, and
|
||||
`KeepListsFresh`, which asks a Remote magpie every 10 minutes), so a
|
||||
`KeepListsFresh`, which asks a Remote magpie every 10 minutes, and
|
||||
`KeepRemoteListsFollowed`, as soon as its list changes there), so a
|
||||
`model_list` row with a 2xx/3xx status and no error is neither written
|
||||
(`usage`'s `probelog.Sink`) nor read back from an older log
|
||||
(`quietProbe`, in the index's parse): ferock on Discord, a Requests page
|
||||
|
||||
@@ -33,7 +33,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
|
||||
| A provider renamed | `Rename` (the editor's id field, `magpie provider set <id> id=<new>`) keeps the old id in `Was`, so a model still picked by it reaches the provider. Usage is recorded under the id a call went out by and never rewritten; whatever reads it names the provider by its id now through `UsageRenames().Of(id, time)`: the summary, the Requests page (its blocks, the probe rows, other computers' days), the Sessions tab's vias, window holds, `NewPricer`/`NewCoster` and the gateway's `loggedAnswers` (cybercaius on Discord: a renamed provider was listed under both ids). `Visit` hands records out as recorded, so `Of` is taken once. An id another provider takes later (a rename onto it, or `Save` of a new provider under it) moves from the first one's `Was` to its `Gave` with the time (`giveID`): calls recorded under it before then stay the first one's, later ones are the new one's. An id held by a provider or a subscription now is never renamed (`Renamed`), and `freeID` doesn't hand out an id in any `Was`, so adding a vendor again gets `-2`. Ids reused before `Gave` existed have no time and go to whoever holds the id now. A provider deleted (`Delete`) is kept in providers.json's `deleted` with its name, `Was`, `Gave` and when (`provider.Deleted`): its calls stay under its id while no provider has that id, and once one is added under it (or a later deleted one had it) they go to `Deleted.UsageID`, `<id>~<when, UTC>`, so the new provider has only its own (cybercaius on Discord). The Usage page names either by the deleted provider's name and marks it with when it was deleted (`Renames.Gone`, `Named.Deleted`). Deletes before this was kept have no record and go to whoever holds the id now. A deleted provider's calls can be merged into a provider there is now, or named by the user, from a "…" beside the Requests page's Provider filter while it is picked (`ledProviderMore` in `plugins/usage/page.js`, `POST /api/usage/deleted`, `GET /api/usage/deleted/into`; CyberCaius on Discord, who had renamed a provider onto the old id to do it). Both are kept on its `Deleted` record, not in settings and never in the log: `MergeDeleted` sets `Into` and `MergedAt`, `NameDeleted` sets `Label` (`Deleted.Shown`), so a provider added later under the old id inherits neither. `Renames.Both(id, time)` gives the id a call is shown under (`Of`, merges followed) and the one it was made to (`Own`): a merged call is listed, filtered and summed under the target, but priced, held and answered by its own (`Record.priceID`, `block_price.go`'s `as`, window holds, `loggedAnswers`), so a merge moves no cost or token. The target's face lists what is merged into it (`Named.Merged`), and the same "…" parts each again (`into` ""). Renaming the target carries the merge; deleting it ends it (a merge older than the target's deletion is not followed). A providers.json that can't be read keeps the last renames read, not none. The summary and Requests caches key on `Renames.Key`, the vias cache too. | [`rename.go`](../../internal/provider/rename.go), [`block_price.go`](../../internal/usage/block_price.go) |
|
||||
| The list | `All` merges stored providers with `Accounts()`. An entry with no URL stores the user's picks for an account. The order is `file.Order`. Reads within one request share one build (`Hold`, #746). Requests that miss a build together (a write drops what is held) wait for the first one's build and take it, unless a write came while it was built; a wait is bounded (`heldWait`), so a caller never waits for good. Before, each built again behind `logins.json`'s lock, and requests sat past the 30s unrouted deadline (#5104: `TestLoginsMissedTogetherListedOnce`, `TestHeldWaiterBuildsAgainAfterAWrite`, `TestHeldWaiterNeverStuck`). `OwnPaused` is held the same way, once a request. | [`provider.go`](../../internal/provider/provider.go) |
|
||||
| Model picks | `Models` are the models the user picked for agents; none means the vendor's list, up to 24 (`Exposed`), unless the user chose Select none (`NoModels`, `magpie provider models <id> none`): then none of its models is served, not to agents, not to any routing group (auto groups included), not by a `provider/model` id, not as a classifier, while its balance and usage are still read (`ServesNone`, #1818). Codex's own list at `/backend-api/codex/models` drops the ChatGPT account's visible models too, as spawn_agent's list of them does, and the list's ETag changes so a running Codex asks again (`CodexNativePicked` in [`codex_models.go`](../../internal/provider/codex_models.go), #2530); the hidden ones Codex runs jobs of its own on (codex-auto-review, gpt-reserve) and other providers' models stay. The editor's serves control names it Usage only, beside Vendor's list and Picked only, and the card says "usage only" (#2068); Picked only from there picks the models the vendor's list serves, to unpick from. A file without `noModels` reads as before, and a pick clears it. With nothing picked and Select none off, Best in family (`BestInFamily`, `magpie provider models <id> best`, the editor's fourth option, Steven on Discord) serves only the newest model of each family the vendor lists, up to 24: the family is the id with its version numbers taken out, a dated snapshot counts as its alias, and sizes and suffixes (-mini, -pro, -8b) stay in the name (`FamilyOf`, `BestInFamily` in [`family.go`](../../internal/catalog/family.go)). A newer one the vendor lists later takes the old one's place with nothing saved. Codex's own list narrows the same way (`CodexNativePicked`). An older one named by its `provider/model` id is still served, as an unpicked one is under Picked only. A pick or Select none clears it, and a file without `bestInFamily` reads as before. `Save` keeps beside new picks the models listed then (`PickedFrom`, `listedWith`), and the same picks saved again keep it. When the picks held every model listed then, one the vendor lists since is served first beside them (`withNewlyListed`, `Picks`); one listed then and left unpicked stays out. Picks saved before `PickedFrom` was kept are taken to hold every model when they hold every one released up to the newest of them (models.dev's `release_date`), so a Claude account whose user picked them all is served Haiku 5.5 (wakaka). The editor and the TUI start from `Picks`, so a later Save keeps the new model. While some picks are set aside (the list is known to be short), a save with new picks keeps the models the earlier `PickedFrom` had beside those listed now, so a model the user saw and left unpicked isn't new when that list has it again; a list short of no pick is taken as it is. A pick a list fetched again stops listing (`Refetch`, `KeepListsFresh`, and a plugin's hourly `KeepPluginsListed`) leaves `Models` for `Delisted` (`dropGonePicks`), not served, and goes back among the picks when a later list has it (`relistPicks`): Our Free Model's plugin lists its account channels' models only once its service has read them after a restart, and its free pools only while they answer, so each magpie update had its user pick every model again (多喝热水 on Discord). Every save keeps `Delisted` but for what it picks again (`delistedWith`); Select none clears it. A provider whose every pick is in `Delisted` serves none of its models for `pickWait` (an hour) from when the last one left (`DelistedAt`, `waitsForPicks`), not the vendor's list; after that, or for picks set aside before `DelistedAt` was kept, the picks are taken as gone for good and the list is served as if none were picked, while they still come back with a list that has them. WorkBuddy AI took its Free plan's deepseek-v4.1-flash off its list for hy3, and an account whose one pick it was got no model in the agents' picker, its row reading "1 image model" (maxleebeta on Discord). `KeepPluginsListed` asks again after `relistSoon` (5 minutes) when a list left a pick out. `TestPluginPicksComeBackWithTheirList`, `TestEveryPickDelistedServesNone`, `TestPicksGoneForGoodServeTheList` and `TestRelayPicksComeBackWithTheirList` cover it. | [`models.go`](../../internal/provider/models.go), [`provider.go`](../../internal/provider/provider.go) |
|
||||
| List schedule and rules | A provider of the user's own (not an account, a plugin's or a decision-only one) can set `RefreshEvery` (`magpie provider refresh-every <id> 6h`, or 1d, or off, at least 10m) and `AutoInclude` (`magpie provider auto-include <id> 'gpt-*' 're:claude-.*'`, or none; a glob with `*`, or `re:` matching the whole id, both in any case (`compilePattern`; `(?-i)` inside a `re:` makes case matter); a plain id is refused) (#2135). The gateway (`magpie serve` or the app) looks each minute and fetches a list once `Fetched` is that old, through the same `Refetch` as Fetch models (`KeepListsFresh`); a failed fetch waits `min(every, 15m)`. `RefetchTaking` adds to the picks a model the fetch newly lists that a rule matches (`takeMatching`), starting from what is served now (`Exposed`), so nothing served is taken away and a model the user unticks stays out (it is not new to the next fetch). Setting the rules takes the current list's matches. Every save that doesn't set them keeps them, the window's editor among them; the editor has no fields for them yet. A Remote magpie with no `RefreshEvery` is fetched every 10m (`RemoteMagpieEvery`, `RefreshSchedule`), so a model the other magpie lists later (ZCode's GLM-5.3-Trial once its plugin read the gift, 6igsteven on Discord) is served without Fetch models; `off` set on it is kept as `"off"` and asks it only when told (`TestRemoteMagpieListFollowsTheOtherMagpie`). | [`autolist.go`](../../internal/provider/autolist.go), [`models.go`](../../internal/provider/models.go), [`providers_cli.go`](../../internal/cli/providers_cli.go) |
|
||||
| List schedule and rules | A provider of the user's own (not an account, a plugin's or a decision-only one) can set `RefreshEvery` (`magpie provider refresh-every <id> 6h`, or 1d, or off, at least 10m) and `AutoInclude` (`magpie provider auto-include <id> 'gpt-*' 're:claude-.*'`, or none; a glob with `*`, or `re:` matching the whole id, both in any case (`compilePattern`; `(?-i)` inside a `re:` makes case matter); a plain id is refused) (#2135). The gateway (`magpie serve` or the app) looks each minute and fetches a list once `Fetched` is that old, through the same `Refetch` as Fetch models (`KeepListsFresh`); a failed fetch waits `min(every, 15m)`. `RefetchTaking` adds to the picks a model the fetch newly lists that a rule matches (`takeMatching`), starting from what is served now (`Exposed`), so nothing served is taken away and a model the user unticks stays out (it is not new to the next fetch). Setting the rules takes the current list's matches. Every save that doesn't set them keeps them, the window's editor among them; the editor has no fields for them yet. A Remote magpie with no `RefreshEvery` is fetched every 10m (`RemoteMagpieEvery`, `RefreshSchedule`), so a model the other magpie lists later (ZCode's GLM-5.3-Trial once its plugin read the gift, 6igsteven on Discord) is served without Fetch models; `off` set on it is kept as `"off"` and asks it only when told (`TestRemoteMagpieListFollowsTheOtherMagpie`). The gateway also follows each Remote magpie's list as it changes there (KaCli on Discord: a route or group changed on the server reached the agents on the computer using it only on the next 10m): `KeepRemoteListsFollowed` keeps one long-poll per Remote magpie, a `GET /v1/models` with `X-Magpie-List-Wait` and the `If-None-Match` of its last answer, and on a new ETag fetches the list through the same `RefetchTaking`, so `catalog.Touched` rewrites the agents' configs within a second or two. A magpie from before answers at once with no ETag; it is left to the schedule and asked to wait again after an hour. One set to `off` is not followed (`TestRemoteMagpieListFollowed`, `TestRemoteMagpieOldListNotFollowed`, `TestRemoteMagpieOffNotFollowed` in [`remote_follow_test.go`](../../internal/provider/remote_follow_test.go)). | [`autolist.go`](../../internal/provider/autolist.go), [`models.go`](../../internal/provider/models.go), [`remote_follow.go`](../../internal/provider/remote_follow.go), [`providers_cli.go`](../../internal/cli/providers_cli.go) |
|
||||
| Keys | Several keys per provider. Requests go to the first key that is on; the gateway moves on when it is out or rate limited. `Key` stays the first, so other code reads it as before. A key can be made for one protocol (`KeyProtocol`): Anthropic, Chat, Responses or a custom provider's Gemini API (corddis_114 on Discord). `WithKey` leaves it that protocol's URL only, and the gateway puts the key that suits the model first (`keyFit`: Claude to the Anthropic key, GPT to a Chat or Responses one, Gemini to the Gemini one; `TestKeyMadeForGemini`, `TestKeyProtocolGemini`, `key-gemini.test.cjs`). A key made for a protocol its provider has no URL for is skipped (`perKeyBarred`); when every key is, the provider is still tried whole on the URLs it has, and the candidate carries `noURL` so it isn't quiet: Routing's row (`Weighed.NoURL`) says "key set to {api} only, no {api} URL · sent on the others", and the editor's key row shows a "No {api} URL" chip (`keyLacksURL`; #1702, `TestKeyForAProtocolWithNoURLIsSaid`, `key-nourl.test.cjs`). A key's value can be replaced in place (`ReplaceKey`, #1869: a key rotated at the vendor): it keeps its name, place, protocol, weight and on or off, and what was set for it by its fingerprint (`AccountModels`, `AccountProxies`, `AccountConcurrency`) and the gateway keys held to it (`access.ReplaceAccount`) move to the new one; the GUI's `keys/replace` also lifts its rests (`UnrestAll`). Its past requests stay under the old fingerprint, by the same name. A provider may hold thousands of keys (@NetRozee on X: a thousand froze magpie). Nothing goes over its keys once for each key: `KeysOn` drops a repeat by a set, a row's rest keys come from `RestKeys` (whether several are on, found once), and whether each key serves a model from `Serving`, which reads the lists once and keeps each model's keys as a set until the lists are read anew (`keyLists`). `KeysListed` and `ListsRead` count them for the tests (`TestProviderInfoListsKeysOnce`, `TestPerKeyReadsListsOnce`). A provider's keys have their balances, plans and remote limits read `keyReadsAtOnce` (8) at a time (`keySlots`); other providers' beside them. The editor's per-key proxy lines fold as its Accounts list does (`proxyLines`, `provider-many-keys-proxy.test.cjs`). Asking a key's models (`fetchPerKey`) still goes one key after another. Each Fetch models carries each key's list into the models it serves (`refreshKeyModels` in [`key_models_refresh.go`](../../internal/provider/key_models_refresh.go)): a key with a list of its own gains what its list gained and loses what it lost, keeping what the user ticked or un-ticked; a key on All models (the provider's first, one added before per-key lists, one whose list wasn't read in time when added) is given its own list when that list leaves out a model the other keys list. A key the user set to All models (`accountmodels` with none) is marked in `AccountModelsAll` and stays so; the editor's save keeps it. A key set to All models before the mark was kept has none, and is narrowed once to its list on the next Fetch (young02036 on Discord, `TestFetchTicksEachKeysListOnAllModels`, `TestFetchModelsTicksEveryKeysModels`). | [`keys.go`](../../internal/provider/keys.go), [`key_models_refresh.go`](../../internal/provider/key_models_refresh.go) |
|
||||
| Accounts at once | `MaxAccounts *int` is the user's own count of keys or accounts taking requests at the same time: nil takes the plugin's (`PluginAtOnce`: `maxAccounts` on the plugin's auth hook or package.json `magpie`, host.js `atOnceOf`), 0 is no limit, saved clamped to 0..`MaxLimit`; a subscription's is kept with its picks (`withPicks`). `AtOnce()` answers the one in force, `SetAtOnce` sets it (`magpie provider at-once`, the editor's Accounts at once; GUI save leaves it as it was when the body has none). The gateway's use is in [gateway routing](gateway-routing.md) (`TestAtOnce`, `TestAtOnceSave`, `TestAtOnceCmd`). | [`concurrency.go`](../../internal/provider/concurrency.go) |
|
||||
| A provider with no key | A provider of the user's own saves, imports and is `Ready` with no key when it is a preset with `NoKey` or its host is on this computer or the user's own network (`keyOptional`, `ownNetwork`): localhost, a loopback, private, link-local or carrier-grade NAT (Tailscale's 100.64/10) address, or a `.local` name, read from the URL alone with no lookup. A company's keyless relay at a LAN address is taken as a local server is (iSnow_999 on X: a Codex relay at http://<LAN IP>:8080 was left out of a CC Switch import as "it has no API key"); a keyless address on the internet still needs its key. With no key it is asked as one on 127.0.0.1 is: a Responses request carries no `Authorization`. | [`provider.go`](../../internal/provider/provider.go), [`importapps.go`](../../internal/provider/importapps.go), [`import_lan_test.go`](../../internal/provider/import_lan_test.go) |
|
||||
|
||||
@@ -844,6 +844,8 @@ func (s *Server) ListenAndServe(ctx context.Context) error {
|
||||
go provider.KeepAccountsListed(ctx)
|
||||
// and fetches the lists of the providers the user asked to keep fresh (#2135)
|
||||
go provider.KeepListsFresh(ctx)
|
||||
// and follows a Remote magpie's list as it changes there (KaCli)
|
||||
go provider.KeepRemoteListsFollowed(ctx)
|
||||
// and keeps the community's plugins up to date, noting others' updates, and the Bun they run on
|
||||
go plugin.KeepUpdated(ctx)
|
||||
go plugin.KeepBunUpdated(ctx)
|
||||
@@ -1545,6 +1547,15 @@ func listKinds(r *http.Request) (chat, image, video bool, err error) {
|
||||
}
|
||||
|
||||
func (s *Server) models(w http.ResponseWriter, r *http.Request) {
|
||||
if waitsForList(r) {
|
||||
// another magpie waiting for the list to change (models_wait.go)
|
||||
s.modelsOnceChanged(w, r)
|
||||
return
|
||||
}
|
||||
s.listModels(w, r)
|
||||
}
|
||||
|
||||
func (s *Server) listModels(w http.ResponseWriter, r *http.Request) {
|
||||
data := []map[string]any{}
|
||||
chat, images, videos, err := listKinds(r)
|
||||
if err != nil {
|
||||
|
||||
@@ -17,8 +17,10 @@ import (
|
||||
// and a file another program writes is seen within the second.
|
||||
func holdCatalog(h http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// a WebSocket lasts a session: each of its turns holds it instead
|
||||
if wantsSocket(r) {
|
||||
// a WebSocket lasts a session: each of its turns holds it
|
||||
// instead, as each look at the list does for another magpie's
|
||||
// wait for its change (modelsOnceChanged)
|
||||
if wantsSocket(r) || waitsForList(r) {
|
||||
h.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/filememo"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// Another magpie that has this one as its provider (remote-magpie) waits
|
||||
// here for this magpie's model list to change, and fetches it again when
|
||||
// it has (KaCli on Discord: a route or group changed on the server reached
|
||||
// the computer using it only on its next 10-minute fetch, and its agents'
|
||||
// configs after that). It is the list's own route, GET /v1/models, so
|
||||
// every guard a list asked for passes (the key, the origin, the network
|
||||
// share, a key's models) holds for the wait as well, with
|
||||
// provider.ListWaitHeader saying how many seconds to wait at most and
|
||||
// If-None-Match the list it has (the ETag of its last answer). The list
|
||||
// is answered, with its ETag, once it is other than that one; at the end
|
||||
// of the wait, and as this gateway stops, 304 says it is the same. A list
|
||||
// is looked at again on each write magpie makes and on each change
|
||||
// another process makes to its files (filememo.Written), not polled.
|
||||
// A client asking without the header is answered as before, no ETag.
|
||||
|
||||
// listWaitMost is the longest a wait for the list is held: under the
|
||||
// minute a proxy in front of a gateway (nginx's proxy_read_timeout) lets
|
||||
// an answer take.
|
||||
const listWaitMost = 50 * time.Second
|
||||
|
||||
// listSettle is how long a write is given for the ones that come with it
|
||||
// (a group saved, then the catalog touched) before the list is looked at.
|
||||
var listSettle = 200 * time.Millisecond
|
||||
|
||||
// waitsForList reports whether r is another magpie waiting for the list to
|
||||
// change.
|
||||
func waitsForList(r *http.Request) bool {
|
||||
if r.Method != http.MethodGet || r.Header.Get(provider.ListWaitHeader) == "" {
|
||||
return false
|
||||
}
|
||||
return r.URL.Path == "/v1/models" || r.URL.Path == "/models"
|
||||
}
|
||||
|
||||
// listWaitOf is how long r asks to wait, at most listWaitMost.
|
||||
func listWaitOf(r *http.Request) time.Duration {
|
||||
n, err := strconv.Atoi(strings.TrimSpace(r.Header.Get(provider.ListWaitHeader)))
|
||||
if err != nil || n <= 0 {
|
||||
return 0
|
||||
}
|
||||
return min(time.Duration(n)*time.Second, listWaitMost)
|
||||
}
|
||||
|
||||
// listTag is a list answer's ETag: of the bytes answered, so it moves
|
||||
// exactly when what another magpie would fetch does.
|
||||
func listTag(status int, body []byte) string {
|
||||
h := sha256.New()
|
||||
h.Write([]byte(strconv.Itoa(status)))
|
||||
h.Write(body)
|
||||
return `"ml-` + hex.EncodeToString(h.Sum(nil)[:12]) + `"`
|
||||
}
|
||||
|
||||
// listAnswer is the list as r would be answered it now.
|
||||
type listAnswer struct {
|
||||
header http.Header
|
||||
status int
|
||||
body bytes.Buffer
|
||||
}
|
||||
|
||||
func (a *listAnswer) Header() http.Header { return a.header }
|
||||
func (a *listAnswer) WriteHeader(code int) {
|
||||
if a.status == 0 {
|
||||
a.status = code
|
||||
}
|
||||
}
|
||||
func (a *listAnswer) Write(b []byte) (int, error) {
|
||||
a.WriteHeader(http.StatusOK)
|
||||
return a.body.Write(b)
|
||||
}
|
||||
|
||||
// lookAtList answers r's list into a listAnswer, holding the catalog and
|
||||
// files it reads for the one look, as holdCatalog does for a request.
|
||||
func (s *Server) lookAtList(r *http.Request) *listAnswer {
|
||||
a := &listAnswer{header: http.Header{}}
|
||||
release, held := provider.Hold(), filememo.Hold()
|
||||
defer release()
|
||||
defer held()
|
||||
s.listModels(a, r)
|
||||
if a.status == 0 {
|
||||
a.status = http.StatusOK
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
// modelsOnceChanged answers r's list once it is other than the one r's
|
||||
// If-None-Match names, or 304 at the end of the wait.
|
||||
func (s *Server) modelsOnceChanged(w http.ResponseWriter, r *http.Request) {
|
||||
since := strings.TrimSpace(r.Header.Get("If-None-Match"))
|
||||
end := time.NewTimer(listWaitOf(r))
|
||||
defer end.Stop()
|
||||
tag := ""
|
||||
for {
|
||||
// before the look, so a write made during it isn't missed
|
||||
written := filememo.Written()
|
||||
a := s.lookAtList(r)
|
||||
tag = listTag(a.status, a.body.Bytes())
|
||||
if a.status != http.StatusOK || tag != since {
|
||||
for k, v := range a.header {
|
||||
w.Header()[k] = v
|
||||
}
|
||||
if a.status == http.StatusOK {
|
||||
w.Header().Set("ETag", tag)
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.WriteHeader(a.status)
|
||||
w.Write(a.body.Bytes())
|
||||
return
|
||||
}
|
||||
// another process's writes are seen at once while filememo.Watch
|
||||
// runs, and every few seconds where it can't
|
||||
others := time.NewTimer(filememo.OthersEvery())
|
||||
select {
|
||||
case <-r.Context().Done():
|
||||
others.Stop()
|
||||
return
|
||||
case <-s.streamsEnding():
|
||||
case <-end.C:
|
||||
case <-written:
|
||||
others.Stop()
|
||||
settle := time.NewTimer(listSettle)
|
||||
select {
|
||||
case <-r.Context().Done():
|
||||
settle.Stop()
|
||||
return
|
||||
case <-settle.C:
|
||||
}
|
||||
continue
|
||||
case <-others.C:
|
||||
continue
|
||||
}
|
||||
others.Stop()
|
||||
w.Header().Set("ETag", tag)
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.WriteHeader(http.StatusNotModified)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// listAsk asks srv's list, waiting wait seconds at the list tag names when
|
||||
// wait is set.
|
||||
func listAsk(t *testing.T, url, wait, tag string) (int, string, string) {
|
||||
t.Helper()
|
||||
req, _ := http.NewRequest("GET", url+"/v1/models", nil)
|
||||
if wait != "" {
|
||||
req.Header.Set(provider.ListWaitHeader, wait)
|
||||
}
|
||||
if tag != "" {
|
||||
req.Header.Set("If-None-Match", tag)
|
||||
}
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
b, _ := io.ReadAll(res.Body)
|
||||
return res.StatusCode, res.Header.Get("ETag"), string(b)
|
||||
}
|
||||
|
||||
// Another magpie waiting at the list (KaCli) is answered the list's ETag;
|
||||
// the same list is held to the end of the wait and answered 304, and a
|
||||
// list asked without the header is answered as before, with no ETag.
|
||||
func TestModelsWaitTagged(t *testing.T) {
|
||||
setup(t, provider.Chat, &fake{t: t})
|
||||
srv := httptest.NewServer(New().Handler())
|
||||
defer srv.Close()
|
||||
|
||||
code, tag, plain := listAsk(t, srv.URL, "", "")
|
||||
if code != 200 || tag != "" {
|
||||
t.Fatalf("a plain list: %d, ETag %q; want 200 and none", code, tag)
|
||||
}
|
||||
code, tag, body := listAsk(t, srv.URL, "1", "")
|
||||
if code != 200 || tag == "" || body != plain {
|
||||
t.Fatalf("a wait with no tag: %d, ETag %q, same body %v", code, tag, body == plain)
|
||||
}
|
||||
start := time.Now()
|
||||
code, again, _ := listAsk(t, srv.URL, "1", tag)
|
||||
if code != http.StatusNotModified || again != tag {
|
||||
t.Fatalf("the same list: %d, ETag %q; want 304 %q", code, again, tag)
|
||||
}
|
||||
if d := time.Since(start); d < 900*time.Millisecond {
|
||||
t.Errorf("the same list answered after %v, before its wait ended", d)
|
||||
}
|
||||
}
|
||||
|
||||
// A change saved while another magpie waits answers it the new list at
|
||||
// once, not at the end of its wait.
|
||||
func TestModelsWaitAnswersAChange(t *testing.T) {
|
||||
setup(t, provider.Chat, &fake{t: t})
|
||||
srv := httptest.NewServer(New().Handler())
|
||||
defer srv.Close()
|
||||
_, tag, _ := listAsk(t, srv.URL, "1", "")
|
||||
|
||||
go func() {
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
if err := provider.Save(provider.Provider{ID: "fake2", Name: "Fake 2", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"m2"}}); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}()
|
||||
start := time.Now()
|
||||
code, now, body := listAsk(t, srv.URL, "30", tag)
|
||||
if code != 200 || now == "" || now == tag {
|
||||
t.Fatalf("after a change: %d, ETag %q (was %q)", code, now, tag)
|
||||
}
|
||||
if !strings.Contains(body, "m2") {
|
||||
t.Errorf("the new list lacks m2: %s", body)
|
||||
}
|
||||
if d := time.Since(start); d > 3*time.Second {
|
||||
t.Errorf("the change answered after %v", d)
|
||||
}
|
||||
}
|
||||
|
||||
// A gateway stopping ends every wait with 304: the other magpie keeps its
|
||||
// tag and asks the next gateway.
|
||||
func TestModelsWaitEndsWithTheGateway(t *testing.T) {
|
||||
setup(t, provider.Chat, &fake{t: t})
|
||||
s := New()
|
||||
srv := httptest.NewServer(s.Handler())
|
||||
defer srv.Close()
|
||||
_, tag, _ := listAsk(t, srv.URL, "1", "")
|
||||
go func() {
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
s.endStreams()
|
||||
}()
|
||||
start := time.Now()
|
||||
code, _, _ := listAsk(t, srv.URL, "30", tag)
|
||||
if code != http.StatusNotModified {
|
||||
t.Fatalf("a wait as the gateway stops: %d, want 304", code)
|
||||
}
|
||||
if d := time.Since(start); d > 3*time.Second {
|
||||
t.Errorf("answered after %v", d)
|
||||
}
|
||||
}
|
||||
|
||||
// The wait is the list's own route: a caller the list refuses (another
|
||||
// computer with no key, a foreign page) is refused it the same with the
|
||||
// header, before anything waits.
|
||||
func TestModelsWaitGuardedAsTheList(t *testing.T) {
|
||||
fresh(t)
|
||||
t.Setenv("MAGPIE_ADDR", "")
|
||||
setup(t, provider.Chat, &fake{t: t})
|
||||
newCaller(t, "LAN client")
|
||||
h := New().Front()
|
||||
ask := func(remote, origin string, wait bool) (int, string) {
|
||||
r := httptest.NewRequest("GET", "/v1/models", nil)
|
||||
r.RemoteAddr = remote
|
||||
if origin != "" {
|
||||
r.Header.Set("Origin", origin)
|
||||
}
|
||||
if wait {
|
||||
r.Header.Set(provider.ListWaitHeader, "30")
|
||||
r.Header.Set("If-None-Match", `"ml-anything"`)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
done := make(chan struct{})
|
||||
go func() { defer close(done); h.ServeHTTP(w, r) }()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatalf("%s %s was held", remote, origin)
|
||||
}
|
||||
return w.Code, w.Body.String()
|
||||
}
|
||||
for _, c := range []struct{ remote, origin string }{
|
||||
{"192.168.1.9:5000", ""},
|
||||
{"127.0.0.1:5000", "https://evil.example"},
|
||||
{"127.0.0.1:5000", "null"},
|
||||
} {
|
||||
plain, _ := ask(c.remote, c.origin, false)
|
||||
if plain == 200 {
|
||||
t.Fatalf("%s %s: the plain list was answered; the case tests nothing", c.remote, c.origin)
|
||||
}
|
||||
waited, body := ask(c.remote, c.origin, true)
|
||||
if waited != plain {
|
||||
t.Errorf("%s %s: %d with the wait, %d without (%s)", c.remote, c.origin, waited, plain, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
"github.com/yetone/magpie/internal/filememo"
|
||||
)
|
||||
|
||||
// A Remote magpie's list is followed (KaCli on Discord): the magpie
|
||||
// serving the gateway here waits at the other magpie's list for it to
|
||||
// change (ListWaitHeader), and fetches it again the moment it has, through
|
||||
// the same RefetchTaking as KeepListsFresh, so the agents' configs written
|
||||
// from it (catalog.Touched, then their Sync) follow a route, group or
|
||||
// provider changed there within seconds rather than on the next
|
||||
// RemoteMagpieEvery. The schedule stays, for a magpie from before that
|
||||
// doesn't wait (it answers its list at once, with no ETag), which is then
|
||||
// asked to wait again only after followOldAgain. A Remote magpie whose
|
||||
// user set its list to be fetched only when asked ("off") is not
|
||||
// followed either.
|
||||
|
||||
// ListWaitHeader asks a magpie's model list to be answered once it is
|
||||
// other than the one If-None-Match names, waiting up to the seconds it
|
||||
// says; at the end of the wait, 304 says it is the same.
|
||||
const ListWaitHeader = "X-Magpie-List-Wait"
|
||||
|
||||
// listWaitAsk is how many seconds a follower asks the other magpie to
|
||||
// wait, which holds it under a minute (the gateway's listWaitMost).
|
||||
const listWaitAsk = 50
|
||||
|
||||
// follow paces: the shortest time between two asks of one magpie, the
|
||||
// first wait after a failure (doubled to followFailMost), and how long
|
||||
// a magpie that doesn't wait is left to the schedule alone.
|
||||
var (
|
||||
followGap = time.Second
|
||||
followFailWait = 5 * time.Second
|
||||
followFailMost = 5 * time.Minute
|
||||
followOldAgain = time.Hour
|
||||
// followLook is how often the providers followed are looked at again
|
||||
// with no write of magpie's to say they changed
|
||||
followLook = time.Minute
|
||||
)
|
||||
|
||||
// errListNotWaited is a magpie that answered the list at once, with no
|
||||
// ETag: one from before ListWaitHeader.
|
||||
var errListNotWaited = errors.New("its magpie doesn't wait for its list to change; fetched on its schedule")
|
||||
|
||||
// KeepRemoteListsFollowed follows the list of each Remote magpie the user
|
||||
// has, while ctx lasts: run by the magpie serving the gateway, beside
|
||||
// KeepListsFresh.
|
||||
func KeepRemoteListsFollowed(ctx context.Context) {
|
||||
type follower struct {
|
||||
stop context.CancelFunc
|
||||
done chan struct{}
|
||||
}
|
||||
going := map[string]follower{}
|
||||
defer func() {
|
||||
for _, f := range going {
|
||||
f.stop()
|
||||
<-f.done
|
||||
}
|
||||
}()
|
||||
for {
|
||||
written := filememo.Written()
|
||||
want := map[string]Provider{}
|
||||
for _, p := range followedMagpies() {
|
||||
want[followKey(p)] = p
|
||||
}
|
||||
for k, f := range going {
|
||||
if _, ok := want[k]; !ok {
|
||||
f.stop()
|
||||
<-f.done
|
||||
delete(going, k)
|
||||
}
|
||||
}
|
||||
for k, p := range want {
|
||||
if _, ok := going[k]; ok {
|
||||
continue
|
||||
}
|
||||
fctx, stop := context.WithCancel(ctx)
|
||||
f := follower{stop, make(chan struct{})}
|
||||
going[k] = f
|
||||
go func() {
|
||||
defer close(f.done)
|
||||
followList(fctx, p.ID)
|
||||
}()
|
||||
}
|
||||
look := time.NewTimer(followLook)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
look.Stop()
|
||||
return
|
||||
case <-written:
|
||||
case <-look.C:
|
||||
}
|
||||
look.Stop()
|
||||
}
|
||||
}
|
||||
|
||||
// followedMagpies are the Remote magpies whose lists are followed: on,
|
||||
// listing, not this magpie itself, with a schedule (their user's, or
|
||||
// RemoteMagpieEvery when none is set).
|
||||
func followedMagpies() []Provider {
|
||||
own, _ := ownOf(load())
|
||||
var out []Provider
|
||||
for _, p := range own {
|
||||
if p.IsRemoteMagpie() && !p.Off && p.lists() && p.Anthropic != "" && !p.SelfLeftOut() && p.RefreshInterval() > 0 {
|
||||
out = append(out, p)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// followKey tells a follower to start again when what it asks with is
|
||||
// another: its address, key, headers or proxy.
|
||||
func followKey(p Provider) string {
|
||||
return fmt.Sprint(p.ID, "\x00", p.Anthropic, "\x00", p.Key, "\x00", p.Proxy, "\x00", p.Headers)
|
||||
}
|
||||
|
||||
// followed counts, for the tests, the lists a follower fetched again.
|
||||
var followed = struct {
|
||||
sync.Mutex
|
||||
n map[string]int
|
||||
}{n: map[string]int{}}
|
||||
|
||||
// followList waits at the Remote magpie id's list for its change, and
|
||||
// fetches it again each time it changed, until ctx ends. The list it has
|
||||
// first is fetched once too: it may have changed since it was fetched.
|
||||
func followList(ctx context.Context, id string) {
|
||||
tag := ""
|
||||
failWait := followFailWait
|
||||
pause := func(d time.Duration) bool {
|
||||
t := time.NewTimer(d)
|
||||
defer t.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
case <-t.C:
|
||||
return true
|
||||
}
|
||||
}
|
||||
for ctx.Err() == nil {
|
||||
asked := time.Now()
|
||||
p := followedOne(id)
|
||||
if p == nil {
|
||||
return
|
||||
}
|
||||
now, err := waitRemoteList(ctx, *p, tag)
|
||||
switch {
|
||||
case ctx.Err() != nil:
|
||||
return
|
||||
case errors.Is(err, errListNotWaited):
|
||||
log.Printf("%s: %v", id, err)
|
||||
tag = ""
|
||||
if !pause(followOldAgain) {
|
||||
return
|
||||
}
|
||||
continue
|
||||
case err != nil:
|
||||
if !pause(failWait) {
|
||||
return
|
||||
}
|
||||
failWait = min(failWait*2, followFailMost)
|
||||
continue
|
||||
}
|
||||
failWait = followFailWait
|
||||
if now != tag {
|
||||
fctx, cancel := context.WithTimeout(ctx, time.Minute)
|
||||
ms, dropped, taken, err := p.RefetchTaking(fctx)
|
||||
cancel()
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
// the tag isn't kept, so the next answer fetches again
|
||||
log.Printf("%s: its list changed there, and its fetch failed: %s", id, err)
|
||||
if !pause(failWait) {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
if tag != "" {
|
||||
log.Printf("%s: its list changed there, fetched again: %d models%s%s", id, len(ms), listNote(" taken by rule: ", taken), listNote(" no longer listed: ", dropped))
|
||||
}
|
||||
followed.Lock()
|
||||
followed.n[id]++
|
||||
followed.Unlock()
|
||||
tag = now
|
||||
}
|
||||
if wait := followGap - time.Since(asked); wait > 0 && !pause(wait) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// followedOne is the Remote magpie id as it is saved now, if it is still
|
||||
// followed.
|
||||
func followedOne(id string) *Provider {
|
||||
for _, p := range followedMagpies() {
|
||||
if p.ID == id {
|
||||
return &p
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// waitRemoteList asks p's list to be answered once it is other than the
|
||||
// one tag names, and answers the tag of the list it has now. It is asked
|
||||
// as the list is fetched (listHeaders, signRemote), so the list the other
|
||||
// magpie compares is the one a fetch is answered.
|
||||
func waitRemoteList(ctx context.Context, p Provider, tag string) (string, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, (listWaitAsk+20)*time.Second)
|
||||
defer cancel()
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, p.Anthropic+"/v1/models", nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
req.Header.Set("User-Agent", "magpie")
|
||||
for k, v := range p.listHeaders() {
|
||||
catalog.PutUserHeader(req.Header, k, v)
|
||||
}
|
||||
p.signRemote(req, p.Key)
|
||||
req.Header.Set(ListWaitHeader, strconv.Itoa(listWaitAsk))
|
||||
if tag != "" {
|
||||
req.Header.Set("If-None-Match", tag)
|
||||
}
|
||||
res, err := p.Do(http.DefaultClient, req)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
io.Copy(io.Discard, io.LimitReader(res.Body, 64<<20))
|
||||
switch {
|
||||
case res.StatusCode == http.StatusNotModified:
|
||||
return tag, nil
|
||||
case res.StatusCode != http.StatusOK:
|
||||
return "", fmt.Errorf("%s answered %s", remoteName(p), res.Status)
|
||||
}
|
||||
now := res.Header.Get("ETag")
|
||||
if now == "" {
|
||||
return "", errListNotWaited
|
||||
}
|
||||
return now, nil
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// followFake is a magpie whose list is model, answered with its ETag, and
|
||||
// held while a wait names that tag, as the gateway's modelsOnceChanged
|
||||
// does. waits says whether it waits at all (one from before doesn't).
|
||||
type followFake struct {
|
||||
mu sync.Mutex
|
||||
model string
|
||||
changed chan struct{}
|
||||
waits bool
|
||||
fetches atomic.Int32 // asked with no wait: the list fetched
|
||||
asks atomic.Int32 // asked to wait
|
||||
}
|
||||
|
||||
func (f *followFake) set(model string) {
|
||||
f.mu.Lock()
|
||||
f.model = model
|
||||
close(f.changed)
|
||||
f.changed = make(chan struct{})
|
||||
f.mu.Unlock()
|
||||
}
|
||||
|
||||
func (f *followFake) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("x-api-key") != "secret" {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
waiting := r.Header.Get(ListWaitHeader) != ""
|
||||
if !waiting {
|
||||
f.fetches.Add(1)
|
||||
} else {
|
||||
f.asks.Add(1)
|
||||
}
|
||||
for {
|
||||
f.mu.Lock()
|
||||
model, changed := f.model, f.changed
|
||||
f.mu.Unlock()
|
||||
tag := `"` + model + `"`
|
||||
if waiting && f.waits && r.Header.Get("If-None-Match") == tag {
|
||||
select {
|
||||
case <-changed:
|
||||
continue
|
||||
case <-r.Context().Done():
|
||||
return
|
||||
case <-time.After(2 * time.Second):
|
||||
w.Header().Set("ETag", tag)
|
||||
w.WriteHeader(http.StatusNotModified)
|
||||
return
|
||||
}
|
||||
}
|
||||
if waiting && f.waits {
|
||||
w.Header().Set("ETag", tag)
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
io.WriteString(w, `{"object":"list","data":[{"id":"`+model+`","object":"model"}]}`)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func followFast(t *testing.T) {
|
||||
t.Helper()
|
||||
gap, fail, old, look := followGap, followFailWait, followOldAgain, followLook
|
||||
followGap, followFailWait, followOldAgain, followLook = 10*time.Millisecond, 50*time.Millisecond, time.Hour, 50*time.Millisecond
|
||||
t.Cleanup(func() { followGap, followFailWait, followOldAgain, followLook = gap, fail, old, look })
|
||||
}
|
||||
|
||||
func followedCount(id string) int {
|
||||
followed.Lock()
|
||||
defer followed.Unlock()
|
||||
return followed.n[id]
|
||||
}
|
||||
|
||||
func followUntil(t *testing.T, what string, ok func() bool) {
|
||||
t.Helper()
|
||||
end := time.Now().Add(10 * time.Second)
|
||||
for !ok() {
|
||||
if time.Now().After(end) {
|
||||
t.Fatalf("never: %s", what)
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func followedIDs(t *testing.T, id string) string {
|
||||
t.Helper()
|
||||
p, err := Find(id)
|
||||
if err != nil {
|
||||
t.Fatalf("%s gone", id)
|
||||
}
|
||||
ms, _, _ := p.live()
|
||||
var ids []string
|
||||
for _, m := range ms {
|
||||
ids = append(ids, m.ID)
|
||||
}
|
||||
return strings.Join(ids, ",")
|
||||
}
|
||||
|
||||
func followRemote(t *testing.T, f *followFake, every string) string {
|
||||
t.Helper()
|
||||
isolate(t)
|
||||
isolateFetchHome(t)
|
||||
followFast(t)
|
||||
srv := httptest.NewServer(f)
|
||||
t.Cleanup(srv.Close)
|
||||
id, err := Add(Provider{ID: "office", Name: "Office", Preset: RemoteMagpiePreset, Key: "secret", Chat: strings.TrimPrefix(srv.URL, "http://"), RefreshEvery: every})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
followed.Lock()
|
||||
delete(followed.n, id)
|
||||
followed.Unlock()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan struct{})
|
||||
go func() { defer close(done); KeepRemoteListsFollowed(ctx) }()
|
||||
t.Cleanup(func() { cancel(); <-done })
|
||||
return id
|
||||
}
|
||||
|
||||
// A list changed on the Remote magpie is fetched here at once (KaCli), not
|
||||
// on the next RemoteMagpieEvery: the follower waits at the list and fetches
|
||||
// it again the moment its tag moves.
|
||||
func TestRemoteMagpieListFollowed(t *testing.T) {
|
||||
f := &followFake{model: "own/m1", changed: make(chan struct{}), waits: true}
|
||||
id := followRemote(t, f, "")
|
||||
followUntil(t, "the first list fetched", func() bool { return followedCount(id) >= 1 })
|
||||
if got := followedIDs(t, id); got != "own/m1" {
|
||||
t.Fatalf("listed %q, want own/m1", got)
|
||||
}
|
||||
before := f.fetches.Load()
|
||||
f.set("own/m2")
|
||||
followUntil(t, "the changed list fetched", func() bool { return followedIDs(t, id) == "own/m2" })
|
||||
if f.fetches.Load() == before {
|
||||
t.Error("the list wasn't fetched again")
|
||||
}
|
||||
// the same list again is waited at, not fetched again and again
|
||||
n := f.fetches.Load()
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
if f.fetches.Load() != n {
|
||||
t.Errorf("fetched %d times with no change", f.fetches.Load()-n)
|
||||
}
|
||||
}
|
||||
|
||||
// A magpie from before answers its list at once with no ETag: it is left
|
||||
// to the schedule, asked to wait again only after followOldAgain, so it is
|
||||
// not asked over and over.
|
||||
func TestRemoteMagpieOldListNotFollowed(t *testing.T) {
|
||||
f := &followFake{model: "own/m1", changed: make(chan struct{})}
|
||||
followRemote(t, f, "")
|
||||
followUntil(t, "asked once", func() bool { return f.asks.Load() >= 1 })
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
if n := f.asks.Load(); n != 1 {
|
||||
t.Errorf("an old magpie asked %d times, want once", n)
|
||||
}
|
||||
if n := f.fetches.Load(); n != 0 {
|
||||
t.Errorf("an old magpie's list fetched %d times by the follower, want 0: its schedule fetches it", n)
|
||||
}
|
||||
}
|
||||
|
||||
// A Remote magpie whose user set its list to be fetched only when asked
|
||||
// is not followed: magpie's default never overrides the user's "off".
|
||||
func TestRemoteMagpieOffNotFollowed(t *testing.T) {
|
||||
f := &followFake{model: "own/m1", changed: make(chan struct{}), waits: true}
|
||||
followRemote(t, f, "off")
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
if n := f.asks.Load() + f.fetches.Load(); n != 0 {
|
||||
t.Errorf("a list set to off was asked %d times", n)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user