Server-side scenario execution: new Rudder.Core.dll, realtime/planstore glue removed

- Rudder.Core.dll rebuilt from csharp-sdk effects rewrite (96,768 bytes)
- Realtime/ adapters, UnityRealtimeTransportFactory, UnityPlanStateStore,
  UnityPlanScheduler, WebGL jslib and RealtimeUrl config deleted (with .meta)
- Scenarios sample rewired to client.Effects; samples login path updated
- AGENTS.md/README/CHANGELOG/package docs + agent skill updated; realtime.md skill doc removed
This commit is contained in:
edmand46
2026-09-04 14:23:38 +03:00
parent 22805173eb
commit 6d115f158e
71 changed files with 3338 additions and 1034 deletions
Binary file not shown.
@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: 2dda93a7ed40941b3a831824b938fe46
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,66 +0,0 @@
// WebSocket bridge for the Rudder Unity SDK (JsWebSocketAdapter).
// Implements the __Internal__ externals declared in Realtime/JsWebSocketAdapter.cs:
// RudderWebSocketCreate(gameObjectName, url)
// RudderWebSocketSend(gameObjectName, data, length)
// RudderWebSocketClose(gameObjectName)
// Events are routed back to the bridge GameObject via SendMessage:
// OnOpen(string), OnMessage(string base64), OnClose(string), OnError(string)
var RudderWebSockets = {};
function RudderWebSocketBase64(bytes) {
var chunks = [];
var chunkSize = 0x8000;
for (var i = 0; i < bytes.length; i += chunkSize) {
chunks.push(String.fromCharCode.apply(null, bytes.subarray(i, i + chunkSize)));
}
return btoa(chunks.join(''));
}
mergeInto(LibraryManager.library, {
RudderWebSocketCreate: function (gameObjectName, url) {
var name = UTF8ToString(gameObjectName);
var socket = new WebSocket(UTF8ToString(url));
socket.binaryType = 'arraybuffer';
RudderWebSockets[name] = socket;
socket.onopen = function () {
SendMessage(name, 'OnOpen', 'opened');
};
socket.onmessage = function (event) {
var bytes;
if (typeof event.data === 'string') {
// Text frame: UTF-8 encode, then base64 (the C# side decodes base64 to bytes).
bytes = new TextEncoder().encode(event.data);
} else {
bytes = new Uint8Array(event.data);
}
SendMessage(name, 'OnMessage', RudderWebSocketBase64(bytes));
};
socket.onerror = function () {
SendMessage(name, 'OnError', 'WebSocket error');
};
socket.onclose = function () {
delete RudderWebSockets[name];
SendMessage(name, 'OnClose', 'closed');
};
},
RudderWebSocketSend: function (gameObjectName, data, length) {
var socket = RudderWebSockets[UTF8ToString(gameObjectName)];
if (!socket || socket.readyState !== WebSocket.OPEN) return;
socket.send(HEAPU8.subarray(data, data + length));
},
RudderWebSocketClose: function (gameObjectName) {
var name = UTF8ToString(gameObjectName);
var socket = RudderWebSockets[name];
if (socket) {
delete RudderWebSockets[name];
socket.close();
}
}
});
@@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: 3f90f5c02b3cd42e8a599649ae0a142d
@@ -11,16 +11,12 @@ namespace RudderSdk.Unity
var clientOptions = new RudderClientOptions
{
BaseUrl = options.BaseUrl,
RealtimeUrl = options.RealtimeUrl,
ProjectKey = options.ProjectKey,
Logger = new UnityLoggerAdapter(options.LoggerSink ?? new UnityDebugLoggerSink()),
Transport = new UnityTransportAdapter(options.BaseUrl, executor),
TokenStore = new UnityTokenStoreAdapter(options.KeyValueStore),
DeviceIdProvider = new UnityDeviceIdProvider(),
Clock = new UnityClock(),
PlanStateStore = new UnityPlanStateStore(options.KeyValueStore),
Scheduler = new UnityPlanScheduler(),
RealtimeTransportFactory = new UnityRealtimeTransportFactory()
Clock = new UnityClock()
};
return new RudderClient(clientOptions);
@@ -3,7 +3,6 @@ namespace RudderSdk.Unity
public class RudderUnityClientOptions
{
public string BaseUrl { get; set; }
public string RealtimeUrl { get; set; }
public string ProjectKey { get; set; }
public int TimeoutSeconds { get; set; } = 10;
public IUnityKeyValueStore KeyValueStore { get; set; }
@@ -1,15 +0,0 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using RudderSdk.Core.Abstractions;
namespace RudderSdk.Unity
{
internal class UnityPlanScheduler : IPlanScheduler
{
public Task ScheduleAsync(TimeSpan delay, CancellationToken cancellationToken = default)
{
return Task.Delay(delay, cancellationToken);
}
}
}
@@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: f4f8e4e8237be445c96672d96294c6c7
@@ -1,30 +0,0 @@
using RudderSdk.Core.Abstractions;
namespace RudderSdk.Unity
{
internal class UnityPlanStateStore : IPlanStateStore
{
private const string KEY = "liveops_plan_runner_state";
private readonly IUnityKeyValueStore _store;
public UnityPlanStateStore(IUnityKeyValueStore store)
{
_store = store;
}
public string State
{
get => _store.GetString(KEY);
set
{
if (string.IsNullOrEmpty(value))
_store.DeleteKey(KEY);
else
_store.SetString(KEY, value);
_store.Save();
}
}
}
}
@@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: 118ea3286be8b4daab53eaf7885507a0
@@ -1,51 +0,0 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using RudderSdk.Core.Abstractions;
namespace RudderSdk.Unity
{
internal sealed class UnityRealtimeTransportFactory : IRealtimeTransportFactory
{
public IRealtimeTransport Create()
{
#if UNITY_WEBGL && !UNITY_EDITOR
return new UnityRealtimeTransport(new JsWebSocketAdapter());
#else
return new UnityRealtimeTransport(new NativeWebSocketAdapter());
#endif
}
}
internal sealed class UnityRealtimeTransport : IRealtimeTransport
{
private readonly IWebSocketAdapter _adapter;
public UnityRealtimeTransport(IWebSocketAdapter adapter)
{
_adapter = adapter;
_adapter.Closed += () => Closed?.Invoke();
_adapter.Received += data => Received?.Invoke(data);
_adapter.ReceivedError += ex => Error?.Invoke(ex);
}
public event Action Closed;
public event Action<ArraySegment<byte>> Received;
public event Action<Exception> Error;
public bool IsConnected => _adapter.IsConnected;
public Task ConnectAsync(Uri uri, TimeSpan timeout, CancellationToken cancellationToken = default)
=> _adapter.ConnectAsync(uri, (int)Math.Ceiling(timeout.TotalSeconds), cancellationToken);
public Task SendAsync(ArraySegment<byte> data, CancellationToken cancellationToken = default)
=> _adapter.SendAsync(data, cancellationToken);
public Task CloseAsync(CancellationToken cancellationToken = default)
=> _adapter.CloseAsync();
public void Update(float deltaTime)
{
}
}
}
@@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: be75d4878806d40648e49338f0ecd508
@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: 3c34eb0ba13fe47eab84ba9a30d8bdb6
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,22 +0,0 @@
using System;
using System.Threading;
using System.Threading.Tasks;
namespace RudderSdk.Unity
{
/// <summary>
/// Interface for WebSocket transport adapters used by the realtime transport bridge.
/// Provides connect, send, close, and main-thread event dispatch for WebSocket connections.
/// </summary>
public interface IWebSocketAdapter
{
event Action Closed;
event Action<ArraySegment<byte>> Received;
event Action<Exception> ReceivedError;
bool IsConnected { get; }
bool IsConnecting { get; }
Task ConnectAsync(Uri uri, int timeoutSeconds, CancellationToken cancellationToken = default);
Task CloseAsync();
Task SendAsync(ArraySegment<byte> data, CancellationToken cancellationToken = default);
}
}
@@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: a7216258d1bc14b1699fce5966a73073
@@ -1,312 +0,0 @@
#if UNITY_WEBGL && !UNITY_EDITOR
using System.Runtime.InteropServices;
#endif
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
namespace RudderSdk.Unity
{
/// <summary>
/// WebGL WebSocket adapter using JavaScript interop via DllImport("__Internal__").
/// Uses SendMessage callbacks from JS to route WebSocket events to Unity's main thread.
/// Only functional in WebGL builds; throws PlatformNotSupportedException elsewhere.
/// </summary>
public sealed class JsWebSocketAdapter : IWebSocketAdapter, IDisposable
{
#if UNITY_WEBGL && !UNITY_EDITOR
[DllImport("__Internal__")]
private static extern void RudderWebSocketCreate(string gameObjectName, string url);
[DllImport("__Internal__")]
private static extern void RudderWebSocketSend(string gameObjectName, byte[] data, int length);
[DllImport("__Internal__")]
private static extern void RudderWebSocketClose(string gameObjectName);
#endif
private CancellationTokenSource _cts;
private readonly ConcurrentQueue<Action> _eventQueue = new();
private JsWebSocketBridge _bridge;
private TaskCompletionSource<bool> _connectionTcs;
private volatile bool _isConnected;
private volatile bool _isConnecting;
private bool _disposed;
/// <summary>
/// Fired when the WebSocket connection is closed.
/// </summary>
public event Action Closed;
/// <summary>
/// Fired when binary data is received from the server.
/// </summary>
public event Action<ArraySegment<byte>> Received;
/// <summary>
/// Fired when an error occurs on the WebSocket.
/// </summary>
public event Action<Exception> ReceivedError;
/// <summary>
/// True when the WebSocket connection is open.
/// </summary>
public bool IsConnected => _isConnected;
/// <summary>
/// True while the WebSocket connection is being established.
/// </summary>
public bool IsConnecting => _isConnecting;
public JsWebSocketAdapter()
{
var go = new GameObject("JsWebSocketBridge");
UnityEngine.Object.DontDestroyOnLoad(go);
_bridge = go.AddComponent<JsWebSocketBridge>();
_bridge.Init(this);
}
/// <summary>
/// Connects to the specified WebSocket URI via the JavaScript WebSocket API.
/// </summary>
/// <param name="uri">The WebSocket server URI (ws:// or wss://).</param>
/// <param name="timeoutSeconds">Connection timeout in seconds.</param>
/// <param name="cancellationToken">Optional cancellation token.</param>
/// <exception cref="ArgumentNullException">Thrown when uri is null.</exception>
/// <exception cref="ArgumentOutOfRangeException">Thrown when timeoutSeconds is not positive.</exception>
/// <exception cref="TimeoutException">Thrown when the connection attempt times out.</exception>
/// <exception cref="PlatformNotSupportedException">Thrown when not running in WebGL.</exception>
public Task ConnectAsync(Uri uri, int timeoutSeconds, CancellationToken cancellationToken = default)
{
if (uri == null)
throw new ArgumentNullException(nameof(uri));
if (timeoutSeconds <= 0)
throw new ArgumentOutOfRangeException(nameof(timeoutSeconds), "Timeout must be greater than zero.");
#if UNITY_WEBGL && !UNITY_EDITOR
_isConnecting = true;
_cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
_connectionTcs = new TaskCompletionSource<bool>();
// Register cancellation (including timeout)
_cts.Token.Register(() =>
{
if (_connectionTcs?.TrySetException(
new TimeoutException($"WebSocket connection timed out after {timeoutSeconds} seconds.")) == true)
{
_isConnecting = false;
}
});
_cts.CancelAfter(TimeSpan.FromSeconds(timeoutSeconds));
RudderWebSocketCreate(_bridge.gameObject.name, uri.ToString());
return _connectionTcs.Task;
#else
// Not available outside WebGL builds; editor test uses NativeWebSocketAdapter.
return Task.FromException(new PlatformNotSupportedException(
"JsWebSocketAdapter is only supported on WebGL. Use NativeWebSocketAdapter for other platforms."));
#endif
}
/// <summary>
/// Gracefully closes the WebSocket connection via the JavaScript WebSocket API.
/// </summary>
public Task CloseAsync()
{
#if UNITY_WEBGL && !UNITY_EDITOR
RudderWebSocketClose(_bridge.gameObject.name);
#endif
_cts?.Cancel();
_isConnected = false;
_isConnecting = false;
EnqueueEvent(() => Closed?.Invoke());
return Task.CompletedTask;
}
/// <summary>
/// Sends binary data over the WebSocket via the JavaScript WebSocket API.
/// </summary>
public Task SendAsync(ArraySegment<byte> data, CancellationToken cancellationToken = default)
{
if (!_isConnected) return Task.CompletedTask;
#if UNITY_WEBGL && !UNITY_EDITOR
byte[] arr;
int offset;
int count;
if (data.Offset == 0 && data.Count == data.Array.Length)
{
arr = data.Array;
offset = 0;
count = data.Count;
}
else
{
// Copy to a contiguous buffer since DllImport needs a pinned array from offset 0
arr = new byte[data.Count];
System.Buffer.BlockCopy(data.Array, data.Offset, arr, 0, data.Count);
offset = 0;
count = data.Count;
}
RudderWebSocketSend(_bridge.gameObject.name, arr, count);
#endif
return Task.CompletedTask;
}
/// <summary>
/// Disposes the adapter, cleaning up the bridge GameObject.
/// </summary>
public void Dispose()
{
if (_disposed) return;
_disposed = true;
#if UNITY_WEBGL && !UNITY_EDITOR
RudderWebSocketClose(_bridge.gameObject.name);
#endif
_cts?.Cancel();
_cts?.Dispose();
if (_bridge != null && _bridge.gameObject != null)
{
UnityEngine.Object.Destroy(_bridge.gameObject);
}
}
/// <summary>
/// Called by JsWebSocketBridge when the JS WebSocket onopen fires.
/// </summary>
internal void HandleOpen()
{
_isConnected = true;
_isConnecting = false;
_connectionTcs?.TrySetResult(true);
}
/// <summary>
/// Called by JsWebSocketBridge when the JS WebSocket onclose fires.
/// </summary>
internal void HandleClose()
{
_isConnected = false;
_isConnecting = false;
_connectionTcs?.TrySetCanceled();
Closed?.Invoke();
}
/// Called by JsWebSocketBridge when the JS WebSocket onerror fires.
/// </summary>
internal void HandleError(string errorMessage)
{
_isConnecting = false;
_connectionTcs?.TrySetException(new Exception(errorMessage));
ReceivedError?.Invoke(new Exception(errorMessage));
}
/// Called by JsWebSocketBridge when binary message data is received.
/// </summary>
internal void HandleMessage(ArraySegment<byte> data)
{
Received?.Invoke(data);
}
internal void HandleMessageError(Exception ex)
{
ReceivedError?.Invoke(ex);
}
internal void EnqueueEvent(Action action)
{
_eventQueue.Enqueue(action);
}
internal void ProcessEvents()
{
while (_eventQueue.TryDequeue(out var action))
{
try
{
action?.Invoke();
}
catch (Exception ex)
{
Debug.LogException(ex);
}
}
}
}
/// <summary>
/// MonoBehaviour that receives SendMessage callbacks from the JavaScript WebSocket bridge
/// and dispatches events on the Unity main thread.
/// </summary>
internal class JsWebSocketBridge : MonoBehaviour
{
private JsWebSocketAdapter _adapter;
public void Init(JsWebSocketAdapter adapter)
{
_adapter = adapter;
}
/// <summary>
/// Called from JavaScript via SendMessage when the WebSocket connection opens.
/// </summary>
public void OnOpen(string _)
{
_adapter?.EnqueueEvent(() => _adapter?.HandleOpen());
}
/// <summary>
/// Called from JavaScript via SendMessage when binary data is received.
/// Data is base64-encoded by the JS bridge and decoded here.
/// </summary>
public void OnMessage(string base64Data)
{
if (string.IsNullOrEmpty(base64Data) || _adapter == null) return;
try
{
var data = Convert.FromBase64String(base64Data);
var segment = new ArraySegment<byte>(data);
_adapter.EnqueueEvent(() => _adapter.HandleMessage(segment));
}
catch (FormatException ex)
{
Debug.LogError($"JsWebSocketBridge: Failed to decode base64 message: {ex.Message}");
_adapter.EnqueueEvent(() => _adapter.HandleMessageError(ex));
}
}
/// <summary>
/// Called from JavaScript via SendMessage when the WebSocket connection closes.
/// </summary>
public void OnClose(string _)
{
_adapter?.EnqueueEvent(() => _adapter?.HandleClose());
}
/// <summary>
/// Called from JavaScript via SendMessage when a WebSocket error occurs.
/// </summary>
public void OnError(string error)
{
_adapter?.EnqueueEvent(() => _adapter?.HandleError(error ?? "Unknown WebSocket error"));
}
private void Update()
{
_adapter?.ProcessEvents();
}
private void OnDestroy()
{
_adapter?.Dispose();
_adapter = null;
}
}
}
@@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: e53d8ae2e7487470280f0da178c56cf8
@@ -1,233 +0,0 @@
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
namespace RudderSdk.Unity
{
/// <summary>
/// Native WebSocket adapter using System.Net.WebSockets.ClientWebSocket.
/// Dispatches received events to the Unity main thread via a MonoBehaviour Update loop.
/// </summary>
public sealed class NativeWebSocketAdapter : IWebSocketAdapter, IDisposable
{
private ClientWebSocket _ws;
private CancellationTokenSource _cts;
private readonly WebSocketDispatcher _dispatcher;
private readonly ConcurrentQueue<Action> _eventQueue = new();
private bool _disposed;
/// <summary>
/// Fired when the WebSocket connection is closed.
/// </summary>
public event Action Closed;
/// <summary>
/// Fired when binary data is received from the server.
/// </summary>
public event Action<ArraySegment<byte>> Received;
/// <summary>
/// Fired when an error occurs on the receive loop.
/// </summary>
public event Action<Exception> ReceivedError;
/// <summary>
/// True when the WebSocket is in the Open state.
/// </summary>
public bool IsConnected => _ws?.State == WebSocketState.Open;
/// <summary>
/// True when the WebSocket is in the Connecting state.
/// </summary>
public bool IsConnecting => _ws?.State == WebSocketState.Connecting;
public NativeWebSocketAdapter()
{
var go = new GameObject("WebSocketDispatcher");
UnityEngine.Object.DontDestroyOnLoad(go);
_dispatcher = go.AddComponent<WebSocketDispatcher>();
_dispatcher.Init(this);
}
/// <summary>
/// Connects to the specified WebSocket URI.
/// </summary>
/// <param name="uri">The WebSocket server URI (ws:// or wss://).</param>
/// <param name="timeoutSeconds">Connection timeout in seconds.</param>
/// <param name="cancellationToken">Optional cancellation token.</param>
/// <exception cref="ArgumentNullException">Thrown when uri is null.</exception>
/// <exception cref="ArgumentOutOfRangeException">Thrown when timeoutSeconds is not positive.</exception>
/// <exception cref="TimeoutException">Thrown when the connection attempt times out.</exception>
public async Task ConnectAsync(Uri uri, int timeoutSeconds, CancellationToken cancellationToken = default)
{
if (uri == null)
throw new ArgumentNullException(nameof(uri));
if (timeoutSeconds <= 0)
throw new ArgumentOutOfRangeException(nameof(timeoutSeconds), "Timeout must be greater than zero.");
_cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
_ws = new ClientWebSocket();
_ws.Options.KeepAliveInterval = TimeSpan.FromSeconds(30);
using var timeoutCts = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutSeconds));
using var linked = CancellationTokenSource.CreateLinkedTokenSource(_cts.Token, timeoutCts.Token);
try
{
await _ws.ConnectAsync(uri, linked.Token);
_ = ReceiveLoop();
}
catch (OperationCanceledException) when (timeoutCts.IsCancellationRequested)
{
throw new TimeoutException($"WebSocket connection timed out after {timeoutSeconds} seconds.");
}
}
/// <summary>
/// Gracefully closes the WebSocket connection.
/// </summary>
public async Task CloseAsync()
{
if (_ws?.State == WebSocketState.Open)
{
try
{
await _ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "Client closing", CancellationToken.None);
}
catch
{
// Best-effort close
}
}
_cts?.Cancel();
EnqueueEvent(() => Closed?.Invoke());
}
/// <summary>
/// Sends binary data over the WebSocket. WebSocket transport is always reliable,
/// so no reliability parameter is needed.
/// </summary>
public async Task SendAsync(ArraySegment<byte> data, CancellationToken cancellationToken = default)
{
if (_ws?.State != WebSocketState.Open)
return;
await _ws.SendAsync(data, WebSocketMessageType.Binary, true, cancellationToken);
}
/// <summary>
/// Disposes the adapter, cancelling any in-flight operations and cleaning up the dispatcher GameObject.
/// </summary>
public void Dispose()
{
if (_disposed) return;
_disposed = true;
_cts?.Cancel();
_cts?.Dispose();
_ws?.Dispose();
if (_dispatcher != null && _dispatcher.gameObject != null)
{
UnityEngine.Object.Destroy(_dispatcher.gameObject);
}
}
private async Task ReceiveLoop()
{
var buffer = new byte[65536];
try
{
while (!_cts.IsCancellationRequested && _ws.State == WebSocketState.Open)
{
using (var ms = new MemoryStream())
{
WebSocketReceiveResult result;
do
{
result = await _ws.ReceiveAsync(new ArraySegment<byte>(buffer), _cts.Token);
ms.Write(buffer, 0, result.Count);
} while (!result.EndOfMessage);
if (result.MessageType == WebSocketMessageType.Close)
{
try
{
await _ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
}
catch
{
// Best-effort close
}
EnqueueEvent(() => Closed?.Invoke());
return;
}
var data = ms.ToArray();
EnqueueEvent(() => Received?.Invoke(new ArraySegment<byte>(data)));
}
}
}
catch (OperationCanceledException)
{
// Normal cancellation, no action needed
}
catch (Exception ex) when (!_disposed)
{
EnqueueEvent(() => ReceivedError?.Invoke(ex));
EnqueueEvent(() => Closed?.Invoke());
}
}
internal void EnqueueEvent(Action action)
{
_eventQueue.Enqueue(action);
}
internal void ProcessEvents()
{
while (_eventQueue.TryDequeue(out var action))
{
try
{
action?.Invoke();
}
catch (Exception ex)
{
Debug.LogException(ex);
}
}
}
}
/// <summary>
/// MonoBehaviour used to dispatch WebSocket events on the Unity main thread via Update.
/// Created and managed by NativeWebSocketAdapter.
/// </summary>
internal class WebSocketDispatcher : MonoBehaviour
{
private NativeWebSocketAdapter _adapter;
public void Init(NativeWebSocketAdapter adapter)
{
_adapter = adapter;
}
private void Update()
{
_adapter?.ProcessEvents();
}
private void OnDestroy()
{
_adapter?.Dispose();
_adapter = null;
}
}
}
@@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: 508609c897805437dab5527c21c9f914
+58 -92
View File
@@ -15,8 +15,8 @@ namespace RudderSdk.Unity
/// <summary>
/// Scene bootstrap MonoBehaviour and public entrypoint of the Rudder Unity SDK.
/// Add the component to a scene with a RudderConfiguration assigned, or call
/// Rudder.Initialize(configuration) and the hidden GameObject is created for you.
/// Put this on a startup scene object, assign a RudderConfiguration, then call
/// <see cref="Initialize"/>. Feature calls live on the returned Core client.
/// </summary>
[DefaultExecutionOrder(-1500), DisallowMultipleComponent]
public class Rudder : MonoBehaviour
@@ -43,33 +43,77 @@ namespace RudderSdk.Unity
if (State != RudderState.Ready || _client == null)
{
throw new InvalidOperationException(
"Rudder is not initialized. Add the Rudder component to the scene with a " +
"RudderConfiguration assigned, or call Rudder.Initialize(configuration).");
"Rudder is not initialized. Add the Rudder component to a scene with a " +
"RudderConfiguration assigned, then call Rudder.Initialize().");
}
return _client;
}
}
/// Completes with the initialized client, or faults with the initialization error.
/// Completes with the client after <see cref="Initialize"/>, or faults on
/// the initialization error. Prefer <see cref="Initialize"/> in game code.
public static Task<CoreClient> Ready => _readyCompletion.Task;
public static void Initialize(RudderConfiguration configuration)
public static CoreClient Initialize()
{
if (configuration == null)
throw new ArgumentNullException(nameof(configuration));
if (State == RudderState.Ready && _client != null)
return _client;
if (State == RudderState.Initializing || State == RudderState.Ready)
throw new InvalidOperationException("Rudder is already initialized.");
if (State == RudderState.Failed)
{
_readyCompletion = NewCompletion();
LastError = null;
State = RudderState.NotInitialized;
}
if (_instance == null)
{
var host = new GameObject(nameof(Rudder));
_instance = host.AddComponent<Rudder>();
throw new InvalidOperationException(
"Rudder is not in the scene. Add the Rudder component to a startup scene " +
"and assign a RudderConfiguration.");
}
_instance._configuration = configuration;
_ = _instance.InitializeAsync();
if (_instance._configuration == null)
{
throw new InvalidOperationException(
"Rudder has no configuration. Assign a RudderConfiguration on the Rudder " +
"component (Assets > Create > Rudder > Configuration).");
}
try
{
State = RudderState.Initializing;
LastError = null;
var options = new RudderUnityClientOptions
{
BaseUrl = _instance._configuration.BaseUrl,
ProjectKey = _instance._configuration.ProjectKey,
TimeoutSeconds = _instance._configuration.TimeoutSeconds,
KeyValueStore = new PlayerPrefsUnityKeyValueStore(),
LoggerSink = new UnityDebugLoggerSink()
};
_client = RudderUnityClientFactory.Create(options);
}
catch (Exception exception)
{
_client = null;
State = RudderState.Failed;
LastError = exception;
_readyCompletion.TrySetException(exception);
Debug.LogError(
"[Rudder] Failed to initialize the Rudder SDK. Check the RudderConfiguration asset " +
$"(ProjectKey and BaseUrl must be set). {exception.Message}");
throw;
}
State = RudderState.Ready;
Debug.Log("[Rudder] Rudder SDK initialized.");
_readyCompletion.TrySetResult(_client);
Initialized?.Invoke(_client);
return _client;
}
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
@@ -95,75 +139,16 @@ namespace RudderSdk.Unity
DontDestroyOnLoad(gameObject);
}
private void Start()
{
if (_instance == this && _configuration != null && State == RudderState.NotInitialized)
_ = InitializeAsync();
}
private async Task InitializeAsync()
{
State = RudderState.Initializing;
LastError = null;
try
{
var options = new RudderUnityClientOptions
{
BaseUrl = _configuration.BaseUrl,
RealtimeUrl = _configuration.RealtimeUrl,
ProjectKey = _configuration.ProjectKey,
TimeoutSeconds = _configuration.TimeoutSeconds,
KeyValueStore = new PlayerPrefsUnityKeyValueStore(),
LoggerSink = new UnityDebugLoggerSink()
};
_client = RudderUnityClientFactory.Create(options);
try
{
await _client.Scenario.RestoreAsync();
}
catch (Exception restoreException)
{
Debug.LogWarning("[Rudder] Failed to restore scenario state: " + restoreException.Message);
}
}
catch (Exception exception)
{
_client = null;
State = RudderState.Failed;
LastError = exception;
_readyCompletion.TrySetException(exception);
Debug.LogError(
"[Rudder] Failed to initialize the Rudder SDK. Check the RudderConfiguration asset " +
$"(ProjectKey and BaseUrl must be set). {exception.Message}");
return;
}
State = RudderState.Ready;
Debug.Log("[Rudder] Rudder SDK initialized.");
_readyCompletion.TrySetResult(_client);
Initialized?.Invoke(_client);
}
private void Update()
{
_client?.Update(Time.deltaTime);
}
private void OnApplicationQuit()
{
DisconnectRealtime();
}
private void OnDestroy()
{
if (_instance != this)
return;
DisconnectRealtime();
_instance = null;
_client = null;
State = RudderState.NotInitialized;
@@ -172,25 +157,6 @@ namespace RudderSdk.Unity
_readyCompletion = NewCompletion();
}
private void DisconnectRealtime()
{
var client = _client;
if (client == null)
return;
try
{
_ = client.Realtime.DisconnectAsync().ContinueWith(
task => Debug.LogWarning(
"[Rudder] Realtime disconnect failed: " + task.Exception?.GetBaseException().Message),
TaskContinuationOptions.OnlyOnFaulted);
}
catch (Exception exception)
{
Debug.LogWarning("[Rudder] Realtime disconnect failed: " + exception.Message);
}
}
private static TaskCompletionSource<CoreClient> NewCompletion()
{
return new TaskCompletionSource<CoreClient>(TaskCreationOptions.RunContinuationsAsynchronously);
@@ -11,9 +11,6 @@ namespace RudderSdk.Unity
[Tooltip("API base URL, e.g. https://api.rudder.build.")]
public string BaseUrl = "https://api.rudder.build";
[Tooltip("Realtime websocket URL. The relay is not deployed yet; set this only once it is.")]
public string RealtimeUrl = "wss://api.rudder.build/api/realtime/ws";
[Tooltip("HTTP request timeout in seconds.")]
[Min(1)]
public int TimeoutSeconds = 10;