-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathattachment_store.cpp
More file actions
452 lines (408 loc) · 16.8 KB
/
Copy pathattachment_store.cpp
File metadata and controls
452 lines (408 loc) · 16.8 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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
#include "attachment_store.hpp"
#include "../image/image_processor.hpp"
#include "../utils/atomic_file.hpp"
#include "../utils/logger.hpp"
#include "../utils/utf8_path.hpp"
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cctype>
#include <fstream>
#include <iterator>
#include <sstream>
#include <system_error>
namespace fs = std::filesystem;
namespace acecode {
namespace {
std::string ascii_lower(std::string value) {
std::transform(value.begin(), value.end(), value.begin(), [](unsigned char c) {
return static_cast<char>(std::tolower(c));
});
return value;
}
std::string extension_from_name(const std::string& name) {
const auto dot = name.find_last_of('.');
if (dot == std::string::npos || dot + 1 >= name.size()) return {};
std::string ext = name.substr(dot);
if (ext.size() > 16) return {};
for (char c : ext) {
if (c == '.') continue;
if (!std::isalnum(static_cast<unsigned char>(c))) return {};
}
return ascii_lower(ext);
}
std::string extension_for_mime(const std::string& mime_type) {
const std::string mime = ascii_lower(mime_type);
if (mime == "image/png") return ".png";
if (mime == "image/jpeg" || mime == "image/jpg") return ".jpg";
if (mime == "image/gif") return ".gif";
if (mime == "image/webp") return ".webp";
if (mime == "image/bmp") return ".bmp";
if (mime == "image/svg+xml") return ".svg";
if (mime == "text/plain") return ".txt";
if (mime == "text/markdown") return ".md";
if (mime == "application/json") return ".json";
return {};
}
std::string replace_extension_for_mime(const std::string& name,
const std::string& mime_type) {
const std::string ext = extension_for_mime(mime_type);
if (ext.empty()) return name;
const auto slash = name.find_last_of("/\\");
const auto dot = name.find_last_of('.');
if (dot != std::string::npos &&
(slash == std::string::npos || dot > slash)) {
return name.substr(0, dot) + ext;
}
return name + ext;
}
fs::path attachments_dir(const std::string& project_dir,
const std::string& session_id) {
return path_from_utf8(project_dir) / "attachments" / session_id;
}
fs::path metadata_path_for(const std::string& project_dir,
const std::string& session_id,
const std::string& attachment_id) {
return attachments_dir(project_dir, session_id) / (attachment_id + ".json");
}
std::string generate_attachment_id() {
static std::atomic<unsigned long long> counter{0};
const auto now = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()).count();
std::ostringstream oss;
oss << "att_" << now << "_" << std::hex << counter.fetch_add(1);
return oss.str();
}
void set_error(std::string* error, std::string value) {
if (error) *error = std::move(value);
}
} // namespace
std::string attachment_blob_url(const std::string& session_id,
const std::string& attachment_id) {
return "/api/sessions/" + session_id + "/attachments/" + attachment_id + "/blob";
}
std::string attachment_mime_for_name(const std::string& name,
const std::string& supplied_mime_type) {
if (!supplied_mime_type.empty()) return supplied_mime_type;
const std::string ext = extension_from_name(name);
if (ext == ".png") return "image/png";
if (ext == ".jpg" || ext == ".jpeg") return "image/jpeg";
if (ext == ".gif") return "image/gif";
if (ext == ".webp") return "image/webp";
if (ext == ".bmp") return "image/bmp";
if (ext == ".svg") return "image/svg+xml";
if (ext == ".pdf") return "application/pdf";
if (ext == ".txt" || ext == ".log") return "text/plain";
if (ext == ".md" || ext == ".markdown") return "text/markdown";
if (ext == ".json") return "application/json";
if (ext == ".csv") return "text/csv";
if (ext == ".js" || ext == ".jsx") return "text/javascript";
if (ext == ".ts" || ext == ".tsx") return "text/typescript";
if (ext == ".css") return "text/css";
if (ext == ".html" || ext == ".htm") return "text/html";
if (ext == ".xml") return "application/xml";
if (ext == ".cpp" || ext == ".hpp" || ext == ".h" || ext == ".c" ||
ext == ".py" || ext == ".rs" || ext == ".go" || ext == ".java" ||
ext == ".yml" || ext == ".yaml" || ext == ".toml" || ext == ".ini") {
return "text/plain";
}
return "application/octet-stream";
}
std::string attachment_kind_for_mime(const std::string& mime_type,
const std::string& name) {
const std::string mime = ascii_lower(attachment_mime_for_name(name, mime_type));
// SVG 是矢量 XML,不是栅格图;多数 vision provider 拒收 data:image/svg+xml,
// 因此把它排除出 image 路由,按普通文件处理(route-attachments-by-capability)。
if (mime == "image/svg+xml") return "file";
if (mime.rfind("image/", 0) == 0) return "image";
if (mime.rfind("text/", 0) == 0 ||
mime == "application/json" ||
mime == "application/xml") {
return "file";
}
return "file";
}
bool is_valid_attachment_id(const std::string& id) {
if (id.empty() || id.size() > 96) return false;
for (char c : id) {
const unsigned char u = static_cast<unsigned char>(c);
if (std::isalnum(u) || c == '_' || c == '-') continue;
return false;
}
return true;
}
std::optional<AttachmentRecord> save_attachment_reference(
const std::string& project_dir,
const std::string& session_id,
const std::string& name,
const std::string& supplied_mime_type,
const std::string& source_path,
std::string* error) {
if (project_dir.empty() || session_id.empty()) {
set_error(error, "session storage unavailable");
return std::nullopt;
}
if (source_path.empty() || source_path.size() > 32768) {
set_error(error, "attachment source path is unavailable");
return std::nullopt;
}
const fs::path input = path_from_utf8(source_path);
if (!input.is_absolute()) {
set_error(error, "attachment source path must be absolute");
return std::nullopt;
}
std::error_code ec;
const fs::path canonical = fs::weakly_canonical(input, ec);
if (ec || canonical.empty() || !fs::is_regular_file(canonical, ec) || ec) {
set_error(error, "attachment source path is unavailable");
return std::nullopt;
}
const std::string source_name = path_to_utf8(canonical.filename());
const std::string stored_name = name.empty()
? (source_name.empty() ? "attachment" : source_name)
: name;
const std::string stored_mime =
attachment_mime_for_name(stored_name, supplied_mime_type);
if (attachment_kind_for_mime(std::string{}, source_name) == "image" ||
attachment_kind_for_mime(stored_mime, stored_name) == "image") {
set_error(error, "image attachments require snapshot data");
return std::nullopt;
}
const std::uintmax_t actual_size = fs::file_size(canonical, ec);
if (ec) {
set_error(error, "failed to inspect attachment source");
return std::nullopt;
}
AttachmentRecord record;
record.id = generate_attachment_id();
record.session_id = session_id;
record.name = stored_name;
record.mime_type = stored_mime;
record.kind = "file";
record.size_bytes = actual_size;
record.metadata = {
{"source_path", path_to_utf8_generic(canonical)},
{"storage", "source_reference"},
};
const fs::path dir = attachments_dir(project_dir, session_id);
fs::create_directories(dir, ec);
if (ec) {
set_error(error, "failed to create attachment directory: " + ec.message());
return std::nullopt;
}
if (!atomic_write_file(
path_to_utf8(metadata_path_for(project_dir, session_id, record.id)),
attachment_to_json(record).dump(2))) {
set_error(error, "failed to write attachment metadata");
return std::nullopt;
}
return record;
}
std::optional<AttachmentRecord> save_attachment(
const std::string& project_dir,
const std::string& session_id,
const std::string& name,
const std::string& supplied_mime_type,
const std::string& bytes,
std::string* error,
const nlohmann::json& initial_metadata) {
if (project_dir.empty() || session_id.empty()) {
set_error(error, "session storage unavailable");
return std::nullopt;
}
if (bytes.empty()) {
set_error(error, "attachment data required");
return std::nullopt;
}
std::string stored_name = name.empty() ? "attachment" : name;
std::string stored_mime = attachment_mime_for_name(stored_name, supplied_mime_type);
std::string stored_bytes = bytes;
nlohmann::json normalization = nlohmann::json::object();
if (attachment_kind_for_mime(stored_mime, stored_name) == "image") {
auto normalized = image::normalize_image_bytes(stored_bytes, stored_mime);
if (normalized.attempted) {
normalization = {
{"backend", normalized.backend},
{"changed", normalized.changed},
{"ok", normalized.ok},
{"reason", normalized.reason},
{"original_size_bytes", bytes.size()},
{"threshold_bytes", image::kImageCompressionThresholdBytes},
{"max_edge", image::kImageNormalizeMaxEdge},
{"input_width", normalized.input.width},
{"input_height", normalized.input.height},
{"input_channels", normalized.input.channels},
};
if (normalized.output.width > 0 && normalized.output.height > 0) {
normalization["output_width"] = normalized.output.width;
normalization["output_height"] = normalized.output.height;
normalization["output_channels"] = normalized.output.channels;
}
if (!normalized.error.empty()) normalization["error"] = normalized.error;
LOG_INFO("[attachment-store] image normalization"
" session=" + session_id +
" name=" + stored_name +
" ok=" + std::string(normalized.ok ? "1" : "0") +
" changed=" + std::string(normalized.changed ? "1" : "0") +
" original_size=" + std::to_string(bytes.size()) +
" reason=" + normalized.reason +
" error=" + normalized.error);
if (!normalized.ok) {
set_error(error, "image normalization failed: " +
(normalized.error.empty() ? normalized.reason : normalized.error));
return std::nullopt;
}
if (normalized.ok && normalized.changed) {
stored_bytes = std::move(normalized.bytes);
if (!normalized.mime_type.empty()) {
const std::string original_name = stored_name;
stored_mime = normalized.mime_type;
stored_name = replace_extension_for_mime(stored_name, stored_mime);
normalization["output_size_bytes"] = stored_bytes.size();
normalization["output_mime_type"] = stored_mime;
normalization["original_name"] = original_name;
}
}
}
}
if (stored_bytes.size() > kMaxAttachmentBytes) {
set_error(error, "attachment too large");
return std::nullopt;
}
AttachmentRecord record;
record.id = generate_attachment_id();
record.session_id = session_id;
record.name = stored_name;
record.mime_type = stored_mime;
record.kind = attachment_kind_for_mime(record.mime_type, record.name);
record.size_bytes = static_cast<std::uintmax_t>(stored_bytes.size());
record.blob_url = attachment_blob_url(session_id, record.id);
if (initial_metadata.is_object()) {
record.metadata = initial_metadata;
}
if (!normalization.empty()) {
record.metadata["image_normalization"] = normalization;
}
std::string ext = extension_from_name(record.name);
if (ext.empty()) ext = extension_for_mime(record.mime_type);
const fs::path dir = attachments_dir(project_dir, session_id);
std::error_code ec;
fs::create_directories(dir, ec);
if (ec) {
set_error(error, "failed to create attachment directory: " + ec.message());
return std::nullopt;
}
const fs::path blob_path = dir / (record.id + ext);
{
std::ofstream ofs(blob_path, std::ios::binary);
if (!ofs.is_open()) {
set_error(error, "failed to write attachment");
return std::nullopt;
}
ofs.write(stored_bytes.data(), static_cast<std::streamsize>(stored_bytes.size()));
if (!ofs.good()) {
set_error(error, "failed to write attachment bytes");
return std::nullopt;
}
}
record.path = path_to_utf8(blob_path);
atomic_write_file(path_to_utf8(metadata_path_for(project_dir, session_id, record.id)),
attachment_to_json(record).dump(2));
return record;
}
std::optional<AttachmentRecord> load_attachment(
const std::string& project_dir,
const std::string& session_id,
const std::string& attachment_id,
std::string* error) {
if (!is_valid_attachment_id(attachment_id)) {
set_error(error, "invalid attachment id");
return std::nullopt;
}
const fs::path meta_path = metadata_path_for(project_dir, session_id, attachment_id);
std::ifstream ifs(meta_path, std::ios::binary);
if (!ifs.is_open()) {
set_error(error, "attachment not found");
return std::nullopt;
}
std::string content((std::istreambuf_iterator<char>(ifs)),
std::istreambuf_iterator<char>());
try {
auto parsed = nlohmann::json::parse(content);
auto record = attachment_from_json(parsed);
if (!record.has_value() || record->session_id != session_id || record->id != attachment_id) {
set_error(error, "invalid attachment metadata");
return std::nullopt;
}
return record;
} catch (const std::exception& e) {
set_error(error, std::string("bad attachment metadata: ") + e.what());
return std::nullopt;
}
}
std::optional<std::string> read_attachment_bytes(
const AttachmentRecord& record,
std::size_t max_bytes,
std::string* error) {
if (record.path.empty()) {
set_error(error, "attachment path missing");
return std::nullopt;
}
std::ifstream ifs(path_from_utf8(record.path), std::ios::binary);
if (!ifs.is_open()) {
set_error(error, "failed to open attachment");
return std::nullopt;
}
std::string bytes((std::istreambuf_iterator<char>(ifs)),
std::istreambuf_iterator<char>());
if (bytes.size() > max_bytes) {
set_error(error, "attachment too large");
return std::nullopt;
}
return bytes;
}
nlohmann::json attachment_to_json(const AttachmentRecord& record) {
nlohmann::json j = {
{"id", record.id},
{"session_id", record.session_id},
{"name", record.name},
{"kind", record.kind},
{"mime_type", record.mime_type},
{"path", record.path},
{"blob_url", record.blob_url},
{"size_bytes", record.size_bytes},
};
if (record.metadata.is_object() && !record.metadata.empty()) {
j["metadata"] = record.metadata;
}
return j;
}
std::optional<AttachmentRecord> attachment_from_json(const nlohmann::json& j) {
if (!j.is_object()) return std::nullopt;
AttachmentRecord record;
if (!j.contains("id") || !j["id"].is_string()) return std::nullopt;
record.id = j["id"].get<std::string>();
if (!is_valid_attachment_id(record.id)) return std::nullopt;
record.session_id = j.value("session_id", std::string{});
record.name = j.value("name", std::string{"attachment"});
record.kind = j.value("kind", std::string{});
record.mime_type = j.value("mime_type", std::string{});
record.path = j.value("path", std::string{});
record.blob_url = j.value("blob_url", std::string{});
record.size_bytes = j.value("size_bytes", static_cast<std::uintmax_t>(0));
if (record.kind.empty()) {
record.kind = attachment_kind_for_mime(record.mime_type, record.name);
}
if (record.mime_type.empty()) {
record.mime_type = attachment_mime_for_name(record.name, std::string{});
}
if (record.blob_url.empty() && !record.session_id.empty() &&
!record.path.empty()) {
record.blob_url = attachment_blob_url(record.session_id, record.id);
}
if (j.contains("metadata") && j["metadata"].is_object()) {
record.metadata = j["metadata"];
}
return record;
}
} // namespace acecode