using System;
using System.Collections.Generic;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
namespace CarpaNet.BuildTasks;
///
/// MSBuild task that enumerates all lexicon records published by an authority
/// using com.atproto.repo.listRecords. Invoked when items are present.
///
public sealed class ResolveAuthorityLexiconsTask : Microsoft.Build.Utilities.Task
{
///
/// Authorities to resolve (from LexiconResolveAuthority MSBuild items).
///
[Required]
public ITaskItem[] Authorities { get; set; } = Array.Empty();
///
/// Directory to cache resolved lexicon files.
///
[Required]
public string CacheDir { get; set; } = string.Empty;
///
/// Cache TTL in hours. Set to 0 to force refresh.
///
public double CacheTtlHours { get; set; } = 24;
///
/// Whether to fail the build on resolution errors (true) or just warn (false).
///
public bool FailOnError { get; set; } = true;
///
/// PLC directory URL for did:plc resolution.
///
public string PlcDirectoryUrl { get; set; } = "https://plc.directory";
///
/// Semicolon-separated DNS server IP addresses.
///
public string DnsServers { get; set; } = string.Empty;
///
/// Output: resolved lexicon file paths to be fed into LexiconFiles.
///
[Output]
public ITaskItem[] ResolvedLexiconFiles { get; set; } = Array.Empty();
public override bool Execute()
{
if (Authorities.Length == 0)
return true;
var cache = new LexiconCache(CacheDir, CacheTtlHours);
var resolvedFiles = new List();
var dnsServers = string.IsNullOrWhiteSpace(DnsServers)
? null
: DnsServers.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
using var resolver = new LexiconResolver(
PlcDirectoryUrl,
dnsServers,
msg => Log.LogMessage(MessageImportance.Normal, msg),
msg => Log.LogWarning(msg));
foreach (var item in Authorities)
{
var input = item.ItemSpec;
var isDid = input.StartsWith("did:", StringComparison.OrdinalIgnoreCase);
if (!isDid && !NsidAuthority.IsValidAuthority(input))
{
Log.LogError("Invalid authority format: '{0}'. Authorities must have at least 2 dot-separated segments, or be a DID (did:plc:... or did:web:...).", input);
return false;
}
try
{
// Check authority manifest cache first
var cachedNsids = cache.TryGetAuthorityManifest(input);
if (cachedNsids != null)
{
Log.LogMessage(MessageImportance.Low, "Using cached authority manifest for '{0}' ({1} lexicons)", input, cachedNsids.Count);
// Verify all individual NSID caches still exist
var allCached = true;
foreach (var nsid in cachedNsids)
{
if (!cache.IsCached(nsid))
{
allCached = false;
break;
}
}
if (allCached)
{
foreach (var nsid in cachedNsids)
{
resolvedFiles.Add(new TaskItem(cache.GetJsonPath(nsid)));
}
continue;
}
Log.LogMessage(MessageImportance.Normal, "Some cached lexicons for '{0}' are missing, re-resolving", input);
}
// Resolve from network
var resolved = isDid
? resolver.ResolveDidAsync(input).GetAwaiter().GetResult()
: resolver.ResolveAuthorityAsync(input).GetAwaiter().GetResult();
var nsidList = new List();
foreach (var (nsid, json) in resolved)
{
cache.Store(nsid, json);
resolvedFiles.Add(new TaskItem(cache.GetJsonPath(nsid)));
nsidList.Add(nsid);
Log.LogMessage(MessageImportance.Normal, "Resolved lexicon: {0}", nsid);
}
cache.StoreAuthorityManifest(input, nsidList);
Log.LogMessage(MessageImportance.Normal, "Resolved {0} lexicons for '{1}'", nsidList.Count, input);
}
catch (LexiconResolutionException ex)
{
if (FailOnError)
{
Log.LogError("Authority lexicon resolution failed for '{0}': {1}", input, ex.Message);
return false;
}
else
{
Log.LogWarning("Authority lexicon resolution failed for '{0}' (continuing because CarpaNet_LexiconFailOnError=false): {1}", input, ex.Message);
}
}
catch (Exception ex)
{
if (FailOnError)
{
Log.LogError("Authority lexicon resolution failed for '{0}' with unexpected error: {1}", input, ex.Message);
return false;
}
else
{
Log.LogWarning("Authority lexicon resolution failed for '{0}' with unexpected error (continuing because CarpaNet_LexiconFailOnError=false): {1}", input, ex.Message);
}
}
}
ResolvedLexiconFiles = resolvedFiles.ToArray();
return !Log.HasLoggedErrors;
}
}