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
29 changes: 18 additions & 11 deletions MergerLogic/Clients/GpkgClient.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using MergerLogic.Batching;
using MergerLogic.DataTypes;
using MergerLogic.Extensions;
using MergerLogic.Utils;
using Microsoft.Extensions.Logging;
Expand Down Expand Up @@ -241,10 +242,10 @@ public void InsertTiles(IEnumerable<Tile> tiles)
}
}

// Keyset pagination over rowid: seeks past lastId instead of OFFSET-scanning, so page cost stays
// constant regardless of depth. lastId is the cursor (0 to start); returns the greatest rowid read
// (or lastId unchanged when the page is empty).
public (List<Tile> Tiles, long LastId) GetBatch(int batchSize, long lastId)
// Keyset paging on the GPKG's UNIQUE(zoom_level, tile_column, tile_row) index: constant page cost, lowest zoom first.
// Merge order matters (partial tiles are filled by upscaling a lower zoom already in the target), so never page by rowid.
// after: last tile read (null to start); returns the page's last tile, or after when the page is empty.
public (List<Tile> Tiles, Coord? Last) GetBatch(int batchSize, Coord? after)
{
List<Tile> tiles = new List<Tile>(batchSize);

Expand All @@ -253,19 +254,25 @@ public void InsertTiles(IEnumerable<Tile> tiles)
var connection = this.GetOrCreateConnection();
using (var command = connection.CreateCommand())
{
string where = after is null ? "" : "WHERE (zoom_level, tile_column, tile_row) > ($z, $x, $y) ";
command.CommandText =
$"SELECT rowid, zoom_level, tile_column, tile_row, tile_data FROM \"{this._tileCache}\" WHERE rowid > $lastId ORDER BY rowid ASC LIMIT $limit";
command.Parameters.AddWithValue("$lastId", lastId);
$"SELECT zoom_level, tile_column, tile_row, tile_data FROM \"{this._tileCache}\" {where}ORDER BY zoom_level, tile_column, tile_row LIMIT $limit";
if (after is not null)
{
command.Parameters.AddWithValue("$z", after.Z);
command.Parameters.AddWithValue("$x", after.X);
command.Parameters.AddWithValue("$y", after.Y);
}
command.Parameters.AddWithValue("$limit", batchSize);

using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
lastId = reader.GetInt64(0);
var z = reader.GetInt32(1);
var x = reader.GetInt32(2);
var y = reader.GetInt32(3);
var z = reader.GetInt32(0);
var x = reader.GetInt32(1);
var y = reader.GetInt32(2);
after = new Coord(z, x, y);
var blob = (byte[])reader["tile_data"];

Tile tile = this.CreateTile(z, x, y, blob)!;
Expand All @@ -275,7 +282,7 @@ public void InsertTiles(IEnumerable<Tile> tiles)
}
}

return (tiles, lastId);
return (tiles, after);
}

public Tile? GetLastTile(int[] coords, int currentTileZoom)
Expand Down
2 changes: 1 addition & 1 deletion MergerLogic/Clients/IGpkgClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ namespace MergerLogic.Clients
{
public interface IGpkgClient : IDataUtils, IDisposable
{
(List<Tile> Tiles, long LastId) GetBatch(int batchSize, long lastId);
(List<Tile> Tiles, Coord? Last) GetBatch(int batchSize, Coord? after);
Extent GetExtent();
Tile? GetLastTile(int[] coords, int currentTileZoom);
long GetTileCount();
Expand Down
40 changes: 31 additions & 9 deletions MergerLogic/DataTypes/Gpkg.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@ namespace MergerLogic.DataTypes
{
public class Gpkg : Data<IGpkgClient>
{
// Keyset cursor: the greatest tile id handed out so far. Persisted as the batch identifier for resume.
private long _batchCursorId;
// Keyset cursor: the last tile handed out (null before the first batch). Persisted as the batch
// identifier for resume: "0" before the first batch, otherwise "z/x/y".
private Coord? _batchCursor;
private const string StartBatchIdentifier = "0";
private Extent _extent;
private readonly IConfigurationManager _configManager;
private readonly object _locker = new object();
Expand All @@ -19,7 +21,7 @@ public Gpkg(IConfigurationManager configuration, IServiceProvider container,
: base(container, DataType.GPKG, path, batchSize, grid, origin, isBase, extent)
{
this._logger.LogDebug($"[{MethodBase.GetCurrentMethod()?.Name}] Ctor started");
this._batchCursorId = 0;
this._batchCursor = null;
this._configManager = configuration;

if (isBase)
Expand Down Expand Up @@ -83,7 +85,7 @@ public override void Reset()
{
lock (_locker)
{
this._batchCursorId = 0;
this._batchCursor = null;
}
}

Expand All @@ -92,9 +94,9 @@ public override List<Tile> GetNextBatch(out string currentBatchIdentifier, out s
lock (_locker)
{
this._logger.LogDebug($"[{MethodBase.GetCurrentMethod()?.Name}] started");
currentBatchIdentifier = this._batchCursorId.ToString();
currentBatchIdentifier = ToBatchIdentifier(this._batchCursor);

var (rawTiles, cursor) = this.Utils.GetBatch(this.BatchSize, this._batchCursorId);
var (rawTiles, cursor) = this.Utils.GetBatch(this.BatchSize, this._batchCursor);
List<Tile> tiles = rawTiles
.Select(t =>
{
Expand All @@ -103,8 +105,8 @@ public override List<Tile> GetNextBatch(out string currentBatchIdentifier, out s
return tile;
}).Where(t => t != null).ToList();

this._batchCursorId = cursor;
nextBatchIdentifier = this._batchCursorId.ToString();
this._batchCursor = cursor;
nextBatchIdentifier = ToBatchIdentifier(this._batchCursor);
this._logger.LogDebug($"[{MethodBase.GetCurrentMethod()?.Name}] ended");
return tiles;
}
Expand All @@ -114,10 +116,30 @@ public override void setBatchIdentifier(string batchIdentifier)
{
lock (_locker)
{
this._batchCursorId = long.Parse(batchIdentifier);
this._batchCursor = FromBatchIdentifier(batchIdentifier);
}
}

private static string ToBatchIdentifier(Coord? cursor)
{
return cursor is null ? StartBatchIdentifier : $"{cursor.Z}/{cursor.X}/{cursor.Y}";
}

private static Coord? FromBatchIdentifier(string batchIdentifier)
{
if (batchIdentifier == StartBatchIdentifier)
{
return null;
}

string[] parts = batchIdentifier.Split('/');
if (parts.Length != 3)
{
throw new FormatException($"invalid gpkg batch identifier '{batchIdentifier}', expected '{StartBatchIdentifier}' or 'z/x/y'");
}
return new Coord(int.Parse(parts[0]), int.Parse(parts[1]), int.Parse(parts[2]));
}

protected override Tile? InternalGetLastExistingTile(Coord baseCoords)
{
this._logger.LogDebug($"[{MethodBase.GetCurrentMethod()?.Name}] started for coord: z:{baseCoords.Z}, x:{baseCoords.X}, y:{baseCoords.Y}");
Expand Down
47 changes: 33 additions & 14 deletions MergerLogicUnitTests/DataTypes/GpkgTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -657,31 +657,49 @@ public static IEnumerable<object[]> GenSetBatchIdentifierParams()
new object[] { true, false }, //is one on one
new object[] { true, false }, //is base
new object[] { GridOrigin.LOWER_LEFT, GridOrigin.UPPER_LEFT }, //origin
new object[] { 7, 13650 } //batch offset
new object[] { "0", "5/7/13650" } //batch identifier
);
}

[TestMethod]
[TestCategory("SetBatchIdentifier")]
[DynamicData(nameof(GenSetBatchIdentifierParams), DynamicDataSourceType.Method)]
public void SetBatchIdentifier(bool isOneXOne, bool isBase, GridOrigin origin, int offset)
public void SetBatchIdentifier(bool isOneXOne, bool isBase, GridOrigin origin, string testIdentifier)
{
var extent = new Extent() { MinX = -180, MinY = -90, MaxX = 180, MaxY = 90 };
Grid grid = isOneXOne ? Grid.OneXOne : Grid.TwoXOne;

this.SetupRequiredBaseMocks(isBase, isOneXOne, extent);
this._gpkgUtilsMock.Setup(utils => utils.GetBatch(10, It.IsAny<long>()))
.Returns<int, long>((_, lastId) => (new List<Tile>(), lastId));
this._gpkgUtilsMock.Setup(utils => utils.GetBatch(10, It.IsAny<Coord?>()))
.Returns<int, Coord?>((_, after) => (new List<Tile>(), after));

var gpkg = new Gpkg(this._configurationManagerMock.Object,
this._serviceProviderMock.Object, "test.gpkg", 10, grid, origin,
isBase, extent);

string testIdentifier = offset.ToString();
gpkg.setBatchIdentifier(testIdentifier);
gpkg.GetNextBatch(out string batchIdentifier, out string? _, null);
Assert.AreEqual(testIdentifier, batchIdentifier);
this._gpkgUtilsMock.Verify(utils => utils.GetBatch(10, offset), Times.Once);
Coord? expectedCursor = testIdentifier == "0" ? null : new Coord(5, 7, 13650);
this._gpkgUtilsMock.Verify(utils => utils.GetBatch(10, expectedCursor), Times.Once);
this.VerifyAll();
}

[TestMethod]
[TestCategory("SetBatchIdentifier")]
[DataRow("13650")]
[DataRow("5/7")]
[DataRow("a/b/c")]
public void SetBatchIdentifierRejectsInvalidIdentifier(string identifier)
{
var extent = new Extent() { MinX = -180, MinY = -90, MaxX = 180, MaxY = 90 };
this.SetupRequiredBaseMocks(false, false, extent);

var gpkg = new Gpkg(this._configurationManagerMock.Object,
this._serviceProviderMock.Object, "test.gpkg", 10, Grid.TwoXOne, GridOrigin.UPPER_LEFT,
false, extent);

Assert.ThrowsException<FormatException>(() => gpkg.setBatchIdentifier(identifier));
this.VerifyAll();
}

Expand All @@ -708,8 +726,8 @@ public void Reset(bool isOneXOne, bool isBase, GridOrigin origin, int batchSize)
Grid grid = isOneXOne ? Grid.OneXOne : Grid.TwoXOne;

this.SetupRequiredBaseMocks(isBase, isOneXOne, extent);
this._gpkgUtilsMock.Setup(utils => utils.GetBatch(batchSize, It.IsAny<long>()))
.Returns<int, long>((_, lastId) => (new List<Tile> { new Tile(0, 0, 0, this._jpegImageData) }, lastId + 1));
this._gpkgUtilsMock.Setup(utils => utils.GetBatch(batchSize, It.IsAny<Coord?>()))
.Returns<int, Coord?>((_, after) => (new List<Tile> { new Tile(0, 0, 0, this._jpegImageData) }, new Coord(0, 0, 0)));
if (origin == GridOrigin.UPPER_LEFT)
{
this._geoUtilsMock.Setup(converter => converter.FlipY(It.IsAny<Tile>()))
Expand All @@ -732,8 +750,8 @@ public void Reset(bool isOneXOne, bool isBase, GridOrigin origin, int batchSize)
gpkg.Reset();
gpkg.GetNextBatch(out batchIdentifier, out string? _, null);
Assert.AreEqual("0", batchIdentifier);
this._gpkgUtilsMock.Verify(utils => utils.GetBatch(batchSize, 0), Times.Exactly(2));
this._gpkgUtilsMock.Verify(utils => utils.GetBatch(batchSize, It.IsAny<long>()), Times.Exactly(3));
this._gpkgUtilsMock.Verify(utils => utils.GetBatch(batchSize, null), Times.Exactly(2));
this._gpkgUtilsMock.Verify(utils => utils.GetBatch(batchSize, It.IsAny<Coord?>()), Times.Exactly(3));
this.VerifyAll();
}

Expand Down Expand Up @@ -772,8 +790,8 @@ public void GetNextBatch(bool isOneXOne, bool isBase, GridOrigin origin, int bat
var batch = tileBatches[i].ToList();
this._gpkgUtilsMock
.InSequence(seq)
.Setup(utils => utils.GetBatch(batchSize, It.IsAny<long>()))
.Returns<int, long>((_, lastId) => (batch, lastId + batch.Count));
.Setup(utils => utils.GetBatch(batchSize, It.IsAny<Coord?>()))
.Returns<int, Coord?>((_, after) => (batch, batch.Last().GetCoord()));
for (var j = 0; j < tileBatches[i].Length; j++)
{
if (origin == GridOrigin.UPPER_LEFT)
Expand Down Expand Up @@ -804,9 +822,10 @@ public void GetNextBatch(bool isOneXOne, bool isBase, GridOrigin origin, int bat

Assert.IsTrue(res.SequenceEqual(exactedBatch, EqualityComparerFactory.Create<Tile>(
(t1, t2) => t1.Z == t2.Z && t1.X == t2.X && t1.Y == t2.Y)));
string expectedBatchId = Math.Min(i * batchSize, tiles.Length).ToString();
Coord? expectedCursor = i == 0 ? null : tileBatches[i - 1].Last().GetCoord();
string expectedBatchId = expectedCursor is null ? "0" : $"{expectedCursor.Z}/{expectedCursor.X}/{expectedCursor.Y}";
Assert.AreEqual(expectedBatchId, batchIdentifier);
this._gpkgUtilsMock.Verify(utils => utils.GetBatch(batchSize, i * batchSize), Times.Once);
this._gpkgUtilsMock.Verify(utils => utils.GetBatch(batchSize, expectedCursor), Times.Once);
foreach (var tile in tileBatches[i])
{
if (origin == GridOrigin.UPPER_LEFT)
Expand Down
60 changes: 49 additions & 11 deletions MergerLogicUnitTests/Utils/GpkgUtilsTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -164,22 +164,21 @@ public void GetBatch(int batchSize, int offset)
this._fileSystemMock.Object, this._geoUtilsMock.Object);

var comparer = ComparerFactory.Create<Tile>((t1, t2) => t1?.Z == t2?.Z && t1?.X == t2?.X && t1?.Y == t2?.Y ? 0 : -1);
// Tiles are inserted in order, so their auto-increment ids are contiguous (1..N) and the
// keyset cursor `id > lastId` selects the same rows the old offset-based paging returned.
var (res, cursor) = gpkgUtils.GetBatch(batchSize, offset);
Coord? after = offset == 0 ? null : new Coord(offset - 1, offset - 1, offset - 1);
var (res, cursor) = gpkgUtils.GetBatch(batchSize, after);
var expected = testTiles.Skip(offset).Take(batchSize).ToArray();
CollectionAssert.AreEqual(expected, res, comparer);
// Cursor advances to the id of the last row read (or stays put when the page is empty).
Assert.AreEqual(offset + expected.Length, cursor);
// Cursor advances to the last tile read (or stays put when the page is empty).
Assert.AreEqual(expected.Length == 0 ? after : expected.Last().GetCoord(), cursor);
}
this.VerifyAll();
}

[TestMethod]
[TestCategory("GetBatch")]
public void GetBatchWithLongOffset()
public void GetBatchAfterLastTileIsEmpty()
{
long offset = 1L + int.MaxValue;
var after = new Coord(0, 0, 1);
string path = this.GetGpkgPath();
var testTiles = new Tile[]
{
Expand All @@ -195,8 +194,47 @@ public void GetBatchWithLongOffset()
var gpkgUtils = new GpkgClient(path, this._timeUtilsMock.Object, this._loggerMock.Object,
this._fileSystemMock.Object, this._geoUtilsMock.Object);

var (res, _) = gpkgUtils.GetBatch(21, offset);
var (res, cursor) = gpkgUtils.GetBatch(21, after);
CollectionAssert.AreEqual(Array.Empty<Tile>(), res);
Assert.AreEqual(after, cursor);
}
this.VerifyAll();
}

[TestMethod]
[TestCategory("GetBatch")]
public void GetBatchReturnsLowestZoomFirstWhateverTheInsertOrder()
{
string path = this.GetGpkgPath();
// Rows stored highest zoom first must still be read lowest zoom first.
var testTiles = new Tile[]
{
new Tile(2, 3, 1, this._jpegImageData), new Tile(2, 0, 2, this._jpegImageData),
new Tile(1, 1, 0, this._jpegImageData), new Tile(1, 0, 1, this._jpegImageData),
new Tile(0, 0, 0, this._jpegImageData),
};
var expected = testTiles.OrderBy(t => t.Z).ThenBy(t => t.X).ThenBy(t => t.Y).ToArray();

using (var connection = new SQLiteConnection($"Data Source={path}"))
{
connection.Open();
this.SetupConstructorRequiredMocks(connection);
this.CreateTestTiles(connection, testTiles);

var gpkgUtils = new GpkgClient(path, this._timeUtilsMock.Object, this._loggerMock.Object,
this._fileSystemMock.Object, this._geoUtilsMock.Object);

var comparer = ComparerFactory.Create<Tile>((t1, t2) => t1?.Z == t2?.Z && t1?.X == t2?.X && t1?.Y == t2?.Y ? 0 : -1);
var read = new List<Tile>();
Coord? cursor = null;
List<Tile> page;
do
{
(page, cursor) = gpkgUtils.GetBatch(2, cursor);
read.AddRange(page);
} while (page.Count > 0);

CollectionAssert.AreEqual(expected, read, comparer);
}
this.VerifyAll();
}
Expand All @@ -222,7 +260,7 @@ public void DisposeAfterUseIsIdempotent()
this._fileSystemMock.Object, this._geoUtilsMock.Object);

// Opens the reused connection.
var (res, _) = gpkgUtils.GetBatch(1, 0);
var (res, _) = gpkgUtils.GetBatch(1, null);
Assert.AreEqual(1, res.Count);

gpkgUtils.Dispose();
Expand Down Expand Up @@ -268,7 +306,7 @@ public void ReadingDoesNotChangeJournalMode()
using (var gpkgUtils = new GpkgClient(path, this._timeUtilsMock.Object, this._loggerMock.Object,
this._fileSystemMock.Object, this._geoUtilsMock.Object))
{
var (res, _) = gpkgUtils.GetBatch(1, 0);
var (res, _) = gpkgUtils.GetBatch(1, null);
Assert.AreEqual(1, res.Count);
}

Expand All @@ -293,7 +331,7 @@ public void ReadsReadOnlyFile()
using (var gpkgUtils = new GpkgClient(path, this._timeUtilsMock.Object, this._loggerMock.Object,
this._fileSystemMock.Object, this._geoUtilsMock.Object))
{
var (res, _) = gpkgUtils.GetBatch(1, 0);
var (res, _) = gpkgUtils.GetBatch(1, null);
Assert.AreEqual(1, res.Count);
}
}
Expand Down
Loading