1 /*
2 * Copyright (c) 2023 Huawei Device Co., Ltd.
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 */
15
16 #include <algorithm>
17 #include <functional>
18 #include <set>
19 #include <string>
20 #include <unordered_map>
21 #include "main.rs.h"
22 #include "client_blobstore.h"
23
24 namespace nsp_org {
25 namespace nsp_blobstore {
26 // Toy implementation of an in-memory nsp_blobstore.
27 //
28 // In reality the implementation of client_blobstore could be a large complex C++
29 // library.
30 class client_blobstore::impl {
31 friend client_blobstore;
32 using Blob = struct {
33 std::string data;
34 std::set<std::string> tags;
35 };
36 std::unordered_map<uint64_t, Blob> blobs;
37 };
38
client_blobstore()39 client_blobstore::client_blobstore() : impl(new class client_blobstore::impl) {}
40
41 // Upload a new blob and return a blobid that serves as a handle to the blob.
put_buf(MultiBufs & buf) const42 uint64_t client_blobstore::put_buf(MultiBufs &buf) const
43 {
44 std::string contents;
45
46 // Traverse the caller's res_chunk iterator.
47 //
48 // In reality there might be sophisticated batching of chunks and/or parallel
49 // upload implemented by the nsp_blobstore's C++ client.
50 while (true) {
51 auto res_chunk = next_chunk(buf);
52 if (res_chunk.size() == 0) {
53 break;
54 }
55 contents.append(reinterpret_cast<const char *>(res_chunk.data()), res_chunk.size());
56 }
57
58 // Insert into map and provide caller the handle.
59 auto res = std::hash<std::string> {} (contents);
60 impl->blobs[res] = {std::move(contents), {}};
61 return res;
62 }
63
64 // Add add_tag to an existing blob.
add_tag(uint64_t blobid,rust::Str add_tag) const65 void client_blobstore::add_tag(uint64_t blobid, rust::Str add_tag) const
66 {
67 impl->blobs[blobid].tags.emplace(add_tag);
68 }
69
70 // Retrieve get_metadata about a blob.
get_metadata(uint64_t blobid) const71 Metadata_Blob client_blobstore::get_metadata(uint64_t blobid) const
72 {
73 Metadata_Blob get_metadata {};
74 auto blob = impl->blobs.find(blobid);
75 if (blob != impl->blobs.end()) {
76 get_metadata.size = blob->second.data.size();
77 std::for_each(blob->second.tags.cbegin(), blob->second.tags.cend(),
78 [&](auto &t) { get_metadata.tags.emplace_back(t); });
79 }
80 return get_metadata;
81 }
82
blobstore_client_new()83 std::unique_ptr<client_blobstore> blobstore_client_new()
84 {
85 return std::make_unique<client_blobstore>();
86 }
87 } // namespace nsp_blobstore
88 } // namespace nsp_org
89