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
17 changes: 14 additions & 3 deletions Sources/Mapnik/FeatureQuery.swift
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,15 @@ enum FeatureQueryParser {
/// geometry fails to decode are dropped as well, and the count is reported
/// through `dropped` so callers are not left guessing why the result is
/// short.
/// True when `number` is one of Foundation's JSON boolean singletons.
///
/// `JSONSerialization` returns the shared boolean instances for `true` and
/// `false`, so identity comparison is reliable and portable, unlike
/// inspecting `objCType`.
private static func isBooleanNumber(_ number: NSNumber) -> Bool {
number === NSNumber(value: true) || number === NSNumber(value: false)
}

static func parseFeatures(json: Data, dropped: inout Int) throws -> [Feature] {
dropped = 0

Expand Down Expand Up @@ -73,9 +82,11 @@ enum FeatureQueryParser {
return string

case let number as NSNumber:
// JSON booleans arrive as NSNumber (objCType "c");
// keep them bool, then integer when exact.
if number.objCType[0] == Int8(99) { // "c" = boolean
// JSON booleans arrive as NSNumber. `objCType` is a
// Foundation implementation detail (and "c" also
// matches small integers on some versions), so compare
// against the shared boolean instances instead.
if isBooleanNumber(number) {
return number.boolValue
}

Expand Down
15 changes: 12 additions & 3 deletions Sources/Mapnik/Mapnik.swift
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,11 @@ public final class Mapnik: @unchecked Sendable {
}
}

/// Destroys the underlying map object.
///
/// - Note: This acquires the process-wide lifecycle lock, so it may block
/// while another map is being created or loaded. Mapnik's global
/// registries cannot be touched concurrently, so the lock is required.
deinit {
Self.lifecycleLock.withLock {
mapnik_map_destroy(map)
Expand All @@ -165,9 +170,13 @@ public final class Mapnik: @unchecked Sendable {
/// Tiles are always rendered in Web Mercator, regardless of the map's
/// `srs`: the tile bounding box (EPSG:3857) is used as the map's extent
/// for the duration of the call, and mapnik reprojects layer data into
/// the map SRS on the fly. Rendering XYZ tiles of a map whose SRS is not
/// Web Mercator (e.g. `epsg:4326`) is therefore valid, but the tile grid
/// geometry is still Web Mercator's.
/// the map SRS on the fly.
///
/// - Warning: on a map whose `srs` is not Web Mercator the tile box is
/// interpreted in that SRS, not reprojected. For an `epsg:4326` map the
/// extent becomes ±20037508 *degrees*, so the tile renders empty. Set
/// the map SRS to `epsg:3857` (the default for stylesheets that omit
/// `@srs`) before rendering XYZ tiles.
///
/// - Parameters:
/// - x: Tile column at zoom `z`, 0 ..< 2^z.
Expand Down
25 changes: 12 additions & 13 deletions Sources/Mapnik/MapnikDatasource.swift
Original file line number Diff line number Diff line change
Expand Up @@ -185,16 +185,14 @@ public final class MapnikDatasource: @unchecked Sendable {
}
return keys.withUnsafeBufferPointer { keysBuffer in
values.withUnsafeBufferPointer { valuesBuffer in
// The C API expects `const char* const*`; the Swift
// arrays are `[UnsafePointer<CChar>?]`, contiguous and
// NUL-free by construction.
let keysPointer = UnsafeRawPointer(keysBuffer.baseAddress!)
.assumingMemoryBound(to: UnsafePointer<CChar>?.self)
let valuesPointer = UnsafeRawPointer(valuesBuffer.baseAddress!)
.assumingMemoryBound(to: UnsafePointer<CChar>?.self)
return mapnik_datasource_create(
keysPointer,
valuesPointer,
// The C API takes `const char* const*`; the Swift arrays
// are already `[UnsafePointer<CChar>?]`, so pass their
// storage directly instead of reinterpreting it through
// UnsafeRawPointer + assumingMemoryBound (undefined
// behaviour).
mapnik_datasource_create(
keysBuffer.baseAddress,
valuesBuffer.baseAddress,
Int32(clamping: parameters.count),
slotPointer)
}
Expand Down Expand Up @@ -223,9 +221,10 @@ public final class MapnikDatasource: @unchecked Sendable {
/// geographic extent is computed by transforming the native extent
/// from this SRS to WGS84. Pass the layer's `srs` field.
/// - fieldFilter: Optional set of attribute names to report and
/// sample; `nil` reports every field. Useful to trim wide tables
/// down to the attributes the editor shows. Geometry samples are
/// available through ``MapnikDatasource/queryBox(_:maxFeatures:)``.
/// sample; `nil` or an empty set reports every field. This is a
/// membership filter: the output keeps the datasource's field order,
/// it does not follow the order of the set. Useful to trim wide
/// tables down to the attributes the editor shows.
/// - Returns: The parsed ``DatasourceInfo``.
/// - Throws: `MapnikError.renderingFailed` when mapnik fails to open or
/// describe the datasource.
Expand Down
18 changes: 18 additions & 0 deletions Sources/Mapnik/Metatile.swift
Original file line number Diff line number Diff line change
Expand Up @@ -119,11 +119,29 @@ public struct MetatileOptions: Sendable {
/// cropping, `bufferSize` the padding applied around the whole metatile.
public var render: RenderOptions

/// Creates metatile options.
///
/// The values are validated when the options are used by a render call,
/// so this initializer stays non-throwing (it is used as a default
/// argument). Call ``validated(metaSize:render:)`` when you want the error
/// at the point of construction.
public init(metaSize: Int = 4, render: RenderOptions = .tile()) {
self.metaSize = metaSize
self.render = render
}

/// Creates metatile options and validates them immediately.
///
/// - Throws: `MapnikError.invalidInput` for out-of-range values.
public static func validated(
metaSize: Int = 4,
render: RenderOptions = .tile(),
) throws -> MetatileOptions {
let options = MetatileOptions(metaSize: metaSize, render: render)
try options.validate()
return options
}

/// The metatile's pixel dimensions (`metaSize * width * scale` by
/// `metaSize * height * scale`).
public var metatileWidth: Int {
Expand Down
8 changes: 6 additions & 2 deletions Sources/Mapnik/RenderOptions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,12 @@ public enum ImageFormat: Sendable, Hashable {
/// Uncompressed TIFF.
case tiff

/// SVG output via the cairo backend. Vector output ignores raster-only
/// options; use `Mapnik.renderSVG(...)` instead of the pixel formats.
/// SVG output via the cairo backend.
///
/// This case exists so a format value can describe vector output, but it
/// is **not** usable with the raster render entry points: every
/// `RenderOptions`-based render rejects it. Use
/// ``Mapnik/renderSVG(width:height:scale:)`` instead.
case svg

/// The mapnik image type string for this format (e.g. `"webp:quality=80"`).
Expand Down
9 changes: 6 additions & 3 deletions Sources/MapnikC/include/mapnik_c.h
Original file line number Diff line number Diff line change
Expand Up @@ -535,9 +535,12 @@ bool mapnik_counting_datasource_push_polygon(mapnik_counting_datasource_t* datas
const char* name,
char** error_out);

/// Attach the datasource to the layer at `index` of the map. The map keeps a
/// shared reference; the caller must keep the handle alive while the map is
/// in use (or until replaced).
/// Attach the datasource to the layer at `index` of the map.
///
/// The layer keeps a `shared_ptr` reference, so the map stays usable even
/// after the handle is destroyed; the handle only needs to outlive the call
/// itself. Destroying it early is therefore safe, and `mapnik_map_destroy`
/// releases the last reference when the map goes away.
bool mapnik_map_use_counting_datasource(mapnik_map_t* map,
int layer_index,
mapnik_counting_datasource_t* datasource,
Expand Down
8 changes: 8 additions & 0 deletions Sources/MapnikC/mapnik_c.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1878,6 +1878,14 @@ mapnik_datasource_t* mapnik_datasource_create(const char* const* keys,
}

void mapnik_datasource_destroy(mapnik_datasource_t* datasource) {
if (datasource == nullptr) {
return;
}

// Destruction touches the same global registries as creation, so it takes
// the same lifecycle mutex; otherwise a datasource could be torn down
// while another thread is loading a stylesheet.
std::lock_guard<std::mutex> lock(mapnik_lifecycle_mutex());
delete datasource;
}

Expand Down
50 changes: 50 additions & 0 deletions Tests/MapnikTests/MapnikDatasourceTests.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import Foundation
import GISTools
@testable import Mapnik
import MapnikC
import Testing

/// Tests for direct datasource creation + inspection (the editor UI path).
Expand Down Expand Up @@ -278,3 +280,51 @@ extension Fixtures {
}()

}

/// Tests for the datasource thread-safety and lifetime contracts.
@Suite("Datasource lifetime")
struct DatasourceLifetimeTests {

/// Datasources can be created, queried and destroyed concurrently.
@Test
func `concurrent datasource lifecycle is safe`() async throws {
try await withThrowingTaskGroup(of: Void.self) { group in
for _ in 0 ..< 8 {
group.addTask {
let datasource = try MapnikDatasource(parameters: [
("type", "geojson"),
("inline", Fixtures.geojson),
])
let info = try datasource.inspect(maxFeatures: 1, srs: "+init=epsg:4326")
_ = try datasource.queryBox(info.extent, maxFeatures: 1)
}
}

try await group.waitForAll()
}
}

/// A map keeps working after the counting datasource handle is destroyed.
@Test
func `map outlives counting datasource handle`() throws {
let map = try Mapnik(xml: Fixtures.polygonStyle)
let counter = try #require(mapnik_counting_datasource_create())
defer { mapnik_counting_datasource_destroy(counter) }

let wkb = MetatileTests.europePolygonWKB()
var errorOut: UnsafeMutablePointer<CChar>? = nil
#expect(mapnik_counting_datasource_push_polygon(counter, wkb, UInt(wkb.count), "Europe", &errorOut))
#expect(errorOut == nil)

try map.withMapPointer { pointer in
#expect(mapnik_map_use_counting_datasource(pointer, 0, counter, &errorOut))
}
#expect(errorOut == nil)

// The layer holds a shared_ptr, so the map stays usable after the
// handle is destroyed: rendering must not crash or throw.
_ = try map.renderTile(Fixtures.europeTile, format: .png())
#expect(map.layerNames == ["land"])
}

}
Loading