Onboarding Guide: treetracker-tile-server
Generated from the Understand-Anything knowledge graph. Source commit b619c05.
This repo is the Greenstand fork of upstream node-mapnik. The Greenstand part is the tile server in
greenstand/, plusdeployment/, theDockerfile, and.github/. Thesrc/C++ code is upstream binding code. The analysis excluded the upstream test fixtures,bench/,docs/, the rootdeps/, allexamples/directories, and the shapefiles.
Project Overview
The tile server renders Treetracker tree data from PostGIS into 256x256 PNG tiles and UTF grid JSON tiles. It uses the native Mapnik binding to draw each tile.
- Package
Name and version:treetracker-map-tile-server4.36.7
Package main:./lib/mapnik.js, the loader of the native Mapnik binding - Languages and frameworks
Tile server: JavaScript, XML, YAML, Express,pg,lru-cache, Jest
Upstream part and delivery: C++, Python, shell, Makefile, Docker, kustomize, GitHub Actions - Entry point
Command:npm startrunsnode --max-old-space-size=1024 greenstand/server.js.
Port:.envsets 23300. The manifests set 3000.
How the parts fit:
greenstand/server.jsloads.envand starts the Express service ingreenstand/app.js.- For each tile,
app.jsasksConfig.getXMLStringingreenstand/config.jsfor the Mapnik style. config.jsgets the tile SQL fromgreenstand/Map.js.Map.jspicks one SQL builder ingreenstand/sqls/.app.jsloads the Mapnik style into a newmapnik.Mapand renders it with the native Mapnik binding.
Architecture Layers
The graph has 657 nodes and 1265 edges. It puts each file into one of 10 layers. The counts are graph nodes.
- Tile Server API (7)
This layer holds the process entry, the Express service, and its routes. - Tile Style Service (7)
This layer holds the style builder, the base styles, and the tile geometry helper. - Tree Query And Cache (15)
This layer holds the query planner, the SQL builders, and the cached query pool. - Tile Server Tests And Fixtures (20)
This layer holds the Jest suites, sample GeoJSON, and sample Mapnik styles. - Container And Kubernetes Deployment (25)
This layer holds theDockerfileand the kustomize base indeployment/with four overlays. - Release And Deploy Pipelines (7)
This layer holds five GitHub Actions workflows,.releaserc, and the legacy upstream.travis.yml. - Project Config And Docs (12)
This layer holdspackage.json,.env, the format and commit settings, and mostly upstream docs. - Upstream layers
Mapnik JS Loader And CLIs (6):lib/mapnik.js,lib/index.js,bin/
Native Mapnik Binding (73): the C++ N-API wrappers insrc/
Native Build And Dev Tooling (35):Makefile,binding.gyp,common.gypi,scripts/,tools/
Key Concepts
- Each request gets a new Mapnik style and a new map.
buildMapInstancecreates a new 256x256mapnik.Mapfor each tile (greenstand/app.js:47).
The native Mapnik binding refuses a Map that another render uses (src/mapnik_map_render.cpp:564). - The zoom level picks the datasource.
At zoom 1 to 15,config.jsruns the SQL and puts the rows into the Mapnik style as inline GeoJSON (greenstand/config.js:122).
At zoom 0 and at zoom 16 and above,config.jsputs the DB_URL credentials and the SQL into a PostGIS base style (greenstand/config.js:276).
In that case, Mapnik runs the SQL at render time.
A GeoJSON Mapnik style above 5 MB fails with "The data is too big" (greenstand/config.js:266).
Theiconparameter picks the base style.ptk-bandptk-sgive the green icons ingreenstand/xml2.js.oor no value gives the orange icons ingreenstand/xml.js. - The map mode picks the SQL builder.
Map.initcheckstreeidfirst (greenstand/Map.js:32). Then it checkscapture_id,userid,wallet,map_name, andtimeline, in that order.
When no value is set,Map.inituses the default map.
Thecapture_idbranch never runs, becauseMap.initdoes not copycapture_idfrom its settings (greenstand/Map.js:39).config.jsdoes not passtreeidtoMap.init(greenstand/config.js:154). So the single tree mode does not run from the tile routes.
Above zoom 15, every mode returns single tree points.
Planter and wallet maps count the trees first. More than 2000 trees give region clusters. 2000 or fewer give on-the-fly clusters. - Two zoom thresholds come from the environment.
AboveMAXIMUM_ZOOM_LEVEL_USING_GLOBAL_DATASET, the default map limits the SQL to the tile bounds (greenstand/config.js:143).
Up to zoom 15, organization maps always use the tile bounds. Planter and wallet maps never use them.
Up toMAXIMUM_ZOOM_LEVEL_HANDLING_ZOOM_TARGET, region clusters get azoom_tocentroid (greenstand/sqls/SQLCase1WithZoomTarget.js:10).server.jsstops at startup when one of the two is not defined (greenstand/server.js:7).
The values are 6 and 6 in.envand the base, 8 and 6 in test, and 15 and 6 in production and beta. - PGPool caches the finished Mapnik style.
On a cache miss, PGPool runs the SQL once for all concurrent callers with the same SQL (greenstand/PGPool.js:27).
The cache stores the finished Mapnik style, not the rows. The cache key is the SQL text only (greenstand/PGPool.js:46).ConfigpassesparseInt(CACHE_SIZE)andparseInt(CACHE_EXPIRE)(greenstand/config.js:104). An unset variable givesNaN, and then the PGPool defaults do not apply.
The manifests setCACHE_EXPIREto 60000..envsets 60. lru-cache 6 reads the value in milliseconds. - The tile server depends on upstream files.
app.jsregisters fonts from the upstream test fixtures intest/data/map-a/(greenstand/app.js:26). Do not delete that directory.app.jsserves a Leaflet viewer at/viewerfromgreenstand/examples/viewer/(greenstand/app.js:40). The analysis excluded that directory. - The image build installs devDependencies.
package.jsonlistspgas a devDependency, butapp.jsrequires it at runtime.make release_baserunsnpm install --ignore-scripts --clang(Makefile:17). The command has no--productionflag, so it installs the devDependencies too.--ignore-scriptsskips theinstallscript of this package, so npm does not fetch a prebuilt binding. Thenmake release_basecompiles the binding withnode-pre-gyp configure build(Makefile:28).
Guided Tour
Follow these 15 steps in order. Steps 1 to 8 cover the tile server. Steps 9 to 12 cover the native Mapnik binding. Steps 13 to 15 cover the delivery.
- Project overview
Files:README.md,package.json
What to see: the README text is upstream node-mapnik documentation. Inpackage.json,mainloads the native Mapnik binding, andstartruns the tile server. - Server entry point
Files:greenstand/server.js,.env
What to see:server.jschecks the two zoom thresholds at startup. - Express tile routes
Files:greenstand/app.js
What to see: the Express service answers PNG and UTF grid routes, and it returns a version banner for other paths. - Per-tile style builder
Files:greenstand/config.js,greenstand/sphericalmercator.js,greenstand/layers/postgis.xml
What to see:getXMLStringhas a GeoJSON branch and a PostGIS branch. - Map modes and base queries
Files:greenstand/Map.js,greenstand/sqls/SQLCase1.jstogreenstand/sqls/SQLCase4.js
What to see: case 1 counts trees per region, case 2 returns tree points, case 3 clusters withST_ClusterWithin, and case 4 reads precomputed clusters. - Specialized query variants
Files:greenstand/sqls/SQLCase1WithZoomTarget.js,greenstand/sqls/SQLZoomTargetCase1.js,greenstand/sqls/*Timeline.js,greenstand/sqls/SQLCase2Wallet.js
What to see: these SQL builders extend the base SQL builders. The zoom target is the most populated subregion two zoom levels deeper. - Cached query pool
Files:greenstand/PGPool.js
What to see: PGPool has an LRU cache and merges concurrent identical queries. - Base styles
Files:greenstand/xml.js,greenstand/xml2.js
What to see:config.jsreplaces thejson_dataandselect * from treesplaceholders. - Mapnik JavaScript loader
Files:lib/mapnik.js,lib/index.js
What to see:lib/mapnik.jsfinds the compiled binding throughnode-pre-gyp. - Native binding core
Files:src/node_mapnik.cpp,src/mapnik_map*.cpp
What to see: these files implementMap.fromStringandMap.render, whichapp.jscalls. - Images, PNG, UTF grids
Files:src/mapnik_image*.cpp,src/mapnik_grid.cpp
What to see: these classes produce the two tile formats. - Native build toolchain
Files:Makefile,binding.gyp,scripts/
What to see:make release_basebuilds the binding against an installedmapnik-config. - Container image
Files:Dockerfile,.dockerignore
What to see: the base imagegreenstand/tile-server-base:firstmust supply Mapnik. TheDockerfileadds Node.js 14.21.3 and runsmake release_base. - Kubernetes deployment
Files:deployment/base/
What to see: the Ambassador Mapping routes/tiles/to the Service. The SealedSecret suppliesDB_URL. - Release and deploy pipelines
Files:.github/workflows/build-deploy.yml,.releaserc,CHANGELOG.md,.github/workflows/deploy-test.yml,.github/workflows/deploy-prod.yml
What to see: a push releases and deploys to development. Test and production need a manual run.
File Map (by layer)
Tile Server API
greenstand/server.js: loads.env, checks the zoom thresholds, and listens onPORT.greenstand/app.js: creates the pg pool (PG_POOL_SIZE, default 10),Config, fonts, CORS, the viewer, and the tile routes.
Tile Style Service
greenstand/config.js: builds the Mapnik style inConfig.getXMLString. Itsreplace,config, andconfigFreetownexports write copies ofpostgis.xmlwith the DB_URL credentials.greenstand/xml.js,greenstand/xml2.js: hold the orange and green base styles.greenstand/sphericalmercator.js: converts tiles to envelopes and makes the buffered SQL bounds.greenstand/layers/postgis.xml: holds a PostGIS base style.
Tree Query And Cache
greenstand/Map.js: picks the SQL builder by map mode and zoom.greenstand/PGPool.js: caches the Mapnik style and merges queries.greenstand/sqls/SQLCase1.js,greenstand/sqls/SQLCase1WithZoomTarget.js: count region clusters fromactive_tree_region.greenstand/sqls/SQLCase2.js,greenstand/sqls/SQLCase2Wallet.js: select tree points.greenstand/sqls/SQLCase3.js: clusters trees on the fly with a radius by zoom.greenstand/sqls/SQLCase4.js: reads precomputed clusters atzoom_level = 14.greenstand/sqls/*Timeline.js: add a date range filter.greenstand/sqls/SQLZoomTargetCase1V2.js:Map.jsimports it (greenstand/Map.js:11), but no code inMap.jsuses it.greenstand/sqls/SQLCase1V2.js,greenstand/sqls/SQLZoomTargetCase1.js,greenstand/sqls/SQLTree.js:Map.jsdoes not import them.
Tile Server Tests And Fixtures
greenstand/*.test.js,greenstand/PGPool.spec.js: run withnpm run jest.greenstand/config.pg.test.jsandgreenstand/db.test.jsneed a live PostGIS database.npm testruns the upstream tape suite intest/, not the tile server tests.
Container And Kubernetes Deployment
Dockerfile: builds one stage ongreenstand/tile-server-base:first, runsmake release_base, and starts withnpm start.deployment/base/: sets namespacetile-server, 1 replica, Service port 80 to 3000, and Mapping/tiles/with a 60000 ms timeout.deployment/overlays/development/: allows CORS from any origin.deployment/overlays/test/: runs 6 replicas and allows CORS fromhttps://test-k8s.treetracker.org.deployment/overlays/production/: runs 2 replicas with a 768Mi request, a 1536Mi limit, no CPU limit, and no gateway timeout.deployment/overlays/beta/: uses namespacetile-server-betaand prefix/tiles-next/.
Release And Deploy Pipelines
.github/workflows/build-deploy.yml: runs semantic-release, pushes the image, and deploys to development on a push tomasterornext..github/workflows/deploy-dev.yml,deploy-test.yml,deploy-prod.yml,deploy-dev-next.yml: deploy a chosen git tag on a manual run.
Project Config And Docs
package.json,.env: hold the scripts, the dependencies, and the local settings..envis in git.CHANGELOG.md: lists the Greenstand releases 4.6.0 (line 773) to 4.36.7 above the upstream# Changelogheading (line 809).README.md,CONTRIBUTING.md,LICENSE.txt,index.html: hold upstream node-mapnik text..huskyrcandcommitlint.config.jscheck Conventional Commits.map.json: holds only the text[object Object]. No code reads it.
Complexity Hotspots
The graph rates 26 files as complex. Two of them are tile server source files: app.js and config.js. The line counts come from the files.
- Tile routes
File:greenstand/app.js(222 lines)
Why: the/newroutes repeat the root handlers and addnewIcons: true(greenstand/app.js:162).getXMLStringdoes not readnewIcons. So the/newroutes return the same tiles as the root routes. - Style builder
File:greenstand/config.js(293 lines)
Why: one method holds the bounds rule, the base style choice, the GeoJSON build, and the PostGIS branch.
Cache: the cache key is the SQL text only. Two requests with the same SQL and a differenticonget the same cached Mapnik style.
Timeline: at zoom 16 and above,SQLCase2Timeline.jsreturns a{text, values}object (greenstand/sqls/SQLCase2Timeline.js:53).config.jspasses that object toreplace(greenstand/config.js:277). The SQL in the Mapnik style then becomes[object Object]. - SQL builders
Files:greenstand/sqls/SQLCase3.js(201),greenstand/sqls/SQLCase2.js(163),greenstand/sqls/SQLCase1.js(149),greenstand/Map.js(198)
Why: the SQL builders put the filter values into the SQL text directly. They use no bound parameters (for examplegreenstand/Map.js:48andgreenstand/Map.js:81). Treat each query parameter as untrusted input. - Stale tests
Files:greenstand/sqls/SQLTree.test.js,greenstand/app.test.js,greenstand/config.test.js,greenstand/config.pg.test.js,greenstand/Map.test.js,greenstand/PGPool.spec.js
SQLTree:SQLTree.test.js:10expectsleft join tokenandleft join entity. The query hasLEFT JOIN wallet.tokenand no entity join (greenstand/sqls/SQLTree.js:27). So the test fails.
App:app.test.jsis empty (0 bytes). Jest fails a suite without tests.
Config:config.test.js:4andconfig.pg.test.js:3importgetXMLString.config.jsdoes not export it (greenstand/config.js:288).
Map:Map.test.js:25expects a{text, values}object.Map.getQueryreturns the value of the SQL builder (greenstand/Map.js:161). All SQL builders thatMap.jsuses return a string, exceptSQLCase2Timeline.js.
PGPool:PGPool.spec.js:17builds PGPool without apool. - Deploy workflows
Files:.github/workflows/deploy-dev.yml,.github/workflows/deploy-dev-next.yml,deployment/overlays/beta/
Why:deploy-dev.yml:38saves the kubeconfig ofTEST_CLUSTER_NAME, but it applies the development overlay.build-deploy.yml:104usesDEV_CLUSTER_NAMEfor the same overlay.deploy-dev-next.yml:32usesdeployment-next/, which is not in the repo. No workflow applies the beta overlay. - Manifests
Files:deployment/base/deployment.yaml,deployment/overlays/production/deployment.yaml
Why: the base Deployment declarescontainerPort: 80(deployment/base/deployment.yaml:41), but the tile server listens on 3000. The Service targets port 3000 by number, so traffic reaches the tile server. The production patch has a comment about a cap on glibc malloc arenas (line 31), but it sets no variable for that cap. - Native Mapnik binding (upstream)
Files: 22 complex files insrc/, for examplesrc/mapnik_map_render.cpp(1335),src/mapnik_map.cpp(938),src/mapnik_image.cpp(735)
Why: this code is upstream C++. The tile server uses only the Map, Image, Grid, Projection, and Logger classes and the font and plugin helpers. - Large files
Files:CHANGELOG.md(2288),greenstand/trees.json(51 MB, 547,448 tree points)
Why: semantic-release writesCHANGELOG.md, so do not edit it by hand. Onlygreenstand/db.test.jsandgreenstand/stylesheet.xmlreadtrees.json.
Business Domains
domain-graph.json has 4 domains, 17 flows, and 90 steps. The bold names are the flow labels in the graph. The domain view of the viewer shows each step.
Map Tile Serving: the Express routes that answer tile requests.
- Start Tile Server (entry:
npm start)server.jsloads.envandapp.js, checks the zoom thresholds, and listens onPORT. - Render PNG Map Tile (entry:
GET /:z/:x/:y.png, also/new/:z/:x/:y.png)
The route builds the map from the Mapnik style and renders a 256x256 PNG. An error gives HTTP 500 with a JSON message. - Render UTF Grid Tile (entry:
GET /:z/:x/:y.grid.json, also/new/:z/:x/:y.grid.json)
The route renders layerl1into a UTF grid withid,latlon,count, andtype. At zoom 9 and below, it addszoom_to. - Report Server Version (entry: any other path, including
GET /)
The catch-all route returns HTTP 200 and thepackage.jsonversion.
Tile Stylesheet Composition: Config.getXMLString builds the Mapnik style.
- Compose GeoJSON Cluster Style (entry:
getXMLStringat zoom 1 to 15)config.jsruns the SQL through PGPool. It puts the rows as GeoJSON into the base style of the chosen icon set. - Compose PostGIS Tree Style (entry:
getXMLStringat zoom 0 and at zoom 16 and above)config.jsputs the DB_URL credentials and the SQL into a PostGIS base style. Mapnik queries PostGIS at render time. - Cache And Coalesce Tile Queries (entry:
PGPool.getQuery)
Concurrent requests with the same SQL share one database query. PGPool caches the finished Mapnik style by SQL text.
Tree Query Selection: Map.init picks an SQL builder.
- Select Default Map Query (entry: a tile request without
userid,wallet,map_name, ortimeline)
Above zoom 15, the SQL returns tree points. From zoom 12 to 15, it reads precomputed clusters. Below zoom 12, it returns region clusters. - Select Planter Map Query (entry: query parameter
userid)Map.initcounts the trees of the planter. Then it picks tree points, region clusters, or on-the-fly clusters. - Select Wallet Map Query (entry: query parameter
wallet)Map.initcounts the tokens of the wallet. Then it picks wallet tree points, region clusters, or on-the-fly clusters. - Select Organization Map Query (entry: query parameter
map_name)
The SQL builders limit the trees to the organization hierarchy. From zoom 12 to 15, they cluster on the fly, except forfreetownandffcphase1(greenstand/Map.js:113). - Select Timeline Map Query (entry: query parameter
timeline)
A timeline SQL builder keeps the trees whosetime_createdfalls in aYYYY-MM-DD_YYYY-MM-DDrange.
Release and Deployment: the workflows, the image, and the manifests.
- Release And Deploy To Development (entry: a push to
masterornext)build-deploy.ymlruns semantic-release and pushes the image with thepackage.jsonversion as the tag. Then it applies the development overlay. - Deploy Tag To Test (entry: a manual run of
deploy-test.yml)
The workflow applies the test overlay for a chosen git tag. It builds no image, so the image must already be in DockerHub. - Promote Tag To Production (entry: a manual run of
deploy-prod.yml)
The workflow applies the production overlay for a chosen git tag on the production cluster. - Redeploy Tag To Development (entry: a manual run of
deploy-dev.yml)
The workflow applies the development overlay again for a chosen git tag. Complexity Hotspots describes its cluster secret. - Route Gateway Tile Traffic (entry: a request to
/tiles/{z}/{x}/{y}.pngor.grid.jsonon the gateway)
The Ambassador Mapping sends/tiles/to the Service. The Service forwards the request to the tile server on port 3000.