|
| 1 | +/** |
| 2 | + * Hook for auto-starting port forwarding rules on app launch. |
| 3 | + * This should be used at the App level to ensure auto-start happens |
| 4 | + * when the application starts, not when the user navigates to the port forwarding page. |
| 5 | + */ |
| 6 | +import { useEffect, useRef } from "react"; |
| 7 | +import { Host, PortForwardingRule } from "../../domain/models"; |
| 8 | +import { STORAGE_KEY_PORT_FORWARDING } from "../../infrastructure/config/storageKeys"; |
| 9 | +import { localStorageAdapter } from "../../infrastructure/persistence/localStorageAdapter"; |
| 10 | +import { |
| 11 | + getActiveConnection, |
| 12 | + setReconnectCallback, |
| 13 | + startPortForward, |
| 14 | + syncWithBackend, |
| 15 | +} from "../../infrastructure/services/portForwardingService"; |
| 16 | +import { logger } from "../../lib/logger"; |
| 17 | + |
| 18 | +export interface UsePortForwardingAutoStartOptions { |
| 19 | + hosts: Host[]; |
| 20 | + keys: { id: string; privateKey: string }[]; |
| 21 | +} |
| 22 | + |
| 23 | +/** |
| 24 | + * Auto-starts port forwarding rules that have autoStart enabled. |
| 25 | + * This hook should be called at the App level to run on app launch. |
| 26 | + */ |
| 27 | +export const usePortForwardingAutoStart = ({ |
| 28 | + hosts, |
| 29 | + keys, |
| 30 | +}: UsePortForwardingAutoStartOptions): void => { |
| 31 | + const autoStartExecutedRef = useRef(false); |
| 32 | + const hostsRef = useRef<Host[]>(hosts); |
| 33 | + const keysRef = useRef<{ id: string; privateKey: string }[]>(keys); |
| 34 | + |
| 35 | + // Keep refs in sync |
| 36 | + useEffect(() => { |
| 37 | + hostsRef.current = hosts; |
| 38 | + }, [hosts]); |
| 39 | + |
| 40 | + useEffect(() => { |
| 41 | + keysRef.current = keys; |
| 42 | + }, [keys]); |
| 43 | + |
| 44 | + // Set up the reconnect callback |
| 45 | + useEffect(() => { |
| 46 | + const handleReconnect = async ( |
| 47 | + ruleId: string, |
| 48 | + onStatusChange: (status: PortForwardingRule["status"], error?: string) => void, |
| 49 | + ) => { |
| 50 | + // Load the current rules from storage |
| 51 | + const rules = localStorageAdapter.read<PortForwardingRule[]>( |
| 52 | + STORAGE_KEY_PORT_FORWARDING, |
| 53 | + ) ?? []; |
| 54 | + |
| 55 | + const rule = rules.find((r) => r.id === ruleId); |
| 56 | + if (!rule || !rule.hostId) { |
| 57 | + return { success: false, error: "Rule or host not found" }; |
| 58 | + } |
| 59 | + |
| 60 | + const host = hostsRef.current.find((h) => h.id === rule.hostId); |
| 61 | + if (!host) { |
| 62 | + return { success: false, error: "Host not found" }; |
| 63 | + } |
| 64 | + |
| 65 | + return startPortForward(rule, host, keysRef.current, onStatusChange, true); |
| 66 | + }; |
| 67 | + |
| 68 | + setReconnectCallback(handleReconnect); |
| 69 | + return () => { |
| 70 | + setReconnectCallback(null); |
| 71 | + }; |
| 72 | + }, []); |
| 73 | + |
| 74 | + // Auto-start rules on app launch |
| 75 | + useEffect(() => { |
| 76 | + if (autoStartExecutedRef.current) return; |
| 77 | + if (hosts.length === 0) return; |
| 78 | + |
| 79 | + const runAutoStart = async () => { |
| 80 | + // First sync with backend to get any active tunnels |
| 81 | + await syncWithBackend(); |
| 82 | + |
| 83 | + // Load rules from storage |
| 84 | + const rules = localStorageAdapter.read<PortForwardingRule[]>( |
| 85 | + STORAGE_KEY_PORT_FORWARDING, |
| 86 | + ) ?? []; |
| 87 | + |
| 88 | + // Only start rules that are not already active |
| 89 | + const autoStartRules = rules.filter((r) => { |
| 90 | + if (!r.autoStart || !r.hostId) return false; |
| 91 | + // Check if there's an active connection for this rule |
| 92 | + const conn = getActiveConnection(r.id); |
| 93 | + // Only start if not already connecting or active |
| 94 | + return !conn || conn.status === 'inactive' || conn.status === 'error'; |
| 95 | + }); |
| 96 | + |
| 97 | + if (autoStartRules.length === 0) return; |
| 98 | + |
| 99 | + autoStartExecutedRef.current = true; |
| 100 | + logger.info(`[PortForwardingAutoStart] Starting ${autoStartRules.length} auto-start rules`); |
| 101 | + |
| 102 | + // Start each auto-start rule |
| 103 | + for (const rule of autoStartRules) { |
| 104 | + const host = hosts.find((h) => h.id === rule.hostId); |
| 105 | + if (host) { |
| 106 | + void startPortForward( |
| 107 | + rule, |
| 108 | + host, |
| 109 | + keys, |
| 110 | + (status, error) => { |
| 111 | + // Update the rule status in storage |
| 112 | + const currentRules = localStorageAdapter.read<PortForwardingRule[]>( |
| 113 | + STORAGE_KEY_PORT_FORWARDING, |
| 114 | + ) ?? []; |
| 115 | + |
| 116 | + const updatedRules = currentRules.map((r) => |
| 117 | + r.id === rule.id |
| 118 | + ? { |
| 119 | + ...r, |
| 120 | + status, |
| 121 | + error, |
| 122 | + lastUsedAt: status === "active" ? Date.now() : r.lastUsedAt, |
| 123 | + } |
| 124 | + : r, |
| 125 | + ); |
| 126 | + |
| 127 | + localStorageAdapter.write(STORAGE_KEY_PORT_FORWARDING, updatedRules); |
| 128 | + }, |
| 129 | + true, // Enable reconnect for auto-start rules |
| 130 | + ); |
| 131 | + } |
| 132 | + } |
| 133 | + }; |
| 134 | + |
| 135 | + void runAutoStart(); |
| 136 | + }, [hosts, keys]); |
| 137 | +}; |
0 commit comments