This is the real test of the week: a new problem, no steps to follow, and hints closed for as long as you can stand. Don't copy the job runner. Reuse its ideas: closed outcome types, bounded work, cancellation that still reports everything, and fakes in place of real waiting.
The time shown for this lesson covers the design and a first working version, with one worker and no failures. The full brief is a bigger job, so expect another two or three hours. Spread it over several sittings, and treat the checks as their own session.
The brief
A link checker starts from one page and follows links. Pages come from an interface, so no real network is involved:
ISite.FetchAsync(string url, CancellationToken token) returns Task<Page>, where Page has a Status and a list of Links.
- Each URL is fetched at most once, however many pages link to it.
- At most
Workersfetches run at once. - A
Depthlimit stops following links: the start page has depth 0, and links on a page at the limit are recorded but aren't fetched. - A status of 500 or above is retried, up to
MaxAttempts, without any delay. A 404 is final. - A fetch that takes longer than
Timeoutis reported as timed out. A fetch that throwsIOExceptionis reported as an error. - After cancellation, the links that were found but not fetched are reported as skipped.
- Results are sorted by URL.
- A URL within
Depthby any path is fetched, and the results don't depend on which fetch finished first.
Acceptance example, with / linking to /a and /b, /a linking to /b and /missing, /b linking to /deep, and /missing being 404, with Depth 1:
/,/a,/b: OK/deepand/missing: skipped, because they're past the depth limit
Warm up: can speed change the answer?
The tricky part is that fetching a page finds more work, and speed can change the answer. Suppose /a is fast and /b is slow, and both lead to /target, one by a longer path. Workers that follow links as soon as they find them can reach /target by the long path first, and if that path is past the limit, a URL that's within reach gets skipped.
The program below visits the same links in a particular order. Predict which level /target lands on, then ask yourself whether a slow /b could ever change that answer.
Dictionary<string, string[]> links = new()
{
["/"] = new[] { "/a", "/b" },
["/a"] = new[] { "/x" },
["/x"] = new[] { "/target" },
["/b"] = new[] { "/target" },
["/target"] = Array.Empty<string>(),
};
var seen = new HashSet<string> { "/" };
var level = new List<string> { "/" };
for (int depth = 0; level.Count > 0; depth++)
{
Console.WriteLine($"{depth}: {string.Join(" ", level)}");
var next = new List<string>();
foreach (string url in level)
{
foreach (string link in links[url])
{
if (seen.Add(link))
{
next.Add(link);
}
}
}
level = next;
}Check your prediction
0: /
1: /a /b
2: /x /targetKeep that output in mind when you design your checker: the brief's last rule says the results must not depend on which fetch finished first.
Build it yourself
The link checker
Implement the brief with a FakeSite built from a dictionary. Add checks for: each URL fetched once, even in a cycle; the peak number of concurrent fetches; the depth limit; two paths of different lengths giving the same results whichever is slower; a retry that recovers; a page that's 500 every time; a timeout; and cancellation still reporting every URL that was found.
When it works, it prints the lines below. Each Name { … } line is a record's built-in ToString, so print the record itself rather than formatting it:
Ok { Url = /, Attempts = 1 }
Ok { Url = /a, Attempts = 1 }
Ok { Url = /b, Attempts = 1 }
Skipped { Url = /deep }
Skipped { Url = /missing }
Checker checks passed#nullable enable
using System.Threading.Channels;
await Task.Yield();
Console.WriteLine("Start here");Hint 1: the idea
The brief's last rule is the hard one. Decide what order of work guarantees that every URL is first found by its shortest path, and then which shared state your workers actually need to touch, and when.
Hint 2: a first step
Write the version with one worker and no failures, and check the depth limit. Then add workers for each level, then retries, the timeout, and cancellation last.
Show one solution
#nullable enable
using System.Threading.Channels;
int failures = 0;
void Check(bool passed, string name)
{
if (!passed)
{
Console.WriteLine($"FAILED: {name}");
failures++;
}
}
Dictionary<string, Page> pages = new()
{
["/"] = new Page(200, new[] { "/a", "/b" }),
["/a"] = new Page(200, new[] { "/b", "/missing", "/" }),
["/b"] = new Page(200, new[] { "/deep" }),
["/missing"] = new Page(404, Array.Empty<string>()),
["/deep"] = new Page(200, Array.Empty<string>()),
["/flaky"] = new Page(200, Array.Empty<string>()),
["/down"] = new Page(500, Array.Empty<string>()),
["/slow"] = new Page(200, Array.Empty<string>()),
["/broken"] = new Page(200, Array.Empty<string>()),
};
var options = new CheckerOptions { Workers = 2, Depth = 1, MaxAttempts = 2, Timeout = TimeSpan.FromMilliseconds(30) };
var site = new FakeSite(pages);
var report = await new Checker(site, options).RunAsync("/");
foreach (LinkResult result in report)
{
Console.WriteLine(result);
}
Check(report.Select(result => $"{result.Url} {result.GetType().Name}").SequenceEqual(new[] { "/ Ok", "/a Ok", "/b Ok", "/deep Skipped", "/missing Skipped" }), "the depth limit matches the brief");
Dictionary<string, Page> paths = new()
{
["/"] = new Page(200, new[] { "/a", "/b" }),
["/a"] = new Page(200, new[] { "/x" }),
["/x"] = new Page(200, new[] { "/target" }),
["/b"] = new Page(200, new[] { "/target" }),
["/target"] = new Page(200, Array.Empty<string>()),
};
var slowShort = new FakeSite(paths) { DelayMs = { ["/b"] = 50 } };
var slowLong = new FakeSite(paths) { DelayMs = { ["/a"] = 50 } };
var pathOptions = options with { Depth = 2, Timeout = TimeSpan.FromSeconds(5) };
var slowShortReport = await new Checker(slowShort, pathOptions).RunAsync("/");
var slowLongReport = await new Checker(slowLong, pathOptions).RunAsync("/");
Check(slowShortReport.Single(result => result.Url == "/target") is LinkResult.Ok, "a page within the limit is fetched, even if a longer path finds it first");
Check(slowShortReport.Select(result => result.Url).SequenceEqual(slowLongReport.Select(result => result.Url)), "timing doesn't change which pages are reported");
Check(slowShortReport.Select(result => result.GetType()).SequenceEqual(slowLongReport.Select(result => result.GetType())), "timing doesn't change any status");
Check(slowShortReport.Count == 5, "each page has one result");
var deep = new FakeSite(pages);
var all = await new Checker(deep, options with { Depth = 5 }).RunAsync("/");
Check(deep.Calls.Values.All(calls => calls == 1), "each URL is fetched once, even in a cycle");
Check(deep.Peak <= 2, "stays within the workers");
Check(all.Single(result => result.Url == "/missing") is LinkResult.Broken { Status: 404 }, "a 404 is final");
var flaky = new FakeSite(pages) { FailFirst = { ["/flaky"] = 1 } };
Check((await new Checker(flaky, options).RunAsync("/flaky")).Single() is LinkResult.Ok { Attempts: 2 }, "a retry recovers");
var down = new FakeSite(pages);
Check((await new Checker(down, options).RunAsync("/down")).Single() is LinkResult.Broken { Status: 500 } && down.Calls["/down"] == 2, "gives up at the limit");
var slow = new FakeSite(pages) { DelayMs = { ["/slow"] = 5000 } };
Check((await new Checker(slow, options).RunAsync("/slow")).Single() is LinkResult.TimedOut, "a slow page times out");
var broken = new FakeSite(pages) { Throw = { "/broken" } };
Check((await new Checker(broken, options).RunAsync("/broken")).Single() is LinkResult.Error, "an IOException is an error");
using (var source = new CancellationTokenSource())
{
source.Cancel();
var cancelled = await new Checker(new FakeSite(pages), options).RunAsync("/", source.Token);
Check(cancelled.Single() is LinkResult.Skipped { Url: "/" }, "cancelling reports what was found");
}
using (var source = new CancellationTokenSource())
{
var waiting = new FakeSite(pages) { DelayMs = { ["/a"] = 5000, ["/b"] = 5000 } };
source.CancelAfter(50);
var midway = await new Checker(waiting, options with { Depth = 5, Timeout = TimeSpan.FromSeconds(10) }).RunAsync("/", source.Token);
Check(midway.Select(result => $"{result.Url} {result.GetType().Name}").SequenceEqual(new[] { "/ Ok", "/a Skipped", "/b Skipped" }), "cancelling midway reports every URL that was found");
}
if (failures > 0)
{
return 1;
}
Console.WriteLine("Checker checks passed");
return 0;
record Page(int Status, IReadOnlyList<string> Links);
record CheckerOptions
{
public int Workers { get; init; } = 4;
public int Depth { get; init; } = 2;
public int MaxAttempts { get; init; } = 3;
public TimeSpan Timeout { get; init; } = TimeSpan.FromSeconds(5);
}
interface ISite
{
Task<Page> FetchAsync(string url, CancellationToken token);
}
abstract record LinkResult(string Url)
{
public sealed record Ok(string Url, int Attempts) : LinkResult(Url);
public sealed record Broken(string Url, int Status) : LinkResult(Url);
public sealed record TimedOut(string Url) : LinkResult(Url);
public sealed record Error(string Url, string Message) : LinkResult(Url);
public sealed record Skipped(string Url) : LinkResult(Url);
}
class Checker(ISite site, CheckerOptions options)
{
public async Task<List<LinkResult>> RunAsync(string start, CancellationToken token = default)
{
var results = new List<LinkResult>();
var seen = new HashSet<string> { start };
IReadOnlyList<string> level = new[] { start };
// Finishing a level before the next means a URL is first found by its shortest path.
for (int depth = 0; level.Count > 0; depth++)
{
var next = new List<string>();
foreach ((LinkResult result, IReadOnlyList<string> links) in await CheckLevelAsync(level, token))
{
results.Add(result);
foreach (string link in links)
{
if (!seen.Add(link))
{
continue;
}
if (depth >= options.Depth)
{
results.Add(new LinkResult.Skipped(link));
}
else
{
next.Add(link);
}
}
}
level = next;
}
return results.OrderBy(result => result.Url, StringComparer.Ordinal).ToList();
}
private async Task<List<(LinkResult Result, IReadOnlyList<string> Links)>> CheckLevelAsync(IReadOnlyList<string> urls, CancellationToken token)
{
Channel<string> queue = Channel.CreateUnbounded<string>();
foreach (string url in urls)
{
queue.Writer.TryWrite(url);
}
queue.Writer.Complete();
var found = new List<(LinkResult Result, IReadOnlyList<string> Links)>();
async Task WorkAsync()
{
await foreach (string url in queue.Reader.ReadAllAsync(CancellationToken.None))
{
var checkedUrl = await CheckAsync(url, token);
lock (found)
{
found.Add(checkedUrl);
}
}
}
await Task.WhenAll(Enumerable.Range(0, options.Workers).Select(_ => WorkAsync()));
return found;
}
private async Task<(LinkResult Result, IReadOnlyList<string> Links)> CheckAsync(string url, CancellationToken token)
{
IReadOnlyList<string> none = Array.Empty<string>();
for (int attempt = 1; ; attempt++)
{
if (token.IsCancellationRequested)
{
return (new LinkResult.Skipped(url), none);
}
using var linked = CancellationTokenSource.CreateLinkedTokenSource(token);
linked.CancelAfter(options.Timeout);
try
{
Page page = await site.FetchAsync(url, linked.Token);
if (page.Status < 400)
{
return (new LinkResult.Ok(url, attempt), page.Links);
}
if (page.Status < 500 || attempt >= options.MaxAttempts)
{
return (new LinkResult.Broken(url, page.Status), none);
}
}
catch (OperationCanceledException) when (token.IsCancellationRequested)
{
return (new LinkResult.Skipped(url), none);
}
catch (OperationCanceledException)
{
return (new LinkResult.TimedOut(url), none);
}
catch (IOException e)
{
return (new LinkResult.Error(url, e.Message), none);
}
}
}
}
class FakeSite(Dictionary<string, Page> pages) : ISite
{
private int running;
public Dictionary<string, int> Calls { get; } = new();
public Dictionary<string, int> FailFirst { get; init; } = new();
public Dictionary<string, int> DelayMs { get; init; } = new();
public HashSet<string> Throw { get; init; } = new();
public int Peak { get; private set; }
public async Task<Page> FetchAsync(string url, CancellationToken token)
{
int now = Interlocked.Increment(ref running);
int calls;
lock (Calls)
{
Peak = Math.Max(Peak, now);
calls = Calls[url] = Calls.GetValueOrDefault(url) + 1;
}
try
{
await Task.Delay(DelayMs.GetValueOrDefault(url, 1), token);
if (Throw.Contains(url))
{
throw new IOException("connection lost");
}
if (calls <= FailFirst.GetValueOrDefault(url))
{
return new Page(503, Array.Empty<string>());
}
return pages.GetValueOrDefault(url) ?? new Page(404, Array.Empty<string>());
}
finally
{
Interlocked.Decrement(ref running);
}
}
}Ok { Url = /, Attempts = 1 }
Ok { Url = /a, Attempts = 1 }
Ok { Url = /b, Attempts = 1 }
Skipped { Url = /deep }
Skipped { Url = /missing }
Checker checks passedThe design is the warm-up's order. Finishing each depth before starting the next means a URL is always found first by its shortest path, however fast or slow each fetch is. The HashSet of seen URLs is touched only between levels, so it needs no lock, and duplicates never reach a level. Each level is a fixed list, which also settles when the work is finished: the run ends when a level finds nothing new. Workers only share one level's list and never add to their own queue, which avoids the Day 4 deadlock, where workers wait to write to a full queue with nobody left to read.
Compare your design with the solution, not your text. Where did you decide that work was finished? What on your version is shared between workers, and is it protected on real threads? What did you do for a link found after cancellation? The solution puts every new link in the next level, and that level reports it as skipped. Could you find a case where your version loses one, or where a slower fetch changes a result?
Completion is saved in this browser only. It does not measure mastery.