-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathack.go
More file actions
278 lines (247 loc) · 7.72 KB
/
ack.go
File metadata and controls
278 lines (247 loc) · 7.72 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
// 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"
"time"
)
// AckCode represents an HL7v2 acknowledgment code (MSA-1).
type AckCode string
const (
AA AckCode = "AA" // Application Accept
AE AckCode = "AE" // Application Error
AR AckCode = "AR" // Application Reject
CA AckCode = "CA" // Commit Accept
CE AckCode = "CE" // Commit Error
CR AckCode = "CR" // Commit Reject
)
// AckOption configures optional fields on an ACK message.
type AckOption func(*ackBuilder)
// WithText sets MSA-3 (text message) for error context.
func WithText(text string) AckOption {
return func(b *ackBuilder) {
b.text = text
}
}
// WithTimestamp overrides the default time.Now() for MSH-7.
func WithTimestamp(t time.Time) AckOption {
return func(b *ackBuilder) {
b.timestamp = t
}
}
// WithErrors adds ERR segments to the ACK message, one per Issue.
// Issues are typically obtained from Validate:
//
// result := msg.Validate(schema)
// ack, err := msg.Ack(hl7.AE, "ACK001", hl7.WithErrors(result.Issues))
//
// Each Issue maps to one ERR segment with error location (ERR-2),
// severity (ERR-4), application error code (ERR-5), and diagnostic
// information (ERR-7).
func WithErrors(issues []Issue) AckOption {
return func(b *ackBuilder) {
b.errors = issues
}
}
type ackBuilder struct {
text string
timestamp time.Time
errors []Issue
}
// Ack creates an ACK message in response to this message.
// The controlID is used as MSH-10 of the ACK. The caller is responsible
// for generating unique control IDs.
//
// The ACK copies delimiters and swaps sender/receiver fields from the
// original MSH segment. Field values are copied as raw bytes to preserve
// any escape sequences.
//
// Returns ErrNoMSHSegment if the message has no MSH segment.
func (m *Message) Ack(code AckCode, controlID string, opts ...AckOption) ([]byte, error) {
if len(m.segments) == 0 || m.segments[0].Type() != "MSH" {
return nil, ErrNoMSHSegment
}
ab := ackBuilder{timestamp: time.Now()}
for _, opt := range opts {
opt(&ab)
}
msh := &m.segments[0]
d := m.delims
f := d.Field
ts := ab.timestamp.Format("20060102150405")
// Pre-calculate buffer size to avoid growing.
// MSH: "MSH" + separator + encoding chars + 10 delimited fields
// MSA: "MSA" + code + control ID + optional text
sendApp := msh.Field(5).Raw()
sendFac := msh.Field(6).Raw()
recvApp := msh.Field(3).Raw()
recvFac := msh.Field(4).Raw()
triggerEvent := msh.Field(9).Rep(0).Component(2).Raw()
procID := msh.Field(11).Raw()
versionID := msh.Field(12).Raw()
origControlID := msh.Field(10).Raw()
// Estimate size: MSH header + fields + MSA segment.
size := 3 + 1 + 4 + // "MSH" + separator + encoding chars
1 + len(sendApp) +
1 + len(sendFac) +
1 + len(recvApp) +
1 + len(recvFac) +
1 + len(ts) +
1 + // empty field (MSH-8)
1 + 3 + 1 + len(triggerEvent) + 1 + 3 + // ACK^trigger^ACK
1 + len(controlID) +
1 + len(procID) +
1 + len(versionID) +
1 + // segment terminator
3 + 1 + len(code) + 1 + len(origControlID) + // MSA|code|controlID
1 // segment terminator
if ab.text != "" {
size += 1 + len(ab.text)
}
// Pre-escape and size ERR segments.
type errData struct {
erl []byte // pre-built ERL field
sev byte // 'E' or 'W'
code []byte // escaped code
desc []byte // escaped description
}
var errs []errData
if len(ab.errors) > 0 {
errs = make([]errData, len(ab.errors))
for i, issue := range ab.errors {
errs[i].erl = appendERL(nil, issue.Location, d)
errs[i].sev = errSeverityByte(issue.Severity)
errs[i].code = Escape([]byte(issue.Code), d)
errs[i].desc = Escape([]byte(issue.Description), d)
// "ERR" + 7 field separators + fields + \r
size += 3 + 7 +
len(errs[i].erl) + // ERR-2
1 + // ERR-4 severity
len(errs[i].code) + // ERR-5
len(errs[i].desc) + // ERR-7
1 // segment terminator
}
}
buf := make([]byte, 0, size)
// MSH segment.
buf = append(buf, 'M', 'S', 'H')
buf = append(buf, f)
buf = append(buf, d.Component, d.Repetition, d.Escape, d.SubComponent)
buf = append(buf, f)
buf = append(buf, sendApp...)
buf = append(buf, f)
buf = append(buf, sendFac...)
buf = append(buf, f)
buf = append(buf, recvApp...)
buf = append(buf, f)
buf = append(buf, recvFac...)
buf = append(buf, f)
buf = append(buf, ts...)
buf = append(buf, f) // MSH-8 (security) — empty
buf = append(buf, f)
buf = append(buf, 'A', 'C', 'K')
if len(triggerEvent) > 0 {
buf = append(buf, d.Component)
buf = append(buf, triggerEvent...)
buf = append(buf, d.Component)
buf = append(buf, 'A', 'C', 'K')
}
buf = append(buf, f)
buf = append(buf, controlID...)
buf = append(buf, f)
buf = append(buf, procID...)
buf = append(buf, f)
buf = append(buf, versionID...)
buf = append(buf, '\r')
// MSA segment.
buf = append(buf, 'M', 'S', 'A')
buf = append(buf, f)
buf = append(buf, code...)
buf = append(buf, f)
buf = append(buf, origControlID...)
if ab.text != "" {
buf = append(buf, f)
buf = append(buf, ab.text...)
}
buf = append(buf, '\r')
// ERR segments.
for _, e := range errs {
buf = append(buf, 'E', 'R', 'R')
buf = append(buf, f) // ERR-1 (deprecated, empty)
buf = append(buf, f) // ERR-2 start
buf = append(buf, e.erl...)
buf = append(buf, f) // ERR-3 (empty)
buf = append(buf, f) // ERR-4 start
buf = append(buf, e.sev)
buf = append(buf, f) // ERR-5 start
buf = append(buf, e.code...)
buf = append(buf, f) // ERR-6 (empty)
buf = append(buf, f) // ERR-7 start
buf = append(buf, e.desc...)
buf = append(buf, '\r')
}
return buf, nil
}
// errSeverityByte converts a Severity to the ERR-4 character code.
func errSeverityByte(s Severity) byte {
if s == SeverityWarning {
return 'W'
}
return 'E'
}
// appendERL builds an ERL (Error Location) composite value from a terser-style
// location string. The format is: segment ^ sequence ^ field ^ component ^ subcomponent.
// On parse failure, returns nil (producing an empty ERR-2).
func appendERL(buf []byte, location string, d Delimiters) []byte {
loc, err := ParseLocation(location)
if err != nil {
// Bare segment names like "PID" don't parse (no field number).
// Try to extract just the segment type if it's 2-3 uppercase letters.
if len(location) >= 2 && len(location) <= 3 && isUpperAlpha(location) {
buf = append(buf, location...)
buf = append(buf, d.Component)
buf = append(buf, '1') // sequence defaults to 1
return buf
}
return buf
}
// ERR-2.1: segment type.
buf = append(buf, loc.Segment...)
buf = append(buf, d.Component)
// ERR-2.2: sequence (1-based). SegmentIndex is 0-based.
buf = append(buf, strconv.Itoa(loc.SegmentIndex+1)...)
buf = append(buf, d.Component)
// ERR-2.3: field number.
buf = append(buf, strconv.Itoa(loc.Field)...)
// ERR-2.4: component (only if specified).
if loc.Component > 0 {
buf = append(buf, d.Component)
buf = append(buf, strconv.Itoa(loc.Component)...)
// ERR-2.5: subcomponent (only if specified).
if loc.SubComponent > 0 {
buf = append(buf, d.Component)
buf = append(buf, strconv.Itoa(loc.SubComponent)...)
}
}
return buf
}
// isUpperAlpha returns true if s contains only A-Z.
func isUpperAlpha(s string) bool {
for i := 0; i < len(s); i++ {
if s[i] < 'A' || s[i] > 'Z' {
return false
}
}
return true
}