Skip to content

Phase 5, Task 2a: Implement parseDatastream() #79

Closed

Description

@Sam-Bolling

Task

Implement parseDatastream() in a new part2.ts file. This is the first Part 2 parser and establishes the shared file that will also house parseObservation(), parseControlStream(), parseCommand(), and parseCommandStatus() in subsequent tasks.

ROADMAP Reference: Phase 5, Task 2a — parseDatastream() Implementation (~1–1.5 hours, Medium complexity)


Files to Create or Modify

File Action Est. Lines Purpose
src/ogc-api/csapi/formats/part2.ts Create ~80–120 parseDatastream() function — transforms raw Datastream JSON into typed Datastream object. First Part 2 parser; this file will be extended by Tasks 3, 4, 5a, 6.

Note: This task creates part2.ts with only parseDatastream(). Tests are in Task 2b.

Blueprint Reference

Follow the tolerant extraction pattern established by extractCSAPIFeature() in src/ogc-api/csapi/formats/geojson.ts (L392+):

  • Input guard (throw if not a non-null object)
  • Cast to Record<string, unknown>
  • Extract fields with type-safe fallbacks
  • Conditional spread for optional fields: ...(typeof obj.field === 'string' ? { field: obj.field } : {})
  • Return typed result using satisfies Datastream

Also reference parseProperty() (Task 1) for the base pattern, and the SensorML sub-parser structure in src/ogc-api/csapi/formats/sensorml/physical-system.ts (L504+) for JSDoc density.

Scope — What to Implement

parseDatastream(json: unknown): Datastream

Implement a single exported function that transforms a raw JSON object from the /datastreams endpoint items array into a typed Datastream object.

Input shape (OGC 23-002, dataStream schema):

{
  "id": "0ocb",
  "name": "FCU Simulated Weather Station - Weather",
  "system@id": "0o0o",
  "system@link": {
    "href": "http://45.55.99.236:8080/sensorhub/api/systems/0o0o?f=json",
    "uid": "urn:osh:sensor:simweather:001",
    "type": "application/geo+json"
  },
  "outputName": "weather",
  "validTime": ["2026-01-26T18:32:01.56Z", "now"],
  "observedProperties": [
    { "definition": "http://mmisw.org/ont/cf/parameter/air_temperature", "label": "Air Temperature" }
  ],
  "formats": [
    "application/om+json",
    "application/swe+json",
    "application/swe+csv",
    "application/swe+xml",
    "application/swe+binary"
  ],
  "phenomenonTime": ["2026-01-26T18:32:01.56Z", "2026-02-19T14:22:03.12Z"],
  "resultTime": ["2026-01-26T18:32:01.56Z", "2026-02-19T14:22:03.12Z"],
  "resultType": "record",
  "live": true,
  "links": [
    { "rel": "self", "href": "/datastreams/0ocb", "type": "application/json" }
  ]
}

Field transformations (13 fields):

Field Source Type Target Type Transformation
id string string Direct extraction
name string string Direct extraction; fall back to empty string
description string | undefined string | undefined Conditional extraction
validTime [string, string] | null TimeInterval | undefined parseValidTime() — handles "now" sentinel, null, array, object formats
formats string[] string[] Extract if array; fall back to empty array
outputName string | undefined string | undefined Conditional extraction
observedProperties array | null string[] Extract definition URIs from objects; fall back to empty array. See normalization note below.
phenomenonTime [string, string] | null TimeInterval | null parseValidTime() or null
resultTime [string, string] | null TimeInterval | null parseValidTime() or null
resultType string | null enum | null Validate against known values ('measure' | 'vector' | 'record' | 'coverage' | 'complex'); null if unknown
live boolean | null boolean | null Direct extraction
type string | undefined 'status' | 'observation' | undefined Conditional extraction
links array ResourceLink[] Extract if array; fall back to empty array

Key Implementation Details

Time Fields (3 fields — validTime, phenomenonTime, resultTime)

All three use the same parseValidTime() function from geojson.ts:

Field Nullable? Semantics
validTime Optional (may be absent) When the datastream is/was valid
phenomenonTime null allowed (readOnly) Time range of all observations
resultTime null allowed (readOnly) Time range of all result timestamps

Import parseValidTime from ./geojson.js. Study its signature (parseValidTime(value: unknown): TimeInterval | undefined) before writing code. It returns undefined for null/absent input. For phenomenonTime and resultTime, the interface type is TimeInterval | null, so you need: parseValidTime(obj.phenomenonTime) ?? null.

observedProperties Normalization

The server returns an array of objects { definition, label, description }. The Datastream interface declares observedProperties: string[]. The parser must:

  1. Extract the definition URI from each object to produce the string array
  2. If the server returns a plain string array (spec allows both), pass through directly
  3. Fall back to empty array if absent
// Handle both object and string forms:
function normalizeObservedProperties(arr: unknown[]): string[] {
  return arr.map((item) => {
    if (typeof item === 'string') return item;
    if (typeof item === 'object' && item !== null && 'definition' in item) {
      return String((item as Record<string, unknown>).definition);
    }
    return '';
  }).filter(Boolean);
}

Cross-references (NOT extracted)

system@id and system@link are present in the raw JSON but are NOT in the Datastream interface. The parser must ignore these fields entirely — do not include them in the output.

resultType enum validation

Validate against the known enum values: 'measure' | 'vector' | 'record' | 'coverage' | 'complex'. If the value doesn't match any known value, return null.

JSDoc Requirements

  • Document parseDatastream() with:
    • @param json — describes the expected input (raw JSON from /datastreams items)
    • @returns — Datastream object with all 13 fields extracted and transformed
    • @throws — when input is not a non-null object
    • Usage example showing a successful parse
    • Note about the 3 time fields and parseValidTime() reuse
    • Note about observedProperties normalization
  • Add @see link to OGC 23-002 Datastream resources section
  • Follow the JSDoc density in src/ogc-api/csapi/formats/sensorml/physical-system.ts (parsePhysicalSystem)
  • Document any helper functions (e.g., normalizeObservedProperties) with JSDoc

Scope — What NOT to Touch

  • ❌ Do NOT modify src/ogc-api/csapi/model.ts — the Datastream interface already exists (L434–462)
  • ❌ Do NOT modify src/ogc-api/csapi/formats/geojson.ts — parseValidTime() is already implemented; import it
  • ❌ Do NOT add tests — that is Task 2b's scope
  • ❌ Do NOT add parseObservation() — that is Task 3's scope
  • ❌ Do NOT add parseControlStream() — that is Task 4's scope
  • ❌ Do NOT add parseCommand() or parseCommandStatus() — those are Tasks 5a and 6
  • ❌ Do NOT create schema-response.ts — that belongs to Task 7
  • ❌ Do NOT modify any SensorML files
  • ❌ Do NOT modify QueryBuilder call sites or response.ts — integration wiring is Task 9
  • ❌ Do NOT modify index.ts exports
  • ❌ Do NOT modify property.ts (Task 1)
  • ❌ Do NOT refactor existing code unless required to complete this task

Acceptance Criteria

  • src/ogc-api/csapi/formats/part2.ts exists with exported parseDatastream() function
  • All 13 fields extracted per the field transformations table
  • 3 time fields parsed via parseValidTime() imported from geojson.ts
  • observedProperties normalization handles both object ({ definition, label }) and string array forms
  • system@id and system@link are NOT present in the output
  • resultType validated against known enum values; unknown values → null
  • Input guard throws on non-object input
  • Function compiles with satisfies Datastream return typing
  • All new code has complete JSDoc documentation
  • No lint errors
  • Existing tests still pass (npm test)

Dependencies

Blocked by: Task 1 (must establish the parseProperty() pattern first; also validates parseValidTime() import path works from a new file)
Blocks: Task 2b (tests for this implementation), Task 3 (parseObservation — will be added to the same part2.ts file), Task 9 (Integration Wiring)


Operational Constraints

⚠️ MANDATORY: Before starting work on this issue, review docs/governance/AI_OPERATIONAL_CONSTRAINTS.md.

For Phase 5 issues: Review the P5 Implementation Guide §4.2 for parseDatastream() field transformations, input shape, time field handling, and observedProperties normalization. Review Phase 5 parser constraints below.

Key constraints for this task:

  • Precedence: OGC specifications → AI Collaboration Agreement → This issue description → Existing code → Conversational context
  • No scope expansion: Do not infer unstated requirements or add unrequested features
  • No refactoring: Do not rename, restructure, or "improve" code outside this issue's scope
  • Minimal diffs: Prefer the smallest change that satisfies the acceptance criteria
  • Ask when unclear: If intent is ambiguous, stop and ask for clarification

Phase 5 Parser Constraints

  • Tolerant extraction (Postel's Law): Never gate on missing fields. If a field is absent, use the interface default (empty string for required strings, undefined for optional fields, empty array for required arrays, null for nullable fields). Never throw on malformed data — only throw when input is not an object.
  • parseValidTime() reuse: Import from ./geojson.js. Do NOT duplicate. For nullable time fields (phenomenonTime, resultTime), use parseValidTime(obj.field) ?? null to convert undefined → null.
  • Cross-reference fields are NOT extracted: system@id and system@link are present in raw JSON but not in the Datastream interface. The parser ignores them.
  • Model interface already exists: The Datastream interface is defined in model.ts L434–462. Do not redefine or modify it.
  • Consistent patterns: Follow the same error handling, conditional spread, and satisfies typing patterns as extractCSAPIFeature() in geojson.ts and parseProperty() in property.ts (Task 1).
  • part2.ts is a shared file: This file will house all Part 2 parsers (Tasks 2a, 3, 4, 5a, 6). Structure it to accommodate future additions: top-level exports, clear function separation, shared helpers (if any) at the top.

References

Primary References (must read)

# Document Section/Lines What It Provides
1 P5 Implementation Guide §4.2 parseDatastream() (L238–328) Input shape, field transformations, time field semantics, observedProperties normalization, test cases
2 P5 Implementation Guide §7.1 parseValidTime() (L815–830) Confirms reuse from geojson.ts, import guidance
3 P5 ROADMAP Task 2a (L110–131) Task definition, deliverables, step-by-step checklist, dependencies
4 P5 Contribution Goal Full document Scope boundary — confirms what is/isn't in Phase 5
5 Parsing Coverage Audit Gap #2 (L187) Source of truth for the gap being addressed

Blueprint References (pattern to follow)

# Document What It Provides
1 src/ogc-api/csapi/formats/geojson.ts L392–472 extractCSAPIFeature() — tolerant extraction pattern, input guard, conditional spread, satisfies typing
2 src/ogc-api/csapi/formats/geojson.ts L274–324 parseValidTime() — the function to import and reuse for 3 time fields
3 src/ogc-api/csapi/formats/property.ts (Task 1) parseProperty() — base pattern for parse*(json: unknown): T signature in a new file
4 src/ogc-api/csapi/formats/sensorml/physical-system.ts L504+ parsePhysicalSystem() — JSDoc density reference

Upstream Type/Import References

# Document What to Import
1 src/ogc-api/csapi/model.ts L434–462 Datastream, ResourceLink, TimeInterval interfaces
2 src/ogc-api/csapi/formats/geojson.ts L274 parseValidTime function

Specification References (for @see links and field accuracy)

# Document Use
1 OGC API - Connected Systems Part 2 (23-002) Datastream resource definition, dataStream schema

Research References (context)

# Document What It Provides
1 validTime coverage analysis Full validTime landscape — confirms Datastream has validTime per Part 2
2 P5 Implementation Guide §11 Risk Register Risk #3: observedProperties shape variance; Risk #5: 52North Part 2 differences

Smoke Test Findings (informing fixture design for Task 2b)

Finding Relevance
ST#7 (Datastream responses) Real OSH Datastream response data for fixture design
F85 validTime absent from OSH Deployments — validates tolerant extraction philosophy
F39 Commands use items envelope — confirms parsers only need item-level logic
F45 Response envelope varies by server — handled by parseCollectionResponse()

Convention Quick Reference

Rule Example
Use .js extension for relative imports import { parseValidTime } from './geojson.js'
Use import type for interfaces/types import type { Datastream, ResourceLink, TimeInterval } from '../model.js'
Three-tier hierarchy: import from lower tiers only shared → ogc-api → csapi
Named exports for types and utilities export function parseDatastream(...)
Meaningful tests only Verify field values, not that code runs without throwing

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions