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 c515ef3a29 feat(bindings/dotnet): expose map-valued service config
options (#9327)
c515ef3a29 is described below
commit c515ef3a29da36ee3e2518d95cf2af13765a9328
Author: Chitral Verma <[email protected]>
AuthorDate: Sat Nov 28 21:35:51 2026 +0530
feat(bindings/dotnet): expose map-valued service config options (#9327)
* feat(bindings/dotnet): expose map-valued service config options
The .NET generator skipped HashMap config fields, so S3ServiceConfig and
HdfsNativeServiceConfig could not set assume_role_session_tags or
options. Core reads a map-valued option from a JSON object string, so
generate IReadOnlyDictionary<string, string>? init properties and emit
them from ToOptions() through Utilities.ToOptionJson, which writes a JSON
object with Utf8JsonWriter in ordinal key order.
Signed-off-by: Chitral Verma <[email protected]>
* test(bindings/dotnet): round-trip map options through ToOptions
Signed-off-by: Chitral Verma <[email protected]>
---------
Signed-off-by: Chitral Verma <[email protected]>
---
.../dotnet/OpenDAL.Tests/ServiceConfigMapTest.cs | 203 +++++++++++++++++++++
.../ServiceConfig/HdfsNativeServiceConfig.cs | 8 +
.../OpenDAL/ServiceConfig/S3ServiceConfig.cs | 8 +
bindings/dotnet/OpenDAL/Utilities.cs | 24 +++
dev/src/generate/dotnet.rs | 19 +-
5 files changed, 252 insertions(+), 10 deletions(-)
diff --git a/bindings/dotnet/OpenDAL.Tests/ServiceConfigMapTest.cs
b/bindings/dotnet/OpenDAL.Tests/ServiceConfigMapTest.cs
new file mode 100644
index 0000000000..f2dbc3e303
--- /dev/null
+++ b/bindings/dotnet/OpenDAL.Tests/ServiceConfigMapTest.cs
@@ -0,0 +1,203 @@
+/*
+ * 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.
+ */
+
+using System.Text.Json;
+using OpenDAL.ServiceConfig;
+
+namespace OpenDAL.Tests;
+
+public class ServiceConfigMapTest
+{
+ private static Dictionary<string, string> SpecialCharacters() => new()
+ {
+ ["q\""] = "b\\",
+ ["nl"] = "a\nb",
+ ["ctl"] = "\u0001",
+ ["ü"] = "ß",
+ ["url"] = "hdfs://ns",
+ };
+
+ [Fact]
+ public void S3SessionTags_ToOptions_EmitsOneJsonObject()
+ {
+ var config = new S3ServiceConfig
+ {
+ AssumeRoleSessionTags = new Dictionary<string, string> { ["Team"]
= "x" },
+ };
+
+ var options = config.ToOptions();
+
+ Assert.Equal("{\"Team\":\"x\"}", options["assume_role_session_tags"]);
+ Assert.False(options.ContainsKey("Team"));
+ }
+
+ [Fact]
+ public void HdfsNativeOptions_ToOptions_EmitsOneJsonObject()
+ {
+ var config = new HdfsNativeServiceConfig
+ {
+ Options = new Dictionary<string, string> { ["dfs.nameservices"] =
"ns" },
+ };
+
+ var options = config.ToOptions();
+
+ Assert.Equal("{\"dfs.nameservices\":\"ns\"}", options["options"]);
+ }
+
+ [Fact]
+ public void MapOption_SortsKeysOrdinalAndKeepsCase()
+ {
+ var tags = new Dictionary<string, string>
+ {
+ ["b"] = "2",
+ ["a"] = "1",
+ ["Fs"] = "x",
+ };
+
+ var json = Utilities.ToOptionJson(tags);
+
+ Assert.Equal("{\"Fs\":\"x\",\"a\":\"1\",\"b\":\"2\"}", json);
+ }
+
+ private static Dictionary<string, string?> DecodeJsonObject(string json)
+ {
+ using var document = JsonDocument.Parse(json);
+ return document.RootElement
+ .EnumerateObject()
+ .ToDictionary(property => property.Name, property =>
property.Value.GetString());
+ }
+
+ [Fact]
+ public void S3SessionTags_ToOptions_RoundTripKeepsKeyCase()
+ {
+ var config = new S3ServiceConfig
+ {
+ Region = "us-east-1",
+ AssumeRoleSessionTags = new Dictionary<string, string>
+ {
+ ["Region"] = "eu-west-1",
+ ["CostCenter"] = "Data-Platform",
+ },
+ };
+
+ var options = config.ToOptions();
+
+ Assert.Equal(new Dictionary<string, string?>
+ {
+ ["Region"] = "eu-west-1",
+ ["CostCenter"] = "Data-Platform",
+ }, DecodeJsonObject(options["assume_role_session_tags"]));
+ Assert.Equal("us-east-1", options["region"]);
+ Assert.False(options.ContainsKey("Region"));
+ }
+
+ [Fact]
+ public void HdfsNativeOptions_ToOptions_RoundTripKeepsKeyCase()
+ {
+ var config = new HdfsNativeServiceConfig
+ {
+ Options = new Dictionary<string, string>
+ {
+ ["fs.defaultFS"] = "hdfs://ns",
+ ["dfs.ha.namenodes.ns"] = "nn1,nn2",
+ },
+ };
+
+ var options = config.ToOptions();
+
+ Assert.Equal(new Dictionary<string, string?>
+ {
+ ["fs.defaultFS"] = "hdfs://ns",
+ ["dfs.ha.namenodes.ns"] = "nn1,nn2",
+ }, DecodeJsonObject(options["options"]));
+ Assert.False(options.ContainsKey("fs.defaultFS"));
+ }
+
+ [Fact]
+ public void MapOption_SpecialCharacters_RoundTrip()
+ {
+ var json = Utilities.ToOptionJson(SpecialCharacters());
+
+ Assert.Equal(new Dictionary<string, string?>
+ {
+ ["q\""] = "b\\",
+ ["nl"] = "a\nb",
+ ["ctl"] = "\u0001",
+ ["ü"] = "ß",
+ ["url"] = "hdfs://ns",
+ }, DecodeJsonObject(json));
+ }
+
+ [Fact]
+ public void MapOption_Empty_EmitsEmptyObject()
+ {
+ var config = new S3ServiceConfig
+ {
+ AssumeRoleSessionTags = new Dictionary<string, string>(),
+ };
+
+ var options = config.ToOptions();
+
+ Assert.Equal("{}", options["assume_role_session_tags"]);
+ }
+
+ [Fact]
+ public void MapOption_Null_IsOmitted()
+ {
+ var config = new S3ServiceConfig
+ {
+ Bucket = "b",
+ };
+
+ var options = config.ToOptions();
+
+ Assert.False(options.ContainsKey("assume_role_session_tags"));
+ }
+
+ [Fact]
+ public void Constructor_S3SessionTags_ConstructsOperator()
+ {
+ var config = new S3ServiceConfig
+ {
+ Bucket = "b",
+ Region = "us-east-1",
+ AssumeRoleSessionTags = SpecialCharacters(),
+ };
+
+ using var op = new Operator(config);
+
+ Assert.NotEqual(IntPtr.Zero, op.DangerousGetHandle());
+ }
+
+ [Fact]
+ public void Constructor_MapOptionNullValue_ThrowsConfigInvalid()
+ {
+ var config = new S3ServiceConfig
+ {
+ Bucket = "b",
+ Region = "us-east-1",
+ AssumeRoleSessionTags = new Dictionary<string, string> { ["Team"]
= null! },
+ };
+
+ var ex = Assert.Throws<OpenDALException>(() => new Operator(config));
+
+ Assert.Equal(ErrorCode.ConfigInvalid, ex.Code);
+ Assert.Contains("assume_role_session_tags", ex.Message);
+ }
+}
diff --git a/bindings/dotnet/OpenDAL/ServiceConfig/HdfsNativeServiceConfig.cs
b/bindings/dotnet/OpenDAL/ServiceConfig/HdfsNativeServiceConfig.cs
index 34d5bccd3a..6074a1094c 100644
--- a/bindings/dotnet/OpenDAL/ServiceConfig/HdfsNativeServiceConfig.cs
+++ b/bindings/dotnet/OpenDAL/ServiceConfig/HdfsNativeServiceConfig.cs
@@ -38,6 +38,10 @@ namespace OpenDAL.ServiceConfig
/// </summary>
public string? NameNode { get; init; }
/// <summary>
+ /// other options for hdfs client
+ /// </summary>
+ public IReadOnlyDictionary<string, string>? Options { get; init; }
+ /// <summary>
/// work dir of this backend
/// </summary>
public string? Root { get; init; }
@@ -57,6 +61,10 @@ namespace OpenDAL.ServiceConfig
{
map["name_node"] = Utilities.ToOptionString(NameNode);
}
+ if (Options is not null)
+ {
+ map["options"] = Utilities.ToOptionJson(Options);
+ }
if (Root is not null)
{
map["root"] = Utilities.ToOptionString(Root);
diff --git a/bindings/dotnet/OpenDAL/ServiceConfig/S3ServiceConfig.cs
b/bindings/dotnet/OpenDAL/ServiceConfig/S3ServiceConfig.cs
index 278aaeb7e9..b1b14f5de8 100644
--- a/bindings/dotnet/OpenDAL/ServiceConfig/S3ServiceConfig.cs
+++ b/bindings/dotnet/OpenDAL/ServiceConfig/S3ServiceConfig.cs
@@ -42,6 +42,10 @@ namespace OpenDAL.ServiceConfig
/// </summary>
public int? AssumeRoleDurationSeconds { get; init; }
/// <summary>
+ /// assume_role_session_tags for this backend.
+ /// </summary>
+ public IReadOnlyDictionary<string, string>? AssumeRoleSessionTags {
get; init; }
+ /// <summary>
/// Deprecated: S3 delete batch capability is enabled by default.
/// </summary>
[System.Obsolete("S3 delete batch capability is enabled by default.
Use CapabilityOverrideLayer to override delete_max_size for specific
endpoints.")]
@@ -215,6 +219,10 @@ namespace OpenDAL.ServiceConfig
{
map["assume_role_duration_seconds"] =
Utilities.ToOptionString(AssumeRoleDurationSeconds);
}
+ if (AssumeRoleSessionTags is not null)
+ {
+ map["assume_role_session_tags"] =
Utilities.ToOptionJson(AssumeRoleSessionTags);
+ }
#pragma warning disable CS0618
if (BatchMaxOperations is not null)
{
diff --git a/bindings/dotnet/OpenDAL/Utilities.cs
b/bindings/dotnet/OpenDAL/Utilities.cs
index a3c7058a4d..71642ef03d 100644
--- a/bindings/dotnet/OpenDAL/Utilities.cs
+++ b/bindings/dotnet/OpenDAL/Utilities.cs
@@ -17,8 +17,11 @@
* under the License.
*/
+using System.Buffers;
using System.Runtime.InteropServices;
using System.Globalization;
+using System.Text;
+using System.Text.Json;
namespace OpenDAL;
@@ -144,6 +147,27 @@ public static class Utilities
};
}
+ /// <summary>
+ /// Encodes a map-valued service option as the JSON object string that
OpenDAL core parses.
+ /// </summary>
+ /// <param name="value">Map to encode. Keys keep their case.</param>
+ /// <returns>A JSON object with keys in ordinal order, or <c>{}</c> for
an empty map. A null value is written as JSON <c>null</c>, which core rejects
with <see cref="ErrorCode.ConfigInvalid"/>.</returns>
+ internal static string ToOptionJson(IReadOnlyDictionary<string, string>
value)
+ {
+ var buffer = new ArrayBufferWriter<byte>();
+ using (var writer = new Utf8JsonWriter(buffer))
+ {
+ writer.WriteStartObject();
+ foreach (var pair in value.OrderBy(pair => pair.Key,
StringComparer.Ordinal))
+ {
+ writer.WriteString(pair.Key, pair.Value);
+ }
+ writer.WriteEndObject();
+ }
+
+ return Encoding.UTF8.GetString(buffer.WrittenSpan);
+ }
+
/// <summary>
/// Converts a positive <see cref="TimeSpan"/> into nanoseconds.
/// </summary>
diff --git a/dev/src/generate/dotnet.rs b/dev/src/generate/dotnet.rs
index 225c6bb003..0b3702b6ca 100644
--- a/dev/src/generate/dotnet.rs
+++ b/dev/src/generate/dotnet.rs
@@ -938,11 +938,8 @@ fn generate_service_configs(workspace_dir: &Path,
services: Services) -> Result<
let fields = srvs[name]
.config
.iter()
- // A HashMap config has no string encoding in the options map, so
- // it cannot be expressed through IServiceConfig.ToOptions.
- .filter(|config| config.value != ConfigType::HashMap)
.map(config_field)
- .collect::<Result<Vec<ConfigField>>>()?;
+ .collect::<Vec<ConfigField>>();
let rendered = tmpl.render(context! {
service => name,
@@ -959,7 +956,7 @@ fn generate_service_configs(workspace_dir: &Path, services:
Services) -> Result<
Ok(())
}
-fn config_field(config: &Config) -> Result<ConfigField> {
+fn config_field(config: &Config) -> ConfigField {
let pascal = heck::AsUpperCamelCase(&config.name).to_string();
// Strings and durations stay nullable even when core requires them, so a
@@ -988,9 +985,11 @@ fn config_field(config: &Config) -> Result<ConfigField> {
true,
format!("string.Join(\",\", {pascal})"),
),
- ConfigType::HashMap => bail!(
- "config `{}` is a HashMap and should have been filtered out",
- config.name
+ // Core reads a map-valued option from a JSON object string.
+ ConfigType::HashMap => (
+ "IReadOnlyDictionary<string, string>?",
+ true,
+ format!("Utilities.ToOptionJson({pascal})"),
),
};
@@ -999,7 +998,7 @@ fn config_field(config: &Config) -> Result<ConfigField> {
None => String::new(),
};
- Ok(ConfigField {
+ ConfigField {
pascal,
key: config.name.clone(),
cs_type: cs_type.to_string(),
@@ -1007,7 +1006,7 @@ fn config_field(config: &Config) -> Result<ConfigField> {
value_expr,
deprecated,
doc: xml_escape(&single_line(&config.comments)),
- })
+ }
}
fn to_option_string(pascal: &str) -> String {