Debian Codegraph @

assert/tracker.go

raw
1 //go:build !no_antithesis_sdk
2
3 package assert
4
5 import (
6 "sync"
7 "sync/atomic"
8
9 "github.com/antithesishq/antithesis-sdk-go/internal"
10 )
11
12 // Tracking info for one assertion id.
13 type trackerInfo struct {
14 Filename string
15 Classname string
16
17 passEmitted atomic.Bool
18 failEmitted atomic.Bool
19 // Serializes only first-emission attempts (including retries after an
20 // emission error); never taken once a flag is set.
21 emitMutex sync.Mutex
22 }
23
24 // assertTracker keeps track of the unique asserts evaluated.
25 var assertTracker sync.Map // message key -> *trackerInfo
26
27 func getTrackerEntry(messageKey string, filename string, classname string) *trackerInfo {
28 if entry, ok := assertTracker.Load(messageKey); ok {
29 return entry.(*trackerInfo)
30 }
31 entry, _ := assertTracker.LoadOrStore(messageKey,
32 &trackerInfo{Filename: filename, Classname: classname})
33 return entry.(*trackerInfo)
34 }
35
36 func (ti *trackerInfo) emit(ai *assertInfo) {
37 if ti == nil || ai == nil {
38 return
39 }
40
41 // Registrations are just sent to voidstar
42 if !ai.Hit {
43 emitAssert(ai)
44 return
45 }
46
47 flag := &ti.passEmitted
48 if !ai.Condition {
49 flag = &ti.failEmitted
50 }
51 if flag.Load() {
52 return
53 }
54 ti.emitMutex.Lock()
55 defer ti.emitMutex.Unlock()
56 if flag.Load() {
57 return
58 }
59 // The flag is only set on success, so an assertion whose emission
60 // failed is retried on its next evaluation (as before).
61 if emitAssert(ai) == nil {
62 flag.Store(true)
63 }
64 }
65
66 // Whether this assertion id has already emitted for this condition — i.e.
67 // whether an evaluation can return before capturing its location.
68 func trackerEmitted(id string, condition bool) bool {
69 entry, ok := assertTracker.Load(id)
70 if !ok {
71 return false
72 }
73 ti := entry.(*trackerInfo)
74 if condition {
75 return ti.passEmitted.Load()
76 }
77 return ti.failEmitted.Load()
78 }
79
80 func emitAssert(ai *assertInfo) error {
81 // The version message is emitted by the internal package when the
82 // handler initializes, before any output can happen.
83 return internal.Json_data(wrappedAssertInfo{ai})
84 }