Ptolemy

A versioned geodatabase on PostgreSQL and PostGIS. Branch, commit, diff and merge geographic datasets, and read them over REST, OGC API - Features and an ArcGIS FeatureServer facade.

License Rust PostGIS REST API
7
Rust crates
15
CLI commands
OGC
API - Features and Tiles
PostGIS
Feature store

Features

Versioned Geodata

  • Git-like branching and merging for features
  • Full changeset history with diffs
  • Branch-level isolation for concurrent edits
  • Three-way merge, conflicts resolved per feature as ours, theirs, custom, delete or auto_merge
  • Features as of any instant, and a diff between any two changesets

PostGIS Backend

  • PostgreSQL + PostGIS for spatial indexing
  • A GIST-indexed geometry column and a JSONB properties column per feature version
  • A features view any PostgreSQL client can read without Ptolemy running
  • Each commit is one PostgreSQL transaction
  • Connection pooling (sqlx)

REST API

  • Axum 0.8 async HTTP server
  • Dataset, branch, and feature CRUD
  • Commit endpoint with DiffOp operations
  • Branch merge with conflict reporting
  • Diff between any two changesets
  • Branch history (commit log)
  • Spatial queries (bbox, intersects, within)
  • MVT vector tile endpoint
  • Cursor-based pagination
  • Batch commit operations
  • Liveness and readiness probes
  • A body or query string naming a field the route does not declare is refused, 422 or 400, with the key named

Collaboration

  • Named branches per team or task
  • Merge requests with approval, comments and a diff
  • Three-way merge with conflict detection
  • Authenticated workspaces and nested projects
  • Owner, editor, and viewer roles with inherited access
  • Expiring workspace and project invitations
  • Invitations grant editor or viewer and require an authenticated acceptance
  • A dataset attached to a project is private to its members, at their project role
  • Agora applies project roles to a document linked to the project
  • Shared project state and project attachments

Geospatial Types

  • Point, LineString, Polygon, Multi-*, GeometryCollection and mixed geometry datasets
  • Arbitrary JSON properties per feature
  • Optional per-feature validity times and pre-reprojection geometry
  • UUID v7 for time-ordered IDs
  • WKB/GeoJSON interchange

Deployment

  • Single binary CLI (ptolemy serve)
  • Container image at ghcr.io/geolang/ptolemy, docker-compose and a Helm chart
  • Configured by environment variables
  • GeoJSON import/export
  • CLI: dataset, branch, commit, merge, log, diff, import, export, backup, restore, api-key
  • Prometheus metrics at /metrics for an admin token
  • Graceful shutdown (SIGTERM/SIGINT)
  • Configurable connection pool

Authentication

  • HS256 JWTs signed with PLATFORM_JWT_SECRET, roles admin, editor and viewer
  • Workspace and project roles: owner, editor, viewer
  • Project access inherited from workspace membership
  • Direct project membership for project-only access
  • A dataset attached to a project is reached by its members: viewer reads, editor writes, owner administers
  • OIDC Single Sign-On against Keycloak: the three endpoint URLs are built from the issuer as /protocol/openid-connect/…, so a provider that spells them differently does not work
  • The OIDC callback answers a Ptolemy JWT with role editor for every user it signs in
  • API keys (ptk_) from ptolemy api-key create, and scoped tool tokens
  • Per-dataset and per-branch grants: read, write, admin

Schema and Topology

  • Dataset schema: field types, required, allowed values, min and max, checked on commit and ArcGIS applyEdits
  • Batch commit, imports and sync skip the check, and geometry rules are never checked
  • Auto-repair invalid geometries (ST_MakeValid)

Webhooks and CDC

  • Subscribe a url per dataset, filtered by event type
  • commit, merge, branch_created, schema_changed, plus custom events
  • HMAC-SHA256 signed delivery, retried with a backoff, five attempts
  • Subscriptions and deliveries to private addresses are refused unless PTOLEMY_WEBHOOK_ALLOW_PRIVATE_HOSTS is true
  • Events are queued in the commit's own transaction, so a restart loses none
  • The worker also deletes settled deliveries and the events behind them, hourly, after PTOLEMY_EVENTS_RETENTION_DAYS

Spatial Analytics

  • Buffer one feature by a distance in meters
  • Union of a branch's features and its area
  • Coverage: the area a branch's features reach when buffered, counted once where they overlap
  • DBSCAN spatial clustering
  • Anomalies: features over 3 standard deviations from the centroid, and non-simple geometries
  • Branch statistics: count, total area and length, extent, centroid

OGC API - Features

  • Part 1 Core
  • GeoJSON feature collections
  • Bbox filtering, pagination
  • Conformance declaration
  • Part 2 CRS by reference: CRS84, EPSG:4326, EPSG:3857 and the dataset srid
  • CRS84 is longitude first, a geographic EPSG code latitude first

ArcGIS FeatureServer

  • Every dataset is a single-layer FeatureServer under /arcgis/rest/services, so Esri clients connect unchanged
  • query takes the SQL-92 where subset those clients send, paging, outSR/inSR, an envelope filter and f=json, pjson or geojson
  • returnDistinctValues, outStatistics with groupByFieldsForStatistics, and having over the same seven functions
  • applyEdits lands the whole batch as one commit on main, or refuses all of it
  • Attachments, and extractChanges deltas against a generation the client holds
  • A stored Esri drawing document is served back as drawingInfo, or translated to Mapbox GL layers at /api/v1/datasets/{id}/style
  • A token may arrive in X-Esri-Authorization or a token parameter, read under this prefix and nowhere else
  • The dataset schema is checked on applyEdits, as on a commit

Your existing PostGIS, read-only

  • Register a table or view as an external dataset and read it through the normal API without copying it
  • Feature listing, bbox, CQL2, OGC items, GeoJSON and CSV export, vector tiles
  • Commits, merges, imports, QGIS push and branch creation answer 409
  • Geometry is served in EPSG:4326, and spatial reads also push an index-served predicate onto the relation's own column in its own SRID
  • An ordinary GiST index on the geometry column is all it needs
  • Registering needs the admin role and PTOLEMY_EXTERNAL_DATABASE_URL, a connection as a SELECT-only role, so PostgreSQL enforces the read-only part. Unset, external datasets are off

Audit Log

  • One row per mutation: subject, route, target, time
  • Reads are not recorded
  • Read back at GET /api/v1/audit, instance admin only

Temporal Queries

  • A branch's features as of an RFC 3339 instant: /api/v1/branches/{id}/features/at?at=
  • Per-feature valid_from and valid_to, filtered with valid_at
  • Branch history and a diff between any two changesets

Data Catalog

  • Substring search over dataset name and description, case-insensitive
  • Tags, and search filtered by them
  • Metadata per dataset: source, license, attribution
  • No ranking and no typo tolerance: it is ILIKE, not a text index

Access

  • Dataset visibility: a private dataset answers 404 and is left out of listings for a caller with no grant
  • Webhooks, audit, metrics, replication and PostGIS Topology need an admin token
  • No multi-tenancy. One instance is one tenant
  • No rate limiting. Put a proxy in front

Operations

  • Webhook delivery worker starts with the server
  • Planner statistics refreshed after a bulk write, over PTOLEMY_ANALYZE_ROW_THRESHOLD rows
  • Console logging through tracing-subscriber, filtered by RUST_LOG
  • Prometheus metrics at /metrics for an admin token
  • No trace export. There is no OTLP exporter in the binary

Geometric Networks

  • Graph topology: junctions + edges
  • Upstream/downstream/bidirectional trace, walked by a recursive CTE
  • Shortest path, A*, isochrone, TSP and connectivity call pgRouting
  • Those five answer 501 where pgRouting is not installed, which no image here installs

Linear Referencing

  • Route creation with measured geometries
  • Point and linear events along routes
  • Point to measure (ST_LineLocatePoint)
  • Measure range to sub-line (ST_LineSubstring)
  • Event geometry from ST_LocateAlong and ST_LocateBetween

Raster and Imagery

  • Raster catalogs per dataset
  • Tiles are uploaded as WKB hex, each carrying the zoom level the uploader gives it
  • Point value extraction (ST_Value)
  • Band statistics over a catalog's tiles
  • Configurable pixel type and SRID
  • Nothing builds an overview pyramid: every level is uploaded

Domains and attribute rules

  • Coded-value and range domains are stored and served
  • Subtypes are stored
  • Enforced nowhere. There is no expression engine

Relationship Classes

  • Simple and composite relationships
  • Forward/backward label navigation at /api/v1/features/{id}/related
  • Cross-dataset feature linking
  • Cardinality is a stored column. Nothing checks a record against it

Cartography

  • Symbology rules with scale ranges, listed in priority order
  • A rule's filter expression is stored and served back, never evaluated here
  • Label rules with font and placement, stored for a client to draw
  • JSON-based symbol definitions
  • An Esri drawing document stored as a symbol is translated to Mapbox GL layers at /api/v1/datasets/{id}/style

pgRouting

  • Dijkstra and A* shortest path
  • Driving distance and isochrones
  • Traveling Salesman (TSP)
  • Connected components analysis
  • Install pgRouting yourself. No image here does, and without it these routes answer 501

PostGIS Topology

  • Create a topology, validate it, list its faces, edges and nodes, add a face
  • Every route but validate needs an admin token
  • Simplify answers simplified and changes nothing

SFCGAL 3D

  • 3D extrusion, volume computation
  • 3D intersection and Minkowski sum
  • Straight skeleton, tesselation
  • Line of sight from an observer point to a feature's centroid
  • Without SFCGAL installed these routes answer 501

H3 Hexagonal Indexing

  • Uber H3 spatial index per feature
  • Hex-based spatial aggregation
  • K-ring neighbors and compaction
  • Multi-resolution analysis (0-15)
  • Without h3-pg installed these routes answer 501

pgvector Similarity

  • Feature embedding and similarity search
  • The embedding is a SHA-256 hash spread over 256 floats, so identical text matches and near-identical text does not
  • Duplicate detection on that basis
  • Equal-size buckets by distance to the mean vector, not k-means
  • IVFFlat index, created when pgvector is installed
  • Without pgvector these routes answer 501

Point Cloud / LiDAR

  • pointcloud extension (pcpatch)
  • Spatial patch queries and elevation profiles
  • Catalog management
  • Points arrive in patches, one row each
  • Without the pointcloud extension, adding a patch and a profile answer 501

MobilityDB Trajectories

  • Temporal geometry (tgeompoint)
  • Speed, distance, nearest approach
  • Position at any timestamp
  • Trajectory simplification
  • Without MobilityDB a trajectory is stored as JSONB and these routes answer 501

CQL2 + OGC Tiles

  • CQL2-JSON: comparisons, and, or, not, like, between, in, isNull
  • Spatial operators: s_intersects, s_within, s_contains
  • OGC TileMatrixSet API
  • Vector tiles (MVT) per dataset

STAC Catalog

  • Catalog, collection and item routes declaring STAC 1.0.0
  • A collection per raster catalog, an item per raster tile
  • Spatial and temporal search
  • Raster tiles are not covered by dataset visibility

Format and CRS

  • GeoJSON, CSV, FlatGeobuf export
  • GeoJSON and CSV import, up to 50,000 features and 64 MiB a request, as one changeset
  • CRS transformation, one geometry per request, through ST_Transform
  • CRS search and lookup (spatial_ref_sys)

Architecture

ptolemy-core

  • Domain types: Dataset, Branch, Changeset, Feature, Diff
  • Serialization with serde
  • WKB and GeoJSON conversion through geozero
  • The DataStore trait a backend crate implements

ptolemy-storage

  • PgStore, the one store the server and CLI use
  • SQL migrations, run on every serve. A v0.1.0 database upgrades in place
  • Reads and writes go through a Reader or Writer that carries the permission decision

ptolemy-geopackage / -mongodb / -elasticsearch

  • Each implements the DataStore trait from ptolemy-core
  • No binary depends on them: the server and the CLI use PgStore
  • The CLI reads shapefiles and GeoPackage and writes GeoPackage itself, through shapefile and rusqlite

ptolemy-api

  • Axum 0.8 HTTP router
  • Layers: tracing, auth, dataset visibility, the write gate, audit, metrics
  • Permissive CORS on the ArcGIS routes, which real ArcGIS servers answer, and nowhere else
  • Typed JSON responses

ptolemy-cli

  • Clap-based CLI
  • ptolemy serve --bind 0.0.0.0:3000
  • Dataset, branch, commit, merge, import, export, backup and API key commands

Quick Start

# Clone and build
git clone https://github.com/GeoLang/ptolemy.git
cd ptolemy
cargo build --release

# Start with a PostGIS database. serve refuses to start without a signing
# secret of 32 bytes or more, and applies migrations before it binds
export DATABASE_URL="postgres://user:pass@localhost/ptolemy"
export PLATFORM_JWT_SECRET="$(openssl rand -hex 32)"
./target/release/ptolemy serve --bind 0.0.0.0:3000

# Check health
curl http://localhost:3000/api/v1/healthz
curl http://localhost:3000/api/v1/readyz