opendal_core/services/lakefs/writer.rs
1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements. See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership. The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License. You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied. See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use std::sync::Arc;
19
20use bytes::Buf;
21use http::StatusCode;
22
23use super::core::LakefsCore;
24use super::core::LakefsStatus;
25use super::error::parse_error;
26use crate::raw::*;
27use crate::*;
28
29pub struct LakefsWriter {
30 core: Arc<LakefsCore>,
31 op: OpWrite,
32 path: String,
33}
34
35impl LakefsWriter {
36 pub fn new(core: Arc<LakefsCore>, path: String, op: OpWrite) -> Self {
37 LakefsWriter { core, path, op }
38 }
39}
40
41impl oio::OneShotWrite for LakefsWriter {
42 async fn write_once(&self, bs: Buffer) -> Result<Metadata> {
43 let resp = self.core.upload_object(&self.path, &self.op, bs).await?;
44
45 let status = resp.status();
46
47 match status {
48 StatusCode::CREATED | StatusCode::OK => {
49 let body = resp.into_body();
50 let body_bytes = body.to_bytes();
51
52 // Try to parse metadata from upload response body
53 match serde_json::from_slice::<LakefsStatus>(&body_bytes) {
54 Ok(lakefs_status) => {
55 // Successfully parsed ObjectStats from upload response
56 Ok(LakefsCore::parse_lakefs_status_into_metadata(
57 &lakefs_status,
58 ))
59 }
60 Err(_) => {
61 // Upload response doesn't contain ObjectStats, fetch via stat API
62 let stat_resp = self.core.get_object_metadata(&self.path).await?;
63
64 match stat_resp.status() {
65 StatusCode::OK => {
66 let lakefs_status: LakefsStatus =
67 serde_json::from_reader(stat_resp.into_body().reader())
68 .map_err(new_json_deserialize_error)?;
69
70 Ok(LakefsCore::parse_lakefs_status_into_metadata(
71 &lakefs_status,
72 ))
73 }
74 _ => Err(parse_error(stat_resp)),
75 }
76 }
77 }
78 }
79 _ => Err(parse_error(resp)),
80 }
81 }
82}