forked from web3infra-foundation/mega
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmod.rs
More file actions
229 lines (208 loc) · 6.67 KB
/
mod.rs
File metadata and controls
229 lines (208 loc) · 6.67 KB
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
use core::fmt;
use std::{path::PathBuf, str::FromStr, sync::Arc};
use bellatrix::Bellatrix;
use callisto::sea_orm_active_enums::RefTypeEnum;
use common::{
errors::{MegaError, ProtocolError},
utils::ZERO_ID,
};
use import_refs::RefCommand;
use jupiter::redis::lock::RedLock;
use repo::Repo;
use tokio::sync::RwLock;
use crate::{
api_service::state::ProtocolApiState,
pack::{RepoHandler, import_repo::ImportRepo, monorepo::MonoRepo},
};
pub mod import_refs;
pub mod repo;
pub mod smart;
#[derive(Clone, Debug)]
pub struct PushUserInfo {
pub username: String,
}
#[derive(Clone)]
pub struct SmartProtocol {
pub transport_protocol: TransportProtocol,
pub capabilities: Vec<Capability>,
pub path: PathBuf,
pub command_list: Vec<RefCommand>,
pub service_type: Option<ServiceType>,
pub username: Option<String>,
pub authenticated_user: Option<PushUserInfo>,
}
#[derive(Debug, PartialEq, Clone, Copy, Default)]
pub enum TransportProtocol {
Local,
#[default]
Http,
Ssh,
Git,
P2p,
}
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum ServiceType {
UploadPack,
ReceivePack,
}
impl fmt::Display for ServiceType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ServiceType::UploadPack => write!(f, "git-upload-pack"),
ServiceType::ReceivePack => write!(f, "git-receive-pack"),
}
}
}
impl FromStr for ServiceType {
type Err = MegaError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"git-upload-pack" => Ok(ServiceType::UploadPack),
"git-receive-pack" => Ok(ServiceType::ReceivePack),
_ => Err(MegaError::Other(format!("Invalid service name: {}", s))),
}
}
}
// TODO: Additional Capabilitys need to be supplemented.
#[derive(Debug, Clone, PartialEq)]
pub enum Capability {
MultiAck,
MultiAckDetailed,
NoDone,
SideBand,
SideBand64k,
ReportStatus,
ReportStatusv2,
OfsDelta,
DeepenSince,
DeepenNot,
}
impl FromStr for Capability {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"report-status" => Ok(Capability::ReportStatus),
"report-status-v2" => Ok(Capability::ReportStatusv2),
"side-band" => Ok(Capability::SideBand),
"side-band-64k" => Ok(Capability::SideBand64k),
"ofs-delta" => Ok(Capability::OfsDelta),
"multi_ack" => Ok(Capability::MultiAck),
"multi_ack_detailed" => Ok(Capability::MultiAckDetailed),
"no-done" => Ok(Capability::NoDone),
"deepen-since" => Ok(Capability::DeepenSince),
"deepen-not" => Ok(Capability::DeepenNot),
_ => Err(()),
}
}
}
pub enum SideBind {
// sideband 1 will contain packfile data,
PackfileData,
// sideband 2 will be used for progress information that the client will generally print to stderr and
ProgressInfo,
// sideband 3 is used for error information.
Error,
}
impl SideBind {
pub fn value(&self) -> u8 {
match self {
Self::PackfileData => b'\x01',
Self::ProgressInfo => b'\x02',
Self::Error => b'\x03',
}
}
}
pub struct RefUpdateRequest {
pub command_list: Vec<RefCommand>,
}
impl SmartProtocol {
pub fn new(path: PathBuf, transport_protocol: TransportProtocol) -> Self {
SmartProtocol {
transport_protocol,
capabilities: Vec::new(),
path,
command_list: Vec::new(),
service_type: None,
username: None,
authenticated_user: None,
}
}
pub fn mock() -> Self {
SmartProtocol {
transport_protocol: TransportProtocol::default(),
capabilities: Vec::new(),
path: PathBuf::new(),
command_list: Vec::new(),
service_type: None,
username: None,
authenticated_user: None,
}
}
pub async fn repo_handler(
&self,
state: &ProtocolApiState,
) -> Result<Arc<dyn RepoHandler>, ProtocolError> {
let config = state.storage.config();
let import_dir = config.monorepo.import_dir.clone();
if self.path.starts_with(import_dir.clone()) {
let storage = state.storage.git_db_storage();
let path_str = self.path.to_str().unwrap();
let model = storage.find_git_repo_exact_match(path_str).await.unwrap();
let repo = if let Some(repo) = model {
repo.into()
} else {
match self.service_type.unwrap() {
ServiceType::UploadPack => {
return Err(ProtocolError::NotFound("Repository not found.".to_owned()));
}
ServiceType::ReceivePack => {
let repo = Repo::new(self.path.clone(), false);
storage.save_git_repo(repo.clone().into()).await.unwrap();
repo
}
}
};
let unpack_redlock = Arc::new(RedLock::new(
state.git_object_cache.connection.clone(),
"git:receive-pack:lock",
30_000, // 30s TTL
));
Ok(Arc::new(ImportRepo {
git_object_cache: state.git_object_cache.clone(),
storage: state.storage.clone(),
repo,
command_list: self.command_list.clone(),
unpack_redlock,
}))
} else {
let mut res = MonoRepo {
git_object_cache: state.git_object_cache.clone(),
storage: state.storage.clone(),
path: self.path.clone(),
base_branch: "main".to_string(),
from_hash: String::new(),
to_hash: String::new(),
current_commit: Arc::new(RwLock::new(None)),
cl_link: Arc::new(RwLock::new(None)),
bellatrix: Arc::new(Bellatrix::new(config.build.clone())),
username: self.username.clone(),
};
if let Some(command) = self
.command_list
.iter()
.find(|x| x.ref_type == RefTypeEnum::Branch)
{
res.from_hash = command.old_id.clone();
res.to_hash = command.new_id.clone();
res.base_branch = command
.ref_name
.strip_prefix("refs/heads/")
.unwrap_or(command.ref_name.as_str())
.to_string();
}
Ok(Arc::new(res))
}
}
}
#[cfg(test)]
mod tests {}