goldsky

package module
v1.1.3 Latest Latest
Warning

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

Go to latest
Published: Sep 8, 2026 License: MIT Imports: 19 Imported by: 0

README

Goldsky Go SDK

Goldsky API Golang Client/SDK/Library

CI Tests Go Version License CodeQL Codecov GitHub Release GoDoc

A small, idiomatic Go client for Goldsky. It covers the REST control plane, Subgraph GraphQL endpoints, and Edge JSON-RPC without pulling any third-party runtime dependencies into your application.

This is a community-maintained SDK, not an official Goldsky package. The public API follows ordinary Go conventions: explicit contexts, typed request and response models where the upstream contract is stable, and raw JSON where Goldsky intentionally leaves a schema open.

The SDK is built against Goldsky REST API v1.2.0 and covers all 40 documented operations. If you prefer learning from complete programs, start with the runnable examples.

Contents

Installation

Go 1.22 or later.

go get github.com/tigusigalpa/goldsky-go
import goldsky "github.com/tigusigalpa/goldsky-go"

Quick start

Create a project API token in the Goldsky dashboard, export it as GOLDSKY_API_KEY, and reuse one client throughout your application:

client, err := goldsky.NewClient(
    os.Getenv("GOLDSKY_API_KEY"),
    goldsky.WithTimeout(30*time.Second),
)
if err != nil {
    log.Fatal(err)
}

ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()

page, err := client.Pipelines.List(ctx, goldsky.ListPipelinesOptions{PageSize: 25})
if err != nil {
    log.Fatal(err)
}
for _, pipeline := range page.Data {
    fmt.Printf("%-30s %s\n", pipeline.Name, pipeline.Status)
}

Client setup

Goldsky uses two different credentials:

  • The project API token authenticates REST and private GraphQL calls. Pass it to NewClient.
  • The Edge endpoint API key authenticates Edge JSON-RPC calls. Pass it with WithEdgeAPIKey or rotate it later with the concurrency-safe SetEdgeAPIKey.

The project token is sent in Authorization: Bearer <token>. The Edge key is sent in X-ERPC-Secret-Token, so it is not embedded in the request URL.

client, err := goldsky.NewClient(
    os.Getenv("GOLDSKY_API_KEY"),
    goldsky.WithEdgeAPIKey(os.Getenv("GOLDSKY_EDGE_API_KEY")),
    goldsky.WithTimeout(30*time.Second),
)
if err != nil {
    log.Fatal(err)
}

If your process only needs public GraphQL or Edge RPC, it does not need a REST token:

client, err := goldsky.NewDataClient(
    goldsky.WithEdgeAPIKey(os.Getenv("GOLDSKY_EDGE_API_KEY")),
)

Calling a REST method or QueryPrivate on this client returns ErrAPITokenRequired locally, before any request is sent. A public GraphQL query needs neither credential; an Edge RPC call needs only the Edge key.

The constructor performs no network calls. Options are validated up front, and a custom http.Client is copied before a timeout override is applied.

Configuration

Most applications only need a token and a timeout. The other options are useful for tests, proxies, private gateways, and operational tuning.

Option Purpose
WithTimeout Sets the end-to-end http.Client timeout. The default is 60 seconds.
WithHTTPClient Supplies a custom transport, proxy, TLS policy, or redirect policy. The client value is shallow-copied.
WithRetryPolicy / WithRetryMaxAttempts Changes automatic retry behavior.
WithMaxResponseBodyBytes Caps buffered REST, GraphQL, and RPC responses. The default is 16 MiB.
WithUserAgent Replaces the default goldsky-go/1.1.2 user agent.
WithLogger Receives redacted retry diagnostics.
WithBaseURL / WithEdgeBaseURL Points tests or compatible gateways at another base URL.

WithTimeout and WithHTTPClient are order-independent. The supplied *http.Client is not mutated, but its Transport is shared by the shallow copy, matching the standard library's normal reuse model.

What is covered

Service Use it for
Pipelines Create, validate, inspect, pause, resume, restart, and delete Turbo Pipelines; read logs, state, and status.
Subgraphs Deploy and manage versions and tags; read indexing logs and webhook entities.
Webhooks Create, list, and delete entity webhooks.
Edge Manage Edge endpoints, keys, lifecycle, and metrics.
Catalogs Discover supported subgraph chains, Edge networks, and Edge Data sources.
GraphQL Query public or private Subgraph GraphQL endpoints.
RPC Make single or batch HTTPS JSON-RPC 2.0 calls through Goldsky Edge.

The exact operation-to-method mapping lives in docs/api-coverage.md.

REST API

ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()

page, err := client.Pipelines.List(ctx, goldsky.ListPipelinesOptions{PageSize: 50})
if err != nil {
    log.Fatal(err)
}
for _, p := range page.Data {
    fmt.Println(p.Name, p.Status)
}

ep, err := client.Edge.Get(ctx, "my-endpoint")
if err != nil {
    log.Fatal(err)
}
fmt.Println(ep.Name, ep.Status)

Path components and query values are escaped by the SDK. Every call accepts a context.Context, so cancellation and deadlines work the same way as in the standard library.

Pagination

Pipelines, subgraphs, and Edge endpoints page with page_size/page_token. A page can hold fewer than page_size items and still have a next page, so completion is inferred from next_page_token alone.

pager := client.Subgraphs.NewSubgraphPager(goldsky.ListSubgraphsOptions{PageSize: 100})
for {
    page, err := pager.NextPage(ctx)
    if err != nil {
        return err
    }
    for _, s := range page.Data {
        fmt.Println(s.Name, s.Version, s.Health)
    }
    if !page.HasMore() {
        break
    }
}

Once a pager reaches the last page, later NextPage calls return an empty page without making another HTTP request. Invalid page sizes are rejected locally.

Deploy a subgraph

Deploy streams the bundle as multipart/form-data without buffering the whole zip in memory. The server accepts up to 50 MB compressed / 100 MB extracted. overwrite=1 is rejected locally before the request is sent.

f, err := os.Open("build.zip")
if err != nil {
    log.Fatal(err)
}
defer f.Close()
s, err := client.Subgraphs.Deploy(ctx, "my-sub", "v1", goldsky.DeploySubgraphOptions{
    Bundle:         f,
    BundleFilename: "build.zip",
})
if err != nil {
    log.Fatal(err)
}
fmt.Println("deployed", s.Name, s.Version)

Streaming uploads are never retried automatically because an arbitrary io.Reader cannot be replayed safely. Open a fresh file and call Deploy again only after you have checked whether the first request took effect.

GraphQL

Use QueryPrivate for a private endpoint and QueryPublic for a public one. Both return the HTTP status and response headers alongside raw data, errors, and extensions fields.

resp, err := client.GraphQL.QueryPrivate(ctx, projectID, "my-sub", "v1", goldsky.GraphQLRequest{
    Query: "{ _meta { block { number } } }",
})
if err != nil {
    log.Fatal(err)
}
if resp.HasErrors() {
    for _, e := range resp.Errors {
        fmt.Println(e.Message)
    }
    return
}
fmt.Println(string(resp.Data))

Decode Data into the shape owned by your application:

var data struct {
    Meta struct {
        Block struct {
            Number int `json:"number"`
        } `json:"block"`
    } `json:"_meta"`
}
if err := json.Unmarshal(resp.Data, &data); err != nil {
    return err
}

For public data access, construct a tokenless client and call QueryPublic:

client, err := goldsky.NewDataClient()
if err != nil {
    log.Fatal(err)
}
resp, err := client.GraphQL.QueryPublic(ctx, projectID, "my-sub", "prod", request)

Public endpoints have a documented default rate limit of 50 requests per 10 seconds; the SDK does not perform aggressive hidden retries.

Edge RPC

HTTPS JSON-RPC 2.0 only — no WebSockets or subscriptions.

client, err := goldsky.NewDataClient(
    goldsky.WithEdgeAPIKey(os.Getenv("GOLDSKY_EDGE_API_KEY")),
)
if err != nil {
    log.Fatal(err)
}

var block string
if err := client.RPC.Call(ctx, 1, "eth_blockNumber", nil, &block); err != nil {
    log.Fatal(err)
}
n, err := strconv.ParseUint(strings.TrimPrefix(block, "0x"), 16, 64)
if err != nil {
    log.Fatalf("unexpected block number %q: %v", block, err)
}
fmt.Println("latest Ethereum block:", n)

Batch responses can arrive in any order; Batch matches them back to the input calls by JSON-RPC request ID:

var block, chain string
responses, err := client.RPC.Batch(ctx, 1, []goldsky.RPCBatchCall{
    {Method: "eth_blockNumber", Result: &block},
    {Method: "eth_chainId", Result: &chain},
})
if err != nil {
    log.Fatal(err)
}
for _, response := range responses {
    if response.Error != nil {
        fmt.Println("RPC error:", response.Error)
    }
}

A successful transport does not mean every batch item succeeded. Always inspect each RPCResponse.Error. The client rejects malformed protocol envelopes, unknown or duplicate IDs, and responses containing both result and error.

Webhook verification

Goldsky deliveries carry the literal goldsky-webhook-secret header. Verify in constant time; no HMAC format is documented.

if !goldsky.VerifyWebhookRequest(r, storedSecret) {
    http.Error(w, "invalid secret", http.StatusUnauthorized)
    return
}

Read the request body only after verification, and return a 2xx status once the event has been accepted. The header contains a shared secret, not an HMAC signature, so protect it like any other credential.

Errors

REST failures are returned as RFC 9457 application/problem+json. Use AsProblem to inspect them and branch on the stable type URI or a status helper, not on human-readable prose:

if problem := goldsky.AsProblem(err); problem != nil {
    if problem.IsNotFound() {
        fmt.Println("resource does not exist")
        return
    }
    if problem.IsRateLimited() {
        if seconds, ok := problem.RetryAfter(); ok {
            fmt.Println("retry after", seconds, "seconds")
        }
    }
    fmt.Println(problem.Type) // stable URI
}

Validation failures (400) include a field errors array. Transport failures (network, cancellation, or malformed JSON) are *TransportError and support errors.As. GraphQL errors remain in GraphQLResponse.Errors; JSON-RPC errors are returned as *RPCError for single calls and per response for batches.

Non-2xx responses retain a bounded copy of the server body in ProblemDetails.RawBody. Treat it as diagnostic data: avoid logging it blindly, because an upstream proxy or application could echo sensitive request content.

Retries

By default only safe reads (GET, HEAD, OPTIONS) are retried on transport errors and 429/500/502/503/504, with capped exponential backoff plus jitter, honouring Retry-After. Mutations are not retried automatically (no documented idempotency keys). Opt in with goldsky.WithRetryMutations() only when your workflow can tolerate a duplicate mutation. Streaming deployments remain single-attempt even after opting in.

To disable retries, set the total attempt count to one:

client, err := goldsky.NewClient(
    os.Getenv("GOLDSKY_API_KEY"),
    goldsky.WithRetryMaxAttempts(1),
)

Security

  • The REST token and Edge key are never logged or included in error messages.
  • Webhook secrets and Edge API keys are one-time secrets returned to the caller only; store them immediately.
  • Edge RPC authentication uses X-ERPC-Secret-Token; the SDK never adds the key to an endpoint URL.
  • Webhook verification compares a shared secret in constant time. It does not prove payload integrity with an HMAC signature because Goldsky does not document such a signature format.
  • See docs/security.md for the full credential and retry guidance.

Best practices

  • Create one Client and reuse it. http.Client, the services, and Edge key rotation are safe for concurrent use; individual pagers are not.
  • Put a deadline on every operation. A client timeout is a safety net, while a request context lets each caller choose an appropriate budget.
  • Keep mutation retries disabled unless duplicate creates or updates are safe in your workflow. Check the resource after an ambiguous timeout.
  • Validate a pipeline before creating it, and use a distinct lowercase name for each example or integration test.
  • Persist one-time webhook and Edge secrets before returning success from your provisioning workflow.
  • For webhook handlers, authenticate first, cap the request body, enqueue work, and respond quickly. Make processing idempotent because deliveries may be retried.

Known limits

  • Edge support is HTTPS JSON-RPC only. WebSockets and subscriptions are outside the current API.
  • GraphQL data, pipeline definitions, and pipeline state remain raw JSON or map[string]any; their schemas belong to user-defined subgraphs and pipeline configurations.
  • Responses are buffered in memory and limited to 16 MiB by default. Increase the cap explicitly only when you expect larger payloads.
  • The local OpenAPI fixture is a reviewed snapshot, not code generated at build time. Re-check it when Goldsky publishes a new REST API version.
  • Streaming subgraph deployment bodies cannot be replayed and are never retried.

FAQ

Do I need both API keys?

No. REST and private GraphQL need the project API token. Edge RPC needs the Edge endpoint key. Public GraphQL needs neither. Use NewDataClient when no REST control-plane access is required.

Why did a batch RPC call return no top-level error but contain failures?

JSON-RPC batch items fail independently. The top-level error reports transport or malformed-envelope failures; inspect response.Error for each item.

Can I retry a timed-out create or update?

Only after checking whether it already succeeded. Goldsky does not document idempotency keys, so automatic mutation retries are deliberately opt-in.

Why is GraphQL Data a json.RawMessage?

Every subgraph has its own schema. Keeping the SDK generic avoids brittle generated types and lets your application decode exactly the fields it owns.

Examples and reference

Development

The repository has no runtime dependencies. Before opening a change, run:

go mod tidy
go build ./...
go vet ./...
go test -race ./...

Contract tests cover every REST operation in the checked-in OpenAPI snapshot; edge-case tests cover pagination, retry behavior, JSON envelopes, multipart streaming, secret handling, and the two data-plane clients.

License

MIT — Copyright (c) 2026 Igor Sazonov

Documentation

Overview

Package goldsky provides a Go client for the Goldsky REST control plane, Subgraph GraphQL endpoints, Edge JSON-RPC, and webhook verification.

Use NewClient for control-plane or private GraphQL operations that require a project API token. Use NewDataClient for public GraphQL and Edge RPC-only applications. A Client is safe to reuse across goroutines; individual pagers are stateful and should be consumed by one goroutine.

Index

Constants

View Source
const DefaultBaseURL = "https://api.goldsky.com/api/v1"

DefaultBaseURL is the Goldsky REST control-plane base URL.

View Source
const DefaultEdgeBaseURL = "https://edge.goldsky.com/standard/evm"

DefaultEdgeBaseURL is the Goldsky Edge RPC HTTPS JSON-RPC base URL.

View Source
const DefaultGraphQLBaseURL = "https://api.goldsky.com/api"

DefaultGraphQLBaseURL is the Goldsky Subgraph GraphQL data-plane base URL.

View Source
const DefaultMaxResponseBodyBytes int64 = 16 << 20 // 16 MiB

DefaultMaxResponseBodyBytes is the largest REST, GraphQL, or JSON-RPC response body read into memory by default.

View Source
const DefaultUserAgent = "goldsky-go/1.1.2"

DefaultUserAgent is the default User-Agent header for REST requests.

View Source
const EdgeSecretHeader = "X-ERPC-Secret-Token"

EdgeSecretHeader is the documented header used to authenticate Edge RPC requests without putting the secret in URLs or access logs.

View Source
const WebhookSecretHeader = "goldsky-webhook-secret"

WebhookSecretHeader is the literal header Goldsky sends on every webhook delivery carrying the shared secret.

Variables

View Source
var ErrAPITokenRequired = errors.New("goldsky: REST project API token is required")

ErrAPITokenRequired is returned when a REST control-plane or private GraphQL operation is attempted without a project API token.

Functions

func VerifyWebhookRequest

func VerifyWebhookRequest(r *http.Request, expected string) bool

VerifyWebhookRequest verifies the goldsky-webhook-secret header on an http.Request against the expected secret. It returns true only when the header is present and matches in constant time.

func VerifyWebhookSecret

func VerifyWebhookSecret(provided, expected string) bool

VerifyWebhookSecret reports whether the provided secret matches the expected secret in constant time. Goldsky deliveries carry the secret verbatim in the goldsky-webhook-secret header; Goldsky does not document an HMAC signature format, so this helper performs a direct constant-time comparison only.

Pass the raw header value as provided and the secret you stored at webhook creation time. A non-empty expected secret is required; an empty expected secret always returns false to prevent accidental acceptance of unset secrets.

Types

type CatalogService

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

CatalogService lists supported chains, networks, and Edge Data sources. These endpoints are also reachable through the Subgraph and Edge services for convenience; this service groups the catalog reads together.

func (*CatalogService) EdgeNetworks

func (s *CatalogService) EdgeNetworks(ctx context.Context) (EdgeNetworksResponse, error)

EdgeNetworks lists supported Edge networks. See https://api.goldsky.com/api/v1/docs#tag/Catalogs/operation/listEdgeNetworks

func (*CatalogService) EdgeSources

func (s *CatalogService) EdgeSources(ctx context.Context) (EdgeSourcesResponse, error)

EdgeSources lists Edge Data sources. See https://api.goldsky.com/api/v1/docs#tag/Catalogs/operation/listEdgeSources

func (*CatalogService) SupportedSubgraphChains

func (s *CatalogService) SupportedSubgraphChains(ctx context.Context) (SubgraphChainsResponse, error)

SupportedSubgraphChains lists supported deployment chains. See https://api.goldsky.com/api/v1/docs#tag/Catalogs/operation/listSubgraphChains

type Client

type Client struct {

	// Pipelines manages Turbo Pipelines.
	Pipelines *PipelineService
	// Subgraphs manages Subgraphs and their versions, tags, and deployments.
	Subgraphs *SubgraphService
	// Webhooks manages Subgraph entity webhooks.
	Webhooks *WebhookService
	// Edge manages Edge endpoints and their lifecycle.
	Edge *EdgeService
	// Catalogs lists supported chains, networks, and Edge Data sources.
	Catalogs *CatalogService
	// GraphQL queries Subgraph GraphQL data-plane endpoints.
	GraphQL *GraphQLService
	// RPC calls the Edge HTTPS JSON-RPC data plane.
	RPC *RPCService
	// contains filtered or unexported fields
}

Client is the top-level Goldsky client. It exposes grouped service clients for the REST control plane and the GraphQL and Edge RPC data planes.

Create one client and reuse it for the lifetime of your application. The REST project API token and the Edge endpoint API key are distinct secrets; both are kept unexported and never appear in error messages or logs.

func NewClient

func NewClient(apiToken string, options ...Option) (*Client, error)

NewClient creates a Goldsky client with the supplied REST project API token and options. It performs no network calls. The token is scoped to a single Goldsky project and is sent as a Bearer header; it is never logged.

func NewDataClient added in v1.1.3

func NewDataClient(options ...Option) (*Client, error)

NewDataClient creates a client for public GraphQL and Edge RPC calls without requiring a REST project token. REST control-plane and private GraphQL calls return ErrAPITokenRequired without sending a request.

func (*Client) BaseURL

func (c *Client) BaseURL() string

BaseURL returns the REST control-plane base URL in use.

func (*Client) SetEdgeAPIKey

func (c *Client) SetEdgeAPIKey(key string)

SetEdgeAPIKey changes the Edge endpoint API key used by RPC calls. It is safe to call while other goroutines use the client. The Edge key is a separate secret from the REST token used by private GraphQL calls.

func (*Client) UserAgent

func (c *Client) UserAgent() string

UserAgent returns the User-Agent header sent on REST requests.

type Clock added in v1.1.2

type Clock interface {
	Now() time.Time
}

Clock supplies the current time for Retry-After calculations. Most callers should use the system clock configured by default; the interface exists for deterministic tests.

type CreateEdgeEndpointRequest

type CreateEdgeEndpointRequest struct {
	Name            string               `json:"name"`
	Product         *EdgeProduct         `json:"product,omitempty"`
	RateLimitBudget *EdgeRateLimitBudget `json:"rate_limit_budget,omitempty"`
	AllowedDomains  []string             `json:"allowed_domains,omitempty"`
}

CreateEdgeEndpointRequest creates an Edge endpoint.

type CreateEdgeEndpointResponse

type CreateEdgeEndpointResponse struct {
	Data struct {
		EdgeEndpoint
		APIKey string `json:"api_key"`
	} `json:"data"`
	Warnings []string `json:"warnings,omitempty"`
}

CreateEdgeEndpointResponse is the create response. APIKey is a one-time secret shown here and via the reveal endpoint only; it is never logged.

type CreatePipelineRequest

type CreatePipelineRequest struct {
	// Name matches ^[a-z0-9-]{1,50}$. May also be set inside Definition.
	Name           string             `json:"name,omitempty"`
	ResourceSize   string             `json:"resource_size,omitempty"`
	Description    string             `json:"description,omitempty"`
	UseDedicatedIP *bool              `json:"use_dedicated_ip,omitempty"`
	Definition     PipelineDefinition `json:"definition"`
}

CreatePipelineRequest creates a pipeline.

type CreateWebhookRequest

type CreateWebhookRequest struct {
	Name                 string  `json:"name"`
	SubgraphName         string  `json:"subgraph_name"`
	SubgraphVersion      string  `json:"subgraph_version"`
	Entity               string  `json:"entity"`
	WebhookURL           string  `json:"webhook_url"`
	Secret               *string `json:"secret,omitempty"`
	NumRetries           *int    `json:"num_retries,omitempty"`
	RetryIntervalSeconds *int    `json:"retry_interval_seconds,omitempty"`
	RetryTimeoutSeconds  *int    `json:"retry_timeout_seconds,omitempty"`
}

CreateWebhookRequest creates an entity webhook.

Secret is sent as the goldsky-webhook-secret header on every delivery. If omitted, the server generates one and returns it once in the create response. num_retries is 0-10; retry_interval_seconds and retry_timeout_seconds are >=1.

type CreateWebhookResponse

type CreateWebhookResponse struct {
	Data struct {
		ID            string `json:"id"`
		Name          string `json:"name"`
		WebhookSecret string `json:"webhook_secret"`
	} `json:"data"`
}

CreateWebhookResponse is the create response. WebhookSecret is a one-time secret: it is returned here and via no other endpoint, and must be stored by the caller immediately. It is never logged by the SDK.

type DeploySubgraphOptions

type DeploySubgraphOptions struct {
	// Bundle is the zip of the compiled subgraph build directory. Required.
	Bundle io.Reader
	// BundleFilename is the file name reported in the multipart part. Required.
	BundleFilename string
	// Overwrite is deprecated; "1" is rejected by the server. Omit or set "0".
	Overwrite string
	// RemoveGraft set to "1" strips the graft from the manifest before deploy.
	RemoveGraft string
	// SkipGraftValidation set to "1" skips validation of the graft base.
	SkipGraftValidation string
	// StartBlock is a block number string to start indexing from.
	StartBlock string
	// GraftFrom is "name/version" of an existing subgraph to graft from.
	GraftFrom string
	// Description is a human-readable description (max 500 characters).
	Description string
	// GraphNodeShard pins the deployment to a specific indexing shard. Advanced.
	GraphNodeShard string
}

DeploySubgraphOptions deploys a compiled subgraph bundle.

Bundle is streamed as a multipart file part and is never fully buffered in memory. The server accepts a maximum 50 MB compressed bundle and 100 MB extracted bundle. Overwrite is deprecated and "1" is rejected by the server; to replace a version, delete it and deploy again, or move a tag to it.

type EdgeEndpoint

type EdgeEndpoint struct {
	Name            string      `json:"name"`
	Product         EdgeProduct `json:"product"`
	Status          EdgeStatus  `json:"status"`
	RateLimitBudget *string     `json:"rate_limit_budget"`
	AllowedDomains  []string    `json:"allowed_domains"`
	CreatedAt       time.Time   `json:"created_at"`
	UpdatedAt       time.Time   `json:"updated_at"`
	PausedAt        *time.Time  `json:"paused_at"`
}

EdgeEndpoint is an Edge endpoint resource.

type EdgeMetricsData

type EdgeMetricsData struct {
	Requests []MetricPoint `json:"requests"`
	Errors   []MetricPoint `json:"errors"`
}

EdgeMetricsData is the data envelope of the Edge metrics endpoint.

type EdgeMetricsOptions

type EdgeMetricsOptions struct {
	From       time.Time
	To         time.Time
	BucketSize string
}

EdgeMetricsOptions filters Edge endpoint metrics.

type EdgeMetricsResponse

type EdgeMetricsResponse struct {
	Data EdgeMetricsData `json:"data"`
}

EdgeMetricsResponse is the Edge metrics endpoint envelope.

type EdgeNetwork

type EdgeNetwork struct {
	ChainID     *json.Number `json:"chain_id"`
	Name        string       `json:"name"`
	NetworkName string       `json:"network_name"`
	ChainName   string       `json:"chain_name"`
	LogoURL     string       `json:"logo_url"`
}

EdgeNetwork is a supported Edge network.

type EdgeNetworksResponse

type EdgeNetworksResponse struct {
	Data []EdgeNetwork `json:"data"`
}

EdgeNetworksResponse lists supported Edge networks.

type EdgePager

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

EdgePager iterates Edge endpoint pages, cancellation-aware.

func (*EdgePager) NextPage

func (p *EdgePager) NextPage(ctx context.Context) (Page[EdgeEndpoint], error)

NextPage fetches the next page.

type EdgeProduct

type EdgeProduct string

EdgeProduct is the product type of an Edge endpoint.

const (
	EdgeProductRPC   EdgeProduct = "rpc"
	EdgeProductData  EdgeProduct = "data"
	EdgeProductBoost EdgeProduct = "boost"
)

Supported Edge product values.

type EdgeRateLimitBudget

type EdgeRateLimitBudget string

EdgeRateLimitBudget is a named rate-limit budget applied per API key across all networks. Known values are listed as constants; the wire value is preserved verbatim so future additions do not break decoding.

const (
	EdgeTier6kUnlimitedPerIP   EdgeRateLimitBudget = "edge-tier-6krpm-total-unlimited-per-ip"
	EdgeTier60kUnlimitedPerIP  EdgeRateLimitBudget = "edge-tier-60krpm-total-unlimited-per-ip"
	EdgeTier180kUnlimitedPerIP EdgeRateLimitBudget = "edge-tier-180krpm-total-unlimited-per-ip"
	EdgeTier360kUnlimitedPerIP EdgeRateLimitBudget = "edge-tier-360krpm-total-unlimited-per-ip"
	EdgeTier600kUnlimitedPerIP EdgeRateLimitBudget = "edge-tier-600krpm-total-unlimited-per-ip"
	EdgeTier6k500PerIP         EdgeRateLimitBudget = "edge-tier-6krpm-total-500rpm-per-ip"
	EdgeTier60k500PerIP        EdgeRateLimitBudget = "edge-tier-60krpm-total-500rpm-per-ip"
	EdgeTier180k500PerIP       EdgeRateLimitBudget = "edge-tier-180krpm-total-500rpm-per-ip"
	EdgeTier360k500PerIP       EdgeRateLimitBudget = "edge-tier-360krpm-total-500rpm-per-ip"
	EdgeTier600k500PerIP       EdgeRateLimitBudget = "edge-tier-600krpm-total-500rpm-per-ip"
	EdgeTierUnlimited100PerIP  EdgeRateLimitBudget = "edge-tier-unlimited-total-100rpm-per-ip"
	EdgeTierUnlimited500PerIP  EdgeRateLimitBudget = "edge-tier-unlimited-total-500rpm-per-ip"
)

Available Edge endpoint rate-limit budgets.

type EdgeService

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

EdgeService manages Edge endpoints and their lifecycle.

func (*EdgeService) Create

Create creates an Edge endpoint and returns the one-time API key. See https://api.goldsky.com/api/v1/docs#tag/Edge%20Endpoints/operation/createEdgeEndpoint

func (*EdgeService) Delete

func (s *EdgeService) Delete(ctx context.Context, name string) error

Delete deletes an Edge endpoint. Returns nil on 204. See https://api.goldsky.com/api/v1/docs#tag/Edge%20Endpoints/operation/deleteEdgeEndpoint

func (*EdgeService) Get

func (s *EdgeService) Get(ctx context.Context, name string) (EdgeEndpoint, error)

Get fetches an Edge endpoint. See https://api.goldsky.com/api/v1/docs#tag/Edge%20Endpoints/operation/getEdgeEndpoint

func (*EdgeService) List

List lists a single page of Edge endpoints. See https://api.goldsky.com/api/v1/docs#tag/Edge%20Endpoints/operation/listEdgeEndpoints

func (*EdgeService) NewEdgePager

func (s *EdgeService) NewEdgePager(opts ListEdgeEndpointsOptions) *EdgePager

NewEdgePager returns a pager over Edge endpoints starting at opts.PageToken.

func (*EdgeService) Pause

func (s *EdgeService) Pause(ctx context.Context, name string) (EdgeEndpoint, error)

Pause pauses an Edge endpoint. See https://api.goldsky.com/api/v1/docs#tag/Edge%20Lifecycle/operation/pauseEdgeEndpoint

func (*EdgeService) Resume

func (s *EdgeService) Resume(ctx context.Context, name string) (EdgeEndpoint, error)

Resume resumes a paused Edge endpoint. See https://api.goldsky.com/api/v1/docs#tag/Edge%20Lifecycle/operation/resumeEdgeEndpoint

func (*EdgeService) RevealKey

func (s *EdgeService) RevealKey(ctx context.Context, name string) (RevealEdgeKeyResponse, error)

RevealKey reveals the Edge endpoint API key. The key is a separate secret from the REST project token and is never logged. See https://api.goldsky.com/api/v1/docs#tag/Edge%20API%20Keys/operation/revealEdgeEndpointKey

type EdgeSource

type EdgeSource struct {
	ID           string `json:"id"`
	Name         string `json:"name"`
	Description  string `json:"description"`
	ProviderID   string `json:"provider_id"`
	ProviderName string `json:"provider_name"`
	LogoURL      string `json:"logo_url"`
	Endpoint     string `json:"endpoint"`
}

EdgeSource is an Edge Data source.

type EdgeSourcesResponse

type EdgeSourcesResponse struct {
	Data []EdgeSource `json:"data"`
}

EdgeSourcesResponse lists Edge Data sources.

type EdgeStatus

type EdgeStatus string

EdgeStatus is the lifecycle state of an Edge endpoint.

const (
	EdgeStatusActive EdgeStatus = "ACTIVE"
	EdgeStatusPaused EdgeStatus = "PAUSED"
)

Known Edge endpoint lifecycle states.

type GraphQLError

type GraphQLError struct {
	Message string          `json:"message"`
	Raw     json.RawMessage `json:"-"`
}

GraphQLError is a single GraphQL error. Message is human-readable; the complete error object is retained in Raw for forward compatibility.

func (*GraphQLError) UnmarshalJSON

func (e *GraphQLError) UnmarshalJSON(b []byte) error

UnmarshalJSON captures the message and retains the full error object.

type GraphQLRequest

type GraphQLRequest struct {
	Query         string         `json:"query"`
	Variables     map[string]any `json:"variables,omitempty"`
	OperationName string         `json:"operationName,omitempty"`
}

GraphQLRequest is the standard GraphQL request envelope.

type GraphQLResponse

type GraphQLResponse struct {
	Data       json.RawMessage `json:"data,omitempty"`
	Errors     []GraphQLError  `json:"errors,omitempty"`
	Extensions json.RawMessage `json:"extensions,omitempty"`
	Status     int             `json:"-"`
	Header     http.Header     `json:"-"`
}

GraphQLResponse is the GraphQL data-plane response.

func (*GraphQLResponse) HasErrors

func (r *GraphQLResponse) HasErrors() bool

HasErrors reports whether the response contains GraphQL errors.

type GraphQLService

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

GraphQLService queries Subgraph GraphQL data-plane endpoints.

Public endpoints use

https://api.goldsky.com/api/public/{project_id}/subgraphs/{subgraph_name}/{version_or_tag}/gn

and have a documented default rate limit of 50 requests per 10 seconds. Private endpoints use https://api.goldsky.com/api/private/.../gn and require the project Bearer token. The SDK does not perform aggressive hidden retries against these endpoints.

func (*GraphQLService) PrivateURL

func (s *GraphQLService) PrivateURL(projectID, subgraphName, versionOrTag string) string

PrivateURL builds the private Subgraph GraphQL endpoint URL.

func (*GraphQLService) PublicURL

func (s *GraphQLService) PublicURL(projectID, subgraphName, versionOrTag string) string

PublicURL builds the public Subgraph GraphQL endpoint URL.

func (*GraphQLService) Query

func (s *GraphQLService) Query(ctx context.Context, endpoint string, req GraphQLRequest, auth bool) (GraphQLResponse, error)

Query sends a GraphQL request to an arbitrary endpoint URL. The caller is responsible for using PublicURL or PrivateURL. When auth is true, the project Bearer token is sent; the token is never logged.

func (*GraphQLService) QueryPrivate

func (s *GraphQLService) QueryPrivate(ctx context.Context, projectID, subgraphName, versionOrTag string, req GraphQLRequest) (GraphQLResponse, error)

QueryPrivate queries a private Subgraph GraphQL endpoint using the project Bearer token.

func (*GraphQLService) QueryPublic

func (s *GraphQLService) QueryPublic(ctx context.Context, projectID, subgraphName, versionOrTag string, req GraphQLRequest) (GraphQLResponse, error)

QueryPublic queries a public Subgraph GraphQL endpoint.

type IndexingProgress

type IndexingProgress struct {
	Network              string      `json:"network"`
	ProgressPercent      json.Number `json:"progress_percent"`
	ChainHeadBlock       json.Number `json:"chain_head_block"`
	DeploymentHeadBlock  json.Number `json:"deployment_head_block"`
	DeploymentStartBlock json.Number `json:"deployment_start_block"`
	Synced               bool        `json:"synced"`
}

IndexingProgress is the per-network sync progress of a deployment.

type ListEdgeEndpointsOptions

type ListEdgeEndpointsOptions struct {
	Product   string
	PageSize  int
	PageToken string
}

ListEdgeEndpointsOptions filters and pages the Edge endpoint list.

type ListPipelinesOptions

type ListPipelinesOptions struct {
	// Type filters by pipeline type.
	Type string
	// PageSize is the page size, 1-200. Zero uses the server default.
	PageSize int
	// PageToken is the pagination cursor from a previous page.
	PageToken string
}

ListPipelinesOptions filters and pages the pipeline list.

type ListSubgraphsOptions

type ListSubgraphsOptions struct {
	PageSize  int
	PageToken string
}

ListSubgraphsOptions pages the subgraph list.

type LogRecord

type LogRecord struct {
	Text      string      `json:"text"`
	Timestamp json.Number `json:"timestamp"`
	Level     string      `json:"level"`
}

LogRecord is a single pipeline or subgraph log line.

type LogResults

type LogResults struct {
	Results []LogRecord  `json:"results"`
	Cursor  *json.Number `json:"cursor,omitempty"`
}

LogResults is the shape of the logs endpoint data envelope.

type MetricPoint

type MetricPoint struct {
	Time  string      `json:"time"`
	Value json.Number `json:"value"`
}

MetricPoint is a single time series sample in Edge endpoint metrics.

type Option

type Option func(*config)

Option configures a Client.

func WithBaseURL

func WithBaseURL(url string) Option

WithBaseURL overrides the REST control-plane base URL.

func WithClock

func WithClock(cl Clock) Option

WithClock injects a Clock for deterministic tests.

func WithEdgeAPIKey

func WithEdgeAPIKey(key string) Option

WithEdgeAPIKey sets the default Edge endpoint API key used by the RPC client. The Edge key is a separate secret from the REST project Bearer token; it is never logged or included in error messages.

func WithEdgeBaseURL

func WithEdgeBaseURL(url string) Option

WithEdgeBaseURL overrides the Edge RPC base URL.

func WithHTTPClient

func WithHTTPClient(h *http.Client) Option

WithHTTPClient supplies a custom *http.Client (transport, proxy, timeouts).

func WithLogger

func WithLogger(l *log.Logger) Option

WithLogger sets the logger used for redacted diagnostic messages.

func WithMaxResponseBodyBytes added in v1.1.3

func WithMaxResponseBodyBytes(n int64) Option

WithMaxResponseBodyBytes limits how much response data the client buffers. The limit applies to REST, GraphQL, and Edge RPC responses. Values must be positive. The default is 16 MiB.

func WithRetryMaxAttempts

func WithRetryMaxAttempts(n int) Option

WithRetryMaxAttempts is a convenience option setting the retry attempt count.

func WithRetryMutations

func WithRetryMutations() Option

WithRetryMutations opts in to retrying replayable non-idempotent mutations. Streaming multipart deployments are never retried because their readers cannot be replayed safely. Unsafe.

func WithRetryPolicy

func WithRetryPolicy(p RetryPolicy) Option

WithRetryPolicy overrides the retry policy.

func WithSleeper

func WithSleeper(s Sleeper) Option

WithSleeper injects a Sleeper for deterministic retry tests.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the timeout used by the client. When combined with WithHTTPClient, the supplied client is shallow-cloned before its timeout is changed, so the caller's *http.Client is never mutated.

func WithUserAgent

func WithUserAgent(ua string) Option

WithUserAgent overrides the User-Agent header.

type Page

type Page[T any] struct {
	Data       []T        `json:"data"`
	Pagination Pagination `json:"pagination"`
}

Page is a single page of paged list results.

func (Page[T]) HasMore

func (p Page[T]) HasMore() bool

HasMore reports whether another page is available.

type Pagination

type Pagination struct {
	// NextPageToken is the cursor for the next page, or nil when the list is
	// complete. A page can hold fewer than page_size items and still have a
	// next page, so completion must be inferred from this field alone.
	NextPageToken *string `json:"next_page_token"`
	// PageSize is the page size the server applied.
	PageSize json.Number `json:"page_size"`
}

Pagination is the cursor metadata returned by paged list endpoints.

type Pipeline

type Pipeline struct {
	Name         string             `json:"name"`
	Type         string             `json:"type"`
	Status       PipelineStatus     `json:"status"`
	Definition   PipelineDefinition `json:"definition"`
	ResourceSize string             `json:"resource_size,omitempty"`
	CreatedAt    time.Time          `json:"created_at"`
	UpdatedAt    time.Time          `json:"updated_at"`
	Version      json.Number        `json:"version,omitempty"`
	ProjectID    string             `json:"project_id,omitempty"`
}

Pipeline is a Turbo Pipeline resource.

type PipelineDefinition

type PipelineDefinition struct {
	// Name may hold the pipeline name when the authoring payload keeps it
	// inside definition. A top-level request Name takes precedence.
	Name           string         `json:"name,omitempty"`
	Sources        map[string]any `json:"sources"`
	Transforms     map[string]any `json:"transforms"`
	Sinks          map[string]any `json:"sinks"`
	Description    string         `json:"description,omitempty"`
	ResourceSize   string         `json:"resource_size,omitempty"`
	UseDedicatedIP bool           `json:"use_dedicated_ip,omitempty"`
	Job            bool           `json:"job,omitempty"`
}

PipelineDefinition is the flexible pipeline authoring payload. Sources, transforms, and sinks are intentionally open object maps in the OpenAPI contract, so they are exposed as map[string]any.

type PipelineErrorCountResponse

type PipelineErrorCountResponse struct {
	Data struct {
		ErrorCount json.Number `json:"error_count"`
	} `json:"data"`
}

PipelineErrorCountResponse is the pipeline error-count endpoint envelope.

type PipelineLogsOptions

type PipelineLogsOptions struct {
	// LogLevels is a comma-separated list of log levels.
	LogLevels string
	// Cursor is the log cursor from a previous response.
	Cursor *float64
	// After is a timestamp cursor.
	After *float64
	// Search filters log text.
	Search string
	// Direction is "asc" or "desc".
	Direction string
}

PipelineLogsOptions filters pipeline logs.

type PipelineLogsResponse

type PipelineLogsResponse struct {
	Data LogResults `json:"data"`
}

PipelineLogsResponse is the pipeline logs endpoint envelope.

type PipelinePager

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

PipelinePager iterates pipeline pages, cancellation-aware.

func (*PipelinePager) NextPage

func (p *PipelinePager) NextPage(ctx context.Context) (Page[Pipeline], error)

NextPage fetches the next page. When no more pages remain, the returned Page.HasMore is false and Data is empty on subsequent calls.

type PipelineService

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

PipelineService manages Turbo Pipelines.

func (*PipelineService) Delete

func (s *PipelineService) Delete(ctx context.Context, name string) error

Delete deletes a pipeline by name. See https://api.goldsky.com/api/v1/docs#tag/Pipelines/operation/deletePipeline

func (*PipelineService) ErrorCount

func (s *PipelineService) ErrorCount(ctx context.Context, name string, sinceHours int) (PipelineErrorCountResponse, error)

ErrorCount fetches the pipeline error count for the last hours. See https://api.goldsky.com/api/v1/docs#tag/Pipeline%20Logs/operation/getPipelineErrorCount

func (*PipelineService) Get

func (s *PipelineService) Get(ctx context.Context, name string) (Pipeline, error)

Get fetches a pipeline by name. See https://api.goldsky.com/api/v1/docs#tag/Pipelines/operation/getPipeline

func (*PipelineService) List

List lists a single page of pipelines. Use NewPipelinePager for full iteration. See https://api.goldsky.com/api/v1/docs#tag/Pipelines/operation/listPipelines

func (*PipelineService) Logs

Logs fetches a page of pipeline logs. See https://api.goldsky.com/api/v1/docs#tag/Pipeline%20Logs/operation/getPipelineLogs

func (*PipelineService) NewPipelinePager

func (s *PipelineService) NewPipelinePager(opts ListPipelinesOptions) *PipelinePager

NewPipelinePager returns a pager over pipelines starting at opts.PageToken.

func (*PipelineService) Pause

func (s *PipelineService) Pause(ctx context.Context, name string) error

Pause pauses a pipeline. See https://api.goldsky.com/api/v1/docs#tag/Pipeline%20Lifecycle/operation/pausePipeline

func (*PipelineService) Preview

Preview previews a pipeline for a limited time. See https://api.goldsky.com/api/v1/docs#tag/Pipeline%20Authoring/operation/previewPipeline

func (*PipelineService) Restart

func (s *PipelineService) Restart(ctx context.Context, name string, req *RestartPipelineRequest) error

Restart restarts a pipeline, optionally clearing state. See https://api.goldsky.com/api/v1/docs#tag/Pipeline%20Lifecycle/operation/restartPipeline

func (*PipelineService) Resume

func (s *PipelineService) Resume(ctx context.Context, name string) error

Resume resumes a paused pipeline. See https://api.goldsky.com/api/v1/docs#tag/Pipeline%20Lifecycle/operation/resumePipeline

func (*PipelineService) State

State fetches the pipeline state. The OpenAPI contract leaves the state schema open, so the raw JSON is returned. See https://api.goldsky.com/api/v1/docs#tag/Pipeline%20Status/operation/getPipelineState

func (*PipelineService) Status

Status fetches the pipeline status. See https://api.goldsky.com/api/v1/docs#tag/Pipeline%20Status/operation/getPipelineStatus

func (*PipelineService) Validate

Validate validates a pipeline definition without creating it. See https://api.goldsky.com/api/v1/docs#tag/Pipeline%20Authoring/operation/validatePipeline

type PipelineStateResponse

type PipelineStateResponse struct {
	Data json.RawMessage `json:"data"`
}

PipelineStateResponse wraps the raw pipeline state, whose schema is intentionally open in the OpenAPI contract.

type PipelineStatus

type PipelineStatus string

PipelineStatus is the lifecycle state of a pipeline. Known values are listed as constants; the wire value is preserved verbatim so future server enum additions do not cause decode failures.

const (
	PipelineStatusRunning    PipelineStatus = "RUNNING"
	PipelineStatusPaused     PipelineStatus = "PAUSED"
	PipelineStatusRestarting PipelineStatus = "RESTARTING"
	PipelineStatusDeploying  PipelineStatus = "DEPLOYING"
	PipelineStatusStopped    PipelineStatus = "STOPPED"
	PipelineStatusFailed     PipelineStatus = "FAILED"
	PipelineStatusSucceeded  PipelineStatus = "SUCCEEDED"
	PipelineStatusUnknown    PipelineStatus = "UNKNOWN"
)

Known pipeline lifecycle states.

type PipelineStatusResponse

type PipelineStatusResponse struct {
	Name   string         `json:"name"`
	Status PipelineStatus `json:"status"`
	Errors []struct {
		Message string `json:"message"`
	} `json:"errors"`
}

PipelineStatusResponse is the pipeline status endpoint envelope.

type PreviewPipelineRequest

type PreviewPipelineRequest struct {
	Definition PipelineDefinition `json:"definition"`
	// TTLSeconds is the preview lifetime, 1-600.
	TTLSeconds json.Number `json:"ttl_seconds,omitempty"`
}

PreviewPipelineRequest previews a pipeline for a limited time.

type PreviewPipelineResponse

type PreviewPipelineResponse struct {
	PipelineName string      `json:"pipeline_name"`
	TTLSeconds   json.Number `json:"ttl_seconds"`
	ExpiresAt    time.Time   `json:"expires_at"`
}

PreviewPipelineResponse is the result of a preview request.

type ProblemDetails

type ProblemDetails struct {
	// Type is the stable problem identifier URI, e.g.
	// "https://api.goldsky.com/api/errors/subgraph-not-found". When the server
	// omits it, this is "about:blank" per RFC 9457.
	Type string `json:"type,omitempty"`
	// Title is a short, human-readable summary. Not stable; do not branch on it.
	Title string `json:"title,omitempty"`
	// Status is the authoritative HTTP response status code.
	Status int `json:"status,omitempty"`
	// Detail is a human-readable explanation specific to this occurrence.
	Detail string `json:"detail,omitempty"`
	// Instance is the URI identifying the specific occurrence, often the path.
	Instance string `json:"instance,omitempty"`
	// Errors is the validation field-error list present on 400 responses.
	Errors []ValidationError `json:"errors,omitempty"`

	// Headers are the response headers, useful for Retry-After and rate-limit
	// metadata. They never contain the request Authorization value.
	Headers http.Header `json:"-"`
	// RawBody is the raw response body retained for diagnostics. Problem
	// bodies do not carry secrets, but callers should still avoid logging it
	// verbatim in shared systems.
	RawBody []byte `json:"-"`
}

ProblemDetails is an RFC 9457 (https://www.rfc-editor.org/rfc/rfc9457) application/problem+json failure returned by the Goldsky REST control plane.

Callers must branch on Type (a stable URI) rather than Title or Detail, which are human-readable prose and may change. Every Type dereferences to a page in the Goldsky error catalogue at https://api.goldsky.com/api/errors.

func AsProblem

func AsProblem(err error) *ProblemDetails

AsProblem returns the *ProblemDetails if err is (or wraps) one, else nil.

func (*ProblemDetails) Error

func (e *ProblemDetails) Error() string

Error implements the error interface. The message never includes request credentials; problem bodies are server-authored and do not echo secrets.

func (*ProblemDetails) Is

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

Is supports errors.Is comparisons against sentinel problem types.

func (*ProblemDetails) IsAuthentication

func (e *ProblemDetails) IsAuthentication() bool

IsAuthentication reports a 401 authentication failure.

func (*ProblemDetails) IsConflict

func (e *ProblemDetails) IsConflict() bool

IsConflict reports a 409 conflict failure.

func (*ProblemDetails) IsNotFound

func (e *ProblemDetails) IsNotFound() bool

IsNotFound reports a 404 not-found failure.

func (*ProblemDetails) IsPermission

func (e *ProblemDetails) IsPermission() bool

IsPermission reports a 403 permission or limit failure.

func (*ProblemDetails) IsRateLimited

func (e *ProblemDetails) IsRateLimited() bool

IsRateLimited reports a 429 rate-limited failure. Inspect RetryAfter for the server-recommended wait.

func (*ProblemDetails) IsServerError

func (e *ProblemDetails) IsServerError() bool

IsServerError reports a 5xx server failure.

func (*ProblemDetails) IsSubscription

func (e *ProblemDetails) IsSubscription() bool

IsSubscription reports a 402 subscription/billing failure.

func (*ProblemDetails) IsUnprocessable

func (e *ProblemDetails) IsUnprocessable() bool

IsUnprocessable reports a 422 unprocessable-entity failure (e.g. deleting a deployment still referenced by a tag, pipeline, or webhook).

func (*ProblemDetails) IsValidation

func (e *ProblemDetails) IsValidation() bool

IsValidation reports a 400 validation failure.

func (*ProblemDetails) RetryAfter

func (e *ProblemDetails) RetryAfter() (seconds int, ok bool)

RetryAfter returns the server-recommended wait from the Retry-After header, or zero if absent or unparseable.

type RPCBatchCall

type RPCBatchCall struct {
	Method string
	Params any
	Result any
}

RPCBatchCall is a single call within a batch. If Result is non-nil, the decoded result is written into it; use a *json.RawMessage to keep the raw result bytes.

type RPCError

type RPCError struct {
	Code    int             `json:"code"`
	Message string          `json:"message"`
	Data    json.RawMessage `json:"data,omitempty"`
}

RPCError is a JSON-RPC 2.0 error object.

func (*RPCError) Error

func (e *RPCError) Error() string

Error implements the error interface.

type RPCResponse

type RPCResponse struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      int64           `json:"id"`
	Result  json.RawMessage `json:"result,omitempty"`
	Error   *RPCError       `json:"error,omitempty"`
}

RPCResponse is a JSON-RPC 2.0 response.

type RPCService

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

RPCService calls the Edge HTTPS JSON-RPC data plane.

The Edge endpoint URL is

https://edge.goldsky.com/standard/evm/{chainId}

The Edge API key is a separate secret from the REST project Bearer token and is sent in X-ERPC-Secret-Token; it is never logged or included in error messages. Goldsky documents HTTPS only; there is no WebSocket/subscription support.

func (*RPCService) Batch

func (s *RPCService) Batch(ctx context.Context, chainID int64, calls []RPCBatchCall) ([]RPCResponse, error)

Batch performs a JSON-RPC batch call. Each call's Result pointer, when non-nil, is filled with the decoded result. The returned responses are matched to the calls by index. A non-nil error indicates a transport or decode failure; individual JSON-RPC errors are available on each response.

func (*RPCService) Call

func (s *RPCService) Call(ctx context.Context, chainID int64, method string, params any, result any) error

Call performs a single JSON-RPC call. If result is non-nil, the decoded result is written into it; pass a *json.RawMessage to keep raw bytes. A non-nil *RPCError is returned when the server reports a JSON-RPC error.

func (*RPCService) EndpointURL

func (s *RPCService) EndpointURL(chainID int64) string

EndpointURL builds the Edge RPC URL for the given chain ID. Authentication is added separately as a header, so this URL never contains the Edge secret.

type RestartPipelineRequest

type RestartPipelineRequest struct {
	ClearState bool `json:"clearState,omitempty"`
}

RestartPipelineRequest optionally clears pipeline state on restart.

type RetryPolicy

type RetryPolicy struct {
	// MaxAttempts is the total number of attempts including the first. A value
	// of 1 disables retry. Zero means use the default.
	MaxAttempts int
	// InitialBackoff is the first backoff delay. Zero means use the default.
	InitialBackoff time.Duration
	// MaxBackoff caps the backoff delay. Zero means use the default.
	MaxBackoff time.Duration
	// RetryMutations, when true, also retries non-safe methods. This is opt-in
	// and unsafe because mutations are not documented as idempotent.
	RetryMutations bool
}

RetryPolicy controls automatic retry of failed requests.

By default only safe reads (GET, HEAD, OPTIONS) are retried on transport errors and the status codes 429, 500, 502, 503, and 504, using capped exponential backoff with jitter and honouring Retry-After. Mutations are not retried automatically because Goldsky does not document idempotency keys; set RetryMutations to opt in to unsafe mutation retry.

func DefaultRetryPolicy

func DefaultRetryPolicy() RetryPolicy

DefaultRetryPolicy returns the default retry policy: up to 3 attempts, 500 ms initial backoff, 30 s max backoff, no mutation retry.

type RevealEdgeKeyResponse

type RevealEdgeKeyResponse struct {
	Data struct {
		APIKey string `json:"api_key"`
	} `json:"data"`
}

RevealEdgeKeyResponse reveals an Edge endpoint API key.

type SetSubgraphTagRequest

type SetSubgraphTagRequest struct {
	TargetVersion string `json:"target_version"`
}

SetSubgraphTagRequest points a tag at a target version.

type Sleeper added in v1.1.2

type Sleeper interface {
	Sleep(context.Context, time.Duration) error
}

Sleeper waits between retry attempts while respecting cancellation. Most callers should use the context-aware system sleeper configured by default.

type Subgraph

type Subgraph struct {
	Name                   string               `json:"name"`
	Version                string               `json:"version"`
	Tag                    *SubgraphTag         `json:"tag,omitempty"`
	Status                 SubgraphStatus       `json:"status"`
	Network                string               `json:"network"`
	Health                 SubgraphHealth       `json:"health"`
	Synced                 bool                 `json:"synced"`
	GraphQLEndpoint        string               `json:"graphql_endpoint"`
	PrivateGraphQLEndpoint string               `json:"private_graphql_endpoint"`
	PublicEndpointEnabled  bool                 `json:"public_endpoint_enabled"`
	PrivateEndpointEnabled bool                 `json:"private_endpoint_enabled"`
	Description            *string              `json:"description"`
	Deployments            []SubgraphDeployment `json:"deployments"`
}

Subgraph is a subgraph version with its deployments and optional tag.

type SubgraphChainsResponse

type SubgraphChainsResponse struct {
	Data struct {
		SupportedChains []string `json:"supported_chains"`
	} `json:"data"`
}

SubgraphChainsResponse lists supported deployment chains.

type SubgraphDeployment

type SubgraphDeployment struct {
	DeploymentID     string            `json:"deployment_id"`
	CreatedAt        time.Time         `json:"created_at"`
	Health           SubgraphHealth    `json:"health"`
	Synced           bool              `json:"synced"`
	FatalError       *string           `json:"fatal_error"`
	NonFatalErrors   []string          `json:"non_fatal_errors"`
	IndexingProgress *IndexingProgress `json:"indexing_progress,omitempty"`
}

SubgraphDeployment is a single deployment of a subgraph version.

type SubgraphHealth

type SubgraphHealth string

SubgraphHealth is the indexing health of a subgraph deployment.

const (
	SubgraphHealthHealthy   SubgraphHealth = "HEALTHY"
	SubgraphHealthUnhealthy SubgraphHealth = "UNHEALTHY"
	SubgraphHealthFailed    SubgraphHealth = "FAILED"
	SubgraphHealthUnknown   SubgraphHealth = "UNKNOWN"
)

Known subgraph indexing health values.

type SubgraphLogsOptions

type SubgraphLogsOptions struct {
	Cursor    *float64
	After     *float64
	Direction string
	Search    string
	LogLevel  string
	LogLevels string
}

SubgraphLogsOptions filters subgraph indexing logs.

type SubgraphLogsResponse

type SubgraphLogsResponse struct {
	Data LogResults `json:"data"`
}

SubgraphLogsResponse is the subgraph logs endpoint envelope.

type SubgraphPager

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

SubgraphPager iterates subgraph pages, cancellation-aware.

func (*SubgraphPager) NextPage

func (p *SubgraphPager) NextPage(ctx context.Context) (Page[Subgraph], error)

NextPage fetches the next page.

type SubgraphService

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

SubgraphService manages Subgraphs and their versions, tags, and deployments.

func (*SubgraphService) DeleteDeployment

func (s *SubgraphService) DeleteDeployment(ctx context.Context, name, version string) error

DeleteDeployment deletes a deployment. This fails with HTTP 422 while the deployment is referenced by a tag, pipeline, or webhook. See https://api.goldsky.com/api/v1/docs#tag/Subgraph%20Deployments/operation/deleteSubgraphDeployment

func (*SubgraphService) DeleteTag

func (s *SubgraphService) DeleteTag(ctx context.Context, name, version string) error

DeleteTag deletes a tag. See https://api.goldsky.com/api/v1/docs#tag/Subgraph%20Tags/operation/deleteSubgraphTag

func (*SubgraphService) Deploy

func (s *SubgraphService) Deploy(ctx context.Context, name, version string, opts DeploySubgraphOptions) (Subgraph, error)

Deploy deploys a compiled subgraph bundle as streaming multipart/form-data. See https://api.goldsky.com/api/v1/docs#tag/Subgraph%20Deployments/operation/deploySubgraph

func (*SubgraphService) Get

func (s *SubgraphService) Get(ctx context.Context, name string) (Page[Subgraph], error)

Get fetches a subgraph with its versions and tags. See https://api.goldsky.com/api/v1/docs#tag/Subgraphs/operation/getSubgraph

func (*SubgraphService) GetVersion

func (s *SubgraphService) GetVersion(ctx context.Context, name, version string) (Page[Subgraph], error)

GetVersion fetches a subgraph tag or deployed version. See https://api.goldsky.com/api/v1/docs#tag/Subgraphs/operation/getSubgraphVersion

func (*SubgraphService) List

List lists a single page of subgraphs. See https://api.goldsky.com/api/v1/docs#tag/Subgraphs/operation/listSubgraphs

func (*SubgraphService) Logs

Logs fetches a page of subgraph indexing logs. See https://api.goldsky.com/api/v1/docs#tag/Subgraph%20Logs/operation/getSubgraphLogs

func (*SubgraphService) NewSubgraphPager

func (s *SubgraphService) NewSubgraphPager(opts ListSubgraphsOptions) *SubgraphPager

NewSubgraphPager returns a pager over subgraphs starting at opts.PageToken.

func (*SubgraphService) Pause

func (s *SubgraphService) Pause(ctx context.Context, name, version string) error

Pause pauses a deployed subgraph version. Pause/resume targets a deployed version, not a moving tag. See https://api.goldsky.com/api/v1/docs#tag/Subgraph%20Lifecycle/operation/pauseSubgraph

func (*SubgraphService) Resume

func (s *SubgraphService) Resume(ctx context.Context, name, version string) error

Resume resumes a paused deployed subgraph version. See https://api.goldsky.com/api/v1/docs#tag/Subgraph%20Lifecycle/operation/resumeSubgraph

func (*SubgraphService) SetTag

func (s *SubgraphService) SetTag(ctx context.Context, name, version string, req SetSubgraphTagRequest) (Subgraph, error)

SetTag creates or moves a tag to a target version. See https://api.goldsky.com/api/v1/docs#tag/Subgraph%20Tags/operation/setSubgraphTag

func (*SubgraphService) SupportedChains

func (s *SubgraphService) SupportedChains(ctx context.Context) (SubgraphChainsResponse, error)

SupportedChains lists supported deployment chains. See https://api.goldsky.com/api/v1/docs#tag/Catalogs/operation/listSubgraphChains

func (*SubgraphService) UpdateVersion

func (s *SubgraphService) UpdateVersion(ctx context.Context, name, version string, req UpdateSubgraphVersionRequest) (Subgraph, error)

UpdateVersion updates endpoint settings on a version or tag. See https://api.goldsky.com/api/v1/docs#tag/Subgraph%20Lifecycle/operation/updateSubgraphVersion

func (*SubgraphService) WebhookEntities

func (s *SubgraphService) WebhookEntities(ctx context.Context, name, version string) (WebhookEntitiesResponse, error)

WebhookEntities lists webhook-able entities for a subgraph version. See https://api.goldsky.com/api/v1/docs#tag/Subgraph%20Webhooks/operation/listWebhookEntities

type SubgraphStatus

type SubgraphStatus string

SubgraphStatus is the lifecycle state of a deployed subgraph version.

const (
	SubgraphStatusActive SubgraphStatus = "ACTIVE"
	SubgraphStatusPaused SubgraphStatus = "PAUSED"
)

Known subgraph lifecycle states.

type SubgraphTag

type SubgraphTag struct {
	TargetVersion string `json:"target_version"`
}

SubgraphTag points a tag at a target version.

type TransportError

type TransportError struct {
	// Op is a short label for the failing operation.
	Op string
	// StatusCode is the HTTP status, or zero for a network failure.
	StatusCode int
	// Err is the underlying error.
	Err error
}

TransportError describes a failure below the API contract, such as a network error or a malformed successful response. It never includes the request Authorization header or the Edge API key.

func AsTransport

func AsTransport(err error) *TransportError

AsTransport returns the *TransportError if err is (or wraps) one, else nil.

func (*TransportError) Error

func (e *TransportError) Error() string

Error implements the error interface.

func (*TransportError) Unwrap

func (e *TransportError) Unwrap() error

Unwrap returns the underlying error.

type UpdateEdgeEndpointRequest

type UpdateEdgeEndpointRequest struct {
	RateLimitBudget *EdgeRateLimitBudget `json:"rate_limit_budget,omitempty"`
	AllowedDomains  []string             `json:"allowed_domains,omitempty"`
	// ClearRateLimitBudget sends an explicit JSON null. It is mutually
	// exclusive with RateLimitBudget.
	ClearRateLimitBudget bool `json:"-"`
}

UpdateEdgeEndpointRequest updates an Edge endpoint. Domain changes are applied before rate-limit changes and the update is not transactional.

func (UpdateEdgeEndpointRequest) MarshalJSON added in v1.1.3

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

MarshalJSON preserves a non-nil empty AllowedDomains slice so callers can clear the allowlist, and supports the API's explicit null budget reset.

type UpdateSubgraphVersionRequest

type UpdateSubgraphVersionRequest struct {
	PublicEndpointEnabled  *bool   `json:"public_endpoint_enabled,omitempty"`
	PrivateEndpointEnabled *bool   `json:"private_endpoint_enabled,omitempty"`
	Description            *string `json:"description,omitempty"`
}

UpdateSubgraphVersionRequest updates endpoint settings on a version/tag.

type ValidatePipelineRequest

type ValidatePipelineRequest struct {
	Name           string             `json:"name,omitempty"`
	ResourceSize   string             `json:"resource_size,omitempty"`
	Description    string             `json:"description,omitempty"`
	UseDedicatedIP *bool              `json:"use_dedicated_ip,omitempty"`
	Definition     PipelineDefinition `json:"definition"`
}

ValidatePipelineRequest validates a pipeline definition without creating it.

type ValidatePipelineResponse

type ValidatePipelineResponse struct {
	Valid    bool                `json:"valid"`
	Errors   []ValidationMessage `json:"errors"`
	Warnings []ValidationMessage `json:"warnings"`
}

ValidatePipelineResponse is the result of pipeline validation.

type ValidationError

type ValidationError struct {
	Field   string `json:"field,omitempty"`
	Message string `json:"message"`
}

ValidationError names a single offending field in a 400 validation response.

type ValidationMessage

type ValidationMessage struct {
	Field   string `json:"field,omitempty"`
	Message string `json:"message"`
}

ValidationMessage names a single validation finding.

type Webhook

type Webhook struct {
	ID              string    `json:"id"`
	Name            string    `json:"name"`
	WebhookURL      string    `json:"webhook_url"`
	Entity          string    `json:"entity"`
	SubgraphName    string    `json:"subgraph_name"`
	SubgraphVersion string    `json:"subgraph_version"`
	CreatedAt       time.Time `json:"created_at"`
}

Webhook is a Subgraph entity webhook. The delivery secret is returned only at create time and is not present in list responses.

type WebhookEntitiesResponse

type WebhookEntitiesResponse struct {
	Data struct {
		Entities []WebhookEntity `json:"entities"`
	} `json:"data"`
}

WebhookEntitiesResponse lists webhook-able entities for a subgraph version.

type WebhookEntity

type WebhookEntity struct {
	Name    string                `json:"name"`
	Rows    string                `json:"rows"`
	Columns []WebhookEntityColumn `json:"columns"`
}

WebhookEntity is a subgraph entity (table) available for webhooks.

type WebhookEntityColumn

type WebhookEntityColumn struct {
	Name     string `json:"name"`
	DataType string `json:"data_type"`
}

WebhookEntityColumn describes a column of a webhook-able entity.

type WebhookListResponse

type WebhookListResponse struct {
	Data []Webhook `json:"data"`
}

WebhookListResponse lists project webhooks.

type WebhookService

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

WebhookService manages Subgraph entity webhooks.

func (*WebhookService) Create

Create creates an entity webhook and returns the one-time delivery secret. See https://api.goldsky.com/api/v1/docs#tag/Subgraph%20Webhooks/operation/createWebhook

func (*WebhookService) Delete

func (s *WebhookService) Delete(ctx context.Context, name string) error

Delete deletes a webhook by name. See https://api.goldsky.com/api/v1/docs#tag/Subgraph%20Webhooks/operation/deleteWebhook

Directories

Path Synopsis
examples
01-list-pipelines command
Example: construct a client and list one page of pipelines.
Example: construct a client and list one page of pipelines.
02-paginate-subgraphs command
Example: walk all subgraph pages with the cancellation-aware pager.
Example: walk all subgraph pages with the cancellation-aware pager.
03-validate-pipeline command
Example: validate a pipeline definition without creating it.
Example: validate a pipeline definition without creating it.
04-create-pipeline command
Example: create a pipeline.
Example: create a pipeline.
05-graphql-query command
Example: query a private Subgraph GraphQL endpoint.
Example: query a private Subgraph GraphQL endpoint.
06-edge-rpc command
Example: call eth_blockNumber over the Edge HTTPS JSON-RPC data plane.
Example: call eth_blockNumber over the Edge HTTPS JSON-RPC data plane.
07-verify-webhook command
Example: verify a goldsky-webhook-secret header in constant time.
Example: verify a goldsky-webhook-secret header in constant time.
08-handle-errors command
Example: distinguish API failures from network and decoding failures.
Example: distinguish API failures from network and decoding failures.
09-batch-edge-rpc command
Example: fetch the chain ID and latest block in one Edge RPC batch.
Example: fetch the chain ID and latest block in one Edge RPC batch.
internal
clock
Package clock provides injectable time and sleeping primitives so that retry and backoff behavior can be made deterministic in tests without real delays.
Package clock provides injectable time and sleeping primitives so that retry and backoff behavior can be made deterministic in tests without real delays.
multipart
Package multipart builds streaming multipart/form-data request bodies for subgraph deployment without buffering the entire bundle in memory.
Package multipart builds streaming multipart/form-data request bodies for subgraph deployment without buffering the entire bundle in memory.

Jump to

Keyboard shortcuts

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