### UploadFile Example Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/api-reference/simpler-storage.md Example demonstrating how to upload a local file to a Cloud Storage bucket using the StorageClient. Ensure the file is opened and deferred closed. ```go import ( "os" "github.com/hrom-in-space/imagination-tools/simpler" ) client, err := simpler.NewStorageClient(ctx) if err != nil { return err } // Upload a file from disk file, err := os.Open("/path/to/local/file.txt") if err != nil { return err } deferr file.Close() err = client.UploadFile(ctx, "my-bucket", "uploads/file.txt", file) if err != nil { return err } ``` -------------------------------- ### Example Usage of NewPubSubClient Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/api-reference/simpler-pubsub.md Shows how to create a PubSubClient using NewPubSubClient and then use it to publish a message. Requires valid GCP credentials and project ID. ```go import ( "context" "github.com/hrom-in-space/imagination-tools/simpler" ) ctx := context.Background() // Create the Pub/Sub client client, err := simpler.NewPubSubClient(ctx, "my-gcp-project") if err != nil { return fmt.Errorf("failed to create pub/sub client: %w", err) } // Use client to publish messages err = client.PublishMessage(ctx, "my-topic", map[string]string{"key": "value"}) if err != nil { return fmt.Errorf("failed to publish: %w", err) } ``` -------------------------------- ### UploadJSONSchematized Example Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/api-reference/simpler-storage.md Example showing how to upload a schema-defined object to Cloud Storage with validation. The object must implement the SchemaProvider interface. ```go import ( "github.com/hrom-in-space/imagination-tools/simpler" "github.com/hrom-in-space/imagination-tools/schemas" ) client, err := simpler.NewStorageClient(ctx) if err != nil { return err } // Create a schema-defined object story := &schemas.StoryDraftedV1{ TaskID: "task-001", ArtifactCount: 3, } // Upload with schema validation err = client.UploadJSONSchematized(ctx, "my-bucket", "stories/drafted.json", story) if err != nil { return err // Object failed validation or upload failed } ``` -------------------------------- ### Mocking Pub/Sub Client for Testing Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/README.md Provides an example of how to create a mock implementation of the Pub/Sub client interface for use in unit tests. ```go type mockPubSubClient struct{} func (m *mockPubSubClient) PublishMessage(ctx context.Context, topicID string, object any) error { // Mock implementation return nil } // Use in tests var client simpler.PubSubClient = &mockPubSubClient{} ``` -------------------------------- ### StoryUploadedV1 Example Usage Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/api-reference/schemas.md Demonstrates creating, marshaling, and unmarshaling a StoryUploadedV1 event. ```go event := &schemas.StoryUploadedV1{ TaskID: "task-456", } // Encode to Avro data, err := event.Marshal() if err != nil { return err } // Decode from Avro var decoded schemas.StoryUploadedV1 if err := decoded.Unmarshal(data); err != nil { return err } println(decoded.TaskID) // "task-456" ``` -------------------------------- ### Example Usage of PublishMessage Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/api-reference/simpler-pubsub.md Demonstrates how to initialize a PubSubClient and publish a JSON-serializable object to a topic. Ensure the object is serializable and the topic exists. ```go import ( "context" "github.com/hrom-in-space/imagination-tools/simpler" ) // Initialize the client ctx := context.Background() client, err := simpler.NewPubSubClient(ctx, "my-gcp-project") if err != nil { return err } // Define a message to publish type OrderPlaced struct { OrderID string `json:"orderId"` Total float64 `json:"total"` } message := OrderPlaced{ OrderID: "order-789", Total: 99.99, } // Publish the message if err := client.PublishMessage(ctx, "orders-topic", message); err != nil { return err // Handle publish failure } // Message published successfully ``` -------------------------------- ### StoryDraftedV1 Example Usage Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/api-reference/schemas.md Demonstrates creating, marshaling, and unmarshaling a StoryDraftedV1 event. ```go import "github.com/hrom-in-space/imagination-tools/schemas" // Create an instance event := &schemas.StoryDraftedV1{ TaskID: "task-123", ArtifactCount: 5, } // Encode to Avro binary data, err := event.Marshal() if err != nil { return err } // Decode from Avro binary var decoded schemas.StoryDraftedV1 if err := decoded.Unmarshal(data); err != nil { return err } println(decoded.TaskID) // "task-123" ``` -------------------------------- ### Get Scene Avro Schema Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/api-reference/schemas.md Returns the Avro schema definition for the Scene type. This is useful for introspection or dynamic schema handling. ```go func (o *Scene) Schema() avro.Schema ``` -------------------------------- ### Get Character Avro Schema Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/api-reference/schemas.md Returns the Avro schema definition for the Character type. This is useful for introspection or dynamic schema handling. ```go func (o *Character) Schema() avro.Schema ``` -------------------------------- ### Basic Pub/Sub Client Initialization and Message Publishing Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/README.md Demonstrates how to create a Pub/Sub client and publish a structured message. The client should be created once and reused. ```go // 1. Create client (once, reuse) client, err := simpler.NewPubSubClient(ctx, "project-id") if err != nil { return err } // 2. Publish structured data event := MyEvent{ /* data */ } err = client.PublishMessage(ctx, "topic-id", event) ``` -------------------------------- ### Schema-Aware Storage Client Initialization and Operations Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/README.md Shows how to initialize a Storage client and perform schema-validated uploads and downloads. The client should be created once and reused. ```go // 1. Create client (once, reuse) client, err := simpler.NewStorageClient(ctx) if err != nil { return err } // 2. Upload with validation obj := &schemas.StoryDraftedV1{ /* data */ } err = client.UploadJSONSchematized(ctx, "bucket", "file.json", obj) // 3. Download with validation var result schemas.StoryDraftedV1 err = client.DownloadJSONSchematized(ctx, "bucket", "file.json", &result) ``` -------------------------------- ### Initialize Pub/Sub Client Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/quick-start.md Create a new Pub/Sub client for publishing messages. Ensure you have a GCP project ID. ```go import "github.com/hrom-in-space/imagination-tools/simpler" ctx := context.Background() client, err := simpler.NewPubSubClient(ctx, "my-gcp-project") if err != nil { return err } ``` -------------------------------- ### Initialize Cloud Storage Client Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/quick-start.md Create a new client for interacting with Cloud Storage. No specific project ID is required for initialization. ```go import "github.com/hrom-in-space/imagination-tools/simpler" ctx := context.Background() client, err := simpler.NewStorageClient(ctx) if err != nil { return err } ``` -------------------------------- ### Create and Publish JSON Messages with Pub/Sub Client Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/README.md Initializes a Pub/Sub client and publishes a JSON message to a specified topic. Ensure the context and project ID are valid. ```go client, err := simpler.NewPubSubClient(ctx, "project-id") if err != nil { return err } type OrderEvent struct { OrderID string Total float64 } err = client.PublishMessage(ctx, "orders-topic", OrderEvent{ OrderID: "order-123", Total: 99.99, }) ``` -------------------------------- ### simpler.NewPubSubClient Source: https://github.com/hrom-in-space/imagination-tools/blob/main/README.md Creates a new Google Cloud Pub/Sub client. This client implements the `PubSubClient` interface. ```APIDOC ## NewPubSubClient ### Description Creates a new Pub/Sub client that implements PubSubClient. ### Signature func NewPubSubClient(ctx context.Context, projectID string) (PubSubClient, error) ``` -------------------------------- ### Create Context with Deadline Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/quick-start.md Shows how to create a context that will be canceled at a specific deadline. Remember to call the `cancel` function to free up resources. ```go deadline := time.Now().Add(5 * time.Minute) ctx, cancel := context.WithDeadline(context.Background(), deadline) deferr cancel() ``` -------------------------------- ### Setting Google Application Credentials for Local Development Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/README.md Demonstrates how to set the GOOGLE_APPLICATION_CREDENTIALS environment variable for local development. ```bash export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account-key.json ``` -------------------------------- ### Import Core Packages Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/quick-start.md Import the necessary packages for using the imagination-tools library. ```go import ( "github.com/hrom-in-space/imagination-tools/econ" "github.com/hrom-in-space/imagination-tools/schemas" "github.com/hrom-in-space/imagination-tools/simpler" ) ``` -------------------------------- ### Create New Storage Client Source: https://github.com/hrom-in-space/imagination-tools/blob/main/README.md Initializes a new StorageGateway instance. This function is used to obtain a client for interacting with storage. ```go func NewStorageClient(ctx context.Context) (StorageClient, error) NewStorageClient creates a new StorageGateway instance. ``` -------------------------------- ### Create New Storage Client Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/api-reference/simpler-storage.md Creates a new Cloud Storage client using the provided context. Ensure Google Cloud credentials are available at runtime via Application Default Credentials (ADC). The returned client is thread-safe. ```go import ( "context" "fmt" "github.com/hrom-in-space/imagination-tools/simpler" ) func main() { ctx := context.Background() // Create the Storage client client, err := simpler.NewStorageClient(ctx) if err != nil { // Handle error: failed to create storage client fmt.Errorf("failed to create storage client: %w", err) return } // Example: Use client to upload files // Assuming fileReader is an io.Reader containing the file content // err = client.UploadFile(ctx, "my-bucket", "path/to/file.txt", fileReader) // if err != nil { // // Handle upload error // fmt.Println(err) // } } ``` -------------------------------- ### Create Context with Timeout Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/quick-start.md Demonstrates creating a context with a specified timeout. The `cancel` function must be called to release resources associated with the context. ```go // Create a context with timeout ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) deferr cancel() err := client.PublishMessage(ctx, "topic", message) ``` -------------------------------- ### Download Event from Storage and Process Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/quick-start.md Download an event from Cloud Storage and then process its data. This is typically done after an event has been stored. ```go // Download from storage var event schemas.StoryDraftedV1 if err := storageClient.DownloadJSONSchematized(ctx, "bucket", "events/t-1.json", &event); err != nil { return err } // Process the data fmt.Printf("Task %s has %d artifacts\n", event.TaskID, event.ArtifactCount) ``` -------------------------------- ### Project File Structure Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/INDEX.md Overview of the project's directory layout and the primary purpose of each file. ```text output/ ├── README.md # Architecture & overview ├── INDEX.md # This file ├── quick-start.md # Examples & patterns ├── types.md # Type reference └── api-reference/ ├── econ.md # CloudEvent utilities ├── schemas.md # Avro schema types ├── simpler-pubsub.md # Pub/Sub client └── simpler-storage.md # Storage client ``` -------------------------------- ### Download a Raw File Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/quick-start.md Download a file from a Cloud Storage bucket. The raw data is returned as a byte slice. ```go data, err := client.DownloadFile(ctx, "bucket", "path/in/bucket.txt") if err != nil { return err } println(string(data)) ``` -------------------------------- ### Publish Event to Pub/Sub and Store in Cloud Storage Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/quick-start.md Publish an event to Pub/Sub and then store the same event data in Cloud Storage. Ensure you have initialized the pubsubClient and storageClient. ```go // Publish to Pub/Sub event := &schemas.StoryDraftedV1{TaskID: "t-1", ArtifactCount: 3} if err := pubsubClient.PublishMessage(ctx, "events", event); err != nil { return err } // Store in Cloud Storage if err := storageClient.UploadJSONSchematized(ctx, "bucket", "events/t-1.json", event); err != nil { return err } ``` -------------------------------- ### Output Directory Structure Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/MANIFEST.md Illustrates the hierarchical organization of generated documentation files. ```text output/ ├── INDEX.md # Start here ├── README.md # Project overview ├── quick-start.md # Common task examples ├── types.md # Type reference ├── MANIFEST.md # This file └── api-reference/ ├── econ.md ├── schemas.md ├── simpler-pubsub.md └── simpler-storage.md ``` -------------------------------- ### simpler.StorageClient.DownloadFile Source: https://github.com/hrom-in-space/imagination-tools/blob/main/README.md Downloads a file from a specified bucket and returns its contents as bytes. ```APIDOC ## DownloadFile ### Description Downloads a file from the specified bucket and returns its contents as bytes. ### Method `DownloadFile` ### Parameters #### Path Parameters - **bucket** (string) - Required - The name of the bucket to download from. - **name** (string) - Required - The name of the file to download. ### Response #### Success Response (200) - **[]byte** - The content of the downloaded file. ``` -------------------------------- ### NewPubSubClient Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/api-reference/simpler-pubsub.md Creates a new Pub/Sub client that implements the PubSubClient interface. It initializes a connection to Google Cloud Pub/Sub for the specified project using Application Default Credentials (ADC). ```APIDOC ## NewPubSubClient Creates a new Pub/Sub client that implements the `PubSubClient` interface. ### Description Initializes a connection to Google Cloud Pub/Sub for the specified project. Uses Application Default Credentials (ADC) for authentication. The returned client is thread-safe. ### Function Signature ```go func NewPubSubClient(ctx context.Context, projectID string) (PubSubClient, error) ``` ### Parameters #### Path Parameters * **ctx** (`context.Context`) - Required - Context for client initialization (controls timeout) * **projectID** (`string`) - Required - Google Cloud Platform project ID ### Returns * `PubSubClient` - A `PubSubClient` implementation. * `error` - An error if initialization fails, typically due to invalid or unavailable project credentials. ### Example Usage ```go import ( "context" "github.com/hrom-in-space/imagination-tools/simpler" ) ctx := context.Background() // Create the Pub/Sub client client, err := simpler.NewPubSubClient(ctx, "my-gcp-project") if err != nil { return fmt.Errorf("failed to create pub/sub client: %w", err) } // Use client to publish messages err = client.PublishMessage(ctx, "my-topic", map[string]string{"key": "value"}) if err != nil { return fmt.Errorf("failed to publish: %w", err) } ``` ``` -------------------------------- ### Upload a Raw File Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/quick-start.md Upload the contents of a local file to a specified bucket and path in Cloud Storage. Ensure the file is opened and deferred closed. ```go import "os" file, err := os.Open("path/to/file.txt") if err != nil { return err } defer file.Close() er r := client.UploadFile(ctx, "bucket-name", "path/in/bucket.txt", file) ``` -------------------------------- ### Define Scene Schema Instance Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/quick-start.md Create an instance of the `Scene` schema type. This is a component used within other schema types like `ScenarioV1`. ```go scene := schemas.Scene{ ID: "scene-1", Name: "Opening", Description: "Action happens here", Characters: []string{"char-1"}, } ``` -------------------------------- ### CloudEvent Processing and Data Extraction Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/README.md Illustrates how to receive a CloudEvent from Pub/Sub and extract business-specific data into a struct. ```go // Receive CloudEvent from Pub/Sub var evt event.Event // Extract business data type BusinessPayload struct { /* fields */ } var payload BusinessPayload err := econ.EventToStruct(evt, &payload) ``` -------------------------------- ### Upload JSON with Schema Validation to Cloud Storage Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/README.md Creates a Storage client and uploads a Go struct as JSON to a bucket, validating it against an Avro schema. Requires a valid context and bucket name. ```go client, err := simpler.NewStorageClient(ctx) if err != nil { return err } // Upload with schema validation story := &schemas.StoryDraftedV1{ TaskID: "task-001", ArtifactCount: 5, } err = client.UploadJSONSchematized(ctx, "bucket", "path/to/file.json", story) ``` -------------------------------- ### Define StoryUploadedV1 Schema Instance Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/quick-start.md Create an instance of the `StoryUploadedV1` schema type. This is useful for publishing or uploading events. ```go event := &schemas.StoryUploadedV1{ TaskID: "task-002", } ``` -------------------------------- ### simpler.StorageClient.UploadFile Source: https://github.com/hrom-in-space/imagination-tools/blob/main/README.md Uploads a file to a specified Google Cloud Storage bucket. The content is provided as an io.Reader. ```APIDOC ## UploadFile ### Description Uploads a file to the specified bucket. ### Method `UploadFile` ### Parameters #### Path Parameters - **bucket** (string) - Required - The name of the bucket to upload to. - **name** (string) - Required - The name of the file to upload. #### Request Body - **content** (io.Reader) - Required - The content of the file to upload. ``` -------------------------------- ### NewPubSubClient Function Signature Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/api-reference/simpler-pubsub.md Signature for the NewPubSubClient function, used to create a new Pub/Sub client instance. ```go func NewPubSubClient(ctx context.Context, projectID string) (PubSubClient, error) ``` -------------------------------- ### Download File from Cloud Storage Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/api-reference/simpler-storage.md Downloads a file from Cloud Storage and returns its contents as bytes. Use this for general file downloads where schema validation is not required. ```Go func (c *storageClient) DownloadFile(ctx context.Context, bucket, name string) ([]byte, error) ``` ```Go client, err := simpler.NewStorageClient(ctx) if err != nil { return err } // Download file data, err := client.DownloadFile(ctx, "my-bucket", "uploads/file.txt") if err != nil { return err } println(string(data)) // Print file contents ``` -------------------------------- ### Download JSON with Schema Validation Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/quick-start.md Download a JSON file from Cloud Storage and unmarshal it into a Go struct, performing schema validation. ```go var story schemas.StoryDraftedV1 er r := client.DownloadJSONSchematized(ctx, "bucket", "stories/drafted.json", &story) if err != nil { return err } println(story.TaskID) ``` -------------------------------- ### StorageClient Interface Definition Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/README.md Defines the interface for Cloud Storage operations, including file upload/download and schema-validated JSON operations. It requires context and bucket/path information. ```go type StorageClient interface { UploadFile(ctx context.Context, bucket, name string, content io.Reader) error UploadJSONSchematized(ctx context.Context, bucket, name string, object SchemaProvider) error DownloadFile(ctx context.Context, bucket, name string) ([]byte, error) DownloadJSONSchematized(ctx context.Context, bucket, name string, object SchemaProvider) error } ``` -------------------------------- ### Download JSON with Schema Validation from Cloud Storage Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/README.md Retrieves a JSON file from a bucket, unmarshals it into a Go struct, and validates it against an Avro schema. Ensure the bucket and path are correct. ```go client, err := simpler.NewStorageClient(ctx) if err != nil { return err } // Download with schema validation var downloaded schemas.StoryDraftedV1 err = client.DownloadJSONSchematized(ctx, "bucket", "path/to/file.json", &downloaded) ``` -------------------------------- ### Define ScenarioV1 Schema Instance Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/quick-start.md Create an instance of the `ScenarioV1` schema type, including nested `Character` and `Scene` types. This is useful for complex event data. ```go scenario := &schemas.ScenarioV1{ Scenario: "A hero's quest", Characters: []schemas.Character{ { ID: "hero-1", Name: "The Hero", Description: "A brave protagonist", }, }, Scenes: []schemas.Scene{ { ID: "scene-1", Name: "The Beginning", Description: "The hero discovers their quest", Characters: []string{"hero-1"}, }, }, } ``` -------------------------------- ### Define Character Schema Instance Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/quick-start.md Create an instance of the `Character` schema type. This is a component used within other schema types like `ScenarioV1`. ```go char := schemas.Character{ ID: "char-1", Name: "Alice", Description: "A curious character", } ``` -------------------------------- ### simpler.PubSubClient.PublishMessage Source: https://github.com/hrom-in-space/imagination-tools/blob/main/README.md Publishes a message to a specified Pub/Sub topic. The message content can be any Go object that can be serialized. ```APIDOC ## PublishMessage ### Description Publishes a message to the specified topic. ### Method `PublishMessage` ### Parameters #### Path Parameters - **topicID** (string) - Required - The ID of the topic to publish to. #### Request Body - **object** (any) - Required - The message payload to publish. This can be any Go type that can be serialized. ### Signature func (c *PubSubClient) PublishMessage(ctx context.Context, topicID string, object any) error ``` -------------------------------- ### DownloadFile Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/api-reference/simpler-storage.md Downloads a file from the specified Cloud Storage bucket. The content is returned as a byte slice. ```APIDOC ## DownloadFile ### Description Downloads a file from the specified Cloud Storage bucket. The content is returned as a byte slice. ### Method GET ### Endpoint `/download/{bucket}/{name}` (Conceptual - actual implementation uses Go SDK) ### Parameters #### Path Parameters - **bucket** (string) - Yes - Cloud Storage bucket name - **name** (string) - Yes - Object name (path) within the bucket #### Query Parameters None #### Request Body None ### Request Example ```go // This is a Go SDK example, not a direct HTTP request. // client.DownloadFile(ctx, "my-bucket", "uploads/file.txt") ``` ### Response #### Success Response (200) - **content** ([]byte) - The content of the downloaded file #### Response Example ```json "SGVsbG8gV29ybGQ=" // Base64 encoded content ``` ### Error Handling - Returns an error if the object is not found or if there's an issue during download. ``` -------------------------------- ### PubSubClient Interface Definition Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/README.md Defines the interface for abstracting Pub/Sub publishing operations. It includes a single method for publishing messages. ```go type PubSubClient interface { PublishMessage(ctx context.Context, topicID string, object any) error } ``` -------------------------------- ### Upload JSON with Schema Validation Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/quick-start.md Upload a Go struct as JSON to Cloud Storage, with automatic schema validation against a predefined schema. ```go story := &schemas.StoryDraftedV1{ TaskID: "task-001", ArtifactCount: 5, } er r := client.UploadJSONSchematized(ctx, "bucket", "stories/drafted.json", story) ``` -------------------------------- ### UploadFile Method Signature Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/api-reference/simpler-storage.md Signature for the UploadFile method, which uploads a file to a Cloud Storage bucket. ```go func (c *storageClient) UploadFile(ctx context.Context, bucket string, name string, content io.Reader) error ``` -------------------------------- ### Marshal Scene to Bytes Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/api-reference/schemas.md Encodes a Scene object into a byte slice. Use this for serializing scene data. ```go func (o *Scene) Marshal() ([]byte, error) ``` -------------------------------- ### StorageClient Interface Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/types.md Handles Google Cloud Storage operations with optional schema validation. Supports uploading and downloading raw files as well as JSON data with Avro schema validation. ```APIDOC ## Interface StorageClient ### Description Handles Google Cloud Storage operations with optional schema validation. Supports uploading and downloading raw files as well as JSON data with Avro schema validation. ### Methods #### UploadFile - **ctx** (context.Context) - Required - Context for the operation. - **bucket** (string) - Required - The name of the storage bucket. - **name** (string) - Required - The name of the file to upload. - **content** (io.Reader) - Required - The content of the file to upload. ### Returns - **error** - An error if the file upload fails. #### UploadJSONSchematized - **ctx** (context.Context) - Required - Context for the operation. - **bucket** (string) - Required - The name of the storage bucket. - **name** (string) - Required - The name of the JSON object to upload. - **object** (SchemaProvider) - Required - The object to upload, which must implement the SchemaProvider interface. ### Returns - **error** - An error if the JSON upload fails or schema validation fails. #### DownloadFile - **ctx** (context.Context) - Required - Context for the operation. - **bucket** (string) - Required - The name of the storage bucket. - **name** (string) - Required - The name of the file to download. ### Returns - **[]byte** - The content of the downloaded file. - **error** - An error if the file download fails. #### DownloadJSONSchematized - **ctx** (context.Context) - Required - Context for the operation. - **bucket** (string) - Required - The name of the storage bucket. - **name** (string) - Required - The name of the JSON object to download. - **object** (SchemaProvider) - Required - An object to unmarshal the downloaded JSON into, which must implement the SchemaProvider interface. ### Returns - **error** - An error if the JSON download or schema validation fails. ``` -------------------------------- ### ScenarioV1 Unmarshal Method Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/api-reference/schemas.md Provides a method to decode a byte slice into a ScenarioV1 receiver using the Avro schema. ```go func (o *ScenarioV1) Unmarshal(b []byte) error ``` -------------------------------- ### simpler.StorageClient.DownloadJSONSchematized Source: https://github.com/hrom-in-space/imagination-tools/blob/main/README.md Downloads a JSON-serializable object from a specified bucket. It validates the stored schema reference and the downloaded object against the schema. ```APIDOC ## DownloadJSONSchematized ### Description Downloads a JSON-serializable object from the specified bucket. It validates that the stored schema reference matches the expected schema and validates the downloaded object against the schema after unmarshaling. ### Method `DownloadJSONSchematized` ### Parameters #### Path Parameters - **bucket** (string) - Required - The name of the bucket to download from. - **name** (string) - Required - The name of the object to download. #### Request Body - **object** (SchemaProvider) - Required - An object to unmarshal the downloaded data into. Must implement the `SchemaProvider` interface. ``` -------------------------------- ### StoryUploadedV1 Marshal and Unmarshal Methods Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/api-reference/schemas.md Provides methods to encode a StoryUploadedV1 event to Avro binary format and decode it back. ```go func (o *StoryUploadedV1) Marshal() ([]byte, error) ``` ```go func (o *StoryUploadedV1) Unmarshal(b []byte) error ``` -------------------------------- ### DownloadJSONSchematized Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/api-reference/simpler-storage.md Downloads a JSON object from Cloud Storage and deserializes it into a Go object, validating against its Avro schema. ```APIDOC ## DownloadJSONSchematized ### Description Downloads a JSON object from Cloud Storage and deserializes it into a Go object, validating against its Avro schema. ### Method GET ### Endpoint `/download/schematized/{bucket}/{name}` (Conceptual - actual implementation uses Go SDK) ### Parameters #### Path Parameters - **bucket** (string) - Yes - Cloud Storage bucket name - **name** (string) - Yes - Object name (path) within the bucket #### Query Parameters None #### Request Body - **object** (SchemaProvider) - Yes - An empty object implementing `SchemaProvider` to unmarshal the downloaded JSON into. ### Request Example ```go // This is a Go SDK example, not a direct HTTP request. // client.DownloadJSONSchematized(ctx, "my-bucket", "stories/drafted.json", &schemas.StoryDraftedV1{}) ``` ### Response #### Success Response (200) - **error** (error) - nil on success. The provided `object` will be populated with the downloaded and deserialized data. #### Response Example ```json null ``` ### Error Handling - Returns wrapped error if the object is not found - Returns wrapped error if the download fails - Returns wrapped error if JSON unmarshaling fails - Returns wrapped error if schema validation fails during deserialization ``` -------------------------------- ### NewStorageClient Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/api-reference/simpler-storage.md Creates a new Cloud Storage client. This client is thread-safe and uses Application Default Credentials (ADC) for authentication. ```APIDOC ## NewStorageClient ### Description Creates a new Cloud Storage client. This client abstracts the underlying Google Cloud Storage client and is thread-safe. ### Method Signature `func NewStorageClient(ctx context.Context) (StorageClient, error)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### Context - **ctx** (`context.Context`) - Required - Context for client initialization. ### Returns - **StorageClient** - A `StorageClient` implementation. - **error** - An error if initialization fails. Returns wrapped error if the underlying Google Cloud Storage client cannot be created (e.g., invalid or unavailable project credentials). ### Example Usage ```go import ( "context" "fmt" "github.com/hrom-in-space/imagination-tools/simpler" ) ctx := context.Background() // Create the Storage client client, err := simpler.NewStorageClient(ctx) if err != nil { // Handle error: fmt.Errorf("failed to create storage client: %w", err) return fmt.Errorf("failed to create storage client: %w", err) } // Use client to upload/download files // err = client.UploadFile(ctx, "my-bucket", "path/to/file.txt", fileReader) // if err != nil { // return err // } ``` ``` -------------------------------- ### Publish a Schema Type Message Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/quick-start.md Publish an event object that conforms to a defined schema to a Pub/Sub topic. ```go event := &schemas.StoryDraftedV1{ TaskID: "task-001", ArtifactCount: 3, } er r := client.PublishMessage(ctx, "story-events", event) ``` -------------------------------- ### Publish a Struct Message Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/quick-start.md Publish a custom struct as a message to a Pub/Sub topic. The struct will be JSON marshaled. ```go type Order struct { OrderID string `json:"orderId"` Total float64 `json:"total"` } order := Order{OrderID: "123", Total: 99.99} er r := client.PublishMessage(ctx, "orders-topic", order) ``` -------------------------------- ### Handle Wrapped Errors Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/quick-start.md All functions return wrapped errors. Check the error message for context when an operation fails. Log the error using %v for detailed context. ```go if err := client.PublishMessage(ctx, "topic", msg); err != nil { // err.Error() contains wrapped context log.Printf("Publish failed: %v", err) return err } ``` -------------------------------- ### ScenarioV1 Schema Definition Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/api-reference/schemas.md Defines the structure for a complete scenario, including its title, characters, and scenes. ```go type ScenarioV1 struct { Scenario string Characters []Character Scenes []Scene } ``` -------------------------------- ### Define StoryDraftedV1 Schema Instance Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/quick-start.md Create an instance of the `StoryDraftedV1` schema type. This is useful for publishing or uploading events. ```go event := &schemas.StoryDraftedV1{ TaskID: "task-001", ArtifactCount: 5, } ``` -------------------------------- ### ScenarioV1 Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/api-reference/schemas.md Represents the schema for a complete scenario containing characters and scenes. It includes methods for Avro schema encoding and decoding. ```APIDOC ## ScenarioV1 ### Description Represents the schema for a complete scenario containing characters and scenes. It includes methods for Avro schema encoding and decoding. ### Fields - **Scenario** (string) - Yes - Description or title of the scenario - **Characters** ([]Character) - Yes - Array of characters defined in the scenario - **Scenes** ([]Scene) - Yes - Array of scenes that comprise the scenario ### Methods #### Schema() Returns the Avro schema for `ScenarioV1`. ```go func (o *ScenarioV1) Schema() avro.Schema ``` **Returns:** `avro.Schema` — The parsed Avro schema definition. #### Unmarshal(b []byte) Decodes a byte slice into the receiver using the Avro schema. ```go func (o *ScenarioV1) Unmarshal(b []byte) error ``` **Parameters:** - **b** (`[]byte`) - Yes - Avro-encoded binary data **Returns:** `error` — An error if decoding fails; `nil` on success. #### Marshal() Encodes the receiver to bytes using the Avro schema. ```go func (o *ScenarioV1) Marshal() ([]byte, error) ``` **Returns:** `([]byte, error)` — Avro-encoded bytes and an error if encoding fails. ``` -------------------------------- ### SchemaProvider Interface Definition Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/README.md Defines an interface for types that can provide their Avro schema. This is used for schema-aware operations in Cloud Storage. ```go type SchemaProvider interface { Schema() avro.Schema } ``` -------------------------------- ### Scene Schema Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/api-reference/schemas.md Represents a scene within a scenario, containing a sequence of events and participating characters. Includes fields for ID, Name, Description, and Characters. ```APIDOC ## Scene Represents a scene within a scenario, containing a sequence of events and participating characters. ### Fields - **ID** (`string`) - Yes - Unique identifier for the scene - **Name** (`string`) - Yes - Display name of the scene - **Description** (`string`) - Yes - Description of scene events and actions - **Characters** (`[]string`) - Yes - Array of character IDs that appear in this scene ### Methods #### Schema() Returns the Avro schema for `Scene`. ```go func (o *Scene) Schema() avro.Schema ``` **Returns:** `avro.Schema` — The parsed Avro schema definition. #### Unmarshal(b []byte) Decodes a byte slice into the receiver. ```go func (o *Scene) Unmarshal(b []byte) error ``` #### Marshal() Encodes the receiver to bytes. ```go func (o *Scene) Marshal() ([]byte, error) ``` ``` -------------------------------- ### simpler.StorageClient.UploadJSONSchematized Source: https://github.com/hrom-in-space/imagination-tools/blob/main/README.md Uploads a JSON-serializable object to a specified bucket. The object is validated against its Avro schema before upload, and the schema reference is stored in metadata. ```APIDOC ## UploadJSONSchematized ### Description Uploads a JSON-serializable object to the specified bucket. It validates the object against its Avro schema before upload and stores the schema reference in the object's metadata for later validation during download. ### Method `UploadJSONSchematized` ### Parameters #### Path Parameters - **bucket** (string) - Required - The name of the bucket to upload to. - **name** (string) - Required - The name of the object to upload. #### Request Body - **object** (SchemaProvider) - Required - The JSON-serializable object to upload. Must implement the `SchemaProvider` interface. ``` -------------------------------- ### PubSubClient Interface Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/types.md Handles Google Cloud Pub/Sub operations. It allows publishing JSON-encoded messages to a specified topic. ```APIDOC ## Interface PubSubClient ### Description Handles Google Cloud Pub/Sub operations. It allows publishing JSON-encoded messages to a specified topic. ### Methods #### PublishMessage - **ctx** (context.Context) - Required - Context for the operation. - **topicID** (string) - Required - The ID of the Pub/Sub topic. - **object** (any) - Required - The JSON-encodable object to publish. ### Returns - **error** - An error if the message publishing fails. ``` -------------------------------- ### Cloud Storage Operations Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/README.md Enables uploading and downloading files to and from Google Cloud Storage, with support for optional Avro schema validation for JSON data. ```APIDOC ## Cloud Storage Operations ### Description Upload and download files and schema-validated JSON. ### Method ```go client, err := simpler.NewStorageClient(ctx) if err != nil { return err } // Upload with schema validation story := &schemas.StoryDraftedV1{ TaskID: "task-001", ArtifactCount: 5, } err = client.UploadJSONSchematized(ctx, "bucket", "path/to/file.json", story) // Download with schema validation var downloaded schemas.StoryDraftedV1 err = client.DownloadJSONSchematized(ctx, "bucket", "path/to/file.json", &downloaded) ``` ### Interface ```go type StorageClient interface { UploadFile(ctx context.Context, bucket, name string, content io.Reader) error UploadJSONSchematized(ctx context.Context, bucket, name string, object SchemaProvider) error DownloadFile(ctx context.Context, bucket, name string) ([]byte, error) DownloadJSONSchematized(ctx context.Context, bucket, name string, object SchemaProvider) error } ``` ``` -------------------------------- ### Pub/Sub Publishing Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/README.md Provides a high-level interface for publishing JSON messages to Google Cloud Pub/Sub topics. It simplifies the process of sending structured data for asynchronous processing. ```APIDOC ## Pub/Sub Publishing ### Description Create a client and publish JSON messages to topics. ### Method ```go client, err := simpler.NewPubSubClient(ctx, "project-id") if err != nil { return err } type OrderEvent struct { OrderID string Total float64 } err = client.PublishMessage(ctx, "orders-topic", OrderEvent{ OrderID: "order-123", Total: 99.99, }) ``` ### Interface ```go type PubSubClient interface { PublishMessage(ctx context.Context, topicID string, object any) error } ``` ``` -------------------------------- ### Marshal ScenarioV1 to Avro Bytes Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/api-reference/schemas.md Encodes a ScenarioV1 object into Avro-formatted byte slices. Use this method when you need to serialize scenario data for storage or transmission. ```go func (o *ScenarioV1) Marshal() ([]byte, error) ``` ```go scenario := &schemas.ScenarioV1{ Scenario: "A hero's journey", Characters: []schemas.Character{ { ID: "char-1", Name: "Hero", Description: "The main protagonist", }, }, Scenes: []schemas.Scene{ { ID: "scene-1", Name: "Opening", Description: "The hero discovers their quest", Characters: []string{"char-1"}, }, }, } // Encode to Avro data, err := scenario.Marshal() if err != nil { return err } ``` -------------------------------- ### schemas.StoryUploadedV1 Source: https://github.com/hrom-in-space/imagination-tools/blob/main/README.md Represents a generated Go type for a "StoryUploaded" event, including task ID. ```APIDOC ## StoryUploadedV1 ### Description StoryUploadedV1 is a generated struct representing the "StoryUploaded" event with taskID. ### Fields - **TaskID** (string) - The ID of the task. ``` -------------------------------- ### UploadFile Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/api-reference/simpler-storage.md Uploads a file to the specified Cloud Storage bucket. This method copies data directly from a reader without any schema validation or metadata setting. ```APIDOC ## UploadFile ### Description Uploads a file to the specified Cloud Storage bucket. This method copies data directly from a reader without any schema validation or metadata setting. ### Method POST ### Endpoint `/upload/{bucket}/{name}` (Conceptual - actual implementation uses Go SDK) ### Parameters #### Path Parameters - **bucket** (string) - Yes - Cloud Storage bucket name - **name** (string) - Yes - Object name (path) within the bucket #### Query Parameters None #### Request Body - **content** (io.Reader) - Yes - Source data stream ### Request Example ```go // This is a Go SDK example, not a direct HTTP request. // client.UploadFile(ctx, "my-bucket", "uploads/file.txt", file) ``` ### Response #### Success Response (200) - **error** (error) - nil on success #### Response Example ```json null ``` ### Error Handling - Returns wrapped error if copying from the reader fails - Returns wrapped error if closing the writer fails (upload incomplete) ``` -------------------------------- ### Marshal Character to Bytes Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/api-reference/schemas.md Encodes a Character object into a byte slice. Use this for serializing character data. ```go func (o *Character) Marshal() ([]byte, error) ``` -------------------------------- ### Character Schema Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/api-reference/schemas.md Represents a character within a scenario. Includes fields for ID, Name, and Description. ```APIDOC ## Character Represents a character within a scenario. ### Fields - **ID** (`string`) - Yes - Unique identifier for the character - **Name** (`string`) - Yes - Display name of the character - **Description** (`string`) - Yes - Character description or background ### Methods #### Schema() Returns the Avro schema for `Character`. ```go func (o *Character) Schema() avro.Schema ``` **Returns:** `avro.Schema` — The parsed Avro schema definition. #### Unmarshal(b []byte) Decodes a byte slice into the receiver. ```go func (o *Character) Unmarshal(b []byte) error ``` #### Marshal() Encodes the receiver to bytes. ```go func (o *Character) Marshal() ([]byte, error) ``` ``` -------------------------------- ### StoryDraftedV1 Marshal and Unmarshal Methods Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/api-reference/schemas.md Provides methods to encode a StoryDraftedV1 event to Avro binary format and decode it back. ```go func (o *StoryDraftedV1) Marshal() ([]byte, error) ``` ```go func (o *StoryDraftedV1) Unmarshal(b []byte) error ``` -------------------------------- ### Scene Struct Definition Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/api-reference/schemas.md Defines the structure for a scene within a scenario. This struct is generated from an Avro schema. ```go type Scene struct { ID string Name string Description string Characters []string } ``` -------------------------------- ### StoryUploadedV1 Schema Definition Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/api-reference/schemas.md Defines the structure for a story upload completion event, containing only a TaskID. ```go type StoryUploadedV1 struct { TaskID string } ``` -------------------------------- ### SchemaProvider Interface Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/types.md Interface for types that provide an Avro schema. Used for schema validation during storage operations. ```APIDOC ## Interface SchemaProvider ### Description Interface for types that provide an Avro schema. Used for schema validation during storage operations. ### Methods #### Schema ### Returns - **avro.Schema** - The Avro schema definition. ``` -------------------------------- ### CloudEvent Listener Handler Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/quick-start.md A basic HTTP handler for processing incoming CloudEvents, commonly used in Cloud Run or Cloud Functions. It decodes the event and then processes the specific payload type. ```go // In a Cloud Run or Cloud Functions handler func handlePubSubMessage(w http.ResponseWriter, r *http.Request) { var evt event.Event if err := json.NewDecoder(r.Body).Decode(&evt); err != nil { http.Error(w, "Invalid event", http.StatusBadRequest) return } var payload MyBusinessType if err := econ.EventToStruct(evt, &payload); err != nil { http.Error(w, "Failed to decode", http.StatusBadRequest) return } // Process payload processEvent(payload) } ``` -------------------------------- ### PublishMessage Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/api-reference/simpler-pubsub.md Publishes a JSON-serialized message to a Pub/Sub topic. The method blocks until the publish operation completes and the Pub/Sub broker acknowledges receipt. ```APIDOC ## PublishMessage Publishes a JSON-serialized message to a Pub/Sub topic. ### Description Encodes the provided object to JSON and publishes it as a message to the specified topic. This method is synchronous and will block until the Pub/Sub broker acknowledges receipt of the message. ### Method Signature ```go func (c *pubSubClient) PublishMessage(ctx context.Context, topicID string, object any) error ``` ### Parameters #### Path Parameters * **ctx** (`context.Context`) - Required - Context for the publish operation (controls timeout and cancellation) * **topicID** (`string`) - Required - The ID of the Pub/Sub topic to publish to * **object** (`any`) - Required - Any JSON-serializable value to publish as the message ### Returns * `error` - An error if marshaling, publishing, or waiting for completion fails; `nil` on success. ### Error Conditions * Returns wrapped error with context if JSON marshaling of `object` fails. * Returns wrapped error with context if publishing to the topic fails. * Returns wrapped error with context if waiting for publish completion fails. ### Example Usage ```go import ( "context" "github.com/hrom-in-space/imagination-tools/simpler" ) // Initialize the client ctx := context.Background() client, err := simpler.NewPubSubClient(ctx, "my-gcp-project") if err != nil { return err } // Define a message to publish type OrderPlaced struct { OrderID string `json:"orderId"` Total float64 `json:"total"` } message := OrderPlaced{ OrderID: "order-789", Total: 99.99, } // Publish the message if err := client.PublishMessage(ctx, "orders-topic", message); err != nil { return err // Handle publish failure } // Message published successfully ``` ``` -------------------------------- ### Character Struct Definition Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/api-reference/schemas.md Defines the structure for a character within a scenario. This struct is generated from an Avro schema. ```go type Character struct { ID string Name string Description string } ``` -------------------------------- ### PublishMessage Method Signature Source: https://github.com/hrom-in-space/imagination-tools/blob/main/_autodocs/api-reference/simpler-pubsub.md Signature for the PublishMessage method, which sends a JSON-serialized message to a Pub/Sub topic. ```go func (c *pubSubClient) PublishMessage(ctx context.Context, topicID string, object any) error ```