( socketPath: string, timeoutMs = 3000, authToken?: string, )
| 137 | * Returns true if the peer responds within the timeout. |
| 138 | */ |
| 139 | export async function isPeerAlive( |
| 140 | socketPath: string, |
| 141 | timeoutMs = 3000, |
| 142 | authToken?: string, |
| 143 | ): Promise<boolean> { |
| 144 | const token = authToken ?? (await findAuthTokenForSocketPath(socketPath)) |
| 145 | if (!token) return false |
| 146 | |
| 147 | return new Promise<boolean>(resolve => { |
| 148 | const conn = createConnection(socketPath, () => { |
| 149 | const ping: UdsMessage = { |
| 150 | type: 'ping', |
| 151 | ts: new Date().toISOString(), |
| 152 | meta: { authToken: token }, |
| 153 | } |
| 154 | conn.write(jsonStringify(ping) + '\n') |
| 155 | }) |
| 156 | |
| 157 | let resolved = false |
| 158 | |
| 159 | const timer = setTimeout(() => { |
| 160 | if (!resolved) { |
| 161 | resolved = true |
| 162 | conn.destroy() |
| 163 | resolve(false) |
| 164 | } |
| 165 | }, timeoutMs) |
| 166 | |
| 167 | let buffer = '' |
| 168 | conn.on('data', chunk => { |
| 169 | if ( |
| 170 | Buffer.byteLength(buffer, 'utf8') + getChunkBytes(chunk) > |
| 171 | MAX_UDS_FRAME_BYTES |
| 172 | ) { |
| 173 | if (!resolved) { |
| 174 | resolved = true |
| 175 | clearTimeout(timer) |
| 176 | conn.destroy() |
| 177 | resolve(false) |
| 178 | } |
| 179 | return |
| 180 | } |
| 181 | buffer += chunk.toString() |
| 182 | if (buffer.includes('"pong"')) { |
| 183 | if (!resolved) { |
| 184 | resolved = true |
| 185 | clearTimeout(timer) |
| 186 | conn.end() |
| 187 | resolve(true) |
| 188 | } |
| 189 | } |
| 190 | }) |
| 191 | |
| 192 | conn.on('error', () => { |
| 193 | if (!resolved) { |
| 194 | resolved = true |
| 195 | clearTimeout(timer) |
| 196 | resolve(false) |
no test coverage detected