diff --git a/.github/actions/summarize-test-results/action.yml b/.github/actions/summarize-test-results/action.yml new file mode 100644 index 0000000..5aef7e0 --- /dev/null +++ b/.github/actions/summarize-test-results/action.yml @@ -0,0 +1,42 @@ +name: Summarize test results +description: Sums JUnit XML test-result attributes under build/test-results/test/*.xml and appends a table to $GITHUB_STEP_SUMMARY. + +runs: + using: composite + steps: + - name: summarize test results + shell: bash + run: | + total=0 + failed=0 + errors=0 + skipped=0 + malformed=0 + shopt -s nullglob + for f in build/test-results/test/*.xml; do + t=$(sed -n 's/.*tests="\([0-9]*\)".*/\1/p' "$f" | head -1) + fl=$(sed -n 's/.*failures="\([0-9]*\)".*/\1/p' "$f" | head -1) + er=$(sed -n 's/.*errors="\([0-9]*\)".*/\1/p' "$f" | head -1) + sk=$(sed -n 's/.*skipped="\([0-9]*\)".*/\1/p' "$f" | head -1) + if [[ -z "$t" || -z "$fl" || -z "$er" || -z "$sk" ]]; then + malformed=$((malformed + 1)) + echo "::warning file=$f::could not parse JUnit XML attributes from $f; excluded from totals" + continue + fi + total=$((total + t)) + failed=$((failed + fl)) + errors=$((errors + er)) + skipped=$((skipped + sk)) + done + passed=$((total - failed - errors - skipped)) + { + echo "### Unit test results" + echo "" + echo "| Total | Passed | Failed | Errors | Skipped |" + echo "|---|---|---|---|---|" + echo "| $total | $passed | $failed | $errors | $skipped |" + if [[ "$malformed" -gt 0 ]]; then + echo "" + echo "⚠️ $malformed report file(s) could not be parsed and were excluded from the totals above." + fi + } >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 88c2b29..bf7d4f6 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -20,11 +20,12 @@ on: jobs: build: runs-on: ubuntu-latest + permissions: + contents: read steps: - name: checkout repository uses: actions/checkout@v6 with: - submodules: recursive fetch-depth: 0 # needed for versioning - name: validate gradle wrapper uses: gradle/actions/wrapper-validation@v6 @@ -39,7 +40,7 @@ jobs: path: | ~/.gradle/caches ~/.gradle/wrapper - key: "${{ runner.os }}-bluemapsignmarkers-${{ hashFiles('**/*.gradle*') }}" + key: "${{ runner.os }}-bluemapsignmarkers-${{ hashFiles('**/*.gradle*', '**/gradle.properties') }}" restore-keys: | ${{ runner.os }}-bluemapsignmarkers- - name: make gradle wrapper executable @@ -48,30 +49,7 @@ jobs: run: ./gradlew test - name: summarize test results if: always() - run: | - total=0 - failed=0 - errors=0 - skipped=0 - shopt -s nullglob - for f in build/test-results/test/*.xml; do - t=$(sed -n 's/.*tests="\([0-9]*\)".*/\1/p' "$f" | head -1) - fl=$(sed -n 's/.*failures="\([0-9]*\)".*/\1/p' "$f" | head -1) - er=$(sed -n 's/.*errors="\([0-9]*\)".*/\1/p' "$f" | head -1) - sk=$(sed -n 's/.*skipped="\([0-9]*\)".*/\1/p' "$f" | head -1) - total=$((total + t)) - failed=$((failed + fl)) - errors=$((errors + er)) - skipped=$((skipped + sk)) - done - passed=$((total - failed - errors - skipped)) - { - echo "### Unit test results" - echo "" - echo "| Total | Passed | Failed | Errors | Skipped |" - echo "|---|---|---|---|---|" - echo "| $total | $passed | $failed | $errors | $skipped |" - } >> "$GITHUB_STEP_SUMMARY" + uses: ./.github/actions/summarize-test-results - name: build with gradle run: ./gradlew build - name: capture build artifacts diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 4bf6978..f5c183b 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -7,10 +7,12 @@ on: jobs: publish: runs-on: ubuntu-latest + environment: modrinth-publish + permissions: + contents: read steps: - uses: actions/checkout@v6 with: - submodules: recursive fetch-depth: 0 # needed for versioning - name: Set up JDK 25 uses: actions/setup-java@v5 @@ -22,7 +24,7 @@ jobs: path: | ~/.gradle/caches ~/.gradle/wrapper - key: "${{ runner.os }}-bluemapsignmarkers-${{ hashFiles('**/*.gradle*') }}" + key: "${{ runner.os }}-bluemapsignmarkers-${{ hashFiles('**/*.gradle*', '**/gradle.properties') }}" restore-keys: | ${{ runner.os }}-bluemapsignmarkers- - name: make gradle wrapper executable @@ -31,30 +33,7 @@ jobs: run: ./gradlew test - name: summarize test results if: always() - run: | - total=0 - failed=0 - errors=0 - skipped=0 - shopt -s nullglob - for f in build/test-results/test/*.xml; do - t=$(sed -n 's/.*tests="\([0-9]*\)".*/\1/p' "$f" | head -1) - fl=$(sed -n 's/.*failures="\([0-9]*\)".*/\1/p' "$f" | head -1) - er=$(sed -n 's/.*errors="\([0-9]*\)".*/\1/p' "$f" | head -1) - sk=$(sed -n 's/.*skipped="\([0-9]*\)".*/\1/p' "$f" | head -1) - total=$((total + t)) - failed=$((failed + fl)) - errors=$((errors + er)) - skipped=$((skipped + sk)) - done - passed=$((total - failed - errors - skipped)) - { - echo "### Unit test results" - echo "" - echo "| Total | Passed | Failed | Errors | Skipped |" - echo "|---|---|---|---|---|" - echo "| $total | $passed | $failed | $errors | $skipped |" - } >> "$GITHUB_STEP_SUMMARY" + uses: ./.github/actions/summarize-test-results - name: Publish alpha to Modrinth if: startsWith(github.ref, 'refs/heads/') env: diff --git a/AGENTS.md b/AGENTS.md index b3cd4a1..f4d30c4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -77,7 +77,7 @@ Two Mixins (`src/main/resources/bluemapsignmarkers.mixins.json`) catch the event table (`SignTransitionResolver.computeTransitionAction`) to get the single `MarkerAction` to dispatch — covering plain add/update/remove, a prefix change moving a sign between groups, and a `POI`↔`LINE` group `type` flip, all as the same kind of - representation diff. `LINE` groups additionally dispatch `SetLineMarkerAction`/`RemoveLineMarkerAction`/ + representation diff. `LINE` groups additionally dispatch `SetMultiPointMarkerAction`/`RemoveMultiPointMarkerAction`/ `GroupTransitionMarkerAction` (built via `ActionFactory`) when a sign joins/leaves a line (see `LineGroupResolver` below). It also implements `IResetHandler.reset()`, which BlueMap fires on `/bluemap reload`: reloads config (`ConfigManager.reload()`, `SignHelper.reloadParser()`, rebuilding its prefix→group lookup and @@ -90,12 +90,15 @@ Two Mixins (`src/main/resources/bluemapsignmarkers.mixins.json`) catch the event `SignManager` can't be unit tested directly (its constructor builds a `BlueMapAPIConnector`, which touches live `BlueMapAPI` static state), but the transition table has no Minecraft/Fabric/BlueMap types in its signature, so extracting it makes it directly testable (`SignTransitionResolverTest`). -3. **`BlueMapAPIConnector`** owns the `ReactiveQueue` and all actual BlueMap API calls. Because the - BlueMap API is only available while BlueMap itself is enabled, actions are queued and only drained - (`markerActionQueue.process()`) while `BlueMapAPI.getInstance().isPresent()`; `BlueMapAPI.onEnable`/`onDisable` - start/stop draining and clear/rebuild the marker-set cache. `MarkerSet`s are looked up/created per - `MarkerSetIdentifier` (map id + marker group), cached in `markerSetsCache` as `MappedMarkerSet` (pairing the - `MarkerSet` with the real `BlueMapMap.getId()` it came from — needed for the per-map render-bounds gating below). +3. **`BlueMapAPIConnector`** owns the `ReactiveQueue`, BlueMap listener lifecycle, action-dispatch + orchestration, render-bounds gating, and the `MarkerSet`/render-mask caches. Because the BlueMap API is only + available while BlueMap itself is enabled, actions are queued and only drained (`markerActionQueue.process()`) + while `BlueMapAPI.getInstance().isPresent()`; `BlueMapAPI.onEnable`/`onDisable` start/stop draining and + clear/rebuild the marker-set cache. `MarkerSet`s are looked up/created per `MarkerSetIdentifier` (map id + marker + group), cached in `markerSetsCache` as `MappedMarkerSet` (pairing the `MarkerSet` with the real + `BlueMapMap.getId()` it came from — needed for the per-map render-bounds gating below). The actual BlueMap marker + builder calls (add/update/remove/set, per marker type) live in a separate `MarkerMutations` class (see "Testable + vs. game-coupled code" below) that `BlueMapAPIConnector` dispatches into. `ReactiveQueue` (`core/reactive`) is a small generic building block: an unbounded queue plus a "should I run right now" predicate, draining onto a fixed thread pool sized to `availableProcessors()`. It isn't BlueMap-specific — reuse @@ -127,11 +130,14 @@ restart alone does not trigger the upgrade sweep (only a genuine BlueMap disable `MarkerGroup` (record: prefix, matchType, type, name, icon, offsetX/Y, defaultHidden, minDistance/maxDistance, lineWidth, lineColor, fillColor, sorting, toggleable, depthTest, cssClasses) is the unit of configuration described -in `README.md`. `type` (`MarkerGroupType`: `POI`, `LINE`, or `SHAPE`) picks which kind of marker the group's signs produce; -`lineWidth`/`lineColor` apply to `LINE`/`SHAPE` groups (setting them on a `POI` group is a warning, not an error). +in `README.md`. `type` (`MarkerGroupType`: `POI`, `LINE`, `SHAPE`, or `EXTRUDE`) picks which kind of marker the +group's signs produce; `lineWidth`/`lineColor` apply to `LINE`/`SHAPE`/`EXTRUDE` groups (setting them on a `POI` +group is a warning, not an error), and `fillColor` additionally applies to `SHAPE`/`EXTRUDE` (a volume gets a +floor/ceiling anchored to its members' Y range, per `MarkerMutations.resolveExtrudeHeightRange`). `sorting`/`toggleable` are thin BlueMap `MarkerSet` passthroughs (menu order, hideability) that apply to every group -type; `depthTest` (terrain occlusion) is `LINE`/`SHAPE`-only and `cssClasses` (custom.css hooks) is `POI`-only, each -resolved in `ConfigProvider` and wired into the corresponding BlueMap builder call in `BlueMapAPIConnector`. +type; `depthTest` (terrain occlusion) is `LINE`/`SHAPE`/`EXTRUDE`-only and `cssClasses` (custom.css hooks) is +`POI`-only, each resolved in `ConfigProvider` and wired into the corresponding BlueMap builder call in +`MarkerMutations`. `ConfigManager` lazily loads a singleton `BMSMConfigV2` via `ConfigProvider` from `config/bluemapsignmarkers/BMSM-Core.json`, creating sane defaults (a single `[poi]` group) if the file is missing or fails to load. `SignLinesParser` matches sign text against groups using either @@ -148,15 +154,24 @@ sign text after the prefix) — that shared (group, label) is a line's membershi Sign state is stored per-world, region-sharded (one file per dimension + 32x32-chunk region — see "Entry point" above), with each region file wrapped in a `VersionedSignFile` envelope (`{version, data}`) so the format can evolve -without breaking old saves. `SignProvider.loadSigns` checks whether the storage root already has region files -(`RegionShardedSignEntryLoader.hasSignData`); if so, it loads every region file the same version-aware way as -before sharding — the versioned-file loader (`VersionedFileSignEntryLoader`, handling V2→V3 migration via -`Version3Converter`, V3→V4 migration via `Version4Converter` (adds `createdAtMillis`, needed to order points within -a line marker; backfilled for pre-V4 entries), and current V4 files directly), falling back to -`Version1SignEntryLoader` for pre-versioning files. If no region files exist yet, `LegacySignFileMigrator` reads a -pre-sharding single `signs.json` (if present) through that same version chain, writes it out region-sharded, and -backs up the legacy file (renamed, not deleted) -only once every expected region file is confirmed on disk. When adding a new persisted field, bump +without breaking old saves. `SignProvider.loadSigns` decides between the two loading paths by whether the +pre-sharding legacy `signs.json` is still present at its legacy path, not merely by whether region files exist yet +(`RegionShardedSignEntryLoader.hasSignData`) — a crash partway through a first migration can leave some region +files written and others missing, and the legacy file is the actual source of truth until it's renamed to its +`.migrated` backup, so its continued presence (regardless of what's already on disk region-sharded) means +`LegacySignFileMigrator` must re-run and re-derive every region file from it. Once the legacy file is gone (already +backed up), `loadSigns` loads every region file the same version-aware way as before sharding — the versioned-file +loader (`VersionedFileSignEntryLoader`, handling V2→V3 migration via `Version3Converter`, V3→V4 migration via +`Version4Converter` (adds `createdAtMillis`, needed to order points within a line marker; backfilled for pre-V4 +entries), V4→V5 migration via `Version5Converter` (adds raw front/back sign lines, backfilled `null` for pre-V5 +entries — needed to reparse a sign against a reloaded config instead of trusting a stale cached parse), and V5→V6 +migration via `Version6Converter` (adds front/back dye, backfilled to `SignEntryHelper.UNDYED_DYE` for pre-V6 +entries), and current V6 files directly), falling back to `Version1SignEntryLoader` for pre-versioning files. When +`LegacySignFileMigrator` runs, it writes the entries out region-sharded (`RegionShardedSignEntryWriter`, via +temp-file + atomic move so a crash mid-write never leaves a truncated region file) and backs up the legacy file +(renamed, not deleted) only once every expected region file round-trip parses back to valid data — not just exists +on disk, since a truncated file existing but failing to parse must still block finalizing the migration (see +`docs/adr/0004-atomic-write-content-verify-persistence.md`). When adding a new persisted field, bump `SignFileVersions` and add a loader/converter rather than changing an existing version's shape in place — old region files (or a not-yet-migrated legacy `signs.json`) on live servers must keep loading. @@ -165,9 +180,14 @@ region files (or a not-yet-migrated legacy `signs.json`) on live servers must ke New `MarkerAction` subtypes go through `ActionFactory` (construction) and need a `case` arm added in both `BlueMapAPIConnector.processMarkerAction`'s switch and `logProcessingMessage`'s switch — `MarkerAction` is a plain abstract class (not sealed), so a missing case silently falls through to the `default` branch instead of failing to -compile. Line markers add `SetLineMarkerAction` (create/update a line's rendered points), `RemoveLineMarkerAction` -(a line drops back below 2 members), and `GroupTransitionMarkerAction` (a sign's representation changes id scheme -between reloads, e.g. a group's `type` flipping `POI`↔`LINE` — dispatches an explicit remove of the old marker +compile. Line/shape/extrude markers add `SetMultiPointMarkerAction` (create/update a line/shape/extrude's rendered +points; replaces the former per-kind `SetLineMarkerAction`/`SetShapeMarkerAction`/`SetExtrudeMarkerAction`, +distinguished the same way by `MultiPointMarkerIdentifier`'s `kind` field, with the per-kind minimum-points threshold +sourced from `MultiPointGroupThresholds`'s `LINE_MIN_MEMBERS`/`SHAPE_MIN_MEMBERS`/`EXTRUDE_MIN_MEMBERS`), +`RemoveMultiPointMarkerAction` (a line/shape/extrude drops back below its minimum member count; also used for +shape/extrude removal, distinguished by `MultiPointMarkerIdentifier`'s `kind` field), and `GroupTransitionMarkerAction` +(a sign's representation changes id +scheme between reloads, e.g. a group's `type` flipping `POI`↔`LINE` — dispatches an explicit remove of the old marker alongside the new one so nothing is orphaned in BlueMap's web UI); `GroupTransitionMarkerAction` replaced the earlier `ChangeGroupMarkerAction`. @@ -178,13 +198,16 @@ signature (like `SignLinesParser`/`ParsingContext`, `SignEntry`/`SignEntryHelper `MarkerGroup`/`MarkerGroupMatchType`, `ConfigManager`/`ConfigProvider`, `ReactiveQueue`, `HtmlUtils`, `FileUtils`, the persistence loaders/converters (including `Version1SignEntryLoader`, `Version4Converter`), `ActionFactory`/`MarkerSetIdentifierCollection`, `LineGroupResolver`, `SignTransitionResolver`, `ColorUtils`, -`DispatchedMarkerIdentifier`/`LineMarkerIdentifier`/`LinePoint`, `RenderMaskEvaluator`) — these can be unit tested +`DispatchedMarkerIdentifier`/`MultiPointMarkerIdentifier`/`LinePoint`, `RenderMaskEvaluator`) — these can be unit tested directly (see `src/test/java/.../core/signs/SignLinesParserTest.java` for the pattern). -Code that must reference game types (`SignHelper`, the mixins, `BlueMapSignMarkersMod`, `BlueMapAPIConnector`) -should stay thin glue around the testable core, since it can only be verified manually via `runServer`. +Code that must reference game types (`SignHelper`, the mixins, `BlueMapSignMarkersMod`, `BlueMapAPIConnector`, +`MarkerMutations`) should stay thin glue around the testable core, since it can only be verified manually via +`runServer`. `MarkerMutations` (the marker-construction logic extracted out of `BlueMapAPIConnector`, see above) is +mostly game-coupled too, but its `resolveExtrudeHeightRange` static takes/returns no `bluemap-api` types, so it's +directly testable the same way `BlueMapAPIConnector`'s own `pointOf`/`isInsideRenderBounds` statics are. -`BlueMapAPIConnector` escapes sign text (`HtmlUtils.toHtmlDetail`, in `common`) before it reaches BlueMap's POI +`MarkerMutations` escapes sign text (`HtmlUtils.toHtmlDetail`, in `common`) before it reaches BlueMap's POI marker `detail` field — BlueMap renders `detail` as raw HTML (unlike `label`, which BlueMap escapes itself), and sign text is player-controlled, so this closes a live XSS vector. See `agent-context/plans/html-detail-escaping-plan.md` for the design. Persisted sign data stays raw/unescaped; escaping happens only at this BlueMap API call site. diff --git a/README.md b/README.md index c0a9546..0ff88c0 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,9 @@ The mod will create a `BMSM-Core.json` file in the `config/bluemapsignmarkers` f options: - `markerGroups` - a list of marker groups (described in detail below); default is a list with a single marker group configured for the `[poi]` prefix. +- `shutdownAwaitSeconds` - how long (in seconds) the mod waits for in-flight BlueMap marker updates to finish when +BlueMap disables (or the server stops), before forcing them to stop; optional; default is `5`; must be a positive +number, otherwise it falls back to the default with a warning. ## Marker Groups A marker group is a collection of markers that can be toggled on and off in the BlueMap UI. Each marker group diff --git a/agent-context/README.md b/agent-context/README.md index 9e8f826..3a9e514 100644 --- a/agent-context/README.md +++ b/agent-context/README.md @@ -33,4 +33,4 @@ method-level behavior, data-shape history — so an agent doesn't have to re-der | `context/testing.md` | `src/test/java/`, `.github/workflows/build.yml`, `.github/workflows/publish.yml` | --- -*Last updated: 2026-09-06 | Verified against: feature/tpwalke2/198-dye-colors (535bb13)* +*Last updated: 2026-09-12 | Verified against: feature/tpwalke2/209-signtransitionresolver (4d45867)* diff --git a/agent-context/context/architecture.md b/agent-context/context/architecture.md index 97a08f6..d872c5f 100644 --- a/agent-context/context/architecture.md +++ b/agent-context/context/architecture.md @@ -43,17 +43,17 @@ AGENTS.md / CLAUDE.md AI agent guidance (source of tr | Package | Contents | |---------|----------| | `com.tpwalke2.bluemapsignmarkers` (root) | `BlueMapSignMarkersMod` (entrypoint, lifecycle hooks; implements `ServerPathProvider`), `Constants` (`MOD_ID`), `ServerPathProvider` (interface: `getMarkerStorageRoot(MinecraftServer): Path`, resolves `{server_root}/bluemapsignmarkers/{level}`) | -| `common` | `FileUtils` — `createBackup`/`moveToBackup(originalPath, suffix, description)` (copy- vs. rename-based backup, used by config/sign migration code before overwriting or retiring an old-format file); `HtmlUtils` — `escape`/`toHtmlDetail`, escapes player-supplied sign text before it crosses into BlueMap's HTML-rendered marker `detail` field; `ColorUtils` — `parseHex(String) -> int[]{r,g,b,a}`, parses a line marker's hex color (`"#RRGGBB"`/`"#RRGGBBAA"`, leading `#` optional), falling back to opaque red with a log rather than throwing on malformed input | +| `common` | `SafeCall` — `run(label, Runnable)`, wraps a lifecycle-hook/mixin entry point in a catch-log-and-continue so a single bad event never crashes the server (see `AGENTS.md`'s "Mod must never crash the server" principle); `ServerPathResolver` — `resolveMarkerStorageRoot`/`resolveLegacyMarkerFilePath(Path rawLevelPath)`, pure `Path`/`String` math extracted from `BlueMapSignMarkersMod` (Minecraft-coupled) so it's directly unit-testable (see `config-and-persistence.md`); `FileUtils` — `createBackup`/`moveToBackup(originalPath, suffix, description)` (copy- vs. rename-based backup, used by config/sign migration code before overwriting or retiring an old-format file); `HtmlUtils` — `escape`/`toHtmlDetail`, escapes player-supplied sign text before it crosses into BlueMap's HTML-rendered marker `detail` field (`escape(null)` returns `""`); `ColorUtils` — `parseHex(String) -> int[]{r,g,b,a}`, parses a line marker's hex color (`"#RRGGBB"`/`"#RRGGBBAA"`, leading `#` optional), falling back to opaque red with a log rather than throwing on malformed input | | `config` | `ConfigManager` (lazy `volatile` singleton over the loaded config, `reload()` on first null `get()`), `ConfigProvider` (load/save/migrate `BMSM-Core.json`) | | `config.models` | `BMSMConfigV1` (legacy, single `poiPrefix` field), `BMSMConfigV2` (current runtime shape — `MarkerGroup[]`, ctor also seeds Gson defaults) | | `config.persistence` | `LoadingBMSMConfigV2` / `LoadingMarkerGroupV2` — a *nullable-boxed-field* mirror of `BMSMConfigV2`/`MarkerGroup` used only for Gson deserialization, so partially-specified user JSON can be detected and defaulted field-by-field in `ConfigProvider.convertToLoadedMarkerGroup` rather than Gson silently zeroing missing primitives | | `core` | `WorldMap` — just the `UNKNOWN` dimension-key sentinel used when a sign's `Level` is null | | `core.bounds` | `RenderMaskEvaluator` (plain Java, no Minecraft/Fabric/BlueMap types: hand-rolled parser for a BlueMap map's `render-mask` config, `load(mapId, mapsConfigDir)` returns a reusable `RenderMask`), `RenderMaskShape` (interface: `contains(x,y,z)`/`subtract()`), `RenderMaskBox`/`RenderMaskCircle`/`RenderMaskEllipse`/`RenderMaskPolygon` (records implementing it), `RenderMaskPoint` (record: polygon vertex, `x`/`z` only) — see `core-pipeline.md` §8 | | `core.bluemap` | `BlueMapAPIConnector` (the only class that touches the BlueMap API), `IResetHandler` (callback interface `SignManager` implements to replay its cache on BlueMap reset) | -| `core.bluemap.actions` | `MarkerAction` (abstract base, holds a `DispatchedMarkerIdentifier`), `AddMarkerAction`/`UpdateMarkerAction`/`RemoveMarkerAction`, `SetLineMarkerAction` (create/update a line's rendered points, carries the full current point list plus a log-only `isFirstAppearance` flag), `RemoveLineMarkerAction` (a line drops back below 2 members), `SetShapeMarkerAction`/`RemoveShapeMarkerAction` (the `SHAPE`-type counterparts, carrying `lineWidth`/`lineColor`/`fillColor` in addition to points), `SetExtrudeMarkerAction`/`RemoveExtrudeMarkerAction` (the `EXTRUDE`-type counterparts, structurally identical to the `SHAPE` pair), `GroupTransitionMarkerAction` (bundles 0-2 `MarkerAction` effects so a sign's representation change — a `POI`/`LINE`/`SHAPE`/`EXTRUDE` type flip, or a prefix change between groups — dispatches leave+join atomically; replaced the deleted `ChangeGroupMarkerAction`), `ActionFactory` (builds actions, resolves `MarkerSetIdentifier`s) | -| `core.markers` | `MarkerGroup` (record: the config unit; gained `lineWidth`/`lineColor`/`fillColor` trailing fields — `fillColor` is `SHAPE`/`EXTRUDE`-only), `MarkerGroupMatchType` (`STARTS_WITH`/`REGEX`), `MarkerGroupType` (`POI`, `LINE`, `SHAPE`, or `EXTRUDE`), `MarkerIdentifier`/`MarkerSetIdentifier`/`MarkerSetIdentifierCollection` (marker identity + dedup), `DispatchedMarkerIdentifier` (interface: `parentSet()`/`getId()`, generalizes over position-keyed and content-keyed marker ids), `LineMarkerIdentifier` (record: `label`, `parentSet`; `getId()` is `"line:" + label` — content-keyed, not position-keyed), `ShapeMarkerIdentifier` (record: same shape as `LineMarkerIdentifier`, `getId()` is `"shape:" + label`), `ExtrudeMarkerIdentifier` (record: same shape again, `getId()` is `"extrude:" + label`), `LinePoint` (record: `x, y, z`, one rendered point of a line/shape/extrude volume) | +| `core.bluemap.actions` | `MarkerAction` (abstract base, holds a `DispatchedMarkerIdentifier`), `AddMarkerAction`/`UpdateMarkerAction`/`RemoveMarkerAction`, `SetMultiPointMarkerAction` (create/update a line/shape/extrude's rendered points — one class for all three kinds, carrying `lineWidth`/`lineColor`/optional `fillColor`, the full current point list, and a log-only `isFirstAppearance` flag; replaced the former separate `SetLineMarkerAction`/`SetShapeMarkerAction`/`SetExtrudeMarkerAction`, which were structurally identical apart from `fillColor` presence and their minimum-points threshold), `RemoveMultiPointMarkerAction` (a line/shape/extrude drops back below its minimum member count; handles all three kinds via `MultiPointMarkerIdentifier`'s `kind` field — replaced the separate `RemoveLineMarkerAction`/`RemoveShapeMarkerAction`/`RemoveExtrudeMarkerAction`, which were structurally identical apart from their `toString()` class-name literals), `GroupTransitionMarkerAction` (bundles 0-2 `MarkerAction` effects so a sign's representation change — a `POI`/`LINE`/`SHAPE`/`EXTRUDE` type flip, or a prefix change between groups — dispatches leave+join atomically; replaced the deleted `ChangeGroupMarkerAction`), `ActionFactory` (builds actions, resolves `MarkerSetIdentifier`s — one factory-method pair, `createSetMultiPointAction`/`createRemoveMultiPointAction`, covers `LINE`/`SHAPE`/`EXTRUDE` alike, deriving kind/minimum-members from `MarkerGroup.type()`; `createGroupTransitionPOIAction` is the `POI`↔`POI` group-change counterpart, renamed from `createChangeGroupPOIAction`) | +| `core.markers` | `MarkerGroup` (record: the config unit; gained `lineWidth`/`lineColor`/`fillColor` trailing fields — `fillColor` is `SHAPE`/`EXTRUDE`-only), `MarkerGroupMatchType` (`STARTS_WITH`/`REGEX`), `MarkerGroupType` (`POI`, `LINE`, `SHAPE`, or `EXTRUDE`), `MarkerIdentifier`/`MarkerSetIdentifier`/`MarkerSetIdentifierCollection` (marker identity + dedup), `DispatchedMarkerIdentifier` (interface: `parentSet()`/`getId()`, generalizes over position-keyed and content-keyed marker ids), `MultiPointMarkerIdentifier` (record: `kind`, `label`, `parentSet`; `getId()` is `kind + ":" + label` — content-keyed, not position-keyed; `kind` is `"line"`/`"shape"`/`"extrude"` — replaced the separate `LineMarkerIdentifier`/`ShapeMarkerIdentifier`/`ExtrudeMarkerIdentifier` records, which differed only by that hardcoded id-prefix), `LinePoint` (record: `x, y, z`, one rendered point of a line/shape/extrude volume) | | `core.reactive` | `ReactiveQueue` (generic buffer-while-unavailable queue) + its three functional-interface callbacks (`ShouldRunCallback`, `MessageProcessorCallback`, `MessageProcessorErrorCallback`) — see `core-pipeline.md` | -| `core.signs` | `SignEntry`/`SignEntryKey` (immutable sign snapshot + position/dimension key; `SignEntry` gained `createdAtMillis` (orders points within a line/shape/extrude volume) and `frontRawLines`/`backRawLines` (raw, unparsed sign text per side — `null` for entries migrated from pre-V5 data, backing the reparse-on-reload self-heal, see `core-pipeline.md` §3), `SignHelper` (game-coupled: builds `SignEntry` from a `SignBlockEntity`, capturing both the parsed result and the raw lines), `SignEntryHelper` (plain-Java: derives label/detail/prefix from a `SignEntry`), `SignLinesParser`/`ParsingContext`/`SignLinesParseResult` (plain-Java parsing state machine), `SignManager` (singleton decision point — cache + dispatch), `SignChunkKey`/`SignChunkIndex` (plain-Java chunk-position lookup backing chunk-load sign reconciliation, see `core-pipeline.md` §4), `LineGroupResolver` (plain-Java: resolves a `LINE` group's members — signs sharing `(parentMap, prefix, label)` — sorted by `createdAtMillis` then position for deterministic tie-breaking), `ShapeGroupResolver`/`ExtrudeGroupResolver` (plain-Java: the `SHAPE`/`EXTRUDE` counterparts, both delegate directly to `LineGroupResolver.members` — identical filtering/ordering, only the caller-side minimum-member count differs, see `core-pipeline.md` §3; see `docs/adr/0002-shape-duplicates-line-pattern.md` for why this duplicates rather than generalizes) | +| `core.signs` | `PlayerIds` (`UNKNOWN` sentinel for "no player id known" — a sign event from a hook with no `Player` in scope, e.g. a dye click or a chunk-load event; a separate constant from `WorldMap.UNKNOWN`, which is the no-dimension-known sentinel — both currently hold `"unknown"`, but must stay distinct since `PlayerIds.UNKNOWN` is compared/persisted as a real `playerId`), `SignEntry`/`SignEntryKey` (immutable sign snapshot + position/dimension key; `SignEntry` gained `createdAtMillis` (orders points within a line/shape/extrude volume) and `frontRawLines`/`backRawLines` (raw, unparsed sign text per side — `null` for entries migrated from pre-V5 data, backing the reparse-on-reload self-heal, see `core-pipeline.md` §3), `SignHelper` (game-coupled: builds `SignEntry` from a `SignBlockEntity`, capturing both the parsed result and the raw lines), `SignEntryHelper` (plain-Java: derives label/detail/prefix from a `SignEntry`), `SignLinesParser`/`ParsingContext`/`SignLinesParseResult` (plain-Java parsing state machine), `SignManager` (singleton decision point — cache + dispatch), `SignChunkKey`/`SignChunkIndex` (plain-Java chunk-position lookup backing chunk-load sign reconciliation, see `core-pipeline.md` §4), `LineGroupResolver` (plain-Java: resolves a `LINE` group's members — signs sharing `(parentMap, prefix, label)` — sorted by `createdAtMillis` then position for deterministic tie-breaking), `ShapeGroupResolver`/`ExtrudeGroupResolver` (plain-Java: the `SHAPE`/`EXTRUDE` counterparts, both delegate directly to `LineGroupResolver.members` — identical filtering/ordering, only the caller-side minimum-member count differs, see `core-pipeline.md` §3; see `docs/adr/0002-shape-duplicates-line-pattern.md` for why this duplicates rather than generalizes) | | `core.signs.persistence` | `SignProvider` (load/save, dispatches to the region-sharded loader/writer or migration), `SignFileVersions` (`V1`-`V5` — per-region-file schema version, unchanged by sharding; `V5` current, adds `frontRawLines`/`backRawLines`), `VersionedSignFile` (`{version, data}` envelope), `SignRegionKey` (record: dimension + region coords; `forPosition` does the `floorDiv` region math, `relativeFilePath` builds the `{namespace}/{path}/r.{x}.{z}.json` path), `SignRegionPartitioner` (groups `SignEntry`s by `SignRegionKey`), `RegionShardedSignEntryWriter` (writes each region's file, current version `V5`; region files that dropped to zero signs are quarantined with a `.stale` suffix, not deleted, unless any region write failed — in which case quarantine is skipped entirely, to avoid mistaking a load failure for a genuine "signs removed" case), `LegacySignFileMigrator` (one-shot: reads the pre-sharding single file through the existing V1-V5 chain, writes it out sharded, backs up the legacy file only once every expected region file is confirmed written to disk) | | `core.signs.persistence.loaders` | `VersionedFileSignEntryLoader` (tries versioned envelope; V2 → `Version3Converter` → `Version4Converter` → `Version5Converter`, backs up as `.v2.bak`; V3 → `Version4Converter` → `Version5Converter`, backs up as `.v3.bak`; V4 → `Version5Converter`, backs up as `.v4.bak`), `Version1SignEntryLoader` (pre-versioning fallback; also normalizes legacy `nether`/`end`/`overworld` map-id strings to real dimension identifiers — the identifiers are spelled out as literal strings rather than read from `net.minecraft.world.level.Level` statics, so the class has no Minecraft-type dependency and is fully unit-testable), `Version3Converter` (V2 model → `SignEntryV3` shape), `Version4Converter` (V3 model → `SignEntryV4` shape, adding `createdAtMillis` — backfilled per-entry as `fileLastModifiedMillis + indexInFile`, arbitrary but stable, since no real placement history exists for pre-existing signs), `Version5Converter` (`SignEntryV4` → current `SignEntry`, setting both `frontRawLines`/`backRawLines` to `null` since no raw text exists on disk to backfill from), `RegionShardedSignEntryLoader` (walks a storage root's directory tree, loads each region file via `VersionedFileSignEntryLoader`, flattens to one list; `hasSignData(Path)` is the migration-trigger check) | | `core.signs.persistence.models` | `SignEntryV2`, `SignLinesParseResultV2`, `MarkerTypeV2` (frozen V2 shape, kept solely so `Version3Converter` can still read old files), `SignEntryV3` (frozen copy of the pre-`createdAtMillis` `SignEntry` shape, kept solely so `Version4Converter` can still read old files), `SignEntryV4` (frozen copy of the pre-raw-lines `SignEntry` shape, kept solely so `Version5Converter` can still read old files) — do not evolve these, they must stay byte-compatible with historical `signs.json` | @@ -71,12 +71,13 @@ dev source for `runServer`/`runClient`. - `./gradlew test` — JUnit 5 suite only (`src/test/java`) - `./gradlew runServer` / `runClient` — dev Minecraft instance with the mod + BlueMap loaded - `.github/workflows/build.yml` — runs on push/PR to `main` and `releases/**`: `./gradlew test` → summarize JUnit - XML results to `$GITHUB_STEP_SUMMARY` (plain shell `sed`, no third-party reporter action — see `testing.md` for - why) → `./gradlew build` → upload `build/libs/` as an artifact + XML results to `$GITHUB_STEP_SUMMARY` via the shared composite action `.github/actions/summarize-test-results/` + (plain shell `sed`, no third-party reporter action — see `testing.md` for why) → `./gradlew build` → upload + `build/libs/` as an artifact - `.github/workflows/publish.yml` — manual `workflow_dispatch` only: runs tests first (failure blocks publish), then `./gradlew modrinth -PbuildNumber=` (alpha, from a branch dispatch) or the same with `-PisRelease` (release, from a `v*` tag dispatch) --- -*Last updated: 2026-09-06 | Verified against: feature/tpwalke2/198-dye-colors (535bb13)* +*Last updated: 2026-09-11 | Verified against: feature/tpwalke2/209-actionfactory (5eb0f1d)* diff --git a/agent-context/context/config-and-persistence.md b/agent-context/context/config-and-persistence.md index 099a0c3..2c0b645 100644 --- a/agent-context/context/config-and-persistence.md +++ b/agent-context/context/config-and-persistence.md @@ -10,10 +10,15 @@ loading/migration mechanics, not the format itself. File: `config/bluemapsignmarkers/BMSM-Core.json`. Path is fixed (not per-world) — `ConfigProvider.getConfigPath()` = `Path.of("config", Constants.MOD_ID, "BMSM-Core.json")`. -- `ConfigManager.get()` returns a `volatile` singleton reference, lazily populated by calling `reload()` on first - access if still `null` (not an eager static-field initializer — that would run the instant anything references - the class, including a test merely loading `ConfigManagerTest`, and write a real config file as a side effect). - **Config is hot-reloadable**: `ConfigManager.reload()` (`synchronized`, public) loads via `ConfigProvider.loadConfig()` +- `ConfigManager.get()` returns a singleton reference, lazily populated by calling `reload()` on first access if + still `null` (not an eager static-field initializer — that would run the instant anything references the class, + including a test merely loading `ConfigManagerTest`, and write a real config file as a side effect). The + null-check-then-load is itself double-checked-locking (finding #72, + `agent-context/reviews/full-codebase-review_2026-09-07_0900.md`): the unsynchronized first check avoids paying a + lock on every `get()` call once loaded, but a second check *inside* a `synchronized (ConfigManager.class)` block + guards the actual `reload()` call, so racing first-time callers converge on a single load/parse pass and the same + config instance instead of each redundantly loading and racing over which instance wins. **Config is + hot-reloadable**: `ConfigManager.reload()` (`synchronized`, public) loads via `ConfigProvider.loadConfig()` and swaps the reference; `volatile` alone is enough for safe publication to other threads since the new `BMSMConfigV2` is fully built before the swap. Reload is wired to BlueMap's `/bluemap reload` via `SignManager.reloadConfig()` — see `core-pipeline.md` §3. A package-private `reload(Path)` overload (and matching @@ -75,7 +80,12 @@ File: `config/bluemapsignmarkers/BMSM-Core.json`. Path is fixed (not per-world) `lineWidth`/`lineColor`, which both also use for their border) — those fields are silently ignored for the group's actual type, so this just flags a likely config mistake rather than rejecting it. `sorting`/`toggleable` apply to every group type (thin `MarkerSet` passthroughs — see `core-pipeline.md` §6) so neither has a - type-mismatch warning. `allowPlayerColors` (GitHub issue #198) is `LINE`/`SHAPE`/`EXTRUDE`-only, resolved by + type-mismatch warning. `name` has no default-safe fallback like the fields above (it's not derivable from a + Java default, only from the group's own prefix): `resolveName` returns the configured name if non-blank, + otherwise falls back to the group's `prefix` if that's non-blank, otherwise the literal `"(unnamed)"`, logging + a warning either way — this replaced passing `markerGroup.name()` straight to `MarkerGroup`'s constructor, + which `requireNonNull`s the field and previously threw on a missing/blank name, wiping the *entire* config + back to defaults rather than degrading just that one group. `allowPlayerColors` (GitHub issue #198) is `LINE`/`SHAPE`/`EXTRUDE`-only, resolved by `resolveAllowPlayerColors`: unset or set on a `POI` group both resolve to `false` (`warnOnTypeFieldMismatches` warns on the `POI` case, alongside `lineWidth`/`lineColor`/`fillColor`/`depthTest`). It lets a player set a multi-point marker's rendered colour by dyeing one of its member signs instead of an admin editing @@ -83,10 +93,22 @@ File: `config/bluemapsignmarkers/BMSM-Core.json`. Path is fixed (not per-world) 4. Any exception during load (`Gson.fromJson` failure, I/O error, or a `validateMarkerGroups` failure) logs and returns `null`, and `ConfigManager.loadCoreConfig` falls back to `new BMSMConfigV2()` defaults — a broken config file never prevents server startup, it just silently reverts to a single default `[poi]` group. +- `BMSMConfigV2` also carries `shutdownAwaitSeconds` (default `DEFAULT_SHUTDOWN_AWAIT_SECONDS = 5`) — how long + `ReactiveQueue.shutdown()` (the BlueMap marker-action queue, `core-pipeline.md` §7) waits for in-flight tasks to + finish before forcing a `shutdownNow()`. Loaded the same validating-with-fallback way as `sorting` + (`LoadingBMSMConfigV2.shutdownAwaitSeconds` is a raw `JsonElement`, not a boxed `Integer`, so a malformed value — + wrong type or non-positive — degrades to the default with a warning via `resolveShutdownAwaitSeconds` instead of + failing `Gson.fromJson` for the whole config). `BlueMapAPIConnector.resetQueue()` reads + `ConfigManager.get().getShutdownAwaitSeconds()` when building each new `ReactiveQueue` instance, so an edited value + takes effect on the next BlueMap disable/enable or `/bluemap reload` (the connector's `onEnable` reloads config + *before* calling `resetQueue()` specifically so this value is current at construction time, not one reload behind + — see `core-pipeline.md` §6). - Config file reads/writes both go through `StandardCharsets.UTF_8` explicitly (`Files.readString`/ `OutputStreamWriter`, ticket 01) rather than the JVM's platform-default charset, so a non-ASCII marker-group name survives a restart regardless of the host's default encoding. - `saveConfig(config)` creates parent dirs if needed and writes pretty-printed Gson JSON. +- `BMSMConfigV2.getMarkerGroups()` returns `markerGroups.clone()`, a defensive shallow copy — a caller mutating the + returned array (e.g. reordering it) can no longer corrupt the singleton config's own backing array. ## Sign persistence (`core/signs/persistence/`) @@ -99,15 +121,18 @@ Storage root is **per-world, region-sharded**: `{server_root}/bluemapsignmarkers externally deleted/regenerated — GitHub issue #109) can query "signs known in this region" cheaply instead of scanning every cached sign; that reconciliation logic itself is not yet implemented. -`ServerPathProvider.getMarkerStorageRoot(server)` (implemented on `BlueMapSignMarkersMod`) resolves the root: -`levelDir = server.getWorldPath(LevelResource.ROOT).toAbsolutePath().normalize()`, server root = -`levelDir.getParent()`, level name = `levelDir.getFileName()`. The `.normalize()` is required because +`ServerPathProvider.getMarkerStorageRoot(server)` (implemented on `BlueMapSignMarkersMod`) delegates to +`ServerPathResolver.resolveMarkerStorageRoot(rawLevelPath)` (`common`, plain Java — extracted so this path math is +directly unit-testable, see `architecture.md`): `levelDir = rawLevelPath.normalize()`, server root = +`levelDir.getParent()`, level name = `levelDir.getFileName()`, where `rawLevelPath` is +`server.getWorldPath(LevelResource.ROOT).toAbsolutePath()`. The `.normalize()` is required because `LevelResource.ROOT`'s relative path is literally `"."`, which `Path.resolve()` doesn't collapse on its own — skipping it shifts `getParent()`/`getFileName()` by one level and lands the storage root inside the world save folder instead of beside it. This also fixed a pre-existing bug where the old path formula's extra `.getParent()` resolved to the *run directory's* name, not the level name (`../plans/codebase-review-2026-07-11.md` finding #1). -`BlueMapSignMarkersMod.getLegacyMarkerFilePath` intentionally keeps the old (buggy) formula unchanged — migration -must locate files at the path they were actually written to, not the corrected one. +`BlueMapSignMarkersMod.getLegacyMarkerFilePath` delegates to `ServerPathResolver.resolveLegacyMarkerFilePath`, which +intentionally keeps the old (buggy) formula unchanged — migration must locate files at the path they were actually +written to, not the corrected one. Loaded on `SERVER_STARTING`, saved on `SERVER_STOPPING` (then `SignManager.stop()`). @@ -149,8 +174,11 @@ representation. `relativeFilePath()` splits `dimension` (a string like `minecraft:overworld`, or the `WorldMap.UNKNOWN` sentinel `"unknown"` with no colon) on the first `:` into namespace/path segments, appending `r.{regionX}.{regionZ}.json`. It rejects (throws `IllegalArgumentException`) a blank/`.`/`..` namespace, or a resolved relative path that's -absolute, starts with `..`, or otherwise escapes the namespace directory after `.normalize()` — a defense against a -maliciously/accidentally crafted dimension id writing outside the storage root. +absolute, starts with `..`, has a non-`null` root component (catches a Windows "drive-relative" path — e.g. a raw +path segment starting with a single `\` — that reports `isAbsolute() == false` but still carries a root component +`resolve()` takes on in place of the namespace directory, so `isAbsolute()` alone wouldn't catch it), or otherwise +escapes the namespace directory after `.normalize()` — a defense against a maliciously/accidentally crafted +dimension id writing outside the storage root. `SignRegionPartitioner.partition(List)` groups entries into `Map>` using each entry's `key().parentMap()`/`x()`/`z()` — the shared grouping logic behind both save and migration. @@ -177,7 +205,10 @@ each entry's `key().parentMap()`/`x()`/`z()` — the shared grouping logic behin a `V5` file goes straight to `Version6Converter`. All loaders isolate per-entry conversion failures (`convertV2EntrySafely`/`loadEntry`, ticket 05) so one malformed V1/V2 entry logs and is skipped instead of losing the whole file — the same pattern `SignProvider.loadSigns` already applies per entry at step 3 below. - `Version1SignEntryLoader`'s dimension + Every `V3`/`V4`/`V5`/current-version branch also filters out `null` elements from the deserialized array + (`Arrays.stream(...).filter(Objects::nonNull)`, GitHub issue #198 review finding) before converting/returning + it — a JSON array with a stray `null` entry (hand-edited or corrupted file) would otherwise NPE partway through + conversion instead of just dropping that one slot. `Version1SignEntryLoader`'s dimension normalization (`getNormalizedMapId`) recognizes both the short legacy names (`"nether"`/`"end"`/`"overworld"`) and the canonical-but-unnamespaced resource paths (`"the_nether"`/`"the_end"`), with or without a `minecraft:` namespace already attached (ticket 05) — previously only the three exact lowercase shorthand strings @@ -192,11 +223,16 @@ each entry's `key().parentMap()`/`x()`/`z()` — the shared grouping logic behin still returning the converted current-version entries in-memory without a pre-migration backup on disk. - Writes the resulting entries via `RegionShardedSignEntryWriter.write(...)` (see below). Backs up the legacy file via `FileUtils.moveToBackup(legacyPath, ".migrated", ...)` — **renamed, not deleted** — only after - confirming every region file expected from `SignRegionPartitioner.partition(entryList)` actually exists on - disk (or the entry list was empty to begin with); if any expected region file is missing, the legacy file is - left in place and an error is logged, so a partial/failed migration doesn't lose the only remaining copy of - the data. A successful migration isn't re-attempted on future boots since step 1 will find the new storage - root non-empty from then on. + `regionFilesRoundTripCleanly` confirms every region file expected from + `SignRegionPartitioner.partition(entryList)` round-trip parses back to the *exact same entry content* it was + written from (or the entry list was empty to begin with); if any expected region file is missing, fails to + parse, or parses to a different entry set than expected (matching count with different/altered content — e.g. + valid-but-corrupted JSON — used to slip past a size-only check), the legacy file is left in place and an error + is logged, so a partial/failed migration doesn't lose the only remaining copy of the data. The comparison is a + `Set` equality check (`SignEntry` is a record, so this is structural content comparison), not a + positional list compare, since the writer's on-disk ordering isn't guaranteed to match `partition()`'s + insertion order. A successful migration isn't re-attempted on future boots since step 1 will find the new + storage root non-empty from then on. 3. Every resulting `SignEntry` (from either path) is fed through `SignManager.addOrUpdate(...)` — same as before sharding, loading signs at startup goes through the exact same decision logic as any other sign event (see `core-pipeline.md` §3). Each entry is wrapped in its own try/catch, so one malformed entry logs an error and is @@ -255,5 +291,5 @@ in place. Old region files (or a not-yet-migrated legacy `signs.json`) on live s the version they were written with. --- -*Last updated: 2026-09-06 | Verified against: feature/tpwalke2/198-dye-colors (535bb13)* +*Last updated: 2026-09-09 | Verified against: main (b2c5fa0)* diff --git a/agent-context/context/core-pipeline.md b/agent-context/context/core-pipeline.md index 33cc821..b5cd2ec 100644 --- a/agent-context/context/core-pipeline.md +++ b/agent-context/context/core-pipeline.md @@ -12,10 +12,12 @@ builds/adds) an entry: found) and calls `SignManager.addOrUpdate(...)` for every stored entry (see `config-and-persistence.md`). 2. **Block entity load** — `BlueMapSignMarkersMod.onBlockEntityLoad` (registered on `ServerBlockEntityEvents.BLOCK_ENTITY_LOAD`) fires for every loaded `SignBlockEntity` and calls - `SignHelper.createSignEntry(entity, WorldMap.UNKNOWN)` → `SignManager.addOrUpdate(...)`. Player id is the - `WorldMap.UNKNOWN` (`"unknown"`) sentinel here because chunk load isn't attributable to a player — this - constant is the single canonical source for that sentinel (ticket 08 consolidated a second, independent - `"unknown"` literal duplicated in `SignManager`; both now reference `WorldMap.UNKNOWN`). + `SignHelper.createSignEntry(entity, PlayerIds.UNKNOWN)` → `SignManager.addOrUpdate(...)`. Player id is the + `PlayerIds.UNKNOWN` (`"unknown"`) sentinel here because chunk load isn't attributable to a player. `PlayerIds` + (`core.signs`) is the single canonical source for that sentinel — deliberately a separate constant from + `WorldMap.UNKNOWN` (the no-dimension-known sentinel), even though both currently hold `"unknown"`, since + `PlayerIds.UNKNOWN` is compared/persisted as a real `playerId` and must keep that exact value regardless of + what `WorldMap.UNKNOWN` does. 3. **Mixins** (`src/main/resources/bluemapsignmarkers.mixins.json`, server-only, `JAVA_21` compat level): - `SignBlockEntityInject` injects `SignBlockEntity.updateSignText` at `HEAD` (sets a `@Unique` guard flag, `bluemapsignmarkers$inUpdateSignText`) and at `TAIL` (clears the flag) → a player edited a sign → @@ -25,7 +27,7 @@ builds/adds) an entry: guard a plain text edit would dispatch twice (harmless but wasteful). This second hook is what makes dyeing/glowing/un-glowing an already-placed sign (right-clicking it with a dye, ink sac, or glow ink sac — none of which call `updateSignText`) visible to the mod at all: `SignManager.addOrUpdate(SignHelper.createSignEntry(this, - WorldMap.UNKNOWN))`, `WorldMap.UNKNOWN` because no `Player` is available at this injection point. See + PlayerIds.UNKNOWN))`, `PlayerIds.UNKNOWN` because no `Player` is available at this injection point. See `../plans/player-marker-colors/spec.md` "Detecting a dye change: mixin" for why a mixin (not a Fabric API event) is the only clean hook for this. - `AbstractBlockInject` injects `BlockBehaviour.affectNeighborsAfterRemoval` at `HEAD`, but only proceeds @@ -79,7 +81,11 @@ the same label/detail. `SignEntryHelper` (plain Java, `core.signs`) derives the values `SignManager` dispatches from a `SignEntry`'s front/back `SignLinesParseResult`s: `getPrefix` prefers the front side's prefix, falling back to the back side's -(`null` if neither matched); `getLabel` likewise prefers front, falling back to back. `getDetail` merges both +(`null` if neither matched); `getLabel` likewise prefers front, falling back to back — but only falls back when +front and back either match the *same* group or the front side didn't match at all; if front and back matched two +*different* groups, a blank front label returns `""` rather than the back's label, since the marker belongs to the +front's group (mirrors `getDetail`'s same-group rule below, and closes the same class of bug: previously a blank +front label on a group-mismatched sign silently borrowed the other group's label text). `getDetail` merges both sides' detail text (`"FRONT: ...%nBACK: ..."`) only when front and back **matched the same marker group** (ticket 07, `.scratch/codebase-review-followups/issues/07-fix-dual-sided-sign-semantics.md`); when they matched two *different* groups, only the front side's detail is used — matching `getPrefix`'s front-preferred rule for which @@ -107,11 +113,14 @@ Singleton (double-checked locking), holds: re-reading the volatile field twice. - One `BlueMapAPIConnector`; `SignManager` registers itself as an `IResetHandler` on it. -`addOrUpdateSign`, `removeByKey`, and `reloadConfig` are all `synchronized` on the same monitor (finding #17, -`../plans/codebase-review-2026-07-11.md`, resolved 2026-07-23) — `reset()`'s config-swap-then-diff sequence in -`reloadConfig()` (below) runs on whatever thread `BlueMapAPI.onEnable` fires on, not necessarily the server thread, -so without this a live sign edit/removal arriving from the mixins mid-diff could be clobbered by a stale -dispatch, or a sign removed mid-diff could be silently re-added. `dispatch()` +`addOrUpdateSign`, `removeByKey`, and `reloadConfig`'s phase 1 (below) are all `synchronized` on the same monitor +(finding #17, `../plans/codebase-review-2026-07-11.md`, resolved 2026-07-23) — `reset()`'s config-swap-then-reparse +sequence runs on whatever thread `BlueMapAPI.onEnable` fires on, not necessarily the server thread, so without this a +live sign edit/removal arriving from the mixins mid-swap could be clobbered by a stale dispatch, or a sign removed +mid-swap could be silently re-added. `reloadConfig`'s phase 2 (the actual dispatch loop) runs **unlocked** — see +below, `.scratch/concurrency-pass-2026-09/issues/05-signmanager-reloadconfig-lock-contention.md` — since it's O(n²) +work (a membership filter/sort per `LINE`/`SHAPE`/`EXTRUDE` sign) that would otherwise block every concurrent sign +edit for the reload's full duration. `dispatch()` only enqueues onto `ReactiveQueue` under this lock (no blocking BlueMap API work), so it doesn't add hot-path contention the way locking around `processMarkerAction` would. @@ -142,15 +151,17 @@ re-querying the cache once per sign. `computeTransitionAction`'s logic (mirrors the table in the spec, generalized to a 4x4 grid of `POI`/`LINE`/`SHAPE`/ `EXTRUDE` alongside `NONE` — see `docs/adr/0002-shape-duplicates-line-pattern.md` for why each new multi-point type -duplicates the same pattern rather than generalizing it): +gets its own row/column and `MIN_MEMBERS` constant here rather than folding into `LINE`'s; the join/leave +*implementation* behind those cells is a single shared parameterized resolver, not duplicated per type — see +`multiPointJoinAction`/`multiPointLeaveAction` below): | Old \ New | NONE | POI | LINE | SHAPE | EXTRUDE | |---|---|---|---|---|---| -| **NONE** | no-op (`null`) | dispatch `createAddPOIAction` | `lineJoinAction` (recompute group *including* this sign; dispatch `SetLineMarkerAction` if ≥2 members, else no-op) | `shapeJoinAction` (same shape, gated on `SHAPE_MIN_MEMBERS = 3` instead of 2) | `extrudeJoinAction` (same shape again, gated on `EXTRUDE_MIN_MEMBERS = 3`) | -| **POI** | dispatch `createRemovePOIAction` | same group (prefix unchanged): label/detail both unchanged is a no-op, either changed dispatches `createUpdatePOIAction`. Different group (prefix changed): leave-effect + join-effect, bundled | leave-effect (Remove POI) + join-effect (`lineJoinAction`) | leave-effect (Remove POI) + join-effect (`shapeJoinAction`) | leave-effect (Remove POI) + join-effect (`extrudeJoinAction`) | -| **LINE** | `lineLeaveAction` (recompute group *excluding* this sign; `SetLineMarkerAction` if ≥2 remain, `RemoveLineMarkerAction` if exactly 1 remains, no-op if 0) | leave-effect (as above) + join-effect (Add POI) | same group+label: `lineJoinAction` with `sameGroupRecompute=true` (refreshes detail/points — always dispatches `Set` since ≥2 members necessarily already existed); different group/label: leave-effect + join-effect | leave-effect (`lineLeaveAction`) + join-effect (`shapeJoinAction`) | leave-effect (`lineLeaveAction`) + join-effect (`extrudeJoinAction`) | -| **SHAPE** | `shapeLeaveAction` (mirrors `lineLeaveAction`, but `RemoveShapeMarkerAction` once membership drops below 3) | leave-effect (`shapeLeaveAction`) + join-effect (Add POI) | leave-effect (`shapeLeaveAction`) + join-effect (`lineJoinAction`) | same group+label: `shapeJoinAction` with `sameGroupRecompute=true` (mirrors `LINE`/`LINE`); different group/label: leave-effect + join-effect | leave-effect (`shapeLeaveAction`) + join-effect (`extrudeJoinAction`) | -| **EXTRUDE** | `extrudeLeaveAction` (mirrors `shapeLeaveAction`, `RemoveExtrudeMarkerAction` once membership drops below 3) | leave-effect (`extrudeLeaveAction`) + join-effect (Add POI) | leave-effect (`extrudeLeaveAction`) + join-effect (`lineJoinAction`) | leave-effect (`extrudeLeaveAction`) + join-effect (`shapeJoinAction`) | same group+label: `extrudeJoinAction` with `sameGroupRecompute=true` (mirrors `SHAPE`/`SHAPE`); different group/label: leave-effect + join-effect | +| **NONE** | no-op (`null`) | dispatch `createAddPOIAction` | `multiPointJoinAction` (recompute group *including* this sign; dispatch `SetMultiPointMarkerAction` if ≥2 members, else no-op) | `multiPointJoinAction` (same call, gated on `SHAPE_MIN_MEMBERS = 3` instead of 2) | `multiPointJoinAction` (same call again, gated on `EXTRUDE_MIN_MEMBERS = 3`) | +| **POI** | dispatch `createRemovePOIAction` | same group (prefix unchanged): label/detail both unchanged is a no-op, either changed dispatches `createUpdatePOIAction`. Different group (prefix changed): leave-effect + join-effect, bundled | leave-effect (Remove POI) + join-effect (`multiPointJoinAction`) | leave-effect (Remove POI) + join-effect (`multiPointJoinAction`) | leave-effect (Remove POI) + join-effect (`multiPointJoinAction`) | +| **LINE** | `multiPointLeaveAction` (recompute group *excluding* this sign; `SetMultiPointMarkerAction` if ≥2 remain, `RemoveMultiPointMarkerAction` if exactly 1 remains, no-op if 0) | leave-effect (as above) + join-effect (Add POI) | same group+label: `multiPointJoinAction` with `sameGroupRecompute=true` (refreshes detail/points — always dispatches `Set` since ≥2 members necessarily already existed); different group/label: leave-effect + join-effect | leave-effect (`multiPointLeaveAction`) + join-effect (`multiPointJoinAction`) | leave-effect (`multiPointLeaveAction`) + join-effect (`multiPointJoinAction`) | +| **SHAPE** | `multiPointLeaveAction` (mirrors the `LINE` row, but `RemoveMultiPointMarkerAction` once membership drops below 3) | leave-effect (`multiPointLeaveAction`) + join-effect (Add POI) | leave-effect (`multiPointLeaveAction`) + join-effect (`multiPointJoinAction`) | same group+label: `multiPointJoinAction` with `sameGroupRecompute=true` (mirrors `LINE`/`LINE`); different group/label: leave-effect + join-effect | leave-effect (`multiPointLeaveAction`) + join-effect (`multiPointJoinAction`) | +| **EXTRUDE** | `multiPointLeaveAction` (mirrors the `SHAPE` row, `RemoveMultiPointMarkerAction` once membership drops below 3) | leave-effect (`multiPointLeaveAction`) + join-effect (Add POI) | leave-effect (`multiPointLeaveAction`) + join-effect (`multiPointJoinAction`) | leave-effect (`multiPointLeaveAction`) + join-effect (`multiPointJoinAction`) | same group+label: `multiPointJoinAction` with `sameGroupRecompute=true` (mirrors `SHAPE`/`SHAPE`); different group/label: leave-effect + join-effect | The POI/POI cell deliberately compares only `group().prefix()`, not label — a label-only edit on an unchanged group used to fall through to the different-group (leave+join) branch, because the older check compared @@ -160,11 +171,17 @@ EXTRUDE/EXTRUDE cells all use `sameGroupAndLabel(a, b)` (compares `group().prefi same-group-recompute shortcut condition is `oldType == newType && oldType != MarkerGroupType.POI && sameGroupAndLabel(...)`, generalized to cover any non-`POI` type rather than naming `LINE` explicitly, since a `LINE`/`SHAPE`/`EXTRUDE` group's identity (and marker id, §5) is keyed on group+label either way. The recompute -shortcut's no-op guard is `oldRep.detail().equals(newRep.detail()) && oldRep.dye().equals(newRep.dye()) && -!isReload` — `dye` was added to that guard (GitHub issue #198) alongside `detail` precisely so a dye-only edit -(detail unchanged) doesn't get silently swallowed: it makes `oldRep != newRep`, defeats the no-op check, and falls -through to the normal recompute path (`joinEffect`), which re-derives the marker's colour from the *current full -membership* via `ColorResolver` regardless of which member's dye actually changed. When a transition +shortcut's no-op guard is `oldRep.detail().equals(newRep.detail()) && dyeUnchanged && !isReload`, where +`dyeUnchanged = !newRep.group().allowPlayerColors() || Objects.equals(oldRep.dye(), newRep.dye())` — `dye` was added +to that guard (GitHub issue #198) alongside `detail` precisely so a dye-only edit (detail unchanged) doesn't get +silently swallowed: it makes `oldRep != newRep`, defeats the no-op check, and falls through to the normal recompute +path (`joinEffect`), which re-derives the marker's colour from the *current full membership* via `ColorResolver` +regardless of which member's dye actually changed. `Objects.equals` (not `oldRep.dye().equals(newRep.dye())`) is a +post-review fix (`../reviews/copilot-review-2026-09-07.md`): a `Representation`'s dye can be `null` in practice +(corrupted/hand-edited persisted data), and the direct `.equals()` call threw an NPE on that path. The +`allowPlayerColors()` short-circuit was added in the same fix so a group that hasn't opted into dye-derived colour +doesn't pay the full membership scan/sort/dispatch cost on every dye change to one of its signs — dye is compared +only when it could actually change the rendered colour. When a transition needs both a leave-effect and a join-effect (a group/label/type change, for any pair of the four types), each effect is computed independently (`null` if that half is a no-op, e.g. leaving a `LINE` group that still has ≥2 members after removal dispatches a `Set`, not a leave at all) and both are collected into a `List`: @@ -173,25 +190,30 @@ zero effects → `null`, one effect → dispatch it directly, two → bundle int `groupIdentityObsolete` (used by the config-reload path, below) is likewise type-agnostic, detecting a config-only type flip or rename for any of the four types. -`lineJoinAction(allSigns, parentMap, rep, actionFactory, sameGroupRecompute)` and `lineLeaveAction(allSigns, -parentMap, rep, actionFactory)` both call `LineGroupResolver.members(allSigns, parentMap, rep.group().prefix(), -rep.label())` against the caller-supplied snapshot — because `signCache` is a full, live snapshot (never cleared -for a config reload, see below), a snapshot taken once per dispatch always scans every sign currently known, so a -`LINE` group recompute is always complete and order-independent regardless of which member triggered it. -`lineJoinAction`'s `isFirstAppearance` flag (`!sameGroupRecompute && members.size() == 2`) is log-only — see §6 — -not a distinct dispatch type. `shapeJoinAction`/`shapeLeaveAction` and `extrudeJoinAction`/`extrudeLeaveAction` are -the direct `SHAPE`/`EXTRUDE` counterparts: they call `ShapeGroupResolver.members(...)`/`ExtrudeGroupResolver.members(...)`, -both of which just delegate to `LineGroupResolver.members(...)` (identical filtering/ordering — the only real -difference between `LINE`, `SHAPE`, and `EXTRUDE` group resolution is the caller-side minimum-member count, `2` vs. -`SHAPE_MIN_MEMBERS = 3` vs. `EXTRUDE_MIN_MEMBERS = 3`), and dispatch via `actionFactory.createSetShapeAction`/ -`createRemoveShapeAction` or `createSetExtrudeAction`/`createRemoveExtrudeAction` instead of the line equivalents. -Every join/leave-recompute call site calls `ColorResolver.resolve(members, rep.group())` (see below) immediately -before dispatching, and passes the resolved `lineColor`/`fillColor` into `createSetLineAction`/ -`createSetShapeAction`/`createSetExtrudeAction` as explicit parameters — `ActionFactory` no longer reads -`markerGroup.lineColor()`/`fillColor()` itself for these three factory methods, keeping it a dumb builder while -`SignTransitionResolver` owns colour resolution. These call sites also now pass `rep.detail()` (not `rep.label()`) -as the dispatched detail text — fixing a bug where a `LINE`/`SHAPE`/`EXTRUDE` marker's rendered detail was always -just its label repeated, since detail text on these signs was never actually threaded through. +`multiPointJoinAction(allSigns, parentMap, rep, actionFactory, sameGroupRecompute, resolver, minMembers, kind)` and +`multiPointLeaveAction(allSigns, parentMap, rep, actionFactory, currentPrefixGroupMap, resolver, minMembers, kind)` +are the single generic implementation behind all three `LINE`/`SHAPE`/`EXTRUDE` cells above — collapsed from three +near-identical `line*Action`/`shape*Action`/`extrude*Action` method pairs (GitHub issue #209) once it was clear they +differed only by which `GroupResolver` (`LineGroupResolver::members`/`ShapeGroupResolver::members`/ +`ExtrudeGroupResolver::members`) they called, the minimum-member threshold (`LINE_MIN_MEMBERS = 2` vs. +`SHAPE_MIN_MEMBERS = 3` vs. `EXTRUDE_MIN_MEMBERS = 3`), and whether a fill colour applies (`hasFill(kind)` is +`false` only for `LINE`, which has no fill). Both call the caller-supplied `resolver` against the caller-supplied +`allSigns` snapshot — because `signCache` is a full, live snapshot (never cleared for a config reload, see below), a +snapshot taken once per dispatch always scans every sign currently known, so a recompute is always complete and +order-independent regardless of which member triggered it. `ShapeGroupResolver.members`/`ExtrudeGroupResolver.members` +just delegate to `LineGroupResolver.members(...)` (identical filtering/ordering — the only real difference between +`LINE`, `SHAPE`, and `EXTRUDE` group resolution is the caller-side minimum-member count). `isFirstAppearance` +(`!sameGroupRecompute && members.size() == minMembers`) is log-only — see §6 — not a distinct dispatch type. Both +dispatch via the single `actionFactory.createSetMultiPointAction`/`createRemoveMultiPointAction` pair for all three +types (§5) — `ActionFactory` derives which kind (and minimum-member threshold) to build from `markerGroup.type()` +itself, so `SignTransitionResolver` doesn't need per-type factory calls here. Every join/leave-recompute call site +calls `ColorResolver.resolve(members, rep.group())` (see below) immediately before dispatching, and passes the +resolved `lineColor`/`fillColor` into `createSetMultiPointAction` as explicit parameters (`fillColor` is `null` for +`LINE`, via `hasFill(kind)`) — `ActionFactory` no longer reads `markerGroup.lineColor()`/`fillColor()` itself for +this factory method, keeping it a dumb builder while `SignTransitionResolver` owns colour resolution. These call +sites also pass `rep.detail()` (not `rep.label()`) as the dispatched detail text — fixing a bug where a +`LINE`/`SHAPE`/`EXTRUDE` marker's rendered detail was always just its label repeated, since detail text on these +signs was never actually threaded through. ### Conflict resolution: `ColorResolver` (player-controlled marker colours, GitHub issue #198) @@ -226,7 +248,7 @@ through this method, so a sign whose prefix was renamed while the server was off correctly rather than dispatched under a stale cached parse. Then looks up `existing` from `signCache`, computes `oldRep`/`newRep` from `existing`/the reparsed `signEntry` respectively, updates `signCache`/`chunkIndex` (removing the key if `newRep == null` and something was cached, else caching the merged entry — the merge preserves the *existing* -cached `playerId` when the incoming entry's is the `WorldMap.UNKNOWN` chunk-load sentinel, and preserves the +cached `playerId` when the incoming entry's is the `PlayerIds.UNKNOWN` chunk-load sentinel, and preserves the existing entry's `createdAtMillis` rather than ever recomputing it), then dispatches whatever `computeTransitionAction` returns (if non-`null`), passing a fresh `getAllSigns()` snapshot as `allSigns`. @@ -237,7 +259,11 @@ code path. ### Config reload (`/bluemap reload`) — `reset()`/`reloadConfig()` -`reset()` (from `IResetHandler`) calls `reloadConfig()`, which: +`reset()` (from `IResetHandler`) calls `reloadConfig()`, which is split into a locked **phase 1** (config swap + +reparse) and an unlocked **phase 2** (dispatch) — see the `synchronized`-monitor note above and +`.scratch/concurrency-pass-2026-09/issues/05-signmanager-reloadconfig-lock-contention.md`: + +**Phase 1** (`synchronized`): 1. Captures `oldPrefixGroupMap = runtimeConfig.prefixGroupMap()` **before** touching anything else. 2. `ConfigManager.reload()` (re-reads `BMSM-Core.json` from disk), `SignHelper.reloadParser()`, then replaces `runtimeConfig` wholesale via `buildRuntimeConfig()` — a freshly rebuilt `prefixGroupMap` paired with a @@ -245,21 +271,31 @@ code path. `blueMapAPIConnector.clearMarkerSetsCache()` (see §6), so neither identifier cache accumulates entries keyed on a `MarkerGroup` value from before the last reload (`MarkerSetIdentifier` keys on the whole record by value, so a changed icon/offset/distance would otherwise be a new, never-evicted cache entry). -3. Before diffing, every currently-cached `SignEntry` is passed through `safeReparseFromRawLines(entry, - newConfig.parser())` (a static, log-and-fall-back wrapper around `reparseFromRawLines`) and, if the result - differs from the original reference, the reparsed entry replaces it in `signCache`. `reparseFromRawLines` - re-runs `SignLinesParser.parse(...)` on the entry's persisted `frontRawLines`/`backRawLines` against the new - config and returns `entry.withParsedText(freshFront, freshBack)` — or the *same* entry reference, cheaply - detectable via `!=`, if either raw-lines array is `null` (an entry migrated from pre-V5 data, with no raw text - on disk to re-parse; see `config-and-persistence.md`). -4. Takes one `getAllSigns()` snapshot (`allSigns`) up front, then for every currently-cached `SignEntry` (the cache - is **not** cleared): computes `oldRep` under `oldPrefixGroupMap` from the sign's representation as cached - *before* reload, `newRep` under the just-rebuilt `prefixGroupMap` from the (possibly reparsed, step 3) entry, - and dispatches `computeTransitionAction(allSigns, entry.key(), oldRep, newRep, ...)` if non-`null` — the exact - same transition table a live sign edit uses, just fed a before/after diff against the *config* instead of the - *sign text*. Reusing one snapshot across the whole loop (rather than each sign's `LINE`/`SHAPE`-group recompute - re-querying `getAllSigns()` independently) avoids an O(n²) re-scan of the cache when a config reload touches - many signs at once. +3. Takes one `getAllSigns()` snapshot (`allSigns`), and for every entry in it computes `oldRep` under + `oldPrefixGroupMap` (stored in an `oldReps` map keyed by `SignEntryKey`) and passes the entry through + `safeReparseFromRawLines(entry, newConfig.parser())` (a static, log-and-fall-back wrapper around + `reparseFromRawLines`); if the result differs from the original reference, the reparsed entry replaces it in + `signCache`. `reparseFromRawLines` re-runs `SignLinesParser.parse(...)` on the entry's persisted + `frontRawLines`/`backRawLines` against the new config and returns `entry.withParsedText(freshFront, freshBack)` — + or the *same* entry reference, cheaply detectable via `!=`, if either raw-lines array is `null` (an entry + migrated from pre-V5 data, with no raw text on disk to re-parse; see `config-and-persistence.md`). + +**Phase 2** (unlocked, runs after the `synchronized` block exits): for every `(key, oldRep)` pair captured in phase +1, re-reads `current = signCache.get(key)` fresh and computes `newRep` under the just-rebuilt `prefixGroupMap` from +`current` (`null` if the key's no longer cached), then dispatches `computeTransitionAction(allSigns, key, oldRep, +newRep, ...)` if non-`null` — the exact same transition table a live sign edit uses, just fed a before/after diff +against the *config* instead of the *sign text*. The `allSigns` snapshot passed to `computeTransitionAction` (via +`this::getAllSigns`, an `allSignsSupplier`) is read **live** off `signCache` on every call, not a snapshot frozen at +the end of phase 1 — a frozen snapshot could go stale mid-phase-2 if a sign is concurrently added/removed/edited +(e.g. a concurrent `removeByKey` dropping a `LINE` member), which would make `LineGroupResolver.members` recompute +against membership that no longer matches `signCache` and could resurrect a member a concurrent dispatch had just +independently removed. A sign edited concurrently during phase 2 is not clobbered: phase 2 only ever reads +`signCache` (never mutates it), so it can only race a concurrent edit's own independent dispatch for the same key or +line/shape — both are best-effort idempotent set/remove actions applied through `ReactiveQueue`, which already gives +no cross-dispatch ordering guarantee (§7), so unlocking phase 2 doesn't introduce a new class of risk, only widens +an existing one to a rarer window. Reading `signCache` fresh per multi-point dispatch costs an extra +`signCache.values()` copy compared to one shared snapshot, but that's the same cost every live sign edit already +pays via `dispatchTransition`. This replaced the previous behavior (`reloadSigns()`: snapshot the cache, clear it, replay every entry through `addOrUpdateSign` so every entry always took the Add branch) for a concrete bug fix documented in @@ -312,7 +348,7 @@ surgery) — the removal mixin (§1.3) only fires for an in-game block change on feature targets — so skipping reconciliation there would defeat the main use case. No performance reason to skip it either: `keysInChunk` is one hashmap `get` returning empty for the overwhelming majority of chunk loads. -## 5. Marker identity — `DispatchedMarkerIdentifier` / `MarkerIdentifier` / `LineMarkerIdentifier` / `MarkerSetIdentifier` / `MarkerSetIdentifierCollection` +## 5. Marker identity — `DispatchedMarkerIdentifier` / `MarkerIdentifier` / `MultiPointMarkerIdentifier` / `MarkerSetIdentifier` / `MarkerSetIdentifierCollection` Two id schemes now exist side by side (position-keyed and content-keyed), unified behind one interface: @@ -323,33 +359,39 @@ Two id schemes now exist side by side (position-keyed and content-keyed), unifie literal key used inside a BlueMap `MarkerSet`'s marker map for POI markers. **No dimension component** — uniqueness across dimensions is guaranteed only because each dimension maps to a separate `MarkerSetIdentifier`/`MarkerSet`, not because the id string itself is unique. -- `LineMarkerIdentifier(label, parentSet)` (record) also implements it — its `getId()` is `"line:" + label`, - **content-keyed**, not position-keyed: a line's points move as members join/leave, but its id stays stable as - long as the (group, label) key doesn't change. This is exactly the id-scheme difference that motivated - `SignManager.reloadConfig()`'s rewrite (§3) — a naive replay only ever adds under a marker's *current* id, so an - id scheme changing between reloads (e.g. a group's `type` flipping `POI`↔`LINE`↔`SHAPE`↔`EXTRUDE`) needs an explicit - dispatch removing the *old* id, not just adding the new one. -- `ShapeMarkerIdentifier(label, parentSet)` (record) is the `SHAPE`-type counterpart, structurally identical to - `LineMarkerIdentifier` — same two fields, same interface — with `getId()` returning `"shape:" + label` instead. - `ExtrudeMarkerIdentifier(label, parentSet)` (record) is the `EXTRUDE`-type counterpart, same shape again, with - `getId()` returning `"extrude:" + label`. +- `MultiPointMarkerIdentifier(kind, label, parentSet)` (record) also implements it — its `getId()` is `kind + ":" + + label`, **content-keyed**, not position-keyed: a line/shape/extrude's points move as members join/leave, but its + id stays stable as long as the (group, label) key doesn't change. `kind` is one of the string literals `"line"`/ + `"shape"`/`"extrude"` (`ActionFactory`'s `LINE_KIND`/`SHAPE_KIND`/`EXTRUDE_KIND` constants), so `getId()` returns + `"line:" + label`/`"shape:" + label`/`"extrude:" + label` respectively. This one record replaces what used to be + three near-identical records (`LineMarkerIdentifier`/`ShapeMarkerIdentifier`/`ExtrudeMarkerIdentifier`), which + differed only by that hardcoded id-prefix. The content-keyed vs. position-keyed distinction is exactly what + motivated `SignManager.reloadConfig()`'s rewrite (§3) — a naive replay only ever adds under a marker's *current* + id, so an id scheme changing between reloads (e.g. a group's `type` flipping `POI`↔`LINE`↔`SHAPE`↔`EXTRUDE`) needs + an explicit dispatch removing the *old* id, not just adding the new one. - `MarkerSetIdentifier(mapId, markerGroup)` — one BlueMap marker-set per (map, marker-group) pair, unchanged by the line-markers work. -- `ActionFactory.createChangeGroupPOIAction(x, y, z, mapId, label, detail, oldMarkerGroup, newMarkerGroup)` now - builds a `GroupTransitionMarkerAction` wrapping `List.of(new RemoveMarkerAction(oldIdentifier), new - AddMarkerAction(newIdentifier, label, detail))` — two full `MarkerAction`s, not the older single action carrying - two identifiers. `createSetLineAction(mapId, markerGroup, label, detail, points, lineColor, isFirstAppearance)` - and `createRemoveLineAction(mapId, markerGroup, label)` are the `LINE`-side counterparts, following the same - `MarkerSetIdentifierCollection.getIdentifier` pattern as every other factory method; `createSetLineAction` builds - a `LineMarkerIdentifier(label, ...)` and carries `markerGroup.lineWidth()` plus the caller-supplied `lineColor` - through — the caller (`SignTransitionResolver`, via `ColorResolver`, GitHub issue #198) passes the *resolved* - colour explicitly rather than `ActionFactory` reading `markerGroup.lineColor()` itself, since a group with - `allowPlayerColors` set may render a dye-derived colour instead of the configured one. - `createSetShapeAction(mapId, markerGroup, label, detail, points, lineColor, fillColor, isFirstAppearance)`/ - `createRemoveShapeAction(mapId, markerGroup, label)` mirror those two exactly but build a `ShapeMarkerIdentifier` - and take both resolved colours as explicit parameters. `createSetExtrudeAction`/`createRemoveExtrudeAction` are - structurally identical to the `SHAPE` pair (same parameters) but build an `ExtrudeMarkerIdentifier` and the - resulting `SetExtrudeMarkerAction`/`RemoveExtrudeMarkerAction`. +- `ActionFactory.createGroupTransitionPOIAction(x, y, z, mapId, label, detail, oldMarkerGroup, newMarkerGroup)` + (renamed from `createChangeGroupPOIAction`) builds a `GroupTransitionMarkerAction` wrapping `List.of(new + RemoveMarkerAction(oldIdentifier), new AddMarkerAction(newIdentifier, label, detail))` — two full `MarkerAction`s, + not a single action carrying two identifiers. A private `markerIdentifier(x, y, z, mapId, markerGroup)` helper + wraps the repeated `new MarkerIdentifier(x, y, z, markerSetIdentifierCollection.getIdentifier(mapId, + markerGroup))` construction shared by `createAddPOIAction`/`createRemovePOIAction`/`createUpdatePOIAction`/ + `createGroupTransitionPOIAction`. + `createSetMultiPointAction(mapId, markerGroup, label, detail, points, lineColor, fillColor, isFirstAppearance)` + and `createRemoveMultiPointAction(mapId, markerGroup, label)` are the single `LINE`/`SHAPE`/`EXTRUDE` factory pair + — replacing the former per-type `createSetLineAction`/`createSetShapeAction`/`createSetExtrudeAction` and + `createRemoveLineAction`/`createRemoveShapeAction`/`createRemoveExtrudeAction` methods. Both derive a private + `MultiPointKind(String name, int minMembers)` from `markerGroup.type()` via a private `multiPointKind` switch + (`LINE`/`SHAPE`/`EXTRUDE` map to their kind string + `MultiPointGroupThresholds` constant; `POI` throws + `IllegalArgumentException`, replacing the former per-method `requireGroupType` checks — safe because every call + site in `SignTransitionResolver` already dispatches by `rep.group().type()` before reaching either method, §3) and + build the `MultiPointMarkerIdentifier(kind.name(), label, ...)` accordingly. `createSetMultiPointAction` carries + `markerGroup.lineWidth()` plus the caller-supplied `lineColor`/`fillColor` through — the caller + (`SignTransitionResolver`, via `ColorResolver`, GitHub issue #198) passes the *resolved* colour(s) explicitly + rather than `ActionFactory` reading `markerGroup.lineColor()`/`fillColor()` itself, since a group with + `allowPlayerColors` set may render a dye-derived colour instead of the configured one; `LINE` callers pass `null` + for `fillColor`, which it has none of. - `MarkerSetIdentifierCollection` is a per-`SignManager`-instance cache that guarantees the *same* `MarkerSetIdentifier` object is returned for a given `(mapId, markerGroup)` pair (indexed both by map and by marker group, intersected) — `ActionFactory` always goes through this rather than constructing @@ -366,22 +408,22 @@ Two id schemes now exist side by side (position-keyed and content-keyed), unifie ## 6. `BlueMapAPIConnector` — the only class touching the BlueMap API - Holds a `volatile ReactiveQueue markerActionQueue`, a - `volatile Map> markerSetsCache`, a - `volatile Map renderMaskCache` (keyed by real `BlueMapMap` id — see §8), - and a `volatile BlueMapAPI blueMapAPI`. All four are `volatile` because `resetQueue()`/`onEnable()`/ - `clearMarkerSetsCache()` always replace them wholesale with a brand-new object rather than mutating the existing - one, so correctness only needs a reader to see the latest *reference* - — that's what `volatile` guarantees (it says nothing about the referenced objects, which are mutated afterward - through their own thread-safe methods: `ReactiveQueue.enqueue()`/`process()`, `ConcurrentHashMap.get()`/ + `volatile Map> markerSetsCache`, and a + `volatile Map renderMaskCache` (keyed by real `BlueMapMap` id — see §8). + All three are `volatile` because `resetQueue()`/`clearMarkerSetsCache()` always replace them wholesale with a + brand-new object rather than mutating the existing one, so correctness only needs a reader to see the latest + *reference* — that's what `volatile` guarantees (it says nothing about the referenced objects, which are mutated + afterward through their own thread-safe methods: `ReactiveQueue.enqueue()`/`process()`, `ConcurrentHashMap.get()`/ `putIfAbsent()`/`computeIfAbsent()`). No reader (`dispatch()`/`onDisable()`/`onEnable()` for the queue, - `getMarkerSets()` for the marker-set cache, `getRenderMask()` for the render-mask cache, `getMaps()` for - `blueMapAPI`) ever needs a joint snapshot of more than one of these fields at once, so per-field visibility is - enough — a shared lock would additionally serialize `dispatch()` (hot path, every sign event) behind - `processMarkerAction()`'s BlueMap API calls, an unrelated critical section. This resolves finding #12 + `getMarkerSets()` for the marker-set cache, `getRenderMask()` for the render-mask cache) ever needs a joint + snapshot of more than one of these fields at once, so per-field visibility is enough — a shared lock would + additionally serialize `dispatch()` (hot path, every sign event) behind `processMarkerAction()`'s BlueMap API + calls, an unrelated critical section. This resolves finding #12 (`../plans/codebase-review-2026-07-11.md`, resolved 2026-07-22) and the field-visibility half of #11. `renderMaskCache` is invalidated (replaced with a fresh empty map) at the exact same call sites as `markerSetsCache` — `resetQueue()` and `clearMarkerSetsCache()` — so neither cache survives a config reload or a - genuine BlueMap disable/enable cycle carrying stale entries. + genuine BlueMap disable/enable cycle carrying stale entries. There is no cached `blueMapAPI` field anymore (see + "No cached `BlueMapAPI` reference" below) — `getMaps()` re-fetches `BlueMapAPI.getInstance()` on every call. - **Listener detach (finding #7, GitHub issue #140, resolved 2026-07-23):** the constructor registers `BlueMapAPI.onEnable(...)`/`onDisable(...)` with two `final Consumer` fields (`onEnableListener`/`onDisableListener` — each built once as `this::onEnable`/`this::onDisable`), and @@ -392,32 +434,55 @@ Two id schemes now exist side by side (position-keyed and content-keyed), unifie `bluemap-api` 2.8.0's source that `onEnable`/`onDisable` do store the `Consumer` and `unregisterListener` does remove it correctly once the same instance is passed both ways — this class is excluded from unit-test coverage (game-coupled, see `testing.md`), so this was verified by reading the dependency's source, not by a test. -- **Startup sign-load bugfix:** `onEnable`/`onDisable` used to gate the reload-vs-first-boot decision on - `markerActionQueue.isShutdown()`, but a brand-new `ReactiveQueue` whose executor was never lazily created also - reports `isShutdown() == true` — exactly what happens at server startup, when `SERVER_STARTING` dispatches an - action for every migrated/loaded sign before BlueMap is available: `process()` returns early (`shouldRun()` is - `false`) without ever creating an executor. That made the *first* `onEnable()` a server ever sees mistake startup - for a reload, call `resetQueue()`, and discard every action enqueued during sign load before a single one was - processed. Fixed with an explicit `volatile boolean disabledSinceLastEnable` field: `onDisable()` sets it `true`; - `onEnable()` only treats the cycle as a genuine reload (and calls `resetQueue()`/`fireReset()`) `if - (disabledSinceLastEnable)`, resetting the flag to `false` immediately after. A freshly constructed connector - starts with the flag `false`, so the very first `onEnable()` always resumes draining the queue that startup - already populated instead of replacing it. + `shutdown()` also now retires `markerActionQueue` itself (`markerActionQueue.shutdown()`, warning if it returns + `false` — couldn't confirm every in-flight task stopped), not just the two listeners — previously this left the + queue's fixed thread pool alive and any in-flight marker action unawaited on server stop, so + `BlueMapSignMarkersMod.onServerStopping`'s configured shutdown timeout (§7) had no effect at all on the connector's + own `shutdown()` path. Mirrors `onDisable()`'s own `shutdown()` call, but runs on server stop regardless of + whether BlueMap ever fired `onDisable` first. +- **Startup sign-load bugfix, superseded twice:** `onEnable`/`onDisable` originally gated the reload-vs-first-boot + decision on `markerActionQueue.isShutdown()`, but a brand-new `ReactiveQueue` whose executor was never lazily + created also reported `isShutdown() == true` — exactly what happens at server startup, when `SERVER_STARTING` + dispatches an action for every migrated/loaded sign before BlueMap is available: `process()` returns early + (`shouldRun()` is `false`) without ever creating an executor. That made the *first* `onEnable()` a server ever sees + mistake startup for a reload, call `resetQueue()`, and discard every action enqueued during sign load before a + single one was processed. That was first fixed with an explicit `volatile boolean disabledSinceLastEnable` field, + then that field was removed once `ReactiveQueue.isShutdown()` itself was corrected to stop conflating "genuinely + shut down" with "never started" (finding 63, `.scratch/concurrency-pass-2026-09/issues/04-reactivequeue-isshutdown-semantics.md` + — see §7's `isShutdown()`/`hasStarted()` split) — `onEnable()` now asks `markerActionQueue.isShutdown()` directly + again, correctly this time. - `BlueMapAPI.onEnable`/`onDisable` are registered in the constructor. `onDisable` shuts the queue down (actions - keep enqueuing but stop draining) and sets `disabledSinceLastEnable = true`. `onEnable(api)`: assigns - `this.blueMapAPI = api` **first**, then, if `disabledSinceLastEnable`, calls `resetQueue()` (fresh queue + fresh - `markerSetsCache`) and `fireReset()` (→ every registered - `IResetHandler`, i.e. `SignManager.reset()`) before resuming draining — this is why a BlueMap reload re-diffs the - entire sign cache against the reloaded config rather than assuming stale `MarkerSet` state is still valid. The `blueMapAPI` assignment must - come before `fireReset()`, not after: `fireReset()`'s replay dispatches `MarkerAction`s that `ReactiveQueue` - starts draining on background threads immediately (`enqueue()` calls `process()` synchronously, which submits - to the executor right away — it doesn't wait for the enqueuing loop, let alone `onEnable`, to finish), and those - threads read `this.blueMapAPI` in `getMaps()`. Assigning it after `fireReset()` (the pre-fix ordering) let replay - actions race ahead and read the *previous* cycle's `blueMapAPI` reference — root cause of a bug where editing a - marker group's config and running `/bluemap reload` made that group's markers (and its `MarkerSet` layer) vanish - instead of updating in place, recoverable only by reloading a second time. `SignManager.reloadConfig()`'s disk - read (see §3) made the race reliably reproducible by widening the window between replay-dispatch and the - now-corrected assignment point. + keep enqueuing but stop draining) and records `lastShutdownConfirmedClean = markerActionQueue.shutdown()`'s return + value (see §7's `shutdown()`) — read by the next `onEnable()` to log a warning if a non-interruptible straggler + task may still race the reset replay below (no better recovery is available; this only makes the violation + observable). `onEnable(api)` runs its whole isGenuineReload check-then-act **`synchronized (this)`** (shares the + monitor `processMarkerAction`/`applySingleAction` use) — BlueMap's listener dispatch is presumed single-threaded + today, but the check-then-act wasn't atomic on its own, so a hypothetical concurrent `onEnable()` call could + otherwise also observe `isShutdown()==true` and double-fire both (finding 44, + `agent-context/reviews/full-codebase-review_2026-09-07_0900.md`) — safe to share since `onEnable()` only runs on a + genuine BlueMap enable/reload, never the hot path. Inside the lock: if `markerActionQueue.isShutdown()` is a + genuine reload, it calls `ConfigManager.reload()` **before** `resetQueue()` (not after) — `resetQueue()` reads + `ConfigManager.get().getShutdownAwaitSeconds()` to build the new queue, and the old ordering left an edited + `shutdownAwaitSeconds` value with no effect until a later disable/re-enable cycle, since the queue's value is + fixed at construction; `fireReset()` still runs its own `ConfigManager.reload()` right after (harmless — re-reads + the same just-reloaded file) since it also needs to rebuild `SignManager`'s parser/prefix map — then calls + `resetQueue()` (fresh queue + fresh `markerSetsCache`) and `fireReset()` (→ every registered `IResetHandler`, i.e. + `SignManager.reset()`). Otherwise, if `markerActionQueue.consumeOverflowSinceLastCheck()` reports at least one + message was rejected for capacity since the last check (see §7's `DEFAULT_CAPACITY`/`overflowedSinceLastCheck`) — + checked and cleared even on this very first `onEnable()`, since a large sign count enqueuing every migrated/loaded + sign's add action while BlueMap is still unavailable at startup can silently overflow, and `isGenuineReload` is + `false` on a first boot so `fireReset()` wouldn't otherwise run to recover the dropped markers (the "capacity does + not bound..." finding, `agent-context/reviews/copilotreview.2026-09-09.md`) — it logs a warning and calls + `fireReset()` to replay every currently tracked sign's marker state and recover the ones capacity dropped. No + `blueMapAPI` field is assigned or read anymore (see below); the previous ordering bug where a cached `BlueMapAPI` + reference could go stale mid-replay no longer applies since `getMaps()` re-fetches the instance fresh every call. +- **No cached `BlueMapAPI` reference:** the connector used to hold a `volatile BlueMapAPI blueMapAPI` field, set in + the constructor (`BlueMapAPI.getInstance().orElse(null)`, since BlueMap may already be enabled by construction + time) and reassigned first thing in `onEnable`, with `getMaps()` reading `this.blueMapAPI.getWorld(mapId)`. That + field is gone (finding 43, `agent-context/reviews/full-codebase-review_2026-09-07_0900.md`): `getMaps(mapId)` now + calls `BlueMapAPI.getInstance()` itself on every invocation, returning `Optional.empty()` (logged at debug) if + empty — a disable/re-enable landing between `processMarkerAction`'s own guard check and this call could otherwise + operate against a defunct cached instance instead of the current one. - `getMarkerSets(identifier)` is `synchronized`; on cache miss it resolves `BlueMapAPI.getWorld(mapId)` → `.getMaps()`, and for each map either fetches an existing `MarkerSet` by `markerGroup.name()` or builds+registers one (`label`, `defaultHidden`, `sorting`, `toggleable` from the `MarkerGroup` — `sorting`/`toggleable` are thin @@ -431,95 +496,137 @@ Two id schemes now exist side by side (position-keyed and content-keyed), unifie - `logProcessingMessage` sanitizes sign-derived detail text via `LogUtils.sanitizeForLog` (`common`, ticket 06) before logging it at INFO — strips ANSI CSI escape sequences and normalizes `\r\n`/`\n`/`\r` to literal `\n` and `\r`, closing a log-injection/log-noise vector where only `\n` was previously escaped. -- `processMarkerAction` is `synchronized` (finding #5, resolved 2026-07-22): `addMarker`/`updateMarker`/ - `removeMarker`/`setLineMarker` mutate a `MarkerSet`'s marker `Map` (thread-safety of which is BlueMap's concern, - not this mod's), and `ReactiveQueue`'s executor is sized to `availableProcessors()`, so without this lock two - actions dispatched close together (e.g. many signs loading at server startup) could race on the same underlying - map. Because `ReactiveQueue.shutdown()` only stops *new* submissions (already-submitted tasks still run — see - §7), several such tasks can end up queued behind this monitor for a while after a shutdown is requested; - `processMarkerAction` re-checks `BlueMapAPI.getInstance().isEmpty()` itself on entry so one of those queued tasks - can't mutate a `MarkerSet` after BlueMap has actually disabled in the meantime. If the dispatched action is a +- `processMarkerAction` is `synchronized` (finding #5, resolved 2026-07-22): the `MarkerMutations` effects it invokes + mutate a `MarkerSet`'s marker `Map` (thread-safety of which is BlueMap's concern, not this mod's), and + `ReactiveQueue`'s executor is sized to `availableProcessors()`, so without this lock two actions dispatched close + together (e.g. many signs loading at server startup) could race on the same underlying map. Because + `ReactiveQueue.shutdown()` only stops *new* submissions (already-submitted tasks still run — see §7), several such + tasks can end up queued behind this monitor for a while after a shutdown is requested; `processMarkerAction` + re-checks `BlueMapAPI.getInstance().isEmpty()` itself on entry so one of those queued tasks can't mutate a + `MarkerSet` after BlueMap has actually disabled in the meantime. If the dispatched action is a `GroupTransitionMarkerAction`, it iterates `transitionAction.effects()` (a `List`, 0-2 entries — see §3/§5) calling `applySingleAction` on each **inside** the same synchronized call, so a bundled leave+join pair (or POI↔LINE swap) can never be observed half-applied by another thread; otherwise it calls `applySingleAction` directly on the one action. `applySingleAction` logs (`logProcessingMessage`) then dispatches on the concrete `MarkerAction` subtype via a `switch` pattern-match: `AddMarkerAction`/`RemoveMarkerAction`/ - `UpdateMarkerAction`/`SetLineMarkerAction`/`RemoveLineMarkerAction` each have a `case` arm — **`MarkerAction` is a + `UpdateMarkerAction`/`SetMultiPointMarkerAction`/`RemoveMultiPointMarkerAction` each have a `case` arm — **`MarkerAction` is a plain abstract class, not `sealed`**, so adding a new subtype without adding a `case` here (and in `logProcessingMessage`'s switch) silently falls through to `default` instead of failing to compile — see `AGENTS.md`'s "Adding a new marker/BlueMap action" section. All cases resolve their marker sets via a shared - `applyToMarkerSets(markerIdentifier, consumer)` helper (parameter type `DispatchedMarkerIdentifier`, needs only - `.parentSet()` — looks up via `getMarkerSets`, no-ops with a debug log if none found, otherwise hands the - consumer a `Stream>`); `RemoveMarkerAction`, `RemoveLineMarkerAction`, `RemoveShapeMarkerAction`, - and `RemoveExtrudeMarkerAction` all route through an id-based `removeMarkerById(String id, Stream<...>)` helper - extracted out of the old `removeMarker` body. `SetShapeMarkerAction`/`RemoveShapeMarkerAction` and - `SetExtrudeMarkerAction`/`RemoveExtrudeMarkerAction` have their own `case` arms alongside the line ones (both in - `processMarkerAction`'s switch and in `logProcessingMessage`). -- `setLineMarker(SetLineMarkerAction, Stream>)` builds/replaces a BlueMap `LineMarker`: bails - (defensively — `SignManager` should never dispatch below 2 points) if `action.getPoints().size() < 2`, otherwise - builds a `de.bluecolored.bluemap.api.math.Line` from the action's `LinePoint`s (via `Vector3d`), parses - `action.getLineColor()` through `ColorUtils.parseHex` (`common`, plain Java) into `de.bluecolored.bluemap.api.math.Color`, - and `put`s a `LineMarker.builder().label(...).detail(HtmlUtils.toHtmlDetail(...)).line(line).lineWidth(...).lineColor(...) - .depthTestEnabled(markerGroup.depthTest()).build()` into each marker set's map, keyed by - `action.getMarkerIdentifier().getId()` (the content-keyed `"line:" + label` id, §5). `ColorUtils.parseHex` is the - only conversion point from the persisted hex string to a real color object, mirroring how `HtmlUtils` is the only - conversion point for HTML-escaped `detail` — both convert at the BlueMap-API call site, keeping the rest of the - pipeline in plain-Java, unescaped/unconverted form. -- `setShapeMarker(SetShapeMarkerAction, Stream>)` is the `SHAPE` counterpart: bails - (defensively, mirroring `setLineMarker`) if `action.getPoints().size() < 3`, builds a 2D `Shape` footprint from - the points' `x`/`z` only, and takes the marker's rendered height from the **tallest member**: - `points.stream().mapToInt(LinePoint::y).max()`. Parses both `lineColor` and `fillColor` through `ColorUtils.parseHex` - (fill defaults to a translucent red, `#FF000033`, unlike `lineColor`'s opaque default — see - `config-and-persistence.md`), then `put`s a `ShapeMarker.builder().label(...).detail(...).shape(shape, - height).lineWidth(...).lineColor(...).fillColor(...).depthTestEnabled(markerGroup.depthTest()).build()` into each - marker set's map, keyed by `action.getMarkerIdentifier().getId()` (the content-keyed `"shape:" + label` id, §5). -- `setExtrudeMarker(SetExtrudeMarkerAction, Map)` is the `EXTRUDE` counterpart: bails (defensively, - mirroring `setShapeMarker`) if `action.getPoints().size() < 3`, builds the same 2D `Shape` footprint from the - points' `x`/`z` as `setShapeMarker`, but instead of a single tallest-member height calls package-private - `resolveExtrudeHeightRange(label, points)` for the volume's floor/ceiling: `minY`/`maxY` are the lowest/tallest - member's Y independently (not both from the tallest member), so the extrusion spans the full height range its - members were placed at regardless of placement order; if every member is at the same Y (`maxY <= minY`, e.g. one - flat floor), it logs at debug and bumps `maxY` to `minY + 1` rather than building a zero-height (invisible) - volume. `resolveExtrudeHeightRange` returns a private `ExtrudeHeightRange(float minY, float maxY)` record — a - plain value holder with no `bluemap-api` types, so it stays directly unit-testable - (`BlueMapAPIConnectorTest`, `testing.md`) even though `BlueMapAPIConnector` itself is otherwise game-coupled and - excluded from coverage. Parses both `lineColor` and `fillColor` through `ColorUtils.parseHex` the same way - `setShapeMarker` does, then `put`s an `ExtrudeMarker.builder().label(...).detail(...).shape(shape, minY, - maxY).lineWidth(...).lineColor(...).fillColor(...).depthTestEnabled(markerGroup.depthTest()).build()` into each - marker set's map, keyed by `action.getMarkerIdentifier().getId()` (the content-keyed `"extrude:" + label` id, §5). -- `addMarker` only actually builds a marker `if (markerGroup.type() == MarkerGroupType.POI)` — this is a real, - live branch now that `MarkerGroupType.LINE`/`SHAPE`/`EXTRUDE` exist (no longer future-proofing for values that - didn't exist): a `LINE`-, `SHAPE`-, or `EXTRUDE`-typed group's signs never reach `addMarker` at all, since - `SignManager`'s transition table (§3) routes those representations to their own `Set`/`Remove` actions instead of - `AddMarkerAction`. It also - conditionally calls `markerBuilder.styleClasses(markerGroup.cssClasses().toArray(new String[0]))` when - `cssClasses` is non-empty — the only marker-builder call gated on the field being present rather than always - called with a possibly-default value, since BlueMap's `styleClasses` has no meaningful "unset" default to fall - back to. -- **HTML escaping (fixed)**: `addMarker`/`updateMarker` wrap `detail` with `HtmlUtils.toHtmlDetail(...)` (`common` - package) before it reaches `POIMarker.builder().detail(...)` / `poiMarker.setDetail(...)` — BlueMap renders - `detail` as raw HTML (unlike `label`, which BlueMap's own `Marker.setLabel()` escapes), and sign text is - player-controlled, so this closed a live XSS vector (`../plans/html-detail-escaping-plan.md`). `toHtmlDetail` escapes - first, then converts `\n` to `
` so multi-line detail renders line breaks correctly — escaping before the `
` - substitution matters, otherwise the inserted tags would themselves get escaped. `SignEntry`/persisted `signs.json` - data stays raw/unescaped; escaping happens only at this BlueMap-API call site. + `prepareGated`/`prepareUngated` helper (parameter type `DispatchedMarkerIdentifier`, needs only `.parentSet()` — + looks up via `getMarkerSets`, returns a no-op `Runnable` with a debug log if none found, otherwise hands the + effect a `Map` per target map) — but each `case` arm's actual mutation is now a method reference + into `MarkerMutations` (below), not code inlined in `BlueMapAPIConnector` itself (ticket 04, + `.scratch/marker-action-consolidation/issues/04-shrink-bluemapapiconnector-marker-mutations.md`). +- **`MarkerMutations`** (new class in `core.bluemap`, package-private, all-`static`) holds every state-free + marker-construction method `BlueMapAPIConnector` used to implement inline — no reference to the connector's + queue/cache/lifecycle fields, so this logic can be read (and tested where possible) independent of dispatch/ + gating/cache concerns. `BlueMapAPIConnector.prepareSingleAction` calls into it via lambdas + (`markers -> MarkerMutations.addMarker(addAction, markers)`, etc.) for every `MarkerAction` case. + `addMarker`/`updateMarker`/`removeMarker`/`removeMarkerById`/`setMultiPointMarker`/`toBlueMapColor`/ + `resolveExtrudeHeightRange` all live here now; `pointOf` and `isInsideRenderBounds` (render-bounds gating, §8) + stayed on `BlueMapAPIConnector` since they're part of the gating logic, not marker construction, and were + explicitly out of scope for ticket 04. +- `MarkerMutations.setMultiPointMarker(SetMultiPointMarkerAction, Map)` replaces the former separate + `setLineMarker`/`setShapeMarker`/`setExtrudeMarker` methods (ticket 04) with one entry point covering all three + kinds: it reads `MultiPointMarkerIdentifier.kind()` off the action's identifier, resolves that kind's minimum + member count via a private `minMembersFor(kind)` switch (`MultiPointGroupThresholds.LINE_MIN_MEMBERS`/ + `SHAPE_MIN_MEMBERS`/`EXTRUDE_MIN_MEMBERS`, warning-and-return if unknown or below threshold — the same defensive + guard the three separate methods used to have individually), then parses `action.getLineColor()` once via + `toBlueMapColor(ColorUtils.parseHex(...))` before branching into a `switch (kind)` **statement** (not an + expression) with one arm per kind: + - `"line"` builds a `de.bluecolored.bluemap.api.math.Line` from the action's `LinePoint`s (via `Vector3d`), then + `put`s a `LineMarker.builder().label(...).detail(HtmlUtils.toHtmlDetail(...)).line(line).lineWidth(...) + .lineColor(...).depthTestEnabled(markerGroup.depthTest()).build()`, keyed by + `action.getMarkerIdentifier().getId()` (the content-keyed `"line:" + label` id, §5). + - `"shape"` builds a 2D `Shape` footprint from the points' `x`/`z` only, taking the marker's rendered height from + the **tallest member** (`points.stream().mapToInt(LinePoint::y).max()`), additionally parses `fillColor` + (defaults to a translucent red, `#FF000033`, unlike `lineColor`'s opaque default — see + `config-and-persistence.md`), and `put`s a `ShapeMarker.builder()...build()` keyed by the content-keyed + `"shape:" + label` id. + - `"extrude"` builds the same 2D `Shape` footprint as `"shape"`, but instead of a single tallest-member height + calls `resolveExtrudeHeightRange(label, points)` for the volume's floor/ceiling — `minY`/`maxY` are the + lowest/tallest member's Y independently (not both from the tallest member), so the extrusion spans the full + height range its members were placed at regardless of placement order; if every member is at the same Y + (`maxY <= minY`, e.g. one flat floor), it logs at debug and bumps `maxY` to `minY + 1` rather than building a + zero-height (invisible) volume. Also parses `fillColor` the same way `"shape"` does, and `put`s an + `ExtrudeMarker.builder()...build()` keyed by the content-keyed `"extrude:" + label` id. + + Each arm builds, sets `minDistance`/`maxDistance`, and `put`s its own concretely-typed marker + (`LineMarker`/`ShapeMarker`/`ExtrudeMarker`) independently, rather than converging all three into one shared + variable typed as their common supertype (`ObjectMarker`) after the switch — `bluemap-api` is `compileOnly` and + absent from the test runtime classpath, and a switch **expression** assigning `LineMarker`/`ShapeMarker`/ + `ExtrudeMarker` branches into one `ObjectMarker`-typed variable forces the JVM verifier to resolve `ObjectMarker` + the moment `MarkerMutations` is first loaded — which broke `MarkerMutationsTest`'s coverage of the *unrelated* + `resolveExtrudeHeightRange` method purely by being in the same class. The switch **statement** form avoids that + merge entirely. `resolveExtrudeHeightRange` returns a private `ExtrudeHeightRange(float minY, float maxY)` record — + a plain value holder with no `bluemap-api` types, so it stays directly unit-testable (`MarkerMutationsTest`, + `testing.md`) even though the rest of `MarkerMutations` is game-coupled. +- Two more small helpers stayed on `BlueMapAPIConnector` itself, package-private (not `private`) specifically for + direct unit testing: `pointOf(MarkerIdentifier)` (builds the single-point `List` used by the + render-bounds gate, §8, for a position-keyed POI marker) and `isInsideRenderBounds(RenderMaskEvaluator.RenderMask, + List)` (the pure mask-vs-points predicate, split out of the `mapId`-taking overload that does the cache + lookup) — both covered in `BlueMapAPIConnectorTest` without needing a live connector instance or `bluemap-api` + (`compileOnly`) on the test classpath. +- `MarkerMutations.addMarker` only actually builds a marker `if (markerGroup.type() == MarkerGroupType.POI)` — this + is a real, live branch now that `MarkerGroupType.LINE`/`SHAPE`/`EXTRUDE` exist (no longer future-proofing for + values that didn't exist): a `LINE`-, `SHAPE`-, or `EXTRUDE`-typed group's signs never reach `addMarker` at all, + since `SignManager`'s transition table (§3) routes those representations to their own `Set`/`Remove` actions + instead of `AddMarkerAction`. It also conditionally calls + `markerBuilder.styleClasses(markerGroup.cssClasses().toArray(new String[0]))` when `cssClasses` is non-empty — + the only marker-builder call gated on the field being present rather than always called with a possibly-default + value, since BlueMap's `styleClasses` has no meaningful "unset" default to fall back to. +- **HTML escaping (fixed)**: `MarkerMutations.addMarker`/`updateMarker` wrap `detail` with + `HtmlUtils.toHtmlDetail(...)` (`common` package) before it reaches `POIMarker.builder().detail(...)` / + `poiMarker.setDetail(...)` — BlueMap renders `detail` as raw HTML (unlike `label`, which BlueMap's own + `Marker.setLabel()` escapes), and sign text is player-controlled, so this closed a live XSS vector + (`../plans/html-detail-escaping-plan.md`). `toHtmlDetail` escapes first, then converts `\n` to `
` so + multi-line detail renders line breaks correctly — escaping before the `
` substitution matters, otherwise the + inserted tags would themselves get escaped. `SignEntry`/persisted `signs.json` data stays raw/unescaped; escaping + happens only at this BlueMap-API call site. ## 7. `ReactiveQueue` — generic buffer-while-unavailable primitive Lives in `core.reactive`, not BlueMap-specific — reusable anywhere something needs to "queue while a dependency is unavailable, drain once it's back." -- `enqueue(message)`: offers to an internal `ConcurrentLinkedQueue`, then calls `process()`. +- `enqueue(message)`: reserves a capacity slot via `tryReserveSlot()` (an `AtomicInteger queuedCount` compare-and-set + loop against `capacity`, default `DEFAULT_CAPACITY = 100_000`); on success offers to an internal + `ConcurrentLinkedQueue` and calls `process()`. On failure (capacity reached), `warnAtCapacity(message)` sets + `overflowedSinceLastCheck` and logs a throttled warning (at most once per `CAPACITY_WARNING_THROTTLE_MILLIS` = + 1000ms, so sustained overflow doesn't flood the log), and the message is **permanently dropped** — `enqueue()` has + no failure signal back to its caller and this queue has no retry/replay path of its own. `capacity` is a defensive + cap (finding 61, `agent-context/reviews/full-codebase-review_2026-09-07_0900.md`) for a class documented as + reusable beyond today's sign-count-bounded usage; set high specifically because `SignManager.reset()` (a + `/bluemap reload`) re-dispatches one message per cached sign and region-sharded persistence exists to support + large sign counts — a tight cap would risk silently dropping markers on reload for exactly the large-server case + this mod targets. `consumeOverflowSinceLastCheck()` (an `AtomicBoolean.getAndSet(false)`) lets a caller with its + own replay mechanism recover from overflow — `BlueMapAPIConnector.onEnable()` polls it and calls `fireReset()` if + it was ever set (§6) — rather than the dropped message staying silently lost forever. - `process()`: bails immediately if `shutdownRequested` or `!shouldRunCallback.shouldRun()` (for - `BlueMapAPIConnector`, `shouldRun` is `BlueMapAPI.getInstance().isPresent()`); otherwise submits `processMessages` - to `getExecutor()`'s fixed thread pool (`Executors.newFixedThreadPool(availableProcessors())`), swallowing a - `RejectedExecutionException` (shut down concurrently between the check and the submission — nothing more to - schedule on a retired instance). -- `processMessages` loops while `!shutdownRequested && !queue.isEmpty() && shouldRun()` still holds, polling one - message at a time and submitting **each individual message** as its own task to the same executor (so message - processing itself is also concurrent, not just the drain loop) — a per-message `RejectedExecutionException` - during a shutdown race just returns; any other exception from the submission reaches - `messageProcessorErrorCallback`. + `BlueMapAPIConnector`, `shouldRun` is `BlueMapAPI.getInstance().isPresent()`); otherwise, if an `AtomicBoolean + draining` compare-and-set from `false`→`true` succeeds (finding 62, + `agent-context/reviews/full-codebase-review_2026-09-07_0900.md` — guards against a burst of concurrent `enqueue()` + calls each submitting their own redundant drain-loop task; if the CAS fails, a drain loop is already active or + about to be, and it will drain this message too, so `process()` just returns), submits `processMessages` to + `getExecutor()`'s fixed thread pool (`Executors.newFixedThreadPool(availableProcessors())`) — resetting `draining` + back to `false` if `getExecutor()` returns `null` or submission throws `RejectedExecutionException` (shut down + concurrently between the check and the submission — nothing more to schedule on a retired instance). +- `processMessages` loops while `canContinueDraining()` (`!shutdownRequested && !queue.isEmpty() && shouldRun()`, + extracted so the loop condition and its post-drain recheck below can't drift apart) holds, polling one message at + a time and submitting **each individual message** as its own task to the same executor (so message processing + itself is also concurrent, not just the drain loop) — a per-message `RejectedExecutionException` during a + shutdown race just returns; any other exception from the submission reaches `messageProcessorErrorCallback`. + `queuedCount` is decremented only once a message's submitted task actually *finishes* (in a `finally` around the + processor/error-callback calls) or is known never to run (executor `null`, submission threw) — **not** right + after `poll()` — because decrementing immediately would free a capacity slot the instant a message left `queue`, + even though it then sat in the executor's own unbounded internal work queue awaiting a free worker thread; a slow + processor could accumulate arbitrarily many not-yet-run tasks there while `enqueue()` kept accepting more, + defeating the point of capacity (it would only ever bound `queue` itself, not total outstanding work). A `finally` + block around the whole loop always resets `draining` back to `false` on exit, then re-checks + `canContinueDraining()` and calls `process()` again if it's still true — closing a race window between the loop + observing "nothing left to do" and the flag actually clearing, where a concurrent `enqueue()`/`process()` call + could otherwise see `draining` still true, skip submitting, and never get drained. - **No ordering guarantee between messages** (investigated for ticket 09, `.scratch/codebase-review-followups/issues/09-reactivequeue-message-ordering.md`, confirmed): because each message becomes its own independent executor task, once the fixed thread pool has more than one worker thread @@ -534,22 +641,44 @@ unavailable, drain once it's back." under a `synchronized` block it sets a `volatile shutdownRequested` flag and calls `executor.shutdown()` together (paired with `getExecutor()` sharing the same monitor, so a `shutdown()` racing a lazy executor creation can't leave a freshly-created executor un-shut-down), then — lock released, so an in-flight task's own - `getExecutor()` call can't deadlock against it — blocks up to `SHUTDOWN_AWAIT_SECONDS` (5) on + `getExecutor()` call can't deadlock against it — blocks up to `shutdownAwaitSeconds` on `awaitTermination`, falling back to `shutdownNow()` (then one more bounded `awaitTermination`) if the timeout - elapses. This is what lets a caller that awaits `shutdown()` returning (e.g. `BlueMapAPIConnector.onDisable`) + elapses, returning `true`/`false` for whether it confirmed a clean stop (read by `BlueMapAPIConnector.onDisable`/ + `shutdown()`, §6). This is what lets a caller that awaits `shutdown()` returning (e.g. `BlueMapAPIConnector.onDisable`) rely on there being no straggler task still able to touch shared state afterward, which otherwise could run after a subsequent `resetQueue()`/`fireReset()` replay and clobber the state that replay just established. + `shutdownAwaitSeconds` is now **configurable** rather than the fixed `DEFAULT_SHUTDOWN_AWAIT_SECONDS` (5): the + public/BlueMapAPIConnector-facing constructor takes it as a parameter, sourced from + `ConfigManager.get().getShutdownAwaitSeconds()` — a `BMSMConfigV2` field (`config-and-persistence.md`) resolved + the same validating-with-fallback way as `sorting`/`lineWidth` (malformed or non-positive falls back to the + default with a warning, `ConfigProvider.resolveShutdownAwaitSeconds`) — so an operator can tune how long server + stop/BlueMap-disable waits for in-flight marker actions before forcing them. - Once `shutdownRequested` is set, `getExecutor()` **never creates a replacement executor** — a shut-down queue is permanently retired rather than self-healing (finding #2). This is why `BlueMapAPIConnector.onEnable` has to call `resetQueue()` (a brand-new `ReactiveQueue` instance) rather than relying on the old one to resurrect itself. -- `executor` is `volatile` (finding #12, resolved 2026-07-22) so `isShutdown()` — callable with no lock held, from - any thread — sees `getExecutor()`'s synchronized write without needing its own synchronization. -- A package-private constructor overload accepts an `ExecutorService` directly (the public 3-arg constructor +- `executor` is `volatile` (finding #12, resolved 2026-07-22) so `isShutdown()`/`hasStarted()` — callable with no + lock held, from any thread — see `getExecutor()`'s synchronized write without needing their own synchronization. + `isShutdown()` returns `shutdownRequested` alone now (finding 63, + `.scratch/concurrency-pass-2026-09/issues/04-reactivequeue-isshutdown-semantics.md`) — it used to also return + `true` for `executor == null || executor.isShutdown()`, conflating "genuinely shut down" with "never started" (a + queue whose `process()` calls all returned early via `shouldRun()`/`shutdownRequested` before ever lazily creating + an executor). That conflation was real: `BlueMapAPIConnector.onEnable()` needed a whole separate + `disabledSinceLastEnable` flag to tell a genuine BlueMap disable/re-enable apart from the very first `onEnable()` + a server ever sees (§6), precisely because the old `isShutdown()` also reported `true` for the never-started case. + `shutdownRequested` alone is sufficient — only `shutdown()` ever sets it, always synchronously with calling + `executor.shutdown()` on whatever executor exists at that moment, and nothing outside this class can shut the + internal executor down through any other path. `hasStarted()` (`executor != null`) exposes the other half of the + old conflation directly, for any caller that genuinely needs to know "has this instance ever lazily created its + executor" regardless of shutdown state. +- A package-private constructor overload accepts an `ExecutorService` directly (the public constructor delegates to it with `null`, same as before) — test-only seam so `ReactiveQueueTest` can inject a synchronous or failure-simulating fake executor instead of the lazily-created fixed thread pool, with no change to real - behavior. See `testing.md` for what it covers, including a documented remaining gap: an exception thrown by the - processor callback itself is swallowed (captured on an unawaited `Future`, never reaching - `messageProcessorErrorCallback`) — only a submission-time failure reaches that callback. + behavior. A previously-documented gap — an exception thrown by the processor callback itself was swallowed + (captured on an unawaited `Future`, never reaching `messageProcessorErrorCallback`), only a submission-time + failure reached that callback — is now fixed: the task submitted per-message in `processMessages` wraps + `messageProcessorCallback.processMessage(message)` in its own `try/catch`, forwarding any exception to + `messageProcessorErrorCallback` (itself wrapped in a `try/catch` so a broken error callback can't kill the worker + thread or propagate back to `enqueue()`'s caller). See `testing.md` for full coverage. ## 8. Per-map render-bounds gating — `core.bounds.RenderMaskEvaluator` @@ -563,7 +692,12 @@ gating" section. This section covers the code-level mechanics. brace-depth-aware splitting on commas); `extractFields`/`extractType` pull a shape's fields into a `Map` (type defaults to `"box"` if omitted). `FIELD_PATTERN` allows an optional matching pair of `"` around a numeric/boolean literal (fixed so `subtract: "true"` parses identically to `subtract: true`, rather - than silently falling back to the field's default because the quoted form went unmatched). + than silently falling back to the field's default because the quoted form went unmatched). `intField` parses its + int-typed fields (`min-x`/`max-x`/`min-y`/`max-y`/`min-z`/`max-z`) via `new BigDecimal(value).intValueExact()` + rather than `Integer.parseInt` — `FIELD_PATTERN`'s numeric alternative allows exponent notation (e.g. `"1e3"`) on + every numeric field, int-typed ones included, and `Integer.parseInt` can't handle that form (would throw, failing + the whole map open on an otherwise-valid value); a genuinely fractional value (e.g. `"1.5"`) still throws via + `intValueExact`, same as before. - Two entry points: `isInsideRenderBounds(mapId, mapsConfigDir, x, y, z)` (one-shot convenience) and `load(mapId, mapsConfigDir)` → `RenderMask` (a small class wrapping `List` with one method, `contains(x, y, z)`) — `BlueMapAPIConnector` always uses `load`, since it tests many points against the same @@ -593,16 +727,16 @@ gating" section. This section covers the code-level mechanics. the pre-existing `markerSetsCache` only stored bare `MarkerSet`s. - **Gated vs. unconditional dispatch**: `prepareSingleAction` routes `AddMarkerAction`/`UpdateMarkerAction` (single point, wrapped via a `pointOf(MarkerIdentifier)` helper into a one-element point list) and - `SetLineMarkerAction`/`SetShapeMarkerAction` (their own multi-point `getPoints()`) through + `SetMultiPointMarkerAction` (its own multi-point `getPoints()`, covering `LINE`/`SHAPE`/`EXTRUDE` alike) through `prepareGated(identifier, points, effect)`. For each target `MappedMarkerSet`, `isInsideRenderBounds` is `points.stream().anyMatch(p -> mask.contains(...))` — **any one point in bounds passes the whole marker** (all-or-nothing for `LINE`/`SHAPE`, no per-point clipping). On a pass, `effect.accept(markers)` runs as normal; on a gate failure, the marker id is actively removed from that map's set (`markers.remove(identifier.getId())`) instead of merely skipping the add/update — this is what sweeps a marker that already existed on a now-out-of-bounds map before this feature shipped, reusing `SignManager.reset()`'s existing reload-forced - re-dispatch of every sign (§3) as the trigger. `RemoveMarkerAction`/`RemoveLineMarkerAction`/ - `RemoveShapeMarkerAction` instead go through `prepareUngated(identifier, effect)` — unconditional, no - gating, since an explicit removal means the sign's representation is genuinely leaving, independent of bounds. + re-dispatch of every sign (§3) as the trigger. `RemoveMarkerAction`/`RemoveMultiPointMarkerAction` instead go + through `prepareUngated(identifier, effect)` — unconditional, no gating, since an explicit removal means the + sign's representation is genuinely leaving, independent of bounds. - **Cold-load-off-the-lock fix**: `prepareGated`/`prepareUngated` return a `Runnable` that performs only the marker-set mutation; `prepareGated` computes each target map's gate decision (`markerSets.get().stream().map(mapped -> Map.entry(mapped, isInsideRenderBounds(...))).toList()`) up front, before @@ -614,5 +748,5 @@ gating" section. This section covers the code-level mechanics. themselves are otherwise unchanged — the fix is localized to `prepareGated`. --- -*Last updated: 2026-09-06 | Verified against: feature/tpwalke2/198-dye-colors (535bb13)* +*Last updated: 2026-09-12 | Verified against: feature/tpwalke2/209-signtransitionresolver (4d45867)* diff --git a/agent-context/context/testing.md b/agent-context/context/testing.md index b29d5e8..0aece3f 100644 --- a/agent-context/context/testing.md +++ b/agent-context/context/testing.md @@ -15,7 +15,7 @@ in `build.gradle`. Only plain-Java classes with **no Minecraft/Fabric/BlueMap API types in their method signatures** are unit tested. Qualifying today: `SignLinesParser`/`ParsingContext`/`SignLinesParseResult`, `SignEntry`, `SignEntryHelper`, `SignChunkKey`/`SignChunkIndex`, `MarkerGroup`/`MarkerGroupMatchType`/`MarkerGroupType`, `ConfigManager`/`ConfigProvider`, -`ReactiveQueue`, `HtmlUtils`, `FileUtils`, `ColorUtils`, `ColorResolver`, +`ReactiveQueue`, `HtmlUtils`, `FileUtils`, `ColorUtils`, `ColorResolver`, `SafeCall`, `ServerPathResolver`, `LineGroupResolver`/`ShapeGroupResolver`/`ExtrudeGroupResolver`, `SignTransitionResolver`, `RenderMaskEvaluator` (`core.bounds` — see `core-pipeline.md` §8), the sign-persistence loaders/converters/writer (`VersionedFileSignEntryLoader`, `Version1SignEntryLoader`, @@ -24,10 +24,16 @@ sign-persistence loaders/converters/writer (`VersionedFileSignEntryLoader`, `Ver `ActionFactory`/`MarkerSetIdentifierCollection`. `SignManager` itself stays game-coupled (its constructor builds a `BlueMapAPIConnector`), but its `reparseFromRawLines`/`safeReparseFromRawLines` reparse-on-reload logic (§3 of `core-pipeline.md`) is extracted as a package-visible static specifically so it's directly testable. -`BlueMapAPIConnector` itself stays game-coupled overall, but its `resolveExtrudeHeightRange` helper (§6 of -`core-pipeline.md`) is a package-private static returning a plain `ExtrudeHeightRange` record with no -`bluemap-api` types, specifically so it's directly testable (`BlueMapAPIConnectorTest`) without pulling -`bluemap-api` (`compileOnly`) onto the test classpath. +`BlueMapAPIConnector` itself stays game-coupled overall, but two helpers (§6 of `core-pipeline.md`) are +package-private specifically so they're directly testable (`BlueMapAPIConnectorTest`) without pulling `bluemap-api` +(`compileOnly`) onto the test classpath or constructing a live connector (which calls `BlueMapAPI.getInstance()`): +`pointOf` (wraps a `MarkerIdentifier`'s coordinates into a single-point `List`), and +`isInsideRenderBounds(RenderMask, ...)` (the pure mask-vs-points predicate behind the render-bounds gate, §8). +`MarkerMutations` (ticket 04, `.scratch/marker-action-consolidation/issues/04-shrink-bluemapapiconnector-marker-mutations.md` +— extracted out of `BlueMapAPIConnector`) is the same story one level down: game-coupled overall (its methods take +live `bluemap-api` marker types), but `resolveExtrudeHeightRange` is package-private specifically so it stays +directly testable (`MarkerMutationsTest`) — a plain `ExtrudeHeightRange` record, no `bluemap-api` types in its +signature. `Version1SignEntryLoader` used to be a partial exception — its legacy-shorthand (`"nether"`/`"end"`/`"overworld"`) dimension normalization branch read `net.minecraft.world.level.Level`'s static constants, requiring a running @@ -36,8 +42,9 @@ e.g. `"minecraft:the_nether"`) specifically so `Version1SignEntryLoaderTest` cou branches directly instead of only via an already-namespaced dimension string. Excluded — anything that must reference live game types (`SignHelper`, the two mixins, `BlueMapSignMarkersMod` -including its `ServerChunkEvents.CHUNK_LOAD` reconciliation handler, `BlueMapAPIConnector` (except its -`resolveExtrudeHeightRange` static, see above), `SignProvider` itself, +including its `ServerChunkEvents.CHUNK_LOAD` reconciliation handler, `BlueMapAPIConnector` (except its `pointOf`/ +`isInsideRenderBounds` statics, see above), `MarkerMutations` (except its `resolveExtrudeHeightRange` static, see +above), `SignProvider` itself, since loading/saving calls the game-coupled `SignManager` singleton) — these are thin glue and can only be verified manually: `./gradlew runServer` + placing/editing/breaking signs in-game (and, for chunk-load reconciliation specifically, removing a sign block without going through the mod — e.g. deleting its chunk's @@ -47,7 +54,7 @@ updates), watching the BlueMap web UI update. ## Current coverage -As of `feature/tpwalke2/198-dye-colors` (`535bb13`), `src/test/java/com/tpwalke2/bluemapsignmarkers/`: +As of `main` (`b2c5fa0`), `src/test/java/com/tpwalke2/bluemapsignmarkers/`: - `core/signs/SignLinesParserTest.java` — 12 `@Test` methods covering `SignLinesParser`: label-on-prefix-line vs. label-on-following-line, multi-line detail joining/trimming, leading/interstitial blank-line handling, no-match and all-blank sign results, `REGEX` match type's whole-line-match requirement (contrasted with `STARTS_WITH`), @@ -69,6 +76,9 @@ As of `feature/tpwalke2/198-dye-colors` (`535bb13`), `src/test/java/com/tpwalke2 - `core/signs/persistence/SignRegionKeyTest.java` — region assignment via `floorDiv` (including negative coordinates and the exact region-boundary blocks 511/512), and `relativeFilePath` namespace/path splitting (including the no-colon `unknown` dimension and a nested-path dimension). + `relativeFilePathRejectsADriveRelativeDimensionPath` (`@EnabledOnOs(OS.WINDOWS)`, since `\` is just an ordinary + filename character elsewhere) confirms a dimension string containing a Windows drive-relative path segment + (`isAbsolute() == false` but still carries a root component) is rejected too, not just a plain absolute path. - `core/signs/persistence/SignRegionPartitionerTest.java` — grouping entries by region and dimension, multiple entries landing in the same region, empty input. - `core/signs/persistence/RegionShardedSignEntryWriterTest.java` — one file per region; stale region files (signs @@ -87,7 +97,9 @@ As of `feature/tpwalke2/198-dye-colors` (`535bb13`), `src/test/java/com/tpwalke2 `getLabel`/`getDetail` front/back precedence and combining, plus `getDetail`'s ticket-07 fix (`getDetailUsesOnlyFrontWhenSidesMatchDifferentGroups`): when front and back match *different* marker groups, only the front's detail is used rather than merging both — see `core-pipeline.md`'s `SignEntryHelper` paragraph. - `getDye` (GitHub issue #198) has front-preferred/back-fallback tests mirroring `getPrefix`'s precedence rule. + `getLabel` has the matching fix covered too: a blank front label on a group-mismatched sign returns `""` instead + of borrowing the back side's label. `getDye` (GitHub issue #198) has front-preferred/back-fallback tests + mirroring `getPrefix`'s precedence rule. - `core/signs/SignEntryTest.java` — standard `equals`/`hashCode` contract on the hand-written implementation (reflexive, symmetric, per-field inequality including the added `createdAtMillis` field, not equal to `null`/another type), `withKey` returning a new instance with only the key changed (`createdAtMillis` carried @@ -103,6 +115,11 @@ As of `feature/tpwalke2/198-dye-colors` (`535bb13`), `src/test/java/com/tpwalke2 `buildResult()` using the set group's `prefix()` plus the current label, multiple `appendDetail` calls joining with `\n`, and that the final `trim()` only strips the outermost whitespace of the joined detail, not per-line padding. +- `common/SafeCallTest.java` — `run` executes the action when it succeeds; swallows a thrown `RuntimeException` or + `Error` (via `assertDoesNotThrow`) instead of letting it propagate. +- `common/ServerPathResolverTest.java` — `resolveMarkerStorageRoot` normalizes the trailing `"."` segment + `LevelResource.ROOT`'s raw path carries; `resolveLegacyMarkerFilePath` reproduces the pre-existing unnormalized + formula unchanged (see `config-and-persistence.md`). - `common/FileUtilsTest.java` — `createBackup` copies the original when no backup exists yet and leaves an existing backup untouched; `moveToBackup` moves the original into place, no-ops when the source is missing, and no-ops when a backup already exists; `createBackupReturnsFalseWhenTheCopyFails` and @@ -125,7 +142,7 @@ As of `feature/tpwalke2/198-dye-colors` (`535bb13`), `src/test/java/com/tpwalke2 a no-op, dispatches `Set` with `isFirstAppearance=true` at exactly two members, `isFirstAppearance=false` joining a third; POI→NONE dispatches Remove; POI→POI on the same group with label/detail both unchanged is a no-op, either changed dispatches `UpdateMarkerAction`, a different group dispatches `GroupTransitionMarkerAction`; - LINE→NONE dropping to one remaining member dispatches `RemoveLineMarkerAction`, to zero is a no-op, to ≥2 dispatches + LINE→NONE dropping to one remaining member dispatches `RemoveMultiPointMarkerAction`, to zero is a no-op, to ≥2 dispatches a refreshed `Set`; LINE→LINE on the same group+label with detail unchanged is a no-op, changed dispatches `Set` with `isFirstAppearance=false`, a different group bundles a leave+join `GroupTransitionMarkerAction`; POI→LINE and LINE→POI each bundle the appropriate remove/set + add/set pair. Confirms the POI/POI cell keys only on @@ -133,11 +150,12 @@ As of `feature/tpwalke2/198-dye-colors` (`535bb13`), `src/test/java/com/tpwalke2 bundled remove+add (fixed alongside the `allSigns`-snapshot performance change, both same commit series). `SHAPE` coverage mirrors `LINE`'s exactly but gated on `SHAPE_MIN_MEMBERS = 3`: NONE↔SHAPE at exactly 3 members (`isFirstAppearance` true/false), below-threshold no-ops, SHAPE→NONE dropping to 2 members dispatching - `RemoveShapeMarkerAction`, SHAPE↔SHAPE same-group/label recompute (no-op vs. detail-changed vs. + `RemoveMultiPointMarkerAction`, SHAPE↔SHAPE same-group/label recompute (no-op vs. detail-changed vs. reload-forced), and the full cross-type bundling matrix (POI↔SHAPE, LINE↔SHAPE) both for a live sign change and for a config-reload-driven type flip/rename (`groupIdentityObsolete`). `EXTRUDE` coverage mirrors `SHAPE`'s exactly (same `EXTRUDE_MIN_MEMBERS = 3` threshold, same no-op/first-appearance/recompute/cross-type-bundling - shape), confirming `extrudeJoinAction`/`extrudeLeaveAction` behave identically to their `SHAPE` counterparts. Every + shape), confirming the shared `multiPointJoinAction`/`multiPointLeaveAction` (§209 collapse, see `core-pipeline.md` + §3) behave identically for `EXTRUDE` as for `SHAPE`. Every `LINE`/`SHAPE`/`EXTRUDE` dispatched-`Set` assertion now checks `set.getDetail()` against each member's *own* detail text, not the group label — this test-suite-wide update caught the `rep.label()`-passed-as-detail bug fixed alongside GitHub issue #198 (see `core-pipeline.md` §3's join/leave paragraph). Player-controlled colours @@ -148,7 +166,11 @@ As of `feature/tpwalke2/198-dye-colors` (`535bb13`), `src/test/java/com/tpwalke2 (and unchanged detail) still no-ops; `lineToLineSameGroupAndLabelDyeOnlyChangeIsNoOpWhenAllowPlayerColorsIsOff` confirms a dye-only edit on an `allowPlayerColors`-disabled group stays a no-op instead of paying the full recompute cost; `lineJoinResolvesColorFromTheEarliestPlacedDyedMember` confirms a fresh join recomputes colour - via `ColorResolver` across the full current membership. + via `ColorResolver` across the full current membership. Two regression tests + (`../reviews/copilot-review-2026-09-07.md`) cover a `null` `Representation.dye()` (corrupted/hand-edited persisted + data): `lineToLineDyeChangedFromNullDispatchesRecomputeInsteadOfThrowing` and + `lineToLineBothDyesNullIsNoOpInsteadOfThrowing` confirm the no-op guard's dye comparison is null-safe + (`Objects.equals`, not a direct `.equals()` call) instead of throwing an NPE. - `core/signs/ColorResolverTest.java` — `resolve` (GitHub issue #198): `allowPlayerColors` off returns the group's configured `lineColor`/`fillColor` unchanged even when a member is dyed; on with no dyed members (all `"BLACK"`) also returns them unchanged; on with a dyed member replaces the hue but keeps the configured alpha byte for both @@ -200,27 +222,54 @@ As of `feature/tpwalke2/198-dye-colors` (`535bb13`), `src/test/java/com/tpwalke2 (GitHub issue #198) has `loadConfigDefaultsAllowPlayerColorsToFalseWhenOmitted` and `loadConfigPreservesExplicitAllowPlayerColorsOnALineGroup` for a `LINE` group, plus `loadConfigWarnsWhenAllowPlayerColorsIsSetOnAPOIGroup` (warning-only, not a load failure, per - `warnOnTypeFieldMismatches`). + `warnOnTypeFieldMismatches`). `name`'s missing/blank fallback (finding 14) has three tests: + `loadConfigFallsBackToThePrefixWhenNameIsMissingRatherThanWipingTheWholeConfig` and + `loadConfigFallsBackToThePrefixWhenNameIsBlank` confirm a missing or blank `name` falls back to that group's + `prefix` with a warning rather than throwing and reverting the *entire* config to defaults; + `loadConfigStillRejectsAnEmptyPrefixEvenWhenNameAlsoFallsBackToAPlaceholder` confirms `resolveName` itself + doesn't throw when both `name` and `prefix` are absent (falls back to the `"(unnamed)"` placeholder), and that + `validateMarkerGroups`'s empty-prefix rejection still fires afterward. + `loadConfigRejectsTheSamePrefixTextAcrossDifferentMatchTypes` confirms `validateMarkerGroups`'s duplicate-prefix + check compares prefix text alone, catching a collision even when one group is `STARTS_WITH` and the other + `REGEX`. `shutdownAwaitSeconds` (`config-and-persistence.md`) has the same shape of coverage as `sorting`: + `loadConfigDefaultsShutdownAwaitSecondsWhenOmitted`, `loadConfigPreservesExplicitShutdownAwaitSeconds`, and + malformed-value fallback tests `loadConfigFallsBackToDefaultShutdownAwaitSecondsWhenMalformed`/ + `...WhenNonPositive`. - `config/ConfigManagerTest.java` — `get()` returns the config from the most recent `reload`; falls back to `new BMSMConfigV2()` defaults when the configured path fails to load; a second `reload()` replaces (not merges - with) what an earlier `reload` cached. + with) what an earlier `reload` cached. `concurrentFirstTimeCallersConvergeOnOneConfigInstance` (finding #72, + `agent-context/reviews/full-codebase-review_2026-09-07_0900.md`) is an active regression test for `get()`'s + double-checked-locking fix: many threads racing the very first (unsynchronized) `get()` call all converge on the + same loaded `BMSMConfigV2` instance instead of each redundantly loading and racing over which instance wins + (`resetForTesting()`, package-private, lets the test exercise the first-load path repeatedly per test method + instead of only once per JVM). - `core/bluemap/actions/ActionFactoryTest.java` — each of `createAddPOIAction`/`createRemovePOIAction`/ `createUpdatePOIAction` builds the right `MarkerIdentifier` and action-specific fields; - `createChangeGroupPOIActionBuildsARemoveAndAddEffectPair` (ticket 09, updated for the line-markers rewrite) now - asserts `createChangeGroupPOIAction` returns a `GroupTransitionMarkerAction` with exactly two `effects` — a - `RemoveMarkerAction` for the old group then an `AddMarkerAction` for the new one — rather than the older single - action type carrying two identifiers directly; repeated calls for the same map/group (same or different action - type) reuse the same `MarkerSetIdentifier` instance via `MarkerSetIdentifierCollection`. `createSetLineAction`/ - `createRemoveLineAction` each have a dedicated test asserting the built `SetLineMarkerAction`/`RemoveLineMarkerAction` - fields and `LineMarkerIdentifier`, plus a reuse test confirming line and POI actions for the same map/group share - one `MarkerSetIdentifier` (ticket 11). `createSetShapeAction`/`createRemoveShapeAction` have the same shape of - dedicated tests, additionally confirming `fillColor` is threaded from the `MarkerGroup` into the built - `SetShapeMarkerAction`, and that set/remove use independent `ShapeMarkerIdentifier`s. `createSetExtrudeAction`/ - `createRemoveExtrudeAction` (ticket 196) have the same shape of tests again, confirming `fillColor` threading and - independent `ExtrudeMarkerIdentifier`s. `createSetLineAction`/`createSetShapeAction`/`createSetExtrudeAction` - (GitHub issue #198) now take an explicit `lineColor`/`fillColor` parameter instead of reading it off - `MarkerGroup` — every existing call site in this test class passes `group.lineColor()`/`group.fillColor()` - explicitly, so the assertions on the built actions' colour fields are unchanged. + `createGroupTransitionPOIActionBuildsARemoveAndAddEffectPair` (ticket 09, renamed from + `createChangeGroupPOIActionBuildsARemoveAndAddEffectPair` when `ActionFactory`'s per-kind factory methods were + collapsed, #209) asserts `createGroupTransitionPOIAction` returns a `GroupTransitionMarkerAction` with exactly two + `effects` — a `RemoveMarkerAction` for the old group then an `AddMarkerAction` for the new one; repeated calls for + the same map/group (same or different action type) reuse the same `MarkerSetIdentifier` instance via + `MarkerSetIdentifierCollection`. `createSetMultiPointAction`/`createRemoveMultiPointAction` are the single + `LINE`/`SHAPE`/`EXTRUDE` factory pair (replacing the former per-type `createSetLineAction`/`createSetShapeAction`/ + `createSetExtrudeAction`/`createRemoveLineAction`/`createRemoveShapeAction`/`createRemoveExtrudeAction` methods, + #209 — `core-pipeline.md` §5): dedicated tests per type assert the built `SetMultiPointMarkerAction`/ + `RemoveMultiPointMarkerAction` fields and the `MultiPointMarkerIdentifier`'s `kind` (`"line"`/`"shape"`/ + `"extrude"`), plus reuse tests confirming actions for the same map/group share one `MarkerSetIdentifier` regardless + of type. `SHAPE`/`EXTRUDE` cases additionally confirm `fillColor` is threaded from the caller into the built + action (`LINE` passes `null`, having none). `createSetMultiPointAction`/`createRemoveMultiPointAction` take + explicit `lineColor`/`fillColor` parameters rather than reading them off `MarkerGroup` (GitHub issue #198) — every + call site in this test class passes `group.lineColor()`/`group.fillColor()` explicitly. + `createSetMultiPointActionRejectsAPOIMarkerGroup`/`createRemoveMultiPointActionRejectsAPOIMarkerGroup` replace the + former three per-type `requireGroupType` rejection tests with one pair, since both factory methods now derive + `kind`/minimum-members from `markerGroup.type()` via a single private `multiPointKind` switch that throws + `IllegalArgumentException` for `POI` (`core-pipeline.md` §5). + `createSetMultiPointActionRejectsFewerThanTwoPointsForALineGroup`/`...ThreePointsForAShapeGroup`/ + `...ThreePointsForAnExtrudeGroup` (copilot-review.2026-09-11.md) pin each type's own minimum-points threshold + directly rather than relying on the happy-path tests' fixed point-list sizes — a regression mapping `SHAPE`/ + `EXTRUDE` to `LINE_MIN_MEMBERS` (2) instead of their own `SHAPE_MIN_MEMBERS`/`EXTRUDE_MIN_MEMBERS` (3) would still + pass a same-sized-points-list test (2 points also satisfies `LINE`), so these assert rejection exactly one point + below each kind's *own* minimum. - `core/markers/MarkerSetIdentifierCollectionTest.java` — `getIdentifier` returns the same instance for a repeated `(mapId, markerGroup)` pair (case-insensitive on `mapId`), distinct pairs get distinct identifiers. Also includes `concurrentFirstTimeCallersForTheSameComboConvergeOnOneIdentifierInstance`, an active (not `@Disabled`) regression @@ -229,23 +278,34 @@ As of `feature/tpwalke2/198-dye-colors` (`535bb13`), `src/test/java/com/tpwalke2 `getIdentifier` became `synchronized` (see `core-pipeline.md` §5). - `core/reactive/ReactiveQueueTest.java` — enqueue → processor callback delivery (single and multiple messages, each exactly once); `shouldRun` gating (queued while false, resumes once true, a mid-drain false leaves the rest - queued); a submission failure for one message reaching the error callback without affecting later messages. + queued); a submission failure for one message reaching the error callback without affecting later messages; + `exceptionThrownByProcessorCallbackIsSurfacedToTheErrorCallback` and + `exceptionThrownByTheErrorCallbackItselfDoesNotStopLaterMessagesFromBeingProcessed` cover the fixed gap where a + processor-callback exception used to be swallowed (`core-pipeline.md` §7). Concurrency-hardening regression coverage (`../plans/codebase-review-2026-07-11.md`, resolved 2026-07-22): `shutdownBlocksUntilAnInFlightTaskFinishesBeforeReturning` (finding #10 — `shutdown()` now blocks on `awaitTermination` rather than returning while a task is still mid-flight), `shutdownPermanentlyStopsTheQueueFromProcessingLaterEnqueues` and `shutdownRacingMidDrainStopsTheLoopWithoutSpawningAReplacementExecutor` (finding #2 — a shut-down queue never self-heals a replacement executor, including when `shutdown()` races a still-draining `processMessages()` loop), - and `concurrentEnqueueBurstDeliversEveryMessageExactlyOnceDespiteRedundantDrainLoopFanOut` (documents current - "before" behavior: a burst of concurrent enqueues spawns more drain-loop submissions than messages, but every - message still lands exactly once — not itself a bug, just characterizing the fan-out). A documented remaining - gap: an exception thrown by the processor callback itself never reaches `messageProcessorErrorCallback` (it's - captured on an unawaited `Future` and dropped) versus a submission-time failure, which does reach it via a fake - executor. `reactiveQueueGivesNoOrderingGuaranteeBetweenIndependentlySubmittedMessages` (ticket 09) confirms and + and `concurrentEnqueueBurstDeliversEveryMessageExactlyOnceWithBoundedDrainLoopSubmissions` (renamed from + `...DespiteRedundantDrainLoopFanOut` once the `draining` CAS guard bounded the fan-out it used to just + characterize — now confirms a burst of concurrent enqueues submits a bounded number of drain-loop tasks while + still delivering every message exactly once). `shutdownReturnsTrueWhenNoExecutorWasEverCreated`, + `shutdownHonorsAConfiguredTimeoutShorterThanTheDefault`, and + `shutdownReturnsFalseWhenATaskIgnoresInterruptionThroughBothAwaitWindows` cover `shutdown()`'s configurable + `shutdownAwaitSeconds` and boolean return value (`core-pipeline.md` §7). `isShutdownIsFalseAndHasNotStartedIsFalseBeforeAnyWorkHasBeenScheduled`, + `isShutdownIsFalseAndHasNotStartedIsFalseWhenShouldRunIsFalse`, and + `isShutdownIsFalseAndHasStartedIsTrueOnceWorkHasBeenScheduled` cover the `isShutdown()`/`hasStarted()` split + (finding 63, `.scratch/concurrency-pass-2026-09/issues/04-reactivequeue-isshutdown-semantics.md`) — `isShutdown()` + no longer conflates "never started" with "genuinely shut down". `enqueueRejectsMessagesOnceCapacityIsReached` and + `consumeOverflowSinceLastCheckReportsAndClearsCapacityRejection` cover the capacity bound and overflow-tracking + added for finding 61 (`agent-context/reviews/full-codebase-review_2026-09-07_0900.md`, `core-pipeline.md` §7). + `reactiveQueueGivesNoOrderingGuaranteeBetweenIndependentlySubmittedMessages` (ticket 09) confirms and reproduces that two independently-`enqueue()`d messages have no relative execution-order guarantee once the executor has more than one worker thread (blocks the first message's processing on a real 2-thread pool and shows the second can finish first) — see `core-pipeline.md` §7 for why this is left as-is rather than fixed in - `ReactiveQueue` itself; its doc comment now points at `GroupTransitionMarkerAction`/`applySingleAction` (renamed - from `ChangeGroupMarkerAction`/`processChangeGroupAction`) as the caller relying on bundled-message ordering. + `ReactiveQueue` itself; its doc comment points at `GroupTransitionMarkerAction`/`applySingleAction` as the caller + relying on bundled-message ordering. - `core/signs/persistence/loaders/Version3ConverterTest.java` — basic V2→V3 conversion (both sides matched, POI group's prefix assumed for both, output is the frozen `SignEntryV3` shape); `aNonMatchingSideStaysNonMatching` and `treatsAMatchedSideAsNonMatchingWhenNoPoiGroupIsConfigured` (GitHub issue #138/review finding #6, parts a and c, @@ -277,7 +337,9 @@ As of `feature/tpwalke2/198-dye-colors` (`535bb13`), `src/test/java/com/tpwalke2 the backup failure and still proceeding with the in-memory migration (rather than aborting) if backing up to `.v2.bak`/`.v3.bak`/`.v4.bak`/`.v5.bak` fails, per `v2ContentStillMigratesWhenTheBackupFails` (ticket 02); and `v5ContentWithANullEntryIsSkippedRatherThanLosingTheWholeFile` confirming a JSON `null` entry in a V5 array is - skipped rather than throwing out of `Version6Converter.convertToV6` and discarding every other entry in the file. + skipped rather than throwing out of `Version6Converter.convertToV6` and discarding every other entry in the file; + `v6ContentWithANullEntryIsSkippedRatherThanLosingTheWholeFile` confirms the same for the current-version branch, + which previously deserialized the array as-is with no null-filtering at all (`../reviews/copilot-review-2026-09-07.md`). - `core/signs/persistence/loaders/Version1SignEntryLoaderTest.java` — the three recognized legacy shorthand strings (`"nether"`/`"end"`/`"overworld"`) *and* the canonical-but-unnamespaced resource paths (`"the_nether"`/`"the_end"`, ticket 05) normalizing to their canonical namespaced identifiers, case-insensitively, @@ -301,9 +363,17 @@ As of `feature/tpwalke2/198-dye-colors` (`535bb13`), `src/test/java/com/tpwalke2 casting); and `quotedBooleanAndNumericFieldsAreEquivalentToBareLiterals` confirming a quoted literal (`subtract: "true"`) parses identically to the bare form (the fix in commit `217c17f`). - `core/bluemap/BlueMapAPIConnectorTest.java` — the sole test class for otherwise-game-coupled `BlueMapAPIConnector`, - exercising only its package-private `resolveExtrudeHeightRange` static (ticket 196, see `core-pipeline.md` §6): - members all at the same Y get a minimum 1-block height instead of collapsing to zero; members at different Ys - span their actual lowest-to-tallest height. + exercising only its package-private statics (see `core-pipeline.md` §6, since even constructing a live connector + calls `BlueMapAPI.getInstance()`): `pointOfWrapsAMarkerIdentifiersCoordinatesIntoASinglePointList` confirms + `pointOf` builds the single-point list a POI marker's render-bounds check uses; `isInsideRenderBounds(RenderMask, + ...)` has a dedicated block using a real `RenderMaskEvaluator.load` fixture — a POI point inside/outside the mask, + a multi-point line with at least one member inside (in bounds) vs. every member outside (out of bounds), and an + unbounded mask (no `render-mask` configured) allowing any point. +- `core/bluemap/MarkerMutationsTest.java` (ticket 04, new — split out of `BlueMapAPIConnectorTest` when + `resolveExtrudeHeightRange` moved into the new `MarkerMutations` class alongside the rest of + `BlueMapAPIConnector`'s marker-construction logic) — `resolveExtrudeHeightRange`: members all at the same Y get a + minimum 1-block height instead of collapsing to zero, members at different Ys span their actual + lowest-to-tallest height. ## CI integration @@ -312,12 +382,16 @@ dispatch) both run `./gradlew test` before anything else — a test failure in ` publish step entirely. Both workflows have a `summarize test results` step (`if: always()`, so it runs even when tests fail) -immediately after the test step: it sums the `tests`/`failures`/`errors`/`skipped` XML attributes out of -`build/test-results/test/*.xml` using plain shell (`sed`, looping the glob, `shopt -s nullglob`) and writes a -markdown pass/fail table to `$GITHUB_STEP_SUMMARY`. This was a **deliberate choice over a `checks: write`-based -JUnit reporter action** — those actions don't get `checks: write` permission on PRs from forks by default in a -public repo, so the summary step was written to need no extra permissions. +immediately after the test step, delegating to the shared composite action `.github/actions/summarize-test-results/ +action.yml`: it sums the `tests`/`failures`/`errors`/`skipped` XML attributes out of `build/test-results/test/*.xml` +using plain shell (`sed`, looping the glob, `shopt -s nullglob`) and writes a markdown pass/fail table to +`$GITHUB_STEP_SUMMARY` — a report file whose attributes can't be parsed is excluded from the totals and called out +in the summary (`::warning`) rather than silently skewing the counts or failing the step. This was a **deliberate +choice over a `checks: write`-based JUnit reporter action** — those actions don't get `checks: write` permission on +PRs from forks by default in a public repo, so the summary step was written to need no extra permissions. Both +workflow jobs also now declare an explicit `permissions: contents: read` (least-privilege, rather than relying on +the repo's default token permissions), and `publish.yml`'s job runs under a `modrinth-publish` GitHub Environment. --- -*Last updated: 2026-09-06 | Verified against: feature/tpwalke2/198-dye-colors (535bb13)* +*Last updated: 2026-09-12 | Verified against: feature/tpwalke2/209-signtransitionresolver (4d45867)* diff --git a/build.gradle b/build.gradle index 40a6525..82b78ca 100644 --- a/build.gradle +++ b/build.gradle @@ -1,7 +1,7 @@ plugins { id 'net.fabricmc.fabric-loom' version "${fabric_loom_version}" id 'maven-publish' - id "com.modrinth.minotaur" version "2.+" + id "com.modrinth.minotaur" version "2.9.0" } base { diff --git a/docs/adr/0002-shape-duplicates-line-pattern.md b/docs/adr/0002-shape-duplicates-line-pattern.md index fd72575..44e77d9 100644 --- a/docs/adr/0002-shape-duplicates-line-pattern.md +++ b/docs/adr/0002-shape-duplicates-line-pattern.md @@ -16,3 +16,10 @@ pattern again (`ExtrudeGroupResolver`, `SetExtrudeMarkerAction`/`RemoveExtrudeMa `ExtrudeMarkerIdentifier`, a 4-way switch in `SignTransitionResolver`) rather than extracting. The transition table's branch-per-type-pair shape held up fine at 4 types; the marginal-reuse-vs-readability tradeoff above still favored duplication. Revisit extraction if a fifth multi-point marker kind appears. + +**Update:** the `Set`/`Remove` `MarkerAction` subtypes (`SetLineMarkerAction`/`SetShapeMarkerAction`/ +`SetExtrudeMarkerAction` → `SetMultiPointMarkerAction`; `RemoveLineMarkerAction`/`RemoveShapeMarkerAction`/ +`RemoveExtrudeMarkerAction` → `RemoveMultiPointMarkerAction`) were later merged into one class each, kind-tagged via +`MultiPointMarkerIdentifier`. This doesn't reopen the decision above: those classes were plain data/validation +holders with no branch-per-type-pair logic, so merging them carried none of the readability risk this ADR weighed. +`SignTransitionResolver`'s transition table itself is still one arm per type, per this ADR. diff --git a/docs/adr/0003-shared-safe-call-utility-for-crash-safety.md b/docs/adr/0003-shared-safe-call-utility-for-crash-safety.md new file mode 100644 index 0000000..e2cddea --- /dev/null +++ b/docs/adr/0003-shared-safe-call-utility-for-crash-safety.md @@ -0,0 +1,7 @@ +# Shared safe-call utility for crash-safety at game-thread entry points + +Several game-thread entry points (mod lifecycle hooks, both mixins, `SignManager`'s static entry points) call into +mod logic with no exception handling, violating the "mod must never crash the server" invariant. We considered +wrapping each entry point individually with a bespoke try/catch tailored to its own concerns, but chose one shared +safe-call utility (catch `Throwable`, log with context, swallow) used at every entry point instead — one pattern to +get right and audit, rather than ~6-8 independent try/catch blocks that can drift or be missed on a future addition. diff --git a/docs/adr/0004-atomic-write-content-verify-persistence.md b/docs/adr/0004-atomic-write-content-verify-persistence.md new file mode 100644 index 0000000..0869a30 --- /dev/null +++ b/docs/adr/0004-atomic-write-content-verify-persistence.md @@ -0,0 +1,11 @@ +# Atomic writes + content-verified migration for sign/config persistence + +Region-sharded sign files and the core config file were written directly to their final path, so a crash or +disk-full mid-write left a truncated file that's silently treated as "no data" on next load — and legacy-to-sharded +migration verified success by checking file *existence* only, so a truncated-but-present region file could still +pass verification and cause the legacy backup to finalize over genuinely lost data. We chose to make every write in +this path go through the existing temp-file + `ATOMIC_MOVE` pattern (`FileUtils.copyFile` already established this +elsewhere) and to make migration verification round-trip *parse* each written file rather than just check that it +exists. The cost is one extra parse pass per region file during migration; we accepted that cost because the +alternative — file-existence-only verification — is exactly the gap that let a real data-loss bug through crash +testing. diff --git a/docs/adr/0005-redos-mitigation-length-cap-only.md b/docs/adr/0005-redos-mitigation-length-cap-only.md new file mode 100644 index 0000000..74bc310 --- /dev/null +++ b/docs/adr/0005-redos-mitigation-length-cap-only.md @@ -0,0 +1,11 @@ +# ReDoS mitigation: sign-line length cap, no match timeout + +`REGEX` marker-group matching runs admin-configured regexes against player-controlled sign text synchronously on the +server thread, with no protection against catastrophic backtracking. We considered adding a time-bounded match (a +timeout via a separate thread/executor) so even a malicious regex+input pair couldn't hang the tick thread +indefinitely, but chose to enforce Minecraft's existing sign-line length limit server-side instead and reject/ +truncate oversized text before it reaches regex matching. Catastrophic backtracking needs a sufficiently long +adversarial input to blow up; capping input length closes the practical attack surface without adding threading +machinery for a risk that's largely bounded by admin-configured (trusted) regex patterns rather than fully +adversarial ones. If a future finding shows short-input regexes can still blow up meaningfully, revisit the timeout +approach. diff --git a/gradle.properties b/gradle.properties index 4ae97ed..1aa622e 100644 --- a/gradle.properties +++ b/gradle.properties @@ -11,7 +11,7 @@ loader_version=0.19.3 # Mod Properties mod_id=bluemapsignmarkers mod_name=BlueMap Sign Markers -mod_version=26.2-0.23.0 +mod_version=26.2-1.0.0 mod_description=A plugin for BlueMap that creates markers from signs maven_group=com.tpwalke2.bluemapsignmarkers archives_base_name=bluemapsignmarkers diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/BlueMapSignMarkersMod.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/BlueMapSignMarkersMod.java index 1c2261c..505d6d9 100644 --- a/src/main/java/com/tpwalke2/bluemapsignmarkers/BlueMapSignMarkersMod.java +++ b/src/main/java/com/tpwalke2/bluemapsignmarkers/BlueMapSignMarkersMod.java @@ -1,6 +1,8 @@ package com.tpwalke2.bluemapsignmarkers; -import com.tpwalke2.bluemapsignmarkers.core.WorldMap; +import com.tpwalke2.bluemapsignmarkers.common.SafeCall; +import com.tpwalke2.bluemapsignmarkers.common.ServerPathResolver; +import com.tpwalke2.bluemapsignmarkers.core.signs.PlayerIds; import com.tpwalke2.bluemapsignmarkers.core.signs.SignHelper; import com.tpwalke2.bluemapsignmarkers.core.signs.SignManager; import com.tpwalke2.bluemapsignmarkers.core.signs.persistence.SignProvider; @@ -33,39 +35,30 @@ public void onInitializeServer() { } private void onServerStarting(MinecraftServer server) { - SignProvider.loadSigns(getMarkerStorageRoot(server), getLegacyMarkerFilePath(server)); + SafeCall.run("onServerStarting", + () -> SignProvider.loadSigns(getMarkerStorageRoot(server), getLegacyMarkerFilePath(server))); } private void onServerStopping(MinecraftServer server) { - SignProvider.saveSigns(getMarkerStorageRoot(server)); + SafeCall.run("onServerStopping.saveSigns", () -> SignProvider.saveSigns(getMarkerStorageRoot(server))); - SignManager.stop(); + SafeCall.run("onServerStopping.stop", SignManager::stop); } @Override public Path getMarkerStorageRoot(MinecraftServer server) { - // normalize() is required: LevelResource.ROOT's relative path is ".", so without it levelDir keeps an - // unresolved trailing "." segment, shifting getParent()/getFileName() by one level (serverRoot would - // resolve to the level dir itself, and levelName to "." instead of the level name). - var levelDir = server.getWorldPath(LevelResource.ROOT).toAbsolutePath().normalize(); - var serverRoot = levelDir.getParent(); - var levelName = levelDir.getFileName(); - - return serverRoot.resolve(Constants.MOD_ID).resolve(levelName); + return ServerPathResolver.resolveMarkerStorageRoot(server.getWorldPath(LevelResource.ROOT).toAbsolutePath()); } - // Pre-existing (buggy) formula kept as-is: it resolves to the run directory's name, not the level name, - // which is exactly what's on disk for every install predating region-sharded storage. Migration needs to - // find files at the path they were actually written to, not the corrected one getMarkerStorageRoot uses. private String getLegacyMarkerFilePath(MinecraftServer server) { - var worldSaveName = server.getWorldPath(LevelResource.ROOT).toAbsolutePath().getParent().getFileName(); - return String.format("config/%s/%s/signs.json", Constants.MOD_ID, worldSaveName); + return ServerPathResolver.resolveLegacyMarkerFilePath(server.getWorldPath(LevelResource.ROOT).toAbsolutePath()); } private void onBlockEntityLoad(BlockEntity blockEntity, ServerLevel world) { if (!(blockEntity instanceof SignBlockEntity castBlockEntity)) return; - SignManager.addOrUpdate(SignHelper.createSignEntry(castBlockEntity, WorldMap.UNKNOWN)); + SafeCall.run("onBlockEntityLoad", + () -> SignManager.addOrUpdate(SignHelper.createSignEntry(castBlockEntity, PlayerIds.UNKNOWN))); } // No special case for a newly-generated chunk (generated == true): that flag also fires when a chunk's saved @@ -73,15 +66,17 @@ private void onBlockEntityLoad(BlockEntity blockEntity, ServerLevel world) { // reconciliation targets. Skipping it there would defeat the main use case, and there's no perf reason to: // getKeysInChunk is a single hashmap lookup, so the cost is the same either way. private void onChunkLoad(ServerLevel level, LevelChunk chunk, boolean generated) { - var parentMap = SignHelper.getSignParentMap(level); - var chunkPos = chunk.getPos(); + SafeCall.run("onChunkLoad", () -> { + var parentMap = SignHelper.getSignParentMap(level); + var chunkPos = chunk.getPos(); - for (var key : SignManager.getKeysInChunk(parentMap, chunkPos.x(), chunkPos.z())) { - if (!(chunk.getBlockEntity(new BlockPos(key.x(), key.y(), key.z())) instanceof SignBlockEntity)) { - LOGGER.info("Removing stale sign marker at {} - no sign block found on chunk load " - + "(external deletion/regen?)", key); - SignManager.remove(key); + for (var key : SignManager.getKeysInChunk(parentMap, chunkPos.x(), chunkPos.z())) { + if (!(chunk.getBlockEntity(new BlockPos(key.x(), key.y(), key.z())) instanceof SignBlockEntity)) { + LOGGER.info("Removing stale sign marker at {} - no sign block found on chunk load " + + "(external deletion/regen?)", key); + SignManager.remove(key); + } } - } + }); } } diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/common/ColorUtils.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/common/ColorUtils.java index 28e5c7a..ebc5682 100644 --- a/src/main/java/com/tpwalke2/bluemapsignmarkers/common/ColorUtils.java +++ b/src/main/java/com/tpwalke2/bluemapsignmarkers/common/ColorUtils.java @@ -13,6 +13,7 @@ public static int[] parseHex(String hex) { var stripped = hex.startsWith("#") ? hex.substring(1) : hex; if (stripped.length() != 6 && stripped.length() != 8) return defaultColor(); + if (!isHexChars(stripped)) return defaultColor(); try { var r = Integer.parseInt(stripped.substring(0, 2), 16); @@ -42,14 +43,16 @@ public static boolean isValidHex(String hex) { if (stripped.length() != 6 && stripped.length() != 8) return false; - try { - Integer.parseInt(stripped.substring(0, 2), 16); - Integer.parseInt(stripped.substring(2, 4), 16); - Integer.parseInt(stripped.substring(4, 6), 16); - if (stripped.length() == 8) Integer.parseInt(stripped.substring(6, 8), 16); - return true; - } catch (NumberFormatException e) { - return false; + return isHexChars(stripped); + } + + // Integer.parseInt(s, 16) also accepts a leading '-'/'+' sign (e.g. "-1" parses to -1 under radix 16), + // so a 2-char component like "-1" passes parseInt without a NumberFormatException even though it isn't + // a valid hex byte. Checking every character is an actual hex digit first closes that gap. + private static boolean isHexChars(String stripped) { + for (var i = 0; i < stripped.length(); i++) { + if (Character.digit(stripped.charAt(i), 16) == -1) return false; } + return true; } } diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/common/FileUtils.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/common/FileUtils.java index ab3b924..17800fd 100644 --- a/src/main/java/com/tpwalke2/bluemapsignmarkers/common/FileUtils.java +++ b/src/main/java/com/tpwalke2/bluemapsignmarkers/common/FileUtils.java @@ -10,6 +10,7 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; +import java.util.UUID; public class FileUtils { private static final Logger LOGGER = LoggerFactory.getLogger(Constants.MOD_ID); @@ -38,20 +39,34 @@ public static void moveToBackup(String originalPath, String suffix, String fileD var originalFile = new File(originalPath); if (!originalFile.exists()) return; - var backupPath = originalPath + suffix; - var backupFile = new File(backupPath); - if (backupFile.exists()) return; + var backupPath = uniqueBackupPath(originalPath, suffix); LOGGER.info("Backing up {}...", fileDescription); moveFile(originalPath, backupPath); } + // Never leaves the original sitting at originalPath just because an earlier backup already occupies the + // default backup path - a caller relying on "the original is gone once backed up" (e.g. LegacySignFileMigrator, + // which re-runs a full migration on every boot for as long as the legacy file still exists) would otherwise + // re-trigger forever, silently overwriting newer state with whatever that stale legacy file still holds. + private static String uniqueBackupPath(String originalPath, String suffix) { + var candidate = originalPath + suffix; + var attempt = 2; + while (new File(candidate).exists()) { + candidate = originalPath + suffix + "." + attempt; + attempt++; + } + return candidate; + } + // Copies via a temp file in the same directory, then an atomic move into place, so a failure partway through // (e.g. disk full mid-copy) never leaves a truncated/corrupt file sitting at destinationPath - one that a // later createBackup() call would otherwise mistake for a valid completed backup. private static boolean copyFile(String sourcePath, String destinationPath) { var destination = Paths.get(destinationPath); - var tempFile = destination.resolveSibling(destination.getFileName() + ".tmp"); + // UUID suffix: currently unreachable given single-threaded call sites, purely defensive against a + // future concurrent caller writing the same destinationPath colliding on this temp file's name. + var tempFile = destination.resolveSibling(destination.getFileName() + "." + UUID.randomUUID() + ".tmp"); try { Files.copy(Paths.get(sourcePath), tempFile, StandardCopyOption.REPLACE_EXISTING); Files.move(tempFile, destination, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); @@ -63,7 +78,9 @@ private static boolean copyFile(String sourcePath, String destinationPath) { } } - private static void deleteQuietly(Path path) { + // Public so other writers doing their own temp-file + ATOMIC_MOVE (RegionShardedSignEntryWriter, + // ConfigProvider) can clean up a leftover temp file the same way copyFile does here. + public static void deleteQuietly(Path path) { try { Files.deleteIfExists(path); } catch (IOException e) { diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/common/HtmlUtils.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/common/HtmlUtils.java index 293578a..ddc6c8e 100644 --- a/src/main/java/com/tpwalke2/bluemapsignmarkers/common/HtmlUtils.java +++ b/src/main/java/com/tpwalke2/bluemapsignmarkers/common/HtmlUtils.java @@ -5,6 +5,9 @@ public class HtmlUtils { private HtmlUtils() {} public static String escape(String text) { + if (text == null) { + return ""; + } return text .replace("&", "&") .replace("<", "<") diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/common/SafeCall.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/common/SafeCall.java new file mode 100644 index 0000000..c99d679 --- /dev/null +++ b/src/main/java/com/tpwalke2/bluemapsignmarkers/common/SafeCall.java @@ -0,0 +1,25 @@ +package com.tpwalke2.bluemapsignmarkers.common; + +import com.tpwalke2.bluemapsignmarkers.Constants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +// Shared safe-call wrapper for every game-thread entry point into mod logic (mod lifecycle hooks, both +// mixins, SignManager's static entry points) - one place to catch Throwable, log with context, and +// swallow, so an uncaught exception can never propagate into live Minecraft server code and crash the +// server. See docs/adr/0003-shared-safe-call-utility-for-crash-safety.md. +public class SafeCall { + + private static final Logger LOGGER = LoggerFactory.getLogger(Constants.MOD_ID); + + private SafeCall() { + } + + public static void run(String context, Runnable action) { + try { + action.run(); + } catch (Throwable t) { + LOGGER.error("Unhandled exception in {}; continuing without crashing the server.", context, t); + } + } +} diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/common/ServerPathResolver.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/common/ServerPathResolver.java new file mode 100644 index 0000000..a756c74 --- /dev/null +++ b/src/main/java/com/tpwalke2/bluemapsignmarkers/common/ServerPathResolver.java @@ -0,0 +1,35 @@ +package com.tpwalke2.bluemapsignmarkers.common; + +import com.tpwalke2.bluemapsignmarkers.Constants; + +import java.nio.file.Path; + +// Pure Path/String math extracted from BlueMapSignMarkersMod so it's directly unit testable (that +// class's own signature is Minecraft-coupled - see AGENTS.md's testable-vs-game-coupled split). Both +// methods take the same raw, un-normalized Path a caller gets from +// server.getWorldPath(LevelResource.ROOT).toAbsolutePath() - normalizing (or not) is each method's own +// concern below, not the caller's. +public class ServerPathResolver { + private ServerPathResolver() {} + + public static Path resolveMarkerStorageRoot(Path rawLevelPath) { + // normalize() is required: LevelResource.ROOT's relative path is ".", so without it rawLevelPath + // keeps an unresolved trailing "." segment, shifting getParent()/getFileName() by one level + // (serverRoot would resolve to the level dir itself, and levelName to "." instead of the level + // name). + var levelDir = rawLevelPath.normalize(); + var serverRoot = levelDir.getParent(); + var levelName = levelDir.getFileName(); + + return serverRoot.resolve(Constants.MOD_ID).resolve(levelName); + } + + // Pre-existing (buggy) formula kept as-is: it resolves to the run directory's name, not the level + // name, which is exactly what's on disk for every install predating region-sharded storage. + // Migration needs to find files at the path they were actually written to, not the corrected one + // resolveMarkerStorageRoot uses above. + public static String resolveLegacyMarkerFilePath(Path rawLevelPath) { + var worldSaveName = rawLevelPath.getParent().getFileName(); + return String.format("config/%s/%s/signs.json", Constants.MOD_ID, worldSaveName); + } +} diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/config/ConfigManager.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/config/ConfigManager.java index 5336ec8..48c0a46 100644 --- a/src/main/java/com/tpwalke2/bluemapsignmarkers/config/ConfigManager.java +++ b/src/main/java/com/tpwalke2/bluemapsignmarkers/config/ConfigManager.java @@ -15,8 +15,27 @@ private ConfigManager() { } public static BMSMConfigV2 get() { + return getOrLoad(ConfigManager::reload); + } + + // Visible for testing: same first-load race protection as get(), but loading from a temp-directory path + // instead of the hardcoded config path, so merely referencing this class in a test never touches the real + // config//BMSM-Core.json on disk. + static BMSMConfigV2 get(Path configPath) { + return getOrLoad(() -> reload(configPath)); + } + + // Synchronizes the check-then-act of "is coreConfig loaded yet?" (double-checked locking on the same + // monitor reload() already uses) so racing first-time callers converge on a single load/parse pass and the + // same config instance, instead of each redundantly loading config and racing over which instance wins + // (finding #72, review: agent-context/reviews/full-codebase-review_2026-09-07_0900.md). + private static BMSMConfigV2 getOrLoad(Runnable loader) { if (coreConfig == null) { - reload(); + synchronized (ConfigManager.class) { + if (coreConfig == null) { + loader.run(); + } + } } return coreConfig; @@ -32,6 +51,12 @@ static synchronized void reload(Path configPath) { coreConfig = loadCoreConfig(ConfigProvider.loadConfig(configPath)); } + // Visible for testing: resets the static config to unloaded state so a test can exercise get()'s + // first-load path repeatedly instead of only once per JVM. + static synchronized void resetForTesting() { + coreConfig = null; + } + private static BMSMConfigV2 loadCoreConfig(BMSMConfigV2 result) { if (result == null) { LOGGER.warn("Failed to load core config, using defaults"); diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/config/ConfigProvider.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/config/ConfigProvider.java index 7c822ad..c4ce5c5 100644 --- a/src/main/java/com/tpwalke2/bluemapsignmarkers/config/ConfigProvider.java +++ b/src/main/java/com/tpwalke2/bluemapsignmarkers/config/ConfigProvider.java @@ -2,6 +2,7 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.Strictness; import com.tpwalke2.bluemapsignmarkers.Constants; @@ -24,7 +25,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import java.util.Arrays; +import java.nio.file.StandardCopyOption; import java.util.HashSet; import java.util.List; import java.util.Objects; @@ -55,7 +56,7 @@ static void saveConfig(BMSMConfigV2 config, Path path) { var file = path.toFile(); var parent = file.getParentFile(); - if (!parent.exists()) { + if (parent != null && !parent.exists()) { try { Files.createDirectories(Paths.get(parent.getAbsolutePath())); } catch (IOException e) { @@ -64,10 +65,23 @@ static void saveConfig(BMSMConfigV2 config, Path path) { } } - try (var writer = new OutputStreamWriter(Files.newOutputStream(file.toPath()), StandardCharsets.UTF_8)) { + // Writes via a temp file in the same directory, then an atomic move into place (same pattern as + // FileUtils.copyFile / RegionShardedSignEntryWriter), so a crash or disk-full mid-write never + // leaves a truncated config file sitting at path. + var tempFile = path.resolveSibling(path.getFileName() + ".tmp"); + try (var writer = new OutputStreamWriter(Files.newOutputStream(tempFile), StandardCharsets.UTF_8)) { GSON.toJson(config, writer); } catch (Exception e) { LOGGER.error("Failed to save config", e); + FileUtils.deleteQuietly(tempFile); + return; + } + + try { + Files.move(tempFile, path, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + } catch (IOException e) { + LOGGER.error("Failed to move temp config file into place at {}", path, e); + FileUtils.deleteQuietly(tempFile); } } @@ -115,15 +129,20 @@ static BMSMConfigV2 loadConfig(Path configPath) { var result = GSON.fromJson(configContent, LoadingBMSMConfigV2.class); var loadingMarkerGroups = result.getMarkerGroups(); - var markerGroups = Arrays - .stream(loadingMarkerGroups) - .map(ConfigProvider::convertToLoadedMarkerGroup) - .toArray(MarkerGroup[]::new); + var markerGroups = new MarkerGroup[loadingMarkerGroups.length]; + for (var i = 0; i < loadingMarkerGroups.length; i++) { + var loadingGroup = loadingMarkerGroups[i]; + // Resolved once per group and threaded through both the conversion and the mismatch + // warnings below, rather than re-resolved at each of the several call sites that need the + // effective type - avoids logging a redundant warning per call site for one malformed value. + var type = resolveType(loadingGroup); + warnOnTypeFieldMismatches(loadingGroup, type); + markerGroups[i] = convertToLoadedMarkerGroup(loadingGroup, type); + } validateMarkerGroups(markerGroups); - warnOnTypeFieldMismatches(loadingMarkerGroups); - return new BMSMConfigV2(markerGroups); + return new BMSMConfigV2(markerGroups, resolveShutdownAwaitSeconds(result.getShutdownAwaitSeconds())); } catch (Exception e) { LOGGER.error("Failed to load config:", e); @@ -131,6 +150,34 @@ static BMSMConfigV2 loadConfig(Path configPath) { } } + // Mod-wide (not per-group) setting, so it's read straight off LoadingBMSMConfigV2 rather than through + // the per-group resolve*Field helpers. A malformed or non-positive value falls back to the default with + // a warning rather than failing GSON.fromJson for the whole config (same treatment as resolveLineWidth). + private static int resolveShutdownAwaitSeconds(JsonElement element) { + var defaultValue = BMSMConfigV2.DEFAULT_SHUTDOWN_AWAIT_SECONDS; + if (element == null || element.isJsonNull()) return defaultValue; + + int value; + try { + if (!element.isJsonPrimitive() || !element.getAsJsonPrimitive().isNumber()) { + throw new IllegalArgumentException("not a numeric JSON primitive"); + } + value = element.getAsBigDecimal().intValueExact(); + } catch (RuntimeException e) { + LOGGER.warn("Config has a malformed 'shutdownAwaitSeconds' ({}); falling back to default {}", + element, defaultValue); + return defaultValue; + } + + if (value <= 0) { + LOGGER.warn("Config has a non-positive 'shutdownAwaitSeconds' ({}); falling back to default {}", + value, defaultValue); + return defaultValue; + } + + return value; + } + private static void validateMarkerGroups(MarkerGroup[] markerGroups) { var seenPrefixes = new HashSet(); @@ -152,6 +199,17 @@ private static void validateMarkerGroups(MarkerGroup[] markerGroups) { } } + // Keyed on raw prefix text alone, not matchType + prefix: a STARTS_WITH "[a]" group and a + // REGEX "[a]" group match different sign text, but every runtime lookup that resolves a + // sign's representation back to its group (SignManager.buildPrefixGroupMap, + // SignEntryHelper.getPrefix/SignTransitionResolver.computeRepresentation) is keyed on raw + // prefix text alone - it has no way to recover which of two same-prefix groups a given sign + // matched. Allowing this pair to validate previously let a config load successfully while one + // of the two groups silently never matched any sign (see + // agent-context/reviews/copilotreview.2026-09-09.md); rejecting it here instead gives the + // admin an upfront error instead of the group quietly not working. Revisit only alongside + // threading (matchType, prefix) identity through SignLinesParseResult and every downstream + // lookup. if (!seenPrefixes.add(prefix)) { throw new IllegalArgumentException( "Marker group '" + markerGroup.name() + "' has a prefix duplicated across groups: " @@ -160,101 +218,204 @@ private static void validateMarkerGroups(MarkerGroup[] markerGroups) { } } - // Centralizes the "null type defaults to POI" rule so the three call sites that need the effective - // type (warnOnTypeFieldMismatches, resolveLineWidth, resolveLineColor) can't drift out of sync. - private static MarkerGroupType effectiveType(LoadingMarkerGroupV2 markerGroup) { - return markerGroup.type() == null ? MarkerGroupType.POI : markerGroup.type(); + // Resolves the 'type' field to its effective MarkerGroupType: missing/null defaults to POI, and a + // malformed value (not a string, or not one of the enum's names) degrades to POI with a warning rather + // than failing GSON.fromJson for the whole config. Called once per group (see the loadConfig loop) and + // threaded through as a parameter so a single malformed value only logs once. + private static MarkerGroupType resolveType(LoadingMarkerGroupV2 markerGroup) { + var element = markerGroup.type(); + if (element == null || element.isJsonNull()) return MarkerGroupType.POI; + + var parsed = parseEnum(element, MarkerGroupType.class); + if (parsed == null) { + LOGGER.warn("Marker group '{}' has a malformed 'type' ({}); falling back to default {}", + markerGroup.name(), element, MarkerGroupType.POI); + return MarkerGroupType.POI; + } + return parsed; } - private static void warnOnTypeFieldMismatches(LoadingMarkerGroupV2[] markerGroups) { - for (var markerGroup : markerGroups) { - var type = effectiveType(markerGroup); - var name = markerGroup.name(); + private static MarkerGroupMatchType resolveMatchType(LoadingMarkerGroupV2 markerGroup) { + var element = markerGroup.matchType(); + if (element == null || element.isJsonNull()) return MarkerGroupMatchType.STARTS_WITH; - if (type == MarkerGroupType.POI) { - if (markerGroup.lineWidth() != null) { - LOGGER.warn("Marker group '{}' is type POI but has 'lineWidth' set; this field is ignored for POI groups", name); - } - if (markerGroup.lineColor() != null) { - LOGGER.warn("Marker group '{}' is type POI but has 'lineColor' set; this field is ignored for POI groups", name); - } - if (markerGroup.fillColor() != null) { - LOGGER.warn("Marker group '{}' is type POI but has 'fillColor' set; this field is ignored for POI groups", name); - } - if (markerGroup.depthTest() != null) { - LOGGER.warn("Marker group '{}' is type POI but has 'depthTest' set; this field is ignored for POI groups", name); - } - if (markerGroup.allowPlayerColors() != null) { - LOGGER.warn("Marker group '{}' is type POI but has 'allowPlayerColors' set; this field is ignored for POI groups", name); - } - } else if (type == MarkerGroupType.LINE) { - if (markerGroup.icon() != null) { - LOGGER.warn("Marker group '{}' is type LINE but has 'icon' set; this field is ignored for LINE groups", name); - } - if (markerGroup.offsetX() != null) { - LOGGER.warn("Marker group '{}' is type LINE but has 'offsetX' set; this field is ignored for LINE groups", name); - } - if (markerGroup.offsetY() != null) { - LOGGER.warn("Marker group '{}' is type LINE but has 'offsetY' set; this field is ignored for LINE groups", name); - } - if (markerGroup.fillColor() != null) { - LOGGER.warn("Marker group '{}' is type LINE but has 'fillColor' set; this field is ignored for LINE groups", name); - } - if (markerGroup.cssClasses() != null && !markerGroup.cssClasses().isEmpty()) { - LOGGER.warn("Marker group '{}' is type LINE but has 'cssClasses' set; this field is ignored for LINE groups", name); - } - } else if (type == MarkerGroupType.SHAPE) { - if (markerGroup.icon() != null) { - LOGGER.warn("Marker group '{}' is type SHAPE but has 'icon' set; this field is ignored for SHAPE groups", name); - } - if (markerGroup.offsetX() != null) { - LOGGER.warn("Marker group '{}' is type SHAPE but has 'offsetX' set; this field is ignored for SHAPE groups", name); - } - if (markerGroup.offsetY() != null) { - LOGGER.warn("Marker group '{}' is type SHAPE but has 'offsetY' set; this field is ignored for SHAPE groups", name); - } - if (markerGroup.cssClasses() != null && !markerGroup.cssClasses().isEmpty()) { - LOGGER.warn("Marker group '{}' is type SHAPE but has 'cssClasses' set; this field is ignored for SHAPE groups", name); - } - } else if (type == MarkerGroupType.EXTRUDE) { - if (markerGroup.icon() != null) { - LOGGER.warn("Marker group '{}' is type EXTRUDE but has 'icon' set; this field is ignored for EXTRUDE groups", name); - } - if (markerGroup.offsetX() != null) { - LOGGER.warn("Marker group '{}' is type EXTRUDE but has 'offsetX' set; this field is ignored for EXTRUDE groups", name); - } - if (markerGroup.offsetY() != null) { - LOGGER.warn("Marker group '{}' is type EXTRUDE but has 'offsetY' set; this field is ignored for EXTRUDE groups", name); - } - if (markerGroup.cssClasses() != null && !markerGroup.cssClasses().isEmpty()) { - LOGGER.warn("Marker group '{}' is type EXTRUDE but has 'cssClasses' set; this field is ignored for EXTRUDE groups", name); - } + var parsed = parseEnum(element, MarkerGroupMatchType.class); + if (parsed == null) { + LOGGER.warn("Marker group '{}' has a malformed 'matchType' ({}); falling back to default {}", + markerGroup.name(), element, MarkerGroupMatchType.STARTS_WITH); + return MarkerGroupMatchType.STARTS_WITH; + } + return parsed; + } + + private static final String DEFAULT_NAME_PLACEHOLDER = "(unnamed)"; + + // name has no default-safe value like the other fields (it's not derivable from a Java default, only from + // the group's own prefix), so it's resolved here rather than via resolve*Field - a missing/blank name must + // degrade to a fallback with a warning instead of throwing MarkerGroup's requireNonNull and wiping the + // whole config back to defaults. + private static String resolveName(LoadingMarkerGroupV2 markerGroup) { + var name = markerGroup.name(); + if (name != null && !name.isBlank()) return name; + + var prefix = markerGroup.prefix(); + var hasPrefix = prefix != null && !prefix.isBlank(); + var fallback = hasPrefix ? prefix : DEFAULT_NAME_PLACEHOLDER; + + // Identify by prefix (like every sibling resolver's warning does via markerGroup.name() - name is + // unavailable here since it's the broken field), falling back to a distinct marker when the prefix is + // also missing/blank, so this warning doesn't read identically for every broken group in a config. + LOGGER.warn("Marker group '{}' has a missing or blank 'name'; falling back to '{}'", + hasPrefix ? prefix : "(no prefix)", fallback); + return fallback; + } + + private static > T parseEnum(JsonElement element, Class enumType) { + try { + if (!element.isJsonPrimitive() || !element.getAsJsonPrimitive().isString()) return null; + return Enum.valueOf(enumType, element.getAsString()); + } catch (IllegalArgumentException e) { + return null; + } + } + + private static int resolveIntField(LoadingMarkerGroupV2 markerGroup, JsonElement element, int defaultValue, + String fieldName) { + if (element == null || element.isJsonNull()) return defaultValue; + + try { + if (!element.isJsonPrimitive() || !element.getAsJsonPrimitive().isNumber()) { + throw new IllegalArgumentException("not a numeric JSON primitive"); + } + return element.getAsBigDecimal().intValueExact(); + } catch (RuntimeException e) { + LOGGER.warn("Marker group '{}' has a malformed '{}' ({}); falling back to default {}", + markerGroup.name(), fieldName, element, defaultValue); + return defaultValue; + } + } + + private static double resolveDoubleField(LoadingMarkerGroupV2 markerGroup, JsonElement element, + double defaultValue, String fieldName) { + if (element == null || element.isJsonNull()) return defaultValue; + + try { + if (!element.isJsonPrimitive() || !element.getAsJsonPrimitive().isNumber()) { + throw new IllegalArgumentException("not a numeric JSON primitive"); + } + return element.getAsDouble(); + } catch (RuntimeException e) { + LOGGER.warn("Marker group '{}' has a malformed '{}' ({}); falling back to default {}", + markerGroup.name(), fieldName, element, defaultValue); + return defaultValue; + } + } + + private static boolean resolveBooleanField( + LoadingMarkerGroupV2 markerGroup, + JsonElement element, + boolean defaultValue, + String fieldName) { + if (element == null || element.isJsonNull()) return defaultValue; + + try { + if (!element.isJsonPrimitive() || !element.getAsJsonPrimitive().isBoolean()) { + throw new IllegalArgumentException("not a boolean JSON primitive"); + } + return element.getAsBoolean(); + } catch (RuntimeException e) { + LOGGER.warn("Marker group '{}' has a malformed '{}' ({}); falling back to default {}", + markerGroup.name(), fieldName, element, defaultValue); + return defaultValue; + } + } + + private static void warnOnTypeFieldMismatches(LoadingMarkerGroupV2 markerGroup, MarkerGroupType type) { + var name = markerGroup.name(); + + if (type == MarkerGroupType.POI) { + if (markerGroup.lineWidth() != null) { + LOGGER.warn("Marker group '{}' is type POI but has 'lineWidth' set; this field is ignored for POI groups", name); + } + if (markerGroup.lineColor() != null) { + LOGGER.warn("Marker group '{}' is type POI but has 'lineColor' set; this field is ignored for POI groups", name); + } + if (markerGroup.fillColor() != null) { + LOGGER.warn("Marker group '{}' is type POI but has 'fillColor' set; this field is ignored for POI groups", name); + } + if (markerGroup.depthTest() != null) { + LOGGER.warn("Marker group '{}' is type POI but has 'depthTest' set; this field is ignored for POI groups", name); + } + if (markerGroup.allowPlayerColors() != null) { + LOGGER.warn("Marker group '{}' is type POI but has 'allowPlayerColors' set; this field is ignored for POI groups", name); + } + } else if (type == MarkerGroupType.LINE) { + if (markerGroup.icon() != null) { + LOGGER.warn("Marker group '{}' is type LINE but has 'icon' set; this field is ignored for LINE groups", name); + } + if (markerGroup.offsetX() != null) { + LOGGER.warn("Marker group '{}' is type LINE but has 'offsetX' set; this field is ignored for LINE groups", name); + } + if (markerGroup.offsetY() != null) { + LOGGER.warn("Marker group '{}' is type LINE but has 'offsetY' set; this field is ignored for LINE groups", name); + } + if (markerGroup.fillColor() != null) { + LOGGER.warn("Marker group '{}' is type LINE but has 'fillColor' set; this field is ignored for LINE groups", name); + } + if (markerGroup.cssClasses() != null && !markerGroup.cssClasses().isEmpty()) { + LOGGER.warn("Marker group '{}' is type LINE but has 'cssClasses' set; this field is ignored for LINE groups", name); + } + } else if (type == MarkerGroupType.SHAPE) { + if (markerGroup.icon() != null) { + LOGGER.warn("Marker group '{}' is type SHAPE but has 'icon' set; this field is ignored for SHAPE groups", name); + } + if (markerGroup.offsetX() != null) { + LOGGER.warn("Marker group '{}' is type SHAPE but has 'offsetX' set; this field is ignored for SHAPE groups", name); + } + if (markerGroup.offsetY() != null) { + LOGGER.warn("Marker group '{}' is type SHAPE but has 'offsetY' set; this field is ignored for SHAPE groups", name); + } + if (markerGroup.cssClasses() != null && !markerGroup.cssClasses().isEmpty()) { + LOGGER.warn("Marker group '{}' is type SHAPE but has 'cssClasses' set; this field is ignored for SHAPE groups", name); + } + } else if (type == MarkerGroupType.EXTRUDE) { + if (markerGroup.icon() != null) { + LOGGER.warn("Marker group '{}' is type EXTRUDE but has 'icon' set; this field is ignored for EXTRUDE groups", name); + } + if (markerGroup.offsetX() != null) { + LOGGER.warn("Marker group '{}' is type EXTRUDE but has 'offsetX' set; this field is ignored for EXTRUDE groups", name); + } + if (markerGroup.offsetY() != null) { + LOGGER.warn("Marker group '{}' is type EXTRUDE but has 'offsetY' set; this field is ignored for EXTRUDE groups", name); + } + if (markerGroup.cssClasses() != null && !markerGroup.cssClasses().isEmpty()) { + LOGGER.warn("Marker group '{}' is type EXTRUDE but has 'cssClasses' set; this field is ignored for EXTRUDE groups", name); } } } private static final int DEFAULT_LINE_WIDTH = 2; - private static MarkerGroup convertToLoadedMarkerGroup(LoadingMarkerGroupV2 markerGroup) { + private static MarkerGroup convertToLoadedMarkerGroup(LoadingMarkerGroupV2 markerGroup, MarkerGroupType type) { return new MarkerGroup( markerGroup.prefix(), - markerGroup.matchType() == null ? MarkerGroupMatchType.STARTS_WITH : markerGroup.matchType(), - effectiveType(markerGroup), - markerGroup.name(), + resolveMatchType(markerGroup), + type, + resolveName(markerGroup), markerGroup.icon(), - markerGroup.offsetX() == null ? 0 : markerGroup.offsetX(), - markerGroup.offsetY() == null ? 0 : markerGroup.offsetY(), - markerGroup.defaultHidden() != null && markerGroup.defaultHidden(), - markerGroup.minDistance() == null ? 0.0 : markerGroup.minDistance(), - markerGroup.maxDistance() == null ? 10000000.0 : markerGroup.maxDistance(), - resolveLineWidth(markerGroup), - resolveLineColor(markerGroup), - resolveFillColor(markerGroup), + resolveIntField(markerGroup, markerGroup.offsetX(), 0, "offsetX"), + resolveIntField(markerGroup, markerGroup.offsetY(), 0, "offsetY"), + resolveBooleanField(markerGroup, markerGroup.defaultHidden(), false, "defaultHidden"), + resolveDoubleField(markerGroup, markerGroup.minDistance(), 0.0, "minDistance"), + resolveDoubleField(markerGroup, markerGroup.maxDistance(), 10000000.0, "maxDistance"), + resolveLineWidth(markerGroup, type), + resolveLineColor(markerGroup, type), + resolveFillColor(markerGroup, type), resolveSorting(markerGroup), resolveToggleable(markerGroup), - resolveDepthTest(markerGroup), - resolveCssClasses(markerGroup), - resolveAllowPlayerColors(markerGroup) + resolveDepthTest(markerGroup, type), + resolveCssClasses(markerGroup, type), + resolveAllowPlayerColors(markerGroup, type) ); } @@ -286,11 +447,10 @@ private static boolean resolveToggleable(LoadingMarkerGroupV2 markerGroup) { // depthTest is LINE/SHAPE/EXTRUDE-only (POI markers are always billboarded on top); unset or set on a // POI group both resolve to the BlueMap default of true - warnOnTypeFieldMismatches already warns on // the POI case. - private static boolean resolveDepthTest(LoadingMarkerGroupV2 markerGroup) { + private static boolean resolveDepthTest(LoadingMarkerGroupV2 markerGroup, MarkerGroupType type) { var depthTest = markerGroup.depthTest(); if (depthTest == null) return true; - var type = effectiveType(markerGroup); if (type != MarkerGroupType.LINE && type != MarkerGroupType.SHAPE && type != MarkerGroupType.EXTRUDE) return true; return depthTest; @@ -298,11 +458,10 @@ private static boolean resolveDepthTest(LoadingMarkerGroupV2 markerGroup) { // allowPlayerColors is LINE/SHAPE/EXTRUDE-only; unset or set on a POI group both resolve to false - // warnOnTypeFieldMismatches already warns on the POI case. - private static boolean resolveAllowPlayerColors(LoadingMarkerGroupV2 markerGroup) { + private static boolean resolveAllowPlayerColors(LoadingMarkerGroupV2 markerGroup, MarkerGroupType type) { var allowPlayerColors = markerGroup.allowPlayerColors(); if (allowPlayerColors == null) return false; - var type = effectiveType(markerGroup); if (type != MarkerGroupType.LINE && type != MarkerGroupType.SHAPE && type != MarkerGroupType.EXTRUDE) return false; return allowPlayerColors; @@ -310,11 +469,11 @@ private static boolean resolveAllowPlayerColors(LoadingMarkerGroupV2 markerGroup // cssClasses is POI-only; unset or set on a LINE/SHAPE group both resolve to an empty list - // warnOnTypeFieldMismatches already warns on the LINE/SHAPE case. - private static List resolveCssClasses(LoadingMarkerGroupV2 markerGroup) { + private static List resolveCssClasses(LoadingMarkerGroupV2 markerGroup, MarkerGroupType type) { var cssClasses = markerGroup.cssClasses(); if (cssClasses == null) return List.of(); - if (effectiveType(markerGroup) != MarkerGroupType.POI) return List.of(); + if (type != MarkerGroupType.POI) return List.of(); var filtered = cssClasses.stream().filter(Objects::nonNull).toList(); if (filtered.size() != cssClasses.size()) { @@ -323,17 +482,18 @@ private static List resolveCssClasses(LoadingMarkerGroupV2 markerGroup) return filtered; } - // Falls back to the default width on a non-positive value rather than throwing - a bad config value - // must not crash the server (same treatment as ColorUtils.parseHex's fallback on a malformed color). - // Only validated for LINE/SHAPE/EXTRUDE groups - lineWidth is ignored for POI groups + // Falls back to the default width on a malformed or non-positive value rather than throwing - a bad + // config value must not crash the server (same treatment as ColorUtils.parseHex's fallback on a + // malformed color). Only validated for LINE/SHAPE/EXTRUDE groups - lineWidth is ignored for POI groups // (warnOnTypeFieldMismatches already warns about it being set), so validating it here too would just be // a second, confusing warning. - private static int resolveLineWidth(LoadingMarkerGroupV2 markerGroup) { - var lineWidth = markerGroup.lineWidth(); - if (lineWidth == null) return DEFAULT_LINE_WIDTH; - - var type = effectiveType(markerGroup); - if (type != MarkerGroupType.LINE && type != MarkerGroupType.SHAPE && type != MarkerGroupType.EXTRUDE) return lineWidth; + private static int resolveLineWidth(LoadingMarkerGroupV2 markerGroup, MarkerGroupType type) { + var lineWidth = resolveIntField(markerGroup, markerGroup.lineWidth(), DEFAULT_LINE_WIDTH, "lineWidth"); + if (type != MarkerGroupType.LINE && type != MarkerGroupType.SHAPE && type != MarkerGroupType.EXTRUDE) { + // Not validated for POI groups, so a malformed value is left as the fallback default above, + // and a non-positive-but-parseable value passes through unchanged. + return lineWidth; + } if (lineWidth <= 0) { LOGGER.warn("Marker group '{}' has a non-positive 'lineWidth' ({}); falling back to default {}", @@ -349,11 +509,10 @@ private static int resolveLineWidth(LoadingMarkerGroupV2 markerGroup) { // Only validated for LINE/SHAPE/EXTRUDE groups - see resolveLineWidth above. private static final String DEFAULT_LINE_COLOR = "#FF0000FF"; - private static String resolveLineColor(LoadingMarkerGroupV2 markerGroup) { + private static String resolveLineColor(LoadingMarkerGroupV2 markerGroup, MarkerGroupType type) { var lineColor = markerGroup.lineColor(); if (lineColor == null) return DEFAULT_LINE_COLOR; - var type = effectiveType(markerGroup); if (type != MarkerGroupType.LINE && type != MarkerGroupType.SHAPE && type != MarkerGroupType.EXTRUDE) return lineColor; if (!ColorUtils.isValidHex(lineColor)) { @@ -370,11 +529,10 @@ private static String resolveLineColor(LoadingMarkerGroupV2 markerGroup) { // for SHAPE/EXTRUDE groups - see resolveLineWidth above. private static final String DEFAULT_FILL_COLOR = "#FF000033"; - private static String resolveFillColor(LoadingMarkerGroupV2 markerGroup) { + private static String resolveFillColor(LoadingMarkerGroupV2 markerGroup, MarkerGroupType type) { var fillColor = markerGroup.fillColor(); if (fillColor == null) return DEFAULT_FILL_COLOR; - var type = effectiveType(markerGroup); if (type != MarkerGroupType.SHAPE && type != MarkerGroupType.EXTRUDE) return fillColor; if (!ColorUtils.isValidHex(fillColor)) { @@ -395,25 +553,37 @@ private static BMSMConfigV2 loadV1Config(File file, BMSMConfigV1 v1Config) { + "avoid overwriting the original with no recoverable backup"); } - return new BMSMConfigV2( - new MarkerGroup( - v1Config.getPoiPrefix(), - MarkerGroupMatchType.STARTS_WITH, - MarkerGroupType.POI, - "Points of Interest", - null, - 0, - 0, - false, - 0, - 10000000.0, - 2, - "#FF0000FF", - "#FF000033", - 0, - true, - true, - List.of(), - false)); + var migratedGroup = new MarkerGroup( + v1Config.getPoiPrefix(), + MarkerGroupMatchType.STARTS_WITH, + MarkerGroupType.POI, + "Points of Interest", + null, + 0, + 0, + false, + 0, + 10000000.0, + 2, + DEFAULT_LINE_COLOR, + DEFAULT_FILL_COLOR, + 0, + true, + true, + List.of(), + false); + + // Runs the migrated group through the same validation a normally-loaded v2 config's groups get + // (e.g. rejecting a blank v1 poiPrefix, which would otherwise silently match every sign's text via + // STARTS_WITH ""), falling back to defaults rather than persisting an invalid migrated config. The + // v1 file has already been backed up above regardless of the outcome here. + try { + validateMarkerGroups(new MarkerGroup[]{migratedGroup}); + } catch (IllegalArgumentException e) { + LOGGER.error("Migrated v1 config produced an invalid marker group; falling back to defaults", e); + return new BMSMConfigV2(); + } + + return new BMSMConfigV2(migratedGroup); } } diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/config/models/BMSMConfigV2.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/config/models/BMSMConfigV2.java index 1d69e5e..ae80143 100644 --- a/src/main/java/com/tpwalke2/bluemapsignmarkers/config/models/BMSMConfigV2.java +++ b/src/main/java/com/tpwalke2/bluemapsignmarkers/config/models/BMSMConfigV2.java @@ -3,19 +3,35 @@ import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerGroup; public final class BMSMConfigV2 { + public static final int DEFAULT_SHUTDOWN_AWAIT_SECONDS = 5; + public BMSMConfigV2() {} public BMSMConfigV2(MarkerGroup[] markerGroups) { - this.markerGroups = markerGroups; + this.markerGroups = markerGroups.clone(); } public BMSMConfigV2(MarkerGroup markerGroup) { this.markerGroups = new MarkerGroup[]{markerGroup}; } + public BMSMConfigV2(MarkerGroup[] markerGroups, int shutdownAwaitSeconds) { + this.markerGroups = markerGroups.clone(); + this.shutdownAwaitSeconds = shutdownAwaitSeconds; + } + private MarkerGroup[] markerGroups = new MarkerGroup[]{MarkerGroup.DEFAULT_POI_GROUP}; + // How long ReactiveQueue.shutdown() (used for the BlueMap marker-action queue) waits for in-flight + // tasks to finish before forcing a shutdownNow(); see AGENTS.md / ReactiveQueue for why this matters. + private int shutdownAwaitSeconds = DEFAULT_SHUTDOWN_AWAIT_SECONDS; + // Clones both at construction (so a caller mutating the array it passed in can't reach into this + // singleton) and here (so a caller mutating the returned array can't either). public MarkerGroup[] getMarkerGroups() { - return markerGroups; + return markerGroups.clone(); + } + + public int getShutdownAwaitSeconds() { + return shutdownAwaitSeconds; } } diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/config/persistence/LoadingBMSMConfigV2.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/config/persistence/LoadingBMSMConfigV2.java index 203f3f1..38e81f1 100644 --- a/src/main/java/com/tpwalke2/bluemapsignmarkers/config/persistence/LoadingBMSMConfigV2.java +++ b/src/main/java/com/tpwalke2/bluemapsignmarkers/config/persistence/LoadingBMSMConfigV2.java @@ -1,6 +1,8 @@ package com.tpwalke2.bluemapsignmarkers.config.persistence; +import com.google.gson.JsonElement; import com.google.gson.JsonPrimitive; +import com.tpwalke2.bluemapsignmarkers.config.models.BMSMConfigV2; import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerGroup; public final class LoadingBMSMConfigV2 { @@ -16,21 +18,25 @@ public LoadingBMSMConfigV2(LoadingMarkerGroupV2 markerGroup) { } private LoadingMarkerGroupV2[] markerGroups = new LoadingMarkerGroupV2[]{defaultGroup()}; + // Read as a raw JsonElement (like sorting/lineWidth/etc. on LoadingMarkerGroupV2) so a malformed value + // (wrong type, non-positive) degrades to the default with a warning instead of failing GSON.fromJson + // for the whole config. + private JsonElement shutdownAwaitSeconds = new JsonPrimitive(BMSMConfigV2.DEFAULT_SHUTDOWN_AWAIT_SECONDS); private static LoadingMarkerGroupV2 defaultGroup() { var defaultGroup = MarkerGroup.DEFAULT_POI_GROUP; return new LoadingMarkerGroupV2( defaultGroup.prefix(), - defaultGroup.matchType(), - defaultGroup.type(), + new JsonPrimitive(defaultGroup.matchType().name()), + new JsonPrimitive(defaultGroup.type().name()), defaultGroup.name(), defaultGroup.icon(), - defaultGroup.offsetX(), - defaultGroup.offsetY(), - defaultGroup.defaultHidden(), - defaultGroup.minDistance(), - defaultGroup.maxDistance(), - defaultGroup.lineWidth(), + new JsonPrimitive(defaultGroup.offsetX()), + new JsonPrimitive(defaultGroup.offsetY()), + new JsonPrimitive(defaultGroup.defaultHidden()), + new JsonPrimitive(defaultGroup.minDistance()), + new JsonPrimitive(defaultGroup.maxDistance()), + new JsonPrimitive(defaultGroup.lineWidth()), defaultGroup.lineColor(), defaultGroup.fillColor(), new JsonPrimitive(defaultGroup.sorting()), @@ -43,4 +49,8 @@ private static LoadingMarkerGroupV2 defaultGroup() { public LoadingMarkerGroupV2[] getMarkerGroups() { return markerGroups; } + + public JsonElement getShutdownAwaitSeconds() { + return shutdownAwaitSeconds; + } } diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/config/persistence/LoadingMarkerGroupV2.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/config/persistence/LoadingMarkerGroupV2.java index 7be4959..a51b5ca 100644 --- a/src/main/java/com/tpwalke2/bluemapsignmarkers/config/persistence/LoadingMarkerGroupV2.java +++ b/src/main/java/com/tpwalke2/bluemapsignmarkers/config/persistence/LoadingMarkerGroupV2.java @@ -1,28 +1,28 @@ package com.tpwalke2.bluemapsignmarkers.config.persistence; import com.google.gson.JsonElement; -import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerGroupMatchType; -import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerGroupType; import java.util.List; +// Fields prone to a type mismatch in hand-edited JSON (matchType, type, offsetX/offsetY, defaultHidden, +// minDistance/maxDistance, lineWidth, sorting) are read as raw JsonElement rather than their real Java type, +// so a malformed value fails to resolve just that one field (ConfigProvider degrades it to a safe default +// with a warning) instead of throwing out of GSON.fromJson and wiping the entire config back to one default +// [poi] group. public record LoadingMarkerGroupV2( String prefix, - MarkerGroupMatchType matchType, - MarkerGroupType type, + JsonElement matchType, + JsonElement type, String name, String icon, - Integer offsetX, - Integer offsetY, - Boolean defaultHidden, - Double minDistance, - Double maxDistance, - Integer lineWidth, + JsonElement offsetX, + JsonElement offsetY, + JsonElement defaultHidden, + JsonElement minDistance, + JsonElement maxDistance, + JsonElement lineWidth, String lineColor, String fillColor, - // JsonElement (rather than Integer) so a non-integer JSON value doesn't fail the whole config's Gson - // parse - resolveSorting in ConfigProvider validates it manually and falls back to the default on a - // malformed value, the same "never crash on a bad field" treatment lineWidth/lineColor get downstream. JsonElement sorting, Boolean toggleable, Boolean depthTest, diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/BlueMapAPIConnector.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/BlueMapAPIConnector.java index eb4c29f..2a4f1b1 100644 --- a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/BlueMapAPIConnector.java +++ b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/BlueMapAPIConnector.java @@ -1,43 +1,26 @@ package com.tpwalke2.bluemapsignmarkers.core.bluemap; -import com.flowpowered.math.vector.Vector3d; import com.tpwalke2.bluemapsignmarkers.Constants; -import com.tpwalke2.bluemapsignmarkers.common.ColorUtils; -import com.tpwalke2.bluemapsignmarkers.common.HtmlUtils; import com.tpwalke2.bluemapsignmarkers.common.LogUtils; +import com.tpwalke2.bluemapsignmarkers.config.ConfigManager; import com.tpwalke2.bluemapsignmarkers.core.bounds.RenderMaskEvaluator; import com.tpwalke2.bluemapsignmarkers.core.bluemap.actions.AddMarkerAction; import com.tpwalke2.bluemapsignmarkers.core.bluemap.actions.GroupTransitionMarkerAction; import com.tpwalke2.bluemapsignmarkers.core.bluemap.actions.MarkerAction; -import com.tpwalke2.bluemapsignmarkers.core.bluemap.actions.RemoveExtrudeMarkerAction; -import com.tpwalke2.bluemapsignmarkers.core.bluemap.actions.RemoveLineMarkerAction; import com.tpwalke2.bluemapsignmarkers.core.bluemap.actions.RemoveMarkerAction; -import com.tpwalke2.bluemapsignmarkers.core.bluemap.actions.RemoveShapeMarkerAction; -import com.tpwalke2.bluemapsignmarkers.core.bluemap.actions.SetExtrudeMarkerAction; -import com.tpwalke2.bluemapsignmarkers.core.bluemap.actions.SetLineMarkerAction; -import com.tpwalke2.bluemapsignmarkers.core.bluemap.actions.SetShapeMarkerAction; +import com.tpwalke2.bluemapsignmarkers.core.bluemap.actions.RemoveMultiPointMarkerAction; +import com.tpwalke2.bluemapsignmarkers.core.bluemap.actions.SetMultiPointMarkerAction; import com.tpwalke2.bluemapsignmarkers.core.bluemap.actions.UpdateMarkerAction; import com.tpwalke2.bluemapsignmarkers.core.markers.DispatchedMarkerIdentifier; -import com.tpwalke2.bluemapsignmarkers.core.markers.ExtrudeMarkerIdentifier; -import com.tpwalke2.bluemapsignmarkers.core.markers.LineMarkerIdentifier; import com.tpwalke2.bluemapsignmarkers.core.markers.LinePoint; -import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerGroupType; import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerIdentifier; import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerSetIdentifier; -import com.tpwalke2.bluemapsignmarkers.core.markers.ShapeMarkerIdentifier; +import com.tpwalke2.bluemapsignmarkers.core.markers.MultiPointMarkerIdentifier; import com.tpwalke2.bluemapsignmarkers.core.reactive.ReactiveQueue; -import com.flowpowered.math.vector.Vector2d; import de.bluecolored.bluemap.api.BlueMapAPI; import de.bluecolored.bluemap.api.BlueMapMap; -import de.bluecolored.bluemap.api.markers.ExtrudeMarker; -import de.bluecolored.bluemap.api.markers.LineMarker; import de.bluecolored.bluemap.api.markers.Marker; import de.bluecolored.bluemap.api.markers.MarkerSet; -import de.bluecolored.bluemap.api.markers.POIMarker; -import de.bluecolored.bluemap.api.markers.ShapeMarker; -import de.bluecolored.bluemap.api.math.Color; -import de.bluecolored.bluemap.api.math.Line; -import de.bluecolored.bluemap.api.math.Shape; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -47,9 +30,9 @@ import java.util.function.Consumer; public class BlueMapAPIConnector { - public static final String MAP_NOT_FOUND = "Map not found: {}"; - public static final String WORLD_NOT_FOUND = "World not found: {}"; - public static final String WORLD_MAPS_EMPTY = "World maps empty: {}"; + private static final String MAP_NOT_FOUND = "Map not found: {}"; + private static final String WORLD_NOT_FOUND = "World not found: {}"; + private static final String WORLD_MAPS_EMPTY = "World maps empty: {}"; private static final Logger LOGGER = LoggerFactory.getLogger(Constants.MOD_ID); // Fixed on Fabric - BlueMap's own per-map config directory, read for each real map's render-mask // (see RenderMaskEvaluator). No BlueMap API accessor exposes this path or a bounds check directly. @@ -59,8 +42,8 @@ public class BlueMapAPIConnector { // that's what volatile guarantees. It says nothing about the referenced objects themselves, which are // freely mutated afterward through their own thread-safe methods (ReactiveQueue.enqueue()/process(), // ConcurrentHashMap.get()/putIfAbsent()). No reader — dispatch()/onDisable()/onEnable() for - // markerActionQueue, getMarkerSets() for markerSetsCache, getMaps() for blueMapAPI — needs a joint - // snapshot of more than one of these fields at once, so per-field visibility is enough; a shared lock + // markerActionQueue, getMarkerSets() for markerSetsCache — needs a joint snapshot of more than one + // of these fields at once, so per-field visibility is enough; a shared lock // would additionally serialize dispatch() (hot path, every sign event) behind processMarkerAction()'s // BlueMap API calls, an unrelated critical section (findings #11 and #12, // plans/codebase-review-2026-07-11.md). @@ -69,17 +52,12 @@ public class BlueMapAPIConnector { // Parsed render-mask per real BlueMapMap id, invalidated alongside markerSetsCache (config // reload, genuine BlueMap disable/enable) rather than re-read/re-parsed on every dispatch. private volatile Map renderMaskCache; - private volatile BlueMapAPI blueMapAPI; - // Tracks whether onDisable() has actually run since the last onEnable(), so onEnable() can tell a - // genuine BlueMap disable/re-enable cycle (a real reload, which must resetQueue()/fireReset() to - // re-diff signCache against the reloaded config) apart from the very first onEnable() a server ever - // sees. markerActionQueue.isShutdown() used to be used for this instead, but it also reports true for - // a brand-new queue whose executor was never lazily created - which is exactly what happens when - // SERVER_STARTING dispatches actions for every migrated/loaded sign before BlueMap is available: - // process() returns early (shouldRun() false) without ever creating an executor, so the first onEnable() - // saw isShutdown()==true and mistook startup for a reload, replacing markerActionQueue with an empty one - // and discarding every action enqueued during sign load before a single one was ever processed. - private volatile boolean disabledSinceLastEnable; + // Set by onDisable() from markerActionQueue.shutdown()'s return value; read by the next onEnable() to + // decide whether to warn that a non-interruptible straggler task may still race the reset replay below + // (findings 26/27, agent-context/reviews/full-codebase-review_2026-09-07_0900.md). There's no better + // recovery available - a task that ignores interruption can't be forced to stop - so this only makes + // the violation observable rather than blocking onEnable() indefinitely. + private volatile boolean lastShutdownConfirmedClean = true; private final List resetHandlers = new ArrayList<>(); // BlueMapAPI.unregisterListener(Consumer) removes by equals/hashCode, and a method reference has no // custom equals - two `this::onEnable` expressions are distinct objects under default identity equality. @@ -95,18 +73,24 @@ private record MappedMarkerSet(String mapId, MarkerSet markerSet) {} public BlueMapAPIConnector() { resetQueue(); - // BlueMap may already be enabled by the time this connector is constructed (e.g. mod reload); don't - // rely solely on the onEnable callback below to set blueMapAPI, or a dispatch() landing before that - // callback runs would see BlueMapAPI.getInstance().isPresent() true but this.blueMapAPI still null. - blueMapAPI = BlueMapAPI.getInstance().orElse(null); BlueMapAPI.onEnable(onEnableListener); BlueMapAPI.onDisable(onDisableListener); } + // Also retires markerActionQueue (awaiting up to its configured shutdownAwaitSeconds) rather than just + // unregistering the BlueMap listeners - previously this left the queue's fixed thread pool alive and + // any in-flight marker action unawaited on server stop, so BlueMapSignMarkersMod.onServerStopping's + // configured shutdown timeout had no effect at all. Mirrors onDisable()'s own shutdown() call, but + // this path runs on server stop regardless of whether BlueMap ever fired onDisable first. public void shutdown() { BlueMapAPI.unregisterListener(onEnableListener); BlueMapAPI.unregisterListener(onDisableListener); + + if (!markerActionQueue.shutdown()) { + LOGGER.warn("Marker action queue shutdown could not confirm all in-flight tasks stopped before " + + "server stop completed"); + } } public void dispatch(MarkerAction action) { @@ -134,7 +118,8 @@ private void resetQueue() { markerActionQueue = new ReactiveQueue<>( () -> BlueMapAPI.getInstance().isPresent(), this::processMarkerAction, - this::onError + this::onError, + ConfigManager.get().getShutdownAwaitSeconds() ); markerSetsCache = new ConcurrentHashMap<>(); @@ -145,7 +130,7 @@ private void resetQueue() { // (including render-mask gating decisions, which can do cold-cache disk I/O via getRenderMask) up // front, and the resulting Runnable is only then run inside a `synchronized (this)` block covering // the action's full mutation fan-out (across every one of its target maps). That keeps - // addMarker/updateMarker/removeMarker's mutation of a MarkerSet's marker Map from running + // MarkerMutations' add/update/remove effects mutating a MarkerSet's marker Map from running // concurrently with another dispatched action against the same (or a different) MarkerSet, and one // action's effect from ever being observably applied on some of its target maps but not others // (findings #5 and the bulk-load fanout item, plans/codebase-review-2026-07-11.md), while ensuring @@ -197,25 +182,17 @@ private void applySingleAction(MarkerAction markerAction) { private Runnable prepareSingleAction(MarkerAction markerAction) { return switch (markerAction) { case AddMarkerAction addAction -> - prepareGated(addAction.getMarkerIdentifier(), pointOf(addAction.getMarkerIdentifier()), markers -> addMarker(addAction, markers)); + prepareGated(addAction.getMarkerIdentifier(), pointOf(addAction.getMarkerIdentifier()), markers -> MarkerMutations.addMarker(addAction, markers)); case UpdateMarkerAction updateAction -> - prepareGated(updateAction.getMarkerIdentifier(), pointOf(updateAction.getMarkerIdentifier()), markers -> updateMarker(updateAction, markers)); - case SetLineMarkerAction setAction -> - prepareGated(setAction.getMarkerIdentifier(), setAction.getPoints(), markers -> setLineMarker(setAction, markers)); - case SetShapeMarkerAction setAction -> - prepareGated(setAction.getMarkerIdentifier(), setAction.getPoints(), markers -> setShapeMarker(setAction, markers)); - case SetExtrudeMarkerAction setAction -> - prepareGated(setAction.getMarkerIdentifier(), setAction.getPoints(), markers -> setExtrudeMarker(setAction, markers)); + prepareGated(updateAction.getMarkerIdentifier(), pointOf(updateAction.getMarkerIdentifier()), markers -> MarkerMutations.updateMarker(updateAction, markers)); + case SetMultiPointMarkerAction setAction -> + prepareGated(setAction.getMarkerIdentifier(), setAction.getPoints(), markers -> MarkerMutations.setMultiPointMarker(setAction, markers)); // Explicit removes - the sign's representation is genuinely leaving, independent of // render bounds - so these apply unconditionally on every real map, no gating needed. case RemoveMarkerAction removeAction -> - prepareUngated(removeAction.getMarkerIdentifier(), markers -> removeMarker(removeAction, markers)); - case RemoveLineMarkerAction removeAction -> - prepareUngated(removeAction.getMarkerIdentifier(), markers -> removeMarkerById(removeAction.getMarkerIdentifier().getId(), markers)); - case RemoveShapeMarkerAction removeAction -> - prepareUngated(removeAction.getMarkerIdentifier(), markers -> removeMarkerById(removeAction.getMarkerIdentifier().getId(), markers)); - case RemoveExtrudeMarkerAction removeAction -> - prepareUngated(removeAction.getMarkerIdentifier(), markers -> removeMarkerById(removeAction.getMarkerIdentifier().getId(), markers)); + prepareUngated(removeAction.getMarkerIdentifier(), markers -> MarkerMutations.removeMarker(removeAction, markers)); + case RemoveMultiPointMarkerAction removeAction -> + prepareUngated(removeAction.getMarkerIdentifier(), markers -> MarkerMutations.removeMarkerById(removeAction.getMarkerIdentifier().getId(), markers)); default -> { LOGGER.warn("Unknown marker action: {}", markerAction); yield () -> {}; @@ -223,7 +200,9 @@ private Runnable prepareSingleAction(MarkerAction markerAction) { }; } - private static List pointOf(MarkerIdentifier identifier) { + // Package-private (not private) specifically so it's directly testable - see the + // resolveExtrudeHeightRange comment below and BlueMapAPIConnectorTest. + static List pointOf(MarkerIdentifier identifier) { return List.of(new LinePoint(identifier.x(), identifier.y(), identifier.z())); } @@ -277,7 +256,13 @@ private Runnable prepareUngated(DispatchedMarkerIdentifier markerIdentifier, Con } private boolean isInsideRenderBounds(String mapId, List points) { - var mask = getRenderMask(mapId); + return isInsideRenderBounds(getRenderMask(mapId), points); + } + + // Pure point-vs-mask test split out of the mapId/cache-lookup overload above so it's directly + // testable without a live BlueMapAPIConnector instance (bluemap-api is compileOnly, not on the + // test classpath - see BlueMapAPIConnectorTest). + static boolean isInsideRenderBounds(RenderMaskEvaluator.RenderMask mask, List points) { return points.stream().anyMatch(p -> mask.contains(p.x(), p.y(), p.z())); } @@ -290,12 +275,8 @@ private void logProcessingMessage(MarkerAction action) { case AddMarkerAction ignored -> "Adding"; case RemoveMarkerAction ignored -> "Removing"; case UpdateMarkerAction ignored -> "Updating"; - case RemoveLineMarkerAction ignored -> "Removing"; - case SetLineMarkerAction setAction -> setAction.isFirstAppearance() ? "Adding" : "Updating"; - case RemoveShapeMarkerAction ignored -> "Removing"; - case SetShapeMarkerAction setAction -> setAction.isFirstAppearance() ? "Adding" : "Updating"; - case RemoveExtrudeMarkerAction ignored -> "Removing"; - case SetExtrudeMarkerAction setAction -> setAction.isFirstAppearance() ? "Adding" : "Updating"; + case RemoveMultiPointMarkerAction ignored -> "Removing"; + case SetMultiPointMarkerAction setAction -> setAction.isFirstAppearance() ? "Adding" : "Updating"; default -> "Processing"; }; @@ -310,18 +291,11 @@ private void logProcessingMessage(MarkerAction action) { var position = ""; if (identifier instanceof MarkerIdentifier markerIdentifier) { position = String.format(" at x=%d y=%d z=%d", markerIdentifier.x(), markerIdentifier.y(), markerIdentifier.z()); - } else if (identifier instanceof LineMarkerIdentifier && action instanceof SetLineMarkerAction setAction) { - position = String.format(" label='%s' with %d point(s)", LogUtils.sanitizeForLog(setAction.getLabel()), setAction.getPoints().size()); - } else if (identifier instanceof LineMarkerIdentifier lineMarkerIdentifier) { - position = String.format(" label='%s'", LogUtils.sanitizeForLog(lineMarkerIdentifier.label())); - } else if (identifier instanceof ShapeMarkerIdentifier && action instanceof SetShapeMarkerAction setAction) { - position = String.format(" label='%s' with %d point(s)", LogUtils.sanitizeForLog(setAction.getLabel()), setAction.getPoints().size()); - } else if (identifier instanceof ShapeMarkerIdentifier shapeMarkerIdentifier) { - position = String.format(" label='%s'", LogUtils.sanitizeForLog(shapeMarkerIdentifier.label())); - } else if (identifier instanceof ExtrudeMarkerIdentifier && action instanceof SetExtrudeMarkerAction setAction) { - position = String.format(" label='%s' with %d point(s)", LogUtils.sanitizeForLog(setAction.getLabel()), setAction.getPoints().size()); - } else if (identifier instanceof ExtrudeMarkerIdentifier extrudeMarkerIdentifier) { - position = String.format(" label='%s'", LogUtils.sanitizeForLog(extrudeMarkerIdentifier.label())); + } else if (identifier instanceof MultiPointMarkerIdentifier multiPointMarkerIdentifier) { + position = switch (action) { + case SetMultiPointMarkerAction setAction -> String.format(" label='%s' with %d point(s)", LogUtils.sanitizeForLog(setAction.getLabel()), setAction.getPoints().size()); + default -> String.format(" label='%s'", LogUtils.sanitizeForLog(multiPointMarkerIdentifier.label())); + }; } LOGGER.debug("{} {} type marker in {}{}{}", @@ -332,176 +306,71 @@ private void logProcessingMessage(MarkerAction action) { detail); } - private static void updateMarker(UpdateMarkerAction updateAction, Map markers) { - LOGGER.debug("Updating marker..."); - - var marker = Optional.ofNullable(markers.get(updateAction.getMarkerIdentifier().getId())); - if (marker.isEmpty()) return; - marker.get().setLabel(updateAction.getNewLabel()); - if (marker.get() instanceof POIMarker poiMarker) { - poiMarker.setDetail(HtmlUtils.toHtmlDetail(updateAction.getNewDetails())); - } - } - - private static void removeMarker(RemoveMarkerAction removeAction, Map markers) { - LOGGER.debug("Removing marker..."); - removeMarkerById(removeAction.getMarkerIdentifier().getId(), markers); - } - - private static void removeMarkerById(String id, Map markers) { - markers.remove(id); - } - - // ColorUtils.parseHex returns alpha in the same 0-255 range as r/g/b, but BlueMap's Color(int, int, int, - // float) constructor takes alpha in 0-1 - passing the raw 0-255 int straight through (as the earlier - // Color(int, int, int, int alpha-as-int) overload does, treating alpha/255f) is NOT what an int - // widening to float gives you: it silently widens to e.g. 51.0f instead of dividing by 255, which - // BlueMap then clamps to fully opaque. Every translucent color (e.g. SHAPE's fillColor default) rendered - // fully opaque as a result. - private static Color toBlueMapColor(int[] rgba) { - return new Color(rgba[0], rgba[1], rgba[2], rgba[3] / 255f); - } - - private static void setLineMarker(SetLineMarkerAction action, Map markers) { - LOGGER.debug("Setting line marker..."); - if (action.getPoints().size() < 2) return; // defensive - SignManager should never dispatch below 2 - - var line = new Line(action.getPoints().stream().map(p -> new Vector3d(p.x(), p.y(), p.z())).toList()); - var color = ColorUtils.parseHex(action.getLineColor()); - var markerGroup = action.getMarkerIdentifier().parentSet().markerGroup(); - - var marker = LineMarker.builder() - .label(action.getLabel()) - .detail(HtmlUtils.toHtmlDetail(action.getDetail())) - .line(line) - .lineWidth(action.getLineWidth()) - .lineColor(toBlueMapColor(color)) - .depthTestEnabled(markerGroup.depthTest()) - .build(); - marker.setMinDistance(markerGroup.minDistance()); - marker.setMaxDistance(markerGroup.maxDistance()); - markers.put(action.getMarkerIdentifier().getId(), marker); - } - - private static void setShapeMarker(SetShapeMarkerAction action, Map markers) { - LOGGER.debug("Setting shape marker..."); - if (action.getPoints().size() < 3) return; // defensive - SignManager should never dispatch below 3 - - var points = action.getPoints(); - var shape = new Shape(points.stream().map(p -> new Vector2d(p.x(), p.z())).toList()); - // Shape height anchors to the tallest member rather than placement order, so the polygon always - // clears the terrain/builds of every sign that defines it. - var shapeY = (float) points.stream().mapToInt(LinePoint::y).max().orElseThrow(); - var lineColor = ColorUtils.parseHex(action.getLineColor()); - var fillColor = ColorUtils.parseHex(action.getFillColor()); - var markerGroup = action.getMarkerIdentifier().parentSet().markerGroup(); - - var marker = ShapeMarker.builder() - .label(action.getLabel()) - .detail(HtmlUtils.toHtmlDetail(action.getDetail())) - .shape(shape, shapeY) - .lineWidth(action.getLineWidth()) - .lineColor(toBlueMapColor(lineColor)) - .fillColor(toBlueMapColor(fillColor)) - .depthTestEnabled(markerGroup.depthTest()) - .build(); - marker.setMinDistance(markerGroup.minDistance()); - marker.setMaxDistance(markerGroup.maxDistance()); - markers.put(action.getMarkerIdentifier().getId(), marker); - } - - // Floor/ceiling of an extrude volume - a plain value holder (no bluemap-api types), so - // resolveExtrudeHeightRange stays testable even though bluemap-api is compileOnly and not on the test - // classpath (see AGENTS.md's testable-vs-game-coupled split). - record ExtrudeHeightRange(float minY, float maxY) {} - - // Floor/ceiling anchor to the lowest/tallest member respectively, so the volume always spans the full - // height range its members were placed at, independent of placement order. All members at the same Y - // (e.g. one floor) would otherwise collapse the extrusion to zero height, rendering nothing on the map - // with no indication why - so give it a one-block floor instead. - static ExtrudeHeightRange resolveExtrudeHeightRange(String label, List points) { - var minY = (float) points.stream().mapToInt(LinePoint::y).min().orElseThrow(); - var maxY = (float) points.stream().mapToInt(LinePoint::y).max().orElseThrow(); - if (maxY <= minY) { - LOGGER.debug("Extrude marker label='{}' has all members at Y={}; giving it a minimum 1-block height", - LogUtils.sanitizeForLog(label), minY); - maxY = minY + 1; - } - return new ExtrudeHeightRange(minY, maxY); - } - - private static void setExtrudeMarker(SetExtrudeMarkerAction action, Map markers) { - LOGGER.debug("Setting extrude marker..."); - if (action.getPoints().size() < 3) return; // defensive - SignManager should never dispatch below 3 - - var points = action.getPoints(); - var shape = new Shape(points.stream().map(p -> new Vector2d(p.x(), p.z())).toList()); - var heightRange = resolveExtrudeHeightRange(action.getLabel(), points); - var lineColor = ColorUtils.parseHex(action.getLineColor()); - var fillColor = ColorUtils.parseHex(action.getFillColor()); - var markerGroup = action.getMarkerIdentifier().parentSet().markerGroup(); - - var marker = ExtrudeMarker.builder() - .label(action.getLabel()) - .detail(HtmlUtils.toHtmlDetail(action.getDetail())) - .shape(shape, heightRange.minY(), heightRange.maxY()) - .lineWidth(action.getLineWidth()) - .lineColor(toBlueMapColor(lineColor)) - .fillColor(toBlueMapColor(fillColor)) - .depthTestEnabled(markerGroup.depthTest()) - .build(); - marker.setMinDistance(markerGroup.minDistance()); - marker.setMaxDistance(markerGroup.maxDistance()); - markers.put(action.getMarkerIdentifier().getId(), marker); - } - - private static void addMarker(AddMarkerAction addAction, Map markers) { - LOGGER.debug("Adding marker..."); - var identifier = addAction.getMarkerIdentifier(); - var markerGroup = identifier.parentSet().markerGroup(); - if (markerGroup.type() == MarkerGroupType.POI) { - LOGGER.debug("Adding POI marker..."); - var markerBuilder = POIMarker.builder() - .position((double) identifier.x(), (double) identifier.y(), (double) identifier.z()) - .label(addAction.getLabel()) - .detail(HtmlUtils.toHtmlDetail(addAction.getDetail())); - - if (markerGroup.icon() != null && !markerGroup.icon().isEmpty()) { - markerBuilder.icon(markerGroup.icon(), markerGroup.offsetX(), markerGroup.offsetY()); - } - - if (!markerGroup.cssClasses().isEmpty()) { - markerBuilder.styleClasses(markerGroup.cssClasses().toArray(new String[0])); - } - - LOGGER.debug("Adding marker (id {}) to marker set", identifier.getId()); - var marker = markerBuilder.build(); - marker.setMinDistance(markerGroup.minDistance()); - marker.setMaxDistance(markerGroup.maxDistance()); - markers.put(identifier.getId(), marker); - } - } - private void onError(Throwable throwable) { LOGGER.error("Error processing marker action", throwable); } + // Genuine BlueMap disable/re-enable cycle (a real reload, which must resetQueue()/fireReset() to + // re-diff signCache against the reloaded config) vs. the very first onEnable() a server ever sees: told + // apart by markerActionQueue.isShutdown(), read here before resetQueue() replaces the reference below. + // Correct now that isShutdown() reports true only for a genuine shutdown() call rather than also + // conflating "never started" (finding 63, + // .scratch/concurrency-pass-2026-09/issues/04-reactivequeue-isshutdown-semantics.md) - this used to need + // a dedicated disabledSinceLastEnable flag instead, precisely because the old isShutdown() would also + // report true for a brand-new queue whose executor was never lazily created (e.g. SERVER_STARTING + // dispatching actions for every migrated/loaded sign before BlueMap is available - process() returns + // early via shouldRun() without ever creating an executor), which mistook first startup for a reload and + // discarded every action enqueued during sign load before a single one was ever processed. private void onEnable(BlueMapAPI api) { - this.blueMapAPI = api; - - if (disabledSinceLastEnable) { - disabledSinceLastEnable = false; - resetQueue(); - - fireReset(); + // synchronized: BlueMap's listener dispatch is presumed single-threaded today, but the + // isShutdown() check-then-act (resetQueue()/fireReset()) isn't atomic on its own - a + // hypothetical concurrent onEnable() call could otherwise also observe isShutdown()==true and + // double-fire both (finding 44, agent-context/reviews/full-codebase-review_2026-09-07_0900.md). + // Shares the same lock as processMarkerAction/applySingleAction's marker mutations, which is + // fine here - onEnable() only runs on a genuine BlueMap enable/reload, never on the hot path. + synchronized (this) { + var isGenuineReload = markerActionQueue.isShutdown(); + // Checked (and cleared) even on the very first onEnable(), before isGenuineReload's branch + // below can replace markerActionQueue with a fresh, never-overflowed one: capacity rejection + // permanently drops a message (enqueue() has no failure signal back to its caller, and this + // queue has no retry/replay path of its own), so a large sign count enqueuing every migrated/ + // loaded sign's add action while BlueMap is still unavailable at startup can silently overflow + // - and since this is the very first enable, isGenuineReload is false and fireReset() would + // otherwise never run to recover the dropped markers. See the "capacity does not bound..." + // finding, agent-context/reviews/copilotreview.2026-09-09.md. + var overflowedBeforeAvailable = markerActionQueue.consumeOverflowSinceLastCheck(); + + if (isGenuineReload) { + if (!lastShutdownConfirmedClean) { + LOGGER.warn("Resuming after a BlueMap disable whose shutdown() could not confirm every " + + "in-flight marker action had stopped; a straggler task may still race this reset's " + + "replay of marker state"); + } + + // Reload config before resetQueue() rather than after: resetQueue() reads + // ConfigManager.get().getShutdownAwaitSeconds() to build the new queue, and fireReset() + // (below) is what would otherwise reload config via SignManager.reloadConfig() - too + // late, since the queue's shutdownAwaitSeconds is fixed at construction. Without this, + // editing that setting and running /bluemap reload had no effect until a later + // disable/re-enable cycle. fireReset() still runs its own ConfigManager.reload() right + // after (harmless - just re-reads the same just-reloaded file) since it also needs to + // rebuild SignManager's parser/prefix map from the reloaded config. + ConfigManager.reload(); + resetQueue(); + + fireReset(); + } else if (overflowedBeforeAvailable) { + LOGGER.warn("Marker action queue dropped one or more actions to capacity before BlueMap became " + + "available; replaying every currently tracked sign's marker state to recover them"); + fireReset(); + } } markerActionQueue.process(); } private void onDisable(BlueMapAPI api) { - disabledSinceLastEnable = true; - markerActionQueue.shutdown(); + lastShutdownConfirmedClean = markerActionQueue.shutdown(); } private synchronized Optional> getMarkerSets(MarkerSetIdentifier markerSetIdentifier) { @@ -532,6 +401,7 @@ private synchronized Optional> getMarkerSets(MarkerSetIden .build(); blueMapMap.getMarkerSets().putIfAbsent(markerSetIdentifier.markerGroup().name(), markerSet); } else { + markerSet.setLabel(markerSetIdentifier.markerGroup().name()); markerSet.setDefaultHidden(markerSetIdentifier.markerGroup().defaultHidden()); markerSet.setSorting(markerSetIdentifier.markerGroup().sorting()); markerSet.setToggleable(markerSetIdentifier.markerGroup().toggleable()); @@ -546,7 +416,16 @@ private synchronized Optional> getMarkerSets(MarkerSetIden } private Optional> getMaps(String mapId) { - var world = this.blueMapAPI.getWorld(mapId); + // Re-fetch rather than trust a cached BlueMapAPI reference: a disable/re-enable between + // processMarkerAction's guard check and this call could otherwise operate against a defunct + // instance (finding 43, agent-context/reviews/full-codebase-review_2026-09-07_0900.md). + var apiInstance = BlueMapAPI.getInstance(); + if (apiInstance.isEmpty()) { + LOGGER.debug("BlueMap API not present; skipping map lookup for {}", mapId); + return Optional.empty(); + } + + var world = apiInstance.get().getWorld(mapId); if (world.isEmpty()) { LOGGER.warn(WORLD_NOT_FOUND, mapId); diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/MarkerMutations.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/MarkerMutations.java new file mode 100644 index 0000000..a44dbd3 --- /dev/null +++ b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/MarkerMutations.java @@ -0,0 +1,222 @@ +package com.tpwalke2.bluemapsignmarkers.core.bluemap; + +import com.flowpowered.math.vector.Vector2d; +import com.flowpowered.math.vector.Vector3d; +import com.tpwalke2.bluemapsignmarkers.Constants; +import com.tpwalke2.bluemapsignmarkers.common.ColorUtils; +import com.tpwalke2.bluemapsignmarkers.common.HtmlUtils; +import com.tpwalke2.bluemapsignmarkers.common.LogUtils; +import com.tpwalke2.bluemapsignmarkers.core.bluemap.actions.AddMarkerAction; +import com.tpwalke2.bluemapsignmarkers.core.bluemap.actions.RemoveMarkerAction; +import com.tpwalke2.bluemapsignmarkers.core.bluemap.actions.SetMultiPointMarkerAction; +import com.tpwalke2.bluemapsignmarkers.core.bluemap.actions.UpdateMarkerAction; +import com.tpwalke2.bluemapsignmarkers.core.markers.LinePoint; +import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerGroupType; +import com.tpwalke2.bluemapsignmarkers.core.markers.MultiPointGroupThresholds; +import com.tpwalke2.bluemapsignmarkers.core.markers.MultiPointMarkerIdentifier; +import de.bluecolored.bluemap.api.markers.ExtrudeMarker; +import de.bluecolored.bluemap.api.markers.LineMarker; +import de.bluecolored.bluemap.api.markers.Marker; +import de.bluecolored.bluemap.api.markers.POIMarker; +import de.bluecolored.bluemap.api.markers.ShapeMarker; +import de.bluecolored.bluemap.api.math.Color; +import de.bluecolored.bluemap.api.math.Line; +import de.bluecolored.bluemap.api.math.Shape; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.List; +import java.util.Map; +import java.util.Optional; + +// State-free marker-construction logic pulled out of BlueMapAPIConnector (ticket 04, +// .scratch/marker-action-consolidation/issues/04-shrink-bluemapapiconnector-marker-mutations.md) - every +// method here takes only the action being applied and the target MarkerSet's mutable marker Map, with no +// reference to BlueMapAPIConnector's queue/cache/lifecycle state, so mutation logic can be read (and +// changed) independent of dispatch/gating/cache concerns. +final class MarkerMutations { + private static final Logger LOGGER = LoggerFactory.getLogger(Constants.MOD_ID); + + private MarkerMutations() { + } + + static void addMarker(AddMarkerAction addAction, Map markers) { + var identifier = addAction.getMarkerIdentifier(); + var markerGroup = identifier.parentSet().markerGroup(); + if (markerGroup.type() != MarkerGroupType.POI) { + LOGGER.warn("Refusing to add a POI marker for non-POI marker group '{}' (type {})", + markerGroup.name(), markerGroup.type()); + return; + } + + LOGGER.debug("Adding POI marker..."); + var markerBuilder = POIMarker.builder() + .position((double) identifier.x(), (double) identifier.y(), (double) identifier.z()) + .label(addAction.getLabel()) + .detail(HtmlUtils.toHtmlDetail(addAction.getDetail())); + + if (markerGroup.icon() != null && !markerGroup.icon().isEmpty()) { + markerBuilder.icon(markerGroup.icon(), markerGroup.offsetX(), markerGroup.offsetY()); + } + + if (!markerGroup.cssClasses().isEmpty()) { + markerBuilder.styleClasses(markerGroup.cssClasses().toArray(new String[0])); + } + + LOGGER.debug("Adding marker (id {}) to marker set", identifier.getId()); + var marker = markerBuilder.build(); + marker.setMinDistance(markerGroup.minDistance()); + marker.setMaxDistance(markerGroup.maxDistance()); + markers.put(identifier.getId(), marker); + } + + static void updateMarker(UpdateMarkerAction updateAction, Map markers) { + LOGGER.debug("Updating marker..."); + + var marker = Optional.ofNullable(markers.get(updateAction.getMarkerIdentifier().getId())); + if (marker.isEmpty()) return; + marker.get().setLabel(updateAction.getNewLabel()); + if (marker.get() instanceof POIMarker poiMarker) { + poiMarker.setDetail(HtmlUtils.toHtmlDetail(updateAction.getNewDetails())); + } + } + + static void removeMarker(RemoveMarkerAction removeAction, Map markers) { + LOGGER.debug("Removing marker..."); + removeMarkerById(removeAction.getMarkerIdentifier().getId(), markers); + } + + static void removeMarkerById(String id, Map markers) { + markers.remove(id); + } + + // Dispatches to the right BlueMap marker builder for this SetMultiPointMarkerAction's kind (set by + // ActionFactory.createSetMultiPointAction on the MultiPointMarkerIdentifier) - a single action type + // covers line/shape/extrude, so this is the one place that still needs to tell them apart. The shared + // preamble (min-member gating, color parsing, min/max distance, storing the built marker) lives once + // here; only the actual per-kind BlueMap builder call differs, since LineMarker.Builder/ + // ShapeMarker.Builder/ExtrudeMarker.Builder share no common builder supertype in bluemap-api. + static void setMultiPointMarker(SetMultiPointMarkerAction action, Map markers) { + var identifier = (MultiPointMarkerIdentifier) action.getMarkerIdentifier(); + var kind = identifier.kind(); + var points = action.getPoints(); + var minMembers = minMembersFor(kind); + if (minMembers < 0) { + LOGGER.warn("Unknown multi-point marker kind '{}' for label='{}'", + kind, LogUtils.sanitizeForLog(action.getLabel())); + return; + } + + if (points.size() < minMembers) { + // defensive - SignManager should never dispatch below the minimum; warn so a regression is visible. + LOGGER.warn("Refusing to set {} marker '{}' with fewer than {} points ({})", + kind, LogUtils.sanitizeForLog(action.getLabel()), minMembers, points.size()); + return; + } + + LOGGER.debug("Setting {} marker...", kind); + var lineColor = toBlueMapColor(ColorUtils.parseHex(action.getLineColor())); + var markerGroup = identifier.parentSet().markerGroup(); + + // Each arm builds and stores its own concrete marker type rather than converging on a shared + // ObjectMarker-typed variable - bluemap-api is compileOnly (absent from the test runtime + // classpath), and a shared variable fed by LineMarker/ShapeMarker/ExtrudeMarker across these + // branches forces the verifier to resolve their common supertype (ObjectMarker) the moment this + // class is first touched, breaking MarkerMutationsTest's resolveExtrudeHeightRange coverage even + // though that method never itself references a bluemap-api type. + switch (kind) { + case "line" -> { + var marker = LineMarker.builder() + .label(action.getLabel()) + .detail(HtmlUtils.toHtmlDetail(action.getDetail())) + .line(new Line(points.stream().map(p -> new Vector3d(p.x(), p.y(), p.z())).toList())) + .lineWidth(action.getLineWidth()) + .lineColor(lineColor) + .depthTestEnabled(markerGroup.depthTest()) + .build(); + marker.setMinDistance(markerGroup.minDistance()); + marker.setMaxDistance(markerGroup.maxDistance()); + markers.put(identifier.getId(), marker); + } + case "shape" -> { + var marker = ShapeMarker.builder() + .label(action.getLabel()) + .detail(HtmlUtils.toHtmlDetail(action.getDetail())) + // Shape height anchors to the tallest member rather than placement order, so the + // polygon always clears the terrain/builds of every sign that defines it. + .shape(shapeOf(points), maxY(points)) + .lineWidth(action.getLineWidth()) + .lineColor(lineColor) + .fillColor(toBlueMapColor(ColorUtils.parseHex(action.getFillColor()))) + .depthTestEnabled(markerGroup.depthTest()) + .build(); + marker.setMinDistance(markerGroup.minDistance()); + marker.setMaxDistance(markerGroup.maxDistance()); + markers.put(identifier.getId(), marker); + } + case "extrude" -> { + var heightRange = resolveExtrudeHeightRange(action.getLabel(), points); + var marker = ExtrudeMarker.builder() + .label(action.getLabel()) + .detail(HtmlUtils.toHtmlDetail(action.getDetail())) + .shape(shapeOf(points), heightRange.minY(), heightRange.maxY()) + .lineWidth(action.getLineWidth()) + .lineColor(lineColor) + .fillColor(toBlueMapColor(ColorUtils.parseHex(action.getFillColor()))) + .depthTestEnabled(markerGroup.depthTest()) + .build(); + marker.setMinDistance(markerGroup.minDistance()); + marker.setMaxDistance(markerGroup.maxDistance()); + markers.put(identifier.getId(), marker); + } + default -> throw new IllegalStateException("Unreachable: unknown kind '" + kind + "' already handled above"); + } + } + + private static int minMembersFor(String kind) { + return switch (kind) { + case "line" -> MultiPointGroupThresholds.LINE_MIN_MEMBERS; + case "shape" -> MultiPointGroupThresholds.SHAPE_MIN_MEMBERS; + case "extrude" -> MultiPointGroupThresholds.EXTRUDE_MIN_MEMBERS; + default -> -1; + }; + } + + private static Shape shapeOf(List points) { + return new Shape(points.stream().map(p -> new Vector2d(p.x(), p.z())).toList()); + } + + private static float maxY(List points) { + return (float) points.stream().mapToInt(LinePoint::y).max().orElseThrow(); + } + + // ColorUtils.parseHex returns alpha in the same 0-255 range as r/g/b, but BlueMap's Color(int, int, int, + // float) constructor takes alpha in 0-1 - passing the raw 0-255 int straight through (as the earlier + // Color(int, int, int, int alpha-as-int) overload does, treating alpha/255f) is NOT what an int + // widening to float gives you: it silently widens to e.g. 51.0f instead of dividing by 255, which + // BlueMap then clamps to fully opaque. Every translucent color (e.g. SHAPE's fillColor default) rendered + // fully opaque as a result. + static Color toBlueMapColor(int[] rgba) { + return new Color(rgba[0], rgba[1], rgba[2], rgba[3] / 255f); + } + + // Floor/ceiling of an extrude volume - a plain value holder (no bluemap-api types), so + // resolveExtrudeHeightRange stays testable even though bluemap-api is compileOnly and not on the test + // classpath (see AGENTS.md's testable-vs-game-coupled split). + record ExtrudeHeightRange(float minY, float maxY) {} + + // Floor/ceiling anchor to the lowest/tallest member respectively, so the volume always spans the full + // height range its members were placed at, independent of placement order. All members at the same Y + // (e.g. one floor) would otherwise collapse the extrusion to zero height, rendering nothing on the map + // with no indication why - so give it a one-block floor instead. + static ExtrudeHeightRange resolveExtrudeHeightRange(String label, List points) { + var minY = (float) points.stream().mapToInt(LinePoint::y).min().orElseThrow(); + var maxY = (float) points.stream().mapToInt(LinePoint::y).max().orElseThrow(); + if (maxY <= minY) { + LOGGER.debug("Extrude marker label='{}' has all members at Y={}; giving it a minimum 1-block height", + LogUtils.sanitizeForLog(label), minY); + maxY = minY + 1; + } + return new ExtrudeHeightRange(minY, maxY); + } +} diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/ActionFactory.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/ActionFactory.java index 91ab204..08b23bb 100644 --- a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/ActionFactory.java +++ b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/ActionFactory.java @@ -1,16 +1,20 @@ package com.tpwalke2.bluemapsignmarkers.core.bluemap.actions; -import com.tpwalke2.bluemapsignmarkers.core.markers.ExtrudeMarkerIdentifier; -import com.tpwalke2.bluemapsignmarkers.core.markers.LineMarkerIdentifier; import com.tpwalke2.bluemapsignmarkers.core.markers.LinePoint; import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerGroup; +import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerGroupType; import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerIdentifier; import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerSetIdentifierCollection; -import com.tpwalke2.bluemapsignmarkers.core.markers.ShapeMarkerIdentifier; +import com.tpwalke2.bluemapsignmarkers.core.markers.MultiPointGroupThresholds; +import com.tpwalke2.bluemapsignmarkers.core.markers.MultiPointMarkerIdentifier; import java.util.List; public class ActionFactory { + private static final String LINE_KIND = "line"; + private static final String SHAPE_KIND = "shape"; + private static final String EXTRUDE_KIND = "extrude"; + private final MarkerSetIdentifierCollection markerSetIdentifierCollection; public ActionFactory(MarkerSetIdentifierCollection markerSetIdentifierCollection) { @@ -25,14 +29,7 @@ public AddMarkerAction createAddPOIAction( String label, String detail, MarkerGroup markerGroup) { - return new AddMarkerAction( - new MarkerIdentifier( - x, - y, - z, - markerSetIdentifierCollection.getIdentifier(mapId, markerGroup)), - label, - detail); + return new AddMarkerAction(markerIdentifier(x, y, z, mapId, markerGroup), label, detail); } public RemoveMarkerAction createRemovePOIAction( @@ -41,15 +38,21 @@ public RemoveMarkerAction createRemovePOIAction( int z, String mapId, MarkerGroup markerGroup) { - return new RemoveMarkerAction( - new MarkerIdentifier( - x, - y, - z, - markerSetIdentifierCollection.getIdentifier(mapId, markerGroup))); + return new RemoveMarkerAction(markerIdentifier(x, y, z, mapId, markerGroup)); } - public GroupTransitionMarkerAction createChangeGroupPOIAction( + public UpdateMarkerAction createUpdatePOIAction( + int x, + int y, + int z, + String mapId, + String newLabel, + String newDetail, + MarkerGroup markerGroup) { + return new UpdateMarkerAction(markerIdentifier(x, y, z, mapId, markerGroup), newLabel, newDetail); + } + + public GroupTransitionMarkerAction createGroupTransitionPOIAction( int x, int y, int z, @@ -58,46 +61,19 @@ public GroupTransitionMarkerAction createChangeGroupPOIAction( String detail, MarkerGroup oldMarkerGroup, MarkerGroup newMarkerGroup) { - var oldIdentifier = new MarkerIdentifier( - x, - y, - z, - markerSetIdentifierCollection.getIdentifier(mapId, oldMarkerGroup)); - var newIdentifier = new MarkerIdentifier( - x, - y, - z, - markerSetIdentifierCollection.getIdentifier(mapId, newMarkerGroup)); + var oldIdentifier = markerIdentifier(x, y, z, mapId, oldMarkerGroup); + var newIdentifier = markerIdentifier(x, y, z, mapId, newMarkerGroup); return new GroupTransitionMarkerAction(List.of( new RemoveMarkerAction(oldIdentifier), new AddMarkerAction(newIdentifier, label, detail))); } - public SetLineMarkerAction createSetLineAction( - String mapId, - MarkerGroup markerGroup, - String label, - String detail, - List points, - String lineColor, - boolean isFirstAppearance) { - return new SetLineMarkerAction( - new LineMarkerIdentifier(label, markerSetIdentifierCollection.getIdentifier(mapId, markerGroup)), - label, - detail, - points, - markerGroup.lineWidth(), - lineColor, - isFirstAppearance); - } - - public RemoveLineMarkerAction createRemoveLineAction(String mapId, MarkerGroup markerGroup, String label) { - return new RemoveLineMarkerAction( - new LineMarkerIdentifier(label, markerSetIdentifierCollection.getIdentifier(mapId, markerGroup))); + private MarkerIdentifier markerIdentifier(int x, int y, int z, String mapId, MarkerGroup markerGroup) { + return new MarkerIdentifier(x, y, z, markerSetIdentifierCollection.getIdentifier(mapId, markerGroup)); } - public SetShapeMarkerAction createSetShapeAction( + public SetMultiPointMarkerAction createSetMultiPointAction( String mapId, MarkerGroup markerGroup, String label, @@ -106,62 +82,35 @@ public SetShapeMarkerAction createSetShapeAction( String lineColor, String fillColor, boolean isFirstAppearance) { - return new SetShapeMarkerAction( - new ShapeMarkerIdentifier(label, markerSetIdentifierCollection.getIdentifier(mapId, markerGroup)), + var kind = multiPointKind(markerGroup.type()); + return new SetMultiPointMarkerAction( + new MultiPointMarkerIdentifier(kind.name(), label, markerSetIdentifierCollection.getIdentifier(mapId, markerGroup)), label, detail, points, markerGroup.lineWidth(), lineColor, fillColor, + kind.minMembers(), isFirstAppearance); } - public RemoveShapeMarkerAction createRemoveShapeAction(String mapId, MarkerGroup markerGroup, String label) { - return new RemoveShapeMarkerAction( - new ShapeMarkerIdentifier(label, markerSetIdentifierCollection.getIdentifier(mapId, markerGroup))); - } - - public SetExtrudeMarkerAction createSetExtrudeAction( - String mapId, - MarkerGroup markerGroup, - String label, - String detail, - List points, - String lineColor, - String fillColor, - boolean isFirstAppearance) { - return new SetExtrudeMarkerAction( - new ExtrudeMarkerIdentifier(label, markerSetIdentifierCollection.getIdentifier(mapId, markerGroup)), - label, - detail, - points, - markerGroup.lineWidth(), - lineColor, - fillColor, - isFirstAppearance); + public RemoveMultiPointMarkerAction createRemoveMultiPointAction(String mapId, MarkerGroup markerGroup, String label) { + var kind = multiPointKind(markerGroup.type()); + return new RemoveMultiPointMarkerAction( + new MultiPointMarkerIdentifier(kind.name(), label, markerSetIdentifierCollection.getIdentifier(mapId, markerGroup))); } - public RemoveExtrudeMarkerAction createRemoveExtrudeAction(String mapId, MarkerGroup markerGroup, String label) { - return new RemoveExtrudeMarkerAction( - new ExtrudeMarkerIdentifier(label, markerSetIdentifierCollection.getIdentifier(mapId, markerGroup))); + private record MultiPointKind(String name, int minMembers) { } - public UpdateMarkerAction createUpdatePOIAction( - int x, - int y, - int z, - String mapId, - String newLabel, - String newDetail, - MarkerGroup markerGroup) { - return new UpdateMarkerAction( - new MarkerIdentifier( - x, - y, - z, - markerSetIdentifierCollection.getIdentifier(mapId, markerGroup)), - newLabel, - newDetail); + private static MultiPointKind multiPointKind(MarkerGroupType type) { + return switch (type) { + case LINE -> new MultiPointKind(LINE_KIND, MultiPointGroupThresholds.LINE_MIN_MEMBERS); + case SHAPE -> new MultiPointKind(SHAPE_KIND, MultiPointGroupThresholds.SHAPE_MIN_MEMBERS); + case EXTRUDE -> new MultiPointKind(EXTRUDE_KIND, MultiPointGroupThresholds.EXTRUDE_MIN_MEMBERS); + case POI -> throw new IllegalArgumentException( + "createSetMultiPointAction/createRemoveMultiPointAction require a LINE, SHAPE, or EXTRUDE marker group, got " + type); + }; } } diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/AddMarkerAction.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/AddMarkerAction.java index 1171a6e..7003825 100644 --- a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/AddMarkerAction.java +++ b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/AddMarkerAction.java @@ -8,8 +8,8 @@ public class AddMarkerAction extends MarkerAction { public AddMarkerAction(MarkerIdentifier markerIdentifier, String label, String detail) { super(markerIdentifier); - this.label = label; - this.detail = detail; + this.label = MarkerActionValidation.requireNonNullField(label, "label", "AddMarkerAction"); + this.detail = MarkerActionValidation.requireNonNullField(detail, "detail", "AddMarkerAction"); } @Override diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/MarkerActionValidation.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/MarkerActionValidation.java new file mode 100644 index 0000000..6851cc4 --- /dev/null +++ b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/MarkerActionValidation.java @@ -0,0 +1,27 @@ +package com.tpwalke2.bluemapsignmarkers.core.bluemap.actions; + +import java.util.List; +import java.util.Objects; + +// Shared validation for MarkerAction constructors - kept as static helpers rather than base-class logic +// per AGENTS.md's "no base-class refactor" scope note for MarkerAction subtypes. +final class MarkerActionValidation { + private MarkerActionValidation() { + } + + static List requireMinPoints(List points, int minPoints, String actionName) { + Objects.requireNonNull(points, actionName + " requires a non-null points list"); + if (points.size() < minPoints) { + throw new IllegalArgumentException( + actionName + " requires at least " + minPoints + " points, got " + points.size()); + } + return List.copyOf(points); + } + + // Null-only, not blank: SignEntryHelper.getLabel/getDetail legitimately return "" for a bare-prefix + // sign (e.g. "[poi]" with no label/detail text), so rejecting blank would break that real, documented + // case. + static String requireNonNullField(String value, String fieldName, String actionName) { + return Objects.requireNonNull(value, actionName + " requires a non-null " + fieldName); + } +} diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/RemoveExtrudeMarkerAction.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/RemoveExtrudeMarkerAction.java deleted file mode 100644 index e786d7e..0000000 --- a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/RemoveExtrudeMarkerAction.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.tpwalke2.bluemapsignmarkers.core.bluemap.actions; - -import com.tpwalke2.bluemapsignmarkers.core.markers.ExtrudeMarkerIdentifier; - -public class RemoveExtrudeMarkerAction extends MarkerAction { - public RemoveExtrudeMarkerAction(ExtrudeMarkerIdentifier markerIdentifier) { - super(markerIdentifier); - } - - @Override - public String toString() { - return "RemoveExtrudeMarkerAction{" + - "markerIdentifier=" + getMarkerIdentifier() + - '}'; - } -} diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/RemoveLineMarkerAction.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/RemoveLineMarkerAction.java deleted file mode 100644 index cd36f1e..0000000 --- a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/RemoveLineMarkerAction.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.tpwalke2.bluemapsignmarkers.core.bluemap.actions; - -import com.tpwalke2.bluemapsignmarkers.core.markers.LineMarkerIdentifier; - -public class RemoveLineMarkerAction extends MarkerAction { - public RemoveLineMarkerAction(LineMarkerIdentifier markerIdentifier) { - super(markerIdentifier); - } - - @Override - public String toString() { - return "RemoveLineMarkerAction{" + - "markerIdentifier=" + getMarkerIdentifier() + - '}'; - } -} diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/RemoveMultiPointMarkerAction.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/RemoveMultiPointMarkerAction.java new file mode 100644 index 0000000..80ccc48 --- /dev/null +++ b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/RemoveMultiPointMarkerAction.java @@ -0,0 +1,19 @@ +package com.tpwalke2.bluemapsignmarkers.core.bluemap.actions; + +import com.tpwalke2.bluemapsignmarkers.core.markers.MultiPointMarkerIdentifier; + +// Replaces the former RemoveLineMarkerAction/RemoveShapeMarkerAction/RemoveExtrudeMarkerAction - those +// three were structurally identical (differing only in toString()'s class-name literal), since +// MultiPointMarkerIdentifier's kind field already distinguishes line/shape/extrude. +public class RemoveMultiPointMarkerAction extends MarkerAction { + public RemoveMultiPointMarkerAction(MultiPointMarkerIdentifier markerIdentifier) { + super(markerIdentifier); + } + + @Override + public String toString() { + return "RemoveMultiPointMarkerAction{" + + "markerIdentifier=" + getMarkerIdentifier() + + '}'; + } +} diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/RemoveShapeMarkerAction.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/RemoveShapeMarkerAction.java deleted file mode 100644 index cb8c63f..0000000 --- a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/RemoveShapeMarkerAction.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.tpwalke2.bluemapsignmarkers.core.bluemap.actions; - -import com.tpwalke2.bluemapsignmarkers.core.markers.ShapeMarkerIdentifier; - -public class RemoveShapeMarkerAction extends MarkerAction { - public RemoveShapeMarkerAction(ShapeMarkerIdentifier markerIdentifier) { - super(markerIdentifier); - } - - @Override - public String toString() { - return "RemoveShapeMarkerAction{" + - "markerIdentifier=" + getMarkerIdentifier() + - '}'; - } -} diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/SetExtrudeMarkerAction.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/SetExtrudeMarkerAction.java deleted file mode 100644 index 746d50c..0000000 --- a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/SetExtrudeMarkerAction.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.tpwalke2.bluemapsignmarkers.core.bluemap.actions; - -import com.tpwalke2.bluemapsignmarkers.core.markers.ExtrudeMarkerIdentifier; -import com.tpwalke2.bluemapsignmarkers.core.markers.LinePoint; - -import java.util.List; - -public class SetExtrudeMarkerAction extends MarkerAction { - private final String label; - private final String detail; - private final List points; - private final int lineWidth; - private final String lineColor; - private final String fillColor; - // Log-only: whether this extrude volume is being created for the first time vs. re-set with an updated - // point list. Not a distinct subtype - BlueMap has no separate add/update call for extrude markers, so - // this only affects the log message, not the BlueMap API call made. - private final boolean isFirstAppearance; - - public SetExtrudeMarkerAction( - ExtrudeMarkerIdentifier markerIdentifier, - String label, - String detail, - List points, - int lineWidth, - String lineColor, - String fillColor, - boolean isFirstAppearance) { - super(markerIdentifier); - this.label = label; - this.detail = detail; - this.points = points; - this.lineWidth = lineWidth; - this.lineColor = lineColor; - this.fillColor = fillColor; - this.isFirstAppearance = isFirstAppearance; - } - - public String getLabel() { - return label; - } - - public String getDetail() { - return detail; - } - - public List getPoints() { - return points; - } - - public int getLineWidth() { - return lineWidth; - } - - public String getLineColor() { - return lineColor; - } - - public String getFillColor() { - return fillColor; - } - - public boolean isFirstAppearance() { - return isFirstAppearance; - } - - @Override - public String toString() { - return "SetExtrudeMarkerAction{" + - "markerIdentifier=" + getMarkerIdentifier() + - ", label='" + label + '\'' + - ", detail='" + detail + '\'' + - ", points=" + points + - ", lineWidth=" + lineWidth + - ", lineColor='" + lineColor + '\'' + - ", fillColor='" + fillColor + '\'' + - ", isFirstAppearance=" + isFirstAppearance + - '}'; - } -} diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/SetLineMarkerAction.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/SetLineMarkerAction.java deleted file mode 100644 index 9622683..0000000 --- a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/SetLineMarkerAction.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.tpwalke2.bluemapsignmarkers.core.bluemap.actions; - -import com.tpwalke2.bluemapsignmarkers.core.markers.LineMarkerIdentifier; -import com.tpwalke2.bluemapsignmarkers.core.markers.LinePoint; - -import java.util.List; - -public class SetLineMarkerAction extends MarkerAction { - private final String label; - private final String detail; - private final List points; - private final int lineWidth; - private final String lineColor; - // Log-only: whether this line is being created for the first time vs. re-set with an updated point - // list. Not a distinct subtype - BlueMap has no separate add/update call for line markers, so this - // only affects the log message, not the BlueMap API call made. - private final boolean isFirstAppearance; - - public SetLineMarkerAction( - LineMarkerIdentifier markerIdentifier, - String label, - String detail, - List points, - int lineWidth, - String lineColor, - boolean isFirstAppearance) { - super(markerIdentifier); - this.label = label; - this.detail = detail; - this.points = points; - this.lineWidth = lineWidth; - this.lineColor = lineColor; - this.isFirstAppearance = isFirstAppearance; - } - - public String getLabel() { - return label; - } - - public String getDetail() { - return detail; - } - - public List getPoints() { - return points; - } - - public int getLineWidth() { - return lineWidth; - } - - public String getLineColor() { - return lineColor; - } - - public boolean isFirstAppearance() { - return isFirstAppearance; - } - - @Override - public String toString() { - return "SetLineMarkerAction{" + - "markerIdentifier=" + getMarkerIdentifier() + - ", label='" + label + '\'' + - ", detail='" + detail + '\'' + - ", points=" + points + - ", lineWidth=" + lineWidth + - ", lineColor='" + lineColor + '\'' + - ", isFirstAppearance=" + isFirstAppearance + - '}'; - } -} diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/SetShapeMarkerAction.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/SetMultiPointMarkerAction.java similarity index 55% rename from src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/SetShapeMarkerAction.java rename to src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/SetMultiPointMarkerAction.java index 3f13382..49a77cb 100644 --- a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/SetShapeMarkerAction.java +++ b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/SetMultiPointMarkerAction.java @@ -1,35 +1,42 @@ package com.tpwalke2.bluemapsignmarkers.core.bluemap.actions; import com.tpwalke2.bluemapsignmarkers.core.markers.LinePoint; -import com.tpwalke2.bluemapsignmarkers.core.markers.ShapeMarkerIdentifier; +import com.tpwalke2.bluemapsignmarkers.core.markers.MultiPointMarkerIdentifier; import java.util.List; -public class SetShapeMarkerAction extends MarkerAction { +// Replaces the former SetLineMarkerAction/SetShapeMarkerAction/SetExtrudeMarkerAction - those three were +// structurally identical (label/detail/points/lineWidth/lineColor/isFirstAppearance), differing only in +// an optional fillColor (SHAPE/EXTRUDE, absent for LINE) and their minimum-points threshold, which the +// caller (ActionFactory) now supplies from MultiPointGroupThresholds' LINE_MIN_MEMBERS/SHAPE_MIN_MEMBERS/ +// EXTRUDE_MIN_MEMBERS - the same single source of truth SignTransitionResolver itself uses (via static +// import) to decide when a line/shape/extrude marker should exist at all. +public class SetMultiPointMarkerAction extends MarkerAction { private final String label; private final String detail; private final List points; private final int lineWidth; private final String lineColor; private final String fillColor; - // Log-only: whether this shape is being created for the first time vs. re-set with an updated point - // list. Not a distinct subtype - BlueMap has no separate add/update call for shape markers, so this - // only affects the log message, not the BlueMap API call made. + // Log-only: whether this marker is being created for the first time vs. re-set with an updated point + // list. Not a distinct subtype - BlueMap has no separate add/update call for line/shape/extrude + // markers, so this only affects the log message, not the BlueMap API call made. private final boolean isFirstAppearance; - public SetShapeMarkerAction( - ShapeMarkerIdentifier markerIdentifier, + public SetMultiPointMarkerAction( + MultiPointMarkerIdentifier markerIdentifier, String label, String detail, List points, int lineWidth, String lineColor, String fillColor, + int minPoints, boolean isFirstAppearance) { super(markerIdentifier); - this.label = label; - this.detail = detail; - this.points = points; + this.label = MarkerActionValidation.requireNonNullField(label, "label", "SetMultiPointMarkerAction"); + this.detail = MarkerActionValidation.requireNonNullField(detail, "detail", "SetMultiPointMarkerAction"); + this.points = MarkerActionValidation.requireMinPoints(points, minPoints, "SetMultiPointMarkerAction"); this.lineWidth = lineWidth; this.lineColor = lineColor; this.fillColor = fillColor; @@ -66,7 +73,7 @@ public boolean isFirstAppearance() { @Override public String toString() { - return "SetShapeMarkerAction{" + + return "SetMultiPointMarkerAction{" + "markerIdentifier=" + getMarkerIdentifier() + ", label='" + label + '\'' + ", detail='" + detail + '\'' + diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/UpdateMarkerAction.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/UpdateMarkerAction.java index 72a1b3c..bd05d90 100644 --- a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/UpdateMarkerAction.java +++ b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/UpdateMarkerAction.java @@ -8,8 +8,8 @@ public class UpdateMarkerAction extends MarkerAction { public UpdateMarkerAction(MarkerIdentifier markerIdentifier, String newLabel, String newDetail) { super(markerIdentifier); - this.newLabel = newLabel; - this.newDetails = newDetail; + this.newLabel = MarkerActionValidation.requireNonNullField(newLabel, "newLabel", "UpdateMarkerAction"); + this.newDetails = MarkerActionValidation.requireNonNullField(newDetail, "newDetail", "UpdateMarkerAction"); } @Override diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bounds/RenderMaskEvaluator.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bounds/RenderMaskEvaluator.java index 3d6a30e..fcebce3 100644 --- a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bounds/RenderMaskEvaluator.java +++ b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/bounds/RenderMaskEvaluator.java @@ -5,6 +5,7 @@ import org.slf4j.LoggerFactory; import java.io.IOException; +import java.math.BigDecimal; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; @@ -34,8 +35,11 @@ public class RenderMaskEvaluator { // subtract: "true") as equivalent to the bare form, and this mod's fields are all // numeric/boolean, so there's no case where treating the quoted and bare spellings the same way // is wrong. + // The numeric alternative includes an optional exponent (1.5e3, -2E-4) so scientific notation + // parses to its full value instead of the mantissa alone matching and the exponent being left + // as unmatched trailing text (silently wrong shape math, not a parse failure). private static final Pattern FIELD_PATTERN = - Pattern.compile("([A-Za-z][\\w-]*)\\s*[:=]\\s*\"?(-?\\d+(?:\\.\\d+)?|true|false)\"?"); + Pattern.compile("([A-Za-z][\\w-]*)\\s*[:=]\\s*\"?(-?\\d+(?:\\.\\d+)?(?:[eE][+-]?\\d+)?|true|false)\"?"); private RenderMaskEvaluator() {} @@ -110,6 +114,9 @@ private static List loadRenderMask(String mapId, Path mapsConfi // Mirrors BlueMapConfigManager.sanitiseMapId (\W -> _) so an oddly-named config file still // resolves to the same id BlueMap itself computed, rather than assuming literal identity. + // findFirst() means that if two *.conf files sanitize to the same mapId (very unlikely given + // BlueMap assigns ids), which one wins is filesystem-listing-order-dependent, i.e. non-deterministic + // across platforms/runs - Files.list() makes no ordering guarantee. private static Path findConfigFile(String mapId, Path mapsConfigDir) { if (!Files.isDirectory(mapsConfigDir)) { return null; @@ -242,9 +249,14 @@ private static Map extractFields(String chunk) { return fields; } + // FIELD_PATTERN's numeric alternative allows exponent notation (e.g. "1e3") on every numeric field, + // int-typed ones (min-x/max-x/min-y/max-y/min-z/max-z) included - Integer.parseInt can't handle that + // form and would throw, failing the whole map open on an otherwise-valid value. Parse via BigDecimal + // instead so any exact-integer value (exponent notation or not) resolves correctly; a genuinely + // fractional value (e.g. "1.5") still throws via intValueExact, same as before. private static int intField(Map fields, String key, int defaultValue) { var value = fields.get(key); - return value == null ? defaultValue : Integer.parseInt(value); + return value == null ? defaultValue : new BigDecimal(value).intValueExact(); } private static double requiredDoubleField(Map fields, String key) { @@ -281,7 +293,7 @@ private static RenderMaskCircle parseCircle(Map fields, boolean return new RenderMaskCircle( requiredDoubleField(fields, "center-x"), requiredDoubleField(fields, "center-z"), - requiredDoubleField(fields, "radius"), + requiredPositiveDoubleField(fields, "radius"), intField(fields, "min-y", Integer.MIN_VALUE), intField(fields, "max-y", Integer.MAX_VALUE), subtract); diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/markers/ExtrudeMarkerIdentifier.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/markers/ExtrudeMarkerIdentifier.java deleted file mode 100644 index e781c4c..0000000 --- a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/markers/ExtrudeMarkerIdentifier.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.tpwalke2.bluemapsignmarkers.core.markers; - -public record ExtrudeMarkerIdentifier(String label, MarkerSetIdentifier parentSet) implements DispatchedMarkerIdentifier { - public String getId() { - return "extrude:" + label; - } -} diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/markers/LineMarkerIdentifier.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/markers/LineMarkerIdentifier.java deleted file mode 100644 index 5280473..0000000 --- a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/markers/LineMarkerIdentifier.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.tpwalke2.bluemapsignmarkers.core.markers; - -public record LineMarkerIdentifier(String label, MarkerSetIdentifier parentSet) implements DispatchedMarkerIdentifier { - public String getId() { - return "line:" + label; - } -} diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/markers/MarkerGroup.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/markers/MarkerGroup.java index eb2da6c..7ee4400 100644 --- a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/markers/MarkerGroup.java +++ b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/markers/MarkerGroup.java @@ -1,6 +1,7 @@ package com.tpwalke2.bluemapsignmarkers.core.markers; import java.util.List; +import java.util.Objects; public record MarkerGroup( String prefix, @@ -21,6 +22,23 @@ public record MarkerGroup( boolean depthTest, List cssClasses, boolean allowPlayerColors) { + // icon is genuinely allowed to be null (POI groups without an icon, LINE/SHAPE/EXTRUDE groups where + // it's ignored - see ConfigProvider.warnOnTypeFieldMismatches). prefix is also allowed to be null - + // SignLinesParser deliberately tolerates a marker group with no prefix configured, logging a warning + // and ignoring that group rather than crashing the server (see SignLinesParser.hasValidPrefix). Every + // other field is load-bearing wherever a MarkerGroup is actually used, so a null there is rejected + // here instead of surfacing as an NPE deep in whichever code path first dereferences it. cssClasses is + // defensively copied since ConfigProvider currently always passes an immutable list, but nothing else + // enforces that. + public MarkerGroup { + Objects.requireNonNull(matchType, "matchType"); + Objects.requireNonNull(type, "type"); + Objects.requireNonNull(name, "name"); + Objects.requireNonNull(lineColor, "lineColor"); + Objects.requireNonNull(fillColor, "fillColor"); + cssClasses = List.copyOf(Objects.requireNonNull(cssClasses, "cssClasses")); + } + public static final MarkerGroup DEFAULT_POI_GROUP = new MarkerGroup( "[poi]", MarkerGroupMatchType.STARTS_WITH, @@ -40,8 +58,4 @@ public record MarkerGroup( true, List.of(), false); - - public MarkerGroup withType(MarkerGroupType type) { - return new MarkerGroup(prefix, matchType, type, name, icon, offsetX, offsetY, defaultHidden, minDistance, maxDistance, lineWidth, lineColor, fillColor, sorting, toggleable, depthTest, cssClasses, allowPlayerColors); - } } diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/markers/MarkerSetIdentifierCollection.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/markers/MarkerSetIdentifierCollection.java index 6f44fee..0790e89 100644 --- a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/markers/MarkerSetIdentifierCollection.java +++ b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/markers/MarkerSetIdentifierCollection.java @@ -1,51 +1,29 @@ package com.tpwalke2.bluemapsignmarkers.core.markers; -import java.util.*; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; public class MarkerSetIdentifierCollection { - private final Map> mapByMap; - private final Map> mapByMarkerSetId; - - public MarkerSetIdentifierCollection() { - mapByMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); - mapByMarkerSetId = new HashMap<>(); - } - - // synchronized so the "is this combo already cached?" check and the "cache it" write - // (addIdentifier) are one atomic step. SignManager reads this via a volatile RuntimeConfig - // snapshot, so it can be called both from the server thread (live sign edits, via the mixins) - // and from whatever thread fires BlueMapAPI.onEnable/IResetHandler.reset() (replaying every - // cached sign after a config reload) at the same time, against the same instance — without - // this, concurrent first-time lookups for the same (mapId, markerGroup) could each miss the - // cache and construct a distinct MarkerSetIdentifier, and the plain TreeMap/HashMap/HashSet - // fields could corrupt under concurrent mutation (finding #16, - // plans/codebase-review-2026-07-11.md). + private final Map identifiers = new HashMap<>(); + + // synchronized so the "is this combo already cached?" check and the "cache it" write are one atomic + // step. SignManager reads this via a volatile RuntimeConfig snapshot, so it can be called both from the + // server thread (live sign edits, via the mixins) and from whatever thread fires + // BlueMapAPI.onEnable/IResetHandler.reset() (replaying every cached sign after a config reload) at the + // same time, against the same instance - without this, concurrent first-time lookups for the same + // (mapId, markerGroup) could each miss the cache and construct a distinct MarkerSetIdentifier, and the + // plain HashMap field could corrupt under concurrent mutation (finding #16, plans/codebase-review-2026-07-11.md). public synchronized MarkerSetIdentifier getIdentifier(String mapId, MarkerGroup markerGroup) { - var byMap = Optional.ofNullable(mapByMap.get(mapId)); - var byMarkerSetId = Optional.ofNullable(mapByMarkerSetId.get(markerGroup)); - - if (byMap.isEmpty() - || byMarkerSetId.isEmpty()) return addIdentifier(mapId, markerGroup); - - var intersection = byMap.get() - .stream() - .filter(byMarkerSetId.get()::contains) - .toList(); - - return intersection.isEmpty() - ? addIdentifier(mapId, markerGroup) - : intersection.get(0); + if (mapId == null) return null; + + // Keyed by lowercased mapId so map-id matching stays case-insensitive; the cached identifier itself + // still carries whichever casing was passed in on its first call for this combo (deliberate - see + // spec.md's "No action" section on finding #60). + return identifiers.computeIfAbsent( + new Key(mapId.toLowerCase(Locale.ROOT), markerGroup), + k -> new MarkerSetIdentifier(mapId, markerGroup)); } - private MarkerSetIdentifier addIdentifier(String mapId, MarkerGroup markerGroup) { - var markerKey = new MarkerSetIdentifier(mapId, markerGroup); - - mapByMap.putIfAbsent(markerKey.mapId(), new HashSet<>()); - mapByMap.get(markerKey.mapId()).add(markerKey); - - mapByMarkerSetId.putIfAbsent(markerKey.markerGroup(), new HashSet<>()); - mapByMarkerSetId.get(markerKey.markerGroup()).add(markerKey); - - return markerKey; - } + private record Key(String mapIdLower, MarkerGroup markerGroup) {} } diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/markers/MultiPointGroupThresholds.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/markers/MultiPointGroupThresholds.java new file mode 100644 index 0000000..2edde3f --- /dev/null +++ b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/markers/MultiPointGroupThresholds.java @@ -0,0 +1,15 @@ +package com.tpwalke2.bluemapsignmarkers.core.markers; + +// Single source of truth for how many signs a LINE/SHAPE/EXTRUDE group needs before its marker exists - +// shared by SignTransitionResolver (decides when to join/leave/recompute a line/shape/extrude) and +// SetMultiPointMarkerAction/ActionFactory (validates/constructs the resulting marker action). Lives here, +// not in core.signs or core.bluemap.actions, because both of those packages already depend on +// core.markers and neither needs to depend on the other just to share these three numbers. +public final class MultiPointGroupThresholds { + public static final int LINE_MIN_MEMBERS = 2; + public static final int SHAPE_MIN_MEMBERS = 3; + public static final int EXTRUDE_MIN_MEMBERS = 3; + + private MultiPointGroupThresholds() { + } +} diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/markers/MultiPointMarkerIdentifier.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/markers/MultiPointMarkerIdentifier.java new file mode 100644 index 0000000..abc5cf3 --- /dev/null +++ b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/markers/MultiPointMarkerIdentifier.java @@ -0,0 +1,9 @@ +package com.tpwalke2.bluemapsignmarkers.core.markers; + +// Unifies what used to be three near-identical records (LineMarkerIdentifier, ShapeMarkerIdentifier, +// ExtrudeMarkerIdentifier), differing only by a hardcoded id-prefix string in getId(). +public record MultiPointMarkerIdentifier(String kind, String label, MarkerSetIdentifier parentSet) implements DispatchedMarkerIdentifier { + public String getId() { + return kind + ":" + label; + } +} diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/markers/ShapeMarkerIdentifier.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/markers/ShapeMarkerIdentifier.java deleted file mode 100644 index eb9110e..0000000 --- a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/markers/ShapeMarkerIdentifier.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.tpwalke2.bluemapsignmarkers.core.markers; - -public record ShapeMarkerIdentifier(String label, MarkerSetIdentifier parentSet) implements DispatchedMarkerIdentifier { - public String getId() { - return "shape:" + label; - } -} diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/reactive/ReactiveQueue.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/reactive/ReactiveQueue.java index f3dd714..c2c65f9 100644 --- a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/reactive/ReactiveQueue.java +++ b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/reactive/ReactiveQueue.java @@ -1,29 +1,77 @@ package com.tpwalke2.bluemapsignmarkers.core.reactive; +import com.tpwalke2.bluemapsignmarkers.Constants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; public class ReactiveQueue { - private static final long SHUTDOWN_AWAIT_SECONDS = 5; + private static final Logger LOGGER = LoggerFactory.getLogger(Constants.MOD_ID); + public static final long DEFAULT_SHUTDOWN_AWAIT_SECONDS = 5; + // Bounded in practice today by sign count, but this class is documented (see AGENTS.md) as reusable + // for other message types, so enqueue() needs a defensive cap rather than accepting unbounded backlog + // (finding 61, agent-context/reviews/full-codebase-review_2026-09-07_0900.md). Callers dispatch from + // the main server thread and can't tolerate enqueue() blocking, so overflow rejects (logs + drops) + // rather than blocking. Set high (rather than a tighter number) because SignManager.reset() (fired by + // /bluemap reload) re-dispatches one message per cached sign, and region-sharded persistence exists + // specifically to support servers with many tracked signs - a low cap would risk silently dropping + // markers on reload for exactly the large-server case this mod is meant to scale to. + public static final int DEFAULT_CAPACITY = 100_000; + // How often, at most, a run of rejected-for-capacity messages logs a WARN - sustained overflow (e.g. + // BlueMap down for a long stretch under continued sign edits) must not flood the log with one line per + // rejected message. + private static final long CAPACITY_WARNING_THROTTLE_MILLIS = 1_000; private final ConcurrentLinkedQueue queue; - // volatile so isShutdown() (called with no lock held, from any thread) sees getExecutor()'s - // synchronized write without needing its own synchronization (finding #12, + // volatile so isShutdown()/hasStarted() (called with no lock held, from any thread) see getExecutor()'s + // synchronized write without needing their own synchronization (finding #12, // plans/codebase-review-2026-07-11.md). private volatile ExecutorService executor; private volatile boolean shutdownRequested; private final ShouldRunCallback shouldRunCallback; private final MessageProcessorCallback messageProcessorCallback; private final MessageProcessorErrorCallback messageProcessorErrorCallback; + private final long shutdownAwaitSeconds; + private final int capacity; + private final AtomicInteger queuedCount = new AtomicInteger(0); + private final AtomicLong lastCapacityWarningAtMillis = new AtomicLong(0); + // Set whenever enqueue() rejects a message for capacity, cleared only by consumeOverflowSinceLastCheck(). + // A caller with its own replay mechanism (BlueMapAPIConnector.onEnable(), re-dispatching every current + // sign representation via SignManager.reset()) can poll this to recover a message permanently lost to + // capacity rejection instead of it staying silently missing forever - concretely, a server with more + // persisted signs than capacity booting while BlueMap is still unavailable (see + // agent-context/reviews/copilotreview.2026-09-09.md). + private final AtomicBoolean overflowedSinceLastCheck = new AtomicBoolean(false); + // Guards against a burst of enqueue() calls each submitting their own redundant drain-loop task + // (finding 62, agent-context/reviews/full-codebase-review_2026-09-07_0900.md). Only the thread that + // wins the compareAndSet actually submits processMessages(); everyone else's message is still safe + // because it's already on `queue` and the active drain loop drains until the queue is empty. + private final AtomicBoolean draining = new AtomicBoolean(false); public ReactiveQueue( ShouldRunCallback shouldRunCallback, MessageProcessorCallback messageProcessorCallback, MessageProcessorErrorCallback messageProcessorErrorCallback) { - this(shouldRunCallback, messageProcessorCallback, messageProcessorErrorCallback, null); + this(shouldRunCallback, messageProcessorCallback, messageProcessorErrorCallback, DEFAULT_SHUTDOWN_AWAIT_SECONDS); + } + + // Lets a caller (BlueMapAPIConnector, wiring in BMSMConfigV2.getShutdownAwaitSeconds()) configure how + // long shutdown() waits for in-flight tasks instead of the hardcoded 5s (findings 26/27, + // agent-context/reviews/full-codebase-review_2026-09-07_0900.md). + public ReactiveQueue( + ShouldRunCallback shouldRunCallback, + MessageProcessorCallback messageProcessorCallback, + MessageProcessorErrorCallback messageProcessorErrorCallback, + long shutdownAwaitSeconds) { + this(shouldRunCallback, messageProcessorCallback, messageProcessorErrorCallback, shutdownAwaitSeconds, null, DEFAULT_CAPACITY); } // Visible for testing: lets tests inject a controllable executor (e.g. one that runs tasks @@ -34,25 +82,101 @@ public ReactiveQueue( MessageProcessorCallback messageProcessorCallback, MessageProcessorErrorCallback messageProcessorErrorCallback, ExecutorService executor) { + this(shouldRunCallback, messageProcessorCallback, messageProcessorErrorCallback, DEFAULT_SHUTDOWN_AWAIT_SECONDS, executor, DEFAULT_CAPACITY); + } + + // Visible for testing: same as above, plus lets a test control the shutdown-await timeout (e.g. to + // verify a short configured timeout is actually honored rather than the 5s default). + ReactiveQueue( + ShouldRunCallback shouldRunCallback, + MessageProcessorCallback messageProcessorCallback, + MessageProcessorErrorCallback messageProcessorErrorCallback, + long shutdownAwaitSeconds, + ExecutorService executor) { + this(shouldRunCallback, messageProcessorCallback, messageProcessorErrorCallback, shutdownAwaitSeconds, executor, DEFAULT_CAPACITY); + } + + // Visible for testing: lets a test use a small capacity so overflow behavior can be exercised + // without actually enqueuing DEFAULT_CAPACITY messages. + ReactiveQueue( + ShouldRunCallback shouldRunCallback, + MessageProcessorCallback messageProcessorCallback, + MessageProcessorErrorCallback messageProcessorErrorCallback, + ExecutorService executor, + int capacity) { + this(shouldRunCallback, messageProcessorCallback, messageProcessorErrorCallback, DEFAULT_SHUTDOWN_AWAIT_SECONDS, executor, capacity); + } + + private ReactiveQueue( + ShouldRunCallback shouldRunCallback, + MessageProcessorCallback messageProcessorCallback, + MessageProcessorErrorCallback messageProcessorErrorCallback, + long shutdownAwaitSeconds, + ExecutorService executor, + int capacity) { this.queue = new ConcurrentLinkedQueue<>(); this.shouldRunCallback = shouldRunCallback; this.messageProcessorCallback = messageProcessorCallback; this.messageProcessorErrorCallback = messageProcessorErrorCallback; + this.shutdownAwaitSeconds = shutdownAwaitSeconds; this.executor = executor; + this.capacity = capacity; } public void enqueue(T message) { + if (!tryReserveSlot()) { + warnAtCapacity(message); + return; + } + queue.offer(message); this.process(); } + private void warnAtCapacity(T message) { + overflowedSinceLastCheck.set(true); + + var now = System.currentTimeMillis(); + var last = lastCapacityWarningAtMillis.get(); + if (now - last < CAPACITY_WARNING_THROTTLE_MILLIS + || !lastCapacityWarningAtMillis.compareAndSet(last, now)) { + return; + } + + LOGGER.warn("ReactiveQueue at capacity ({}); rejecting enqueued message (further rejections within {}ms " + + "will not be individually logged): {}", capacity, CAPACITY_WARNING_THROTTLE_MILLIS, message); + } + + // Reserves a capacity slot only if one is free. Not perfectly atomic with queue.offer() (a slot could + // in theory be reserved slightly ahead of the item actually landing on `queue`), but that's fine here: + // it can only ever under-count concurrent in-flight enqueues by a small, bounded margin, never let the + // queue grow unbounded. + private boolean tryReserveSlot() { + while (true) { + int current = queuedCount.get(); + if (current >= capacity) { + return false; + } + if (queuedCount.compareAndSet(current, current + 1)) { + return true; + } + } + } + public void process() { if (shutdownRequested || !shouldRunCallback.shouldRun()) { return; } + if (!draining.compareAndSet(false, true)) { + // A drain loop is already active (or about to be submitted); it will drain this message too, + // so submitting another one would be redundant. + return; + } + var currentExecutor = getExecutor(); if (currentExecutor == null) { + draining.set(false); return; } @@ -61,34 +185,110 @@ public void process() { } catch (RejectedExecutionException e) { // Shut down concurrently between the checks above and this submission; this instance is // retired, nothing more to schedule. + draining.set(false); } } + // Shared by processMessages()'s while-condition and its post-drain recheck below, so the two can't + // drift apart if this condition is ever changed in one place but not the other. + private boolean canContinueDraining() { + return !shutdownRequested && !queue.isEmpty() && shouldRunCallback.shouldRun(); + } + private void processMessages() { - while (!shutdownRequested && !queue.isEmpty() && shouldRunCallback.shouldRun()) { - T message = queue.poll(); - if (message == null) continue; - - var currentExecutor = getExecutor(); - if (currentExecutor == null) return; - - try { - currentExecutor.submit(() -> messageProcessorCallback.processMessage(message)); - } catch (RejectedExecutionException e) { - // Shut down concurrently between poll() and this submission; expected during a normal - // shutdown race, not a processing failure worth reporting to the error callback. - return; - } catch (Exception e) { - messageProcessorErrorCallback.onError(e); + try { + while (canContinueDraining()) { + T message = queue.poll(); + if (message == null) continue; + + // queuedCount is decremented only once the submitted task actually finishes (or is known + // never to run), not here right after poll() - decrementing here freed a capacity slot the + // instant a message left `queue`, even though it then sat in the executor's own unbounded + // internal work queue awaiting a free worker thread. That let a slow processor accumulate + // arbitrarily many not-yet-run tasks there while enqueue() kept accepting more, defeating + // the whole point of capacity - it only ever bounded `queue` itself, not total outstanding + // work. Counting "submitted but not yet complete" the same as "still queued" makes capacity + // an actual bound on total outstanding work. + var currentExecutor = getExecutor(); + if (currentExecutor == null) { + queuedCount.decrementAndGet(); + return; + } + + try { + currentExecutor.submit(() -> { + try { + messageProcessorCallback.processMessage(message); + } catch (Exception e) { + try { + messageProcessorErrorCallback.onError(e); + } catch (Exception errorCallbackException) { + // A broken error callback must not kill this worker thread mid-drain (leaving + // later messages unprocessed) or propagate back to enqueue()'s caller. + } + } finally { + queuedCount.decrementAndGet(); + } + }); + } catch (RejectedExecutionException e) { + // Shut down concurrently between poll() and this submission; expected during a normal + // shutdown race, not a processing failure worth reporting to the error callback. + queuedCount.decrementAndGet(); + return; + } catch (Exception e) { + queuedCount.decrementAndGet(); + messageProcessorErrorCallback.onError(e); + } + } + } finally { + draining.set(false); + // Closes the race window between the loop above observing "nothing left to do" (queue empty, + // or shouldRun() false) and this flag actually clearing: a message enqueue()'d or a process() + // call landing in that window would otherwise see draining still true, skip submitting, and + // never get drained. Re-checking after the flag clears guarantees this thread (or whichever + // enqueue() call raced it) picks it back up instead. + if (canContinueDraining()) { + process(); } } } + // Previously also returned true whenever executor == null, conflating "genuinely shut down" with + // "never started" (a queue whose process() calls have all returned early via the shouldRun()/ + // shutdownRequested checks before ever lazily creating an executor - e.g. SERVER_STARTING dispatching + // sign-load actions before BlueMap is available). BlueMapAPIConnector.onEnable() hit that conflation for + // real: it used to need a dedicated disabledSinceLastEnable flag to detect a genuine BlueMap + // disable/re-enable cycle, precisely because isShutdown() also reported true for the never-started case + // and mistook first startup for a reload - discarding every action enqueued during sign load before a + // single one was processed. Fixed here, that flag is gone; onEnable() now asks + // markerActionQueue.isShutdown() directly (see its comment) - see also hasStarted() below for querying + // the other half of the old conflation directly (finding 63, + // agent-context/reviews/full-codebase-review_2026-09-07_0900.md). + // + // shutdownRequested alone is sufficient here: only shutdown() ever sets it, always synchronously with + // calling executor.shutdown() on whatever executor exists at that moment (null or not), and no code + // outside this class can shut the internal executor down through any other path - so there's no + // scenario where the executor is independently shut down while shutdownRequested is still false. public boolean isShutdown() { - return shutdownRequested || executor == null || executor.isShutdown(); + return shutdownRequested; + } + + // Distinguishes "never processed anything yet" from "genuinely shut down" - the other half of the + // conflation isShutdown() used to have (finding 63, see above). True once this instance has lazily + // created its executor, i.e. at least one process() call got past the shouldRun()/shutdownRequested + // checks - regardless of whether it has since been shut down. + public boolean hasStarted() { + return executor != null; + } + + // True if enqueue() rejected at least one message for capacity since the last call to this method, + // false otherwise - clears the flag as a side effect so repeated polling only reports genuinely new + // overflow. See overflowedSinceLastCheck's declaration for why a caller needs this. + public boolean consumeOverflowSinceLastCheck() { + return overflowedSinceLastCheck.getAndSet(false); } - // Blocks (up to SHUTDOWN_AWAIT_SECONDS) until every task already submitted to this generation's + // Blocks (up to shutdownAwaitSeconds) until every task already submitted to this generation's // executor has finished, so a caller that awaits shutdown() returning can rely on there being no // straggler still able to touch shared state afterward — otherwise such a straggler could run after // a subsequent resetQueue()/fireReset() replay and clobber the state that replay just established @@ -99,7 +299,14 @@ public boolean isShutdown() { // before: a shutdown() racing a lazy executor creation can't leave a freshly-created executor // un-shut-down), but the lock is released before awaitTermination() blocks — held across the wait, // it would deadlock against an in-flight task's own getExecutor() call needing the same monitor. - public void shutdown() { + // + // Returns whether a clean stop was actually confirmed. A task that ignores Thread.interrupt() (blocked + // on non-interruptible I/O, or CPU-bound with no poll point) can still be running after shutdownNow()'s + // own await times out — this method can't force that task to stop, so it can't uphold the "no straggler + // touches shared state after shutdown() returns" guarantee. Returning false makes that violation + // observable to the caller instead of silently returning as if shutdown succeeded cleanly (findings + // 26/27, agent-context/reviews/full-codebase-review_2026-09-07_0900.md). + public boolean shutdown() { ExecutorService toAwait; synchronized (this) { shutdownRequested = true; @@ -110,20 +317,32 @@ public void shutdown() { } if (toAwait == null) { - return; + return true; } try { - if (!toAwait.awaitTermination(SHUTDOWN_AWAIT_SECONDS, TimeUnit.SECONDS)) { - toAwait.shutdownNow(); - // Give the forced cancellation a real chance to converge — returning immediately after - // shutdownNow() would still let a task caught mid-run touch shared state after this - // method returns, the exact guarantee this method exists to provide. - toAwait.awaitTermination(SHUTDOWN_AWAIT_SECONDS, TimeUnit.SECONDS); + if (toAwait.awaitTermination(shutdownAwaitSeconds, TimeUnit.SECONDS)) { + return true; } + + toAwait.shutdownNow(); + // Give the forced cancellation a real chance to converge — returning immediately after + // shutdownNow() would still let a task caught mid-run touch shared state after this + // method returns, the exact guarantee this method exists to provide. + if (toAwait.awaitTermination(shutdownAwaitSeconds, TimeUnit.SECONDS)) { + return true; + } + + LOGGER.warn("ReactiveQueue shutdown could not confirm all in-flight tasks stopped within {}s of " + + "shutdownNow(); a straggler task ignored interruption and may still be running, and could " + + "observe or mutate shared state after this shutdown() call returns", shutdownAwaitSeconds); + return false; } catch (InterruptedException e) { Thread.currentThread().interrupt(); toAwait.shutdownNow(); + LOGGER.warn("Interrupted while awaiting ReactiveQueue shutdown; could not confirm all in-flight " + + "tasks stopped before returning"); + return false; } } diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/PlayerIds.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/PlayerIds.java new file mode 100644 index 0000000..5f0e0c5 --- /dev/null +++ b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/PlayerIds.java @@ -0,0 +1,13 @@ +package com.tpwalke2.bluemapsignmarkers.core.signs; + +// Sentinel for "no player id known" - a live sign edit came from a hook with no Player in scope (a +// dye/ink-sac/glow-ink-sac click via SignBlockEntityInject.onUpdateText, or a sign loading via +// BlueMapSignMarkersMod.onBlockEntityLoad). Deliberately a separate constant from WorldMap.UNKNOWN +// (a different sentinel: no dimension/world known) even though both currently hold the same string - +// that value must stay "unknown" regardless, since it's already persisted as a real playerId in +// existing save files and SignManager.addOrUpdateSign compares against it by equality. +public class PlayerIds { + public static final String UNKNOWN = "unknown"; + + private PlayerIds() {} +} diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/SignEntryHelper.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/SignEntryHelper.java index d1c97a2..95ef353 100644 --- a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/SignEntryHelper.java +++ b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/SignEntryHelper.java @@ -38,6 +38,16 @@ public static String getLabel(SignEntry signEntry) { return signEntry.frontText().label(); } + var frontPrefix = signEntry.frontText().prefix(); + var backPrefix = signEntry.backText().prefix(); + + // Front and back matched different marker groups: the marker belongs to the front's group + // (see getPrefix), so a blank front label must not fall back to the back's label - that + // label belongs to a group the marker doesn't represent. + if (frontPrefix != null && backPrefix != null && !frontPrefix.equals(backPrefix)) { + return ""; + } + return signEntry.backText().label().isBlank() ? "" : signEntry.backText().label(); } diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/SignLinesParser.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/SignLinesParser.java index 4c030d0..94314f4 100644 --- a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/SignLinesParser.java +++ b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/SignLinesParser.java @@ -19,6 +19,17 @@ public class SignLinesParser { private static final Pattern INVISIBLE_WHITESPACE_AT_EDGES = Pattern.compile("^[\\s\\u00A0\\u200B\\u3000]+|[\\s\\u00A0\\u200B\\u3000]+$"); + // Vanilla sign editing fits far fewer characters per line than this - a generous cap, not a + // mirror of any exact client-side constant. A REGEX marker group's prefix pattern runs against + // raw, player-controlled sign text via line.matches(...); an admin-configured pattern can hit + // catastrophic backtracking on a long enough adversarial line (e.g. a sign edited via + // commands/NBT to bypass the client's width limit). Capping length here bounds that blowup for + // the realistic case (a short, accidentally-pathological prefix pattern) without eliminating it + // for a deliberately-adversarial admin-authored pattern (e.g. several unbounded capturing groups + // in a row), which is an accepted residual risk - see + // docs/adr/0005-redos-mitigation-length-cap-only.md. + private static final int MAX_LINE_LENGTH = 100; + private enum ParseStates { START, HAS_MARKER_TYPE, @@ -60,7 +71,7 @@ public SignLinesParseResult parse(String[] lines) { var context = new ParsingContext(); for (String line : lines) { - line = trimLine(line); + line = trimLine(truncateLine(line)); if (state == ParseStates.START) { state = processStartState(line, context, markerGroups); } else if (state == ParseStates.HAS_MARKER_TYPE) { @@ -77,6 +88,15 @@ private static String trimLine(String line) { return INVISIBLE_WHITESPACE_AT_EDGES.matcher(line).replaceAll(""); } + private static String truncateLine(String line) { + if (line.length() <= MAX_LINE_LENGTH) { + return line; + } + + int end = Character.isHighSurrogate(line.charAt(MAX_LINE_LENGTH - 1)) ? MAX_LINE_LENGTH - 1 : MAX_LINE_LENGTH; + return line.substring(0, end); + } + private static ParseStates processStartState( String line, ParsingContext context, diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/SignManager.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/SignManager.java index fe9994d..9e372ec 100644 --- a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/SignManager.java +++ b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/SignManager.java @@ -1,8 +1,8 @@ package com.tpwalke2.bluemapsignmarkers.core.signs; import com.tpwalke2.bluemapsignmarkers.Constants; +import com.tpwalke2.bluemapsignmarkers.common.SafeCall; import com.tpwalke2.bluemapsignmarkers.config.ConfigManager; -import com.tpwalke2.bluemapsignmarkers.core.WorldMap; import com.tpwalke2.bluemapsignmarkers.core.bluemap.BlueMapAPIConnector; import com.tpwalke2.bluemapsignmarkers.core.bluemap.IResetHandler; import com.tpwalke2.bluemapsignmarkers.core.bluemap.actions.ActionFactory; @@ -41,11 +41,11 @@ private static SignManager getInstance() { private static final Logger LOGGER = LoggerFactory.getLogger(Constants.MOD_ID); public static void addOrUpdate(SignEntry signEntry) { - getInstance().addOrUpdateSign(signEntry); + SafeCall.run("SignManager.addOrUpdate", () -> getInstance().addOrUpdateSign(signEntry)); } public static void remove(SignEntryKey key) { - getInstance().removeByKey(key); + SafeCall.run("SignManager.remove", () -> getInstance().removeByKey(key)); } public static List getAll() { @@ -128,7 +128,7 @@ private synchronized void addOrUpdateSign(SignEntry signEntry) { ? signEntry : new SignEntry( key, - WorldMap.UNKNOWN.equals(signEntry.playerId()) ? existing.playerId() : signEntry.playerId(), + PlayerIds.UNKNOWN.equals(signEntry.playerId()) ? existing.playerId() : signEntry.playerId(), signEntry.frontText(), signEntry.backText(), existing.createdAtMillis(), @@ -196,13 +196,20 @@ public void reset() { reloadConfig(); } - // synchronized (same monitor as addOrUpdateSign/removeByKey above) so the whole swap-config-then-diff - // sequence is one atomic step relative to live sign edits/removals arriving from the mixins on the - // server thread. IResetHandler.reset() fires on whatever thread BlueMapAPI.onEnable runs on, not - // necessarily the server thread, so without this a live edit could land mid-diff and get clobbered by - // a stale dispatch, or a sign removed mid-diff could be silently re-added. dispatch() only enqueues - // onto ReactiveQueue (no blocking BlueMap API work happens under this lock), so this doesn't introduce - // hot-path contention the way locking around processMarkerAction would. + // Only the config swap + phase 1 reparse run under the monitor (same one addOrUpdateSign/removeByKey + // use) - see the phase 1/phase 2 split below. That's the minimum needed to keep IResetHandler.reset() + // (which can fire on any thread, not necessarily the server thread) from racing a live edit: a sign + // landing mid-swap-or-reparse could otherwise get clobbered by a stale dispatch, or a sign removed + // mid-reparse could be silently re-added. Phase 2 - the expensive part, an O(n) membership + // filter/sort per LINE/SHAPE/EXTRUDE sign, O(n^2) total across a reload - runs unlocked, so it no + // longer blocks every concurrent sign edit/removal from the mixins for the reload's full duration (see + // .scratch/concurrency-pass-2026-09/issues/05-signmanager-reloadconfig-lock-contention.md). A sign + // edited concurrently during phase 2 is not clobbered: phase 2 reads `signCache` fresh (never mutated + // by phase 2 itself) for both its own transitions and LINE/SHAPE/EXTRUDE membership resolution, so it + // can only race a concurrent edit's own independent dispatch for the same key or the same line/shape - + // both are best-effort idempotent set/remove actions applied through ReactiveQueue, which already gives + // no cross-dispatch ordering guarantee (see dispatchTransition), so this doesn't introduce a new class + // of risk, only widens an existing one to a rarer window. // // signCache/chunkIndex are deliberately NOT cleared here (unlike a naive clear-and-replay): a marker's // id can be content-keyed (a LINE marker's id is "line:" + label) rather than position-keyed, so a @@ -211,43 +218,57 @@ public void reset() { // and nothing ever explicitly removes the old one. Diffing each sign's representation under the old vs. // new config and running that pair through the same transition table as a live edit dispatches an // explicit leave-effect for the old representation whenever it differs, so no id is ever left behind. - private synchronized void reloadConfig() { + private void reloadConfig() { LOGGER.info("Reloading marker group configuration..."); - var oldPrefixGroupMap = runtimeConfig.prefixGroupMap(); - ConfigManager.reload(); - SignHelper.reloadParser(); - runtimeConfig = buildRuntimeConfig(); - blueMapAPIConnector.clearMarkerSetsCache(); - - var newConfig = runtimeConfig; - var allSigns = getAllSigns(); - - // Phase 1: reparse every entry against the new config and land it in signCache before dispatching - // anything. LINE transitions look up a line's current membership via the allSignsSupplier passed - // to dispatchTransition below; if reparsing and dispatching were interleaved in one pass, that - // supplier would see a different, partially-reparsed membership set on each iteration, so two - // signs joining the same line under a prefix change could enqueue conflicting intermediate - // transitions for the same line id - and since ReactiveQueue gives no ordering guarantee between - // them, BlueMap could apply them out of order and leave the line absent. Finishing every reparse - // first means every dispatch in phase 2 sees the final, fully-reparsed membership set. - var oldReps = new HashMap(); - for (SignEntry entry : allSigns) { - oldReps.put(entry.key(), SignTransitionResolver.computeRepresentation(entry, oldPrefixGroupMap)); - - // Self-heal a sign whose representation drifted from its cached parse (e.g. a REGEX group's - // prefix text was edited) by reparsing from the raw sign text under the new config, rather - // than trusting the stale cached SignLinesParseResult as an identity key - see - // agent-context/plans/stale-prefix-orphaned-signs-fix.md. Entries with no raw text (migrated - // pre-V5) fall back to today's behavior: diff the cached parse as-is. - var reparsed = safeReparseFromRawLines(entry, newConfig.parser()); - if (reparsed != entry) { - signCache.put(reparsed.key(), reparsed); + RuntimeConfig newConfig; + HashMap oldReps; + + synchronized (this) { + var oldPrefixGroupMap = runtimeConfig.prefixGroupMap(); + + ConfigManager.reload(); + SignHelper.reloadParser(); + newConfig = buildRuntimeConfig(); + runtimeConfig = newConfig; + blueMapAPIConnector.clearMarkerSetsCache(); + + var allSigns = getAllSigns(); + + // Phase 1: reparse every entry against the new config and land it in signCache before + // dispatching anything. LINE transitions look up a line's current membership via the + // allSignsSupplier passed to dispatchTransition below; if reparsing and dispatching were + // interleaved in one pass, that supplier would see a different, partially-reparsed membership + // set on each iteration, so two signs joining the same line under a prefix change could + // enqueue conflicting intermediate transitions for the same line id - and since ReactiveQueue + // gives no ordering guarantee between them, BlueMap could apply them out of order and leave + // the line absent. Finishing every reparse first means every dispatch in phase 2 sees the + // final, fully-reparsed membership set. + oldReps = new HashMap<>(); + for (SignEntry entry : allSigns) { + oldReps.put(entry.key(), SignTransitionResolver.computeRepresentation(entry, oldPrefixGroupMap)); + + // Self-heal a sign whose representation drifted from its cached parse (e.g. a REGEX + // group's prefix text was edited) by reparsing from the raw sign text under the new + // config, rather than trusting the stale cached SignLinesParseResult as an identity key - + // see agent-context/plans/stale-prefix-orphaned-signs-fix.md. Entries with no raw text + // (migrated pre-V5) fall back to today's behavior: diff the cached parse as-is. + var reparsed = safeReparseFromRawLines(entry, newConfig.parser()); + if (reparsed != entry) { + signCache.put(reparsed.key(), reparsed); + } } } - // Phase 2: cache is now fully reparsed, so dispatch each entry's transition against a consistent - // final state. + // Phase 2: dispatch each entry's transition. Deliberately unlocked - see the method comment above. + // allSignsSupplier reads signCache live (via this::getAllSigns) rather than a snapshot frozen at + // the end of phase 1: a snapshot can go stale mid-phase-2 when a sign is concurrently + // added/removed/edited (e.g. removeByKey dropping a line's other member), and LINE/SHAPE/EXTRUDE + // membership resolution (LineGroupResolver.members et al.) would then recompute a marker against + // membership that no longer matches signCache - e.g. resurrecting a line member that a concurrent + // removeByKey had just independently dispatched a remove for. Reading live costs an extra + // signCache.values() copy per multi-point dispatch instead of one snapshot copy for the whole + // phase, but that's the same cost every live sign edit already pays via dispatchTransition. for (var keyAndOldRep : oldReps.entrySet()) { var key = keyAndOldRep.getKey(); var current = signCache.get(key); diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/SignTransitionResolver.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/SignTransitionResolver.java index b78fc79..16e61cc 100644 --- a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/SignTransitionResolver.java +++ b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/SignTransitionResolver.java @@ -11,11 +11,16 @@ import org.slf4j.LoggerFactory; import java.util.ArrayList; +import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.function.Supplier; +import static com.tpwalke2.bluemapsignmarkers.core.markers.MultiPointGroupThresholds.EXTRUDE_MIN_MEMBERS; +import static com.tpwalke2.bluemapsignmarkers.core.markers.MultiPointGroupThresholds.LINE_MIN_MEMBERS; +import static com.tpwalke2.bluemapsignmarkers.core.markers.MultiPointGroupThresholds.SHAPE_MIN_MEMBERS; + public class SignTransitionResolver { private static final Logger LOGGER = LoggerFactory.getLogger(Constants.MOD_ID); @@ -100,7 +105,7 @@ static MarkerAction computeTransitionAction( } return actionFactory.createUpdatePOIAction(key.x(), key.y(), key.z(), key.parentMap(), newRep.label(), newRep.detail(), newRep.group()); } - return actionFactory.createChangeGroupPOIAction(key.x(), key.y(), key.z(), key.parentMap(), newRep.label(), newRep.detail(), oldRep.group(), newRep.group()); + return actionFactory.createGroupTransitionPOIAction(key.x(), key.y(), key.z(), key.parentMap(), newRep.label(), newRep.detail(), oldRep.group(), newRep.group()); } // Same-group-and-label recompute for either multi-point type (LINE↔LINE or SHAPE↔SHAPE); sameGroupAndLabel @@ -134,9 +139,9 @@ static MarkerAction computeTransitionAction( private static MarkerAction leaveEffect(Supplier> allSignsSupplier, SignEntryKey key, Representation rep, ActionFactory actionFactory, Map currentPrefixGroupMap) { return switch (rep.group().type()) { case POI -> actionFactory.createRemovePOIAction(key.x(), key.y(), key.z(), key.parentMap(), rep.group()); - case LINE -> lineLeaveAction(allSignsSupplier, key.parentMap(), rep, actionFactory, currentPrefixGroupMap); - case SHAPE -> shapeLeaveAction(allSignsSupplier, key.parentMap(), rep, actionFactory, currentPrefixGroupMap); - case EXTRUDE -> extrudeLeaveAction(allSignsSupplier, key.parentMap(), rep, actionFactory, currentPrefixGroupMap); + case LINE -> multiPointLeaveAction(allSignsSupplier, key.parentMap(), rep, actionFactory, currentPrefixGroupMap, LineGroupResolver::members, LINE_MIN_MEMBERS, MarkerGroupType.LINE); + case SHAPE -> multiPointLeaveAction(allSignsSupplier, key.parentMap(), rep, actionFactory, currentPrefixGroupMap, ShapeGroupResolver::members, SHAPE_MIN_MEMBERS, MarkerGroupType.SHAPE); + case EXTRUDE -> multiPointLeaveAction(allSignsSupplier, key.parentMap(), rep, actionFactory, currentPrefixGroupMap, ExtrudeGroupResolver::members, EXTRUDE_MIN_MEMBERS, MarkerGroupType.EXTRUDE); }; } @@ -160,118 +165,65 @@ private static boolean groupIdentityObsolete(Representation rep, Map> allSignsSupplier, SignEntryKey key, Representation rep, ActionFactory actionFactory, boolean sameGroupRecompute) { return switch (rep.group().type()) { case POI -> actionFactory.createAddPOIAction(key.x(), key.y(), key.z(), key.parentMap(), rep.label(), rep.detail(), rep.group()); - case LINE -> lineJoinAction(allSignsSupplier, key.parentMap(), rep, actionFactory, sameGroupRecompute); - case SHAPE -> shapeJoinAction(allSignsSupplier, key.parentMap(), rep, actionFactory, sameGroupRecompute); - case EXTRUDE -> extrudeJoinAction(allSignsSupplier, key.parentMap(), rep, actionFactory, sameGroupRecompute); + case LINE -> multiPointJoinAction(allSignsSupplier, key.parentMap(), rep, actionFactory, sameGroupRecompute, LineGroupResolver::members, LINE_MIN_MEMBERS, MarkerGroupType.LINE); + case SHAPE -> multiPointJoinAction(allSignsSupplier, key.parentMap(), rep, actionFactory, sameGroupRecompute, ShapeGroupResolver::members, SHAPE_MIN_MEMBERS, MarkerGroupType.SHAPE); + case EXTRUDE -> multiPointJoinAction(allSignsSupplier, key.parentMap(), rep, actionFactory, sameGroupRecompute, ExtrudeGroupResolver::members, EXTRUDE_MIN_MEMBERS, MarkerGroupType.EXTRUDE); }; } - // Recomputes a line group including the current sign (it must already be in signCache under this - // group/label by the time this is called). Dispatches Set once ≥2 members exist; below that the line - // is still incomplete and nothing is dispatched. sameGroupRecompute forces isFirstAppearance=false, - // since it's used both for same-group/label recomputes (only reachable at ≥2 members if a marker - // already existed) and for reload-forced recreates (isFirstAppearance is log-only there, so the - // false value is harmless either way). - private static MarkerAction lineJoinAction(Supplier> allSignsSupplier, String parentMap, Representation rep, ActionFactory actionFactory, boolean sameGroupRecompute) { - var members = LineGroupResolver.members(allSignsSupplier.get(), parentMap, rep.group().prefix(), rep.label()); - if (members.size() < 2) return null; - - var isFirstAppearance = !sameGroupRecompute && members.size() == 2; - var colors = ColorResolver.resolve(members, rep.group()); - return actionFactory.createSetLineAction(parentMap, rep.group(), rep.label(), rep.detail(), toPoints(members), colors.lineColor(), isFirstAppearance); - } - - // Recomputes a line group excluding the current sign (it must already be removed from/no longer - // present in signCache under this group/label by the time this is called). Dispatches Set if ≥2 - // members remain, Remove if it drops below 2 and a marker existed before (i.e. exactly 1 remains - - // meaning there were 2 before), or nothing if there was never a marker to begin with (0 remain). - private static MarkerAction lineLeaveAction(Supplier> allSignsSupplier, String parentMap, Representation rep, ActionFactory actionFactory, Map currentPrefixGroupMap) { - if (groupIdentityObsolete(rep, currentPrefixGroupMap)) { - return actionFactory.createRemoveLineAction(parentMap, rep.group(), rep.label()); - } - - var members = LineGroupResolver.members(allSignsSupplier.get(), parentMap, rep.group().prefix(), rep.label()); - - if (members.size() >= 2) { - var colors = ColorResolver.resolve(members, rep.group()); - return actionFactory.createSetLineAction(parentMap, rep.group(), rep.label(), rep.detail(), toPoints(members), colors.lineColor(), false); - } - - if (members.size() == 1) { - return actionFactory.createRemoveLineAction(parentMap, rep.group(), rep.label()); - } - - return null; + @FunctionalInterface + private interface GroupResolver { + List members(Collection allSigns, String parentMap, String prefix, String label); } - private static List toPoints(List members) { - return members.stream().map(e -> new LinePoint(e.key().x(), e.key().y(), e.key().z())).toList(); + // Only LINE has no fill (a stroke-only marker); SHAPE/EXTRUDE both anchor a floor/ceiling from their + // members' Y range and so need ColorResolver's fillColor alongside its lineColor. + private static boolean hasFill(MarkerGroupType kind) { + return kind != MarkerGroupType.LINE; } - // SHAPE mirrors LINE's join/leave/recompute shape (see lineJoinAction/lineLeaveAction above), but at a - // 3-member render threshold instead of 2 - see docs/adr/0002-shape-duplicates-line-pattern.md. Points - // stay ordered by createdAtMillis (toPoints/ShapeGroupResolver.members) purely for polygon vertex order; - // the shape's Y anchor (BlueMapAPIConnector.setShapeMarker) is the tallest member, not the oldest. - private static final int SHAPE_MIN_MEMBERS = 3; - - private static MarkerAction shapeJoinAction(Supplier> allSignsSupplier, String parentMap, Representation rep, ActionFactory actionFactory, boolean sameGroupRecompute) { - var members = ShapeGroupResolver.members(allSignsSupplier.get(), parentMap, rep.group().prefix(), rep.label()); - if (members.size() < SHAPE_MIN_MEMBERS) return null; - - var isFirstAppearance = !sameGroupRecompute && members.size() == SHAPE_MIN_MEMBERS; + // Recomputes a LINE/SHAPE/EXTRUDE group including the current sign (it must already be in signCache + // under this group/label by the time this is called). Dispatches Set once the kind's member threshold + // is met; below that the marker is still incomplete and nothing is dispatched. sameGroupRecompute + // forces isFirstAppearance=false, since it's used both for same-group/label recomputes (only reachable + // at/above threshold if a marker already existed) and for reload-forced recreates (isFirstAppearance is + // log-only there, so the false value is harmless either way). + private static MarkerAction multiPointJoinAction(Supplier> allSignsSupplier, String parentMap, Representation rep, ActionFactory actionFactory, boolean sameGroupRecompute, GroupResolver resolver, int minMembers, MarkerGroupType kind) { + var members = resolver.members(allSignsSupplier.get(), parentMap, rep.group().prefix(), rep.label()); + if (members.size() < minMembers) return null; + + var isFirstAppearance = !sameGroupRecompute && members.size() == minMembers; var colors = ColorResolver.resolve(members, rep.group()); - return actionFactory.createSetShapeAction(parentMap, rep.group(), rep.label(), rep.detail(), toPoints(members), colors.lineColor(), colors.fillColor(), isFirstAppearance); + return actionFactory.createSetMultiPointAction(parentMap, rep.group(), rep.label(), rep.detail(), toPoints(members), colors.lineColor(), hasFill(kind) ? colors.fillColor() : null, isFirstAppearance); } - private static MarkerAction shapeLeaveAction(Supplier> allSignsSupplier, String parentMap, Representation rep, ActionFactory actionFactory, Map currentPrefixGroupMap) { + // Recomputes a LINE/SHAPE/EXTRUDE group excluding the current sign (it must already be removed + // from/no longer present in signCache under this group/label by the time this is called). Dispatches + // Set if the kind's member threshold is still met, Remove if it drops one below that (i.e. a marker + // existed before), or nothing if there was never a marker to begin with. + private static MarkerAction multiPointLeaveAction(Supplier> allSignsSupplier, String parentMap, Representation rep, ActionFactory actionFactory, Map currentPrefixGroupMap, GroupResolver resolver, int minMembers, MarkerGroupType kind) { if (groupIdentityObsolete(rep, currentPrefixGroupMap)) { - return actionFactory.createRemoveShapeAction(parentMap, rep.group(), rep.label()); + return actionFactory.createRemoveMultiPointAction(parentMap, rep.group(), rep.label()); } - var members = ShapeGroupResolver.members(allSignsSupplier.get(), parentMap, rep.group().prefix(), rep.label()); + var members = resolver.members(allSignsSupplier.get(), parentMap, rep.group().prefix(), rep.label()); - if (members.size() >= SHAPE_MIN_MEMBERS) { + if (members.size() >= minMembers) { var colors = ColorResolver.resolve(members, rep.group()); - return actionFactory.createSetShapeAction(parentMap, rep.group(), rep.label(), rep.detail(), toPoints(members), colors.lineColor(), colors.fillColor(), false); + return actionFactory.createSetMultiPointAction(parentMap, rep.group(), rep.label(), rep.detail(), toPoints(members), colors.lineColor(), hasFill(kind) ? colors.fillColor() : null, false); } - if (members.size() == SHAPE_MIN_MEMBERS - 1) { - return actionFactory.createRemoveShapeAction(parentMap, rep.group(), rep.label()); + if (members.size() == minMembers - 1) { + return actionFactory.createRemoveMultiPointAction(parentMap, rep.group(), rep.label()); } return null; } - // EXTRUDE mirrors SHAPE's join/leave/recompute shape (see shapeJoinAction/shapeLeaveAction above) at the - // same 3-member render threshold - the floor/ceiling Y values are computed from the ordered points at - // dispatch time (BlueMapAPIConnector.setExtrudeMarker), not here. - private static final int EXTRUDE_MIN_MEMBERS = 3; - - private static MarkerAction extrudeJoinAction(Supplier> allSignsSupplier, String parentMap, Representation rep, ActionFactory actionFactory, boolean sameGroupRecompute) { - var members = ExtrudeGroupResolver.members(allSignsSupplier.get(), parentMap, rep.group().prefix(), rep.label()); - if (members.size() < EXTRUDE_MIN_MEMBERS) return null; - - var isFirstAppearance = !sameGroupRecompute && members.size() == EXTRUDE_MIN_MEMBERS; - var colors = ColorResolver.resolve(members, rep.group()); - return actionFactory.createSetExtrudeAction(parentMap, rep.group(), rep.label(), rep.detail(), toPoints(members), colors.lineColor(), colors.fillColor(), isFirstAppearance); - } - - private static MarkerAction extrudeLeaveAction(Supplier> allSignsSupplier, String parentMap, Representation rep, ActionFactory actionFactory, Map currentPrefixGroupMap) { - if (groupIdentityObsolete(rep, currentPrefixGroupMap)) { - return actionFactory.createRemoveExtrudeAction(parentMap, rep.group(), rep.label()); - } - - var members = ExtrudeGroupResolver.members(allSignsSupplier.get(), parentMap, rep.group().prefix(), rep.label()); - - if (members.size() >= EXTRUDE_MIN_MEMBERS) { - var colors = ColorResolver.resolve(members, rep.group()); - return actionFactory.createSetExtrudeAction(parentMap, rep.group(), rep.label(), rep.detail(), toPoints(members), colors.lineColor(), colors.fillColor(), false); - } - - if (members.size() == EXTRUDE_MIN_MEMBERS - 1) { - return actionFactory.createRemoveExtrudeAction(parentMap, rep.group(), rep.label()); - } - - return null; + // Points stay ordered by createdAtMillis (the GroupResolver.members contract) purely for polygon/line + // vertex order; a SHAPE/EXTRUDE's Y anchor (BlueMapAPIConnector.setShapeMarker/setExtrudeMarker) is the + // tallest member, not the oldest. + private static List toPoints(List members) { + return members.stream().map(e -> new LinePoint(e.key().x(), e.key().y(), e.key().z())).toList(); } } diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/persistence/LegacySignFileMigrator.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/persistence/LegacySignFileMigrator.java index 1c16227..70fd1ef 100644 --- a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/persistence/LegacySignFileMigrator.java +++ b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/persistence/LegacySignFileMigrator.java @@ -15,6 +15,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; +import java.util.HashSet; import java.util.List; public class LegacySignFileMigrator { @@ -57,13 +58,14 @@ public static List migrate(String legacyPath, Path storageRoot, Marke } var entryList = Arrays.asList(signEntries); - RegionShardedSignEntryWriter.write(storageRoot, entryList, gson); + var writeSucceeded = RegionShardedSignEntryWriter.write(storageRoot, entryList, gson); // Back up the legacy file once migration is complete (or immediately if it contained zero entries). - var expectedRegionFiles = SignRegionPartitioner.partition(entryList).keySet().stream() - .map(key -> storageRoot.resolve(key.relativeFilePath())) - .toList(); - var migrationWroteAllRegions = entryList.isEmpty() || expectedRegionFiles.stream().allMatch(Files::exists); + // Content-verifies rather than just checking file existence: a region file that exists but is + // truncated/corrupt must still block finalizing the migration, since otherwise the legacy backup + // finalizes over genuinely lost data. + var migrationWroteAllRegions = entryList.isEmpty() + || (writeSucceeded && regionFilesRoundTripCleanly(storageRoot, entryList, markerGroups, gson)); if (migrationWroteAllRegions) { FileUtils.moveToBackup(legacyPath, ".migrated", "legacy markers file"); @@ -75,4 +77,48 @@ public static List migrate(String legacyPath, Path storageRoot, Marke return entryList; } + + // Round-trip parses each region file the write pass produced (rather than just checking it exists) so + // a truncated/corrupt region file - which loads as "no entries" - can't slip past verification and + // let the legacy file get backed up over genuinely lost data. Compares the full parsed entry set + // against what was expected to be written, not just its size - matching lengths with different/altered + // content (e.g. valid-but-corrupted JSON) would otherwise pass and retire the legacy source over + // altered data. SignEntry is a record, so set equality is a structural content comparison; a Set + // (rather than a positional list compare) is used since the writer's on-disk ordering isn't guaranteed + // to match partition()'s insertion order. + // Visible for testing: lets tests exercise this against a region file corrupted after being written, + // which migrate() itself has no seam to do (it writes and verifies in the same call). + static boolean regionFilesRoundTripCleanly( + Path storageRoot, List entryList, MarkerGroup[] markerGroups, Gson gson) { + var partitions = SignRegionPartitioner.partition(entryList); + + for (var partition : partitions.entrySet()) { + Path filePath; + try { + filePath = storageRoot.resolve(partition.getKey().relativeFilePath()); + } catch (IllegalArgumentException e) { + LOGGER.error("Failed to resolve storage path for region key {} while verifying migration", partition.getKey(), e); + return false; + } + + String content; + try { + content = Files.readString(filePath, StandardCharsets.UTF_8); + } catch (IOException e) { + LOGGER.error("Region file {} is missing or unreadable after migration write", filePath, e); + return false; + } + + var parsed = VersionedFileSignEntryLoader.loadSignEntries(filePath.toString(), content, markerGroups, gson); + var expected = partition.getValue(); + if (parsed == null || parsed.length != expected.size() || !new HashSet<>(Arrays.asList(parsed)).equals(new HashSet<>(expected))) { + LOGGER.error( + "Region file {} failed to round-trip parse after migration write (expected {} entries matching {}, got {})", + filePath, expected.size(), expected, parsed == null ? "none" : Arrays.toString(parsed)); + return false; + } + } + + return true; + } } diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/persistence/RegionShardedSignEntryWriter.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/persistence/RegionShardedSignEntryWriter.java index 257c212..5ca78d3 100644 --- a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/persistence/RegionShardedSignEntryWriter.java +++ b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/persistence/RegionShardedSignEntryWriter.java @@ -2,6 +2,7 @@ import com.google.gson.Gson; import com.tpwalke2.bluemapsignmarkers.Constants; +import com.tpwalke2.bluemapsignmarkers.common.FileUtils; import com.tpwalke2.bluemapsignmarkers.core.signs.SignEntry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -22,48 +23,62 @@ public class RegionShardedSignEntryWriter { private RegionShardedSignEntryWriter() { } -public static void write(Path storageRoot, List signEntries, Gson gson) { - var partitions = SignRegionPartitioner.partition(signEntries); + // Returns true if every region file wrote cleanly (callers use this instead of independently re-deriving + // the same success/failure by re-partitioning and re-stating every file, which can drift from what + // actually happened here - see LegacySignFileMigrator). + public static boolean write(Path storageRoot, List signEntries, Gson gson) { + var partitions = SignRegionPartitioner.partition(signEntries); - var writtenFiles = new HashSet(); - var hadWriteFailures = false; + var writtenFiles = new HashSet(); + var hadWriteFailures = false; - for (var partition : partitions.entrySet()) { - Path filePath; - try { - filePath = storageRoot.resolve(partition.getKey().relativeFilePath()); - } catch (IllegalArgumentException e) { - hadWriteFailures = true; - LOGGER.error("Failed to resolve storage path for region key {}; skipping this partition", partition.getKey(), e); - continue; + for (var partition : partitions.entrySet()) { + Path filePath; + try { + filePath = storageRoot.resolve(partition.getKey().relativeFilePath()); + } catch (IllegalArgumentException e) { + hadWriteFailures = true; + LOGGER.error("Failed to resolve storage path for region key {}; skipping this partition", partition.getKey(), e); + continue; + } + + if (writeRegionFile(filePath, partition.getValue(), gson)) { + writtenFiles.add(filePath); + } else { + hadWriteFailures = true; + } } - if (writeRegionFile(filePath, partition.getValue(), gson)) { - writtenFiles.add(filePath); + if (!hadWriteFailures) { + quarantineStaleRegionFiles(storageRoot, writtenFiles); } else { - hadWriteFailures = true; + LOGGER.warn("One or more region files failed to write; skipping stale-file quarantine under {}", storageRoot); } - } - if (!hadWriteFailures) { - quarantineStaleRegionFiles(storageRoot, writtenFiles); - } else { - LOGGER.warn("One or more region files failed to write; skipping stale-file quarantine under {}", storageRoot); + return !hadWriteFailures; } -} -private static boolean writeRegionFile(Path filePath, List signEntries, Gson gson) { - try { - Files.createDirectories(filePath.getParent()); - var signEntryData = gson.toJson(signEntries); - var json = gson.toJson(new VersionedSignFile(SignFileVersions.V6, signEntryData)); - Files.writeString(filePath, json, StandardCharsets.UTF_8); - return true; - } catch (IOException e) { - LOGGER.error("Failed to write region file {}", filePath, e); - return false; + // Writes via a temp file in the same directory, then an atomic move into place (same pattern as + // FileUtils.copyFile), so a crash or disk-full mid-write never leaves a truncated/corrupt file sitting at + // filePath - one that load would otherwise silently treat as "no entries for that region". + private static boolean writeRegionFile(Path filePath, List signEntries, Gson gson) { + Path tempFile = null; + try { + Files.createDirectories(filePath.getParent()); + var signEntryData = gson.toJson(signEntries); + var json = gson.toJson(new VersionedSignFile(SignFileVersions.V6, signEntryData)); + tempFile = filePath.resolveSibling(filePath.getFileName() + ".tmp"); + Files.writeString(tempFile, json, StandardCharsets.UTF_8); + Files.move(tempFile, filePath, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + return true; + } catch (IOException e) { + LOGGER.error("Failed to write region file {}", filePath, e); + if (tempFile != null) { + FileUtils.deleteQuietly(tempFile); + } + return false; + } } -} // A region absent from writtenFiles may be genuinely empty, or may have failed to load at // startup - can't tell which here, so quarantine instead of delete to avoid losing real data. diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/persistence/SignProvider.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/persistence/SignProvider.java index 2e37589..a66a167 100644 --- a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/persistence/SignProvider.java +++ b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/persistence/SignProvider.java @@ -11,6 +11,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.nio.file.Files; import java.nio.file.Path; public class SignProvider { @@ -28,9 +29,15 @@ public static void loadSigns(Path storageRoot, String legacyPath) { try { var groups = ConfigManager.get().getMarkerGroups(); - var signEntries = RegionShardedSignEntryLoader.hasSignData(storageRoot) - ? RegionShardedSignEntryLoader.loadSignEntries(storageRoot, groups, GSON) - : LegacySignFileMigrator.migrate(legacyPath, storageRoot, groups, GSON); + // The legacy file's continued presence (not yet renamed to its ".migrated" backup) is what + // signals an incomplete migration - not just "no region files exist yet". A crash partway + // through a first migration can leave some region files written and others missing; re-running + // migrate() in that case re-derives every region file from the still-present legacy source + // (the actual source of truth) instead of loading the partial region-sharded state as if it + // were complete, which would permanently lose every sign not yet written at crash time. + var signEntries = Files.exists(Path.of(legacyPath)) || !RegionShardedSignEntryLoader.hasSignData(storageRoot) + ? LegacySignFileMigrator.migrate(legacyPath, storageRoot, groups, GSON) + : RegionShardedSignEntryLoader.loadSignEntries(storageRoot, groups, GSON); for (SignEntry signEntry : signEntries) { try { @@ -47,6 +54,8 @@ public static void loadSigns(Path storageRoot, String legacyPath) { public static void saveSigns(Path storageRoot) { LOGGER.info("Saving markers to {}...", storageRoot); - RegionShardedSignEntryWriter.write(storageRoot, SignManager.getAll(), GSON); + if (!RegionShardedSignEntryWriter.write(storageRoot, SignManager.getAll(), GSON)) { + LOGGER.error("One or more region files failed to save under {}; some signs may not survive a restart", storageRoot); + } } } diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/persistence/SignRegionKey.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/persistence/SignRegionKey.java index 1402fe1..f858c07 100644 --- a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/persistence/SignRegionKey.java +++ b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/persistence/SignRegionKey.java @@ -25,7 +25,12 @@ public Path relativeFilePath() { var namespaceDir = Path.of(namespace); var relativeDir = namespaceDir.resolve(rawPath).normalize(); - if (relativeDir.isAbsolute() || relativeDir.startsWith("..") || !relativeDir.startsWith(namespaceDir)) { + // getRoot() != null catches a Windows "drive-relative" path (e.g. a raw path segment starting + // with a single '\') on its own: such a path reports isAbsolute() == false, but resolve() still + // discards namespaceDir in favor of it, carrying a root component namespaceDir never had - so + // relying on isAbsolute() alone would let it slip past this guard. + if (relativeDir.getRoot() != null || relativeDir.isAbsolute() || relativeDir.startsWith("..") + || !relativeDir.startsWith(namespaceDir)) { throw new IllegalArgumentException("Unsafe dimension id for storage path: " + dimension); } diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/persistence/loaders/Version1SignEntryLoader.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/persistence/loaders/Version1SignEntryLoader.java index ba5eb32..a6ea726 100644 --- a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/persistence/loaders/Version1SignEntryLoader.java +++ b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/persistence/loaders/Version1SignEntryLoader.java @@ -52,6 +52,11 @@ public static SignEntry[] loadSignEntries( result[i] = Version6Converter.convertToV6(signEntriesV5[i]); } + // Aborts on backup failure (rather than logging and continuing, as VersionedFileSignEntryLoader's + // v2-v5 branches do) because this is the one-time legacy signs.json migration path: failing loudly + // here leaves the legacy file untouched and migration retryable on a later boot, instead of + // converting the last remaining copy of very old data with no recoverable backup if something + // then goes wrong. if (!FileUtils.createBackup(path, ".v1.bak", "markers file")) { throw new IllegalStateException( "Failed to back up markers file " + path + " before v1-to-v3 migration; aborting migration to " diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/persistence/loaders/VersionedFileSignEntryLoader.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/persistence/loaders/VersionedFileSignEntryLoader.java index 62ad84c..3ba933a 100644 --- a/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/persistence/loaders/VersionedFileSignEntryLoader.java +++ b/src/main/java/com/tpwalke2/bluemapsignmarkers/core/signs/persistence/loaders/VersionedFileSignEntryLoader.java @@ -21,6 +21,12 @@ import java.util.List; import java.util.Objects; +// Deliberately logs and continues on backup failure below (rather than aborting the whole load, as +// Version1SignEntryLoader does for the one-time legacy signs.json migration) - this loader also runs once +// per region file on every server boot, and never overwrites the file it's reading, only writes an +// optional backup copy alongside it. Aborting the whole load over one region's transient backup failure +// would risk data becoming unavailable for a reason unrelated to that data's own integrity; the region file +// itself is untouched either way, so backing it up can be retried on a later boot. public class VersionedFileSignEntryLoader { private static final Logger LOGGER = LoggerFactory.getLogger(Constants.MOD_ID); diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/mixin/AbstractBlockInject.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/mixin/AbstractBlockInject.java index 98b9c47..850d663 100644 --- a/src/main/java/com/tpwalke2/bluemapsignmarkers/mixin/AbstractBlockInject.java +++ b/src/main/java/com/tpwalke2/bluemapsignmarkers/mixin/AbstractBlockInject.java @@ -1,5 +1,6 @@ package com.tpwalke2.bluemapsignmarkers.mixin; +import com.tpwalke2.bluemapsignmarkers.common.SafeCall; import com.tpwalke2.bluemapsignmarkers.core.signs.SignEntryKey; import com.tpwalke2.bluemapsignmarkers.core.signs.SignHelper; import com.tpwalke2.bluemapsignmarkers.core.signs.SignManager; @@ -23,6 +24,7 @@ public void onStateReplaced(BlockState state, CallbackInfo ci) { if (!(state.getBlock() instanceof SignBlock)) return; - SignManager.remove(new SignEntryKey(pos.getX(), pos.getY(), pos.getZ(), SignHelper.getSignParentMap(level))); + SafeCall.run("onStateReplaced", () -> + SignManager.remove(new SignEntryKey(pos.getX(), pos.getY(), pos.getZ(), SignHelper.getSignParentMap(level)))); } } diff --git a/src/main/java/com/tpwalke2/bluemapsignmarkers/mixin/SignBlockEntityInject.java b/src/main/java/com/tpwalke2/bluemapsignmarkers/mixin/SignBlockEntityInject.java index d035558..3be4eed 100644 --- a/src/main/java/com/tpwalke2/bluemapsignmarkers/mixin/SignBlockEntityInject.java +++ b/src/main/java/com/tpwalke2/bluemapsignmarkers/mixin/SignBlockEntityInject.java @@ -1,6 +1,7 @@ package com.tpwalke2.bluemapsignmarkers.mixin; -import com.tpwalke2.bluemapsignmarkers.core.WorldMap; +import com.tpwalke2.bluemapsignmarkers.common.SafeCall; +import com.tpwalke2.bluemapsignmarkers.core.signs.PlayerIds; import com.tpwalke2.bluemapsignmarkers.core.signs.SignHelper; import com.tpwalke2.bluemapsignmarkers.core.signs.SignManager; import org.spongepowered.asm.mixin.Mixin; @@ -43,9 +44,9 @@ void onTryChangeText( List lines, CallbackInfo cir) { bluemapsignmarkers$inUpdateSignText = false; - SignManager.addOrUpdate(SignHelper.createSignEntry( + SafeCall.run("onTryChangeText", () -> SignManager.addOrUpdate(SignHelper.createSignEntry( (SignBlockEntity) (Object) this, - player.getStringUUID())); + player.getStringUUID()))); } // updateSignText (above) routes through this same method internally, so without the @@ -53,7 +54,7 @@ void onTryChangeText( // duplicate, idempotent recompute - for every plain text edit. This is the only hook that fires for // dye/ink-sac/glow-ink-sac application, none of which call updateSignText - see // agent-context/plans/player-marker-colors/spec.md "Detecting a dye change: mixin". No Player is - // available at this injection point, so playerId falls back to WorldMap.UNKNOWN, the same placeholder + // available at this injection point, so playerId falls back to PlayerIds.UNKNOWN, the same placeholder // BlueMapSignMarkersMod.onBlockEntityLoad uses when it has no live player context either. @Inject(method = "updateText", at = @At("RETURN")) void onUpdateText( @@ -63,8 +64,8 @@ void onUpdateText( if (!cir.getReturnValueZ()) return; if (bluemapsignmarkers$inUpdateSignText) return; - SignManager.addOrUpdate(SignHelper.createSignEntry( + SafeCall.run("onUpdateText", () -> SignManager.addOrUpdate(SignHelper.createSignEntry( (SignBlockEntity) (Object) this, - WorldMap.UNKNOWN)); + PlayerIds.UNKNOWN))); } } diff --git a/src/test/java/com/tpwalke2/bluemapsignmarkers/common/ColorUtilsTest.java b/src/test/java/com/tpwalke2/bluemapsignmarkers/common/ColorUtilsTest.java index 715b180..4e87ef2 100644 --- a/src/test/java/com/tpwalke2/bluemapsignmarkers/common/ColorUtilsTest.java +++ b/src/test/java/com/tpwalke2/bluemapsignmarkers/common/ColorUtilsTest.java @@ -64,4 +64,16 @@ void isValidHexRejectsWrongLength() { void isValidHexRejectsNonHexCharacters() { assertFalse(ColorUtils.isValidHex("#ZZZZZZ")); } + + // "-1-1-1-1" is length 8 (passes the length check) and each 2-char component parses as decimal -1 + // under radix 16 with no NumberFormatException, so a naive Integer.parseInt-only check wrongly accepts it. + @Test + void isValidHexRejectsAMinusSignInAComponent() { + assertFalse(ColorUtils.isValidHex("#-1-1-1-1")); + } + + @Test + void parseHexFallsBackToOpaqueRedForAMinusSignInAComponent() { + assertArrayEquals(new int[]{255, 0, 0, 255}, ColorUtils.parseHex("#-1-1-1-1")); + } } diff --git a/src/test/java/com/tpwalke2/bluemapsignmarkers/common/FileUtilsTest.java b/src/test/java/com/tpwalke2/bluemapsignmarkers/common/FileUtilsTest.java index 46015bf..2b6ef96 100644 --- a/src/test/java/com/tpwalke2/bluemapsignmarkers/common/FileUtilsTest.java +++ b/src/test/java/com/tpwalke2/bluemapsignmarkers/common/FileUtilsTest.java @@ -64,8 +64,11 @@ void moveToBackupDoesNothingWhenTheOriginalFileDoesNotExist(@TempDir Path tempDi assertFalse(Files.exists(tempDir.resolve("missing.txt.bak"))); } + // A caller relying on "the original is gone once moveToBackup returns" (LegacySignFileMigrator re-runs a + // full migration on every boot for as long as the legacy file still exists) would otherwise be stuck + // re-migrating forever if the original were left in place just because ".bak" was already taken. @Test - void moveToBackupDoesNothingWhenABackupAlreadyExists(@TempDir Path tempDir) throws IOException { + void moveToBackupFallsBackToANumberedNameWhenTheDefaultBackupAlreadyExists(@TempDir Path tempDir) throws IOException { var original = tempDir.resolve("original.txt"); Files.writeString(original, "original content"); var backup = tempDir.resolve("original.txt.bak"); @@ -73,8 +76,26 @@ void moveToBackupDoesNothingWhenABackupAlreadyExists(@TempDir Path tempDir) thro FileUtils.moveToBackup(original.toString(), ".bak", "test file"); - assertTrue(Files.exists(original), "the original should not be moved when a backup already exists"); - assertEquals("pre-existing backup content", Files.readString(backup)); + var secondBackup = tempDir.resolve("original.txt.bak.2"); + assertFalse(Files.exists(original), "the original must always be retired, even if the default backup path is taken"); + assertEquals("pre-existing backup content", Files.readString(backup), "an existing backup should not be overwritten"); + assertTrue(Files.exists(secondBackup)); + assertEquals("original content", Files.readString(secondBackup)); + } + + @Test + void moveToBackupKeepsNumberingWhenMultipleBackupsAlreadyExist(@TempDir Path tempDir) throws IOException { + var original = tempDir.resolve("original.txt"); + Files.writeString(original, "original content"); + Files.writeString(tempDir.resolve("original.txt.bak"), "first backup"); + Files.writeString(tempDir.resolve("original.txt.bak.2"), "second backup"); + + FileUtils.moveToBackup(original.toString(), ".bak", "test file"); + + var thirdBackup = tempDir.resolve("original.txt.bak.3"); + assertFalse(Files.exists(original)); + assertTrue(Files.exists(thirdBackup)); + assertEquals("original content", Files.readString(thirdBackup)); } // The backup destination is routed through the original file itself as a fake parent directory (a regular diff --git a/src/test/java/com/tpwalke2/bluemapsignmarkers/common/HtmlUtilsTest.java b/src/test/java/com/tpwalke2/bluemapsignmarkers/common/HtmlUtilsTest.java index d6f3bd9..5d33bf4 100644 --- a/src/test/java/com/tpwalke2/bluemapsignmarkers/common/HtmlUtilsTest.java +++ b/src/test/java/com/tpwalke2/bluemapsignmarkers/common/HtmlUtilsTest.java @@ -49,4 +49,14 @@ void toHtmlDetailConvertsConsecutiveNewlines() { void toHtmlDetailIsNoOpOnLineBreaksWhenNoneArePresent() { assertEquals("Town Hall", HtmlUtils.toHtmlDetail("Town Hall")); } + + @Test + void escapeTreatsNullAsEmptyString() { + assertEquals("", HtmlUtils.escape(null)); + } + + @Test + void toHtmlDetailTreatsNullAsEmptyString() { + assertEquals("", HtmlUtils.toHtmlDetail(null)); + } } diff --git a/src/test/java/com/tpwalke2/bluemapsignmarkers/common/SafeCallTest.java b/src/test/java/com/tpwalke2/bluemapsignmarkers/common/SafeCallTest.java new file mode 100644 index 0000000..1c45e40 --- /dev/null +++ b/src/test/java/com/tpwalke2/bluemapsignmarkers/common/SafeCallTest.java @@ -0,0 +1,32 @@ +package com.tpwalke2.bluemapsignmarkers.common; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class SafeCallTest { + + @Test + void runsTheActionWhenItSucceeds() { + var ran = new boolean[1]; + + SafeCall.run("test", () -> ran[0] = true); + + assertTrue(ran[0]); + } + + @Test + void swallowsARuntimeExceptionInsteadOfPropagatingIt() { + assertDoesNotThrow(() -> SafeCall.run("test", () -> { + throw new RuntimeException("boom"); + })); + } + + @Test + void swallowsAnErrorInsteadOfPropagatingIt() { + assertDoesNotThrow(() -> SafeCall.run("test", () -> { + throw new StackOverflowError(); + })); + } +} diff --git a/src/test/java/com/tpwalke2/bluemapsignmarkers/common/ServerPathResolverTest.java b/src/test/java/com/tpwalke2/bluemapsignmarkers/common/ServerPathResolverTest.java new file mode 100644 index 0000000..2d921c1 --- /dev/null +++ b/src/test/java/com/tpwalke2/bluemapsignmarkers/common/ServerPathResolverTest.java @@ -0,0 +1,32 @@ +package com.tpwalke2.bluemapsignmarkers.common; + +import com.tpwalke2.bluemapsignmarkers.Constants; +import org.junit.jupiter.api.Test; + +import java.nio.file.Path; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ServerPathResolverTest { + + // getWorldPath(LevelResource.ROOT) carries an unresolved trailing "." segment (see + // ServerPathResolver's own comment) - mirrored here rather than passed as an already-normalized + // Path, since that trailing "." is exactly what each method's own (mis)handling of it is tested for. + private static Path rawLevelPath(String... levelDirSegments) { + return Path.of(".", levelDirSegments).resolve("."); + } + + @Test + void resolveMarkerStorageRootNormalizesTheTrailingDotSegment() { + var result = ServerPathResolver.resolveMarkerStorageRoot(rawLevelPath("run", "myworld")); + + assertEquals(Path.of("run", Constants.MOD_ID, "myworld"), result); + } + + @Test + void resolveLegacyMarkerFilePathReproducesTheUnnormalizedFormula() { + var result = ServerPathResolver.resolveLegacyMarkerFilePath(rawLevelPath("run", "myworld")); + + assertEquals("config/" + Constants.MOD_ID + "/myworld/signs.json", result); + } +} diff --git a/src/test/java/com/tpwalke2/bluemapsignmarkers/config/ConfigManagerTest.java b/src/test/java/com/tpwalke2/bluemapsignmarkers/config/ConfigManagerTest.java index 5db524f..00b8a47 100644 --- a/src/test/java/com/tpwalke2/bluemapsignmarkers/config/ConfigManagerTest.java +++ b/src/test/java/com/tpwalke2/bluemapsignmarkers/config/ConfigManagerTest.java @@ -6,8 +6,16 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; class ConfigManagerTest { @@ -58,4 +66,61 @@ void reloadSwapsInAFreshlyLoadedConfig(@TempDir Path tempDir) throws IOException ConfigManager.reload(pathB); assertEquals("[b]", ConfigManager.get().getMarkerGroups()[0].prefix()); } + + // Documents review finding #72 (agent-context/reviews/full-codebase-review_2026-09-07_0900.md): get()'s + // "is coreConfig loaded yet?" check and its first load are now one synchronized step, so many threads + // racing to call get() before anything has loaded converge on one canonical config instance instead of + // each redundantly loading and racing over which instance wins. Same pattern as + // MarkerSetIdentifierCollectionTest's concurrentFirstTimeCallersForTheSameComboConvergeOnOneIdentifierInstance. + @Test + void concurrentFirstTimeCallersConvergeOnOneConfigInstance(@TempDir Path tempDir) throws Exception { + var path = tempDir.resolve("BMSM-Core.json"); + Files.writeString(path, """ + { "markerGroups": [ { "prefix": "[custom]", "name": "Custom Group" } ] } + """); + + final int threadCount = 8; + final int iterations = 500; + + var executor = Executors.newFixedThreadPool(threadCount); + try { + for (int i = 0; i < iterations; i++) { + ConfigManager.resetForTesting(); + var ready = new CountDownLatch(threadCount); + var go = new CountDownLatch(1); + var results = Collections.synchronizedList(new ArrayList()); + + var futures = new ArrayList>(); + for (int t = 0; t < threadCount; t++) { + futures.add(executor.submit(() -> { + ready.countDown(); + awaitUninterruptibly(go); + results.add(ConfigManager.get(path)); + })); + } + + assertTrue(ready.await(5, TimeUnit.SECONDS), "iteration " + i + ": a task failed to start in time"); + go.countDown(); + for (var future : futures) { + future.get(5, TimeUnit.SECONDS); + } + + var distinctInstances = Collections.newSetFromMap(new IdentityHashMap()); + distinctInstances.addAll(results); + assertEquals(1, distinctInstances.size(), + "iteration " + i + ": concurrent first-time callers should converge on one config instance, got " + + distinctInstances.size()); + } + } finally { + executor.shutdownNow(); + } + } + + private static void awaitUninterruptibly(CountDownLatch latch) { + try { + latch.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } } diff --git a/src/test/java/com/tpwalke2/bluemapsignmarkers/config/ConfigProviderTest.java b/src/test/java/com/tpwalke2/bluemapsignmarkers/config/ConfigProviderTest.java index 44556e7..903b527 100644 --- a/src/test/java/com/tpwalke2/bluemapsignmarkers/config/ConfigProviderTest.java +++ b/src/test/java/com/tpwalke2/bluemapsignmarkers/config/ConfigProviderTest.java @@ -522,6 +522,23 @@ void saveAndLoadConfigRoundTripNonAsciiMarkerGroupNamesThroughUtf8(@TempDir Path assertEquals("地図マーカー éèà", reloaded.getMarkerGroups()[0].name()); } + @Test + void aFailedSaveLeavesNoPartialFileAtTheFinalPathAndCleansUpItsTempFile(@TempDir Path tempDir) throws IOException { + var path = tempDir.resolve("BMSM-Core.json"); + Files.writeString(path, "{ \"markerGroups\": [] }"); + // Occupies the final path with a directory, so the save's ATOMIC_MOVE onto it must fail - standing + // in for a crash/interrupt partway through the write without actually killing the JVM mid-test. + Files.delete(path); + Files.createDirectory(path); + + ConfigProvider.saveConfig(new BMSMConfigV2(), path); + + assertTrue(Files.isDirectory(path), "a failed save must never leave a partial file at the final path"); + assertFalse( + Files.exists(path.resolveSibling(path.getFileName() + ".tmp")), + "a failed save must clean up its temp file rather than leaving it behind"); + } + @Test void loadConfigDefaultsSortingToggleableDepthTestAndCssClassesWhenOmitted(@TempDir Path tempDir) throws IOException { var path = tempDir.resolve("BMSM-Core.json"); @@ -601,6 +618,79 @@ void loadConfigDropsNullEntriesInCssClasses(@TempDir Path tempDir) throws IOExce assertTrue(warnings.stream().anyMatch(m -> m.contains("cssClasses"))); } + @Test + void loadConfigDefaultsShutdownAwaitSecondsWhenOmitted(@TempDir Path tempDir) throws IOException { + var path = tempDir.resolve("BMSM-Core.json"); + Files.writeString(path, """ + { + "markerGroups": [ + { "prefix": "[poi]", "name": "POI Group" } + ] + } + """); + + var config = ConfigProvider.loadConfig(path); + + assertEquals(BMSMConfigV2.DEFAULT_SHUTDOWN_AWAIT_SECONDS, config.getShutdownAwaitSeconds()); + } + + @Test + void loadConfigPreservesExplicitShutdownAwaitSeconds(@TempDir Path tempDir) throws IOException { + var path = tempDir.resolve("BMSM-Core.json"); + Files.writeString(path, """ + { + "shutdownAwaitSeconds": 30, + "markerGroups": [ + { "prefix": "[poi]", "name": "POI Group" } + ] + } + """); + + var config = ConfigProvider.loadConfig(path); + + assertEquals(30, config.getShutdownAwaitSeconds()); + } + + @Test + void loadConfigFallsBackToDefaultShutdownAwaitSecondsWhenMalformed(@TempDir Path tempDir) throws IOException { + var path = tempDir.resolve("BMSM-Core.json"); + Files.writeString(path, """ + { + "shutdownAwaitSeconds": "notanumber", + "markerGroups": [ + { "prefix": "[poi]", "name": "POI Group" } + ] + } + """); + + var result = new BMSMConfigV2[1]; + var warnings = captureWarnMessages(() -> ConfigProvider.loadConfig(path), result); + var config = result[0]; + + assertEquals(BMSMConfigV2.DEFAULT_SHUTDOWN_AWAIT_SECONDS, config.getShutdownAwaitSeconds()); + assertTrue(warnings.stream().anyMatch(m -> m.contains("shutdownAwaitSeconds"))); + } + + @Test + void loadConfigFallsBackToDefaultShutdownAwaitSecondsWhenNonPositive(@TempDir Path tempDir) throws IOException { + var path = tempDir.resolve("BMSM-Core.json"); + Files.writeString(path, """ + { + "shutdownAwaitSeconds": 0, + "markerGroups": [ + { "prefix": "[poi]", "name": "POI Group" } + ] + } + """); + + var result = new BMSMConfigV2[1]; + var warnings = captureWarnMessages(() -> ConfigProvider.loadConfig(path), result); + var config = result[0]; + + assertEquals(BMSMConfigV2.DEFAULT_SHUTDOWN_AWAIT_SECONDS, config.getShutdownAwaitSeconds()); + assertTrue(warnings.stream().anyMatch(m -> m.contains("shutdownAwaitSeconds"))); + } + @Test void loadConfigFallsBackToDefaultSortingWhenMalformed(@TempDir Path tempDir) throws IOException { var path = tempDir.resolve("BMSM-Core.json"); @@ -878,6 +968,122 @@ void loadConfigStillLoadsAnExtrudeGroupWithIconAndOffsetsSet(@TempDir Path tempD assertTrue(warnings.stream().anyMatch(m -> m.contains("offsetY"))); } + // Superseded by copilotreview.2026-09-09.md: finding 41 keyed duplicate-prefix detection on + // (matchType, prefix), reasoning that a STARTS_WITH "[a]" group and a REGEX "[a]" group match different + // sign text and so aren't real duplicates. That's true for matching, but every runtime lookup that + // resolves a sign's representation back to its group (SignManager.buildPrefixGroupMap, + // SignEntryHelper.getPrefix/SignTransitionResolver.computeRepresentation) is keyed on raw prefix text + // alone, with no way to recover which of the two groups a given sign actually matched - so this pair + // validated successfully while one of the two groups silently never matched any sign. Raw prefixes must + // be unique across groups again until (matchType, prefix) identity is threaded through + // SignLinesParseResult and every downstream lookup too. + @Test + void loadConfigRejectsTheSamePrefixTextAcrossDifferentMatchTypes(@TempDir Path tempDir) throws IOException { + var path = tempDir.resolve("BMSM-Core.json"); + Files.writeString(path, """ + { + "markerGroups": [ + { "prefix": "[a]", "matchType": "STARTS_WITH", "name": "First" }, + { "prefix": "[a]", "matchType": "REGEX", "name": "Second" } + ] + } + """); + + var config = ConfigProvider.loadConfig(path); + + assertNull(config); + } + + // finding 6: a v1 config with an empty/blank poiPrefix must not migrate into a v2 group whose empty + // STARTS_WITH "" prefix would silently match every sign's text - it should fall back to defaults instead. + @Test + void loadConfigFallsBackToDefaultsWhenAV1ConfigHasABlankPoiPrefix(@TempDir Path tempDir) throws IOException { + var path = tempDir.resolve("BMSM-Core.json"); + Files.writeString(path, """ + { "poiPrefix": "" } + """); + + var config = ConfigProvider.loadConfig(path); + + assertEquals(1, config.getMarkerGroups().length); + assertEquals("[poi]", config.getMarkerGroups()[0].prefix()); + assertTrue( + Files.exists(tempDir.resolve("BMSM-Core.json.v1.bak")), + "original v1 file should still have been backed up even though migration was rejected"); + } + + // finding 7: a single group with a malformed 'type' must degrade just that group's type to POI (with a + // warning) rather than throwing out of GSON.fromJson and wiping every group in the config back to one + // default [poi] group. + @Test + void loadConfigDegradesJustOneGroupWhenItsTypeIsMalformedRatherThanWipingTheWholeConfig( + @TempDir Path tempDir) throws IOException { + var path = tempDir.resolve("BMSM-Core.json"); + Files.writeString(path, """ + { + "markerGroups": [ + { "prefix": "[good]", "name": "Good Group" }, + { "prefix": "[bad]", "name": "Bad Group", "type": "NOT_A_TYPE" } + ] + } + """); + + var result = new BMSMConfigV2[1]; + var warnings = captureWarnMessages(() -> ConfigProvider.loadConfig(path), result); + var config = result[0]; + + assertEquals(2, config.getMarkerGroups().length); + assertEquals("[good]", config.getMarkerGroups()[0].prefix()); + assertEquals("[bad]", config.getMarkerGroups()[1].prefix()); + assertEquals(MarkerGroupType.POI, config.getMarkerGroups()[1].type()); + assertTrue(warnings.stream().anyMatch(m -> m.contains("type"))); + } + + // Same as above, but for a malformed 'matchType' rather than 'type'. + @Test + void loadConfigDegradesJustOneGroupWhenItsMatchTypeIsMalformedRatherThanWipingTheWholeConfig( + @TempDir Path tempDir) throws IOException { + var path = tempDir.resolve("BMSM-Core.json"); + Files.writeString(path, """ + { + "markerGroups": [ + { "prefix": "[bad]", "name": "Bad Group", "matchType": "NOT_A_MATCH_TYPE" } + ] + } + """); + + var result = new BMSMConfigV2[1]; + var warnings = captureWarnMessages(() -> ConfigProvider.loadConfig(path), result); + var config = result[0]; + + assertEquals(1, config.getMarkerGroups().length); + assertEquals(MarkerGroupMatchType.STARTS_WITH, config.getMarkerGroups()[0].matchType()); + assertTrue(warnings.stream().anyMatch(m -> m.contains("matchType"))); + } + + // Same as above, but for a malformed 'offsetX' (a non-numeric value rather than a wrong-shaped enum). + @Test + void loadConfigDegradesJustOneGroupWhenItsOffsetXIsMalformedRatherThanWipingTheWholeConfig( + @TempDir Path tempDir) throws IOException { + var path = tempDir.resolve("BMSM-Core.json"); + Files.writeString(path, """ + { + "markerGroups": [ + { "prefix": "[good]", "name": "Good Group" }, + { "prefix": "[bad]", "name": "Bad Group", "offsetX": "notanumber" } + ] + } + """); + + var result = new BMSMConfigV2[1]; + var warnings = captureWarnMessages(() -> ConfigProvider.loadConfig(path), result); + var config = result[0]; + + assertEquals(2, config.getMarkerGroups().length); + assertEquals(0, config.getMarkerGroups()[1].offsetX()); + assertTrue(warnings.stream().anyMatch(m -> m.contains("offsetX"))); + } + @Test void loadConfigWarnsWhenCssClassesIsSetOnAnExtrudeGroup(@TempDir Path tempDir) throws IOException { var path = tempDir.resolve("BMSM-Core.json"); @@ -897,4 +1103,72 @@ void loadConfigWarnsWhenCssClassesIsSetOnAnExtrudeGroup(@TempDir Path tempDir) t assertTrue(config.getMarkerGroups()[0].cssClasses().isEmpty()); assertTrue(warnings.stream().anyMatch(m -> m.contains("cssClasses"))); } + + // finding 14: a group with a missing 'name' must degrade to a fallback name (with a warning) rather than + // throwing MarkerGroup's requireNonNull and wiping every group in the config back to one default [poi] group. + @Test + void loadConfigFallsBackToThePrefixWhenNameIsMissingRatherThanWipingTheWholeConfig( + @TempDir Path tempDir) throws IOException { + var path = tempDir.resolve("BMSM-Core.json"); + Files.writeString(path, """ + { + "markerGroups": [ + { "prefix": "[good]", "name": "Good Group" }, + { "prefix": "[bad]" } + ] + } + """); + + var result = new BMSMConfigV2[1]; + var warnings = captureWarnMessages(() -> ConfigProvider.loadConfig(path), result); + var config = result[0]; + + assertEquals(2, config.getMarkerGroups().length); + assertEquals("[good]", config.getMarkerGroups()[0].prefix()); + assertEquals("[bad]", config.getMarkerGroups()[1].prefix()); + assertEquals("[bad]", config.getMarkerGroups()[1].name()); + assertTrue(warnings.stream().anyMatch(m -> m.contains("name"))); + } + + // Same as above, but the name is present and blank rather than entirely absent. + @Test + void loadConfigFallsBackToThePrefixWhenNameIsBlank(@TempDir Path tempDir) throws IOException { + var path = tempDir.resolve("BMSM-Core.json"); + Files.writeString(path, """ + { + "markerGroups": [ + { "prefix": "[bad]", "name": " " } + ] + } + """); + + var result = new BMSMConfigV2[1]; + var warnings = captureWarnMessages(() -> ConfigProvider.loadConfig(path), result); + var config = result[0]; + + assertEquals(1, config.getMarkerGroups().length); + assertEquals("[bad]", config.getMarkerGroups()[0].name()); + assertTrue(warnings.stream().anyMatch(m -> m.contains("name"))); + } + + // A missing name and an empty prefix together must not make resolveName itself throw (it falls back to + // DEFAULT_NAME_PLACEHOLDER rather than assuming prefix is present) - validateMarkerGroups still rejects + // the empty prefix afterwards, so the placeholder value is never observable here, only that construction + // doesn't NPE before validation gets a chance to run. + @Test + void loadConfigStillRejectsAnEmptyPrefixEvenWhenNameAlsoFallsBackToAPlaceholder( + @TempDir Path tempDir) throws IOException { + var path = tempDir.resolve("BMSM-Core.json"); + Files.writeString(path, """ + { + "markerGroups": [ + { "prefix": "" } + ] + } + """); + + var config = ConfigProvider.loadConfig(path); + + assertNull(config, "an empty prefix is still rejected by validateMarkerGroups after name resolution"); + } } diff --git a/src/test/java/com/tpwalke2/bluemapsignmarkers/config/models/BMSMConfigV2Test.java b/src/test/java/com/tpwalke2/bluemapsignmarkers/config/models/BMSMConfigV2Test.java new file mode 100644 index 0000000..cc5333f --- /dev/null +++ b/src/test/java/com/tpwalke2/bluemapsignmarkers/config/models/BMSMConfigV2Test.java @@ -0,0 +1,36 @@ +package com.tpwalke2.bluemapsignmarkers.config.models; + +import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerGroup; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; + +class BMSMConfigV2Test { + + @Test + void getShutdownAwaitSecondsDefaultsWhenNotSpecified() { + var config = new BMSMConfigV2(MarkerGroup.DEFAULT_POI_GROUP); + + assertEquals(BMSMConfigV2.DEFAULT_SHUTDOWN_AWAIT_SECONDS, config.getShutdownAwaitSeconds()); + } + + @Test + void getShutdownAwaitSecondsReturnsTheConfiguredValue() { + var config = new BMSMConfigV2(new MarkerGroup[]{MarkerGroup.DEFAULT_POI_GROUP}, 30); + + assertEquals(30, config.getShutdownAwaitSeconds()); + } + + @Test + void getMarkerGroupsReturnsADefensiveCopy() { + var config = new BMSMConfigV2(MarkerGroup.DEFAULT_POI_GROUP); + + var first = config.getMarkerGroups(); + first[0] = null; + + var second = config.getMarkerGroups(); + assertNotSame(first, second); + assertEquals(MarkerGroup.DEFAULT_POI_GROUP, second[0]); + } +} diff --git a/src/test/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/BlueMapAPIConnectorTest.java b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/BlueMapAPIConnectorTest.java index 0292d4b..990bc7c 100644 --- a/src/test/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/BlueMapAPIConnectorTest.java +++ b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/BlueMapAPIConnectorTest.java @@ -1,33 +1,93 @@ package com.tpwalke2.bluemapsignmarkers.core.bluemap; +import com.tpwalke2.bluemapsignmarkers.core.bounds.RenderMaskEvaluator; import com.tpwalke2.bluemapsignmarkers.core.markers.LinePoint; +import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerGroup; +import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerIdentifier; +import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerSetIdentifier; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; -// resolveExtrudeHeightRange is package-private specifically so it's testable without pulling in bluemap-api -// (compileOnly, not on the test classpath - see the class's other private/game-coupled methods). +// pointOf and isInsideRenderBounds(RenderMask, ...) are package-private specifically so they're testable +// without pulling in bluemap-api (compileOnly, not on the test classpath - see the class's other +// private/game-coupled methods, which can't be exercised this way since even constructing a +// BlueMapAPIConnector calls BlueMapAPI.getInstance()). resolveExtrudeHeightRange moved to +// MarkerMutationsTest alongside the rest of the marker-construction logic it lives with now. class BlueMapAPIConnectorTest { @Test - void allMembersAtTheSameYGetAMinimumOneBlockHeightInsteadOfCollapsingToZero() { - var points = List.of(new LinePoint(0, 64, 0), new LinePoint(10, 64, 0), new LinePoint(10, 64, 10)); + void pointOfWrapsAMarkerIdentifiersCoordinatesIntoASinglePointList() { + var identifier = new MarkerIdentifier(10, 64, -5, new MarkerSetIdentifier("world", MarkerGroup.DEFAULT_POI_GROUP)); - var range = BlueMapAPIConnector.resolveExtrudeHeightRange("Town Hall", points); + var points = BlueMapAPIConnector.pointOf(identifier); - assertEquals(64f, range.minY()); - assertEquals(65f, range.maxY()); + assertEquals(List.of(new LinePoint(10, 64, -5)), points); + } + + private static Path writeRenderMaskConfig(Path mapsDir, String renderMaskBlock) throws IOException { + var file = mapsDir.resolve("world.conf"); + Files.writeString(file, "world: \"world\"\n" + renderMaskBlock); + return file; + } + + @Test + void poiPointInsideTheMaskIsInBounds(@TempDir Path mapsDir) throws IOException { + writeRenderMaskConfig(mapsDir, "render-mask: [ { min-y: 100 } ]\n"); + var mask = RenderMaskEvaluator.load("world", mapsDir); + + var result = BlueMapAPIConnector.isInsideRenderBounds(mask, List.of(new LinePoint(0, 150, 0))); + + assertTrue(result); + } + + @Test + void poiPointOutsideTheMaskIsOutOfBounds(@TempDir Path mapsDir) throws IOException { + writeRenderMaskConfig(mapsDir, "render-mask: [ { min-y: 100 } ]\n"); + var mask = RenderMaskEvaluator.load("world", mapsDir); + + var result = BlueMapAPIConnector.isInsideRenderBounds(mask, List.of(new LinePoint(0, 50, 0))); + + assertFalse(result); + } + + @Test + void lineWithAtLeastOneMemberInsideTheMaskIsInBounds(@TempDir Path mapsDir) throws IOException { + writeRenderMaskConfig(mapsDir, "render-mask: [ { min-y: 100 } ]\n"); + var mask = RenderMaskEvaluator.load("world", mapsDir); + var points = List.of(new LinePoint(0, 50, 0), new LinePoint(0, 150, 0)); + + var result = BlueMapAPIConnector.isInsideRenderBounds(mask, points); + + assertTrue(result); + } + + @Test + void lineWithEveryMemberOutsideTheMaskIsOutOfBounds(@TempDir Path mapsDir) throws IOException { + writeRenderMaskConfig(mapsDir, "render-mask: [ { min-y: 100 } ]\n"); + var mask = RenderMaskEvaluator.load("world", mapsDir); + var points = List.of(new LinePoint(0, 10, 0), new LinePoint(0, 50, 0)); + + var result = BlueMapAPIConnector.isInsideRenderBounds(mask, points); + + assertFalse(result); } @Test - void membersAtDifferentYsSpanTheirActualLowestToTallestHeight() { - var points = List.of(new LinePoint(0, 60, 0), new LinePoint(10, 70, 0), new LinePoint(10, 65, 10)); + void unboundedMaskAllowsAnyPoint(@TempDir Path mapsDir) throws IOException { + writeRenderMaskConfig(mapsDir, ""); + var mask = RenderMaskEvaluator.load("world", mapsDir); - var range = BlueMapAPIConnector.resolveExtrudeHeightRange("Town Hall", points); + var result = BlueMapAPIConnector.isInsideRenderBounds(mask, List.of(new LinePoint(0, -6000, 0))); - assertEquals(60f, range.minY()); - assertEquals(70f, range.maxY()); + assertTrue(result); } } diff --git a/src/test/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/MarkerMutationsTest.java b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/MarkerMutationsTest.java new file mode 100644 index 0000000..ec75f91 --- /dev/null +++ b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/MarkerMutationsTest.java @@ -0,0 +1,34 @@ +package com.tpwalke2.bluemapsignmarkers.core.bluemap; + +import com.tpwalke2.bluemapsignmarkers.core.markers.LinePoint; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +// resolveExtrudeHeightRange is package-private specifically so it's testable without pulling in +// bluemap-api (compileOnly, not on the test classpath) - see MarkerMutations' other static +// marker-construction methods, which can't be exercised this way since they take live bluemap-api types. +class MarkerMutationsTest { + + @Test + void allMembersAtTheSameYGetAMinimumOneBlockHeightInsteadOfCollapsingToZero() { + var points = List.of(new LinePoint(0, 64, 0), new LinePoint(10, 64, 0), new LinePoint(10, 64, 10)); + + var range = MarkerMutations.resolveExtrudeHeightRange("Town Hall", points); + + assertEquals(64f, range.minY()); + assertEquals(65f, range.maxY()); + } + + @Test + void membersAtDifferentYsSpanTheirActualLowestToTallestHeight() { + var points = List.of(new LinePoint(0, 60, 0), new LinePoint(10, 70, 0), new LinePoint(10, 65, 10)); + + var range = MarkerMutations.resolveExtrudeHeightRange("Town Hall", points); + + assertEquals(60f, range.minY()); + assertEquals(70f, range.maxY()); + } +} diff --git a/src/test/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/ActionFactoryTest.java b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/ActionFactoryTest.java index 75e9192..13bad1b 100644 --- a/src/test/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/ActionFactoryTest.java +++ b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/ActionFactoryTest.java @@ -1,12 +1,12 @@ package com.tpwalke2.bluemapsignmarkers.core.bluemap.actions; -import com.tpwalke2.bluemapsignmarkers.core.markers.LineMarkerIdentifier; import com.tpwalke2.bluemapsignmarkers.core.markers.LinePoint; import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerGroup; import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerGroupMatchType; import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerGroupType; import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerIdentifier; import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerSetIdentifierCollection; +import com.tpwalke2.bluemapsignmarkers.core.markers.MultiPointMarkerIdentifier; import org.junit.jupiter.api.Test; import java.util.List; @@ -14,6 +14,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; class ActionFactoryTest { @@ -68,12 +69,12 @@ void createUpdatePOIActionBuildsTheMarkerIdentifierAndActionFields() { } @Test - void createChangeGroupPOIActionBuildsARemoveAndAddEffectPair() { + void createGroupTransitionPOIActionBuildsARemoveAndAddEffectPair() { var factory = new ActionFactory(new MarkerSetIdentifierCollection()); var oldGroup = markerGroup("[event]"); var newGroup = markerGroup("[poi]"); - var action = factory.createChangeGroupPOIAction(1, 2, 3, "world", "label", "detail", oldGroup, newGroup); + var action = factory.createGroupTransitionPOIAction(1, 2, 3, "world", "label", "detail", oldGroup, newGroup); assertEquals(2, action.effects().size()); var removeAction = assertInstanceOf(RemoveMarkerAction.class, action.effects().get(0)); @@ -93,14 +94,15 @@ void createChangeGroupPOIActionBuildsARemoveAndAddEffectPair() { } @Test - void createSetLineActionBuildsTheLineMarkerIdentifierAndActionFields() { + void createSetMultiPointActionBuildsTheLineMarkerIdentifierAndActionFields() { var factory = new ActionFactory(new MarkerSetIdentifierCollection()); var group = lineMarkerGroup("[line]"); var points = List.of(new LinePoint(1, 2, 3), new LinePoint(4, 5, 6)); - var action = factory.createSetLineAction("world", group, "label", "detail", points, group.lineColor(), true); - var identifier = (LineMarkerIdentifier) action.getMarkerIdentifier(); + var action = factory.createSetMultiPointAction("world", group, "label", "detail", points, group.lineColor(), null, true); + var identifier = (MultiPointMarkerIdentifier) action.getMarkerIdentifier(); + assertEquals("line", identifier.kind()); assertEquals("label", identifier.label()); assertEquals("world", identifier.parentSet().mapId()); assertEquals(group, identifier.parentSet().markerGroup()); @@ -113,13 +115,14 @@ void createSetLineActionBuildsTheLineMarkerIdentifierAndActionFields() { } @Test - void createRemoveLineActionBuildsTheLineMarkerIdentifier() { + void createRemoveMultiPointActionBuildsTheLineMarkerIdentifier() { var factory = new ActionFactory(new MarkerSetIdentifierCollection()); var group = lineMarkerGroup("[line]"); - var action = factory.createRemoveLineAction("world", group, "label"); - var identifier = (LineMarkerIdentifier) action.getMarkerIdentifier(); + var action = factory.createRemoveMultiPointAction("world", group, "label"); + var identifier = (MultiPointMarkerIdentifier) action.getMarkerIdentifier(); + assertEquals("line", identifier.kind()); assertEquals("label", identifier.label()); assertEquals("world", identifier.parentSet().mapId()); assertEquals(group, identifier.parentSet().markerGroup()); @@ -150,14 +153,15 @@ void differentActionTypesForTheSameMapAndGroupReuseTheSameMarkerSetIdentifier() } @Test - void createSetShapeActionBuildsTheShapeMarkerIdentifierAndActionFields() { + void createSetMultiPointActionBuildsTheShapeMarkerIdentifierAndActionFields() { var factory = new ActionFactory(new MarkerSetIdentifierCollection()); var group = shapeMarkerGroup("[shape]"); var points = List.of(new LinePoint(1, 2, 3), new LinePoint(4, 5, 6), new LinePoint(7, 8, 9)); - var action = factory.createSetShapeAction("world", group, "label", "detail", points, group.lineColor(), group.fillColor(), true); - var identifier = (com.tpwalke2.bluemapsignmarkers.core.markers.ShapeMarkerIdentifier) action.getMarkerIdentifier(); + var action = factory.createSetMultiPointAction("world", group, "label", "detail", points, group.lineColor(), group.fillColor(), true); + var identifier = (MultiPointMarkerIdentifier) action.getMarkerIdentifier(); + assertEquals("shape", identifier.kind()); assertEquals("label", identifier.label()); assertEquals("world", identifier.parentSet().mapId()); assertEquals(group, identifier.parentSet().markerGroup()); @@ -171,13 +175,14 @@ void createSetShapeActionBuildsTheShapeMarkerIdentifierAndActionFields() { } @Test - void createRemoveShapeActionBuildsTheShapeMarkerIdentifier() { + void createRemoveMultiPointActionBuildsTheShapeMarkerIdentifier() { var factory = new ActionFactory(new MarkerSetIdentifierCollection()); var group = shapeMarkerGroup("[shape]"); - var action = factory.createRemoveShapeAction("world", group, "label"); - var identifier = (com.tpwalke2.bluemapsignmarkers.core.markers.ShapeMarkerIdentifier) action.getMarkerIdentifier(); + var action = factory.createRemoveMultiPointAction("world", group, "label"); + var identifier = (MultiPointMarkerIdentifier) action.getMarkerIdentifier(); + assertEquals("shape", identifier.kind()); assertEquals("label", identifier.label()); assertEquals("world", identifier.parentSet().mapId()); assertEquals(group, identifier.parentSet().markerGroup()); @@ -188,8 +193,9 @@ void shapeActionsForTheSameMapAndGroupReuseTheSameMarkerSetIdentifierAsPOIAction var factory = new ActionFactory(new MarkerSetIdentifierCollection()); var group = shapeMarkerGroup("[shape]"); - var set = factory.createSetShapeAction("world", group, "label", "detail", List.of(), group.lineColor(), group.fillColor(), true); - var removed = factory.createRemoveShapeAction("world", group, "other label"); + var points = List.of(new LinePoint(1, 2, 3), new LinePoint(4, 5, 6), new LinePoint(7, 8, 9)); + var set = factory.createSetMultiPointAction("world", group, "label", "detail", points, group.lineColor(), group.fillColor(), true); + var removed = factory.createRemoveMultiPointAction("world", group, "other label"); assertSame(set.getMarkerIdentifier().parentSet(), removed.getMarkerIdentifier().parentSet()); } @@ -199,21 +205,23 @@ void lineActionsForTheSameMapAndGroupReuseTheSameMarkerSetIdentifierAsPOIActions var factory = new ActionFactory(new MarkerSetIdentifierCollection()); var group = lineMarkerGroup("[line]"); - var set = factory.createSetLineAction("world", group, "label", "detail", List.of(), group.lineColor(), true); - var removed = factory.createRemoveLineAction("world", group, "other label"); + var points = List.of(new LinePoint(1, 2, 3), new LinePoint(4, 5, 6)); + var set = factory.createSetMultiPointAction("world", group, "label", "detail", points, group.lineColor(), null, true); + var removed = factory.createRemoveMultiPointAction("world", group, "other label"); assertSame(set.getMarkerIdentifier().parentSet(), removed.getMarkerIdentifier().parentSet()); } @Test - void createSetExtrudeActionBuildsTheExtrudeMarkerIdentifierAndActionFields() { + void createSetMultiPointActionBuildsTheExtrudeMarkerIdentifierAndActionFields() { var factory = new ActionFactory(new MarkerSetIdentifierCollection()); var group = extrudeMarkerGroup("[extrude]"); var points = List.of(new LinePoint(1, 2, 3), new LinePoint(4, 5, 6), new LinePoint(7, 8, 9)); - var action = factory.createSetExtrudeAction("world", group, "label", "detail", points, group.lineColor(), group.fillColor(), true); - var identifier = (com.tpwalke2.bluemapsignmarkers.core.markers.ExtrudeMarkerIdentifier) action.getMarkerIdentifier(); + var action = factory.createSetMultiPointAction("world", group, "label", "detail", points, group.lineColor(), group.fillColor(), true); + var identifier = (MultiPointMarkerIdentifier) action.getMarkerIdentifier(); + assertEquals("extrude", identifier.kind()); assertEquals("label", identifier.label()); assertEquals("world", identifier.parentSet().mapId()); assertEquals(group, identifier.parentSet().markerGroup()); @@ -227,13 +235,14 @@ void createSetExtrudeActionBuildsTheExtrudeMarkerIdentifierAndActionFields() { } @Test - void createRemoveExtrudeActionBuildsTheExtrudeMarkerIdentifier() { + void createRemoveMultiPointActionBuildsTheExtrudeMarkerIdentifier() { var factory = new ActionFactory(new MarkerSetIdentifierCollection()); var group = extrudeMarkerGroup("[extrude]"); - var action = factory.createRemoveExtrudeAction("world", group, "label"); - var identifier = (com.tpwalke2.bluemapsignmarkers.core.markers.ExtrudeMarkerIdentifier) action.getMarkerIdentifier(); + var action = factory.createRemoveMultiPointAction("world", group, "label"); + var identifier = (MultiPointMarkerIdentifier) action.getMarkerIdentifier(); + assertEquals("extrude", identifier.kind()); assertEquals("label", identifier.label()); assertEquals("world", identifier.parentSet().mapId()); assertEquals(group, identifier.parentSet().markerGroup()); @@ -244,12 +253,67 @@ void extrudeActionsForTheSameMapAndGroupReuseTheSameMarkerSetIdentifierAsPOIActi var factory = new ActionFactory(new MarkerSetIdentifierCollection()); var group = extrudeMarkerGroup("[extrude]"); - var set = factory.createSetExtrudeAction("world", group, "label", "detail", List.of(), group.lineColor(), group.fillColor(), true); - var removed = factory.createRemoveExtrudeAction("world", group, "other label"); + var points = List.of(new LinePoint(1, 2, 3), new LinePoint(4, 5, 6), new LinePoint(7, 8, 9)); + var set = factory.createSetMultiPointAction("world", group, "label", "detail", points, group.lineColor(), group.fillColor(), true); + var removed = factory.createRemoveMultiPointAction("world", group, "other label"); assertSame(set.getMarkerIdentifier().parentSet(), removed.getMarkerIdentifier().parentSet()); } + @Test + void createSetMultiPointActionRejectsAPOIMarkerGroup() { + var factory = new ActionFactory(new MarkerSetIdentifierCollection()); + var group = markerGroup("[poi]"); + var points = List.of(new LinePoint(1, 2, 3), new LinePoint(4, 5, 6)); + + assertThrows(IllegalArgumentException.class, + () -> factory.createSetMultiPointAction("world", group, "label", "detail", points, group.lineColor(), null, true)); + } + + @Test + void createRemoveMultiPointActionRejectsAPOIMarkerGroup() { + var factory = new ActionFactory(new MarkerSetIdentifierCollection()); + var group = markerGroup("[poi]"); + + assertThrows(IllegalArgumentException.class, + () -> factory.createRemoveMultiPointAction("world", group, "label")); + } + + // multiPointKind derives each type's minimum-points threshold from MultiPointGroupThresholds, keyed on + // markerGroup.type() - a regression mapping SHAPE/EXTRUDE to LINE's threshold (2) instead of their own + // (3) would still pass a same-sized-points-list test, since 2 points also satisfies LINE. These pin the + // per-kind threshold directly: exactly one point below each kind's own minimum must be rejected, not + // just below every kind's minimum. + @Test + void createSetMultiPointActionRejectsFewerThanTwoPointsForALineGroup() { + var factory = new ActionFactory(new MarkerSetIdentifierCollection()); + var group = lineMarkerGroup("[line]"); + var points = List.of(new LinePoint(1, 2, 3)); + + assertThrows(IllegalArgumentException.class, + () -> factory.createSetMultiPointAction("world", group, "label", "detail", points, group.lineColor(), null, true)); + } + + @Test + void createSetMultiPointActionRejectsFewerThanThreePointsForAShapeGroup() { + var factory = new ActionFactory(new MarkerSetIdentifierCollection()); + var group = shapeMarkerGroup("[shape]"); + var points = List.of(new LinePoint(1, 2, 3), new LinePoint(4, 5, 6)); + + assertThrows(IllegalArgumentException.class, + () -> factory.createSetMultiPointAction("world", group, "label", "detail", points, group.lineColor(), group.fillColor(), true)); + } + + @Test + void createSetMultiPointActionRejectsFewerThanThreePointsForAnExtrudeGroup() { + var factory = new ActionFactory(new MarkerSetIdentifierCollection()); + var group = extrudeMarkerGroup("[extrude]"); + var points = List.of(new LinePoint(1, 2, 3), new LinePoint(4, 5, 6)); + + assertThrows(IllegalArgumentException.class, + () -> factory.createSetMultiPointAction("world", group, "label", "detail", points, group.lineColor(), group.fillColor(), true)); + } + private static MarkerGroup markerGroup(String prefix) { return new MarkerGroup( prefix, MarkerGroupMatchType.STARTS_WITH, MarkerGroupType.POI, prefix, "icon.png", 0, 0, false, 0, 0, diff --git a/src/test/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/AddMarkerActionTest.java b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/AddMarkerActionTest.java new file mode 100644 index 0000000..548407f --- /dev/null +++ b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/AddMarkerActionTest.java @@ -0,0 +1,32 @@ +package com.tpwalke2.bluemapsignmarkers.core.bluemap.actions; + +import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerGroup; +import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerGroupMatchType; +import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerGroupType; +import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerIdentifier; +import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerSetIdentifier; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertThrows; + +class AddMarkerActionTest { + + @Test + void constructorRejectsANullLabel() { + assertThrows(NullPointerException.class, () -> new AddMarkerAction(identifier(), null, "detail")); + } + + @Test + void constructorRejectsANullDetail() { + assertThrows(NullPointerException.class, () -> new AddMarkerAction(identifier(), "label", null)); + } + + private static MarkerIdentifier identifier() { + var group = new MarkerGroup( + "[poi]", MarkerGroupMatchType.STARTS_WITH, MarkerGroupType.POI, "[poi]", "icon.png", 0, 0, false, 0, + 0, 2, "#FF0000FF", "#FF000033", 0, true, true, List.of(), false); + return new MarkerIdentifier(1, 2, 3, new MarkerSetIdentifier("world", group)); + } +} diff --git a/src/test/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/GroupTransitionMarkerActionTest.java b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/GroupTransitionMarkerActionTest.java new file mode 100644 index 0000000..368bd82 --- /dev/null +++ b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/GroupTransitionMarkerActionTest.java @@ -0,0 +1,49 @@ +package com.tpwalke2.bluemapsignmarkers.core.bluemap.actions; + +import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerGroup; +import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerGroupMatchType; +import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerGroupType; +import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerIdentifier; +import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerSetIdentifier; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class GroupTransitionMarkerActionTest { + + @Test + void constructorRejectsAnEmptyEffectsList() { + assertThrows(IllegalArgumentException.class, () -> new GroupTransitionMarkerAction(List.of())); + } + + @Test + void getMarkerIdentifierReturnsTheSoleEffectsIdentifierForASingleEffect() { + var effect = new RemoveMarkerAction(identifier(1, 2, 3)); + + var action = new GroupTransitionMarkerAction(List.of(effect)); + + assertSame(effect.getMarkerIdentifier(), action.getMarkerIdentifier()); + } + + @Test + void getMarkerIdentifierReturnsTheFirstEffectsIdentifierSpecifically() { + var first = new RemoveMarkerAction(identifier(1, 2, 3)); + var second = new AddMarkerAction(identifier(4, 5, 6), "label", "detail"); + + var action = new GroupTransitionMarkerAction(List.of(first, second)); + + assertSame(first.getMarkerIdentifier(), action.getMarkerIdentifier()); + assertEquals(2, action.effects().size()); + } + + private static MarkerIdentifier identifier(int x, int y, int z) { + var group = new MarkerGroup( + "[poi]", MarkerGroupMatchType.STARTS_WITH, MarkerGroupType.POI, "[poi]", "icon.png", 0, 0, false, 0, + 0, 2, "#FF0000FF", "#FF000033", 0, true, true, List.of(), false); + return new MarkerIdentifier(x, y, z, new MarkerSetIdentifier("world", group)); + } +} diff --git a/src/test/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/SetExtrudeMarkerActionTest.java b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/SetExtrudeMarkerActionTest.java new file mode 100644 index 0000000..972151e --- /dev/null +++ b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/SetExtrudeMarkerActionTest.java @@ -0,0 +1,78 @@ +package com.tpwalke2.bluemapsignmarkers.core.bluemap.actions; + +import com.tpwalke2.bluemapsignmarkers.core.markers.LinePoint; +import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerGroup; +import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerGroupMatchType; +import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerGroupType; +import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerSetIdentifier; +import com.tpwalke2.bluemapsignmarkers.core.markers.MultiPointGroupThresholds; +import com.tpwalke2.bluemapsignmarkers.core.markers.MultiPointMarkerIdentifier; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +// A SetMultiPointMarkerAction constructed with the EXTRUDE minimum (3 points) and a fillColor - see +// SetLineMarkerActionTest for the LINE minimum (2 points, no fillColor). +class SetExtrudeMarkerActionTest { + private static final int MIN_POINTS = MultiPointGroupThresholds.EXTRUDE_MIN_MEMBERS; + + @Test + void constructorRejectsAnEmptyPointList() { + assertThrows(IllegalArgumentException.class, () -> newAction(List.of())); + } + + @Test + void constructorRejectsFewerThanThreePoints() { + assertThrows(IllegalArgumentException.class, + () -> newAction(List.of(new LinePoint(1, 2, 3), new LinePoint(4, 5, 6)))); + } + + @Test + void constructorAcceptsThreePoints() { + var points = threePoints(); + var action = newAction(points); + + assertEquals(points, action.getPoints()); + } + + @Test + void constructorDefensivelyCopiesThePointsList() { + var mutablePoints = new ArrayList<>(threePoints()); + var action = newAction(mutablePoints); + + mutablePoints.add(new LinePoint(10, 11, 12)); + + assertEquals(3, action.getPoints().size()); + } + + @Test + void constructorRejectsANullLabel() { + assertThrows(NullPointerException.class, () -> new SetMultiPointMarkerAction( + identifier(), null, "detail", threePoints(), 2, "#FFFFFFFF", "#FFFFFF33", MIN_POINTS, true)); + } + + @Test + void constructorRejectsANullDetail() { + assertThrows(NullPointerException.class, () -> new SetMultiPointMarkerAction( + identifier(), "label", null, threePoints(), 2, "#FFFFFFFF", "#FFFFFF33", MIN_POINTS, true)); + } + + private static SetMultiPointMarkerAction newAction(List points) { + return new SetMultiPointMarkerAction(identifier(), "label", "detail", points, 2, "#FFFFFFFF", "#FFFFFF33", MIN_POINTS, true); + } + + private static List threePoints() { + return List.of(new LinePoint(1, 2, 3), new LinePoint(4, 5, 6), new LinePoint(7, 8, 9)); + } + + private static MultiPointMarkerIdentifier identifier() { + var group = new MarkerGroup( + "[extrude]", MarkerGroupMatchType.STARTS_WITH, MarkerGroupType.EXTRUDE, "[extrude]", null, 0, 0, + false, 0, 0, 2, "#FF0000FF", "#FF000033", 0, true, true, List.of(), false); + return new MultiPointMarkerIdentifier("extrude", "label", new MarkerSetIdentifier("world", group)); + } +} diff --git a/src/test/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/SetLineMarkerActionTest.java b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/SetLineMarkerActionTest.java new file mode 100644 index 0000000..8fbe2b0 --- /dev/null +++ b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/SetLineMarkerActionTest.java @@ -0,0 +1,78 @@ +package com.tpwalke2.bluemapsignmarkers.core.bluemap.actions; + +import com.tpwalke2.bluemapsignmarkers.core.markers.LinePoint; +import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerGroup; +import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerGroupMatchType; +import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerGroupType; +import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerSetIdentifier; +import com.tpwalke2.bluemapsignmarkers.core.markers.MultiPointGroupThresholds; +import com.tpwalke2.bluemapsignmarkers.core.markers.MultiPointMarkerIdentifier; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +// A SetMultiPointMarkerAction constructed with the LINE minimum (2 points), no fillColor - see +// SetShapeMarkerActionTest/SetExtrudeMarkerActionTest for the SHAPE/EXTRUDE minimums (3 points, with +// fillColor). +class SetLineMarkerActionTest { + private static final int MIN_POINTS = MultiPointGroupThresholds.LINE_MIN_MEMBERS; + + @Test + void constructorRejectsAnEmptyPointList() { + assertThrows(IllegalArgumentException.class, () -> newAction(List.of())); + } + + @Test + void constructorRejectsASinglePointList() { + assertThrows(IllegalArgumentException.class, () -> newAction(List.of(new LinePoint(1, 2, 3)))); + } + + @Test + void constructorAcceptsTwoPoints() { + var points = List.of(new LinePoint(1, 2, 3), new LinePoint(4, 5, 6)); + var action = newAction(points); + + assertEquals(points, action.getPoints()); + } + + @Test + void constructorDefensivelyCopiesThePointsList() { + var mutablePoints = new ArrayList<>(List.of(new LinePoint(1, 2, 3), new LinePoint(4, 5, 6))); + var action = newAction(mutablePoints); + + mutablePoints.add(new LinePoint(7, 8, 9)); + + assertEquals(2, action.getPoints().size()); + } + + @Test + void constructorRejectsANullLabel() { + assertThrows(NullPointerException.class, () -> new SetMultiPointMarkerAction( + identifier(), null, "detail", twoPoints(), 2, "#FFFFFFFF", null, MIN_POINTS, true)); + } + + @Test + void constructorRejectsANullDetail() { + assertThrows(NullPointerException.class, () -> new SetMultiPointMarkerAction( + identifier(), "label", null, twoPoints(), 2, "#FFFFFFFF", null, MIN_POINTS, true)); + } + + private static SetMultiPointMarkerAction newAction(List points) { + return new SetMultiPointMarkerAction(identifier(), "label", "detail", points, 2, "#FFFFFFFF", null, MIN_POINTS, true); + } + + private static List twoPoints() { + return List.of(new LinePoint(1, 2, 3), new LinePoint(4, 5, 6)); + } + + private static MultiPointMarkerIdentifier identifier() { + var group = new MarkerGroup( + "[line]", MarkerGroupMatchType.STARTS_WITH, MarkerGroupType.LINE, "[line]", null, 0, 0, false, 0, 0, + 2, "#FF0000FF", "#FF000033", 0, true, true, List.of(), false); + return new MultiPointMarkerIdentifier("line", "label", new MarkerSetIdentifier("world", group)); + } +} diff --git a/src/test/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/SetShapeMarkerActionTest.java b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/SetShapeMarkerActionTest.java new file mode 100644 index 0000000..d8148ae --- /dev/null +++ b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/SetShapeMarkerActionTest.java @@ -0,0 +1,78 @@ +package com.tpwalke2.bluemapsignmarkers.core.bluemap.actions; + +import com.tpwalke2.bluemapsignmarkers.core.markers.LinePoint; +import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerGroup; +import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerGroupMatchType; +import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerGroupType; +import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerSetIdentifier; +import com.tpwalke2.bluemapsignmarkers.core.markers.MultiPointGroupThresholds; +import com.tpwalke2.bluemapsignmarkers.core.markers.MultiPointMarkerIdentifier; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +// A SetMultiPointMarkerAction constructed with the SHAPE minimum (3 points) and a fillColor - see +// SetLineMarkerActionTest for the LINE minimum (2 points, no fillColor). +class SetShapeMarkerActionTest { + private static final int MIN_POINTS = MultiPointGroupThresholds.SHAPE_MIN_MEMBERS; + + @Test + void constructorRejectsAnEmptyPointList() { + assertThrows(IllegalArgumentException.class, () -> newAction(List.of())); + } + + @Test + void constructorRejectsFewerThanThreePoints() { + assertThrows(IllegalArgumentException.class, + () -> newAction(List.of(new LinePoint(1, 2, 3), new LinePoint(4, 5, 6)))); + } + + @Test + void constructorAcceptsThreePoints() { + var points = threePoints(); + var action = newAction(points); + + assertEquals(points, action.getPoints()); + } + + @Test + void constructorDefensivelyCopiesThePointsList() { + var mutablePoints = new ArrayList<>(threePoints()); + var action = newAction(mutablePoints); + + mutablePoints.add(new LinePoint(10, 11, 12)); + + assertEquals(3, action.getPoints().size()); + } + + @Test + void constructorRejectsANullLabel() { + assertThrows(NullPointerException.class, () -> new SetMultiPointMarkerAction( + identifier(), null, "detail", threePoints(), 2, "#FFFFFFFF", "#FFFFFF33", MIN_POINTS, true)); + } + + @Test + void constructorRejectsANullDetail() { + assertThrows(NullPointerException.class, () -> new SetMultiPointMarkerAction( + identifier(), "label", null, threePoints(), 2, "#FFFFFFFF", "#FFFFFF33", MIN_POINTS, true)); + } + + private static SetMultiPointMarkerAction newAction(List points) { + return new SetMultiPointMarkerAction(identifier(), "label", "detail", points, 2, "#FFFFFFFF", "#FFFFFF33", MIN_POINTS, true); + } + + private static List threePoints() { + return List.of(new LinePoint(1, 2, 3), new LinePoint(4, 5, 6), new LinePoint(7, 8, 9)); + } + + private static MultiPointMarkerIdentifier identifier() { + var group = new MarkerGroup( + "[shape]", MarkerGroupMatchType.STARTS_WITH, MarkerGroupType.SHAPE, "[shape]", null, 0, 0, false, 0, + 0, 2, "#FF0000FF", "#FF000033", 0, true, true, List.of(), false); + return new MultiPointMarkerIdentifier("shape", "label", new MarkerSetIdentifier("world", group)); + } +} diff --git a/src/test/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/UpdateMarkerActionTest.java b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/UpdateMarkerActionTest.java new file mode 100644 index 0000000..662b1bd --- /dev/null +++ b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/bluemap/actions/UpdateMarkerActionTest.java @@ -0,0 +1,32 @@ +package com.tpwalke2.bluemapsignmarkers.core.bluemap.actions; + +import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerGroup; +import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerGroupMatchType; +import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerGroupType; +import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerIdentifier; +import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerSetIdentifier; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertThrows; + +class UpdateMarkerActionTest { + + @Test + void constructorRejectsANullLabel() { + assertThrows(NullPointerException.class, () -> new UpdateMarkerAction(identifier(), null, "detail")); + } + + @Test + void constructorRejectsANullDetail() { + assertThrows(NullPointerException.class, () -> new UpdateMarkerAction(identifier(), "label", null)); + } + + private static MarkerIdentifier identifier() { + var group = new MarkerGroup( + "[poi]", MarkerGroupMatchType.STARTS_WITH, MarkerGroupType.POI, "[poi]", "icon.png", 0, 0, false, 0, + 0, 2, "#FF0000FF", "#FF000033", 0, true, true, List.of(), false); + return new MarkerIdentifier(1, 2, 3, new MarkerSetIdentifier("world", group)); + } +} diff --git a/src/test/java/com/tpwalke2/bluemapsignmarkers/core/bounds/RenderMaskEvaluatorTest.java b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/bounds/RenderMaskEvaluatorTest.java index dcdc9a7..63ea7ae 100644 --- a/src/test/java/com/tpwalke2/bluemapsignmarkers/core/bounds/RenderMaskEvaluatorTest.java +++ b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/bounds/RenderMaskEvaluatorTest.java @@ -98,6 +98,28 @@ void unreadableConfigFileIsUnbounded(@TempDir Path mapsDir) throws IOException { } } + @Test + void unlistableMapsDirectoryIsUnbounded(@TempDir Path mapsDir) throws IOException { + writeConfig(mapsDir, "world.conf", "render-mask: [ { min-y: 127 } ]\n"); + mapsDir.toFile().setReadable(false); + try { + // Same caveat as unreadableConfigFileIsUnbounded: setReadable(false)'s return value + // doesn't guarantee Files.list actually fails on this platform/user (e.g. an owner/admin + // process on Windows can still list it), so verify the real outcome and skip otherwise + // rather than reading an unearned pass. + boolean listingBlocked; + try (var files = Files.list(mapsDir)) { + listingBlocked = false; + } catch (IOException e) { + listingBlocked = true; + } + assumeTrue(listingBlocked, "Could not revoke listing permission on this platform; fail-open behavior unverified"); + assertTrue(RenderMaskEvaluator.isInsideRenderBounds("world", mapsDir, 0, -6000, 0)); + } finally { + mapsDir.toFile().setReadable(true); + } + } + @Test void maskStartingWithSubtractIncludesEverythingElse(@TempDir Path mapsDir) throws IOException { writeConfig(mapsDir, "world.conf", """ @@ -364,6 +386,139 @@ void polygonEntryEvaluatesNonConvexShapeViaPointInPolygon(@TempDir Path mapsDir) assertTrue(RenderMaskEvaluator.isInsideRenderBounds("world", mapsDir, 8, 0, 1)); } + @Test + void circleEntryWithZeroRadiusFailsOpen(@TempDir Path mapsDir) throws IOException { + writeConfig(mapsDir, "world.conf", """ + render-mask: [ + { + type: circle + center-x: 0 + center-z: 0 + radius: 0 + } + ] + """); + + assertTrue(RenderMaskEvaluator.isInsideRenderBounds("world", mapsDir, 0, 0, 0)); + } + + @Test + void circleEntryWithNegativeRadiusFailsOpen(@TempDir Path mapsDir) throws IOException { + writeConfig(mapsDir, "world.conf", """ + render-mask: [ + { + type: circle + center-x: 0 + center-z: 0 + radius: -10 + } + ] + """); + + assertTrue(RenderMaskEvaluator.isInsideRenderBounds("world", mapsDir, 0, 0, 0)); + } + + @Test + void scientificNotationFieldParsesToItsFullValueNotJustTheMantissa(@TempDir Path mapsDir) throws IOException { + writeConfig(mapsDir, "world.conf", """ + render-mask: [ + { + type: circle + center-x: 0 + center-z: 0 + radius: 1.5e3 + } + ] + """); + + // radius 1500, not 1.5 - a point at x=1000 must be inside, not outside + assertTrue(RenderMaskEvaluator.isInsideRenderBounds("world", mapsDir, 1000, 0, 0)); + } + + @Test + void nonNumericFieldValueFailsOpenForWholeMap(@TempDir Path mapsDir) throws IOException { + writeConfig(mapsDir, "world.conf", """ + render-mask: [ + { + type: circle + center-x: 0 + center-z: 0 + radius: not-a-number + } + ] + """); + + // "radius" never matches FIELD_PATTERN's numeric alternative, so it's simply absent from + // the fields map - requiredDoubleField then throws its own "missing required field", + // failing the whole map open rather than throwing an uncaught parse exception. + assertTrue(RenderMaskEvaluator.isInsideRenderBounds("world", mapsDir, 1_000_000, 0, 0)); + } + + @Test + void overflowingIntegerFieldValueFailsOpenForWholeMap(@TempDir Path mapsDir) throws IOException { + writeConfig(mapsDir, "world.conf", """ + render-mask: [ + { + min-x: 99999999999999 + max-x: 10 + } + ] + """); + + // min-x overflows int; Integer.parseInt throws, caught by parseRenderMask's catch-all and + // failing the whole map open instead of propagating an uncaught exception. + assertTrue(RenderMaskEvaluator.isInsideRenderBounds("world", mapsDir, 1_000_000, 0, 0)); + } + + @Test + void polygonMissingShapeArrayFailsOpen(@TempDir Path mapsDir) throws IOException { + writeConfig(mapsDir, "world.conf", """ + render-mask: [ + { + type: polygon + min-y: 0 + } + ] + """); + + assertTrue(RenderMaskEvaluator.isInsideRenderBounds("world", mapsDir, 0, 0, 0)); + } + + @Test + void polygonWithFewerThanThreePointsFailsOpen(@TempDir Path mapsDir) throws IOException { + writeConfig(mapsDir, "world.conf", """ + render-mask: [ + { + type: polygon + shape: [ + { x: 0, z: 0 } + { x: 10, z: 0 } + ] + } + ] + """); + + assertTrue(RenderMaskEvaluator.isInsideRenderBounds("world", mapsDir, 5, 0, 0)); + } + + @Test + void polygonPointMissingCoordinateFailsOpen(@TempDir Path mapsDir) throws IOException { + writeConfig(mapsDir, "world.conf", """ + render-mask: [ + { + type: polygon + shape: [ + { x: 0, z: 0 } + { x: 10, z: 0 } + { x: 10 } + ] + } + ] + """); + + assertTrue(RenderMaskEvaluator.isInsideRenderBounds("world", mapsDir, 5, 0, 0)); + } + @Test void unrecognizedTypeFailsOpenForWholeMap(@TempDir Path mapsDir) throws IOException { writeConfig(mapsDir, "world.conf", """ diff --git a/src/test/java/com/tpwalke2/bluemapsignmarkers/core/markers/MarkerGroupTest.java b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/markers/MarkerGroupTest.java new file mode 100644 index 0000000..a4b2134 --- /dev/null +++ b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/markers/MarkerGroupTest.java @@ -0,0 +1,122 @@ +package com.tpwalke2.bluemapsignmarkers.core.markers; + +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class MarkerGroupTest { + + @Test + void defaultPoiGroupHasExpectedValues() { + var group = MarkerGroup.DEFAULT_POI_GROUP; + + assertEquals("[poi]", group.prefix()); + assertEquals(MarkerGroupMatchType.STARTS_WITH, group.matchType()); + assertEquals(MarkerGroupType.POI, group.type()); + assertEquals("Points of Interest", group.name()); + assertEquals(null, group.icon()); + assertEquals(0, group.offsetX()); + assertEquals(0, group.offsetY()); + assertFalse(group.defaultHidden()); + assertEquals(0.0, group.minDistance()); + assertEquals(10000000.0, group.maxDistance()); + assertEquals(2, group.lineWidth()); + assertEquals("#FF0000FF", group.lineColor()); + assertEquals("#FF000033", group.fillColor()); + assertEquals(0, group.sorting()); + assertTrue(group.toggleable()); + assertTrue(group.depthTest()); + assertEquals(List.of(), group.cssClasses()); + assertFalse(group.allowPlayerColors()); + } + + @Test + void constructorDefensivelyCopiesCssClasses() { + var mutable = new ArrayList(); + mutable.add("marker-a"); + + var group = markerGroup(mutable); + mutable.add("marker-b"); + + assertEquals(List.of("marker-a"), group.cssClasses()); + } + + @Test + void constructorAllowsNullPrefix() { + // SignLinesParser deliberately tolerates this (see SignLinesParser.hasValidPrefix) - a + // misconfigured group with no prefix logs a warning and is ignored, rather than the whole config + // load failing. + var group = markerGroupWithPrefix(null); + + assertEquals(null, group.prefix()); + } + + @Test + void constructorRejectsNullMatchType() { + assertThrows(NullPointerException.class, () -> new MarkerGroup( + "[poi]", null, MarkerGroupType.POI, "name", null, 0, 0, false, 0, 0, + 2, "#FF0000FF", "#FF000033", 0, true, true, List.of(), false)); + } + + @Test + void constructorRejectsNullType() { + assertThrows(NullPointerException.class, () -> new MarkerGroup( + "[poi]", MarkerGroupMatchType.STARTS_WITH, null, "name", null, 0, 0, false, 0, 0, + 2, "#FF0000FF", "#FF000033", 0, true, true, List.of(), false)); + } + + @Test + void constructorRejectsNullName() { + assertThrows(NullPointerException.class, () -> new MarkerGroup( + "[poi]", MarkerGroupMatchType.STARTS_WITH, MarkerGroupType.POI, null, null, 0, 0, false, 0, 0, + 2, "#FF0000FF", "#FF000033", 0, true, true, List.of(), false)); + } + + @Test + void constructorRejectsNullLineColor() { + assertThrows(NullPointerException.class, () -> new MarkerGroup( + "[poi]", MarkerGroupMatchType.STARTS_WITH, MarkerGroupType.POI, "name", null, 0, 0, false, 0, 0, + 2, null, "#FF000033", 0, true, true, List.of(), false)); + } + + @Test + void constructorRejectsNullFillColor() { + assertThrows(NullPointerException.class, () -> new MarkerGroup( + "[poi]", MarkerGroupMatchType.STARTS_WITH, MarkerGroupType.POI, "name", null, 0, 0, false, 0, 0, + 2, "#FF0000FF", null, 0, true, true, List.of(), false)); + } + + @Test + void constructorRejectsNullCssClasses() { + assertThrows(NullPointerException.class, () -> new MarkerGroup( + "[poi]", MarkerGroupMatchType.STARTS_WITH, MarkerGroupType.POI, "name", null, 0, 0, false, 0, 0, + 2, "#FF0000FF", "#FF000033", 0, true, true, null, false)); + } + + @Test + void constructorAllowsNullIcon() { + var group = new MarkerGroup( + "[poi]", MarkerGroupMatchType.STARTS_WITH, MarkerGroupType.POI, "name", null, 0, 0, false, 0, 0, + 2, "#FF0000FF", "#FF000033", 0, true, true, List.of(), false); + + assertEquals(null, group.icon()); + } + + private static MarkerGroup markerGroup(List cssClasses) { + return new MarkerGroup( + "[poi]", MarkerGroupMatchType.STARTS_WITH, MarkerGroupType.POI, "name", null, 0, 0, false, 0, 0, + 2, "#FF0000FF", "#FF000033", 0, true, true, cssClasses, false); + } + + private static MarkerGroup markerGroupWithPrefix(String prefix) { + return new MarkerGroup( + prefix, MarkerGroupMatchType.STARTS_WITH, MarkerGroupType.POI, "name", null, 0, 0, false, 0, 0, + 2, "#FF0000FF", "#FF000033", 0, true, true, List.of(), false); + } +} diff --git a/src/test/java/com/tpwalke2/bluemapsignmarkers/core/markers/MarkerIdentifierTest.java b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/markers/MarkerIdentifierTest.java new file mode 100644 index 0000000..e4439b3 --- /dev/null +++ b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/markers/MarkerIdentifierTest.java @@ -0,0 +1,23 @@ +package com.tpwalke2.bluemapsignmarkers.core.markers; + +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class MarkerIdentifierTest { + + @Test + void getIdFormatsCoordinates() { + var identifier = new MarkerIdentifier(1, -2, 3, new MarkerSetIdentifier("world", group())); + + assertEquals("x1_y-2_z3", identifier.getId()); + } + + private static MarkerGroup group() { + return new MarkerGroup( + "[poi]", MarkerGroupMatchType.STARTS_WITH, MarkerGroupType.POI, "name", null, 0, 0, false, 0, 0, + 2, "#FF0000FF", "#FF000033", 0, true, true, List.of(), false); + } +} diff --git a/src/test/java/com/tpwalke2/bluemapsignmarkers/core/markers/MarkerSetIdentifierCollectionTest.java b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/markers/MarkerSetIdentifierCollectionTest.java index 257466a..5f832cd 100644 --- a/src/test/java/com/tpwalke2/bluemapsignmarkers/core/markers/MarkerSetIdentifierCollectionTest.java +++ b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/markers/MarkerSetIdentifierCollectionTest.java @@ -13,11 +13,20 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; class MarkerSetIdentifierCollectionTest { + @Test + void getIdentifierReturnsNullForANullMapIdInsteadOfThrowing() { + var collection = new MarkerSetIdentifierCollection(); + var group = markerGroup("[poi]"); + + assertNull(collection.getIdentifier(null, group)); + } + @Test void getIdentifierReturnsTheSameInstanceForARepeatedCombo() { var collection = new MarkerSetIdentifierCollection(); diff --git a/src/test/java/com/tpwalke2/bluemapsignmarkers/core/markers/MultiPointMarkerIdentifierTest.java b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/markers/MultiPointMarkerIdentifierTest.java new file mode 100644 index 0000000..da1692d --- /dev/null +++ b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/markers/MultiPointMarkerIdentifierTest.java @@ -0,0 +1,37 @@ +package com.tpwalke2.bluemapsignmarkers.core.markers; + +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class MultiPointMarkerIdentifierTest { + + @Test + void getIdFormatsAsKindColonLabelForLine() { + var identifier = new MultiPointMarkerIdentifier("line", "Ridge Trail", new MarkerSetIdentifier("world", group(MarkerGroupType.LINE))); + + assertEquals("line:Ridge Trail", identifier.getId()); + } + + @Test + void getIdFormatsAsKindColonLabelForShape() { + var identifier = new MultiPointMarkerIdentifier("shape", "Town Border", new MarkerSetIdentifier("world", group(MarkerGroupType.SHAPE))); + + assertEquals("shape:Town Border", identifier.getId()); + } + + @Test + void getIdFormatsAsKindColonLabelForExtrude() { + var identifier = new MultiPointMarkerIdentifier("extrude", "Tower Base", new MarkerSetIdentifier("world", group(MarkerGroupType.EXTRUDE))); + + assertEquals("extrude:Tower Base", identifier.getId()); + } + + private static MarkerGroup group(MarkerGroupType type) { + return new MarkerGroup( + "[prefix]", MarkerGroupMatchType.STARTS_WITH, type, "name", null, 0, 0, false, 0, 0, + 2, "#FF0000FF", "#FF000033", 0, true, true, List.of(), false); + } +} diff --git a/src/test/java/com/tpwalke2/bluemapsignmarkers/core/reactive/ReactiveQueueTest.java b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/reactive/ReactiveQueueTest.java index f0b9ad7..82cb1b6 100644 --- a/src/test/java/com/tpwalke2/bluemapsignmarkers/core/reactive/ReactiveQueueTest.java +++ b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/reactive/ReactiveQueueTest.java @@ -61,15 +61,34 @@ void enqueueDeliversEachOfMultipleMessagesExactlyOnce() throws Exception { assertEquals(expected, Set.copyOf(received)); } + // Regression test for finding 63 (.scratch/concurrency-pass-2026-09/issues/04-reactivequeue-isshutdown-semantics.md): + // isShutdown() used to also return true for a queue that had simply never started (executor == null), + // conflating that state with a genuine shutdown - hasStarted() now answers "never started" directly, so + // isShutdown() no longer needs to (and doesn't) report true for it. @Test - void isShutdownIsTrueBeforeAnyWorkHasBeenScheduled() { + void isShutdownIsFalseAndHasStartedIsFalseBeforeAnyWorkHasBeenScheduled() { var queue = new ReactiveQueue(() -> true, message -> { }, error -> { }); - assertTrue(queue.isShutdown()); + assertFalse(queue.isShutdown(), "a queue that never processed anything is not shut down"); + assertFalse(queue.hasStarted(), "a queue that never processed anything has not started"); } + // The other conflated state from finding 63: shouldRun() being false stops process() from ever creating + // an executor, same as a queue that's simply never been enqueued to - neither is a genuine shutdown. @Test - void isShutdownIsFalseOnceWorkHasBeenScheduled() throws Exception { + void isShutdownIsFalseAndHasStartedIsFalseWhenShouldRunIsFalse() { + var invocations = new AtomicInteger(); + var queue = new ReactiveQueue(() -> false, message -> invocations.incrementAndGet(), error -> { }); + + queue.enqueue("hello"); + + assertEquals(0, invocations.get()); + assertFalse(queue.isShutdown(), "shouldRun() being false is not a shutdown"); + assertFalse(queue.hasStarted(), "process() returning early via shouldRun() never created an executor"); + } + + @Test + void isShutdownIsFalseAndHasStartedIsTrueOnceWorkHasBeenScheduled() throws Exception { var delivered = new CountDownLatch(1); var queue = new ReactiveQueue(() -> true, message -> delivered.countDown(), error -> { }); @@ -77,6 +96,7 @@ void isShutdownIsFalseOnceWorkHasBeenScheduled() throws Exception { assertTrue(delivered.await(5, TimeUnit.SECONDS)); assertFalse(queue.isShutdown()); + assertTrue(queue.hasStarted(), "a queue that has processed a message has started"); } @Test @@ -101,6 +121,7 @@ void shutdownBlocksUntilAnInFlightTaskFinishesBeforeReturning() throws Exception var taskStarted = new CountDownLatch(1); var releaseTask = new CountDownLatch(1); var taskFinished = new AtomicBoolean(false); + var shutdownConfirmedClean = new AtomicBoolean(false); var delegate = Executors.newFixedThreadPool(2); var queue = new ReactiveQueue( () -> true, @@ -115,7 +136,7 @@ void shutdownBlocksUntilAnInFlightTaskFinishesBeforeReturning() throws Exception queue.enqueue("hello"); assertTrue(taskStarted.await(5, TimeUnit.SECONDS), "processor task never started"); - var shutdownThread = new Thread(queue::shutdown); + var shutdownThread = new Thread(() -> shutdownConfirmedClean.set(queue.shutdown())); shutdownThread.start(); // Wait for shutdown() to have actually called executor.shutdown() (rather than guessing with // a fixed sleep) before asserting the task hasn't finished yet, so a slow/contended runner @@ -128,6 +149,93 @@ void shutdownBlocksUntilAnInFlightTaskFinishesBeforeReturning() throws Exception assertFalse(shutdownThread.isAlive(), "shutdown() should have returned by now"); assertTrue(taskFinished.get(), "shutdown() should not return until the in-flight task finished"); + assertTrue(shutdownConfirmedClean.get(), + "shutdown() should report a clean stop once the in-flight task actually finished"); + } finally { + delegate.shutdownNow(); + } + } + + @Test + void shutdownReturnsTrueWhenNoExecutorWasEverCreated() { + var queue = new ReactiveQueue(() -> true, message -> { }, error -> { }); + + assertTrue(queue.shutdown(), + "shutdown() should report a clean stop when there was never any work to await"); + } + + // Regression test for the configurable-timeout half of findings 26/27 + // (.scratch/concurrency-pass-2026-09/issues/02-reactivequeue-shutdown-guarantee-and-timeout.md): the + // await window used to be a hardcoded 5s constant. shutdown() now honors an explicitly configured + // (short) timeout instead of always waiting the 5s default. + @Test + void shutdownHonorsAConfiguredTimeoutShorterThanTheDefault() throws Exception { + var shutdownAwaitSeconds = 1L; + var taskStarted = new CountDownLatch(1); + var releaseTask = new CountDownLatch(1); + var delegate = Executors.newFixedThreadPool(1); + var queue = new ReactiveQueue( + () -> true, + message -> { + taskStarted.countDown(); + awaitUninterruptibly(releaseTask); + }, + error -> { }, + shutdownAwaitSeconds, + delegate); + try { + queue.enqueue("hello"); + assertTrue(taskStarted.await(5, TimeUnit.SECONDS), "processor task never started"); + + var start = System.nanoTime(); + releaseTask.countDown(); + assertTrue(queue.shutdown(), "shutdown() should report a clean stop once the task released"); + var elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start); + + assertTrue(elapsedMillis < TimeUnit.SECONDS.toMillis(4), + "shutdown() took " + elapsedMillis + "ms; a 1s configured timeout should return well " + + "under the 5s default, once the task is free to finish"); + } finally { + delegate.shutdownNow(); + } + } + + // Finding 64's "non-interruptible straggler" scenario: a task that ignores Thread.interrupt() entirely + // (blocked on non-interruptible I/O, or CPU-bound with no poll point) can still be running after both + // awaitTermination calls time out. shutdown() can't force it to stop, but must report that it couldn't + // confirm a clean stop rather than returning as if the guarantee held. + @Test + void shutdownReturnsFalseWhenATaskIgnoresInterruptionThroughBothAwaitWindows() throws Exception { + var shutdownAwaitSeconds = 1L; + var taskStarted = new CountDownLatch(1); + var delegate = Executors.newFixedThreadPool(1); + var queue = new ReactiveQueue( + () -> true, + message -> { + taskStarted.countDown(); + var deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(3); + // Deliberately never checks Thread.interrupted() - simulates a straggler that + // shutdownNow()'s interrupt can't actually stop. + while (System.nanoTime() < deadline) { + Thread.onSpinWait(); + } + }, + error -> { }, + shutdownAwaitSeconds, + delegate); + try { + queue.enqueue("hello"); + assertTrue(taskStarted.await(5, TimeUnit.SECONDS), "processor task never started"); + + var start = System.nanoTime(); + var confirmedClean = queue.shutdown(); + var elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start); + + assertFalse(confirmedClean, + "shutdown() should report it could not confirm a clean stop against a non-interruptible straggler"); + assertTrue(elapsedMillis >= TimeUnit.SECONDS.toMillis(2 * shutdownAwaitSeconds), + "shutdown() should have waited out both await windows (2x the configured timeout) before " + + "giving up, took " + elapsedMillis + "ms"); } finally { delegate.shutdownNow(); } @@ -190,7 +298,8 @@ void processDoesNotScheduleWorkWhileShouldRunIsFalse() { // shouldRun() is checked before any executor is touched, so nothing was ever scheduled. assertEquals(0, invocations.get()); - assertTrue(queue.isShutdown()); + // Not a shutdown - just never started (finding 63, see isShutdownIsFalseAndHasStartedIsFalseWhenShouldRunIsFalse). + assertFalse(queue.isShutdown()); } @Test @@ -265,14 +374,14 @@ void submissionFailureForOneMessageInvokesErrorCallbackAndLeavesLaterMessagesUna assertEquals(List.of("second"), received, "the failure on the first message should not stop later messages"); } - // Documents current behavior: messageProcessorCallback is invoked inside a task handed to - // ExecutorService.submit(), so an exception it throws is captured on that task's Future and never - // surfaces to the try/catch in processMessages() (nothing ever calls Future.get()). The error callback - // is only reachable via a submission-time failure (see the test above), not a processing exception. - // Known gap for the concurrency-hardening pass. + // Fixed for finding 8 (High) / ticket 01 (.scratch/concurrency-pass-2026-09/issues/01-reactivequeue-swallowed-exceptions.md): + // messageProcessorCallback is invoked inside a task handed to ExecutorService.submit(); that task now + // wraps the callback invocation in its own try/catch and routes any exception to + // messageProcessorErrorCallback, rather than letting it vanish on the task's unobserved Future. @Test - void exceptionThrownByProcessorCallbackIsNotSurfacedToTheErrorCallback() throws Exception { - var errors = new ArrayList(); + void exceptionThrownByProcessorCallbackIsSurfacedToTheErrorCallback() throws Exception { + var errors = new ConcurrentLinkedQueue(); + var errorDelivered = new CountDownLatch(1); var secondMessageDelivered = new CountDownLatch(1); var queue = new ReactiveQueue( () -> true, @@ -282,21 +391,53 @@ void exceptionThrownByProcessorCallbackIsNotSurfacedToTheErrorCallback() throws } secondMessageDelivered.countDown(); }, - errors::add); + error -> { + errors.add(error); + errorDelivered.countDown(); + }); queue.enqueue("first"); queue.enqueue("second"); assertTrue(secondMessageDelivered.await(5, TimeUnit.SECONDS), "later message should still be processed"); - assertTrue(errors.isEmpty(), "current implementation swallows processor exceptions rather than reporting them"); + assertTrue(errorDelivered.await(5, TimeUnit.SECONDS), "processor exception was never reported to the error callback"); + assertEquals(1, errors.size()); + assertEquals("boom", errors.peek().getMessage()); } - // Characterizes the current "before" behavior ahead of the concurrency-hardening pass: enqueue() - // unconditionally submits a fresh drain loop on every call rather than checking whether one is already - // running, so a burst of concurrent enqueues spawns more drain-loop submissions than there are messages. - // Despite that redundancy, every message is still delivered exactly once. + // Finding 64's "error-callback-throws" scenario: once a processor exception reaches + // messageProcessorErrorCallback, an exception thrown by the error callback itself must not kill the + // worker thread mid-drain (leaving later messages unprocessed) or propagate back to enqueue()'s caller. @Test - void concurrentEnqueueBurstDeliversEveryMessageExactlyOnceDespiteRedundantDrainLoopFanOut() throws Exception { + void exceptionThrownByTheErrorCallbackItselfDoesNotStopLaterMessagesFromBeingProcessed() throws Exception { + var secondMessageDelivered = new CountDownLatch(1); + var queue = new ReactiveQueue( + () -> true, + message -> { + if (message.equals("first")) { + throw new RuntimeException("boom"); + } + secondMessageDelivered.countDown(); + }, + error -> { + throw new RuntimeException("error callback also broken"); + }); + + queue.enqueue("first"); + queue.enqueue("second"); + + assertTrue(secondMessageDelivered.await(5, TimeUnit.SECONDS), + "a broken error callback should not stop later messages from being processed"); + } + + // Regression test for finding 62 (.scratch/concurrency-pass-2026-09/issues/03-reactivequeue-backpressure-and-redundant-drain.md): + // process() used to unconditionally submit a fresh drain loop on every enqueue() rather than checking + // whether one was already active, so a burst of concurrent enqueues could spawn as many redundant + // drain-loop tasks as messages (on top of the one submission per message actually needed). The + // in-flight-drain-loop guard now caps drain-loop submissions regardless of burst size, while still + // delivering every message exactly once. + @Test + void concurrentEnqueueBurstDeliversEveryMessageExactlyOnceWithBoundedDrainLoopSubmissions() throws Exception { final int messageCount = 20; var submissionCount = new AtomicInteger(); var delegate = Executors.newFixedThreadPool(Math.max(4, Runtime.getRuntime().availableProcessors())); @@ -331,16 +472,86 @@ void concurrentEnqueueBurstDeliversEveryMessageExactlyOnceDespiteRedundantDrainL assertEquals( IntStream.range(0, messageCount).boxed().collect(Collectors.toSet()), Set.copyOf(received)); + // One submission per message (the inner per-message task) plus a small, bounded number of + // drain-loop submissions (never one per enqueue() call) - nowhere near 2x messageCount, which + // is what unconditional per-enqueue drain-loop submission would produce. assertTrue( - submissionCount.get() > messageCount, - "expected more executor submissions than messages (redundant drain-loop fan-out), got " - + submissionCount.get()); + submissionCount.get() < messageCount * 2, + "expected drain-loop submissions to be bounded rather than scaling with the burst size, got " + + submissionCount.get() + " submissions for " + messageCount + " messages"); } finally { starters.shutdownNow(); delegate.shutdownNow(); } } + // Regression test for finding 61 (.scratch/concurrency-pass-2026-09/issues/03-reactivequeue-backpressure-and-redundant-drain.md): + // enqueue() now rejects (logs + drops) rather than growing the backing queue without bound once the + // configured capacity is reached. + @Test + void enqueueRejectsMessagesOnceCapacityIsReached() throws Exception { + var releaseProcessing = new CountDownLatch(1); + var firstMessageStarted = new CountDownLatch(1); + var received = new ConcurrentLinkedQueue(); + var delegate = Executors.newFixedThreadPool(1); + var capacity = 2; + var queue = new ReactiveQueue( + () -> true, + message -> { + firstMessageStarted.countDown(); + awaitUninterruptibly(releaseProcessing); + received.add(message); + }, + error -> { }, + delegate, + capacity); + try { + // Stays counted against capacity for as long as it's in flight - its slot isn't released + // until the callback above actually returns (see copilotreview.2026-09-09.md's "capacity + // does not bound backlog while processing is enabled" finding) - so it, not just what's + // still sitting in the internal queue, counts toward the limit below. + queue.enqueue(0); + assertTrue(firstMessageStarted.await(5, TimeUnit.SECONDS), "first message never started processing"); + + queue.enqueue(1); + // Capacity (2) is now exhausted: message 0 still in flight (blocked on releaseProcessing) plus + // message 1 queued behind it. + queue.enqueue(2); + + releaseProcessing.countDown(); + + assertTrue(awaitTrue(() -> received.size() >= 2, 5000), + "the messages that fit within capacity should still all be processed"); + assertEquals(List.of(0, 1), List.copyOf(received), + "message 2 should have been rejected once capacity was reached, never processed"); + } finally { + delegate.shutdownNow(); + } + } + + // Regression test for the "capacity rejection permanently loses marker state updates" finding + // (agent-context/reviews/copilotreview.2026-09-09.md): a caller with its own replay mechanism needs a + // way to learn that enqueue() dropped a message, so consumeOverflowSinceLastCheck() must actually flip + // true on overflow and reset to false once consumed rather than staying stuck either way. + @Test + void consumeOverflowSinceLastCheckReportsAndClearsCapacityRejection() { + var delegate = Executors.newSingleThreadExecutor(); + try { + var queue = new ReactiveQueue( + () -> false, message -> { }, error -> { }, delegate, 1); + + assertFalse(queue.consumeOverflowSinceLastCheck(), "no overflow should be reported before any rejection"); + + queue.enqueue(0); + queue.enqueue(1); // rejected: capacity is 1 and shouldRun() is always false, so nothing ever drains + + assertTrue(queue.consumeOverflowSinceLastCheck(), "a rejected enqueue should be reported as overflow"); + assertFalse(queue.consumeOverflowSinceLastCheck(), "overflow should be cleared once consumed"); + } finally { + delegate.shutdownNow(); + } + } + // Investigated for ticket 09 (.scratch/codebase-review-followups/issues/09-reactivequeue-message-ordering.md): // processMessages() submits each queued message as its own independent task to the executor // (see ReactiveQueue.processMessages), so there is no guarantee a message finishes - or even diff --git a/src/test/java/com/tpwalke2/bluemapsignmarkers/core/signs/SignEntryHelperTest.java b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/signs/SignEntryHelperTest.java index 465d208..d476e75 100644 --- a/src/test/java/com/tpwalke2/bluemapsignmarkers/core/signs/SignEntryHelperTest.java +++ b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/signs/SignEntryHelperTest.java @@ -95,6 +95,15 @@ void getLabelFallsBackToBackTextWhenFrontBlank() { assertEquals("Back Label", SignEntryHelper.getLabel(entry)); } + @Test + void getLabelReturnsEmptyWhenSidesMatchDifferentGroups() { + // Front and back match different marker groups - the marker belongs to the front's group + // (getPrefix prefers front), so a blank front label must not fall back to the back's label. + var entry = signEntry(parsed("[poi]", "", ""), parsed("[event]", "Fair", "Fair")); + + assertEquals("", SignEntryHelper.getLabel(entry)); + } + @Test void getLabelReturnsEmptyWhenBothBlank() { var entry = signEntry(empty(), empty()); diff --git a/src/test/java/com/tpwalke2/bluemapsignmarkers/core/signs/SignLinesParserTest.java b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/signs/SignLinesParserTest.java index 80c64dc..bae3bf3 100644 --- a/src/test/java/com/tpwalke2/bluemapsignmarkers/core/signs/SignLinesParserTest.java +++ b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/signs/SignLinesParserTest.java @@ -4,10 +4,12 @@ import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerGroupMatchType; import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerGroupType; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; class SignLinesParserTest { @@ -195,4 +197,52 @@ void regexPrefixWithTrailingLabelTextOnTheSameLineResultsInBlankLabel() { assertEquals("", result.label()); assertEquals("", result.detail()); } + + @Test + @Timeout(5) + void pathologicalRegexAgainstOversizedLineDoesNotHang() { + // A single nested quantifier ((a+)+) is the textbook catastrophic-backtracking example, but + // the JVM's own regex engine already special-cases that shape. Several sequential unbounded + // capturing groups over the same character class ((a*)(a*)(a*)(a*)) still exhibits genuine + // combinatorial blowup that grows sharply with input length - without a cap, matching this + // against tens of thousands of characters would not finish in any practical time. The + // line-length cap truncates the line to a fixed size before it ever reaches line.matches(...), + // so the match cost stays bounded regardless of how long the attacking sign text is. + var parser = new SignLinesParser(List.of(regexGroup("(a*)(a*)(a*)(a*)b", "Pathological"))); + + var adversarialLine = "a".repeat(50_000); + var result = parser.parse(new String[]{adversarialLine}); + + assertNull(result.prefix()); + } + + @Test + void oversizedLineIsTruncatedBeforeMatching() { + var parser = new SignLinesParser(List.of(startsWithGroup("[poi]", "Points of Interest"))); + + var prefix = "[poi] "; + var longLabel = "x".repeat(200); + var result = parser.parse(new String[]{prefix + longLabel}); + + assertEquals("[poi]", result.prefix()); + assertEquals(100 - prefix.length(), result.label().length()); + } + + @Test + void oversizedLineTruncationDoesNotSplitASurrogatePair() { + // Copilot review finding: substring(0, MAX_LINE_LENGTH) can land mid-surrogate-pair when the + // line contains characters outside the BMP (e.g. an emoji), leaving an unpaired low/high + // surrogate in the truncated string. Build a label whose emoji straddles the truncation + // boundary and verify truncation backs off a character instead of splitting the pair. + var parser = new SignLinesParser(List.of(startsWithGroup("[poi]", "Points of Interest"))); + + var prefix = "[poi] "; + var padding = "x".repeat(100 - prefix.length() - 1); + var emoji = "😀"; // U+1F600, a surrogate pair + var result = parser.parse(new String[]{prefix + padding + emoji}); + + assertEquals("[poi]", result.prefix()); + assertFalse(Character.isLowSurrogate(result.label().charAt(result.label().length() - 1))); + assertFalse(Character.isHighSurrogate(result.label().charAt(result.label().length() - 1))); + } } diff --git a/src/test/java/com/tpwalke2/bluemapsignmarkers/core/signs/SignTransitionResolverTest.java b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/signs/SignTransitionResolverTest.java index b9f0e80..58fd77f 100644 --- a/src/test/java/com/tpwalke2/bluemapsignmarkers/core/signs/SignTransitionResolverTest.java +++ b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/signs/SignTransitionResolverTest.java @@ -4,18 +4,15 @@ import com.tpwalke2.bluemapsignmarkers.core.bluemap.actions.AddMarkerAction; import com.tpwalke2.bluemapsignmarkers.core.bluemap.actions.GroupTransitionMarkerAction; import com.tpwalke2.bluemapsignmarkers.core.bluemap.actions.MarkerAction; -import com.tpwalke2.bluemapsignmarkers.core.bluemap.actions.RemoveExtrudeMarkerAction; -import com.tpwalke2.bluemapsignmarkers.core.bluemap.actions.RemoveLineMarkerAction; import com.tpwalke2.bluemapsignmarkers.core.bluemap.actions.RemoveMarkerAction; -import com.tpwalke2.bluemapsignmarkers.core.bluemap.actions.RemoveShapeMarkerAction; -import com.tpwalke2.bluemapsignmarkers.core.bluemap.actions.SetExtrudeMarkerAction; -import com.tpwalke2.bluemapsignmarkers.core.bluemap.actions.SetLineMarkerAction; -import com.tpwalke2.bluemapsignmarkers.core.bluemap.actions.SetShapeMarkerAction; +import com.tpwalke2.bluemapsignmarkers.core.bluemap.actions.RemoveMultiPointMarkerAction; +import com.tpwalke2.bluemapsignmarkers.core.bluemap.actions.SetMultiPointMarkerAction; import com.tpwalke2.bluemapsignmarkers.core.bluemap.actions.UpdateMarkerAction; import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerGroup; import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerGroupMatchType; import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerGroupType; import com.tpwalke2.bluemapsignmarkers.core.markers.MarkerSetIdentifierCollection; +import com.tpwalke2.bluemapsignmarkers.core.markers.MultiPointMarkerIdentifier; import org.junit.jupiter.api.Test; import java.util.List; @@ -134,7 +131,8 @@ void noneToLineAtExactlyTwoMembersDispatchesSetWithFirstAppearanceTrue() { var action = SignTransitionResolver.computeTransitionAction(() -> List.of(first, second), second.key(), null, newRep, actionFactory(), false, Map.of(group.prefix(), group)); - var set = assertInstanceOf(SetLineMarkerAction.class, action); + var set = assertInstanceOf(SetMultiPointMarkerAction.class, action); + assertEquals("line", ((MultiPointMarkerIdentifier) set.getMarkerIdentifier()).kind()); assertTrue(set.isFirstAppearance()); assertEquals(2, set.getPoints().size()); assertEquals("d2", set.getDetail()); @@ -150,7 +148,7 @@ void noneToLineJoiningAThirdMemberDispatchesSetWithFirstAppearanceFalse() { var action = SignTransitionResolver.computeTransitionAction(() -> List.of(first, second, third), third.key(), null, newRep, actionFactory(), false, Map.of(group.prefix(), group)); - var set = assertInstanceOf(SetLineMarkerAction.class, action); + var set = assertInstanceOf(SetMultiPointMarkerAction.class, action); assertTrue(!set.isFirstAppearance()); assertEquals("d3", set.getDetail()); assertEquals(3, set.getPoints().size()); @@ -233,7 +231,8 @@ void lineToNoneDroppingToOneRemainingMemberDispatchesRemoveLine() { var action = SignTransitionResolver.computeTransitionAction(() -> List.of(remaining), departing.key(), oldRep, null, actionFactory(), false, Map.of(group.prefix(), group)); - assertInstanceOf(RemoveLineMarkerAction.class, action); + var remove = assertInstanceOf(RemoveMultiPointMarkerAction.class, action); + assertEquals("line", ((MultiPointMarkerIdentifier) remove.getMarkerIdentifier()).kind()); } @Test @@ -257,7 +256,7 @@ void lineToNoneWithTwoOrMoreRemainingDispatchesRefreshedSet() { var action = SignTransitionResolver.computeTransitionAction(() -> List.of(remaining1, remaining2), departing.key(), oldRep, null, actionFactory(), false, Map.of(group.prefix(), group)); - var set = assertInstanceOf(SetLineMarkerAction.class, action); + var set = assertInstanceOf(SetMultiPointMarkerAction.class, action); assertEquals(2, set.getPoints().size()); assertEquals("d1", set.getDetail()); } @@ -286,7 +285,7 @@ void lineToLineSameGroupAndLabelDetailChangedDispatchesSetWithFirstAppearanceFal var action = SignTransitionResolver.computeTransitionAction(() -> List.of(newEntry, other), newEntry.key(), oldRep, newRep, actionFactory(), false, Map.of(group.prefix(), group)); - var set = assertInstanceOf(SetLineMarkerAction.class, action); + var set = assertInstanceOf(SetMultiPointMarkerAction.class, action); assertTrue(!set.isFirstAppearance()); } @@ -300,7 +299,7 @@ void lineToLineSameGroupAndLabelDetailUnchangedOnReloadDispatchesSet() { var action = SignTransitionResolver.computeTransitionAction(() -> List.of(self, other), self.key(), oldRep, newRep, actionFactory(), true, Map.of(group.prefix(), group)); - var set = assertInstanceOf(SetLineMarkerAction.class, action); + var set = assertInstanceOf(SetMultiPointMarkerAction.class, action); assertEquals(2, set.getPoints().size()); assertEquals("detail", set.getDetail()); } @@ -320,8 +319,8 @@ void lineToLineDifferentGroupBundlesLeaveAndJoin() { var transition = assertInstanceOf(GroupTransitionMarkerAction.class, action); assertEquals(2, transition.effects().size()); - assertInstanceOf(RemoveLineMarkerAction.class, transition.effects().get(0)); - var join = assertInstanceOf(SetLineMarkerAction.class, transition.effects().get(1)); + assertInstanceOf(RemoveMultiPointMarkerAction.class, transition.effects().get(0)); + var join = assertInstanceOf(SetMultiPointMarkerAction.class, transition.effects().get(1)); assertEquals(2, join.getPoints().size()); } @@ -339,7 +338,7 @@ void poiToLineBundlesRemovePoiAndSetLine() { var transition = assertInstanceOf(GroupTransitionMarkerAction.class, action); assertEquals(2, transition.effects().size()); assertInstanceOf(RemoveMarkerAction.class, transition.effects().get(0)); - assertInstanceOf(SetLineMarkerAction.class, transition.effects().get(1)); + assertInstanceOf(SetMultiPointMarkerAction.class, transition.effects().get(1)); } @Test @@ -357,7 +356,7 @@ void lineToPoiBundlesSetLineAndAddPoi() { var transition = assertInstanceOf(GroupTransitionMarkerAction.class, action); assertEquals(2, transition.effects().size()); - var leave = assertInstanceOf(SetLineMarkerAction.class, transition.effects().get(0)); + var leave = assertInstanceOf(SetMultiPointMarkerAction.class, transition.effects().get(0)); assertEquals(2, leave.getPoints().size()); assertInstanceOf(AddMarkerAction.class, transition.effects().get(1)); } @@ -386,7 +385,8 @@ void noneToShapeAtExactlyThreeMembersDispatchesSetWithFirstAppearanceTrue() { var action = SignTransitionResolver.computeTransitionAction(() -> List.of(first, second, third), third.key(), null, newRep, actionFactory(), false, Map.of(group.prefix(), group)); - var set = assertInstanceOf(SetShapeMarkerAction.class, action); + var set = assertInstanceOf(SetMultiPointMarkerAction.class, action); + assertEquals("shape", ((MultiPointMarkerIdentifier) set.getMarkerIdentifier()).kind()); assertTrue(set.isFirstAppearance()); assertEquals(3, set.getPoints().size()); assertEquals("d3", set.getDetail()); @@ -403,7 +403,7 @@ void noneToShapeJoiningAFourthMemberDispatchesSetWithFirstAppearanceFalse() { var action = SignTransitionResolver.computeTransitionAction(() -> List.of(first, second, third, fourth), fourth.key(), null, newRep, actionFactory(), false, Map.of(group.prefix(), group)); - var set = assertInstanceOf(SetShapeMarkerAction.class, action); + var set = assertInstanceOf(SetMultiPointMarkerAction.class, action); assertTrue(!set.isFirstAppearance()); assertEquals(4, set.getPoints().size()); } @@ -418,7 +418,8 @@ void shapeToNoneDroppingToTwoRemainingMembersDispatchesRemoveShape() { var action = SignTransitionResolver.computeTransitionAction(() -> List.of(remaining1, remaining2), departing.key(), oldRep, null, actionFactory(), false, Map.of(group.prefix(), group)); - assertInstanceOf(RemoveShapeMarkerAction.class, action); + var remove = assertInstanceOf(RemoveMultiPointMarkerAction.class, action); + assertEquals("shape", ((MultiPointMarkerIdentifier) remove.getMarkerIdentifier()).kind()); } @Test @@ -446,7 +447,7 @@ void shapeToNoneWithThreeOrMoreRemainingDispatchesRefreshedSet() { var action = SignTransitionResolver.computeTransitionAction(() -> List.of(remaining1, remaining2, remaining3), departing.key(), oldRep, null, actionFactory(), false, Map.of(group.prefix(), group)); - var set = assertInstanceOf(SetShapeMarkerAction.class, action); + var set = assertInstanceOf(SetMultiPointMarkerAction.class, action); assertEquals(3, set.getPoints().size()); assertEquals("d1", set.getDetail()); } @@ -477,7 +478,7 @@ void shapeToShapeSameGroupAndLabelDetailChangedDispatchesSetWithFirstAppearanceF var action = SignTransitionResolver.computeTransitionAction(() -> List.of(newEntry, other1, other2), newEntry.key(), oldRep, newRep, actionFactory(), false, Map.of(group.prefix(), group)); - var set = assertInstanceOf(SetShapeMarkerAction.class, action); + var set = assertInstanceOf(SetMultiPointMarkerAction.class, action); assertTrue(!set.isFirstAppearance()); } @@ -492,7 +493,7 @@ void shapeToShapeSameGroupAndLabelDetailUnchangedOnReloadDispatchesSet() { var action = SignTransitionResolver.computeTransitionAction(() -> List.of(self, other1, other2), self.key(), oldRep, newRep, actionFactory(), true, Map.of(group.prefix(), group)); - var set = assertInstanceOf(SetShapeMarkerAction.class, action); + var set = assertInstanceOf(SetMultiPointMarkerAction.class, action); assertEquals(3, set.getPoints().size()); assertEquals("detail", set.getDetail()); } @@ -514,8 +515,8 @@ void shapeToShapeDifferentGroupBundlesLeaveAndJoin() { var transition = assertInstanceOf(GroupTransitionMarkerAction.class, action); assertEquals(2, transition.effects().size()); - assertInstanceOf(RemoveShapeMarkerAction.class, transition.effects().get(0)); - var join = assertInstanceOf(SetShapeMarkerAction.class, transition.effects().get(1)); + assertInstanceOf(RemoveMultiPointMarkerAction.class, transition.effects().get(0)); + var join = assertInstanceOf(SetMultiPointMarkerAction.class, transition.effects().get(1)); assertEquals(3, join.getPoints().size()); } @@ -536,7 +537,7 @@ void poiToShapeBundlesRemovePoiAndSetShape() { var transition = assertInstanceOf(GroupTransitionMarkerAction.class, action); assertEquals(2, transition.effects().size()); assertInstanceOf(RemoveMarkerAction.class, transition.effects().get(0)); - var join = assertInstanceOf(SetShapeMarkerAction.class, transition.effects().get(1)); + var join = assertInstanceOf(SetMultiPointMarkerAction.class, transition.effects().get(1)); assertTrue(join.isFirstAppearance()); } @@ -556,7 +557,7 @@ void shapeToPoiBundlesSetShapeAndAddPoi() { var transition = assertInstanceOf(GroupTransitionMarkerAction.class, action); assertEquals(2, transition.effects().size()); - var leave = assertInstanceOf(SetShapeMarkerAction.class, transition.effects().get(0)); + var leave = assertInstanceOf(SetMultiPointMarkerAction.class, transition.effects().get(0)); assertEquals(3, leave.getPoints().size()); assertInstanceOf(AddMarkerAction.class, transition.effects().get(1)); } @@ -577,8 +578,8 @@ void lineToShapeBundlesRemoveLineAndSetShape() { var transition = assertInstanceOf(GroupTransitionMarkerAction.class, action); assertEquals(2, transition.effects().size()); - assertInstanceOf(RemoveLineMarkerAction.class, transition.effects().get(0)); - var join = assertInstanceOf(SetShapeMarkerAction.class, transition.effects().get(1)); + assertInstanceOf(RemoveMultiPointMarkerAction.class, transition.effects().get(0)); + var join = assertInstanceOf(SetMultiPointMarkerAction.class, transition.effects().get(1)); assertTrue(join.isFirstAppearance()); } @@ -598,8 +599,8 @@ void shapeToLineBundlesRemoveShapeAndSetLine() { var transition = assertInstanceOf(GroupTransitionMarkerAction.class, action); assertEquals(2, transition.effects().size()); - assertInstanceOf(RemoveShapeMarkerAction.class, transition.effects().get(0)); - assertInstanceOf(SetLineMarkerAction.class, transition.effects().get(1)); + assertInstanceOf(RemoveMultiPointMarkerAction.class, transition.effects().get(0)); + assertInstanceOf(SetMultiPointMarkerAction.class, transition.effects().get(1)); } // --- isReload variants for POI<->SHAPE and LINE<->SHAPE flips, mirroring the existing POI/LINE reload coverage --- @@ -619,7 +620,7 @@ void poiToShapeOnReloadStillBundlesRemovePoiAndSetShape() { var transition = assertInstanceOf(GroupTransitionMarkerAction.class, action); assertEquals(2, transition.effects().size()); assertInstanceOf(RemoveMarkerAction.class, transition.effects().get(0)); - var join = assertInstanceOf(SetShapeMarkerAction.class, transition.effects().get(1)); + var join = assertInstanceOf(SetMultiPointMarkerAction.class, transition.effects().get(1)); assertTrue(join.isFirstAppearance()); } @@ -639,7 +640,7 @@ void shapeToPoiOnReloadStillBundlesSetShapeAndAddPoi() { var transition = assertInstanceOf(GroupTransitionMarkerAction.class, action); assertEquals(2, transition.effects().size()); - var leave = assertInstanceOf(SetShapeMarkerAction.class, transition.effects().get(0)); + var leave = assertInstanceOf(SetMultiPointMarkerAction.class, transition.effects().get(0)); assertEquals(3, leave.getPoints().size()); assertInstanceOf(AddMarkerAction.class, transition.effects().get(1)); } @@ -660,8 +661,8 @@ void lineToShapeOnReloadStillBundlesRemoveLineAndSetShape() { var transition = assertInstanceOf(GroupTransitionMarkerAction.class, action); assertEquals(2, transition.effects().size()); - assertInstanceOf(RemoveLineMarkerAction.class, transition.effects().get(0)); - var join = assertInstanceOf(SetShapeMarkerAction.class, transition.effects().get(1)); + assertInstanceOf(RemoveMultiPointMarkerAction.class, transition.effects().get(0)); + var join = assertInstanceOf(SetMultiPointMarkerAction.class, transition.effects().get(1)); assertTrue(join.isFirstAppearance()); } @@ -681,8 +682,8 @@ void shapeToLineOnReloadStillBundlesRemoveShapeAndSetLine() { var transition = assertInstanceOf(GroupTransitionMarkerAction.class, action); assertEquals(2, transition.effects().size()); - assertInstanceOf(RemoveShapeMarkerAction.class, transition.effects().get(0)); - assertInstanceOf(SetLineMarkerAction.class, transition.effects().get(1)); + assertInstanceOf(RemoveMultiPointMarkerAction.class, transition.effects().get(0)); + assertInstanceOf(SetMultiPointMarkerAction.class, transition.effects().get(1)); } // Regression for agent-context/reviews/review-2026-08-20.md: a reload where a group's *type* flips @@ -705,7 +706,7 @@ void shapeToPoiConfigOnlyTypeFlipOnReloadRemovesShapeInsteadOfRecomputing() { var transition = assertInstanceOf(GroupTransitionMarkerAction.class, action); assertEquals(2, transition.effects().size()); - assertInstanceOf(RemoveShapeMarkerAction.class, transition.effects().get(0)); + assertInstanceOf(RemoveMultiPointMarkerAction.class, transition.effects().get(0)); assertInstanceOf(AddMarkerAction.class, transition.effects().get(1)); } @@ -728,9 +729,9 @@ void shapeToShapeGroupRenameOnReloadBundlesRemoveOldSetAndAddNewSet() { var transition = assertInstanceOf(GroupTransitionMarkerAction.class, action); assertEquals(2, transition.effects().size()); - var leave = assertInstanceOf(RemoveShapeMarkerAction.class, transition.effects().get(0)); + var leave = assertInstanceOf(RemoveMultiPointMarkerAction.class, transition.effects().get(0)); assertEquals(oldGroup, leave.getMarkerIdentifier().parentSet().markerGroup()); - var join = assertInstanceOf(SetShapeMarkerAction.class, transition.effects().get(1)); + var join = assertInstanceOf(SetMultiPointMarkerAction.class, transition.effects().get(1)); assertEquals(newGroup, join.getMarkerIdentifier().parentSet().markerGroup()); assertEquals(3, join.getPoints().size()); } @@ -759,7 +760,8 @@ void noneToExtrudeAtExactlyThreeMembersDispatchesSetWithFirstAppearanceTrue() { var action = SignTransitionResolver.computeTransitionAction(() -> List.of(first, second, third), third.key(), null, newRep, actionFactory(), false, Map.of(group.prefix(), group)); - var set = assertInstanceOf(SetExtrudeMarkerAction.class, action); + var set = assertInstanceOf(SetMultiPointMarkerAction.class, action); + assertEquals("extrude", ((MultiPointMarkerIdentifier) set.getMarkerIdentifier()).kind()); assertTrue(set.isFirstAppearance()); assertEquals(3, set.getPoints().size()); assertEquals("d3", set.getDetail()); @@ -776,7 +778,7 @@ void noneToExtrudeJoiningAFourthMemberDispatchesSetWithFirstAppearanceFalse() { var action = SignTransitionResolver.computeTransitionAction(() -> List.of(first, second, third, fourth), fourth.key(), null, newRep, actionFactory(), false, Map.of(group.prefix(), group)); - var set = assertInstanceOf(SetExtrudeMarkerAction.class, action); + var set = assertInstanceOf(SetMultiPointMarkerAction.class, action); assertTrue(!set.isFirstAppearance()); assertEquals(4, set.getPoints().size()); } @@ -791,7 +793,8 @@ void extrudeToNoneDroppingToTwoRemainingMembersDispatchesRemoveExtrude() { var action = SignTransitionResolver.computeTransitionAction(() -> List.of(remaining1, remaining2), departing.key(), oldRep, null, actionFactory(), false, Map.of(group.prefix(), group)); - assertInstanceOf(RemoveExtrudeMarkerAction.class, action); + var remove = assertInstanceOf(RemoveMultiPointMarkerAction.class, action); + assertEquals("extrude", ((MultiPointMarkerIdentifier) remove.getMarkerIdentifier()).kind()); } @Test @@ -819,7 +822,7 @@ void extrudeToNoneWithThreeOrMoreRemainingDispatchesRefreshedSet() { var action = SignTransitionResolver.computeTransitionAction(() -> List.of(remaining1, remaining2, remaining3), departing.key(), oldRep, null, actionFactory(), false, Map.of(group.prefix(), group)); - var set = assertInstanceOf(SetExtrudeMarkerAction.class, action); + var set = assertInstanceOf(SetMultiPointMarkerAction.class, action); assertEquals(3, set.getPoints().size()); assertEquals("d1", set.getDetail()); } @@ -850,7 +853,7 @@ void extrudeToExtrudeSameGroupAndLabelDetailChangedDispatchesSetWithFirstAppeara var action = SignTransitionResolver.computeTransitionAction(() -> List.of(newEntry, other1, other2), newEntry.key(), oldRep, newRep, actionFactory(), false, Map.of(group.prefix(), group)); - var set = assertInstanceOf(SetExtrudeMarkerAction.class, action); + var set = assertInstanceOf(SetMultiPointMarkerAction.class, action); assertTrue(!set.isFirstAppearance()); } @@ -865,7 +868,7 @@ void extrudeToExtrudeSameGroupAndLabelDetailUnchangedOnReloadDispatchesSet() { var action = SignTransitionResolver.computeTransitionAction(() -> List.of(self, other1, other2), self.key(), oldRep, newRep, actionFactory(), true, Map.of(group.prefix(), group)); - var set = assertInstanceOf(SetExtrudeMarkerAction.class, action); + var set = assertInstanceOf(SetMultiPointMarkerAction.class, action); assertEquals(3, set.getPoints().size()); assertEquals("detail", set.getDetail()); } @@ -887,8 +890,8 @@ void extrudeToExtrudeDifferentGroupBundlesLeaveAndJoin() { var transition = assertInstanceOf(GroupTransitionMarkerAction.class, action); assertEquals(2, transition.effects().size()); - assertInstanceOf(RemoveExtrudeMarkerAction.class, transition.effects().get(0)); - var join = assertInstanceOf(SetExtrudeMarkerAction.class, transition.effects().get(1)); + assertInstanceOf(RemoveMultiPointMarkerAction.class, transition.effects().get(0)); + var join = assertInstanceOf(SetMultiPointMarkerAction.class, transition.effects().get(1)); assertEquals(3, join.getPoints().size()); } @@ -909,7 +912,7 @@ void poiToExtrudeBundlesRemovePoiAndSetExtrude() { var transition = assertInstanceOf(GroupTransitionMarkerAction.class, action); assertEquals(2, transition.effects().size()); assertInstanceOf(RemoveMarkerAction.class, transition.effects().get(0)); - var join = assertInstanceOf(SetExtrudeMarkerAction.class, transition.effects().get(1)); + var join = assertInstanceOf(SetMultiPointMarkerAction.class, transition.effects().get(1)); assertTrue(join.isFirstAppearance()); } @@ -929,7 +932,7 @@ void extrudeToPoiBundlesSetExtrudeAndAddPoi() { var transition = assertInstanceOf(GroupTransitionMarkerAction.class, action); assertEquals(2, transition.effects().size()); - var leave = assertInstanceOf(SetExtrudeMarkerAction.class, transition.effects().get(0)); + var leave = assertInstanceOf(SetMultiPointMarkerAction.class, transition.effects().get(0)); assertEquals(3, leave.getPoints().size()); assertInstanceOf(AddMarkerAction.class, transition.effects().get(1)); } @@ -950,8 +953,8 @@ void lineToExtrudeBundlesRemoveLineAndSetExtrude() { var transition = assertInstanceOf(GroupTransitionMarkerAction.class, action); assertEquals(2, transition.effects().size()); - assertInstanceOf(RemoveLineMarkerAction.class, transition.effects().get(0)); - var join = assertInstanceOf(SetExtrudeMarkerAction.class, transition.effects().get(1)); + assertInstanceOf(RemoveMultiPointMarkerAction.class, transition.effects().get(0)); + var join = assertInstanceOf(SetMultiPointMarkerAction.class, transition.effects().get(1)); assertTrue(join.isFirstAppearance()); } @@ -971,8 +974,8 @@ void extrudeToLineBundlesRemoveExtrudeAndSetLine() { var transition = assertInstanceOf(GroupTransitionMarkerAction.class, action); assertEquals(2, transition.effects().size()); - assertInstanceOf(RemoveExtrudeMarkerAction.class, transition.effects().get(0)); - assertInstanceOf(SetLineMarkerAction.class, transition.effects().get(1)); + assertInstanceOf(RemoveMultiPointMarkerAction.class, transition.effects().get(0)); + assertInstanceOf(SetMultiPointMarkerAction.class, transition.effects().get(1)); } @Test @@ -992,8 +995,8 @@ void shapeToExtrudeBundlesRemoveShapeAndSetExtrude() { var transition = assertInstanceOf(GroupTransitionMarkerAction.class, action); assertEquals(2, transition.effects().size()); - assertInstanceOf(RemoveShapeMarkerAction.class, transition.effects().get(0)); - var join = assertInstanceOf(SetExtrudeMarkerAction.class, transition.effects().get(1)); + assertInstanceOf(RemoveMultiPointMarkerAction.class, transition.effects().get(0)); + var join = assertInstanceOf(SetMultiPointMarkerAction.class, transition.effects().get(1)); assertTrue(join.isFirstAppearance()); } @@ -1014,8 +1017,8 @@ void extrudeToShapeBundlesRemoveExtrudeAndSetShape() { var transition = assertInstanceOf(GroupTransitionMarkerAction.class, action); assertEquals(2, transition.effects().size()); - assertInstanceOf(RemoveExtrudeMarkerAction.class, transition.effects().get(0)); - var join = assertInstanceOf(SetShapeMarkerAction.class, transition.effects().get(1)); + assertInstanceOf(RemoveMultiPointMarkerAction.class, transition.effects().get(0)); + var join = assertInstanceOf(SetMultiPointMarkerAction.class, transition.effects().get(1)); assertTrue(join.isFirstAppearance()); } @@ -1036,7 +1039,7 @@ void poiToExtrudeOnReloadStillBundlesRemovePoiAndSetExtrude() { var transition = assertInstanceOf(GroupTransitionMarkerAction.class, action); assertEquals(2, transition.effects().size()); assertInstanceOf(RemoveMarkerAction.class, transition.effects().get(0)); - var join = assertInstanceOf(SetExtrudeMarkerAction.class, transition.effects().get(1)); + var join = assertInstanceOf(SetMultiPointMarkerAction.class, transition.effects().get(1)); assertTrue(join.isFirstAppearance()); } @@ -1056,7 +1059,7 @@ void extrudeToPoiOnReloadStillBundlesSetExtrudeAndAddPoi() { var transition = assertInstanceOf(GroupTransitionMarkerAction.class, action); assertEquals(2, transition.effects().size()); - var leave = assertInstanceOf(SetExtrudeMarkerAction.class, transition.effects().get(0)); + var leave = assertInstanceOf(SetMultiPointMarkerAction.class, transition.effects().get(0)); assertEquals(3, leave.getPoints().size()); assertInstanceOf(AddMarkerAction.class, transition.effects().get(1)); } @@ -1077,8 +1080,8 @@ void lineToExtrudeOnReloadStillBundlesRemoveLineAndSetExtrude() { var transition = assertInstanceOf(GroupTransitionMarkerAction.class, action); assertEquals(2, transition.effects().size()); - assertInstanceOf(RemoveLineMarkerAction.class, transition.effects().get(0)); - var join = assertInstanceOf(SetExtrudeMarkerAction.class, transition.effects().get(1)); + assertInstanceOf(RemoveMultiPointMarkerAction.class, transition.effects().get(0)); + var join = assertInstanceOf(SetMultiPointMarkerAction.class, transition.effects().get(1)); assertTrue(join.isFirstAppearance()); } @@ -1098,8 +1101,8 @@ void extrudeToLineOnReloadStillBundlesRemoveExtrudeAndSetLine() { var transition = assertInstanceOf(GroupTransitionMarkerAction.class, action); assertEquals(2, transition.effects().size()); - assertInstanceOf(RemoveExtrudeMarkerAction.class, transition.effects().get(0)); - assertInstanceOf(SetLineMarkerAction.class, transition.effects().get(1)); + assertInstanceOf(RemoveMultiPointMarkerAction.class, transition.effects().get(0)); + assertInstanceOf(SetMultiPointMarkerAction.class, transition.effects().get(1)); } @Test @@ -1119,8 +1122,8 @@ void shapeToExtrudeOnReloadStillBundlesRemoveShapeAndSetExtrude() { var transition = assertInstanceOf(GroupTransitionMarkerAction.class, action); assertEquals(2, transition.effects().size()); - assertInstanceOf(RemoveShapeMarkerAction.class, transition.effects().get(0)); - var join = assertInstanceOf(SetExtrudeMarkerAction.class, transition.effects().get(1)); + assertInstanceOf(RemoveMultiPointMarkerAction.class, transition.effects().get(0)); + var join = assertInstanceOf(SetMultiPointMarkerAction.class, transition.effects().get(1)); assertTrue(join.isFirstAppearance()); } @@ -1141,8 +1144,8 @@ void extrudeToShapeOnReloadStillBundlesRemoveExtrudeAndSetShape() { var transition = assertInstanceOf(GroupTransitionMarkerAction.class, action); assertEquals(2, transition.effects().size()); - assertInstanceOf(RemoveExtrudeMarkerAction.class, transition.effects().get(0)); - assertInstanceOf(SetShapeMarkerAction.class, transition.effects().get(1)); + assertInstanceOf(RemoveMultiPointMarkerAction.class, transition.effects().get(0)); + assertInstanceOf(SetMultiPointMarkerAction.class, transition.effects().get(1)); } // Regression mirroring shapeToPoiConfigOnlyTypeFlipOnReloadRemovesShapeInsteadOfRecomputing above, for @@ -1163,7 +1166,7 @@ void extrudeToPoiConfigOnlyTypeFlipOnReloadRemovesExtrudeInsteadOfRecomputing() var transition = assertInstanceOf(GroupTransitionMarkerAction.class, action); assertEquals(2, transition.effects().size()); - assertInstanceOf(RemoveExtrudeMarkerAction.class, transition.effects().get(0)); + assertInstanceOf(RemoveMultiPointMarkerAction.class, transition.effects().get(0)); assertInstanceOf(AddMarkerAction.class, transition.effects().get(1)); } @@ -1185,9 +1188,9 @@ void extrudeToExtrudeGroupRenameOnReloadBundlesRemoveOldSetAndAddNewSet() { var transition = assertInstanceOf(GroupTransitionMarkerAction.class, action); assertEquals(2, transition.effects().size()); - var leave = assertInstanceOf(RemoveExtrudeMarkerAction.class, transition.effects().get(0)); + var leave = assertInstanceOf(RemoveMultiPointMarkerAction.class, transition.effects().get(0)); assertEquals(oldGroup, leave.getMarkerIdentifier().parentSet().markerGroup()); - var join = assertInstanceOf(SetExtrudeMarkerAction.class, transition.effects().get(1)); + var join = assertInstanceOf(SetMultiPointMarkerAction.class, transition.effects().get(1)); assertEquals(newGroup, join.getMarkerIdentifier().parentSet().markerGroup()); assertEquals(3, join.getPoints().size()); } @@ -1225,7 +1228,7 @@ void lineToLineSameGroupAndLabelDyeOnlyChangeDispatchesSetInsteadOfNoOp() { var action = SignTransitionResolver.computeTransitionAction(() -> List.of(newEntry, other), newEntry.key(), oldRep, newRep, actionFactory(), false, Map.of(group.prefix(), group)); - var set = assertInstanceOf(SetLineMarkerAction.class, action); + var set = assertInstanceOf(SetMultiPointMarkerAction.class, action); assertEquals("#B02E26FF", set.getLineColor()); } @@ -1266,7 +1269,7 @@ void lineJoinResolvesColorFromTheEarliestPlacedDyedMember() { var action = SignTransitionResolver.computeTransitionAction(() -> List.of(first, second), second.key(), null, newRep, actionFactory(), false, Map.of(group.prefix(), group)); - var set = assertInstanceOf(SetLineMarkerAction.class, action); + var set = assertInstanceOf(SetMultiPointMarkerAction.class, action); assertEquals("#B02E26FF", set.getLineColor()); } @@ -1285,7 +1288,7 @@ void lineToLineDyeChangedFromNullDispatchesRecomputeInsteadOfThrowing() { var action = SignTransitionResolver.computeTransitionAction(() -> List.of(dyed, other), self.key(), oldRep, newRep, actionFactory(), false, Map.of(group.prefix(), group)); - assertInstanceOf(SetLineMarkerAction.class, action); + assertInstanceOf(SetMultiPointMarkerAction.class, action); } @Test diff --git a/src/test/java/com/tpwalke2/bluemapsignmarkers/core/signs/persistence/LegacySignFileMigratorTest.java b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/signs/persistence/LegacySignFileMigratorTest.java index d83823d..5f9bf88 100644 --- a/src/test/java/com/tpwalke2/bluemapsignmarkers/core/signs/persistence/LegacySignFileMigratorTest.java +++ b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/signs/persistence/LegacySignFileMigratorTest.java @@ -82,6 +82,20 @@ void migratesALegacyV1FileFabricatingPrefixFromThePOIGroup(@TempDir Path tempDir assertTrue(Files.exists(Path.of(legacyPath + ".migrated"))); } + @Test + void regionFilesRoundTripCleanlyDetectsARegionFileThatFailsToParse(@TempDir Path storageRoot) throws IOException { + var entry = signEntry(0, 0, "minecraft:overworld", "Town Hall"); + RegionShardedSignEntryWriter.write(storageRoot, List.of(entry), GSON); + + // Corrupted after being written cleanly - standing in for a file left truncated by a crash between + // the write pass and this verification, which migrate() itself has no seam to reproduce since it + // writes and verifies in the same call. + var regionFile = storageRoot.resolve("minecraft").resolve("overworld").resolve("r.0.0.json"); + Files.writeString(regionFile, "{ this is not valid json", StandardCharsets.UTF_8); + + assertFalse(LegacySignFileMigrator.regionFilesRoundTripCleanly(storageRoot, List.of(entry), NO_GROUPS, GSON)); + } + private static void writeLegacyV4File(String path, SignEntry... entries) throws IOException { var data = GSON.toJson(entries); var content = GSON.toJson(new VersionedSignFile(SignFileVersions.V4, data)); diff --git a/src/test/java/com/tpwalke2/bluemapsignmarkers/core/signs/persistence/RegionShardedSignEntryLoaderTest.java b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/signs/persistence/RegionShardedSignEntryLoaderTest.java index 10cac51..6fefd41 100644 --- a/src/test/java/com/tpwalke2/bluemapsignmarkers/core/signs/persistence/RegionShardedSignEntryLoaderTest.java +++ b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/signs/persistence/RegionShardedSignEntryLoaderTest.java @@ -9,6 +9,9 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.nio.file.Path; import java.util.List; @@ -58,6 +61,23 @@ void loadSignEntriesRoundTripsAcrossRegionsAndDimensions(@TempDir Path storageRo assertTrue(loaded.contains(netherEntry)); } + @Test + void loadSignEntriesSkipsATruncatedRegionFileButLoadsOtherRegions(@TempDir Path storageRoot) throws IOException { + var goodEntry = signEntry(0, 0, "minecraft:overworld", "Town Hall"); + RegionShardedSignEntryWriter.write(storageRoot, List.of(goodEntry), GSON); + + // Written directly (not round-tripped through the writer) to simulate a file left truncated by a + // crash or disk-full mid-write, rather than one the writer itself produced. + var netherRegionDir = storageRoot.resolve("minecraft").resolve("the_nether"); + Files.createDirectories(netherRegionDir); + Files.writeString(netherRegionDir.resolve("r.0.0.json"), "{ this is not valid json", StandardCharsets.UTF_8); + + var loaded = RegionShardedSignEntryLoader.loadSignEntries(storageRoot, NO_GROUPS, GSON); + + assertEquals(1, loaded.size()); + assertTrue(loaded.contains(goodEntry)); + } + private static SignEntry signEntry(int x, int z, String dimension, String label) { return new SignEntry( new SignEntryKey(x, 64, z, dimension), diff --git a/src/test/java/com/tpwalke2/bluemapsignmarkers/core/signs/persistence/RegionShardedSignEntryWriterTest.java b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/signs/persistence/RegionShardedSignEntryWriterTest.java index fdda7c0..40887a5 100644 --- a/src/test/java/com/tpwalke2/bluemapsignmarkers/core/signs/persistence/RegionShardedSignEntryWriterTest.java +++ b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/signs/persistence/RegionShardedSignEntryWriterTest.java @@ -71,6 +71,25 @@ void movingASignToAnotherRegionQuarantinesTheOldRegionFile(@TempDir Path storage assertTrue(Files.exists(newRegionFile)); } + @Test + void aFailedWriteLeavesNoPartialFileAtTheFinalPathAndCleansUpItsTempFile(@TempDir Path storageRoot) throws IOException { + var entry = signEntry(0, 0, "minecraft:overworld", "Town Hall"); + var regionDir = storageRoot.resolve("minecraft").resolve("overworld"); + Files.createDirectories(regionDir); + var regionFile = regionDir.resolve("r.0.0.json"); + // Occupies the final path with a directory, so the write's ATOMIC_MOVE onto it must fail - standing + // in for a crash/interrupt partway through the write without actually killing the JVM mid-test. + Files.createDirectory(regionFile); + + var succeeded = RegionShardedSignEntryWriter.write(storageRoot, List.of(entry), GSON); + + assertFalse(succeeded); + assertTrue(Files.isDirectory(regionFile), "a failed write must never leave a partial file at the final path"); + assertFalse( + Files.exists(regionFile.resolveSibling(regionFile.getFileName() + ".tmp")), + "a failed write must clean up its temp file rather than leaving it behind"); + } + private static SignEntry signEntry(int x, int z, String dimension, String label) { return new SignEntry( new SignEntryKey(x, 64, z, dimension), diff --git a/src/test/java/com/tpwalke2/bluemapsignmarkers/core/signs/persistence/SignRegionKeyTest.java b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/signs/persistence/SignRegionKeyTest.java index 0f2f737..1268e80 100644 --- a/src/test/java/com/tpwalke2/bluemapsignmarkers/core/signs/persistence/SignRegionKeyTest.java +++ b/src/test/java/com/tpwalke2/bluemapsignmarkers/core/signs/persistence/SignRegionKeyTest.java @@ -1,10 +1,14 @@ package com.tpwalke2.bluemapsignmarkers.core.signs.persistence; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledOnOs; +import org.junit.jupiter.api.condition.OS; +import java.nio.file.FileSystems; import java.nio.file.Path; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; class SignRegionKeyTest { @@ -56,4 +60,54 @@ void relativeFilePathHandlesNestedDimensionPath() { assertEquals(Path.of("somemod", "custom", "dimension", "r.0.0.json"), key.relativeFilePath()); } + + @Test + void relativeFilePathRejectsABlankNamespace() { + var key = new SignRegionKey(":custom/dimension", 0, 0); + + assertThrows(IllegalArgumentException.class, key::relativeFilePath); + } + + @Test + void relativeFilePathRejectsADotNamespace() { + var key = new SignRegionKey(".", 0, 0); + + assertThrows(IllegalArgumentException.class, key::relativeFilePath); + } + + @Test + void relativeFilePathRejectsADotDotNamespace() { + var key = new SignRegionKey("..", 0, 0); + + assertThrows(IllegalArgumentException.class, key::relativeFilePath); + } + + @Test + void relativeFilePathRejectsADimensionPathThatEscapesViaDotDotTraversal() { + var key = new SignRegionKey("somemod:../../escape", 0, 0); + + assertThrows(IllegalArgumentException.class, key::relativeFilePath); + } + + @Test + void relativeFilePathRejectsAnAbsoluteDimensionPath() { + // Built from the platform's own root so this holds on both Windows (drive-absolute paths) and + // Linux (root-absolute paths) rather than hardcoding one platform's absolute-path syntax. + var absolutePath = FileSystems.getDefault().getRootDirectories().iterator().next().resolve("escape").toString(); + var key = new SignRegionKey("somemod:" + absolutePath, 0, 0); + + assertThrows(IllegalArgumentException.class, key::relativeFilePath); + } + + // A raw path segment starting with a single '\' parses as a Windows "drive-relative" path - + // isAbsolute() reports false for it, but it still carries a root component that discards + // namespaceDir on resolve(). Only reproducible on Windows; '\' is just an ordinary filename + // character on other platforms. + @Test + @EnabledOnOs(OS.WINDOWS) + void relativeFilePathRejectsADriveRelativeDimensionPath() { + var key = new SignRegionKey("somemod:\\escape", 0, 0); + + assertThrows(IllegalArgumentException.class, key::relativeFilePath); + } }