gcp

package
v0.1.98 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2026 License: Apache-2.0 Imports: 20 Imported by: 1 module, 0 packages

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

Documentation

Overview

Package gcp holds thin typed REST clients for the Google Cloud APIs commons-db uses. They are built on commons/http with bearer-token authentication, expose only the operations and fields commons-db reads, and replace the generated cloud.google.com/go and google.golang.org/api client libraries.

Index

Constants

View Source
const (
	ScopeCloudPlatform  = "https://www.googleapis.com/auth/cloud-platform"
	ScopeDevStorageFull = "https://www.googleapis.com/auth/devstorage.full_control"
	ScopeBigQuery       = "https://www.googleapis.com/auth/bigquery"
	ScopeLoggingRead    = "https://www.googleapis.com/auth/logging.read"
	ScopeKMS            = "https://www.googleapis.com/auth/cloudkms"
	ScopePubSub         = "https://www.googleapis.com/auth/pubsub"
	ScopeSQLAdmin       = "https://www.googleapis.com/auth/sqlservice.admin"
	ScopeSQLLogin       = "https://www.googleapis.com/auth/sqlservice.login"
)

Scopes the clients in this package request.

View Source
const (

	// StorageEmulatorHostEnv is honoured when no endpoint is configured, matching
	// the convention used by the Google Cloud Storage client libraries.
	StorageEmulatorHostEnv = "STORAGE_EMULATOR_HOST"

	// DefaultUploadChunkSize is how much of a streamed upload is held in memory
	// at once.
	DefaultUploadChunkSize = 8 << 20
)
View Source
const (

	// PubSubEmulatorHostEnv is honoured when no endpoint is configured, matching
	// the convention used by the Google Cloud Pub/Sub client libraries.
	PubSubEmulatorHostEnv = "PUBSUB_EMULATOR_HOST"
)

Variables

This section is empty.

Functions

func CredentialsTokenSource

func CredentialsTokenSource(ctx context.Context, credentialsJSON []byte, scopes ...string) (oauth2.TokenSource, error)

CredentialsTokenSource returns a token source for a service-account (or authorized-user) JSON credential. The source outlives ctx's cancellation: token refreshes happen long after the call that created it returned.

func DefaultTokenSource

func DefaultTokenSource(ctx context.Context, scopes ...string) (oauth2.TokenSource, error)

DefaultTokenSource returns a token source from the ambient application default credentials (GOOGLE_APPLICATION_CREDENTIALS, gcloud, metadata server).

func IsNotFound

func IsNotFound(err error) bool

IsNotFound reports whether err is a Google API 404.

Types

type APIError

type APIError struct {
	StatusCode int
	Code       int
	Status     string
	Message    string
	Reason     string
}

APIError is a Google API error response, parsed from the JSON error envelope {"error": {"code": ..., "message": ..., "status": ..., "errors": [{"reason": ...}]}}.

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) Is

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

Is lets a 404 match fs.ErrNotExist so filesystem callers need no GCP types.

type BigQueryClient

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

BigQueryClient talks to the BigQuery REST API.

func NewBigQueryClient

func NewBigQueryClient(opts Options) (*BigQueryClient, error)

NewBigQueryClient builds a BigQuery client. An Endpoint may carry the /bigquery/v2 path, as emulator endpoints usually do.

func (*BigQueryClient) Query

Query runs the SQL, waits for the job to finish and reads every result page.

type BigQueryField

type BigQueryField struct {
	Name string `json:"name"`
	// Type is the BigQuery type name, e.g. STRING, INTEGER, RECORD.
	Type string `json:"type"`
	// Mode is NULLABLE, REQUIRED or REPEATED.
	Mode string `json:"mode"`
	// Fields are the sub-fields of a RECORD.
	Fields []*BigQueryField `json:"fields,omitempty"`
}

BigQueryField is one column of a result schema.

type BigQuerySchema

type BigQuerySchema []*BigQueryField

BigQuerySchema is the ordered column list of a result set.

type Cluster

type Cluster struct {
	// Endpoint is the cluster's control-plane IP address.
	Endpoint   string `json:"endpoint"`
	MasterAuth struct {
		// ClusterCaCertificate is the base64-encoded PEM cluster CA.
		ClusterCaCertificate string `json:"clusterCaCertificate"`
	} `json:"masterAuth"`
}

Cluster is the subset of a GKE cluster commons-db reads.

type ClusterRef

type ClusterRef struct {
	Project  string
	Location string
	Cluster  string
}

ClusterRef names a GKE cluster; Location is a zone or region.

type ConnectSettings

type ConnectSettings struct {
	Region          string `json:"region"`
	BackendType     string `json:"backendType"`
	DatabaseVersion string `json:"databaseVersion"`
	ServerCaMode    string `json:"serverCaMode"`
	ServerCaCert    *struct {
		// Cert is the PEM-encoded server CA chain.
		Cert string `json:"cert"`
	} `json:"serverCaCert"`
	IPAddresses []struct {
		// Type is PRIMARY (public), PRIVATE or OUTGOING.
		Type      string `json:"type"`
		IPAddress string `json:"ipAddress"`
	} `json:"ipAddresses"`
	PscEnabled bool   `json:"pscEnabled"`
	DNSName    string `json:"dnsName"`
	DNSNames   []struct {
		Name           string `json:"name"`
		ConnectionType string `json:"connectionType"`
		DNSScope       string `json:"dnsScope"`
	} `json:"dnsNames"`
}

ConnectSettings is the subset of connectSettings the dialer reads.

type ContainerClient

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

ContainerClient talks to the Kubernetes Engine (GKE) REST API.

func NewContainerClient

func NewContainerClient(opts Options) (*ContainerClient, error)

NewContainerClient builds a GKE client.

func (*ContainerClient) GetCluster

func (c *ContainerClient) GetCluster(ctx context.Context, ref ClusterRef) (*Cluster, error)

GetCluster fetches a cluster.

type EntriesPage

type EntriesPage struct {
	Entries       []*LogEntry `json:"entries"`
	NextPageToken string      `json:"nextPageToken"`
}

EntriesPage is one page of log entries.

type EphemeralCert

type EphemeralCert struct {
	// CertPEM is the PEM-encoded client certificate.
	CertPEM    string
	Expiration time.Time
}

EphemeralCert is an issued client certificate.

type EphemeralCertRequest

type EphemeralCertRequest struct {
	SQLInstanceRef
	// PublicKeyPEM is the PEM-encoded public key the certificate is issued for.
	PublicKeyPEM string
	// AccessToken, when set, is embedded in the certificate to authenticate an
	// IAM database user; it must carry the sqlservice.login scope.
	AccessToken string
}

EphemeralCertRequest asks for a short-lived client certificate.

type JobStatistics

type JobStatistics struct {
	CreationTime   time.Time
	StartTime      time.Time
	EndTime        time.Time
	BytesProcessed int64
	BytesBilled    int64
	SlotMillis     int64
}

JobStatistics are the execution statistics of a finished query job.

type KMSClient

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

KMSClient talks to the Cloud KMS REST API.

func NewKMSClient

func NewKMSClient(opts Options) (*KMSClient, error)

NewKMSClient builds a Cloud KMS client.

func (*KMSClient) Decrypt

func (k *KMSClient) Decrypt(ctx context.Context, keyName string, ciphertext []byte) ([]byte, error)

Decrypt decrypts ciphertext produced by Encrypt with the same key.

func (*KMSClient) Encrypt

func (k *KMSClient) Encrypt(ctx context.Context, keyName string, plaintext []byte) ([]byte, error)

Encrypt encrypts plaintext with the key resource name (projects/P/locations/L/keyRings/R/cryptoKeys/K).

type ListEntriesOptions

type ListEntriesOptions struct {
	// ResourceNames are the parents to read, e.g. "projects/my-project".
	ResourceNames []string
	Filter        string
	// OrderBy is "timestamp asc" or "timestamp desc".
	OrderBy   string
	PageSize  int
	PageToken string
}

ListEntriesOptions are the entries.list parameters commons-db uses.

type LogEntry

type LogEntry struct {
	LogName   string    `json:"logName"`
	InsertID  string    `json:"insertId"`
	Timestamp time.Time `json:"timestamp"`
	// Severity is the API enum name, e.g. "WARNING".
	Severity string `json:"severity"`
	Resource *struct {
		Type   string            `json:"type"`
		Labels map[string]string `json:"labels"`
	} `json:"resource"`
	Labels       map[string]string `json:"labels"`
	TextPayload  *string           `json:"textPayload"`
	JSONPayload  map[string]any    `json:"jsonPayload"`
	ProtoPayload map[string]any    `json:"protoPayload"`
}

LogEntry is the subset of a Cloud Logging entry commons-db reads.

func (*LogEntry) Payload

func (e *LogEntry) Payload() any

Payload returns the entry's payload: the text string, or the JSON/proto object. It is nil when the entry carries none.

func (*LogEntry) SeverityName

func (e *LogEntry) SeverityName() string

SeverityName returns the severity in title case ("Warning"), or "" for the unset DEFAULT severity.

type LoggingClient

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

LoggingClient talks to the Cloud Logging REST API.

func NewLoggingClient

func NewLoggingClient(opts Options) (*LoggingClient, error)

NewLoggingClient builds a Cloud Logging client.

func (*LoggingClient) EachEntry

func (l *LoggingClient) EachEntry(ctx context.Context, opts ListEntriesOptions, visit func(*LogEntry) (done bool, err error)) error

EachEntry calls visit for every entry, following pages, until visit returns done=true, an error, or the entries run out.

func (*LoggingClient) ListEntries

func (l *LoggingClient) ListEntries(ctx context.Context, opts ListEntriesOptions) (*EntriesPage, error)

ListEntries fetches one page of log entries.

type Object

type Object struct {
	Bucket      string
	Name        string
	ContentType string
	Size        int64
	Updated     time.Time
}

Object is the subset of Cloud Storage object metadata commons-db reads.

func (*Object) UnmarshalJSON

func (o *Object) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the API form, where size is a string-encoded int64.

type ObjectPage

type ObjectPage struct {
	Objects       []*Object
	NextPageToken string
}

ObjectPage is one page of an object listing.

type Options

type Options struct {
	// Endpoint overrides the service root URL (for example an emulator). The
	// service's version path is appended when the endpoint does not already end
	// with it.
	Endpoint string

	// TokenSource authenticates every request with a bearer token. A nil source
	// sends requests unauthenticated, which is what emulators expect.
	TokenSource oauth2.TokenSource

	// SkipTLSVerify disables server certificate verification.
	SkipTLSVerify bool
}

Options configures a service client.

type PubSubClient

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

PubSubClient talks to the Pub/Sub REST API for subscribers.

func NewPubSubClient

func NewPubSubClient(opts Options) (*PubSubClient, error)

NewPubSubClient builds a Pub/Sub client. With no Endpoint it uses PUBSUB_EMULATOR_HOST when set, else pubsub.googleapis.com.

func (*PubSubClient) Acknowledge

func (p *PubSubClient) Acknowledge(ctx context.Context, subscription string, ackIDs []string) error

Acknowledge acknowledges messages by ack ID.

func (*PubSubClient) ModifyAckDeadline

func (p *PubSubClient) ModifyAckDeadline(ctx context.Context, subscription string, ackIDs []string, deadline time.Duration) error

ModifyAckDeadline sets the ack deadline of messages; 0 nacks them.

func (*PubSubClient) Pull

Pull retrieves up to MaxMessages messages.

type PubSubMessage

type PubSubMessage struct {
	Data        []byte            `json:"data"`
	Attributes  map[string]string `json:"attributes"`
	MessageID   string            `json:"messageId"`
	PublishTime time.Time         `json:"publishTime"`
	OrderingKey string            `json:"orderingKey"`
}

PubSubMessage is a delivered message.

type PullOptions

type PullOptions struct {
	Subscription string
	MaxMessages  int
	// ReturnImmediately returns an empty response instead of waiting for messages.
	ReturnImmediately bool
}

PullOptions configures a pull. Subscription is the full resource name (projects/P/subscriptions/S).

type QueryRequest

type QueryRequest struct {
	Project string
	SQL     string
	// Location pins the job's location; empty lets BigQuery choose.
	Location string
}

QueryRequest is a standard-SQL query to run.

type QueryResult

type QueryResult struct {
	Schema BigQuerySchema
	// Rows hold decoded values: string, int64, float64, bool, time.Time ([]byte
	// for BYTES, *big.Rat for NUMERIC, []any for REPEATED and RECORD, nil for NULL).
	Rows      [][]any
	TotalRows int64
	Stats     *JobStatistics
}

QueryResult is a finished query: all result rows, decoded per the schema.

type ReceivedMessage

type ReceivedMessage struct {
	AckID           string        `json:"ackId"`
	Message         PubSubMessage `json:"message"`
	DeliveryAttempt int           `json:"deliveryAttempt"`
}

ReceivedMessage is a message with the ack ID used to acknowledge it.

type SQLAdminClient

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

SQLAdminClient talks to the Cloud SQL Admin REST API (v1beta4), which hands out the connection metadata and ephemeral client certificates the Cloud SQL dialer needs.

func NewSQLAdminClient

func NewSQLAdminClient(opts Options) (*SQLAdminClient, error)

NewSQLAdminClient builds a Cloud SQL Admin client.

func (*SQLAdminClient) GenerateEphemeralCert

func (s *SQLAdminClient) GenerateEphemeralCert(ctx context.Context, req EphemeralCertRequest) (*EphemeralCert, error)

GenerateEphemeralCert requests a client certificate for the supplied public key.

func (*SQLAdminClient) GetConnectSettings

func (s *SQLAdminClient) GetConnectSettings(ctx context.Context, ref SQLInstanceRef) (*ConnectSettings, error)

GetConnectSettings reads an instance's connection metadata.

type SQLInstanceRef

type SQLInstanceRef struct {
	Project  string
	Instance string
}

SQLInstanceRef names a Cloud SQL instance.

type StorageClient

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

StorageClient talks to the Cloud Storage JSON API.

func NewStorageClient

func NewStorageClient(opts Options) (*StorageClient, error)

NewStorageClient builds a Cloud Storage client. With no Endpoint it uses STORAGE_EMULATOR_HOST when set, else storage.googleapis.com. An endpoint may be the server root or carry the /storage/v1 path.

func (*StorageClient) DeleteObject

func (s *StorageClient) DeleteObject(ctx context.Context, bucket, name string) error

DeleteObject removes an object; a missing object is an error satisfying IsNotFound.

func (*StorageClient) GetObject

func (s *StorageClient) GetObject(ctx context.Context, bucket, name string) (*Object, error)

GetObject reads an object's metadata.

func (*StorageClient) ListObjects

func (s *StorageClient) ListObjects(ctx context.Context, bucket, prefix string) ([]*Object, error)

ListObjects lists every object whose name starts with prefix, following pages.

func (*StorageClient) ListObjectsPage

func (s *StorageClient) ListObjectsPage(ctx context.Context, bucket, prefix, pageToken string) (*ObjectPage, error)

ListObjectsPage lists one page of objects whose names start with prefix.

func (*StorageClient) OpenObject

func (s *StorageClient) OpenObject(ctx context.Context, bucket, name string) (io.ReadCloser, error)

OpenObject streams an object's content; the caller closes the reader.

func (*StorageClient) WriteObject

func (s *StorageClient) WriteObject(ctx context.Context, o WriteObjectOptions) (*Object, error)

WriteObject uploads Body. A body that fits one chunk is sent in a single request; anything longer, or of unknown length, is streamed through a resumable session one chunk at a time, so memory use stays at one chunk.

type WriteObjectOptions

type WriteObjectOptions struct {
	Bucket      string
	Name        string
	Body        io.Reader
	ContentType string
	// ChunkSize bounds memory use and must be a multiple of 256 KiB;
	// DefaultUploadChunkSize when zero.
	ChunkSize int
}

WriteObjectOptions describes an upload.

Jump to

Keyboard shortcuts

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