HotPatchResourceStore.cs 18 KB

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