using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Cysharp.Threading.Tasks; using UnityEngine; using UnityEngine.Networking; namespace HotPatch { public sealed class HotPatchLocalResources { public string RootPath { get; } public HotPatchManifest Manifest { get; } public HotPatchManifest BundledManifest { get; } public HotPatchLocalResources(string rootPath, HotPatchManifest manifest, HotPatchManifest bundledManifest) { RootPath = rootPath; Manifest = manifest; BundledManifest = bundledManifest; } public string GetPath(HotPatchResource resource) => Path.Combine(RootPath, resource.RelativePath); } public static class HotPatchResourceStore { public const string ManifestFileName = "manifest.json"; public static async UniTask LoadBundledAsync(Uri bundledManifestUri, string cacheDirectory, string assemblyName, string platform, Action progress, CancellationToken ct, string sceneName = null) { progress?.Invoke(new HotPatchProgress("Checking version", 0)); var json = await ReadTextAsync(bundledManifestUri, ct); var manifest = Parse(json); ValidateBundledManifest(manifest, assemblyName, platform, sceneName); var root = Path.Combine(cacheDirectory, "LocalTest", HotPatchHash.Of(Encoding.UTF8.GetBytes(json))); var resources = new[] { manifest.aotBundle }.Concat(manifest.resources).ToArray(); HotPatchLog.Info("local_test_cache path=" + root + " version=" + manifest.version); for (int i = 0; i < resources.Length; i++) { ct.ThrowIfCancellationRequested(); var resource = resources[i]; var destination = Path.Combine(root, resource.RelativePath); if (!IsVerified(destination, resource)) await DownloadFileAsync(new Uri(bundledManifestUri, resource.RelativePath), destination, resource, bytes => progress?.Invoke(new HotPatchProgress("Checking version", .8f * (i + (float)bytes / resource.size) / resources.Length)), ct); } ct.ThrowIfCancellationRequested(); SaveManifest(Path.Combine(root, ManifestFileName), manifest); HotPatchLog.Info("local_test_ready version=" + manifest.version + " remote_requests=0"); progress?.Invoke(new HotPatchProgress("Loading resources", .8f)); return new HotPatchLocalResources(root, manifest, manifest); } static void ValidateBundledManifest(HotPatchManifest manifest, string assemblyName, string platform, string sceneName) { manifest.Validate(assemblyName, platform, sceneName); if (manifest.aotBundle == null || manifest.aotMetadata == null || !manifest.aotMetadata.Select(r => r.name).OrderBy(n => n).SequenceEqual(HotPatchBundleLoader.AotAssemblyNames.OrderBy(n => n))) throw new InvalidDataException("Original resources must include an AOT bundle and verification records for all four AOT DLLs."); } public static async UniTask SynchronizeAsync(Uri bundledManifestUri, Uri remoteManifestUri, string cacheDirectory, string assemblyName, string platform, Action progress, CancellationToken ct, string sceneName = null) { remoteManifestUri = RemoteManifestUri(remoteManifestUri?.AbsoluteUri); var elapsed = System.Diagnostics.Stopwatch.StartNew(); HotPatchLog.Info($"sync_start assembly={assemblyName} platform={platform} bundled={HotPatchLog.SafeUrl(bundledManifestUri)} remote={HotPatchLog.SafeUrl(remoteManifestUri)}"); progress?.Invoke(new HotPatchProgress("Checking version", 0)); var original = Parse(await ReadTextAsync(bundledManifestUri, ct)); HotPatchLog.Info($"bundled_manifest platform={original.platform} build={original.playerBuildId} version={original.version}"); ValidateBundledManifest(original, assemblyName, platform, sceneName); var root = Path.Combine(cacheDirectory, HotPatchHash.Of(Encoding.UTF8.GetBytes(original.playerBuildId))); Directory.CreateDirectory(root); HotPatchLog.Info("cache_path path=" + root); var manifestPath = Path.Combine(root, ManifestFileName); var aotMetadata = original.aotMetadata ?? Array.Empty(); var aotPath = Path.Combine(root, original.aotBundle.RelativePath); if (!IsVerified(aotPath, original.aotBundle)) await DownloadFileAsync(new Uri(bundledManifestUri, original.aotBundle.RelativePath), aotPath, original.aotBundle, bytes => progress?.Invoke(new HotPatchProgress("Checking version", .1f * (float)bytes / original.aotBundle.size)), ct); var local = TryReadLocal(manifestPath, original); if (local != null && !local.resources.Any(r => IsVerified(Path.Combine(root, r.RelativePath), r))) local = null; if (local == null) { HotPatchLog.Info("cache_restore source=StreamingAssets reason=missing_or_invalid"); for (int i = 0; i < original.resources.Length; i++) { var resource = original.resources[i]; var destination = Path.Combine(root, resource.RelativePath); if (!IsVerified(destination, resource)) await DownloadFileAsync(new Uri(bundledManifestUri, resource.RelativePath), destination, resource, bytes => progress?.Invoke(new HotPatchProgress("Checking version", .1f + .1f * (i + (float)bytes / resource.size) / original.resources.Length)), ct); ct.ThrowIfCancellationRequested(); } local = Parse(JsonUtility.ToJson(original)); SaveManifest(manifestPath, local); } else HotPatchLog.Info("cache_reuse version=" + local.version); progress?.Invoke(new HotPatchProgress("Checking version", .2f)); var fresh = new UriBuilder(remoteManifestUri); fresh.Query = fresh.Query.TrimStart('?') + (fresh.Query.Length > 0 ? "&" : "") + "hotpatch=" + DateTime.UtcNow.Ticks; var remote = Parse(await ReadTextAsync(fresh.Uri, ct, true)); HotPatchLog.Info($"remote_manifest platform={remote.platform} build={remote.playerBuildId} version={remote.version}"); remote.ValidateAgainst(original); var previous = local.resources.ToDictionary(r => r.name, StringComparer.OrdinalIgnoreCase); var changed = remote.resources.Where(resource => !previous.TryGetValue(resource.name, out var old) || !resource.SameContent(old) || !IsVerified(Path.Combine(root, resource.RelativePath), resource)).ToArray(); changed = changed.Where(r => !IsVerified(Path.Combine(root, r.RelativePath), r)).ToArray(); long total = changed.Sum(r => checked(r.size)), completed = 0; HotPatchLog.Info($"version_compare local={local.version} remote={remote.version} changedFiles={changed.Length} transferBytes={total}"); foreach (var resource in changed) { ct.ThrowIfCancellationRequested(); var bundled = original.resources.FirstOrDefault(r => r.SameContent(resource)); var source = new Uri(bundled != null ? bundledManifestUri : remoteManifestUri, resource.RelativePath); await DownloadFileAsync(source, Path.Combine(root, resource.RelativePath), resource, bytes => progress?.Invoke(new HotPatchProgress(bundled != null ? "Repairing local resources" : "Downloading updates", .2f + .6f * (float)((completed + (double)bytes) / Math.Max(1, total)), (ulong)completed + bytes, total)), ct); completed += resource.size; } ct.ThrowIfCancellationRequested(); remote.aotMetadata = aotMetadata; remote.aotBundle = original.aotBundle; bool unchanged = local.SameVersion(remote); if (!unchanged) SaveManifest(manifestPath, remote); HotPatchLog.Info("manifest_" + (unchanged ? "unchanged" : "committed") + " path=" + manifestPath); RemoveObsoleteFiles(root, remote); HotPatchLog.Info($"sync_complete version={remote.version} changedFiles={changed.Length} transferBytes={total} elapsedMs={elapsed.ElapsedMilliseconds}"); progress?.Invoke(new HotPatchProgress(unchanged && changed.Length == 0 ? "Resources are up to date" : "Local resources updated", .8f, (ulong)total, total)); return new HotPatchLocalResources(root, remote, original); } static HotPatchManifest TryReadLocal(string path, HotPatchManifest original) { if (!File.Exists(path)) return null; try { var manifest = Parse(File.ReadAllText(path)); manifest.ValidateAgainst(original); return manifest; } catch (Exception e) when (e is IOException || e is ArgumentException || e is InvalidOperationException) { HotPatchLog.Warning("cache_manifest_invalid path=" + path + " reason=" + e.Message); return null; } } public static HotPatchManifest Parse(string json) => JsonUtility.FromJson(json) ?? throw new InvalidDataException("The resource manifest is empty."); public static bool IsVerified(string path, HotPatchResource resource) => File.Exists(path) && new FileInfo(path).Length == resource.size && string.Equals(HotPatchHash.OfFile(path), resource.sha256, StringComparison.OrdinalIgnoreCase); static void SaveManifest(string path, HotPatchManifest manifest) { var temp = path + "." + Guid.NewGuid().ToString("N") + ".tmp"; try { File.WriteAllText(temp, JsonUtility.ToJson(manifest, true), new UTF8Encoding(false)); CommitFile(temp, path); } finally { if (File.Exists(temp)) File.Delete(temp); } } static void RemoveObsoleteFiles(string root, HotPatchManifest manifest) { var retained = new HashSet(manifest.resources.Select(r => Path.GetFileName(r.RelativePath)), StringComparer.OrdinalIgnoreCase); var files = Path.Combine(root, "files"); if (!Directory.Exists(files)) return; foreach (var file in Directory.GetFiles(files)) { var name = Path.GetFileName(file); if (retained.Contains(name) || !Regex.IsMatch(name, @"\A(?:[0-9a-f]{64}(?:\.bundle|(?:\.dll|\.bundle)?\.bytes)|download-[0-9a-f]{32}\.tmp)\z")) continue; File.Delete(file); } } public static Uri StreamingManifestUri() { return ManifestUriFromStreamingPath(Application.streamingAssetsPath); } public static Uri RemoteManifestUri(string downloadUrl) { if (!Uri.TryCreate(downloadUrl?.Trim(), UriKind.Absolute, out var uri)) throw new InvalidOperationException("Configure a valid hot patch DownloadUrl in AppSettings."); HotPatchHash.RequireHttp(uri); var builder = new UriBuilder(uri) { Fragment = string.Empty }; if (!builder.Path.EndsWith(".json", StringComparison.OrdinalIgnoreCase)) builder.Path = builder.Path.TrimEnd('/') + "/" + ManifestFileName; return builder.Uri; } public static Uri ManifestUriFromStreamingPath(string streamingAssetsPath) { var path = streamingAssetsPath.TrimEnd('/', '\\') + "/" + ManifestFileName; return new Uri(path.Contains("://") ? path : Path.GetFullPath(path)); } static async UniTask ReadTextAsync(Uri uri, CancellationToken ct, bool noCache = false) { var elapsed = System.Diagnostics.Stopwatch.StartNew(); HotPatchLog.Info("manifest_request url=" + HotPatchLog.SafeUrl(uri)); try { using var request = UnityWebRequest.Get(uri.AbsoluteUri); request.timeout = 30; if (noCache) request.SetRequestHeader("Cache-Control", "no-cache, no-store"); var operation = request.SendWebRequest(); while (!operation.isDone) { if (ct.IsCancellationRequested) { request.Abort(); ct.ThrowIfCancellationRequested(); } await UniTask.Yield(ct); } ct.ThrowIfCancellationRequested(); if (request.result != UnityWebRequest.Result.Success) throw RequestFailure("Failed to read resource manifest", uri, request); HotPatchLog.Info($"manifest_response url={HotPatchLog.SafeUrl(uri)} status={request.responseCode} bytes={request.downloadedBytes} elapsedMs={elapsed.ElapsedMilliseconds}"); return Encoding.UTF8.GetString(request.downloadHandler.data).TrimStart('\uFEFF'); } catch (Exception e) { HotPatchLog.Warning($"manifest_failed url={HotPatchLog.SafeUrl(uri)} elapsedMs={elapsed.ElapsedMilliseconds} type={e.GetType().Name} reason={e.Message}"); throw; } } static IOException RequestFailure(string message, Uri uri, UnityWebRequest request) => new IOException(message + ": HTTP " + request.responseCode + " / " + HotPatchLog.SafeUrl(uri) + " / " + request.error); public static async UniTask DownloadFileAsync(Uri uri, string destination, HotPatchResource resource, Action progress, CancellationToken ct) { var elapsed = System.Diagnostics.Stopwatch.StartNew(); bool remote = uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps; var action = remote ? "download" : "extract"; HotPatchLog.Info($"{action}_start name={resource.name} bytes={resource.size} sha256={resource.sha256} url={HotPatchLog.SafeUrl(uri)} destination={destination}"); Directory.CreateDirectory(Path.GetDirectoryName(destination)); var temp = Path.Combine(Path.GetDirectoryName(destination), "download-" + Guid.NewGuid().ToString("N") + ".tmp"); try { long nextProgressMs = 1000; using (var request = UnityWebRequest.Get(uri.AbsoluteUri)) { request.timeout = 30; request.downloadHandler.Dispose(); request.downloadHandler = new DownloadHandlerFile(temp) { removeFileOnAbort = true }; var operation = request.SendWebRequest(); while (!operation.isDone) { if (ct.IsCancellationRequested) { request.Abort(); ct.ThrowIfCancellationRequested(); } if (request.downloadedBytes > (ulong)resource.size) { request.Abort(); throw new InvalidDataException("The resource exceeds the size declared in the manifest: " + resource.name); } progress?.Invoke(request.downloadedBytes); if (elapsed.ElapsedMilliseconds >= nextProgressMs) { HotPatchLog.Info($"{action}_progress name={resource.name} bytes={request.downloadedBytes}/{resource.size} percent={Math.Min(100, request.downloadedBytes * 100d / resource.size):F0}"); nextProgressMs = elapsed.ElapsedMilliseconds + 1000; } await UniTask.Yield(ct); } ct.ThrowIfCancellationRequested(); if (request.result != UnityWebRequest.Result.Success) throw RequestFailure("Failed to read resource: " + resource.name, uri, request); HotPatchLog.Info($"{action}_response name={resource.name} status={request.responseCode} bytes={request.downloadedBytes}"); } if (!IsVerified(temp, resource)) throw new InvalidDataException("Resource size or SHA-256 verification failed: " + resource.name); CommitFile(temp, destination); HotPatchLog.Info($"{action}_complete name={resource.name} bytes={resource.size} percent=100 sha256=verified elapsedMs={elapsed.ElapsedMilliseconds} destination={destination}"); progress?.Invoke((ulong)resource.size); } catch (Exception e) { HotPatchLog.Warning($"{action}_failed name={resource.name} url={HotPatchLog.SafeUrl(uri)} elapsedMs={elapsed.ElapsedMilliseconds} type={e.GetType().Name} reason={e.Message}"); throw; } finally { if (File.Exists(temp)) File.Delete(temp); } } static void CommitFile(string temp, string destination) { if (File.Exists(destination)) File.Replace(temp, destination, null); else File.Move(temp, destination); } } }