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.
The package consists of Page and Cursor for list pagination, Error with its Reason classification, Resource and ResourceRef for first-party media, and WriteResource for atomic saves with progress.
This package does not import product models or account state. Product-specific clients live in sdk/pixiv and sdk/fanbox; they share these primitives and remain independent of each other.
Index ¶
- func CursorEphemeral(c Cursor) bool
- func CursorIdentity(c Cursor) (identity string, ok bool)
- func CursorPayload(c Cursor) ([]byte, error)
- func CursorQueryHash(query url.Values) string
- func IsReason(err error, reason Reason) bool
- func ResourceRefPayload(r ResourceRef) ([]byte, error)
- func ResourceRefProduct(r ResourceRef) (string, error)
- func ValidateCursor(c Cursor, product, operation string, bindingVersion int, queryHash string) error
- func ValidateCursorInstance(c Cursor, instance string) error
- func WriteResource(ctx context.Context, product, operation string, source io.Reader, total int64, ...) (int64, error)
- type Cursor
- type CursorOption
- type Error
- type ErrorOption
- type OpenResourceRequest
- type Page
- type Reason
- type Resource
- type ResourceMethod
- type ResourceRef
- type ResourceResponse
- func (r *ResourceResponse) AcceptRanges() string
- func (r *ResourceResponse) CacheControl() string
- func (r *ResourceResponse) ContentLength() int64
- func (r *ResourceResponse) ContentRange() string
- func (r *ResourceResponse) ContentType() string
- func (r *ResourceResponse) ETag() string
- func (r *ResourceResponse) Header() http.Header
- func (r *ResourceResponse) LastModified() string
- type RetryAdvice
- type SaveOptions
- type SaveProgress
- type SavedResource
- type Transport
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CursorEphemeral ¶
CursorEphemeral reports whether the cursor is valid only for the client instance that produced it, which happens when creation could not verify an identity.
func CursorIdentity ¶
CursorIdentity reports the verified non-secret identity bound to the cursor, if any.
func CursorPayload ¶
CursorPayload returns the opaque upstream continuation state, letting product SDK implementations re-attach per-request secrets when continuing an operation.
func CursorQueryHash ¶ added in v1.3.0
CursorQueryHash returns the stable binding digest of a base request query. Keys and repeated values are sorted without modifying query; product SDKs remove continuation parameters before calling it.
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 ¶
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.
func WriteResource ¶ added in v1.3.0
func WriteResource(ctx context.Context, product, operation string, source io.Reader, total int64, options SaveOptions) (int64, error)
WriteResource atomically saves a validated resource stream with progress. Product SDK implementations supply their error product/operation labels and the known byte total (zero when unknown). The caller owns and closes source. Write failures return LocalStateError with only a redacted cause; cancellation remains recognizable through errors.Is and leaves the destination unchanged.
Types ¶
type Cursor ¶
type Cursor struct {
// contains filtered or unexported fields
}
Cursor is the opaque continuation token carried by sdk.Page. Its value belongs to the product SDK, which creates it; 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 ¶
ParseCursor decodes a cursor from its route-safe unpadded base64url text encoding, returning InvalidCursor for malformed input.
func (Cursor) MarshalJSON ¶
MarshalJSON encodes the cursor as a JSON string containing its Text form.
func (Cursor) MarshalText ¶
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 ¶
String returns the text encoding. It is safe to log and persist, although an ephemeral cursor may still be rejected by another client instance or process.
func (*Cursor) UnmarshalJSON ¶
UnmarshalJSON decodes a cursor from a JSON string containing its Text form.
func (*Cursor) UnmarshalText ¶
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 adds binding metadata while NewCursor builds a cursor.
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 carries a classified, redacted failure from the product SDKs and 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 ¶
Error renders a human-readable summary that never includes raw upstream artifacts; the cause is a redacted classification.
type ErrorOption ¶
type ErrorOption func(*Error)
ErrorOption adds classification fields while NewError builds an Error.
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 records the normalized upstream HTTP status; zero means upstream reported none.
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 describes one OpenResource call. The zero Method means GET. The header fields are validated with Validate, so 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 ¶
Page pairs one page of list results with the cursor for 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.
func (Page[T]) MarshalJSON ¶ added in v1.3.0
MarshalJSON emits the cursor as its stable text; the last page has an empty next cursor.
type Reason ¶
type Reason string
Reason classifies a failure in a form both product SDKs share and callers can match on. Reasons are part of the v1 contract: new reasons may be added, but an existing one is never removed, renamed, or reused for another meaning.
const ( InvalidArgument Reason = "invalid_argument" InvalidCursor Reason = "invalid_cursor" CredentialsExpired Reason = "credentials_expired" Forbidden Reason = "forbidden" NotFound Reason = "not_found" ChallengeRequired Reason = "challenge_required" RateLimited Reason = "rate_limited" UpstreamError Reason = "upstream_error" MalformedUpstreamResponse Reason = "malformed_upstream_response" ResourceForbidden Reason = "resource_forbidden" LocalStateError Reason = "local_state_error" RemovedSetting Reason = "removed_setting" )
InvalidArgument and the remaining reasons are the stable v1 classifications both product SDKs return. A reason may be added, never removed, renamed, or reused for another meaning.
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 describes a first-party media item returned 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 serve different purposes and neither is derived from the other. The JSON form exposes only Ref and RequiresCredentials, so runtime locators never cross an output boundary.
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 ¶
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.
func (Resource) MarshalJSON ¶ added in v1.3.0
MarshalJSON emits only the opaque reference and the credential requirement, never URL, request headers, or expiry metadata. A resource without a reference marshals as null.
type ResourceMethod ¶
type ResourceMethod string
ResourceMethod names an OpenResource verb. The zero value means GET.
const ( ResourceMethodGet ResourceMethod = "GET" ResourceMethodHead ResourceMethod = "HEAD" )
ResourceMethodGet and ResourceMethodHead are the two accepted verbs.
type ResourceRef ¶
type ResourceRef struct {
// contains filtered or unexported fields
}
ResourceRef identifies one first-party media resource within a product namespace. It is a stable cache key that callers hand back to OpenResource or SaveResource so the product SDK can revalidate and safely read the resource. Unlike Resource.URL, it survives beyond a single signed locator.
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 unset.
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, suitable for URL path segments.
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 {
// Filename is an upstream-suggested attachment name, including its extension
// when provided. Empty means unavailable. It is metadata, not a trusted path;
// callers must normalize it before choosing a filesystem destination.
Filename string
StatusCode int
Body io.ReadCloser
// contains filtered or unexported fields
}
ResourceResponse reports the result of opening a resource. The caller owns Body and must close it; it is a non-nil empty stream for HEAD, 204, and 304 responses. Header and the typed getters expose only allowlisted representation headers.
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 upstream range support header, or empty when absent.
func (*ResourceResponse) CacheControl ¶
func (r *ResourceResponse) CacheControl() string
CacheControl returns the upstream caching directive, or empty when absent.
func (*ResourceResponse) ContentLength ¶
func (r *ResourceResponse) ContentLength() int64
ContentLength parses the allowlisted Content-Length header, or returns zero when it is absent or malformed. It describes the upstream representation, so a HEAD or 304 response can report a non-zero length with an empty Body.
func (*ResourceResponse) ContentRange ¶
func (r *ResourceResponse) ContentRange() string
ContentRange returns the upstream byte-range header, or empty when absent.
func (*ResourceResponse) ContentType ¶
func (r *ResourceResponse) ContentType() string
ContentType returns the upstream media type, or empty when not provided.
func (*ResourceResponse) ETag ¶
func (r *ResourceResponse) ETag() string
ETag returns the upstream entity tag, or empty when absent.
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 upstream modification time in HTTP date form, or empty when absent.
type RetryAdvice ¶
RetryAdvice carries retry information derived only from verified upstream sources. Safe means the operation can be retried without risking a duplicate commit; the SDK never retries on its own. After comes from a validated upstream value and is meaningful only when HasAfter is true.
type SaveOptions ¶
type SaveOptions struct {
Path string
Progress func(SaveProgress)
}
SaveOptions controls a single-resource atomic save. Path receives the completed file, so a partially transferred file never appears there. Progress, when non-nil, runs on the reading goroutine; it must not block or perform network I/O.
type SaveProgress ¶
SaveProgress reports incremental progress during a save. Total is the expected size in bytes, or zero when unknown; Done is the number of bytes read so far.
type SavedResource ¶
SavedResource reports where a product save finished and the size it wrote. ContentType comes from the product's own response metadata.
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. |