Skip to main content

openstack_sdk_load_balancer/v2/l7policy/
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 policy.
19//!
20//! If the request is valid, the service returns the `Accepted (202)` response
21//! code. To confirm the update, check that the L7 policy provisioning status
22//! is `ACTIVE`. If the status is `PENDING_UPDATE`, use a GET operation to poll
23//! the L7 policy object for changes.
24//!
25//! This operation returns the updated L7 policy object with the `ACTIVE`,
26//! `PENDING_UPDATE`, or `ERROR` provisioning status.
27//!
28//! If a policy is updated with a position that matches that of an existing
29//! policy, then the updated policy is inserted at the given position.
30//!
31use derive_builder::Builder;
32use http::{HeaderMap, HeaderName, HeaderValue};
33
34use openstack_sdk_core::api::rest_endpoint_prelude::*;
35
36use serde::Deserialize;
37use serde::Serialize;
38use std::borrow::Cow;
39
40#[derive(Debug, Deserialize, Clone, Serialize)]
41pub enum Action {
42    #[serde(rename = "REDIRECT_PREFIX")]
43    RedirectPrefix,
44    #[serde(rename = "REDIRECT_TO_POOL")]
45    RedirectToPool,
46    #[serde(rename = "REDIRECT_TO_URL")]
47    RedirectToUrl,
48    #[serde(rename = "REJECT")]
49    Reject,
50}
51
52/// Defines attributes that are acceptable of a PUT request.
53#[derive(Builder, Debug, Deserialize, Clone, Serialize)]
54#[builder(setter(strip_option))]
55pub struct L7policy<'a> {
56    /// The L7 policy action. One of `REDIRECT_PREFIX`, `REDIRECT_TO_POOL`,
57    /// `REDIRECT_TO_URL`, or `REJECT`.
58    #[serde(skip_serializing_if = "Option::is_none")]
59    #[builder(default)]
60    pub(crate) action: Option<Action>,
61
62    /// The administrative state of the resource, which is up (`true`) or down
63    /// (`false`). Default is `true`.
64    #[serde(skip_serializing_if = "Option::is_none")]
65    #[builder(default, setter(into))]
66    pub(crate) admin_state_up: Option<bool>,
67
68    /// A human-readable description for the resource.
69    #[serde(skip_serializing_if = "Option::is_none")]
70    #[builder(default, setter(into))]
71    pub(crate) description: Option<Cow<'a, str>>,
72
73    /// Human-readable name of the resource.
74    #[serde(skip_serializing_if = "Option::is_none")]
75    #[builder(default, setter(into))]
76    pub(crate) name: Option<Cow<'a, str>>,
77
78    /// The position of this policy on the listener. Positions start at 1.
79    #[serde(skip_serializing_if = "Option::is_none")]
80    #[builder(default, setter(into))]
81    pub(crate) position: Option<i32>,
82
83    /// Requests matching this policy will be redirected to the specified URL
84    /// or Prefix URL with the HTTP response code. Valid if `action` is
85    /// `REDIRECT_TO_URL` or `REDIRECT_PREFIX`. Valid options are: 301, 302,
86    /// 303, 307, or 308. Default is 302.
87    ///
88    /// **New in version 2.9**
89    #[serde(skip_serializing_if = "Option::is_none")]
90    #[builder(default, setter(into))]
91    pub(crate) redirect_http_code: Option<i32>,
92
93    /// Requests matching this policy will be redirected to the pool with this
94    /// ID. Only valid if `action` is `REDIRECT_TO_POOL`. The pool has some
95    /// restrictions, See
96    /// [Protocol Combinations (Listener/Pool)](#valid-protocol).
97    #[serde(skip_serializing_if = "Option::is_none")]
98    #[builder(default, setter(into))]
99    pub(crate) redirect_pool_id: Option<Cow<'a, str>>,
100
101    /// Requests matching this policy will be redirected to this Prefix URL.
102    /// Only valid if `action` is `REDIRECT_PREFIX`.
103    #[serde(skip_serializing_if = "Option::is_none")]
104    #[builder(default, setter(into))]
105    pub(crate) redirect_prefix: Option<Cow<'a, str>>,
106
107    /// Requests matching this policy will be redirected to this URL. Only
108    /// valid if `action` is `REDIRECT_TO_URL`.
109    #[serde(skip_serializing_if = "Option::is_none")]
110    #[builder(default, setter(into))]
111    pub(crate) redirect_url: Option<Cow<'a, str>>,
112
113    /// A list of simple strings assigned to the resource.
114    ///
115    /// **New in version 2.5**
116    #[serde(skip_serializing_if = "Option::is_none")]
117    #[builder(default, setter(into))]
118    pub(crate) tags: Option<Vec<Cow<'a, str>>>,
119}
120
121#[derive(Builder, Debug, Clone)]
122#[builder(setter(strip_option))]
123pub struct Request<'a> {
124    /// Defines attributes that are acceptable of a PUT request.
125    #[builder(setter(into))]
126    pub(crate) l7policy: L7policy<'a>,
127
128    /// l7policy_id parameter for /v2/lbaas/l7policies/{l7policy_id} API
129    #[builder(default, setter(into))]
130    id: Cow<'a, str>,
131
132    #[builder(setter(name = "_headers"), default, private)]
133    _headers: Option<HeaderMap>,
134}
135impl<'a> Request<'a> {
136    /// Create a builder for the endpoint.
137    pub fn builder() -> RequestBuilder<'a> {
138        RequestBuilder::default()
139    }
140}
141
142impl<'a> RequestBuilder<'a> {
143    /// Add a single header to the L7Policy.
144    pub fn header<K, V>(&mut self, header_name: K, header_value: V) -> &mut Self
145    where
146        K: Into<HeaderName>,
147        V: Into<HeaderValue>,
148    {
149        self._headers
150            .get_or_insert(None)
151            .get_or_insert_with(HeaderMap::new)
152            .insert(header_name.into(), header_value.into());
153        self
154    }
155
156    /// Add multiple headers.
157    pub fn headers<I, T>(&mut self, iter: I) -> &mut Self
158    where
159        I: Iterator<Item = T>,
160        T: Into<(Option<HeaderName>, HeaderValue)>,
161    {
162        self._headers
163            .get_or_insert(None)
164            .get_or_insert_with(HeaderMap::new)
165            .extend(iter.map(Into::into));
166        self
167    }
168}
169
170impl RestEndpoint for Request<'_> {
171    fn method(&self) -> http::Method {
172        http::Method::PUT
173    }
174
175    fn endpoint(&self) -> Cow<'static, str> {
176        format!("lbaas/l7policies/{id}", id = self.id.as_ref(),).into()
177    }
178
179    fn parameters(&self) -> QueryParams<'_> {
180        QueryParams::default()
181    }
182
183    fn body(&self) -> Result<Option<(&'static str, Vec<u8>)>, BodyError> {
184        let mut params = JsonBodyParams::default();
185
186        params.push("l7policy", serde_json::to_value(&self.l7policy)?);
187
188        params.into_body()
189    }
190
191    fn service_type(&self) -> ServiceType {
192        ServiceType::LoadBalancer
193    }
194
195    fn response_key(&self) -> Option<Cow<'static, str>> {
196        Some("l7policy".into())
197    }
198
199    /// Returns headers to be set into the request
200    fn request_headers(&self) -> Option<&HeaderMap> {
201        self._headers.as_ref()
202    }
203
204    /// Returns required API version
205    fn api_version(&self) -> Option<ApiVersion> {
206        Some(ApiVersion::new(2, 0))
207    }
208}
209
210#[cfg(test)]
211mod tests {
212    use super::*;
213    use http::{HeaderName, HeaderValue};
214    use httpmock::MockServer;
215    #[cfg(feature = "sync")]
216    use openstack_sdk_core::api::Query;
217    use openstack_sdk_core::test::client::FakeOpenStackClient;
218    use openstack_sdk_core::types::ServiceType;
219    use serde_json::json;
220
221    #[test]
222    fn test_service_type() {
223        assert_eq!(
224            Request::builder()
225                .l7policy(L7policyBuilder::default().build().unwrap())
226                .build()
227                .unwrap()
228                .service_type(),
229            ServiceType::LoadBalancer
230        );
231    }
232
233    #[test]
234    fn test_response_key() {
235        assert_eq!(
236            Request::builder()
237                .l7policy(L7policyBuilder::default().build().unwrap())
238                .build()
239                .unwrap()
240                .response_key()
241                .unwrap(),
242            "l7policy"
243        );
244    }
245
246    #[cfg(feature = "sync")]
247    #[test]
248    fn endpoint() {
249        let server = MockServer::start();
250        let client = FakeOpenStackClient::new(server.base_url());
251        let mock = server.mock(|when, then| {
252            when.method(httpmock::Method::PUT)
253                .path(format!("/lbaas/l7policies/{id}", id = "id",));
254
255            then.status(200)
256                .header("content-type", "application/json")
257                .json_body(json!({ "l7policy": {} }));
258        });
259
260        let endpoint = Request::builder()
261            .id("id")
262            .l7policy(L7policyBuilder::default().build().unwrap())
263            .build()
264            .unwrap();
265        let _: serde_json::Value = endpoint.query(&client).unwrap();
266        mock.assert();
267    }
268
269    #[cfg(feature = "sync")]
270    #[test]
271    fn endpoint_headers() {
272        let server = MockServer::start();
273        let client = FakeOpenStackClient::new(server.base_url());
274        let mock = server.mock(|when, then| {
275            when.method(httpmock::Method::PUT)
276                .path(format!("/lbaas/l7policies/{id}", id = "id",))
277                .header("foo", "bar")
278                .header("not_foo", "not_bar");
279            then.status(200)
280                .header("content-type", "application/json")
281                .json_body(json!({ "l7policy": {} }));
282        });
283
284        let endpoint = Request::builder()
285            .id("id")
286            .l7policy(L7policyBuilder::default().build().unwrap())
287            .headers(
288                [(
289                    Some(HeaderName::from_static("foo")),
290                    HeaderValue::from_static("bar"),
291                )]
292                .into_iter(),
293            )
294            .header(
295                HeaderName::from_static("not_foo"),
296                HeaderValue::from_static("not_bar"),
297            )
298            .build()
299            .unwrap();
300        let _: serde_json::Value = endpoint.query(&client).unwrap();
301        mock.assert();
302    }
303}