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 c3b07c37d9 fix(bindings/haskell): fix metadata ABI layout, shared
Operator borrowing, and UTF-8 FFI encoding (#9019)
c3b07c37d9 is described below
commit c3b07c37d904abaf7c66bc072f6aaa0e9ebe4792
Author: Xuanwo <[email protected]>
AuthorDate: Wed Nov 25 08:07:50 2026 +0800
fix(bindings/haskell): fix metadata ABI layout, shared Operator borrowing,
and UTF-8 FFI encoding (#9019)
* fix(bindings/haskell): fix FFI ABI layout, operator aliasing, UTF-8
encoding, and logger lifecycle
* fix(bindings/haskell): narrow FFI layout and logger changes
* fix(bindings/haskell): defer logger changes
* test(bindings/haskell): verify 64-bit metadata through FFI
* ci(haskell): expose the bundled Windows C compiler to Cabal
---
.github/workflows/ci_bindings_haskell.yml | 57 +++++++++++++
bindings/haskell/haskell-src/OpenDAL.hs | 50 ++++++-----
bindings/haskell/haskell-src/OpenDAL/FFI.hs | 104 ++++++++++++++---------
bindings/haskell/opendal.cabal | 13 +++
bindings/haskell/src/lib.rs | 124 +++++++++++++++++++++-------
bindings/haskell/src/types.rs | 67 +++++++++++++++
bindings/haskell/test/MetadataTest.hs | 70 ++++++++++++++++
bindings/haskell/test/ResourceTest.hs | 45 +++++++++-
8 files changed, 442 insertions(+), 88 deletions(-)
diff --git a/.github/workflows/ci_bindings_haskell.yml
b/.github/workflows/ci_bindings_haskell.yml
index b95ad10dfc..321b4e5efb 100644
--- a/.github/workflows/ci_bindings_haskell.yml
+++ b/.github/workflows/ci_bindings_haskell.yml
@@ -108,6 +108,63 @@ jobs:
~/.cabal/store
bindings/haskell/dist-newstyle
+ test-windows-metadata:
+ runs-on: windows-2025
+ timeout-minutes: 45
+ defaults:
+ run:
+ working-directory: bindings/haskell
+ steps:
+ - uses: actions/checkout@v7
+ - name: Install native x64 GHC and Cabal
+ shell: pwsh
+ run: |
+ $PSNativeCommandUseErrorActionPreference = $true
+ $toolchain = "$env:RUNNER_TEMP/haskell"
+ New-Item -ItemType Directory -Path $toolchain | Out-Null
+ $ghc = 'ghc-9.4.8-x86_64-unknown-mingw32'
+ $cabal = 'cabal-install-3.16.1.0'
+ curl.exe -fsSL --retry 3
"https://downloads.haskell.org/ghc/9.4.8/$ghc.tar.xz" -o "$toolchain/ghc.tar.xz"
+ tar.exe -xf "$toolchain/ghc.tar.xz" -C "$toolchain"
+ curl.exe -fsSL --retry 3
"https://downloads.haskell.org/cabal/$cabal/$cabal-x86_64-windows.zip" -o
"$toolchain/cabal.zip"
+ Expand-Archive "$toolchain/cabal.zip" "$toolchain/cabal"
+ "$toolchain/$ghc/bin" >> $env:GITHUB_PATH
+ "$toolchain/cabal" >> $env:GITHUB_PATH
+ - name: Build Rust DLL
+ run: cargo build --target x86_64-pc-windows-msvc
+ - name: Run metadata test against the DLL
+ shell: bash
+ # Link the focused test directly to the Rust DLL. Setup.hs configures
+ # Unix rpath for Cabal's library build. Keep the dependencies and GHC
+ # extensions in sync with opendal.cabal.
+ run: |
+ ghc --info
+ mkdir -p dist-newstyle
+ cabal_config=dist-newstyle/metadata-cabal.config
+ cat > "$cabal_config" <<'EOF'
+ repository hackage-direct
+ url: https://hackage.haskell.org/
+ secure: False
+ active-repositories: hackage-direct
+ EOF
+ cabal --config-file="$cabal_config" update --ignore-project
+ # Make GHC's bundled cc available to dependency configure scripts.
+ mingw_bin="$(cygpath -u
"$RUNNER_TEMP")/haskell/ghc-9.4.8-x86_64-unknown-mingw32/mingw/bin"
+ PATH="$PATH:$mingw_bin" \
+ cabal --config-file="$cabal_config" install --ignore-project --lib
--package-env=./metadata-test.env \
+ bytestring mtl text time unordered-containers co-log network tasty
tasty-hunit \
+ --constraint='bytestring >= 0.11.4 && < 0.12' --constraint='mtl >=
2.2.2 && < 2.3' \
+ --constraint='text >= 2.0.2 && < 2.1' --constraint='time >= 1.11.1
&& < 1.12' \
+ --constraint='unordered-containers >= 0.2.19 && < 0.3'
--constraint='co-log >= 0.5 && < 0.7' \
+ --constraint='network >= 3.2 && < 3.3' --constraint='tasty >= 1.5
&& < 1.6' \
+ --constraint='tasty-hunit >= 0.10.1 && < 0.11'
+ rust_dir=target/x86_64-pc-windows-msvc/debug
+ ghc --make -threaded -ihaskell-src -outputdir
dist-newstyle/metadata-test \
+ -package-env metadata-test.env -XOverloadedStrings
-XForeignFunctionInterface \
+ -XDerivingStrategies -XGeneralizedNewtypeDeriving -XLambdaCase \
+ -L"$rust_dir" -l:opendal_hs.dll.lib -o
"$rust_dir/metadata-test.exe" test/MetadataTest.hs
+ "$rust_dir/metadata-test.exe"
+
package:
# GHC's hsc2hs links with -fuse-ld=gold, which Ubuntu 26.04's
# binutils no longer ships.
diff --git a/bindings/haskell/haskell-src/OpenDAL.hs
b/bindings/haskell/haskell-src/OpenDAL.hs
index c1492c2682..46e15d6f6e 100644
--- a/bindings/haskell/haskell-src/OpenDAL.hs
+++ b/bindings/haskell/haskell-src/OpenDAL.hs
@@ -89,7 +89,9 @@ import Data.Text (pack)
import Data.Time (UTCTime, parseTimeM, zonedTimeToUTC)
import Data.Time.Format (defaultTimeLocale)
import Foreign
-import Foreign.C.String
+import Foreign.C.String (CString, peekCString)
+import qualified GHC.Foreign as GHCForeign
+import GHC.IO.Encoding (utf8)
import GHC.Stack (emptyCallStack)
import OpenDAL.FFI
@@ -332,18 +334,24 @@ parseEntryMode 0 = File
parseEntryMode 1 = Dir
parseEntryMode _ = Unknown
+withUtf8CString :: String -> (CString -> IO a) -> IO a
+withUtf8CString = GHCForeign.withCString utf8
+
+peekUtf8CString :: CString -> IO String
+peekUtf8CString = GHCForeign.peekCString utf8
+
maybePeekCString :: CString -> IO (Maybe String)
maybePeekCString value | value == nullPtr = return Nothing
-maybePeekCString value = Just <$> peekCString value
+maybePeekCString value = Just <$> peekUtf8CString value
-- | Peek a Rust-owned `CString` and release it through Rust's `free_string`.
--- The pointer is always released, even when `peekCString` throws.
+-- The pointer is always released, even when `peekUtf8CString` throws.
-- Every byte allocated by Rust must be freed by a Rust function; calling C
-- `free` on it is an allocator mismatch.
parseOwnedCString :: CString -> IO (Maybe String)
parseOwnedCString value
| value == nullPtr = return Nothing
- | otherwise = (Just <$> peekCString value) `finally` freeString value
+ | otherwise = (Just <$> peekUtf8CString value) `finally` freeString value
-- | Convert a failed `FFIResult` into an `OpenDALError`, releasing the
-- Rust-owned `errorMessage` buffer through `free_string`.
@@ -417,9 +425,9 @@ runOp op = runExceptT . flip runReaderT op . runOperatorT
newOperator :: OperatorConfig -> IO (Either OpenDALError Operator)
newOperator (OperatorConfig scheme hashMap maybeLogger) = do
let keysAndValues = HashMap.toList hashMap
- withCString scheme $ \cScheme ->
- withMany withCString (map fst keysAndValues) $ \cKeys ->
- withMany withCString (map snd keysAndValues) $ \cValues ->
+ withUtf8CString scheme $ \cScheme ->
+ withMany withUtf8CString (map fst keysAndValues) $ \cKeys ->
+ withMany withUtf8CString (map snd keysAndValues) $ \cValues ->
allocaArray (length keysAndValues) $ \cKeysPtr ->
allocaArray (length keysAndValues) $ \cValuesPtr ->
alloca $ \ffiResultPtr -> mask_ $ do
@@ -455,7 +463,7 @@ newOperator (OperatorConfig scheme hashMap maybeLogger) = do
-- | Read the whole path into a bytes.
readOpRaw :: Operator -> String -> IO (Either OpenDALError ByteString)
readOpRaw (Operator op) path = withForeignPtr op $ \opptr ->
- withCString path $ \cPath ->
+ withUtf8CString path $ \cPath ->
alloca $ \ffiResultPtr -> mask_ $ do
c_blocking_read opptr cPath ffiResultPtr
ffiResult <- peek ffiResultPtr
@@ -470,7 +478,7 @@ readOpRaw (Operator op) path = withForeignPtr op $ \opptr ->
-- | Write bytes into given path.
writeOpRaw :: Operator -> String -> ByteString -> IO (Either OpenDALError ())
writeOpRaw (Operator op) path byte = withForeignPtr op $ \opptr ->
- withCString path $ \cPath ->
+ withUtf8CString path $ \cPath ->
BS.useAsCStringLen byte $ \(cByte, len) ->
alloca $ \ffiResultPtr -> mask_ $ do
c_blocking_write opptr cPath cByte (fromIntegral len) ffiResultPtr
@@ -482,7 +490,7 @@ writeOpRaw (Operator op) path byte = withForeignPtr op $
\opptr ->
-- | Check if this path exists or not.
isExistOpRaw :: Operator -> String -> IO (Either OpenDALError Bool)
isExistOpRaw (Operator op) path = withForeignPtr op $ \opptr ->
- withCString path $ \cPath ->
+ withUtf8CString path $ \cPath ->
alloca $ \ffiResultPtr -> mask_ $ do
c_blocking_is_exist opptr cPath ffiResultPtr
ffiResult <- peek ffiResultPtr
@@ -496,7 +504,7 @@ isExistOpRaw (Operator op) path = withForeignPtr op $
\opptr ->
-- | Create a dir at given path.
createDirOpRaw :: Operator -> String -> IO (Either OpenDALError ())
createDirOpRaw (Operator op) path = withForeignPtr op $ \opptr ->
- withCString path $ \cPath ->
+ withUtf8CString path $ \cPath ->
alloca $ \ffiResultPtr -> mask_ $ do
c_blocking_create_dir opptr cPath ffiResultPtr
ffiResult <- peek ffiResultPtr
@@ -507,8 +515,8 @@ createDirOpRaw (Operator op) path = withForeignPtr op $
\opptr ->
-- | Copy a file from srcPath to dstPath.
copyOpRaw :: Operator -> String -> String -> IO (Either OpenDALError ())
copyOpRaw (Operator op) srcPath dstPath = withForeignPtr op $ \opptr ->
- withCString srcPath $ \cSrcPath ->
- withCString dstPath $ \cDstPath ->
+ withUtf8CString srcPath $ \cSrcPath ->
+ withUtf8CString dstPath $ \cDstPath ->
alloca $ \ffiResultPtr -> mask_ $ do
c_blocking_copy opptr cSrcPath cDstPath ffiResultPtr
ffiResult <- peek ffiResultPtr
@@ -519,8 +527,8 @@ copyOpRaw (Operator op) srcPath dstPath = withForeignPtr op
$ \opptr ->
-- | Rename a file from srcPath to dstPath.
renameOpRaw :: Operator -> String -> String -> IO (Either OpenDALError ())
renameOpRaw (Operator op) srcPath dstPath = withForeignPtr op $ \opptr ->
- withCString srcPath $ \cSrcPath ->
- withCString dstPath $ \cDstPath ->
+ withUtf8CString srcPath $ \cSrcPath ->
+ withUtf8CString dstPath $ \cDstPath ->
alloca $ \ffiResultPtr -> mask_ $ do
c_blocking_rename opptr cSrcPath cDstPath ffiResultPtr
ffiResult <- peek ffiResultPtr
@@ -531,7 +539,7 @@ renameOpRaw (Operator op) srcPath dstPath = withForeignPtr
op $ \opptr ->
-- | Delete given path.
deleteOpRaw :: Operator -> String -> IO (Either OpenDALError ())
deleteOpRaw (Operator op) path = withForeignPtr op $ \opptr ->
- withCString path $ \cPath ->
+ withUtf8CString path $ \cPath ->
alloca $ \ffiResultPtr -> mask_ $ do
c_blocking_delete opptr cPath ffiResultPtr
ffiResult <- peek ffiResultPtr
@@ -542,7 +550,7 @@ deleteOpRaw (Operator op) path = withForeignPtr op $ \opptr
->
-- | Get given path's metadata without cache directly.
statOpRaw :: Operator -> String -> IO (Either OpenDALError Metadata)
statOpRaw (Operator op) path = withForeignPtr op $ \opptr ->
- withCString path $ \cPath ->
+ withUtf8CString path $ \cPath ->
alloca $ \ffiResultPtr -> mask_ $ do
c_blocking_stat opptr cPath ffiResultPtr
ffiResult <- peek ffiResultPtr
@@ -559,7 +567,7 @@ statOpRaw (Operator op) path = withForeignPtr op $ \opptr ->
-- An error will be returned if path doesn't end with /.
listOpRaw :: Operator -> String -> IO (Either OpenDALError Lister)
listOpRaw (Operator op) path = withForeignPtr op $ \opptr ->
- withCString path $ \cPath ->
+ withUtf8CString path $ \cPath ->
alloca $ \ffiResultPtr -> mask_ $ do
c_blocking_list opptr cPath ffiResultPtr
ffiResult <- peek ffiResultPtr
@@ -577,7 +585,7 @@ listOpRaw (Operator op) path = withForeignPtr op $ \opptr ->
-- An error will be returned if given path doesn't end with /.
scanOpRaw :: Operator -> String -> IO (Either OpenDALError Lister)
scanOpRaw (Operator op) path = withForeignPtr op $ \opptr ->
- withCString path $ \cPath ->
+ withUtf8CString path $ \cPath ->
alloca $ \ffiResultPtr -> mask_ $ do
c_blocking_scan opptr cPath ffiResultPtr
ffiResult <- peek ffiResultPtr
@@ -639,7 +647,7 @@ writerClose (Writer writer) = withForeignPtr writer $
\writerptr ->
-- | Create a new writer for given path with specified options.
writerOpRaw :: Operator -> String -> WriterOption -> IO (Either OpenDALError
Writer)
writerOpRaw (Operator op) path writerOption = withForeignPtr op $ \opptr ->
- withCString path $ \cPath ->
+ withUtf8CString path $ \cPath ->
alloca $ \ffiResultPtr -> mask_ $ do
if woAppend writerOption
then c_blocking_writer_append opptr cPath ffiResultPtr
@@ -659,7 +667,7 @@ writerOpRaw (Operator op) path writerOption =
withForeignPtr op $ \opptr ->
-- | Remove all files and directories recursively.
removeAllOpRaw :: Operator -> String -> IO (Either OpenDALError ())
removeAllOpRaw (Operator op) path = withForeignPtr op $ \opptr ->
- withCString path $ \cPath ->
+ withUtf8CString path $ \cPath ->
alloca $ \ffiResultPtr -> mask_ $ do
c_blocking_remove_all opptr cPath ffiResultPtr
ffiResult <- peek ffiResultPtr
diff --git a/bindings/haskell/haskell-src/OpenDAL/FFI.hs
b/bindings/haskell/haskell-src/OpenDAL/FFI.hs
index 38d511c2f4..c565a34a14 100644
--- a/bindings/haskell/haskell-src/OpenDAL/FFI.hs
+++ b/bindings/haskell/haskell-src/OpenDAL/FFI.hs
@@ -21,6 +21,11 @@ import Foreign
import Foreign.C.String
import Foreign.C.Types
+alignUp :: Int -> Int -> Int
+alignUp offset align
+ | align <= 1 = offset
+ | otherwise = ((offset + align - 1) `div` align) * align
+
data RawOperator
data RawLister
@@ -81,7 +86,7 @@ data FFIMetadata = FFIMetadata
{ ffiMode :: CUInt,
ffiCacheControl :: CString,
ffiContentDisposition :: CString,
- ffiContentLength :: CULong,
+ ffiContentLength :: Word64,
ffiContentMD5 :: CString,
ffiContentType :: CString,
ffiETag :: CString,
@@ -89,46 +94,71 @@ data FFIMetadata = FFIMetadata
}
deriving (Show)
+ffiMetadataModeOffset :: Int
+ffiMetadataModeOffset = 0
+
+ffiMetadataCacheControlOffset :: Int
+ffiMetadataCacheControlOffset =
+ alignUp (ffiMetadataModeOffset + sizeOf (undefined :: CUInt)) (alignment
(undefined :: CString))
+
+ffiMetadataContentDispositionOffset :: Int
+ffiMetadataContentDispositionOffset =
+ alignUp (ffiMetadataCacheControlOffset + sizeOf (undefined :: CString))
(alignment (undefined :: CString))
+
+ffiMetadataContentLengthOffset :: Int
+ffiMetadataContentLengthOffset =
+ alignUp (ffiMetadataContentDispositionOffset + sizeOf (undefined ::
CString)) (alignment (undefined :: Word64))
+
+ffiMetadataContentMD5Offset :: Int
+ffiMetadataContentMD5Offset =
+ alignUp (ffiMetadataContentLengthOffset + sizeOf (undefined :: Word64))
(alignment (undefined :: CString))
+
+ffiMetadataContentTypeOffset :: Int
+ffiMetadataContentTypeOffset =
+ alignUp (ffiMetadataContentMD5Offset + sizeOf (undefined :: CString))
(alignment (undefined :: CString))
+
+ffiMetadataETagOffset :: Int
+ffiMetadataETagOffset =
+ alignUp (ffiMetadataContentTypeOffset + sizeOf (undefined :: CString))
(alignment (undefined :: CString))
+
+ffiMetadataLastModifiedOffset :: Int
+ffiMetadataLastModifiedOffset =
+ alignUp (ffiMetadataETagOffset + sizeOf (undefined :: CString)) (alignment
(undefined :: CString))
+
+ffiMetadataAlignment :: Int
+ffiMetadataAlignment =
+ maximum
+ [ alignment (undefined :: CUInt),
+ alignment (undefined :: CString),
+ alignment (undefined :: Word64)
+ ]
+
+ffiMetadataSize :: Int
+ffiMetadataSize =
+ alignUp (ffiMetadataLastModifiedOffset + sizeOf (undefined :: CString))
ffiMetadataAlignment
+
instance Storable FFIMetadata where
- sizeOf _ = sizeOf (undefined :: CSize) + sizeOf (undefined :: CString) * 6 +
sizeOf (undefined :: CULong)
- alignment _ = alignment (undefined :: CSize)
+ sizeOf _ = ffiMetadataSize
+ alignment _ = ffiMetadataAlignment
peek ptr = do
- mode <- peekByteOff ptr modeOffset
- cacheControl <- peekByteOff ptr cacheControlOffset
- contentDisposition <- peekByteOff ptr contentDispositionOffset
- contentLength <- peekByteOff ptr contentLengthOffset
- contentMD5 <- peekByteOff ptr contentMD5Offset
- contentType <- peekByteOff ptr contentTypeOffset
- eTag <- peekByteOff ptr eTagOffset
- lastModified <- peekByteOff ptr lastModifiedOffset
+ mode <- peekByteOff ptr ffiMetadataModeOffset
+ cacheControl <- peekByteOff ptr ffiMetadataCacheControlOffset
+ contentDisposition <- peekByteOff ptr ffiMetadataContentDispositionOffset
+ contentLength <- peekByteOff ptr ffiMetadataContentLengthOffset
+ contentMD5 <- peekByteOff ptr ffiMetadataContentMD5Offset
+ contentType <- peekByteOff ptr ffiMetadataContentTypeOffset
+ eTag <- peekByteOff ptr ffiMetadataETagOffset
+ lastModified <- peekByteOff ptr ffiMetadataLastModifiedOffset
return $ FFIMetadata mode cacheControl contentDisposition contentLength
contentMD5 contentType eTag lastModified
- where
- modeOffset = 0
- cacheControlOffset = modeOffset + sizeOf (undefined :: CSize)
- contentDispositionOffset = cacheControlOffset + sizeOf (undefined ::
CString)
- contentLengthOffset = contentDispositionOffset + sizeOf (undefined ::
CString)
- contentMD5Offset = contentLengthOffset + sizeOf (undefined :: CULong)
- contentTypeOffset = contentMD5Offset + sizeOf (undefined :: CString)
- eTagOffset = contentTypeOffset + sizeOf (undefined :: CString)
- lastModifiedOffset = eTagOffset + sizeOf (undefined :: CString)
poke ptr (FFIMetadata mode cacheControl contentDisposition contentLength
contentMD5 contentType eTag lastModified) = do
- pokeByteOff ptr modeOffset mode
- pokeByteOff ptr cacheControlOffset cacheControl
- pokeByteOff ptr contentDispositionOffset contentDisposition
- pokeByteOff ptr contentLengthOffset contentLength
- pokeByteOff ptr contentMD5Offset contentMD5
- pokeByteOff ptr contentTypeOffset contentType
- pokeByteOff ptr eTagOffset eTag
- pokeByteOff ptr lastModifiedOffset lastModified
- where
- modeOffset = 0
- cacheControlOffset = modeOffset + sizeOf (undefined :: CSize)
- contentDispositionOffset = cacheControlOffset + sizeOf (undefined ::
CString)
- contentLengthOffset = contentDispositionOffset + sizeOf (undefined ::
CString)
- contentMD5Offset = contentLengthOffset + sizeOf (undefined :: CULong)
- contentTypeOffset = contentMD5Offset + sizeOf (undefined :: CString)
- eTagOffset = contentTypeOffset + sizeOf (undefined :: CString)
- lastModifiedOffset = eTagOffset + sizeOf (undefined :: CString)
+ pokeByteOff ptr ffiMetadataModeOffset mode
+ pokeByteOff ptr ffiMetadataCacheControlOffset cacheControl
+ pokeByteOff ptr ffiMetadataContentDispositionOffset contentDisposition
+ pokeByteOff ptr ffiMetadataContentLengthOffset contentLength
+ pokeByteOff ptr ffiMetadataContentMD5Offset contentMD5
+ pokeByteOff ptr ffiMetadataContentTypeOffset contentType
+ pokeByteOff ptr ffiMetadataETagOffset eTag
+ pokeByteOff ptr ffiMetadataLastModifiedOffset lastModified
foreign import ccall "via_map_ffi"
c_via_map_ffi ::
diff --git a/bindings/haskell/opendal.cabal b/bindings/haskell/opendal.cabal
index 1014ca6ff6..97bb63e4cf 100644
--- a/bindings/haskell/opendal.cabal
+++ b/bindings/haskell/opendal.cabal
@@ -87,3 +87,16 @@ test-suite opendal-test
opendal,
tasty >= 1.5 && < 1.6,
tasty-hunit >= 0.10.1 && < 0.11,
+
+test-suite metadata-test
+ import: base
+ type: exitcode-stdio-1.0
+ main-is: MetadataTest.hs
+ hs-source-dirs: test
+ -- The HTTP fixture runs while the test thread is blocked in Rust.
+ ghc-options: -threaded
+ build-depends:
+ network >= 3.2 && < 3.3,
+ opendal,
+ tasty >= 1.5 && < 1.6,
+ tasty-hunit >= 0.10.1 && < 0.11,
diff --git a/bindings/haskell/src/lib.rs b/bindings/haskell/src/lib.rs
index f1ece91a7e..66abc62a38 100644
--- a/bindings/haskell/src/lib.rs
+++ b/bindings/haskell/src/lib.rs
@@ -173,7 +173,7 @@ pub unsafe extern "C" fn free_operator(operator: *mut
od::blocking::Operator) {
/// `error_message` must be released with `free_string`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blocking_read(
- op: *mut od::blocking::Operator,
+ op: *const od::blocking::Operator,
path: *const c_char,
result: *mut FFIResult<ByteSlice>,
) {
@@ -182,7 +182,7 @@ pub unsafe extern "C" fn blocking_read(
*result = FFIResult::err("Operator is null");
return;
} else {
- &mut *op
+ &*op
};
let path_str = match c_str_arg(path) {
@@ -227,7 +227,7 @@ unsafe fn copy_bytes<'a>(bytes: *const c_char, len: usize)
-> Option<&'a [u8]> {
/// * `result` is a valid pointer with space for one `FFIResult`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blocking_write(
- op: *mut od::blocking::Operator,
+ op: *const od::blocking::Operator,
path: *const c_char,
bytes: *const c_char,
len: usize,
@@ -238,7 +238,7 @@ pub unsafe extern "C" fn blocking_write(
*result = FFIResult::err("Operator is null");
return;
} else {
- &mut *op
+ &*op
};
let path_str = match c_str_arg(path) {
@@ -275,7 +275,7 @@ pub unsafe extern "C" fn blocking_write(
/// `error_message` must be released with `free_string`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blocking_is_exist(
- op: *mut od::blocking::Operator,
+ op: *const od::blocking::Operator,
path: *const c_char,
result: *mut FFIResult<bool>,
) {
@@ -284,7 +284,7 @@ pub unsafe extern "C" fn blocking_is_exist(
*result = FFIResult::err("Operator is null");
return;
} else {
- &mut *op
+ &*op
};
let path_str = match c_str_arg(path) {
@@ -311,7 +311,7 @@ pub unsafe extern "C" fn blocking_is_exist(
/// * `result` is a valid pointer with space for one `FFIResult`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blocking_create_dir(
- op: *mut od::blocking::Operator,
+ op: *const od::blocking::Operator,
path: *const c_char,
result: *mut FFIResult<()>,
) {
@@ -320,7 +320,7 @@ pub unsafe extern "C" fn blocking_create_dir(
*result = FFIResult::err("Operator is null");
return;
} else {
- &mut *op
+ &*op
};
let path_str = match c_str_arg(path) {
@@ -347,7 +347,7 @@ pub unsafe extern "C" fn blocking_create_dir(
/// * `result` is a valid pointer with space for one `FFIResult`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blocking_copy(
- op: *mut od::blocking::Operator,
+ op: *const od::blocking::Operator,
path_from: *const c_char,
path_to: *const c_char,
result: *mut FFIResult<()>,
@@ -357,7 +357,7 @@ pub unsafe extern "C" fn blocking_copy(
*result = FFIResult::err("Operator is null");
return;
} else {
- &mut *op
+ &*op
};
let path_from_str = match c_str_arg(path_from) {
@@ -392,7 +392,7 @@ pub unsafe extern "C" fn blocking_copy(
/// * `result` is a valid pointer with space for one `FFIResult`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blocking_rename(
- op: *mut od::blocking::Operator,
+ op: *const od::blocking::Operator,
path_from: *const c_char,
path_to: *const c_char,
result: *mut FFIResult<()>,
@@ -402,7 +402,7 @@ pub unsafe extern "C" fn blocking_rename(
*result = FFIResult::err("Operator is null");
return;
} else {
- &mut *op
+ &*op
};
let path_from_str = match c_str_arg(path_from) {
@@ -437,7 +437,7 @@ pub unsafe extern "C" fn blocking_rename(
/// * `result` is a valid pointer with space for one `FFIResult`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blocking_delete(
- op: *mut od::blocking::Operator,
+ op: *const od::blocking::Operator,
path: *const c_char,
result: *mut FFIResult<()>,
) {
@@ -446,7 +446,7 @@ pub unsafe extern "C" fn blocking_delete(
*result = FFIResult::err("Operator is null");
return;
} else {
- &mut *op
+ &*op
};
let path_str = match c_str_arg(path) {
@@ -475,7 +475,7 @@ pub unsafe extern "C" fn blocking_delete(
/// `error_message` must be released with `free_string`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blocking_stat(
- op: *mut od::blocking::Operator,
+ op: *const od::blocking::Operator,
path: *const c_char,
result: *mut FFIResult<Metadata>,
) {
@@ -484,7 +484,7 @@ pub unsafe extern "C" fn blocking_stat(
*result = FFIResult::err("Operator is null");
return;
} else {
- &mut *op
+ &*op
};
let path_str = match c_str_arg(path) {
@@ -513,7 +513,7 @@ pub unsafe extern "C" fn blocking_stat(
/// failure `error_message` must be released with `free_string`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blocking_list(
- op: *mut od::blocking::Operator,
+ op: *const od::blocking::Operator,
path: *const c_char,
result: *mut FFIResult<blocking::Lister>,
) {
@@ -522,7 +522,7 @@ pub unsafe extern "C" fn blocking_list(
*result = FFIResult::err("Operator is null");
return;
} else {
- &mut *op
+ &*op
};
let path_str = match c_str_arg(path) {
@@ -551,7 +551,7 @@ pub unsafe extern "C" fn blocking_list(
/// failure `error_message` must be released with `free_string`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blocking_scan(
- op: *mut od::blocking::Operator,
+ op: *const od::blocking::Operator,
path: *const c_char,
result: *mut FFIResult<blocking::Lister>,
) {
@@ -560,7 +560,7 @@ pub unsafe extern "C" fn blocking_scan(
*result = FFIResult::err("Operator is null");
return;
} else {
- &mut *op
+ &*op
};
let path_str = match c_str_arg(path) {
@@ -639,7 +639,7 @@ pub unsafe extern "C" fn free_lister(lister: *mut
blocking::Lister) {
/// `error_message` must be released with `free_string`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn operator_info(
- op: *mut od::blocking::Operator,
+ op: *const od::blocking::Operator,
result: *mut FFIResult<c_char>,
) {
unsafe {
@@ -647,7 +647,7 @@ pub unsafe extern "C" fn operator_info(
*result = FFIResult::err("Operator is null");
return;
} else {
- &mut *op
+ &*op
};
let info = op.info();
@@ -666,7 +666,7 @@ pub unsafe extern "C" fn operator_info(
/// * `result` is a valid pointer with space for one `FFIResult`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blocking_remove_all(
- op: *mut od::blocking::Operator,
+ op: *const od::blocking::Operator,
path: *const c_char,
result: *mut FFIResult<()>,
) {
@@ -675,7 +675,7 @@ pub unsafe extern "C" fn blocking_remove_all(
*result = FFIResult::err("Operator is null");
return;
} else {
- &mut *op
+ &*op
};
let path_str = match c_str_arg(path) {
@@ -715,7 +715,7 @@ pub unsafe extern "C" fn blocking_remove_all(
/// failure `error_message` must be released with `free_string`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blocking_writer(
- op: *mut od::blocking::Operator,
+ op: *const od::blocking::Operator,
path: *const c_char,
result: *mut FFIResult<blocking::Writer>,
) {
@@ -724,7 +724,7 @@ pub unsafe extern "C" fn blocking_writer(
*result = FFIResult::err("Operator is null");
return;
} else {
- &mut *op
+ &*op
};
let path_str = match c_str_arg(path) {
@@ -755,7 +755,7 @@ pub unsafe extern "C" fn blocking_writer(
/// failure `error_message` must be released with `free_string`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blocking_writer_append(
- op: *mut od::blocking::Operator,
+ op: *const od::blocking::Operator,
path: *const c_char,
result: *mut FFIResult<blocking::Writer>,
) {
@@ -764,7 +764,7 @@ pub unsafe extern "C" fn blocking_writer_append(
*result = FFIResult::err("Operator is null");
return;
} else {
- &mut *op
+ &*op
};
let path_str = match c_str_arg(path) {
@@ -1031,7 +1031,7 @@ mod tests {
unsafe {
let path = c"file";
let mut read_result = FFIResult::<ByteSlice>::default();
- blocking_read(ptr::null_mut(), path.as_ptr(), &mut read_result);
+ blocking_read(ptr::null(), path.as_ptr(), &mut read_result);
assert_eq!(read_result.code, result::FFIErrorCode::FFIError);
free_string(read_result.error_message);
}
@@ -1161,4 +1161,70 @@ mod tests {
free_operator(op);
}
}
+
+ #[test]
+ fn concurrent_operator_ffi_calls_share_const_pointer() {
+ struct SharedOp(*const od::blocking::Operator);
+ // SAFETY: `od::blocking::Operator` is `Send + Sync`, and all FFI
+ // entrypoints take `*const od::blocking::Operator` and only borrow
`&*op`.
+ unsafe impl Sync for SharedOp {}
+
+ unsafe {
+ let op = memory_operator();
+ let shared = SharedOp(op.cast_const());
+
+ std::thread::scope(|scope| {
+ for worker in 0..8usize {
+ let shared = &shared;
+ scope.spawn(move || {
+ let path =
+
std::ffi::CString::new(format!("concurrent/worker-{worker}")).unwrap();
+ let payload = format!("payload-{worker}");
+
+ let mut write_result = FFIResult::<()>::default();
+ blocking_write(
+ shared.0,
+ path.as_ptr(),
+ payload.as_ptr() as *const c_char,
+ payload.len(),
+ &mut write_result,
+ );
+ assert_eq!(write_result.code,
result::FFIErrorCode::Ok);
+
+ let mut exists_result = FFIResult::<bool>::default();
+ blocking_is_exist(shared.0, path.as_ptr(), &mut
exists_result);
+ assert_eq!(exists_result.code,
result::FFIErrorCode::Ok);
+ assert!(*exists_result.data_ptr);
+ free_bool(exists_result.data_ptr);
+
+ let mut stat_result = FFIResult::<Metadata>::default();
+ blocking_stat(shared.0, path.as_ptr(), &mut
stat_result);
+ assert_eq!(stat_result.code, result::FFIErrorCode::Ok);
+ assert_eq!((*stat_result.data_ptr).content_length,
payload.len() as u64);
+ free_metadata(stat_result.data_ptr);
+
+ let mut read_result =
FFIResult::<ByteSlice>::default();
+ blocking_read(shared.0, path.as_ptr(), &mut
read_result);
+ assert_eq!(read_result.code, result::FFIErrorCode::Ok);
+ let slice = &*read_result.data_ptr;
+ let view = std::slice::from_raw_parts(slice.data as
*const u8, slice.len);
+ assert_eq!(view, payload.as_bytes());
+ free_byteslice(read_result.data_ptr);
+
+ let mut info_result = FFIResult::<c_char>::default();
+ operator_info(shared.0, &mut info_result);
+ assert_eq!(info_result.code, result::FFIErrorCode::Ok);
+
assert_eq!(CStr::from_ptr(info_result.data_ptr).to_bytes(), b"memory");
+ free_string(info_result.data_ptr);
+
+ let mut delete_result = FFIResult::<()>::default();
+ blocking_delete(shared.0, path.as_ptr(), &mut
delete_result);
+ assert_eq!(delete_result.code,
result::FFIErrorCode::Ok);
+ });
+ }
+ });
+
+ free_operator(op);
+ }
+ }
}
diff --git a/bindings/haskell/src/types.rs b/bindings/haskell/src/types.rs
index 1fd5e6d976..ae760f6cbf 100644
--- a/bindings/haskell/src/types.rs
+++ b/bindings/haskell/src/types.rs
@@ -193,6 +193,73 @@ pub(crate) fn into_raw_c_string(s: &str) -> *mut c_char {
mod tests {
use super::*;
use std::ffi::CStr;
+ use std::ffi::c_uint;
+ use std::mem::align_of;
+ use std::mem::offset_of;
+ use std::mem::size_of;
+
+ const fn align_up(offset: usize, align: usize) -> usize {
+ if align <= 1 {
+ offset
+ } else {
+ offset.div_ceil(align) * align
+ }
+ }
+
+ #[test]
+ fn metadata_layout_matches_c_field_types() {
+ assert_eq!(size_of::<EntryMode>(), size_of::<c_uint>());
+ assert_eq!(align_of::<EntryMode>(), align_of::<c_uint>());
+
+ let mode_offset = 0;
+ let cache_control_offset =
+ align_up(mode_offset + size_of::<c_uint>(), align_of::<*mut
c_char>());
+ let content_disposition_offset = align_up(
+ cache_control_offset + size_of::<*mut c_char>(),
+ align_of::<*mut c_char>(),
+ );
+ let content_length_offset = align_up(
+ content_disposition_offset + size_of::<*mut c_char>(),
+ align_of::<u64>(),
+ );
+ let content_md5_offset = align_up(
+ content_length_offset + size_of::<u64>(),
+ align_of::<*mut c_char>(),
+ );
+ let content_type_offset = align_up(
+ content_md5_offset + size_of::<*mut c_char>(),
+ align_of::<*mut c_char>(),
+ );
+ let etag_offset = align_up(
+ content_type_offset + size_of::<*mut c_char>(),
+ align_of::<*mut c_char>(),
+ );
+ let last_modified_offset = align_up(
+ etag_offset + size_of::<*mut c_char>(),
+ align_of::<*mut c_char>(),
+ );
+ let expected_align = align_of::<c_uint>()
+ .max(align_of::<*mut c_char>())
+ .max(align_of::<u64>());
+ let expected_size = align_up(
+ last_modified_offset + size_of::<*mut c_char>(),
+ expected_align,
+ );
+
+ assert_eq!(offset_of!(Metadata, mode), mode_offset);
+ assert_eq!(offset_of!(Metadata, cache_control), cache_control_offset);
+ assert_eq!(
+ offset_of!(Metadata, content_disposition),
+ content_disposition_offset
+ );
+ assert_eq!(offset_of!(Metadata, content_length),
content_length_offset);
+ assert_eq!(offset_of!(Metadata, content_md5), content_md5_offset);
+ assert_eq!(offset_of!(Metadata, content_type), content_type_offset);
+ assert_eq!(offset_of!(Metadata, etag), etag_offset);
+ assert_eq!(offset_of!(Metadata, last_modified), last_modified_offset);
+ assert_eq!(align_of::<Metadata>(), expected_align);
+ assert_eq!(size_of::<Metadata>(), expected_size);
+ }
#[test]
fn byteslice_roundtrip_preserves_bytes() {
diff --git a/bindings/haskell/test/MetadataTest.hs
b/bindings/haskell/test/MetadataTest.hs
new file mode 100644
index 0000000000..0a6c625049
--- /dev/null
+++ b/bindings/haskell/test/MetadataTest.hs
@@ -0,0 +1,70 @@
+-- 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.
+
+module Main (main) where
+
+import Control.Concurrent (forkIO, killThread)
+import Control.Exception (bracket)
+import qualified Data.ByteString as BS
+import qualified Data.HashMap.Strict as HashMap
+import Network.Socket
+import Network.Socket.ByteString (recv, sendAll)
+import OpenDAL
+import Test.Tasty (defaultMain)
+import Test.Tasty.HUnit (Assertion, assertEqual, assertFailure, testCase)
+
+main :: IO ()
+main = defaultMain (testCase "stat preserves 64-bit metadata" testStatMetadata)
+
+testStatMetadata :: Assertion
+testStatMetadata = withSocketsDo $
+ bracket (socket AF_INET Stream defaultProtocol) close $ \listener -> do
+ bind listener (SockAddrInet 0 (tupleToHostAddress (127, 0, 0, 1)))
+ listen listener 1
+ SockAddrInet port _ <- getSocketName listener
+ bracket (forkIO (serveHead listener)) killThread $ \_ -> do
+ let endpoint = "http://127.0.0.1:" ++ show port
+ newOperator "http" {ocConfig = HashMap.singleton "endpoint" endpoint}
>>= \case
+ Left err -> assertFailure $ "Failed to create HTTP operator: " ++ show
err
+ Right op -> statOpRaw op "large-object" >>= \case
+ Left err -> assertFailure $ "HTTP stat failed: " ++ show err
+ Right metadata -> do
+ -- Above 4 GiB with nonzero low bits. C unsigned long is only 32
bits on Win64.
+ assertEqual "Content-Length" 4294967313 (mContentLength metadata)
+ assertEqual "ETag" (Just "\"large-object-etag\"") (mETag metadata)
+
+serveHead :: Socket -> Assertion
+serveHead listener = bracket (fst <$> accept listener) close $ \client -> do
+ request <- readHeaders client BS.empty
+ if "HEAD /large-object HTTP/1.1\r\n" `BS.isPrefixOf` request
+ then sendAll client $
+ BS.concat
+ [ "HTTP/1.1 200 OK\r\n",
+ "Content-Length: 4294967313\r\n",
+ "ETag: \"large-object-etag\"\r\n",
+ "Connection: close\r\n\r\n"
+ ]
+ else sendAll client "HTTP/1.1 400 Bad Request\r\nContent-Length:
0\r\nConnection: close\r\n\r\n"
+ where
+ readHeaders client received
+ | "\r\n\r\n" `BS.isInfixOf` received = return received
+ | BS.length received >= 4096 = fail "HTTP request headers exceed 4 KiB"
+ | otherwise = do
+ chunk <- recv client (4096 - BS.length received)
+ if BS.null chunk
+ then fail "HTTP client closed before sending headers"
+ else readHeaders client (received <> chunk)
diff --git a/bindings/haskell/test/ResourceTest.hs
b/bindings/haskell/test/ResourceTest.hs
index e4dc84b414..270493f7ea 100644
--- a/bindings/haskell/test/ResourceTest.hs
+++ b/bindings/haskell/test/ResourceTest.hs
@@ -21,8 +21,11 @@
-- repetition, especially after forcing the garbage collector.
module ResourceTest (resourceTests) where
+import Control.Exception (bracket)
import Control.Monad.IO.Class (MonadIO, liftIO)
import qualified Data.ByteString as BS
+import qualified Data.HashMap.Strict as HashMap
+import GHC.IO.Encoding (getForeignEncoding, latin1, setForeignEncoding)
import OpenDAL
import System.Mem (performGC)
import Test.Tasty
@@ -38,7 +41,8 @@ resourceTests =
testCase "testRepeatedStatOps" testRepeatedStatOps,
testCase "testListerExhaustion" testListerExhaustion,
testCase "testForeignPtrFinalizers" testForeignPtrFinalizers,
- testCase "testRepeatedWriterClose" testRepeatedWriterClose
+ testCase "testRepeatedWriterClose" testRepeatedWriterClose,
+ testCase "testUtf8UnderLatin1Encoding" testUtf8UnderLatin1Encoding
]
testRepeatedReadOps :: Assertion
@@ -145,6 +149,45 @@ testRepeatedWriterClose = do
([1 .. 50] :: [Int])
performGC
+testUtf8UnderLatin1Encoding :: Assertion
+testUtf8UnderLatin1Encoding =
+ bracket getForeignEncoding setForeignEncoding $ \_ -> do
+ setForeignEncoding latin1
+ Right op <-
+ newOperator
+ OperatorConfig
+ { ocScheme = "memory",
+ ocConfig = HashMap.fromList [("root", "/根目录-café/")],
+ ocLogAction = Nothing
+ }
+ let dirPath = "目录-café/"
+ filePath = "目录-café/日本語-file.txt"
+ missingPath = "不存在/café.txt"
+ createDirOpRaw op dirPath ?= Right ()
+ writeOpRaw op filePath "hello-utf8" ?= Right ()
+ isExistOpRaw op filePath ?= Right True
+ readOpRaw op filePath ?= Right "hello-utf8"
+ statOpRaw op filePath >>= \case
+ Right meta -> mContentLength meta @?= 10
+ Left err -> assertFailure $ "stat failed: " ++ show err
+ Right lister <- listOpRaw op dirPath
+ items <- collectListerItems lister
+ assertBool ("expected UTF-8 path in listing, got: " ++ show items)
(filePath `elem` items)
+ readOpRaw op missingPath >>= \case
+ Left err -> errorCode err @?= NotFound
+ Right _ -> assertFailure "Expected NotFound for missing UTF-8 path"
+ deleteOpRaw op filePath ?= Right ()
+ isExistOpRaw op filePath ?= Right False
+ where
+ collectListerItems lister = go []
+ where
+ go acc = do
+ r <- nextLister lister
+ case r of
+ Right (Just p) -> go (p : acc)
+ Right Nothing -> return acc
+ Left err -> assertFailure $ "lister error: " ++ show err
+
-- helper function
(?=) :: (MonadIO m, Eq a, Show a) => m a -> a -> m ()