All files / dingtalk-openclaw-connector/src probe.ts

0% Statements 0/149
0% Branches 0/1
0% Functions 0/1
0% Lines 0/149

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180                                                                                                                                                                                                                                                                                                                                                                       
import { raceWithTimeoutAndAbort } from "./utils/async.ts";
import type { DingtalkProbeResult } from "./types/index.ts";
 
/** Cache probe results to reduce repeated health-check calls. */
const probeCache = new Map<string, { result: DingtalkProbeResult; expiresAt: number }>();
const PROBE_SUCCESS_TTL_MS = 10 * 60 * 1000; // 10 minutes
const PROBE_ERROR_TTL_MS = 60 * 1000; // 1 minute
const MAX_PROBE_CACHE_SIZE = 64;
export const DINGTALK_PROBE_REQUEST_TIMEOUT_MS = 10_000;
export type ProbeDingtalkOptions = {
  timeoutMs?: number;
  abortSignal?: AbortSignal;
};
 
type DingtalkBotInfoResponse = {
  errcode?: number;
  errmsg?: string;
  nick?: string;
  unionid?: string;
};
 
function setCachedProbeResult(
  cacheKey: string,
  result: DingtalkProbeResult,
  ttlMs: number,
): DingtalkProbeResult {
  probeCache.set(cacheKey, { result, expiresAt: Date.now() + ttlMs });
  if (probeCache.size > MAX_PROBE_CACHE_SIZE) {
    const oldest = probeCache.keys().next().value;
    if (oldest !== undefined) {
      probeCache.delete(oldest);
    }
  }
  return result;
}
 
export async function probeDingtalk(
  creds?: { clientId: string; clientSecret: string; accountId?: string },
  options: ProbeDingtalkOptions = {},
): Promise<DingtalkProbeResult> {
  if (!creds?.clientId || !creds?.clientSecret) {
    return {
      ok: false,
      error: "missing credentials (clientId, clientSecret)",
    };
  }
  if (options.abortSignal?.aborted) {
    return {
      ok: false,
      clientId: creds.clientId,
      error: "probe aborted",
    };
  }
 
  const timeoutMs = options.timeoutMs ?? DINGTALK_PROBE_REQUEST_TIMEOUT_MS;
 
  // Return cached result if still valid.
  const cacheKey = creds.accountId ?? `${creds.clientId}:${creds.clientSecret.slice(0, 8)}`;
  const cached = probeCache.get(cacheKey);
  if (cached && cached.expiresAt > Date.now()) {
    return cached.result;
  }
 
  try {
    // Get access token
    const tokenResponse = await raceWithTimeoutAndAbort(
      fetch("https://api.dingtalk.com/v1.0/oauth2/accessToken", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          appKey: creds.clientId,
          appSecret: creds.clientSecret,
        }),
      }),
      { timeoutMs, abortSignal: options.abortSignal },
    );
 
    if (tokenResponse.status === "aborted") {
      return {
        ok: false,
        clientId: creds.clientId,
        error: "probe aborted",
      };
    }
    if (tokenResponse.status === "timeout") {
      return setCachedProbeResult(
        cacheKey,
        {
          ok: false,
          clientId: creds.clientId,
          error: `probe timed out after ${timeoutMs}ms`,
        },
        PROBE_ERROR_TTL_MS,
      );
    }
 
    const tokenData = await tokenResponse.value.json() as { accessToken?: string };
    if (!tokenData.accessToken) {
      return setCachedProbeResult(
        cacheKey,
        {
          ok: false,
          clientId: creds.clientId,
          error: "failed to get access token",
        },
        PROBE_ERROR_TTL_MS,
      );
    }
 
    // Get bot info
    const botResponse = await raceWithTimeoutAndAbort(
      fetch(`https://api.dingtalk.com/v1.0/contact/users/me`, {
        method: "GET",
        headers: {
          "x-acs-dingtalk-access-token": tokenData.accessToken,
          "Content-Type": "application/json",
        },
      }),
      { timeoutMs, abortSignal: options.abortSignal },
    );
 
    if (botResponse.status === "aborted") {
      return {
        ok: false,
        clientId: creds.clientId,
        error: "probe aborted",
      };
    }
    if (botResponse.status === "timeout") {
      return setCachedProbeResult(
        cacheKey,
        {
          ok: false,
          clientId: creds.clientId,
          error: `probe timed out after ${timeoutMs}ms`,
        },
        PROBE_ERROR_TTL_MS,
      );
    }
 
    const botData = await botResponse.value.json() as DingtalkBotInfoResponse;
    if (botData.errcode && botData.errcode !== 0) {
      return setCachedProbeResult(
        cacheKey,
        {
          ok: false,
          clientId: creds.clientId,
          error: `API error: ${botData.errmsg || `code ${botData.errcode}`}`,
        },
        PROBE_ERROR_TTL_MS,
      );
    }
 
    return setCachedProbeResult(
      cacheKey,
      {
        ok: true,
        clientId: creds.clientId,
        botName: botData.nick,
      },
      PROBE_SUCCESS_TTL_MS,
    );
  } catch (err) {
    return setCachedProbeResult(
      cacheKey,
      {
        ok: false,
        clientId: creds.clientId,
        error: err instanceof Error ? err.message : String(err),
      },
      PROBE_ERROR_TTL_MS,
    );
  }
}
 
/** Clear the probe cache (for testing). */
export function clearProbeCache(): void {
  probeCache.clear();
}