Skip to main content

polyester/codecs/decode/
triggers.rs

1//! Trigger response decoders.
2
3use super::enums::enum_value_side;
4use super::money::{decode_price_ticks, decode_qty_scaled};
5use crate::codecs::scalars::format_uint64_id;
6use crate::models::{
7    Trigger, TriggerDetails, TriggerEvent, TriggerEventsList, TriggerLadderDetails,
8    TriggerMutationResult, TriggerStopDetails, TriggerTrailingDetails, TriggerTwapDetails,
9    TriggersList,
10};
11use crate::proto::orders::v1::{
12    FeeAsset, SelfTradePreventionMode, TriggerDirection, TriggerPriceSource,
13};
14use crate::proto::triggers::v1::{
15    CancelTriggerResponse, ConditionalTrigger, CreateTriggerResponse, GetTriggerResponse,
16    LadderDistribution, ListTriggerEventsResponse, ListTriggersResponse, ModifyTriggerResponse,
17    PauseTriggerResponse, ResumeTriggerResponse, Trigger as ProtoTrigger,
18    TriggerEvent as ProtoTriggerEvent, TriggerStatus, conditional_child_execution, trigger,
19    twap_trigger,
20};
21use crate::types::Price;
22use buffa::Enumeration;
23use buffa_types::google::protobuf::Timestamp;
24
25pub fn trigger_status_label(status: TriggerStatus) -> &'static str {
26    match status {
27        TriggerStatus::StatusCreated => "created",
28        TriggerStatus::StatusArmed => "armed",
29        TriggerStatus::StatusRunning => "running",
30        TriggerStatus::StatusCompleted => "completed",
31        TriggerStatus::StatusCanceled => "cancelled",
32        TriggerStatus::StatusFailed => "failed",
33        TriggerStatus::StatusPaused => "paused",
34        TriggerStatus::StatusUnspecified => "",
35    }
36}
37
38/// Parse a trigger status filter label into a proto enum.
39pub fn trigger_status_from_label(label: &str) -> Result<TriggerStatus, String> {
40    match label.trim().to_ascii_lowercase().as_str() {
41        "created" => Ok(TriggerStatus::StatusCreated),
42        "armed" => Ok(TriggerStatus::StatusArmed),
43        "running" => Ok(TriggerStatus::StatusRunning),
44        "completed" => Ok(TriggerStatus::StatusCompleted),
45        "cancelled" | "canceled" => Ok(TriggerStatus::StatusCanceled),
46        "failed" => Ok(TriggerStatus::StatusFailed),
47        "paused" => Ok(TriggerStatus::StatusPaused),
48        other => Err(format!(
49            "invalid trigger status {other:?}; expected one of: created, armed, running, completed, cancelled, failed, paused"
50        )),
51    }
52}
53
54fn enum_value_trigger_status(value: buffa::EnumValue<TriggerStatus>) -> String {
55    value
56        .as_known()
57        .map(trigger_status_label)
58        .map(str::to_owned)
59        .unwrap_or_else(|| format!("UNKNOWN({})", value.to_i32()))
60}
61
62fn trigger_price_source_label(value: buffa::EnumValue<TriggerPriceSource>) -> String {
63    match value.as_known() {
64        Some(TriggerPriceSource::LastPrice) => "last".to_owned(),
65        Some(TriggerPriceSource::IndexPrice) => "index".to_owned(),
66        Some(TriggerPriceSource::MarkPrice) => "mark".to_owned(),
67        Some(_) => String::new(),
68        None => format!("UNKNOWN({})", value.to_i32()),
69    }
70}
71
72fn trigger_direction_label(value: buffa::EnumValue<TriggerDirection>) -> String {
73    match value.as_known() {
74        Some(TriggerDirection::Above) => "above".to_owned(),
75        Some(TriggerDirection::Below) => "below".to_owned(),
76        Some(_) => String::new(),
77        None => format!("UNKNOWN({})", value.to_i32()),
78    }
79}
80
81fn fee_asset_label(value: buffa::EnumValue<FeeAsset>) -> String {
82    match value.as_known() {
83        Some(FeeAsset::Quote) => "quote".to_owned(),
84        Some(FeeAsset::Base) => "base".to_owned(),
85        Some(_) => String::new(),
86        None => format!("UNKNOWN({})", value.to_i32()),
87    }
88}
89
90fn stp_mode_label(value: buffa::EnumValue<SelfTradePreventionMode>) -> String {
91    match value.as_known() {
92        Some(SelfTradePreventionMode::ExpireTaker) => "expire_taker".to_owned(),
93        Some(SelfTradePreventionMode::ExpireMaker) => "expire_maker".to_owned(),
94        Some(SelfTradePreventionMode::ExpireBoth) => "expire_both".to_owned(),
95        Some(_) => String::new(),
96        None => format!("UNKNOWN({})", value.to_i32()),
97    }
98}
99
100fn ladder_distribution_label(value: buffa::EnumValue<LadderDistribution>) -> String {
101    match value.as_known() {
102        Some(LadderDistribution::Linear) => "linear".to_owned(),
103        Some(LadderDistribution::Geometric) => "geometric".to_owned(),
104        Some(LadderDistribution::WeightedFavorable) => "weighted_favorable".to_owned(),
105        Some(_) => String::new(),
106        None => format!("UNKNOWN({})", value.to_i32()),
107    }
108}
109
110fn clone_timestamp(ts: Option<&Timestamp>) -> Option<Timestamp> {
111    ts.map(|t| Timestamp {
112        seconds: t.seconds,
113        nanos: t.nanos,
114        ..Default::default()
115    })
116}
117
118fn trigger_details_from_proto(
119    msg: &ProtoTrigger,
120    symbol: Option<String>,
121    symbol_id_opt: Option<u32>,
122) -> Option<TriggerDetails> {
123    match msg.runtime_details.as_ref() {
124        Some(trigger::RuntimeDetails::Stop(stop)) => {
125            Some(TriggerDetails::Stop(TriggerStopDetails {
126                trigger_price: decode_price_ticks(stop.trigger_price_ticks, symbol.clone()),
127                trigger_price_source: trigger_price_source_label(stop.trigger_price_source),
128                trigger_direction: trigger_direction_label(stop.trigger_direction),
129            }))
130        }
131        Some(trigger::RuntimeDetails::Trailing(trailing)) => {
132            Some(TriggerDetails::Trailing(TriggerTrailingDetails {
133                trailing_distance: if trailing.trailing_distance_ticks > 0 {
134                    decode_price_ticks(trailing.trailing_distance_ticks, symbol.clone())
135                } else {
136                    None
137                },
138                trailing_distance_bps: trailing.trailing_distance_bps,
139                activation_price: if trailing.activation_price_ticks > 0 {
140                    decode_price_ticks(trailing.activation_price_ticks, symbol.clone())
141                } else {
142                    None
143                },
144                peak_price: if trailing.peak_price_ticks > 0 {
145                    decode_price_ticks(trailing.peak_price_ticks, symbol.clone())
146                } else {
147                    None
148                },
149                trough_price: if trailing.trough_price_ticks > 0 {
150                    decode_price_ticks(trailing.trough_price_ticks, symbol.clone())
151                } else {
152                    None
153                },
154                max_slippage: if trailing.max_slippage_ticks > 0 {
155                    decode_price_ticks(i64::from(trailing.max_slippage_ticks), symbol.clone())
156                } else {
157                    None
158                },
159                max_slippage_bps: trailing.max_slippage_bps,
160                trigger_price_source: trigger_price_source_label(trailing.trigger_price_source),
161                trigger_direction: trigger_direction_label(trailing.trigger_direction),
162            }))
163        }
164        Some(trigger::RuntimeDetails::TwapState(twap)) => {
165            Some(TriggerDetails::Twap(TriggerTwapDetails {
166                twap_duration_ms: twap.twap_duration_ms,
167                twap_slice_interval_ms: twap.twap_slice_interval_ms,
168                slice_idx: twap.slice_idx,
169                slice_count: twap.slice_count,
170                executed_qty: decode_qty_scaled(
171                    twap.executed_qty_scaled,
172                    None,
173                    symbol.clone(),
174                    symbol_id_opt,
175                ),
176            }))
177        }
178        Some(trigger::RuntimeDetails::LadderState(ladder)) => {
179            Some(TriggerDetails::Ladder(TriggerLadderDetails {
180                ladder_price_min: if ladder.ladder_price_min_ticks > 0 {
181                    decode_price_ticks(ladder.ladder_price_min_ticks, symbol.clone())
182                } else {
183                    None
184                },
185                ladder_price_max: if ladder.ladder_price_max_ticks > 0 {
186                    decode_price_ticks(ladder.ladder_price_max_ticks, symbol.clone())
187                } else {
188                    None
189                },
190                ladder_levels: ladder.ladder_levels,
191                ladder_distribution: ladder_distribution_label(ladder.ladder_distribution),
192            }))
193        }
194        None => None,
195    }
196}
197
198fn trigger_price_from_details(details: &Option<TriggerDetails>) -> Option<Price> {
199    match details {
200        Some(TriggerDetails::Stop(stop)) => stop.trigger_price.clone(),
201        _ => None,
202    }
203}
204
205/// Flat public trigger fields derived from the immutable `Configuration` oneof.
206#[derive(Default)]
207struct TriggerConfigProjection {
208    trigger_type: String,
209    side: String,
210    order_type: String,
211    time_in_force: String,
212    post_only: bool,
213    limit_price: Option<Price>,
214    trigger_price: Option<Price>,
215}
216
217/// Derive flat child fields (side/order_type/tif/post_only/limit_price) from a
218/// stop-loss / take-profit `ConditionalTrigger` configuration.
219fn conditional_child_projection(
220    cond: &ConditionalTrigger,
221    symbol: Option<String>,
222) -> (String, String, String, bool, Option<Price>) {
223    let side = enum_value_side(cond.side).to_owned();
224    let mut order_type = String::new();
225    let mut time_in_force = String::new();
226    let mut post_only = false;
227    let mut limit_price = None;
228    if let Some(child) = cond.child.as_option() {
229        match child.execution.as_ref() {
230            Some(conditional_child_execution::Execution::MarketIoc(_)) => {
231                order_type = "market".to_owned();
232                time_in_force = "ioc".to_owned();
233            }
234            Some(conditional_child_execution::Execution::LimitGtc(limit)) => {
235                order_type = "limit".to_owned();
236                time_in_force = "gtc".to_owned();
237                post_only = limit.post_only;
238                limit_price = decode_price_ticks(limit.price_ticks, symbol);
239            }
240            Some(conditional_child_execution::Execution::LimitIoc(limit)) => {
241                order_type = "limit".to_owned();
242                time_in_force = "ioc".to_owned();
243                limit_price = decode_price_ticks(limit.price_ticks, symbol);
244            }
245            Some(conditional_child_execution::Execution::LimitFok(limit)) => {
246                order_type = "limit".to_owned();
247                time_in_force = "fok".to_owned();
248                limit_price = decode_price_ticks(limit.price_ticks, symbol);
249            }
250            None => {}
251        }
252    }
253    (side, order_type, time_in_force, post_only, limit_price)
254}
255
256/// Derive the flat public trigger fields (type/side/order_type/tif/post_only/
257/// limit_price/trigger_price) from the immutable `Configuration` oneof.
258fn trigger_config_projection(
259    msg: &ProtoTrigger,
260    symbol: Option<String>,
261) -> TriggerConfigProjection {
262    let mut proj = TriggerConfigProjection::default();
263    match msg.configuration.as_ref() {
264        Some(trigger::Configuration::StopLoss(cond)) => {
265            proj.trigger_type = "stop_loss".to_owned();
266            let (side, order_type, tif, post_only, limit_price) =
267                conditional_child_projection(cond, symbol.clone());
268            proj.side = side;
269            proj.order_type = order_type;
270            proj.time_in_force = tif;
271            proj.post_only = post_only;
272            proj.limit_price = limit_price;
273            if cond.trigger_price_ticks != 0 {
274                proj.trigger_price = decode_price_ticks(cond.trigger_price_ticks, symbol);
275            }
276        }
277        Some(trigger::Configuration::TakeProfit(cond)) => {
278            proj.trigger_type = "take_profit".to_owned();
279            let (side, order_type, tif, post_only, limit_price) =
280                conditional_child_projection(cond, symbol.clone());
281            proj.side = side;
282            proj.order_type = order_type;
283            proj.time_in_force = tif;
284            proj.post_only = post_only;
285            proj.limit_price = limit_price;
286            if cond.trigger_price_ticks != 0 {
287                proj.trigger_price = decode_price_ticks(cond.trigger_price_ticks, symbol);
288            }
289        }
290        Some(trigger::Configuration::TrailingStop(_)) => {
291            // Trailing stop is an implicit SELL market-IOC strategy.
292            proj.trigger_type = "trailing_stop".to_owned();
293            proj.side = "sell".to_owned();
294            proj.order_type = "market".to_owned();
295            proj.time_in_force = "ioc".to_owned();
296        }
297        Some(trigger::Configuration::Twap(twap)) => {
298            proj.trigger_type = "twap".to_owned();
299            proj.side = enum_value_side(twap.side).to_owned();
300            match twap.execution.as_ref() {
301                Some(twap_trigger::Execution::LimitGtc(limit)) => {
302                    proj.order_type = "limit".to_owned();
303                    proj.time_in_force = "gtc".to_owned();
304                    proj.limit_price = decode_price_ticks(limit.price_ticks, symbol);
305                }
306                Some(twap_trigger::Execution::MarketIoc(_)) => {
307                    proj.order_type = "market".to_owned();
308                    proj.time_in_force = "ioc".to_owned();
309                }
310                None => {}
311            }
312        }
313        Some(trigger::Configuration::Ladder(ladder)) => {
314            proj.trigger_type = "ladder".to_owned();
315            proj.side = enum_value_side(ladder.side).to_owned();
316            proj.order_type = "limit".to_owned();
317            proj.time_in_force = "gtc".to_owned();
318            proj.post_only = ladder.post_only;
319        }
320        None => {}
321    }
322    proj
323}
324
325pub fn trigger_from_proto(msg: &ProtoTrigger) -> Trigger {
326    let symbol_id = msg.symbol_id;
327    let symbol_id_opt = if symbol_id == 0 {
328        None
329    } else {
330        Some(symbol_id)
331    };
332    let symbol = if msg.symbol.is_empty() {
333        None
334    } else {
335        Some(msg.symbol.clone())
336    };
337    let details = trigger_details_from_proto(msg, symbol.clone(), symbol_id_opt);
338    let proj = trigger_config_projection(msg, symbol.clone());
339    // Fall back to stop runtime details for the trigger-price convenience field.
340    let trigger_price = proj
341        .trigger_price
342        .clone()
343        .or_else(|| trigger_price_from_details(&details));
344    Trigger {
345        trigger_id: format_uint64_id(msg.trigger_id),
346        subaccount_id: format_uint64_id(msg.subaccount_id),
347        symbol_id,
348        symbol: msg.symbol.clone(),
349        trigger_type: proj.trigger_type,
350        status: enum_value_trigger_status(msg.status),
351        parent_order_id: msg.parent_order_id.map(format_uint64_id),
352        side: proj.side,
353        order_type: proj.order_type,
354        time_in_force: proj.time_in_force,
355        qty: decode_qty_scaled(msg.qty_scaled, None, symbol.clone(), symbol_id_opt),
356        limit_price: proj.limit_price,
357        fee_asset: fee_asset_label(msg.fee_asset),
358        self_trade_prevention_mode: stp_mode_label(msg.self_trade_prevention_mode),
359        post_only: proj.post_only,
360        trigger_price,
361        client_trigger_id: msg.client_trigger_id.clone(),
362        created_at: clone_timestamp(msg.created_at.as_option()),
363        updated_at: clone_timestamp(msg.updated_at.as_option()),
364        armed_at: clone_timestamp(msg.armed_at.as_option()),
365        completed_at: clone_timestamp(msg.completed_at.as_option()),
366        child_order_ids: msg
367            .child_order_ids
368            .iter()
369            .copied()
370            .map(format_uint64_id)
371            .collect(),
372        details,
373    }
374}
375
376pub fn triggers_list_from_proto(msg: &ListTriggersResponse) -> TriggersList {
377    let triggers: Vec<_> = msg.triggers.iter().map(trigger_from_proto).collect();
378    let total = triggers.len();
379    TriggersList {
380        triggers,
381        total,
382        next_page_token: msg.next_page_token.clone(),
383    }
384}
385
386pub fn get_trigger_from_proto(msg: &GetTriggerResponse) -> Option<Trigger> {
387    msg.trigger.as_option().map(trigger_from_proto)
388}
389
390fn trigger_mutation(
391    trigger_id: u64,
392    status: buffa::EnumValue<TriggerStatus>,
393) -> crate::errors::Result<TriggerMutationResult> {
394    let status = enum_value_trigger_status(status);
395    if trigger_id == 0 || status.is_empty() {
396        return Err(crate::Error::transport(
397            "invalid trigger mutation response: missing trigger_id or status",
398        ));
399    }
400    Ok(TriggerMutationResult {
401        trigger_id: format_uint64_id(trigger_id),
402        client_trigger_id: String::new(),
403        status,
404    })
405}
406
407/// `CreateTriggerResponse` acknowledges admission only and no longer carries a
408/// status field; synthesize `"accepted"`.
409pub fn trigger_mutation_from_create(
410    msg: &CreateTriggerResponse,
411) -> crate::errors::Result<TriggerMutationResult> {
412    if msg.trigger_id == 0 || msg.client_trigger_id.trim().is_empty() {
413        return Err(crate::Error::transport(
414            "invalid CreateTrigger response: missing trigger_id or client_trigger_id",
415        ));
416    }
417    Ok(TriggerMutationResult {
418        trigger_id: format_uint64_id(msg.trigger_id),
419        client_trigger_id: msg.client_trigger_id.clone(),
420        status: "accepted".to_owned(),
421    })
422}
423
424pub fn trigger_mutation_from_cancel(
425    msg: &CancelTriggerResponse,
426) -> crate::errors::Result<TriggerMutationResult> {
427    trigger_mutation(msg.trigger_id, msg.status)
428}
429
430pub fn trigger_mutation_from_pause(
431    msg: &PauseTriggerResponse,
432) -> crate::errors::Result<TriggerMutationResult> {
433    trigger_mutation(msg.trigger_id, msg.status)
434}
435
436pub fn trigger_mutation_from_resume(
437    msg: &ResumeTriggerResponse,
438) -> crate::errors::Result<TriggerMutationResult> {
439    trigger_mutation(msg.trigger_id, msg.status)
440}
441
442pub fn trigger_mutation_from_modify(
443    msg: &ModifyTriggerResponse,
444) -> crate::errors::Result<TriggerMutationResult> {
445    trigger_mutation(msg.trigger_id, msg.status)
446}
447
448fn enum_proto_name<E: Enumeration>(value: buffa::EnumValue<E>) -> String {
449    value
450        .as_known()
451        .map(|e| e.proto_name().to_owned())
452        .unwrap_or_else(|| format!("UNKNOWN({})", value.to_i32()))
453}
454
455pub fn trigger_event_from_proto(msg: &ProtoTriggerEvent) -> TriggerEvent {
456    TriggerEvent {
457        trigger_id: format_uint64_id(msg.trigger_id),
458        event_type: enum_proto_name(msg.event_type),
459        ts_ns: if msg.ts_ns == 0 {
460            String::new()
461        } else {
462            msg.ts_ns.to_string()
463        },
464    }
465}
466
467pub fn trigger_events_list_from_proto(msg: &ListTriggerEventsResponse) -> TriggerEventsList {
468    TriggerEventsList {
469        events: msg.events.iter().map(trigger_event_from_proto).collect(),
470        next_page_token: msg.next_page_token.clone(),
471    }
472}
473
474#[cfg(test)]
475mod tests {
476    use super::*;
477    use crate::proto::orders::v1::Side;
478    use crate::proto::triggers::v1::{
479        ConditionalChildExecution, ConditionalTrigger, GetTriggerResponse,
480        ListTriggerEventsResponse, ListTriggersResponse, StopDetails, TriggerEventType,
481        TriggerLimitGtc,
482    };
483
484    #[test]
485    fn trigger_from_proto_maps_status_and_stop_price() {
486        let msg = ProtoTrigger {
487            trigger_id: 42,
488            subaccount_id: 9,
489            symbol_id: 3,
490            symbol: "ETH-USDT".into(),
491            status: TriggerStatus::StatusArmed.into(),
492            qty_scaled: 100,
493            client_trigger_id: "cid".into(),
494            configuration: Some(trigger::Configuration::StopLoss(Box::new(
495                ConditionalTrigger {
496                    trigger_price_ticks: 5000,
497                    side: Side::Buy.into(),
498                    child: ConditionalChildExecution {
499                        execution: Some(conditional_child_execution::Execution::LimitGtc(
500                            Box::new(TriggerLimitGtc {
501                                price_ticks: 4990,
502                                post_only: true,
503                                ..Default::default()
504                            }),
505                        )),
506                        ..Default::default()
507                    }
508                    .into(),
509                    ..Default::default()
510                },
511            ))),
512            runtime_details: Some(trigger::RuntimeDetails::Stop(Box::new(StopDetails {
513                trigger_price_ticks: 5000,
514                ..Default::default()
515            }))),
516            ..Default::default()
517        };
518        let t = trigger_from_proto(&msg);
519        assert_eq!(t.trigger_id, format_uint64_id(42));
520        assert_eq!(t.subaccount_id, format_uint64_id(9));
521        assert_eq!(t.trigger_type, "stop_loss");
522        assert_eq!(t.status, "armed");
523        assert_eq!(t.side, "buy");
524        assert_eq!(t.order_type, "limit");
525        assert_eq!(t.time_in_force, "gtc");
526        assert!(t.post_only);
527        assert_eq!(t.limit_price.as_ref().unwrap().as_ticks(), 4990);
528        assert_eq!(t.qty.as_ref().unwrap().as_scaled(), 100);
529        assert_eq!(t.trigger_price.as_ref().unwrap().as_ticks(), 5000);
530        assert_eq!(t.client_trigger_id, "cid");
531        assert!(matches!(t.details, Some(TriggerDetails::Stop(_))));
532    }
533
534    #[test]
535    fn trigger_from_proto_projects_twap_child_orders_and_executed_qty() {
536        use crate::proto::triggers::v1::{TwapDetails, TwapTrigger};
537
538        let msg = ProtoTrigger {
539            trigger_id: 11,
540            symbol_id: 1,
541            symbol: "BTC-USDT".into(),
542            status: TriggerStatus::StatusRunning.into(),
543            qty_scaled: 100_000_000,
544            client_trigger_id: "twap-1".into(),
545            child_order_ids: vec![101, 202],
546            configuration: Some(trigger::Configuration::Twap(Box::new(TwapTrigger {
547                side: Side::Buy.into(),
548                duration_ms: 60_000,
549                slice_interval_ms: 5_000,
550                execution: Some(twap_trigger::Execution::MarketIoc(Box::default())),
551                ..Default::default()
552            }))),
553            runtime_details: Some(trigger::RuntimeDetails::TwapState(Box::new(TwapDetails {
554                twap_duration_ms: 60_000,
555                twap_slice_interval_ms: 5_000,
556                slice_idx: 2,
557                slice_count: 12,
558                executed_qty_scaled: 25_000_000,
559                ..Default::default()
560            }))),
561            ..Default::default()
562        };
563        let t = trigger_from_proto(&msg);
564        assert_eq!(t.trigger_type, "twap");
565        assert_eq!(t.side, "buy");
566        assert_eq!(t.order_type, "market");
567        assert_eq!(
568            t.child_order_ids,
569            vec![format_uint64_id(101), format_uint64_id(202)]
570        );
571        let Some(TriggerDetails::Twap(twap)) = t.details.as_ref() else {
572            panic!("expected twap details");
573        };
574        assert_eq!(twap.slice_idx, 2);
575        assert_eq!(twap.slice_count, 12);
576        assert_eq!(twap.executed_qty.as_ref().unwrap().as_scaled(), 25_000_000);
577    }
578
579    #[test]
580    fn trigger_status_from_label_validates() {
581        assert_eq!(
582            trigger_status_from_label("armed").unwrap(),
583            TriggerStatus::StatusArmed
584        );
585        assert_eq!(
586            trigger_status_from_label("cancelled").unwrap(),
587            TriggerStatus::StatusCanceled
588        );
589        assert!(trigger_status_from_label("nope").is_err());
590    }
591
592    #[test]
593    fn singular_trigger_mutations_reject_empty_success_responses() {
594        assert!(trigger_mutation_from_create(&CreateTriggerResponse::default()).is_err());
595        assert!(trigger_mutation_from_cancel(&CancelTriggerResponse::default()).is_err());
596        assert!(trigger_mutation_from_pause(&PauseTriggerResponse::default()).is_err());
597        assert!(trigger_mutation_from_resume(&ResumeTriggerResponse::default()).is_err());
598        assert!(trigger_mutation_from_modify(&ModifyTriggerResponse::default()).is_err());
599
600        let created = trigger_mutation_from_create(&CreateTriggerResponse {
601            trigger_id: 7,
602            client_trigger_id: "stable-trigger".into(),
603            ..Default::default()
604        })
605        .unwrap();
606        assert_eq!(created.client_trigger_id, "stable-trigger");
607    }
608
609    #[test]
610    fn triggers_list_and_get() {
611        let listed = triggers_list_from_proto(&ListTriggersResponse {
612            triggers: vec![ProtoTrigger {
613                trigger_id: 1,
614                symbol_id: 1,
615                ..Default::default()
616            }],
617            next_page_token: "trig-page-2".into(),
618            ..Default::default()
619        });
620        assert_eq!(listed.triggers.len(), 1);
621        assert_eq!(listed.total, 1);
622        assert_eq!(listed.next_page_token, "trig-page-2");
623
624        let got = get_trigger_from_proto(&GetTriggerResponse {
625            trigger: ProtoTrigger {
626                trigger_id: 3,
627                symbol_id: 1,
628                ..Default::default()
629            }
630            .into(),
631            ..Default::default()
632        });
633        assert_eq!(got.unwrap().trigger_id, format_uint64_id(3));
634    }
635
636    #[test]
637    fn trigger_events_list_keeps_next_page_token() {
638        let listed = trigger_events_list_from_proto(&ListTriggerEventsResponse {
639            events: vec![ProtoTriggerEvent {
640                trigger_id: 1,
641                event_type: TriggerEventType::EventFired.into(),
642                ts_ns: 123,
643                ..Default::default()
644            }],
645            next_page_token: "evt-page-2".into(),
646            ..Default::default()
647        });
648        assert_eq!(listed.events.len(), 1);
649        assert_eq!(listed.next_page_token, "evt-page-2");
650    }
651
652    #[test]
653    fn trigger_event_preserves_unknown_event_type_number() {
654        let event = trigger_event_from_proto(&ProtoTriggerEvent {
655            trigger_id: 1,
656            event_type: buffa::EnumValue::Unknown(321),
657            ..Default::default()
658        });
659        assert_eq!(event.event_type, "UNKNOWN(321)");
660    }
661}