opendal/services/aliyun_drive/
writer.rs1use std::sync::Arc;
19
20use bytes::Buf;
21
22use super::core::AliyunDriveCore;
23use super::core::CheckNameMode;
24use super::core::CreateResponse;
25use super::core::CreateType;
26use super::core::UploadUrlResponse;
27use crate::raw::*;
28use crate::*;
29
30pub struct AliyunDriveWriter {
31 core: Arc<AliyunDriveCore>,
32
33 _op: OpWrite,
34 parent_file_id: String,
35 name: String,
36
37 file_id: Option<String>,
38 upload_id: Option<String>,
39 part_number: usize,
40}
41
42impl AliyunDriveWriter {
43 pub fn new(core: Arc<AliyunDriveCore>, parent_file_id: &str, name: &str, op: OpWrite) -> Self {
44 AliyunDriveWriter {
45 core,
46 _op: op,
47 parent_file_id: parent_file_id.to_string(),
48 name: name.to_string(),
49 file_id: None,
50 upload_id: None,
51 part_number: 1, }
53 }
54}
55
56impl oio::Write for AliyunDriveWriter {
57 async fn write(&mut self, bs: Buffer) -> Result<()> {
58 let (upload_id, file_id) = match (self.upload_id.as_ref(), self.file_id.as_ref()) {
59 (Some(upload_id), Some(file_id)) => (upload_id, file_id),
60 _ => {
61 let res = self
62 .core
63 .create(
64 Some(&self.parent_file_id),
65 &self.name,
66 CreateType::File,
67 CheckNameMode::Refuse,
68 )
69 .await?;
70 let output: CreateResponse =
71 serde_json::from_reader(res.reader()).map_err(new_json_deserialize_error)?;
72 if output.exist.is_some_and(|x| x) {
73 return Err(Error::new(ErrorKind::AlreadyExists, "file exists"));
74 }
75 self.upload_id = output.upload_id;
76 self.file_id = Some(output.file_id);
77 (
78 self.upload_id.as_ref().expect("cannot find upload_id"),
79 self.file_id.as_ref().expect("cannot find file_id"),
80 )
81 }
82 };
83
84 let res = self
85 .core
86 .get_upload_url(file_id, upload_id, Some(self.part_number))
87 .await?;
88 let output: UploadUrlResponse =
89 serde_json::from_reader(res.reader()).map_err(new_json_deserialize_error)?;
90
91 let Some(upload_url) = output
92 .part_info_list
93 .as_ref()
94 .and_then(|list| list.first())
95 .map(|part_info| &part_info.upload_url)
96 else {
97 return Err(Error::new(ErrorKind::Unexpected, "cannot find upload_url"));
98 };
99
100 if let Err(err) = self.core.upload(upload_url, bs).await {
101 if err.kind() != ErrorKind::AlreadyExists {
102 return Err(err);
103 }
104 };
105
106 self.part_number += 1;
107
108 Ok(())
109 }
110
111 async fn close(&mut self) -> Result<Metadata> {
112 let (Some(upload_id), Some(file_id)) = (self.upload_id.as_ref(), self.file_id.as_ref())
113 else {
114 return Ok(Metadata::default());
115 };
116
117 self.core.complete(file_id, upload_id).await?;
118 Ok(Metadata::default())
119 }
120
121 async fn abort(&mut self) -> Result<()> {
122 let Some(file_id) = self.file_id.as_ref() else {
123 return Ok(());
124 };
125 self.core.delete_path(file_id).await
126 }
127}