Documentation
¶
Overview ¶
OBJECTIVES: - Define the StorageClient interface to decouple storage operations from concrete GCP client implementations. - Implement defaultStorageClient to execute optimized GCS bucket attribute fetching and object listing.
CORE COMPONENTS & DATA FLOW: - StorageClient Interface: Defines BucketAttrs and ListObjects contracts. - defaultStorageClient Struct: Wraps concrete *storage.Client. - BucketAttrs(): Calls storage.Client.Bucket(name).Attrs(ctx). - ListObjects(): Applies ProjectionNoACL and SetAttrSelection([]string{"name"}), pre-allocates object slice, iterates GCS objects up to maxObjects.
Package gcsconntest provides a production-grade, reusable Go engine and CLI to verify Google Cloud Storage (GCS) connectivity, authentication, and object accessibility.
OBJECTIVES: - Encapsulate configuration parameters for GCS connection testing. - Perform input sanitization (path cleaning) and parameter defaulting. - Enforce mandatory validation rules before initiating network connections.
CORE COMPONENTS & DATA FLOW: - Config struct: Holds credential paths, raw credential bytes, ADC flags, project/bucket metadata, limits, and timeouts. - Config.Clean(): Sanitizes input paths via filepath.Clean and populates default limits/timeouts. - Config.Validate(): Evaluates mandatory parameter presence, returning ErrInvalidConfig on failure.
OBJECTIVES: - Define domain error variables and granular exit codes (0 to 5) for process orchestration. - Implement error classification logic to map standard Go errors, net.Error, and googleapi.Error to diagnostic exit codes.
CORE COMPONENTS & DATA FLOW: - Exit code constants (ExitSuccess, ExitUsageError, ExitAuthError, ExitNetworkError, ExitPermissionError, ExitApiError). - Sentinel error definitions (ErrInvalidConfig, ErrAuthFailed, ErrBucketAccess, ErrNetworkFailed, ErrApiError). - ClassifyError(err error) int: Inspects error tree using errors.Is and errors.As to return precise exit code.
OBJECTIVES: - Encapsulate execution results from GCS connection testing. - Provide JSON serialization support for structured logging and machine consumption.
CORE COMPONENTS & DATA FLOW: - Result struct: Holds target bucket name, bucket attributes (*storage.BucketAttrs), object names slice, and object count. - Result.ToJSON(): Converts Result into a formatted JSON string using json.MarshalIndent.
OBJECTIVES: - Implement core GCS connection verification logic for library consumers and CLI entry points. - Manage client lifecycle, authentication resolution (File, JSON Bytes, ADC), context timeouts, and error handling. - Expose interface-based TestConnectionWithStorageClient to support mock-driven testing.
CORE COMPONENTS & DATA FLOW: - NewClient(ctx, cfg): Resolves authentication options -> creates *storage.Client. - TestConnection(ctx, cfg): Validates config -> cleans parameters -> applies timeout context -> instantiates client -> executes test -> closes client. - TestConnectionWithClient(ctx, client, cfg): Wraps concrete *storage.Client into StorageClient interface. - TestConnectionWithStorageClient(ctx, client, cfg): Executes BucketAttrs and ListObjects operations -> aggregates into *Result.
Index ¶
Constants ¶
const ( ExitSuccess = 0 // Operational success ExitUsageError = 1 // Missing or invalid configuration / parameters ExitAuthError = 2 // Credentials file unreadable, malformed, or authentication failed ExitNetworkError = 3 // Network failure, DNS issue, or request context timeout ExitPermissionError = 4 // GCS 403 Forbidden or 404 Bucket Not Found ExitApiError = 5 // General GCS API or iterator failure )
Exit codes for CLI diagnostics and process orchestration.
const DefaultMaxObjects = 10
DefaultMaxObjects is the default limit for listed objects when not specified.
const DefaultTimeout = 30 * time.Second
DefaultTimeout is the default duration limit for GCS operations.
Variables ¶
var ( ErrInvalidConfig = errors.New("invalid configuration") ErrAuthFailed = errors.New("authentication failed") ErrBucketAccess = errors.New("bucket access denied or not found") ErrNetworkFailed = errors.New("network connectivity error") ErrApiError = errors.New("API operation error") )
Custom error types for programmatic classification.
Functions ¶
func ClassifyError ¶
ClassifyError inspects an error and returns the corresponding diagnostic exit code. DATA FLOW: Input error -> Context check -> Sentinel error check -> OS file error check -> net.Error check -> googleapi.Error status code check -> Exit Code Integer.
func NewClient ¶
NewClient initializes a storage.Client using credentials specified in Config. DATA FLOW: Config -> SecretProtector Key Resolution (optional) -> Credential Mode Resolution (CredJSON / CredFile / AllowADC) -> Decryption (optional) -> Memory Zeroing -> storage.NewClient -> *storage.Client / Error.
Types ¶
type Config ¶
type Config struct {
// CredFile is the path to the Google Cloud service account JSON key file.
CredFile string
// CredJSON is raw service account JSON key content. If provided, CredFile is ignored.
CredJSON []byte
// AllowADC allows falling back to GCP Application Default Credentials if CredFile/CredJSON are omitted.
AllowADC bool
// BucketName is the target GCS bucket name (required).
BucketName string
// BucketPrefix is an optional prefix filter for object listing.
BucketPrefix string
// ProjectID is the Google Cloud Project ID (required).
ProjectID string
// MaxObjects limits the number of objects to list. Defaults to 10 if <= 0.
MaxObjects int
// Timeout specifies the maximum time allowed for the connection test. Defaults to 30s if <= 0.
Timeout time.Duration
// MasterKey is an optional raw/hex SecretProtector master key used to decrypt CredFile or CredJSON.
MasterKey string
// MasterKeyEnv is the name of an environment variable containing the SecretProtector master key.
MasterKeyEnv string
// MasterKeyFile is the file path containing the SecretProtector master key.
MasterKeyFile string
}
Config holds the parameters for GCS connection testing.
type Result ¶
type Result struct {
// BucketName is the target bucket tested.
BucketName string `json:"bucket_name"`
// BucketAttrs contains metadata retrieved for the bucket.
BucketAttrs *storage.BucketAttrs `json:"bucket_attrs,omitempty"`
// ObjectNames contains names of objects found (up to MaxObjects).
ObjectNames []string `json:"object_names"`
// TotalListed is the count of objects listed in this execution.
TotalListed int `json:"total_listed"`
}
Result contains details returned from a GCS connection test.
func TestConnection ¶
TestConnection tests connectivity to GCS by validating configuration, applying timeouts, instantiating a client, fetching bucket attributes, and listing objects. DATA FLOW: Context + Config -> Validation & Cleaning -> Timeout Context Creation -> Client Initialization -> Test Execution -> Resource Cleanup -> *Result.
func TestConnectionWithClient ¶
func TestConnectionWithClient(ctx context.Context, client *storage.Client, cfg Config) (*Result, error)
TestConnectionWithClient runs the connectivity test using a caller-provided storage.Client. DATA FLOW: Context + *storage.Client + Config -> StorageClient Interface Wrapper -> TestConnectionWithStorageClient.
func TestConnectionWithStorageClient ¶
func TestConnectionWithStorageClient(ctx context.Context, client StorageClient, cfg Config) (*Result, error)
TestConnectionWithStorageClient runs the connectivity test using a StorageClient interface (enables full offline mocking). DATA FLOW: Context + StorageClient + Config -> BucketAttrs() -> ListObjects() -> Aggregated *Result / Error.
type StorageClient ¶
type StorageClient interface {
BucketAttrs(ctx context.Context, bucketName string) (*storage.BucketAttrs, error)
ListObjects(ctx context.Context, bucketName, prefix string, maxObjects int) ([]string, error)
}
StorageClient abstracts GCS bucket attribute and object listing operations to enable unit testing and mocking without live network requests.
func NewStorageClient ¶
func NewStorageClient(client *storage.Client) StorageClient
NewStorageClient creates a StorageClient interface wrapper around *storage.Client. DATA FLOW: *storage.Client -> StorageClient Interface Wrapper.
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
gcsconntest
command
OBJECTIVES: - Standalone CLI application entry point for Google Cloud Storage connectivity testing.
|
OBJECTIVES: - Standalone CLI application entry point for Google Cloud Storage connectivity testing. |