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
99 changes: 99 additions & 0 deletions src/dapps/dapps.core.tests/MeshFabricScenarioTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
using AwesomeAssertions;
using dapps.meshcore.sim;
using Xunit;

namespace dapps.core.tests;

/// <summary>
/// Full-stack scenarios: the REAL MeshCore bearer (transport + reliability ACK/resend +
/// idempotent inbound + passive discovery) running on many nodes over a multi-hop
/// virtual mesh - the coverage two directly-adjacent bench radios can't give. No RF, no
/// loss (so it's fast + deterministic); loss-recovery timing is left to a longer harness
/// run since reliability resends are on a multi-second cadence.
/// </summary>
public sealed class MeshFabricScenarioTests
{
private static async Task WaitUntil(Func<bool> cond, TimeSpan timeout)
{
var deadline = DateTime.UtcNow + timeout;
while (DateTime.UtcNow < deadline)
{
if (cond()) return;
await Task.Delay(100);
}
}

[Fact]
public async Task FullStack_FourRelayHops_BidirectionalDelivery_Discovery_NoDuplicates()
{
// A off R1 ... R4 off C: the two DAPPS nodes are four relay hops apart.
var f = new MeshFabric();
f.AddRelay("R1"); f.AddRelay("R2"); f.AddRelay("R3"); f.AddRelay("R4");
f.ConnectChain(["R1", "R2", "R3", "R4"]);
var a = new MeshDappsNode(f, "GB7A-1");
var c = new MeshDappsNode(f, "GB7C-1");
f.Connect("GB7A-1", "R1");
f.Connect("GB7C-1", "R4");

using var cts = new CancellationTokenSource();
var loops = Task.WhenAll(a.RunAsync(cts.Token), c.RunAsync(cts.Token));

const int N = 4;
for (var i = 0; i < N; i++)
{
await a.SendAsync("GB7C-1", i, $"A->C #{i}", cts.Token);
await c.SendAsync("GB7A-1", i, $"C->A #{i}", cts.Token);
}

await WaitUntil(() => a.DistinctSeqs == N && c.DistinctSeqs == N, TimeSpan.FromSeconds(15));
cts.Cancel();
try { await loops; } catch { /* cancelled */ }

c.DistinctSeqs.Should().Be(N, "every message reached C across four relay hops");
a.DistinctSeqs.Should().Be(N);
c.Delivered.Should().Be(N, "idempotent: flooding + dedup never double-delivers to the app");
a.Delivered.Should().Be(N);
c.DiscoveredPeers.Should().Contain("GB7A-1", "C learned A purely by hearing its traffic, multi-hop");
a.DiscoveredPeers.Should().Contain("GB7C-1");
}

[Fact]
public async Task FullStack_FanIn_ManySendersOneCollector_AllDeliveredOnce()
{
// Five DAPPS senders hang off a relay backbone; all send to one collector. Proves
// many nodes + concurrent multi-hop floods still deliver each message exactly once.
var f = new MeshFabric();
var relays = new[] { "R0", "R1", "R2", "R3", "R4", "R5" };
foreach (var r in relays) f.AddRelay(r);
f.ConnectChain(relays);

var collector = new MeshDappsNode(f, "GB7COL-1");
f.Connect("GB7COL-1", "R0");

var senders = new List<MeshDappsNode>();
for (var i = 0; i < 5; i++)
{
var s = new MeshDappsNode(f, $"GB7S{i}-1");
f.Connect(s.Callsign, relays[i + 1]); // each sender off a different relay
senders.Add(s);
}

using var cts = new CancellationTokenSource();
var loops = Task.WhenAll(new[] { collector.RunAsync(cts.Token) }
.Concat(senders.Select(s => s.RunAsync(cts.Token))));

const int PerSender = 3;
foreach (var s in senders)
for (var i = 0; i < PerSender; i++)
await s.SendAsync("GB7COL-1", i, $"{s.Callsign} #{i}", cts.Token);

var expected = senders.Count * PerSender; // seq values collide across senders, so count deliveries
await WaitUntil(() => collector.Delivered >= expected, TimeSpan.FromSeconds(20));
cts.Cancel();
try { await loops; } catch { /* cancelled */ }

collector.Delivered.Should().Be(expected, "each of the 15 messages delivered exactly once (no duplicates)");
collector.DiscoveredPeers.Should().Contain(senders.Select(s => s.Callsign),
"the collector discovered every sender it heard");
}
}
198 changes: 198 additions & 0 deletions src/dapps/dapps.core.tests/MeshFabricTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
using System.Text;
using AwesomeAssertions;
using dapps.client.Backhaul;
using dapps.meshcore;
using dapps.meshcore.sim;
using Xunit;

namespace dapps.core.tests;

/// <summary>
/// The simulated multi-hop MeshCore fabric (#24 test-strategy follow-up): validates the
/// flood/dedup/hop/scope model, and that the REAL bearer transport carries a
/// BackhaulMessage across several relay hops and decodes it exactly once. Deterministic
/// and fast - no bearer poll loops, no RF. See MeshFabricScenarioTests for the full
/// bearer stack running over the fabric.
/// </summary>
public sealed class MeshFabricTests
{
// How many app-deliveries a leaf's link received (each fabric Deliver enqueues one
// ChannelData; a deduped duplicate never enqueues).
private static int Received(SimulatedMeshCoreLink link)
{
var batch = link.DrainAsync(CancellationToken.None).GetAwaiter().GetResult();
return batch?.Data.Count ?? 0;
}

[Fact]
public void Chain_MultiHop_DeliversToFarLeaf()
{
// A(leaf) - R1 - R2 - R3 - B(leaf): a message from A must traverse 3 relay hops.
var f = new MeshFabric();
var a = f.AddLeaf("A");
f.AddRelay("R1"); f.AddRelay("R2"); f.AddRelay("R3");
var b = f.AddLeaf("B");
f.ConnectChain(["A", "R1", "R2", "R3", "B"]);

a.SendDataAsync("hello"u8.ToArray(), CancellationToken.None).GetAwaiter().GetResult();

Check warning on line 37 in src/dapps/dapps.core.tests/MeshFabricTests.cs

View workflow job for this annotation

GitHub Actions / test

Test methods should not use blocking task operations, as they can cause deadlocks. Use an async test method and await instead. (https://xunit.net/xunit.analyzers/rules/xUnit1031)

Received(b).Should().Be(1, "the far leaf hears the flood exactly once");
}

[Fact]
public void Flood_DedupsAcrossMultiplePaths()
{
// Diamond: A -> {R1, R2} -> B. B hears the same packet via both relays but the
// dedup ring must deliver it only once.
var f = new MeshFabric();
var a = f.AddLeaf("A");
f.AddRelay("R1"); f.AddRelay("R2");
var b = f.AddLeaf("B");
f.Connect("A", "R1"); f.Connect("A", "R2");
f.Connect("R1", "B"); f.Connect("R2", "B");

a.SendDataAsync("x"u8.ToArray(), CancellationToken.None).GetAwaiter().GetResult();

Check warning on line 54 in src/dapps/dapps.core.tests/MeshFabricTests.cs

View workflow job for this annotation

GitHub Actions / test

Test methods should not use blocking task operations, as they can cause deadlocks. Use an async test method and await instead. (https://xunit.net/xunit.analyzers/rules/xUnit1031)

Received(b).Should().Be(1, "two paths, but the packet is deduped to a single delivery");
}

[Fact]
public void Leaf_DoesNotRelay()
{
// A - B(leaf) - C: B is a LEAF so it must not re-flood; C never hears it.
var f = new MeshFabric();
var a = f.AddLeaf("A");
var b = f.AddLeaf("B");
var c = f.AddLeaf("C");
f.ConnectChain(["A", "B", "C"]);

a.SendDataAsync("y"u8.ToArray(), CancellationToken.None).GetAwaiter().GetResult();

Check warning on line 69 in src/dapps/dapps.core.tests/MeshFabricTests.cs

View workflow job for this annotation

GitHub Actions / test

Test methods should not use blocking task operations, as they can cause deadlocks. Use an async test method and await instead. (https://xunit.net/xunit.analyzers/rules/xUnit1031)

Received(b).Should().Be(1, "the adjacent leaf hears it");
Received(c).Should().Be(0, "a leaf does not relay, so the far node is unreachable");
}

[Fact]
public void Ring_Dedup_Terminates()
{
// A ring of relays would flood forever without dedup; the ring must terminate and
// each leaf still gets one copy.
var f = new MeshFabric();
var a = f.AddLeaf("A");
f.AddRelay("R1"); f.AddRelay("R2"); f.AddRelay("R3"); f.AddRelay("R4");
var b = f.AddLeaf("B");
f.Connect("A", "R1");
f.ConnectChain(["R1", "R2", "R3", "R4", "R1"]); // R1-R2-R3-R4-R1 cycle
f.Connect("R3", "B");

a.SendDataAsync("z"u8.ToArray(), CancellationToken.None).GetAwaiter().GetResult();

Check warning on line 88 in src/dapps/dapps.core.tests/MeshFabricTests.cs

View workflow job for this annotation

GitHub Actions / test

Test methods should not use blocking task operations, as they can cause deadlocks. Use an async test method and await instead. (https://xunit.net/xunit.analyzers/rules/xUnit1031)

Received(b).Should().Be(1, "delivered once despite the cycle");
}

[Fact]
public void ScopedFlood_ContainedByOutOfScopeRelay()
{
// Model B: A(scope=uk) - R1(scope=uk) - R2(scope=other) - B. The scoped flood must
// stop at R2 (wrong scope), so B never hears it.
var f = new MeshFabric();
var a = f.AddLeaf("A", scope: "uk");
f.AddRelay("R1", scope: "uk");
f.AddRelay("R2", scope: "other");
var b = f.AddLeaf("B");
f.ConnectChain(["A", "R1", "R2", "B"]);

a.SendDataAsync("scoped"u8.ToArray(), CancellationToken.None).GetAwaiter().GetResult();

Check warning on line 105 in src/dapps/dapps.core.tests/MeshFabricTests.cs

View workflow job for this annotation

GitHub Actions / test

Test methods should not use blocking task operations, as they can cause deadlocks. Use an async test method and await instead. (https://xunit.net/xunit.analyzers/rules/xUnit1031)

Received(b).Should().Be(0, "an out-of-scope relay drops the flood (containment)");
}

[Fact]
public void ScopedFlood_CarriedByInScopeRelays()
{
// Control for the containment test: when every relay shares the scope, delivery works.
var f = new MeshFabric();
var a = f.AddLeaf("A", scope: "uk");
f.AddRelay("R1", scope: "uk");
f.AddRelay("R2", scope: "uk");
var b = f.AddLeaf("B");
f.ConnectChain(["A", "R1", "R2", "B"]);

a.SendDataAsync("scoped"u8.ToArray(), CancellationToken.None).GetAwaiter().GetResult();

Check warning on line 121 in src/dapps/dapps.core.tests/MeshFabricTests.cs

View workflow job for this annotation

GitHub Actions / test

Test methods should not use blocking task operations, as they can cause deadlocks. Use an async test method and await instead. (https://xunit.net/xunit.analyzers/rules/xUnit1031)

Received(b).Should().Be(1, "in-scope relays carry the flood to the destination");
}

[Fact]
public void UnscopedFlood_CrossesRelaysRegardlessOfTheirScope()
{
// An unscoped flood (model A) is carried by any relay, even scoped ones.
var f = new MeshFabric();
var a = f.AddLeaf("A"); // no scope
f.AddRelay("R1", scope: "uk");
f.AddRelay("R2", scope: "other");
var b = f.AddLeaf("B");
f.ConnectChain(["A", "R1", "R2", "B"]);

a.SendDataAsync("open"u8.ToArray(), CancellationToken.None).GetAwaiter().GetResult();

Check warning on line 137 in src/dapps/dapps.core.tests/MeshFabricTests.cs

View workflow job for this annotation

GitHub Actions / test

Test methods should not use blocking task operations, as they can cause deadlocks. Use an async test method and await instead. (https://xunit.net/xunit.analyzers/rules/xUnit1031)

Received(b).Should().Be(1, "unscoped floods propagate through every relay");
}

[Theory]
[InlineData(64, 1)] // 64 relays all forward (R64 receives path_len 63 < 64) -> B hears it
[InlineData(65, 0)] // the 65th relay would receive path_len 64 -> dropped -> B unreachable
public void HopCap_DeliversAtExactly64Relays_DropsBeyond(int relayCount, int expected)
{
// The firmware cap is MAX_PATH_SIZE=64 forwarders (path_len < 64). Pin the exact
// boundary - this is the long-chain edge the fabric exists to exercise.
var f = new MeshFabric();
f.AddLeaf("A");
var chain = new List<string> { "A" };
for (var i = 1; i <= relayCount; i++) { f.AddRelay($"R{i}"); chain.Add($"R{i}"); }
f.AddLeaf("B");
chain.Add("B");
f.ConnectChain(chain);

f.Link("A").SendDataAsync("edge"u8.ToArray(), CancellationToken.None).GetAwaiter().GetResult();

Check warning on line 157 in src/dapps/dapps.core.tests/MeshFabricTests.cs

View workflow job for this annotation

GitHub Actions / test

Test methods should not use blocking task operations, as they can cause deadlocks. Use an async test method and await instead. (https://xunit.net/xunit.analyzers/rules/xUnit1031)

Received(f.Link("B")).Should().Be(expected);
}

[Theory]
[InlineData("73 de M0LTE")] // one fragment
[InlineData("Hello from the DAPPS mailbox, a longer store-and-forward message over the mesh that fragments. 73 de M0LTE GB7ABC-1 599 599 599")] // multi-fragment
public void Transport_MultiHop_DecodesOnceAtDestination(string text)
{
// The REAL bearer transport (encode + compress + fragment + nonce) carried across
// 3 relay hops must reassemble/decode to the original message, exactly once.
var f = new MeshFabric();
var a = f.AddLeaf("A");
f.AddRelay("R1"); f.AddRelay("R2"); f.AddRelay("R3");
var b = f.AddLeaf("B");
f.ConnectChain(["A", "R1", "R2", "R3", "B"]);

var msg = new BackhaulMessage(
Id: "abc0001", Destination: "GB7B-1", Salt: 7, Ttl: 3600,
Payload: Encoding.UTF8.GetBytes(text), Originator: "GB7A-1", LinkSourceCallsign: "GB7A-1");

// Encode + fragment + nonce at A, send each frame; B reassembles + decodes.
var frames = new MeshCoreChannelTransport().ToFrames(msg, DappsCompression.Mode.ZstdDict);
foreach (var frame in frames)
a.SendDataAsync(frame, CancellationToken.None).GetAwaiter().GetResult();

Check warning on line 182 in src/dapps/dapps.core.tests/MeshFabricTests.cs

View workflow job for this annotation

GitHub Actions / test

Test methods should not use blocking task operations, as they can cause deadlocks. Use an async test method and await instead. (https://xunit.net/xunit.analyzers/rules/xUnit1031)

var rx = new MeshCoreChannelTransport();
var got = new List<BackhaulMessage>();
var batch = b.DrainAsync(CancellationToken.None).GetAwaiter().GetResult();

Check warning on line 186 in src/dapps/dapps.core.tests/MeshFabricTests.cs

View workflow job for this annotation

GitHub Actions / test

Test methods should not use blocking task operations, as they can cause deadlocks. Use an async test method and await instead. (https://xunit.net/xunit.analyzers/rules/xUnit1031)
batch.Should().NotBeNull("the destination leaf heard the frames");
foreach (var d in batch!.Data)
{
var r = rx.Ingest(d.Payload, DateTime.UtcNow);
if (r.Kind == MeshCoreChannelTransport.Kind.BackhaulComplete) got.Add(r.Message!);
}

got.Should().HaveCount(1, "the message reassembles/decodes exactly once");
Encoding.UTF8.GetString(got[0].Payload).Should().Be(text);
got[0].Id.Should().Be("abc0001");
}
}
1 change: 1 addition & 0 deletions src/dapps/dapps.core.tests/dapps.core.tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

<ItemGroup>
<ProjectReference Include="..\dapps.core\dapps.core.csproj" />
<ProjectReference Include="..\dapps.meshcore.sim\dapps.meshcore.sim.csproj" />
</ItemGroup>

<ItemGroup>
Expand Down
Loading