File size: 4,150 Bytes
6cdce85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
'use client';

import { useState, useEffect, useCallback, useRef } from 'react';

export type WarmupStatus = 'idle' | 'checking' | 'warming' | 'ready' | 'error';

interface WarmupState {
  status: WarmupStatus;
  message: string;
  workers: {
    idle: number;
    ready?: number;
    running: number;
    initializing: number;
  } | null;
}

interface UseWarmupReturn extends WarmupState {
  triggerWarmup: () => Promise<void>;
  checkStatus: () => Promise<void>;
}

let warmupInProgress = false;
let lastWarmupTime = 0;
const WARMUP_COOLDOWN = 5000; 

/**
 * Hook to pre-warm RunPod workers when user lands on the page.
 * Automatically triggers warmup on mount and polls for readiness.
 */
export function useWarmup(autoWarmup = true): UseWarmupReturn {
  const [state, setState] = useState<WarmupState>({
    status: 'idle',
    message: '',
    workers: null,
  });
  const mountedRef = useRef(true);

  const checkStatus = useCallback(async () => {
    try {
      const response = await fetch('/api/warmup', { method: 'GET' });
      if (response.ok && mountedRef.current) {
        const data = await response.json();
        
        if (data.ready) {
          setState({
            status: 'ready',
            message: 'Model ready',
            workers: data.workers || null,
          });
          return;
        }
        
        if (data.warming) {
          setState({
            status: 'warming',
            message: 'Model starting...',
            workers: data.workers || null,
          });
          return;
        }

        if (data.busy) {
          setState({
            status: 'warming',
            message: 'Model busy...',
            workers: data.workers || null,
          });
          return;
        }

        setState((prev) => ({
          ...prev,
          workers: data.workers || null,
        }));
      }
    } catch {
      // Silently fail status checks
    }
  }, []);

  const triggerWarmup = useCallback(async () => {
    // Prevent duplicate warmups
    const now = Date.now();
    if (warmupInProgress || (now - lastWarmupTime) < WARMUP_COOLDOWN) {
      await checkStatus();
      return;
    }
    
    warmupInProgress = true;
    lastWarmupTime = now;
    
    setState((prev) => ({ ...prev, status: 'checking', message: 'Checking model status...' }));

    try {
      const response = await fetch('/api/warmup', { method: 'POST' });
      const data = await response.json();
      
      if (!mountedRef.current) return;

      if (data.status === 'ready') {
        setState({
          status: 'ready',
          message: 'Model ready',
          workers: data.workers || null,
        });
      } else if (data.status === 'warming') {
        setState({
          status: 'warming',
          message: data.message || 'Starting model...',
          workers: data.workers || null,
        });
      } else if (data.status === 'skipped') {
        setState({
          status: 'ready',
          message: '',
          workers: null,
        });
      } else if (data.status === 'error') {
        setState({
          status: 'error',
          message: data.message || 'Warmup failed',
          workers: null,
        });
      }
    } catch (error) {
      if (mountedRef.current) {
        setState({
          status: 'error',
          message: error instanceof Error ? error.message : 'Warmup request failed',
          workers: null,
        });
      }
    } finally {
      warmupInProgress = false;
    }
  }, [checkStatus]);

  useEffect(() => {
    mountedRef.current = true;
    
    if (autoWarmup) {
      triggerWarmup();
    }
    
    return () => {
      mountedRef.current = false;
    };
  }, [autoWarmup, triggerWarmup]);

  useEffect(() => {
    if (state.status !== 'warming') return;

    const pollInterval = setInterval(() => {
      checkStatus();
    }, 5000); 

    const timeout = setTimeout(() => {
      clearInterval(pollInterval);
    }, 180000);

    return () => {
      clearInterval(pollInterval);
      clearTimeout(timeout);
    };
  }, [state.status, checkStatus]);

  return {
    ...state,
    triggerWarmup,
    checkStatus,
  };
}