forked from newrelic/go-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
txn_cross_process.go
421 lines (351 loc) · 11.5 KB
/
txn_cross_process.go
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
// Copyright 2020 New Relic Corporation. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package newrelic
import (
"encoding/json"
"errors"
"fmt"
"time"
"github.com/Easypay/go-agent/v3/internal"
"github.com/Easypay/go-agent/v3/internal/cat"
)
// Bitfield values for the txnCrossProcess.Type field.
const (
txnCrossProcessSynthetics = (1 << 0)
txnCrossProcessInbound = (1 << 1)
txnCrossProcessOutbound = (1 << 2)
)
var (
// errAccountNotTrusted indicates that, while the inbound headers were valid,
// the account ID within them is not trusted by the user's application.
errAccountNotTrusted = errors.New("account not trusted")
)
// txnCrossProcess contains the metadata required for CAT and Synthetics
// headers, transaction events, and traces.
type txnCrossProcess struct {
// The user side switch controlling whether CAT is enabled or not.
Enabled bool
// The user side switch controlling whether Distributed Tracing is enabled or not
// This is required by synthetics support. If Distributed Tracing is enabled,
// any synthetics functionality that is triggered should not set nr.guid.
DistributedTracingEnabled bool
// Rather than copying in the entire ConnectReply, here are the fields that
// we need to support CAT.
CrossProcessID []byte
EncodingKey []byte
TrustedAccounts internal.TrustedAccountSet
// CAT state for a given transaction.
Type uint8
ClientID string
GUID string
TripID string
PathHash string
AlternatePathHashes map[string]bool
ReferringPathHash string
ReferringTxnGUID string
Synthetics *cat.SyntheticsHeader
// The encoded synthetics header received as part of the request headers, if
// any. By storing this here, we avoid needing to marshal the invariant
// Synthetics struct above each time an external segment is created.
SyntheticsHeader string
}
// crossProcessMetadata represents the metadata that must be transmitted with
// an external request for CAT to work.
type crossProcessMetadata struct {
ID string
TxnData string
Synthetics string
}
// Init initialises a txnCrossProcess based on the given application connect
// reply.
func (txp *txnCrossProcess) Init(enabled bool, dt bool, reply *internal.ConnectReply) {
txp.CrossProcessID = []byte(reply.CrossProcessID)
txp.EncodingKey = []byte(reply.EncodingKey)
txp.DistributedTracingEnabled = dt
txp.Enabled = enabled
txp.TrustedAccounts = reply.TrustedAccounts
}
// CreateCrossProcessMetadata generates request metadata that enable CAT and
// Synthetics support for an external segment.
func (txp *txnCrossProcess) CreateCrossProcessMetadata(txnName, appName string) (crossProcessMetadata, error) {
metadata := crossProcessMetadata{}
// Regardless of the user's CAT settings, if there was a synthetics header in
// the inbound request, a synthetics header should always be included in the
// outbound request headers.
if txp.IsSynthetics() {
metadata.Synthetics = txp.SyntheticsHeader
}
if txp.Enabled {
txp.SetOutbound(true)
txp.requireTripID()
id, err := txp.outboundID()
if err != nil {
return metadata, err
}
txnData, err := txp.outboundTxnData(txnName, appName)
if err != nil {
return metadata, err
}
metadata.ID = id
metadata.TxnData = txnData
}
return metadata, nil
}
// Finalise handles any end-of-transaction tasks. In practice, this simply
// means ensuring the path hash is set if it hasn't already been.
func (txp *txnCrossProcess) Finalise(txnName, appName string) error {
if txp.Enabled && txp.Used() {
_, err := txp.setPathHash(txnName, appName)
return err
}
// If there was no CAT activity, then do nothing, successfully.
return nil
}
// IsInbound returns true if the transaction had inbound CAT headers.
func (txp *txnCrossProcess) IsInbound() bool {
return 0 != (txp.Type & txnCrossProcessInbound)
}
// IsOutbound returns true if the transaction has generated outbound CAT
// headers.
func (txp *txnCrossProcess) IsOutbound() bool {
// We don't actually use this anywhere today, but it feels weird not having
// it.
return 0 != (txp.Type & txnCrossProcessOutbound)
}
// IsSynthetics returns true if the transaction had inbound Synthetics headers.
func (txp *txnCrossProcess) IsSynthetics() bool {
// Technically, this is redundant: the presence of a non-nil Synthetics
// pointer should be sufficient to determine if this is a synthetics
// transaction. Nevertheless, it's convenient to have the Type field be
// non-zero if any CAT behaviour has occurred.
return 0 != (txp.Type&txnCrossProcessSynthetics) && nil != txp.Synthetics
}
// ParseAppData decodes the given appData value.
func (txp *txnCrossProcess) ParseAppData(encodedAppData string) (*cat.AppDataHeader, error) {
if !txp.Enabled {
return nil, nil
}
if encodedAppData != "" {
rawAppData, err := deobfuscate(encodedAppData, txp.EncodingKey)
if err != nil {
return nil, err
}
appData := &cat.AppDataHeader{}
if err := json.Unmarshal(rawAppData, appData); err != nil {
return nil, err
}
return appData, nil
}
return nil, nil
}
// CreateAppData creates the appData value that should be sent with a response
// to ensure CAT operates as expected.
func (txp *txnCrossProcess) CreateAppData(name string, queueTime, responseTime time.Duration, contentLength int64) (string, error) {
// If CAT is disabled, do nothing, successfully.
if !txp.Enabled {
return "", nil
}
data, err := json.Marshal(&cat.AppDataHeader{
CrossProcessID: string(txp.CrossProcessID),
TransactionName: name,
QueueTimeInSeconds: queueTime.Seconds(),
ResponseTimeInSeconds: responseTime.Seconds(),
ContentLength: contentLength,
TransactionGUID: txp.GUID,
})
if err != nil {
return "", err
}
obfuscated, err := obfuscate(data, txp.EncodingKey)
if err != nil {
return "", err
}
return obfuscated, nil
}
// Used returns true if any CAT or Synthetics related functionality has been
// triggered on the transaction.
func (txp *txnCrossProcess) Used() bool {
return 0 != txp.Type
}
// SetInbound sets the inbound CAT flag. This function is provided only for
// internal and unit testing purposes, and should not be used outside of this
// package normally.
func (txp *txnCrossProcess) SetInbound(inbound bool) {
if inbound {
txp.Type |= txnCrossProcessInbound
} else {
txp.Type &^= txnCrossProcessInbound
}
}
// SetOutbound sets the outbound CAT flag. This function is provided only for
// internal and unit testing purposes, and should not be used outside of this
// package normally.
func (txp *txnCrossProcess) SetOutbound(outbound bool) {
if outbound {
txp.Type |= txnCrossProcessOutbound
} else {
txp.Type &^= txnCrossProcessOutbound
}
}
// SetSynthetics sets the Synthetics CAT flag. This function is provided only
// for internal and unit testing purposes, and should not be used outside of
// this package normally.
func (txp *txnCrossProcess) SetSynthetics(synthetics bool) {
if synthetics {
txp.Type |= txnCrossProcessSynthetics
} else {
txp.Type &^= txnCrossProcessSynthetics
}
}
// handleInboundRequestHeaders parses the CAT headers from the given metadata
// and updates the relevant fields on the provided TxnData.
func (txp *txnCrossProcess) handleInboundRequestHeaders(metadata crossProcessMetadata) error {
if txp.Enabled && metadata.ID != "" && metadata.TxnData != "" {
if err := txp.handleInboundRequestEncodedCAT(metadata.ID, metadata.TxnData); err != nil {
return err
}
}
if metadata.Synthetics != "" {
if err := txp.handleInboundRequestEncodedSynthetics(metadata.Synthetics); err != nil {
return err
}
}
return nil
}
func (txp *txnCrossProcess) handleInboundRequestEncodedCAT(encodedID, encodedTxnData string) error {
rawID, err := deobfuscate(encodedID, txp.EncodingKey)
if err != nil {
return err
}
rawTxnData, err := deobfuscate(encodedTxnData, txp.EncodingKey)
if err != nil {
return err
}
if err := txp.handleInboundRequestID(rawID); err != nil {
return err
}
return txp.handleInboundRequestTxnData(rawTxnData)
}
func (txp *txnCrossProcess) handleInboundRequestID(raw []byte) error {
id, err := cat.NewIDHeader(raw)
if err != nil {
return err
}
if !txp.TrustedAccounts.IsTrusted(id.AccountID) {
return errAccountNotTrusted
}
txp.SetInbound(true)
txp.ClientID = string(raw)
txp.setRequireGUID()
return nil
}
func (txp *txnCrossProcess) handleInboundRequestTxnData(raw []byte) error {
txnData := &cat.TxnDataHeader{}
if err := json.Unmarshal(raw, txnData); err != nil {
return err
}
txp.SetInbound(true)
if txnData.TripID != "" {
txp.TripID = txnData.TripID
} else {
txp.setRequireGUID()
txp.TripID = txp.GUID
}
txp.ReferringTxnGUID = txnData.GUID
txp.ReferringPathHash = txnData.PathHash
return nil
}
func (txp *txnCrossProcess) handleInboundRequestEncodedSynthetics(encoded string) error {
raw, err := deobfuscate(encoded, txp.EncodingKey)
if err != nil {
return err
}
if err := txp.handleInboundRequestSynthetics(raw); err != nil {
return err
}
txp.SyntheticsHeader = encoded
return nil
}
func (txp *txnCrossProcess) handleInboundRequestSynthetics(raw []byte) error {
synthetics := &cat.SyntheticsHeader{}
if err := json.Unmarshal(raw, synthetics); err != nil {
return err
}
// The specced behaviour here if the account isn't trusted is to disable the
// synthetics handling, but not CAT in general, so we won't return an error
// here.
if txp.TrustedAccounts.IsTrusted(synthetics.AccountID) {
txp.SetSynthetics(true)
txp.setRequireGUID()
txp.Synthetics = synthetics
}
return nil
}
func (txp *txnCrossProcess) outboundID() (string, error) {
return obfuscate(txp.CrossProcessID, txp.EncodingKey)
}
func (txp *txnCrossProcess) outboundTxnData(txnName, appName string) (string, error) {
pathHash, err := txp.setPathHash(txnName, appName)
if err != nil {
return "", err
}
data, err := json.Marshal(&cat.TxnDataHeader{
GUID: txp.GUID,
TripID: txp.TripID,
PathHash: pathHash,
})
if err != nil {
return "", err
}
return obfuscate(data, txp.EncodingKey)
}
// setRequireGUID ensures that the transaction has a valid GUID, and sets the
// nr.guid and trip ID if they are not already set. If the customer has enabled
// DistributedTracing, then the new style of guid will be set elsewhere.
func (txp *txnCrossProcess) setRequireGUID() {
if txp.DistributedTracingEnabled {
return
}
if txp.GUID != "" {
return
}
txp.GUID = fmt.Sprintf("%x", randUint64())
if txp.TripID == "" {
txp.requireTripID()
}
}
// requireTripID ensures that the transaction has a valid trip ID.
func (txp *txnCrossProcess) requireTripID() {
if !txp.Enabled {
return
}
if txp.TripID != "" {
return
}
txp.setRequireGUID()
txp.TripID = txp.GUID
}
// setPathHash generates a path hash, sets the transaction's path hash to
// match, and returns it. This function will also ensure that the alternate
// path hashes are correctly updated.
func (txp *txnCrossProcess) setPathHash(txnName, appName string) (string, error) {
pathHash, err := cat.GeneratePathHash(txp.ReferringPathHash, txnName, appName)
if err != nil {
return "", err
}
if pathHash != txp.PathHash {
if txp.PathHash != "" {
// Lazily initialise the alternate path hashes if they haven't been
// already.
if txp.AlternatePathHashes == nil {
txp.AlternatePathHashes = make(map[string]bool)
}
// The spec limits us to a maximum of 10 alternate path hashes.
if len(txp.AlternatePathHashes) < 10 {
txp.AlternatePathHashes[txp.PathHash] = true
}
}
txp.PathHash = pathHash
}
return pathHash, nil
}