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
- func CredentialsTokenSource(ctx context.Context, credentialsJSON []byte, scopes ...string) (oauth2.TokenSource, error)
- func DefaultTokenSource(ctx context.Context, scopes ...string) (oauth2.TokenSource, error)
- func IsNotFound(err error) bool
- type APIError
- type BigQueryClient
- type BigQueryField
- type BigQuerySchema
- type Cluster
- type ClusterRef
- type ConnectSettings
- type ContainerClient
- type EntriesPage
- type EphemeralCert
- type EphemeralCertRequest
- type JobStatistics
- type KMSClient
- type ListEntriesOptions
- type LogEntry
- type LoggingClient
- type Object
- type ObjectPage
- type Options
- type PubSubClient
- func (p *PubSubClient) Acknowledge(ctx context.Context, subscription string, ackIDs []string) error
- func (p *PubSubClient) ModifyAckDeadline(ctx context.Context, subscription string, ackIDs []string, ...) error
- func (p *PubSubClient) Pull(ctx context.Context, o PullOptions) ([]ReceivedMessage, error)
- type PubSubMessage
- type PullOptions
- type QueryRequest
- type QueryResult
- type ReceivedMessage
- type SQLAdminClient
- type SQLInstanceRef
- type StorageClient
- func (s *StorageClient) DeleteObject(ctx context.Context, bucket, name string) error
- func (s *StorageClient) GetObject(ctx context.Context, bucket, name string) (*Object, error)
- func (s *StorageClient) ListObjects(ctx context.Context, bucket, prefix string) ([]*Object, error)
- func (s *StorageClient) ListObjectsPage(ctx context.Context, bucket, prefix, pageToken string) (*ObjectPage, error)
- func (s *StorageClient) OpenObject(ctx context.Context, bucket, name string) (io.ReadCloser, error)
- func (s *StorageClient) WriteObject(ctx context.Context, o WriteObjectOptions) (*Object, error)
- type WriteObjectOptions
Constants ¶
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.
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 )
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 ¶
DefaultTokenSource returns a token source from the ambient application default credentials (GOOGLE_APPLICATION_CREDENTIALS, gcloud, metadata server).
func IsNotFound ¶
IsNotFound reports whether err is a Google API 404.
Types ¶
type APIError ¶
APIError is a Google API error response, parsed from the JSON error envelope {"error": {"code": ..., "message": ..., "status": ..., "errors": [{"reason": ...}]}}.
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 ¶
func (b *BigQueryClient) Query(ctx context.Context, req QueryRequest) (*QueryResult, error)
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 ¶
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 ¶
NewKMSClient builds a Cloud KMS client.
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 ¶
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 ¶
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 ¶
Object is the subset of Cloud Storage object metadata commons-db reads.
func (*Object) UnmarshalJSON ¶
UnmarshalJSON decodes the API form, where size is a string-encoded int64.
type ObjectPage ¶
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 ¶
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 ¶
func (p *PubSubClient) Pull(ctx context.Context, o PullOptions) ([]ReceivedMessage, error)
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 ¶
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) ListObjects ¶
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.