storage

package
v2.21.0 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: Apache-2.0 Imports: 9 Imported by: 3 modules, 4 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 storage exposes the MediaStorageService interface for media persistence, plus instrumentation that wires storage operations into the runtime's event bus and OpenTelemetry spans.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type InstrumentedStorage

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

InstrumentedStorage wraps any MediaStorageService with telemetry — OTel spans on every call, runtime events on success and failure, and (when the consumer wires them in) bytes, latency and error metrics derived from the emitted events.

A nil bus disables events, and a nil MediaMetadata is tolerated. Only SetBus and Inner are safe on a nil *InstrumentedStorage.

The caller supplies the backend name (`local`, `s3`, ...) at construction, so the same wrapper works with any inner implementation.

func NewInstrumentedStorage

func NewInstrumentedStorage(inner MediaStorageService, bus events.Bus, backend string) *InstrumentedStorage

NewInstrumentedStorage wraps inner so every call publishes a media lifecycle event to bus and records an OTel span. backend names the concrete implementation (e.g. "local", "s3") and ends up on every emitted event and span.

Passing a nil inner returns nil. A nil bus is allowed (events become no-ops); spans still emit via the global tracer provider.

func (*InstrumentedStorage) DeleteMedia

func (s *InstrumentedStorage) DeleteMedia(ctx context.Context, reference Reference) error

DeleteMedia traces, times, and announces a delete operation.

func (*InstrumentedStorage) GetURL

func (s *InstrumentedStorage) GetURL(
	ctx context.Context, reference Reference, expiry time.Duration,
) (string, error)

GetURL traces and times URL generation. It emits no event on success, because URL generation moves no bytes, and publishes an error event on failure.

func (*InstrumentedStorage) Inner

Inner returns the wrapped MediaStorageService, for callers that need to type-assert to a backend-specific interface.

func (*InstrumentedStorage) RetrieveMedia

func (s *InstrumentedStorage) RetrieveMedia(
	ctx context.Context, reference Reference,
) (*types.MediaContent, error)

RetrieveMedia traces, times, and announces a retrieve operation.

func (*InstrumentedStorage) SetBus

func (s *InstrumentedStorage) SetBus(bus events.Bus)

SetBus swaps the event bus the wrapper publishes to, for callers that build the storage before the event bus exists. It is safe to call concurrently with operations. Passing nil disables events.

func (*InstrumentedStorage) StoreMedia

func (s *InstrumentedStorage) StoreMedia(
	ctx context.Context, content *types.MediaContent, metadata *MediaMetadata,
) (Reference, error)

StoreMedia traces, times, and announces a store operation.

type MediaExpiryReporter added in v2.17.0

type MediaExpiryReporter interface {
	// MediaExpiresAt returns when media with this metadata expires under its
	// PolicyName, honoring ExpiresAt when it is set. expires is false when the
	// media never expires, for example when PolicyName and ExpiresAt are both
	// empty. An unknown
	// policy is an error.
	MediaExpiresAt(metadata *MediaMetadata) (expiresAt time.Time, expires bool, err error)
}

MediaExpiryReporter is implemented by a MediaPolicyHandler that can say when stored media expires. When a deduplicating store returns an existing file for new content, it uses MediaExpiresAt to keep that file for as long as the longest-lived store that references it asked for.

type MediaMetadata

type MediaMetadata struct {
	// RunID identifies the test run that generated this media
	RunID string `json:"run_id"`

	// ConversationID identifies the conversation containing this media
	ConversationID string `json:"conversation_id,omitempty"`

	// SessionID identifies the session (for streaming sessions)
	SessionID string `json:"session_id,omitempty"`

	// MessageIdx is the index of the message containing this media (0-based)
	MessageIdx int `json:"message_idx"`

	// PartIdx is the index of the content part containing this media (0-based)
	PartIdx int `json:"part_idx"`

	// MIMEType is the media MIME type (e.g., "image/jpeg", "audio/mp3")
	MIMEType string `json:"mime_type"`

	// SizeBytes is the size of the media content in bytes
	SizeBytes int64 `json:"size_bytes"`

	// ProviderID identifies the provider that generated this media
	ProviderID string `json:"provider_id,omitempty"`

	// Timestamp is when the media was stored
	Timestamp time.Time `json:"timestamp"`

	// PolicyName is the retention policy to apply to this media
	PolicyName string `json:"policy_name,omitempty"`

	// ExpiresAt, when set, is when the media expires, with or without a
	// PolicyName; it takes the place of Timestamp plus the policy's duration.
	// Media with neither ExpiresAt nor PolicyName never expires. A
	// deduplicating store sets it when a later store of the same content
	// extends the shared file's retention, so the file keeps the first
	// store's Timestamp.
	ExpiresAt *time.Time `json:"expires_at,omitempty"`
}

MediaMetadata contains metadata about stored media for organization and policy enforcement. Storage uses this metadata to organize media files and apply retention policies.

type MediaPolicyHandler added in v2.17.0

type MediaPolicyHandler interface {
	// ApplyPolicy applies the policy named by metadata.PolicyName to a media
	// item before it is stored. An empty policy name means no policy. An error
	// (for example, an unknown policy) makes the store reject the media.
	ApplyPolicy(ctx context.Context, metadata *MediaMetadata) error

	// EnforcePolicy scans stored media under baseDir and enforces policies,
	// for example by deleting expired media. It should log and continue on
	// errors for individual files. It is typically called periodically.
	EnforcePolicy(ctx context.Context, baseDir string) error
}

MediaPolicyHandler applies and enforces retention policies on stored media. policy.TimeBasedPolicyHandler implements it, and a local.FileStore given one through local.WithPolicyHandler applies it to every media item it stores.

type MediaPolicyTracker added in v2.17.0

type MediaPolicyTracker interface {
	// TrackMedia records the media item whose metadata file is at metaPath.
	// metadata is the metadata that was written, including the effective
	// PolicyName.
	TrackMedia(metaPath string, metadata *MediaMetadata) error
}

MediaPolicyTracker is implemented by a MediaPolicyHandler that keeps its own record of stored media, such as an expiry index. After a store writes a media item's metadata file, it calls TrackMedia so the handler can enforce the item's policy without rescanning the store.

type MediaStorageService

type MediaStorageService interface {
	// StoreMedia stores media content and returns a storage reference.
	// The reference can be used to retrieve the media later.
	//
	// Parameters:
	//   - ctx: Context for cancellation and timeouts
	//   - content: The media content to store (must have Data, FilePath, or URL set)
	//   - metadata: Metadata about the media for organization and policies
	//
	// Returns:
	//   - Reference that can be used to retrieve the media
	//   - Error if storage fails
	//
	// The implementation should:
	//   - Validate the content and metadata
	//   - Store the media content durably
	//   - Apply any configured policies (e.g., retention)
	//   - Return a reference that uniquely identifies the stored media
	StoreMedia(ctx context.Context, content *types.MediaContent, metadata *MediaMetadata) (Reference, error)

	// RetrieveMedia retrieves media content by its storage reference.
	//
	// Parameters:
	//   - ctx: Context for cancellation and timeouts
	//   - reference: The storage reference returned by StoreMedia
	//
	// Returns:
	//   - MediaContent with FilePath set (Data should NOT be loaded into memory)
	//   - Error if retrieval fails or reference is invalid
	//
	// The implementation should:
	//   - Validate the reference
	//   - Return MediaContent with FilePath pointing to the stored media
	//   - NOT load the full media data into memory (caller can use GetBase64Data if needed)
	RetrieveMedia(ctx context.Context, reference Reference) (*types.MediaContent, error)

	// DeleteMedia deletes media content by its storage reference.
	//
	// Parameters:
	//   - ctx: Context for cancellation and timeouts
	//   - reference: The storage reference to delete
	//
	// Returns:
	//   - Error if deletion fails or reference is invalid
	//
	// The implementation should:
	//   - Validate the reference
	//   - Delete the media content if not referenced elsewhere (for dedup)
	//   - Clean up any associated metadata
	//   - Handle concurrent deletions safely
	DeleteMedia(ctx context.Context, reference Reference) error

	// GetURL returns a URL that can be used to access the media.
	// For local storage, this returns a file:// URL.
	// For cloud storage, this may return a signed URL with expiration.
	//
	// Parameters:
	//   - ctx: Context for cancellation and timeouts
	//   - reference: The storage reference
	//   - expiry: How long the URL should be valid (ignored for local storage).
	//     An expiry <= 0 means the store chooses its own expiry/caching policy.
	//
	// Returns:
	//   - URL string that can be used to access the media
	//   - Error if URL generation fails or reference is invalid
	GetURL(ctx context.Context, reference Reference, expiry time.Duration) (string, error)
}

MediaStorageService defines the interface for storing and retrieving media content. Implementations may store media in local filesystem, cloud storage, or other backends.

Example usage:

store, err := local.NewFileStore(local.FileStoreConfig{
    BaseDir:      "/var/promptkit/media",
    Organization: storage.OrganizationByRun,
})
if err != nil {
    return err
}
ref, err := store.StoreMedia(ctx, mediaContent, metadata)
if err != nil {
    return err
}
content, err := store.RetrieveMedia(ctx, ref)

Implementations should be safe for concurrent use by multiple goroutines.

Example

ExampleMediaStorageService shows storing and retrieving media content through the local filesystem implementation of MediaStorageService. It needs no network access or cloud credentials — media lands under a temporary directory that is cleaned up at the end of the example.

package main

import (
	"context"
	"fmt"
	"os"

	"github.com/AltairaLabs/PromptKit/runtime/v2/storage"
	"github.com/AltairaLabs/PromptKit/runtime/v2/storage/local"
	"github.com/AltairaLabs/PromptKit/runtime/v2/types"
)

func main() {
	dir, err := os.MkdirTemp("", "storage-example")
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	defer os.RemoveAll(dir)

	fs, err := local.NewFileStore(local.FileStoreConfig{BaseDir: dir})
	if err != nil {
		fmt.Println("error:", err)
		return
	}

	data := "aGVsbG8=" // base64 for "hello"
	ref, err := fs.StoreMedia(context.Background(),
		&types.MediaContent{Data: &data, MIMEType: "text/plain"},
		&storage.MediaMetadata{SessionID: "s1", MIMEType: "text/plain"})
	if err != nil {
		fmt.Println("error:", err)
		return
	}

	out, err := fs.RetrieveMedia(context.Background(), ref)
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Println(out.MIMEType)
}
Output:
text/plain

type MediaWriteGuard added in v2.17.0

type MediaWriteGuard interface {
	// BeginMediaWrite marks the item at metaPath as being written and returns
	// the function that ends the write. The returned function is safe to call
	// more than once.
	BeginMediaWrite(metaPath string) (end func())
}

MediaWriteGuard is implemented by a MediaPolicyHandler that deletes media while stores are writing it. A store calls BeginMediaWrite before it writes a media item's files, and calls the returned function once it has written them and called TrackMedia. Until then the handler must not delete the files of the item whose metadata file is at metaPath, so a store that replaces an item's files cannot have them deleted on the strength of the old metadata.

type OrganizationMode

type OrganizationMode string

OrganizationMode defines how media files are organized in storage.

const (
	// OrganizationBySession organizes media by session ID
	OrganizationBySession OrganizationMode = "by-session"

	// OrganizationByConversation organizes media by conversation ID
	OrganizationByConversation OrganizationMode = "by-conversation"

	// OrganizationByRun organizes media by run ID
	OrganizationByRun OrganizationMode = "by-run"
)

type PolicyHandler

type PolicyHandler interface {
	// ApplyPolicy applies a named policy to a media file.
	// This typically stores policy metadata alongside the media.
	//
	// Parameters:
	//   - ctx: Context for cancellation and timeouts
	//   - filePath: Path to the media file
	//   - policyName: Name of the policy to apply (e.g., "delete-after-10min", "retain-30days")
	//
	// Returns:
	//   - Error if policy application fails or policy is unknown
	ApplyPolicy(ctx context.Context, filePath string, policyName string) error

	// EnforcePolicy scans stored media and enforces policies.
	// This is typically called periodically in the background.
	//
	// Parameters:
	//   - ctx: Context for cancellation and timeouts
	//
	// Returns:
	//   - Error if enforcement fails (should log but not crash on individual file errors)
	//
	// The implementation should:
	//   - Scan media directories for policy metadata
	//   - Apply policies (e.g., delete expired files)
	//   - Log enforcement actions
	//   - Handle errors gracefully (don't stop on permission denied, etc.)
	EnforcePolicy(ctx context.Context) error
}

PolicyHandler defines the interface for applying and enforcing storage policies. Policies control media retention, cleanup, and other lifecycle management.

The built-in policy.TimeBasedPolicyHandler implements MediaPolicyHandler, which is the interface local.FileStore applies, not this one.

type Reference

type Reference string

Reference is a reference to media stored in a backend. The format and meaning is backend-specific.

Directories

Path Synopsis
Package local provides local filesystem-based storage implementation.
Package local provides local filesystem-based storage implementation.
Package policy provides storage retention and cleanup policy management.
Package policy provides storage retention and cleanup policy management.

Jump to

Keyboard shortcuts

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