Skip to main content

rustfs_policy/policy/
doc.rs

1// Copyright 2024 RustFS Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use serde::{Deserialize, Serialize};
16use time::OffsetDateTime;
17
18use super::Policy;
19
20#[derive(Serialize, Deserialize, Default, Clone)]
21pub struct PolicyDoc {
22    pub version: i64,
23    pub policy: Policy,
24    pub create_date: Option<OffsetDateTime>,
25    pub update_date: Option<OffsetDateTime>,
26}
27
28impl PolicyDoc {
29    pub fn new(policy: Policy) -> Self {
30        Self {
31            version: 1,
32            policy,
33            create_date: Some(OffsetDateTime::now_utc()),
34            update_date: Some(OffsetDateTime::now_utc()),
35        }
36    }
37
38    pub fn update(&mut self, policy: Policy) {
39        self.version += 1;
40        self.policy = policy;
41        self.update_date = Some(OffsetDateTime::now_utc());
42
43        if self.create_date.is_none() {
44            self.create_date = self.update_date;
45        }
46    }
47
48    pub fn default_policy(policy: Policy) -> Self {
49        Self {
50            version: 1,
51            policy,
52            create_date: None,
53            update_date: None,
54        }
55    }
56}
57
58impl TryFrom<Vec<u8>> for PolicyDoc {
59    type Error = serde_json::Error;
60
61    fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
62        match serde_json::from_slice::<PolicyDoc>(&value) {
63            Ok(res) => Ok(res),
64            Err(err) => match serde_json::from_slice::<Policy>(&value) {
65                Ok(res2) => Ok(Self {
66                    policy: res2,
67                    ..Default::default()
68                }),
69                Err(_) => Err(err),
70            },
71        }
72    }
73}