Repository navigation
Expand file tree
/
Copy pathserver.rs
More file actions
2880 lines (2649 loc) · 135 KB
/
Copy pathserver.rs
File metadata and controls
2880 lines (2649 loc) · 135 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
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
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::convert::Infallible;
use std::net::SocketAddr;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use chrono::TimeZone;
use rust_decimal::Decimal;
use axum::extract::{Path, Query, State};
use axum::response::sse::{Event, Sse};
use axum::response::{Html, IntoResponse, Json};
use axum::routing::get;
use axum::Router;
use tokio_stream::StreamExt;
use arb_common::types::ExchangeId;
use super::auth::AuthDb;
use super::extended_api::ExtendedApi;
use super::extractors::Session;
use super::state::DashState;
use super::web_storage::WebStorage;
#[derive(Clone)]
pub struct AppState {
pub dash: Arc<DashState>,
pub auth: Arc<Mutex<AuthDb>>,
pub extended_api: Option<ExtendedApi>,
/// Raw db_path retained for: (a) the SSE snapshot enrichment helper which
/// is invoked from inside `spawn_blocking` and prefers a one-shot open,
/// and (b) long-running background tasks in `web::optimizer` /
/// `web::backtest` that need their own private connection. Day-to-day
/// per-request handlers should use `web_db` instead.
pub db_path: &'static str,
/// Shared SQLite connection for short-lived web request handlers.
/// See `web::web_storage::WebStorage` doc for the rationale.
pub web_db: WebStorage,
/// Active symbols from exchange_symbols DB table (loaded once at startup).
pub active_symbols: Arc<Vec<String>>,
/// Serializes concurrent credential edits so two admins cannot race a
/// read-modify-write on `.env`. Held for the whole save flow (pause →
/// validate → write).
pub credentials_write_lock: Arc<tokio::sync::Mutex<()>>,
/// Simple per-session rate limiter for credential endpoints. Maps
/// user_id → timestamps of recent hits. Caller trims old entries.
pub credentials_rate: Arc<std::sync::Mutex<std::collections::HashMap<i64, Vec<std::time::Instant>>>>,
/// Snapshot of every exchange's `orderbook_depth` as it was at process
/// start. Hot reload compares new TOML values against this map — any
/// divergence means the live WS clients still hold the old subscription
/// URL and the change requires a full bot restart to take effect.
pub boot_orderbook_depths: Arc<std::collections::HashMap<String, crate::config::OrderbookDepth>>,
/// Snapshot of every exchange's `ws_ob_mode` as it was at process start.
/// Like `boot_orderbook_depths`: WS connection topology (single all-markets
/// vs one-per-symbol) is decided when the OB client task spawns, so a
/// hot-reload flip is silently ineffective until restart.
pub boot_ws_ob_modes: Arc<std::collections::HashMap<String, crate::config::WsObMode>>,
/// Rolling Tick→Recv histogram per exchange. Written by the executor
/// on every market update (lock-free); read here on every `/api/state`
/// call to produce the dashboard snapshot.
pub tick_latency: Arc<crate::metrics::tick_latency::TickLatencyTracker>,
/// Exchanges deliberately excluded from `tick_latency` at startup
/// (e.g. Zero1 which doesn't publish event timestamps). Surfaced in
/// the JSON snapshot so the UI can render greyed-out rows with a
/// tooltip instead of silently hiding the venue.
pub tick_latency_untracked: Arc<Vec<crate::metrics::tick_latency::TickLatencyUntrackedEntry>>,
}
/// Start the web dashboard server. Runs until the process exits.
pub async fn start(
dash_state: Arc<DashState>,
auth_db: Arc<Mutex<AuthDb>>,
extended_api: Option<ExtendedApi>,
addr: SocketAddr,
db_path: &'static str,
boot_orderbook_depths: std::collections::HashMap<String, crate::config::OrderbookDepth>,
boot_ws_ob_modes: std::collections::HashMap<String, crate::config::WsObMode>,
tick_latency: Arc<crate::metrics::tick_latency::TickLatencyTracker>,
tick_latency_untracked: Vec<crate::metrics::tick_latency::TickLatencyUntrackedEntry>,
) -> anyhow::Result<()> {
let dash_for_shutdown = dash_state.clone();
let active_symbols = Arc::new({
let db = crate::storage::sqlite::Storage::open(db_path)?;
db.load_pairs_params().active_symbols()
});
let web_db = WebStorage::new(db_path)?;
let state = AppState {
dash: dash_state,
auth: auth_db,
extended_api,
db_path,
web_db,
active_symbols,
credentials_write_lock: Arc::new(tokio::sync::Mutex::new(())),
credentials_rate: Arc::new(std::sync::Mutex::new(std::collections::HashMap::new())),
boot_orderbook_depths: Arc::new(boot_orderbook_depths),
boot_ws_ob_modes: Arc::new(boot_ws_ob_modes),
tick_latency,
tick_latency_untracked: Arc::new(tick_latency_untracked),
};
let app = Router::new()
// Public routes (no auth)
.route("/login", get(login_page))
.route("/api/auth/login", axum::routing::post(super::auth_routes::login))
// Auth management (require session)
.route("/api/auth/logout", axum::routing::post(super::auth_routes::logout))
.route("/api/auth/me", get(super::auth_routes::me))
.route("/api/auth/password", axum::routing::post(super::auth_routes::change_password))
// App routes (require session + permissions)
.route("/", get(index))
.route("/app.js", get(app_js))
.route("/api/state", get(api_state))
.route("/api/events", get(sse_events))
.route("/api/log", get(api_log))
.route("/api/logs/list", get(api_logs_list))
.route("/api/logs/download/{filename}", get(api_logs_download))
.route("/api/logs/download-session/{session_id}", get(api_logs_download_session))
.route("/api/logs/download-all", get(api_logs_download_all))
.route("/api/config", get(api_get_config).post(api_set_config))
.route("/api/credentials/schemas", get(api_credentials_schemas))
.route("/api/credentials", get(api_credentials_get))
.route("/api/credentials/{exchange_id}", axum::routing::post(api_credentials_save))
.route("/api/credentials/{exchange_id}/test", axum::routing::post(api_credentials_test))
.route("/api/restart", axum::routing::post(api_restart))
.route("/api/restart/binaries", get(api_restart_binaries))
.route("/api/shutdown", axum::routing::post(api_shutdown))
.route("/api/close-all", axum::routing::post(api_close_all))
.route("/api/close-trade/{trade_id}", axum::routing::post(api_close_trade))
.route("/api/halt/pause", axum::routing::post(api_halt_pause))
.route("/api/halt/resume", axum::routing::post(api_halt_resume))
.route("/api/halt/resume-api", axum::routing::post(api_halt_resume_api))
// History (cross-session)
.route("/api/history/sessions", get(api_history_sessions))
.route("/api/history/sessions/{id}/trades", get(api_history_session_trades))
// Extended exchange data (rewards/leaderboard only — funding moved to Parquet)
.route("/api/extended/rewards", get(api_extended_rewards))
// Backtest
.route("/api/backtest", axum::routing::post(super::backtest::api_backtest_run))
.route("/api/backtest/dates", get(super::backtest::api_backtest_dates))
.route("/api/backtest/symbols", get(super::backtest::api_backtest_symbols))
.route("/api/backtest/config", get(super::backtest::api_backtest_config))
.route("/api/backtest/history", get(super::backtest::api_backtest_history_list))
.route("/api/backtest/history/{filename}", get(super::backtest::api_backtest_history_get))
// Optimizer
.route("/api/optimizer/config", get(super::optimizer::api_optimizer_config))
.route("/api/optimizer/symbols", get(super::optimizer::api_optimizer_symbols))
.route("/api/optimizer/start", axum::routing::post(super::optimizer::api_optimizer_start))
.route("/api/optimizer/running", get(super::optimizer::api_optimizer_running))
.route("/api/optimizer/simulate", axum::routing::post(super::optimizer::api_optimizer_simulate))
.route("/api/optimizer/cancel", axum::routing::post(super::optimizer::api_optimizer_cancel))
.route("/api/optimizer/runs", get(super::optimizer::api_optimizer_runs))
.route("/api/optimizer/runs/{id}", get(super::optimizer::api_optimizer_run_detail))
.route("/api/optimizer/apply", axum::routing::post(super::optimizer::api_optimizer_apply))
.route("/api/optimizer/tick-stats/{symbol}", get(super::optimizer::api_optimizer_tick_stats))
// Config sync (push to remote servers)
.route("/api/servers", get(api_get_servers))
.route("/api/config/snapshot", get(api_config_snapshot))
.route("/api/config/push", axum::routing::post(api_config_push))
.route("/api/config/hot-reload", axum::routing::post(api_config_hot_reload))
// Symbol overrides
.route("/api/symbol-overrides", get(api_get_symbol_overrides).post(api_set_symbol_override))
.route("/api/symbol-overrides/{symbol}/{ex1}/{ex2}", axum::routing::delete(api_delete_symbol_override))
// Symbol blocks (disable/enable trading per symbol)
.route("/api/symbol-blocks", get(api_get_symbol_blocks).post(api_create_symbol_block))
.route("/api/symbol-blocks/{id}", axum::routing::delete(api_delete_symbol_block))
// Admin routes
.route("/api/auth/users", get(super::auth_routes::list_users).post(super::auth_routes::create_user))
.route("/api/auth/users/{id}", axum::routing::put(super::auth_routes::update_user).delete(super::auth_routes::delete_user))
.route("/api/auth/roles", get(super::auth_routes::list_roles).post(super::auth_routes::create_role))
.route("/api/auth/roles/{name}", axum::routing::put(super::auth_routes::update_role).delete(super::auth_routes::delete_role))
.with_state(state);
// SO_REUSEADDR: allow binding even if the port is in TIME_WAIT from previous process.
// Without this, restart fails with "Address already in use" for up to 120s on macOS.
let socket = socket2::Socket::new(
if addr.is_ipv6() { socket2::Domain::IPV6 } else { socket2::Domain::IPV4 },
socket2::Type::STREAM,
Some(socket2::Protocol::TCP),
)?;
socket.set_reuse_address(true)?;
socket.set_nonblocking(true)?;
socket.bind(&addr.into())?;
socket.listen(1024)?;
let listener = tokio::net::TcpListener::from_std(socket.into())?;
tracing::info!(%addr, "Web dashboard listening");
// Web server runs until process is killed by bot_start.sh.
// SO_REUSEADDR + retry ensures new process can bind even while old holds port.
// No graceful shutdown — keeps serving dashboard during cargo build (~2min).
let _ = dash_for_shutdown; // used by engine shutdown, not web server
axum::serve(listener, app.into_make_service_with_connect_info::<SocketAddr>()).await?;
Ok(())
}
/// Serve login.html from disk (hot-reloadable) with compiled fallback.
async fn login_page() -> Html<String> {
if let Ok(content) = tokio::fs::read_to_string("bot/src/web/login.html").await {
return Html(content);
}
Html(include_str!("login.html").to_string())
}
/// Serve app.html — requires valid session, otherwise redirects to /login.
async fn index(
State(state): State<AppState>,
headers: axum::http::HeaderMap,
) -> impl IntoResponse {
// Check session server-side — redirect to login if invalid
let authenticated = super::extractors::extract_session_token(&headers)
.and_then(|token| {
let auth = state.auth.lock().ok()?;
auth.validate_session(&token).ok().flatten()
})
.is_some();
if !authenticated {
return axum::response::Redirect::to("/login").into_response();
}
let html = if let Ok(content) = tokio::fs::read_to_string("bot/src/web/app.html").await {
content
} else {
include_str!("app.html").to_string()
};
Html(html).into_response()
}
/// Serve app.js — requires valid session.
async fn app_js(
State(state): State<AppState>,
headers: axum::http::HeaderMap,
) -> impl IntoResponse {
let authenticated = super::extractors::extract_session_token(&headers)
.and_then(|token| {
let auth = state.auth.lock().ok()?;
auth.validate_session(&token).ok().flatten()
})
.is_some();
if !authenticated {
return axum::response::Redirect::to("/login").into_response();
}
let js = if let Ok(content) = tokio::fs::read_to_string("bot/src/web/app.js").await {
content
} else {
include_str!("app.js").to_string()
};
([("content-type", "application/javascript")], js).into_response()
}
async fn api_state(session: Session, State(state): State<AppState>) -> impl IntoResponse {
if let Err(e) = session.require_permission("dashboard.view") { return e.into_response(); }
let mut snapshot = state.dash.read();
// Enrich with SQLite data via the shared web connection (was opening
// a fresh read-only conn per request, ~3 transient FDs each).
let result = state.web_db.run(move |db| {
let enrich_result = enrich_snapshot(&mut snapshot, db);
let balance_delta = compute_balance_delta(&snapshot, db);
(snapshot, enrich_result.is_ok(), balance_delta)
}).await;
let (snap, _ok, balance_delta) = result;
// Attach the per-exchange Tick→Recv snapshot. The tracker lives in the
// executor's hot path and is unaffected by the DashSnapshot rebuild
// cadence — we just pull a fresh view here on every API call. Merging
// into the parent JSON keeps the dashboard on a single poll path.
let mut tick_snap = state.tick_latency.snapshot();
tick_snap.untracked = (*state.tick_latency_untracked).clone();
let mut body = match serde_json::to_value(&snap) {
Ok(v) => v,
Err(e) => {
tracing::warn!(error = %e, "api_state: snapshot serialize failed");
return Json(snap).into_response();
}
};
if let Some(obj) = body.as_object_mut() {
match serde_json::to_value(&tick_snap) {
Ok(v) => { obj.insert("tick_latency".to_string(), v); }
Err(e) => tracing::warn!(error = %e, "api_state: tick_latency serialize failed"),
}
match serde_json::to_value(&balance_delta) {
Ok(v) => { obj.insert("balance_delta".to_string(), v); }
Err(e) => tracing::warn!(error = %e, "api_state: balance_delta serialize failed"),
}
}
Json(body).into_response()
}
/// Balance Δ = Σ current equity − Σ session-start equity. Sanity check
/// against Σ trade.pnl (computed through `derive_pnl`). When the two
/// disagree, accounting is losing fills somewhere — the 2026-04-18 MEGA
/// orphan scenario.
///
/// Returns per-exchange breakdown so the user sees WHICH exchange drifted.
/// Uses current `ExchangeHealthSnap.equity` as "current" (already fetched
/// by the periodic `refresh_balances` task) and the
/// `session_start_balances` table as "start". Exchanges missing from one
/// side contribute 0 to that side.
#[derive(serde::Serialize)]
struct BalanceDeltaEntry {
exchange: String,
start_usd: String,
current_usd: String,
delta_usd: String,
}
#[derive(serde::Serialize)]
struct BalanceDeltaSummary {
/// True when we have both start + current for at least one exchange.
/// Sessions that predate the feature report `available=false` and the
/// UI should render "n/a" rather than a misleading zero delta.
available: bool,
total_start_usd: String,
total_current_usd: String,
total_delta_usd: String,
per_exchange: Vec<BalanceDeltaEntry>,
}
fn compute_balance_delta(
snap: &crate::web::state::DashSnapshot,
db: &crate::storage::sqlite::Storage,
) -> BalanceDeltaSummary {
use rust_decimal::Decimal;
use std::str::FromStr;
let session_id = snap.session_id as i64;
let starts: std::collections::HashMap<i64, Decimal> = match db.load_session_start_balances(session_id) {
Ok(rows) => rows.into_iter().collect(),
Err(e) => {
tracing::warn!(session_id, error = %e, "compute_balance_delta: load start balances failed");
std::collections::HashMap::new()
}
};
let mut total_start = Decimal::ZERO;
let mut total_current = Decimal::ZERO;
let mut per_exchange: Vec<BalanceDeltaEntry> = Vec::new();
let mut any_known = false;
// Resolve name → id once from the `exchanges` table (seeded with
// lighter=1, extended=2, zero1=3, hyperliquid=4 and any hot-registered
// others). Avoids a query per exchange below.
let name_to_id: std::collections::HashMap<String, i64> = db
.load_exchange_ids()
.unwrap_or_default()
.into_iter()
.collect();
for ex in &snap.health.exchanges {
let Some(&exchange_id) = name_to_id.get(&ex.name) else { continue; };
let start = starts.get(&exchange_id).copied().unwrap_or(Decimal::ZERO);
let current = ex
.equity
.as_deref()
.and_then(|s| Decimal::from_str(s.trim()).ok())
.unwrap_or(Decimal::ZERO);
if !start.is_zero() || !current.is_zero() {
any_known = true;
}
total_start += start;
total_current += current;
per_exchange.push(BalanceDeltaEntry {
exchange: ex.name.clone(),
start_usd: start.to_string(),
current_usd: current.to_string(),
delta_usd: (current - start).to_string(),
});
}
BalanceDeltaSummary {
available: any_known && !starts.is_empty(),
total_start_usd: total_start.to_string(),
total_current_usd: total_current.to_string(),
total_delta_usd: (total_current - total_start).to_string(),
per_exchange,
}
}
/// Log tail endpoint: returns last N lines from latest bot log.
#[derive(serde::Deserialize)]
struct LogQuery {
#[serde(default = "default_log_lines")]
lines: usize,
}
fn default_log_lines() -> usize { 1000 }
/// Cap on how many lines a single `/api/log` call may request. Prevents a
/// caller from forcing the server to read an arbitrarily large prefix of
/// the log file (memory + IO DoS).
const MAX_LOG_LINES: usize = 5000;
/// Approximate average log line length in bytes — used to size the initial
/// tail-read window. Production lines are 100-200 bytes; we round up so the
/// usual case fits in one read without seeking back further.
const LOG_LINE_AVG_BYTES: usize = 256;
async fn api_log(session: Session, Query(q): Query<LogQuery>) -> impl IntoResponse {
if let Err(e) = session.require_permission("log.view") { return e.into_response(); }
let want = q.lines.clamp(1, MAX_LOG_LINES);
let path = format!("{}/latest.log", arb_common::constants::LOG_DIR);
// Tail-read: previously this handler `read_to_string`'d the whole log
// file (often 8+ MB) on every poll, allocated a Vec<&str> for ALL
// lines, and discarded everything except the last N. With the dashboard
// auto-refreshing every few seconds that became sustained memory churn
// and a contributing factor in the FD exhaustion incident on the
// server. Now we seek to near the end and grow the read window only if
// the requested line count isn't satisfied.
let result = match tail_read_lines(&path, want).await {
Ok(v) => v,
Err(e) => {
tracing::warn!(error = %e, path = %path, "api_log: tail_read_lines failed");
return Json(serde_json::json!({ "lines": Vec::<String>::new(), "total": 0 })).into_response();
}
};
Json(serde_json::json!({
"lines": result.lines,
"total": result.total_lines_in_window,
})).into_response()
}
struct TailReadResult {
lines: Vec<String>,
/// Number of lines present in the window we actually scanned. Not the
/// total lines in the whole file (we deliberately don't scan the whole
/// file). The dashboard treats this as informational only.
total_lines_in_window: usize,
}
async fn tail_read_lines(path: &str, want: usize) -> std::io::Result<TailReadResult> {
use tokio::io::{AsyncReadExt, AsyncSeekExt, SeekFrom};
let mut file = tokio::fs::File::open(path).await?;
let file_size = file.metadata().await?.len();
if file_size == 0 {
return Ok(TailReadResult { lines: Vec::new(), total_lines_in_window: 0 });
}
// Estimate how many bytes are needed for `want` lines, rounded up to a
// power-of-two-ish chunk so successive enlargements double cleanly. We
// start at 4× the estimate so a single read is enough for the common
// case (~256-byte lines × 1000 = 256 KB → start at 1 MB).
let mut window: u64 = ((want as u64) * (LOG_LINE_AVG_BYTES as u64) * 4).max(64 * 1024);
loop {
let read_from = file_size.saturating_sub(window);
let read_len = (file_size - read_from) as usize;
file.seek(SeekFrom::Start(read_from)).await?;
let mut buf = vec![0u8; read_len];
file.read_exact(&mut buf).await?;
// If we started mid-file, the first line in the buffer is almost
// certainly truncated — drop everything up to (and including) the
// first newline. When read_from == 0 we have the whole file and
// must keep the first line.
let usable: &[u8] = if read_from == 0 {
&buf
} else {
match buf.iter().position(|&b| b == b'\n') {
Some(pos) => &buf[pos + 1..],
None => &[], // window contained no newline at all
}
};
// `from_utf8_lossy` handles a chunk boundary that splits a UTF-8
// sequence (rare in tracing output but possible for non-ASCII fields).
let text = String::from_utf8_lossy(usable);
let line_count = text.lines().count();
// If we have enough lines, take the last `want` and return. Also
// return when we already read the whole file — no point growing.
if line_count >= want || read_from == 0 {
let collected: Vec<String> = text
.lines()
.rev()
.take(want)
.map(|s| s.to_string())
.collect::<Vec<_>>()
.into_iter()
.rev()
.collect();
return Ok(TailReadResult {
lines: collected,
total_lines_in_window: line_count,
});
}
// Not enough lines — double the window and try again. Capped so a
// pathologically sparse file (huge lines) can't drag the server
// into reading the whole thing.
let next_window = window.saturating_mul(2);
if next_window >= file_size {
window = file_size;
} else if next_window > 16 * 1024 * 1024 {
// 16 MB hard cap — beyond this, just return what we have.
window = 16 * 1024 * 1024;
if window <= read_from { // already past cap
let collected: Vec<String> = text
.lines()
.rev()
.take(want)
.map(|s| s.to_string())
.collect::<Vec<_>>()
.into_iter()
.rev()
.collect();
return Ok(TailReadResult {
lines: collected,
total_lines_in_window: line_count,
});
}
} else {
window = next_window;
}
}
}
/// Parse `bot_YYYY-MM-DD_HHMMSS.log` into epoch milliseconds (local timezone).
fn parse_log_filename_ms(name: &str) -> Option<u64> {
let stem = name.strip_prefix("bot_")?.strip_suffix(".log")?;
let (date, time) = stem.split_once('_')?;
if date.len() != 10 || time.len() != 6 { return None; }
let dt_str = format!("{} {}:{}:{}", date, &time[0..2], &time[2..4], &time[4..6]);
let naive = chrono::NaiveDateTime::parse_from_str(&dt_str, "%Y-%m-%d %H:%M:%S").ok()?;
let local = chrono::Local.from_local_datetime(&naive).single()?;
Some(local.timestamp_millis() as u64)
}
/// Read log files from disk, match to bot_runs for session grouping.
struct LogFileEntry {
name: String,
start_ms: u64,
end_ms: u64,
size: u64,
is_current: bool,
session_id: Option<i64>,
}
async fn read_log_entries(web_db: &super::web_storage::WebStorage) -> Vec<LogFileEntry> {
let log_dir = std::path::Path::new(arb_common::constants::LOG_DIR);
// Read symlink target to identify current log
let current_file = tokio::fs::read_link(log_dir.join("latest.log")).await
.ok()
.and_then(|p| p.file_name().map(|n| n.to_string_lossy().to_string()));
// Read log files from disk
let mut entries = Vec::new();
let mut dir = match tokio::fs::read_dir(log_dir).await {
Ok(d) => d,
Err(_) => return entries,
};
while let Ok(Some(entry)) = dir.next_entry().await {
let name = entry.file_name().to_string_lossy().to_string();
if !name.starts_with("bot_") || !name.ends_with(".log") { continue; }
let meta = match entry.metadata().await { Ok(m) => m, Err(_) => continue };
let start_ms = parse_log_filename_ms(&name).unwrap_or(0);
let end_ms = meta.modified().ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_millis() as u64)
.unwrap_or(0);
entries.push(LogFileEntry {
is_current: current_file.as_deref() == Some(&name),
name, start_ms, end_ms, size: meta.len(),
session_id: None,
});
}
// Match log files to bot_runs by start time (within 60s tolerance).
// Uses the shared web connection — previously this opened a fresh
// raw rusqlite::Connection per call (Logs tab + 5s polling), burning
// ~3 transient FDs each.
let runs: Vec<(i64, i64)> = web_db.run(|db| {
let mut stmt = match db.conn_ref().prepare(
"SELECT started_at_ms, session_id FROM bot_runs WHERE session_id IS NOT NULL ORDER BY id"
) {
Ok(s) => s,
Err(_) => return Vec::new(),
};
stmt.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))
.map(|rows| rows.filter_map(|r| r.ok()).collect())
.unwrap_or_default()
}).await;
for entry in &mut entries {
// Find closest bot_run within 60s of log file start
for &(run_started_ms, sid) in &runs {
let diff = (entry.start_ms as i64 - run_started_ms).unsigned_abs();
if diff < 60_000 {
entry.session_id = Some(sid);
break;
}
}
}
// Sort newest first
entries.sort_by_key(|b| std::cmp::Reverse(b.start_ms));
entries
}
/// List all log files grouped by session.
async fn api_logs_list(session: Session, State(state): State<AppState>) -> impl IntoResponse {
if let Err(e) = session.require_permission("log.view") { return e.into_response(); }
let entries = read_log_entries(&state.web_db).await;
// Group by session_id. Preserve order (newest first within each group).
let mut sessions: Vec<serde_json::Value> = Vec::new();
let mut session_map: std::collections::HashMap<i64, usize> = std::collections::HashMap::new();
let mut ungrouped: Vec<serde_json::Value> = Vec::new();
for e in &entries {
let log_json = serde_json::json!({
"name": e.name,
"start_ms": e.start_ms,
"end_ms": e.end_ms,
"size": e.size,
"is_current": e.is_current,
});
if let Some(sid) = e.session_id {
if let Some(&idx) = session_map.get(&sid) {
sessions[idx]["logs"].as_array_mut().unwrap().push(log_json);
// Update session range
let s = &mut sessions[idx];
let cur_start = s["start_ms"].as_u64().unwrap_or(u64::MAX);
let cur_end = s["end_ms"].as_u64().unwrap_or(0);
if e.start_ms < cur_start { s["start_ms"] = serde_json::json!(e.start_ms); }
if e.end_ms > cur_end { s["end_ms"] = serde_json::json!(e.end_ms); }
let cur_size = s["total_size"].as_u64().unwrap_or(0);
s["total_size"] = serde_json::json!(cur_size + e.size);
if e.is_current { s["is_current"] = serde_json::json!(true); }
} else {
let idx = sessions.len();
session_map.insert(sid, idx);
sessions.push(serde_json::json!({
"session_id": sid,
"start_ms": e.start_ms,
"end_ms": e.end_ms,
"total_size": e.size,
"is_current": e.is_current,
"logs": [log_json],
}));
}
} else {
ungrouped.push(log_json);
}
}
// Sort sessions by start_ms descending (newest first)
sessions.sort_by(|a, b| {
let a_ms = a["start_ms"].as_u64().unwrap_or(0);
let b_ms = b["start_ms"].as_u64().unwrap_or(0);
b_ms.cmp(&a_ms)
});
Json(serde_json::json!({
"sessions": sessions,
"ungrouped": ungrouped,
})).into_response()
}
/// Download a single log file by name.
async fn api_logs_download(session: Session, Path(filename): Path<String>) -> impl IntoResponse {
if let Err(e) = session.require_permission("log.view") { return e.into_response(); }
if !filename.starts_with("bot_") || !filename.ends_with(".log")
|| filename.contains('/') || filename.contains('\\') || filename.contains("..")
{
return (axum::http::StatusCode::BAD_REQUEST, "Invalid filename").into_response();
}
let path = format!("{}/{}", arb_common::constants::LOG_DIR, filename);
match tokio::fs::read(&path).await {
Ok(content) => {
let headers = [
(axum::http::header::CONTENT_TYPE, "text/plain; charset=utf-8"),
(axum::http::header::CONTENT_DISPOSITION, &format!("attachment; filename=\"{}\"", filename)),
];
(headers, content).into_response()
}
Err(_) => (axum::http::StatusCode::NOT_FOUND, "Log file not found").into_response(),
}
}
/// Download all logs for a specific session (concatenated, oldest first).
async fn api_logs_download_session(session: Session, State(state): State<AppState>, Path(session_id): Path<i64>) -> impl IntoResponse {
if let Err(e) = session.require_permission("log.view") { return e.into_response(); }
let entries = read_log_entries(&state.web_db).await;
let mut files: Vec<&LogFileEntry> = entries.iter()
.filter(|e| e.session_id == Some(session_id))
.collect();
files.sort_by_key(|e| e.start_ms); // oldest first for concatenation
if files.is_empty() {
return (axum::http::StatusCode::NOT_FOUND, "No logs for this session").into_response();
}
let mut combined = String::new();
for f in &files {
if !combined.is_empty() {
combined.push_str("\n\n");
}
if files.len() > 1 {
combined.push_str("══════════════════════════════════════════════════════════════\n");
combined.push_str(&format!(" {}\n", f.name));
combined.push_str("══════════════════════════════════════════════════════════════\n\n");
}
if let Ok(content) = tokio::fs::read_to_string(format!("{}/{}", arb_common::constants::LOG_DIR, f.name)).await {
combined.push_str(&content);
}
}
let filename = format!("session_{}.log", session_id);
let headers = [
(axum::http::header::CONTENT_TYPE, "text/plain; charset=utf-8"),
(axum::http::header::CONTENT_DISPOSITION, &format!("attachment; filename=\"{}\"", filename)),
];
(headers, combined).into_response()
}
/// Download all log files concatenated into a single file (oldest first).
async fn api_logs_download_all(session: Session, State(state): State<AppState>) -> impl IntoResponse {
if let Err(e) = session.require_permission("log.view") { return e.into_response(); }
let entries = read_log_entries(&state.web_db).await;
let mut sorted: Vec<&LogFileEntry> = entries.iter().collect();
sorted.sort_by_key(|e| e.start_ms); // oldest first
let mut combined = String::new();
for f in &sorted {
if !combined.is_empty() {
combined.push_str("\n\n");
}
combined.push_str("══════════════════════════════════════════════════════════════\n");
combined.push_str(&format!(" {}\n", f.name));
combined.push_str("══════════════════════════════════════════════════════════════\n\n");
if let Ok(content) = tokio::fs::read_to_string(format!("{}/{}", arb_common::constants::LOG_DIR, f.name)).await {
combined.push_str(&content);
}
}
let headers = [
(axum::http::header::CONTENT_TYPE, "text/plain; charset=utf-8"),
(axum::http::header::CONTENT_DISPOSITION, "attachment; filename=\"arb_bot_all_logs.log\""),
];
(headers, combined).into_response()
}
/// Read merged config: default.toml + local.toml overlay.
fn read_merged_config_table() -> toml::Value {
let content = std::fs::read_to_string(arb_common::constants::CONFIG_DEFAULT_PATH).unwrap_or_default();
let mut table: toml::Value = content.parse().unwrap_or(toml::Value::Table(Default::default()));
arb_common::config::merge_local_overlay(&mut table, arb_common::constants::CONFIG_LOCAL_PATH);
table
}
/// GET current config (read from toml).
async fn api_get_config(session: Session, State(state): State<AppState>) -> impl IntoResponse {
if let Err(e) = session.require_permission("settings.view") { return e.into_response(); }
use super::state::HotConfig;
let table = read_merged_config_table();
let s = |section: &str, key: &str| -> Option<&toml::Value> {
table.get(section)?.get(key)
};
let f = |section: &str, key: &str, def: f64| -> f64 {
s(section, key).and_then(|v| v.as_float().or_else(|| v.as_integer().map(|i| i as f64))).unwrap_or(def)
};
let config = HotConfig {
max_order_size_usd: f("position", "max_order_size_usd", 25.0),
leverage: s("position", "leverage").and_then(|v| v.as_integer()).unwrap_or(3) as u16,
max_used_capital_usd: f("position", "max_used_capital_usd", 50.0),
max_open_positions: s("position", "max_open_positions").and_then(|v| v.as_integer()).unwrap_or(5) as usize,
min_entry_spread_bps: f("strategy", "min_entry_spread_bps", 35.0),
include_fees_in_entry: s("strategy", "include_fees_in_entry").and_then(|v| v.as_bool()).unwrap_or(false),
min_top_level_usd: f("strategy", "min_top_level_usd", 0.0),
tick_max_spike_bps: f("strategy", "tick_max_spike_bps", 0.0),
tick_spike_window_ms: f("strategy", "tick_spike_window_ms", 0.0),
max_trade_divergence_bps: f("strategy", "max_trade_divergence_bps", 0.0),
max_recv_staleness_secs: f("strategy", "max_recv_staleness_secs", 0.1),
max_tick_age_ms: f("strategy", "max_tick_age_ms", 100.0),
signal_cooldown_secs: f("strategy", "signal_cooldown_secs", 3.0),
exit_mode: s("strategy", "exit_mode").and_then(|v| v.as_str()).unwrap_or("spread").to_string(),
min_exit_spread_bps: f("strategy", "min_exit_spread_bps", 5.0),
min_exit_pnl_pct: f("strategy", "min_exit_pnl_pct", 0.3),
min_exit_checks: s("strategy", "min_exit_checks").and_then(|v| v.as_integer()).unwrap_or(1) as u32,
include_fees_in_exit: s("strategy", "include_fees_in_exit").and_then(|v| v.as_bool()).unwrap_or(true),
exchanges: std::collections::HashMap::new(),
disabled_pairs: Vec::new(),
};
// Build exchanges JSON dynamically from [exchanges.*] TOML sections.
let exchanges = {
let mut map = serde_json::Map::new();
if let Some(ex_table) = table.get("exchanges").and_then(|v| v.as_table()) {
for (name, section) in ex_table {
if let Some(sec) = section.as_table() {
let mut ex_json = serde_json::Map::new();
for (key, val) in sec {
match val {
toml::Value::String(s) => { ex_json.insert(key.clone(), serde_json::Value::String(s.clone())); }
toml::Value::Float(f) => { ex_json.insert(key.clone(), serde_json::json!(*f)); }
toml::Value::Integer(i) => { ex_json.insert(key.clone(), serde_json::json!(*i)); }
toml::Value::Boolean(b) => { ex_json.insert(key.clone(), serde_json::json!(*b)); }
toml::Value::Array(arr) => {
let json_arr: Vec<serde_json::Value> = arr.iter()
.filter_map(|v| v.as_str().map(|s| serde_json::Value::String(s.to_string())))
.collect();
ex_json.insert(key.clone(), serde_json::Value::Array(json_arr));
}
_ => {}
}
}
map.insert(name.clone(), serde_json::Value::Object(ex_json));
}
}
}
serde_json::Value::Object(map)
};
let mut result = serde_json::to_value(&config).unwrap_or_default();
result["exchanges"] = exchanges;
// Add exchange config schemas for dynamic UI rendering
let schemas: Vec<serde_json::Value> = state.dash.exchange_schemas().iter()
.map(|(name, fields)| serde_json::json!({ "name": name, "fields": fields }))
.collect();
result["exchange_schemas"] = serde_json::json!(schemas);
// Add exchange name→id mapping + active symbols via the shared web
// connection. Both reads run inside one spawn_blocking so the lock is
// taken once.
let (exchange_ids, active_syms, sym_exchanges) = state.web_db.run(|db| {
let ids: Vec<serde_json::Value> = db.load_exchange_ids().unwrap_or_default()
.into_iter()
.map(|(name, id)| serde_json::json!({"name": name, "id": id}))
.collect();
let syms = db.load_active_common_symbols().unwrap_or_default();
let pairs = db.load_active_symbol_exchanges().unwrap_or_default();
let mut map: std::collections::BTreeMap<String, Vec<i64>> = std::collections::BTreeMap::new();
for (sym, ex_id) in pairs {
map.entry(sym).or_default().push(ex_id);
}
(ids, syms, map)
}).await;
result["exchange_ids"] = serde_json::json!(exchange_ids);
result["active_symbols"] = serde_json::json!(active_syms);
result["symbol_exchanges"] = serde_json::json!(sym_exchanges);
// Extra global defaults for override pre-fill (not in HotConfig struct)
result["signal_cooldown_secs"] = serde_json::json!(f("strategy", "signal_cooldown_secs", 3.0));
result["min_exit_checks"] = serde_json::json!(f("strategy", "min_exit_checks", 1.0) as u32);
result["max_positions_per_symbol"] = serde_json::json!(
s("position", "max_positions_per_symbol").and_then(|v| v.as_integer()).unwrap_or(1)
);
Json(result).into_response()
}
/// POST new config: apply hot + save to default.toml.
async fn api_set_config(
session: Session,
State(state): State<AppState>,
Json(config): Json<serde_json::Value>,
) -> impl IntoResponse {
if let Err(e) = session.require_permission("settings.edit") { return e.into_response(); }
// Discover exchange names from merged config (authoritative ordering from [exchanges.*])
let merged = read_merged_config_table();
let exchange_names: Vec<String> = merged.get("exchanges")
.and_then(|v| v.as_table())
.map(|t| t.keys().cloned().collect())
.unwrap_or_default();
// Enforce exchange slippage limits before saving
let mut config = config;
clamp_exchange_slippage(&mut config, &exchange_names);
let ex = config.get("exchanges");
// Fields that cannot be hot-reloaded — changing them in [exchanges.NAME]
// requires a bot restart. (key, default-if-missing, human-readable label)
const RESTART_FIELDS: &[(&str, &str, &str)] = &[
("margin_mode", "isolated", "margin_mode"),
("ws_ob_mode", "per_market", "ws_ob_mode"),
];
// Collect (exchange_name, field_label) pairs for changed restart-required fields.
let mut restart_changes: Vec<(String, &'static str)> = Vec::new();
for name in &exchange_names {
for (field_key, default, label) in RESTART_FIELDS {
let new_val = ex.and_then(|e| e.get(name))
.and_then(|v| v.get(field_key))
.and_then(|v| v.as_str());
let Some(new_val) = new_val else { continue; };
let current = merged.get("exchanges")
.and_then(|t| t.get(name))
.and_then(|t| t.get(field_key))
.and_then(|v| v.as_str())
.unwrap_or(default);
if new_val != current {
restart_changes.push((name.clone(), label));
}
}
}
// Save full config (strategy + exchange) to toml
if let Err(e) = save_config_to_toml(&config).await {
return Json(serde_json::json!({"ok": false, "error": e.to_string()})).into_response();
}
// Build HotExchangeConfig from the incoming JSON for each exchange.
let build_hot_exchange = |name: &str| -> super::state::HotExchangeConfig {
let v = ex.and_then(|e| e.get(name));
let parse_slip = |val: Option<&serde_json::Value>, field: &str| -> Option<crate::config::SlippagePct> {
let v = val?.get(field)?;
if let Some(s) = v.as_str() {
if s.eq_ignore_ascii_case("max") { return Some(crate::config::SlippagePct::Max); }
s.parse::<f64>().ok().map(crate::config::SlippagePct::Fixed)
} else {
v.as_f64().map(crate::config::SlippagePct::Fixed)
}
};
super::state::HotExchangeConfig {
enabled: v.and_then(|v| v["enabled"].as_bool()),
entry_order_type: v.and_then(|v| v["entry_order_type"].as_str()).map(String::from),
entry_slippage_pct: parse_slip(v, "entry_slippage_pct"),
exit_order_type: v.and_then(|v| v["exit_order_type"].as_str()).map(String::from),
exit_slippage_pct: parse_slip(v, "exit_slippage_pct"),
emergency_slippage_pct: parse_slip(v, "emergency_slippage_pct"),
stop_loss_type: v.and_then(|v| v["stop_loss_type"].as_str()).map(String::from),
allowed_with: v.and_then(|v| v["allowed_with"].as_array()).map(|arr| {
arr.iter().filter_map(|e| e.as_str().map(String::from)).collect()
}),
}
};
let mut hot_exchanges = std::collections::HashMap::new();
for name in &exchange_names {
hot_exchanges.insert(name.clone(), build_hot_exchange(name));
}
// Extract hot config fields for engine live-reload
let hot = super::state::HotConfig {
max_order_size_usd: config["max_order_size_usd"].as_f64().unwrap_or(25.0),
leverage: config["leverage"].as_u64().unwrap_or(3) as u16,
max_used_capital_usd: config["max_used_capital_usd"].as_f64().unwrap_or(50.0),
max_open_positions: config["max_open_positions"].as_u64().unwrap_or(5) as usize,
min_entry_spread_bps: config["min_entry_spread_bps"].as_f64().unwrap_or(35.0),
include_fees_in_entry: config["include_fees_in_entry"].as_bool().unwrap_or(false),
min_top_level_usd: config["min_top_level_usd"].as_f64().unwrap_or(0.0),
tick_max_spike_bps: config["tick_max_spike_bps"].as_f64().unwrap_or(0.0),
tick_spike_window_ms: config["tick_spike_window_ms"].as_f64().unwrap_or(0.0),
max_trade_divergence_bps: config["max_trade_divergence_bps"].as_f64().unwrap_or(0.0),
max_recv_staleness_secs: config["max_recv_staleness_secs"].as_f64().unwrap_or(0.1),
max_tick_age_ms: config["max_tick_age_ms"].as_f64().unwrap_or(100.0),
signal_cooldown_secs: config["signal_cooldown_secs"].as_f64().unwrap_or(3.0),
exit_mode: config["exit_mode"].as_str().unwrap_or("spread").to_string(),
min_exit_spread_bps: config["min_exit_spread_bps"].as_f64().unwrap_or(5.0),
min_exit_pnl_pct: config["min_exit_pnl_pct"].as_f64().unwrap_or(0.3),
min_exit_checks: config["min_exit_checks"].as_u64().unwrap_or(1) as u32,
include_fees_in_exit: config["include_fees_in_exit"].as_bool().unwrap_or(true),
exchanges: hot_exchanges,
disabled_pairs: config["disabled_pairs"].as_array()
.map(|arr| arr.iter().filter_map(|v| v.as_str().map(String::from)).collect())
.unwrap_or_default(),
};
let version = state.dash.set_hot_config(hot);
tracing::info!(version, user = %session.username, "Config updated via web UI");
if !restart_changes.is_empty() {
let parts: Vec<String> = restart_changes.iter()
.map(|(name, label)| format!("{name}.{label}"))
.collect();
tracing::info!(changes = ?parts, "restart-required field changed in config");
Json(serde_json::json!({
"ok": true, "version": version,
"restart_required": true,
"restart_reason": format!("{} changed — requires restart to apply", parts.join(", "))
})).into_response()
} else {
Json(serde_json::json!({"ok": true, "version": version})).into_response()
}
}
/// Clamp numeric slippage fields for Extended to the hard exchange limit.
/// "max" values are not clamped — they resolve per-symbol at order time.