Skip to main content

openstack_sdk_load_balancer/v2/l7policy/rule/
set.rs

1// Licensed under the Apache License, Version 2.0 (the "License");
2// you may not use this file except in compliance with the License.
3// You may obtain a copy of the License at
4//
5//     http://www.apache.org/licenses/LICENSE-2.0
6//
7// Unless required by applicable law or agreed to in writing, software
8// distributed under the License is distributed on an "AS IS" BASIS,
9// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10// See the License for the specific language governing permissions and
11// limitations under the License.
12//
13// SPDX-License-Identifier: Apache-2.0
14//
15// WARNING: This file is automatically generated from OpenAPI schema using
16// `openstack-codegenerator`.
17
18//! Updates a L7 rule.
19//!
20//! If the request is valid, the service returns the `Accepted (202)` response
21//! code. To confirm the update, check that the L7 rule provisioning status is
22//! `ACTIVE`. If the status is `PENDING_UPDATE`, use a GET operation to poll
23//! the L7 rule object for changes.
24//!
25//! This operation returns the updated L7 rule object with the `ACTIVE`,
26//! `PENDING_UPDATE`, or `ERROR` provisioning status.
27//!
28use derive_builder::Builder;
29use http::{HeaderMap, HeaderName, HeaderValue};
30
31use openstack_sdk_core::api::rest_endpoint_prelude::*;
32
33use serde::Deserialize;
34use serde::Serialize;
35use std::borrow::Cow;
36
37#[derive(Debug, Deserialize, Clone, Serialize)]
38pub enum CompareType {
39    #[serde(rename = "CONTAINS")]
40    Contains,
41    #[serde(rename = "ENDS_WITH")]
42    EndsWith,
43    #[serde(rename = "EQUAL_TO")]
44    EqualTo,
45    #[serde(rename = "REGEX")]
46    Regex,
47    #[serde(rename = "STARTS_WITH")]
48    StartsWith,
49}
50
51#[derive(Debug, Deserialize, Clone, Serialize)]
52pub enum Type {
53    #[serde(rename = "COOKIE")]
54    Cookie,
55    #[serde(rename = "FILE_TYPE")]
56    FileType,
57    #[serde(rename = "HEADER")]
58    Header,
59    #[serde(rename = "HOST_NAME")]
60    HostName,
61    #[serde(rename = "PATH")]
62    Path,
63    #[serde(rename = "SSL_CONN_HAS_CERT")]
64    SslConnHasCert,
65    #[serde(rename = "SSL_DN_FIELD")]
66    SslDnField,
67    #[serde(rename = "SSL_VERIFY_RESULT")]
68    SslVerifyResult,
69}
70
71/// Defines attributes that are acceptable of a PUT request.
72#[derive(Builder, Debug, Deserialize, Clone, Serialize)]
73#[builder(setter(strip_option))]
74pub struct Rule<'a> {
75    /// The administrative state of the resource, which is up (`true`) or down
76    /// (`false`). Default is `true`.
77    #[serde(skip_serializing_if = "Option::is_none")]
78    #[builder(default, setter(into))]
79    pub(crate) admin_state_up: Option<bool>,
80
81    /// The comparison type for the L7 rule. One of `CONTAINS`, `ENDS_WITH`,
82    /// `EQUAL_TO`, `REGEX`, or `STARTS_WITH`.
83    #[serde(skip_serializing_if = "Option::is_none")]
84    #[builder(default)]
85    pub(crate) compare_type: Option<CompareType>,
86
87    /// When `true` the logic of the rule is inverted. For example, with invert
88    /// `true`, equal to would become not equal to. Default is `false`.
89    #[serde(skip_serializing_if = "Option::is_none")]
90    #[builder(default, setter(into))]
91    pub(crate) invert: Option<bool>,
92
93    /// The key to use for the comparison. For example, the name of the cookie
94    /// to evaluate.
95    #[serde(skip_serializing_if = "Option::is_none")]
96    #[builder(default, setter(into))]
97    pub(crate) key: Option<Cow<'a, str>>,
98
99    /// A list of simple strings assigned to the resource.
100    ///
101    /// **New in version 2.5**
102    #[serde(skip_serializing_if = "Option::is_none")]
103    #[builder(default, setter(into))]
104    pub(crate) tags: Option<Vec<Cow<'a, str>>>,
105
106    /// The L7 rule type. One of `COOKIE`, `FILE_TYPE`, `HEADER`, `HOST_NAME`,
107    /// `PATH`, `SSL_CONN_HAS_CERT`, `SSL_VERIFY_RESULT`, or `SSL_DN_FIELD`.
108    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
109    #[builder(default)]
110    pub(crate) _type: Option<Type>,
111
112    /// The value to use for the comparison. For example, the file type to
113    /// compare.
114    #[serde(skip_serializing_if = "Option::is_none")]
115    #[builder(default, setter(into))]
116    pub(crate) value: Option<Cow<'a, str>>,
117}
118
119#[derive(Builder, Debug, Clone)]
120#[builder(setter(strip_option))]
121pub struct Request<'a> {
122    /// Defines attributes that are acceptable of a PUT request.
123    #[builder(setter(into))]
124    pub(crate) rule: Rule<'a>,
125
126    /// rule_id parameter for
127    /// /v2/lbaas/l7policies/{l7policy_id}/rules/{rule_id} API
128    #[builder(default, setter(into))]
129    id: Cow<'a, str>,
130
131    /// l7policy_id parameter for
132    /// /v2/lbaas/l7policies/{l7policy_id}/rules/{rule_id} API
133    #[builder(default, setter(into))]
134    l7policy_id: Cow<'a, str>,
135
136    #[builder(setter(name = "_headers"), default, private)]
137    _headers: Option<HeaderMap>,
138}
139impl<'a> Request<'a> {
140    /// Create a builder for the endpoint.
141    pub fn builder() -> RequestBuilder<'a> {
142        RequestBuilder::default()
143    }
144}
145
146impl<'a> RequestBuilder<'a> {
147    /// Add a single header to the Rule.
148    pub fn header<K, V>(&mut self, header_name: K, header_value: V) -> &mut Self
149    where
150        K: Into<HeaderName>,
151        V: Into<HeaderValue>,
152    {
153        self._headers
154            .get_or_insert(None)
155            .get_or_insert_with(HeaderMap::new)
156            .insert(header_name.into(), header_value.into());
157        self
158    }
159
160    /// Add multiple headers.
161    pub fn headers<I, T>(&mut self, iter: I) -> &mut Self
162    where
163        I: Iterator<Item = T>,
164        T: Into<(Option<HeaderName>, HeaderValue)>,
165    {
166        self._headers
167            .get_or_insert(None)
168            .get_or_insert_with(HeaderMap::new)
169            .extend(iter.map(Into::into));
170        self
171    }
172}
173
174impl RestEndpoint for Request<'_> {
175    fn method(&self) -> http::Method {
176        http::Method::PUT
177    }
178
179    fn endpoint(&self) -> Cow<'static, str> {
180        format!(
181            "lbaas/l7policies/{l7policy_id}/rules/{id}",
182            l7policy_id = self.l7policy_id.as_ref(),
183            id = self.id.as_ref(),
184        )
185        .into()
186    }
187
188    fn parameters(&self) -> QueryParams<'_> {
189        QueryParams::default()
190    }
191
192    fn body(&self) -> Result<Option<(&'static str, Vec<u8>)>, BodyError> {
193        let mut params = JsonBodyParams::default();
194
195        params.push("rule", serde_json::to_value(&self.rule)?);
196
197        params.into_body()
198    }
199
200    fn service_type(&self) -> ServiceType {
201        ServiceType::LoadBalancer
202    }
203
204    fn response_key(&self) -> Option<Cow<'static, str>> {
205        Some("rule".into())
206    }
207
208    /// Returns headers to be set into the request
209    fn request_headers(&self) -> Option<&HeaderMap> {
210        self._headers.as_ref()
211    }
212
213    /// Returns required API version
214    fn api_version(&self) -> Option<ApiVersion> {
215        Some(ApiVersion::new(2, 0))
216    }
217}
218
219#[cfg(test)]
220mod tests {
221    use super::*;
222    use http::{HeaderName, HeaderValue};
223    use httpmock::MockServer;
224    #[cfg(feature = "sync")]
225    use openstack_sdk_core::api::Query;
226    use openstack_sdk_core::test::client::FakeOpenStackClient;
227    use openstack_sdk_core::types::ServiceType;
228    use serde_json::json;
229
230    #[test]
231    fn test_service_type() {
232        assert_eq!(
233            Request::builder()
234                .rule(RuleBuilder::default().build().unwrap())
235                .build()
236                .unwrap()
237                .service_type(),
238            ServiceType::LoadBalancer
239        );
240    }
241
242    #[test]
243    fn test_response_key() {
244        assert_eq!(
245            Request::builder()
246                .rule(RuleBuilder::default().build().unwrap())
247                .build()
248                .unwrap()
249                .response_key()
250                .unwrap(),
251            "rule"
252        );
253    }
254
255    #[cfg(feature = "sync")]
256    #[test]
257    fn endpoint() {
258        let server = MockServer::start();
259        let client = FakeOpenStackClient::new(server.base_url());
260        let mock = server.mock(|when, then| {
261            when.method(httpmock::Method::PUT).path(format!(
262                "/lbaas/l7policies/{l7policy_id}/rules/{id}",
263                l7policy_id = "l7policy_id",
264                id = "id",
265            ));
266
267            then.status(200)
268                .header("content-type", "application/json")
269                .json_body(json!({ "rule": {} }));
270        });
271
272        let endpoint = Request::builder()
273            .l7policy_id("l7policy_id")
274            .id("id")
275            .rule(RuleBuilder::default().build().unwrap())
276            .build()
277            .unwrap();
278        let _: serde_json::Value = endpoint.query(&client).unwrap();
279        mock.assert();
280    }
281
282    #[cfg(feature = "sync")]
283    #[test]
284    fn endpoint_headers() {
285        let server = MockServer::start();
286        let client = FakeOpenStackClient::new(server.base_url());
287        let mock = server.mock(|when, then| {
288            when.method(httpmock::Method::PUT)
289                .path(format!(
290                    "/lbaas/l7policies/{l7policy_id}/rules/{id}",
291                    l7policy_id = "l7policy_id",
292                    id = "id",
293                ))
294                .header("foo", "bar")
295                .header("not_foo", "not_bar");
296            then.status(200)
297                .header("content-type", "application/json")
298                .json_body(json!({ "rule": {} }));
299        });
300
301        let endpoint = Request::builder()
302            .l7policy_id("l7policy_id")
303            .id("id")
304            .rule(RuleBuilder::default().build().unwrap())
305            .headers(
306                [(
307                    Some(HeaderName::from_static("foo")),
308                    HeaderValue::from_static("bar"),
309                )]
310                .into_iter(),
311            )
312            .header(
313                HeaderName::from_static("not_foo"),
314                HeaderValue::from_static("not_bar"),
315            )
316            .build()
317            .unwrap();
318        let _: serde_json::Value = endpoint.query(&client).unwrap();
319        mock.assert();
320    }
321}