-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidate.go
More file actions
632 lines (573 loc) · 15.7 KB
/
validate.go
File metadata and controls
632 lines (573 loc) · 15.7 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
// Copyright 2026 Joshua Jones <joshua.jones.software@gmail.com>
//
// 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 hl7
import "strconv"
// Severity indicates the severity of a validation issue.
type Severity int
const (
SeverityError Severity = iota
SeverityWarning
)
func (s Severity) String() string {
switch s {
case SeverityError:
return "error"
case SeverityWarning:
return "warning"
default:
return "unknown"
}
}
// Issue codes for machine-readable categorization of validation findings.
const (
CodeUnknownStructure = "UNKNOWN_STRUCTURE"
CodeRequiredSegment = "REQUIRED_SEGMENT"
CodeUnexpectedSegment = "UNEXPECTED_SEGMENT"
CodeSegmentCardinality = "SEGMENT_CARDINALITY"
CodeRequiredField = "REQUIRED_FIELD"
CodeFieldLength = "FIELD_LENGTH"
CodeFieldCardinality = "FIELD_CARDINALITY"
CodeRequiredComponent = "REQUIRED_COMPONENT"
CodeComponentLength = "COMPONENT_LENGTH"
CodeInvalidFormat = "INVALID_FORMAT"
CodeInvalidTableValue = "INVALID_TABLE_VALUE"
CodeInvalidValue = "INVALID_VALUE"
)
// Issue represents a single validation finding.
type Issue struct {
Severity Severity
Location string // terser-style location, e.g., "PID-3.1" or segment type
Code string // machine-readable code, e.g., CodeRequiredField
Description string // human-readable description
}
func (i Issue) String() string {
return "[" + i.Severity.String() + "] " + i.Location + ": " + i.Description + " (" + i.Code + ")"
}
// ValidationResult holds the outcome of message validation.
type ValidationResult struct {
Valid bool
Issues []Issue
}
// Validate checks a parsed message against a schema and returns all findings.
//
// Validation runs in three phases:
// 1. Structure — checks segment presence, order, and cardinality against the
// MessageDef looked up from MSH-9.
// 2. Content — checks field presence, length, cardinality, data type format,
// and coded table values against SegmentDef, DataTypeDef, and TableDef.
// Also runs FieldCheckFunc and SegmentCheckFunc validators if defined.
// 3. Custom checks — runs MessageCheckFunc validators from schema.Checks for
// cross-segment business rules.
//
// Each phase runs only if the relevant definitions exist in the schema.
// A nil receiver or nil schema returns a valid result with no issues.
func (m *Message) Validate(schema *Schema) *ValidationResult {
if m == nil || schema == nil {
return &ValidationResult{Valid: true}
}
v := &validator{msg: m, schema: schema}
v.validateStructure()
v.validateFields()
v.validateChecks()
return &ValidationResult{
Valid: !v.hasErr,
Issues: v.issues,
}
}
type validator struct {
msg *Message
schema *Schema
issues []Issue
hasErr bool
}
func (v *validator) addIssue(sev Severity, loc, code, desc string) {
v.issues = append(v.issues, Issue{
Severity: sev,
Location: loc,
Code: code,
Description: desc,
})
if sev == SeverityError {
v.hasErr = true
}
}
func (v *validator) appendIssues(issues []Issue) {
for i := range issues {
v.issues = append(v.issues, issues[i])
if issues[i].Severity == SeverityError {
v.hasErr = true
}
}
}
// --- Phase 3: Custom Message Checks ---
func (v *validator) validateChecks() {
for _, fn := range v.schema.Checks {
v.appendIssues(fn(v.msg))
}
}
// --- Phase 1: Structure Validation ---
func (v *validator) validateStructure() {
msgDef := v.lookupMessageDef()
if msgDef == nil {
return
}
segments := v.msg.Segments()
pos := v.matchElements(msgDef.Elements, segments, 0)
for i := pos; i < len(segments); i++ {
typ := segments[i].Type()
v.addIssue(SeverityError, typ, CodeUnexpectedSegment,
"Unexpected segment "+typ)
}
}
func (v *validator) lookupMessageDef() *MessageDef {
if v.schema.Messages == nil {
return nil
}
structID := v.msg.Get("MSH-9.3").String()
if structID == "" {
code := v.msg.Get("MSH-9.1").String()
event := v.msg.Get("MSH-9.2").String()
if code != "" && event != "" {
structID = code + "_" + event
}
}
if structID == "" {
return nil
}
def, ok := v.schema.Messages[structID]
if !ok {
v.addIssue(SeverityError, "MSH-9", CodeUnknownStructure,
"No message definition found for "+structID)
return nil
}
return def
}
// matchElements walks a list of element definitions and tries to consume
// matching segments starting at pos. Returns the new position after matching.
func (v *validator) matchElements(elems []Element, segs []Segment, pos int) int {
for _, elem := range elems {
if elem.Segment != "" {
pos = v.matchSegmentElem(elem, segs, pos)
} else if len(elem.Elements) > 0 {
pos = v.matchGroupElem(elem, segs, pos)
}
}
return pos
}
func (v *validator) matchSegmentElem(elem Element, segs []Segment, pos int) int {
count := 0
max := elem.Max
for pos < len(segs) && segs[pos].Type() == elem.Segment {
count++
pos++
if max > 0 && count >= max {
break
}
}
if count < elem.Min {
v.addIssue(SeverityError, elem.Segment, CodeRequiredSegment,
"Required segment "+elem.Segment+" is missing")
}
// Check for additional occurrences beyond max.
if max > 0 {
extra := 0
for pos < len(segs) && segs[pos].Type() == elem.Segment {
extra++
pos++
}
if extra > 0 {
v.addIssue(SeverityError, elem.Segment, CodeSegmentCardinality,
"Segment "+elem.Segment+" appears "+strconv.Itoa(count+extra)+" times, max is "+strconv.Itoa(max))
}
}
return pos
}
func (v *validator) matchGroupElem(elem Element, segs []Segment, pos int) int {
count := 0
max := elem.Max
for {
start := pos
// Snapshot before probing so we can roll back spurious errors
// if the group doesn't consume any segments this iteration.
snap := v.snapshotIssues()
newPos := v.matchElements(elem.Elements, segs, pos)
if newPos == start {
v.restoreIssues(snap)
break
}
count++
pos = newPos
if max > 0 && count >= max {
break
}
}
if count < elem.Min {
name := elem.Group
if name == "" {
name = "unnamed"
}
v.addIssue(SeverityError, "", CodeRequiredSegment,
"Required group "+name+" is missing")
}
return pos
}
type issueSnapshot struct {
count int
hasErr bool
}
func (v *validator) snapshotIssues() issueSnapshot {
return issueSnapshot{count: len(v.issues), hasErr: v.hasErr}
}
func (v *validator) restoreIssues(s issueSnapshot) {
v.issues = v.issues[:s.count]
v.hasErr = s.hasErr
}
// --- Phase 2: Content Validation (fields, data types, tables) ---
func (v *validator) validateFields() {
if v.schema.Segments == nil {
return
}
segments := v.msg.Segments()
counts := make(map[string]int)
for i := range segments {
seg := &segments[i]
typ := seg.Type()
idx := counts[typ]
counts[typ]++
segDef, ok := v.schema.Segments[typ]
if !ok {
continue
}
segLoc := formatSegLoc(typ, idx)
v.validateSegmentFields(seg, segDef, segLoc)
}
}
func (v *validator) validateSegmentFields(seg *Segment, def *SegmentDef, segLoc string) {
for _, fd := range def.Fields {
field := seg.Field(fd.Index)
if fd.Required && !field.HasValue() {
loc := segLoc + "-" + strconv.Itoa(fd.Index)
desc := "Required field " + loc + " is missing"
if fd.Name != "" {
desc = "Required field " + loc + " (" + fd.Name + ") is missing"
}
v.addIssue(SeverityError, loc, CodeRequiredField, desc)
}
if field.IsEmpty() || field.IsNull() {
continue
}
repCount := field.RepetitionCount()
if !fd.Repeating && repCount > 1 {
loc := segLoc + "-" + strconv.Itoa(fd.Index)
v.addIssue(SeverityError, loc, CodeFieldCardinality,
"Field "+loc+" repeats "+strconv.Itoa(repCount)+" times but is not repeating")
}
for ri := range repCount {
rep := field.Rep(ri)
v.validateRep(rep, fd, segLoc, ri, repCount)
}
if fd.Check != nil {
v.appendIssues(fd.Check(field))
}
}
if def.Check != nil {
v.appendIssues(def.Check(seg))
}
}
func (v *validator) validateRep(rep Repetition, fd FieldDef, segLoc string, repIdx, repCount int) {
raw := rep.Raw()
if fd.Value != "" && string(raw) != fd.Value {
loc := buildFieldLoc(segLoc, fd.Index, repIdx, repCount)
v.addIssue(SeverityError, loc, CodeInvalidValue,
"Field "+loc+" has value "+strconv.Quote(string(raw))+", expected "+strconv.Quote(fd.Value))
return
}
if fd.MaxLength > 0 && len(raw) > fd.MaxLength {
loc := buildFieldLoc(segLoc, fd.Index, repIdx, repCount)
v.addIssue(SeverityError, loc, CodeFieldLength,
"Field "+loc+" exceeds max length "+strconv.Itoa(fd.MaxLength)+" (got "+strconv.Itoa(len(raw))+")")
}
var dtDef *DataTypeDef
if fd.DataType != "" && v.schema.DataTypes != nil {
dtDef = v.schema.DataTypes[fd.DataType]
}
if dtDef != nil && len(dtDef.Components) > 0 {
v.validateComposite(rep, dtDef, segLoc, fd.Index, repIdx, repCount)
} else {
if fd.DataType != "" && !isValidPrimitiveFormat(raw, fd.DataType) {
loc := buildFieldLoc(segLoc, fd.Index, repIdx, repCount)
v.addIssue(SeverityError, loc, CodeInvalidFormat,
"Value "+strconv.Quote(string(raw))+" at "+loc+" is not a valid "+fd.DataType)
}
if fd.Table != "" && !v.isInTable(raw, fd.Table) {
loc := buildFieldLoc(segLoc, fd.Index, repIdx, repCount)
v.addIssue(SeverityError, loc, CodeInvalidTableValue,
"Value "+strconv.Quote(string(raw))+" at "+loc+" is not in table "+fd.Table)
}
}
}
func (v *validator) validateComposite(rep Repetition, dtDef *DataTypeDef, segLoc string, fieldIdx, repIdx, repCount int) {
for _, cd := range dtDef.Components {
comp := rep.Component(cd.Index)
if cd.Required && comp.IsEmpty() {
loc := buildCompLoc(segLoc, fieldIdx, repIdx, repCount, cd.Index)
desc := "Required component " + loc + " is missing"
if cd.Name != "" {
desc = "Required component " + loc + " (" + cd.Name + ") is missing"
}
v.addIssue(SeverityError, loc, CodeRequiredComponent, desc)
continue
}
if comp.IsEmpty() {
continue
}
raw := comp.Raw()
if cd.Value != "" && string(raw) != cd.Value {
loc := buildCompLoc(segLoc, fieldIdx, repIdx, repCount, cd.Index)
v.addIssue(SeverityError, loc, CodeInvalidValue,
"Component "+loc+" has value "+strconv.Quote(string(raw))+", expected "+strconv.Quote(cd.Value))
continue
}
if cd.MaxLength > 0 && len(raw) > cd.MaxLength {
loc := buildCompLoc(segLoc, fieldIdx, repIdx, repCount, cd.Index)
v.addIssue(SeverityError, loc, CodeComponentLength,
"Component "+loc+" exceeds max length "+strconv.Itoa(cd.MaxLength)+" (got "+strconv.Itoa(len(raw))+")")
}
if cd.DataType != "" && !isValidPrimitiveFormat(raw, cd.DataType) {
loc := buildCompLoc(segLoc, fieldIdx, repIdx, repCount, cd.Index)
v.addIssue(SeverityError, loc, CodeInvalidFormat,
"Value "+strconv.Quote(string(raw))+" at "+loc+" is not a valid "+cd.DataType)
}
if cd.Table != "" && !v.isInTable(raw, cd.Table) {
loc := buildCompLoc(segLoc, fieldIdx, repIdx, repCount, cd.Index)
v.addIssue(SeverityError, loc, CodeInvalidTableValue,
"Value "+strconv.Quote(string(raw))+" at "+loc+" is not in table "+cd.Table)
}
}
}
// --- Location builders (only called on error paths) ---
func buildFieldLoc(segLoc string, field, repIdx, repCount int) string {
loc := segLoc + "-" + strconv.Itoa(field)
if repCount > 1 {
loc += "[" + strconv.Itoa(repIdx) + "]"
}
return loc
}
func buildCompLoc(segLoc string, field, repIdx, repCount, comp int) string {
return buildFieldLoc(segLoc, field, repIdx, repCount) + "." + strconv.Itoa(comp)
}
func formatSegLoc(typ string, idx int) string {
if idx == 0 {
return typ
}
return typ + "(" + strconv.Itoa(idx) + ")"
}
// --- Primitive Format Validation ---
//
// Format validators operate on raw bytes to avoid Unescape allocations.
// Escape sequences in date, numeric, or coded value fields are pathological
// and would correctly fail format validation on the raw representation.
func isValidPrimitiveFormat(raw []byte, dataType string) bool {
switch dataType {
case "DT":
return isValidDT(raw)
case "TM":
return isValidTM(raw)
case "DTM", "TS":
return isValidDTM(raw)
case "NM":
return isValidNM(raw)
case "SI":
return isValidSI(raw)
default:
return true
}
}
// isValidDT validates the HL7 DT (date) format: YYYY[MM[DD]].
func isValidDT(b []byte) bool {
n := len(b)
if n != 4 && n != 6 && n != 8 {
return false
}
if !allDigitsB(b) {
return false
}
if n >= 6 {
month := parseTwoDigitsB(b[4:6])
if month < 1 || month > 12 {
return false
}
}
if n == 8 {
day := parseTwoDigitsB(b[6:8])
if day < 1 || day > 31 {
return false
}
}
return true
}
// isValidTM validates the HL7 TM (time) format: HH[MM[SS[.S[S[S[S]]]]]]]][+/-ZZZZ].
func isValidTM(b []byte) bool {
if len(b) < 2 {
return false
}
base, _ := stripTimezoneB(b)
base, ok := stripFractionalB(base)
if !ok {
return false
}
n := len(base)
if n != 2 && n != 4 && n != 6 {
return false
}
if !allDigitsB(base) {
return false
}
return validateTimeDigitsB(base)
}
// isValidDTM validates the HL7 DTM/TS (datetime) format:
// YYYY[MM[DD[HH[MM[SS[.S[S[S[S]]]]]]]]]]][+/-ZZZZ].
func isValidDTM(b []byte) bool {
if len(b) < 4 {
return false
}
base, _ := stripTimezoneB(b)
base, ok := stripFractionalB(base)
if !ok {
return false
}
n := len(base)
if n < 4 || n > 14 || n%2 != 0 {
return false
}
if !allDigitsB(base) {
return false
}
if n >= 6 {
month := parseTwoDigitsB(base[4:6])
if month < 1 || month > 12 {
return false
}
}
if n >= 8 {
day := parseTwoDigitsB(base[6:8])
if day < 1 || day > 31 {
return false
}
}
if n >= 10 {
return validateTimeDigitsB(base[8:])
}
return true
}
// isValidNM validates the HL7 NM (numeric) format: [+/-]digits[.digits].
func isValidNM(b []byte) bool {
if len(b) == 0 {
return false
}
i := 0
if b[0] == '+' || b[0] == '-' {
i++
}
if i >= len(b) {
return false
}
hasDigit := false
hasDot := false
for ; i < len(b); i++ {
if b[i] >= '0' && b[i] <= '9' {
hasDigit = true
} else if b[i] == '.' && !hasDot {
hasDot = true
} else {
return false
}
}
return hasDigit
}
// isValidSI validates the HL7 SI (sequence ID) format: non-negative integer.
func isValidSI(b []byte) bool {
if len(b) == 0 {
return false
}
return allDigitsB(b)
}
// --- Format validation helpers ---
func allDigitsB(b []byte) bool {
for _, c := range b {
if c < '0' || c > '9' {
return false
}
}
return true
}
func parseTwoDigitsB(b []byte) int {
return int(b[0]-'0')*10 + int(b[1]-'0')
}
func stripTimezoneB(b []byte) ([]byte, bool) {
n := len(b)
if n >= 5 {
if c := b[n-5]; c == '+' || c == '-' {
if allDigitsB(b[n-4:]) {
return b[:n-5], true
}
}
}
return b, false
}
func stripFractionalB(b []byte) ([]byte, bool) {
for i, c := range b {
if c == '.' {
frac := b[i+1:]
if len(frac) < 1 || len(frac) > 4 || !allDigitsB(frac) {
return b, false
}
return b[:i], true
}
}
return b, true
}
func validateTimeDigitsB(b []byte) bool {
n := len(b)
if n >= 2 {
if parseTwoDigitsB(b[0:2]) > 23 {
return false
}
}
if n >= 4 {
if parseTwoDigitsB(b[2:4]) > 59 {
return false
}
}
if n >= 6 {
if parseTwoDigitsB(b[4:6]) > 59 {
return false
}
}
return true
}
// --- Table Validation ---
func (v *validator) isInTable(raw []byte, tableID string) bool {
if v.schema.Tables == nil {
return true
}
td, ok := v.schema.Tables[tableID]
if !ok {
return true
}
// string(raw) in a map index expression is optimized by the compiler
// to avoid allocation (mapaccess optimization).
_, valid := td.Values[string(raw)]
return valid
}