Skip to content
Open
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
27 changes: 27 additions & 0 deletions Sources/GroveFHIRContract/RecordingFile.swift
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,33 @@ public struct RecordingFile: Sendable {
return try builder.finish()
}

/// Stages the bytes `body` produces synchronously, written in chunks of at most 64 KiB.
///
/// An error `body` throws or an exceeded byte limit discards the file instead of returning a partial snapshot, and
/// `append` refuses every further byte after its first failure.
package static func stage(
maximumByteCount: Int,
producing body: (_ append: (Data) throws -> Void) throws -> Void
) throws -> Self {
var builder = try Builder(maximumByteCount: maximumByteCount)
var failure: (any Error)?
try body { bytes in
if let failure {
throw failure
}
do {
try builder.append(bytes)
} catch {
failure = error
throw error
}
}
if let failure {
throw failure
}
return try builder.finish()
}

/// Reads the bytes in chunks of at most 64 KiB, independently of any other reader.
///
/// Only the current chunk is retained; `consume` controls whether it retains delivered chunks. An error or
Expand Down
10 changes: 0 additions & 10 deletions Sources/GroveSensorKit/Sample Types/Other+Unsafe.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,6 @@
// We use the @preconcurrency import to make it work anyway, for the time being.


extension SRMessagesUsageReport: SensorKitSampleProtocol {
public typealias SafeRepresentation = DefaultSensorKitSampleSafeRepresentation<SRMessagesUsageReport>
}


extension SRPhoneUsageReport: SensorKitSampleProtocol {
public typealias SafeRepresentation = DefaultSensorKitSampleSafeRepresentation<SRPhoneUsageReport>
}


extension SRKeyboardMetrics: SensorKitSampleProtocol {
public typealias SafeRepresentation = DefaultSensorKitSampleSafeRepresentation<SRKeyboardMetrics>
}
105 changes: 105 additions & 0 deletions Sources/GroveSensorKit/Sample Types/UsageReports.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
//
// This source file is part of the Grove open-source project
//
// SPDX-FileCopyrightText: 2026 Stanford University and the project authors (see CONTRIBUTORS.md)
//
// SPDX-License-Identifier: MIT
//

public import Foundation
public import SensorKit


extension SRMessagesUsageReport: SensorKitSampleProtocol {
/// Every public field of a messages-usage report, copied on the SensorKit callback thread.
public struct SafeRepresentation: SensorKitSampleSafeRepresentation {
/// The time SensorKit states for the report.
public let timestamp: Date
/// The length of the reporting interval, in seconds.
public let duration: TimeInterval
/// The number of messages the person sent during the interval.
public let totalOutgoingMessages: Int
/// The number of messages the person received during the interval.
public let totalIncomingMessages: Int
/// The number of distinct contacts the person exchanged messages with during the interval.
public let totalUniqueContacts: Int
/// The report's ``timestamp``, as an empty range.
public var timeRange: Range<Date> { timestamp..<timestamp }

/// Creates a report from its fields.
public init(timestamp: Date, duration: TimeInterval, totalOutgoingMessages: Int, totalIncomingMessages: Int, totalUniqueContacts: Int) {
self.timestamp = timestamp
self.duration = duration
self.totalOutgoingMessages = totalOutgoingMessages
self.totalIncomingMessages = totalIncomingMessages
self.totalUniqueContacts = totalUniqueContacts
}
}

public static func processIntoSafeRepresentation(
_ samples: some Sequence<(timestamp: Date, sample: SRMessagesUsageReport)>
) -> [SafeRepresentation] {
samples.map { timestamp, report in
SafeRepresentation(
timestamp: timestamp,
duration: report.duration,
totalOutgoingMessages: report.totalOutgoingMessages,
totalIncomingMessages: report.totalIncomingMessages,
totalUniqueContacts: report.totalUniqueContacts
)
}
}
}


extension SRPhoneUsageReport: SensorKitSampleProtocol {
/// Every public field of a phone-usage report, copied on the SensorKit callback thread.
public struct SafeRepresentation: SensorKitSampleSafeRepresentation {
/// The time SensorKit states for the report.
public let timestamp: Date
/// The length of the reporting interval, in seconds.
public let duration: TimeInterval
/// The number of calls the person placed during the interval.
public let totalOutgoingCalls: Int
/// The number of calls the person received during the interval.
public let totalIncomingCalls: Int
/// The number of distinct contacts the person called or was called by during the interval.
public let totalUniqueContacts: Int
/// The total length of the person's calls during the interval, in seconds.
public let totalPhoneCallDuration: TimeInterval
/// The report's ``timestamp``, as an empty range.
public var timeRange: Range<Date> { timestamp..<timestamp }

/// Creates a report from its fields.
public init(
timestamp: Date,
duration: TimeInterval,
totalOutgoingCalls: Int,
totalIncomingCalls: Int,
totalUniqueContacts: Int,
totalPhoneCallDuration: TimeInterval
) {
self.timestamp = timestamp
self.duration = duration
self.totalOutgoingCalls = totalOutgoingCalls
self.totalIncomingCalls = totalIncomingCalls
self.totalUniqueContacts = totalUniqueContacts
self.totalPhoneCallDuration = totalPhoneCallDuration
}
}

public static func processIntoSafeRepresentation(
_ samples: some Sequence<(timestamp: Date, sample: SRPhoneUsageReport)>
) -> [SafeRepresentation] {
samples.map { timestamp, report in
SafeRepresentation(
timestamp: timestamp,
duration: report.duration,
totalOutgoingCalls: report.totalOutgoingCalls,
totalIncomingCalls: report.totalIncomingCalls,
totalUniqueContacts: report.totalUniqueContacts,
totalPhoneCallDuration: report.totalPhoneCallDuration
)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -187,17 +187,19 @@ The conformance lane in `Scripts/validate-fhir-conformance.sh` proves this adapt
One batch becomes records in one of two ways:

- **One record per batch.** A tabular stream (accelerometer, ambient light, ambient pressure, heart rate, pedometer) becomes one ``SensorKitTabularRecording`` from all its samples, and a photoplethysmogram batch one ``SensorKitPreparedPPGRecording`` from `SensorKitPPGRecording(samples:).prepared()`. A rotation-rate batch becomes one ``SensorKitRotationRateRecord`` from its samples, which exposes no `retryEvidence`, so digest the samples you pass. The record's ordinal is 0.
- **One record per sample.** A visit, an on-wrist event, a device-usage report and an ECG session each become one ``SensorKitPreparedStructuredRecord``, and a wrist-temperature session one ``SensorKitTabularRecording``; each takes the zero-based position of its sample in the batch as its ordinal.
- **One record per sample.** A visit, an on-wrist event, a messages-usage or phone-usage report, a device-usage report and an ECG session each become one ``SensorKitPreparedStructuredRecord``, and a wrist-temperature session one ``SensorKitTabularRecording``; each takes the zero-based position of its sample in the batch as its ordinal. ``SensorKitPreparedStructuredFile`` writes the native evidence of a device-usage report or an ECG session directly into a recording file.

The other record cases, such as messages or phone usage, keyboard metrics, sleep sessions and a raw recording, take values you assemble; digest exactly what you pass.
The other record cases, such as keyboard metrics, sleep sessions and a raw recording, take values you assemble; digest exactly what you pass.

``SensorKitSourceRecordID/derived(acquisitionBatch:sourceToken:deviceProductType:recordOrdinal:)`` names each record from the batch's coordinate, the stream's catalog token (`SensorKitCatalog.sourceToken(for:)`), the batch's device product type and that ordinal, never from its content.
A fresh query anchor starts a random stream partition of its own, which the coordinate states, so a reinstall names no record of an earlier installation although its cursor restarts at the same place.

Your digest keeps one name meaning one content.
Each preparation exposes `retryEvidence`, the bytes Grove derives the record from.
Digest them, persist the digest beside the record's id, and on a redelivery of the batch fail the batch when a digest differs: SensorKit may change records inside an unacknowledged boundary, and only this digest stops an id from naming other content.
An ECG session's evidence covers its identifier, states and waveform; its start, sampling frequency, lead and guidance enter its record too, so digest them beside it.
An ECG session's evidence covers its identifier, states and waveform, followed by its start, sampling frequency, lead and guidance, which its record states too.

Persist a ``SensorKitBatchSnapshot`` of the application, host and source devices, the time zone and the conversion instant before the first conversion of a batch, and convert a redelivery with the decoded snapshot, so the retry states the same facts.

Failing a batch means throwing before `acknowledge()`: the anchor stays, and the batch is reissued after a restart under the same coordinate and ids.
The reissued batch holds the same samples while SensorKit returns the same fetch results up to the batch's boundary; data recorded after the batch does not change it. An ECG batch whose last session was delivered without its end state also depends on what followed that session, as the ECG Sessions section of the GroveSensorKit documentation describes.
Expand Down Expand Up @@ -365,7 +367,9 @@ On iOS, typed initializers map Grove's already-fetched safe representations into
- ``SensorKitTabularRecording/File``
- ``SensorKitPreparedPPGRecording``
- ``SensorKitPreparedStructuredRecord``
- ``SensorKitPreparedStructuredFile``
- ``SensorKitRecordingLocation``
- ``SensorKitBatchSnapshot``
- ``SensorKitSummaryError``

### Recording payloads
Expand All @@ -378,3 +382,4 @@ On iOS, typed initializers map Grove's already-fetched safe representations into

- ``SensorKitCatalog``
- ``SensorKitCatalogEntry``
- ``SensorKitOutputDefinition``
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
// This validator intentionally keeps the closed payload grammar in one exhaustive switch.
// swiftlint:disable cyclomatic_complexity function_body_length

import Foundation
public import Foundation
public import GroveFHIRContract
import ModelsR4

Expand Down Expand Up @@ -48,6 +48,33 @@ extension RegisteredRecordingFormat {
csvColumns == nil && self != .cdaDocument && self != .sourceFile
}

/// Validates a recording file against this format's grammar within the caller's byte limit.
///
/// A CSV is validated in bounded chunks, retaining one bounded row. JSON, FHIR and PPG payloads are decoded as a
/// whole and stay within ``maximumDecodedPayloadByteCount`` as well. The caller separately verifies the source
/// digests, the media type, the consent and the clinical graph.
///
/// - Parameters:
/// - file: The recording file.
/// - maximumByteCount: The most bytes the file may hold, between 1 and `Int32.max`.
/// - Throws: A ``RegisteredRecordingPayloadError``, a `RecordingFile.FileError` or `CancellationError`.
public func validatePayload(_ file: RecordingFile, maximumByteCount: Int) throws {
try Self.validateByteCount(file.byteCount, maximumByteCount: maximumByteCount)
try validatePayload(file)
}

/// Validates bytes already in memory against this format's grammar within the caller's byte limit.
///
/// Payloads that are decoded as a whole stay within ``maximumDecodedPayloadByteCount`` as well.
///
/// - Parameters:
/// - bytes: The payload.
/// - maximumByteCount: The most bytes the payload may hold, between 1 and `Int32.max`.
public func validatePayload(_ bytes: Data, maximumByteCount: Int) throws(RegisteredRecordingPayloadError) {
try Self.validateByteCount(bytes.count, maximumByteCount: maximumByteCount)
try validatePayload(bytes)
}

func validatePayloadSize(_ byteCount: Int) throws(RegisteredRecordingPayloadError) {
guard !requiresWholePayloadDecoding || byteCount <= Self.maximumDecodedPayloadByteCount else { throw .payloadLimitExceeded }
}
Expand Down Expand Up @@ -165,3 +192,13 @@ extension RegisteredRecordingFormat {
}
}
}


extension RegisteredRecordingFormat {
/// Both entry points admit at most the caller's limit, which an attachment's `Int32` size bounds.
fileprivate static func validateByteCount(_ byteCount: Int, maximumByteCount: Int) throws(RegisteredRecordingPayloadError) {
guard (1...Int(Int32.max)).contains(maximumByteCount), byteCount <= maximumByteCount else {
throw .payloadLimitExceeded
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
//
// This source file is part of the Grove open-source project
//
// SPDX-FileCopyrightText: 2026 Stanford University and the project authors (see CONTRIBUTORS.md)
//
// SPDX-License-Identifier: MIT
//

import GroveFHIRContract


extension SensorKitBatchSnapshot {
struct RecordingFacts: Codable {
let stableUnitToken: String?
let tokenScope: String?
let name: String?
let manufacturer: String?
let model: String?
let productType: String?
let systemName: String?
let systemVersion: String?
let hardwareVersion: String?
let firmwareVersion: String?
let softwareVersion: String?
let localIdentifier: String?
let udiDeviceIdentifier: String?
let udiProductionIdentifier: String?
let serialNumber: String?

var strings: [String] {
[
stableUnitToken, tokenScope, name, manufacturer,
model, productType, systemName, systemVersion,
hardwareVersion, firmwareVersion, softwareVersion, localIdentifier,
udiDeviceIdentifier, udiProductionIdentifier, serialNumber
].compactMap { $0 }
}

var value: RecordingDevice {
var device = RecordingDevice()
device.stableUnitToken = stableUnitToken
device.tokenScope = tokenScope
device.name = name
device.manufacturer = manufacturer
device.model = model
device.productType = productType
device.systemName = systemName
device.systemVersion = systemVersion
device.hardwareVersion = hardwareVersion
device.firmwareVersion = firmwareVersion
device.softwareVersion = softwareVersion
device.localIdentifier = localIdentifier
device.udiDeviceIdentifier = udiDeviceIdentifier
device.udiProductionIdentifier = udiProductionIdentifier
device.serialNumber = serialNumber
return device
}

init(_ device: RecordingDevice) {
stableUnitToken = device.stableUnitToken
tokenScope = device.tokenScope
name = device.name
manufacturer = device.manufacturer
model = device.model
productType = device.productType
systemName = device.systemName
systemVersion = device.systemVersion
hardwareVersion = device.hardwareVersion
firmwareVersion = device.firmwareVersion
softwareVersion = device.softwareVersion
localIdentifier = device.localIdentifier
udiDeviceIdentifier = device.udiDeviceIdentifier
udiProductionIdentifier = device.udiProductionIdentifier
serialNumber = device.serialNumber
}
}
}
Loading
Loading