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 ¶
- func CursorEphemeral(c Cursor) bool
- func CursorIdentity(c Cursor) (identity string, ok bool)
- func CursorPayload(c Cursor) ([]byte, error)
- 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
- type Cursor
- type CursorOption
- type Error
- type ErrorOption
- type OpenResourceRequest
- type Page
- type PageDTO
- type Reason
- type Resource
- type ResourceDTO
- 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 only valid for the client instance that produced it because no identity could be verified at creation.
func CursorIdentity ¶
CursorIdentity returns the verified non-secret identity bound to the cursor, if any.
func CursorPayload ¶
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 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.
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 ¶
ParseCursor decodes a cursor from its route-safe unpadded base64url text encoding, returning InvalidCursor for malformed input.
func (Cursor) IsZero ¶
IsZero reports whether the cursor is the zero value, which means there is no further page.
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 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 ¶
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 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 ¶
Error returns a safe, human-readable summary. It never includes raw upstream artifacts; the cause is expected to be a redacted classification.
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 ¶
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 ¶
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" 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" )
The v1 error reasons are the stable, machine-readable classifications shared by both product SDKs.
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.
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 {
// 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 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 ¶
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 ¶
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 ¶
SavedResource reports the result of SaveResource. ContentType is the allowlisted upstream media type when the product resource response supplied it.
Source Files
¶
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. |