api

package
v1.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 8, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Package api covers the core HTTP service used by every other bee-go sub-package, plus the cross-cutting endpoints that don't fit neatly into a single domain: pin, tag, stewardship, grantee, envelope, and "is reference retrievable?" checks.

It also defines the upload / download option structs that bee-go's upload methods accept:

Mirrors bee-js's UploadOptions / DownloadOptions / PostageBatchOptions fan-out and bee-js's pin / tag / stewardship / grantee endpoints.

Index

Constants

View Source
const MaxCheckPinsResponseBytes = 32 << 20

MaxCheckPinsResponseBytes caps the cumulative size of a /pins/check response. A misbehaving or compromised Bee could otherwise stream an unbounded NDJSON body and exhaust the client's memory; the per-line cap inside Service.CheckPins only bounds individual rows. 32 MiB fits roughly 350k integrity rows — far above any realistic node.

Variables

This section is empty.

Functions

func BoolPtr

func BoolPtr(b bool) *bool

BoolPtr is a convenience for setting *bool fields on options structs:

opts := &api.UploadOptions{Pin: api.BoolPtr(true)}

func PrepareCollectionUploadHeaders

func PrepareCollectionUploadHeaders(req *http.Request, batchID swarm.BatchID, opts *CollectionUploadOptions)

PrepareCollectionUploadHeaders prepares the headers for a tar /bzz upload.

IndexDocument and ErrorDocument become HTTP header values. Go's net/http rejects header values containing CR / LF / NUL at request write time (manifesting as a confusing "net/http: invalid header field value" wrapped deep in the I/O path); to surface that as a clean argument error early, callers should validate via ValidateCollectionUploadOptions before invoking this helper. PrepareCollectionUploadHeaders silently omits header values containing those forbidden bytes so a misuse cannot smuggle a header-injection payload onto the wire.

func PrepareDownloadHeaders

func PrepareDownloadHeaders(req *http.Request, opts *DownloadOptions)

PrepareDownloadHeaders writes every applicable download header onto req. nil opts is a no-op (Bee defaults are used).

func PrepareFileUploadHeaders

func PrepareFileUploadHeaders(req *http.Request, batchID swarm.BatchID, opts *FileUploadOptions)

PrepareFileUploadHeaders prepares the headers for a POST /bzz file upload. It also overrides Content-Type / Content-Length if FileUploadOptions sets them.

func PrepareRedundantUploadHeaders

func PrepareRedundantUploadHeaders(req *http.Request, batchID swarm.BatchID, opts *RedundantUploadOptions)

PrepareRedundantUploadHeaders is PrepareUploadHeaders + Swarm-Redundancy-Level.

func PrepareUploadHeaders

func PrepareUploadHeaders(req *http.Request, batchID swarm.BatchID, opts *UploadOptions)

PrepareUploadHeaders writes every applicable upload header onto req. The batch is required (Bee rejects uploads without a stamp).

func ValidateCollectionUploadOptions added in v1.2.1

func ValidateCollectionUploadOptions(opts *CollectionUploadOptions) error

ValidateCollectionUploadOptions returns a swarm.BeeArgumentError if any field of opts cannot safely become an HTTP header value. nil opts is valid (Bee defaults are used). Currently checks IndexDocument and ErrorDocument for CR / LF / NUL bytes, which would otherwise be rejected at request write time (or, on older Go versions, would allow header injection).

Types

type CollectionUploadOptions

type CollectionUploadOptions struct {
	UploadOptions
	// IndexDocument is served when the collection root is requested
	// (e.g. "index.html").
	IndexDocument string
	// ErrorDocument is served when a path inside the collection is missing.
	ErrorDocument string
	// RedundancyLevel adds erasure coding to the upload.
	RedundancyLevel RedundancyLevel
}

CollectionUploadOptions adds the directory-specific knobs used by tar uploads on POST /bzz.

type DownloadOptions

type DownloadOptions struct {
	// RedundancyStrategy picks a chunk-prefetch policy for erasure coded
	// data.
	RedundancyStrategy *RedundancyStrategy

	// Fallback toggles whether retrieve strategies cascade. Default true.
	Fallback *bool

	// TimeoutMs is the per-chunk retrieval timeout (not the whole download).
	TimeoutMs int

	// ActPublisher is the public key of the ACT publisher when reading
	// access-controlled data.
	ActPublisher *swarm.PublicKey

	// ActHistoryAddress is the history root used to resolve permissions at
	// ActTimestamp.
	ActHistoryAddress *swarm.Reference

	// ActTimestamp is the Unix timestamp at which to evaluate ACT
	// permissions. 0 means "now".
	ActTimestamp int64
}

DownloadOptions controls retrieval behaviour. All fields are optional; passing nil to a download method keeps Bee defaults.

type EnvelopeResponse

type EnvelopeResponse struct {
	Issuer    string `json:"issuer"`
	Index     string `json:"index"`
	Timestamp string `json:"timestamp"`
	Signature string `json:"signature"`
}

EnvelopeResponse represents the envelope response.

type FileHeaders

type FileHeaders struct {
	Name        string
	TagUID      uint32
	ContentType string
}

FileHeaders is the parsed form of the response headers Bee returns when downloading a file (Content-Disposition / swarm-tag-uid / Content-Type).

func ParseFileHeaders

func ParseFileHeaders(headers http.Header) FileHeaders

ParseFileHeaders extracts the file metadata Bee places on download responses. Missing or malformed headers fall through silently — the returned FileHeaders zero values mirror bee-js's `undefined` semantics.

type FileUploadOptions

type FileUploadOptions struct {
	UploadOptions
	// Size sets Content-Length explicitly. Required when uploading from an
	// io.Reader of unknown length.
	Size int64
	// ContentType becomes the file's reported MIME type.
	ContentType string
	// RedundancyLevel adds erasure coding to the upload.
	RedundancyLevel RedundancyLevel
}

FileUploadOptions adds the file-specific knobs used by POST /bzz uploads.

type GranteeResponse

type GranteeResponse struct {
	Ref        string `json:"ref"`
	HistoryRef string `json:"historyref"`
}

GranteeResponse represents the response from create/patch grantee.

type GranteesResponse

type GranteesResponse struct {
	Grantees []string `json:"grantees"`
}

GranteesResponse represents the list of grantees.

type PinIntegrity added in v1.2.0

type PinIntegrity struct {
	Reference swarm.Reference `json:"reference"`
	Total     int             `json:"total"`
	Missing   int             `json:"missing"`
	Invalid   int             `json:"invalid"`
}

PinIntegrity is one row of the GET /pins/check NDJSON stream — the integrity status of a single pinned reference. IsHealthy returns true iff every chunk under the reference is present and valid.

func (PinIntegrity) IsHealthy added in v1.2.0

func (p PinIntegrity) IsHealthy() bool

IsHealthy reports whether the pinned reference's chunk tree is fully retrievable. False means at least one chunk is missing or invalid; the missing / invalid counts pinpoint the breakage.

type PostageBatchOptions

type PostageBatchOptions struct {
	Label     string
	Immutable *bool
	GasPrice  string
	GasLimit  string
}

PostageBatchOptions covers query-string knobs accepted by stamp creation (label, immutable, gas overrides). Mirrors bee-js PostageBatchOptions.

type RedundancyLevel

type RedundancyLevel int

RedundancyLevel is the data redundancy level applied when uploading. Mirrors bee-js's RedundancyLevel enum.

const (
	RedundancyLevelOff      RedundancyLevel = 0
	RedundancyLevelMedium   RedundancyLevel = 1
	RedundancyLevelStrong   RedundancyLevel = 2
	RedundancyLevelInsane   RedundancyLevel = 3
	RedundancyLevelParanoid RedundancyLevel = 4
)

type RedundancyStrategy

type RedundancyStrategy int

RedundancyStrategy is the chunk-prefetch policy used when downloading erasure-coded data. Mirrors bee-js's RedundancyStrategy enum.

const (
	RedundancyStrategyNone RedundancyStrategy = 0
	RedundancyStrategyData RedundancyStrategy = 1
	RedundancyStrategyProx RedundancyStrategy = 2
	RedundancyStrategyRace RedundancyStrategy = 3
)

func RedundancyStrategyPtr

func RedundancyStrategyPtr(s RedundancyStrategy) *RedundancyStrategy

RedundancyStrategyPtr is the analogous convenience for *RedundancyStrategy.

type RedundantUploadOptions

type RedundantUploadOptions struct {
	UploadOptions
	RedundancyLevel RedundancyLevel
}

RedundantUploadOptions adds the redundancy level applied to data uploads.

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service is the cross-cutting API endpoint group: pin, tag, stewardship, grantee, envelope, and "is reference retrievable?" checks. Get one from the top-level Client.API field rather than constructing it directly.

func NewService

func NewService(baseURL *url.URL, httpClient *http.Client) *Service

NewService wires up an api.Service against a Bee base URL and HTTP client. The top-level bee.NewClient calls this for you; use it directly only if you need the api endpoints in isolation (without the rest of the bee-go sub-services).

func (*Service) CheckPins added in v1.2.0

func (s *Service) CheckPins(ctx context.Context, ref *swarm.Reference) ([]PinIntegrity, error)

CheckPins streams the GET /pins/check NDJSON response and collects the integrity rows into a slice. ref is optional — when nil, every pinned reference is checked; otherwise only the named reference is reported (as the ?ref={hex} query parameter). Returns an empty slice on success when no rows match.

The total response body is capped at MaxCheckPinsResponseBytes; individual NDJSON lines are capped at 1 MiB.

Mirrors bee-rs ApiService::check_pins and bee-py client.api.check_pins.

func (*Service) CreateGrantees

func (s *Service) CreateGrantees(ctx context.Context, batchID swarm.BatchID, grantees []string) (GranteeResponse, error)

CreateGrantees creates a new grantee list.

func (*Service) CreateTag

func (s *Service) CreateTag(ctx context.Context) (Tag, error)

CreateTag creates a new tag.

func (*Service) DeleteTag

func (s *Service) DeleteTag(ctx context.Context, uid uint32) error

DeleteTag deletes a tag by UID.

func (*Service) GetGrantees

func (s *Service) GetGrantees(ctx context.Context, ref swarm.Reference) ([]string, error)

GetGrantees retrieves the grantees for a reference.

func (*Service) GetPin

func (s *Service) GetPin(ctx context.Context, ref swarm.Reference) (bool, error)

GetPin checks the pin status (or gets pin info if it exists). For now, simpler check. Note: GET /pins/ref generally returns 200/404.

func (*Service) GetTag

func (s *Service) GetTag(ctx context.Context, uid uint32) (Tag, error)

GetTag retrieves a tag by UID.

func (*Service) IsRetrievable

func (s *Service) IsRetrievable(ctx context.Context, ref swarm.Reference) (bool, error)

IsRetrievable checks if the content is retrievable.

func (*Service) ListPins

func (s *Service) ListPins(ctx context.Context) ([]swarm.Reference, error)

ListPins retrieves all pinned references.

func (*Service) ListTags

func (s *Service) ListTags(ctx context.Context, offset int, limit int) ([]Tag, error)

ListTags retrieves a list of tags.

func (*Service) PatchGrantees

func (s *Service) PatchGrantees(ctx context.Context, batchID swarm.BatchID, ref swarm.Reference, historyRef swarm.Reference, add []string, revoke []string) (GranteeResponse, error)

PatchGrantees updates the grantees for a reference.

func (*Service) Pin

func (s *Service) Pin(ctx context.Context, ref swarm.Reference) error

Pin pins a reference.

func (*Service) PostEnvelope

func (s *Service) PostEnvelope(ctx context.Context, batchID swarm.BatchID, ref swarm.Reference) (EnvelopeResponse, error)

PostEnvelope posts an envelope.

func (*Service) RetrieveTag

func (s *Service) RetrieveTag(ctx context.Context, uid uint32) (Tag, error)

RetrieveTag is the bee-js name for GetTag.

func (*Service) Reupload

func (s *Service) Reupload(ctx context.Context, ref swarm.Reference, batchID swarm.BatchID) error

Reupload re-uploads locally pinned data.

func (*Service) Unpin

func (s *Service) Unpin(ctx context.Context, ref swarm.Reference) error

Unpin unpins a reference.

func (*Service) UpdateTag

func (s *Service) UpdateTag(ctx context.Context, uid uint32, tag Tag) error

UpdateTag updates a tag by UID.

type Subscription

type Subscription struct {
	// contains filtered or unexported fields
}

Subscription represents a WebSocket subscription.

func GSOCSubscribe

func GSOCSubscribe(ctx context.Context, baseURL *url.URL, dialer *websocket.Dialer, address string) (*Subscription, error)

GSOCSubscribe subscribes to GSOC messages.

func PSSSubscribe

func PSSSubscribe(ctx context.Context, baseURL *url.URL, dialer *websocket.Dialer, topic string) (*Subscription, error)

PSSSubscribe subscribes to a PSS topic.

func (*Subscription) Close

func (s *Subscription) Close() error

Close closes the subscription.

func (*Subscription) ReadMessage

func (s *Subscription) ReadMessage() (int, []byte, error)

ReadMessage reads a message from the subscription.

type Tag

type Tag struct {
	UID       uint32 `json:"uid"`
	Name      string `json:"name"`
	Total     int64  `json:"total"`
	Split     int64  `json:"split"`
	Seen      int64  `json:"seen"`
	Stored    int64  `json:"stored"`
	Sent      int64  `json:"sent"`
	Synced    int64  `json:"synced"`
	Address   string `json:"address"`
	StartedAt string `json:"startedAt"`
}

Tag represents a Swarm tag. Structure from Bee API docs.

type UploadOptions

type UploadOptions struct {
	// Act, when true, instructs Bee to create an Access Control Trie (ACT)
	// for the uploaded data. The history address is returned in the
	// swarm-act-history-address response header.
	Act *bool

	// ActHistoryAddress extends an existing ACT history when re-uploading
	// updated content under the same access policy.
	ActHistoryAddress *swarm.Reference

	// Pin keeps a local copy of the uploaded data on the Bee node so it can
	// be re-uploaded if it disappears from the network.
	Pin *bool

	// Encrypt instructs Bee to encrypt the chunks; the returned reference
	// includes the decryption key (64-byte reference instead of 32).
	Encrypt *bool

	// Tag attaches an existing tag UID to the upload to track sync progress.
	Tag uint32

	// Deferred toggles between "client waits for full sync" (false) and
	// "Bee accepts upload then syncs in the background" (true). Default in
	// Bee is true.
	Deferred *bool
}

UploadOptions is the base set of options accepted by every upload endpoint. Mirrors bee-js's UploadOptions.

Pointer fields (*bool) distinguish "unset" from "explicitly false". Bee reads any of these only if the corresponding header is present; we omit the header entirely when the pointer is nil.

func (*UploadOptions) ApplyToRequest deprecated

func (o *UploadOptions) ApplyToRequest(req *http.Request)

ApplyToRequest is preserved for backwards compatibility with previously inlined call sites; new code should use PrepareUploadHeaders instead. It only sets the four legacy fields.

Deprecated: use PrepareUploadHeaders or one of the typed Prepare* helpers.

type UploadResult

type UploadResult struct {
	Reference      swarm.Reference
	TagUID         uint32
	HistoryAddress *swarm.Reference
}

UploadResult is the standardized return shape for every upload endpoint. Mirrors bee-js's UploadResult. TagUID is 0 when Bee did not return a swarm-tag header. HistoryAddress is nil when no ACT history was created.

func ReadUploadResult

func ReadUploadResult(refHex string, headers http.Header) (UploadResult, error)

ReadUploadResult parses an UploadResult from an HTTP response. The reference is taken from the JSON body (already decoded into refHex by the caller), the tag UID and history address come from response headers.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL