This is an automated email from the ASF dual-hosted git repository.
Xuanwo pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/opendal.git
The following commit(s) were added to refs/heads/main by this push:
new a4ea7deed7 fix(bindings/cpp): keep last_modified in UTC with
subseconds (#8837)
a4ea7deed7 is described below
commit a4ea7deed71671a90dd0d9be45019f4b31925774
Author: Xuanwo <[email protected]>
AuthorDate: Mon Nov 23 16:38:48 2026 +0800
fix(bindings/cpp): keep last_modified in UTC with subseconds (#8837)
`parse_meta_data` parsed the RFC 3339 `last_modified` string with
`sscanf` and passed the fields to `std::mktime`, which interprets them
in the host's local timezone and drops the fractional second. On non-UTC
hosts, `Stat()` returned an instant shifted by the UTC offset, so
passing it back as `if_modified_since` / `if_unmodified_since` compared
against a different instant than the service reported.
Carry `last_modified` through the cxx bridge as the existing
`OptionalTimestamp` seconds and nanoseconds instead. Normalize the Rust
timestamp into a floor second and non-negative nanosecond so instants
before the Unix epoch round-trip with `ToFfiOptionalTimestamp`, and build
the `system_clock::time_point` directly in C++.
Add an `fs` regression test that pins a file mtime with a subsecond
fraction, runs under UTC+9, and checks both the exact `Stat` value and
the conditional-read round trip. Add Rust unit tests for the
seconds/nanoseconds conversion, including a pre-1970 timestamp.
---
bindings/cpp/CMakeLists.txt | 6 +-
bindings/cpp/src/lib.rs | 2 +-
bindings/cpp/src/operator.cpp | 43 +++----
bindings/cpp/src/types.rs | 77 ++++++++++++-
bindings/cpp/tests/timestamp_test.cpp | 206 ++++++++++++++++++++++++++++++++++
5 files changed, 301 insertions(+), 33 deletions(-)
diff --git a/bindings/cpp/CMakeLists.txt b/bindings/cpp/CMakeLists.txt
index ca0c6b7abe..9fda22e1c9 100644
--- a/bindings/cpp/CMakeLists.txt
+++ b/bindings/cpp/CMakeLists.txt
@@ -66,9 +66,9 @@ endif()
if (OPENDAL_ENABLE_TESTING)
if (OPENDAL_FEATURES)
- set(OPENDAL_FEATURES
"${OPENDAL_FEATURES},testing,opendal/services-dashmap")
+ set(OPENDAL_FEATURES
"${OPENDAL_FEATURES},testing,opendal/services-dashmap,opendal/services-fs")
else()
- set(OPENDAL_FEATURES "testing,opendal/services-dashmap")
+ set(OPENDAL_FEATURES
"testing,opendal/services-dashmap,opendal/services-fs")
endif()
endif()
@@ -222,7 +222,7 @@ if (OPENDAL_ENABLE_TESTING)
)
endif()
- list(APPEND TEST_SOURCE_FILE tests/basic_test.cpp tests/layer_test.cpp
tests/metadata_test.cpp tests/test_main.cpp)
+ list(APPEND TEST_SOURCE_FILE tests/basic_test.cpp tests/layer_test.cpp
tests/metadata_test.cpp tests/timestamp_test.cpp tests/test_main.cpp)
if (OPENDAL_ENABLE_ASYNC)
list(APPEND TEST_SOURCE_FILE tests/async_test.cpp)
endif()
diff --git a/bindings/cpp/src/lib.rs b/bindings/cpp/src/lib.rs
index d86ab6a79f..21e3a61a94 100644
--- a/bindings/cpp/src/lib.rs
+++ b/bindings/cpp/src/lib.rs
@@ -227,7 +227,7 @@ mod ffi {
content_type: OptionalString,
content_encoding: OptionalString,
etag: OptionalString,
- last_modified: OptionalString,
+ last_modified: OptionalTimestamp,
version: OptionalString,
is_current: OptionalBool,
is_deleted: bool,
diff --git a/bindings/cpp/src/operator.cpp b/bindings/cpp/src/operator.cpp
index 12845142b0..4a3b6afce9 100644
--- a/bindings/cpp/src/operator.cpp
+++ b/bindings/cpp/src/operator.cpp
@@ -19,8 +19,6 @@
#include <chrono>
#include <cstdint>
-#include <cstdio>
-#include <ctime>
#include "lib.rs.h"
#include "opendal.hpp"
@@ -204,6 +202,19 @@ std::optional<bool> parse_optional_bool(ffi::OptionalBool
&&b) {
}
}
+std::optional<std::chrono::system_clock::time_point> parse_optional_timestamp(
+ ffi::OptionalTimestamp &&ts) {
+ if (!ts.has_value) {
+ return std::nullopt;
+ }
+
+ auto duration = std::chrono::seconds(ts.seconds) +
+ std::chrono::nanoseconds(ts.nanoseconds);
+ return std::chrono::system_clock::time_point(
+ std::chrono::duration_cast<std::chrono::system_clock::duration>(
+ duration));
+}
+
Metadata parse_meta_data(ffi::Metadata &&meta) {
Metadata metadata;
@@ -226,32 +237,8 @@ Metadata parse_meta_data(ffi::Metadata &&meta) {
metadata.is_current = parse_optional_bool(std::move(meta.is_current));
metadata.is_deleted = meta.is_deleted;
- // Parse last_modified timestamp
- auto last_modified_str =
parse_optional_string(std::move(meta.last_modified));
- if (last_modified_str.has_value()) {
- // Parse ISO 8601 string to time_point using strptime to avoid locale lock
- std::tm tm = {};
- const char *str = last_modified_str.value().c_str();
-
- // Parse ISO 8601 format: YYYY-MM-DDTHH:MM:SS
- int year, month, day, hour, minute, second;
- if (sscanf(str, "%d-%d-%dT%d:%d:%d", &year, &month, &day, &hour, &minute,
- &second) == 6) {
- tm.tm_year = year - 1900; // years since 1900
- tm.tm_mon = month - 1; // months since January (0-11)
- tm.tm_mday = day;
- tm.tm_hour = hour;
- tm.tm_min = minute;
- tm.tm_sec = second;
- tm.tm_isdst = -1; // let mktime determine DST
-
- std::time_t time_t_value = std::mktime(&tm);
- if (time_t_value != -1) {
- metadata.last_modified =
- std::chrono::system_clock::from_time_t(time_t_value);
- }
- }
- }
+ metadata.last_modified =
+ parse_optional_timestamp(std::move(meta.last_modified));
return metadata;
}
diff --git a/bindings/cpp/src/types.rs b/bindings/cpp/src/types.rs
index 2e522bfdee..87808630e7 100644
--- a/bindings/cpp/src/types.rs
+++ b/bindings/cpp/src/types.rs
@@ -29,7 +29,7 @@ impl From<od::Metadata> for ffi::Metadata {
let content_type = meta.content_type().map(ToOwned::to_owned).into();
let content_encoding =
meta.content_encoding().map(ToOwned::to_owned).into();
let etag = meta.etag().map(ToOwned::to_owned).into();
- let last_modified = meta.last_modified().map(|time|
time.to_string()).into();
+ let last_modified = to_ffi_optional_timestamp(meta.last_modified());
let version = meta.version().map(ToOwned::to_owned).into();
let is_current = meta.is_current().into();
let is_deleted = meta.is_deleted();
@@ -68,6 +68,37 @@ impl From<od::EntryMode> for ffi::EntryMode {
}
}
+/// Convert a UTC timestamp into the signed seconds and non-negative
+/// nanoseconds used by the C++ binding.
+///
+/// `Timestamp::as_second` truncates toward zero and
+/// `Timestamp::subsec_nanosecond` carries the same sign for instants before
+/// the Unix epoch. Normalize them into a floor second and a non-negative
+/// nanosecond so C++ can rebuild the instant with `seconds + nanoseconds`.
+fn to_ffi_optional_timestamp(timestamp: Option<od::raw::Timestamp>) ->
ffi::OptionalTimestamp {
+ let Some(timestamp) = timestamp else {
+ return ffi::OptionalTimestamp {
+ has_value: false,
+ seconds: 0,
+ nanoseconds: 0,
+ };
+ };
+
+ let timestamp = timestamp.into_inner();
+ let mut seconds = timestamp.as_second();
+ let mut nanoseconds = timestamp.subsec_nanosecond();
+ if nanoseconds < 0 {
+ seconds -= 1;
+ nanoseconds += 1_000_000_000;
+ }
+
+ ffi::OptionalTimestamp {
+ has_value: true,
+ seconds,
+ nanoseconds: nanoseconds as u32,
+ }
+}
+
impl From<Option<String>> for ffi::OptionalString {
fn from(s: Option<String>) -> Self {
match s {
@@ -114,3 +145,47 @@ impl From<Option<od::Entry>> for ffi::OptionalEntry {
}
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn last_modified_of(timestamp: od::raw::Timestamp) ->
ffi::OptionalTimestamp {
+ let mut builder = od::MetadataBuilder::file(0);
+ builder.last_modified(timestamp);
+ let metadata: ffi::Metadata = builder.build().into();
+ metadata.last_modified
+ }
+
+ #[test]
+ fn test_last_modified_keeps_subsecond_precision() {
+ let timestamp = od::raw::Timestamp::new(1_700_000_000,
123_456_789).unwrap();
+
+ let ffi = last_modified_of(timestamp);
+
+ assert!(ffi.has_value);
+ assert_eq!(ffi.seconds, 1_700_000_000);
+ assert_eq!(ffi.nanoseconds, 123_456_789);
+ }
+
+ #[test]
+ fn test_last_modified_normalizes_pre_epoch_timestamp() {
+ // 1969-12-31T23:59:58.5Z: jiff keeps the negative fraction in
+ // `subsec_nanosecond`, while the C++ bridge expects a floor second
+ // with a non-negative nanosecond.
+ let timestamp = od::raw::Timestamp::new(-1, -500_000_000).unwrap();
+
+ let ffi = last_modified_of(timestamp);
+
+ assert!(ffi.has_value);
+ assert_eq!(ffi.seconds, -2);
+ assert_eq!(ffi.nanoseconds, 500_000_000);
+ }
+
+ #[test]
+ fn test_last_modified_absent() {
+ let metadata: ffi::Metadata =
od::MetadataBuilder::file(0).build().into();
+
+ assert!(!metadata.last_modified.has_value);
+ }
+}
diff --git a/bindings/cpp/tests/timestamp_test.cpp
b/bindings/cpp/tests/timestamp_test.cpp
new file mode 100644
index 0000000000..329e1574be
--- /dev/null
+++ b/bindings/cpp/tests/timestamp_test.cpp
@@ -0,0 +1,206 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include <atomic>
+#include <chrono>
+#include <cstdint>
+#include <cstdlib>
+#include <ctime>
+#include <filesystem>
+#include <optional>
+#include <string>
+
+#ifdef _WIN32
+#define NOMINMAX
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#else
+#include <fcntl.h>
+#include <sys/stat.h>
+#endif
+
+#include "gtest/gtest.h"
+#include "opendal.hpp"
+
+namespace {
+
+std::chrono::system_clock::time_point MakeTimePoint(std::int64_t seconds,
+ std::int64_t nanoseconds) {
+ auto duration = std::chrono::seconds(seconds) +
+ std::chrono::nanoseconds(nanoseconds);
+ return std::chrono::system_clock::time_point(
+ std::chrono::duration_cast<std::chrono::system_clock::duration>(
+ duration));
+}
+
+class ScopedTempDir {
+ public:
+ ScopedTempDir() {
+ static std::atomic<unsigned> next_id{0};
+ auto name = "opendal-cpp-timestamp-" +
+ std::to_string(std::chrono::steady_clock::now()
+ .time_since_epoch()
+ .count()) +
+ "-" + std::to_string(next_id.fetch_add(1));
+ path_ = std::filesystem::temp_directory_path() / name;
+ std::filesystem::create_directories(path_);
+ }
+
+ ~ScopedTempDir() {
+ std::error_code ignored;
+ std::filesystem::remove_all(path_, ignored);
+ }
+
+ ScopedTempDir(const ScopedTempDir &) = delete;
+ ScopedTempDir &operator=(const ScopedTempDir &) = delete;
+
+ const std::filesystem::path &path() const { return path_; }
+
+ private:
+ std::filesystem::path path_;
+};
+
+// Runs a test in a fixed non-UTC timezone and restores TZ afterwards.
+class ScopedTimeZone {
+ public:
+ explicit ScopedTimeZone(const char *timezone) {
+ if (const char *current = std::getenv("TZ"); current != nullptr) {
+ previous_ = current;
+ }
+
+#ifdef _WIN32
+ _putenv_s("TZ", timezone);
+ _tzset();
+#else
+ setenv("TZ", timezone, 1);
+ tzset();
+#endif
+ }
+
+ ~ScopedTimeZone() {
+#ifdef _WIN32
+ _putenv_s("TZ", previous_.has_value() ? previous_->c_str() : "");
+ _tzset();
+#else
+ if (previous_.has_value()) {
+ setenv("TZ", previous_->c_str(), 1);
+ } else {
+ unsetenv("TZ");
+ }
+ tzset();
+#endif
+ }
+
+ ScopedTimeZone(const ScopedTimeZone &) = delete;
+ ScopedTimeZone &operator=(const ScopedTimeZone &) = delete;
+
+ private:
+ std::optional<std::string> previous_;
+};
+
+void SetModificationTime(const std::filesystem::path &path,
+ std::chrono::system_clock::time_point time) {
+#ifdef _WIN32
+ auto nanoseconds_since_epoch =
+ std::chrono::duration_cast<std::chrono::nanoseconds>(
+ time.time_since_epoch())
+ .count();
+ auto filetime = nanoseconds_since_epoch / 100 + 116444736000000000LL;
+ ULARGE_INTEGER value;
+ value.QuadPart = static_cast<ULONGLONG>(filetime);
+ FILETIME timestamp{value.LowPart, value.HighPart};
+
+ HANDLE handle = CreateFileW(
+ path.wstring().c_str(), FILE_WRITE_ATTRIBUTES,
+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr,
+ OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
+ ASSERT_NE(handle, INVALID_HANDLE_VALUE);
+ EXPECT_TRUE(SetFileTime(handle, nullptr, nullptr, ×tamp));
+ CloseHandle(handle);
+#else
+ auto since_epoch = time.time_since_epoch();
+ auto seconds = std::chrono::duration_cast<std::chrono::seconds>(since_epoch);
+ auto nanoseconds =
+ std::chrono::duration_cast<std::chrono::nanoseconds>(since_epoch -
+ seconds);
+ if (nanoseconds.count() < 0) {
+ seconds -= std::chrono::seconds(1);
+ nanoseconds += std::chrono::seconds(1);
+ }
+
+ struct timespec times[2];
+ times[0].tv_sec = 0;
+ times[0].tv_nsec = UTIME_OMIT;
+ times[1].tv_sec = static_cast<time_t>(seconds.count());
+ times[1].tv_nsec = static_cast<long>(nanoseconds.count());
+ ASSERT_EQ(utimensat(AT_FDCWD, path.c_str(), times, 0), 0);
+#endif
+}
+
+class TimestampTest : public ::testing::Test {
+ protected:
+ void SetUp() override {
+ op_ = opendal::Operator("fs", {{"root", dir_.path().string()}});
+ ASSERT_TRUE(op_.Available());
+ }
+
+ ScopedTempDir dir_;
+ opendal::Operator op_;
+};
+
+} // namespace
+
+TEST_F(TimestampTest, LastModifiedIsUtcWithSubseconds) {
+ // UTC+9 exposes any conversion that treats the UTC timestamp as local time.
+ ScopedTimeZone timezone("ZZZ-9");
+
+ const std::string path = "timestamp.txt";
+ op_.Write(path, "timestamp content");
+
+ auto expected = MakeTimePoint(1'700'000'000, 123'456'000);
+ SetModificationTime(dir_.path() / path, expected);
+
+ auto metadata = op_.Stat(path);
+
+ ASSERT_TRUE(metadata.LastModified().has_value());
+ EXPECT_EQ(metadata.LastModified()->time_since_epoch(),
+ expected.time_since_epoch());
+}
+
+TEST_F(TimestampTest, LastModifiedRoundTripsThroughConditions) {
+ ScopedTimeZone timezone("ZZZ-9");
+
+ const std::string path = "timestamp.txt";
+ const std::string content = "timestamp content";
+ op_.Write(path, content);
+
+ auto expected = MakeTimePoint(1'700'000'000, 123'456'000);
+ SetModificationTime(dir_.path() / path, expected);
+
+ auto metadata = op_.Stat(path);
+ ASSERT_TRUE(metadata.LastModified().has_value());
+
+ opendal::ReadOptions options;
+ options.if_unmodified_since = metadata.LastModified();
+ EXPECT_EQ(op_.Read(path, options), content);
+
+ options.if_unmodified_since =
+ *metadata.LastModified() - std::chrono::seconds(1);
+ EXPECT_THROW(op_.Read(path, options), std::exception);
+}