Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions ModuleManager/Collections/KeyValueCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,25 @@ public TValue Fetch(TKey key, Func<TValue> createValue)
}
}
}

// Takes the key as an argument so that callers can pass a delegate that captures nothing,
// which the compiler caches, instead of allocating a closure on every call.
public TValue FetchWithKey(TKey key, Func<TKey, TValue> createValue)
{
if (createValue == null) throw new ArgumentNullException(nameof(createValue));
lock(lockObject)
{
if (dict.TryGetValue(key, out TValue value))
{
return value;
}
else
{
TValue newValue = createValue(key);
dict.Add(key, newValue);
return newValue;
}
}
}
}
}
168 changes: 168 additions & 0 deletions ModuleManager/ConfigFileHasher.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
using System;
using System.IO;
using System.Runtime.ExceptionServices;
using System.Security.Cryptography;
using System.Threading;

namespace ModuleManager
{
// Computes each file's SHA256 on worker threads, while the caller uses them in order.
// WaitForHash(i) gives file i's hash once ready, or throws what reading it threw.
//
// The workers stay at most ReadAhead files ahead of the caller. If a worker thread dies (an abort), the file it was on is marked as failed
// with that exception; if every worker is gone, the caller reads the files it waits for itself.
public sealed class ConfigFileHasher : IDisposable
{
private const int ReadAhead = 64;

private readonly string[] paths;
private readonly string[] hashes;
private readonly Exception[] errors;
private readonly bool[] ready;
private readonly Thread[] workers;
private readonly object lockObject = new object();
private int next = -1;
private int waitingFor;
private int liveWorkers;
private bool stopping;
private int readCount;

// How many files the workers have read so far
public int ReadCount
{
get { lock (lockObject) return readCount; }
}

public ConfigFileHasher(string[] paths)
{
this.paths = paths ?? throw new ArgumentNullException(nameof(paths));
hashes = new string[paths.Length];
errors = new Exception[paths.Length];
ready = new bool[paths.Length];

int count = Math.Max(1, Math.Min(Environment.ProcessorCount - 1, 8));
if (count > paths.Length) count = Math.Max(1, paths.Length);
workers = new Thread[count];
liveWorkers = count;
for (int i = 0; i < count; i++)
{
workers[i] = new Thread(Work) { IsBackground = true, Name = "ModuleManager file hasher " + i };
workers[i].Start();
}
}

public string WaitForHash(int i)
{
bool readHere = false;
lock (lockObject)
{
waitingFor = i;
Monitor.PulseAll(lockObject);
while (!ready[i])
{
if (liveWorkers == 0)
{
// Nobody is left to read it: claim it if no worker has
if (i > next) next = i;
readHere = true;
break;
}
Monitor.Wait(lockObject);
}
}
if (readHere) Read(i, null);

if (errors[i] != null)
ExceptionDispatchInfo.Capture(errors[i]).Throw();
return hashes[i];
}

private void Read(int i, SHA256 sha)
{
try
{
using FileStream stream = new FileStream(paths[i], FileMode.Open, FileAccess.Read, FileShare.Read, 65536);
if (sha == null)
{
using SHA256 own = SHA256.Create();
hashes[i] = BitConverter.ToString(own.ComputeHash(stream));
}
else
{
hashes[i] = BitConverter.ToString(sha.ComputeHash(stream));
}
}
catch (Exception e)
{
errors[i] = e;
}
}

private void Work()
{
int current = -1;
try
{
using SHA256 sha = SHA256.Create();
while (true)
{
lock (lockObject)
{
while (!stopping && next + 1 < paths.Length && next + 1 > waitingFor + ReadAhead)
Monitor.Wait(lockObject);
if (stopping || next + 1 >= paths.Length) return;
current = ++next;
}

Read(current, sha);

lock (lockObject)
{
ready[current] = true;
readCount++;
current = -1;
Monitor.PulseAll(lockObject);
}
}
}
catch (Exception e)
{
lock (lockObject)
{
if (current >= 0 && !ready[current])
{
errors[current] = e;
ready[current] = true;
}
}
// Not rethrown: a worker that cannot start (SHA256.Create) leaves its files to
// the others, or to the caller, which then meets the same error itself
}
finally
{
lock (lockObject)
{
// An abort that hit between two lines above still leaves no file half done
if (current >= 0 && !ready[current])
{
errors[current] = errors[current] ?? new ThreadInterruptedException("ModuleManager file hasher stopped while reading " + paths[current]);
ready[current] = true;
}
liveWorkers--;
Monitor.PulseAll(lockObject);
}
}
}

public void Dispose()
{
lock (lockObject)
{
stopping = true;
Monitor.PulseAll(lockObject);
}
foreach (Thread worker in workers)
worker.Join();
}
}
}
170 changes: 170 additions & 0 deletions ModuleManager/ConfigNodeWriter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
using System;
using System.IO;

namespace ModuleManager
{
// Writes a ConfigNode to a file exactly as ConfigNode.Save(path) does, without the flush
// ConfigNode.Save does at the end of every node, which costs more than the writing for the
// cache's hundred thousand nodes.
public static class ConfigNodeWriter
{
public static void Save(ConfigNode node, string path)
{
if (node == null) throw new ArgumentNullException(nameof(node));
if (path == null) throw new ArgumentNullException(nameof(path));

using StreamWriter writer = Open(path);
Save(node, writer);
}

// The encoding a StreamWriter uses by default, as ConfigNode.Save's does
private static StreamWriter Open(string path) => new StreamWriter(File.Open(path, FileMode.Create), new System.Text.UTF8Encoding(false, true), 1 << 16);

// Writes the cache node: its values and its UrlConfig nodes as they are, and the nodes in
// each UrlConfig node as their DeepCopy would be written once escaped with
// EscapeValuesRecursive, without making that copy (see WriteCopy).
public static void SaveCache(ConfigNode cache, string path)
{
if (cache == null) throw new ArgumentNullException(nameof(cache));
if (path == null) throw new ArgumentNullException(nameof(path));

using StreamWriter writer = Open(path);
SaveCache(cache, writer);
}

public static void SaveCache(ConfigNode cache, TextWriter writer)
{
if (cache == null) throw new ArgumentNullException(nameof(cache));
if (writer == null) throw new ArgumentNullException(nameof(writer));
WriteValues(writer, cache, "");
for (int i = 0; i < cache.nodes.Count; i++)
{
ConfigNode urlConfig = cache.nodes[i];
WriteHeader(writer, urlConfig, urlConfig.name, "");
WriteValues(writer, urlConfig, "\t");
for (int j = 0; j < urlConfig.nodes.Count; j++)
WriteCopy(writer, urlConfig.nodes[j], "\t");
writer.WriteLine("}");
}
}

// Same text as ConfigNode.Save: UTF-8 without a byte order mark, and
// name // comment
// {
// <tab>key = value // comment
// ...
// }
// with the comments only where there are some.
public static void Save(ConfigNode node, TextWriter writer)
{
if (node == null) throw new ArgumentNullException(nameof(node));
if (writer == null) throw new ArgumentNullException(nameof(writer));
WriteValues(writer, node, "");
for (int i = 0; i < node.nodes.Count; i++)
WriteNode(writer, node.nodes[i], "");
}

private static void WriteValues(TextWriter writer, ConfigNode node, string indent)
{
ConfigNode.ValueList values = node.values;
for (int i = 0; i < values.Count; i++)
{
ConfigNode.Value value = values[i];
writer.Write(indent);
writer.Write(value.name);
writer.Write(" = ");
writer.Write(value.value);
if (!string.IsNullOrEmpty(value.comment))
{
writer.Write(" // ");
writer.Write(value.comment);
}
writer.WriteLine();
}
}

private static void WriteNode(TextWriter writer, ConfigNode node, string indent)
{
WriteHeader(writer, node, node.name, indent);

string inner = indent + "\t";
WriteValues(writer, node, inner);
for (int i = 0; i < node.nodes.Count; i++)
WriteNode(writer, node.nodes[i], inner);

writer.Write(indent);
writer.WriteLine("}");
}

private static void WriteHeader(TextWriter writer, ConfigNode node, string name, string indent)
{
writer.Write(indent);
writer.Write(name);
if (!string.IsNullOrEmpty(node.comment))
{
writer.Write(" // ");
writer.Write(node.comment);
}
writer.WriteLine();
writer.Write(indent);
writer.WriteLine("{");
}

// Characters that the ConfigNode(string) constructor removes or splits the name on
private static readonly char[] nameCleanupChars = { '\n', '\r', '\t', '(', ')', ' ' };
private static readonly char[] escapedChars = { '\n', '\r', '\t' };

// Writes node as DeepCopy(node), then EscapeValuesRecursive, would give it:
// - the name as the ConfigNode(string) constructor makes it (DeepCopy skips that when it
// has nothing to do), and no comment;
// - each value as ConfigNode.ValueList.Add sanitizes it ({ and } become [ and ], and = in
// names becomes -), then with newlines, returns and tabs escaped, and no comment.
private static void WriteCopy(TextWriter writer, ConfigNode node, string indent)
{
string name = node.name;
if (name == null || name.IndexOfAny(nameCleanupChars) >= 0)
name = new ConfigNode(name).name;
writer.Write(indent);
writer.WriteLine(name);
writer.Write(indent);
writer.WriteLine("{");

string inner = indent + "\t";
ConfigNode.ValueList values = node.values;
for (int i = 0; i < values.Count; i++)
{
ConfigNode.Value value = values[i];
string valueName = Sanitize(value.name, true);
string text = Sanitize(value.value, false);
if (text.IndexOfAny(escapedChars) >= 0)
text = text.Replace("\n", "\\n").Replace("\r", "\\r").Replace("\t", "\\t");
writer.Write(inner);
writer.Write(valueName);
writer.Write(" = ");
writer.Write(text);
writer.WriteLine();
}
for (int i = 0; i < node.nodes.Count; i++)
WriteCopy(writer, node.nodes[i], inner);

writer.Write(indent);
writer.WriteLine("}");
}

// ConfigNode.Value.Sanitize, for one string: throws on null as it does
private static string Sanitize(string s, bool isName)
{
for (int i = s.Length - 1; i >= 0; i--)
{
char c = s[i];
if (c == '{' || c == '}' || (isName && c == '='))
{
s = s.Replace('{', '[').Replace('}', ']');
if (isName) s = s.Replace('=', '-');
break;
}
}
return s;
}
}
}
Loading
Loading