sdk

package
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Sep 23, 2026 License: MIT Imports: 9 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package sdk provides protocol-agnostic primitives shared by the public Pixiv and Pixiv FANBOX SDK packages: paginated pages and their opaque cursors, classified errors with safe redaction, and the resource contract used for first-party media.

This package does not import product models or local state. Product-specific clients live in sdk/pixiv and sdk/fanbox; both depend only on this package and never on each other.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CursorEphemeral

func CursorEphemeral(c Cursor) bool

CursorEphemeral reports whether the cursor is only valid for the client instance that produced it because no identity could be verified at creation.

func CursorIdentity

func CursorIdentity(c Cursor) (identity string, ok bool)

CursorIdentity returns the verified non-secret identity bound to the cursor, if any.

func CursorPayload

func CursorPayload(c Cursor) ([]byte, error)

CursorPayload returns the opaque upstream continuation state embedded in the cursor. It is intended for product SDK implementations that re-attach per-request secrets when continuing an operation.

func IsReason

func IsReason(err error, reason Reason) bool

IsReason reports whether err is or wraps an *Error with the given reason.

func ResourceRefPayload

func ResourceRefPayload(r ResourceRef) ([]byte, error)

ResourceRefPayload returns the opaque identity payload of a parsed reference so the product SDK can revalidate the resource it names.

func ResourceRefProduct

func ResourceRefProduct(r ResourceRef) (string, error)

ResourceRefProduct returns the product namespace of a parsed reference.

func ValidateCursor

func ValidateCursor(c Cursor, product, operation string, bindingVersion int, queryHash string) error

ValidateCursor revalidates the bindings a caller must repeat when continuing pagination: product, operation, binding version, and query digest. A zero cursor or any mismatch returns InvalidCursor.

func ValidateCursorInstance

func ValidateCursorInstance(c Cursor, instance string) error

ValidateCursorInstance verifies the non-secret instance binding of an ephemeral cursor. A zero cursor, malformed cursor, non-ephemeral cursor, missing instance binding, or mismatched instance returns InvalidCursor.

Types

type Cursor

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

Cursor is an opaque continuation token carried by sdk.Page. Its value is owned by the product SDK and cannot be constructed through a struct literal; callers receive cursors from page results, persist them through the Text or JSON codecs, and pass them back through the matching request struct.

A cursor is bound to a product, operation, binding version, and query digest. Product SDKs revalidate those bindings when a caller continues pagination and return InvalidCursor on mismatch; a cursor never silently restarts from the first page across product, operation, or query changes.

func NewCursor

func NewCursor(product, operation string, bindingVersion int, queryHash string, payload []byte, opts ...CursorOption) (Cursor, error)

NewCursor constructs a cursor bound to the given product operation. It is intended for product SDK implementations; application code receives cursors from page results. product and operation must be non-empty, bindingVersion must be positive, queryHash must be the digest of the request's query parameters, and payload must be the opaque, secret-free upstream continuation state. Violations return an error with InvalidArgument.

func ParseCursor

func ParseCursor(text string) (Cursor, error)

ParseCursor decodes a cursor from its route-safe unpadded base64url text encoding, returning InvalidCursor for malformed input.

func (Cursor) IsZero

func (c Cursor) IsZero() bool

IsZero reports whether the cursor is the zero value, which means there is no further page.

func (Cursor) MarshalJSON

func (c Cursor) MarshalJSON() ([]byte, error)

MarshalJSON encodes the cursor as a JSON string containing its Text form.

func (Cursor) MarshalText

func (c Cursor) MarshalText() ([]byte, error)

MarshalText returns the route-safe unpadded base64url text encoding of the cursor. The encoding is versioned and remains decodable across later versions of the same major. Marshaling a zero cursor returns InvalidArgument.

func (Cursor) String

func (c Cursor) String() string

String returns the route-safe text encoding of the cursor. It is safe to log and persist; an ephemeral cursor may still be rejected when used by another client instance or process.

func (*Cursor) UnmarshalJSON

func (c *Cursor) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes a cursor from a JSON string containing its Text form.

func (*Cursor) UnmarshalText

func (c *Cursor) UnmarshalText(text []byte) error

UnmarshalText decodes a cursor from its route-safe unpadded base64url text encoding. Unrecognized or malformed encodings return InvalidCursor.

type CursorOption

type CursorOption func(*cursorEnvelope)

CursorOption adjusts the binding metadata of a cursor during construction.

func WithCursorEphemeral

func WithCursorEphemeral() CursorOption

WithCursorEphemeral marks a cursor that could not be bound to a verifiable identity. Product SDKs should pair it with WithCursorEphemeralInstance so reuse by another client instance is rejected.

func WithCursorEphemeralInstance

func WithCursorEphemeralInstance(instance string) CursorOption

WithCursorEphemeralInstance binds an ephemeral cursor to a non-secret identifier owned by the client instance that created it. Product SDKs should generate a fresh identifier for each client and validate it before continuing an identity-scoped operation whose upstream identity is unknown.

func WithCursorIdentity

func WithCursorIdentity(identity string) CursorOption

WithCursorIdentity binds a verified non-secret identity (for example an upstream user ID) to an identity-scoped operation's cursor. The identity must not be secret; cursor encodings that carry it remain safe to persist.

type Error

type Error struct {
	Product    string
	Operation  string
	Reason     Reason
	Detail     string
	HTTPStatus int
	Transport  Transport
	Retry      RetryAdvice
	// contains filtered or unexported fields
}

Error is a classified, redacted error returned by the product SDKs and by this package's parsing helpers. It implements error, errors.Is, and errors.As, and its Unwrap chain preserves context.Canceled and context.DeadlineExceeded when one of those caused the failure.

The error chain never contains raw URLs, request headers, response bodies, tokens, cookies, proxy userinfo, browser paths, or configuration content. The cause, when present, is always a redacted local classification.

func NewError

func NewError(product, operation string, reason Reason, opts ...ErrorOption) *Error

NewError constructs a classified error for product and operation. product may be empty for errors produced by this shared package.

func (*Error) Error

func (e *Error) Error() string

Error returns a safe, human-readable summary. It never includes raw upstream artifacts; the cause is expected to be a redacted classification.

func (*Error) Is

func (e *Error) Is(target error) bool

Is reports whether target is an *Error with the same Reason. This lets a classified error match a Reason-only sentinel.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the redacted cause, allowing errors.Is and errors.As to walk the chain (for example to match context.Canceled).

type ErrorOption

type ErrorOption func(*Error)

ErrorOption configures a classified error during construction.

func WithCause

func WithCause(cause error) ErrorOption

WithCause attaches a redacted underlying cause. The chain must not contain secrets or raw upstream artifacts; product SDKs are responsible for classifying and redacting before wrapping.

func WithDetail

func WithDetail(detail string) ErrorOption

WithDetail attaches a controlled, redacted detail string that further classifies the failure without leaking upstream artifacts.

func WithHTTPStatus

func WithHTTPStatus(status int) ErrorOption

WithHTTPStatus attaches the normalized upstream HTTP status code. Zero is treated as "not provided".

func WithRetry

func WithRetry(retry RetryAdvice) ErrorOption

WithRetry attaches retry advice derived only from verified upstream sources.

func WithTransport

func WithTransport(transport Transport) ErrorOption

WithTransport attaches the transport layer classification.

type OpenResourceRequest

type OpenResourceRequest struct {
	Ref             ResourceRef
	Method          ResourceMethod
	Range           string
	IfNoneMatch     string
	IfModifiedSince string
	IfRange         string
}

OpenResourceRequest selects how a product client opens a resource by its opaque reference. The zero Method is treated as GET. Header fields reject control characters; SDKs never accept arbitrary header maps.

func (OpenResourceRequest) Validate

func (r OpenResourceRequest) Validate() error

Validate checks that the method is allowed and that request header fields contain no control characters, returning InvalidArgument otherwise.

type Page

type Page[T any] struct {
	Items []T
	Next  Cursor
}

Page holds one page of results from a list operation and the cursor needed to fetch the next page.

A successful page with no items must have a non-nil empty Items slice rather than a nil slice. Next.IsZero() reports that there is no further page; a non-zero Next must be passed back through the matching request struct to continue the iteration. Callers repeat the original query parameters when continuing; product SDKs reject a cursor whose product, operation, binding version, or query digest does not match with InvalidCursor.

type PageDTO

type PageDTO[T any] struct {
	Items []T    `json:"items"`
	Next  string `json:"next"`
}

PageDTO is the output-safe representation of a page. Cursor identity is reduced to its stable opaque text; query-bound validation remains a runtime concern of Page and Cursor.

type Reason

type Reason string

Reason is a stable, machine-readable error classification shared by both product SDKs. Reasons are part of the v1 compatibility contract: a reason may only be added, never removed, renamed, or reused for a different meaning.

const (
	InvalidArgument           Reason = "invalid_argument"
	InvalidCursor             Reason = "invalid_cursor"
	Unauthorized              Reason = "unauthorized"
	CredentialsExpired        Reason = "credentials_expired"
	Forbidden                 Reason = "forbidden"
	NotFound                  Reason = "not_found"
	ContentUnavailable        Reason = "content_unavailable"
	ChallengeRequired         Reason = "challenge_required"
	RateLimited               Reason = "rate_limited"
	UpstreamError             Reason = "upstream_error"
	UpstreamUnavailable       Reason = "upstream_unavailable"
	MalformedUpstreamResponse Reason = "malformed_upstream_response"
	ResourceForbidden         Reason = "resource_forbidden"
	LocalStateError           Reason = "local_state_error"
	RemovedSetting            Reason = "removed_setting"
)

The v1 error reasons are the stable, machine-readable classifications shared by both product SDKs.

func ReasonOf

func ReasonOf(err error) Reason

ReasonOf returns the sdk.Reason of err when it is or wraps an *Error, and the empty string otherwise.

type Resource

type Resource struct {
	Ref                 ResourceRef       `json:"ref"`
	URL                 string            `json:"url"`
	RequestHeaders      map[string]string `json:"request_headers,omitempty"`
	ExpiresAt           *time.Time        `json:"expires_at,omitempty"`
	RequiresCredentials bool              `json:"requires_credentials,omitempty"`
}

Resource is a first-party media item exposed by product models. URL is a currently-usable upstream locator that a caller may stream directly or proxy without buffering to disk; Ref is the stable opaque identity to hand back to OpenResource or SaveResource. The two are not interchangeable and neither can be derived from the other.

URL must be validated (scheme, host, userinfo, allowed resource path) before it enters a public model. RequestHeaders contains only non-secret headers a caller must forward, such as a Pixiv image referer; it must never carry cookies, authorization, or proxy credentials. When the resource still needs product credentials invisible to the caller, RequiresCredentials is true and callers should use OpenResource instead of treating URL as a public link. ExpiresAt is set only when the upstream or protocol can reliably determine it; callers must not treat URL as a permanent identity.

func (*Resource) Copy

func (r *Resource) Copy() Resource

Copy returns a deep copy of the resource. RequestHeaders is returned to callers as a fresh map so mutating it never changes the client's internal state.

type ResourceDTO

type ResourceDTO struct {
	Ref                 string `json:"ref"`
	RequiresCredentials bool   `json:"requires_credentials,omitempty"`
}

ResourceDTO is the output-safe representation of a Resource. It carries only the opaque reference and the fact that opening it needs credentials; runtime locators, request headers, and expiry metadata never cross an output boundary.

func ToResourceDTO

func ToResourceDTO(value Resource) *ResourceDTO

ToResourceDTO converts a runtime resource to its output-safe representation. A resource without an opaque reference is absent from the DTO rather than an invalid empty reference being emitted.

type ResourceMethod

type ResourceMethod string

ResourceMethod is the HTTP method accepted by OpenResource.

const (
	ResourceMethodGet  ResourceMethod = "GET"
	ResourceMethodHead ResourceMethod = "HEAD"
)

ResourceMethod values are the HTTP methods OpenResource accepts.

type ResourceRef

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

ResourceRef is an opaque, product-scoped identity for a first-party media resource. It does not encode or promise to persist Resource.URL: callers use it as a stable cache key and hand it back to OpenResource or SaveResource so the product SDK can revalidate and safely read the resource.

The Text codec uses the route-safe unpadded base64url alphabet and is suitable for URL path segments. The JSON codec is the same text form as a JSON string. A ResourceRef cannot be constructed from an arbitrary raw URL.

func NewResourceRef

func NewResourceRef(product string, payload []byte) (ResourceRef, error)

NewResourceRef constructs an opaque reference for product carrying the given opaque identity payload. It is intended for product SDK implementations. product must be non-empty and payload must be non-empty; violations return InvalidArgument.

func ParseResourceRef

func ParseResourceRef(text string) (ResourceRef, error)

ParseResourceRef decodes a reference from its route-safe unpadded base64url text encoding, returning InvalidArgument for malformed input.

func (ResourceRef) IsZero

func (r ResourceRef) IsZero() bool

IsZero reports whether the reference is the zero value.

func (ResourceRef) MarshalJSON

func (r ResourceRef) MarshalJSON() ([]byte, error)

MarshalJSON encodes the reference as a JSON string containing its Text form. Marshaling a zero reference returns InvalidArgument.

func (ResourceRef) MarshalText

func (r ResourceRef) MarshalText() ([]byte, error)

MarshalText returns the route-safe unpadded base64url text encoding of the reference.

func (ResourceRef) String

func (r ResourceRef) String() string

String returns the route-safe text encoding of the reference.

func (*ResourceRef) UnmarshalJSON

func (r *ResourceRef) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes a reference from a JSON string containing its Text form.

func (*ResourceRef) UnmarshalText

func (r *ResourceRef) UnmarshalText(text []byte) error

UnmarshalText decodes a reference from its route-safe unpadded base64url text encoding, returning InvalidArgument for malformed input.

type ResourceResponse

type ResourceResponse struct {
	StatusCode int
	Body       io.ReadCloser
	// contains filtered or unexported fields
}

ResourceResponse is the result of opening a resource. StatusCode is the upstream status, Body is the streamed response body owned by the caller (who must close it), and Header returns only the allowlisted representation headers. For HEAD, 204, and 304 responses the Body is a non-nil empty stream that remains safe to close.

func NewResourceResponse

func NewResourceResponse(statusCode int, src http.Header, body io.ReadCloser) *ResourceResponse

NewResourceResponse builds a response carrying only the allowlisted representation headers copied from src. The caller owns body and must close it.

func (*ResourceResponse) AcceptRanges

func (r *ResourceResponse) AcceptRanges() string

AcceptRanges returns the allowlisted Accept-Ranges header value.

func (*ResourceResponse) CacheControl

func (r *ResourceResponse) CacheControl() string

CacheControl returns the allowlisted Cache-Control header value.

func (*ResourceResponse) ContentLength

func (r *ResourceResponse) ContentLength() int64

ContentLength returns the allowlisted Content-Length header value as an integer, or zero when absent or malformed.

func (*ResourceResponse) ContentRange

func (r *ResourceResponse) ContentRange() string

ContentRange returns the allowlisted Content-Range header value.

func (*ResourceResponse) ContentType

func (r *ResourceResponse) ContentType() string

ContentType returns the allowlisted Content-Type header value.

func (*ResourceResponse) ETag

func (r *ResourceResponse) ETag() string

ETag returns the allowlisted ETag header value.

func (*ResourceResponse) Header

func (r *ResourceResponse) Header() http.Header

Header returns a copy of the allowlisted representation headers.

func (*ResourceResponse) LastModified

func (r *ResourceResponse) LastModified() string

LastModified returns the allowlisted Last-Modified header value.

type RetryAdvice

type RetryAdvice struct {
	Safe     bool
	After    time.Time
	HasAfter bool
}

RetryAdvice carries retry information derived only from verified upstream sources. Safe expresses that the operation can be safely retried from an operation-commit perspective; it does not mean the SDK retries automatically. After is only populated from a validated upstream value and is meaningful when HasAfter is true.

type SaveOptions

type SaveOptions struct {
	Path     string
	Progress func(SaveProgress)
}

SaveOptions configures a single-resource atomic save. SaveResource writes to an atomic destination under Path, so a partially transferred file never appears at the final path. Progress, when non-nil, is called as bytes are written; it must not block or perform network I/O.

type SaveProgress

type SaveProgress struct {
	Total int64
	Done  int64
}

SaveProgress reports incremental progress while a resource is being saved. Total is the expected size in bytes when known, otherwise zero; Done is the number of bytes written so far.

type SavedResource

type SavedResource struct {
	Path        string
	Size        int64
	ContentType string
}

SavedResource reports the result of SaveResource. ContentType is the allowlisted upstream media type when the product resource response supplied it.

type Transport

type Transport string

Transport classifies the transport layer a failure originated in. It helps callers distinguish network-level failures from classified upstream errors.

const (
	TransportHTTP  Transport = "http"
	TransportTLS   Transport = "tls"
	TransportDNS   Transport = "dns"
	TransportLocal Transport = "local"
)

Transport kinds classify the transport layer a failure originated in.

Directories

Path Synopsis
Package fanbox provides the public Pixiv FANBOX SDK.
Package fanbox provides the public Pixiv FANBOX SDK.
Package pixiv provides the public Pixiv SDK backed exclusively by the Pixiv App API.
Package pixiv provides the public Pixiv SDK backed exclusively by the Pixiv App API.

Jump to

Keyboard shortcuts

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