|
| 1 | +package tech.httptoolkit.javaagent.jettyclient; |
| 2 | + |
| 3 | +import net.bytebuddy.asm.Advice; |
| 4 | +import org.eclipse.jetty.client.*; |
| 5 | + |
| 6 | +import java.util.Collections; |
| 7 | +import java.util.Map; |
| 8 | +import java.util.Set; |
| 9 | +import java.util.WeakHashMap; |
| 10 | + |
| 11 | +public class JettyResetDestinationsAdvice { |
| 12 | + |
| 13 | + // Track each client with a weak ref, to avoid unnecessary reflection overhead by only |
| 14 | + // initializing them once, instead of every request |
| 15 | + public static Set<Object> patchedHttpClients = Collections.newSetFromMap(new WeakHashMap()); |
| 16 | + |
| 17 | + @Advice.OnMethodEnter |
| 18 | + public static void beforeResolveDestination( |
| 19 | + @Advice.This Object thisHttpClient |
| 20 | + // ^ Note that we can't use the real HttpClient type here, since this class is redefining it, so it would |
| 21 | + // cause a circular reference that breaks patching completely. |
| 22 | + ) { |
| 23 | + if (patchedHttpClients.contains(thisHttpClient)) return; |
| 24 | + |
| 25 | + // If this is the first time that we've seen this client, it's possible that it existed before we attached, |
| 26 | + // and it might have some existing open connections that don't use our proxy. To fix that, just once per |
| 27 | + // client, we use reflection to get the destinations (cached connections) and reset them. |
| 28 | + try { |
| 29 | + @SuppressWarnings("unchecked") |
| 30 | + Map<Origin, HttpDestination> destinations = (Map<Origin, HttpDestination>) |
| 31 | + thisHttpClient.getClass().getDeclaredField("destinations").get(thisHttpClient); |
| 32 | + |
| 33 | + // Reset this destinations list: |
| 34 | + for (HttpDestination destination : destinations.values()) { |
| 35 | + destination.close(); |
| 36 | + } |
| 37 | + destinations.clear(); |
| 38 | + } catch (Exception e) { |
| 39 | + throw new RuntimeException(e); |
| 40 | + } |
| 41 | + |
| 42 | + patchedHttpClients.add(thisHttpClient); |
| 43 | + } |
| 44 | +} |
0 commit comments