lightstreamer_client/
subscription.rs

1use crate::subscription_listener::SubscriptionListener;
2use std::collections::HashMap;
3use std::error::Error;
4use std::fmt::{self, Debug, Formatter};
5use tokio::sync::watch::{self, Sender, Receiver};
6
7/// Enum representing the snapshot delivery preferences to be requested to Lightstreamer Server for the items in the Subscription.
8#[derive(Debug, Default)]
9pub enum Snapshot {
10    Yes,
11    No,
12    Number(usize),
13    #[default]
14    None,
15}
16
17impl Default for &Snapshot {
18    fn default() -> Self {
19        &Snapshot::None
20    }
21}
22
23impl ToString for Snapshot {
24    fn to_string(&self) -> String {
25        match self {
26            Snapshot::Yes => "true".to_string(),
27            Snapshot::No => "false".to_string(),
28            Snapshot::Number(n) => n.to_string(),
29            Snapshot::None => "none".to_string(),
30        }
31    }
32}
33
34/// Enum representing the subscription mode.
35#[derive(Debug, PartialEq, Eq)]
36pub enum SubscriptionMode {
37    Merge,
38    Distinct,
39    Raw,
40    Command,
41}
42
43impl ToString for SubscriptionMode {
44    fn to_string(&self) -> String {
45        match self {
46            SubscriptionMode::Merge => "MERGE".to_string(),
47            SubscriptionMode::Distinct => "DISTINCT".to_string(),
48            SubscriptionMode::Raw => "RAW".to_string(),
49            SubscriptionMode::Command => "COMMAND".to_string(),
50        }
51    }
52}
53
54/// Struct representing a Subscription to be submitted to a Lightstreamer Server.
55/// It contains subscription details and the listeners needed to process the real-time data.
56pub struct Subscription {
57    /// The subscription mode for the items, required by Lightstreamer Server.
58    mode: SubscriptionMode,
59    /// An array of items to be subscribed to through Lightstreamer server.
60    items: Option<Vec<String>>,
61    /// An "Item Group" identifier representing a list of items.
62    item_group: Option<String>,
63    /// An array of fields for the items to be subscribed to through Lightstreamer Server.
64    fields: Option<Vec<String>>,
65    /// A "Field Schema" identifier representing a list of fields.
66    field_schema: Option<String>,
67    /// The name of the Data Adapter that supplies all the items for this Subscription.
68    data_adapter: Option<String>,
69    /// The name of the second-level Data Adapter for a COMMAND Subscription.
70    command_second_level_data_adapter: Option<String>,
71    /// The "Field List" to be subscribed to through Lightstreamer Server for the second-level items in a COMMAND Subscription.
72    command_second_level_fields: Option<Vec<String>>,
73    /// The "Field Schema" to be subscribed to through Lightstreamer Server for the second-level items in a COMMAND Subscription.
74    command_second_level_field_schema: Option<String>,
75    /// The length to be requested to Lightstreamer Server for the internal queuing buffers for the items in the Subscription.
76    requested_buffer_size: Option<usize>,
77    /// The maximum update frequency to be requested to Lightstreamer Server for all the items in the Subscription.
78    requested_max_frequency: Option<f64>,
79    /// The snapshot delivery preferences to be requested to Lightstreamer Server for the items in the Subscription.
80    requested_snapshot: Option<Snapshot>,
81    /// The selector name for all the items in the Subscription, used as a filter on the updates received.
82    selector: Option<String>,
83    /// A list of SubscriptionListener instances that will receive events from this Subscription.
84    listeners: Vec<Box<dyn SubscriptionListener>>,
85    /// A HashMap storing the latest values received for each item/field pair.
86    values: HashMap<(usize, usize), String>,
87    /// A HashMap storing the latest values received for each key/field pair in a COMMAND Subscription.
88    command_values: HashMap<String, HashMap<usize, String>>,
89    /// A flag indicating whether the Subscription is currently active or not.
90    is_active: bool,
91    /// A flag indicating whether the Subscription is currently subscribed to through the server or not.
92    is_subscribed: bool,
93    /// Client assigned subscription ID.
94    pub(crate) id: usize,
95    /// A channel sender to send the subscription ID to the Lightstreamer client.
96    pub(crate) id_sender: Sender<usize>,
97    /// A channel receiver to receive the subscription ID from the Lightstreamer client.
98    pub(crate) id_receiver: Receiver<usize>,
99}
100
101impl Subscription {
102    /// Constructor for creating a new Subscription instance.
103    ///
104    /// # Parameters
105    /// - `mode`: The subscription mode for the items, required by Lightstreamer Server.
106    /// - `items`: An array of items to be subscribed to through Lightstreamer server. It is also possible to specify the "Item List" or "Item Group" later.
107    /// - `fields`: An array of fields for the items to be subscribed to through Lightstreamer Server. It is also possible to specify the "Field List" or "Field Schema" later.
108    ///
109    /// # Errors
110    /// Returns an error if no items or fields are provided.
111    pub fn new(
112        mode: SubscriptionMode,
113        items: Option<Vec<String>>,
114        fields: Option<Vec<String>>,
115    ) -> Result<Subscription, Box<dyn Error>> {
116        if items.is_none() || fields.is_none() {
117            return Err("Items and fields must be provided".to_string().into());
118        }
119        
120        let (id_sender, id_receiver) = watch::channel(0);
121        
122        Ok(Subscription {
123            mode,
124            items,
125            item_group: None,
126            fields,
127            field_schema: None,
128            data_adapter: None,
129            command_second_level_data_adapter: None,
130            command_second_level_fields: None,
131            command_second_level_field_schema: None,
132            requested_buffer_size: None,
133            requested_max_frequency: None,
134            requested_snapshot: None,
135            selector: None,
136            listeners: Vec::new(),
137            values: HashMap::new(),
138            command_values: HashMap::new(),
139            is_active: false,
140            is_subscribed: false,
141            id: 0,
142            id_sender,
143            id_receiver
144        })
145    }
146
147    /// Adds a listener that will receive events from the Subscription instance.
148    ///
149    /// The same listener can be added to several different Subscription instances.
150    ///
151    /// # Lifecycle
152    /// A listener can be added at any time. A call to add a listener already present will be ignored.
153    ///
154    /// # Parameters
155    /// - `listener`: An object that will receive the events as documented in the SubscriptionListener interface.
156    ///
157    /// # See also
158    /// `removeListener()`
159    pub fn add_listener(&mut self, listener: Box<dyn SubscriptionListener>) {
160        self.listeners.push(listener);
161    }
162
163    /// Removes a listener from the Subscription instance so that it will not receive events anymore.
164    ///
165    /// # Lifecycle
166    /// A listener can be removed at any time.
167    ///
168    /// # Parameters
169    /// - `listener`: The listener to be removed.
170    ///
171    /// # See also
172    /// `addListener()`
173    pub fn remove_listener<T>(&mut self, listener: &T)
174    where
175        T: SubscriptionListener,
176    {
177        self.listeners.retain(|l| {
178            let l_ref = l.as_ref() as &dyn SubscriptionListener;
179            let listener_ref = listener as &dyn SubscriptionListener;
180            !(std::ptr::addr_of!(*l_ref) == std::ptr::addr_of!(*listener_ref))
181        });
182    }
183
184    /// Returns a list containing the SubscriptionListener instances that were added to this client.
185    ///
186    /// # Returns
187    /// A list containing the listeners that were added to this client.
188    ///
189    /// # See also
190    /// `addListener()`
191    pub fn get_listeners(&self) -> &Vec<Box<dyn SubscriptionListener>> {
192        &self.listeners
193    }
194
195    /// Inquiry method that can be used to read the mode specified for this Subscription.
196    ///
197    /// # Lifecycle
198    /// This method can be called at any time.
199    ///
200    /// # Returns
201    /// The Subscription mode specified in the constructor.
202    pub fn get_mode(&self) -> &SubscriptionMode {
203        &self.mode
204    }
205
206    /// Setter method that sets the "Item Group" to be subscribed to through Lightstreamer Server.
207    ///
208    /// Any call to this method will override any "Item List" or "Item Group" previously specified.
209    ///
210    /// # Lifecycle
211    /// This method can only be called while the Subscription instance is in its "inactive" state.
212    ///
213    /// # Errors
214    /// Returns an error if the Subscription is currently "active".
215    ///
216    /// # Parameters
217    /// - `group`: A String to be expanded into an item list by the Metadata Adapter.
218    pub fn set_item_group(&mut self, group: String) -> Result<(), String> {
219        if self.is_active {
220            return Err("Subscription is active. This method can only be called while the Subscription instance is in its 'inactive' state.".to_string());
221        }
222        self.item_group = Some(group);
223        Ok(())
224    }
225
226    /// Inquiry method that can be used to read the item group specified for this Subscription.
227    ///
228    /// # Lifecycle
229    /// This method can only be called if the Subscription has been initialized using an "Item Group"
230    ///
231    /// # Returns
232    /// The "Item Group" to be subscribed to through the server, or `None` if the Subscription was initialized with an "Item List" or was not initialized at all.
233    pub fn get_item_group(&self) -> Option<&String> {
234        self.item_group.as_ref()
235    }
236
237    /// Setter method that sets the "Item List" to be subscribed to through Lightstreamer Server.
238    ///
239    /// Any call to this method will override any "Item List" or "Item Group" previously specified.
240    ///
241    /// # Lifecycle
242    /// This method can only be called while the Subscription instance is in its "inactive" state.
243    ///
244    /// # Errors
245    /// - Returns an error if the Subscription is currently "active".
246    /// - Returns an error if any of the item names in the "Item List" contains a space, is a number, or is empty/None.
247    ///
248    /// # Parameters
249    /// - `items`: An array of items to be subscribed to through the server.
250    pub fn set_items(&mut self, items: Vec<String>) -> Result<(), String> {
251        if self.is_active {
252            return Err("Subscription is active".to_string());
253        }
254        for item in &items {
255            if item.contains(" ") || item.parse::<usize>().is_ok() || item.is_empty() {
256                return Err("Invalid item name".to_string());
257            }
258        }
259        self.items = Some(items);
260        Ok(())
261    }
262
263    /// Inquiry method that can be used to read the "Item List" specified for this Subscription.
264    /// Note that if the single-item-constructor was used, this method will return an array of length 1 containing such item.
265    ///
266    /// # Lifecycle
267    /// This method can only be called if the Subscription has been initialized with an "Item List".
268    ///
269    /// # Returns
270    /// The "Item List" to be subscribed to through the server, or `None` if the Subscription was initialized with an "Item Group" or was not initialized at all.
271    pub fn get_items(&self) -> Option<&Vec<String>> {
272        self.items.as_ref()
273    }
274
275    /// Setter method that sets the "Field Schema" to be subscribed to through Lightstreamer Server.
276    ///
277    /// Any call to this method will override any "Field List" or "Field Schema" previously specified.
278    ///
279    /// # Lifecycle
280    /// This method can only be called while the Subscription instance is in its "inactive" state.
281    ///
282    /// # Errors
283    /// Returns an error if the Subscription is currently "active".
284    ///
285    /// # Parameters
286    /// - `schema`: A String to be expanded into a field list by the Metadata Adapter.
287    pub fn set_field_schema(&mut self, schema: String) -> Result<(), String> {
288        if self.is_active {
289            return Err("Subscription is active".to_string());
290        }
291        self.field_schema = Some(schema);
292        Ok(())
293    }
294
295    /// Inquiry method that can be used to read the field schema specified for this Subscription.
296    ///
297    /// # Lifecycle
298    /// This method can only be called if the Subscription has been initialized using a "Field Schema"
299    ///
300    /// # Returns
301    /// The "Field Schema" to be subscribed to through the server, or `None` if the Subscription was initialized with a "Field List" or was not initialized at all.
302    pub fn get_field_schema(&self) -> Option<&String> {
303        self.field_schema.as_ref()
304    }
305
306    /// Setter method that sets the "Field List" to be subscribed to through Lightstreamer Server.
307    ///
308    /// Any call to this method will override any "Field List" or "Field Schema" previously specified.
309    ///
310    /// # Lifecycle
311    /// This method can only be called while the Subscription instance is in its "inactive" state.
312    ///
313    /// # Errors
314    /// - Returns an error if the Subscription is currently "active".
315    /// - Returns an error if any of the field names in the list contains a space or is empty/None.
316    ///
317    /// # Parameters
318    /// - `fields`: An array of fields to be subscribed to through the server.
319    pub fn set_fields(&mut self, fields: Vec<String>) -> Result<(), String> {
320        if self.is_active {
321            return Err("Subscription is active".to_string());
322        }
323        for field in &fields {
324            if field.contains(" ") || field.is_empty() {
325                return Err("Invalid field name".to_string());
326            }
327        }
328        self.fields = Some(fields);
329        Ok(())
330    }
331
332    /// Inquiry method that can be used to read the "Field List" specified for this Subscription.
333    ///
334    /// # Lifecycle
335    /// This method can only be called if the Subscription has been initialized using a "Field List".
336    ///
337    /// # Returns
338    /// The "Field List" to be subscribed to through the server, or `None` if the Subscription was initialized with a "Field Schema" or was not initialized at all.
339    pub fn get_fields(&self) -> Option<&Vec<String>> {
340        self.fields.as_ref()
341    }
342
343    /// Setter method that sets the name of the Data Adapter (within the Adapter Set used by the current session) that supplies all the items for this Subscription.
344    ///
345    /// The Data Adapter name is configured on the server side through the "name" attribute of the `<data_provider>` element, in the "adapters.xml" file that defines the Adapter Set (a missing attribute configures the "DEFAULT" name).
346    ///
347    /// Note that if more than one Data Adapter is needed to supply all the items in a set of items, then it is not possible to group all the items of the set in a single Subscription. Multiple Subscriptions have to be defined.
348    ///
349    /// # Default
350    /// The default Data Adapter for the Adapter Set, configured as "DEFAULT" on the Server.
351    ///
352    /// # Lifecycle
353    /// This method can only be called while the Subscription instance is in its "inactive" state.
354    ///
355    /// # Errors
356    /// Returns an error if the Subscription is currently "active".
357    ///
358    /// # Parameters
359    /// - `adapter`: The name of the Data Adapter. A `None` value is equivalent to the "DEFAULT" name.
360    ///
361    /// # See also
362    /// `ConnectionDetails.setAdapterSet()`
363    pub fn set_data_adapter(&mut self, adapter: Option<String>) -> Result<(), String> {
364        if self.is_active {
365            return Err("Subscription is active".to_string());
366        }
367        self.data_adapter = adapter;
368        Ok(())
369    }
370
371    /// Inquiry method that can be used to read the name of the Data Adapter specified for this Subscription through `setDataAdapter()`.
372    ///
373    /// # Lifecycle
374    /// This method can be called at any time.
375    ///
376    /// # Returns
377    /// The name of the Data Adapter; returns `None` if no name has been configured, so that the "DEFAULT" Adapter Set is used.
378    pub fn get_data_adapter(&self) -> Option<&String> {
379        self.data_adapter.as_ref()
380    }
381
382    /// Setter method that sets the name of the second-level Data Adapter (within the Adapter Set used by the current session)
383    /// Setter method that sets the name of the second-level Data Adapter (within the Adapter Set used by the current session) that supplies all the second-level items for a COMMAND Subscription.
384    ///
385    /// All the possible second-level items should be supplied in "MERGE" mode with snapshot available.
386    ///
387    /// The Data Adapter name is configured on the server side through the "name" attribute of the `<data_provider>` element, in the "adapters.xml" file that defines the Adapter Set (a missing attribute configures the "DEFAULT" name).
388    ///
389    /// # Default
390    /// The default Data Adapter for the Adapter Set, configured as "DEFAULT" on the Server.
391    ///
392    /// # Lifecycle
393    /// This method can only be called while the Subscription instance is in its "inactive" state.
394    ///
395    /// # Errors
396    /// - Returns an error if the Subscription is currently "active".
397    /// - Returns an error if the Subscription mode is not "COMMAND".
398    ///
399    /// # Parameters
400    /// - `adapter`: The name of the Data Adapter. A `None` value is equivalent to the "DEFAULT" name.
401    ///
402    /// # See also
403    /// `Subscription.setCommandSecondLevelFields()`
404    ///
405    /// # See also
406    /// `Subscription.setCommandSecondLevelFieldSchema()`
407    pub fn set_command_second_level_data_adapter(
408        &mut self,
409        adapter: Option<String>,
410    ) -> Result<(), String> {
411        if self.is_active {
412            return Err("Subscription is active".to_string());
413        }
414        if self.mode != SubscriptionMode::Command {
415            return Err("Subscription mode is not Command".to_string());
416        }
417        self.command_second_level_data_adapter = adapter;
418        Ok(())
419    }
420
421    /// Inquiry method that can be used to read the name of the second-level Data Adapter specified for this Subscription through `setCommandSecondLevelDataAdapter()`.
422    ///
423    /// # Lifecycle
424    /// This method can be called at any time.
425    ///
426    /// # Errors
427    /// Returns an error if the Subscription mode is not COMMAND.
428    ///
429    /// # Returns
430    /// The name of the second-level Data Adapter.
431    ///
432    /// # See also
433    /// `setCommandSecondLevelDataAdapter()`
434    pub fn get_command_second_level_data_adapter(&self) -> Option<&String> {
435        if self.mode != SubscriptionMode::Command {
436            return None;
437        }
438        self.command_second_level_data_adapter.as_ref()
439    }
440
441    /// Setter method that sets the "Field Schema" to be subscribed to through Lightstreamer Server for the second-level items. It can only be used on COMMAND Subscriptions.
442    ///
443    /// Any call to this method will override any "Field List" or "Field Schema" previously specified for the second-level.
444    ///
445    /// Calling this method enables the two-level behavior:
446    ///
447    /// In synthesis, each time a new key is received on the COMMAND Subscription, the key value is treated as an Item name and an underlying Subscription for this Item is created and subscribed to automatically, to feed fields specified by this method. This mono-item Subscription is specified through an "Item List" containing only the Item name received. As a consequence, all the conditions provided for subscriptions through Item Lists have to be satisfied. The item is subscribed to in "MERGE" mode, with snapshot request and with the same maximum frequency setting as for the first-level items (including the "unfiltered" case). All other Subscription properties are left as the default. When the key is deleted by a DELETE command on the first-level Subscription, the associated second-level Subscription is also unsubscribed from.
448    ///
449    /// Specify `None` as parameter will disable the two-level behavior.
450    ///
451    /// # Lifecycle
452    /// This method can only be called while the Subscription instance is in its "inactive" state.
453    ///
454    /// # Errors
455    /// - Returns an error if the Subscription is currently "active".
456    /// - Returns an error if the Subscription mode is not "COMMAND".
457    ///
458    /// # Parameters
459    /// - `schema`: A String to be expanded into a field list by the Metadata Adapter.
460    ///
461    /// # See also
462    /// `Subscription.setCommandSecondLevelFields()`
463    pub fn set_command_second_level_field_schema(
464        &mut self,
465        schema: Option<String>,
466    ) -> Result<(), String> {
467        if self.is_active {
468            return Err("Subscription is active".to_string());
469        }
470        if self.mode != SubscriptionMode::Command {
471            return Err("Subscription mode is not Command".to_string());
472        }
473        self.command_second_level_field_schema = schema;
474        Ok(())
475    }
476
477    /// Inquiry method that can be used to read the "Field Schema" specified for second-level Subscriptions.
478    ///
479    /// # Lifecycle
480    /// This method can only be called if the second-level of this Subscription has been initialized using a "Field Schema".
481    ///
482    /// # Errors
483    /// Returns an error if the Subscription mode is not COMMAND.
484    ///
485    /// # Returns
486    /// The "Field Schema" to be subscribed to through the server, or `None` if the Subscription was initialized with a "Field List" or was not initialized at all.
487    ///
488    /// # See also
489    /// `Subscription.setCommandSecondLevelFieldSchema()`
490    pub fn get_command_second_level_field_schema(&self) -> Option<&String> {
491        if self.mode != SubscriptionMode::Command {
492            return None;
493        }
494        self.command_second_level_field_schema.as_ref()
495    }
496
497    /// Setter method that sets the "Field List" to be subscribed to through Lightstreamer Server for the second-level items. It can only be used on COMMAND Subscriptions.
498    ///
499    /// Any call to this method will override any "Field List" or "Field Schema" previously specified for the second-level.
500    ///
501    /// Calling this method enables the two-level behavior:
502    ///
503    /// In synthesis, each time a new key is received on the COMMAND Subscription, the key value is treated as an Item name and an underlying Subscription for this Item is created and subscribed to automatically, to feed fields specified by this method. This mono-item Subscription is specified through an "Item List" containing only the Item name received. As a consequence, all the conditions provided for subscriptions through Item Lists have to be satisfied. The item is subscribed to in "MERGE" mode, with snapshot request and with the same maximum frequency setting as for the first-level items (including the "unfiltered" case). All other Subscription properties are left as the default. When the key is deleted by a DELETE command on the first-level Subscription, the associated second-level Subscription is also unsubscribed from.
504    ///
505    /// Specifying `None` as parameter will disable the two-level behavior.
506    ///
507    /// # Lifecycle
508    /// This method can only be called while the Subscription instance is in its "inactive" state.
509    ///
510    /// # Errors
511    /// - Returns an error if the Subscription is currently "active".
512    /// - Returns an error if the Subscription mode is not "COMMAND".
513    /// - Returns an error if any of the field names in the "Field List" contains a space or is empty/None.
514    ///
515    /// # Parameters
516    /// - `fields`: An array of Strings containing a list of fields to be subscribed to through the server. Ensure that no name conflict is generated between first-level and second-level fields. In case of conflict, the second-level field will not be accessible by name, but only by position.
517    ///
518    /// # See also
519    /// `Subscription.setCommandSecondLevelFieldSchema()`
520    pub fn set_command_second_level_fields(
521        &mut self,
522        fields: Option<Vec<String>>,
523    ) -> Result<(), String> {
524        if self.is_active {
525            return Err("Subscription is active".to_string());
526        }
527        if self.mode != SubscriptionMode::Command {
528            return Err("Subscription mode is not Command".to_string());
529        }
530        if let Some(ref fields) = fields {
531            for field in fields {
532                if field.contains(" ") || field.is_empty() {
533                    return Err("Invalid field name".to_string());
534                }
535            }
536        }
537        self.command_second_level_fields = fields;
538        Ok(())
539    }
540
541    /// Inquiry method that can be used to read the "Field List" specified for second-level Subscriptions.
542    ///
543    /// # Lifecycle
544    /// This method can only be called if the second-level of this Subscription has been initialized using a "Field List"
545    ///
546    /// # Errors
547    /// Returns an error if the Subscription mode is not COMMAND.
548    ///
549    /// # Returns
550    /// The list of fields to be subscribed to through the server, or `None` if the Subscription was initialized with a "Field Schema" or was not initialized at all.
551    ///
552    /// # See also
553    /// `Subscription.setCommandSecondLevelFields()`
554    pub fn get_command_second_level_fields(&self) -> Option<&Vec<String>> {
555        if self.mode != SubscriptionMode::Command {
556            return None;
557        }
558        self.command_second_level_fields.as_ref()
559    }
560
561    /// Setter method that sets the length to be requested to Lightstreamer Server for the internal queuing buffers for the items in the Subscription. A Queuing buffer is used by the Server to accumulate a burst of updates for an item, so that they can all be sent to the client, despite of bandwidth or frequency limits. It can be used only when the subscription mode is MERGE or DISTINCT and unfiltered dispatching has not been requested. Note that the Server may pose an upper limit on the size of its internal buffers.
562    ///
563    /// # Default
564    /// `None`, meaning to lean on the Server default based on the subscription mode. This means that the buffer size will be 1 for MERGE subscriptions and "unlimited" for DISTINCT subscriptions. See the "General Concepts" document for further details.
565    ///
566    /// # Lifecycle
567    /// This method can only be called while the Subscription instance is in its "inactive" state.
568    ///
569    /// # Errors
570    /// - Returns an error if the Subscription is currently "active".
571    /// - Returns an error if the specified value is not `None` nor "unlimited" nor a valid positive integer number.
572    ///
573    /// # Parameters
574    /// - `size`: An integer number, representing the length of the internal queuing buffers to be used in the Server. If the string "unlimited" is supplied, then no buffer size limit is requested (the check is case insensitive). It is also possible to supply a `None` value to stick to the Server default (which currently depends on the subscription mode).
575    ///
576    /// # See also
577    /// `Subscription.setRequestedMaxFrequency()`
578    pub fn set_requested_buffer_size(&mut self, size: Option<usize>) -> Result<(), String> {
579        if self.is_active {
580            return Err("Subscription is active".to_string());
581        }
582        self.requested_buffer_size = size;
583        Ok(())
584    }
585
586    /// Inquiry method that can be used to read the buffer size, configured though `setRequestedBufferSize()`, to be requested to the Server for this Subscription.
587    ///
588    /// # Lifecycle
589    /// This method can be called at any time.
590    ///
591    /// # Returns
592    /// An integer number, representing the buffer size to be requested to the server, or the string "unlimited", or `None`.
593    pub fn get_requested_buffer_size(&self) -> Option<&usize> {
594        self.requested_buffer_size.as_ref()
595    }
596
597    /// Setter method that sets the maximum update frequency to be requested to Lightstreamer Server for all the items in the Subscription. It can be used only if the Subscription mode is MERGE, DISTINCT or COMMAND (in the latter case, the frequency limitation applies to the UPDATE events for each single key). For Subscriptions with two-level behavior (see `Subscription.setCommandSecondLevelFields()` and `Subscription.setCommandSecondLevelFieldSchema()`), the specified frequency limit applies to both first-level and second-level items.
598    ///
599    /// Note that frequency limits on the items can also be set on the server side and this request can only be issued in order to furtherly reduce the frequency, not to rise it beyond these limits.
600    ///
601    /// This method can also be used to request unfiltered dispatching for the items in the Subscription. However, unfiltered dispatching requests may be refused if any frequency limit is posed on the server side for some item.
602    ///
603    /// # General Edition Note
604    /// A further global frequency limit could also be imposed by the Server, depending on Edition and License Type; this specific limit also applies to RAW mode and to unfiltered dispatching. To know what features are enabled by your license, please see the License tab of the Monitoring Dashboard (by default, available at /dashboard).
605    ///
606    /// # Default
607    /// `None`, meaning to lean on the Server default based on the subscription mode. This consists, for all modes, in not applying any frequency limit to the subscription (the same as "unlimited"); see the "General Concepts" document for further details.
608    ///
609    /// # Lifecycle
610    /// This method can can be called at any time with some differences based on the Subscription status:
611    ///
612    /// - If the Subscription instance is in its "inactive" state then this method can be called at will.
613    ///
614    /// - If the Subscription instance is in its "active" state then the method can still be called unless the current value is "unfiltered" or the supplied value is "unfiltered" or `None`. If the Subscription instance is in its "active" state and the connection to the server is currently open, then a request to change the frequency of the Subscription on the fly is sent to the server.
615    ///
616    /// # Errors
617    /// - Returns an error if the Subscription is currently "active" and the current value of this property is "unfiltered".
618    /// - Returns an error if the Subscription is currently "active" and the given parameter is `None` or "unfiltered".
619    /// - Returns an error if the specified value is not `None` nor one of the special "unlimited" and "unfiltered" values nor a valid positive number.
620    ///
621    /// # Parameters
622    /// - `freq`: A decimal number, representing the maximum update frequency (expressed in updates per second) for each item in the Subscription; for instance, with a setting of 0.5, for each single item, no more than one update every 2 seconds will be received. If the string "unlimited" is supplied, then no frequency limit is requested. It is also possible to supply the string "unfiltered", to ask for unfiltered dispatching, if it is allowed for the items, or a `None` value to stick to the Server default (which currently corresponds to "unlimited"). The check for the string constants is case insensitive.
623    pub fn set_requested_max_frequency(&mut self, freq: Option<f64>) -> Result<(), String> {
624        if self.is_active && self.requested_max_frequency.is_none() {
625            return Err("Subscription is active and current value is unfiltered".to_string());
626        }
627        if self.is_active && freq.is_none() {
628            return Err("Cannot set unfiltered while active".to_string());
629        }
630        if self.is_active && freq.is_none() {
631            return Err("Cannot set None while active".to_string());
632        }
633        self.requested_max_frequency = freq;
634        Ok(())
635    }
636
637    /// Inquiry method that can be used to read the max frequency, configured through `setRequestedMaxFrequency()`, to be requested to the Server for this Subscription.
638    ///
639    /// # Lifecycle
640    /// This method can be called at any time.
641    ///
642    /// # Returns
643    /// A decimal number, representing the max frequency to be requested to the server (expressed in updates per second), or the strings "unlimited" or "unfiltered", or `None`.
644    pub fn get_requested_max_frequency(&self) -> Option<&f64> {
645        self.requested_max_frequency.as_ref()
646    }
647
648    /// Setter method that enables/disables snapshot delivery request for the items in the Subscription. The snapshot can be requested only if the Subscription mode is MERGE, DISTINCT or COMMAND.
649    ///
650    /// # Default
651    /// "yes" if the Subscription mode is not "RAW", `None` otherwise.
652    ///
653    /// # Lifecycle
654    /// This method can only be called while the Subscription instance is in its "inactive" state.
655    ///
656    /// # Errors
657    /// - Returns an error if the Subscription is currently "active".
658    /// - Returns an error if the specified value is not "yes" nor "no" nor `None` nor a valid integer positive number.
659    /// - Returns an error if the specified value is not compatible with the mode of the Subscription:
660    ///     - In case of a RAW Subscription only `None` is a valid value;
661    ///     - In case of a non-DISTINCT Subscription only `None` "yes" and "no" are valid values.
662    ///
663    /// # Parameters
664    /// - `snapshot`: "yes"/"no" to request/not request snapshot delivery (the check is case insensitive). If the Subscription mode is DISTINCT, instead of "yes", it is also possible to supply an integer number, to specify the requested length of the snapshot (though the length of the received snapshot may be less than
665    /// requested, because of insufficient data or server side limits); passing "yes" means that the snapshot length should be determined only by the Server. `None` is also a valid value; if specified, no snapshot preference will be sent to the server that will decide itself whether or not to send any snapshot.
666    ///
667    /// # See also
668    /// `ItemUpdate.isSnapshot()`
669    pub fn set_requested_snapshot(&mut self, snapshot: Option<Snapshot>) -> Result<(), String> {
670        if self.is_active {
671            return Err("Subscription is active".to_string());
672        }
673        match snapshot {
674            Some(Snapshot::None) => {
675                if self.mode == SubscriptionMode::Raw {
676                    return Err("Cannot request snapshot for Raw mode".to_string());
677                }
678            }
679            Some(Snapshot::Number(_)) => {
680                if self.mode != SubscriptionMode::Distinct {
681                    return Err("Cannot specify snapshot length for non-Distinct mode".to_string());
682                }
683            }
684            _ => {}
685        }
686        self.requested_snapshot = snapshot;
687        Ok(())
688    }
689
690    /// Inquiry method that can be used to read the snapshot preferences, configured through `setRequestedSnapshot()`, to be requested to the Server for this Subscription.
691    ///
692    /// # Lifecycle
693    /// This method can be called at any time.
694    ///
695    /// # Returns
696    /// "yes", "no", `None`, or an integer number.
697    pub fn get_requested_snapshot(&self) -> Option<&Snapshot> {
698        self.requested_snapshot.as_ref()
699    }
700
701    /// Setter method that sets the selector name for all the items in the Subscription. The selector is a filter on the updates received. It is executed on the Server and implemented by the Metadata Adapter.
702    ///
703    /// # Default
704    /// `None` (no selector).
705    ///
706    /// # Lifecycle
707    /// This method can only be called while the Subscription instance is in its "inactive" state.
708    ///
709    /// # Errors
710    /// Returns an error if the Subscription is currently "active".
711    ///
712    /// # Parameters
713    /// - `selector`: The name of a selector, to be recognized by the Metadata Adapter, or `None` to unset the selector.
714    pub fn set_selector(&mut self, selector: Option<String>) -> Result<(), String> {
715        if self.is_active {
716            return Err("Subscription is active".to_string());
717        }
718        self.selector = selector;
719        Ok(())
720    }
721
722    /// Inquiry method that can be used to read the selector name specified for this Subscription through `setSelector()`.
723    ///
724    /// # Lifecycle
725    /// This method can be called at any time.
726    ///
727    /// # Returns
728    /// The name of the selector.
729    pub fn get_selector(&self) -> Option<&String> {
730        self.selector.as_ref()
731    }
732
733    /// Returns the latest value received for the specified item/field pair.
734    ///
735    /// It is suggested to consume real-time data by implementing and adding a proper SubscriptionListener rather than probing this method. In case of COMMAND Subscriptions, the value returned by this method may be misleading, as in COMMAND mode all the keys received, being part of the same item, will overwrite each other; for COMMAND Subscriptions, use `Subscription.getCommandValue()` instead.
736    ///
737    /// Note that internal data is cleared when the Subscription is unsubscribed from.
738    ///
739    /// # Lifecycle
740    /// This method can be called at any time; if called to retrieve a value that has not been received yet, then it will return `None`.
741    ///
742    /// # Errors
743    /// Returns an error if an invalid item name or field name is specified or if the specified item position or field position is out of bounds.
744    ///
745    /// # Parameters
746    /// - `item_pos`: A String representing an item in the configured item list or a Number representing the 1-based position of the item in the specified item group. (In case an item list was specified, passing the item position is also possible).
747    /// - `field_pos`: A String representing a field in the configured field list or a Number representing the 1-based position of the field in the specified field schema. (In case a field list was specified, passing the field position is also possible).
748    ///
749    /// # Returns
750    /// The current value for the specified field of the specified item(possibly `None`), or `None` if no value has been received yet.
751    pub fn get_value(&self, item_pos: usize, field_pos: usize) -> Option<&String> {
752        self.values.get(&(item_pos, field_pos))
753    }
754
755    /// Returns the latest value received for the specified item/key/field combination in a COMMAND Subscription. This method can only be used if the Subscription mode is COMMAND. Subscriptions with two-level behavior are also supported, hence the specified field can be either a first-level or a second-level one.
756    ///
757    /// It is suggested to consume real-time data by implementing and adding a proper SubscriptionListener rather than probing this method.
758    ///
759    /// Note that internal data is cleared when the Subscription is unsubscribed from.
760    ///
761    /// # Lifecycle
762    /// This method can be called at any time; if called to retrieve a value that has not been received yet, then it will return `None`.
763    ///
764    /// # Errors
765    /// - Returns an error if an invalid item name or field name is specified or if the specified item position or field position is out of bounds.
766    /// - Returns an error if the Subscription mode is not COMMAND.
767    ///
768    /// # Parameters
769    /// - `item_pos`: A String representing an item in the configured item list or a Number representing the 1-based position of the item in the specified item group. (In case an item list was specified, passing the item position is also possible).
770    /// - `key`: A String containing the value of a key received on the COMMAND subscription.
771    /// - `field_pos`: A String representing a field in the configured field list or a Number representing the 1-based position of the field in the specified field schema. (In case a field list was specified, passing the field position is also possible).
772    ///
773    /// # Returns
774    /// The current value for the specified field of the specified key within the specified item (possibly `None`), or `None` if the specified key has not been added yet (note that it might have been added and eventually deleted).
775    pub fn get_command_value(
776        &self,
777        item_pos: usize,
778        key: &str,
779        field_pos: usize,
780    ) -> Option<&String> {
781        let key = format!("{}_{}", item_pos, key);
782        self.command_values
783            .get(&key)
784            .and_then(|fields| fields.get(&field_pos))
785    }
786
787    /// Inquiry method that checks if the Subscription is currently "active" or not. Most of the Subscription properties cannot be modified if a Subscription is "active".
788    ///
789    /// The status of a Subscription is changed to "active" through the `LightstreamerClient.subscribe()` method and back to "inactive" through the `LightstreamerClient.unsubscribe()` one.
790    ///
791    /// # Lifecycle
792    /// This method can be called at any time.
793    ///
794    /// # Returns
795    /// `true`/`false` if the Subscription is "active" or not.
796    ///
797    /// # See also
798    /// `LightstreamerClient.subscribe()`
799    ///
800    /// # See also
801    /// `LightstreamerClient.unsubscribe()`
802    pub fn is_active(&self) -> bool {
803        self.is_active
804    }
805
806    /// Inquiry method that checks if the Subscription is currently subscribed to through the server or not.
807    ///
808    /// This flag is switched to true by server sent Subscription events, and back to false in case of client disconnection, `LightstreamerClient.unsubscribe()` calls and server sent unsubscription events.
809    ///
810    /// # Lifecycle
811    /// This method can be called at any time.
812    ///
813    /// # Returns
814    /// `true`/`false` if the Subscription is subscribed to through the server or not.
815    pub fn is_subscribed(&self) -> bool {
816        self.is_subscribed
817    }
818
819    /// Returns the position of the "key" field in a COMMAND Subscription.
820    ///
821    /// This method can only be used if the Subscription mode is COMMAND and the Subscription was initialized using a "Field Schema".
822    ///
823    /// # Lifecycle
824    /// This method can be called at any time after the first `SubscriptionListener.onSubscription()` event.
825    ///
826    /// # Errors
827    /// - Returns an error if the Subscription mode is not COMMAND or if the `SubscriptionListener.onSubscription()` event for this Subscription was not yet fired.
828    /// - Returns an error if a "Field List" was specified.
829    ///
830    /// # Returns
831    /// The 1-based position of the "key" field within the "Field Schema".
832    pub fn get_key_position(&self) -> Option<usize> {
833        if self.mode != SubscriptionMode::Command || !self.is_subscribed {
834            return None;
835        }
836        if let Some(ref schema) = self.field_schema {
837            return schema.split(',').position(|field| field.trim() == "key");
838        }
839        None
840    }
841
842    /// Returns the position of the "command" field in a COMMAND Subscription.
843    ///
844    /// This method can only be used if the Subscription mode is COMMAND and the Subscription was initialized using a "Field Schema".
845    ///
846    /// # Lifecycle
847    /// This method can be called at any time after the first `SubscriptionListener.onSubscription()` event.
848    ///
849    /// # Errors
850    /// - Returns an error if the Subscription mode is not COMMAND or if the `SubscriptionListener.onSubscription()` event for this Subscription was not yet fired.
851    ///
852    /// # Returns
853    /// The 1-based position of the "command" field within the "Field Schema".
854    pub fn get_command_position(&self) -> Option<usize> {
855        if self.mode != SubscriptionMode::Command || !self.is_subscribed {
856            return None;
857        }
858        if let Some(ref schema) = self.field_schema {
859            return schema
860                .split(',')
861                .position(|field| field.trim() == "command");
862        }
863        None
864    }
865
866    /*
867    /// Handles the subscription event.
868    pub fn on_subscription(&mut self) {
869        self.is_subscribed = true;
870        for listener in &mut self.listeners {
871            listener.on_subscription();
872        }
873    }
874
875    /// Handles the unsubscription event.
876    pub fn on_unsubscription(&mut self) {
877        self.is_subscribed = false;
878        self.values.clear();
879        self.command_values.clear();
880        for listener in &mut self.listeners {
881            listener.on_unsubscription();
882        }
883    }
884
885    /// Handles an update event for a regular Subscription.
886    pub fn on_update(&mut self, item_pos: usize, field_pos: usize, value: String, is_snapshot: bool) {
887        self.values.insert((item_pos, field_pos), value.clone());
888        for listener in &mut self.listeners {
889            listener.on_update(item_pos, field_pos, &value, is_snapshot);
890        }
891    }
892
893    /// Handles an update event for a COMMAND Subscription.
894    pub fn on_command_update(&mut self, key: String, item_pos: usize, field_pos: usize, value: String, is_snapshot: bool) {
895        self.command_values
896            .entry(key.clone())
897            .or_insert_with(HashMap::new)
898            .insert(field_pos, value.clone());
899        for listener in &mut self.listeners {
900            listener.on_command_update(&key, item_pos, field_pos, &value, is_snapshot);
901        }
902    }
903    */
904}
905
906impl Debug for Subscription {
907    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
908        f.debug_struct("Subscription")
909            .field("mode", &self.mode)
910            .field("item_group", &self.item_group)
911            .field("items", &self.items)
912            .field("field_schema", &self.field_schema)
913            .field("fields", &self.fields)
914            .field("data_adapter", &self.data_adapter)
915            .field(
916                "command_second_level_data_adapter",
917                &self.command_second_level_data_adapter,
918            )
919            .field(
920                "command_second_level_field_schema",
921                &self.command_second_level_field_schema,
922            )
923            .field(
924                "command_second_level_fields",
925                &self.command_second_level_fields,
926            )
927            .field("requested_buffer_size", &self.requested_buffer_size)
928            .field("requested_max_frequency", &self.requested_max_frequency)
929            .field("requested_snapshot", &self.requested_snapshot)
930            .field("selector", &self.selector)
931            .field("is_active", &self.is_active)
932            .field("is_subscribed", &self.is_subscribed)
933            .finish()
934    }
935}