HotPatchResourceStore.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Text.RegularExpressions;
  7. using System.Threading;
  8. using Cysharp.Threading.Tasks;
  9. using UnityEngine;
  10. using UnityEngine.Networking;
  11. namespace HotPatch
  12. {
  13. public sealed class HotPatchLocalResources
  14. {
  15. public string RootPath { get; }
  16. public HotPatchManifest Manifest { get; }
  17. public HotPatchManifest BundledManifest { get; }
  18. public HotPatchLocalResources(string rootPath, HotPatchManifest manifest, HotPatchManifest bundledManifest)
  19. { RootPath = rootPath; Manifest = manifest; BundledManifest = bundledManifest; }
  20. public string GetPath(HotPatchResource resource) => Path.Combine(RootPath, resource.RelativePath);
  21. }
  22. public static class HotPatchResourceStore
  23. {
  24. public const string ManifestFileName = "manifest.json";
  25. public static async UniTask<HotPatchLocalResources> SynchronizeAsync(Uri bundledManifestUri, Uri remoteManifestUri,
  26. string cacheDirectory, string assemblyName, string platform, Action<HotPatchProgress> progress, CancellationToken ct, string sceneName = null)
  27. {
  28. remoteManifestUri = RemoteManifestUri(remoteManifestUri?.AbsoluteUri);
  29. var elapsed = System.Diagnostics.Stopwatch.StartNew();
  30. HotPatchLog.Info($"sync_start assembly={assemblyName} platform={platform} bundled={HotPatchLog.SafeUrl(bundledManifestUri)} remote={HotPatchLog.SafeUrl(remoteManifestUri)}");
  31. progress?.Invoke(new HotPatchProgress("Checking version", 0));
  32. var original = Parse(await ReadTextAsync(bundledManifestUri, ct));
  33. HotPatchLog.Info($"bundled_manifest platform={original.platform} build={original.playerBuildId} version={original.version}");
  34. original.Validate(assemblyName, platform, sceneName);
  35. if (original.aotBundle == null || original.aotMetadata == null ||
  36. !original.aotMetadata.Select(r => r.name).OrderBy(n => n).SequenceEqual(HotPatchBundleLoader.AotAssemblyNames.OrderBy(n => n)))
  37. throw new InvalidDataException("Original resources must include an AOT bundle and verification records for all four AOT DLLs.");
  38. var root = Path.Combine(cacheDirectory, HotPatchHash.Of(Encoding.UTF8.GetBytes(original.playerBuildId)));
  39. Directory.CreateDirectory(root);
  40. HotPatchLog.Info("cache_path path=" + root);
  41. var manifestPath = Path.Combine(root, ManifestFileName);
  42. var aotMetadata = original.aotMetadata ?? Array.Empty<HotPatchResource>();
  43. var aotPath = Path.Combine(root, original.aotBundle.RelativePath);
  44. if (!IsVerified(aotPath, original.aotBundle))
  45. await DownloadFileAsync(new Uri(bundledManifestUri, original.aotBundle.RelativePath), aotPath, original.aotBundle,
  46. bytes => progress?.Invoke(new HotPatchProgress("Checking version", .1f * (float)bytes / original.aotBundle.size)), ct);
  47. var local = TryReadLocal(manifestPath, original);
  48. if (local != null && !local.resources.Any(r => IsVerified(Path.Combine(root, r.RelativePath), r)))
  49. local = null;
  50. if (local == null)
  51. {
  52. HotPatchLog.Info("cache_restore source=StreamingAssets reason=missing_or_invalid");
  53. for (int i = 0; i < original.resources.Length; i++)
  54. {
  55. var resource = original.resources[i];
  56. var destination = Path.Combine(root, resource.RelativePath);
  57. if (!IsVerified(destination, resource))
  58. await DownloadFileAsync(new Uri(bundledManifestUri, resource.RelativePath), destination, resource,
  59. bytes => progress?.Invoke(new HotPatchProgress("Checking version", .1f + .1f * (i + (float)bytes / resource.size) / original.resources.Length)), ct);
  60. ct.ThrowIfCancellationRequested();
  61. }
  62. local = Parse(JsonUtility.ToJson(original));
  63. SaveManifest(manifestPath, local);
  64. }
  65. else HotPatchLog.Info("cache_reuse version=" + local.version);
  66. progress?.Invoke(new HotPatchProgress("Checking version", .2f));
  67. var fresh = new UriBuilder(remoteManifestUri);
  68. fresh.Query = fresh.Query.TrimStart('?') + (fresh.Query.Length > 0 ? "&" : "") + "hotpatch=" + DateTime.UtcNow.Ticks;
  69. var remote = Parse(await ReadTextAsync(fresh.Uri, ct, true));
  70. HotPatchLog.Info($"remote_manifest platform={remote.platform} build={remote.playerBuildId} version={remote.version}");
  71. remote.ValidateAgainst(original);
  72. var previous = local.resources.ToDictionary(r => r.name, StringComparer.OrdinalIgnoreCase);
  73. var changed = remote.resources.Where(resource =>
  74. !previous.TryGetValue(resource.name, out var old) || !resource.SameContent(old) ||
  75. !IsVerified(Path.Combine(root, resource.RelativePath), resource)).ToArray();
  76. changed = changed.Where(r => !IsVerified(Path.Combine(root, r.RelativePath), r)).ToArray();
  77. long total = changed.Sum(r => checked(r.size)), completed = 0;
  78. HotPatchLog.Info($"version_compare local={local.version} remote={remote.version} changedFiles={changed.Length} transferBytes={total}");
  79. foreach (var resource in changed)
  80. {
  81. ct.ThrowIfCancellationRequested();
  82. var bundled = original.resources.FirstOrDefault(r => r.SameContent(resource));
  83. var source = new Uri(bundled != null ? bundledManifestUri : remoteManifestUri, resource.RelativePath);
  84. await DownloadFileAsync(source, Path.Combine(root, resource.RelativePath), resource,
  85. bytes => progress?.Invoke(new HotPatchProgress(bundled != null ? "Repairing local resources" : "Downloading updates",
  86. .2f + .6f * (float)((completed + (double)bytes) / Math.Max(1, total)),
  87. (ulong)completed + bytes, total)), ct);
  88. completed += resource.size;
  89. }
  90. ct.ThrowIfCancellationRequested();
  91. remote.aotMetadata = aotMetadata;
  92. remote.aotBundle = original.aotBundle;
  93. bool unchanged = local.SameVersion(remote);
  94. if (!unchanged) SaveManifest(manifestPath, remote);
  95. HotPatchLog.Info("manifest_" + (unchanged ? "unchanged" : "committed") + " path=" + manifestPath);
  96. RemoveObsoleteFiles(root, remote);
  97. HotPatchLog.Info($"sync_complete version={remote.version} changedFiles={changed.Length} transferBytes={total} elapsedMs={elapsed.ElapsedMilliseconds}");
  98. progress?.Invoke(new HotPatchProgress(unchanged && changed.Length == 0 ? "Resources are up to date" : "Local resources updated", .8f, (ulong)total, total));
  99. return new HotPatchLocalResources(root, remote, original);
  100. }
  101. static HotPatchManifest TryReadLocal(string path, HotPatchManifest original)
  102. {
  103. if (!File.Exists(path)) return null;
  104. try
  105. {
  106. var manifest = Parse(File.ReadAllText(path));
  107. manifest.ValidateAgainst(original);
  108. return manifest;
  109. }
  110. catch (Exception e) when (e is IOException || e is ArgumentException || e is InvalidOperationException)
  111. {
  112. HotPatchLog.Warning("cache_manifest_invalid path=" + path + " reason=" + e.Message);
  113. return null;
  114. }
  115. }
  116. public static HotPatchManifest Parse(string json)
  117. => JsonUtility.FromJson<HotPatchManifest>(json) ?? throw new InvalidDataException("The resource manifest is empty.");
  118. public static bool IsVerified(string path, HotPatchResource resource)
  119. => File.Exists(path) && new FileInfo(path).Length == resource.size &&
  120. string.Equals(HotPatchHash.OfFile(path), resource.sha256, StringComparison.OrdinalIgnoreCase);
  121. static void SaveManifest(string path, HotPatchManifest manifest)
  122. {
  123. var temp = path + "." + Guid.NewGuid().ToString("N") + ".tmp";
  124. try
  125. {
  126. File.WriteAllText(temp, JsonUtility.ToJson(manifest, true), new UTF8Encoding(false));
  127. CommitFile(temp, path);
  128. }
  129. finally { if (File.Exists(temp)) File.Delete(temp); }
  130. }
  131. static void RemoveObsoleteFiles(string root, HotPatchManifest manifest)
  132. {
  133. var retained = new HashSet<string>(manifest.resources.Select(r => Path.GetFileName(r.RelativePath)), StringComparer.OrdinalIgnoreCase);
  134. var files = Path.Combine(root, "files");
  135. if (!Directory.Exists(files)) return;
  136. foreach (var file in Directory.GetFiles(files))
  137. {
  138. var name = Path.GetFileName(file);
  139. if (retained.Contains(name) || !Regex.IsMatch(name, @"\A(?:[0-9a-f]{64}(?:\.bundle|(?:\.dll|\.bundle)?\.bytes)|download-[0-9a-f]{32}\.tmp)\z")) continue;
  140. File.Delete(file);
  141. }
  142. }
  143. public static Uri StreamingManifestUri()
  144. {
  145. return ManifestUriFromStreamingPath(Application.streamingAssetsPath);
  146. }
  147. public static Uri RemoteManifestUri(string downloadUrl)
  148. {
  149. if (!Uri.TryCreate(downloadUrl?.Trim(), UriKind.Absolute, out var uri))
  150. throw new InvalidOperationException("Configure a valid hot patch DownloadUrl in AppSettings.");
  151. HotPatchHash.RequireHttp(uri);
  152. var builder = new UriBuilder(uri) { Fragment = string.Empty };
  153. if (!builder.Path.EndsWith(".json", StringComparison.OrdinalIgnoreCase))
  154. builder.Path = builder.Path.TrimEnd('/') + "/" + ManifestFileName;
  155. return builder.Uri;
  156. }
  157. public static Uri ManifestUriFromStreamingPath(string streamingAssetsPath)
  158. {
  159. var path = streamingAssetsPath.TrimEnd('/', '\\') + "/" + ManifestFileName;
  160. return new Uri(path.Contains("://") ? path : Path.GetFullPath(path));
  161. }
  162. static async UniTask<string> ReadTextAsync(Uri uri, CancellationToken ct, bool noCache = false)
  163. {
  164. var elapsed = System.Diagnostics.Stopwatch.StartNew();
  165. HotPatchLog.Info("manifest_request url=" + HotPatchLog.SafeUrl(uri));
  166. try
  167. {
  168. using var request = UnityWebRequest.Get(uri.AbsoluteUri);
  169. request.timeout = 30;
  170. if (noCache) request.SetRequestHeader("Cache-Control", "no-cache, no-store");
  171. var operation = request.SendWebRequest();
  172. while (!operation.isDone)
  173. {
  174. if (ct.IsCancellationRequested) { request.Abort(); ct.ThrowIfCancellationRequested(); }
  175. await UniTask.Yield(ct);
  176. }
  177. ct.ThrowIfCancellationRequested();
  178. if (request.result != UnityWebRequest.Result.Success) throw RequestFailure("Failed to read resource manifest", uri, request);
  179. HotPatchLog.Info($"manifest_response url={HotPatchLog.SafeUrl(uri)} status={request.responseCode} bytes={request.downloadedBytes} elapsedMs={elapsed.ElapsedMilliseconds}");
  180. return Encoding.UTF8.GetString(request.downloadHandler.data).TrimStart('\uFEFF');
  181. }
  182. catch (Exception e)
  183. {
  184. HotPatchLog.Warning($"manifest_failed url={HotPatchLog.SafeUrl(uri)} elapsedMs={elapsed.ElapsedMilliseconds} type={e.GetType().Name} reason={e.Message}");
  185. throw;
  186. }
  187. }
  188. static IOException RequestFailure(string message, Uri uri, UnityWebRequest request)
  189. => new IOException(message + ": HTTP " + request.responseCode + " / " +
  190. HotPatchLog.SafeUrl(uri) + " / " + request.error);
  191. public static async UniTask DownloadFileAsync(Uri uri, string destination, HotPatchResource resource,
  192. Action<ulong> progress, CancellationToken ct)
  193. {
  194. var elapsed = System.Diagnostics.Stopwatch.StartNew();
  195. bool remote = uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps;
  196. var action = remote ? "download" : "extract";
  197. HotPatchLog.Info($"{action}_start name={resource.name} bytes={resource.size} sha256={resource.sha256} url={HotPatchLog.SafeUrl(uri)} destination={destination}");
  198. Directory.CreateDirectory(Path.GetDirectoryName(destination));
  199. var temp = Path.Combine(Path.GetDirectoryName(destination), "download-" + Guid.NewGuid().ToString("N") + ".tmp");
  200. try
  201. {
  202. long nextProgressMs = 1000;
  203. using (var request = UnityWebRequest.Get(uri.AbsoluteUri))
  204. {
  205. request.timeout = 30;
  206. request.downloadHandler.Dispose();
  207. request.downloadHandler = new DownloadHandlerFile(temp) { removeFileOnAbort = true };
  208. var operation = request.SendWebRequest();
  209. while (!operation.isDone)
  210. {
  211. if (ct.IsCancellationRequested) { request.Abort(); ct.ThrowIfCancellationRequested(); }
  212. if (request.downloadedBytes > (ulong)resource.size)
  213. { request.Abort(); throw new InvalidDataException("The resource exceeds the size declared in the manifest: " + resource.name); }
  214. progress?.Invoke(request.downloadedBytes);
  215. if (elapsed.ElapsedMilliseconds >= nextProgressMs)
  216. {
  217. HotPatchLog.Info($"{action}_progress name={resource.name} bytes={request.downloadedBytes}/{resource.size} percent={Math.Min(100, request.downloadedBytes * 100d / resource.size):F0}");
  218. nextProgressMs = elapsed.ElapsedMilliseconds + 1000;
  219. }
  220. await UniTask.Yield(ct);
  221. }
  222. ct.ThrowIfCancellationRequested();
  223. if (request.result != UnityWebRequest.Result.Success) throw RequestFailure("Failed to read resource: " + resource.name, uri, request);
  224. HotPatchLog.Info($"{action}_response name={resource.name} status={request.responseCode} bytes={request.downloadedBytes}");
  225. }
  226. if (!IsVerified(temp, resource)) throw new InvalidDataException("Resource size or SHA-256 verification failed: " + resource.name);
  227. CommitFile(temp, destination);
  228. HotPatchLog.Info($"{action}_complete name={resource.name} bytes={resource.size} percent=100 sha256=verified elapsedMs={elapsed.ElapsedMilliseconds} destination={destination}");
  229. progress?.Invoke((ulong)resource.size);
  230. }
  231. catch (Exception e)
  232. {
  233. HotPatchLog.Warning($"{action}_failed name={resource.name} url={HotPatchLog.SafeUrl(uri)} elapsedMs={elapsed.ElapsedMilliseconds} type={e.GetType().Name} reason={e.Message}");
  234. throw;
  235. }
  236. finally { if (File.Exists(temp)) File.Delete(temp); }
  237. }
  238. static void CommitFile(string temp, string destination)
  239. {
  240. if (File.Exists(destination)) File.Replace(temp, destination, null);
  241. else File.Move(temp, destination);
  242. }
  243. }
  244. }