Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion api/surface.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,13 @@
"method": "GET",
"path": "/collections",
"conformanceClass": "http://www.opengis.net/spec/ogcapi-movingfeatures-1/1.0/conf/mf-collection",
"functions": []
"functions": [
"bandPixelType",
"extent",
"numBands",
"stbox",
"transform"
]
},
{
"method": "POST",
Expand All @@ -36,7 +42,9 @@
"path": "/collections/{cid}",
"conformanceClass": "http://www.opengis.net/spec/ogcapi-movingfeatures-1/1.0/conf/mf-collection",
"functions": [
"bandPixelType",
"extent",
"numBands",
"stbox",
"transform"
]
Expand Down
117 changes: 87 additions & 30 deletions coverage.go
Original file line number Diff line number Diff line change
Expand Up @@ -192,34 +192,75 @@ func ensureRegistry(ctx context.Context, tx Tx) error {
}

// coverageLinks are the links of a raster collection in /collections and in
// its own description.
// its own description, each with the rel and type
// /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 {
return []map[string]string{
{"rel": "self", "href": "/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},
}
for _, q := range edrQueries {
links = append(links, map[string]string{"rel": "data", "href": "/collections/" + cid + "/" + q.name,
"type": mediaCovJSON, "title": q.name})
}
return links
}

// coverageCollection writes the description of a raster collection: its links
// and its extent, the bounds of its rasters in CRS84 and the span of its
// periods.
// 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)
if err != nil {
httpErr(w, errStatus(err, 500), err.Error())
return
}
writeJSON(w, 200, col)
}

// 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
// (the bounds of its rasters in CRS84 and the span of its periods), the EDR
// 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) {
var title, desc string
var srid int
if err := db.QueryRow(r.Context(), `SELECT title,description,crs FROM collections WHERE id=$1`, cid).
if err := db.QueryRow(ctx, `SELECT title,description,crs FROM collections WHERE id=$1`, cid).
Scan(&title, &desc, &srid); err != nil {
httpErr(w, 404, "collection not found")
return
return nil, statusErr{404, "collection not found"}
}
bands, err := coverageBands(ctx, cid, src)
if err != nil {
return nil, err
}
params := map[string]any{}
for i, ptype := range bands {
key, label := "band"+itoa(i+1), "Band "+itoa(i+1)
dataType := "integer"
if jsonPixelType(ptype) == "number" {
dataType = "float"
}
params[key] = map[string]any{
"type": "Parameter", "id": key, "label": label, "data-type": dataType,
"observedProperty": map[string]any{"label": map[string]string{"en": label}},
}
}
col := map[string]any{
"id": cid, "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),
// The EDR queries the collection answers
"data_queries": edrDataQueries(cid),
"data_queries": edrDataQueries(cid),
"output_formats": []string{edrFormat},
"parameter_names": params,
}
if srid != 4326 {
col["storageCrs"] = "http://www.opengis.net/def/crs/EPSG/0/" + itoa(srid)
Expand All @@ -230,7 +271,7 @@ func coverageCollection(w http.ResponseWriter, r *http.Request, cid string, src
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(r.Context(), sql).Scan(&xmin, &ymin, &xmax, &ymax, &tmin, &tmax); err == nil &&
if err := db.QueryRow(ctx, sql).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}},
Expand All @@ -240,7 +281,7 @@ func coverageCollection(w http.ResponseWriter, r *http.Request, cid string, src
}
}
}
writeJSON(w, 200, col)
return col, nil
}

// coverageSchema writes the fields of a raster collection, its bands, as
Expand All @@ -254,16 +295,41 @@ func coverageSchema(w http.ResponseWriter, r *http.Request) {
httpErr(w, 404, "no raster collection "+cid)
return
}
bands, err := coverageBands(r.Context(), cid, src)
if err != nil {
httpErr(w, errStatus(err, 500), err.Error())
return
}
props := map[string]any{}
seq := make([]string, 0, len(bands))
for i, ptype := range bands {
b := i + 1
key := "band" + itoa(b)
props[key] = map[string]any{"title": "Band " + itoa(b), "type": jsonPixelType(ptype),
"x-ogc-pixelType": ptype}
seq = append(seq, key)
}
w.Header().Set("Content-Type", mediaSchema)
w.WriteHeader(200)
json.NewEncoder(w).Encode(map[string]any{
"$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object",
"title": cid, "properties": props, "x-ogc-propertySeq": seq,
})
}

// coverageBands answers the pixel type of each band of a raster collection, in
// band order, read by numBands and bandPixelType from a raster of the period
// that ends last, the raster #coverageSchema and #coverageDescription both
// describe.
func coverageBands(ctx context.Context, cid string, src coverageSource) ([]string, error) {
nbands := 1
if rasterHas(src.Type, "numBands") {
if err := db.QueryRow(r.Context(), "SELECT numBands("+ident(src.Raster)+") FROM "+
if err := db.QueryRow(ctx, "SELECT numBands("+ident(src.Raster)+") FROM "+
ident(src.Table)+" ORDER BY "+ident(src.Time)+" DESC LIMIT 1").Scan(&nbands); err != nil {
httpErr(w, 404, "the raster collection "+cid+" holds no raster")
return
return nil, statusErr{404, "the raster collection " + cid + " holds no raster"}
}
}
props := map[string]any{}
seq := make([]string, 0, nbands)
out := make([]string, 0, nbands)
for b := 1; b <= nbands; b++ {
var ptype string
sql := "SELECT bandPixelType(" + ident(src.Raster) + ", " + itoa(b) + ") FROM " +
Expand All @@ -272,21 +338,12 @@ func coverageSchema(w http.ResponseWriter, r *http.Request) {
sql = "SELECT bandPixelType(" + ident(src.Raster) + ") FROM " + ident(src.Table) +
" ORDER BY " + ident(src.Time) + " DESC LIMIT 1"
}
if err := db.QueryRow(r.Context(), sql).Scan(&ptype); err != nil {
httpErr(w, 500, err.Error())
return
if err := db.QueryRow(ctx, sql).Scan(&ptype); err != nil {
return nil, err
}
key := "band" + itoa(b)
props[key] = map[string]any{"title": "Band " + itoa(b), "type": jsonPixelType(ptype),
"x-ogc-pixelType": ptype}
seq = append(seq, key)
out = append(out, ptype)
}
w.Header().Set("Content-Type", mediaSchema)
w.WriteHeader(200)
json.NewEncoder(w).Encode(map[string]any{
"$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object",
"title": cid, "properties": props, "x-ogc-propertySeq": seq,
})
return out, nil
}

// jsonPixelType answers the JSON Schema type of a pixel type, an integer for
Expand Down
71 changes: 71 additions & 0 deletions coverage_live_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,77 @@ func TestLiveRasterCollection(t *testing.T) {
t.Errorf("the temporal extent is %v, want 2024-01-01 to 2024-03-01", iv)
}

// The description carries what /req/edr/rc-collection-info and
// collection.yaml of EDR 1.1 require: every link with its rel and type, a
// data link per query, the output formats, and the band as a Parameter
// keyed as parameter-name reads it. enc compares decoded members as their
// JSON encodings.
enc := func(v any) string { b, _ := json.Marshal(v); return string(b) }
var edr struct {
Links []struct {
Rel, Href, Type string
}
OutputFormats []string `json:"output_formats"`
Keywords []string `json:"keywords"`
ParameterNames map[string]map[string]any `json:"parameter_names"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &edr); err != nil {
t.Fatalf("reading the description: %v", err)
}
data := map[string]bool{}
for _, l := range edr.Links {
if l.Type == "" {
t.Errorf("the link %s %s has no type", l.Rel, l.Href)
}
if l.Rel == "data" && l.Type == mediaCovJSON {
data[l.Href] = true
}
}
for _, q := range edrQueries {
if !data["/collections/cov/"+q.name] {
t.Errorf("the description has no data link to the %s query: %+v", q.name, edr.Links)
}
}
if len(edr.OutputFormats) != 1 || edr.OutputFormats[0] != edrFormat {
t.Errorf("output_formats is %v, want [%s]", edr.OutputFormats, edrFormat)
}
if len(edr.Keywords) == 0 {
t.Errorf("the description has no keywords")
}
if p := edr.ParameterNames["band1"]; len(edr.ParameterNames) != 1 || p["type"] != "Parameter" ||
p["id"] != "band1" || p["data-type"] != "integer" ||
!strings.Contains(enc(p["observedProperty"]), `"label":{"en":"Band 1"}`) {
t.Errorf("parameter_names is %v, want band1 an integer Parameter labelled Band 1", edr.ParameterNames)
}

// /collections lists the collection with the id, title, description and
// extent of its own description, as /req/collections/src-md-success C
// requires.
rec = atsDo(t, mux, "GET", "/collections", "")
var list struct{ Collections []map[string]any }
if err := json.Unmarshal(rec.Body.Bytes(), &list); err != nil || rec.Code != 200 {
t.Fatalf("listing the collections answered %d: %s", rec.Code, rec.Body.String())
}
var own map[string]any
if err := json.Unmarshal(atsDo(t, mux, "GET", "/collections/cov", "").Body.Bytes(), &own); err != nil {
t.Fatalf("reading the description: %v", err)
}
found := false
for _, c := range list.Collections {
if c["id"] != "cov" {
continue
}
found = true
for _, k := range []string{"id", "title", "description", "extent", "parameter_names", "output_formats"} {
if enc(c[k]) != enc(own[k]) {
t.Errorf("/collections states %s as %s, /collections/cov as %s", k, enc(c[k]), enc(own[k]))
}
}
}
if !found {
t.Errorf("/collections does not list cov: %s", rec.Body.String())
}

// The schema lists the one band.
rec = coverageGet(t, "/collections/cov/schema", "")
if rec.Code != 200 || !strings.Contains(rec.Body.String(), `"band1"`) ||
Expand Down
22 changes: 19 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -425,15 +425,31 @@ func listCollections(w http.ResponseWriter, r *http.Request) {
{"rel": "items", "href": "/collections/" + id + "/items"},
{"rel": "enclosure", "href": "/collections/" + id + "/export", "type": "application/x-ndjson"},
}
if itemType != nil && *itemType == coverageItems {
links = coverageLinks(id)
}
cols = append(cols, map[string]any{
"id": id, "title": title, "description": desc, "itemType": itemType,
"crs": []string{"http://www.opengis.net/def/crs/EPSG/0/" + itoa(crs)},
"links": links,
})
}
rows.Close()
// A raster collection is listed with the description #coverageDescription
// answers for /collections/{cid}, read once the registry's rows are closed.
for i, c := range cols {
if it, _ := c["itemType"].(*string); it == nil || *it != coverageItems {
continue
}
id := c["id"].(string)
src, ok := coverageMeta(r.Context(), id)
if !ok {
continue
}
col, err := coverageDescription(r.Context(), id, src)
if err != nil {
httpErr(w, errStatus(err, 500), err.Error())
return
}
cols[i] = col
}
writeJSON(w, 200, map[string]any{
"collections": cols,
"links": []map[string]string{{"rel": "self", "href": "/collections"}},
Expand Down