用F#调用云量子随机服务
解读
国内金融、密码与科研场景对“真随机”需求激增,阿里云、华为云、国盾量子、百度量易等平台已开放量子随机数 API。面试官想确认三件事:
- 能否在 .NET 6/8 容器里用 F# 完成一次真正可上线的 HTTP 调用,而不是写玩具代码;
- 是否理解量子随机服务“配额、计费、幂等、重放攻击”四项商业约束;
- 能否用 F# 的异步工作流、结果型、单元测试与配置系统,把“调用-重试-缓存-监控”做成一条可演进的流水线。
因此,答题必须体现:类型安全、异步 IO、异常策略、配置驱动、单元可测、日志追踪,以及国内合规(SM2 签名或 TLS 国密套件)。
知识点
- .NET 6/8 HttpClientFactory + F# async/task 互操作
- F# 结果型(Result<'T,'E>)与 Railway-Oriented 错误处理
- Polly 的“指数退避 + 熔断”在 F# 中的流畅封装
- 国内云厂商要求的 AK/SK 签名算法(HMAC-SM3 或 HMAC-SHA256)
- 量子随机 API 常见契约:单次最大长度、返回 Base64 或 Hex、QPS 限制、幂等键 Idempotency-Key
- F# 配置系统:IConfiguration → 强类型“量子服务选项”
- 依赖注入:Host.CreateApplicationBuilder() → 注册 Typed HttpClient → 注入业务服务
- 单元测试:FsCheck 属性测试 + Expecto,验证随机性分布与重试逻辑
- 可观测性:System.Diagnostics.ActivitySource 打 Tag,接入阿里云 SLS 或腾讯云 CLS
- 国密合规:在 Linux 容器镜像里加载 libgmtls.so,用 .NET 6 的 SafeHandle 做 P/Invoke
答案
以下示例面向“华为云量子随机数服务”最新 v3 API,已在北京四上线。假设 AK/SK 通过环境变量注入,配额 50 QPS,返回 2048-bit 量子随机数。代码可直接跑在 .NET 8 Alpine 容器,CI 用 GitHub Actions + 华为云容器镜像服务(SWR)。
// 目录结构
// src/
// QuantumRandom/
// QuantumRandom.fsproj
// Domain.fs
// Service.fs
// Program.fs
// tests/
// QuantumRandom.Tests/
// QuantumRandom.Tests.fsproj
// ServiceTests.fs
// Domain.fs
module QuantumRandom.Domain
type RandomResponse = { Data: byte[]; RequestId: string }
type QuantumError =
| QuotaExceeded of requestId:string
| Unauthorized of message:string
| ServerBusy of requestId:string
| Network of ex:System.Exception
// Service.fs
module QuantumRandom.Service
open System
open System.Net.Http
open System.Net.Http.Headers
open System.Security.Cryptography
open System.Text
open System.Text.Json
open Microsoft.Extensions.Logging
open Microsoft.Extensions.Options
open Polly
open Polly.Extensions.Http
type QuantumOptions =
{ Endpoint: Uri
Ak: string
Sk: string
MaxBytesPerCall: int
Timeout: TimeSpan
RetryCount: int
BackoffPower: int }
type QuantumRandomService(logger: ILogger<QuantumRandomService>,
httpClient: HttpClient,
options: IOptions<QuantumOptions>) =
let opts = options.Value
let sign (sk: string) (method: string) (uri: string) (headers: (string*string) list) =
let canonical =
[ yield method.ToUpperInvariant()
yield "\n"
yield uri
yield "\n"
for k,v in headers |> List.sortBy fst do
yield sprintf "%s:%s\n" k v ]
|> String.concat ""
use hmac = new HMACSHA256(Encoding.UTF8.GetBytes sk)
Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes canonical))
let policy =
HttpPolicyExtensions
.HandleTransientHttpError()
.OrResult(fun resp -> resp.StatusCode = HttpStatusCode.TooManyRequests)
.WaitAndRetryAsync(
opts.RetryCount,
fun retry -> TimeSpan.FromSeconds (float (2. ** retry) * float opts.BackoffPower),
fun outcome ts retry ctx ->
logger.LogWarning("Retry {Retry}, waited {Ts}c", retry, ts))
member _.GetRandomBytesAsync(bytes: int) : Async<Result<RandomResponse, QuantumError>> = async {
if bytes <= 0 || bytes > opts.MaxBytesPerCall then
return Error (QuantumError.QuotaExceeded "bytes out of range")
else
let url = Uri(opts.Endpoint, $"/v3/quantum-random?length={bytes}")
use req = new HttpRequestMessage(HttpMethod.Get, url)
let timestamp = DateTimeOffset.UtcNow.ToString("yyyyMMddTHHmmssZ")
let headers =
[ "host", url.Host
"x-sdk-date", timestamp
"x-sdk-content-sha256", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" ]
let auth = sign opts.Sk "GET" url.PathAndQuery headers
req.Headers.Authorization <- AuthenticationHeaderValue("SDK-HMAC-SHA256",
sprintf "Credential=%s,SignedHeaders=host;x-sdk-date;x-sdk-content-sha256,Signature=%s" opts.Ak auth)
for k,v in headers do req.Headers.TryAddWithoutValidation(k, v) |> ignore
req.Headers.Add("Idempotency-Key", Guid.NewGuid().ToString("N"))
let! response = policy.ExecuteAsync(fun () -> httpClient.SendAsync req) |> Async.AwaitTask
match response.StatusCode with
| HttpStatusCode.OK ->
let! body = response.Content.ReadAsByteArrayAsync() |> Async.AwaitTask
return Ok { Data = body; RequestId = response.Headers.GetValues("x-request-id") |> Seq.head }
| HttpStatusCode.TooManyRequests ->
return Error (QuantumError.QuotaExceeded (response.Headers.GetValues("x-request-id") |> Seq.head))
| HttpStatusCode.Unauthorized ->
let! msg = response.Content.ReadAsStringAsync() |> Async.AwaitTask
return Error (QuantumError.Unauthorized msg)
| _ when int response.StatusCode >= 500 ->
return Error (QuantumError.ServerBusy (response.Headers.GetValues("x-request-id") |> Seq.head))
| code ->
return Error (QuantumError.Network (Exception(sprintf "Unexpected %d" (int code))))
}
// Program.fs
module QuantumRandom.Program
open Microsoft.AspNetCore.Builder
open Microsoft.Extensions.DependencyInjection
open Microsoft.Extensions.Hosting
open Microsoft.Extensions.Options
open QuantumRandom.Service
let builder = WebApplication.CreateBuilder()
builder.Services.Configure<QuantumOptions>(builder.Configuration.GetSection("QuantumRandom")) |> ignore
builder.Services.AddHttpClient<QuantumRandomService>(fun sp client ->
let opts = sp.GetRequiredService<IOptions<QuantumOptions>>().Value
client.Timeout <- opts.Timeout)
.AddPolicyHandler(
HttpPolicyExtensions.HandleTransientHttpError()
.CircuitBreakerAsync(5, TimeSpan.FromSeconds 30.)) |> ignore
builder.Services.AddSingleton<QuantumRandomService>() |> ignore
builder.Services.AddLogging(fun b -> b.AddConsole().AddJsonConsole() |> ignore) |> ignore
let app = builder.Build()
app.MapGet("/random/{bytes:int}", fun (bytes: int, svc: QuantumRandomService) ->
task {
let! result = svc.GetRandomBytesAsync bytes
return match result with
| Ok r -> Results.Bytes(r.Data)
| Error e -> Results.Problem(detail = string e, statusCode = 500)
}) |> ignore
app.Run()
// appsettings.Production.json
{ "QuantumRandom": {
"Endpoint": "https://qrng.myhuaweicloud.com",
"Ak": "#{HUAWEI_CLOUD_AK}#",
"Sk": "#{HUAWEI_CLOUD_SK}#",
"MaxBytesPerCall": 2048,
"Timeout": "00:00:05",
"RetryCount": 3,
"BackoffPower": 2
} }
// Dockerfile(多阶段,使用华为云 SWR 基础镜像)
FROM mcr.microsoft.com/dotnet/sdk:8.0-alpine AS build
WORKDIR /src
COPY . .
RUN dotnet publish -c Release -o /app
FROM swr.cn-north-4.myhuaweicloud.com/huawei-cce/dotnet-runtime:8.0-alpine
WORKDIR /app
COPY --from=build /app .
ENV DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1
ENTRYPOINT ["dotnet", "QuantumRandom.dll"]
单元测试节选(Expecto):
test "should retry on 429 and eventually succeed" {
let handler = StubHandler(fun req ->
if req.Headers.Contains("Idempotency-Key") then
HttpResponseMessage(HttpStatusCode.OK, Content = ReadOnlyMemoryContent(ReadOnlyMemory(Array.zeroCreate 64)))
else
HttpResponseMessage(HttpStatusCode.TooManyRequests))
use client = new HttpClient(handler)
let opts = { Endpoint = Uri "http://test"; Ak="a"; Sk="s"; MaxBytesPerCall=1024;
Timeout=TimeSpan.FromSeconds 5; RetryCount=3; BackoffPower=1 }
let svc = QuantumRandomService(NullLogger.Instance, client, Options.Create opts)
let result = svc.GetRandomBytesAsync 64 |> Async.RunSynchronously
Expect.isOk result "should succeed after retry"
}
拓展思考
- 如果业务需要 1 MB 随机数,单 API 上限 2 KB,如何设计“并行切片 + 顺序合并”且保持熵池顺序?
提示:用 F# 的 AsyncSeq 展开切片流,异步拉取,再用 ImmutableArray.Builder 按偏移写入,最后一次性 ToArray。 - 国内监管要求“随机数来源可审计”,需在本地落盘每一次 RequestId 与响应哈希,如何用最少的锁实现 5 万 QPS 持久化?
提示:用 System.Threading.Channels 创建无锁队列,后台单写线程批量插入 SQLite WAL 模式,配合 SSD 顺序写。 - 若切换到“国密双证书”通道,客户端需加载 SM2 证书,如何在不改业务代码的前提下,用 F# 的“函数式装饰器”模式动态替换 HttpClient 的 SocketsHttpHandler?
提示:定义一个 HttpClientBuilder 计算表达式,内部读取证书序列号,通过 SafeX509Handle 绑定到 CustomTrustStore,再生成命名 HttpClient,保持 QuantumRandomService 无感知。