All files / api/src/middlewares hooks.ts

4.19% Statements 7/167
100% Branches 1/1
16.66% Functions 1/6
4.19% Lines 7/167

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 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218      1x         1x 1x                                                                                                                                                                                                                                                                                                                                                                                             1x 1x 1x   1x                          
import type { HooksConnector } from '@api/types/connector';
import type { AppContext, AppEnv } from '@api/types/hono';
import type { SuperAgentsRequestData } from '@shared/types/api/request/body';
import { FunctionName } from '@shared/types/api/request/function-name';
import type { SuperAgentsConfig } from '@shared/types/api/request/headers';
import type { SuperAgentsResponseBody } from '@shared/types/api/response/body';
import type { HookLog } from '@shared/types/data';
 
import { CacheStatus } from '@shared/types/middleware/cache';
import {
  type Hook,
  HookResult,
  HookType,
} from '@shared/types/middleware/hooks';
import type { MiddlewareHandler } from 'hono';
import type { Factory } from 'hono/factory';
 
async function executeHookByProvider(
  c: AppContext,
  hook: Hook,
): Promise<HookResult> {
  try {
    const hookConnectorsMap = c.get('hooks_connectors_map');
    const result: HookResult =
      await hookConnectorsMap[hook.hook_provider].executeHook(hook);
    return {
      deny_request: result.deny_request,
      request_body_override: result.request_body_override,
      response_body_override: result.response_body_override,
      skipped: result.skipped,
    };
  } catch (err: unknown) {
    console.error(`Error executing hook "${hook.id}":`, err);
    return {
      deny_request: false,
      request_body_override: undefined,
      response_body_override: undefined,
      skipped: false,
    };
  }
}
 
function shouldSkipHook(
  hook: Hook,
  fn: FunctionName,
  statusCode: number | null,
  isStreamingRequest: boolean,
  saResponseBody?:
    | SuperAgentsResponseBody
    | ReadableStream
    | FormData
    | ArrayBuffer,
): boolean {
  return (
    ![
      FunctionName.CHAT_COMPLETE,
      FunctionName.COMPLETE,
      FunctionName.EMBED,
    ].includes(fn) ||
    (fn === FunctionName.EMBED && hook.type !== HookType.INPUT_HOOK) ||
    (hook.type === HookType.OUTPUT_HOOK && statusCode !== 200) ||
    (hook.type === HookType.OUTPUT_HOOK &&
      isStreamingRequest &&
      !saResponseBody)
  );
}
 
async function executeHook(
  c: AppContext,
  hook: Hook,
  statusCode: number | null,
  isStreamingRequest: boolean,
  saRequestData: SuperAgentsRequestData,
  saResponseBody?: SuperAgentsResponseBody,
): Promise<{
  hookResult: HookResult;
  cacheStatus: CacheStatus;
}> {
  if (
    shouldSkipHook(
      hook,
      saRequestData.functionName,
      statusCode,
      isStreamingRequest,
      saResponseBody,
    )
  ) {
    const hookResult: HookResult = {
      deny_request: false,
      request_body_override: undefined,
      response_body_override: undefined,
      skipped: true,
    };
    return {
      hookResult,
      cacheStatus: CacheStatus.DISABLED,
    };
  }
 
  const saConfig = c.get('sa_config');
 
  let cacheStatus = CacheStatus.MISS;
  if (!saConfig.force_hook_refresh) {
    const getHookResponseFromCache = c.get('getHookResponseFromCache');
 
    const cacheResult = await getHookResponseFromCache(
      c,
      hook,
      saRequestData,
      saResponseBody,
    );
 
    if (cacheResult.status === CacheStatus.HIT) {
      return {
        hookResult: HookResult.parse(cacheResult.value),
        cacheStatus: cacheResult.status,
      };
    }
 
    cacheStatus = cacheResult.status;
  } else {
    cacheStatus = CacheStatus.REFRESH;
  }
 
  const result = await executeHookByProvider(c, hook);
 
  return {
    hookResult: result,
    cacheStatus,
  };
}
 
function getHooksToExecute(
  config: SuperAgentsConfig,
  hookType: HookType,
): Hook[] {
  const hooksToExecute: Hook[] = [];
  hooksToExecute.push(...config.hooks.filter((h) => h.type === hookType));
 
  return hooksToExecute;
}
 
export async function executeHooks(
  c: AppContext,
  hookType: HookType,
  statusCode: number | null,
  isStreamingRequest: boolean,
  saRequestData: SuperAgentsRequestData,
  saResponseBody?: SuperAgentsResponseBody,
): Promise<HookLog[]> {
  const saConfig = c.get('sa_config');
 
  const hooksToExecute = getHooksToExecute(saConfig, hookType);
 
  if (hooksToExecute.length === 0) {
    return [];
  }
 
  try {
    const results = await Promise.all(
      hooksToExecute.map(async (hook) => {
        const startTime = Date.now();
        const { hookResult, cacheStatus } = await executeHook(
          c,
          hook,
          statusCode,
          isStreamingRequest,
          saRequestData,
          saResponseBody,
        );
        const endTime = Date.now();
        const duration = endTime - startTime;
 
        const hookLog: HookLog = {
          trace_id: saConfig.trace_id,
          hook: hook,
          result: hookResult,
          start_time: startTime,
          end_time: endTime,
          duration: duration,
          cache_status: cacheStatus,
        };
 
        const currentHookLogs = c.get('hook_logs') || [];
        c.set('hook_logs', [...currentHookLogs, hookLog]);
 
        return hookLog;
      }),
    );
 
    return results;
  } catch (err) {
    console.error(`Error executing hooks:`, err);
    return [];
  }
}
 
/**
 * Middleware to handle hooks.
 */
export const hooksMiddleware = (
  factory: Factory<AppEnv>,
  connectors: HooksConnector[],
): MiddlewareHandler =>
  factory.createMiddleware(async (c, next) => {
    const hookConnectorsMap: Record<string, HooksConnector> = {};
 
    for (const connector of connectors) {
      hookConnectorsMap[connector.name] = connector;
    }
 
    c.set('hooks_connectors_map', hookConnectorsMap);
 
    c.set('executeHooks', executeHooks);
 
    await next();
  });