alpaca-trader-rs 0.6.0

Alpaca Markets trading toolkit — async REST client library and interactive TUI trading terminal
Documentation
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
//! Application logging setup using `tracing` and `tracing-appender`.
#[cfg(unix)]
use std::sync::Mutex;

use tracing_appender::non_blocking::WorkerGuard;
#[cfg(unix)]
use tracing_subscriber::Layer;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};

// ── Syslog layer ──────────────────────────────────────────────────────────────

#[cfg(unix)]
struct MessageVisitor {
    message: String,
}

#[cfg(unix)]
impl tracing::field::Visit for MessageVisitor {
    fn record_str(&mut self, field: &tracing::field::Field, value: &str) {
        if field.name() == "message" {
            self.message = value.to_string();
        }
    }
    fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
        if field.name() == "message" {
            self.message = format!("{value:?}").trim_matches('"').to_string();
        }
    }
}

#[cfg(unix)]
struct SyslogLayer {
    logger: Mutex<syslog::Logger<syslog::LoggerBackend, syslog::Formatter3164>>,
}

#[cfg(unix)]
impl<S: tracing::Subscriber> Layer<S> for SyslogLayer {
    fn on_event(
        &self,
        event: &tracing::Event<'_>,
        _ctx: tracing_subscriber::layer::Context<'_, S>,
    ) {
        let mut visitor = MessageVisitor {
            message: String::new(),
        };
        event.record(&mut visitor);
        if visitor.message.is_empty() {
            return;
        }
        if let Ok(mut logger) = self.logger.lock() {
            let msg = &visitor.message;
            let _ = match *event.metadata().level() {
                tracing::Level::ERROR => logger.err(msg),
                tracing::Level::WARN => logger.warning(msg),
                tracing::Level::INFO => logger.info(msg),
                _ => logger.debug(msg),
            };
        }
    }
}

// ── Public API ────────────────────────────────────────────────────────────────

/// Initialise file + syslog logging. Returns a `WorkerGuard` that **must** be
/// kept alive for the entire process — dropping it flushes and closes the log.
///
/// Call this before `enable_raw_mode()` so stdout is still safe to use for any
/// early error messages from this function itself.
pub fn init() -> anyhow::Result<WorkerGuard> {
    let log_dir = log_dir();
    let guard = init_with_dir(&log_dir)?;
    tracing::info!(log_dir = %log_dir.display(), "logging initialised");
    Ok(guard)
}

/// Set up file + syslog logging rooted at `log_dir`.
///
/// Separated from [`init`] so that tests can exercise the full setup path
/// with a temporary directory without touching the process-wide subscriber.
/// Uses `try_init` so that calling this when a global subscriber is already
/// installed (e.g. in a test process) silently succeeds rather than panicking.
pub(crate) fn init_with_dir(log_dir: &std::path::Path) -> anyhow::Result<WorkerGuard> {
    std::fs::create_dir_all(log_dir)?;

    // Non-blocking daily-rotating file writer
    let file_appender = tracing_appender::rolling::daily(log_dir, "alpaca-trader.log");
    let (non_blocking, guard) = tracing_appender::non_blocking(file_appender);

    let file_layer = tracing_subscriber::fmt::layer()
        .with_writer(non_blocking)
        .with_ansi(false)
        .with_target(true);

    // EnvFilter: RUST_LOG env var takes priority, otherwise sensible defaults
    let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| {
        EnvFilter::new("info,alpaca_trader_rs=debug,tokio=warn,crossterm=warn,ratatui=warn")
    });

    let registry = tracing_subscriber::registry().with(filter).with(file_layer);

    #[cfg(unix)]
    {
        // Optional syslog layer — silently skipped if the socket is unavailable
        let syslog_layer = syslog::unix(syslog::Formatter3164 {
            facility: syslog::Facility::LOG_USER,
            hostname: None,
            process: "alpaca-trader".into(),
            pid: std::process::id(),
        })
        .ok()
        .map(|logger| SyslogLayer {
            logger: Mutex::new(logger),
        });

        if let Some(syslog) = syslog_layer {
            registry.with(syslog).try_init().ok();
        } else {
            registry.try_init().ok();
        }
    }

    #[cfg(not(unix))]
    registry.try_init().ok();

    Ok(guard)
}

fn log_dir() -> std::path::PathBuf {
    log_dir_from(dirs::home_dir())
}

/// Determine the log directory given an optional home path.
///
/// Resolution order (first hit wins):
/// 1. Platform-appropriate subdirectory under `home` (preferred)
/// 2. `./alpaca-trader-logs` relative to the current working directory
/// 3. `<temp_dir>/alpaca-trader-logs`
///
/// A `tracing::warn!` is emitted whenever a fallback is used so the operator
/// can see where logs are being written.
pub(crate) fn log_dir_from(home: Option<std::path::PathBuf>) -> std::path::PathBuf {
    #[cfg(target_os = "macos")]
    let platform_dir = home.map(|h| h.join("Library/Logs/alpaca-trader"));

    #[cfg(target_os = "windows")]
    let platform_dir = {
        let _ = home; // unused on Windows; log dir comes from %LOCALAPPDATA%
        dirs::data_local_dir().map(|d| d.join("alpaca-trader").join("logs"))
    };

    #[cfg(all(not(target_os = "macos"), not(target_os = "windows")))]
    let platform_dir = home.map(|h| h.join(".local/share/alpaca-trader/logs"));

    if let Some(dir) = platform_dir {
        return dir;
    }

    // Fallback 1: current working directory
    if let Ok(cwd) = std::env::current_dir() {
        tracing::warn!(
            path = %cwd.display(),
            "$HOME is not set; writing logs relative to current directory"
        );
        return cwd.join("alpaca-trader-logs");
    }

    // Fallback 2: system temp directory
    let tmp = std::env::temp_dir();
    tracing::warn!(
        path = %tmp.display(),
        "could not determine current directory; writing logs to temp directory"
    );
    tmp.join("alpaca-trader-logs")
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;
    #[cfg(unix)]
    use std::sync::{Arc, Mutex};
    #[cfg(unix)]
    use tracing_subscriber::layer::SubscriberExt;

    // ── Helper: run a closure under a per-thread subscriber that captures
    //    whatever MessageVisitor extracts from each tracing event. ─────────────

    #[cfg(unix)]
    struct MessageCapture(Arc<Mutex<String>>);

    #[cfg(unix)]
    impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for MessageCapture {
        fn on_event(
            &self,
            event: &tracing::Event<'_>,
            _ctx: tracing_subscriber::layer::Context<'_, S>,
        ) {
            let mut visitor = MessageVisitor {
                message: String::new(),
            };
            event.record(&mut visitor);
            *self.0.lock().unwrap() = visitor.message.clone();
        }
    }

    /// Run `f` under a thread-local subscriber that records the last captured
    /// message into the returned string. Does not touch the global subscriber.
    #[cfg(unix)]
    fn capture<F: FnOnce()>(f: F) -> String {
        let captured = Arc::new(Mutex::new(String::new()));
        let sub = tracing_subscriber::registry().with(MessageCapture(Arc::clone(&captured)));
        tracing::subscriber::with_default(sub, f);
        let result = captured.lock().unwrap().clone();
        result
    }

    // ── MessageVisitor ────────────────────────────────────────────────────────

    #[test]
    #[cfg(unix)]
    fn message_visitor_record_debug_captures_message() {
        // tracing!("text") records the message via record_debug
        let msg = capture(|| tracing::info!("hello from test"));
        assert_eq!(msg, "hello from test");
    }

    #[test]
    #[cfg(unix)]
    fn message_visitor_record_debug_non_message_field_is_ignored() {
        // count = 42 exercises the record_debug non-"message" branch;
        // the text part still gets captured.
        let msg = capture(|| tracing::info!(count = 42, "with extra field"));
        assert_eq!(msg, "with extra field");
    }

    #[test]
    #[cfg(unix)]
    fn message_visitor_record_str_captures_explicit_message_field() {
        // message = "string" uses record_str for the message field
        let msg = capture(|| tracing::info!(message = "explicit string"));
        assert_eq!(msg, "explicit string");
    }

    #[test]
    #[cfg(unix)]
    fn message_visitor_record_str_non_message_field_is_ignored() {
        // name = "alice" is a &str that is NOT the "message" field;
        // exercises the record_str non-"message" branch.
        let msg = capture(|| tracing::info!(name = "alice", "with str field"));
        assert_eq!(msg, "with str field");
    }

    // ── SyslogLayer ───────────────────────────────────────────────────────────

    #[cfg(unix)]
    fn make_syslog_layer() -> Option<SyslogLayer> {
        syslog::unix(syslog::Formatter3164 {
            facility: syslog::Facility::LOG_USER,
            hostname: None,
            process: "alpaca-trader-test".into(),
            pid: 0,
        })
        .ok()
        .map(|l| SyslogLayer {
            logger: Mutex::new(l),
        })
    }

    #[test]
    #[cfg(unix)]
    fn syslog_layer_empty_message_returns_early_without_panic() {
        let Some(layer) = make_syslog_layer() else {
            return; // syslog socket unavailable — skip
        };
        // An event whose message field is an empty string should not panic.
        let sub = tracing_subscriber::registry().with(layer);
        tracing::subscriber::with_default(sub, || tracing::info!(""));
    }

    #[test]
    #[cfg(unix)]
    fn syslog_layer_dispatches_error_level() {
        let Some(layer) = make_syslog_layer() else {
            return;
        };
        let sub = tracing_subscriber::registry().with(layer);
        tracing::subscriber::with_default(sub, || tracing::error!("error level msg"));
    }

    #[test]
    #[cfg(unix)]
    fn syslog_layer_dispatches_warn_level() {
        let Some(layer) = make_syslog_layer() else {
            return;
        };
        let sub = tracing_subscriber::registry().with(layer);
        tracing::subscriber::with_default(sub, || tracing::warn!("warn level msg"));
    }

    #[test]
    #[cfg(unix)]
    fn syslog_layer_dispatches_info_level() {
        let Some(layer) = make_syslog_layer() else {
            return;
        };
        let sub = tracing_subscriber::registry().with(layer);
        tracing::subscriber::with_default(sub, || tracing::info!("info level msg"));
    }

    #[test]
    #[cfg(unix)]
    fn syslog_layer_dispatches_debug_level() {
        let Some(layer) = make_syslog_layer() else {
            return;
        };
        let sub = tracing_subscriber::registry().with(layer);
        tracing::subscriber::with_default(sub, || tracing::debug!("debug level msg"));
    }

    // ── init_with_dir ─────────────────────────────────────────────────────────

    #[test]
    fn init_with_dir_creates_log_dir_and_returns_guard() {
        let tmp = tempfile::tempdir().unwrap();
        let log_subdir = tmp.path().join("logs");
        // Directory does not exist yet — init_with_dir must create it.
        let _guard =
            init_with_dir(&log_subdir).expect("init_with_dir should succeed with a temp dir");
        assert!(
            log_subdir.exists(),
            "log dir should have been created by init_with_dir"
        );
    }

    #[test]
    fn init_with_dir_is_idempotent_when_subscriber_already_set() {
        let tmp = tempfile::tempdir().unwrap();
        // Call twice — second call must not panic (try_init silently ignores conflicts).
        let _g1 = init_with_dir(tmp.path()).expect("first call should succeed");
        let _g2 = init_with_dir(tmp.path()).expect("second call should not panic");
    }

    // ── log_dir ───────────────────────────────────────────────────────────────

    #[test]
    fn log_dir_returns_non_empty_path() {
        let dir = log_dir();
        assert!(
            dir.components().count() > 0,
            "log_dir() returned an empty path"
        );
    }

    // ── log_dir_from ─────────────────────────────────────────────────────────

    #[test]
    #[cfg(target_os = "macos")]
    fn home_present_returns_macos_log_path() {
        let dir = log_dir_from(Some(PathBuf::from("/Users/tester")));
        assert_eq!(
            dir,
            PathBuf::from("/Users/tester/Library/Logs/alpaca-trader")
        );
    }

    #[test]
    #[cfg(target_os = "macos")]
    fn home_present_last_component_is_alpaca_trader() {
        let dir = log_dir_from(Some(PathBuf::from("/Users/alice")));
        assert_eq!(dir.file_name().unwrap(), "alpaca-trader");
    }

    #[test]
    #[cfg(all(not(target_os = "macos"), not(target_os = "windows")))]
    fn home_present_returns_xdg_log_path() {
        let dir = log_dir_from(Some(PathBuf::from("/home/tester")));
        assert_eq!(
            dir,
            PathBuf::from("/home/tester/.local/share/alpaca-trader/logs")
        );
    }

    #[test]
    #[cfg(all(not(target_os = "macos"), not(target_os = "windows")))]
    fn home_present_last_component_is_logs() {
        let dir = log_dir_from(Some(PathBuf::from("/home/alice")));
        assert_eq!(dir.file_name().unwrap(), "logs");
    }

    #[test]
    #[cfg(target_os = "windows")]
    fn home_present_returns_windows_log_path() {
        // On Windows the home parameter is ignored; log dir comes from %LOCALAPPDATA%
        let dir = log_dir_from(Some(PathBuf::from("C:\\Users\\tester")));
        let dir_str = dir.to_str().unwrap_or("");
        assert!(
            dir_str.contains("alpaca-trader"),
            "expected alpaca-trader in Windows log path, got: {dir_str}"
        );
    }

    #[test]
    #[cfg(target_os = "windows")]
    fn home_present_last_component_is_logs_on_windows() {
        let dir = log_dir_from(Some(PathBuf::from("C:\\Users\\alice")));
        assert_eq!(dir.file_name().unwrap(), "logs");
    }

    // On Windows, log_dir_from(None) returns the %LOCALAPPDATA% path rather than
    // the CWD/temp fallback because the Windows branch ignores the `home` argument.
    #[test]
    #[cfg(not(target_os = "windows"))]
    fn no_home_falls_back_to_non_panicking_dir() {
        let dir = log_dir_from(None);
        assert!(
            dir.ends_with("alpaca-trader-logs"),
            "fallback path should end with alpaca-trader-logs, got: {}",
            dir.display()
        );
    }

    #[test]
    #[cfg(target_os = "windows")]
    fn no_home_returns_localappdata_dir_on_windows() {
        // On Windows the home arg is unused; log dir comes from %LOCALAPPDATA%.
        let dir = log_dir_from(None);
        let dir_str = dir.to_str().unwrap_or("");
        assert!(
            dir_str.contains("alpaca-trader"),
            "expected alpaca-trader in Windows log path, got: {dir_str}"
        );
        assert_eq!(
            dir.file_name().unwrap(),
            "logs",
            "last component should be 'logs', got: {dir_str}"
        );
    }

    #[test]
    fn no_home_result_is_absolute() {
        // Every platform must return an absolute path regardless of whether
        // the home arg is None.
        let dir = log_dir_from(None);
        assert!(
            dir.is_absolute(),
            "log dir should be absolute, got: {}",
            dir.display()
        );
    }

    #[test]
    #[cfg(target_os = "macos")]
    fn log_dir_from_preserves_home_prefix() {
        let home = PathBuf::from("/tmp/fakehome");
        let dir = log_dir_from(Some(home.clone()));
        assert!(dir.starts_with(&home));
    }
}