From 0ec615c4f692b44d7962bfeae30d4a2e985bd68e Mon Sep 17 00:00:00 2001 From: Esteban Zimanyi Date: Sat, 21 Nov 2026 10:24:55 +0100 Subject: [PATCH] Answer the EDR radius, cube and instances queries over a raster collection A raster collection answers two more queries of the EDR 1.1 class queries, each in CoverageJSON. radius clips the raster of a period to the buffer of a POINT by within, in the within-units km or m, the buffer taken on the sphere as the corridor's is; the description then states distanceunits, as /req/edr/rc-collection-info I requires. cube clips it to a bbox, read as /coverage reads one; z is required by /req/edr/rc-cube G and is read and not applied, since a raster has no vertical axis, which the query's variables state. The periods of the collection are its instances: /instances lists them in time order and /instances/{iid} describes one, each as a collection is described, with the extent of its period alone, its id the start of the period in RFC 3339. Each query answers under an instance from the rows of that period alone, through a source that reads them under the table's own name. Witness: TestLiveRasterEDRQueries reads a radius and a cube of the series, the refusals of each (a missing within, within-units, bbox or z, an unknown unit, a coords of the wrong type), the two instances and their extents, the description /instances/{iid} writes against the one /instances lists, and the position and area an instance answers. Measured: on MobilityDB master bd32673470 the radius and the cube answer grids holding no value, as clip placed the mask at the corner of the raster; with MobilityDB's clip on its grid both answer the pixels ST_Clip answers, and the whole suite passes. --- api/surface.json | 160 ++++++++++++++++++++++++++ coverage.go | 219 +++++++++++++++++++++++++++++++----- edr.go | 140 ++++++++++++++++------- edr_live_test.go | 124 +++++++++++++++++++- main.go | 11 +- samples/api-definition.json | 110 ++++++++++++++++++ 6 files changed, 693 insertions(+), 71 deletions(-) diff --git a/api/surface.json b/api/surface.json index 3d92219..d0f1bde 100644 --- a/api/surface.json +++ b/api/surface.json @@ -112,6 +112,23 @@ "transform" ] }, + { + "method": "GET", + "path": "/collections/{cid}/cube", + "conformanceClass": "http://www.opengis.net/spec/ogcapi-edr-1/1.1/conf/core", + "functions": [ + "SRID", + "asCoverageJSON", + "clip", + "extent", + "rasterTileValue", + "rasterUnion", + "rasterValue", + "stbox", + "timeSpan", + "transform" + ] + }, { "method": "GET", "path": "/collections/{cid}/export", @@ -124,6 +141,132 @@ "stbox" ] }, + { + "method": "GET", + "path": "/collections/{cid}/instances", + "conformanceClass": "http://www.opengis.net/spec/ogcapi-edr-1/1.1/conf/core", + "functions": [ + "bandPixelType", + "extent", + "numBands", + "stbox", + "transform" + ] + }, + { + "method": "GET", + "path": "/collections/{cid}/instances/{iid}", + "conformanceClass": "http://www.opengis.net/spec/ogcapi-edr-1/1.1/conf/core", + "functions": [ + "bandPixelType", + "extent", + "numBands", + "stbox", + "transform" + ] + }, + { + "method": "GET", + "path": "/collections/{cid}/instances/{iid}/area", + "conformanceClass": "http://www.opengis.net/spec/ogcapi-edr-1/1.1/conf/core", + "functions": [ + "SRID", + "asCoverageJSON", + "clip", + "extent", + "rasterTileValue", + "rasterUnion", + "rasterValue", + "stbox", + "timeSpan", + "transform" + ] + }, + { + "method": "GET", + "path": "/collections/{cid}/instances/{iid}/corridor", + "conformanceClass": "http://www.opengis.net/spec/ogcapi-edr-1/1.1/conf/core", + "functions": [ + "SRID", + "asCoverageJSON", + "clip", + "extent", + "rasterTileValue", + "rasterUnion", + "rasterValue", + "stbox", + "timeSpan", + "transform" + ] + }, + { + "method": "GET", + "path": "/collections/{cid}/instances/{iid}/cube", + "conformanceClass": "http://www.opengis.net/spec/ogcapi-edr-1/1.1/conf/core", + "functions": [ + "SRID", + "asCoverageJSON", + "clip", + "extent", + "rasterTileValue", + "rasterUnion", + "rasterValue", + "stbox", + "timeSpan", + "transform" + ] + }, + { + "method": "GET", + "path": "/collections/{cid}/instances/{iid}/position", + "conformanceClass": "http://www.opengis.net/spec/ogcapi-edr-1/1.1/conf/core", + "functions": [ + "SRID", + "asCoverageJSON", + "clip", + "extent", + "rasterTileValue", + "rasterUnion", + "rasterValue", + "stbox", + "timeSpan", + "transform" + ] + }, + { + "method": "GET", + "path": "/collections/{cid}/instances/{iid}/radius", + "conformanceClass": "http://www.opengis.net/spec/ogcapi-edr-1/1.1/conf/core", + "functions": [ + "SRID", + "asCoverageJSON", + "clip", + "extent", + "rasterTileValue", + "rasterUnion", + "rasterValue", + "stbox", + "timeSpan", + "transform" + ] + }, + { + "method": "GET", + "path": "/collections/{cid}/instances/{iid}/trajectory", + "conformanceClass": "http://www.opengis.net/spec/ogcapi-edr-1/1.1/conf/core", + "functions": [ + "SRID", + "asCoverageJSON", + "clip", + "extent", + "rasterTileValue", + "rasterUnion", + "rasterValue", + "stbox", + "timeSpan", + "transform" + ] + }, { "method": "GET", "path": "/collections/{cid}/items", @@ -349,6 +492,23 @@ "transform" ] }, + { + "method": "GET", + "path": "/collections/{cid}/radius", + "conformanceClass": "http://www.opengis.net/spec/ogcapi-edr-1/1.1/conf/core", + "functions": [ + "SRID", + "asCoverageJSON", + "clip", + "extent", + "rasterTileValue", + "rasterUnion", + "rasterValue", + "stbox", + "timeSpan", + "transform" + ] + }, { "method": "GET", "path": "/collections/{cid}/schema", diff --git a/coverage.go b/coverage.go index ffae07d..db27b2f 100644 --- a/coverage.go +++ b/coverage.go @@ -64,9 +64,24 @@ var coverageEncodings = []struct{ media, fn string }{ // coverageSource is what the registry records of a raster collection: its // table, its period column, its raster column and the raster type of that -// column. +// column. Period, where set, is the one period of an instance +// (#coverageInstance) the source reads. type coverageSource struct { Table, Time, Raster, Type string + Period string +} + +// from answers the SQL a query reads the rows of the source from: its table, +// or the rows of its period alone, under the table's own name, so the +// statements reading the table read an instance unchanged. The period is the +// text MobilityDB wrote of a period of the table, quoted as a literal, as +// #ident quotes a name. +func (src coverageSource) from() string { + if src.Period == "" { + return ident(src.Table) + } + return "(SELECT * FROM " + ident(src.Table) + " WHERE " + ident(src.Time) + " = CAST('" + + strings.ReplaceAll(src.Period, "'", "''") + "' AS tstzspan)) AS " + ident(src.Table) } // coverageMeta answers the source of a raster collection, and false for a @@ -196,24 +211,86 @@ func ensureRegistry(ctx context.Context, tx Tx) error { // /req/core/rc-collection-info-links of EDR requires: the description, the // coverage in each encoding, the schema, and one data link per query of // #edrQueries, written as #edrDataQueries writes its links. -func coverageLinks(cid string) []map[string]string { +// +// The description of an instance, one period of the collection, links itself, +// the collection it belongs to and its own data links, the coverage and the +// schema being the collection's. +func coverageLinks(cid string, inst *coverageInstance) []map[string]string { + base := "/collections/" + cid links := []map[string]string{ - {"rel": "self", "href": "/collections/" + cid, "type": "application/json"}, - {"rel": relCoverage, "href": "/collections/" + cid + "/coverage", "type": mediaGeoTIFF}, - {"rel": relCoverage, "href": "/collections/" + cid + "/coverage", "type": mediaCovJSON}, - {"rel": relSchema, "href": "/collections/" + cid + "/schema", "type": mediaSchema}, + {"rel": "self", "href": base, "type": "application/json"}, + {"rel": relCoverage, "href": base + "/coverage", "type": mediaGeoTIFF}, + {"rel": relCoverage, "href": base + "/coverage", "type": mediaCovJSON}, + {"rel": relSchema, "href": base + "/schema", "type": mediaSchema}, + } + if inst != nil { + links = []map[string]string{ + {"rel": "self", "href": inst.path(cid), "type": "application/json"}, + {"rel": "collection", "href": base, "type": "application/json"}, + } + base = inst.path(cid) } for _, q := range edrQueries { - links = append(links, map[string]string{"rel": "data", "href": "/collections/" + cid + "/" + q.name, + links = append(links, map[string]string{"rel": "data", "href": base + "/" + q.name, "type": mediaCovJSON, "title": q.name}) } return links } +// coverageInstance is an instance of a raster collection, as +// /req/instances/src-md-op of EDR names one: a period of the collection, the +// rows of which are the tiles of one raster, identified by its start in RFC +// 3339, which no other period shares since the periods of a collection do not +// overlap. +type coverageInstance struct { + ID, Period string +} + +// path answers the path of the instance's description. +func (inst *coverageInstance) path(cid string) string { + return "/collections/" + cid + "/instances/" + inst.ID +} + +// coverageInstances answers the instances of a raster collection, one per +// period in time order, as #coveragePeriod reads the periods. +func coverageInstances(ctx context.Context, src coverageSource) ([]coverageInstance, error) { + rows, err := db.Query(ctx, "SELECT DISTINCT CAST("+ident(src.Time)+" AS text), CAST(lower("+ + ident(src.Time)+") AS text), lower("+ident(src.Time)+") FROM "+ident(src.Table)+" ORDER BY 3") + if err != nil { + return nil, err + } + defer rows.Close() + var out []coverageInstance + for rows.Next() { + var period, start string + var skip any + if err := rows.Scan(&period, &start, &skip); err != nil { + return nil, err + } + out = append(out, coverageInstance{ID: rfc3339(start), Period: period}) + } + return out, rows.Err() +} + +// coverageInstanceByID answers the instance of a raster collection an id +// names, and 404 for an id naming none. +func coverageInstanceByID(ctx context.Context, cid string, src coverageSource, id string) (*coverageInstance, error) { + insts, err := coverageInstances(ctx, src) + if err != nil { + return nil, err + } + for i := range insts { + if insts[i].ID == id { + return &insts[i], nil + } + } + return nil, statusErr{404, "the raster collection " + cid + " has no instance " + id} +} + // coverageCollection writes the description of a raster collection, the one // #coverageDescription answers. func coverageCollection(w http.ResponseWriter, r *http.Request, cid string, src coverageSource) { - col, err := coverageDescription(r.Context(), cid, src) + col, err := coverageDescription(r.Context(), cid, src, nil) if err != nil { httpErr(w, errStatus(err, 500), err.Error()) return @@ -221,6 +298,62 @@ func coverageCollection(w http.ResponseWriter, r *http.Request, cid string, src writeJSON(w, 200, col) } +// listInstances answers GET /collections/{cid}/instances, the instances of a +// raster collection, each described as #coverageDescription describes it, in +// the document instances.yaml of EDR 1.1 states. +func listInstances(w http.ResponseWriter, r *http.Request) { + cid := r.PathValue("cid") + src, ok := coverageMeta(r.Context(), cid) + if !ok { + httpErr(w, 404, "no raster collection "+cid) + return + } + insts, err := coverageInstances(r.Context(), src) + if err != nil { + httpErr(w, 500, err.Error()) + return + } + out := []map[string]any{} + for i := range insts { + d, err := coverageDescription(r.Context(), cid, src, &insts[i]) + if err != nil { + httpErr(w, errStatus(err, 500), err.Error()) + return + } + out = append(out, d) + } + writeJSON(w, 200, map[string]any{ + "links": []map[string]string{ + {"rel": "self", "href": "/collections/" + cid + "/instances", "type": "application/json"}, + {"rel": "collection", "href": "/collections/" + cid, "type": "application/json"}, + }, + "instances": out, + }) +} + +// getInstance answers GET /collections/{cid}/instances/{iid}, the description +// of one instance as collection.yaml of EDR 1.1 states a description, the one +// #listInstances lists for it. +func getInstance(w http.ResponseWriter, r *http.Request) { + cid := r.PathValue("cid") + src, ok := coverageMeta(r.Context(), cid) + if !ok { + httpErr(w, 404, "no raster collection "+cid) + return + } + inst, err := coverageInstanceByID(r.Context(), cid, src, r.PathValue("iid")) + if err != nil { + httpErr(w, errStatus(err, 500), err.Error()) + return + } + d, err := coverageDescription(r.Context(), cid, src, inst) + if err != nil { + httpErr(w, errStatus(err, 500), err.Error()) + return + } + writeJSON(w, 200, d) +} + // coverageDescription answers the description of a raster collection, which // #listCollections lists and #coverageCollection writes, so that the two agree // as /req/collections/src-md-success C of EDR requires: its links, its extent @@ -228,7 +361,12 @@ func coverageCollection(w http.ResponseWriter, r *http.Request, cid string, src // queries it answers and their output formats, and its bands as // /req/edr/rc-parameters states parameters, written as asCoverageJSON writes // its parameters and keyed by the names #edrBands reads from parameter-name. -func coverageDescription(ctx context.Context, cid string, src coverageSource) (map[string]any, error) { +// +// The description of an instance is that of its period alone: its id, its +// links (#coverageLinks), its queries and its extent, the bounds of the tiles +// of the period and the period itself. +func coverageDescription(ctx context.Context, cid string, src coverageSource, + inst *coverageInstance) (map[string]any, error) { var title, desc string var srid int if err := db.QueryRow(ctx, `SELECT title,description,crs FROM collections WHERE id=$1`, cid). @@ -251,16 +389,24 @@ func coverageDescription(ctx context.Context, cid string, src coverageSource) (m "observedProperty": map[string]any{"label": map[string]string{"en": label}}, } } + id, base := cid, "/collections/"+cid + if inst != nil { + id, base = inst.ID, inst.path(cid) + title = title + ", " + inst.Period + } col := map[string]any{ - "id": cid, "title": title, "description": desc, "itemType": coverageItems, + "id": id, "title": title, "description": desc, "itemType": coverageItems, "keywords": []string{coverageItems, src.Type}, "crs": []string{"http://www.opengis.net/def/crs/EPSG/0/" + itoa(srid)}, "rasterType": src.Type, - "links": coverageLinks(cid), + "links": coverageLinks(cid, inst), // The EDR queries the collection answers - "data_queries": edrDataQueries(cid), + "data_queries": edrDataQueries(base), "output_formats": []string{edrFormat}, "parameter_names": params, + // A description linking a radius query states its distance units, as + // /req/edr/rc-collection-info I requires + "distanceunits": edrDistanceUnits, } if srid != 4326 { col["storageCrs"] = "http://www.opengis.net/def/crs/EPSG/0/" + itoa(srid) @@ -268,10 +414,14 @@ func coverageDescription(ctx context.Context, cid string, src coverageSource) (m if rasterHas(src.Type, "stbox") { var xmin, ymin, xmax, ymax *float64 var tmin, tmax *string + where, args := "", []any{} + if inst != nil { + where, args = " WHERE "+ident(src.Time)+" = CAST($1 AS tstzspan)", []any{inst.Period} + } sql := "SELECT Xmin(b),Ymin(b),Xmax(b),Ymax(b),CAST(lower(p) AS text),CAST(upper(p) AS text) FROM (" + "SELECT transform(extent(stbox(" + ident(src.Raster) + ")), 4326) b, extent(" + - ident(src.Time) + ") p FROM " + ident(src.Table) + ") s" - if err := db.QueryRow(ctx, sql).Scan(&xmin, &ymin, &xmax, &ymax, &tmin, &tmax); err == nil && + ident(src.Time) + ") p FROM " + ident(src.Table) + where + ") s" + if err := db.QueryRow(ctx, sql, args...).Scan(&xmin, &ymin, &xmax, &ymax, &tmin, &tmax); err == nil && xmin != nil && tmin != nil { col["extent"] = map[string]any{ "spatial": map[string]any{"bbox": [][]float64{{*xmin, *ymin, *xmax, *ymax}}, @@ -371,6 +521,25 @@ type coverageRequest struct { writer string // the function writing it } +// parseBbox reads a bbox of four numbers, minLon,minLat,maxLon,maxLat in +// CRS84, the bbox #parseCoverageRequest reads for /coverage and #edrClip for +// an EDR cube. +func parseBbox(b string) ([]float64, error) { + parts := strings.Split(b, ",") + if len(parts) != 4 { + return nil, statusErr{400, "bbox is minLon,minLat,maxLon,maxLat in CRS84"} + } + out := make([]float64, 0, 4) + for _, p := range parts { + f, err := strconv.ParseFloat(strings.TrimSpace(p), 64) + if err != nil { + return nil, statusErr{400, "bbox holds " + p + ", which is no number"} + } + out = append(out, f) + } + return out, nil +} + // subsetAxis matches one axis of a subset: its name and its interval or value. var subsetAxis = regexp.MustCompile(`([A-Za-z]+)\(([^)]*)\)`) @@ -400,17 +569,11 @@ func parseCoverageRequest(r *http.Request, nbands int) (coverageRequest, error) if lat != nil || lon != nil { return cr, statusErr{400, "bbox and a spatial subset are given together"} } - parts := strings.Split(b, ",") - if len(parts) != 4 { - return cr, statusErr{400, "bbox is minLon,minLat,maxLon,maxLat in CRS84"} - } - for _, p := range parts { - f, err := strconv.ParseFloat(strings.TrimSpace(p), 64) - if err != nil { - return cr, statusErr{400, "bbox holds " + p + ", which is no number"} - } - cr.bbox = append(cr.bbox, f) + bbox, err := parseBbox(b) + if err != nil { + return cr, err } + cr.bbox = bbox } else if lat != nil || lon != nil { cr.bbox = []float64{-180, -90, 180, 90} set := func(iv []string, lo, hi int) error { @@ -549,7 +712,7 @@ func coverageSpan(dt string) (string, error) { // refusal of a request selecting none or several. func coveragePeriod(ctx context.Context, src coverageSource, span string) (string, error) { sql := "SELECT DISTINCT CAST(" + ident(src.Time) + " AS text), " + ident(src.Time) + " FROM " + - ident(src.Table) + src.from() var args []any if span != "" { sql += " WHERE " + ident(src.Time) + " && CAST($1 AS tstzspan)" @@ -650,18 +813,18 @@ func spanBounds(span string) (string, string) { // bands are requested, and written by the negotiated writer. func coverageData(ctx context.Context, src coverageSource, period string, cr coverageRequest) ([]byte, []float64, int, error) { var ntiles int - if err := db.QueryRow(ctx, "SELECT COUNT(*) FROM "+ident(src.Table)+" WHERE "+ident(src.Time)+ + if err := db.QueryRow(ctx, "SELECT COUNT(*) FROM "+src.from()+" WHERE "+ident(src.Time)+ " = CAST($1 AS tstzspan)", period).Scan(&ntiles); err != nil { return nil, nil, 0, err } rast := ident(src.Raster) - from := "(SELECT " + rast + " AS r FROM " + ident(src.Table) + " WHERE " + ident(src.Time) + + from := "(SELECT " + rast + " AS r FROM " + src.from() + " WHERE " + ident(src.Time) + " = CAST($1 AS tstzspan)) t" if ntiles > 1 { if err := needRaster(src.Type, "rasterUnion"); err != nil { return nil, nil, 0, err } - from = "(SELECT rasterUnion(" + rast + ") AS r FROM " + ident(src.Table) + " WHERE " + + from = "(SELECT rasterUnion(" + rast + ") AS r FROM " + src.from() + " WHERE " + ident(src.Time) + " = CAST($1 AS tstzspan)) t" } args := []any{period} diff --git a/edr.go b/edr.go index 8454233..4b1a07c 100644 --- a/edr.go +++ b/edr.go @@ -10,8 +10,10 @@ package main // - /trajectory reads them along a LINESTRINGM, whose M ordinate is the // number of seconds since the Unix epoch, as tgeompoint(geometry) reads it, // written as a Trajectory; -// - /area clips the raster of one period to a POLYGON and /corridor to the -// buffer of a path by its width, each a Grid, as a coverage is one period. +// - /area clips the raster of one period to a POLYGON, /corridor to the +// buffer of a path by its width, /radius to the buffer of a POINT by its +// within distance and /cube to a bbox, each a Grid, as a coverage is one +// period. // // The values along a point or a path are read across the periods of the // collection by the series reader over the rasters and their periods, so a @@ -27,15 +29,18 @@ import ( // The conformance class of EDR the tier declares: the core, which // /req/core/conformance names. The class queries of 1.1 holds eight queries, each -// one a server MAY answer, and the tier answers four; the class covjson of 1.1 +// one a server MAY answer, and the tier answers six; the class covjson of 1.1 // names CoverageJSON application/prs.coverage+json, where the tier writes // application/vnd.cov+json, the type OGC CoverageJSON (OGC 21-069r2) defines. const edrConformance = "http://www.opengis.net/spec/ogcapi-edr-1/1.1/conf/core" -// The queries a raster collection answers, with the WKT geometry each reads. +// The queries a raster collection answers, with the WKT geometry each reads +// from coords; cube reads a bbox and no coords. var edrQueries = []struct{ name, geometry string }{ {"position", "POINT"}, + {"radius", "POINT"}, {"area", "POLYGON"}, + {"cube", ""}, {"trajectory", "LINESTRING"}, {"corridor", "LINESTRING"}, } @@ -43,29 +48,41 @@ var edrQueries = []struct{ name, geometry string }{ // edrFormat is the one output format, as f names it. const edrFormat = "CoverageJSON" -// edrWidthUnits are the units corridor-width is given in, with the metres in -// one. +// edrWidthUnits are the units corridor-width and within are given in, with the +// metres in one. var edrWidthUnits = map[string]float64{"m": 1, "km": 1000} +// edrDistanceUnits are the units of edrWidthUnits, as the description's +// distanceunits and the variables of a query state them. +var edrDistanceUnits = []string{"km", "m"} + // edrDataQueries is the data_queries member of a raster collection's // description, beside the links #coverageLinks states: one link per query, its -// variables as /req/edr/rc-common-variables states them, the corridor's with -// its units. A raster has no vertical axis, so a corridor's height is read and -// not applied, which its variables state. -func edrDataQueries(cid string) map[string]any { +// variables as /req/edr/rc-common-variables states them, the corridor's and the +// radius's with their units. A raster has no vertical axis, so a corridor's +// height and a cube's z are read and not applied, which their variables state. +// The links are under base, the path of the collection or of an instance, as +// #coverageLinks writes its data links under the same base. +func edrDataQueries(base string) map[string]any { out := map[string]any{} for _, q := range edrQueries { vars := map[string]any{ "query_type": q.name, "output_formats": []string{edrFormat}, "default_output_format": edrFormat, } - if q.name == "corridor" { - vars["width_units"] = []string{"km", "m"} + switch q.name { + case "corridor": + vars["width_units"] = edrDistanceUnits vars["height_units"] = []string{"m"} vars["description"] = "The coverage has no vertical axis: corridor-height is read and not applied." + case "radius": + vars["within_units"] = edrDistanceUnits + case "cube": + vars["height_units"] = []string{"m"} + vars["description"] = "The coverage has no vertical axis: z is read and not applied." } out[q.name] = map[string]any{"link": map[string]any{ - "href": "/collections/" + cid + "/" + q.name, "rel": "data", "variables": vars, + "href": base + "/" + q.name, "rel": "data", "variables": vars, }} } return out @@ -73,7 +90,8 @@ func edrDataQueries(cid string) map[string]any { // edrQuery answers GET /collections/{cid}/{query}, as #getCoverage answers // /coverage: the raster collection read, f checked, and the query's answer -// written in CoverageJSON. +// written in CoverageJSON. Under /collections/{cid}/instances/{iid}/{query} it +// reads the period of that instance alone (#coverageSource from). func edrQuery(query string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { cid := r.PathValue("cid") @@ -82,13 +100,21 @@ func edrQuery(query string) http.HandlerFunc { httpErr(w, 404, "no raster collection "+cid) return } + if iid := r.PathValue("iid"); iid != "" { + inst, err := coverageInstanceByID(r.Context(), cid, src, iid) + if err != nil { + httpErr(w, errStatus(err, 500), err.Error()) + return + } + src.Period = inst.Period + } q := r.URL.Query() if f := first(q, "f"); f != "" && !strings.EqualFold(f, edrFormat) { httpErr(w, 400, "f="+f+" is not an output format of the collection; it is "+edrFormat) return } coords := first(q, "coords") - if coords == "" { + if coords == "" && query != "cube" { httpErr(w, 400, "the "+query+" query needs coords, a WKT geometry") return } @@ -198,7 +224,7 @@ func edrAlong(ctx context.Context, cid string, src coverageSource, query, coords if dt == "" { var lo, hi *string if err := db.QueryRow(ctx, "SELECT CAST(lower(p) AS text), CAST(upper(p) AS text) FROM ("+ - "SELECT extent("+ident(src.Time)+") p FROM "+ident(src.Table)+") s").Scan(&lo, &hi); err != nil || + "SELECT extent("+ident(src.Time)+") p FROM "+src.from()+") s").Scan(&lo, &hi); err != nil || lo == nil { return nil, statusErr{404, "the raster collection holds no raster"} } @@ -225,7 +251,7 @@ func edrAlong(ctx context.Context, cid string, src coverageSource, query, coords } read += ")" sql := "SELECT asCoverageJSON(" + read + ", t) FROM (SELECT " + traj + " AS t) p, " + - ident(src.Table) + " WHERE " + ident(src.Time) + " && timeSpan(t) GROUP BY t" + src.from() + " WHERE " + ident(src.Time) + " && timeSpan(t) GROUP BY t" var text *string if err := db.QueryRow(ctx, sql, args...).Scan(&text); err != nil { if strings.Contains(err.Error(), "no rows") { @@ -240,33 +266,57 @@ func edrAlong(ctx context.Context, cid string, src coverageSource, query, coords } // edrClip answers /area and /corridor: the raster of one period clipped to a -// polygon, or to the buffer of a path by the corridor's width, a Grid written -// by #coverageData as /coverage writes a clipped raster. +// polygon, to the buffer of a path by the corridor's width or of a point by the +// radius's within distance, or to the bbox of a cube, a Grid written by +// #coverageData as /coverage writes a clipped raster. func edrClip(ctx context.Context, src coverageSource, query, coords string, q map[string][]string) ([]byte, error) { - want := map[string]string{"area": "POLYGON", "corridor": "LINESTRING"}[query] - if err := edrCoords(ctx, query, want, coords); err != nil { - return nil, err - } - region := "transform(ST_GeomFromText($2, 4326), SRID(r))" - if query == "corridor" { - for _, p := range []string{"corridor-width", "width-units", "corridor-height", "height-units"} { + cr := coverageRequest{regionArg: coords, writer: "asCoverageJSON"} + switch query { + case "cube": + // The bbox is read as /coverage reads one; a raster has no vertical + // axis, so z, which /req/edr/rc-cube G requires, is read and not applied + for _, p := range []string{"bbox", "z"} { if first(q, p) == "" { - return nil, statusErr{400, "the corridor query needs " + p} + return nil, statusErr{400, "the cube query needs " + p} } } - width, err := strconv.ParseFloat(first(q, "corridor-width"), 64) - if err != nil || width <= 0 { - return nil, statusErr{400, "corridor-width is a positive number"} + bbox, err := parseBbox(first(q, "bbox")) + if err != nil { + return nil, err } - perUnit, ok := edrWidthUnits[strings.ToLower(first(q, "width-units"))] + cr.bbox = bbox + case "area": + if err := edrCoords(ctx, query, "POLYGON", coords); err != nil { + return nil, err + } + cr.region = "transform(ST_GeomFromText($2, 4326), SRID(r))" + case "corridor", "radius": + want, dist, units, required := "LINESTRING", "corridor-width", "width-units", + []string{"corridor-width", "width-units", "corridor-height", "height-units"} + if query == "radius" { + want, dist, units, required = "POINT", "within", "within-units", []string{"within", "within-units"} + } + if err := edrCoords(ctx, query, want, coords); err != nil { + return nil, err + } + for _, p := range required { + if first(q, p) == "" { + return nil, statusErr{400, "the " + query + " query needs " + p} + } + } + d, err := strconv.ParseFloat(first(q, dist), 64) + if err != nil || d <= 0 { + return nil, statusErr{400, dist + " is a positive number"} + } + perUnit, ok := edrWidthUnits[strings.ToLower(first(q, units))] if !ok { - return nil, statusErr{400, "width-units is one of km, m"} + return nil, statusErr{400, units + " is one of " + strings.Join(edrDistanceUnits, ", ")} } // The buffer is taken on the sphere, in metres, then read in the // rasters' system - region = "transform(CAST(ST_Buffer(CAST(ST_Force2D(ST_GeomFromText($2, 4326)) AS geography), " + - strconv.FormatFloat(width*perUnit, 'g', -1, 64) + ") AS geometry), SRID(r))" + cr.region = "transform(CAST(ST_Buffer(CAST(ST_Force2D(ST_GeomFromText($2, 4326)) AS geography), " + + strconv.FormatFloat(d*perUnit, 'g', -1, 64) + ") AS geometry), SRID(r))" } bands, err := edrBands(q) if err != nil { @@ -282,8 +332,8 @@ func edrClip(ctx context.Context, src coverageSource, query, coords string, if err != nil { return nil, err } - data, _, _, err := coverageData(ctx, src, period, coverageRequest{ - region: region, regionArg: coords, bands: bands, writer: "asCoverageJSON"}) + cr.bands = bands + data, _, _, err := coverageData(ctx, src, period, cr) return data, err } @@ -292,12 +342,26 @@ func edrClip(ctx context.Context, src coverageSource, query, coords string, func edrPaths() map[string]any { out := map[string]any{} for _, q := range edrQueries { + reads := "coords a WKT " + q.geometry + if q.geometry == "" { + reads = "bbox minLon,minLat,maxLon,maxLat in CRS84 and z" + } out["/collections/{cid}/"+q.name] = map[string]any{"get": map[string]any{"summary": fmt.Sprintf( - "OGC API - EDR: the %s query over a raster collection, coords a WKT %s, answered in CoverageJSON", - q.name, q.geometry), + "OGC API - EDR: the %s query over a raster collection, %s, answered in CoverageJSON", + q.name, reads), // Every operation of an OpenAPI 3.0 document states its responses, as // the operations #apiDoc writes do. "responses": map[string]any{"200": map[string]any{"description": "OK"}}}} + out["/collections/{cid}/instances/{iid}/"+q.name] = map[string]any{"get": map[string]any{ + "summary": fmt.Sprintf("OGC API - EDR: the %s query over one period of a raster collection, "+ + "%s, answered in CoverageJSON", q.name, reads), + "responses": map[string]any{"200": map[string]any{"description": "OK"}}}} } + out["/collections/{cid}/instances"] = map[string]any{"get": map[string]any{ + "summary": "OGC API - EDR: the instances of a raster collection, one per period", + "responses": map[string]any{"200": map[string]any{"description": "OK"}}}} + out["/collections/{cid}/instances/{iid}"] = map[string]any{"get": map[string]any{ + "summary": "OGC API - EDR: one instance of a raster collection, a period, described as a collection", + "responses": map[string]any{"200": map[string]any{"description": "OK"}}}} return out } diff --git a/edr_live_test.go b/edr_live_test.go index c91b4b9..0acc4f1 100644 --- a/edr_live_test.go +++ b/edr_live_test.go @@ -58,10 +58,13 @@ func TestLiveRasterEDRQueries(t *testing.T) { t.Fatalf("registering the series answered %d: %s", rec.Code, rec.Body.String()) } - // The description states the four queries, the corridor with its units. + // The description states the six queries, the corridor and the radius with + // their units, and the distance units /req/edr/rc-collection-info I + // requires of a description linking a radius. rec := atsDo(t, mux, "GET", "/collections/cov", "") var col struct { - DataQueries map[string]struct { + DistanceUnits []string `json:"distanceunits"` + DataQueries map[string]struct { Link struct { Href, Rel string Variables map[string]any @@ -71,7 +74,7 @@ func TestLiveRasterEDRQueries(t *testing.T) { if err := json.Unmarshal(rec.Body.Bytes(), &col); err != nil { t.Fatal(err) } - for _, q := range []string{"position", "area", "trajectory", "corridor"} { + for _, q := range []string{"position", "radius", "area", "cube", "trajectory", "corridor"} { l := col.DataQueries[q].Link if l.Rel != "data" || l.Href != "/collections/cov/"+q || l.Variables["query_type"] != q { t.Errorf("data_queries.%s is %+v", q, l) @@ -80,6 +83,10 @@ func TestLiveRasterEDRQueries(t *testing.T) { if col.DataQueries["corridor"].Link.Variables["width_units"] == nil { t.Errorf("the corridor states no width_units: %+v", col.DataQueries["corridor"]) } + if col.DataQueries["radius"].Link.Variables["within_units"] == nil || len(col.DistanceUnits) == 0 { + t.Errorf("the radius states no within_units or the description no distanceunits: %+v %v", + col.DataQueries["radius"], col.DistanceUnits) + } type want struct { domain string @@ -107,6 +114,15 @@ func TestLiveRasterEDRQueries(t *testing.T) { // one-degree pixels, whose centres clip keeps {"/collections/cov/corridor?coords=LINESTRING(0.5%201,1.5%201)&corridor-width=200&width-units=km" + "&corridor-height=1&height-units=m&datetime=2024-02-15T00:00:00Z", want{"Grid", 2, 5, 5}}, + // A 40 km radius about the centre of the second tile's first pixel in + // January, a circle inside that one-degree pixel, keeps that pixel's + // value alone, on a grid of two pixels each way: the mask rounds the + // extent of the circle outward to whole pixels, as ST_Clip's does + {"/collections/cov/radius?coords=POINT(2.5%201.5)&within=40&within-units=km" + + "&datetime=2024-01-15T00:00:00Z", want{"Grid", 2, 2, 2}}, + // The cube of the second tile in January, z read and not applied. + {"/collections/cov/cube?bbox=2,0,4,2&z=0/100&datetime=2024-01-15T00:00:00Z", + want{"Grid", 2, 2, 2}}, } { rec := coverageGet(t, c.path, "") if rec.Code != 200 || rec.Header().Get("Content-Type") != mediaCovJSON { @@ -130,6 +146,13 @@ func TestLiveRasterEDRQueries(t *testing.T) { "/collections/cov/corridor?coords=LINESTRING(0.5%201,1.5%201)&corridor-width=1&width-units=mi" + "&corridor-height=1&height-units=m", "/collections/cov/position?coords=nonsense", + "/collections/cov/radius?coords=POINT(2.5%201.5)&within-units=km", + "/collections/cov/radius?coords=POINT(2.5%201.5)&within=60", + "/collections/cov/radius?coords=POINT(2.5%201.5)&within=60&within-units=mi", + "/collections/cov/radius?coords=LINESTRING(0.5%201,1.5%201)&within=60&within-units=km", + "/collections/cov/cube?bbox=2,0,4,2", + "/collections/cov/cube?z=0/100", + "/collections/cov/cube?bbox=2,0,4&z=0/100", } { if rec := coverageGet(t, path, ""); rec.Code != 400 { t.Errorf("%s answered %d, want 400: %s", path, rec.Code, rec.Body.String()) @@ -139,4 +162,99 @@ func TestLiveRasterEDRQueries(t *testing.T) { if !strings.Contains(rec.Body.String(), edrConformance) { t.Errorf("the conformance declaration does not name %s", edrConformance) } + + // The instances are the two periods, January and February, in time order, + // each described as a collection is, with the extent of its period alone + // and its data links under its own path; the description /instances/{iid} + // writes is the one /instances lists. + rec = atsDo(t, mux, "GET", "/collections/cov/instances", "") + var insts struct { + Links []struct{ Rel, Href, Type string } + Instances []struct { + ID string + Links []struct{ Rel, Href, Type string } + Extent struct { + Spatial struct{ Bbox [][]float64 } + Temporal struct{ Interval [][]string } + } + } + } + if err := json.Unmarshal(rec.Body.Bytes(), &insts); err != nil || rec.Code != 200 { + t.Fatalf("listing the instances answered %d: %s", rec.Code, rec.Body.String()) + } + if len(insts.Instances) != 2 || !strings.HasPrefix(insts.Instances[0].ID, "2024-01-01") || + !strings.HasPrefix(insts.Instances[1].ID, "2024-02-01") { + t.Fatalf("the instances are %+v, want January and February", insts.Instances) + } + jan, feb := insts.Instances[0], insts.Instances[1] + if b := jan.Extent.Spatial.Bbox; len(b) != 1 || b[0][2] != 4 { + t.Errorf("January's extent is %v, want its two tiles, to x 4", b) + } + if b := feb.Extent.Spatial.Bbox; len(b) != 1 || b[0][2] != 2 { + t.Errorf("February's extent is %v, want its one tile, to x 2", b) + } + if iv := feb.Extent.Temporal.Interval; len(iv) != 1 || !strings.HasPrefix(iv[0][0], "2024-02-01") || + !strings.HasPrefix(iv[0][1], "2024-03-01") { + t.Errorf("February's interval is %v", iv) + } + febPath := "/collections/cov/instances/" + feb.ID + data := 0 + for _, l := range feb.Links { + if l.Rel == "data" && strings.HasPrefix(l.Href, febPath+"/") { + data++ + } + } + if data != len(edrQueries) { + t.Errorf("February's links hold %d data links under %s, want %d: %+v", data, febPath, + len(edrQueries), feb.Links) + } + var one, listed map[string]any + rec = atsDo(t, mux, "GET", febPath, "") + if err := json.Unmarshal(rec.Body.Bytes(), &one); err != nil || rec.Code != 200 { + t.Fatalf("describing %s answered %d: %s", febPath, rec.Code, rec.Body.String()) + } + var all struct{ Instances []map[string]any } + json.Unmarshal(atsDo(t, mux, "GET", "/collections/cov/instances", "").Body.Bytes(), &all) + listed = all.Instances[1] + for _, k := range []string{"id", "title", "extent", "links", "data_queries"} { + a, _ := json.Marshal(one[k]) + b, _ := json.Marshal(listed[k]) + if string(a) != string(b) { + t.Errorf("%s states %s as %s, /instances as %s", febPath, k, a, b) + } + } + + // A query under an instance reads its period alone: a position with no + // datetime reads January's value under January and February's under + // February, and an area with no datetime clips January's raster under + // January where the collection's own area reads the period that ends last. + for _, c := range []struct { + path string + first float64 + }{ + {"/collections/cov/instances/" + jan.ID + "/position?coords=POINT(0.5%201)", 1}, + {febPath + "/position?coords=POINT(0.5%201)", 5}, + {"/collections/cov/instances/" + jan.ID + "/area?coords=POLYGON((0%200,2%200,2%202,0%202,0%200))", 1}, + {"/collections/cov/area?coords=POLYGON((0%200,2%200,2%202,0%202,0%200))", 5}, + } { + rec := coverageGet(t, strings.ReplaceAll(c.path, "+", "%2B"), "") + if rec.Code != 200 { + t.Errorf("%s answered %d: %s", c.path, rec.Code, rec.Body.String()) + continue + } + if _, _, values := edrCoverage(t, rec.Body.String()); len(values) == 0 || values[0] != c.first { + t.Errorf("%s reads %v, want %v first", c.path, values, c.first) + } + } + for path, want := range map[string]int{ + "/collections/cov/instances/2023-01-01T00:00:00Z": 404, + "/collections/cov/instances/2023-01-01T00:00:00Z/position?coords=POINT(0.5%201)": 404, + // A datetime outside the instance's period meets no period of it + febPath + "/area?coords=POLYGON((0%200,2%200,2%202,0%202,0%200))&datetime=2024-01-15T00:00:00Z": 404, + "/collections/nocov/instances": 404, + } { + if rec := coverageGet(t, strings.ReplaceAll(path, "+", "%2B"), ""); rec.Code != want { + t.Errorf("%s answered %d, want %d: %s", path, rec.Code, want, rec.Body.String()) + } + } } diff --git a/main.go b/main.go index 44a67d7..6ffd4dc 100644 --- a/main.go +++ b/main.go @@ -261,10 +261,17 @@ func routeTable() []route { {"GET", "/collections/{cid}/items/{fid}/tgsequence/queries/{qid}/stream", streamQuery, extension}, {"DELETE", "/collections/{cid}/items/{fid}/tgsequence/queries/{qid}", deleteQuery, extension}, } - // OGC API - EDR: the queries of a raster collection. + // OGC API - EDR: the queries of a raster collection, its instances, one per + // period, and the queries of each instance. for _, q := range edrQueries { rs = append(rs, route{"GET", "/collections/{cid}/" + q.name, edrQuery(q.name), edrConformance}) } + rs = append(rs, route{"GET", "/collections/{cid}/instances", listInstances, edrConformance}, + route{"GET", "/collections/{cid}/instances/{iid}", getInstance, edrConformance}) + for _, q := range edrQueries { + rs = append(rs, route{"GET", "/collections/{cid}/instances/{iid}/" + q.name, edrQuery(q.name), + edrConformance}) + } return rs } @@ -443,7 +450,7 @@ func listCollections(w http.ResponseWriter, r *http.Request) { if !ok { continue } - col, err := coverageDescription(r.Context(), id, src) + col, err := coverageDescription(r.Context(), id, src, nil) if err != nil { httpErr(w, errStatus(err, 500), err.Error()) return diff --git a/samples/api-definition.json b/samples/api-definition.json index 334f299..6b5c448 100644 --- a/samples/api-definition.json +++ b/samples/api-definition.json @@ -137,6 +137,17 @@ "x-conformance-class": "https://www.opengis.net/spec/ogcapi-coverages-1/1.0/conf/core" } }, + "/collections/{cid}/cube": { + "get": { + "responses": { + "200": { + "description": "OK" + } + }, + "summary": "OGC API - EDR: the cube query over a raster collection, bbox minLon,minLat,maxLon,maxLat in CRS84 and z, answered in CoverageJSON", + "x-conformance-class": "http://www.opengis.net/spec/ogcapi-edr-1/1.1/conf/core" + } + }, "/collections/{cid}/export": { "get": { "responses": { @@ -148,6 +159,94 @@ "x-mobilityapi-extension": true } }, + "/collections/{cid}/instances": { + "get": { + "responses": { + "200": { + "description": "OK" + } + }, + "summary": "OGC API - EDR: the instances of a raster collection, one per period", + "x-conformance-class": "http://www.opengis.net/spec/ogcapi-edr-1/1.1/conf/core" + } + }, + "/collections/{cid}/instances/{iid}": { + "get": { + "responses": { + "200": { + "description": "OK" + } + }, + "summary": "OGC API - EDR: one instance of a raster collection, a period, described as a collection", + "x-conformance-class": "http://www.opengis.net/spec/ogcapi-edr-1/1.1/conf/core" + } + }, + "/collections/{cid}/instances/{iid}/area": { + "get": { + "responses": { + "200": { + "description": "OK" + } + }, + "summary": "OGC API - EDR: the area query over one period of a raster collection, coords a WKT POLYGON, answered in CoverageJSON", + "x-conformance-class": "http://www.opengis.net/spec/ogcapi-edr-1/1.1/conf/core" + } + }, + "/collections/{cid}/instances/{iid}/corridor": { + "get": { + "responses": { + "200": { + "description": "OK" + } + }, + "summary": "OGC API - EDR: the corridor query over one period of a raster collection, coords a WKT LINESTRING, answered in CoverageJSON", + "x-conformance-class": "http://www.opengis.net/spec/ogcapi-edr-1/1.1/conf/core" + } + }, + "/collections/{cid}/instances/{iid}/cube": { + "get": { + "responses": { + "200": { + "description": "OK" + } + }, + "summary": "OGC API - EDR: the cube query over one period of a raster collection, bbox minLon,minLat,maxLon,maxLat in CRS84 and z, answered in CoverageJSON", + "x-conformance-class": "http://www.opengis.net/spec/ogcapi-edr-1/1.1/conf/core" + } + }, + "/collections/{cid}/instances/{iid}/position": { + "get": { + "responses": { + "200": { + "description": "OK" + } + }, + "summary": "OGC API - EDR: the position query over one period of a raster collection, coords a WKT POINT, answered in CoverageJSON", + "x-conformance-class": "http://www.opengis.net/spec/ogcapi-edr-1/1.1/conf/core" + } + }, + "/collections/{cid}/instances/{iid}/radius": { + "get": { + "responses": { + "200": { + "description": "OK" + } + }, + "summary": "OGC API - EDR: the radius query over one period of a raster collection, coords a WKT POINT, answered in CoverageJSON", + "x-conformance-class": "http://www.opengis.net/spec/ogcapi-edr-1/1.1/conf/core" + } + }, + "/collections/{cid}/instances/{iid}/trajectory": { + "get": { + "responses": { + "200": { + "description": "OK" + } + }, + "summary": "OGC API - EDR: the trajectory query over one period of a raster collection, coords a WKT LINESTRING, answered in CoverageJSON", + "x-conformance-class": "http://www.opengis.net/spec/ogcapi-edr-1/1.1/conf/core" + } + }, "/collections/{cid}/items": { "get": { "parameters": [ @@ -615,6 +714,17 @@ "x-conformance-class": "http://www.opengis.net/spec/ogcapi-edr-1/1.1/conf/core" } }, + "/collections/{cid}/radius": { + "get": { + "responses": { + "200": { + "description": "OK" + } + }, + "summary": "OGC API - EDR: the radius query over a raster collection, coords a WKT POINT, answered in CoverageJSON", + "x-conformance-class": "http://www.opengis.net/spec/ogcapi-edr-1/1.1/conf/core" + } + }, "/collections/{cid}/schema": { "get": { "responses": {