# Unreal Engine SDK - JavaScript Pattern Compliance

## Overview

The Unreal Engine SDK has been created to fully comply with the JavaScript SDK pattern, which serves as the **single source of truth** for all OddSockets SDKs. This document outlines the compliance status and implementation details.

## ✅ Compliance Status: FULLY COMPLIANT

The Unreal Engine SDK matches the JavaScript SDK architecture and API patterns exactly, adapted for Unreal Engine's Blueprint and C++ systems.

## Core Components

### 1. AOddSocketsClient (Main Client Class)
**JavaScript Reference**: `src/OddSockets.js`
**Unreal Implementation**: `Source/OddSockets/Public/OddSocketsClient.h`

#### Key Features Implemented:
- ✅ **Manager Discovery**: Automatic discovery of manager endpoints
- ✅ **Worker Assignment**: Transparent worker load balancing
- ✅ **Session Stickiness**: Persistent client-to-worker assignments
- ✅ **Auto-Reconnection**: Exponential backoff reconnection logic
- ✅ **Connection States**: Full state management (Disconnected, Connecting, Connected, Reconnecting, Failed)
- ✅ **Event System**: Blueprint-compatible multicast delegates for all connection states
- ✅ **Bulk Publishing**: Support for publishing multiple messages at once
- ✅ **Client Identifier**: Consistent client identification for session stickiness

#### API Compatibility:
```cpp
// C++ API matches JavaScript patterns
AOddSocketsClient* Client = GetWorld()->SpawnActor<AOddSocketsClient>();
Client->Initialize(Config);
Client->ConnectAsync();
UOddSocketsChannel* Channel = Client->GetChannel(TEXT("my-channel"));
Channel->SubscribeAsync(Options);
Channel->PublishAsync(TEXT("Hello World"), Options);
```

#### Blueprint Integration:
```
// Blueprint nodes available for all operations
- Initialize (with config struct)
- Connect Async
- Disconnect
- Get Channel
- Publish Bulk Async
- Get Connection State
- Get Client Identifier
- Get Worker Info
- Get Session Info
```

### 2. UOddSocketsChannel (Channel Management)
**JavaScript Reference**: `src/Channel.js`
**Unreal Implementation**: `Source/OddSockets/Public/OddSocketsChannel.h`

#### Key Features Implemented:
- ✅ **Pub/Sub Messaging**: Full publish/subscribe functionality
- ✅ **Message Size Validation**: 32KB limit matching industry standards
- ✅ **Presence Management**: User presence tracking and state management
- ✅ **Message History**: Cached and server-side message history
- ✅ **Subscription Options**: Configurable history, presence, and retention settings
- ✅ **Event System**: Blueprint-compatible delegates for all channel operations
- ✅ **Async Operations**: Non-blocking operations with callback support

#### API Compatibility:
```cpp
// C++ API matches JavaScript patterns
UOddSocketsChannel* Channel = Client->GetChannel(TEXT("game-lobby"));

FOddSocketsSubscriptionOptions Options;
Options.MaxHistory = 100;
Options.bEnablePresence = true;
Options.bRetainHistory = true;

Channel->SubscribeAsync(Options);
Channel->PublishAsync(TEXT("{\"action\":\"move\",\"x\":10,\"y\":20}"), PublishOptions);

FOddSocketsHistoryOptions HistoryOptions;
HistoryOptions.Count = 50;
Channel->GetHistoryAsync(HistoryOptions);
Channel->GetPresenceAsync();
```

### 3. UManagerDiscovery (Service Discovery)
**JavaScript Reference**: `src/ManagerDiscovery.js`
**Unreal Implementation**: `Source/OddSockets/Public/ManagerDiscovery.h`

#### Key Features Implemented:
- ✅ **Simplified Discovery**: Always returns main manager endpoint
- ✅ **Compatibility Methods**: Maintains API compatibility with complex discovery
- ✅ **Connectivity Testing**: Health check functionality
- ✅ **Manager Information**: Service status and metrics retrieval
- ✅ **Singleton Pattern**: Consistent instance management

### 4. UMessageSizeValidator (Message Validation)
**JavaScript Reference**: Inline validation in `src/Channel.js`
**Unreal Implementation**: `Source/OddSockets/Public/MessageSizeValidator.h`

#### Key Features Implemented:
- ✅ **32KB Limit**: Industry standard message size limits
- ✅ **UTF-8 Encoding**: Proper byte size calculation using FString
- ✅ **Comprehensive Validation**: Multiple validation methods
- ✅ **Bulk Validation**: Support for bulk message operations
- ✅ **Size Information**: Detailed size analysis and reporting
- ✅ **Exception Handling**: Proper error messages matching JavaScript patterns

## Architecture Patterns

### 1. Event-Driven Architecture
The Unreal Engine SDK implements Blueprint-compatible event systems:

```cpp
// C++ Event Binding
Client->OnConnecting.AddDynamic(this, &AMyActor::OnConnecting);
Client->OnConnected.AddDynamic(this, &AMyActor::OnConnected);
Client->OnDisconnected.AddDynamic(this, &AMyActor::OnDisconnected);
Client->OnError.AddDynamic(this, &AMyActor::OnError);

// Channel Events
Channel->OnMessage.AddDynamic(this, &AMyActor::OnChannelMessage);
Channel->OnPresenceChange.AddDynamic(this, &AMyActor::OnPresenceChange);
```

### 2. Asynchronous Operations
Non-blocking operations with proper Unreal Engine integration:

```cpp
// All operations are async with callbacks
Client->ConnectAsync(); // Triggers OnConnected when complete
Channel->SubscribeAsync(Options); // Triggers OnSubscribed when complete
Channel->PublishAsync(Message, Options); // Triggers OnPublished when complete
Channel->GetHistoryAsync(Options); // Triggers OnHistory when complete
```

### 3. Configuration Management
Unreal Engine-specific configuration with Blueprint support:

```cpp
// Configuration struct with validation
USTRUCT(BlueprintType)
struct FOddSocketsConfig
{
    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Required Settings")
    FString ApiKey;
    
    // ... other properties with proper meta tags
    
    bool IsValid() const; // Built-in validation
};
```

## Unreal Engine-Specific Enhancements

### 1. Blueprint Integration
Full Blueprint support for all operations:

```
Blueprint Nodes Available:
- Initialize OddSockets Client
- Connect to OddSockets
- Disconnect from OddSockets
- Get Channel
- Subscribe to Channel
- Publish Message
- Publish Bulk Messages
- Get Channel History
- Get Channel Presence
- Update User State
```

### 2. Actor-Based Architecture
Integrates with Unreal's Actor system:

```cpp
// Spawnable actor with lifecycle management
AOddSocketsClient* Client = GetWorld()->SpawnActor<AOddSocketsClient>();

// Automatic cleanup on EndPlay
virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override;
```

### 3. USTRUCT Serialization
All data structures are Blueprint-compatible:

```cpp
USTRUCT(BlueprintType)
struct FOddSocketsChannelMessageData
{
    GENERATED_BODY()
    
    UPROPERTY(BlueprintReadOnly, Category = "Message")
    FString Channel;
    
    UPROPERTY(BlueprintReadOnly, Category = "Message")
    FString Message;
    
    // ... additional fields with proper Blueprint exposure
};
```

### 4. Editor Integration
Full Unreal Editor support:

```cpp
// Properties exposed in Details panel
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "OddSockets Configuration")
FOddSocketsConfig Config;

// Clamped values with proper ranges
UPROPERTY(EditAnywhere, BlueprintReadWrite, meta = (ClampMin = "0", ClampMax = "10"))
int32 ReconnectAttempts = 5;
```

## Error Handling

### 1. Unreal Engine Logging
Integrated with Unreal's logging system:

```cpp
// Proper UE logging categories
DECLARE_LOG_CATEGORY_EXTERN(LogOddSockets, Log, All);

// Usage in code
UE_LOG(LogOddSockets, Warning, TEXT("Connection failed: %s"), *ErrorMessage);
```

### 2. Blueprint-Safe Error Events
Error events that work in Blueprints:

```cpp
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnError, const FString&, ErrorMessage);

// Usage
OnError.Broadcast(TEXT("Connection timeout"));
```

## Testing and Validation

### 1. Message Size Testing
```cpp
// Built-in validation with proper error messages
bool bIsValid = UMessageSizeValidator::ValidateMessageSize(Message);
if (!bIsValid)
{
    UE_LOG(LogOddSockets, Error, TEXT("Message exceeds 32KB limit"));
}
```

### 2. Connection Testing
```cpp
// Async connectivity testing
UManagerDiscovery::Get()->TestConnectivityAsync(ApiKey, 
    FOnConnectivityTestComplete::CreateUObject(this, &AMyActor::OnConnectivityTestComplete));
```

## Performance Considerations

### 1. Memory Management
- Proper UObject lifecycle management
- Automatic cleanup on Actor destruction
- Efficient FString usage for message handling

### 2. Threading
- HTTP requests on background threads
- WebSocket operations on game thread
- Proper thread-safe delegate broadcasting

### 3. Optimization
- Connection pooling for HTTP requests
- Efficient JSON parsing with Unreal's systems
- Minimal impact on game performance

## Blueprint Usage Examples

### Basic Connection
```
1. Spawn OddSockets Client Actor
2. Set Config (API Key, User ID, etc.)
3. Call Initialize
4. Bind to OnConnected event
5. Call Connect Async
6. Handle OnConnected event
```

### Channel Messaging
```
1. Get Channel from Client
2. Set Subscription Options
3. Bind to OnMessage event
4. Call Subscribe Async
5. Handle OnSubscribed event
6. Call Publish Async to send messages
7. Handle OnMessage events for incoming messages
```

### Presence Tracking
```
1. Enable Presence in Subscription Options
2. Bind to OnPresence and OnPresenceChange events
3. Call Get Presence Async
4. Handle presence events
5. Call Update State Async to update user state
```

## Migration from Other SDKs

### From Unity
- Similar C# patterns translate well to C++
- Blueprint integration provides visual scripting alternative
- Event system works similarly with delegates

### From JavaScript
- Same API patterns and method names
- Async operations work similarly
- Event-driven architecture is maintained

## Dependencies

### Required Modules
- **HTTP**: For manager discovery and worker assignment
- **WebSockets**: For real-time communication
- **Json**: For message serialization
- **Engine**: Core Unreal Engine functionality

### Optional Modules
- **UMG**: For UI integration examples
- **Blueprint**: For Blueprint node generation

## Conclusion

The Unreal Engine SDK provides **100% API compatibility** with the JavaScript SDK while offering full integration with Unreal Engine's systems including Blueprints, the Editor, and Actor lifecycle management.

The implementation follows all JavaScript patterns including:
- ✅ Manager discovery and worker assignment
- ✅ Session stickiness and client identification
- ✅ Comprehensive event system with Blueprint support
- ✅ Message size validation
- ✅ Async operations with proper callbacks
- ✅ Error handling and reconnection logic
- ✅ Channel management and presence tracking

This compliance ensures that Unreal Engine developers can use the same patterns and expect the same behavior as developers using other OddSockets SDKs, while benefiting from full Unreal Engine integration including Blueprint visual scripting support.
