-
Notifications
You must be signed in to change notification settings - Fork 7
Add support for definition based extraction mechanism #28
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Itskiprotich
wants to merge
15
commits into
ohs-foundation:main
Choose a base branch
from
Itskiprotich:jk-definition-based-extraction
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
efc7558
UPD: add support for definition based extraction mechanism
Itskiprotich 21ef190
UPD: Refine extraction engine behavior, spec alignment, and tests.
Itskiprotich dde31d7
UPD: Organize definition extraction data models in a dedicated file
Itskiprotich e981b38
UPD: fix versioned vs unversioned canonicals
Itskiprotich 271eb68
UPD: Remove definition extraction %resource fallback logic
Itskiprotich 28d2457
UPD: Remove dead fullUrl fallback branch in definition extraction
Itskiprotich 7d031ad
UPD: Improve definition extraction resource type inference for custom…
Itskiprotich 8bfed8c
UPD: ensure resource variable matches
Itskiprotich 2d5c2f7
fix(extraction): retain resource when a singular element receives mul…
Itskiprotich e6d0a33
refactor(extraction): reuse FhirPathService.toJsonElement in encodeVa…
Itskiprotich ff50cf0
UPD: code refactor and centralizing reusable funtions
Itskiprotich 931398d
Update datacapture/src/commonMain/kotlin/dev/ohs/fhir/datacapture/ext…
Itskiprotich 7966ce7
refactor: centralize resource descriptor lookup for definition extrac…
Itskiprotich 5161b46
UPD: Refactor DefinitionExtractionEngine into focused files
Itskiprotich d0fd6e5
UPD: add a test for a repeated group
Itskiprotich File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
205 changes: 205 additions & 0 deletions
205
...rc/commonMain/kotlin/dev/ohs/fhir/datacapture/extraction/definition/BundleEntryBuilder.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,205 @@ | ||
| /* | ||
| * Copyright 2026 Open Health Stack Foundation | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
| package dev.ohs.fhir.datacapture.extraction.definition | ||
|
|
||
| import co.touchlab.kermit.Logger | ||
| import dev.ohs.fhir.datacapture.extensions.generateAllocatedFullUrl | ||
| import dev.ohs.fhir.model.r4.Bundle | ||
| import dev.ohs.fhir.model.r4.Questionnaire | ||
| import dev.ohs.fhir.model.r4.QuestionnaireResponse | ||
| import kotlinx.serialization.json.Json | ||
| import kotlinx.serialization.json.JsonElement | ||
| import kotlinx.serialization.json.JsonObject | ||
| import kotlinx.serialization.json.JsonPrimitive | ||
| import kotlinx.serialization.json.buildJsonObject | ||
|
|
||
| private val json = Json { | ||
| explicitNulls = false | ||
| encodeDefaults = false | ||
| } | ||
|
|
||
| /** | ||
| * Executes one `definitionExtract` scope and returns the `Bundle.entry` JSON for that scope. | ||
| * | ||
| * This is the spec's "initiate resource extraction" step. It creates the stub resource identified | ||
| * by the `definitionExtract.definition`, applies any root/item `definitionExtractValue` directives | ||
| * in scope, walks descendant items whose `Questionnaire.item.definition` canonical matches the | ||
| * scoped canonical, and then assembles request metadata such as `fullUrl`, `method`, and | ||
| * conditional headers. | ||
| */ | ||
| internal fun extractBundleEntryForDefinitionScope( | ||
| definitionExtract: DefinitionExtractConfig, | ||
| questionnaire: Questionnaire, | ||
| questionnaireResponse: QuestionnaireResponse, | ||
| scopeBase: Any, | ||
| scopeQuestionnaireItem: Questionnaire.Item?, | ||
| scopePairs: List<QuestionnaireItemResponsePair>, | ||
| inheritedAllocateIds: Map<String, String>, | ||
| resolveProfileResourceType: ((String) -> String?)?, | ||
| ): JsonObject { | ||
| val resourceType = | ||
| inferResourceType( | ||
| definitionCanonical = definitionExtract.definition, | ||
| questionnaire = questionnaire, | ||
| scopeQuestionnaireItem = scopeQuestionnaireItem, | ||
| scopePairs = scopePairs, | ||
| resolveProfileResourceType = resolveProfileResourceType, | ||
| ) | ||
| val rootDescriptor = resourceDescriptor(resourceType) | ||
| val resourceNode = MutableJsonObject(rootDescriptor) | ||
| val rootAnchor = | ||
| AnchorContext(path = emptyList(), node = resourceNode, descriptor = rootDescriptor) | ||
| val scopeCanonical = definitionExtract.definition | ||
|
|
||
| if (scopeQuestionnaireItem == null) { | ||
| applyDefinitionExtractValueDirectives( | ||
| sourceExtensions = questionnaire.extension, | ||
| scopeCanonical = scopeCanonical, | ||
| questionnaire = questionnaire, | ||
| questionnaireResponse = questionnaireResponse, | ||
| base = questionnaireResponse, | ||
| questionnaireItem = null, | ||
| responseItem = null, | ||
| allocateIds = inheritedAllocateIds, | ||
| rootAnchor = rootAnchor, | ||
| parentAnchor = rootAnchor, | ||
| directAnchor = null, | ||
| ) | ||
| } | ||
|
|
||
| scopePairs.forEach { | ||
| applyQuestionnairePairToDefinitionScope( | ||
| pair = it, | ||
| questionnaire = questionnaire, | ||
| questionnaireResponse = questionnaireResponse, | ||
| scopeCanonical = scopeCanonical, | ||
| inheritedAllocateIds = inheritedAllocateIds, | ||
| rootAnchor = rootAnchor, | ||
| parentAnchor = rootAnchor, | ||
| ) | ||
| } | ||
|
|
||
| addProfileIfNeeded(resourceNode, definitionExtract.definition, resourceType) | ||
|
|
||
| val resourceJson = resourceNode.toJsonObject(resourceType) | ||
| val resourceId = resourceNode.values["id"]?.toJsonElement()?.asString() | ||
| val requestMethod = if (resourceId.isNullOrBlank()) "POST" else "PUT" | ||
|
|
||
| return buildJsonObject { | ||
| val fullUrl = | ||
| definitionExtract.fullUrlExpression | ||
| ?.let { | ||
| evaluateDefinitionExtractExpressionToString( | ||
| expression = it, | ||
| base = scopeBase, | ||
| questionnaire = questionnaire, | ||
| questionnaireResponse = questionnaireResponse, | ||
| questionnaireItem = scopeQuestionnaireItem, | ||
| responseItem = scopeBase as? QuestionnaireResponse.Item, | ||
| allocateIds = inheritedAllocateIds, | ||
| ) | ||
| } | ||
| ?.takeIf { it.isNotBlank() } ?: generateAllocatedFullUrl() | ||
| put("fullUrl", JsonPrimitive(fullUrl)) | ||
|
|
||
| put("resource", resourceJson) | ||
|
|
||
| put( | ||
| "request", | ||
| buildRequestJson( | ||
| definitionExtract = definitionExtract, | ||
| questionnaire = questionnaire, | ||
| questionnaireResponse = questionnaireResponse, | ||
| scopeBase = scopeBase, | ||
| scopeQuestionnaireItem = scopeQuestionnaireItem, | ||
| resourceType = resourceType, | ||
| resourceId = resourceId, | ||
| requestMethod = requestMethod, | ||
| inheritedAllocateIds = inheritedAllocateIds, | ||
| ), | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Builds `Bundle.entry.request`, including any conditional headers whose expressions evaluate to a | ||
| * non-blank string. | ||
| */ | ||
| private fun buildRequestJson( | ||
| definitionExtract: DefinitionExtractConfig, | ||
| questionnaire: Questionnaire, | ||
| questionnaireResponse: QuestionnaireResponse, | ||
| scopeBase: Any, | ||
| scopeQuestionnaireItem: Questionnaire.Item?, | ||
| resourceType: String, | ||
| resourceId: String?, | ||
| requestMethod: String, | ||
| inheritedAllocateIds: Map<String, String>, | ||
| ): JsonObject = buildJsonObject { | ||
| put("method", JsonPrimitive(requestMethod)) | ||
| put( | ||
| "url", | ||
| JsonPrimitive(if (resourceId.isNullOrBlank()) resourceType else "$resourceType/$resourceId"), | ||
| ) | ||
|
|
||
| fun putConditionalHeader(jsonKey: String, expression: String?) { | ||
| expression | ||
| ?.let { | ||
| evaluateDefinitionExtractExpressionToString( | ||
| expression = it, | ||
| base = scopeBase, | ||
| questionnaire = questionnaire, | ||
| questionnaireResponse = questionnaireResponse, | ||
| questionnaireItem = scopeQuestionnaireItem, | ||
| responseItem = scopeBase as? QuestionnaireResponse.Item, | ||
| allocateIds = inheritedAllocateIds, | ||
| ) | ||
| } | ||
| ?.takeIf { it.isNotBlank() } | ||
| ?.let { put(jsonKey, JsonPrimitive(it)) } | ||
| } | ||
|
|
||
| putConditionalHeader("ifNoneMatch", definitionExtract.ifNoneMatchExpression) | ||
| putConditionalHeader("ifModifiedSince", definitionExtract.ifModifiedSinceExpression) | ||
| putConditionalHeader("ifMatch", definitionExtract.ifMatchExpression) | ||
| putConditionalHeader("ifNoneExist", definitionExtract.ifNoneExistExpression) | ||
| } | ||
|
|
||
| /** | ||
| * Adds an extracted entry only if it fully materializes as a valid `Bundle.entry`. | ||
| * | ||
| * The SDC guide says extraction errors should be logged and processing should continue as though | ||
| * the failed query or directive produced no data. This helper keeps that behavior localized to one | ||
| * resource scope instead of failing the whole extraction transaction. | ||
| */ | ||
| internal inline fun materializeValidEntryOrNull( | ||
| scopeDescription: String, | ||
| block: () -> JsonObject, | ||
| ): JsonObject? = | ||
| try { | ||
| val entryJson = block() | ||
| json.decodeFromJsonElement(Bundle.Entry.serializer(), entryJson) | ||
| entryJson | ||
| } catch (throwable: Throwable) { | ||
| Logger.w( | ||
| "Skipping definition-based extraction for $scopeDescription because it could not be fully materialized.", | ||
| throwable, | ||
| ) | ||
| null | ||
| } | ||
|
|
||
| private fun JsonElement.asString(): String? = | ||
| (this as? JsonPrimitive)?.content?.takeIf { it.isNotBlank() } |
34 changes: 34 additions & 0 deletions
34
...otlin/dev/ohs/fhir/datacapture/extraction/definition/DefinitionExtractResourceRegistry.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| /* | ||
| * Copyright 2026 Open Health Stack Foundation | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
| package dev.ohs.fhir.datacapture.extraction.definition | ||
|
|
||
| import dev.ohs.fhir.model.r4.Resource | ||
| import kotlinx.serialization.descriptors.SerialDescriptor | ||
|
|
||
| internal object DefinitionExtractResourceRegistry { | ||
| private val descriptorsByType: Map<String, SerialDescriptor> by lazy { | ||
| val resourceDescriptor = Resource.serializer().descriptor | ||
| val union = resourceDescriptor.getElementDescriptor(resourceDescriptor.getElementIndex("value")) | ||
| (0 until union.elementsCount).associate { index -> | ||
| union.getElementName(index) to union.getElementDescriptor(index) | ||
| } | ||
| } | ||
| internal val supportedResourceTypes: Set<String> | ||
| get() = descriptorsByType.keys | ||
|
|
||
| internal fun descriptorFor(resourceType: String): SerialDescriptor? = | ||
| descriptorsByType[resourceType] | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.