-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathokx_test.go
More file actions
277 lines (249 loc) · 6.95 KB
/
Copy pathokx_test.go
File metadata and controls
277 lines (249 loc) · 6.95 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
package browserpm
import (
"context"
"encoding/json"
"fmt"
"net/url"
"strconv"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/playwright-community/playwright-go"
)
// --- OKX helpers ---
func buildURL(base string, params map[string]string) string {
values := url.Values{}
for k, v := range params {
values.Set(k, v)
}
return base + "?" + values.Encode()
}
func nowMillis() string {
return strconv.FormatInt(time.Now().UnixMilli(), 10)
}
func buildCommunityPositionsURL(baseURL string, uniqueName string) string {
if baseURL == "" {
baseURL = "https://www.okx.com"
}
base := baseURL + "/priapi/v5/ecotrade/public/community/user/position-current"
params := map[string]string{
"uniqueName": uniqueName,
"t": nowMillis(),
}
return buildURL(base, params)
}
// ontGet calls OKX's window.utils.ont.get via page.Evaluate.
func ontGet(page playwright.Page, apiURL string) (map[string]interface{}, error) {
if page == nil || page.IsClosed() {
return nil, fmt.Errorf("page is closed or nil")
}
result, err := page.Evaluate(
`u => window.utils.ont.get(u).catch(e=>({error:e.message||String(e)}))`,
apiURL,
)
if err != nil {
return nil, fmt.Errorf("evaluate failed for url=%s: %w", apiURL, err)
}
resp, ok := result.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("unexpected response type %T for url=%s", result, apiURL)
}
if errMsg, hasErr := resp["error"]; hasErr {
return nil, fmt.Errorf("API error for url=%s: %s", apiURL, formatErrorValue(errMsg))
}
return resp, nil
}
func formatErrorValue(v interface{}) string {
switch val := v.(type) {
case string:
return val
case map[string]interface{}:
if msg, ok := val["message"].(string); ok {
return msg
}
if msg, ok := val["msg"].(string); ok {
return msg
}
if jsonBytes, err := json.Marshal(val); err == nil {
return string(jsonBytes)
}
return fmt.Sprintf("%+v", val)
default:
return fmt.Sprintf("%v", val)
}
}
// --- OKX Context & Page Providers ---
func okxContextProvider() ContextProvider {
return NewContextProvider(
playwright.BrowserNewContextOptions{
UserAgent: playwright.String("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"),
},
nil,
)
}
func okxPageProvider() PageProvider {
return NewPageProvider(
func(ctx context.Context, page playwright.Page) error {
_, err := page.Goto("https://www.okx.com", playwright.PageGotoOptions{
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
Timeout: playwright.Float(60000),
})
if err != nil {
return fmt.Errorf("goto okx.com failed: %w", err)
}
_, err = page.WaitForFunction(
`() => window.utils?.ont?.get !== undefined`,
playwright.PageWaitForFunctionOptions{Timeout: playwright.Float(60000)},
)
if err != nil {
return fmt.Errorf("wait for ont.get failed: %w", err)
}
return nil
},
func(ctx context.Context, page playwright.Page) bool {
if page.IsClosed() {
return false
}
result, err := page.Evaluate(`() => typeof window.utils?.ont?.get === 'function'`)
if err != nil {
return false
}
ok, _ := result.(bool)
return ok
},
)
}
// TestOKX is the main integration test for OKX ontGet high-concurrency monitoring.
//
// Configuration summary (from exhaustive optimisation):
//
// Baseline: 77 QPS (5 pages, 50 concurrency, single ontGet)
// Optimised: 3813 QPS (1 page, 1000 concurrency, batch100 Promise.all)
// Improvement: ~50x
//
// Key findings:
// - Fewer pages (1-3) outperform more pages (10-15) because the browser
// process handles concurrent async JS natively.
// - Batch Evaluate (Promise.all) is the biggest single improvement (~5-10x)
// by reducing CDP round-trips.
// - Higher concurrency (500-1000 goroutines) keeps more requests in-flight.
func TestOKX(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
const (
pageCount = 1
concurrency = 1000
totalCalls = 2000
batchSize = 100
uniqueName = "E512EAA2C34FAF44"
)
manager, err := New(
WithHeadless(true),
WithAutoInstall(false),
WithMinPages(pageCount),
WithMaxPages(pageCount),
WithPoolTTL(30*time.Minute),
WithOperationTimeout(90*time.Second),
WithInitTimeout(90*time.Second),
WithHealthCheckInterval(10*time.Minute),
)
if err != nil {
t.Fatalf("failed to create manager: %v", err)
}
defer manager.Close()
session, err := manager.CreateSession("okx", okxContextProvider(), okxPageProvider())
if err != nil {
t.Fatalf("failed to create session: %v", err)
}
ctx := context.Background()
// Warm up: verify single call works.
warmURL := buildCommunityPositionsURL("", uniqueName)
err = session.DoShare(ctx, func(page playwright.Page) error {
resp, err := ontGet(page, warmURL)
if err != nil {
return err
}
t.Logf("warm-up response keys: %v", resp)
return nil
})
if err != nil {
t.Fatalf("warm-up call failed: %v", err)
}
// Stress test with batch Promise.all.
var (
successCount atomic.Int64
errorCount atomic.Int64
wg sync.WaitGroup
sem = make(chan struct{}, concurrency)
)
batches := totalCalls / batchSize
start := time.Now()
for i := 0; i < batches; i++ {
wg.Add(1)
sem <- struct{}{}
go func() {
defer wg.Done()
defer func() { <-sem }()
urls := make([]string, batchSize)
for j := range urls {
urls[j] = buildCommunityPositionsURL("", uniqueName)
}
err := session.DoShare(ctx, func(page playwright.Page) error {
result, err := page.Evaluate(
`urls => Promise.all(urls.map(u => window.utils.ont.get(u).catch(e=>({error:e.message||String(e)}))))`,
urls,
)
if err != nil {
return err
}
arr, ok := result.([]interface{})
if !ok {
return fmt.Errorf("unexpected type %T", result)
}
for _, item := range arr {
m, _ := item.(map[string]interface{})
if m == nil {
errorCount.Add(1)
} else if _, has := m["error"]; has {
errorCount.Add(1)
} else {
successCount.Add(1)
}
}
t.Logf("warm-up response keys: %v", result)
return nil
})
if err != nil {
errorCount.Add(int64(batchSize))
}
}()
}
wg.Wait()
elapsed := time.Since(start)
success := successCount.Load()
errors := errorCount.Load()
qps := float64(success) / elapsed.Seconds()
t.Logf("=== OKX Stress Test Results ===")
t.Logf("Pages: %d", pageCount)
t.Logf("Concurrency: %d", concurrency)
t.Logf("Batch size: %d", batchSize)
t.Logf("Total calls: %d", totalCalls)
t.Logf("Success: %d", success)
t.Logf("Errors: %d", errors)
t.Logf("Elapsed: %s", elapsed.Round(time.Millisecond))
t.Logf("QPS: %.1f", qps)
info := session.Status()
t.Logf("Session: state=%s pages=%d active_ops=%d", info.State, info.PageCount, info.ActiveOps)
if success == 0 {
t.Fatal("all calls failed")
}
}
func mapKeys(m map[string]interface{}) []string {
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
return keys
}