|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using Microsoft.Build.Framework; |
| 4 | +using Microsoft.Build.Utilities; |
| 5 | + |
| 6 | +namespace CarpaNet.BuildTasks; |
| 7 | + |
| 8 | +/// <summary> |
| 9 | +/// MSBuild task that resolves AT Protocol handles to DIDs, then enumerates their lexicon records. |
| 10 | +/// Invoked when <see cref="LexiconResolveHandle"/> items are present. |
| 11 | +/// </summary> |
| 12 | +public sealed class ResolveHandleLexiconsTask : Microsoft.Build.Utilities.Task |
| 13 | +{ |
| 14 | + /// <summary> |
| 15 | + /// Handles to resolve (from LexiconResolveHandle MSBuild items). |
| 16 | + /// </summary> |
| 17 | + [Required] |
| 18 | + public ITaskItem[] Handles { get; set; } = Array.Empty<ITaskItem>(); |
| 19 | + |
| 20 | + /// <summary> |
| 21 | + /// Directory to cache resolved lexicon files. |
| 22 | + /// </summary> |
| 23 | + [Required] |
| 24 | + public string CacheDir { get; set; } = string.Empty; |
| 25 | + |
| 26 | + /// <summary> |
| 27 | + /// Cache TTL in hours. Set to 0 to force refresh. |
| 28 | + /// </summary> |
| 29 | + public double CacheTtlHours { get; set; } = 24; |
| 30 | + |
| 31 | + /// <summary> |
| 32 | + /// Whether to fail the build on resolution errors (true) or just warn (false). |
| 33 | + /// </summary> |
| 34 | + public bool FailOnError { get; set; } = true; |
| 35 | + |
| 36 | + /// <summary> |
| 37 | + /// PLC directory URL for did:plc resolution. |
| 38 | + /// </summary> |
| 39 | + public string PlcDirectoryUrl { get; set; } = "https://plc.directory"; |
| 40 | + |
| 41 | + /// <summary> |
| 42 | + /// Semicolon-separated DNS server IP addresses. |
| 43 | + /// </summary> |
| 44 | + public string DnsServers { get; set; } = string.Empty; |
| 45 | + |
| 46 | + /// <summary> |
| 47 | + /// Output: resolved lexicon file paths to be fed into LexiconFiles. |
| 48 | + /// </summary> |
| 49 | + [Output] |
| 50 | + public ITaskItem[] ResolvedLexiconFiles { get; set; } = Array.Empty<ITaskItem>(); |
| 51 | + |
| 52 | + public override bool Execute() |
| 53 | + { |
| 54 | + if (Handles.Length == 0) |
| 55 | + return true; |
| 56 | + |
| 57 | + var cache = new LexiconCache(CacheDir, CacheTtlHours); |
| 58 | + var resolvedFiles = new List<ITaskItem>(); |
| 59 | + |
| 60 | + var dnsServers = string.IsNullOrWhiteSpace(DnsServers) |
| 61 | + ? null |
| 62 | + : DnsServers.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); |
| 63 | + |
| 64 | + using var resolver = new LexiconResolver( |
| 65 | + PlcDirectoryUrl, |
| 66 | + dnsServers, |
| 67 | + msg => Log.LogMessage(MessageImportance.Normal, msg), |
| 68 | + msg => Log.LogWarning(msg)); |
| 69 | + |
| 70 | + foreach (var item in Handles) |
| 71 | + { |
| 72 | + var handle = item.ItemSpec; |
| 73 | + |
| 74 | + // Strip leading @ (common copy-paste from Bluesky) |
| 75 | + if (handle.StartsWith("@", StringComparison.Ordinal)) |
| 76 | + handle = handle.Substring(1); |
| 77 | + |
| 78 | + if (!IsValidHandle(handle)) |
| 79 | + { |
| 80 | + Log.LogError("Invalid handle format: '{0}'. Handles must have at least 2 dot-separated segments with a valid TLD (last segment must not start with a digit).", handle); |
| 81 | + return false; |
| 82 | + } |
| 83 | + |
| 84 | + try |
| 85 | + { |
| 86 | + // Check authority manifest cache first (keyed by handle) |
| 87 | + var cachedNsids = cache.TryGetAuthorityManifest(handle); |
| 88 | + if (cachedNsids != null) |
| 89 | + { |
| 90 | + Log.LogMessage(MessageImportance.Low, "Using cached handle manifest for '{0}' ({1} lexicons)", handle, cachedNsids.Count); |
| 91 | + |
| 92 | + // Verify all individual NSID caches still exist |
| 93 | + var allCached = true; |
| 94 | + foreach (var nsid in cachedNsids) |
| 95 | + { |
| 96 | + if (!cache.IsCached(nsid)) |
| 97 | + { |
| 98 | + allCached = false; |
| 99 | + break; |
| 100 | + } |
| 101 | + } |
| 102 | + |
| 103 | + if (allCached) |
| 104 | + { |
| 105 | + foreach (var nsid in cachedNsids) |
| 106 | + { |
| 107 | + resolvedFiles.Add(new TaskItem(cache.GetJsonPath(nsid))); |
| 108 | + } |
| 109 | + |
| 110 | + continue; |
| 111 | + } |
| 112 | + |
| 113 | + Log.LogMessage(MessageImportance.Normal, "Some cached lexicons for handle '{0}' are missing, re-resolving", handle); |
| 114 | + } |
| 115 | + |
| 116 | + // Resolve from network: handle → DID → PDS → listRecords |
| 117 | + var resolved = resolver.ResolveHandleAsync(handle).GetAwaiter().GetResult(); |
| 118 | + var nsidList = new List<string>(); |
| 119 | + |
| 120 | + foreach (var (nsid, json) in resolved) |
| 121 | + { |
| 122 | + cache.Store(nsid, json); |
| 123 | + resolvedFiles.Add(new TaskItem(cache.GetJsonPath(nsid))); |
| 124 | + nsidList.Add(nsid); |
| 125 | + Log.LogMessage(MessageImportance.Normal, "Resolved lexicon: {0}", nsid); |
| 126 | + } |
| 127 | + |
| 128 | + cache.StoreAuthorityManifest(handle, nsidList); |
| 129 | + Log.LogMessage(MessageImportance.Normal, "Resolved {0} lexicons for handle '{1}'", nsidList.Count, handle); |
| 130 | + } |
| 131 | + catch (LexiconResolutionException ex) |
| 132 | + { |
| 133 | + if (FailOnError) |
| 134 | + { |
| 135 | + Log.LogError("Handle lexicon resolution failed for '{0}': {1}", handle, ex.Message); |
| 136 | + return false; |
| 137 | + } |
| 138 | + else |
| 139 | + { |
| 140 | + Log.LogWarning("Handle lexicon resolution failed for '{0}' (continuing because CarpaNet_LexiconFailOnError=false): {1}", handle, ex.Message); |
| 141 | + } |
| 142 | + } |
| 143 | + catch (Exception ex) |
| 144 | + { |
| 145 | + if (FailOnError) |
| 146 | + { |
| 147 | + Log.LogError("Handle lexicon resolution failed for '{0}' with unexpected error: {1}", handle, ex.Message); |
| 148 | + return false; |
| 149 | + } |
| 150 | + else |
| 151 | + { |
| 152 | + Log.LogWarning("Handle lexicon resolution failed for '{0}' with unexpected error (continuing because CarpaNet_LexiconFailOnError=false): {1}", handle, ex.Message); |
| 153 | + } |
| 154 | + } |
| 155 | + } |
| 156 | + |
| 157 | + ResolvedLexiconFiles = resolvedFiles.ToArray(); |
| 158 | + return !Log.HasLoggedErrors; |
| 159 | + } |
| 160 | + |
| 161 | + /// <summary> |
| 162 | + /// Validates that a string is a well-formed AT Protocol handle. |
| 163 | + /// Handles are domain-like: at least 2 dot-separated segments, each alphanumeric/hyphen, |
| 164 | + /// and the last segment (TLD) must not start with a digit. |
| 165 | + /// </summary> |
| 166 | + internal static bool IsValidHandle(string handle) |
| 167 | + { |
| 168 | + if (string.IsNullOrWhiteSpace(handle)) |
| 169 | + return false; |
| 170 | + |
| 171 | + var segments = handle.Split('.'); |
| 172 | + if (segments.Length < 2) |
| 173 | + return false; |
| 174 | + |
| 175 | + foreach (var segment in segments) |
| 176 | + { |
| 177 | + if (string.IsNullOrEmpty(segment) || segment.Length > 63) |
| 178 | + return false; |
| 179 | + |
| 180 | + if (!char.IsLetterOrDigit(segment[0]) || !char.IsLetterOrDigit(segment[segment.Length - 1])) |
| 181 | + return false; |
| 182 | + |
| 183 | + foreach (var c in segment) |
| 184 | + { |
| 185 | + if (!char.IsLetterOrDigit(c) && c != '-') |
| 186 | + return false; |
| 187 | + } |
| 188 | + } |
| 189 | + |
| 190 | + // Last segment (TLD) must not start with a digit |
| 191 | + if (char.IsDigit(segments[segments.Length - 1][0])) |
| 192 | + return false; |
| 193 | + |
| 194 | + return true; |
| 195 | + } |
| 196 | +} |
0 commit comments