-
Notifications
You must be signed in to change notification settings - Fork 333
Reduce per-query allocations in SQLCommenter.inject() #11154
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
Draft
dougqh
wants to merge
3
commits into
master
Choose a base branch
from
dougqh/reduce-sqlcommenter-allocs
base: master
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.
+316
−20
Draft
Changes from 1 commit
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -9,6 +9,7 @@ | |
| import java.io.UnsupportedEncodingException; | ||
| import java.net.URLEncoder; | ||
| import java.nio.charset.StandardCharsets; | ||
| import java.util.concurrent.ConcurrentHashMap; | ||
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
|
|
||
|
|
@@ -32,17 +33,63 @@ public class SharedDBCommenter { | |
| private static final String TRACEPARENT = encode("traceparent"); | ||
| private static final String DD_SERVICE_HASH = encode("ddsh"); | ||
|
|
||
| /** | ||
| * Cache for static comment strings (those without traceParent or peerService). The key combines | ||
| * dbService, hostname, dbName, and Config identity to ensure correctness if Config is replaced. | ||
| */ | ||
| private static final ConcurrentHashMap<StaticCommentKey, String> staticCommentCache = | ||
| new ConcurrentHashMap<>(); | ||
|
|
||
| // Pre-computed marker strings for trace comment detection | ||
| private static final String PARENT_SERVICE_EQ = PARENT_SERVICE + "="; | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. These constants are obviously a good idea, keep them |
||
| private static final String DATABASE_SERVICE_EQ = DATABASE_SERVICE + "="; | ||
| private static final String DD_HOSTNAME_EQ = DD_HOSTNAME + "="; | ||
| private static final String DD_DB_NAME_EQ = DD_DB_NAME + "="; | ||
| private static final String DD_PEER_SERVICE_EQ = DD_PEER_SERVICE + "="; | ||
| private static final String DD_ENV_EQ = DD_ENV + "="; | ||
| private static final String DD_VERSION_EQ = DD_VERSION + "="; | ||
| private static final String TRACEPARENT_EQ = TRACEPARENT + "="; | ||
| private static final String DD_SERVICE_HASH_EQ = DD_SERVICE_HASH + "="; | ||
|
|
||
| // Used by SQLCommenter and MongoCommentInjector to avoid duplicate comment injection | ||
| public static boolean containsTraceComment(String commentContent) { | ||
| return commentContent.contains(PARENT_SERVICE + "=") | ||
| || commentContent.contains(DATABASE_SERVICE + "=") | ||
| || commentContent.contains(DD_HOSTNAME + "=") | ||
| || commentContent.contains(DD_DB_NAME + "=") | ||
| || commentContent.contains(DD_PEER_SERVICE + "=") | ||
| || commentContent.contains(DD_ENV + "=") | ||
| || commentContent.contains(DD_VERSION + "=") | ||
| || commentContent.contains(TRACEPARENT + "=") | ||
| || commentContent.contains(DD_SERVICE_HASH + "="); | ||
| return commentContent.contains(PARENT_SERVICE_EQ) | ||
| || commentContent.contains(DATABASE_SERVICE_EQ) | ||
| || commentContent.contains(DD_HOSTNAME_EQ) | ||
| || commentContent.contains(DD_DB_NAME_EQ) | ||
| || commentContent.contains(DD_PEER_SERVICE_EQ) | ||
| || commentContent.contains(DD_ENV_EQ) | ||
| || commentContent.contains(DD_VERSION_EQ) | ||
| || commentContent.contains(TRACEPARENT_EQ) | ||
| || commentContent.contains(DD_SERVICE_HASH_EQ); | ||
| } | ||
|
|
||
| /** | ||
| * Checks for trace comment markers within a range of the given string, without allocating a | ||
| * substring. Searches within [fromIndex, toIndex) of the source string. | ||
| */ | ||
| public static boolean containsTraceComment(String sql, int fromIndex, int toIndex) { | ||
| return containsInRange(sql, PARENT_SERVICE_EQ, fromIndex, toIndex) | ||
| || containsInRange(sql, DATABASE_SERVICE_EQ, fromIndex, toIndex) | ||
| || containsInRange(sql, DD_HOSTNAME_EQ, fromIndex, toIndex) | ||
| || containsInRange(sql, DD_DB_NAME_EQ, fromIndex, toIndex) | ||
| || containsInRange(sql, DD_PEER_SERVICE_EQ, fromIndex, toIndex) | ||
| || containsInRange(sql, DD_ENV_EQ, fromIndex, toIndex) | ||
| || containsInRange(sql, DD_VERSION_EQ, fromIndex, toIndex) | ||
| || containsInRange(sql, TRACEPARENT_EQ, fromIndex, toIndex) | ||
| || containsInRange(sql, DD_SERVICE_HASH_EQ, fromIndex, toIndex); | ||
| } | ||
|
|
||
| /** Checks if {@code target} appears within the range [fromIndex, toIndex) of {@code source}. */ | ||
| private static boolean containsInRange(String source, String target, int fromIndex, int toIndex) { | ||
| int targetLen = target.length(); | ||
| int limit = toIndex - targetLen; | ||
| for (int i = fromIndex; i <= limit; i++) { | ||
| if (source.regionMatches(i, target, 0, targetLen)) { | ||
| return true; | ||
| } | ||
| } | ||
| return false; | ||
| } | ||
|
|
||
| // Build database comment content without comment delimiters such as /* */ | ||
|
|
@@ -69,6 +116,60 @@ public static String buildComment( | |
| return sb.length() > 0 ? sb.toString() : null; | ||
| } | ||
|
|
||
| /** | ||
| * Builds the static portion of a database comment that does not change per-span. This includes | ||
| * parentService, databaseService, hostname, dbName, env, version, and serviceHash. The dynamic | ||
| * parts (peerService, traceParent) are excluded and must be appended separately. | ||
| * | ||
| * <p>Results are cached per (dbService, hostname, dbName, Config) combination to avoid redundant | ||
| * URLEncoder.encode() calls and StringBuilder work on every query execution. | ||
| * | ||
| * @return the static comment prefix, or null if no static fields are set | ||
| */ | ||
| public static String buildStaticComment(String dbService, String hostname, String dbName) { | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Remove this caching and the associated StaticCommentKey class for this initial PR |
||
| Config config = Config.get(); | ||
| StaticCommentKey key = new StaticCommentKey(dbService, hostname, dbName, config); | ||
| String cached = staticCommentCache.get(key); | ||
| if (cached != null) { | ||
| return cached; | ||
| } | ||
|
|
||
| StringBuilder sb = new StringBuilder(); | ||
|
|
||
| int initSize = 0; | ||
| append(sb, PARENT_SERVICE, config.getServiceName(), initSize); | ||
| append(sb, DATABASE_SERVICE, dbService, initSize); | ||
| append(sb, DD_HOSTNAME, hostname, initSize); | ||
| append(sb, DD_DB_NAME, dbName, initSize); | ||
| // peerService is per-span, skip here | ||
| append(sb, DD_ENV, config.getEnv(), initSize); | ||
| append(sb, DD_VERSION, config.getVersion(), initSize); | ||
| // traceParent is per-span, skip here | ||
|
|
||
| if (config.isDbmInjectSqlBaseHash() && config.isExperimentalPropagateProcessTagsEnabled()) { | ||
| append(sb, DD_SERVICE_HASH, BaseHash.getBaseHashStr(), initSize); | ||
| } | ||
|
|
||
| String result = sb.length() > 0 ? sb.toString() : null; | ||
| if (result != null) { | ||
| staticCommentCache.putIfAbsent(key, result); | ||
| } | ||
| return result; | ||
| } | ||
|
|
||
| /** Returns true if the current active span has a non-null, non-empty peer service tag. */ | ||
| public static boolean hasPeerService() { | ||
| AgentSpan span = activeSpan(); | ||
| if (span != null) { | ||
| Object peerService = span.getTag(Tags.PEER_SERVICE); | ||
| if (peerService != null) { | ||
| String str = peerService.toString(); | ||
| return str != null && !str.isEmpty(); | ||
| } | ||
| } | ||
| return false; | ||
| } | ||
|
|
||
| private static String getPeerService() { | ||
| AgentSpan span = activeSpan(); | ||
| Object peerService = null; | ||
|
|
@@ -104,4 +205,50 @@ private static void append(StringBuilder sb, String key, String value, int initS | |
| } | ||
| sb.append(key).append(EQUALS).append(QUOTE).append(encodedValue).append(QUOTE); | ||
| } | ||
|
|
||
| /** | ||
| * Cache key for static comment lookup. Uses Config identity (rather than individual field values) | ||
| * to ensure the cache is automatically invalidated if Config is replaced (as happens in tests). | ||
| * In production, Config is created once, so identity comparison is both correct and cheap. | ||
| */ | ||
| private static final class StaticCommentKey { | ||
| private final String dbService; | ||
| private final String hostname; | ||
| private final String dbName; | ||
| private final Config config; | ||
| private final int hashCode; | ||
|
|
||
| StaticCommentKey(String dbService, String hostname, String dbName, Config config) { | ||
| this.dbService = dbService; | ||
| this.hostname = hostname; | ||
| this.dbName = dbName; | ||
| this.config = config; | ||
| int h = 17; | ||
| h = 31 * h + (dbService != null ? dbService.hashCode() : 0); | ||
| h = 31 * h + (hostname != null ? hostname.hashCode() : 0); | ||
| h = 31 * h + (dbName != null ? dbName.hashCode() : 0); | ||
| h = 31 * h + System.identityHashCode(config); | ||
| this.hashCode = h; | ||
| } | ||
|
|
||
| @Override | ||
| public boolean equals(Object o) { | ||
| if (this == o) return true; | ||
| if (!(o instanceof StaticCommentKey)) return false; | ||
| StaticCommentKey that = (StaticCommentKey) o; | ||
| return config == that.config | ||
| && eq(dbService, that.dbService) | ||
| && eq(hostname, that.hostname) | ||
| && eq(dbName, that.dbName); | ||
| } | ||
|
|
||
| private static boolean eq(String a, String b) { | ||
| return a == null ? b == null : a.equals(b); | ||
| } | ||
|
|
||
| @Override | ||
| public int hashCode() { | ||
| return hashCode; | ||
| } | ||
| } | ||
| } | ||
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
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.
Cache doesn't seem worth the trouble given that statements in Java are usually prepared
Let's remove the cache for this initial pull request