Repository navigation
Make JBWAPI ready to connect as fast as possible #97
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
dgant
wants to merge
1
commit into
JavaBWAPI:develop
Choose a base branch
from
dgant:develop
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,147 @@ | ||
| package bwapi; | ||
|
|
||
| import com.sun.jna.Native; | ||
| import com.sun.jna.Platform; | ||
|
|
||
| import java.io.ByteArrayOutputStream; | ||
| import java.io.IOException; | ||
| import java.io.InputStream; | ||
| import java.net.URISyntaxException; | ||
| import java.nio.ByteBuffer; | ||
| import java.nio.channels.SeekableByteChannel; | ||
| import java.nio.file.Files; | ||
| import java.nio.file.Path; | ||
| import java.nio.file.Paths; | ||
| import java.util.Arrays; | ||
|
|
||
| import static java.nio.file.LinkOption.NOFOLLOW_LINKS; | ||
| import static java.nio.file.StandardOpenOption.READ; | ||
|
|
||
| /** | ||
| * Loads a matching Windows JNA DLL beside the bot's JAR before connecting to BWAPI. | ||
| * Shipping the DLL separately avoids extracting it to a temporary file on each launch. | ||
| * The file must match the JAR's embedded library for the running JVM's architecture. | ||
| * | ||
| * <p>Missing, stale, or unusable DLLs leave JNA's ordinary loading path available. | ||
| * Other platforms also use ordinary JNA loading. Explicit JNA loading settings | ||
| * and an already initialized JNA take precedence. | ||
| */ | ||
| final class JnaNativeLoader { | ||
| private static final String BOOT_PATH = "jna.boot.library.path"; | ||
| private static final String BOOT_NAME = "jna.boot.library.name"; | ||
|
|
||
| private JnaNativeLoader() { | ||
| } | ||
|
|
||
| /** | ||
| * Call before constructing a platform connector or otherwise initializing JNA. | ||
| */ | ||
| static synchronized void initialize() { | ||
| String path; | ||
| String bootName; | ||
| try { | ||
| if (!Platform.isWindows() || isConfigured()) { | ||
| return; | ||
| } | ||
| byte[] binary = readEmbeddedLibrary(); | ||
| if (binary == null) { | ||
| return; | ||
| } | ||
| Path library = bundledLibrary(binary); | ||
| if (library == null || isConfigured()) { | ||
| return; | ||
| } | ||
| path = library.getParent().toAbsolutePath().toString(); | ||
| bootName = "jnidispatch-" + Platform.RESOURCE_PREFIX; | ||
| } catch (IOException | RuntimeException unavailable) { | ||
| // An optional optimization must not prevent JNA's ordinary loading path. | ||
| return; | ||
| } | ||
| loadPreparedLibrary(path, bootName); | ||
| } | ||
|
|
||
| private static byte[] readEmbeddedLibrary() throws IOException { | ||
| String resource = "/com/sun/jna/" + Platform.RESOURCE_PREFIX + "/jnidispatch.dll"; | ||
| // A class literal does not initialize Native; use its loader's exact binary. | ||
| try (InputStream input = Native.class.getResourceAsStream(resource); | ||
| ByteArrayOutputStream output = new ByteArrayOutputStream()) { | ||
| if (input == null) { | ||
| return null; | ||
| } | ||
| byte[] buffer = new byte[32768]; | ||
| int size; | ||
| while ((size = input.read(buffer)) != -1) { | ||
| output.write(buffer, 0, size); | ||
| } | ||
| return output.toByteArray(); | ||
| } | ||
| } | ||
|
|
||
| private static void loadPreparedLibrary(String path, String bootName) { | ||
| try { | ||
| try { | ||
| System.setProperty(BOOT_PATH, path); | ||
| System.setProperty(BOOT_NAME, bootName); | ||
| } catch (RuntimeException unavailable) { | ||
| return; | ||
| } | ||
| // JNA itself falls back to ordinary extraction if this binary cannot be loaded. | ||
| Class.forName(Native.class.getName(), true, Native.class.getClassLoader()); | ||
| } catch (ClassNotFoundException impossible) { | ||
| throw new IllegalStateException("Cannot initialize JNA: its class loader could not find " | ||
| + "com.sun.jna.Native, which is required to load the native library. Ensure JNA is included " | ||
| + "in the bot's runtime classpath and is visible to its class loader.", impossible); | ||
| } finally { | ||
| // Do not leave a process-wide path pointing at this class loader's JNA version. | ||
| if (path.equals(System.getProperty(BOOT_PATH))) { | ||
| System.clearProperty(BOOT_PATH); | ||
| } | ||
| if (bootName.equals(System.getProperty(BOOT_NAME))) { | ||
| System.clearProperty(BOOT_NAME); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private static boolean isConfigured() { | ||
| if (Boolean.getBoolean("jna.loaded")) { | ||
| return true; | ||
| } | ||
| for (String setting : new String[] {BOOT_PATH, BOOT_NAME, | ||
| "jna.noclasspath", "jna.nosys", "jna.prefix", "jnidispatch.preserve"}) { | ||
| if (System.getProperty(setting) != null) { | ||
| return true; | ||
| } | ||
| } | ||
| return false; | ||
| } | ||
|
|
||
| private static Path bundledLibrary(byte[] binary) { | ||
| try { | ||
| // Resolve beside the JAR (or wrapped EXE), never relative to a launcher's working directory. | ||
| Path artifact = Paths.get(JnaNativeLoader.class.getProtectionDomain().getCodeSource().getLocation().toURI()); | ||
| Path library = artifact.resolveSibling("jnidispatch-" + Platform.RESOURCE_PREFIX + ".dll"); | ||
| // A replaced JAR must not accidentally load a DLL left over from another JNA version. | ||
| return matches(library, binary) ? library : null; | ||
| } catch (IOException | URISyntaxException | RuntimeException unavailable) { | ||
| return null; | ||
| } | ||
| } | ||
|
|
||
| private static boolean matches(Path file, byte[] expected) throws IOException { | ||
| if (!Files.exists(file, NOFOLLOW_LINKS)) { | ||
| return false; | ||
| } | ||
| try (SeekableByteChannel channel = Files.newByteChannel(file, READ, NOFOLLOW_LINKS)) { | ||
| if (channel.size() != expected.length) { | ||
| return false; | ||
| } | ||
| ByteBuffer bytes = ByteBuffer.allocate(expected.length); | ||
| while (bytes.hasRemaining()) { | ||
| if (channel.read(bytes) < 0) { | ||
| return false; | ||
| } | ||
| } | ||
| return Arrays.equals(expected, bytes.array()); | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| package bwapi; | ||
|
|
||
| import org.junit.Test; | ||
|
|
||
| import java.lang.management.BufferPoolMXBean; | ||
| import java.lang.management.ManagementFactory; | ||
|
|
||
| import static org.junit.Assert.assertNull; | ||
| import static org.junit.Assert.assertThrows; | ||
| import static org.junit.Assert.assertTrue; | ||
| import static org.mockito.Mockito.doAnswer; | ||
| import static org.mockito.Mockito.mock; | ||
|
|
||
| /** | ||
| * Guards the order of startup work: attempt the BWAPI connection before creating | ||
| * performance metrics or allocating the large buffers used for asynchronous frames. | ||
| * Measures direct-buffer allocation at a mocked connection boundary, so the test | ||
| * needs neither a running server nor a machine-dependent elapsed-time threshold. | ||
| */ | ||
| public class BWClientStartupTest { | ||
| // Stops startGame at the mocked connection boundary, before a game loop can run. | ||
| private static class StopAfterConnectionAttempt extends RuntimeException { | ||
| } | ||
|
|
||
| @Test | ||
| public void attemptsConnectionBeforeAllocatingFrameBuffersOrMetrics() { | ||
| BWClient bwClient = new BWClient(new DefaultBWListener()); | ||
| Client client = mock(Client.class); | ||
| bwClient.setClient(client); | ||
| BWClientConfiguration configuration = new BWClientConfiguration.Builder() | ||
| .withAsync(true) | ||
| .withAsyncFrameBufferCapacity(3) | ||
| .build(); | ||
| BufferPoolMXBean directBuffers = ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class) | ||
| .stream() | ||
| .filter(pool -> "direct".equals(pool.getName())) | ||
| .findFirst() | ||
| .get(); | ||
| long bytesBeforeStart = directBuffers.getMemoryUsed(); | ||
| doAnswer(invocation -> { | ||
| assertTrue("Connection attempts must precede allocation of even one game-state buffer", | ||
| directBuffers.getMemoryUsed() - bytesBeforeStart < ClientData.GameData.SIZE); | ||
| assertNull(bwClient.getPerformanceMetrics()); | ||
| throw new StopAfterConnectionAttempt(); | ||
| }).when(client).reconnect(); | ||
|
|
||
| assertThrows(StopAfterConnectionAttempt.class, () -> bwClient.startGame(configuration)); | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
My naive assumption is that change is actually the most important for the startup boost (e.g. the Client starting to listen ASAP). Do you have individual timing on how much each of the 3 changes actually brings individually?
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The deferred buffer allocation is certainly the easiest win though :)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ok interesting, thanks for the numbers. I would prefer putting the "Using pre-extracted JNA DLL" (most complicated) in another PR which I can look at in more detail another time, the deferral and narrow bindings look like free wins, those LGTM for this CL, thanks a bunch!