s3

package module
v0.0.0-...-df32a63 Latest Latest
Warning

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

Go to latest
Published: Jul 16, 2026 License: MIT Imports: 28 Imported by: 0

README

🗂️ s3 — S3-compatible storage for Starlark

Go Reference license codecov binary footprint

Universal S3-compatible storage operations for Starlark scripts. Built on the AWS SDK for Go v2, the module works with Amazon S3, MinIO, DigitalOcean Spaces, Cloudflare R2, Wasabi, Backblaze B2, and other S3-compatible services, with smart provider auto-detection from endpoints, regions, and credentials.

Overview

Within the starpkg philosophy — support for necessary local operations plus simple abstractions over common online services, for ease of uses3 is an online-service abstraction: it puts a small, uniform Starlark surface over a family of remote object stores. It also touches the local filesystem at two points (put_object_file reads a local file to upload, get_object_file writes a downloaded object to a local file), so it straddles the line, but its centre of gravity is the online service.

  • One client, many providerscreate_client builds a client for Amazon S3, MinIO, DigitalOcean Spaces, Cloudflare R2, Wasabi, Backblaze B2, and more, with smart auto-detection from the endpoint, region, or credentials.
  • Buckets and objects — create / delete / list / inspect buckets; put / get / copy / delete / list objects, with metadata, tags, and content headers.
  • Local-file helpersput_object_file / get_object_file upload from and download to the local filesystem, confined to the host-only file_root (a script can't read or write arbitrary host files; see Configuration).
  • URLs — public URLs from the client's config (get_public_url) and temporary pre-signed URLs (presign_url).
  • Credentials are host-injected, never script-passed — a script chooses the provider / region / endpoint but never sees secret keys.

For the complete per-builtin reference — signatures, parameters, returns, errors, examples — and the configuration accessors, see docs/API.md.

Installation

go get github.com/starpkg/s3

Quickstart

load("s3", "create_client")

# Create a client — credentials come from the host, region is enough for AWS
# auto-detection.
client = create_client(region="us-west-2")

# Upload and download
client.put_object("my-bucket", "hello.txt", "Hello, World!")
content = client.get_object("my-bucket", "hello.txt")   # => "Hello, World!"

# List objects (returns the object list directly)
for obj in client.list_objects("my-bucket", prefix="docs/"):
    print(obj["key"], obj["size"])

# A public URL (from the client's own config) and a temporary signed URL
public = client.get_public_url("my-bucket", "hello.txt")
signed = client.presign_url("my-bucket", "hello.txt", expires_in=3600)
load("s3", "create_client")

# MinIO via an explicit endpoint; inspect what the client resolved to.
minio = create_client(service_type="minio", endpoint="localhost:9000", use_ssl=False)
info = minio.get_client_info()
print(info.service_type, info.region, info.endpoint)
print("credentials present:", info.access_key_set and info.secret_key_set)

Starlark API at a glance

Top-level builtins (load("s3", …)):

  • create_client(service_type?, region?, endpoint?, force_path_style?, use_ssl?, timeout?, max_retries?, part_size?, concurrency?, enable_logging?, user_agent?) — build an S3 client (credentials are host-injected, not accepted here).
  • validate_bucket_name(name) — whether name is a valid S3 bucket name.
  • validate_object_key(key) — whether key is a valid S3 object key.
  • get_supported_services() — the list of supported service-type strings.

Client object methods (returned by create_client):

  • get_client_info() — effective config struct (secret values reported only as *_set booleans).
  • get_public_url(bucket, key) — build a public URL from the client's config.
  • presign_url(bucket, key, expires_in=3600, method="GET") — temporary signed URL (GET/PUT/HEAD).
  • create_bucket(bucket, region=None) — create a bucket.
  • delete_bucket(bucket, force=False) — delete a bucket (force=True empties it first).
  • list_buckets() — list buckets as a list of dicts.
  • bucket_exists(bucket) — whether a bucket exists.
  • get_bucket_info(bucket) — comprehensive bucket info dict.
  • put_object(bucket, key, content, **options) — upload an object from a string.
  • put_object_file(bucket, key, file_path, **options) — upload an object from a local file.
  • get_object(bucket, key) — download an object as a string.
  • get_object_file(bucket, key, file_path) — download an object to a local file.
  • delete_object(bucket, key) — delete an object.
  • list_objects(bucket, prefix="", delimiter="", max_keys=1000) — list objects (returns the list directly).
  • object_exists(bucket, key) — whether an object exists.
  • get_object_info(bucket, key) — object metadata dict.
  • set_object_info(bucket, key, **options) — set object metadata/properties in place.
  • copy_object(src_bucket, src_key, dst_bucket, dst_key, **options) — copy an object.

get_object reads at most max_object_size bytes into memory (host-only, 256 MiB default) so a huge object can't exhaust host memory.

The object-writing methods (put_object, put_object_file, set_object_info, copy_object) accept the optional keyword arguments content_type, metadata, tags, cache_control, content_disposition, content_encoding, content_language, and expires.

See docs/API.md for the full signatures, return values, errors, and examples of every builtin and method above.

Configuration

The module's options (service_type, region, endpoint, force_path_style, use_ssl, timeout, max_retries, part_size, concurrency, enable_logging, user_agent) are configured via environment variables (S3_*) or per-option get_<key> / set_<key> accessor builtins, and the non-secret ones double as create_client defaults. Credentials (access_key, secret_key, session_token) are secret and host-injected only — set-only, never readable, and never create_client keyword arguments. See the Configuration section of docs/API.md for the full option table, accessors, env vars, defaults, and the host-injected-credentials rule.

License

MIT — see LICENSE.

Documentation

Overview

Package s3 provides constants and configuration for S3-compatible service providers

Package s3 provides a Starlark module for S3-compatible storage operations.

Index

Constants

View Source
const (
	// ProviderAWS is Amazon S3
	ProviderAWS = "aws"
	// ProviderMinIO is MinIO
	ProviderMinIO = "minio"
	// ProviderDigitalOcean is DigitalOcean Spaces
	ProviderDigitalOcean = "digitalocean"
	// ProviderLinode is Linode Object Storage
	ProviderLinode = "linode"
	// ProviderWasabi is Wasabi Hot Cloud Storage
	ProviderWasabi = "wasabi"
	// ProviderBackblaze is Backblaze B2
	ProviderBackblaze = "backblaze"
	// ProviderCloudflare is Cloudflare R2
	ProviderCloudflare = "cloudflare"
	// ProviderScaleway is Scaleway Object Storage
	ProviderScaleway = "scaleway"
	// ProviderAlibaba is Alibaba Cloud OSS
	ProviderAlibaba = "alibaba"
	// ProviderGoogle is Google Cloud Storage
	ProviderGoogle = "google"
	// ProviderOracle is Oracle Cloud Infrastructure
	ProviderOracle = "oracle"
	// ProviderIBM is IBM Cloud Object Storage
	ProviderIBM = "ibm"
	// ProviderCustom is for custom providers
	ProviderCustom = "custom"
)

S3-compatible service provider constants

View Source
const ModuleName = "s3"

ModuleName defines the expected name for this module when used in Starlark's load() function

Variables

This section is empty.

Functions

func DetectProviderFromConfig

func DetectProviderFromConfig(config *ClientConfig) string

DetectProviderFromConfig uses pluggable detection rules to identify the best provider

func GenerateURLWithProvider

func GenerateURLWithProvider(bucket, key, region, endpoint string, useSSL bool, provider string) string

GenerateURLWithProvider generates a public URL using provider-specific logic

func GetAllProviders

func GetAllProviders() []string

GetAllProviders returns a list of all supported provider names

Types

type BucketInfo

type BucketInfo struct {
	Name                string            `json:"name"`
	CreationDate        time.Time         `json:"creation_date,omitempty"`
	Region              string            `json:"region,omitempty"`
	Location            string            `json:"location,omitempty"`
	VersioningStatus    string            `json:"versioning_status,omitempty"`
	PublicAccessBlocked bool              `json:"public_access_blocked,omitempty"`
	HasPolicy           bool              `json:"has_policy,omitempty"`
	HasCors             bool              `json:"has_cors,omitempty"`
	EncryptionEnabled   bool              `json:"encryption_enabled,omitempty"`
	EncryptionType      string            `json:"encryption_type,omitempty"`
	ObjectCount         int64             `json:"object_count,omitempty"`
	TotalSize           int64             `json:"total_size,omitempty"`
	StorageClass        string            `json:"storage_class,omitempty"`
	Tags                map[string]string `json:"tags,omitempty"`
	Owner               string            `json:"owner,omitempty"`
	BucketType          string            `json:"bucket_type,omitempty"`
}

BucketInfo contains comprehensive information about an S3 bucket

func (*BucketInfo) MarshalStarlark

func (b *BucketInfo) MarshalStarlark() (starlark.Value, error)

MarshalStarlark implements the Marshaler interface for BucketInfo

type Client

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

Client wraps the AWS S3 client with configuration

func NewClient

func NewClient(ctx context.Context, clientConfig *ClientConfig) (*Client, error)

NewClient creates a new S3 client with the provided configuration

func (*Client) BucketExists

func (c *Client) BucketExists(ctx context.Context, bucket string) (bool, error)

BucketExists checks if a bucket exists

func (*Client) CopyObject

func (c *Client) CopyObject(ctx context.Context, srcBucket, srcKey, dstBucket, dstKey string, opts *ObjectOptions) error

CopyObject copies an object from one location to another

func (*Client) CreateBucket

func (c *Client) CreateBucket(ctx context.Context, bucket string, region ...string) error

CreateBucket creates a new S3 bucket

func (*Client) DeleteBucket

func (c *Client) DeleteBucket(ctx context.Context, bucket string, force bool) error

DeleteBucket deletes an S3 bucket

func (*Client) DeleteObject

func (c *Client) DeleteObject(ctx context.Context, bucket, key string) error

DeleteObject deletes an object from S3

func (*Client) GetBucketInfo

func (c *Client) GetBucketInfo(ctx context.Context, bucket string) (*BucketInfo, error)

GetBucketInfo gets information about a bucket

func (*Client) GetConfig

func (c *Client) GetConfig() *ClientConfig

GetConfig returns the client configuration

func (*Client) GetObject

func (c *Client) GetObject(ctx context.Context, bucket, key string) (io.ReadCloser, error)

GetObject downloads an object from S3

func (*Client) GetObjectInfo

func (c *Client) GetObjectInfo(ctx context.Context, bucket, key string) (*ObjectInfo, error)

GetObjectInfo gets information about an object

func (*Client) GetObjectToFile

func (c *Client) GetObjectToFile(ctx context.Context, bucket, key, filePath string) error

GetObjectToFile downloads an object from S3 to a file

func (*Client) ListBuckets

func (c *Client) ListBuckets(ctx context.Context) ([]BucketInfo, error)

ListBuckets lists all S3 buckets

func (*Client) ListObjects

func (c *Client) ListObjects(ctx context.Context, bucket string, opts *ListObjectsOptions) (*ListObjectsResult, error)

ListObjects lists objects in a bucket

func (*Client) ObjectExists

func (c *Client) ObjectExists(ctx context.Context, bucket, key string) (bool, error)

ObjectExists checks if an object exists in S3

func (*Client) PresignURL

func (c *Client) PresignURL(ctx context.Context, bucket, key string, expiresInSec int, method string) (string, error)

PresignURL generates a pre-signed URL for temporary access to an object

func (*Client) PutObject

func (c *Client) PutObject(ctx context.Context, bucket, key string, body io.Reader, opts *ObjectOptions) error

PutObject uploads an object to S3

func (*Client) PutObjectFromFile

func (c *Client) PutObjectFromFile(ctx context.Context, bucket, key, filePath string, opts *ObjectOptions) error

PutObjectFromFile uploads a file to S3

func (*Client) SetObjectInfo

func (c *Client) SetObjectInfo(ctx context.Context, bucket, key string, opts *ObjectOptions) error

SetObjectInfo sets metadata and other properties for an existing object

type ClientConfig

type ClientConfig struct {
	// Service configuration
	ServiceType    string // Service type (aws_s3, cloudflare_r2, etc.)
	Endpoint       string // Custom endpoint URL
	Region         string // AWS region or equivalent
	ForcePathStyle bool   // Use path-style addressing
	UseSSL         bool   // Enable/disable SSL

	// Authentication
	AccessKey    string // Access key ID
	SecretKey    string // Secret access key
	SessionToken string // Session token for temporary credentials

	// Performance and reliability
	Timeout     int   // Per-request timeout in seconds (bounds each HTTP request)
	MaxRetries  int   // Maximum attempts per request, including the first try
	PartSize    int64 // Multi-part upload part size in bytes
	Concurrency int   // Concurrent operations

	// Advanced options
	EnableLogging bool   // Enable request logging
	UserAgent     string // Custom user agent
}

ClientConfig contains configuration for an S3 client

func (*ClientConfig) Validate

func (c *ClientConfig) Validate() error

Validate validates the client configuration and sets defaults.

type ClientWrapper

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

ClientWrapper wraps the S3Client for Starlark

func NewClientWrapper

func NewClientWrapper(client *Client) *ClientWrapper

NewClientWrapper creates a new ClientWrapper with initialized method maps

func (*ClientWrapper) Attr

func (cw *ClientWrapper) Attr(name string) (starlark.Value, error)

Attr implements starlark.HasAttrs, resolving a method name (e.g. "put_object") to its bound builtin, or returning a no-such-attribute error.

func (*ClientWrapper) AttrNames

func (cw *ClientWrapper) AttrNames() []string

AttrNames implements starlark.HasAttrs and lists every callable method name on the client (used for dir() and attribute completion).

func (*ClientWrapper) Freeze

func (cw *ClientWrapper) Freeze()

Freeze implements starlark.Value. The client is immutable after creation, so freezing is a no-op.

func (*ClientWrapper) Hash

func (cw *ClientWrapper) Hash() (uint32, error)

Hash implements starlark.Value. The client is unhashable (it cannot be used as a dict key), so this always returns an error.

func (*ClientWrapper) String

func (cw *ClientWrapper) String() string

String implements starlark.Value; it renders the client as "<s3.Client service_type=… region=…>" for printing and error messages.

func (*ClientWrapper) Truth

func (cw *ClientWrapper) Truth() starlark.Bool

Truth implements starlark.Value; a client is always truthy.

func (*ClientWrapper) Type

func (cw *ClientWrapper) Type() string

Type implements starlark.Value and returns the Starlark type name "s3.Client".

type DetectionRule

type DetectionRule struct {
	// Priority determines the order of evaluation (lower = higher priority)
	Priority int
	// DetectFunc returns true if this provider matches the config
	DetectFunc func(config *ClientConfig) bool
	// Description explains what this rule detects
	Description string
}

DetectionRule represents a rule for detecting a specific provider

type ListObjectsOptions

type ListObjectsOptions struct {
	Prefix            *string
	Delimiter         *string
	MaxKeys           *int
	ContinuationToken *string
}

ListObjectsOptions configures ListObjects operations

func NewListObjectsOptions

func NewListObjectsOptions() *ListObjectsOptions

NewListObjectsOptions creates a new ListObjectsOptions instance

func (*ListObjectsOptions) ApplyToListObjects

func (o *ListObjectsOptions) ApplyToListObjects(input *s3.ListObjectsV2Input)

ApplyToListObjects applies the options to a ListObjectsV2Input

func (*ListObjectsOptions) Validate

func (o *ListObjectsOptions) Validate() bool

Validate returns true if the options contain any non-nil values

type ListObjectsResult

type ListObjectsResult struct {
	Contents       []ObjectInfo `json:"contents"`
	CommonPrefixes []string     `json:"common_prefixes,omitempty"`
	IsTruncated    bool         `json:"is_truncated"`
	NextMarker     string       `json:"next_marker,omitempty"`
	MaxKeys        int          `json:"max_keys"`
	Prefix         string       `json:"prefix,omitempty"`
	Delimiter      string       `json:"delimiter,omitempty"`
}

ListObjectsResult contains the result of a list objects operation

func (*ListObjectsResult) MarshalStarlark

func (l *ListObjectsResult) MarshalStarlark() (starlark.Value, error)

MarshalStarlark implements the Marshaler interface for ListObjectsResult Returns a dict with all ListObjectsResult fields

type Module

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

Module wraps the ConfigurableModule with specific functionality for S3 operations

func NewModule

func NewModule() *Module

NewModule creates a new instance of Module with default configurations

func (*Module) LoadModule

func (m *Module) LoadModule() starlet.ModuleLoader

LoadModule returns the Starlark module loader with S3-specific functions

type ObjectInfo

type ObjectInfo struct {
	Key                string            `json:"key"`
	Size               int64             `json:"size"`
	LastModified       time.Time         `json:"last_modified"`
	ETag               string            `json:"etag"`
	ContentType        string            `json:"content_type,omitempty"`
	ContentEncoding    string            `json:"content_encoding,omitempty"`
	ContentDisposition string            `json:"content_disposition,omitempty"`
	ContentLanguage    string            `json:"content_language,omitempty"`
	CacheControl       string            `json:"cache_control,omitempty"`
	Expires            *time.Time        `json:"expires,omitempty"`
	StorageClass       string            `json:"storage_class,omitempty"`
	ChecksumAlgorithm  string            `json:"checksum_algorithm,omitempty"`
	VersionID          string            `json:"version_id,omitempty"`
	IsLatest           bool              `json:"is_latest,omitempty"`
	Owner              string            `json:"owner,omitempty"`
	Metadata           map[string]string `json:"metadata,omitempty"`
	Tags               map[string]string `json:"tags,omitempty"`
}

ObjectInfo contains comprehensive information about an S3 object

func (*ObjectInfo) MarshalStarlark

func (o *ObjectInfo) MarshalStarlark() (starlark.Value, error)

MarshalStarlark implements the Marshaler interface for ObjectInfo

type ObjectOptions

type ObjectOptions struct {
	ContentType        *string
	Metadata           *map[string]string
	Tags               *map[string]string
	CacheControl       *string
	ContentEncoding    *string
	ContentDisposition *string
	ContentLanguage    *string
	Expires            *time.Time
}

ObjectOptions contains options for object operations

func NewObjectOptions

func NewObjectOptions() *ObjectOptions

NewObjectOptions creates a new ObjectOptions instance

func (*ObjectOptions) ApplyToCopyObject

func (o *ObjectOptions) ApplyToCopyObject(input *s3.CopyObjectInput)

ApplyToCopyObject applies the options to a CopyObjectInput and sets metadata directive

func (*ObjectOptions) ApplyToPutObject

func (o *ObjectOptions) ApplyToPutObject(input *s3.PutObjectInput)

ApplyToPutObject applies the options to a PutObjectInput

func (*ObjectOptions) Validate

func (o *ObjectOptions) Validate() bool

Validate returns true if the options contain any non-nil values

type ProviderConfig

type ProviderConfig struct {
	// Basic information
	Name          string
	DisplayName   string
	DefaultRegion string
	DefaultPort   string

	// Connection settings
	ForcePathStyle bool
	URLStyle       URLStyle

	// Endpoint configuration
	EndpointPattern string

	// URL patterns for parsing different URL formats
	URLPatterns []URLPattern

	// URL generation function
	GenerateURL func(bucket, key, region, endpoint string, useSSL bool) string

	// Provider-specific settings
	SupportsVirtualHosted bool
	SupportsPathStyle     bool
	RequiresAccountID     bool
	RequiresNamespace     bool

	// Detection rules for smart provider detection
	DetectionRules []DetectionRule
}

ProviderConfig contains comprehensive configuration for S3-compatible service providers

func GetProviderConfig

func GetProviderConfig(provider string) *ProviderConfig

GetProviderConfig returns the configuration for a specific provider

type ServiceConfig

type ServiceConfig struct {
	Name            string
	DefaultRegion   string
	EndpointPattern string
	ForcePathStyle  bool
	DefaultPort     string
}

ServiceConfig contains configuration for known S3-compatible services

type URLPattern

type URLPattern struct {
	// Pattern is a regexp pattern for matching URLs
	Pattern *regexp.Regexp
	// ParseFunc extracts bucket and key from URL components
	ParseFunc func(host, path string) (bucket, key string, ok bool)
	// GenerateFunc generates a URL from bucket, key, and other parameters
	GenerateFunc func(bucket, key, region, endpoint string, useSSL bool) string
}

URLPattern represents a URL pattern for parsing or generating URLs

type URLStyle

type URLStyle int

URLStyle represents different URL addressing styles

const (
	// URLStyleVirtualHosted uses virtual-hosted-style URLs: bucket.s3.amazonaws.com/key
	URLStyleVirtualHosted URLStyle = iota
	// URLStylePath uses path-style URLs: s3.amazonaws.com/bucket/key
	URLStylePath
	// URLStyleBoth supports both virtual-hosted and path-style URLs
	URLStyleBoth
)

Jump to

Keyboard shortcuts

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