-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhelpers_types.go
More file actions
executable file
·212 lines (183 loc) · 5.11 KB
/
helpers_types.go
File metadata and controls
executable file
·212 lines (183 loc) · 5.11 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
package g
import (
"context"
"os"
"runtime"
"sync"
"time"
"github.com/flarco/g/sizedwaitgroup"
cmap "github.com/orcaman/concurrent-map/v2"
"github.com/spf13/cast"
)
// Context is to manage context
type Context struct {
Ctx context.Context `json:"-"`
Cancel context.CancelFunc `json:"-"`
ErrGroup ErrorGroup `json:"-"`
Wg SizedWaitGroup `json:"-"`
Mux *sync.Mutex `json:"-"`
LockChn chan struct{} `json:"-"`
MsgChan chan map[string]any `json:"-"`
Map cmap.ConcurrentMap[string, any] `json:"map"`
with map[string]any `json:"-"` // for single log event
}
// SizedWaitGroup with separate wait groups for read & write
type SizedWaitGroup struct {
Read *sizedwaitgroup.SizedWaitGroup
Write *sizedwaitgroup.SizedWaitGroup
Limit int
}
// NewContext creates a new context
func NewContext(parentCtx context.Context, concurrencyLimits ...int) *Context {
concurrencyLimit := runtime.NumCPU()
if len(concurrencyLimits) > 0 {
concurrencyLimit = concurrencyLimits[0]
} else if os.Getenv("CONCURRENCY_LIMIT") != "" {
concurrencyLimit = cast.ToInt(os.Getenv("CONCURRENCY_LIMIT"))
}
ctx, cancel := context.WithCancel(parentCtx)
wg := SizedWaitGroup{
Limit: concurrencyLimit,
Read: sizedwaitgroup.New(concurrencyLimit),
Write: sizedwaitgroup.New(concurrencyLimit),
}
return &Context{
Ctx: ctx,
Cancel: cancel,
Wg: wg,
Mux: &sync.Mutex{},
ErrGroup: ErrorGroup{},
LockChn: make(chan struct{}),
MsgChan: make(chan map[string]any),
Map: cmap.New[any](),
}
}
const (
logKeyID = "_log_keys"
logCalledStartVal = "_DEBUG_CALLER_START=4"
)
// GlobalLogValues allows a key/values inserted in all logging events
var GlobalLogValues = cmap.New[any]()
// Wrapper to set log key/values
func (c *Context) With(KVs ...any) *Context {
c.SetLogValues(KVs...)
return c
}
// SetLogValues sets log key and value pairs
func (c *Context) SetLogValues(KVs ...any) {
logKeysMap := c.getLogKeysMap()
for k, v := range M(KVs...) {
c.Map.Set(k, v)
logKeysMap[k] = nil
}
c.Map.Set(logKeyID, logKeysMap)
}
var muxWithMap sync.Mutex
// GetLogValues gets Log values as a map
func (c *Context) GetLogValues() map[string]any {
muxWithMap.Lock()
defer muxWithMap.Unlock()
m := M()
for k, v := range GlobalLogValues.Items() {
m[k] = v
}
for k := range c.getLogKeysMap() {
m[k], _ = c.Map.Get(k)
}
for k, v := range c.with {
m[k] = v
}
c.with = nil // reset
return m
}
// getLogKeysMap gets log key map
func (c *Context) getLogKeysMap() (logKeysMap map[string]any) {
if val, ok := c.Map.Get(logKeyID); ok {
logKeysMap = val.(map[string]any)
} else {
logKeysMap = map[string]any{}
}
return logKeysMap
}
// WithNext provides KVs for only the next log event
func (c *Context) WithNext(KVs ...any) *Context {
muxWithMap.Lock()
defer muxWithMap.Unlock()
if c.with == nil {
c.with = M()
}
for k, v := range M(KVs...) {
c.with[k] = v // overwrite
}
return c
}
func (c *Context) Trace(text string, args ...any) {
Trace(text, append(args, c.GetLogValues(), logCalledStartVal)...)
}
func (c *Context) Debug(text string, args ...any) {
Debug(text, append(args, c.GetLogValues(), logCalledStartVal)...)
}
func (c *Context) Info(text string, args ...any) {
Info(text, append(args, c.GetLogValues(), logCalledStartVal)...)
}
func (c *Context) Warn(text string, args ...any) {
Warn(text, append(args, c.GetLogValues(), logCalledStartVal)...)
}
func (c *Context) Error(text string, args ...any) {
Err(text, append(args, c.GetLogValues(), logCalledStartVal)...)
}
func (c *Context) LogError(E error, args ...interface{}) bool {
return LogError(E, append(args, c.GetLogValues(), logCalledStartVal)...)
}
// SetConcurrencyLimit sets the concurrency limit
func (c *Context) SetConcurrencyLimit(concurrencyLimit int) {
c.Wg = SizedWaitGroup{
Limit: concurrencyLimit,
Read: sizedwaitgroup.New(concurrencyLimit),
Write: sizedwaitgroup.New(concurrencyLimit),
}
}
// MemBasedLimit limit the concurrency based on mem
func (c *Context) MemBasedLimit(percentLimit int) {
stats := GetMachineProcStats()
if ramPct := cast.ToInt(stats.RamPct); ramPct > percentLimit {
// loop until memory is low again
Warn("Memory based limit applied. High RAM detected: %d%%. Consider lowering CONCURRENCY setting.", ramPct)
for {
time.Sleep(2 * time.Second)
ramPct = cast.ToInt(GetMachineProcStats().RamPct)
if ramPct < percentLimit {
break
}
}
Info("Memory based limit released. Current RAM: %d%", ramPct)
}
}
// CaptureErr if err != nil, captures the error from concurent function
// and cancels the context
func (c *Context) CaptureErr(E error, args ...interface{}) bool {
if E != nil {
Trace("Context.CaptureErr => %#v", E)
if GetLogLevel() == TraceLevel {
LogError(E)
}
E = NewError(3, E, args...)
c.Cancel() // cancel context
}
return c.ErrGroup.Capture(E)
}
// Err return error if any
func (c *Context) Err() error {
if c.Ctx.Err() != nil {
c.ErrGroup.Capture(c.Ctx.Err())
}
return c.ErrGroup.Err()
}
// Lock locks mutex
func (c *Context) Lock() {
c.Mux.Lock()
}
// Unlock unlocks mutex
func (c *Context) Unlock() {
c.Mux.Unlock()
}