> ## Documentation Index
> Fetch the complete documentation index at: https://docs.stateset.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Event-Driven APIs with StateSet One

> Build autonomous commerce applications with StateSet's event-driven API.

# Event-Driven APIs with StateSet One

StateSet One provides a powerful event-driven API, designed to empower developers to build autonomous and responsive commerce applications. This approach allows systems to react in real-time to changes, creating more dynamic and efficient processes.

## Core Architecture Principles

StateSet's architecture follows a Three-Factor App model integrated with a Durable Execution OS. This design prioritizes scalability, reliability, and maintainability.

### Three-Factor App Architecture with Durable Execution OS

* **Single-Point GraphQL API:**  A unified interface for data interactions, providing remote data joins.
* **Event Triggers and Webhooks:** Enable seamless integrations and automation through event-driven logic.
* **Realtime Search:**  Provides customer service and warehouse operations with efficient data access.
* **Data Validation and Synchronization:** Maintains data integrity and consistency.
* **Workflow Orchestration:** Manages complex business processes using Temporal.
* **Automated Processes:** Automates routine tasks such as label printing and refund processing.
* **Comprehensive Testing:** Ensures quality through rigorous QA testing for all serverless functions.

### Three Factors of StateSet Architecture

#### Factor #1: Realtime GraphQL API

StateSet uses GraphQL as a flexible and efficient way for clients to interact with its data.

* **Low-Latency Responses:** GraphQL ensures that state changes provide immediate feedback to the user.
* **GraphQL Subscriptions:** Enables real-time data streaming, eliminating the need for polling and improving scalability.
  ```mermaid theme={null}
      graph LR
      A[Client App] <--> B(GraphQL API)
      B --> C[Data Source]
  ```
  > A client application sends a GraphQL query to the API which then fetches the data from its underlying data sources.

#### Factor #2: Reliable Eventing System

StateSet is built on an event-driven architecture where state changes trigger events.

* **Atomic Operations:** State changes and event generation are atomic, ensuring consistency.
* **At-Least-Once Delivery:** Guarantees that events are delivered to consumers, allowing a complete state history for observability.
  ```mermaid theme={null}
      graph LR
      A[State Change] --> B(Event Bus);
      B --> C[Event Handlers];
  ```
  > When a state change happens, it is sent to the event bus and then picked up by the configured event handlers.

#### Factor #3: Asynchronous Serverless Functions

StateSet uses serverless functions to handle events, providing scalability and cost-efficiency.

* **Idempotent Functions:** Functions can handle duplicate events without creating inconsistencies.
* **Out-of-Order Event Handling:** Functions handle events reliably, regardless of the order of arrival.

  ```mermaid theme={null}
      graph LR
      A[Event] --> B(Serverless Function);
      B --> C[Action];
  ```

  > An event is received by a serverless function which then executes an action.

### Detailed Architecture Components

Here's a deeper look at the core components:

#### Three-Factor App with Durable Execution OS

StateSet's architecture promotes:

* **Modular Design:** Business domains are separated into distinct services, allowing independent development and deployment.
* **Durable Execution OS:** Ensures workflows and state transitions are reliable, preventing data loss, and enabling recovery from failures.

#### Single-Point GraphQL API

The GraphQL API offers:

* **Remote Data Joins:**  Combines data from multiple sources into a single API request, reducing network calls.
* **Flexible Queries:** Clients can request specific data, optimizing performance.

```mermaid theme={null}
    graph LR
        A[Client App] <--> B(GraphQL API)
        B --> C[Data Source 1]
        B --> D[Data Source 2]
```

> The GraphQL API combines data from multiple sources into a single response.

#### Event Triggers and Webhooks

StateSet leverages:

* **Seamless Integrations:** Connects with external systems and services.
* **Automated Workflows:** Enables event-driven automated processes.

#### Realtime Search Capabilities

StateSet provides powerful search functionalities for:

* **Customer Service:**  Enables quick access to customer information for support teams.
* **Warehouse Operations:** Facilitates efficient inventory and order management.

#### Data Validation and Synchronization

StateSet maintains data integrity with:

* **Comprehensive Validation:** Validates incoming data to prevent errors.
* **Synchronization Mechanisms:** Keeps data consistent across all systems.

#### Workflow Orchestration with Temporal

StateSet uses Temporal for:

* **Complex Workflow Management:** Orchestrates intricate business processes with ease.
* **Automated Execution:** Ensures workflows are reliably executed and can recover from failures.
  ```mermaid theme={null}
      graph LR
      A[Event Trigger] --> B(Temporal Workflow);
      B --> C[Activity 1];
      B --> D[Activity 2];
  ```
  > An event triggers a temporal workflow. The workflow then coordinates multiple activities

#### Automated Processes

StateSet automates critical operations:

* **Label Printing:**  Automatically generates and prints shipping labels for various regions.
* **Refund Processing:**  Streamlines refund handling for quick and accurate transactions.

#### Comprehensive Testing and QA

StateSet ensures reliability through:

* **Test QA Paths:** Rigorous testing for all serverless functions.

## Event Handling

Here's a simple example of how event handling might be implemented in a serverless function:

```javascript theme={null}
exports.handler = async (event) => {
  console.log('Received event:', JSON.stringify(event, null, 2));

  try {
    // Extract event data
    const { type, payload } = event;

    if (type === 'order.created') {
        // Process Order Created Event
      console.log('Processing order creation:', payload);
      // Add business logic to perform when order is created
      // ...
    }
        else if (type === 'return.created') {
        // Process Return Created Event
        console.log('Processing return creation:', payload);
        // Add business logic to perform when return is created
        // ...
        }
    else if (type === 'inventory.updated') {
        // Process Inventory Updated Event
        console.log('Processing inventory update:', payload);
        // Add business logic to perform when inventory is updated
        // ...
    }
      else {
         console.log('Unknown Event Type')
      }

    return {
      statusCode: 200,
      body: JSON.stringify({ message: 'Event processed successfully' }),
    };
  } catch (error) {
    console.error('Error processing event:', error);
    return {
      statusCode: 500,
      body: JSON.stringify({ message: 'Error processing event' }),
    };
  }
};
```

> This is an example of a serverless function that can handle multiple different events. The function will check for the event type, extract the payload, perform the business logic, and then return a response.

```mermaid theme={null}
graph TD
    A[StateSet One Web App] <--> B[Realtime GraphQL API]
    B --> C[(State)]
    C --> D[Event system]
    D --> B
    D --> T[StateSet Cloud Platform]

    subgraph StateSet_Cloud_Platform[StateSet Cloud Platform]
        T --> H[Workflows]
        H --> I[Generate Label]
        H --> J[Create Order]
        H --> K[Process Refund]
    end
```

> The diagram shows the high level interactions between the different parts of the system.

## Conclusion

StateSet's event-driven API provides a powerful foundation for building modern commerce applications that are responsive, scalable, and reliable. This framework enables developers to build autonomous systems that react in real-time to changes in their environment.
