ipfs-follow takes any set of parts and doesn't hang on a stalled fetch
A pin that gets no new block for 20 minutes gives up, so a publish the swarm can't serve whole no longer holds the node until the next hour never comes. A fresh daemon has no peers yet, so the name lookup is retried for a few minutes instead of failing the first run. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
68ba3c0d8c
commit
8b2fb34614
2 files changed
+141
-17
No files matched your search
+97
-15
@@ -9,18 +9,55 @@ import (
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// PartNames are the parts of a publish, in the order they're fetched.
|
||||
var PartNames = []string{"oci", "packages", "git", "bin"}
|
||||
|
||||
// Parts reads which parts to host: names from PartNames, comma-separated,
|
||||
// or "all", or "images" (oci).
|
||||
func Parts(spec string) ([]string, error) {
|
||||
switch spec {
|
||||
case "all":
|
||||
return PartNames, nil
|
||||
case "images":
|
||||
return []string{"oci"}, nil
|
||||
}
|
||||
var names []string
|
||||
for _, n := range strings.Split(spec, ",") {
|
||||
if !slices.Contains(PartNames, n) {
|
||||
return nil, fmt.Errorf("parts are all, images, or some of %s, not %q", strings.Join(PartNames, ","), spec)
|
||||
}
|
||||
if !slices.Contains(names, n) {
|
||||
names = append(names, n)
|
||||
}
|
||||
}
|
||||
return names, nil
|
||||
}
|
||||
|
||||
// resolveTries and resolveWait are how often, and how far apart, Follow
|
||||
// looks the name up before giving up until the next run.
|
||||
var resolveTries, resolveWait = 10, 30 * time.Second
|
||||
|
||||
// stall is how long a fetch may go without a new block before Follow gives
|
||||
// up, so a publish the swarm can't serve whole doesn't hold the node forever.
|
||||
var stall = 20 * time.Minute
|
||||
|
||||
// Follow keeps a hosting node's copy of the newest publish: it resolves
|
||||
// the IPNS name on the node at api, checks the index's signature, pins
|
||||
// what parts asks for ("all", or "images": the OCI layout) with the index
|
||||
// itself, then unpins what the last run pinned and collects it. state is
|
||||
// a file remembering that, and the newest version seen, so an older
|
||||
// publish is never taken over a newer one.
|
||||
// the parts asked for (see Parts) with the index itself, then unpins what
|
||||
// the last run pinned and collects it. state is a file remembering that,
|
||||
// and the newest version seen, so an older publish is never taken over a
|
||||
// newer one.
|
||||
func Follow(ctx context.Context, api, parts, state string, log func(string)) error {
|
||||
c := apiClient{base: strings.TrimRight(api, "/") + "/api/v0/"}
|
||||
names, err := Parts(parts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var last struct {
|
||||
Version int64 `json:"version"`
|
||||
Pins []string `json:"pins"`
|
||||
@@ -29,9 +66,21 @@ func Follow(ctx context.Context, api, parts, state string, log func(string)) err
|
||||
_ = json.Unmarshal(b, &last)
|
||||
}
|
||||
|
||||
// A node that just started has no peers yet and fails at once; retry.
|
||||
var res struct{ Path string }
|
||||
if err := c.call(ctx, &res, "name/resolve", "arg", "/ipns/"+Name, "recursive", "true", "timeout", "5m"); err != nil {
|
||||
return fmt.Errorf("resolving the publish: %w", err)
|
||||
for try := 1; ; try++ {
|
||||
err := c.call(ctx, &res, "name/resolve", "arg", "/ipns/"+Name, "recursive", "true", "timeout", "5m")
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
if try == resolveTries {
|
||||
return fmt.Errorf("resolving the publish: %w", err)
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-time.After(resolveWait):
|
||||
}
|
||||
}
|
||||
root, ok := strings.CutPrefix(res.Path, "/ipfs/")
|
||||
if !ok || !cidRe.MatchString(root) {
|
||||
@@ -55,21 +104,17 @@ func Follow(ctx context.Context, api, parts, state string, log func(string)) err
|
||||
|
||||
// The root's own block and the index, so peers can find their way in.
|
||||
pins := []string{root + "/index.json", root + "/index.json.sig"}
|
||||
switch parts {
|
||||
case "all":
|
||||
pins = append(pins, idx.Parts.Packages, idx.Parts.OCI, idx.Parts.Git, idx.Parts.Bin)
|
||||
case "images":
|
||||
pins = append(pins, idx.Parts.OCI)
|
||||
default:
|
||||
return fmt.Errorf("parts must be all or images, not %q", parts)
|
||||
cids := map[string]string{"packages": idx.Parts.Packages, "oci": idx.Parts.OCI, "git": idx.Parts.Git, "bin": idx.Parts.Bin}
|
||||
for _, n := range names {
|
||||
pins = append(pins, cids[n])
|
||||
}
|
||||
log(fmt.Sprintf("hosting the publish of %s (%s)", idx.Created, parts))
|
||||
log(fmt.Sprintf("hosting the publish of %s (%s)", idx.Created, strings.Join(names, ", ")))
|
||||
if err := c.call(ctx, nil, "pin/add", "arg", root, "recursive", "false"); err != nil {
|
||||
return fmt.Errorf("pinning %s: %w", root, err)
|
||||
}
|
||||
for _, p := range pins {
|
||||
log("fetching " + p)
|
||||
if err := c.call(ctx, nil, "pin/add", "arg", p); err != nil {
|
||||
if err := c.pin(ctx, p); err != nil {
|
||||
return fmt.Errorf("pinning %s: %w", p, err)
|
||||
}
|
||||
}
|
||||
@@ -139,6 +184,43 @@ func (c apiClient) call(ctx context.Context, out any, cmd string, args ...string
|
||||
return json.NewDecoder(res.Body).Decode(out)
|
||||
}
|
||||
|
||||
// pin pins path recursively, giving up once no block has arrived for stall.
|
||||
func (c apiClient) pin(ctx context.Context, path string) error {
|
||||
ctx, cancel := context.WithCancelCause(ctx)
|
||||
defer cancel(nil)
|
||||
stalled := fmt.Errorf("nothing arrived for %s; the swarm doesn't have all of it now", stall)
|
||||
t := time.AfterFunc(stall, func() { cancel(stalled) })
|
||||
defer t.Stop()
|
||||
res, err := c.do(ctx, "pin/add", "arg", path, "progress", "true")
|
||||
if err != nil {
|
||||
if context.Cause(ctx) == stalled {
|
||||
return stalled
|
||||
}
|
||||
return err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
dec, last := json.NewDecoder(res.Body), -1
|
||||
for {
|
||||
var m struct{ Progress int }
|
||||
err := dec.Decode(&m)
|
||||
switch {
|
||||
case err == io.EOF:
|
||||
if e := res.Trailer.Get("X-Stream-Error"); e != "" {
|
||||
return fmt.Errorf("%s", e)
|
||||
}
|
||||
return nil
|
||||
case err != nil && context.Cause(ctx) == stalled:
|
||||
return stalled
|
||||
case err != nil:
|
||||
return err
|
||||
}
|
||||
if m.Progress != last {
|
||||
last = m.Progress
|
||||
t.Reset(stall)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c apiClient) cat(ctx context.Context, path string, limit int64) ([]byte, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 10*time.Minute)
|
||||
defer cancel()
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// fakeNode answers the few RPC calls Follow makes, from one signed index.
|
||||
@@ -19,11 +20,17 @@ type fakeNode struct {
|
||||
root string
|
||||
index, sig string
|
||||
pinned, unpin []string
|
||||
stuck string
|
||||
unresolved int // name lookups to fail first
|
||||
}
|
||||
|
||||
func (n *fakeNode) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
n.mu.Lock()
|
||||
defer n.mu.Unlock()
|
||||
if strings.TrimPrefix(r.URL.Path, "/api/v0/") == "pin/add" && r.URL.Query().Get("arg") == n.stuck {
|
||||
n.mu.Unlock() // so the test can go on while this hangs
|
||||
} else {
|
||||
defer n.mu.Unlock()
|
||||
}
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "POST only", 405)
|
||||
return
|
||||
@@ -31,6 +38,11 @@ func (n *fakeNode) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
arg := r.URL.Query().Get("arg")
|
||||
switch strings.TrimPrefix(r.URL.Path, "/api/v0/") {
|
||||
case "name/resolve":
|
||||
if n.unresolved > 0 {
|
||||
n.unresolved--
|
||||
http.Error(w, `{"Message":"could not resolve name"}`, 500)
|
||||
return
|
||||
}
|
||||
w.Write([]byte(`{"Path":"/ipfs/` + n.root + `"}`))
|
||||
case "cat":
|
||||
switch arg {
|
||||
@@ -42,6 +54,12 @@ func (n *fakeNode) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, `{"Message":"no link"}`, 500)
|
||||
}
|
||||
case "pin/add":
|
||||
if arg == n.stuck {
|
||||
w.Write([]byte(`{"Progress":1}` + "\n"))
|
||||
w.(http.Flusher).Flush()
|
||||
<-r.Context().Done() // the swarm never has the rest
|
||||
return
|
||||
}
|
||||
n.pinned = append(n.pinned, arg)
|
||||
case "pin/rm":
|
||||
n.unpin = append(n.unpin, arg)
|
||||
@@ -62,7 +80,9 @@ func TestFollow(t *testing.T) {
|
||||
"parts":{"packages":"` + cid(c) + `","oci":"` + cid("o") + `","git":"` + cid(c) + `","bin":"` + cid(c) + `"}}`
|
||||
return s, base64.StdEncoding.EncodeToString(ed25519.Sign(priv, []byte(s)))
|
||||
}
|
||||
node := &fakeNode{root: cid("r")}
|
||||
defer func(d time.Duration) { resolveWait = d }(resolveWait)
|
||||
resolveWait = time.Millisecond
|
||||
node := &fakeNode{root: cid("r"), unresolved: 2} // a node that just started
|
||||
node.index, node.sig = index("5", "p")
|
||||
srv := httptest.NewServer(node)
|
||||
defer srv.Close()
|
||||
@@ -97,4 +117,26 @@ func TestFollow(t *testing.T) {
|
||||
if err := Follow(ctx, srv.URL, "all", state, log); err == nil || len(node.pinned) > 0 {
|
||||
t.Errorf("an unsigned publish was taken: %v %v", err, node.pinned)
|
||||
}
|
||||
|
||||
// A publish the swarm can't serve whole is given up on.
|
||||
defer func(d time.Duration) { stall = d }(stall)
|
||||
stall = 200 * time.Millisecond
|
||||
node.index, node.sig = index("8", "z")
|
||||
node.stuck = cid("z")
|
||||
if err := Follow(ctx, srv.URL, "packages,git", state, log); err == nil || !strings.Contains(err.Error(), "nothing arrived") {
|
||||
t.Errorf("a stalled fetch: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParts(t *testing.T) {
|
||||
for spec, want := range map[string]string{"all": "oci,packages,git,bin", "images": "oci", "git,oci,git": "git,oci"} {
|
||||
if got, err := Parts(spec); err != nil || strings.Join(got, ",") != want {
|
||||
t.Errorf("Parts(%q) = %v, %v", spec, got, err)
|
||||
}
|
||||
}
|
||||
for _, bad := range []string{"", "oci,", "everything"} {
|
||||
if _, err := Parts(bad); err == nil {
|
||||
t.Errorf("Parts(%q) passed", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user