wrolpi/tiles/test/test_tiles.py
lrnselfreliance ee30d99212
Map tiles for ATAK and iTAK (#1024)
* Map tiles for ATAK and iTAK

A new service, wrolpi-tiles (tiles/), draws WROLPi's map as 256 px raster
tiles from the map's PMTiles with MapLibre Native (mapli), so ATAK and iTAK
can use the map as a map source, and ATAK can download an area of it.

- Tiles are drawn in blocks of 4x4 (ATAK asks for tiles in quadtree order),
  each block once however many requests wait on it, in render processes of
  their own.  Phones are served in turn.
- A tile is always a 200: blank where there is no map, or when it was not
  drawn before ATAK's 5 second timeout.  Five failed tiles in a row stop an
  ATAK download, and a 401/403 stops the map source.
- Drawn tiles are kept in /var/cache/wrolpi-tiles, with a size cap and a
  free-space floor; JPEG, about a seventh of a PNG.
- The basemap is the web map's (protomaps-themes-base, light), kept equal
  to it by a Jest test.  Unreadable map files and missing map fonts are
  left out rather than failing every tile.
- Caddy serves it at /tiles/ over HTTPS and on port 8088 over plain HTTP
  (a phone must trust WROLPi's CA for HTTPS).  /tiles/wrolpi.xml is the
  MOBAC map source to import.
- A separate service with lower CPU priority and a memory cap, so a phone
  downloading an area cannot slow the API.  Docker runs it from the api
  image.
- The map page has an ATAK tab: the map source links, how to use them, and
  what the tile service is doing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tiles: bound PMTiles decompression before it happens

A few bytes of a downloaded map file could decompress to far more than the
cap, which was applied only afterwards.  Decompress at most MAX_METADATA_SIZE,
as modules.map.pmtiles does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tiles: never send a blank for a late tile; start render processes with the service

QA on a Pi 4 found the first tile after a start sent blank: starting the
render processes and the first draw took 4.5 s, past the deadline.  A
downloader (ATAK's, iTAK's) keeps whatever a tile request returns, so a
blank sent for a late or failed tile is a hole in its offline map for
good.  Such a tile is now a 503 (ATAK tries each tile twice; only 401 and
403 stop a map source), and the render processes start with the service.

Also:
- OOMScoreAdjust=500: Raspberry Pi OS disables the memory cgroup, so
  MemoryMax does nothing there; the tile service is killed before the API.
- sanic-ext's auto extensions are off in the tile service.
- The map's ATAK tab is before Manage: Manage is the last tab.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tiles: put backgroundColor back in the map source; iTAK requires it

iTAK refuses a MOBAC map source without <backgroundColor> ("The data couldn't
be read because it is missing").  ATAK ignores it.  It is the map's own
background color.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tiles: leave out the map files hidden on the Manage tab, as the web map does

maps.yaml's ignored_files names the map files the user hid; the web map
does not draw them, and the tiles drew them anyway.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tiles: bound the render processes' memory and the tiles-per-second times

QA on a Pi 4, a phone taking 123,000 tiles offline: each render process
grew from about 270 MB to 370 MB (MapLibre keeps what it has read and
drawn) and did not shrink when idle.  A render process is now replaced
after 2,000 blocks.  The serve times behind tiles-per-second were only
forgotten when the status was asked for; they are forgotten as tiles are
served.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Map ATAK tab: iTAK takes an area offline too

An iPhone downloaded 123,000 tiles with iTAK and showed them offline with
none missing; the tab said only ATAK could.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Map ATAK tab: a button to clear the tiles the tile service keeps

POST /tiles/cache/clear on the tile service (which keeps the cache's size)
removes the kept tiles; they are drawn again when next asked for.  The
button asks first, and says that maps already downloaded to phones are not
changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tiles: measure the cache as the disk does; clear it at once, delete in the background

QA on a Pi 4 after a 123,000-tile download: the cache counted 375 MB of tile
bytes while its files took 660 MB of the SD card (each small file takes a
whole 4 KiB block), so the 1 GB cap allowed about 1.7 GB.  The cache is now
measured in disk blocks.

Clearing deleted 128,000 files in the request: about 40 seconds, with the
Pi's load warning on.  A clear (or a new style) now renames the tiles out of
the way at once and deletes them in a lowest-priority thread, pausing every
500 files; a deletion cut short is finished at the next start.  A tile drawn
again no longer counts twice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Help: ATAK and iTAK

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tiles: a page on port 8088 saying what it is

A person who finds port 8088 got a 404.  / (and /tiles/) is now a short page:
WROLPi's map tile service for ATAK and iTAK, the map source to open on a
phone, and links to the WROLPi app and the map's ATAK tab, made from the
address the page was reached by (Docker publishes the app on
TILES_HTTPS_PORT).  Port 8088 serves WROLPi's icon.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tiles: review fixes

- Caddy: a tile request is never redirected to the fallback page when the
  tile service is down or restarting (handle_errors on 443).  ATAK keeps
  whatever a tile request ends with, so the page was stored as the tile;
  it is now a 503 with Retry-After, which ATAK tries again.
- The cache's oldest tiles are found and deleted in a lowest-priority
  thread, pausing as it goes, not in the tile request which filled it.
- ATAK tab: only the newest status request writes the status, so a slow
  answer can not undo a newer one (or a clear).  It says when the page was
  opened on localhost and the addresses work only there, and names each
  map source as the app lists it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 11:21:45 -07:00

600 lines
26 KiB
Python

import asyncio
import gzip
import io
import json
import struct
import sys
import threading
import time
import uuid
import xml.etree.ElementTree as ElementTree
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import pytest
from PIL import Image
from modules.map import pmtiles as map_pmtiles
from modules.map.conftest import PROTOMAPS_LAYERS, pmtiles_bytes, vector_metadata
from tiles import maps, render, service as tile_service
from tiles.blocks import BLOCK, Block, block_center, block_of, is_tile, tile_corner
from tiles.cache import TileCache, disk_size
from tiles.service import TileService, create_app, index_html, mobac_xml
from tiles.style import SKIP_SECONDARY, background_color, basemap_layers, build_style, style_id
@pytest.fixture(autouse=True)
def media_directory(tmp_path, monkeypatch) -> Path:
"""The tile service reads configs (wrolpi.yaml, maps.yaml) from a media directory of the test's own."""
monkeypatch.setattr(maps, 'MEDIA_DIRECTORY', tmp_path / 'media')
return tmp_path / 'media'
def write_header_only(path: Path, metadata=None, **kwargs) -> Path:
"""A PMTiles file with a header and metadata but no tiles (as modules.map's tests make)."""
path.parent.mkdir(parents=True, exist_ok=True)
if metadata is None and kwargs.get('tile_type', 1) == 1:
metadata = vector_metadata(*PROTOMAPS_LAYERS)
path.write_bytes(pmtiles_bytes(metadata, **kwargs))
return path
def varint(n: int) -> bytes:
out = bytearray()
while True:
byte, n = n & 0x7f, n >> 7
out.append(byte | 0x80 if n else byte)
if not n:
return bytes(out)
def write_pmtiles(path: Path, metadata: dict = None) -> Path:
"""A PMTiles (version 3) file MapLibre can read: one empty vector tile, of the whole world at zoom 0."""
path.parent.mkdir(parents=True, exist_ok=True)
metadata = metadata if metadata is not None else vector_metadata(*PROTOMAPS_LAYERS)
tile = gzip.compress(b'')
# One entry: tile id 0, run length 1, its length, offset 0 (written as offset + 1).
root = gzip.compress(varint(1) + varint(0) + varint(1) + varint(len(tile)) + varint(1))
raw_metadata = gzip.compress(json.dumps(metadata).encode())
header = bytearray(127)
header[0:7] = b'PMTiles'
header[7] = 3
root_offset = 127
metadata_offset = root_offset + len(root)
tiles_offset = metadata_offset + len(raw_metadata)
struct.pack_into('<QQQQQQQQ', header, 8, root_offset, len(root), metadata_offset, len(raw_metadata),
tiles_offset, 0, tiles_offset, len(tile))
struct.pack_into('<QQQ', header, 72, 1, 1, 1)
# Clustered, gzip directories, gzip tiles, vector, zoom 0 to 0.
struct.pack_into('<6B', header, 96, 1, 2, 2, 1, 0, 0)
struct.pack_into('<4i', header, 102, -1800000000, -850000000, 1800000000, 850000000)
path.write_bytes(bytes(header) + root + raw_metadata + tile)
return path
# Map files.
@pytest.mark.parametrize('name,metadata,kwargs', [
('basemap.pmtiles', None, dict()),
('uncompressed.pmtiles', None, dict(compress=False)),
('roads-only.pmtiles', vector_metadata('roads'), dict()),
('overlay.pmtiles', vector_metadata('trails', 'campsites'), dict()),
('raster.pmtiles', None, dict(tile_type=2)),
('terrain-z0-8.pmtiles', None, dict()),
('no-layers.pmtiles', dict(name='x'), dict()),
])
def test_is_basemap_agrees_with_the_map(tmp_path, name, metadata, kwargs):
"""The tile service decides what a basemap is without importing modules.map; both must say the same."""
path = write_header_only(tmp_path / name, metadata, **kwargs)
expected = map_pmtiles.classify(path.name, map_pmtiles.read_pmtiles_info(path)) == map_pmtiles.KIND_BASEMAP
assert maps.is_basemap(path) is expected
def test_is_basemap_unreadable(tmp_path):
(tmp_path / 'junk.pmtiles').write_bytes(b'not a map')
(tmp_path / 'empty.pmtiles').write_bytes(b'')
assert not maps.is_basemap(tmp_path / 'junk.pmtiles')
assert not maps.is_basemap(tmp_path / 'empty.pmtiles')
assert not maps.is_basemap(tmp_path / 'missing.pmtiles')
def test_is_drawable(tmp_path):
"""A file MapLibre cannot read would fail every tile, so it is left out."""
assert maps.is_drawable(write_pmtiles(tmp_path / 'good.pmtiles'))
# No tiles: an empty root directory.
assert not maps.is_drawable(write_header_only(tmp_path / 'empty.pmtiles'))
# Cut short.
data = (tmp_path / 'good.pmtiles').read_bytes()
(tmp_path / 'short.pmtiles').write_bytes(data[:140])
assert not maps.is_drawable(tmp_path / 'short.pmtiles')
# A corrupt root directory.
(tmp_path / 'corrupt.pmtiles').write_bytes(data[:127] + b'x' * (len(data) - 127))
assert not maps.is_drawable(tmp_path / 'corrupt.pmtiles')
assert not maps.is_drawable(tmp_path / 'missing.pmtiles')
(tmp_path / 'map').mkdir()
for name in ('empty.pmtiles', 'short.pmtiles', 'corrupt.pmtiles', 'good.pmtiles'):
(tmp_path / 'map' / name).write_bytes((tmp_path / name).read_bytes())
assert maps.find_basemaps(tmp_path / 'map') == [tmp_path / 'map/good.pmtiles']
def test_decompression_is_bounded(tmp_path, monkeypatch):
"""Metadata or a directory which decompresses to more than MAX_METADATA_SIZE is not read."""
monkeypatch.setattr(maps, 'MAX_METADATA_SIZE', 1000)
bomb = gzip.compress(b'0' * 100_000) # small, but 100 KB decompressed
with pytest.raises(ValueError):
maps.gunzip(bomb)
assert maps.gunzip(gzip.compress(b'ok')) == b'ok'
# Metadata padded past the limit.
path = write_header_only(tmp_path / 'big.pmtiles', vector_metadata(*PROTOMAPS_LAYERS, padding='x' * 100_000))
assert not maps.is_basemap(path)
def test_find_maps(tmp_path):
write_pmtiles(tmp_path / 'map/b.pmtiles')
write_pmtiles(tmp_path / 'map/region/a.pmtiles')
write_pmtiles(tmp_path / 'map/.partial/c.pmtiles') # an unfinished download
write_pmtiles(tmp_path / 'map/overlay.pmtiles', vector_metadata('trails'))
write_header_only(tmp_path / 'map/no-tiles.pmtiles')
overview = write_pmtiles(tmp_path / 'blobs/map-overview.pmtiles')
assert maps.find_basemaps(tmp_path / 'map') == [tmp_path / 'map/b.pmtiles', tmp_path / 'map/region/a.pmtiles']
# The overview is under every other file.
assert maps.find_maps(tmp_path / 'map', overview)[0] == overview
assert maps.find_maps(tmp_path / 'map', tmp_path / 'missing.pmtiles') == maps.find_basemaps(tmp_path / 'map')
def test_find_maps_leaves_out_hidden_files(tmp_path):
"""A map file hidden on the Manage tab (maps.yaml's ignored_files) is not drawn, as on the web map."""
write_pmtiles(tmp_path / 'map/a.pmtiles')
write_pmtiles(tmp_path / 'map/region/b.pmtiles')
assert len(maps.find_maps(tmp_path / 'map', None, tmp_path)) == 2
(tmp_path / 'config').mkdir()
(tmp_path / 'config/maps.yaml').write_text('version: 1\nignored_files:\n- region/b.pmtiles\n')
assert maps.find_maps(tmp_path / 'map', None, tmp_path) == [tmp_path / 'map/a.pmtiles']
# A broken config hides nothing.
(tmp_path / 'config/maps.yaml').write_text('ignored_files: [')
assert len(maps.find_maps(tmp_path / 'map', None, tmp_path)) == 2
def test_get_map_directory(tmp_path):
assert maps.get_map_directory(tmp_path) == tmp_path / 'map'
(tmp_path / 'config').mkdir()
(tmp_path / 'config/wrolpi.yaml').write_text('map_destination: maps/osm\n')
assert maps.get_map_directory(tmp_path) == tmp_path / 'maps/osm'
(tmp_path / 'config/wrolpi.yaml').write_text(': not yaml [')
assert maps.get_map_directory(tmp_path) == tmp_path / 'map'
# Style.
def make_static(directory: Path) -> Path:
"""The map's static directory, with a font installed."""
(directory / 'fonts/Noto Sans Regular').mkdir(parents=True)
(directory / 'fonts/Noto Sans Regular/0-255.pbf').write_bytes(b'')
return directory
def test_build_style_as_the_web_map(tmp_path):
first, second = tmp_path / 'overview.pmtiles', tmp_path / 'mexico.pmtiles'
static = make_static(tmp_path / 'static')
style = build_style([first, second], static=static)
assert style['sources'] == {
'0-overview': dict(type='vector', url=f'pmtiles://file://{first}'),
'1-mexico': dict(type='vector', url=f'pmtiles://file://{second}'),
}
ids = [i['id'] for i in style['layers']]
assert len(ids) == len(set(ids)), 'layer ids must be unique'
template = basemap_layers('x')
# Every layer of the first file; the second file's renamed, without what would cover the first.
assert {'background', 'earth'} <= set(ids)
assert len(ids) == 2 * len(template) - len(SKIP_SECONDARY)
assert not {f'1-mexico:{i}' for i in SKIP_SECONDARY} & set(ids)
assert {i['source'] for i in style['layers'] if i['id'].startswith('1-mexico:')} == {'1-mexico'}
# Every label is over the ground of every file.
types = [i['type'] for i in style['layers']]
assert types.index('symbol') > max(i for i, t in enumerate(types) if t != 'symbol')
assert style['glyphs'] == f'file://{static}/fonts/{{fontstack}}/{{range}}.pbf'
assert style['sprite'] == f'file://{static}/sprites/light'
def test_build_style_without_fonts(tmp_path):
"""Without the fonts MapLibre fails every tile with a label; the map is drawn without them."""
style = build_style([tmp_path / 'a.pmtiles'], static=tmp_path / 'static')
assert 'glyphs' not in style
assert style['layers'] and not [i for i in style['layers'] if i['type'] == 'symbol']
make_static(tmp_path / 'static')
assert [i for i in build_style([tmp_path / 'a.pmtiles'], static=tmp_path / 'static')['layers']
if i['type'] == 'symbol']
def test_build_style_without_maps():
style = build_style([])
assert style['sources'] == dict()
assert [i['type'] for i in style['layers']] == ['background']
assert background_color(style).startswith('#')
def test_style_id():
style = build_style([Path('/a.pmtiles')])
assert style_id(style, (('/a.pmtiles', 1, 2),)) == style_id(style, (('/a.pmtiles', 1, 2),))
assert style_id(style, (('/a.pmtiles', 1, 2),)) != style_id(style, (('/a.pmtiles', 3, 2),))
# Blocks.
def test_blocks():
assert block_of(15, 7361, 14583) == Block(15, 1840, 3645)
assert list(Block(15, 1840, 3645).tiles())[0] == (7360, 14580)
assert len(list(Block(15, 1840, 3645).tiles())) == BLOCK * BLOCK
# Below zoom 2 the world is the block.
assert block_of(1, 1, 1) == Block(1, 0, 0)
assert sorted(Block(1, 0, 0).tiles()) == [(0, 0), (0, 1), (1, 0), (1, 1)]
assert list(Block(0, 0, 0).tiles()) == [(0, 0)]
# The center of a block is the corner its middle four tiles share.
assert block_center(Block(15, 1840, 3645)) == tile_corner(15, 7362, 14582)
assert tile_corner(1, 1, 1) == (0, 0)
assert is_tile(0, 0, 0) and not is_tile(3, 8, 0) and not is_tile(-1, 0, 0) and not is_tile(30, 0, 0)
# Cache.
def du(directory: Path) -> int:
"""What the tiles in a directory take of the disk, as `du` counts it."""
return sum(disk_size(i.stat()) for i in directory.rglob('*.jpg'))
def test_cache(tmp_path):
cache = TileCache(tmp_path / 'cache', max_bytes=10_000_000, min_free_bytes=0)
cache.use_style('a')
cache.put(15, {(1, 2): b'one', (1, 3): b'two'}, 'a')
assert cache.get(15, 1, 2) == b'one' and cache.get(15, 1, 3) == b'two'
assert cache.get(15, 9, 9) is None
# Measured as the disk measures it: a whole block for each little file, not its bytes.
assert cache.size == du(tmp_path / 'cache/a') >= 2 * 512
# A tile drawn again replaces itself; it is not counted twice.
cache.put(15, {(1, 2): b'one again'}, 'a')
assert cache.size == du(tmp_path / 'cache/a')
# Tiles of a style no longer drawn are not kept, and a new style removes the old.
cache.put(15, {(5, 5): b'old'}, 'gone')
assert cache.get(15, 5, 5) is None
cache.use_style('b')
assert cache.get(15, 1, 2) is None
assert not (tmp_path / 'cache/a').exists()
assert cache.size == 0
cache.wait_for_deletes(5)
assert [i.name for i in (tmp_path / 'cache').iterdir()] == []
# A kept cache is counted again when the service starts.
cache.put(3, {(0, 0): b'x' * 100}, 'b')
again = TileCache(tmp_path / 'cache', 10_000_000, 0)
again.use_style('b')
assert again.size == du(tmp_path / 'cache/b') > 0
def test_cache_clear(tmp_path):
"""Clearing is at once: the tiles are moved out of the way, and deleted in the background."""
cache = TileCache(tmp_path / 'cache', max_bytes=10_000_000, min_free_bytes=0)
cache.use_style('a')
cache.put(15, {(x, 0): b'tile' for x in range(50)}, 'a')
size = cache.size
assert cache.clear() == size > 0
assert cache.size == 0 and cache.get(15, 1, 0) is None
assert not (tmp_path / 'cache/a').exists()
# Tiles are kept again at once, beside the old ones being deleted.
cache.put(15, {(1, 0): b'new'}, 'a')
assert cache.get(15, 1, 0) == b'new' and cache.size == du(tmp_path / 'cache/a')
cache.wait_for_deletes(5)
assert sorted(i.name for i in (tmp_path / 'cache').iterdir()) == ['a']
assert TileCache(tmp_path / 'off', 0, 0).clear() == 0
def test_cache_finishes_deleting_at_start(tmp_path):
"""A deletion cut short (the service restarted) is finished when the service starts again."""
leftover = tmp_path / 'cache/.trash-a-1234abcd/15/1'
leftover.mkdir(parents=True)
(leftover / '2.jpg').write_bytes(b'old')
cache = TileCache(tmp_path / 'cache', max_bytes=10_000_000, min_free_bytes=0)
cache.use_style('b')
cache.wait_for_deletes(5)
assert list((tmp_path / 'cache').iterdir()) == []
def test_cache_evicts_oldest(tmp_path):
probe = TileCache(tmp_path / 'probe', max_bytes=10_000_000, min_free_bytes=0)
probe.use_style('a')
probe.put(10, {(0, 0): b'x' * 200}, 'a')
tile = probe.size # one tile, on this disk
cache = TileCache(tmp_path / 'cache', max_bytes=5 * tile, min_free_bytes=0)
cache.use_style('a')
for x in range(10):
cache.put(10, {(x, 0): b'x' * 200}, 'a')
cache.wait_for_deletes(5) # evicting is in the background
time.sleep(0.01)
assert cache.size == du(tmp_path / 'cache/a') <= 5 * tile * 0.8
assert cache.get(10, 9, 0) # the newest are kept
assert cache.get(10, 0, 0) is None
def test_cache_evicts_in_the_background(tmp_path, monkeypatch):
"""A tile request which fills the cache does not wait while the oldest tiles are found and deleted."""
cache = TileCache(tmp_path / 'cache', max_bytes=10_000_000, min_free_bytes=0)
cache.use_style('a')
cache.put(10, {(x, 0): b'x' * 200 for x in range(20)}, 'a')
started, release = threading.Event(), threading.Event()
real_evict = cache._evict
def slow_evict(style_id):
started.set()
release.wait(5)
real_evict(style_id)
monkeypatch.setattr(cache, '_evict', slow_evict)
cache.max_bytes = cache.size # the next tile fills it
begun = time.perf_counter()
cache.put(10, {(99, 0): b'new'}, 'a')
assert time.perf_counter() - begun < 1 and started.wait(5)
# Kept while evicting is still counted after.
cache.put(10, {(98, 0): b'newer'}, 'a')
release.set()
cache.wait_for_deletes(5)
assert cache.size == du(tmp_path / 'cache/a') <= cache.max_bytes * 0.8
assert cache.get(10, 98, 0) == b'newer'
def test_cache_disabled_or_disk_full(tmp_path):
disabled = TileCache(tmp_path / 'off', max_bytes=0, min_free_bytes=0)
disabled.use_style('a')
disabled.put(1, {(0, 0): b'x'}, 'a')
assert disabled.get(1, 0, 0) is None and not (tmp_path / 'off').exists()
full = TileCache(tmp_path / 'full', max_bytes=1000, min_free_bytes=2 ** 62)
full.use_style('a')
full.put(1, {(0, 0): b'x'}, 'a')
assert full.get(1, 0, 0) is None
# The map source file.
def test_mobac_xml():
root = ElementTree.fromstring(mobac_xml('http://192.0.2.8:8088', 'WROLPi & Map', 17).encode())
assert root.tag == 'customMapSource'
assert root.findtext('name') == 'WROLPi & Map'
assert root.findtext('url') == 'http://192.0.2.8:8088/tiles/{$z}/{$x}/{$y}.jpg'
# ATAK requires a maxZoom.
assert (root.findtext('minZoom'), root.findtext('maxZoom')) == ('0', '17')
# iTAK refuses a map source without one.
assert root.findtext('backgroundColor') == '#cccccc'
def test_index_html(monkeypatch):
"""The page a person finds on port 8088 says what it is and links to the map source and to WROLPi."""
page = index_html('http://192.0.2.8:8088', 5)
assert 'WROLPi Map Tiles' in page and 'ATAK' in page and 'iTAK' in page
assert 'href="http://192.0.2.8:8088/tiles/wrolpi.xml"' in page
assert 'href="https://192.0.2.8/"' in page and 'href="https://192.0.2.8/map/atak"' in page
assert 'Drawn from 5 map files' in page
assert 'There are no map files' in index_html('https://wrolpi.local', 0)
# Offline: nothing from elsewhere.
assert 'src=' not in page and '<link' not in page
# Docker publishes the WROLPi app on another port.
monkeypatch.setattr(tile_service, 'HTTPS_PORT', 8443)
assert 'href="https://wrolpi.local:8443/map/atak"' in index_html('http://wrolpi.local:8088', 1)
assert 'href="https://[fd00::8]:8443/"' in index_html('http://[fd00::8]:8088', 1)
def test_index_html_escapes_the_host():
"""The address is the request's Host header, which anyone can write."""
page = index_html('http://evil"><script>alert(1)</script>', 1)
assert '<script>' not in page
# The service, with a renderer which draws nothing.
class FakeRenderer:
def __init__(self, delay: float = 0, fail: bool = False):
self.delay = delay
self.fail = fail
self.blocks = []
self.lock = threading.Lock()
def __call__(self, sid, style, block):
with self.lock:
self.blocks.append(block)
time.sleep(self.delay)
if self.fail:
raise RuntimeError('cannot draw')
return {(x, y): f'{block.z}/{x}/{y}'.encode() for x, y in block.tiles()}
@pytest.fixture
def make_service(tmp_path, monkeypatch):
"""A TileService drawing in threads with a fake renderer."""
services = []
async def _(renderer: FakeRenderer = None, processes: int = 2, cache_bytes: int = 0) -> TileService:
monkeypatch.setattr(render, 'render_block', renderer or FakeRenderer())
write_pmtiles(tmp_path / 'map/basemap.pmtiles')
cache = TileCache(tmp_path / 'cache', cache_bytes, 0)
service = TileService(tmp_path / 'map', cache, processes=processes, overview=None)
monkeypatch.setattr(service, '_new_executor', lambda: ThreadPoolExecutor(processes))
await service.start()
services.append(service)
await service.tasks[-1] # the render processes are warmed
if isinstance(render.render_block, FakeRenderer):
render.render_block.blocks.clear()
return service
yield _
for service in services:
service.executor.shutdown(wait=False, cancel_futures=True)
for task in service.tasks:
task.cancel()
async def test_service_draws_a_block_once(make_service):
"""ATAK asks for 4 tiles at a time, all of one block; the block is drawn once."""
renderer = FakeRenderer(delay=0.1)
service = await make_service(renderer)
tiles = [(x, y) for x in range(8, 12) for y in range(20, 24)]
results = await asyncio.gather(*(service.tile(15, x, y, 'phone') for x, y in tiles))
assert renderer.blocks == [Block(15, 2, 5)]
assert [data for data, _ in results] == [f'15/{x}/{y}'.encode() for x, y in tiles]
assert all(keep for _, keep in results)
async def test_service_serves_phones_in_turn(make_service):
"""A phone downloading many blocks does not keep another's tiles waiting behind all of them."""
renderer = FakeRenderer(delay=0.05)
service = await make_service(renderer, processes=1)
downloading = [asyncio.create_task(service.tile(15, 4 * i, 0, 'downloading')) for i in range(10)]
await asyncio.sleep(0)
other = await service.tile(15, 0, 400, 'browsing')
assert other[0] == b'15/0/400'
assert renderer.blocks.index(Block(15, 0, 100)) <= 2
await asyncio.gather(*downloading)
async def test_service_warms_render_processes(make_service):
"""Every render process draws when the service starts, not when the first tile is asked for; the world it
draws is kept."""
renderer = FakeRenderer()
service = await make_service(renderer, processes=2, cache_bytes=10_000_000)
assert service.cache.get(0, 0, 0) == b'0/0/0'
assert await service.tile(0, 0, 0, 'phone') == (b'0/0/0', True)
assert renderer.blocks == [] # from the cache
async def test_service_late_tile(make_service, monkeypatch):
"""A tile not drawn before ATAK gives up on it is not sent at all (a downloader would keep a blank in its
place for good): the phone asks again, and then the tile has been drawn."""
monkeypatch.setattr(tile_service, 'DEADLINE', 0.05)
service = await make_service(FakeRenderer(delay=0.3), cache_bytes=10_000_000)
data, keep = await service.tile(12, 1, 1, 'phone')
assert (data, keep) == (None, False)
await asyncio.sleep(0.5)
assert await service.tile(12, 1, 1, 'phone') == (b'12/1/1', True)
assert service.stats['tiles_late'] == 1 and service.stats['tiles_cached'] == 1
async def test_service_failed_tile(make_service):
"""A tile which could not be drawn is not sent (not as a blank a downloader would keep); a tile outside the
world is the background."""
service = await make_service(FakeRenderer(fail=True))
assert await service.tile(12, 1, 1, 'phone') == (None, False)
assert await service.tile(3, 8, 8, 'phone') == (service.blank_tile, False) # not a tile
async def test_service_forgets_old_serve_times(make_service, monkeypatch):
"""Tiles per second counts the last minute; older times are not kept, whether or not anyone asks."""
service = await make_service()
now = time.time()
service.served.extend([now - 120] * 1000)
await service.tile(12, 1, 1, 'phone')
assert len(service.served) == 1
async def test_service_new_map_file(make_service, tmp_path):
service = await make_service()
first = service.style_id
assert not service.refresh_maps()
write_pmtiles(tmp_path / 'map/another.pmtiles')
assert service.refresh_maps()
assert service.style_id != first and len(service.maps) == 2
async def test_service_drops_tiles_a_phone_gave_up_on(make_service, monkeypatch):
monkeypatch.setattr(tile_service, 'MAX_QUEUED_PER_CLIENT', 2)
monkeypatch.setattr(tile_service, 'DEADLINE', 1)
service = await make_service(FakeRenderer(delay=0.2), processes=1)
results = await asyncio.gather(*(service.tile(15, 4 * i, 0, 'phone') for i in range(5)))
assert service.stats['blocks_dropped'] >= 1
assert (None, False) in results
async def test_service_http(make_service):
service = await make_service(cache_bytes=10_000_000)
app = create_app(service, name=f'tiles_{uuid.uuid4().hex}')
# The service is started by the fixture.
app.ctx.service.start = app.ctx.service.stop = lambda: asyncio.sleep(0)
headers = {'x-forwarded-proto': 'https', 'x-forwarded-host': 'wrolpi.local', 'x-forwarded-for': '192.0.2.34'}
_, resp = await app.asgi_client.get('/tiles/wrolpi.xml', headers=headers)
assert resp.status == 200
root = ElementTree.fromstring(resp.body)
assert root.findtext('url') == 'https://wrolpi.local/tiles/{$z}/{$x}/{$y}.jpg'
assert root.findtext('name') == 'WROLPi Map (HTTPS)'
assert 'wrolpi-map-https.xml' in resp.headers['content-disposition']
_, resp = await app.asgi_client.get('/tiles/10/5/6.jpg', headers=headers)
assert resp.status == 200 and resp.body == b'10/5/6'
assert resp.headers['content-type'] == 'image/jpeg'
assert 'max-age' in resp.headers['cache-control']
_, resp = await app.asgi_client.get('/tiles/10/5/6.png')
assert resp.status == 404
# The page for a person who finds the port.
for path in ('/', '/tiles', '/tiles/'):
_, resp = await app.asgi_client.get(path, headers=headers)
assert resp.status == 200 and 'text/html' in resp.headers['content-type'], path
assert 'https://wrolpi.local/tiles/wrolpi.xml' in resp.text
# Not drawn in time: a 503 (never a 401 or 403, which stop an ATAK map source), never a blank to keep.
async def late(*args):
return None, False
app.ctx.service.tile = late
_, resp = await app.asgi_client.get('/tiles/10/5/7.jpg')
assert resp.status == 503 and resp.headers['retry-after'] == '1'
assert resp.headers['cache-control'] == 'no-store'
_, resp = await app.asgi_client.get('/tiles/status')
assert resp.status == 200
assert resp.json['clients'][0]['client'] == '192.0.2.34'
assert resp.json['stats']['blocks_drawn'] >= 1
# The ATAK tab clears the kept tiles. (The tile drawn above is kept in the background; wait for it, or it
# would be kept after the clear.)
for _ in range(100):
if service.cache.get(10, 5, 6):
break
await asyncio.sleep(0.01)
assert service.cache.get(10, 5, 6) == b'10/5/6'
_, resp = await app.asgi_client.post('/tiles/cache/clear')
assert resp.status == 200 and resp.json['freed_bytes'] >= 4
assert service.cache.get(10, 5, 6) is None and service.cache.size == 0
# Real drawing. mapli has wheels for Linux only: everywhere WROLPi runs.
@pytest.mark.skipif(sys.platform != 'linux', reason='mapli is Linux-only')
def test_render_block(tmp_path):
render.init_process()
style = build_style([write_pmtiles(tmp_path / 'overview.pmtiles'), write_pmtiles(tmp_path / 'basemap.pmtiles')])
tiles = render.render_block('test', style, Block(15, 1840, 3645))
assert set(tiles) == set(Block(15, 1840, 3645).tiles())
image = Image.open(io.BytesIO(tiles[(7360, 14580)]))
assert image.format == 'JPEG' and image.size == (256, 256)
# The files have no features: every tile is the background.
expected = tuple(int(background_color(style)[i:i + 2], 16) for i in (1, 3, 5))
assert all(abs(a - b) <= 3 for a, b in zip(image.getpixel((128, 128)), expected))
world = render.render_block('test', style, Block(1, 0, 0))
assert len(world) == 4 and Image.open(io.BytesIO(world[(1, 1)])).size == (256, 256)
# Without map files, the background alone.
empty = render.render_block('empty', build_style([]), Block(0, 0, 0))
assert Image.open(io.BytesIO(empty[(0, 0)])).size == (256, 256)