rpc.ts 2.62 KB
import type { RemoteRequest } from '@uj/contracts';
import { requestViaHost } from '@uj/platform-sdk';
import { getGatewayCredential, getGatewayToken } from './credentials';
import { resolveGateway } from './gateways';
import { toHostEnvelope } from './gateways/glsx';
import type { RpcCall } from './types';

/** 老系统的 RPC 网关统一 3 分钟超时(原 config 的 request.timeout: 180000)。 */
const LEGACY_TIMEOUT = 180000;

/**
 * 把一次「业务语义」的 RPC 调用组装成对方真正接受的 HTTP 请求,并交主壳发出。
 *
 * 只有三件事在这里发生:
 *  1. 落点:绝对 URL(含网关 origin),因此主壳不会再补自己的 context-path;
 *  2. 请求体:method 名与业务参数平铺在同一层,再并进该网关的加签字段;
 *  3. 返回:网关自己的 code 语义在响应拦截器之前归一,业务层拿到的就是纯数据。
 *
 * 签名状态(密钥、公钥、context-path、401 登出)仍然只存在于主壳那一份实例里,
 * 请求层不下放的约束没有被破坏(见 ARCHITECTURE.md §2)。
 */
export function rpcCall<T>(call: RpcCall): Promise<T> {
  const strategy = resolveGateway(call.gateway);
  const credential = getGatewayCredential(call.gateway);
  const params = call.params;
  const timestamp = Date.now();

  const body: Record<string, unknown> = { ...params, method: call.method };
  const needsSign = call.signed !== false;
  if (needsSign) {
    if (!credential.secret) {
      throw new Error(
        `${call.gateway} 的接口需要加签,但未配置 VITE_POINTS_GATEWAY_APP_KEY / VITE_POINTS_GATEWAY_SECRET。`,
      );
    }
    Object.assign(
      body,
      strategy.signer.fields({
        method: call.method,
        params,
        timestamp,
        appKey: credential.appKey,
        secret: credential.secret,
        version: credential.version,
        format: credential.format,
        exclude: call.unsignedKeys,
      }),
    );
  }

  const token = getGatewayToken();
  const request = {
    method: 'POST',
    url: `${credential.origin.replace(/\/+$/, '')}/${strategy.router}`,
    data: body,
    headers: token ? { [strategy.tokenHeader]: token } : {},
    transformResponse: [toHostEnvelope],
    timeout: LEGACY_TIMEOUT,
    withCredentials: true,
  } satisfies RemoteRequest;

  // 主壳拦截器收到的是 { data } 形态(已在 toHostEnvelope 里判定成功),
  // 失败与登录失效由拦截器统一抛出/登出,这里只负责把业务数据交出去。
  return requestViaHost()(request).then((response) => {
    const envelope = response as { data?: unknown };
    return envelope?.data as T;
  });
}