From 7e1eb27a06e5545b3d1b77b5998dc0463df27d70 Mon Sep 17 00:00:00 2001 From: daniloaz Date: Sun, 24 Mar 2024 20:39:38 +0100 Subject: Created structure and scaffolding for the Lightstreamer client. --- src/subscription.rs | 840 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 840 insertions(+) create mode 100644 src/subscription.rs (limited to 'src/subscription.rs') diff --git a/src/subscription.rs b/src/subscription.rs new file mode 100644 index 0000000..035614d --- /dev/null +++ b/src/subscription.rs @@ -0,0 +1,840 @@ +use crate::subscription_listener::SubscriptionListener; +use std::collections::HashMap; + +/// Enum representing the subscription mode +#[derive(Debug, PartialEq, Eq)] +pub enum SubscriptionMode { + Merge, + Distinct, + Raw, + Command, +} + +impl SubscriptionMode { + fn from_str(s: &str) -> Result { + match s.to_lowercase().as_str() { + "merge" => Ok(SubscriptionMode::Merge), + "distinct" => Ok(SubscriptionMode::Distinct), + "raw" => Ok(SubscriptionMode::Raw), + "command" => Ok(SubscriptionMode::Command), + _ => Err(format!("Invalid subscription mode: {}", s)), + } + } +} + +/// Struct representing a Subscription to be submitted to a Lightstreamer Server. +/// It contains subscription details and the listeners needed to process the real-time data. +pub struct Subscription { + /// The subscription mode for the items, required by Lightstreamer Server. + mode: SubscriptionMode, + /// An array of items to be subscribed to through Lightstreamer server. + items: Option>, + /// An "Item Group" identifier representing a list of items. + item_group: Option, + /// An array of fields for the items to be subscribed to through Lightstreamer Server. + fields: Option>, + /// A "Field Schema" identifier representing a list of fields. + field_schema: Option, + /// The name of the Data Adapter that supplies all the items for this Subscription. + data_adapter: Option, + /// The name of the second-level Data Adapter for a COMMAND Subscription. + command_second_level_data_adapter: Option, + /// The "Field List" to be subscribed to through Lightstreamer Server for the second-level items in a COMMAND Subscription. + command_second_level_fields: Option>, + /// The "Field Schema" to be subscribed to through Lightstreamer Server for the second-level items in a COMMAND Subscription. + command_second_level_field_schema: Option, + /// The length to be requested to Lightstreamer Server for the internal queuing buffers for the items in the Subscription. + requested_buffer_size: Option, + /// The maximum update frequency to be requested to Lightstreamer Server for all the items in the Subscription. + requested_max_frequency: Option, + /// The snapshot delivery preferences to be requested to Lightstreamer Server for the items in the Subscription. + requested_snapshot: Option, + /// The selector name for all the items in the Subscription, used as a filter on the updates received. + selector: Option, + /// A list of SubscriptionListener instances that will receive events from this Subscription. + listeners: Vec>, + /// A HashMap storing the latest values received for each item/field pair. + values: HashMap<(usize, usize), String>, + /// A HashMap storing the latest values received for each key/field pair in a COMMAND Subscription. + command_values: HashMap>, + /// A flag indicating whether the Subscription is currently active or not. + is_active: bool, + /// A flag indicating whether the Subscription is currently subscribed to through the server or not. + is_subscribed: bool, +} + +impl Subscription { + /// Constructor for creating a new Subscription instance. + /// + /// # Parameters + /// - `mode`: The subscription mode for the items, required by Lightstreamer Server. + /// - `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. + /// - `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. + /// + /// # Errors + /// Returns an error if no items or fields are provided. + pub fn new( + mode: SubscriptionMode, + items: Option>, + fields: Option>, + ) -> Result { + if items.is_none() || fields.is_none() { + return Err("Items and fields must be provided".to_string()); + } + + Ok(Subscription { + mode, + items, + item_group: None, + fields, + field_schema: None, + data_adapter: None, + command_second_level_data_adapter: None, + command_second_level_fields: None, + command_second_level_field_schema: None, + requested_buffer_size: None, + requested_max_frequency: None, + requested_snapshot: None, + selector: None, + listeners: Vec::new(), + values: HashMap::new(), + command_values: HashMap::new(), + is_active: false, + is_subscribed: false, + }) + } + + /// Adds a listener that will receive events from the Subscription instance. + /// + /// The same listener can be added to several different Subscription instances. + /// + /// # Lifecycle + /// A listener can be added at any time. A call to add a listener already present will be ignored. + /// + /// # Parameters + /// - `listener`: An object that will receive the events as documented in the SubscriptionListener interface. + /// + /// # See also + /// `removeListener()` + pub fn add_listener(&mut self, listener: Box) { + self.listeners.push(listener); + } + + /// Removes a listener from the Subscription instance so that it will not receive events anymore. + /// + /// # Lifecycle + /// A listener can be removed at any time. + /// + /// # Parameters + /// - `listener`: The listener to be removed. + /// + /// # See also + /// `addListener()` + pub fn remove_listener(&mut self, listener: &T) + where + T: SubscriptionListener, + { + self.listeners.retain(|l| { + let l_ref = l.as_ref() as &dyn SubscriptionListener; + let listener_ref = listener as &dyn SubscriptionListener; + !(l_ref as *const dyn SubscriptionListener == listener_ref as *const dyn SubscriptionListener) + }); + } + + /// Returns a list containing the SubscriptionListener instances that were added to this client. + /// + /// # Returns + /// A list containing the listeners that were added to this client. + /// + /// # See also + /// `addListener()` + pub fn get_listeners(&self) -> &Vec> { + &self.listeners + } + + /// Inquiry method that can be used to read the mode specified for this Subscription. + /// + /// # Lifecycle + /// This method can be called at any time. + /// + /// # Returns + /// The Subscription mode specified in the constructor. + pub fn get_mode(&self) -> &SubscriptionMode { + &self.mode + } + + /// Setter method that sets the "Item Group" to be subscribed to through Lightstreamer Server. + /// + /// Any call to this method will override any "Item List" or "Item Group" previously specified. + /// + /// # Lifecycle + /// This method can only be called while the Subscription instance is in its "inactive" state. + /// + /// # Errors + /// Returns an error if the Subscription is currently "active". + /// + /// # Parameters + /// - `group`: A String to be expanded into an item list by the Metadata Adapter. + pub fn set_item_group(&mut self, group: String) -> Result<(), String> { + if self.is_active { + return Err("Subscription is active".to_string()); + } + self.item_group = Some(group); + Ok(()) + } + + /// Inquiry method that can be used to read the item group specified for this Subscription. + /// + /// # Lifecycle + /// This method can only be called if the Subscription has been initialized using an "Item Group" + /// + /// # Returns + /// 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. + pub fn get_item_group(&self) -> Option<&String> { + self.item_group.as_ref() + } + + /// Setter method that sets the "Item List" to be subscribed to through Lightstreamer Server. + /// + /// Any call to this method will override any "Item List" or "Item Group" previously specified. + /// + /// # Lifecycle + /// This method can only be called while the Subscription instance is in its "inactive" state. + /// + /// # Errors + /// - Returns an error if the Subscription is currently "active". + /// - Returns an error if any of the item names in the "Item List" contains a space, is a number, or is empty/None. + /// + /// # Parameters + /// - `items`: An array of items to be subscribed to through the server. + pub fn set_items(&mut self, items: Vec) -> Result<(), String> { + if self.is_active { + return Err("Subscription is active".to_string()); + } + for item in &items { + if item.contains(" ") || item.parse::().is_ok() || item.is_empty() { + return Err("Invalid item name".to_string()); + } + } + self.items = Some(items); + Ok(()) + } + + /// Inquiry method that can be used to read the "Item List" specified for this Subscription. + /// Note that if the single-item-constructor was used, this method will return an array of length 1 containing such item. + /// + /// # Lifecycle + /// This method can only be called if the Subscription has been initialized with an "Item List". + /// + /// # Returns + /// 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. + pub fn get_items(&self) -> Option<&Vec> { + self.items.as_ref() + } + + /// Setter method that sets the "Field Schema" to be subscribed to through Lightstreamer Server. + /// + /// Any call to this method will override any "Field List" or "Field Schema" previously specified. + /// + /// # Lifecycle + /// This method can only be called while the Subscription instance is in its "inactive" state. + /// + /// # Errors + /// Returns an error if the Subscription is currently "active". + /// + /// # Parameters + /// - `schema`: A String to be expanded into a field list by the Metadata Adapter. + pub fn set_field_schema(&mut self, schema: String) -> Result<(), String> { + if self.is_active { + return Err("Subscription is active".to_string()); + } + self.field_schema = Some(schema); + Ok(()) + } + + /// Inquiry method that can be used to read the field schema specified for this Subscription. + /// + /// # Lifecycle + /// This method can only be called if the Subscription has been initialized using a "Field Schema" + /// + /// # Returns + /// 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. + pub fn get_field_schema(&self) -> Option<&String> { + self.field_schema.as_ref() + } + + /// Setter method that sets the "Field List" to be subscribed to through Lightstreamer Server. + /// + /// Any call to this method will override any "Field List" or "Field Schema" previously specified. + /// + /// # Lifecycle + /// This method can only be called while the Subscription instance is in its "inactive" state. + /// + /// # Errors + /// - Returns an error if the Subscription is currently "active". + /// - Returns an error if any of the field names in the list contains a space or is empty/None. + /// + /// # Parameters + /// - `fields`: An array of fields to be subscribed to through the server. + pub fn set_fields(&mut self, fields: Vec) -> Result<(), String> { + if self.is_active { + return Err("Subscription is active".to_string()); + } + for field in &fields { + if field.contains(" ") || field.is_empty() { + return Err("Invalid field name".to_string()); + } + } + self.fields = Some(fields); + Ok(()) + } + + /// Inquiry method that can be used to read the "Field List" specified for this Subscription. + /// + /// # Lifecycle + /// This method can only be called if the Subscription has been initialized using a "Field List". + /// + /// # Returns + /// 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. + pub fn get_fields(&self) -> Option<&Vec> { + self.fields.as_ref() + } + + /// 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. + /// + /// The Data Adapter name is configured on the server side through the "name" attribute of the `` element, in the "adapters.xml" file that defines the Adapter Set (a missing attribute configures the "DEFAULT" name). + /// + /// 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. + /// + /// # Default + /// The default Data Adapter for the Adapter Set, configured as "DEFAULT" on the Server. + /// + /// # Lifecycle + /// This method can only be called while the Subscription instance is in its "inactive" state. + /// + /// # Errors + /// Returns an error if the Subscription is currently "active". + /// + /// # Parameters + /// - `adapter`: The name of the Data Adapter. A `None` value is equivalent to the "DEFAULT" name. + /// + /// # See also + /// `ConnectionDetails.setAdapterSet()` + pub fn set_data_adapter(&mut self, adapter: Option) -> Result<(), String> { + if self.is_active { + return Err("Subscription is active".to_string()); + } + self.data_adapter = adapter; + Ok(()) + } + + /// Inquiry method that can be used to read the name of the Data Adapter specified for this Subscription through `setDataAdapter()`. + /// + /// # Lifecycle + /// This method can be called at any time. + /// + /// # Returns + /// The name of the Data Adapter; returns `None` if no name has been configured, so that the "DEFAULT" Adapter Set is used. + pub fn get_data_adapter(&self) -> Option<&String> { + self.data_adapter.as_ref() + } + + /// Setter method that sets the name of the second-level Data Adapter (within the Adapter Set used by the current session) + /// 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. + /// + /// All the possible second-level items should be supplied in "MERGE" mode with snapshot available. + /// + /// The Data Adapter name is configured on the server side through the "name" attribute of the `` element, in the "adapters.xml" file that defines the Adapter Set (a missing attribute configures the "DEFAULT" name). + /// + /// # Default + /// The default Data Adapter for the Adapter Set, configured as "DEFAULT" on the Server. + /// + /// # Lifecycle + /// This method can only be called while the Subscription instance is in its "inactive" state. + /// + /// # Errors + /// - Returns an error if the Subscription is currently "active". + /// - Returns an error if the Subscription mode is not "COMMAND". + /// + /// # Parameters + /// - `adapter`: The name of the Data Adapter. A `None` value is equivalent to the "DEFAULT" name. + /// + /// # See also + /// `Subscription.setCommandSecondLevelFields()` + /// + /// # See also + /// `Subscription.setCommandSecondLevelFieldSchema()` + pub fn set_command_second_level_data_adapter(&mut self, adapter: Option) -> Result<(), String> { + if self.is_active { + return Err("Subscription is active".to_string()); + } + if self.mode != SubscriptionMode::Command { + return Err("Subscription mode is not Command".to_string()); + } + self.command_second_level_data_adapter = adapter; + Ok(()) + } + + /// Inquiry method that can be used to read the name of the second-level Data Adapter specified for this Subscription through `setCommandSecondLevelDataAdapter()`. + /// + /// # Lifecycle + /// This method can be called at any time. + /// + /// # Errors + /// Returns an error if the Subscription mode is not COMMAND. + /// + /// # Returns + /// The name of the second-level Data Adapter. + /// + /// # See also + /// `setCommandSecondLevelDataAdapter()` + pub fn get_command_second_level_data_adapter(&self) -> Option<&String> { + if self.mode != SubscriptionMode::Command { + return None; + } + self.command_second_level_data_adapter.as_ref() + } + + /// 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. + /// + /// Any call to this method will override any "Field List" or "Field Schema" previously specified for the second-level. + /// + /// Calling this method enables the two-level behavior: + /// + /// 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. + /// + /// Specify `None` as parameter will disable the two-level behavior. + /// + /// # Lifecycle + /// This method can only be called while the Subscription instance is in its "inactive" state. + /// + /// # Errors + /// - Returns an error if the Subscription is currently "active". + /// - Returns an error if the Subscription mode is not "COMMAND". + /// + /// # Parameters + /// - `schema`: A String to be expanded into a field list by the Metadata Adapter. + /// + /// # See also + /// `Subscription.setCommandSecondLevelFields()` + pub fn set_command_second_level_field_schema(&mut self, schema: Option) -> Result<(), String> { + if self.is_active { + return Err("Subscription is active".to_string()); + } + if self.mode != SubscriptionMode::Command { + return Err("Subscription mode is not Command".to_string()); + } + self.command_second_level_field_schema = schema; + Ok(()) + } + + /// Inquiry method that can be used to read the "Field Schema" specified for second-level Subscriptions. + /// + /// # Lifecycle + /// This method can only be called if the second-level of this Subscription has been initialized using a "Field Schema". + /// + /// # Errors + /// Returns an error if the Subscription mode is not COMMAND. + /// + /// # Returns + /// 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. + /// + /// # See also + /// `Subscription.setCommandSecondLevelFieldSchema()` + pub fn get_command_second_level_field_schema(&self) -> Option<&String> { + if self.mode != SubscriptionMode::Command { + return None; + } + self.command_second_level_field_schema.as_ref() + } + + /// 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. + /// + /// Any call to this method will override any "Field List" or "Field Schema" previously specified for the second-level. + /// + /// Calling this method enables the two-level behavior: + /// + /// 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. + /// + /// Specifying `None` as parameter will disable the two-level behavior. + /// + /// # Lifecycle + /// This method can only be called while the Subscription instance is in its "inactive" state. + /// + /// # Errors + /// - Returns an error if the Subscription is currently "active". + /// - Returns an error if the Subscription mode is not "COMMAND". + /// - Returns an error if any of the field names in the "Field List" contains a space or is empty/None. + /// + /// # Parameters + /// - `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. + /// + /// # See also + /// `Subscription.setCommandSecondLevelFieldSchema()` + pub fn set_command_second_level_fields(&mut self, fields: Option>) -> Result<(), String> { + if self.is_active { + return Err("Subscription is active".to_string()); + } + if self.mode != SubscriptionMode::Command { + return Err("Subscription mode is not Command".to_string()); + } + if let Some(ref fields) = fields { + for field in fields { + if field.contains(" ") || field.is_empty() { + return Err("Invalid field name".to_string()); + } + } + } + self.command_second_level_fields = fields; + Ok(()) + } + + /// Inquiry method that can be used to read the "Field List" specified for second-level Subscriptions. + /// + /// # Lifecycle + /// This method can only be called if the second-level of this Subscription has been initialized using a "Field List" + /// + /// # Errors + /// Returns an error if the Subscription mode is not COMMAND. + /// + /// # Returns + /// 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. + /// + /// # See also + /// `Subscription.setCommandSecondLevelFields()` + pub fn get_command_second_level_fields(&self) -> Option<&Vec> { + if self.mode != SubscriptionMode::Command { + return None; + } + self.command_second_level_fields.as_ref() + } + + /// 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. + /// + /// # Default + /// `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. + /// + /// # Lifecycle + /// This method can only be called while the Subscription instance is in its "inactive" state. + /// + /// # Errors + /// - Returns an error if the Subscription is currently "active". + /// - Returns an error if the specified value is not `None` nor "unlimited" nor a valid positive integer number. + /// + /// # Parameters + /// - `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). + /// + /// # See also + /// `Subscription.setRequestedMaxFrequency()` + pub fn set_requested_buffer_size(&mut self, size: Option) -> Result<(), String> { + if self.is_active { + return Err("Subscription is active".to_string()); + } + self.requested_buffer_size = size; + Ok(()) + } + + /// Inquiry method that can be used to read the buffer size, configured though `setRequestedBufferSize()`, to be requested to the Server for this Subscription. + /// + /// # Lifecycle + /// This method can be called at any time. + /// + /// # Returns + /// An integer number, representing the buffer size to be requested to the server, or the string "unlimited", or `None`. + pub fn get_requested_buffer_size(&self) -> Option<&usize> { + self.requested_buffer_size.as_ref() + } + + /// 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. + /// + /// 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. + /// + /// 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. + /// + /// # General Edition Note + /// 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). + /// + /// # Default + /// `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. + /// + /// # Lifecycle + /// This method can can be called at any time with some differences based on the Subscription status: + /// + /// - If the Subscription instance is in its "inactive" state then this method can be called at will. + /// + /// - 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. + /// + /// # Errors + /// - Returns an error if the Subscription is currently "active" and the current value of this property is "unfiltered". + /// - Returns an error if the Subscription is currently "active" and the given parameter is `None` or "unfiltered". + /// - Returns an error if the specified value is not `None` nor one of the special "unlimited" and "unfiltered" values nor a valid positive number. + /// + /// # Parameters + /// - `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. + pub fn set_requested_max_frequency(&mut self, freq: Option) -> Result<(), String> { + if self.is_active && self.requested_max_frequency.is_none() { + return Err("Subscription is active and current value is unfiltered".to_string()); + } + if self.is_active && freq.is_none() { + return Err("Cannot set unfiltered while active".to_string()); + } + if self.is_active && freq.is_none() { + return Err("Cannot set None while active".to_string()); + } + self.requested_max_frequency = freq; + Ok(()) + } + + /// Inquiry method that can be used to read the max frequency, configured through `setRequestedMaxFrequency()`, to be requested to the Server for this Subscription. + /// + /// # Lifecycle + /// This method can be called at any time. + /// + /// # Returns + /// 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`. + pub fn get_requested_max_frequency(&self) -> Option<&f64> { + self.requested_max_frequency.as_ref() + } + + /// 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. + /// + /// # Default + /// "yes" if the Subscription mode is not "RAW", `None` otherwise. + /// + /// # Lifecycle + /// This method can only be called while the Subscription instance is in its "inactive" state. + /// + /// # Errors + /// - Returns an error if the Subscription is currently "active". + /// - Returns an error if the specified value is not "yes" nor "no" nor `None` nor a valid integer positive number. + /// - Returns an error if the specified value is not compatible with the mode of the Subscription: + /// - In case of a RAW Subscription only `None` is a valid value; + /// - In case of a non-DISTINCT Subscription only `None` "yes" and "no" are valid values. + /// + /// # Parameters + /// - `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 + /// 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. + /// + /// # See also + /// `ItemUpdate.isSnapshot()` + pub fn set_requested_snapshot(&mut self, snapshot: Option) -> Result<(), String> { + if self.is_active { + return Err("Subscription is active".to_string()); + } + if self.mode == SubscriptionMode::Raw && snapshot.is_some() { + return Err("Cannot request snapshot for Raw mode".to_string()); + } + if self.mode != SubscriptionMode::Distinct && snapshot.is_some() && snapshot.as_ref().unwrap().parse::().is_ok() { + return Err("Cannot specify snapshot length for non-Distinct mode".to_string()); + } + self.requested_snapshot = snapshot; + Ok(()) + } + + /// Inquiry method that can be used to read the snapshot preferences, configured through `setRequestedSnapshot()`, to be requested to the Server for this Subscription. + /// + /// # Lifecycle + /// This method can be called at any time. + /// + /// # Returns + /// "yes", "no", `None`, or an integer number. + pub fn get_requested_snapshot(&self) -> Option<&String> { + self.requested_snapshot.as_ref() + } + + /// 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. + /// + /// # Default + /// `None` (no selector). + /// + /// # Lifecycle + /// This method can only be called while the Subscription instance is in its "inactive" state. + /// + /// # Errors + /// Returns an error if the Subscription is currently "active". + /// + /// # Parameters + /// - `selector`: The name of a selector, to be recognized by the Metadata Adapter, or `None` to unset the selector. + pub fn set_selector(&mut self, selector: Option) -> Result<(), String> { + if self.is_active { + return Err("Subscription is active".to_string()); + } + self.selector = selector; + Ok(()) + } + + /// Inquiry method that can be used to read the selector name specified for this Subscription through `setSelector()`. + /// + /// # Lifecycle + /// This method can be called at any time. + /// + /// # Returns + /// The name of the selector. + pub fn get_selector(&self) -> Option<&String> { + self.selector.as_ref() + } + + /// Returns the latest value received for the specified item/field pair. + /// + /// 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. + /// + /// Note that internal data is cleared when the Subscription is unsubscribed from. + /// + /// # Lifecycle + /// 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`. + /// + /// # Errors + /// 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. + /// + /// # Parameters + /// - `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). + /// - `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). + /// + /// # Returns + /// The current value for the specified field of the specified item(possibly `None`), or `None` if no value has been received yet. + pub fn get_value(&self, item_pos: usize, field_pos: usize) -> Option<&String> { + self.values.get(&(item_pos, field_pos)) + } + + /// 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. + /// + /// It is suggested to consume real-time data by implementing and adding a proper SubscriptionListener rather than probing this method. + /// + /// Note that internal data is cleared when the Subscription is unsubscribed from. + /// + /// # Lifecycle + /// 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`. + /// + /// # Errors + /// - 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. + /// - Returns an error if the Subscription mode is not COMMAND. + /// + /// # Parameters + /// - `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). + /// - `key`: A String containing the value of a key received on the COMMAND subscription. + /// - `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). + /// + /// # Returns + /// 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). + pub fn get_command_value(&self, item_pos: usize, key: &str, field_pos: usize) -> Option<&String> { + self.command_values + .get(key) + .and_then(|fields| fields.get(&field_pos)) + } + + /// 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". + /// + /// The status of a Subscription is changed to "active" through the `LightstreamerClient.subscribe()` method and back to "inactive" through the `LightstreamerClient.unsubscribe()` one. + /// + /// # Lifecycle + /// This method can be called at any time. + /// + /// # Returns + /// `true`/`false` if the Subscription is "active" or not. + /// + /// # See also + /// `LightstreamerClient.subscribe()` + /// + /// # See also + /// `LightstreamerClient.unsubscribe()` + pub fn is_active(&self) -> bool { + self.is_active + } + + /// Inquiry method that checks if the Subscription is currently subscribed to through the server or not. + /// + /// 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. + /// + /// # Lifecycle + /// This method can be called at any time. + /// + /// # Returns + /// `true`/`false` if the Subscription is subscribed to through the server or not. + pub fn is_subscribed(&self) -> bool { + self.is_subscribed + } + + /// Returns the position of the "key" field in a COMMAND Subscription. + /// + /// This method can only be used if the Subscription mode is COMMAND and the Subscription was initialized using a "Field Schema". + /// + /// # Lifecycle + /// This method can be called at any time after the first `SubscriptionListener.onSubscription()` event. + /// + /// # Errors + /// - Returns an error if the Subscription mode is not COMMAND or if the `SubscriptionListener.onSubscription()` event for this Subscription was not yet fired. + /// - Returns an error if a "Field List" was specified. + /// + /// # Returns + /// The 1-based position of the "key" field within the "Field Schema". + pub fn get_key_position(&self) -> Option { + if self.mode != SubscriptionMode::Command || !self.is_subscribed { + return None; + } + if let Some(ref schema) = self.field_schema { + return schema.split(',').position(|field| field.trim() == "key"); + } + None + } + + /// Returns the position of the "command" field in a COMMAND Subscription. + /// + /// This method can only be used if the Subscription mode is COMMAND and the Subscription was initialized using a "Field Schema". + /// + /// # Lifecycle + /// This method can be called at any time after the first `SubscriptionListener.onSubscription()` event. + /// + /// # Errors + /// - Returns an error if the Subscription mode is not COMMAND or if the `SubscriptionListener.onSubscription()` event for this Subscription was not yet fired. + /// + /// # Returns + /// The 1-based position of the "command" field within the "Field Schema". + pub fn get_command_position(&self) -> Option { + if self.mode != SubscriptionMode::Command || !self.is_subscribed { + return None; + } + if let Some(ref schema) = self.field_schema { + return schema.split(',').position(|field| field.trim() == "command"); + } + None + } + + /* + /// Handles the subscription event. + pub fn on_subscription(&mut self) { + self.is_subscribed = true; + for listener in &mut self.listeners { + listener.on_subscription(); + } + } + + /// Handles the unsubscription event. + pub fn on_unsubscription(&mut self) { + self.is_subscribed = false; + self.values.clear(); + self.command_values.clear(); + for listener in &mut self.listeners { + listener.on_unsubscription(); + } + } + + /// Handles an update event for a regular Subscription. + pub fn on_update(&mut self, item_pos: usize, field_pos: usize, value: String, is_snapshot: bool) { + self.values.insert((item_pos, field_pos), value.clone()); + for listener in &mut self.listeners { + listener.on_update(item_pos, field_pos, &value, is_snapshot); + } + } + + /// Handles an update event for a COMMAND Subscription. + pub fn on_command_update(&mut self, key: String, item_pos: usize, field_pos: usize, value: String, is_snapshot: bool) { + self.command_values + .entry(key.clone()) + .or_insert_with(HashMap::new) + .insert(field_pos, value.clone()); + for listener in &mut self.listeners { + listener.on_command_update(&key, item_pos, field_pos, &value, is_snapshot); + } + } + */ +} \ No newline at end of file -- cgit v1.2.3