File: distributed_tracing_test.go

package info (click to toggle)
golang-github-newrelic-go-agent 3.15.2-9
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 8,356 kB
  • sloc: sh: 65; makefile: 6
file content (701 lines) | stat: -rw-r--r-- 22,835 bytes parent folder | download
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
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
// Copyright 2020 New Relic Corporation. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package newrelic

import (
	"encoding/json"
	"net/http"
	"reflect"
	"testing"
	"time"
)

var (
	samplePayload = payload{
		Type:                 callerTypeApp,
		Account:              "123",
		App:                  "456",
		ID:                   "myid",
		TracedID:             "mytrip",
		Priority:             0.12345,
		Timestamp:            timestampMillis(time.Now()),
		HasNewRelicTraceInfo: true,
	}
)

func TestPayloadNil(t *testing.T) {
	var support distributedTracingSupport
	out, err := acceptPayload(nil, "123", &support)
	if err != nil || out != nil {
		t.Fatal(err, out)
	}
	if !support.isEmpty() {
		t.Error("support flags expected to be empty", support)
	}
}

func TestPayloadText(t *testing.T) {
	hdrs := http.Header{}
	hdrs.Set(DistributedTraceNewRelicHeader, samplePayload.NRText())
	var support distributedTracingSupport
	out, err := acceptPayload(hdrs, "123", &support)
	if err != nil || out == nil {
		t.Fatal(err, out)
	}
	if !support.AcceptPayloadSuccess {
		t.Error("unexpected support flags", support)
	}
	out.Timestamp = samplePayload.Timestamp // account for timezone differences
	if samplePayload != *out {
		t.Fatal(samplePayload, out)
	}
}

func TestPayloadHTTPSafe(t *testing.T) {
	hdrs := http.Header{}
	hdrs.Set(DistributedTraceNewRelicHeader, samplePayload.NRHTTPSafe())
	var support distributedTracingSupport
	out, err := acceptPayload(hdrs, "123", &support)
	if err != nil || nil == out {
		t.Fatal(err, out)
	}
	if !support.AcceptPayloadSuccess {
		t.Error("unexpected support flags", support)
	}
	out.Timestamp = samplePayload.Timestamp // account for timezone differences
	if samplePayload != *out {
		t.Fatal(samplePayload, out)
	}
}

func TestTimestampMillisMarshalUnmarshal(t *testing.T) {
	var sec int64 = 111
	var millis int64 = 222
	var micros int64 = 333
	var nsecWithMicros = 1000*1000*millis + 1000*micros
	var nsecWithoutMicros = 1000 * 1000 * millis

	input := time.Unix(sec, nsecWithMicros)
	expectOutput := time.Unix(sec, nsecWithoutMicros)

	var tm timestampMillis
	tm.Set(input)
	js, err := json.Marshal(tm)
	if nil != err {
		t.Fatal(err)
	}
	var out timestampMillis
	err = json.Unmarshal(js, &out)
	if nil != err {
		t.Fatal(err)
	}
	if out.Time() != expectOutput {
		t.Fatal(out.Time(), expectOutput)
	}
}

func BenchmarkPayloadText(b *testing.B) {
	b.ReportAllocs()
	b.ResetTimer()

	for n := 0; n < b.N; n++ {
		samplePayload.NRText()
	}
}

func TestEmptyPayloadData(t *testing.T) {
	// does an empty payload json blob result in an invalid payload
	var payload payload
	fixture := []byte(`{}`)

	if err := json.Unmarshal(fixture, &payload); nil != err {
		t.Log("Could not marshall fixture data into payload")
		t.Error(err)
	}

	if err := payload.validateNewRelicData(); err == nil {
		t.Log("Expected error from empty payload data")
		t.Fail()
	}
}

func TestRequiredFieldsPayloadData(t *testing.T) {
	var payload payload
	fixture := []byte(`{
		"ty":"App",
		"ac":"123",
		"ap":"456",
		"id":"id",
		"tr":"traceID",
		"ti":1488325987402
	}`)

	if err := json.Unmarshal(fixture, &payload); nil != err {
		t.Log("Could not marshall fixture data into payload")
		t.Error(err)
	}

	if err := payload.validateNewRelicData(); err != nil {
		t.Log("Expected valid payload if ty, ac, ap, id, tr, and ti are set")
		t.Error(err)
	}
}

func TestRequiredFieldsMissingType(t *testing.T) {
	var payload payload
	fixture := []byte(`{
		"ac":"123",
		"ap":"456",
		"id":"id",
		"tr":"traceID",
		"ti":1488325987402
	}`)

	if err := json.Unmarshal(fixture, &payload); nil != err {
		t.Log("Could not marshall fixture data into payload")
		t.Error(err)
	}

	if err := payload.validateNewRelicData(); err == nil {
		t.Log("Expected error from missing Type (ty)")
		t.Fail()
	}
}

func TestRequiredFieldsMissingAccount(t *testing.T) {
	var payload payload
	fixture := []byte(`{
		"ty":"App",
		"ap":"456",
		"id":"id",
		"tr":"traceID",
		"ti":1488325987402
	}`)

	if err := json.Unmarshal(fixture, &payload); nil != err {
		t.Log("Could not marshall fixture data into payload")
		t.Error(err)
	}

	if err := payload.validateNewRelicData(); err == nil {
		t.Log("Expected error from missing Account (ac)")
		t.Fail()
	}
}

func TestRequiredFieldsMissingApp(t *testing.T) {
	var payload payload
	fixture := []byte(`{
		"ty":"App",
		"ac":"123",
		"id":"id",
		"tr":"traceID",
		"ti":1488325987402
	}`)

	if err := json.Unmarshal(fixture, &payload); nil != err {
		t.Log("Could not marshall fixture data into payload")
		t.Error(err)
	}

	if err := payload.validateNewRelicData(); err == nil {
		t.Log("Expected error from missing App (ap)")
		t.Fail()
	}
}

func TestRequiredFieldsMissingTimestamp(t *testing.T) {
	var payload payload
	fixture := []byte(`{
		"ty":"App",
		"ac":"123",
		"ap":"456",
		"tr":"traceID"
	}`)

	if err := json.Unmarshal(fixture, &payload); nil != err {
		t.Log("Could not marshall fixture data into payload")
		t.Error(err)
	}

	if err := payload.validateNewRelicData(); err == nil {
		t.Log("Expected error from missing Timestamp (ti)")
		t.Fail()
	}
}

func TestRequiredFieldsZeroTimestamp(t *testing.T) {
	var payload payload
	fixture := []byte(`{
		"ty":"App",
		"ac":"123",
		"ap":"456",
		"tr":"traceID",
		"ti":0
	}`)

	if err := json.Unmarshal(fixture, &payload); nil != err {
		t.Log("Could not marshall fixture data into payload")
		t.Error(err)
	}

	if err := payload.validateNewRelicData(); err == nil {
		t.Log("Expected error from missing Timestamp (ti)")
		t.Fail()
	}
}

func TestPayload_W3CTraceState(t *testing.T) {
	var payload payload
	fixture := []byte(`{
		"ty":"App",
		"ac":"123",
		"ap":"456",
		"tr":"traceID",
		"ti":0,
		"id":"1234567890123456",
		"tx":"6543210987654321",
		"pr":0.24689,
        "tk":"123"
	}`)

	if err := json.Unmarshal(fixture, &payload); nil != err {
		t.Log("Could not marshall fixture data into payload")
		t.Error(err)
	}
	cases := map[string]string{
		"":        "123@nr=0-0-123-456-1234567890123456-6543210987654321-0-0.24689-0",
		"a=1,b=2": "123@nr=0-0-123-456-1234567890123456-6543210987654321-0-0.24689-0,a=1,b=2",
	}
	for k, v := range cases {
		payload.NonTrustedTraceState = k
		if act := payload.W3CTraceState(); act != v {
			t.Errorf("Unexpected trace state - expected %s but got %s", v, act)
		}
	}
}

func TestProcessTraceParent(t *testing.T) {
	traceParentHdr := http.Header{
		DistributedTraceW3CTraceParentHeader: []string{"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"},
	}
	payload, err := processTraceParent(traceParentHdr)
	if nil != err {
		t.Errorf("Unexpected error for trace parent %s: %v", traceParentHdr, err)
	}
	traceID := "4bf92f3577b34da6a3ce929d0e0e4736"
	if payload.TracedID != traceID {
		t.Errorf("Unexpected Trace ID in trace parent - expected %s, got %v", traceID, payload.TracedID)
	}
	spanID := "00f067aa0ba902b7"
	if payload.ID != spanID {
		t.Errorf("Unexpected Span ID in trace parent - expected %s, got %v", spanID, payload.ID)
	}
	if payload.Sampled != nil {
		t.Errorf("Expected traceparent %s sampled to be unset, but it is not", traceParentHdr)
	}
}

func TestProcessTraceParentInvalidFormat(t *testing.T) {
	cases := []string{
		"000-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
		"0X-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
		"0-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
		"00-4bf92f3577b34da6a3ce929d-00f067aa0ba902b7-01",
		"0-4bf92f3577b34da6a3ce929d0e0e47366666666-00f067aa0ba902b7-01",
		"00-4bf92f3577b34da6a3ce929d0e0e4MMM-00f067aa0ba902b7-01",
		"00-4bf92f3577b34da6a3ce929d0e0e4736-f067aa0ba902b7-01",
		"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b711111-01",
		"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba9TTT7-01",
		"00-12345678901234567890123456789012-1234567890123456-.0",
		"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-0T",
		"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-0",
		"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-031",
	}
	for _, traceParent := range cases {
		traceParentHdr := http.Header{DistributedTraceW3CTraceParentHeader: []string{traceParent}}
		_, err := processTraceParent(traceParentHdr)
		if nil == err {
			t.Errorf("No error reported for trace parent %s", traceParent)
		}
	}
}

func TestProcessTraceState(t *testing.T) {
	var payload payload
	traceStateHdr := http.Header{
		DistributedTraceW3CTraceStateHeader: []string{"190@nr=0-2-332029-2827902-5f474d64b9cc9b2a-7d3efb1b173fecfa---1518469636035,rojo=00f067aa0ba902b7"},
	}
	processTraceState(traceStateHdr, "190", &payload)
	if payload.TrustedAccountKey != "190" {
		t.Errorf("Wrong trusted account key: expected 190 but got %s", payload.TrustedAccountKey)
	}
	if payload.Type != "Mobile" {
		t.Errorf("Wrong payload type: expected Mobile but got %s", payload.Type)
	}
	if payload.Account != "332029" {
		t.Errorf("Wrong account: expected 332029 but got %s", payload.Account)
	}
	if payload.App != "2827902" {
		t.Errorf("Wrong app ID: expected 2827902 but got %s", payload.App)
	}
	if payload.TrustedParentID != "5f474d64b9cc9b2a" {
		t.Errorf("Wrong Trusted Parent ID: expected 5f474d64b9cc9b2a but got %s", payload.ID)
	}
	if payload.TransactionID != "7d3efb1b173fecfa" {
		t.Errorf("Wrong transaction ID: expected 7d3efb1b173fecfa but got %s", payload.TransactionID)
	}
	if nil != payload.Sampled {
		t.Errorf("Payload sampled field was set when it should not be")
	}
	if payload.Priority != 0.0 {
		t.Errorf("Wrong priority: expected 0.0 but got %f", payload.Priority)
	}
	if payload.Timestamp != timestampMillis(timeFromUnixMilliseconds(1518469636035)) {
		t.Errorf("Wrong timestamp: expected 1518469636035 but got %v", payload.Timestamp)
	}
}

func TestExtractNRTraceStateEntry(t *testing.T) {
	trustedAccountID := "12345"
	trustedNRVal := "0-0-1349956-41346604-27ddd2d8890283b4-b28be285632bbc0a-1-0.246890-1569367663277"
	trustedNR := "12345@nr=" + trustedNRVal
	nonTrustedNR := "190@nr=0-2-332029-2827902-5f474d64b9cc9b2a-7d3efb1b173fecfa---1518469636035"
	cases := map[string]string{
		"rojo=00f06": "",
		// comma separator
		trustedNR + ",rojo=00f06,congo=t61":                      trustedNRVal,
		"congo=t61," + trustedNR + ",rojo=00f06":                 trustedNRVal,
		trustedNR + "," + nonTrustedNR:                           trustedNRVal,
		"rojo=00f06," + nonTrustedNR + ",congo=t61," + trustedNR: trustedNRVal,
		"rojo=00f06," + nonTrustedNR + ",congo=t61":              "",
		// comma space separator
		trustedNR + ", rojo=00f06, congo=t61":                       trustedNRVal,
		"congo=t61, " + trustedNR + ", rojo=00f06":                  trustedNRVal,
		trustedNR + ", " + nonTrustedNR:                             trustedNRVal,
		"rojo=00f06, " + nonTrustedNR + ", congo=t61, " + trustedNR: trustedNRVal,
		"rojo=00f06, " + nonTrustedNR + ", congo=t61":               "",
		// comma tab separator
		trustedNR + ",\trojo=00f06,congo=t61":                          trustedNRVal,
		"congo=t61,\t" + trustedNR + ",\trojo=00f06":                   trustedNRVal,
		trustedNR + ",\t" + nonTrustedNR:                               trustedNRVal,
		"rojo=00f06,\t" + nonTrustedNR + ",\tcongo=t61,\t" + trustedNR: trustedNRVal,
		"rojo=00f06,\t" + nonTrustedNR + ",\tcongo=t61":                "",
	}

	for test, expected := range cases {
		_, _, result := parseTraceState(test, trustedAccountID)
		if result != expected {
			t.Errorf("Expected %s but got %s", expected, result)
		}
	}
}

func TestParseTraceState(t *testing.T) {
	cases := []struct {
		// Input
		trustedAccount string
		full           string
		// Expect
		trusted          string
		expVendors       string
		expNonTrustState string
	}{
		{
			trustedAccount:   "12345",
			full:             "12345@nr=0-0-1349956-41346604-27ddd2d8890283b4-b28be285632bbc0a-1-0.246890-1569367663277,rojo=00f067aa0ba902b7,congo=t61rcWkgMzE",
			trusted:          "0-0-1349956-41346604-27ddd2d8890283b4-b28be285632bbc0a-1-0.246890-1569367663277",
			expVendors:       "rojo,congo",
			expNonTrustState: "rojo=00f067aa0ba902b7,congo=t61rcWkgMzE",
		},
		{
			trustedAccount:   "12345",
			full:             "congo=t61rcWkgMzE,12345@nr=0-0-1349956-41346604-27ddd2d8890283b4-b28be285632bbc0a-1-0.246890-1569367663277,rojo=00f067aa0ba902b7",
			trusted:          "0-0-1349956-41346604-27ddd2d8890283b4-b28be285632bbc0a-1-0.246890-1569367663277",
			expVendors:       "congo,rojo",
			expNonTrustState: "congo=t61rcWkgMzE,rojo=00f067aa0ba902b7",
		},
		{
			trustedAccount:   "12345",
			full:             "12345@nr=0-0-1349956-41346604-27ddd2d8890283b4-b28be285632bbc0a-1-0.246890-1569367663277,190@nr=0-2-332029-2827902-5f474d64b9cc9b2a-7d3efb1b173fecfa---1518469636035",
			trusted:          "0-0-1349956-41346604-27ddd2d8890283b4-b28be285632bbc0a-1-0.246890-1569367663277",
			expVendors:       "190@nr",
			expNonTrustState: "190@nr=0-2-332029-2827902-5f474d64b9cc9b2a-7d3efb1b173fecfa---1518469636035",
		},
		{
			trustedAccount:   "12345",
			full:             "atd@rojo=00f067aa0ba902b7,190@nr=0-2-332029-2827902-5f474d64b9cc9b2a-7d3efb1b173fecfa---1518469636035,congo=t61rcWkgMzE,12345@nr=0-0-1349956-41346604-27ddd2d8890283b4-b28be285632bbc0a-1-0.246890-1569367663277",
			trusted:          "0-0-1349956-41346604-27ddd2d8890283b4-b28be285632bbc0a-1-0.246890-1569367663277",
			expVendors:       "atd@rojo,190@nr,congo",
			expNonTrustState: "atd@rojo=00f067aa0ba902b7,190@nr=0-2-332029-2827902-5f474d64b9cc9b2a-7d3efb1b173fecfa---1518469636035,congo=t61rcWkgMzE",
		},
		{
			trustedAccount:   "12345",
			full:             "rojo=00f067aa0ba902b7,190@nr=0-2-332029-2827902-5f474d64b9cc9b2a-7d3efb1b173fecfa---1518469636035,fff@congo=t61rcWkgMzE",
			trusted:          "",
			expVendors:       "rojo,190@nr,fff@congo",
			expNonTrustState: "rojo=00f067aa0ba902b7,190@nr=0-2-332029-2827902-5f474d64b9cc9b2a-7d3efb1b173fecfa---1518469636035,fff@congo=t61rcWkgMzE",
		},
		{
			trustedAccount:   "12345",
			full:             "rojo=00f067aa0ba902b7",
			trusted:          "",
			expVendors:       "rojo",
			expNonTrustState: "rojo=00f067aa0ba902b7",
		},
		{
			trustedAccount:   "12345",
			full:             "",
			trusted:          "",
			expVendors:       "",
			expNonTrustState: "",
		},
		{
			trustedAccount:   "12345",
			full:             "abcdefghijklmnopqrstuvwxyz0123456789_-*/@a-z0-9_-*/= !\"#$%&'()*+-./0123456789:;<>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz",
			trusted:          "",
			expVendors:       "abcdefghijklmnopqrstuvwxyz0123456789_-*/@a-z0-9_-*/",
			expNonTrustState: "abcdefghijklmnopqrstuvwxyz0123456789_-*/@a-z0-9_-*/= !\"#$%&'()*+-./0123456789:;<>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz",
		},
	}

	for idx, tc := range cases {
		vendors, state, trusted := parseTraceState(tc.full, tc.trustedAccount)
		if vendors != tc.expVendors {
			t.Errorf("testcase %d: wrong value for vendors returned, expected=%s actual=%s",
				idx, tc.expVendors, vendors)
		}
		if state != tc.expNonTrustState {
			t.Errorf("testcase %d: wrong value for state returned, expected=%s actual=%s",
				idx, tc.expNonTrustState, state)
		}
		if trusted != tc.trusted {
			t.Errorf("testcase %d: wrong value for trust returned, expected=%s actual=%s",
				idx, tc.trusted, trusted)
		}
	}
}

// Our code assumes that the keys we are using are canoncial header keys, so we should make sure
// we don't accidentally change that.
func TestW3CKeysAreCannoncial(t *testing.T) {
	if DistributedTraceW3CTraceParentHeader != http.CanonicalHeaderKey(DistributedTraceW3CTraceParentHeader) {
		t.Error(DistributedTraceW3CTraceParentHeader + " is not canonical")
	}
	if DistributedTraceW3CTraceStateHeader != http.CanonicalHeaderKey(DistributedTraceW3CTraceStateHeader) {
		t.Error(DistributedTraceW3CTraceParentHeader + " is not canonical")
	}
}

func TestTransactionIDTraceStateField(t *testing.T) {
	// Test that tracestate headers transactionId accepts varying vales
	trustKey := "33"
	testcases := []struct {
		tracestate string
		expect     string
	}{
		{tracestate: "33@nr=0-0-33-5-1234567890123456--0-0.0-0", expect: ""},
		// TODO: support this use case which is called out specifically in the spec
		// {tracestate: "33@nr=0-0-33-5-1234567890123456-meatballs!-0-0.0-0", expect: "meatballs!"},
	}

	for _, tc := range testcases {
		p := &payload{}
		h := http.Header{
			DistributedTraceW3CTraceStateHeader: []string{tc.tracestate},
		}
		processTraceState(h, trustKey, p)
		if p.TransactionID != tc.expect {
			t.Errorf("wrong transactionId gathered: expect=%s actual=%s", tc.expect, p.TransactionID)
		}
	}
}

func TestSpanIDTraceStateField(t *testing.T) {
	// Test that tracestate headers spanId accepts varying vales
	trustKey := "33"
	testcases := []struct {
		tracestate string
		expect     string
	}{
		{tracestate: "33@nr=0-0-33-5--0123456789012345-0-0.0-0", expect: ""},
		// TODO: support this use case which is called out specifically in the spec
		// {tracestate: "33@nr=0-0-33-5-meatballs!-0123456789012345-0-0.0-0", expect: "meatballs!"},
	}

	for _, tc := range testcases {
		p := &payload{}
		h := http.Header{
			DistributedTraceW3CTraceStateHeader: []string{tc.tracestate},
		}
		processTraceState(h, trustKey, p)
		if p.TrustedParentID != tc.expect {
			t.Errorf("wrong transactionId gathered: expect=%s actual=%s", tc.expect, p.TrustedParentID)
		}
	}
}

func TestVersionTraceStateField(t *testing.T) {
	// Test that tracestate headers version accepts varying values
	trustKey := "33"
	testcases := []struct {
		tracestate string
		expAppID   string
	}{
		{
			tracestate: "33@nr=0-0-33-5-0123456789012345-5432109876543210-1-0.5-123",
			expAppID:   "5",
		},
		{
			// when version is too high we still try to parse what we can
			tracestate: "33@nr=1-0-33-5-0123456789012345-5432109876543210-1-0.5-123-extra-fields",
			expAppID:   "5",
		},
	}

	for _, tc := range testcases {
		p := &payload{}
		h := http.Header{
			DistributedTraceW3CTraceStateHeader: []string{tc.tracestate},
		}
		processTraceState(h, trustKey, p)
		if p.App != tc.expAppID {
			t.Errorf("wrong application id set on payload: expect=%s actual=%s", tc.expAppID, p.App)
		}
	}
}

func TestPayloadIsSampled(t *testing.T) {
	p := &payload{}
	if s := p.isSampled(); s {
		t.Error(s)
	}
	p.SetSampled(true)
	if s := p.isSampled(); !s {
		t.Error(s)
	}
	p.SetSampled(false)
	if s := p.isSampled(); s {
		t.Error(s)
	}
}

func TestTraceStateSpanTxnIDs(t *testing.T) {
	// Test that we cover this case as stated in the spec for the tracestate
	// header:
	// Conforming agents should not require any particular format of this
	// string on inbound payloads beyond receiving non-delimiter characters
	// that are valid in a tracestate header entry. meatball! is an acceptable
	// spanId or transactionId.

	hdrs := http.Header{
		DistributedTraceW3CTraceParentHeader: []string{"00-52fdfc072182654f163f5f0f9a621d72-9566c74d10d1e2c6-01"},
		DistributedTraceW3CTraceStateHeader:  []string{"123@nr=0-0-123-456-meatball!-meatballs!-1-0.43771-1577830891900"},
	}
	var support distributedTracingSupport
	p, err := acceptPayload(hdrs, "123", &support)
	if err != nil {
		t.Error("failure to AcceptPayload:", err)
	}
	if !support.TraceContextAcceptSuccess {
		t.Error("unexpected support flags", support)
	}
	if p.TrustedParentID != "meatball!" {
		t.Error("wrong payload ID", p.ID)
	}
	if p.TransactionID != "meatballs!" {
		t.Error("wrong payload TransactionID", p.TransactionID)
	}
}

func TestAcceptMultipleTraceParentHeaders(t *testing.T) {
	// Test that when multiple traceparent headers are received, we discard the
	// headers all together.  From
	// https://github.com/w3c/trace-context/blob/3d02cfc15778ef850df9bc4e9d2740a4a2627fd5/test/test.py#L134
	sup := new(distributedTracingSupport)
	hdrs := http.Header{
		DistributedTraceW3CTraceParentHeader: []string{
			"00-01234567890123456789012345678901-0123456789012345-01",
			"00-01234567890123456789012345678902-0123456789012346-01",
		},
	}
	_, err := acceptPayload(hdrs, "123", sup)
	if err == nil {
		t.Error("error should have been returned")
	}
}

func TestAcceptW3CSuccess(t *testing.T) {
	hdrs := http.Header{
		DistributedTraceW3CTraceParentHeader: []string{
			"00-11223344556677889900aabbccddeeff-0aaabbbcccdddeee-01",
		},
		DistributedTraceW3CTraceStateHeader: []string{
			"atd@rojo=00f067aa0ba902b7,190@nr=0-2-332029-2827902-5f474d64b9cc9b2a-7d3efb1b173fecfa---1518469636035,congo=t61rcWkgMzE,12345@nr=0-0-1349956-41346604-27ddd2d8890283b4-b28be285632bbc0a-1-0.246890-1569367663277",
		},
	}
	trustedAccountKey := "12345"
	support := distributedTracingSupport{}
	p, err := acceptPayload(hdrs, trustedAccountKey, &support)
	if err != nil {
		t.Fatal(err)
	}
	truePtr := true
	expect := &payload{
		Type:                 "App",
		App:                  "41346604",
		Account:              "1349956",
		TransactionID:        "b28be285632bbc0a",
		ID:                   "0aaabbbcccdddeee",
		TracedID:             "11223344556677889900aabbccddeeff",
		Priority:             0.24689,
		Sampled:              &truePtr,
		Timestamp:            timestampMillis(timeFromUnixMilliseconds(1569367663277)),
		TransportDuration:    0,
		TrustedParentID:      "27ddd2d8890283b4",
		TracingVendors:       "atd@rojo,190@nr,congo",
		HasNewRelicTraceInfo: true,
		TrustedAccountKey:    "12345",
		NonTrustedTraceState: "atd@rojo=00f067aa0ba902b7,190@nr=0-2-332029-2827902-5f474d64b9cc9b2a-7d3efb1b173fecfa---1518469636035,congo=t61rcWkgMzE",
		OriginalTraceState:   "atd@rojo=00f067aa0ba902b7,190@nr=0-2-332029-2827902-5f474d64b9cc9b2a-7d3efb1b173fecfa---1518469636035,congo=t61rcWkgMzE,12345@nr=0-0-1349956-41346604-27ddd2d8890283b4-b28be285632bbc0a-1-0.246890-1569367663277",
	}
	if !reflect.DeepEqual(p, expect) {
		t.Errorf("%#v", p)
	}
}

func BenchmarkAcceptW3C(b *testing.B) {
	hdrs := http.Header{
		DistributedTraceW3CTraceParentHeader: []string{
			"00-11223344556677889900aabbccddeeff-0aaabbbcccdddeee-01",
		},
		DistributedTraceW3CTraceStateHeader: []string{
			"atd@rojo=00f067aa0ba902b7,190@nr=0-2-332029-2827902-5f474d64b9cc9b2a-7d3efb1b173fecfa---1518469636035,congo=t61rcWkgMzE,12345@nr=0-0-1349956-41346604-27ddd2d8890283b4-b28be285632bbc0a-1-0.246890-1569367663277",
		},
	}
	trustedAccountKey := "12345"
	support := distributedTracingSupport{}

	b.ReportAllocs()
	b.ResetTimer()

	for n := 0; n < b.N; n++ {
		_, err := acceptPayload(hdrs, trustedAccountKey, &support)
		if err != nil {
			b.Fatal(err)
		}
	}
}

func Test_processTraceState_invalidEntry(t *testing.T) {
	payload := payload{}
	hdrs := http.Header{
		DistributedTraceW3CTraceStateHeader: []string{"33@nr=-0-33-2827902-b4a146e3237b4df1-e8b91a159289ff74-1-1.23456-1518469636035"},
	}

	err := processTraceState(hdrs, "33", &payload)
	if err == nil || err != errInvalidNRTraceState {
		t.Errorf("expected invalidNRTraceState error but got %v", err)
	}
}