// Copyright (c) 2025-2026 GeWuYou
// SPDX-License-Identifier: Apache-2.0
using GFramework.Core.Abstractions.Query;
using GFramework.Core.Abstractions.Rule;
using GFramework.Core.Cqrs;
using GFramework.Cqrs.Abstractions.Cqrs;
namespace GFramework.Core.Query;
///
/// 异步查询总线实现,用于处理异步查询请求
///
public sealed class AsyncQueryExecutor(ICqrsRuntime? runtime = null) : IAsyncQueryExecutor
{
private readonly ICqrsRuntime? _runtime = runtime;
///
/// 获取当前执行器是否已接入统一 CQRS runtime。
///
public bool UsesCqrsRuntime => _runtime is not null;
///
/// 异步发送查询请求并返回结果
///
/// 查询结果类型
/// 要执行的异步查询对象
/// 包含查询结果的异步任务
public Task SendAsync(IAsyncQuery query)
{
ArgumentNullException.ThrowIfNull(query);
if (TryResolveDispatchContext(query, out var context) && _runtime is not null)
{
return BridgeAsyncQueryAsync(context, query);
}
return query.DoAsync();
}
///
/// 通过统一 CQRS runtime 异步执行 legacy 查询,并把装箱结果还原为目标类型。
///
/// 查询结果类型。
/// 当前架构上下文。
/// 要桥接的 legacy 查询。
/// 查询执行结果。
private async Task BridgeAsyncQueryAsync(
GFramework.Core.Abstractions.Architectures.IArchitectureContext context,
IAsyncQuery query)
{
var boxedResult = await _runtime!.SendAsync(
context,
new LegacyAsyncQueryDispatchRequest(
query,
async () => await query.DoAsync().ConfigureAwait(false)))
.ConfigureAwait(false);
return (TResult)boxedResult!;
}
///
/// 解析当前 legacy 查询应该绑定到哪个架构上下文。
///
/// 即将执行的 legacy 查询对象。
/// 命中时返回可用于 CQRS runtime 的架构上下文。
/// 如果既接入了 runtime 且查询对象提供了上下文,则返回 。
private bool TryResolveDispatchContext(object query, out GFramework.Core.Abstractions.Architectures.IArchitectureContext context)
{
context = null!;
if (_runtime is null || query is not IContextAware contextAware)
{
return false;
}
try
{
context = contextAware.GetContext();
return true;
}
catch (InvalidOperationException)
{
return false;
}
}
}