|
| 1 | +// Copyright 2026 The Swarm Authors. All rights reserved. |
| 2 | +// Use of this source code is governed by a BSD-style |
| 3 | +// license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +package api |
| 6 | + |
| 7 | +import ( |
| 8 | + "context" |
| 9 | + "encoding/binary" |
| 10 | + "errors" |
| 11 | + "net/http" |
| 12 | + "strings" |
| 13 | + |
| 14 | + "github.com/ethersphere/bee/v2/pkg/file/loadsave" |
| 15 | + "github.com/ethersphere/bee/v2/pkg/file/redundancy" |
| 16 | + "github.com/ethersphere/bee/v2/pkg/jsonhttp" |
| 17 | + "github.com/ethersphere/bee/v2/pkg/manifest" |
| 18 | + "github.com/ethersphere/bee/v2/pkg/swarm" |
| 19 | + "github.com/ethersphere/bee/v2/pkg/tracing" |
| 20 | + "github.com/gorilla/mux" |
| 21 | +) |
| 22 | + |
| 23 | +const ( |
| 24 | + manifestListDefaultLimit = 1000 |
| 25 | + manifestListMaxLimit = 10000 |
| 26 | +) |
| 27 | + |
| 28 | +// emptyManifestEntry is the reference bee's uploader stores for manifest-level |
| 29 | +// metadata held at RootPath (e.g. website-index-document): 32 zero bytes. Note |
| 30 | +// this is NOT swarm.ZeroAddress (which has nil bytes), so Address.IsZero() does |
| 31 | +// not match it — mirror the convention used by mantarayManifest.IterateAddresses. |
| 32 | +var emptyManifestEntry = swarm.NewAddress([]byte{31: 0}) |
| 33 | + |
| 34 | +type ManifestListEntry struct { |
| 35 | + Path string `json:"path"` |
| 36 | + Reference swarm.Address `json:"reference"` |
| 37 | + Metadata map[string]string `json:"metadata,omitempty"` |
| 38 | + Size *int64 `json:"size,omitempty"` |
| 39 | +} |
| 40 | + |
| 41 | +type ManifestListResponse struct { |
| 42 | + Entries []ManifestListEntry `json:"entries"` |
| 43 | + CommonPrefixes []string `json:"commonPrefixes,omitempty"` |
| 44 | + Truncated bool `json:"truncated"` |
| 45 | + NextMarker string `json:"nextMarker,omitempty"` |
| 46 | +} |
| 47 | + |
| 48 | +// manifestListHandler serves a server-side listing of a manifest's contents, |
| 49 | +// walking the Mantaray trie on the node instead of forcing clients to fetch |
| 50 | +// and traverse it chunk by chunk. Semantics mirror S3 ListObjectsV2 (prefix, |
| 51 | +// delimiter, pagination) — see ethersphere/bee#5535. |
| 52 | +func (s *Service) manifestListHandler(w http.ResponseWriter, r *http.Request) { |
| 53 | + logger := tracing.NewLoggerWithTraceID(r.Context(), s.logger.WithName("get_manifest").Build()) |
| 54 | + |
| 55 | + paths := struct { |
| 56 | + Address swarm.Address `map:"address,resolve" validate:"required"` |
| 57 | + Prefix string `map:"path"` |
| 58 | + }{} |
| 59 | + if response := s.mapStructure(mux.Vars(r), &paths); response != nil { |
| 60 | + response("invalid path params", logger, w) |
| 61 | + return |
| 62 | + } |
| 63 | + |
| 64 | + queries := struct { |
| 65 | + Delimiter string `map:"delimiter"` |
| 66 | + Limit int `map:"limit"` |
| 67 | + After string `map:"after"` |
| 68 | + Sizes bool `map:"sizes"` |
| 69 | + }{ |
| 70 | + Limit: manifestListDefaultLimit, |
| 71 | + } |
| 72 | + if response := s.mapStructure(r.URL.Query(), &queries); response != nil { |
| 73 | + response("invalid query params", logger, w) |
| 74 | + return |
| 75 | + } |
| 76 | + // enforce the node-side hard cap; a non-positive limit falls back to it too. |
| 77 | + if queries.Limit <= 0 || queries.Limit > manifestListMaxLimit { |
| 78 | + queries.Limit = manifestListMaxLimit |
| 79 | + } |
| 80 | + |
| 81 | + address := paths.Address |
| 82 | + if v := getAddressFromContext(r.Context()); !v.IsZero() { |
| 83 | + address = v |
| 84 | + } |
| 85 | + |
| 86 | + ctx := r.Context() |
| 87 | + ls := loadsave.NewReadonly(s.storer.Download(true), s.storer.Cache(), redundancy.DefaultDownloadLevel) |
| 88 | + |
| 89 | + m, err := manifest.NewDefaultManifestReference(address, ls) |
| 90 | + if err != nil { |
| 91 | + logger.Debug("manifest list: not a manifest", "address", address, "error", err) |
| 92 | + logger.Error(nil, "manifest list: not a manifest") |
| 93 | + jsonhttp.NotFound(w, nil) |
| 94 | + return |
| 95 | + } |
| 96 | + |
| 97 | + walker, ok := m.(manifest.EntryWalker) |
| 98 | + if !ok { |
| 99 | + logger.Error(nil, "manifest list: manifest type does not support listing") |
| 100 | + jsonhttp.InternalServerError(w, "manifest listing not supported") |
| 101 | + return |
| 102 | + } |
| 103 | + |
| 104 | + prefix := paths.Prefix |
| 105 | + resp := ManifestListResponse{Entries: []ManifestListEntry{}} |
| 106 | + seenPrefix := make(map[string]struct{}) |
| 107 | + // marker tracks the last path fully consumed on this page; on truncation it |
| 108 | + // becomes nextMarker so a resumed page starts strictly after it. It is only |
| 109 | + // advanced for paths that are actually accounted for (emitted or folded into |
| 110 | + // a common prefix), never for entries skipped by the `after` continuation. |
| 111 | + var marker string |
| 112 | + |
| 113 | + walkErr := walker.WalkEntry(ctx, prefix, func(p string, entry manifest.Entry) error { |
| 114 | + // skip the synthetic root-metadata entry (empty reference); its |
| 115 | + // manifest-level metadata (e.g. website-index-document) is not a file. |
| 116 | + if entry.Reference().IsZero() || entry.Reference().Equal(emptyManifestEntry) { |
| 117 | + return nil |
| 118 | + } |
| 119 | + // continuation token: only paths strictly after it are unseen. |
| 120 | + if queries.After != "" && p <= queries.After { |
| 121 | + return nil |
| 122 | + } |
| 123 | + |
| 124 | + if queries.Delimiter != "" { |
| 125 | + rest := strings.TrimPrefix(p, prefix) |
| 126 | + if idx := strings.Index(rest, queries.Delimiter); idx >= 0 { |
| 127 | + cp := prefix + rest[:idx+len(queries.Delimiter)] |
| 128 | + if _, dup := seenPrefix[cp]; dup { |
| 129 | + // already an open common prefix — folding p in is free. |
| 130 | + marker = p |
| 131 | + return nil |
| 132 | + } |
| 133 | + if len(resp.Entries)+len(resp.CommonPrefixes) >= queries.Limit { |
| 134 | + resp.Truncated = true |
| 135 | + resp.NextMarker = marker |
| 136 | + return manifest.ErrStopWalk |
| 137 | + } |
| 138 | + seenPrefix[cp] = struct{}{} |
| 139 | + resp.CommonPrefixes = append(resp.CommonPrefixes, cp) |
| 140 | + marker = p |
| 141 | + return nil |
| 142 | + } |
| 143 | + } |
| 144 | + |
| 145 | + if len(resp.Entries)+len(resp.CommonPrefixes) >= queries.Limit { |
| 146 | + resp.Truncated = true |
| 147 | + resp.NextMarker = marker |
| 148 | + return manifest.ErrStopWalk |
| 149 | + } |
| 150 | + |
| 151 | + le := ManifestListEntry{ |
| 152 | + Path: p, |
| 153 | + Reference: entry.Reference(), |
| 154 | + Metadata: entry.Metadata(), |
| 155 | + } |
| 156 | + if queries.Sizes { |
| 157 | + if size, err := s.manifestEntrySize(ctx, entry.Reference()); err == nil { |
| 158 | + le.Size = &size |
| 159 | + } else { |
| 160 | + // size is best-effort: a legacy/unreachable entry still lists. |
| 161 | + logger.Debug("manifest list: size resolution failed", "path", p, "error", err) |
| 162 | + } |
| 163 | + } |
| 164 | + resp.Entries = append(resp.Entries, le) |
| 165 | + marker = p |
| 166 | + return nil |
| 167 | + }) |
| 168 | + if walkErr != nil { |
| 169 | + if errors.Is(walkErr, manifest.ErrNotFound) { |
| 170 | + logger.Debug("manifest list: prefix not found", "address", address, "prefix", prefix) |
| 171 | + jsonhttp.NotFound(w, "prefix not found") |
| 172 | + return |
| 173 | + } |
| 174 | + // a partially-retrievable manifest is reported as an error rather than |
| 175 | + // silently returning a truncated view (see #5535 error semantics). |
| 176 | + logger.Debug("manifest list: walk failed", "address", address, "error", walkErr) |
| 177 | + logger.Error(nil, "manifest list: walk failed") |
| 178 | + jsonhttp.NotFound(w, "manifest incomplete or not retrievable") |
| 179 | + return |
| 180 | + } |
| 181 | + |
| 182 | + jsonhttp.OK(w, resp) |
| 183 | +} |
| 184 | + |
| 185 | +// manifestEntrySize resolves a file entry's byte length by reading the 8-byte |
| 186 | +// span header from its root chunk. Opt-in (sizes=true): one extra chunk read |
| 187 | +// per entry. |
| 188 | +func (s *Service) manifestEntrySize(ctx context.Context, ref swarm.Address) (int64, error) { |
| 189 | + ch, err := s.storer.Download(true).Get(ctx, ref) |
| 190 | + if err != nil { |
| 191 | + return 0, err |
| 192 | + } |
| 193 | + data := ch.Data() |
| 194 | + if len(data) < swarm.SpanSize { |
| 195 | + return 0, errors.New("chunk shorter than span") |
| 196 | + } |
| 197 | + return int64(binary.LittleEndian.Uint64(data[:swarm.SpanSize])), nil |
| 198 | +} |
0 commit comments