diff --git a/MergerLogic/Clients/GpkgClient.cs b/MergerLogic/Clients/GpkgClient.cs index 4d6edaa..2fcd2a4 100644 --- a/MergerLogic/Clients/GpkgClient.cs +++ b/MergerLogic/Clients/GpkgClient.cs @@ -1,4 +1,5 @@ using MergerLogic.Batching; +using MergerLogic.DataTypes; using MergerLogic.Extensions; using MergerLogic.Utils; using Microsoft.Extensions.Logging; @@ -241,10 +242,10 @@ public void InsertTiles(IEnumerable 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 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 Tiles, Coord? Last) GetBatch(int batchSize, Coord? after) { List tiles = new List(batchSize); @@ -253,19 +254,25 @@ public void InsertTiles(IEnumerable 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)!; @@ -275,7 +282,7 @@ public void InsertTiles(IEnumerable tiles) } } - return (tiles, lastId); + return (tiles, after); } public Tile? GetLastTile(int[] coords, int currentTileZoom) diff --git a/MergerLogic/Clients/IGpkgClient.cs b/MergerLogic/Clients/IGpkgClient.cs index a619eec..340b86f 100644 --- a/MergerLogic/Clients/IGpkgClient.cs +++ b/MergerLogic/Clients/IGpkgClient.cs @@ -6,7 +6,7 @@ namespace MergerLogic.Clients { public interface IGpkgClient : IDataUtils, IDisposable { - (List Tiles, long LastId) GetBatch(int batchSize, long lastId); + (List Tiles, Coord? Last) GetBatch(int batchSize, Coord? after); Extent GetExtent(); Tile? GetLastTile(int[] coords, int currentTileZoom); long GetTileCount(); diff --git a/MergerLogic/DataTypes/Gpkg.cs b/MergerLogic/DataTypes/Gpkg.cs index 27bb142..bb6e330 100644 --- a/MergerLogic/DataTypes/Gpkg.cs +++ b/MergerLogic/DataTypes/Gpkg.cs @@ -8,8 +8,10 @@ namespace MergerLogic.DataTypes { public class Gpkg : Data { - // 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(); @@ -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) @@ -83,7 +85,7 @@ public override void Reset() { lock (_locker) { - this._batchCursorId = 0; + this._batchCursor = null; } } @@ -92,9 +94,9 @@ public override List 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 tiles = rawTiles .Select(t => { @@ -103,8 +105,8 @@ public override List 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; } @@ -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}"); diff --git a/MergerLogicUnitTests/DataTypes/GpkgTest.cs b/MergerLogicUnitTests/DataTypes/GpkgTest.cs index 3f4c272..203cd29 100644 --- a/MergerLogicUnitTests/DataTypes/GpkgTest.cs +++ b/MergerLogicUnitTests/DataTypes/GpkgTest.cs @@ -657,31 +657,49 @@ public static IEnumerable 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())) - .Returns((_, lastId) => (new List(), lastId)); + this._gpkgUtilsMock.Setup(utils => utils.GetBatch(10, It.IsAny())) + .Returns((_, after) => (new List(), 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(() => gpkg.setBatchIdentifier(identifier)); this.VerifyAll(); } @@ -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())) - .Returns((_, lastId) => (new List { new Tile(0, 0, 0, this._jpegImageData) }, lastId + 1)); + this._gpkgUtilsMock.Setup(utils => utils.GetBatch(batchSize, It.IsAny())) + .Returns((_, after) => (new List { 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())) @@ -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()), Times.Exactly(3)); + this._gpkgUtilsMock.Verify(utils => utils.GetBatch(batchSize, null), Times.Exactly(2)); + this._gpkgUtilsMock.Verify(utils => utils.GetBatch(batchSize, It.IsAny()), Times.Exactly(3)); this.VerifyAll(); } @@ -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())) - .Returns((_, lastId) => (batch, lastId + batch.Count)); + .Setup(utils => utils.GetBatch(batchSize, It.IsAny())) + .Returns((_, after) => (batch, batch.Last().GetCoord())); for (var j = 0; j < tileBatches[i].Length; j++) { if (origin == GridOrigin.UPPER_LEFT) @@ -804,9 +822,10 @@ public void GetNextBatch(bool isOneXOne, bool isBase, GridOrigin origin, int bat Assert.IsTrue(res.SequenceEqual(exactedBatch, EqualityComparerFactory.Create( (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) diff --git a/MergerLogicUnitTests/Utils/GpkgUtilsTest.cs b/MergerLogicUnitTests/Utils/GpkgUtilsTest.cs index 8b52aee..f0f119b 100644 --- a/MergerLogicUnitTests/Utils/GpkgUtilsTest.cs +++ b/MergerLogicUnitTests/Utils/GpkgUtilsTest.cs @@ -164,22 +164,21 @@ public void GetBatch(int batchSize, int offset) this._fileSystemMock.Object, this._geoUtilsMock.Object); var comparer = ComparerFactory.Create((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[] { @@ -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(), 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((t1, t2) => t1?.Z == t2?.Z && t1?.X == t2?.X && t1?.Y == t2?.Y ? 0 : -1); + var read = new List(); + Coord? cursor = null; + List page; + do + { + (page, cursor) = gpkgUtils.GetBatch(2, cursor); + read.AddRange(page); + } while (page.Count > 0); + + CollectionAssert.AreEqual(expected, read, comparer); } this.VerifyAll(); } @@ -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(); @@ -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); } @@ -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); } }