-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbatch.go
More file actions
406 lines (364 loc) · 10.7 KB
/
batch.go
File metadata and controls
406 lines (364 loc) · 10.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
// 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 (
"bytes"
"strconv"
"time"
)
// Batch represents an HL7 batch (BHS...BTS) containing one or more messages.
type Batch struct {
Header *Segment // BHS segment, may be nil if absent
Trailer *Segment // BTS segment, may be nil if absent
Messages []*Message // Messages within the batch
}
// File represents an HL7 file (FHS...FTS) containing one or more batches.
type File struct {
Header *Segment // FHS segment, may be nil if absent
Trailer *Segment // FTS segment, may be nil if absent
Batches []Batch // Batches within the file
}
// ParseBatch parses a batch of HL7 messages from raw bytes.
//
// A batch may optionally begin with a BHS segment and end with a BTS segment.
// Individual messages within the batch are identified by MSH segment boundaries.
func ParseBatch(data []byte) (*Batch, error) {
lines := splitLines(data)
if len(lines) == 0 {
return nil, ErrMessageTooShort
}
batch := &Batch{}
var msgLines [][]byte
for _, line := range lines {
segType := segmentType(line)
switch segType {
case "BHS":
seg := parseStandaloneSegment(line)
batch.Header = &seg
case "BTS":
// Flush any accumulated message.
if len(msgLines) > 0 {
msg, err := ParseMessage(joinLines(msgLines))
if err == nil {
batch.Messages = append(batch.Messages, msg)
}
msgLines = nil
}
seg := parseStandaloneSegment(line)
batch.Trailer = &seg
case "MSH":
// Flush previous message if any.
if len(msgLines) > 0 {
msg, err := ParseMessage(joinLines(msgLines))
if err == nil {
batch.Messages = append(batch.Messages, msg)
}
}
msgLines = [][]byte{line}
default:
if len(msgLines) > 0 {
msgLines = append(msgLines, line)
}
}
}
// Flush final accumulated message.
if len(msgLines) > 0 {
msg, err := ParseMessage(joinLines(msgLines))
if err == nil {
batch.Messages = append(batch.Messages, msg)
}
}
return batch, nil
}
// ParseFile parses an HL7 file containing batches from raw bytes.
//
// A file may optionally begin with an FHS segment and end with an FTS segment.
// It contains one or more batches, each optionally delimited by BHS/BTS segments.
// Messages not wrapped in BHS/BTS are placed in an implicit batch.
func ParseFile(data []byte) (*File, error) {
lines := splitLines(data)
if len(lines) == 0 {
return nil, ErrMessageTooShort
}
file := &File{}
var currentBatch *Batch
var msgLines [][]byte
flushMessage := func() {
if len(msgLines) == 0 {
return
}
msg, err := ParseMessage(joinLines(msgLines))
if err == nil {
if currentBatch == nil {
currentBatch = &Batch{}
}
currentBatch.Messages = append(currentBatch.Messages, msg)
}
msgLines = nil
}
flushBatch := func() {
flushMessage()
if currentBatch != nil {
file.Batches = append(file.Batches, *currentBatch)
currentBatch = nil
}
}
for _, line := range lines {
segType := segmentType(line)
switch segType {
case "FHS":
seg := parseStandaloneSegment(line)
file.Header = &seg
case "FTS":
flushBatch()
seg := parseStandaloneSegment(line)
file.Trailer = &seg
case "BHS":
flushBatch()
currentBatch = &Batch{}
seg := parseStandaloneSegment(line)
currentBatch.Header = &seg
case "BTS":
flushMessage()
if currentBatch != nil {
seg := parseStandaloneSegment(line)
currentBatch.Trailer = &seg
}
flushBatch()
case "MSH":
flushMessage()
msgLines = [][]byte{line}
default:
if len(msgLines) > 0 {
msgLines = append(msgLines, line)
}
}
}
flushBatch()
return file, nil
}
// splitLines splits data on \r (with optional \n) into non-empty lines.
func splitLines(data []byte) [][]byte {
var lines [][]byte
start := 0
for i := 0; i < len(data); i++ {
if data[i] == '\r' || data[i] == '\n' {
if i > start {
lines = append(lines, data[start:i])
}
if data[i] == '\r' && i+1 < len(data) && data[i+1] == '\n' {
i++
}
start = i + 1
}
}
if start < len(data) {
trimmed := bytes.TrimRight(data[start:], "\r\n")
if len(trimmed) > 0 {
lines = append(lines, trimmed)
}
}
return lines
}
// joinLines joins line slices with \r separators.
func joinLines(lines [][]byte) []byte {
if len(lines) == 0 {
return nil
}
total := 0
for _, l := range lines {
total += len(l) + 1
}
result := make([]byte, 0, total)
for i, l := range lines {
result = append(result, l...)
if i < len(lines)-1 {
result = append(result, '\r')
}
}
return result
}
// segmentType returns the 3-character segment type from a line, or "".
func segmentType(line []byte) string {
if len(line) < 3 {
return ""
}
return string(line[0:3])
}
// parseStandaloneSegment creates a Segment from a line using default delimiters.
// Used for BHS/BTS/FHS/FTS which may appear outside of a parsed message.
func parseStandaloneSegment(line []byte) Segment {
delims := DefaultDelimiters()
// Try to extract delimiters if the line has enough data and looks like it
// has a field separator at position 3.
if len(line) >= 8 {
d, err := extractHeaderDelimiters(line)
if err == nil {
delims = d
}
}
return Segment{raw: line, delims: delims}
}
// BatchBuilder constructs a BHS/BTS-wrapped HL7 batch from individual messages.
//
// Example:
//
// bb := hl7.NewBatchBuilder()
// bb.SetHeader(3, "MYAPP").SetHeader(4, "MYFAC")
// bb.Add(msg1).Add(msg2)
// data, err := bb.Build()
type BatchBuilder struct {
delims Delimiters
fields map[int]string // fieldNum (1-based) -> plain-text value
messages []*Message
}
// BatchBuilderOption configures a BatchBuilder.
type BatchBuilderOption func(*BatchBuilder)
// WithBatchDelimiters sets the delimiter set used in the BHS header.
func WithBatchDelimiters(d Delimiters) BatchBuilderOption {
return func(b *BatchBuilder) {
b.delims = d
}
}
// NewBatchBuilder returns a BatchBuilder with a default BHS header using
// DefaultDelimiters(). BHS-7 (date/time) is set to time.Now() at Build time
// unless overridden via SetHeader(7, ...).
func NewBatchBuilder(opts ...BatchBuilderOption) *BatchBuilder {
b := &BatchBuilder{delims: DefaultDelimiters()}
for _, opt := range opts {
opt(b)
}
return b
}
// SetHeader sets BHS field fieldNum (1-based) to the given plain-text value.
// The value is escaped at Build time. Common fields:
// BHS-3 (sending application), BHS-4 (sending facility), BHS-11 (batch control ID).
// Returns the receiver for chaining.
func (b *BatchBuilder) SetHeader(fieldNum int, value string) *BatchBuilder {
if b.fields == nil {
b.fields = make(map[int]string)
}
b.fields[fieldNum] = value
return b
}
// Add appends msg to the batch. msg.Raw() bytes are written verbatim at Build time.
// Returns the receiver for chaining.
func (b *BatchBuilder) Add(msg *Message) *BatchBuilder {
b.messages = append(b.messages, msg)
return b
}
// Reset clears accumulated messages. Header field values set via SetHeader are preserved.
func (b *BatchBuilder) Reset() {
b.messages = nil
}
// Build finalizes the batch and returns BHS + messages + BTS as a byte slice.
// BTS-1 (message count) is set to the number of messages added via Add.
// BatchBuilder is reusable after Build; call Reset to clear messages while
// keeping header field values.
//
// Returns an error if the delimiter set is invalid.
func (b *BatchBuilder) Build() ([]byte, error) {
if err := b.delims.validate(); err != nil {
return nil, err
}
delims := b.delims
now := time.Now()
// Determine the maximum field number written to the BHS segment.
// BHS-7 (datetime) is always included as the minimum.
maxField := 7
for k := range b.fields {
if k > maxField {
maxField = k
}
}
// Collect escaped field values for BHS fields 3..maxField.
fieldVals := make([][]byte, maxField-2) // index 0 = field 3
for i := 3; i <= maxField; i++ {
idx := i - 3
if v, ok := b.fields[i]; ok {
fieldVals[idx] = Escape([]byte(v), delims)
} else if i == 7 {
// Default BHS-7 to current date/time.
fieldVals[idx] = []byte(now.Format("20060102150405"))
}
// All other unset fields remain nil (written as empty between separators).
}
// Pre-calculate BHS segment size:
// "BHS" (3) + fieldSep (1) + 4 encoding chars + (maxField-2) separators + field bytes
bhsSize := 7 + (maxField - 2)
for _, v := range fieldVals {
bhsSize += len(v)
}
// Pre-calculate BTS segment size: "BTS" (3) + fieldSep (1) + count digits
countStr := strconv.Itoa(len(b.messages))
btsSize := 3 + 1 + len(countStr)
// Pre-calculate total output size.
totalSize := bhsSize + 1 // BHS + \r
for _, msg := range b.messages {
raw := msg.Raw()
totalSize += len(raw)
if len(raw) == 0 || raw[len(raw)-1] != '\r' {
totalSize++ // ensure \r terminator after each message
}
}
totalSize += btsSize + 1 // BTS + \r
// Allocate once and build output.
out := make([]byte, 0, totalSize)
// BHS segment: BHS + fieldSep + encoding chars + fields 3..maxField
out = append(out, 'B', 'H', 'S')
out = append(out, delims.Field)
out = append(out, delims.Component, delims.Repetition, delims.Escape, delims.SubComponent)
for _, v := range fieldVals {
out = append(out, delims.Field)
out = append(out, v...)
}
out = append(out, '\r')
// Messages: write each message's raw bytes, ensuring \r termination.
for _, msg := range b.messages {
raw := msg.Raw()
out = append(out, raw...)
if len(raw) == 0 || raw[len(raw)-1] != '\r' {
out = append(out, '\r')
}
}
// BTS segment: BTS + fieldSep + count
out = append(out, 'B', 'T', 'S')
out = append(out, delims.Field)
out = append(out, countStr...)
out = append(out, '\r')
return out, nil
}
// extractHeaderDelimiters extracts delimiters from batch/file header segments
// (BHS, FHS) which share the same encoding character layout as MSH.
func extractHeaderDelimiters(data []byte) (Delimiters, error) {
if len(data) < 8 {
return Delimiters{}, ErrInvalidMSH
}
// BHS and FHS use the same encoding character positions as MSH.
typ := string(data[0:3])
if typ != "BHS" && typ != "FHS" && typ != "MSH" {
return DefaultDelimiters(), nil
}
d := Delimiters{
Field: data[3],
Component: data[4],
Repetition: data[5],
Escape: data[6],
SubComponent: data[7],
}
if err := d.validate(); err != nil {
return DefaultDelimiters(), nil
}
return d, nil
}