1. Deconstruct the User's Request:
* Core Subject: Design Token API.
* Mechanism: Streaming updates via EventSource (Server-Sent Events - SSE).
* Key Features:
* Transactional rollbacks (changes are atomic, if something fails, it reverts).
* Audit logs (tracking who changed what and when).
* Goal: Draft the architecture and API design.
Identify the Key Challenges & Requirements:
Design Tokens: Usually JSON structures (colors, spacing, typography). Need a schema.
SSE (EventSource): Unidirectional (server to client). Client needs to send updates via standard HTTP POST/PUT, which then trigger SSE broadcasts.
Transactions: If I update 50 tokens, I don't want the system to crash after token 49. It's all or nothing.
Rollbacks: Related to transactions. If the validation or persistence fails, the state remains unchanged.
Audit Logs: Immutable record of changes. Essential for design systems where a broken button color affects the whole org.
Concurrency: What if two devs edit the same token? Optimistic locking is usually best here (version numbers).
Architectural Overview:
Client: Subscribes to /stream. Sends updates to /tokens.
Server:
Controller (API endpoints).
Service (Business logic, validation, transactions).
Repository (Database).
Broadcaster (SSE management).
Audit Service.
Designing the Data Model:
Token: id, name, value, type, scope, version (for locking).
GET /v1/tokens/stream: The SSE connection. Needs to send initial state and subsequent deltas.
POST /v1/tokens/batch: The update endpoint. This is where the magic happens.
Input: Array of changes.
Output: Success/Fail + Transaction ID.
POST /v1/tokens/rollback/:transactionId: Manual rollback endpoint (bonus, but requested).
Addressing "Transactional Rollbacks" in an API context:
Scenario: Client sends a batch update.
Step 1: Start DB Transaction.
Step 2: Validate all tokens.
Step 3: Write Audit Logs (within the transaction).
Step 4: Commit Transaction.
Step 5: Broadcast update via SSE.
If failure: Rollback DB transaction, return error to client, do not broadcast.
Addressing "Audit Logs":
Need to store "Before" and "After" states? Or just the diff? Diffs are harder to query but smaller. Full snapshots are safer for compliance. Let's go with a structured log approach.
Drafting the Code/Structure (Iterative Refinement):
Protocol: HTTP/1.1 SSE is standard.
Format: JSON.
Tech Stack: Agnostic, but TypeScript/Node.js is easiest to illustrate. I'll use a pseudo-code/TypeScript mix for clarity.
Structuring the Response:
1. High-Level Architecture: Explain how the pieces fit together.
2. Data Model: Define the JSON shapes.
3. API Specification: The actual endpoints (REST + SSE).
4. The Event Stream Protocol: How updates look over the wire.
5. Transactional Logic & Rollback: The core algorithm.
6. Audit Strategy: How to log it.
Refining the "Rollback" aspect:
The prompt asks for transactional rollbacks. Usually, this means "if the write fails, undo it." But it could also mean "Allow the user to undo a specific transaction." I should support both implicit (error-based) and explicit (undo-button) rollbacks.
To support explicit rollbacks, the Audit Log effectively becomes the backup source.
Writing the content (Self-Correction during drafting):
Initial thought: Just send the new values in SSE.
Correction: Clients need to know which transaction caused the change so they can reconcile state or show a toast ("Bob updated colors"). Include transactionId in SSE events.
Initial thought: Use WebSockets.
Correction: Prompt specifically asked for EventSource. Keep it SSE.
Final Polish: Ensure naming conventions are clear (e.g., token.update, token.rollback). Add a section on error handling. (Self-correction: Make sure to emphasize optimistic concurrency—using a version field—otherwise, the streaming updates will conflict with user edits).
Output Generation: (Proceeding to generate the response based on the above structure.)
Here is a comprehensive design proposal for a Transactional Design Token API.
This design addresses the core requirements: EventSource (SSE) for real-time state synchronization, Transactional Safety to ensure design system integrity, and Audit Logs for compliance and history.
1. High-Level Architecture
We will use a Command Query Responsibility Segregation (CQRS) light pattern.
The Command Channel (REST/POST): Clients submit batch updates. The server validates, opens a transaction, writes to the DB, and commits.
The Event Channel (EventSource/SSE): Upon successful commit, the server pushes the new state to all connected clients.
The Audit Store: An immutable ledger linked to every transaction.
Core Components
Token Store (PostgreSQL/JSONB): Relational database with JSON support for token schemas.
Broadcaster: A Pub/Sub mechanism (e.g., Redis Pub/Sub or database Listen/Notify) to bridge the API and the SSE connections.
Audit Service: A middleware or side-effect worker that writes to an append-only log.
2. API Specification
A. The Command Endpoint (State Mutation)
Clients do not update tokens via SSE. They send HTTP requests.
CREATE TABLE design_tokens (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
namespace VARCHAR(255), -- e.g., 'global', 'dark-mode'
token_data JSONB NOT NULL,
version INT NOT NULL,
updated_at TIMESTAMPTZ DEFAULT NOW(),
CONSTRAINT unique_namespace_version UNIQUE (namespace, version)
);
Table: audit_logs
The immutable ledger.
sql
CREATE TABLE audit_logs (
id BIGSERIAL PRIMARY KEY,
transaction_id UUID NOT NULL UNIQUE,
user_id UUID NOT NULL,
action VARCHAR(50), -- 'UPDATE', 'ROLLBACK', 'FORCE_PUSH'
changes JSONB NOT NULL, -- The operations array sent by client
previous_state_hash VARCHAR(64), -- Integrity check
created_at TIMESTAMPTZ DEFAULT NOW()
);
Note: To perform a rollback, we do not delete this row. We insert a new row with action: ROLLBACK and apply the inverse logic to the design_tokens table.