1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
pub mod commands;
pub mod config;
pub mod models;

use async_trait::async_trait;
use commands::{is_published, publish, yank};
use models::PublishedVersion;

pub enum BackendCommand {
    Publish(
        String,
        models::PublishRequest,
        tokio::sync::oneshot::Sender<bool>,
    ),
    Yank(
        String,
        models::YankRequest,
        tokio::sync::oneshot::Sender<bool>,
    ),
    IsVersionPublished(String, String, String, tokio::sync::oneshot::Sender<bool>),
}

pub enum StorageCommand {
    Get(models::StorageGetRequest),
    Put(models::StoragePutRequest),
}

#[async_trait]
pub trait Backend {
    async fn get_file(
        &self,
        token: &str,
        crate_path: &str,
    ) -> Result<(String, String, String), reqwest::Error>;

    async fn create_file(
        &self,
        token: &str,
        crate_path: &str,
        branch_name: &str,
        version: &PublishedVersion,
    ) -> Result<(), reqwest::Error>;

    async fn update_file(
        &self,
        token: &str,
        crate_path: &str,
        branch_name: &str,
        versions: &[PublishedVersion],
        current_sha: &str,
    ) -> Result<(), reqwest::Error>;

    async fn delete_branch(&self, token: &str, branch_name: &str) -> Result<(), reqwest::Error>;

    async fn create_pull_request(
        &self,
        token: &str,
        title: &str,
        branch_name: &str,
    ) -> Result<u64, reqwest::Error>;

    async fn merge_pull_request(&self, token: &str, id: u64) -> Result<(), reqwest::Error>;

    async fn delete_pull_request(&self, token: &str, id: u64) -> Result<(), reqwest::Error>;
}

#[async_trait]
pub trait Storage {
    async fn get(
        &self,
        crate_name: &str,
        crate_version: &str,
    ) -> Result<Vec<u8>, models::StorageError>;
    async fn put(
        &mut self,
        crate_name: &str,
        crate_version: &str,
        data: &[u8],
    ) -> Result<(), models::StorageError>;
}

pub fn get_crate_path(name: &str) -> String {
    match name.len() {
        1 => "1".into(),
        2 => "2".into(),
        3 => format!("3/{}", name[0..1].to_string()),
        _ => {
            format!("{}/{}", name[0..2].to_string(), name[2..4].to_string())
        }
    }
}

pub fn get_crate_file_path(name: &str) -> String {
    format!("{}/{}", get_crate_path(name), name)
}

pub struct BackendService<T: Backend + Sync + Send> {
    backend: T,
}

impl<T: Backend + Sync + Send + 'static> BackendService<T> {
    pub fn new(backend: T) -> Self {
        Self { backend }
    }

    pub fn run(
        self,
    ) -> (
        tokio::task::JoinHandle<()>,
        tokio::sync::mpsc::Sender<BackendCommand>,
    ) {
        let (sender, mut receiver) = tokio::sync::mpsc::channel::<BackendCommand>(16);
        let handle = tokio::spawn(async move {
            loop {
                match receiver.recv().await {
                    Some(command) => match command {
                        BackendCommand::Publish(token, req, sender) => {
                            match publish::execute(&self.backend, &token, &req).await {
                                Ok(_) => {
                                    if sender.send(true).is_err() {
                                        tracing::error!("Failed to send publish result!");
                                    }
                                }
                                Err(e) => {
                                    tracing::error!("Publish failed: {}", e);
                                    if sender.send(false).is_err() {
                                        tracing::error!("Failed to send publish result!");
                                    }
                                }
                            }
                        }
                        BackendCommand::Yank(token, req, sender) => {
                            match yank::execute(&self.backend, &token, &req).await {
                                Ok(_) => {
                                    if sender.send(true).is_err() {
                                        tracing::error!("Failed to send yank result!");
                                    }
                                }
                                Err(e) => {
                                    tracing::error!("Yank/Unyank failed: {}", e);
                                    if sender.send(false).is_err() {
                                        tracing::error!("Failed to send yank result!");
                                    }
                                }
                            }
                        }
                        BackendCommand::IsVersionPublished(token, name, version, sender) => {
                            match is_published::execute(&self.backend, &token, &name, &version)
                                .await
                            {
                                Ok(result) => {
                                    if sender.send(result).is_err() {
                                        tracing::error!("Failed to send isPublished result!");
                                    }
                                }
                                Err(_) => {
                                    if sender.send(false).is_err() {
                                        tracing::error!("Failed to send isPublished result!");
                                    }
                                }
                            }
                        }
                    },
                    None => {
                        tracing::warn!("Did not receive a BackendCommand!")
                    }
                }
            }
        });

        (handle, sender)
    }
}

pub struct StorageService<T: Storage + Sync + Send> {
    storage: T,
}

impl<T: Storage + Sync + Send + 'static> StorageService<T> {
    pub fn new(storage: T) -> Self {
        Self { storage }
    }

    pub fn run(
        mut self,
    ) -> (
        tokio::task::JoinHandle<()>,
        tokio::sync::mpsc::Sender<StorageCommand>,
    ) {
        let (sender, mut receiver) = tokio::sync::mpsc::channel::<StorageCommand>(16);
        let handle = tokio::spawn(async move {
            loop {
                match receiver.recv().await {
                    Some(command) => match command {
                        StorageCommand::Get(req) => {
                            match self.storage.get(&req.crate_name, &req.crate_version).await {
                                Ok(data) => {
                                    if req.result_sender.send(Some(data)).is_err() {
                                        tracing::error!("Failed to send storage result!");
                                    }
                                }
                                Err(e) => {
                                    tracing::error!("Storage get failed: {}", e);
                                    if req.result_sender.send(None).is_err() {
                                        tracing::error!("Failed to send storage result!");
                                    }
                                }
                            }
                        }
                        StorageCommand::Put(req) => {
                            match self
                                .storage
                                .put(&req.crate_name, &req.crate_version, &req.data)
                                .await
                            {
                                Ok(_) => {
                                    if req.result_sender.send(true).is_err() {
                                        tracing::error!("Failed to send storage result!");
                                    }
                                }
                                Err(e) => {
                                    tracing::error!("Storage put failed: {}", e);
                                    if req.result_sender.send(false).is_err() {
                                        tracing::error!("Failed to send storage result!");
                                    }
                                }
                            }
                        }
                    },
                    None => {
                        tracing::warn!("Did not receive a StorageCommand!")
                    }
                }
            }
        });

        (handle, sender)
    }
}