From ef3f69451eff64c63322d1de7f8a206efa250bb4 Mon Sep 17 00:00:00 2001 From: Brandon Fergerson Date: Mon, 31 Jan 2022 18:15:10 -0500 Subject: [PATCH 01/12] watch log --- .../sourcemarker/status/LogStatusBar.java | 95 +++++++++++-------- .../command/ControlBarController.kt | 14 ++- .../command/LiveControlCommand.kt | 6 ++ .../sourcemarker/search/SourceMarkSearch.kt | 5 + .../sourcemarker/service/LiveViewManager.kt | 31 ++++-- .../sourcemarker/status/LiveStatusManager.kt | 45 +++++++-- 6 files changed, 142 insertions(+), 54 deletions(-) diff --git a/plugin/src/main/java/spp/jetbrains/sourcemarker/status/LogStatusBar.java b/plugin/src/main/java/spp/jetbrains/sourcemarker/status/LogStatusBar.java index 9773078d1..e58b0587f 100644 --- a/plugin/src/main/java/spp/jetbrains/sourcemarker/status/LogStatusBar.java +++ b/plugin/src/main/java/spp/jetbrains/sourcemarker/status/LogStatusBar.java @@ -13,26 +13,26 @@ import com.intellij.util.ui.ListTableModel; import com.intellij.util.ui.UIUtil; import io.vertx.core.json.Json; +import io.vertx.core.json.JsonObject; import net.miginfocom.swing.MigLayout; import org.jetbrains.annotations.NotNull; import spp.jetbrains.marker.source.mark.inlay.InlayMark; import spp.jetbrains.sourcemarker.PluginIcons; import spp.jetbrains.sourcemarker.PluginUI; -import spp.jetbrains.sourcemarker.service.log.VariableParser; +import spp.jetbrains.sourcemarker.SourceMarkerPlugin; import spp.jetbrains.sourcemarker.command.AutocompleteFieldRow; import spp.jetbrains.sourcemarker.mark.SourceMarkKeys; import spp.jetbrains.sourcemarker.service.InstrumentEventListener; import spp.jetbrains.sourcemarker.service.log.LogHitColumnInfo; +import spp.jetbrains.sourcemarker.service.log.VariableParser; import spp.jetbrains.sourcemarker.settings.LiveLogConfigurationPanel; import spp.jetbrains.sourcemarker.status.util.AutocompleteField; import spp.protocol.SourceMarkerServices; import spp.protocol.artifact.log.Log; -import spp.protocol.instrument.InstrumentThrottle; -import spp.protocol.instrument.LiveInstrument; -import spp.protocol.instrument.LiveInstrumentEvent; -import spp.protocol.instrument.LiveSourceLocation; -import spp.protocol.instrument.ThrottleStep; +import spp.protocol.artifact.log.LogResult; +import spp.protocol.instrument.*; import spp.protocol.instrument.log.LiveLog; +import spp.protocol.instrument.log.event.LiveLogHit; import spp.protocol.instrument.log.event.LiveLogRemoved; import spp.protocol.service.live.LiveInstrumentService; @@ -43,15 +43,7 @@ import javax.swing.event.DocumentEvent; import javax.swing.text.StyleContext; import java.awt.*; -import java.awt.event.ComponentEvent; -import java.awt.event.FocusAdapter; -import java.awt.event.FocusEvent; -import java.awt.event.KeyAdapter; -import java.awt.event.KeyEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; +import java.awt.event.*; import java.time.Instant; import java.time.ZoneId; import java.time.format.DateTimeFormatter; @@ -67,16 +59,9 @@ import java.util.stream.Collectors; import static spp.jetbrains.marker.SourceMarker.conditionParser; -import static spp.jetbrains.sourcemarker.PluginUI.BGND_FOCUS_COLOR; -import static spp.jetbrains.sourcemarker.PluginUI.CNFG_PANEL_BGND_COLOR; -import static spp.jetbrains.sourcemarker.PluginUI.CNFG_PANEL_FOCUS_COLOR; -import static spp.jetbrains.sourcemarker.PluginUI.COMPLETE_COLOR_PURPLE; -import static spp.jetbrains.sourcemarker.PluginUI.ROBOTO_LIGHT_PLAIN_14; -import static spp.jetbrains.sourcemarker.PluginUI.ROBOTO_LIGHT_PLAIN_17; -import static spp.jetbrains.sourcemarker.PluginUI.SELECT_COLOR_RED; -import static spp.jetbrains.sourcemarker.PluginUI.STATUS_BAR_TXT_BG_COLOR; -import static spp.jetbrains.sourcemarker.PluginUI.DFLT_BGND_COLOR; +import static spp.jetbrains.sourcemarker.PluginUI.*; import static spp.jetbrains.sourcemarker.status.util.ViewUtils.addRecursiveMouseListener; +import static spp.protocol.ProtocolAddress.Global.ArtifactLogUpdated; import static spp.protocol.instrument.LiveInstrumentEventType.LOG_HIT; import static spp.protocol.instrument.LiveInstrumentEventType.LOG_REMOVED; @@ -94,6 +79,7 @@ public class LogStatusBar extends JPanel implements StatusBar, VisibleAreaListen private final List scopeVars; private final Function> lookup; private final String placeHolderText; + private final boolean watchExpression; private EditorImpl editor; private LiveLog liveLog; private Instant latestTime; @@ -116,7 +102,8 @@ public class LogStatusBar extends JPanel implements StatusBar, VisibleAreaListen new ArrayList<>(), 0, SortOrder.DESCENDING); private final Pair patternPair; - public LogStatusBar(LiveSourceLocation sourceLocation, List scopeVars, InlayMark inlayMark) { + public LogStatusBar(LiveSourceLocation sourceLocation, List scopeVars, InlayMark inlayMark, + boolean watchExpression) { this.sourceLocation = sourceLocation; this.scopeVars = scopeVars.stream().map(it -> new AutocompleteFieldRow() { public String getText() { @@ -152,16 +139,49 @@ public Icon getIcon() { patternPair = VariableParser.createPattern(scopeVars); this.inlayMark = inlayMark; + this.watchExpression = watchExpression; - placeHolderText = "Input log message (use $ for variables)"; + if (watchExpression) { + placeHolderText = WAITING_FOR_LIVE_LOG_DATA; + } else { + placeHolderText = "Input log message (use $ for variables)"; + } initComponents(); setupComponents(); - showEditableMode(); - liveLogTextField.setEditMode(true); - - liveLogTextField.addSaveListener(this::saveLiveLog); + if (watchExpression) { + liveLogTextField.setCanShowSaveButton(false); + liveLogTextField.setEditMode(false); + removeActiveDecorations(); + configDropdownLabel.setVisible(false); + displayTimeField(); + addExpandButton(); + + SourceMarkerPlugin.INSTANCE.getVertx().eventBus().consumer(ArtifactLogUpdated, event -> { + LogResult logResult = (LogResult) event.body(); + Log latestLog = logResult.getLogs().get(0); + setLatestLog(Instant.now(), latestLog); + + JsonObject logJson = JsonObject.mapFrom(new LiveLogHit( + "-1", kotlinx.datetime.Instant.Companion.now(), "null", "null", logResult + )); + logJson.getJsonObject("logResult").getJsonArray("logs").forEach(it -> { + JsonObject log = (JsonObject) it; + log.remove("formattedMessage"); + }); + + LiveInstrumentEvent liveInstrumentEvent = new LiveInstrumentEvent( + LOG_HIT, + logJson.toString() + ); + commandModel.insertRow(0, liveInstrumentEvent); + }); + } else { + showEditableMode(); + liveLogTextField.setEditMode(true); + liveLogTextField.addSaveListener(this::saveLiveLog); + } } public void setLiveInstrument(LiveInstrument liveInstrument) { @@ -173,7 +193,7 @@ public void setLiveInstrument(LiveInstrument liveInstrument) { displayTimeField(); addExpandButton(); repaint(); - LiveStatusManager.INSTANCE.addStatusBar(inlayMark,this); + LiveStatusManager.INSTANCE.addStatusBar(inlayMark, this); } public void setWrapperPanel(JPanel wrapperPanel) { @@ -183,14 +203,14 @@ public void setWrapperPanel(JPanel wrapperPanel) { @Override public void visibleAreaChanged(@NotNull VisibleAreaEvent e) { liveLogTextField.hideAutocompletePopup(); - if(popup != null) { + if (popup != null) { popup.dispose(); popup = null; } } public void setLatestLog(Instant time, Log latestLog) { - if (liveLog == null) return; + if (liveLog == null && !watchExpression) return; this.latestTime = time; this.latestLog = latestLog; @@ -393,7 +413,7 @@ public void keyTyped(KeyEvent e) { liveLogTextField.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { - if (errored || liveLogTextField.getEditMode()) return; + if (watchExpression || errored || liveLogTextField.getEditMode()) return; liveLogTextField.setEditMode(true); if (liveLog != null) { @@ -434,7 +454,7 @@ public void mouseClicked(MouseEvent e) { @Override public void mouseEntered(MouseEvent mouseEvent) { - if (!errored && !removed) showEditableMode(); + if (!watchExpression && !errored && !removed) showEditableMode(); } @Override @@ -483,7 +503,7 @@ public void mouseReleased(MouseEvent e) { configPanel.addMouseMotionListener(new MouseAdapter() { @Override public void mouseMoved(MouseEvent e) { - if (!errored && !removed) configPanel.setBackground(CNFG_PANEL_FOCUS_COLOR); + if (!watchExpression && !errored && !removed) configPanel.setBackground(CNFG_PANEL_FOCUS_COLOR); } }); @@ -491,7 +511,8 @@ public void mouseMoved(MouseEvent e) { addRecursiveMouseListener(configPanel, new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { - if (!errored && !removed && System.currentTimeMillis() - popupLastOpened.get() > 200) { + if (!watchExpression && !errored && !removed + && System.currentTimeMillis() - popupLastOpened.get() > 200) { ApplicationManager.getApplication().runWriteAction(() -> showConfigurationPopup(popupLastOpened)); } } diff --git a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/command/ControlBarController.kt b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/command/ControlBarController.kt index 7dc1ebdea..7821bf44e 100644 --- a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/command/ControlBarController.kt +++ b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/command/ControlBarController.kt @@ -65,7 +65,7 @@ object ControlBarController { LiveControlCommand.values().toList().filter { @Suppress("UselessCallOnCollection") //unknown enums are null selfInfo.permissions.filterNotNull().map { it.name }.contains(it.name) - } + } + listOf(WATCH_LOG) } } @@ -75,6 +75,16 @@ object ControlBarController { VIEW_ACTIVITY.command -> handleViewPortalCommand(editor, VIEW_ACTIVITY) VIEW_TRACES.command -> handleViewPortalCommand(editor, VIEW_TRACES) VIEW_LOGS.command -> handleViewPortalCommand(editor, VIEW_LOGS) + WATCH_LOG.command -> { + //replace command inlay with log status inlay + val prevCommandBar = previousControlBar!! + previousControlBar!!.dispose() + previousControlBar = null + + ApplicationManager.getApplication().runWriteAction { + LiveStatusManager.showLogStatusBar(editor, prevCommandBar.lineNumber, true) + } + } ADD_LIVE_BREAKPOINT.command -> { //replace command inlay with breakpoint status inlay val prevCommandBar = previousControlBar!! @@ -92,7 +102,7 @@ object ControlBarController { previousControlBar = null ApplicationManager.getApplication().runWriteAction { - LiveStatusManager.showLogStatusBar(editor, prevCommandBar.lineNumber) + LiveStatusManager.showLogStatusBar(editor, prevCommandBar.lineNumber, false) } } ADD_LIVE_METER.command -> { diff --git a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/command/LiveControlCommand.kt b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/command/LiveControlCommand.kt index 70682babf..143346ee3 100644 --- a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/command/LiveControlCommand.kt +++ b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/command/LiveControlCommand.kt @@ -52,6 +52,12 @@ enum class LiveControlCommand( PluginIcons.Command.viewLogsSelected, PluginIcons.Command.viewLogsUnSelected ), + WATCH_LOG( + "Watch Log", + "Live View ➛ Log ➛ Scope: Expression", + PluginIcons.Command.viewLogsSelected, + PluginIcons.Command.viewLogsUnSelected + ), WATCH_VARIABLE( "watch", "Manual Tracing ➛ Watched Variables ➛ Scope: Local / Add *variable* to watched variables" diff --git a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/search/SourceMarkSearch.kt b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/search/SourceMarkSearch.kt index ca5f36334..32cce5cf2 100644 --- a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/search/SourceMarkSearch.kt +++ b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/search/SourceMarkSearch.kt @@ -74,6 +74,7 @@ object SourceMarkSearch { return when (artifact.type) { ArtifactType.ENDPOINT -> findEndpointSourceMark(artifact) ArtifactType.STATEMENT -> findExpressionAdvice(artifact) + ArtifactType.EXPRESSION -> findExpressionAdvice(artifact) else -> TODO("impl") } } @@ -121,6 +122,10 @@ object SourceMarkSearch { } private fun findExpressionAdvice(artifact: ArtifactQualifiedName): ExpressionSourceMark? { + if (artifact.type == ArtifactType.EXPRESSION) { + return SourceMarker.getSourceMarks().find { it.artifactQualifiedName == artifact } as ExpressionSourceMark? + } + val qualifiedClassName = artifact.identifier.substring(0, artifact.identifier.lastIndexOf(".")) val fileMarker = SourceMarker.getSourceFileMarker(qualifiedClassName) return if (fileMarker != null) { diff --git a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/service/LiveViewManager.kt b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/service/LiveViewManager.kt index 6dd1af2d7..5e4e56c69 100644 --- a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/service/LiveViewManager.kt +++ b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/service/LiveViewManager.kt @@ -30,6 +30,7 @@ import kotlinx.coroutines.launch import kotlinx.datetime.toJavaInstant import kotlinx.datetime.toKotlinInstant import org.slf4j.LoggerFactory +import spp.jetbrains.marker.SourceMarker import spp.jetbrains.marker.source.mark.api.SourceMark import spp.jetbrains.portal.SourcePortal import spp.jetbrains.sourcemarker.discover.TCPServiceDiscoveryBackend @@ -41,6 +42,7 @@ import spp.protocol.ProtocolAddress.Global.ArtifactMetricsUpdated import spp.protocol.ProtocolAddress.Global.ArtifactTracesUpdated import spp.protocol.ProtocolAddress.Global.TraceSpanUpdated import spp.protocol.SourceMarkerServices.Provide +import spp.protocol.artifact.ArtifactType import spp.protocol.artifact.QueryTimeFrame import spp.protocol.artifact.log.Log import spp.protocol.artifact.log.LogOrderType @@ -81,6 +83,10 @@ class LiveViewManager(val markerConfig: SourceMarkerConfig) : CoroutineVerticle( vertx.eventBus().consumer("local." + Provide.LIVE_VIEW_SUBSCRIBER + "." + developer) { val event = Json.decodeValue(it.body().toString(), LiveViewEvent::class.java) if (log.isTraceEnabled) log.trace("Received live event: {}", event) + if (!SourceMarker.enabled) { + log.warn("SourceMarker is not enabled, ignoring live event: {}", event) + return@consumer + } when (event.viewConfig.viewName) { "LIVE_METER" -> GlobalScope.launch(vertx.dispatcher()) { consumeLiveMeterEvent(event) } @@ -141,16 +147,23 @@ class LiveViewManager(val markerConfig: SourceMarkerConfig) : CoroutineVerticle( Int.MAX_VALUE ) - for ((content, logs) in logsResult.logs.groupBy { it.content }) { - SourceMarkSearch.findInheritedSourceMarks(content).forEach { - vertx.eventBus().send( - ProtocolAddress.Global.ArtifactLogUpdated, - logsResult.copy( - artifactQualifiedName = it.artifactQualifiedName, - total = logs.size, - logs = logs, + if (event.artifactQualifiedName.type == ArtifactType.EXPRESSION) { + val expressionMark = SourceMarkSearch.findSourceMark(event.artifactQualifiedName) + if (expressionMark != null) { + vertx.eventBus().send(ProtocolAddress.Global.ArtifactLogUpdated, logsResult) + } + } else { + for ((content, logs) in logsResult.logs.groupBy { it.content }) { + SourceMarkSearch.findInheritedSourceMarks(content).forEach { + vertx.eventBus().send( + ProtocolAddress.Global.ArtifactLogUpdated, + logsResult.copy( + artifactQualifiedName = it.artifactQualifiedName, + total = logs.size, + logs = logs, + ) ) - ) + } } } } diff --git a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/status/LiveStatusManager.kt b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/status/LiveStatusManager.kt index 2f12a4b27..3e4cf4ec7 100644 --- a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/status/LiveStatusManager.kt +++ b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/status/LiveStatusManager.kt @@ -165,7 +165,7 @@ object LiveStatusManager : SourceMarkEventListener { /** * Invoked via control bar. Force visible. */ - fun showLogStatusBar(editor: Editor, lineNumber: Int) { + fun showLogStatusBar(editor: Editor, lineNumber: Int, watchExpression: Boolean) { val fileMarker = PsiDocumentManager.getInstance(editor.project!!).getPsiFile(editor.document)!! .getUserData(SourceFileMarker.KEY) if (fileMarker == null) { @@ -178,17 +178,47 @@ object LiveStatusManager : SourceMarkEventListener { val wrapperPanel = JPanel() wrapperPanel.layout = BorderLayout() + if (watchExpression) { + SourceMarkerServices.Instance.liveView!!.addLiveViewSubscription( + LiveViewSubscription( + null, + listOf("Getting user list"), + ArtifactQualifiedName( + inlayMark.artifactQualifiedName.identifier, + lineNumber = inlayMark.artifactQualifiedName.lineNumber, + type = ArtifactType.EXPRESSION + ), + LiveSourceLocation( + inlayMark.artifactQualifiedName.identifier, + line = inlayMark.artifactQualifiedName.lineNumber!! + ), + LiveViewConfig( + "LOGS", + true, + listOf("endpoint_logs"), + 0 + ) + ) + ) { + if (it.failed()) { + log.error("Failed to add live view subscription", it.cause()) + } + } + } + val config = Json.decodeValue( PropertiesComponent.getInstance(editor.project!!).getValue("sourcemarker_plugin_config"), SourceMarkerConfig::class.java ) val statusBar = LogStatusBar( LiveSourceLocation( - namingService.getClassQualifiedNames(fileMarker.psiFile)[0].identifier, lineNumber, + namingService.getClassQualifiedNames(fileMarker.psiFile)[0].identifier, + lineNumber, service = config.serviceName ), - scopeService.getScopeVariables(fileMarker, lineNumber), - inlayMark + if (watchExpression) emptyList() else scopeService.getScopeVariables(fileMarker, lineNumber), + inlayMark, + watchExpression ) inlayMark.putUserData(SourceMarkKeys.STATUS_BAR, statusBar) statusBar.setWrapperPanel(wrapperPanel) @@ -214,7 +244,9 @@ object LiveStatusManager : SourceMarkEventListener { ) } - statusBar.focus() + if (!watchExpression) { + statusBar.focus() + } } } @@ -363,7 +395,8 @@ object LiveStatusManager : SourceMarkEventListener { val statusBar = LogStatusBar( liveLog.location, emptyList(), - inlayMark + inlayMark, + false ) inlayMark.putUserData(SourceMarkKeys.STATUS_BAR, statusBar) statusBar.setWrapperPanel(wrapperPanel) From 759a77eff1ea1f262d4d39e2c9bd8b6559e17c62 Mon Sep 17 00:00:00 2001 From: Brandon Fergerson Date: Mon, 31 Jan 2022 18:49:45 -0500 Subject: [PATCH 02/12] unused --- .../marker/jvm/psi/PluginSqlProducerSearch.kt | 136 ------------------ .../jvm/psi/sqlsource/SpringDataSqlSource.kt | 76 ---------- .../sourcemarker/SourceMarkerPlugin.kt | 16 --- .../discover/TCPServiceDiscoveryBackend.kt | 1 - .../main/resources/plugin-configuration.json | 1 - 5 files changed, 230 deletions(-) delete mode 100644 marker/jvm-marker/src/main/kotlin/spp/jetbrains/marker/jvm/psi/PluginSqlProducerSearch.kt delete mode 100644 marker/jvm-marker/src/main/kotlin/spp/jetbrains/marker/jvm/psi/sqlsource/SpringDataSqlSource.kt diff --git a/marker/jvm-marker/src/main/kotlin/spp/jetbrains/marker/jvm/psi/PluginSqlProducerSearch.kt b/marker/jvm-marker/src/main/kotlin/spp/jetbrains/marker/jvm/psi/PluginSqlProducerSearch.kt deleted file mode 100644 index 50904504c..000000000 --- a/marker/jvm-marker/src/main/kotlin/spp/jetbrains/marker/jvm/psi/PluginSqlProducerSearch.kt +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Source++, the open-source live coding platform. - * Copyright (C) 2022 CodeBrig, Inc. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package spp.jetbrains.marker.jvm.psi - -import com.intellij.openapi.application.ApplicationManager -import com.intellij.psi.PsiMethod -import com.intellij.psi.impl.compiled.ClsMethodImpl -import com.intellij.psi.search.searches.OverridingMethodsSearch -import spp.jetbrains.marker.jvm.ArtifactSearch -import spp.jetbrains.marker.source.JVMMarkerUtils -import spp.protocol.artifact.ArtifactQualifiedName -import spp.protocol.artifact.ArtifactType -import spp.protocol.extend.SqlProducerSearch -import spp.jetbrains.marker.jvm.psi.sqlsource.SpringDataSqlSource -import io.vertx.core.Promise -import io.vertx.core.Vertx -import io.vertx.kotlin.coroutines.await -import io.vertx.kotlin.coroutines.dispatcher -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import org.jetbrains.uast.UCallExpression -import org.jetbrains.uast.UMethod -import org.jetbrains.uast.toUElementOfType -import org.jetbrains.uast.visitor.AbstractUastVisitor -import org.jooq.Query -import org.slf4j.LoggerFactory -import java.util.* - -/** - * todo: description. - * - * @since 0.1.0 - * @author [Brandon Fergerson](mailto:bfergerson@apache.org) - */ -class PluginSqlProducerSearch(val vertx: Vertx) : SqlProducerSearch { - - companion object { - private val log = LoggerFactory.getLogger(PluginSqlProducerSearch::class.java) - } - - private val detectorSet = setOf( - SpringDataSqlSource() - ) - - val possibleRegressionSources = mutableListOf() - - override suspend fun determineSource( - query: Query, - searchPoint: ArtifactQualifiedName - ): Optional { - val promise = Promise.promise>() - val searchArtifact = ArtifactSearch.findArtifact(vertx ,searchPoint) - if (searchArtifact == null) { - promise.fail("Could not determine search point artifact") - return promise.future().await() - } - - ApplicationManager.getApplication().runReadAction { - dependencySearch(searchArtifact.toUElementOfType()!!) - - GlobalScope.launch(vertx.dispatcher()) { - var keepSearching = true - for (method in possibleRegressionSources) { //todo: fix dupes - for (detector in detectorSet) { - try { - if (detector.isSqlSource(query, method)) { - promise.complete(Optional.of(JVMMarkerUtils.getFullyQualifiedName(method.method))) - keepSearching = false - } - } catch (throwable: Throwable) { - promise.fail(throwable) - } - if (!keepSearching) break - } - if (!keepSearching) break - } - promise.tryComplete(Optional.empty()) - } - } - return promise.future().await() - } - - private fun dependencySearch(method: UMethod) { - method.accept(object : AbstractUastVisitor() { - override fun visitCallExpression(node: UCallExpression): Boolean { - val calledMethod = node.resolve() - if (calledMethod != null) { - if (calledMethod.body == null) { - possibleRegressionSources.add(CalledMethod(node, calledMethod)) - - if (calledMethod !is ClsMethodImpl) { - //interface/abstract method; search implementations - val implMethods = OverridingMethodsSearch.search(calledMethod).toList() - implMethods.forEach { - dependencySearch(it.toUElementOfType()!!) - } - } - } - } else { - log.warn("Failed to resolve: $node") - } - return super.visitCallExpression(node) - } - }) - } - - /** - * todo: description. - */ - interface SqlSourceDeterminer { - fun isSqlSource(query: Query, calledMethod: CalledMethod): Boolean - } - - /** - * todo: description. - */ - data class CalledMethod( - val call: UCallExpression, - val method: PsiMethod - ) -} diff --git a/marker/jvm-marker/src/main/kotlin/spp/jetbrains/marker/jvm/psi/sqlsource/SpringDataSqlSource.kt b/marker/jvm-marker/src/main/kotlin/spp/jetbrains/marker/jvm/psi/sqlsource/SpringDataSqlSource.kt deleted file mode 100644 index 9233d5d26..000000000 --- a/marker/jvm-marker/src/main/kotlin/spp/jetbrains/marker/jvm/psi/sqlsource/SpringDataSqlSource.kt +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Source++, the open-source live coding platform. - * Copyright (C) 2022 CodeBrig, Inc. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package spp.jetbrains.marker.jvm.psi.sqlsource - -import com.intellij.psi.impl.compiled.ClsMethodImpl -import com.intellij.psi.util.PsiUtil -import spp.jetbrains.marker.jvm.psi.PluginSqlProducerSearch -import spp.jetbrains.marker.jvm.psi.PluginSqlProducerSearch.CalledMethod -import org.jooq.Query - -/** - * todo: description. - * - * @since 0.1.0 - * @author [Brandon Fergerson](mailto:bfergerson@apache.org) - */ -class SpringDataSqlSource : PluginSqlProducerSearch.SqlSourceDeterminer { - - private val findAll = "org.springframework.data.repository.CrudRepository.findAll" - - override fun isSqlSource(query: Query, calledMethod: CalledMethod): Boolean { - if (calledMethod.method is ClsMethodImpl) { - if (PsiUtil.getMemberQualifiedName(calledMethod.method) == findAll) { - //todo: more strict verification - //java.lang.Iterable - val iterableType = calledMethod.call.returnType!!.canonicalText - val queryType = iterableType.substring(0, iterableType.length - 1) - .replace("java.lang.Iterable<", "") - var tableName = queryType - if (tableName.contains(".")) { - tableName = tableName.substring(tableName.lastIndexOf(".") + 1).toUpperCase() - } - val tableNames = query.tableNames() - if (tableNames.size == 1) { - return tableNames[0] == tableName - } - return false - } else { - return false - } - } else { - return false - } - } - - //todo: remove when jooq offers public access to parsed queries - private fun Query.tableNames(): List { - val fromField = javaClass.getDeclaredField("from") - fromField.isAccessible = true - val fromTables = fromField.get(this) as List<*> - return fromTables.map { - val aliasField = it!!.javaClass.getDeclaredField("alias") - aliasField.isAccessible = true - val alias = aliasField.get(it) - val wrappedField = alias.javaClass.getDeclaredField("wrapped") - wrappedField.isAccessible = true - val wrapped = wrappedField.get(alias) - wrapped.toString() - } - } -} diff --git a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/SourceMarkerPlugin.kt b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/SourceMarkerPlugin.kt index 5e256eaa0..6b1115902 100644 --- a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/SourceMarkerPlugin.kt +++ b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/SourceMarkerPlugin.kt @@ -110,7 +110,6 @@ import spp.protocol.service.LiveService import spp.protocol.service.live.LiveInstrumentService import spp.protocol.service.live.LiveViewService import spp.protocol.service.logging.LogCountIndicatorService -import spp.protocol.service.tracing.LocalTracingService import spp.protocol.util.KSerializers import spp.protocol.util.LocalMessageCodec import java.awt.Color @@ -374,21 +373,6 @@ object SourceMarkerPlugin { log.info("Live views disabled") } - //local tracing - if (hardcodedConfig.getJsonObject("services").getBoolean("local_tracing")) { - if (availableRecords.any { it.name == SourceMarkerServices.Utilize.LOCAL_TRACING }) { - log.info("Local tracing available") - Instance.localTracing = ServiceProxyBuilder(vertx) - .apply { config.serviceToken?.let { setToken(it) } } - .setAddress(SourceMarkerServices.Utilize.LOCAL_TRACING) - .build(LocalTracingService::class.java) - } else { - log.warn("Local tracing unavailable") - } - } else { - log.info("Local tracing disabled") - } - //log count indicator if (hardcodedConfig.getJsonObject("services").getBoolean("log_count_indicator")) { if (availableRecords.any { it.name == SourceMarkerServices.Utilize.LOG_COUNT_INDICATOR }) { diff --git a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/discover/TCPServiceDiscoveryBackend.kt b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/discover/TCPServiceDiscoveryBackend.kt index 77accb813..c63aec091 100644 --- a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/discover/TCPServiceDiscoveryBackend.kt +++ b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/discover/TCPServiceDiscoveryBackend.kt @@ -123,7 +123,6 @@ class TCPServiceDiscoveryBackend : ServiceDiscoveryBackend { setupHandler(vertx, Utilize.LIVE_SERVICE) setupHandler(vertx, Utilize.LIVE_INSTRUMENT) setupHandler(vertx, Utilize.LIVE_VIEW) - setupHandler(vertx, Utilize.LOCAL_TRACING) setupHandler(vertx, Utilize.LOG_COUNT_INDICATOR) //setup connection diff --git a/plugin/src/main/resources/plugin-configuration.json b/plugin/src/main/resources/plugin-configuration.json index 6bf445836..b736dabda 100644 --- a/plugin/src/main/resources/plugin-configuration.json +++ b/plugin/src/main/resources/plugin-configuration.json @@ -6,7 +6,6 @@ "service_port": 5445, "tcp_service_port": 5455, "services": { - "local_tracing": false, "log_count_indicator": false, "live_instrument": true, "live_view": true From 3892b40bd64ba92ca587ba07f177d6cd63836155 Mon Sep 17 00:00:00 2001 From: Brandon Fergerson Date: Mon, 31 Jan 2022 19:03:50 -0500 Subject: [PATCH 03/12] refactor --- .../listeners/PortalEventListener.kt | 53 ++----------------- .../sourcemarker/status/LiveStatusManager.kt | 14 +---- .../jetbrains/StandaloneActivityLiveView.kt | 7 +-- 3 files changed, 6 insertions(+), 68 deletions(-) diff --git a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/listeners/PortalEventListener.kt b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/listeners/PortalEventListener.kt index dd59396a6..7e29647cd 100644 --- a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/listeners/PortalEventListener.kt +++ b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/listeners/PortalEventListener.kt @@ -25,7 +25,6 @@ import com.intellij.psi.PsiNameIdentifierOwner import com.intellij.util.PsiNavigateUtil import io.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND import io.vertx.core.eventbus.ReplyException -import io.vertx.core.eventbus.ReplyFailure import io.vertx.core.json.Json import io.vertx.core.json.JsonObject import io.vertx.kotlin.coroutines.CoroutineVerticle @@ -33,7 +32,6 @@ import io.vertx.kotlin.coroutines.dispatcher import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.datetime.Instant -import kotlinx.datetime.toKotlinInstant import org.slf4j.LoggerFactory import spp.jetbrains.marker.SourceMarker import spp.jetbrains.marker.SourceMarker.creationService @@ -92,7 +90,6 @@ import spp.protocol.artifact.metrics.ArtifactSummarizedResult import spp.protocol.artifact.metrics.MetricType import spp.protocol.artifact.trace.TraceResult import spp.protocol.artifact.trace.TraceSpan -import spp.protocol.error.AccessDenied import spp.protocol.instrument.LiveSourceLocation import spp.protocol.portal.PageType import spp.protocol.utils.ArtifactNameUtils @@ -284,12 +281,7 @@ class PortalEventListener( listOf(endpointName), portal.viewingArtifact, LiveSourceLocation(portal.viewingArtifact.identifier, 0), //todo: fix - LiveViewConfig( - "ACTIVITY", - false, - listOf("endpoint_cpm", "endpoint_avg", "endpoint_sla"), - 0 - ) + LiveViewConfig("ACTIVITY", listOf("endpoint_cpm", "endpoint_avg", "endpoint_sla")) ) ) { if (it.failed()) { @@ -328,12 +320,7 @@ class PortalEventListener( listOf(endpointName), portal.viewingArtifact, LiveSourceLocation(portal.viewingArtifact.identifier, 0), //todo: fix - LiveViewConfig( - "TRACES", - false, - listOf("endpoint_traces"), - 0 - ) + LiveViewConfig("TRACES", listOf("endpoint_traces")) ) ) { if (it.failed()) { @@ -382,12 +369,7 @@ class PortalEventListener( logPatterns, portal.viewingArtifact, LiveSourceLocation(portal.viewingArtifact.identifier, 0), //todo: fix - LiveViewConfig( - "LOGS", - false, - listOf("endpoint_logs"), - 0 - ) + LiveViewConfig("LOGS", listOf("endpoint_logs")) ) ) { if (it.failed()) { @@ -467,33 +449,6 @@ class PortalEventListener( handleTraceResult(traceResult, portal, portal.viewingArtifact) } - } else if (Instance.localTracing != null) { - portal.tracesView.localTracing = true - Instance.localTracing!!.getTraceResult( - artifactQualifiedName = portal.viewingArtifact, - start = ZonedDateTime.now().minusHours(24).toInstant().toKotlinInstant(), - stop = ZonedDateTime.now().toInstant().toKotlinInstant(), - orderType = portal.tracesView.orderType, - pageSize = portal.tracesView.viewTraceAmount, - pageNumber = portal.tracesView.pageNumber, - ) { - if (it.succeeded()) { - handleTraceResult(it.result(), portal, portal.viewingArtifact) - } else { - val replyException = it.cause() as ReplyException - if (replyException.failureType() == ReplyFailure.TIMEOUT) { - log.warn("Timed out getting local trace results") - } else { - val actualException = replyException.cause!! - if (actualException is AccessDenied) { - log.error("Access denied. Reason: " + actualException.reason) - } else { - it.cause().printStackTrace() - log.error("Failed to get local trace results", it.cause()) - } - } - } - } } } } @@ -679,8 +634,6 @@ class PortalEventListener( portal.configuration.visibleActivity = true portal.configuration.visibleTraces = true portal.configuration.visibleLogs = true //todo: can hide based on if there is logs - } else if (Instance.localTracing != null) { - portal.configuration.visibleTraces = true } else { //non-endpoint artifact; hide activity/traces till manually shown portal.configuration.visibleActivity = false diff --git a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/status/LiveStatusManager.kt b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/status/LiveStatusManager.kt index 3e4cf4ec7..942474cd5 100644 --- a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/status/LiveStatusManager.kt +++ b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/status/LiveStatusManager.kt @@ -192,12 +192,7 @@ object LiveStatusManager : SourceMarkEventListener { inlayMark.artifactQualifiedName.identifier, line = inlayMark.artifactQualifiedName.lineNumber!! ), - LiveViewConfig( - "LOGS", - true, - listOf("endpoint_logs"), - 0 - ) + LiveViewConfig("LOGS", listOf("endpoint_logs")) ) ) { if (it.failed()) { @@ -439,12 +434,7 @@ object LiveStatusManager : SourceMarkEventListener { listOf(liveMeter.toMetricId()), ArtifactQualifiedName(liveMeter.location.source, type = ArtifactType.EXPRESSION), liveMeter.location, - LiveViewConfig( - "LIVE_METER", - true, - listOf("last_minute", "last_hour", "last_day"), - 0 - ) + LiveViewConfig("LIVE_METER", listOf("last_minute", "last_hour", "last_day")) ) ) { if (it.failed()) { diff --git a/plugin/src/test/kotlin/spp/jetbrains/StandaloneActivityLiveView.kt b/plugin/src/test/kotlin/spp/jetbrains/StandaloneActivityLiveView.kt index f41484b90..d3b82952a 100644 --- a/plugin/src/test/kotlin/spp/jetbrains/StandaloneActivityLiveView.kt +++ b/plugin/src/test/kotlin/spp/jetbrains/StandaloneActivityLiveView.kt @@ -151,12 +151,7 @@ class StandaloneActivityLiveView : LightJavaCodeInsightFixtureTestCase() { listOf(endpointName), sourceMark.artifactQualifiedName, LiveSourceLocation(sourceMark.artifactQualifiedName.identifier, -1), - LiveViewConfig( - "ACTIVITY", - false, - listOf("endpoint_cpm", "endpoint_avg", "endpoint_sla"), - refreshRateLimit = 0 - ) + LiveViewConfig("ACTIVITY", listOf("endpoint_cpm", "endpoint_avg", "endpoint_sla")) ) ) { if (it.succeeded()) { From 15a56c711a495030389d52ee46d97b042ac4b408 Mon Sep 17 00:00:00 2001 From: Brandon Fergerson Date: Mon, 31 Jan 2022 19:08:21 -0500 Subject: [PATCH 04/12] refactor --- .../java/spp/jetbrains/sourcemarker/status/LogStatusBar.java | 2 +- .../spp/jetbrains/sourcemarker/service/log/LogHitColumnInfo.kt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/plugin/src/main/java/spp/jetbrains/sourcemarker/status/LogStatusBar.java b/plugin/src/main/java/spp/jetbrains/sourcemarker/status/LogStatusBar.java index e58b0587f..40b1f1a91 100644 --- a/plugin/src/main/java/spp/jetbrains/sourcemarker/status/LogStatusBar.java +++ b/plugin/src/main/java/spp/jetbrains/sourcemarker/status/LogStatusBar.java @@ -215,7 +215,7 @@ public void setLatestLog(Instant time, Log latestLog) { this.latestLog = latestLog; String formattedTime = time.atZone(ZoneId.systemDefault()).format(TIME_FORMATTER); - String formattedMessage = latestLog.getFormattedMessage(); + String formattedMessage = latestLog.toFormattedMessage(); if (!timeLabel.getText().equals(formattedTime) || !liveLogTextField.getText().equals(formattedMessage)) { SwingUtilities.invokeLater(() -> { if (liveLogTextField.getEditMode()) { diff --git a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/service/log/LogHitColumnInfo.kt b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/service/log/LogHitColumnInfo.kt index 8a2f4c129..4280952bb 100644 --- a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/service/log/LogHitColumnInfo.kt +++ b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/service/log/LogHitColumnInfo.kt @@ -62,7 +62,7 @@ class LogHitColumnInfo(name: String) : ColumnInfo(n if (event.eventType == LiveInstrumentEventType.LOG_HIT) { val item = Json.decodeValue(event.data, LiveLogHit::class.java) return when (name) { - "Message" -> item.logResult.logs.first().getFormattedMessage() + "Message" -> item.logResult.logs.first().toFormattedMessage() "Time" -> (Clock.System.now().toEpochMilliseconds() - item.occurredAt.toEpochMilliseconds()) .toPrettyDuration() + " " + message("ago") From 5cc74c3fd82de85be4bd690b989533f606531ff1 Mon Sep 17 00:00:00 2001 From: Brandon Fergerson Date: Mon, 31 Jan 2022 19:40:01 -0500 Subject: [PATCH 05/12] moved portal only code to portal --- .../skywalking/SkywalkingExtensions.kt | 1 - .../listeners/ArtifactAdviceListener.kt | 123 ------------------ .../sourcemarker/mark/SourceMarkKeys.kt | 2 - 3 files changed, 126 deletions(-) delete mode 100644 plugin/src/main/kotlin/spp/jetbrains/sourcemarker/listeners/ArtifactAdviceListener.kt diff --git a/monitor/src/main/kotlin/spp/jetbrains/monitor/skywalking/SkywalkingExtensions.kt b/monitor/src/main/kotlin/spp/jetbrains/monitor/skywalking/SkywalkingExtensions.kt index 5f23fdbbc..e94cec454 100644 --- a/monitor/src/main/kotlin/spp/jetbrains/monitor/skywalking/SkywalkingExtensions.kt +++ b/monitor/src/main/kotlin/spp/jetbrains/monitor/skywalking/SkywalkingExtensions.kt @@ -31,7 +31,6 @@ import monitor.skywalking.protocol.trace.QueryTraceQuery import monitor.skywalking.protocol.type.QueryOrder import monitor.skywalking.protocol.type.TraceState import spp.protocol.artifact.ArtifactQualifiedName -import java.math.BigDecimal fun toProtocol( artifactQualifiedName: ArtifactQualifiedName, diff --git a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/listeners/ArtifactAdviceListener.kt b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/listeners/ArtifactAdviceListener.kt deleted file mode 100644 index 99eda0ff4..000000000 --- a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/listeners/ArtifactAdviceListener.kt +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Source++, the open-source live coding platform. - * Copyright (C) 2022 CodeBrig, Inc. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package spp.jetbrains.sourcemarker.listeners - -import com.intellij.openapi.application.ApplicationManager -import spp.jetbrains.marker.SourceMarker -import spp.jetbrains.marker.source.mark.api.MethodSourceMark -import spp.jetbrains.marker.source.mark.api.SourceMark -import spp.jetbrains.marker.source.mark.api.event.SourceMarkEvent -import spp.jetbrains.marker.source.mark.api.event.SourceMarkEventCode -import spp.jetbrains.marker.source.mark.api.event.SourceMarkEventListener -import spp.protocol.advice.AdviceListener -import spp.protocol.advice.ArtifactAdvice -import spp.protocol.artifact.ArtifactType -import spp.jetbrains.sourcemarker.SourceMarkerPlugin -import spp.jetbrains.sourcemarker.mark.SourceMarkConstructor -import spp.jetbrains.sourcemarker.mark.SourceMarkKeys.ARTIFACT_ADVICE -import spp.jetbrains.sourcemarker.mark.SourceMarkKeys.ENDPOINT_DETECTOR -import spp.jetbrains.sourcemarker.mark.SourceMarkKeys.SOURCE_PORTAL -import io.vertx.kotlin.coroutines.dispatcher -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import org.slf4j.LoggerFactory - -/** - * todo: description. - * - * @since 0.1.0 - * @author [Brandon Fergerson](mailto:bfergerson@apache.org) - */ -class ArtifactAdviceListener : AdviceListener, SourceMarkEventListener { - - companion object { - private val log = LoggerFactory.getLogger(ArtifactAdviceListener::class.java) - } - - private val pendingAdvice = mutableSetOf() - - override suspend fun advised(advice: ArtifactAdvice) { - when (advice.artifact.type) { - ArtifactType.ENDPOINT -> createEndpointAdvice(advice) - ArtifactType.STATEMENT -> ApplicationManager.getApplication() - .runReadAction { createExpressionAdvice(advice) } - else -> TODO("impl") - } - } - - override fun handleEvent(event: SourceMarkEvent) { - if (event.eventCode == SourceMarkEventCode.MARK_ADDED) { - GlobalScope.launch(SourceMarkerPlugin.vertx.dispatcher()) { - pendingAdvice.toList().forEach { - advised(it) - } - } - } - } - - private suspend fun createEndpointAdvice(advice: ArtifactAdvice) { - val operationName = advice.artifact.identifier - val sourceMark = SourceMarker.getSourceMarks() - .filterIsInstance() - .firstOrNull { it.getUserData(ENDPOINT_DETECTOR)!!.getOrFindEndpointName(it) == operationName } - if (sourceMark != null) { - SourceMarkConstructor.attachAdvice(sourceMark, advice) - addAdviceData(sourceMark, advice) - } else { - pendingAdvice.add(advice) - } - } - - private fun createExpressionAdvice(advice: ArtifactAdvice) { - val qualifiedClassName = advice.artifact.identifier - .substring(0, advice.artifact.identifier.lastIndexOf(".")) - val fileMarker = SourceMarker.getSourceFileMarker(qualifiedClassName) - if (fileMarker != null) { - val sourceMark = SourceMarkConstructor.getOrSetupSourceMark(fileMarker, advice) - if (sourceMark != null) { - addAdviceData(sourceMark, advice) - } - } else { - pendingAdvice.add(advice) - } - } - - private fun addAdviceData(sourceMark: SourceMark, advice: ArtifactAdvice) { - pendingAdvice.remove(advice) - if (sourceMark.getUserData(ARTIFACT_ADVICE) == null) { - sourceMark.putUserData(ARTIFACT_ADVICE, mutableListOf()) - } - - val activeAdvice = sourceMark.getUserData(ARTIFACT_ADVICE)!! - val updatedAdvice = activeAdvice.any { - if (it.isSameArtifactAdvice(advice)) { - it.updateArtifactAdvice(advice) - true - } else { - false - } - } - if (updatedAdvice) { - log.trace("Updated artifact advice: $advice") - } else { - activeAdvice.add(advice) - sourceMark.getUserData(SOURCE_PORTAL)?.advice?.add(advice) - log.debug("Added artifact advice: $advice") - } - } -} diff --git a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/mark/SourceMarkKeys.kt b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/mark/SourceMarkKeys.kt index b626086c6..c7e5b046c 100644 --- a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/mark/SourceMarkKeys.kt +++ b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/mark/SourceMarkKeys.kt @@ -20,7 +20,6 @@ package spp.jetbrains.sourcemarker.mark import spp.jetbrains.marker.source.mark.api.SourceMark import spp.jetbrains.marker.source.mark.api.key.SourceKey import spp.jetbrains.portal.SourcePortal -import spp.protocol.advice.ArtifactAdvice import spp.jetbrains.marker.jvm.psi.EndpointDetector import spp.jetbrains.marker.jvm.psi.LoggerDetector import spp.jetbrains.sourcemarker.service.InstrumentEventListener @@ -36,7 +35,6 @@ object SourceMarkKeys { val SOURCE_PORTAL = SourceKey("SOURCE_PORTAL") val ENDPOINT_DETECTOR = SourceKey("ENDPOINT_DETECTOR") val LOGGER_DETECTOR = SourceKey("LOGGER_DETECTOR") - val ARTIFACT_ADVICE = SourceKey>("ARTIFACT_ADVICE") val BREAKPOINT_ID = SourceKey("BREAKPOINT_ID") val LOG_ID = SourceKey("LOG_ID") val METER_ID = SourceKey("METER_ID") From a0ea2375b1d532b511a1efc7661484bb6481c4b7 Mon Sep 17 00:00:00 2001 From: Brandon Fergerson Date: Mon, 31 Jan 2022 23:24:53 -0500 Subject: [PATCH 06/12] protocol update --- .../status/BreakpointStatusBar.java | 9 +- .../status/LiveMeterStatusPanel.java | 3 +- .../sourcemarker/status/LogStatusBar.java | 8 +- .../sourcemarker/status/MeterStatusBar.java | 6 +- .../sourcemarker/status/SpanStatusBar.java | 6 +- .../listeners/PortalEventListener.kt | 150 ++++++++---------- .../service/LogCountIndicators.kt | 63 ++++---- 7 files changed, 106 insertions(+), 139 deletions(-) diff --git a/plugin/src/main/java/spp/jetbrains/sourcemarker/status/BreakpointStatusBar.java b/plugin/src/main/java/spp/jetbrains/sourcemarker/status/BreakpointStatusBar.java index b70c3ca9a..ab3d1d9e6 100644 --- a/plugin/src/main/java/spp/jetbrains/sourcemarker/status/BreakpointStatusBar.java +++ b/plugin/src/main/java/spp/jetbrains/sourcemarker/status/BreakpointStatusBar.java @@ -25,7 +25,6 @@ import spp.jetbrains.sourcemarker.service.breakpoint.BreakpointHitWindowService; import spp.jetbrains.sourcemarker.settings.LiveBreakpointConfigurationPanel; import spp.jetbrains.sourcemarker.status.util.AutocompleteField; -import spp.protocol.SourceMarkerServices; import spp.protocol.instrument.InstrumentThrottle; import spp.protocol.instrument.LiveInstrument; import spp.protocol.instrument.LiveInstrumentEvent; @@ -34,7 +33,6 @@ import spp.protocol.instrument.breakpoint.LiveBreakpoint; import spp.protocol.instrument.breakpoint.event.LiveBreakpointHit; import spp.protocol.instrument.breakpoint.event.LiveBreakpointRemoved; -import spp.protocol.service.live.LiveInstrumentService; import javax.swing.*; import javax.swing.border.CompoundBorder; @@ -53,7 +51,6 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; -import java.util.Objects; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; @@ -62,6 +59,7 @@ import static spp.jetbrains.marker.SourceMarker.conditionParser; import static spp.jetbrains.sourcemarker.PluginUI.*; import static spp.jetbrains.sourcemarker.status.util.ViewUtils.addRecursiveMouseListener; +import static spp.protocol.SourceMarkerServices.Instance.INSTANCE; import static spp.protocol.instrument.LiveInstrumentEventType.BREAKPOINT_HIT; import static spp.protocol.instrument.LiveInstrumentEventType.BREAKPOINT_REMOVED; @@ -444,7 +442,6 @@ private void saveLiveBreakpoint() { HashMap meta = new HashMap<>(); meta.put("original_source_mark", inlayMark.getId()); - LiveInstrumentService instrumentService = Objects.requireNonNull(SourceMarkerServices.Instance.INSTANCE.getLiveInstrument()); LiveBreakpoint instrument = new LiveBreakpoint( sourceLocation, condition, @@ -457,7 +454,7 @@ private void saveLiveBreakpoint() { throttle, meta ); - instrumentService.addLiveInstrument(instrument, it -> { + INSTANCE.getLiveInstrument().addLiveInstrument(instrument).onComplete(it -> { if (it.succeeded()) { liveBreakpoint = (LiveBreakpoint) it.result(); inlayMark.putUserData(SourceMarkKeys.INSTANCE.getBREAKPOINT_ID(), liveBreakpoint.getId()); @@ -481,7 +478,7 @@ private void dispose() { if (groupedMarks != null) groupedMarks.forEach(SourceMark::dispose); if (liveBreakpoint != null) { - SourceMarkerServices.Instance.INSTANCE.getLiveInstrument().removeLiveInstrument(liveBreakpoint.getId(), it -> { + INSTANCE.getLiveInstrument().removeLiveInstrument(liveBreakpoint.getId()).onComplete(it -> { if (it.succeeded()) { LiveStatusManager.INSTANCE.removeActiveLiveInstrument(liveBreakpoint); } else { diff --git a/plugin/src/main/java/spp/jetbrains/sourcemarker/status/LiveMeterStatusPanel.java b/plugin/src/main/java/spp/jetbrains/sourcemarker/status/LiveMeterStatusPanel.java index 368dae66c..028ae83ae 100644 --- a/plugin/src/main/java/spp/jetbrains/sourcemarker/status/LiveMeterStatusPanel.java +++ b/plugin/src/main/java/spp/jetbrains/sourcemarker/status/LiveMeterStatusPanel.java @@ -23,6 +23,7 @@ import static spp.jetbrains.sourcemarker.PluginUI.LABEL_FOREGROUND_COLOR; import static spp.jetbrains.sourcemarker.PluginUI.ROBOTO_LIGHT_PLAIN_15; import static spp.jetbrains.sourcemarker.status.util.ViewUtils.addRecursiveMouseListener; +import static spp.protocol.SourceMarkerServices.Instance.INSTANCE; public class LiveMeterStatusPanel extends JPanel implements InstrumentEventListener { @@ -96,7 +97,7 @@ public void mouseMoved(MouseEvent e) { addRecursiveMouseListener(closeLabel, new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { - SourceMarkerServices.Instance.INSTANCE.getLiveInstrument().removeLiveInstrument(liveMeter.getId(), it -> { + INSTANCE.getLiveInstrument().removeLiveInstrument(liveMeter.getId()).onComplete(it -> { if (it.succeeded()) { gutterMark.dispose(); LiveStatusManager.INSTANCE.removeActiveLiveInstrument(liveMeter); diff --git a/plugin/src/main/java/spp/jetbrains/sourcemarker/status/LogStatusBar.java b/plugin/src/main/java/spp/jetbrains/sourcemarker/status/LogStatusBar.java index 40b1f1a91..ea9db8212 100644 --- a/plugin/src/main/java/spp/jetbrains/sourcemarker/status/LogStatusBar.java +++ b/plugin/src/main/java/spp/jetbrains/sourcemarker/status/LogStatusBar.java @@ -62,6 +62,7 @@ import static spp.jetbrains.sourcemarker.PluginUI.*; import static spp.jetbrains.sourcemarker.status.util.ViewUtils.addRecursiveMouseListener; import static spp.protocol.ProtocolAddress.Global.ArtifactLogUpdated; +import static spp.protocol.SourceMarkerServices.Instance.INSTANCE; import static spp.protocol.instrument.LiveInstrumentEventType.LOG_HIT; import static spp.protocol.instrument.LiveInstrumentEventType.LOG_REMOVED; @@ -583,7 +584,7 @@ private void saveLiveLog() { latestTime = null; latestLog = null; - SourceMarkerServices.Instance.INSTANCE.getLiveInstrument().removeLiveInstrument(oldLiveLog.getId(), it -> { + INSTANCE.getLiveInstrument().removeLiveInstrument(oldLiveLog.getId()).onComplete(it -> { if (it.succeeded()) { LiveStatusManager.INSTANCE.removeActiveLiveInstrument(oldLiveLog); } else { @@ -619,7 +620,6 @@ private void saveLiveLog() { HashMap meta = new HashMap<>(); meta.put("original_source_mark", inlayMark.getId()); - LiveInstrumentService instrumentService = Objects.requireNonNull(SourceMarkerServices.Instance.INSTANCE.getLiveInstrument()); LiveLog instrument = new LiveLog( finalLogPattern, resp.second.stream().map(it -> it.substring(1)).collect(Collectors.toList()), @@ -642,7 +642,7 @@ private void saveLiveLog() { displayTimeField(); wrapper.grabFocus(); - instrumentService.addLiveInstrument(instrument, it -> { + INSTANCE.getLiveInstrument().addLiveInstrument(instrument).onComplete(it -> { if (it.succeeded()) { liveLog = (LiveLog) it.result(); inlayMark.putUserData(SourceMarkKeys.INSTANCE.getLOG_ID(), it.result().getId()); @@ -667,7 +667,7 @@ private void dispose() { inlayMark.dispose(true); if (liveLog != null) { - SourceMarkerServices.Instance.INSTANCE.getLiveInstrument().removeLiveInstrument(liveLog.getId(), it -> { + INSTANCE.getLiveInstrument().removeLiveInstrument(liveLog.getId()).onComplete(it -> { if (it.succeeded()) { LiveStatusManager.INSTANCE.removeActiveLiveInstrument(liveLog); } else { diff --git a/plugin/src/main/java/spp/jetbrains/sourcemarker/status/MeterStatusBar.java b/plugin/src/main/java/spp/jetbrains/sourcemarker/status/MeterStatusBar.java index ba2d19216..8b9d63857 100644 --- a/plugin/src/main/java/spp/jetbrains/sourcemarker/status/MeterStatusBar.java +++ b/plugin/src/main/java/spp/jetbrains/sourcemarker/status/MeterStatusBar.java @@ -46,6 +46,7 @@ import static spp.jetbrains.marker.SourceMarker.conditionParser; import static spp.jetbrains.sourcemarker.PluginUI.*; import static spp.jetbrains.sourcemarker.status.util.ViewUtils.addRecursiveMouseListener; +import static spp.protocol.SourceMarkerServices.Instance.INSTANCE; import static spp.protocol.instrument.LiveInstrumentEventType.METER_REMOVED; public class MeterStatusBar extends JPanel implements StatusBar, VisibleAreaListener { @@ -357,7 +358,6 @@ private void saveLiveMeter() { HashMap meta = new HashMap<>(); meta.put("original_source_mark", inlayMark.getId()); - LiveInstrumentService instrumentService = Objects.requireNonNull(SourceMarkerServices.Instance.INSTANCE.getLiveInstrument()); LiveMeter instrument = new LiveMeter( meterNameField.getText(), MeterType.valueOf(meterTypeComboBox.getSelectedItem().toString().toUpperCase()), @@ -373,7 +373,7 @@ private void saveLiveMeter() { null, meta ); - instrumentService.addLiveInstrument(instrument, it -> { + INSTANCE.getLiveInstrument().addLiveInstrument(instrument).onComplete(it -> { if (it.succeeded()) { liveMeter = (LiveMeter) it.result(); LiveStatusManager.INSTANCE.addActiveLiveInstrument(liveMeter); @@ -404,7 +404,7 @@ private void dispose() { if (groupedMarks != null) groupedMarks.forEach(SourceMark::dispose); if (liveMeter != null) { - SourceMarkerServices.Instance.INSTANCE.getLiveInstrument().removeLiveInstrument(liveMeter.getId(), it -> { + INSTANCE.getLiveInstrument().removeLiveInstrument(liveMeter.getId()).onComplete(it -> { if (it.succeeded()) { LiveStatusManager.INSTANCE.removeActiveLiveInstrument(liveMeter); } else { diff --git a/plugin/src/main/java/spp/jetbrains/sourcemarker/status/SpanStatusBar.java b/plugin/src/main/java/spp/jetbrains/sourcemarker/status/SpanStatusBar.java index cc33d8549..d13b5e747 100644 --- a/plugin/src/main/java/spp/jetbrains/sourcemarker/status/SpanStatusBar.java +++ b/plugin/src/main/java/spp/jetbrains/sourcemarker/status/SpanStatusBar.java @@ -43,6 +43,7 @@ import static spp.jetbrains.marker.SourceMarker.conditionParser; import static spp.jetbrains.sourcemarker.PluginUI.*; import static spp.jetbrains.sourcemarker.status.util.ViewUtils.addRecursiveMouseListener; +import static spp.protocol.SourceMarkerServices.Instance.INSTANCE; import static spp.protocol.instrument.LiveInstrumentEventType.METER_REMOVED; public class SpanStatusBar extends JPanel implements StatusBar, VisibleAreaListener { @@ -344,7 +345,6 @@ private void saveLiveSpan() { HashMap meta = new HashMap<>(); meta.put("original_source_mark", inlayMark.getId()); - LiveInstrumentService instrumentService = Objects.requireNonNull(SourceMarkerServices.Instance.INSTANCE.getLiveInstrument()); LiveSpan instrument = new LiveSpan( spanOperationNameField.getText(), sourceLocation, @@ -358,7 +358,7 @@ private void saveLiveSpan() { null, meta ); - instrumentService.addLiveInstrument(instrument, it -> { + INSTANCE.getLiveInstrument().addLiveInstrument(instrument).onComplete(it -> { if (it.succeeded()) { liveSpan = (LiveSpan) it.result(); LiveStatusManager.INSTANCE.addActiveLiveInstrument(liveSpan); @@ -385,7 +385,7 @@ private void dispose() { if (groupedMarks != null) groupedMarks.forEach(SourceMark::dispose); if (liveSpan != null) { - SourceMarkerServices.Instance.INSTANCE.getLiveInstrument().removeLiveInstrument(liveSpan.getId(), it -> { + INSTANCE.getLiveInstrument().removeLiveInstrument(liveSpan.getId()).onComplete(it -> { if (it.succeeded()) { LiveStatusManager.INSTANCE.removeActiveLiveInstrument(liveSpan); } else { diff --git a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/listeners/PortalEventListener.kt b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/listeners/PortalEventListener.kt index 7e29647cd..c150577b1 100644 --- a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/listeners/PortalEventListener.kt +++ b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/listeners/PortalEventListener.kt @@ -28,6 +28,7 @@ import io.vertx.core.eventbus.ReplyException import io.vertx.core.json.Json import io.vertx.core.json.JsonObject import io.vertx.kotlin.coroutines.CoroutineVerticle +import io.vertx.kotlin.coroutines.await import io.vertx.kotlin.coroutines.dispatcher import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch @@ -265,33 +266,24 @@ class PortalEventListener( //update subscriptions if (Instance.liveView != null) { - Instance.liveView!!.clearLiveViewSubscriptions { - if (it.succeeded()) { - GlobalScope.launch(vertx.dispatcher()) { - val sourceMark = SourceMarker.getSourceMark( - portal.viewingArtifact, SourceMark.Type.GUTTER - ) ?: return@launch - val endpointName = sourceMark.getUserData( - ENDPOINT_DETECTOR - )?.getOrFindEndpointName(sourceMark) ?: return@launch - - Instance.liveView!!.addLiveViewSubscription( - LiveViewSubscription( - null, - listOf(endpointName), - portal.viewingArtifact, - LiveSourceLocation(portal.viewingArtifact.identifier, 0), //todo: fix - LiveViewConfig("ACTIVITY", listOf("endpoint_cpm", "endpoint_avg", "endpoint_sla")) - ) - ) { - if (it.failed()) { - log.error("Failed to add live view subscription", it.cause()) - } - } - } - } else { - log.error("Failed to clear live view subscriptions", it.cause()) - } + GlobalScope.launch(vertx.dispatcher()) { + Instance.liveView!!.clearLiveViewSubscriptions().await() + val sourceMark = SourceMarker.getSourceMark( + portal.viewingArtifact, SourceMark.Type.GUTTER + ) ?: return@launch + val endpointName = sourceMark.getUserData( + ENDPOINT_DETECTOR + )?.getOrFindEndpointName(sourceMark) ?: return@launch + + Instance.liveView!!.addLiveViewSubscription( + LiveViewSubscription( + null, + listOf(endpointName), + portal.viewingArtifact, + LiveSourceLocation(portal.viewingArtifact.identifier, 0), //todo: fix + LiveViewConfig("ACTIVITY", listOf("endpoint_cpm", "endpoint_avg", "endpoint_sla")) + ) + ).await() } } } @@ -304,33 +296,24 @@ class PortalEventListener( //update subscriptions if (Instance.liveView != null) { - Instance.liveView!!.clearLiveViewSubscriptions { - if (it.succeeded()) { - GlobalScope.launch(vertx.dispatcher()) { - val sourceMark = SourceMarker.getSourceMark( - portal.viewingArtifact, SourceMark.Type.GUTTER - ) ?: return@launch - val endpointName = sourceMark.getUserData( - ENDPOINT_DETECTOR - )?.getOrFindEndpointName(sourceMark) ?: return@launch - - Instance.liveView!!.addLiveViewSubscription( - LiveViewSubscription( - null, - listOf(endpointName), - portal.viewingArtifact, - LiveSourceLocation(portal.viewingArtifact.identifier, 0), //todo: fix - LiveViewConfig("TRACES", listOf("endpoint_traces")) - ) - ) { - if (it.failed()) { - log.error("Failed to add live view subscription", it.cause()) - } - } - } - } else { - log.error("Failed to clear live view subscriptions", it.cause()) - } + GlobalScope.launch(vertx.dispatcher()) { + Instance.liveView!!.clearLiveViewSubscriptions().await() + val sourceMark = SourceMarker.getSourceMark( + portal.viewingArtifact, SourceMark.Type.GUTTER + ) ?: return@launch + val endpointName = sourceMark.getUserData( + ENDPOINT_DETECTOR + )?.getOrFindEndpointName(sourceMark) ?: return@launch + + Instance.liveView!!.addLiveViewSubscription( + LiveViewSubscription( + null, + listOf(endpointName), + portal.viewingArtifact, + LiveSourceLocation(portal.viewingArtifact.identifier, 0), //todo: fix + LiveViewConfig("TRACES", listOf("endpoint_traces")) + ) + ).await() } } } @@ -343,43 +326,34 @@ class PortalEventListener( //update subscriptions if (Instance.liveView != null) { - Instance.liveView!!.clearLiveViewSubscriptions { - if (it.succeeded()) { - GlobalScope.launch(vertx.dispatcher()) { - val sourceMark = SourceMarker.getSourceMark( - portal.viewingArtifact, SourceMark.Type.GUTTER - ) - - val logPatterns = if (sourceMark is ClassSourceMark) { - sourceMark.sourceFileMarker.getSourceMarks().filterIsInstance() - .flatMap { - it.getUserData(SourceMarkKeys.LOGGER_DETECTOR)!! - .getOrFindLoggerStatements(it) - }.map { it.logPattern } - } else if (sourceMark is MethodSourceMark) { - sourceMark.getUserData(SourceMarkKeys.LOGGER_DETECTOR)!! - .getOrFindLoggerStatements(sourceMark).map { it.logPattern } - } else { - throw IllegalStateException("Unsupported source mark type") - } + GlobalScope.launch(vertx.dispatcher()) { + Instance.liveView!!.clearLiveViewSubscriptions().await() + val sourceMark = SourceMarker.getSourceMark( + portal.viewingArtifact, SourceMark.Type.GUTTER + ) - Instance.liveView!!.addLiveViewSubscription( - LiveViewSubscription( - null, - logPatterns, - portal.viewingArtifact, - LiveSourceLocation(portal.viewingArtifact.identifier, 0), //todo: fix - LiveViewConfig("LOGS", listOf("endpoint_logs")) - ) - ) { - if (it.failed()) { - log.error("Failed to add live view subscription", it.cause()) - } - } - } + val logPatterns = if (sourceMark is ClassSourceMark) { + sourceMark.sourceFileMarker.getSourceMarks().filterIsInstance() + .flatMap { + it.getUserData(SourceMarkKeys.LOGGER_DETECTOR)!! + .getOrFindLoggerStatements(it) + }.map { it.logPattern } + } else if (sourceMark is MethodSourceMark) { + sourceMark.getUserData(SourceMarkKeys.LOGGER_DETECTOR)!! + .getOrFindLoggerStatements(sourceMark).map { it.logPattern } } else { - log.error("Failed to clear live view subscriptions", it.cause()) + throw IllegalStateException("Unsupported source mark type") } + + Instance.liveView!!.addLiveViewSubscription( + LiveViewSubscription( + null, + logPatterns, + portal.viewingArtifact, + LiveSourceLocation(portal.viewingArtifact.identifier, 0), //todo: fix + LiveViewConfig("LOGS", listOf("endpoint_logs")) + ) + ).await() } } } diff --git a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/service/LogCountIndicators.kt b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/service/LogCountIndicators.kt index fd7135e67..6ed683425 100644 --- a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/service/LogCountIndicators.kt +++ b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/service/LogCountIndicators.kt @@ -22,6 +22,7 @@ import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.project.ProjectManager import io.vertx.core.json.Json import io.vertx.kotlin.coroutines.CoroutineVerticle +import io.vertx.kotlin.coroutines.await import kotlinx.coroutines.launch import kotlinx.datetime.Clock import kotlinx.datetime.DateTimeUnit @@ -63,48 +64,42 @@ class LogCountIndicators : CoroutineVerticle() { val fileLogPatterns = fileMarker.getSourceMarks().filterIsInstance().flatMap { it.getUserData(LOGGER_DETECTOR)!!.getOrFindLoggerStatements(it) } - Instance.logCountIndicator!!.getPatternOccurrences( + val occurrences = Instance.logCountIndicator!!.getPatternOccurrences( fileLogPatterns.map { it.logPattern }, config.serviceName, Clock.System.now().minus(15, DateTimeUnit.MINUTE), Clock.System.now(), DurationStep.MINUTE - ) { - if (it.succeeded()) { - val occurrences = it.result() - //log.info("Found ${occurrences} occurrences of log patterns") + ).await() + //log.info("Found ${occurrences} occurrences of log patterns") - ApplicationManager.getApplication().runReadAction { - fileLogPatterns.forEach { logger -> - val sumValue = occurrences.getJsonObject(logger.logPattern) - .getJsonArray("values").list.sumOf { it as Int? ?: 0 } + ApplicationManager.getApplication().runReadAction { + fileLogPatterns.forEach { logger -> + val sumValue = occurrences.getJsonObject(logger.logPattern) + .getJsonArray("values").list.sumOf { it as Int? ?: 0 } - val logIndicator = creationService.getOrCreateExpressionGutterMark( - fileMarker, - logger.lineLocation - ).get() - if (!fileMarker.containsSourceMark(logIndicator)) { - logIndicator.configuration.icon = - SourceMarkerIcons.getNumericGutterMarkIcon( - sumValue, - if (logger.level == "warn" || logger.level == "error") "#e1483b" - else "#182d34" - ) - logIndicator.apply(true) - } else { - logIndicator.configuration.icon = - SourceMarkerIcons.getNumericGutterMarkIcon( - sumValue, - if (logger.level == "warn" || logger.level == "error") "#e1483b" - else "#182d34" - ) - //todo: should just be updating rendering, not all analysis - fileMarker.refresh() - } - } + val logIndicator = creationService.getOrCreateExpressionGutterMark( + fileMarker, + logger.lineLocation + ).get() + if (!fileMarker.containsSourceMark(logIndicator)) { + logIndicator.configuration.icon = + SourceMarkerIcons.getNumericGutterMarkIcon( + sumValue, + if (logger.level == "warn" || logger.level == "error") "#e1483b" + else "#182d34" + ) + logIndicator.apply(true) + } else { + logIndicator.configuration.icon = + SourceMarkerIcons.getNumericGutterMarkIcon( + sumValue, + if (logger.level == "warn" || logger.level == "error") "#e1483b" + else "#182d34" + ) + //todo: should just be updating rendering, not all analysis + fileMarker.refresh() } - } else { - log.error("Failed to get log pattern occurrences", it.cause()) } } } From b77f5a3b732bf52918bb030961ffbbc37f6643e7 Mon Sep 17 00:00:00 2001 From: Brandon Fergerson Date: Sun, 27 Feb 2022 16:35:03 +0100 Subject: [PATCH 07/12] clean --- .../discover/TCPServiceDiscoveryBackend.kt | 24 ++++--------------- 1 file changed, 5 insertions(+), 19 deletions(-) diff --git a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/discover/TCPServiceDiscoveryBackend.kt b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/discover/TCPServiceDiscoveryBackend.kt index 736abc47e..ddc5a709b 100644 --- a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/discover/TCPServiceDiscoveryBackend.kt +++ b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/discover/TCPServiceDiscoveryBackend.kt @@ -166,21 +166,10 @@ class TCPServiceDiscoveryBackend : ServiceDiscoveryBackend { } } - override fun store(record: Record, resultHandler: Handler>) { - TODO("Not yet implemented") - } - - override fun remove(record: Record, resultHandler: Handler>) { - TODO("Not yet implemented") - } - - override fun remove(uuid: String, resultHandler: Handler>) { - TODO("Not yet implemented") - } - - override fun update(record: Record, resultHandler: Handler>) { - TODO("Not yet implemented") - } + override fun store(record: Record, resultHandler: Handler>) = Unit + override fun remove(record: Record, resultHandler: Handler>) = Unit + override fun remove(uuid: String, resultHandler: Handler>) = Unit + override fun update(record: Record, resultHandler: Handler>) = Unit override fun getRecords(resultHandler: Handler>>) { if (setupFuture.isComplete) { @@ -212,9 +201,6 @@ class TCPServiceDiscoveryBackend : ServiceDiscoveryBackend { } } - override fun getRecord(uuid: String, resultHandler: Handler>) { - TODO("Not yet implemented") - } - + override fun getRecord(uuid: String, resultHandler: Handler>) = Unit override fun name() = "tcp-service-discovery" } From 778124f94c09f1210d78c37fda91f65b806aad75 Mon Sep 17 00:00:00 2001 From: Brandon Fergerson Date: Sun, 27 Feb 2022 20:05:40 +0100 Subject: [PATCH 08/12] watch log command --- .../source/mark/api/ExpressionSourceMark.kt | 12 +++++ .../sourcemarker/status/LogStatusBar.java | 16 +++--- .../command/ControlBarController.kt | 23 +++++++- .../sourcemarker/service/LiveViewManager.kt | 1 + .../service/LogCountIndicators.kt | 53 ++++++++++--------- .../sourcemarker/status/LiveStatusManager.kt | 34 ++++++++---- 6 files changed, 95 insertions(+), 44 deletions(-) diff --git a/marker/src/main/kotlin/spp/jetbrains/marker/source/mark/api/ExpressionSourceMark.kt b/marker/src/main/kotlin/spp/jetbrains/marker/source/mark/api/ExpressionSourceMark.kt index 0ccc6ef2c..53dd4a98e 100644 --- a/marker/src/main/kotlin/spp/jetbrains/marker/source/mark/api/ExpressionSourceMark.kt +++ b/marker/src/main/kotlin/spp/jetbrains/marker/source/mark/api/ExpressionSourceMark.kt @@ -21,6 +21,7 @@ import com.intellij.openapi.Disposable import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiElement import com.intellij.psi.PsiInvalidElementAccessException +import spp.jetbrains.marker.SourceMarker import spp.jetbrains.marker.SourceMarker.namingService import spp.jetbrains.marker.source.SourceFileMarker import spp.jetbrains.marker.source.mark.api.component.api.SourceMarkComponent @@ -31,6 +32,7 @@ import spp.jetbrains.marker.source.mark.api.key.SourceKey import spp.jetbrains.marker.source.mark.gutter.GutterMark import spp.jetbrains.marker.source.mark.inlay.InlayMark import spp.protocol.artifact.ArtifactQualifiedName +import spp.protocol.artifact.ArtifactType import java.util.* /** @@ -96,6 +98,16 @@ abstract class ExpressionSourceMark( super.dispose(removeFromMarker, assertRemoval) } + fun getParentSourceMark(): SourceMark? { + return SourceMarker.getSourceMark( + artifactQualifiedName.copy( + identifier = artifactQualifiedName.identifier.substringBefore("#"), + type = ArtifactType.METHOD + ), + SourceMark.Type.GUTTER + ) + } + private val userData = HashMap() override fun getUserData(key: SourceKey): T? = userData[key] as T? override fun putUserData(key: SourceKey, value: T?) { diff --git a/plugin/src/main/java/spp/jetbrains/sourcemarker/status/LogStatusBar.java b/plugin/src/main/java/spp/jetbrains/sourcemarker/status/LogStatusBar.java index e27794564..c56bfa771 100644 --- a/plugin/src/main/java/spp/jetbrains/sourcemarker/status/LogStatusBar.java +++ b/plugin/src/main/java/spp/jetbrains/sourcemarker/status/LogStatusBar.java @@ -19,6 +19,7 @@ import spp.jetbrains.marker.source.mark.inlay.InlayMark; import spp.jetbrains.sourcemarker.PluginIcons; import spp.jetbrains.sourcemarker.PluginUI; +import spp.jetbrains.sourcemarker.SourceMarkerPlugin; import spp.jetbrains.sourcemarker.command.AutocompleteFieldRow; import spp.jetbrains.sourcemarker.mark.SourceMarkKeys; import spp.jetbrains.sourcemarker.service.InstrumentEventListener; @@ -27,11 +28,13 @@ import spp.jetbrains.sourcemarker.settings.LiveLogConfigurationPanel; import spp.jetbrains.sourcemarker.status.util.AutocompleteField; import spp.protocol.artifact.log.Log; +import spp.protocol.artifact.log.LogResult; import spp.protocol.instrument.LiveInstrument; import spp.protocol.instrument.LiveLog; import spp.protocol.instrument.LiveSourceLocation; import spp.protocol.instrument.event.LiveInstrumentEvent; import spp.protocol.instrument.event.LiveInstrumentRemoved; +import spp.protocol.instrument.event.LiveLogHit; import spp.protocol.instrument.throttle.InstrumentThrottle; import spp.protocol.instrument.throttle.ThrottleStep; @@ -58,6 +61,7 @@ import static spp.jetbrains.marker.SourceMarker.conditionParser; import static spp.jetbrains.sourcemarker.PluginUI.*; import static spp.jetbrains.sourcemarker.status.util.ViewUtils.addRecursiveMouseListener; +import static spp.protocol.ProtocolAddress.Global.ArtifactLogUpdated; import static spp.protocol.marshall.ProtocolMarshaller.deserializeLiveInstrumentRemoved; import static spp.protocol.SourceServices.Instance.INSTANCE; import static spp.protocol.instrument.event.LiveInstrumentEventType.LOG_HIT; @@ -157,21 +161,21 @@ public Icon getIcon() { SourceMarkerPlugin.INSTANCE.getVertx().eventBus().consumer(ArtifactLogUpdated, event -> { LogResult logResult = (LogResult) event.body(); + if (!inlayMark.getArtifactQualifiedName().equals(logResult.getArtifactQualifiedName())) { + return; + } Log latestLog = logResult.getLogs().get(0); setLatestLog(Instant.now(), latestLog); - JsonObject logJson = JsonObject.mapFrom(new LiveLogHit( - "-1", kotlinx.datetime.Instant.Companion.now(), "null", "null", logResult + JsonObject logJson = JsonObject.mapFrom(new LiveLogHit( //todo: real hit info + "-1", latestLog.getTimestamp(), "null", "null", logResult )); logJson.getJsonObject("logResult").getJsonArray("logs").forEach(it -> { JsonObject log = (JsonObject) it; log.remove("formattedMessage"); }); - LiveInstrumentEvent liveInstrumentEvent = new LiveInstrumentEvent( - LOG_HIT, - logJson.toString() - ); + LiveInstrumentEvent liveInstrumentEvent = new LiveInstrumentEvent(LOG_HIT, logJson.toString()); commandModel.insertRow(0, liveInstrumentEvent); }); } else { diff --git a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/command/ControlBarController.kt b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/command/ControlBarController.kt index 7e593ddad..8185036eb 100644 --- a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/command/ControlBarController.kt +++ b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/command/ControlBarController.kt @@ -32,6 +32,7 @@ import spp.jetbrains.marker.source.mark.api.SourceMark import spp.jetbrains.marker.source.mark.api.component.swing.SwingSourceMarkComponentProvider import spp.jetbrains.marker.source.mark.api.event.SourceMarkEvent import spp.jetbrains.marker.source.mark.api.event.SourceMarkEventCode +import spp.jetbrains.marker.source.mark.inlay.ExpressionInlayMark import spp.jetbrains.marker.source.mark.inlay.InlayMark import spp.jetbrains.sourcemarker.ControlBar import spp.jetbrains.sourcemarker.SourceMarkerPlugin @@ -62,8 +63,26 @@ object ControlBarController { LiveControlCommand.values().toList().filter { @Suppress("UselessCallOnCollection") //unknown enums are null selfInfo.permissions.filterNotNull().map { it.name }.contains(it.name) - } + listOf(WATCH_LOG) + } + } + } + + private fun determineAvailableCommands(inlayMark: ExpressionInlayMark): List { + val availableCommandsAtLocation = availableCommands.toMutableList() + val parentMark = inlayMark.getParentSourceMark() + if (parentMark is MethodSourceMark) { + val loggerDetector = parentMark.getUserData(SourceMarkKeys.LOGGER_DETECTOR) + if (loggerDetector != null) { + runBlocking { + val detectedLogs = loggerDetector.getOrFindLoggerStatements(parentMark) + val logOnCurrentLine = detectedLogs.find { it.lineLocation == inlayMark.lineNumber } + if (logOnCurrentLine != null) { + availableCommandsAtLocation.add(WATCH_LOG) + } + } + } } + return availableCommandsAtLocation } fun handleCommandInput(input: String, editor: Editor) { @@ -263,7 +282,7 @@ object ControlBarController { val wrapperPanel = JPanel() wrapperPanel.layout = BorderLayout() - val controlBar = ControlBar(editor, inlayMark, availableCommands) + val controlBar = ControlBar(editor, inlayMark, determineAvailableCommands(inlayMark)) wrapperPanel.add(controlBar) editor.scrollingModel.addVisibleAreaListener(controlBar) diff --git a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/service/LiveViewManager.kt b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/service/LiveViewManager.kt index 8bf6ef5af..815132231 100644 --- a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/service/LiveViewManager.kt +++ b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/service/LiveViewManager.kt @@ -41,6 +41,7 @@ import spp.protocol.ProtocolAddress.Global.ArtifactMetricsUpdated import spp.protocol.ProtocolAddress.Global.ArtifactTracesUpdated import spp.protocol.ProtocolAddress.Global.TraceSpanUpdated import spp.protocol.SourceServices.Provide.toLiveViewSubscriberAddress +import spp.protocol.artifact.ArtifactType import spp.protocol.artifact.QueryTimeFrame import spp.protocol.artifact.log.Log import spp.protocol.artifact.log.LogOrderType diff --git a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/service/LogCountIndicators.kt b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/service/LogCountIndicators.kt index 6980da49b..35a68ce2d 100644 --- a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/service/LogCountIndicators.kt +++ b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/service/LogCountIndicators.kt @@ -22,7 +22,6 @@ import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.project.ProjectManager import io.vertx.core.json.Json import io.vertx.kotlin.coroutines.CoroutineVerticle -import io.vertx.kotlin.coroutines.await import kotlinx.coroutines.launch import kotlinx.datetime.Clock import kotlinx.datetime.DateTimeUnit @@ -75,32 +74,34 @@ class LogCountIndicators : CoroutineVerticle() { val occurrences = it.result() //log.info("Found ${occurrences} occurrences of log patterns") - ApplicationManager.getApplication().runReadAction { - fileLogPatterns.forEach { logger -> - val sumValue = occurrences.getJsonObject(logger.logPattern) - .getJsonArray("values").list.sumOf { it as Int? ?: 0 } + ApplicationManager.getApplication().runReadAction { + fileLogPatterns.forEach { logger -> + val sumValue = occurrences.getJsonObject(logger.logPattern) + .getJsonArray("values").list.sumOf { it as Int? ?: 0 } - val logIndicator = creationService.getOrCreateExpressionGutterMark( - fileMarker, - logger.lineLocation - ).get() - if (!fileMarker.containsSourceMark(logIndicator)) { - logIndicator.configuration.icon = - SourceMarkerIcons.getNumericGutterMarkIcon( - sumValue, - if (logger.level == "warn" || logger.level == "error") "#e1483b" - else "#182d34" - ) - logIndicator.apply(true) - } else { - logIndicator.configuration.icon = - SourceMarkerIcons.getNumericGutterMarkIcon( - sumValue, - if (logger.level == "warn" || logger.level == "error") "#e1483b" - else "#182d34" - ) - //todo: should just be updating rendering, not all analysis - fileMarker.refresh() + val logIndicator = creationService.getOrCreateExpressionGutterMark( + fileMarker, + logger.lineLocation + ).get() + if (!fileMarker.containsSourceMark(logIndicator)) { + logIndicator.configuration.icon = + SourceMarkerIcons.getNumericGutterMarkIcon( + sumValue, + if (logger.level == "warn" || logger.level == "error") "#e1483b" + else "#182d34" + ) + logIndicator.apply(true) + } else { + logIndicator.configuration.icon = + SourceMarkerIcons.getNumericGutterMarkIcon( + sumValue, + if (logger.level == "warn" || logger.level == "error") "#e1483b" + else "#182d34" + ) + //todo: should just be updating rendering, not all analysis + fileMarker.refresh() + } + } } } } diff --git a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/status/LiveStatusManager.kt b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/status/LiveStatusManager.kt index 0c71a6f62..ae6d75194 100644 --- a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/status/LiveStatusManager.kt +++ b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/status/LiveStatusManager.kt @@ -23,6 +23,7 @@ import com.intellij.openapi.editor.Editor import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.psi.PsiDocumentManager import io.vertx.core.json.Json +import kotlinx.coroutines.runBlocking import org.slf4j.LoggerFactory import spp.jetbrains.marker.SourceMarker.creationService import spp.jetbrains.marker.SourceMarker.namingService @@ -175,10 +176,25 @@ object LiveStatusManager : SourceMarkEventListener { wrapperPanel.layout = BorderLayout() if (watchExpression) { - SourceMarkerServices.Instance.liveView!!.addLiveViewSubscription( + val logPatterns = mutableListOf() + val parentMark = inlayMark.getParentSourceMark() + if (parentMark is MethodSourceMark) { + val loggerDetector = parentMark.getUserData(SourceMarkKeys.LOGGER_DETECTOR) + if (loggerDetector != null) { + runBlocking { + val detectedLogs = loggerDetector.getOrFindLoggerStatements(parentMark) + val logOnCurrentLine = detectedLogs.find { it.lineLocation == inlayMark.lineNumber } + if (logOnCurrentLine != null) { + logPatterns.add(logOnCurrentLine.logPattern) + } + } + } + } + + SourceServices.Instance.liveView!!.addLiveViewSubscription( LiveViewSubscription( null, - listOf("Getting user list"), + logPatterns, ArtifactQualifiedName( inlayMark.artifactQualifiedName.identifier, lineNumber = inlayMark.artifactQualifiedName.lineNumber, @@ -190,7 +206,7 @@ object LiveStatusManager : SourceMarkEventListener { ), LiveViewConfig("LOGS", listOf("endpoint_logs")) ) - ) { + ).onComplete { if (it.failed()) { log.error("Failed to add live view subscription", it.cause()) } @@ -228,14 +244,12 @@ object LiveStatusManager : SourceMarkEventListener { sourcePortal.configuration.currentPage = PageType.LOGS sourcePortal.configuration.statusBar = true - SourceMarkerPlugin.vertx.eventBus().consumer(DisplayLogs(sourcePortal.portalUuid)) { - val latestLog = it.body().logs.first() - statusBar.setLatestLog( - Instant.ofEpochMilli(latestLog.timestamp.toEpochMilliseconds()), latestLog - ) - } - if (!watchExpression) { + SourceMarkerPlugin.vertx.eventBus().consumer(DisplayLogs(sourcePortal.portalUuid)) { + val latestLog = it.body().logs.first() + statusBar.setLatestLog(Instant.ofEpochMilli(latestLog.timestamp.toEpochMilliseconds()), latestLog) + } + statusBar.focus() } } From 6c58b9e6f195e5915b4ee44332b282fdb100f1f5 Mon Sep 17 00:00:00 2001 From: Brandon Fergerson Date: Sun, 27 Feb 2022 21:35:44 +0100 Subject: [PATCH 09/12] bump --- mapper/build.gradle.kts | 2 +- marker/build.gradle.kts | 2 +- marker/jvm-marker/build.gradle.kts | 2 +- marker/py-marker/build.gradle.kts | 2 +- monitor/build.gradle.kts | 2 +- plugin/build.gradle.kts | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/mapper/build.gradle.kts b/mapper/build.gradle.kts index f3f7d362c..cb2c10937 100644 --- a/mapper/build.gradle.kts +++ b/mapper/build.gradle.kts @@ -24,7 +24,7 @@ repositories { } dependencies { - implementation("com.github.sourceplusplus.protocol:protocol:473051b4e5") + implementation("com.github.sourceplusplus.protocol:protocol:2bd4bea9ad") implementation("com.github.sh5i:git-stein:v0.5.0") implementation("org.apache.commons:commons-lang3:3.12.0") implementation("org.eclipse.jgit:org.eclipse.jgit:6.0.0.202111291000-r") diff --git a/marker/build.gradle.kts b/marker/build.gradle.kts index a55dc3b0e..6ed34f049 100644 --- a/marker/build.gradle.kts +++ b/marker/build.gradle.kts @@ -30,7 +30,7 @@ dependencies { val intellijVersion = "213.6777.52" compileOnly("org.jooq:joor:$joorVersion") - compileOnly("com.github.sourceplusplus.protocol:protocol:473051b4e5") + compileOnly("com.github.sourceplusplus.protocol:protocol:2bd4bea9ad") compileOnly("org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlinVersion") compileOnly("org.jetbrains.kotlin:kotlin-stdlib-jdk8") compileOnly("com.google.guava:guava:31.0.1-jre") diff --git a/marker/jvm-marker/build.gradle.kts b/marker/jvm-marker/build.gradle.kts index 5373d0151..4aaa44cad 100644 --- a/marker/jvm-marker/build.gradle.kts +++ b/marker/jvm-marker/build.gradle.kts @@ -21,7 +21,7 @@ dependencies { compileOnly(project(":marker")) compileOnly(project(":monitor")) } - compileOnly("com.github.sourceplusplus.protocol:protocol:473051b4e5") + compileOnly("com.github.sourceplusplus.protocol:protocol:2bd4bea9ad") val intellijVersion = "213.6777.52" implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlinVersion") diff --git a/marker/py-marker/build.gradle.kts b/marker/py-marker/build.gradle.kts index f7a8a588f..005753418 100644 --- a/marker/py-marker/build.gradle.kts +++ b/marker/py-marker/build.gradle.kts @@ -18,7 +18,7 @@ dependencies { } else { compileOnly(project(":marker")) } - compileOnly("com.github.sourceplusplus.protocol:protocol:473051b4e5") + compileOnly("com.github.sourceplusplus.protocol:protocol:2bd4bea9ad") val intellijVersion = "213.6777.52" implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlinVersion") diff --git a/monitor/build.gradle.kts b/monitor/build.gradle.kts index 50c85c418..b81cb760d 100644 --- a/monitor/build.gradle.kts +++ b/monitor/build.gradle.kts @@ -10,7 +10,7 @@ val projectVersion: String by project val slf4jVersion: String by project dependencies { - implementation("com.github.sourceplusplus.protocol:protocol:473051b4e5") + implementation("com.github.sourceplusplus.protocol:protocol:2bd4bea9ad") implementation("org.slf4j:slf4j-api:$slf4jVersion") implementation("com.apollographql.apollo3:apollo-runtime:$apolloVersion") api("com.apollographql.apollo3:apollo-api:$apolloVersion") diff --git a/plugin/build.gradle.kts b/plugin/build.gradle.kts index 1506c850e..deb6c620d 100644 --- a/plugin/build.gradle.kts +++ b/plugin/build.gradle.kts @@ -65,7 +65,7 @@ dependencies { implementation(project(":marker:py-marker")) implementation(project(":monitor")) implementation("com.github.sourceplusplus.interface-portal:portal-jvm:$projectVersion") { isTransitive = false } - implementation("com.github.sourceplusplus.protocol:protocol:473051b4e5") + implementation("com.github.sourceplusplus.protocol:protocol:2bd4bea9ad") } implementation("org.jooq:joor:$joorVersion") From e3cc12a9c4040693d1846df2edadcfd48be2a600 Mon Sep 17 00:00:00 2001 From: Brandon Fergerson Date: Mon, 28 Feb 2022 10:46:15 +0100 Subject: [PATCH 10/12] refactor --- .../sourcemarker/search/SourceMarkSearch.kt | 27 ++--------------- .../service/LiveInstrumentManager.kt | 29 +++++-------------- .../sourcemarker/service/LiveViewManager.kt | 2 +- 3 files changed, 12 insertions(+), 46 deletions(-) diff --git a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/search/SourceMarkSearch.kt b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/search/SourceMarkSearch.kt index 32cce5cf2..48f94aab8 100644 --- a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/search/SourceMarkSearch.kt +++ b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/search/SourceMarkSearch.kt @@ -40,27 +40,6 @@ object SourceMarkSearch { } } - fun findByMeterId(meterId: String): SourceMark? { - return SourceMarker.getSourceMarks() - .firstOrNull { - it.getUserData(SourceMarkKeys.METER_ID) == meterId - } - } - - fun findByLogId(logId: String): SourceMark? { - return SourceMarker.getSourceMarks() - .firstOrNull { - it.getUserData(SourceMarkKeys.LOG_ID) == logId - } - } - - fun findByBreakpointId(breakpointId: String): SourceMark? { - return SourceMarker.getSourceMarks() - .firstOrNull { - it.getUserData(SourceMarkKeys.BREAKPOINT_ID) == breakpointId - } - } - fun findByInstrumentId(instrumentId: String): SourceMark? { return SourceMarker.getSourceMarks() .firstOrNull { @@ -73,8 +52,8 @@ object SourceMarkSearch { suspend fun findSourceMark(artifact: ArtifactQualifiedName): SourceMark? { return when (artifact.type) { ArtifactType.ENDPOINT -> findEndpointSourceMark(artifact) - ArtifactType.STATEMENT -> findExpressionAdvice(artifact) - ArtifactType.EXPRESSION -> findExpressionAdvice(artifact) + ArtifactType.STATEMENT -> findExpressionSourceMark(artifact) + ArtifactType.EXPRESSION -> findExpressionSourceMark(artifact) else -> TODO("impl") } } @@ -121,7 +100,7 @@ object SourceMarkSearch { } } - private fun findExpressionAdvice(artifact: ArtifactQualifiedName): ExpressionSourceMark? { + private fun findExpressionSourceMark(artifact: ArtifactQualifiedName): ExpressionSourceMark? { if (artifact.type == ArtifactType.EXPRESSION) { return SourceMarker.getSourceMarks().find { it.artifactQualifiedName == artifact } as ExpressionSourceMark? } diff --git a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/service/LiveInstrumentManager.kt b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/service/LiveInstrumentManager.kt index f4903f7f9..944a9d0e5 100644 --- a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/service/LiveInstrumentManager.kt +++ b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/service/LiveInstrumentManager.kt @@ -37,7 +37,6 @@ import spp.jetbrains.sourcemarker.service.breakpoint.BreakpointTriggerListener import spp.jetbrains.sourcemarker.settings.SourceMarkerConfig import spp.jetbrains.sourcemarker.status.LiveStatusManager import spp.protocol.ProtocolAddress.Global.ArtifactLogUpdated -import spp.protocol.marshall.ProtocolMarshaller.deserializeLiveInstrumentRemoved import spp.protocol.SourceServices.Instance import spp.protocol.SourceServices.Provide.toLiveInstrumentSubscriberAddress import spp.protocol.instrument.LiveBreakpoint @@ -46,6 +45,7 @@ import spp.protocol.instrument.event.LiveInstrumentEvent import spp.protocol.instrument.event.LiveInstrumentEventType import spp.protocol.instrument.event.LiveLogHit import spp.protocol.marshall.ProtocolMarshaller +import spp.protocol.marshall.ProtocolMarshaller.deserializeLiveInstrumentRemoved /** * todo: description. @@ -79,9 +79,9 @@ class LiveInstrumentManager( LiveInstrumentEventType.LOG_HIT -> handleLogHitEvent(liveEvent) LiveInstrumentEventType.BREAKPOINT_HIT -> handleBreakpointHitEvent(liveEvent) LiveInstrumentEventType.BREAKPOINT_ADDED -> handleBreakpointAddedEvent(liveEvent) - LiveInstrumentEventType.BREAKPOINT_REMOVED -> handleBreakpointRemovedEvent(liveEvent) + LiveInstrumentEventType.BREAKPOINT_REMOVED -> handleInstrumentRemovedEvent(liveEvent) LiveInstrumentEventType.LOG_ADDED -> handleLogAddedEvent(liveEvent) - LiveInstrumentEventType.LOG_REMOVED -> handleLogRemovedEvent(liveEvent) + LiveInstrumentEventType.LOG_REMOVED -> handleInstrumentRemovedEvent(liveEvent) else -> log.warn("Un-implemented event type: {}", liveEvent.eventType) } } @@ -105,19 +105,6 @@ class LiveInstrumentManager( } } - private fun handleLogRemovedEvent(liveEvent: LiveInstrumentEvent) { - val logRemoved = deserializeLiveInstrumentRemoved(JsonObject(liveEvent.data)) - ApplicationManager.getApplication().invokeLater { - val inlayMark = SourceMarkSearch.findByLogId(logRemoved.liveInstrument.id!!) - if (inlayMark != null) { - val eventListeners = inlayMark.getUserData(SourceMarkKeys.INSTRUMENT_EVENT_LISTENERS) - if (eventListeners?.isNotEmpty() == true) { - eventListeners.forEach { it.accept(liveEvent) } - } - } - } - } - private fun handleLogAddedEvent(liveEvent: LiveInstrumentEvent) { if (!SourceMarker.enabled) { log.debug("SourceMarker disabled. Ignored log added") @@ -151,10 +138,10 @@ class LiveInstrumentManager( } } - private fun handleBreakpointRemovedEvent(liveEvent: LiveInstrumentEvent) { - val bpRemoved = deserializeLiveInstrumentRemoved(JsonObject(liveEvent.data)) + private fun handleInstrumentRemovedEvent(liveEvent: LiveInstrumentEvent) { + val instrumentRemoved = deserializeLiveInstrumentRemoved(JsonObject(liveEvent.data)) ApplicationManager.getApplication().invokeLater { - val inlayMark = SourceMarkSearch.findByBreakpointId(bpRemoved.liveInstrument.id!!) + val inlayMark = SourceMarkSearch.findByInstrumentId(instrumentRemoved.liveInstrument.id!!) if (inlayMark != null) { val eventListeners = inlayMark.getUserData(SourceMarkKeys.INSTRUMENT_EVENT_LISTENERS) if (eventListeners?.isNotEmpty() == true) { @@ -170,7 +157,7 @@ class LiveInstrumentManager( val project = ProjectManager.getInstance().openProjects[0] BreakpointHitWindowService.getInstance(project).addBreakpointHit(bpHit) - val inlayMark = SourceMarkSearch.findByBreakpointId(bpHit.breakpointId) + val inlayMark = SourceMarkSearch.findByInstrumentId(bpHit.breakpointId) if (inlayMark != null) { val eventListeners = inlayMark.getUserData(SourceMarkKeys.INSTRUMENT_EVENT_LISTENERS) if (eventListeners?.isNotEmpty() == true) { @@ -189,7 +176,7 @@ class LiveInstrumentManager( //todo: can get log hit without log added (race) try open val logHit = Json.decodeValue(liveEvent.data, LiveLogHit::class.java) ApplicationManager.getApplication().invokeLater { - val inlayMark = SourceMarkSearch.findByLogId(logHit.logId) + val inlayMark = SourceMarkSearch.findByInstrumentId(logHit.logId) if (inlayMark != null) { val eventListeners = inlayMark.getUserData(SourceMarkKeys.INSTRUMENT_EVENT_LISTENERS) if (eventListeners?.isNotEmpty() == true) { diff --git a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/service/LiveViewManager.kt b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/service/LiveViewManager.kt index 815132231..ab347a4fb 100644 --- a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/service/LiveViewManager.kt +++ b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/service/LiveViewManager.kt @@ -122,7 +122,7 @@ class LiveViewManager(private val pluginConfig: SourceMarkerConfig) : CoroutineV val meterTypeStr = event.entityId.substringAfter("spp_").substringBefore("_").toUpperCase() val meterType = MeterType.valueOf(meterTypeStr) val meterId = event.entityId.substringAfter(meterType.name.toLowerCase() + "_").replace("_", "-") - val meterMark = SourceMarkSearch.findByMeterId(meterId) + val meterMark = SourceMarkSearch.findByInstrumentId(meterId) if (meterMark == null) { log.info("Could not find source mark for: " + event.entityId) return From 9f48b6f5fe0aaddf4035a95aa50c5adb00fa7dd6 Mon Sep 17 00:00:00 2001 From: Brandon Fergerson Date: Mon, 28 Feb 2022 10:49:30 +0100 Subject: [PATCH 11/12] format --- .../listeners/PortalEventListener.kt | 25 +++++++++---------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/listeners/PortalEventListener.kt b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/listeners/PortalEventListener.kt index c8a3a1486..842aad59d 100644 --- a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/listeners/PortalEventListener.kt +++ b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/listeners/PortalEventListener.kt @@ -28,7 +28,6 @@ import io.vertx.core.eventbus.ReplyException import io.vertx.core.json.Json import io.vertx.core.json.JsonObject import io.vertx.kotlin.coroutines.CoroutineVerticle -import io.vertx.kotlin.coroutines.await import io.vertx.kotlin.coroutines.dispatcher import kotlinx.coroutines.launch import kotlinx.datetime.Instant @@ -350,18 +349,18 @@ class PortalEventListener( portal.viewingArtifact, SourceMark.Type.GUTTER ) - val logPatterns = if (sourceMark is ClassSourceMark) { - sourceMark.sourceFileMarker.getSourceMarks().filterIsInstance() - .flatMap { - it.getUserData(SourceMarkKeys.LOGGER_DETECTOR)!! - .getOrFindLoggerStatements(it) - }.map { it.logPattern } - } else if (sourceMark is MethodSourceMark) { - sourceMark.getUserData(SourceMarkKeys.LOGGER_DETECTOR)!! - .getOrFindLoggerStatements(sourceMark).map { it.logPattern } - } else { - throw IllegalStateException("Unsupported source mark type") - } + val logPatterns = if (sourceMark is ClassSourceMark) { + sourceMark.sourceFileMarker.getSourceMarks().filterIsInstance() + .flatMap { + it.getUserData(SourceMarkKeys.LOGGER_DETECTOR)!! + .getOrFindLoggerStatements(it) + }.map { it.logPattern } + } else if (sourceMark is MethodSourceMark) { + sourceMark.getUserData(SourceMarkKeys.LOGGER_DETECTOR)!! + .getOrFindLoggerStatements(sourceMark).map { it.logPattern } + } else { + throw IllegalStateException("Unsupported source mark type") + } Instance.liveView!!.addLiveViewSubscription( LiveViewSubscription( From 24934cd6d26382b4554a4de230650c17819222f6 Mon Sep 17 00:00:00 2001 From: Brandon Fergerson Date: Mon, 28 Feb 2022 11:41:47 +0100 Subject: [PATCH 12/12] remove subscription on mark remove --- .../sourcemarker/status/LiveStatusManager.kt | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/status/LiveStatusManager.kt b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/status/LiveStatusManager.kt index ae6d75194..b581c9441 100644 --- a/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/status/LiveStatusManager.kt +++ b/plugin/src/main/kotlin/spp/jetbrains/sourcemarker/status/LiveStatusManager.kt @@ -207,7 +207,19 @@ object LiveStatusManager : SourceMarkEventListener { LiveViewConfig("LOGS", listOf("endpoint_logs")) ) ).onComplete { - if (it.failed()) { + if (it.succeeded()) { + inlayMark.addEventListener { event -> + if (event.eventCode == SourceMarkEventCode.MARK_REMOVED) { + SourceServices.Instance.liveView!!.removeLiveViewSubscription( + it.result().subscriptionId!! + ).onComplete { + if (it.failed()) { + log.error("Failed to remove subscription: {}", it.cause()) + } + } + } + } + } else { log.error("Failed to add live view subscription", it.cause()) } }