-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
1685 lines (1626 loc) · 59.4 KB
/
Copy pathmain.go
File metadata and controls
1685 lines (1626 loc) · 59.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// MobilityAPI-go — a thin, compiled OGC API – Moving Features tier over
// MobilityDB, built for very large databases and the lakehouse direction:
// - streaming responses (the FeatureCollection is written row-by-row from a
// server-side cursor, so memory is bounded regardless of result size);
// - keyset pagination (WHERE id > :after) with OGC next links — no OFFSET;
// - index-using spatial/temporal filters (bbox, datetime) pushed to the
// MobilityDB GiST index via the && operator;
// - a streaming NDJSON bulk-export endpoint the lake (DuckDB / MobilityDuck /
// Spark) can ingest directly.
//
// All temporal work and (de)serialization run in MobilityDB (asMFJSON,
// atTime, tgeompointFromMFJSON); the tier holds no MEOS (no cgo, no PyMEOS).
package main
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"net/url"
"os"
"os/signal"
"regexp"
"strconv"
"strings"
"syscall"
"time"
"github.com/parquet-go/parquet-go"
)
var (
db Backend
defaultLimit = envInt("MFAPI_DEFAULT_LIMIT", 100)
maxLimit = envInt("MFAPI_MAX_LIMIT", 10000)
exportBatch = envInt("MFAPI_EXPORT_LIMIT", 0) // 0 = unbounded stream
parquetRG = envInt("MFAPI_PARQUET_ROWGROUP", 1024) // rows per Parquet row group (bounds export memory)
)
// OGC <-> MobilityDB conventions (assessed against live MobilityDB):
// MobilityDB rejects "Stepwise" and uses "Step"; crs is "EPSG:<n>" vs the URN.
var ogc2mdbInterp = map[string]string{"Linear": "Linear", "Stepwise": "Step", "Discrete": "Discrete"}
var epsgName = regexp.MustCompile(`"name":\s*"EPSG:(\d+)"`)
var epsgURN = regexp.MustCompile(`EPSG:+(\d+)`)
// hourOnlyOffset matches PostgreSQL's hour-only timezone offset on an ISO
// timestamp ("…18:57:52+00"); RFC 3339 — and strict parsers such as JS Date —
// require the ":00" minutes.
var hourOnlyOffset = regexp.MustCompile(`(\d\d:\d\d:\d\d(?:\.\d+)?)([+-]\d\d)(["\s]|$)`)
// rfc3339Tz completes hour-only timezone offsets so datetimes are RFC 3339.
func rfc3339Tz(s string) string { return hourOnlyOffset.ReplaceAllString(s, `$1$2:00$3`) }
func ogcify(s string) string {
s = strings.ReplaceAll(s, `"interpolation": "Step"`, `"interpolation": "Stepwise"`)
s = strings.ReplaceAll(s, `"interpolation":"Step"`, `"interpolation":"Stepwise"`)
s = rfc3339Tz(s)
return epsgName.ReplaceAllString(s, `"name":"urn:ogc:def:crs:EPSG::$1"`)
}
func envInt(k string, def int) int {
if v := os.Getenv(k); v != "" {
if n, e := strconv.Atoi(v); e == nil {
return n
}
}
return def
}
func main() {
dsn := os.Getenv("MFAPI_DSN")
if dsn == "" {
dsn = "postgres:///mfapi_demo?host=/tmp&port=5432&user=esteban"
}
var err error
db, err = openBackend(dsn)
if err != nil {
log.Fatal(err)
}
defer db.Close()
if err := db.Ping(context.Background()); err != nil {
log.Fatal("db ping: ", err)
}
if broker := os.Getenv("MFAPI_MQTT_BROKER"); broker != "" {
if _, err := startMQTTIngest(broker, "mfapi-"+strconv.Itoa(os.Getpid())); err != nil {
log.Printf("MQTT ingestion disabled: %v", err)
} else {
log.Printf("MQTT ingestion on %s (topic mfapi/<cid>/<fid>/<pname>)", broker)
}
}
mux := http.NewServeMux()
mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) { writeRaw(w, 200, `{"status":"ok"}`) })
mux.HandleFunc("GET /", landing)
mux.HandleFunc("GET /api", apiDoc)
mux.HandleFunc("GET /conformance", conformance)
mux.HandleFunc("GET /collections", listCollections)
mux.HandleFunc("POST /collections", postCollection)
mux.HandleFunc("GET /collections/{cid}", getCollection)
mux.HandleFunc("PUT /collections/{cid}", putCollection)
mux.HandleFunc("DELETE /collections/{cid}", deleteCollection)
mux.HandleFunc("GET /collections/{cid}/trajectories", trajectories)
mux.HandleFunc("GET /collections/{cid}/timeseries", timeseries)
mux.HandleFunc("GET /collections/{cid}/items", streamItems)
mux.HandleFunc("GET /collections/{cid}/items/{fid}", getItem)
mux.HandleFunc("POST /collections/{cid}/items", postItem)
mux.HandleFunc("GET /collections/{cid}/export", export) // lakehouse bulk feed (NDJSON | Parquet)
// extension (not in conformsTo): bulk ingest of a real-time fleet feed
mux.HandleFunc("POST /collections/{cid}/bulk", bulkIngest)
// OGC API – Moving Features sub-resources of a moving feature:
mux.HandleFunc("GET /collections/{cid}/items/{fid}/tgsequence", tgSequence)
mux.HandleFunc("GET /collections/{cid}/items/{fid}/tgsequence/{tgid}/{qtype}", tgSequenceQuery)
mux.HandleFunc("GET /collections/{cid}/items/{fid}/tproperties", listTProperties)
mux.HandleFunc("GET /collections/{cid}/items/{fid}/tproperties/{pname}", getTProperty)
// writes: replace / delete a feature, append a temporally-disjoint sub-trajectory
mux.HandleFunc("PUT /collections/{cid}/items/{fid}", putItem)
mux.HandleFunc("DELETE /collections/{cid}/items/{fid}", deleteItem)
mux.HandleFunc("POST /collections/{cid}/items/{fid}/tgsequence", postTgSequence)
// temporal properties are user-supplied, stored, time-varying attributes
mux.HandleFunc("POST /collections/{cid}/items/{fid}/tproperties", postTProperties)
mux.HandleFunc("POST /collections/{cid}/items/{fid}/tproperties/{pname}", postTPropertyValues)
mux.HandleFunc("DELETE /collections/{cid}/items/{fid}/tproperties/{pname}", deleteTProperty)
mux.HandleFunc("DELETE /collections/{cid}/items/{fid}/tgsequence/{tgid}", deleteTgSequence)
// MF Part 4 (Stream Extension): continuous queries on a temporal property,
// delivered over Server-Sent Events.
mux.HandleFunc("POST /collections/{cid}/items/{fid}/tproperties/{pname}/queries", postQuery)
mux.HandleFunc("GET /collections/{cid}/items/{fid}/tproperties/{pname}/queries", listQueries)
mux.HandleFunc("GET /collections/{cid}/items/{fid}/tproperties/{pname}/queries/{qid}", getQuery)
mux.HandleFunc("GET /collections/{cid}/items/{fid}/tproperties/{pname}/queries/{qid}/stream", streamQuery)
mux.HandleFunc("DELETE /collections/{cid}/items/{fid}/tproperties/{pname}/queries/{qid}", deleteQuery)
// live ingestion: a producer pushes records that live queries process in real time
mux.HandleFunc("POST /collections/{cid}/items/{fid}/tproperties/{pname}/ingest", ingestProperty)
// MF Part 4: a continuous query that streams the moving feature's position
// (the temporal geometry), the feed for an animated map.
mux.HandleFunc("POST /collections/{cid}/items/{fid}/tgsequence/queries", postGeometryQuery)
mux.HandleFunc("GET /collections/{cid}/items/{fid}/tgsequence/queries", listGeometryQueries)
mux.HandleFunc("GET /collections/{cid}/items/{fid}/tgsequence/queries/{qid}", getQuery)
mux.HandleFunc("GET /collections/{cid}/items/{fid}/tgsequence/queries/{qid}/stream", streamQuery)
mux.HandleFunc("DELETE /collections/{cid}/items/{fid}/tgsequence/queries/{qid}", deleteQuery)
addr := ":" + strconv.Itoa(envInt("MFAPI_PORT", 8088))
srv := &http.Server{Addr: addr, Handler: mux, ReadHeaderTimeout: 10 * time.Second, IdleTimeout: 60 * time.Second}
// streaming/export responses can be long-lived: no WriteTimeout (use ctx).
go func() {
log.Printf("MobilityAPI-go on %s (pool max=%d, default/max limit=%d/%d) — streaming, keyset-paged, lakehouse-ready", addr, envInt("MFAPI_MAXCONNS", 16), defaultLimit, maxLimit)
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatal(err)
}
}()
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
<-sig
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
srv.Shutdown(ctx)
log.Println("shut down")
}
func writeRaw(w http.ResponseWriter, code int, body string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
w.Write([]byte(body))
}
func writeJSON(w http.ResponseWriter, code int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
json.NewEncoder(w).Encode(v)
}
func httpErr(w http.ResponseWriter, code int, desc string) {
writeJSON(w, code, map[string]any{"code": strconv.Itoa(code), "description": desc})
}
// collectionMeta validates the collection id against the registry and returns
// the feature table name and crs (whitelist — no interpolation of user input).
func collectionMeta(ctx context.Context, cid string) (table string, srid int, ok bool) {
err := db.QueryRow(ctx, `SELECT id, crs FROM collections WHERE id=$1`, cid).Scan(&table, &srid)
return table, srid, err == nil
}
// collectionGeneric reports whether a collection's feature table carries a
// generic `properties jsonb` column (collections created through POST
// /collections) rather than the typed ships columns (mmsi, name).
func collectionGeneric(ctx context.Context, table string) bool {
// Portable column probe: selecting the generic `properties` column succeeds
// only when it exists, on PostgreSQL, DuckDB and Spark alike (Spark Connect
// has no information_schema).
rows, err := db.Query(ctx, "SELECT properties FROM "+ident(table)+" LIMIT 0")
if err != nil {
return false
}
rows.Close()
return true
}
// featCols lists the non-geometry feature columns carried through the inner
// selects so the projection can read them.
func featCols(generic bool) string {
if generic {
return "id, properties"
}
return "id, mmsi, name"
}
func ident(s string) string { return `"` + strings.ReplaceAll(s, `"`, `""`) + `"` }
// validID guards identifiers interpolated into CREATE/DROP TABLE (which cannot
// be parameterised): a collection id must be a plain SQL identifier.
var validID = regexp.MustCompile(`^[a-z_][a-z0-9_]*$`)
func landing(w http.ResponseWriter, r *http.Request) {
writeJSON(w, 200, map[string]any{
"title": "MobilityAPI-go", "description": "OGC API – Moving Features over MobilityDB",
"links": []map[string]string{
{"rel": "self", "href": "/", "type": "application/json"},
{"rel": "service-desc", "href": "/api", "type": "application/vnd.oai.openapi+json;version=3.0"},
{"rel": "conformance", "href": "/conformance", "type": "application/json"},
{"rel": "data", "href": "/collections", "type": "application/json"},
}})
}
func conformance(w http.ResponseWriter, r *http.Request) {
writeJSON(w, 200, map[string]any{"conformsTo": []string{
"http://www.opengis.net/spec/ogcapi-movingfeatures-1/1.0/conf/common",
"http://www.opengis.net/spec/ogcapi-movingfeatures-1/1.0/conf/mf-collection",
"http://www.opengis.net/spec/ogcapi-movingfeatures-1/1.0/conf/movingfeatures",
"http://www.opengis.net/spec/ogcapi-movingfeatures-4/1.0/conf/cquery",
"http://www.opengis.net/spec/ogcapi-common-1/1.0/conf/core",
"http://www.opengis.net/spec/ogcapi-common-2/1.0/conf/collections",
}})
}
func listCollections(w http.ResponseWriter, r *http.Request) {
rows, err := db.Query(r.Context(), `SELECT id, title, description, item_type, crs FROM collections ORDER BY id`)
if err != nil {
httpErr(w, 500, err.Error())
return
}
defer rows.Close()
cols := []map[string]any{}
for rows.Next() {
var id string
var title, desc, itemType *string
var crs int
if err := rows.Scan(&id, &title, &desc, &itemType, &crs); err != nil {
httpErr(w, 500, err.Error())
return
}
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": []map[string]string{
{"rel": "self", "href": "/collections/" + id},
{"rel": "items", "href": "/collections/" + id + "/items"},
{"rel": "enclosure", "href": "/collections/" + id + "/export", "type": "application/x-ndjson"},
},
})
}
writeJSON(w, 200, map[string]any{
"collections": cols,
"links": []map[string]string{{"rel": "self", "href": "/collections"}},
})
}
func getCollection(w http.ResponseWriter, r *http.Request) {
cid := r.PathValue("cid")
tbl, srid, ok := collectionMeta(r.Context(), cid)
if !ok {
httpErr(w, 404, "collection not found")
return
}
var title, desc, itemType string
if err := db.QueryRow(r.Context(), `SELECT title,description,item_type FROM collections WHERE id=$1`, cid).
Scan(&title, &desc, &itemType); err != nil {
httpErr(w, 404, "collection not found")
return
}
crsURI := "http://www.opengis.net/def/crs/EPSG/0/" + itoa(srid)
col := map[string]any{
"id": cid, "title": title, "description": desc, "itemType": itemType,
"crs": []string{crsURI},
"links": []map[string]string{
{"rel": "self", "href": "/collections/" + cid},
{"rel": "items", "href": "/collections/" + cid + "/items"},
{"rel": "enclosure", "href": "/collections/" + cid + "/export", "type": "application/x-ndjson"},
},
}
// extent: spatial bbox and temporal interval from the collection's STBOX
var xmin, ymin, xmax, ymax *float64
var tmin, tmax *string
if err := db.QueryRow(r.Context(), "SELECT Xmin(e),Ymin(e),Xmax(e),Ymax(e),CAST(Tmin(e) AS text),CAST(Tmax(e) AS text) "+
"FROM (SELECT extent(trip) e FROM "+ident(tbl)+") s").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}}, "crs": crsURI},
"temporal": map[string]any{"interval": [][]string{{*tmin, *tmax}}, "trs": "http://www.opengis.net/def/uom/ISO-8601/0/Gregorian"},
}
}
writeJSON(w, 200, col)
}
// epsgURI matches the EPSG code in an OGC CRS URI (.../def/crs/EPSG/0/<code>).
var epsgURI = regexp.MustCompile(`EPSG/\d+/(\d+)`)
// crsCode extracts an EPSG code from a collection body's crs field (a URI, a
// URI array, or a bare integer); it defaults to 4326 (CRS84) when absent.
func crsCode(raw json.RawMessage) int {
s := string(raw)
if m := epsgURI.FindStringSubmatch(s); m != nil {
n, _ := strconv.Atoi(m[1])
return n
}
if m := epsgURN.FindStringSubmatch(s); m != nil {
n, _ := strconv.Atoi(m[1])
return n
}
if n, err := strconv.Atoi(strings.Trim(s, " \t\n\"")); err == nil {
return n
}
return 4326
}
// postCollection registers a new collection: it creates the feature table with
// the generic (id, properties, trip) schema and a GiST index, then records the
// collection metadata in the registry the tier reads.
func postCollection(w http.ResponseWriter, r *http.Request) {
var c struct {
ID string `json:"id"`
Title string `json:"title"`
Description string `json:"description"`
ItemType string `json:"itemType"`
CRS json.RawMessage `json:"crs"`
}
if err := json.NewDecoder(r.Body).Decode(&c); err != nil || c.ID == "" {
httpErr(w, 400, "invalid Collection / missing id")
return
}
if !validID.MatchString(c.ID) {
httpErr(w, 400, "collection id must match [a-z_][a-z0-9_]* (a plain SQL identifier)")
return
}
if _, _, exists := collectionMeta(r.Context(), c.ID); exists {
httpErr(w, 409, "collection already exists")
return
}
if c.ItemType == "" {
c.ItemType = "movingfeature"
}
srid := crsCode(c.CRS)
tx, err := db.Begin(r.Context())
if err != nil {
httpErr(w, 500, err.Error())
return
}
defer tx.Rollback(r.Context())
if _, err := tx.Exec(r.Context(),
`CREATE TABLE IF NOT EXISTS collections (id text PRIMARY KEY, title text,
description text, item_type text, crs integer)`); err != nil {
httpErr(w, 500, err.Error())
return
}
if _, err := tx.Exec(r.Context(),
"CREATE TABLE "+ident(c.ID)+" (id integer PRIMARY KEY, properties jsonb, trip tgeompoint)"); err != nil {
httpErr(w, 400, "create collection failed: "+err.Error())
return
}
if _, err := tx.Exec(r.Context(),
"CREATE INDEX ON "+ident(c.ID)+" USING gist (trip)"); err != nil {
httpErr(w, 500, err.Error())
return
}
if _, err := tx.Exec(r.Context(),
`INSERT INTO collections (id,title,description,item_type,crs) VALUES ($1,$2,$3,$4,$5)`,
c.ID, c.Title, c.Description, c.ItemType, srid); err != nil {
httpErr(w, 400, "register collection failed: "+err.Error())
return
}
if err := tx.Commit(r.Context()); err != nil {
httpErr(w, 500, err.Error())
return
}
w.Header().Set("Location", "/collections/"+c.ID)
writeJSON(w, 201, map[string]any{"message": "created", "id": c.ID})
}
// putCollection replaces a collection's metadata (title, description, crs).
func putCollection(w http.ResponseWriter, r *http.Request) {
cid := r.PathValue("cid")
var c struct {
Title string `json:"title"`
Description string `json:"description"`
CRS json.RawMessage `json:"crs"`
}
if err := json.NewDecoder(r.Body).Decode(&c); err != nil {
httpErr(w, 400, "invalid Collection body")
return
}
ct, err := db.Exec(r.Context(),
`UPDATE collections SET title=$2, description=$3, crs=$4 WHERE id=$1`,
cid, c.Title, c.Description, crsCode(c.CRS))
if err != nil {
httpErr(w, 400, "update failed: "+err.Error())
return
}
if ct == 0 {
httpErr(w, 404, "collection not found")
return
}
writeJSON(w, 200, map[string]any{"message": "replaced", "id": cid})
}
// deleteCollection removes a registered collection: it drops the feature table
// and deletes the registry row in one transaction.
func deleteCollection(w http.ResponseWriter, r *http.Request) {
cid := r.PathValue("cid")
tbl, _, ok := collectionMeta(r.Context(), cid)
if !ok {
httpErr(w, 404, "collection not found")
return
}
tx, err := db.Begin(r.Context())
if err != nil {
httpErr(w, 500, err.Error())
return
}
defer tx.Rollback(r.Context())
if _, err := tx.Exec(r.Context(), "DROP TABLE IF EXISTS "+ident(tbl)); err != nil {
httpErr(w, 500, err.Error())
return
}
if _, err := tx.Exec(r.Context(), "DELETE FROM collections WHERE id=$1", cid); err != nil {
httpErr(w, 500, err.Error())
return
}
if err := tx.Commit(r.Context()); err != nil {
httpErr(w, 500, err.Error())
return
}
purgeTProps(r.Context(), "cid=$1", cid)
w.WriteHeader(204)
}
// itemFilters builds the index-using WHERE clause and the temporalGeometry
// expression (clipped when subTrajectory=true) from the OGC query parameters.
func itemFilters(tbl string, srid int, q map[string][]string) (where string, tgExpr string, args []any, err error) {
conds := []string{}
add := func(c string, a ...any) { conds = append(conds, c); args = append(args, a...) }
// keyset cursor: ?after=<id>
if v := first(q, "after"); v != "" {
id, e := strconv.ParseInt(v, 10, 64)
if e != nil {
return "", "", nil, errors.New("invalid 'after'")
}
add("id > $"+strconv.Itoa(len(args)+1), id)
}
// bbox: minx,miny,maxx,maxy in the collection CRS. The GiST && on the
// inline STBOX prefilters on the index; eintersects then refines to the
// trajectories whose path actually crosses the envelope (exact, not the
// bounding-box superset), so the result is "vessels that cross the box".
if v := first(q, "bbox"); v != "" {
p := strings.Split(v, ",")
if len(p) != 4 {
return "", "", nil, errors.New("bbox must be minx,miny,maxx,maxy")
}
f := make([]any, 4)
for i := range p {
if f[i], err = strconv.ParseFloat(strings.TrimSpace(p[i]), 64); err != nil {
return "", "", nil, errors.New("invalid bbox number")
}
}
n := len(args)
env := "ST_MakeEnvelope($" + itoa(n+1) + ",$" + itoa(n+2) + ",$" + itoa(n+3) + ",$" + itoa(n+4) + ",$" + itoa(n+5) + ")"
add("trip && stbox("+env+") AND eintersects(trip, "+env+")",
f[0], f[1], f[2], f[3], srid)
}
// OGC uses lowercase "subtrajectory"; accept the camelCase form too.
sub := first(q, "subtrajectory")
if sub == "" {
sub = first(q, "subTrajectory")
}
if sub == "true" && first(q, "datetime") == "" {
return "", "", nil, errors.New("subtrajectory requires a bounded datetime interval")
}
// datetime: start/end (RFC3339 interval) -> && on the time dimension
dt := first(q, "datetime")
if dt != "" {
s, e, ok := splitInterval(dt)
if !ok {
return "", "", nil, errors.New("datetime must be start/end (RFC3339)")
}
n := len(args)
span := "CAST($" + itoa(n+1) + " AS tstzspan)"
add("trip && "+span, "["+s+", "+e+"]")
if sub == "true" {
// clip each trajectory to the window; drop rows whose values fall in
// a temporal gap (the time box overlaps but atTime is empty)
tgExpr = "atTime(trip, " + span + ")"
conds = append(conds, "atTime(trip, "+span+") IS NOT NULL")
}
}
if tgExpr == "" {
tgExpr = "trip"
}
if len(conds) > 0 {
where = "WHERE " + strings.Join(conds, " AND ")
}
return where, tgExpr, args, nil
}
// streamItems writes the FeatureCollection incrementally from a server-side
// cursor: bounded memory for any result size; keyset next link for paging.
func streamItems(w http.ResponseWriter, r *http.Request) {
tbl, srid, ok := collectionMeta(r.Context(), r.PathValue("cid"))
if !ok {
httpErr(w, 404, "collection not found")
return
}
q := r.URL.Query()
limit := defaultLimit
if l := q.Get("limit"); l != "" {
if n, e := strconv.Atoi(l); e == nil && n > 0 {
limit = n
}
}
if limit > maxLimit {
limit = maxLimit
}
where, tgExpr, args, ferr := itemFilters(tbl, srid, q)
if ferr != nil {
httpErr(w, 400, ferr.Error())
return
}
args = append(args, limit)
lp := "$" + itoa(len(args))
generic := collectionGeneric(r.Context(), tbl)
fc := featCols(generic)
sql := "SELECT id, " + propSel(generic) + ", Xmin(b),Ymin(b),Xmax(b),Ymax(b),CAST(Tmin(b) AS text),CAST(Tmax(b) AS text), asMFJSON(g) FROM (" +
"SELECT " + fc + ", g, stbox(g) AS b FROM (" +
"SELECT " + fc + ", " + tgExpr + " AS g FROM " + ident(tbl) + " " + where +
" ORDER BY id LIMIT " + lp + ") i) s ORDER BY id"
rows, err := db.Query(r.Context(), sql, args...)
if err != nil {
httpErr(w, 500, err.Error())
return
}
defer rows.Close()
cid := r.PathValue("cid")
w.Header().Set("Content-Type", "application/json")
bw := bufio.NewWriterSize(w, 64*1024)
defer bw.Flush()
bw.WriteString(`{"type":"FeatureCollection","features":[`)
var lastID int64
n := 0
for rows.Next() {
id, props, bx, tmin, tmax, tgeom, serr := scanFeatureRow(rows, generic)
if serr != nil {
break
}
feat, ferr := buildFeature(id, props, srid, bx, tmin, tmax, tgeom, nil, cid)
if ferr != nil {
break
}
if n > 0 {
bw.WriteByte(',')
}
bw.Write(feat)
lastID = id
n++
if n%256 == 0 {
bw.Flush()
}
}
bw.WriteString(`],"numberReturned":` + itoa(n))
if n == limit { // a full page -> there may be more; emit a keyset next link
nq := cloneQuery(q)
nq.Set("after", strconv.FormatInt(lastID, 10))
nq.Set("limit", itoa(limit))
bw.WriteString(`,"links":[{"rel":"next","href":"/collections/` + r.PathValue("cid") + `/items?` + nq.Encode() + `"}]`)
}
bw.WriteString(`}`)
}
func getItem(w http.ResponseWriter, r *http.Request) {
tbl, srid, ok := collectionMeta(r.Context(), r.PathValue("cid"))
if !ok {
httpErr(w, 404, "collection not found")
return
}
fid, err := strconv.Atoi(r.PathValue("fid"))
if err != nil {
httpErr(w, 400, "invalid feature id")
return
}
generic := collectionGeneric(r.Context(), tbl)
fc := featCols(generic)
sql := "SELECT id, " + propSel(generic) + ", Xmin(b),Ymin(b),Xmax(b),Ymax(b),CAST(Tmin(b) AS text),CAST(Tmax(b) AS text), asMFJSON(g), CAST(ST_AsGeoJSON(trajectory(g)) AS text) FROM (" +
"SELECT " + fc + ", g, stbox(g) AS b FROM (" +
"SELECT " + fc + ", trip AS g FROM " + ident(tbl) + " WHERE id=$1) i) s"
var id int64
bx := make([]float64, 4)
var tmin, tmax, tgeom, geom string
var props json.RawMessage
var serr error
if generic {
var pt string
serr = db.QueryRow(r.Context(), sql, fid).Scan(&id, &pt, &bx[0], &bx[1], &bx[2], &bx[3], &tmin, &tmax, &tgeom, &geom)
props = json.RawMessage(pt)
} else {
var mmsi *int64
var name *string
serr = db.QueryRow(r.Context(), sql, fid).Scan(&id, &mmsi, &name, &bx[0], &bx[1], &bx[2], &bx[3], &tmin, &tmax, &tgeom, &geom)
props = typedProps(mmsi, name)
}
if serr != nil {
httpErr(w, 404, "feature not found")
return
}
feat, ferr := buildFeature(id, props, srid, bx, tmin, tmax, []byte(tgeom), []byte(geom), r.PathValue("cid"))
if ferr != nil {
httpErr(w, 500, ferr.Error())
return
}
writeRaw(w, 200, string(feat))
}
// propSpec is a temporal property derived from the trajectory by an exact
// MobilityDB function (no resampling). speed/azimuth are piecewise-constant
// (Step) because the position is linearly interpolated between observations;
// cumulativeLength accumulates per segment (Linear). The handlers report each
// function's true interpolation — they do not coerce it.
type propSpec struct{ expr, uom, desc string }
var tProps = map[string]propSpec{
"velocity": {"speed(trip)", "m/s", "Speed over ground (velocity magnitude), a piecewise-constant function of the trajectory."},
"distance": {"cumulativeLength(trip)", "m", "Cumulative distance travelled along the trajectory."},
}
// tType describes how a scalar temporal property is carried: mf is the
// MobilityDB MF-JSON moving-type token, col its storage column, cast its type,
// ogc the canonical OGC type token, and defInterp the interpolation MobilityDB
// assumes when the body omits one.
type tType struct{ mf, col, cast, ogc, defInterp string }
// tPropType resolves an OGC temporal property type token to the four scalar
// temporal types MobilityDB carries as time-varying attribute values.
func tPropType(t string) (tType, bool) {
switch strings.ToLower(strings.TrimSpace(t)) {
case "", "treal", "tfloat", "measure", "real", "float", "double", "number":
return tType{"MovingFloat", "vfloat", "tfloat", "TReal", "Linear"}, true
case "tint", "tinteger", "integer", "int":
return tType{"MovingInteger", "vint", "tint", "TInt", "Step"}, true
case "ttext", "tstring", "text", "string":
return tType{"MovingText", "vtext", "ttext", "TText", "Discrete"}, true
case "tbool", "tboolean", "boolean", "bool":
return tType{"MovingBoolean", "vbool", "tbool", "TBool", "Step"}, true
}
return tType{}, false
}
// orTrue returns the JSON boolean v, or true when v is absent — MF-JSON sequence
// bounds default to inclusive.
func orTrue(v any) bool {
if b, ok := v.(bool); ok {
return b
}
return true
}
// tPropMFJSON renders a MobilityDB MF-JSON document for one temporal property
// from its OGC body: either a flat {datetimes, values, interpolation} object or
// a valueSequence array (a sequence set when it holds more than one segment).
// The interpolation token is mapped from OGC to MobilityDB and defaults per type.
func tPropMFJSON(mfType, defInterp string, body map[string]any) (string, error) {
mapInterp := func(v any) string {
s, _ := v.(string)
if s == "" {
return defInterp
}
if m, ok := ogc2mdbInterp[s]; ok {
return m
}
return s
}
if vs, ok := body["valueSequence"].([]any); ok && len(vs) > 0 {
if len(vs) == 1 {
seq, _ := vs[0].(map[string]any)
return tPropMFJSON(mfType, defInterp, seq)
}
seqs := make([]any, 0, len(vs))
interp := ""
for _, s := range vs {
m, _ := s.(map[string]any)
if interp == "" {
interp = mapInterp(m["interpolation"])
}
seqs = append(seqs, map[string]any{
"values": m["values"], "datetimes": m["datetimes"],
"lower_inc": orTrue(m["lower_inc"]), "upper_inc": orTrue(m["upper_inc"]),
})
}
b, _ := json.Marshal(map[string]any{"type": mfType, "sequences": seqs, "interpolation": interp})
return string(b), nil
}
if body["datetimes"] == nil || body["values"] == nil {
return "", errors.New("temporal property requires datetimes and values (or a valueSequence)")
}
b, _ := json.Marshal(map[string]any{
"type": mfType, "datetimes": body["datetimes"], "values": body["values"],
"interpolation": mapInterp(body["interpolation"]),
"lower_inc": orTrue(body["lower_inc"]), "upper_inc": orTrue(body["upper_inc"]),
})
return string(b), nil
}
// ensureTPropTable creates the shared temporal-property store on first write: a
// row per (collection, feature, property) holding the value as a native
// MobilityDB temporal value in the column matching its type.
func ensureTPropTable(ctx context.Context, q interface {
Exec(context.Context, string, ...any) (int64, error)
}) error {
_, err := q.Exec(ctx, `CREATE TABLE IF NOT EXISTS mf_tproperty (
cid text NOT NULL, fid bigint NOT NULL, name text NOT NULL,
ptype text NOT NULL, uom text, description text,
vfloat tfloat, vint tint, vtext ttext, vbool tbool,
PRIMARY KEY (cid, fid, name))`)
return err
}
// clip wraps a temporal expression with atTime for the OGC leaf (instant set)
// or datetime (interval) selector, binding the selector value as a parameter.
func clip(expr string, q url.Values, args []any) (string, []any, error) {
if lf := q.Get("leaf"); lf != "" {
set, err := tstzSet(lf)
if err != nil {
return "", nil, err
}
args = append(args, set)
return "atTime(" + expr + ", CAST($" + itoa(len(args)) + " AS tstzset))", args, nil
}
if dt := q.Get("datetime"); dt != "" {
if s, e, ok := splitInterval(dt); ok {
args = append(args, "["+s+", "+e+"]")
return "atTime(" + expr + ", CAST($" + itoa(len(args)) + " AS tstzspan))", args, nil
}
args = append(args, "{"+strings.TrimSpace(dt)+"}") // a single instant
return "atTime(" + expr + ", CAST($" + itoa(len(args)) + " AS tstzset))", args, nil
}
return expr, args, nil
}
// tgSequence returns the moving feature's temporal geometry (MF-JSON), optionally
// clipped to a datetime interval or to leaf instants.
func tgSequence(w http.ResponseWriter, r *http.Request) {
tbl, _, ok := collectionMeta(r.Context(), r.PathValue("cid"))
if !ok {
httpErr(w, 404, "collection not found")
return
}
fid, err := strconv.Atoi(r.PathValue("fid"))
if err != nil {
httpErr(w, 400, "invalid feature id")
return
}
expr, args, cerr := clip("trip", r.URL.Query(), []any{fid})
if cerr != nil {
httpErr(w, 400, cerr.Error())
return
}
var one int
if err := db.QueryRow(r.Context(), "SELECT 1 FROM "+ident(tbl)+" WHERE id=$1", fid).Scan(&one); errors.Is(err, ErrNoRows) {
httpErr(w, 404, "feature not found")
return
} else if err != nil {
httpErr(w, 500, err.Error())
return
}
// The tgeompoint is a sequence set; each member sequence is one OGC temporal
// primitive geometry, addressed by its 1-based index (sequenceN). The count
// is iterated in the tier so the SQL stays portable (no generate_series).
var nseq *int
if err := db.QueryRow(r.Context(), "SELECT numSequences("+expr+") FROM "+ident(tbl)+" WHERE id=$1", args...).Scan(&nseq); err != nil {
httpErr(w, 400, err.Error())
return
}
count := 0
if nseq != nil {
count = *nseq
}
var ns []int
var mfjsons [][]byte
for n := 1; n <= count; n++ {
var mf string
if err := db.QueryRow(r.Context(), "SELECT asMFJSON(sequenceN("+expr+", "+itoa(n)+")) FROM "+ident(tbl)+" WHERE id=$1", args...).Scan(&mf); err != nil {
break
}
ns = append(ns, n)
mfjsons = append(mfjsons, []byte(mf))
}
body, err := buildTGSequence(r.URL.Path, ns, mfjsons)
if err != nil {
httpErr(w, 500, err.Error())
return
}
writeRaw(w, 200, ogcify(string(body)))
}
// tgSequenceQuery serves the OGC TemporalGeometry derived queries. distance and
// velocity are exact MobilityDB functions; acceleration is NOT_IMPLEMENTED
// because with linearly interpolated position the speed is piecewise-constant,
// so its derivative is zero within each segment and undefined at the vertices.
func tgSequenceQuery(w http.ResponseWriter, r *http.Request) {
q := strings.ToLower(r.PathValue("qtype"))
if q == "acceleration" {
httpErr(w, 501, "acceleration is not derivable: linearly interpolated position gives a piecewise-constant (Step) speed, whose derivative is zero within each segment and undefined at the vertices")
return
}
if q != "velocity" && q != "distance" {
httpErr(w, 404, "unknown query type: "+q)
return
}
tbl, _, ok := collectionMeta(r.Context(), r.PathValue("cid"))
if !ok {
httpErr(w, 404, "collection not found")
return
}
fid, err := strconv.Atoi(r.PathValue("fid"))
if err != nil {
httpErr(w, 400, "invalid feature id")
return
}
tg, err := strconv.Atoi(r.PathValue("tgid"))
if err != nil || tg < 1 {
httpErr(w, 400, "invalid temporal geometry id (1-based index into the sequence)")
return
}
var nseq *int
err = db.QueryRow(r.Context(), "SELECT numSequences(trip) FROM "+ident(tbl)+" WHERE id=$1", fid).Scan(&nseq)
if errors.Is(err, ErrNoRows) {
httpErr(w, 404, "feature not found")
return
}
if err != nil {
httpErr(w, 400, err.Error())
return
}
if nseq == nil || tg > *nseq {
httpErr(w, 404, "no temporal geometry #"+itoa(tg)+" for this feature")
return
}
// Address the temporal primitive geometry by its sequence index.
spec := tProps[q]
spec.expr = strings.Replace(spec.expr, "trip", "sequenceN(trip, "+itoa(tg)+")", 1)
writeTemporalProperty(w, r, tbl, q, spec)
}
// getTProperty serves one stored temporal property as an OGC temporalProperty,
// optionally clipped to a datetime interval or to leaf instants.
func getTProperty(w http.ResponseWriter, r *http.Request) {
cid := r.PathValue("cid")
name := r.PathValue("pname")
if _, _, ok := collectionMeta(r.Context(), cid); !ok {
httpErr(w, 404, "collection not found")
return
}
fid, err := strconv.Atoi(r.PathValue("fid"))
if err != nil {
httpErr(w, 400, "invalid feature id")
return
}
var ptype, uom, desc string
err = db.QueryRow(r.Context(),
"SELECT ptype, coalesce(uom,''), coalesce(description,'') FROM mf_tproperty WHERE cid=$1 AND fid=$2 AND name=$3",
cid, fid, name).Scan(&ptype, &uom, &desc)
if errors.Is(err, ErrNoRows) {
httpErr(w, 404, "unknown temporal property: "+name)
return
}
if err != nil {
httpErr(w, 500, err.Error())
return
}
tt, ok := tPropType(ptype)
if !ok {
httpErr(w, 500, "stored property has an unknown type: "+ptype)
return
}
expr, args, cerr := clip(tt.col, r.URL.Query(), []any{cid, fid, name})
if cerr != nil {
httpErr(w, 400, cerr.Error())
return
}
sql := "SELECT asMFJSON(" + expr + ") FROM mf_tproperty WHERE cid=$1 AND fid=$2 AND name=$3"
var mfjson *string
if err := db.QueryRow(r.Context(), sql, args...).Scan(&mfjson); err != nil {
httpErr(w, 400, err.Error())
return
}
mf := []byte("null")
if mfjson != nil {
mf = []byte(*mfjson)
}
body, berr := reshapeTemporalProperty(name, tt.ogc, uom, desc, r.URL.Path, mf)
if berr != nil {
httpErr(w, 500, berr.Error())
return
}
writeRaw(w, 200, ogcify(string(body)))
}
// writeTemporalProperty serves a derived measure as an OGC temporalProperty:
// the tfloat is serialised with asMFJSON and reshaped in the tier, carrying each
// segment's own interpolation verbatim from MobilityDB.
func writeTemporalProperty(w http.ResponseWriter, r *http.Request, tbl, name string, spec propSpec) {
fid, err := strconv.Atoi(r.PathValue("fid"))
if err != nil {
httpErr(w, 400, "invalid feature id")
return
}
expr, args, cerr := clip(spec.expr, r.URL.Query(), []any{fid})
if cerr != nil {
httpErr(w, 400, cerr.Error())
return
}
sql := "SELECT asMFJSON(" + expr + ") FROM " + ident(tbl) + " WHERE id=$1"
var mfjson *string
err = db.QueryRow(r.Context(), sql, args...).Scan(&mfjson)
if errors.Is(err, ErrNoRows) {
httpErr(w, 404, "feature not found")
return
}
if err != nil {
httpErr(w, 400, err.Error())
return
}
mf := []byte("null")
if mfjson != nil {
mf = []byte(*mfjson)
}
body, berr := reshapeTemporalProperty(name, "TReal", spec.uom, spec.desc, r.URL.Path, mf)
if berr != nil {
httpErr(w, 500, berr.Error())
return
}
writeRaw(w, 200, ogcify(string(body)))
}
// listTProperties lists the stored temporal properties of a feature.
func listTProperties(w http.ResponseWriter, r *http.Request) {
cid := r.PathValue("cid")
tbl, _, ok := collectionMeta(r.Context(), cid)
if !ok {
httpErr(w, 404, "collection not found")
return
}
fid, err := strconv.Atoi(r.PathValue("fid"))
if err != nil {
httpErr(w, 400, "invalid feature id")
return
}
var one int
if err := db.QueryRow(r.Context(), "SELECT 1 FROM "+ident(tbl)+" WHERE id=$1", fid).Scan(&one); err != nil {
httpErr(w, 404, "feature not found")
return
}
base := r.URL.Path
list := make([]map[string]any, 0)
var reg *string
db.QueryRow(r.Context(), "SELECT to_regclass('mf_tproperty')").Scan(®)
if reg != nil {
rows, err := db.Query(r.Context(),
"SELECT name, ptype, coalesce(uom,''), coalesce(description,'') FROM mf_tproperty WHERE cid=$1 AND fid=$2 ORDER BY name",
cid, fid)
if err != nil {
httpErr(w, 500, err.Error())
return
}
defer rows.Close()
for rows.Next() {
var name, ptype, uom, desc string
if err := rows.Scan(&name, &ptype, &uom, &desc); err != nil {
break
}
list = append(list, map[string]any{"name": name, "type": ptype, "form": uom, "description": desc,
"links": []map[string]string{{"rel": "self", "href": base + "/" + name}}})
}
}
writeJSON(w, 200, map[string]any{
"temporalProperties": list, "numberReturned": len(list), "numberMatched": len(list),
"timeStamp": time.Now().UTC().Format(time.RFC3339),
"links": []map[string]string{{"rel": "self", "href": base}},
})
}
func tstzSet(csv string) (string, error) {
parts := strings.Split(csv, ",")
out := make([]string, 0, len(parts))
for _, p := range parts {
if p = strings.TrimSpace(p); p != "" {
out = append(out, p)