// DorageClient.cs — drop into the Unity project (server build). // Stores/retrieves JSON documents per match on a Dorage API. // // Set two environment variables on the Edgegap app version: // DORAGE_URL = https://api.dorage.co.uk // DORAGE_KEY = dg_live_... // // Usage (from any MonoBehaviour): // StartCoroutine(DorageClient.Save(matchId, "start", jsonString, ok => Debug.Log(ok))); // StartCoroutine(DorageClient.Load(matchId, "end", (ok, json) => { ... })); // // Version history (previous versions kept per slot, default 3): // StartCoroutine(DorageClient.History(matchId, "start", (ok, json) => { // var v = JsonUtility.FromJson(json); // v.current.version, v.history[i].version // })); // StartCoroutine(DorageClient.LoadVersion(matchId, "start", 4, (ok, json) => { ... })); // StartCoroutine(DorageClient.Revert(matchId, "start", 4, ok => { ... })); // // Save() retries with backoff. If every attempt fails, the JSON is written to // Application.persistentDataPath/dorage-failed/ and logged, so nothing is // silently lost (copy it out of the container logs if needed). using System; using System.Collections; using System.IO; using System.Text; using UnityEngine; using UnityEngine.Networking; public static class DorageClient { static readonly string BaseUrl = (Environment.GetEnvironmentVariable("DORAGE_URL") ?? "https://api.dorage.co.uk").TrimEnd('/'); static readonly string ApiKey = Environment.GetEnvironmentVariable("DORAGE_KEY") ?? ""; public static int MaxAttempts = 5; public static int TimeoutSeconds = 10; static string Url(string matchId, string slot) => $"{BaseUrl}/v1/matches/{UnityWebRequest.EscapeURL(matchId)}/{UnityWebRequest.EscapeURL(slot)}"; /// Store a JSON string for a match slot (e.g. "start" or "end"). Overwrites if it exists. public static IEnumerator Save(string matchId, string slot, string json, Action done = null) { if (string.IsNullOrEmpty(ApiKey)) { Debug.LogError("[Dorage] DORAGE_KEY not set"); Fallback(matchId, slot, json); done?.Invoke(false); yield break; } byte[] body = Encoding.UTF8.GetBytes(json); float delay = 1f; for (int attempt = 1; attempt <= MaxAttempts; attempt++) { using (var req = new UnityWebRequest(Url(matchId, slot), "PUT")) { req.uploadHandler = new UploadHandlerRaw(body); req.downloadHandler = new DownloadHandlerBuffer(); req.SetRequestHeader("Content-Type", "application/json"); req.SetRequestHeader("Authorization", "Bearer " + ApiKey); req.timeout = TimeoutSeconds; yield return req.SendWebRequest(); long code = req.responseCode; if (req.result == UnityWebRequest.Result.Success && (code == 200 || code == 201)) { done?.Invoke(true); yield break; } // 4xx (except 429) won't fix themselves by retrying. bool retryable = code == 0 || code == 429 || code >= 500; Debug.LogWarning($"[Dorage] Save {matchId}/{slot} attempt {attempt} failed: HTTP {code} {req.error} {req.downloadHandler?.text}"); if (!retryable) break; } if (attempt < MaxAttempts) { yield return new WaitForSecondsRealtime(delay); delay *= 2f; } } Fallback(matchId, slot, json); done?.Invoke(false); } /// Fetch the current JSON for a match slot. ok=false and json=null if missing or failed. public static IEnumerator Load(string matchId, string slot, Action done) => Request("GET", Url(matchId, slot), $"Load {matchId}/{slot}", done); /// /// List versions for a slot. Returns JSON like: /// {"current":{"version":6,...},"history":[{"version":5,"size":..,"saved_at":".."},...]} /// Parse with JsonUtility into DorageVersions (below). /// public static IEnumerator History(string matchId, string slot, Action done) => Request("GET", Url(matchId, slot) + "/versions", $"History {matchId}/{slot}", done); /// Fetch a specific version's JSON (current or from history). public static IEnumerator LoadVersion(string matchId, string slot, int version, Action done) => Request("GET", Url(matchId, slot) + "/versions/" + version, $"LoadVersion {matchId}/{slot}/{version}", done); /// Make an old version current again. The version it replaces goes into history, so this can be undone. public static IEnumerator Revert(string matchId, string slot, int version, Action done = null) => Request("POST", Url(matchId, slot) + "/revert/" + version, $"Revert {matchId}/{slot} to {version}", (ok, _) => done?.Invoke(ok)); static IEnumerator Request(string method, string url, string label, Action done) { float delay = 1f; for (int attempt = 1; attempt <= MaxAttempts; attempt++) { using (var req = new UnityWebRequest(url, method)) { req.downloadHandler = new DownloadHandlerBuffer(); req.SetRequestHeader("Authorization", "Bearer " + ApiKey); req.timeout = TimeoutSeconds; yield return req.SendWebRequest(); long code = req.responseCode; if (req.result == UnityWebRequest.Result.Success && code == 200) { done(true, req.downloadHandler.text); yield break; } if (code == 404) { done(false, null); yield break; } bool retryable = code == 0 || code == 429 || code >= 500; Debug.LogWarning($"[Dorage] {label} attempt {attempt} failed: HTTP {code} {req.error} {req.downloadHandler?.text}"); if (!retryable) break; } if (attempt < MaxAttempts) { yield return new WaitForSecondsRealtime(delay); delay *= 2f; } } done(false, null); } [Serializable] public class DorageVersionInfo { public int version; public int size; public string saved_at; public string archived_at; } [Serializable] public class DorageVersions { public string match_id; public string slot; public DorageVersionInfo current; public DorageVersionInfo[] history; public int history_versions_kept; } static void Fallback(string matchId, string slot, string json) { try { string dir = Path.Combine(Application.persistentDataPath, "dorage-failed"); Directory.CreateDirectory(dir); string file = Path.Combine(dir, $"{matchId}_{slot}_{DateTime.UtcNow:yyyyMMddHHmmss}.json"); File.WriteAllText(file, json); Debug.LogError($"[Dorage] Gave up saving {matchId}/{slot}. Written to {file}. Payload: {json}"); } catch (Exception e) { Debug.LogError($"[Dorage] Gave up saving {matchId}/{slot} and fallback failed: {e.Message}. Payload: {json}"); } } }