├── .github └── workflows │ ├── ci.yml │ └── clean.yml ├── .gitignore ├── .scalafmt.conf ├── LICENSE ├── README.md ├── project ├── build.properties └── plugins.sbt └── src └── main └── scala └── cats └── effect └── shell ├── CeJmx.scala ├── ConnectionState.scala ├── Formats.scala ├── Jmx.scala ├── Main.scala └── StatefulList.scala /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | # This file was automatically generated by sbt-github-actions using the 2 | # githubWorkflowGenerate task. You should add and commit this file to 3 | # your git repository. It goes without saying that you shouldn't edit 4 | # this file by hand! Instead, if you wish to make changes, you should 5 | # change your sbt build configuration to revise the workflow description 6 | # to meet your needs, then regenerate this file. 7 | 8 | name: Continuous Integration 9 | 10 | on: 11 | pull_request: 12 | branches: ['**', '!update/**', '!pr/**'] 13 | push: 14 | branches: ['**', '!update/**', '!pr/**'] 15 | tags: [v*] 16 | 17 | env: 18 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 19 | 20 | 21 | concurrency: 22 | group: ${{ github.workflow }} @ ${{ github.ref }} 23 | cancel-in-progress: true 24 | 25 | jobs: 26 | build: 27 | name: Build and Test 28 | strategy: 29 | matrix: 30 | os: [ubuntu-latest] 31 | scala: [3] 32 | java: [temurin@17] 33 | runs-on: ${{ matrix.os }} 34 | timeout-minutes: 60 35 | steps: 36 | - name: Checkout current branch (full) 37 | uses: actions/checkout@v4 38 | with: 39 | fetch-depth: 0 40 | 41 | - name: Setup Java (temurin@17) 42 | id: setup-java-temurin-17 43 | if: matrix.java == 'temurin@17' 44 | uses: actions/setup-java@v3 45 | with: 46 | distribution: temurin 47 | java-version: 17 48 | cache: sbt 49 | 50 | - name: sbt update 51 | if: matrix.java == 'temurin@17' && steps.setup-java-temurin-17.outputs.cache-hit == 'false' 52 | run: sbt +update 53 | 54 | - name: Check that workflows are up to date 55 | run: sbt githubWorkflowCheck 56 | 57 | - name: Check headers and formatting 58 | if: matrix.java == 'temurin@17' && matrix.os == 'ubuntu-latest' 59 | run: sbt '++ ${{ matrix.scala }}' headerCheckAll scalafmtCheckAll 'project /' scalafmtSbtCheck 60 | 61 | - name: Test 62 | run: sbt '++ ${{ matrix.scala }}' test 63 | 64 | - name: Check binary compatibility 65 | if: matrix.java == 'temurin@17' && matrix.os == 'ubuntu-latest' 66 | run: sbt '++ ${{ matrix.scala }}' mimaReportBinaryIssues 67 | 68 | - name: Generate API documentation 69 | if: matrix.java == 'temurin@17' && matrix.os == 'ubuntu-latest' 70 | run: sbt '++ ${{ matrix.scala }}' doc 71 | 72 | - name: Make target directories 73 | if: github.event_name != 'pull_request' && (startsWith(github.ref, 'refs/tags/v') || github.ref == 'refs/heads/main') 74 | run: mkdir -p target project/target 75 | 76 | - name: Compress target directories 77 | if: github.event_name != 'pull_request' && (startsWith(github.ref, 'refs/tags/v') || github.ref == 'refs/heads/main') 78 | run: tar cf targets.tar target project/target 79 | 80 | - name: Upload target directories 81 | if: github.event_name != 'pull_request' && (startsWith(github.ref, 'refs/tags/v') || github.ref == 'refs/heads/main') 82 | uses: actions/upload-artifact@v3 83 | with: 84 | name: target-${{ matrix.os }}-${{ matrix.java }}-${{ matrix.scala }} 85 | path: targets.tar 86 | 87 | publish: 88 | name: Publish Artifacts 89 | needs: [build] 90 | if: github.event_name != 'pull_request' && (startsWith(github.ref, 'refs/tags/v') || github.ref == 'refs/heads/main') 91 | strategy: 92 | matrix: 93 | os: [ubuntu-latest] 94 | java: [temurin@17] 95 | runs-on: ${{ matrix.os }} 96 | steps: 97 | - name: Checkout current branch (full) 98 | uses: actions/checkout@v4 99 | with: 100 | fetch-depth: 0 101 | 102 | - name: Setup Java (temurin@17) 103 | id: setup-java-temurin-17 104 | if: matrix.java == 'temurin@17' 105 | uses: actions/setup-java@v3 106 | with: 107 | distribution: temurin 108 | java-version: 17 109 | cache: sbt 110 | 111 | - name: sbt update 112 | if: matrix.java == 'temurin@17' && steps.setup-java-temurin-17.outputs.cache-hit == 'false' 113 | run: sbt +update 114 | 115 | - name: Download target directories (3) 116 | uses: actions/download-artifact@v3 117 | with: 118 | name: target-${{ matrix.os }}-${{ matrix.java }}-3 119 | 120 | - name: Inflate target directories (3) 121 | run: | 122 | tar xf targets.tar 123 | rm targets.tar 124 | 125 | - name: Import signing key 126 | if: env.PGP_SECRET != '' && env.PGP_PASSPHRASE == '' 127 | env: 128 | PGP_SECRET: ${{ secrets.PGP_SECRET }} 129 | PGP_PASSPHRASE: ${{ secrets.PGP_PASSPHRASE }} 130 | run: echo $PGP_SECRET | base64 -d -i - | gpg --import 131 | 132 | - name: Import signing key and strip passphrase 133 | if: env.PGP_SECRET != '' && env.PGP_PASSPHRASE != '' 134 | env: 135 | PGP_SECRET: ${{ secrets.PGP_SECRET }} 136 | PGP_PASSPHRASE: ${{ secrets.PGP_PASSPHRASE }} 137 | run: | 138 | echo "$PGP_SECRET" | base64 -d -i - > /tmp/signing-key.gpg 139 | echo "$PGP_PASSPHRASE" | gpg --pinentry-mode loopback --passphrase-fd 0 --import /tmp/signing-key.gpg 140 | (echo "$PGP_PASSPHRASE"; echo; echo) | gpg --command-fd 0 --pinentry-mode loopback --change-passphrase $(gpg --list-secret-keys --with-colons 2> /dev/null | grep '^sec:' | cut --delimiter ':' --fields 5 | tail -n 1) 141 | 142 | - name: Publish 143 | env: 144 | SONATYPE_USERNAME: ${{ secrets.SONATYPE_USERNAME }} 145 | SONATYPE_PASSWORD: ${{ secrets.SONATYPE_PASSWORD }} 146 | SONATYPE_CREDENTIAL_HOST: ${{ secrets.SONATYPE_CREDENTIAL_HOST }} 147 | run: sbt tlCiRelease 148 | 149 | dependency-submission: 150 | name: Submit Dependencies 151 | if: github.event_name != 'pull_request' 152 | strategy: 153 | matrix: 154 | os: [ubuntu-latest] 155 | java: [temurin@17] 156 | runs-on: ${{ matrix.os }} 157 | steps: 158 | - name: Checkout current branch (full) 159 | uses: actions/checkout@v4 160 | with: 161 | fetch-depth: 0 162 | 163 | - name: Setup Java (temurin@17) 164 | id: setup-java-temurin-17 165 | if: matrix.java == 'temurin@17' 166 | uses: actions/setup-java@v3 167 | with: 168 | distribution: temurin 169 | java-version: 17 170 | cache: sbt 171 | 172 | - name: sbt update 173 | if: matrix.java == 'temurin@17' && steps.setup-java-temurin-17.outputs.cache-hit == 'false' 174 | run: sbt +update 175 | 176 | - name: Submit Dependencies 177 | uses: scalacenter/sbt-dependency-submission@v2 178 | with: 179 | configs-ignore: test scala-tool scala-doc-tool test-internal 180 | -------------------------------------------------------------------------------- /.github/workflows/clean.yml: -------------------------------------------------------------------------------- 1 | # This file was automatically generated by sbt-github-actions using the 2 | # githubWorkflowGenerate task. You should add and commit this file to 3 | # your git repository. It goes without saying that you shouldn't edit 4 | # this file by hand! Instead, if you wish to make changes, you should 5 | # change your sbt build configuration to revise the workflow description 6 | # to meet your needs, then regenerate this file. 7 | 8 | name: Clean 9 | 10 | on: push 11 | 12 | jobs: 13 | delete-artifacts: 14 | name: Delete Artifacts 15 | runs-on: ubuntu-latest 16 | env: 17 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 18 | steps: 19 | - name: Delete artifacts 20 | run: | 21 | # Customize those three lines with your repository and credentials: 22 | REPO=${GITHUB_API_URL}/repos/${{ github.repository }} 23 | 24 | # A shortcut to call GitHub API. 25 | ghapi() { curl --silent --location --user _:$GITHUB_TOKEN "$@"; } 26 | 27 | # A temporary file which receives HTTP response headers. 28 | TMPFILE=/tmp/tmp.$$ 29 | 30 | # An associative array, key: artifact name, value: number of artifacts of that name. 31 | declare -A ARTCOUNT 32 | 33 | # Process all artifacts on this repository, loop on returned "pages". 34 | URL=$REPO/actions/artifacts 35 | while [[ -n "$URL" ]]; do 36 | 37 | # Get current page, get response headers in a temporary file. 38 | JSON=$(ghapi --dump-header $TMPFILE "$URL") 39 | 40 | # Get URL of next page. Will be empty if we are at the last page. 41 | URL=$(grep '^Link:' "$TMPFILE" | tr ',' '\n' | grep 'rel="next"' | head -1 | sed -e 's/.*.*//') 42 | rm -f $TMPFILE 43 | 44 | # Number of artifacts on this page: 45 | COUNT=$(( $(jq <<<$JSON -r '.artifacts | length') )) 46 | 47 | # Loop on all artifacts on this page. 48 | for ((i=0; $i < $COUNT; i++)); do 49 | 50 | # Get name of artifact and count instances of this name. 51 | name=$(jq <<<$JSON -r ".artifacts[$i].name?") 52 | ARTCOUNT[$name]=$(( $(( ${ARTCOUNT[$name]} )) + 1)) 53 | 54 | id=$(jq <<<$JSON -r ".artifacts[$i].id?") 55 | size=$(( $(jq <<<$JSON -r ".artifacts[$i].size_in_bytes?") )) 56 | printf "Deleting '%s' #%d, %'d bytes\n" $name ${ARTCOUNT[$name]} $size 57 | ghapi -X DELETE $REPO/actions/artifacts/$id 58 | done 59 | done 60 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | .classpath 3 | .project 4 | .settings/ 5 | .worksheet/ 6 | .cache 7 | .tags 8 | .idea 9 | .idea_modules/ 10 | .DS_Store 11 | *.swp 12 | .metaserver 13 | .bloop 14 | .metals 15 | .vscode 16 | project/metals.sbt 17 | project/project 18 | .bsp 19 | 20 | -------------------------------------------------------------------------------- /.scalafmt.conf: -------------------------------------------------------------------------------- 1 | version = "3.7.7" 2 | 3 | style = default 4 | 5 | runner.dialect = scala3 6 | 7 | maxColumn = 100 8 | 9 | rewrite.rules = [ 10 | AvoidInfix 11 | RedundantBraces 12 | RedundantParens 13 | Imports 14 | PreferCurlyFors 15 | ] 16 | 17 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # cats-effect-shell 2 | Command line debugging console for Cats Effect 3 | -------------------------------------------------------------------------------- /project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version=1.9.1 2 | -------------------------------------------------------------------------------- /project/plugins.sbt: -------------------------------------------------------------------------------- 1 | val sbtTypelevelVersion = "0.6.2" 2 | addSbtPlugin("org.typelevel" % "sbt-typelevel" % sbtTypelevelVersion) 3 | addSbtPlugin("org.typelevel" % "sbt-typelevel-site" % sbtTypelevelVersion) 4 | addSbtPlugin("org.scalameta" % "sbt-mdoc" % "2.3.7") 5 | -------------------------------------------------------------------------------- /src/main/scala/cats/effect/shell/CeJmx.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Typelevel 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | /* 18 | * Copyright 2023 Typelevel 19 | * 20 | * Licensed under the Apache License, Version 2.0 (the "License"); 21 | * you may not use this file except in compliance with the License. 22 | * You may obtain a copy of the License at 23 | * 24 | * http://www.apache.org/licenses/LICENSE-2.0 25 | * 26 | * Unless required by applicable law or agreed to in writing, software 27 | * distributed under the License is distributed on an "AS IS" BASIS, 28 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 29 | * See the License for the specific language governing permissions and 30 | * limitations under the License. 31 | */ 32 | 33 | package cats.effect.shell 34 | 35 | import scala.jdk.CollectionConverters.* 36 | import scala.util.control.NonFatal 37 | 38 | import javax.management.{MBeanServerConnection, ObjectInstance, ObjectName} 39 | 40 | object CeJmx: 41 | 42 | case class ComputePoolStats( 43 | workerThreadCount: Int, 44 | activeThreadCount: Int, 45 | searchingThreadCount: Int, 46 | blockedWorkerThreadCount: Int, 47 | localQueueFiberCount: Long, 48 | suspendedFiberCount: Long 49 | ) 50 | 51 | case class FiberDump(raw: IArray[String]): 52 | lazy val lines: IArray[String] = 53 | IArray.unsafeFromArray(raw.unsafeArray.dropWhile(_.trim.isEmpty).flatMap(_.split("\n"))) 54 | 55 | private def findMBean(mbeanServer: MBeanServerConnection, name: String): Option[ObjectInstance] = 56 | val namePattern = new ObjectName(name) 57 | mbeanServer.queryMBeans(namePattern, null).asScala.headOption 58 | 59 | def snapshotComputePoolStats(mbeanServer: MBeanServerConnection): Option[ComputePoolStats] = 60 | findMBean(mbeanServer, "cats.effect.unsafe.metrics:type=ComputePoolSampler-*").flatMap: 61 | computePoolMBean => 62 | val attrNames = Array[String]( 63 | "WorkerThreadCount", 64 | "ActiveThreadCount", 65 | "SearchingThreadCount", 66 | "BlockedWorkerThreadCount", 67 | "LocalQueueFiberCount", 68 | "SuspendedFiberCount" 69 | ) 70 | val attrs = 71 | mbeanServer.getAttributes(computePoolMBean.getObjectName(), attrNames).asList.asScala 72 | if attrs.size == attrNames.length then 73 | Some( 74 | ComputePoolStats( 75 | attrs(0).getValue.asInstanceOf[java.lang.Integer].intValue, 76 | attrs(1).getValue.asInstanceOf[java.lang.Integer].intValue, 77 | attrs(2).getValue.asInstanceOf[java.lang.Integer].intValue, 78 | attrs(3).getValue.asInstanceOf[java.lang.Integer].intValue, 79 | attrs(4).getValue.asInstanceOf[java.lang.Long].longValue, 80 | attrs(5).getValue.asInstanceOf[java.lang.Long].longValue 81 | ) 82 | ) 83 | else None 84 | 85 | def snapshotLiveFibers(mbeanServer: MBeanServerConnection): Option[FiberDump] = 86 | findMBean(mbeanServer, "cats.effect.unsafe.metrics:type=LiveFiberSnapshotTrigger-*").flatMap: 87 | fiberMBean => 88 | try 89 | val result = mbeanServer 90 | .invoke(fiberMBean.getObjectName(), "liveFiberSnapshot", Array.empty, Array.empty) 91 | .asInstanceOf[Array[String]] 92 | Some(FiberDump(IArray.unsafeFromArray(result))) 93 | catch case NonFatal(_) => None 94 | -------------------------------------------------------------------------------- /src/main/scala/cats/effect/shell/ConnectionState.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Typelevel 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package cats.effect.shell 18 | 19 | import scala.concurrent.Future 20 | import cats.effect.IO 21 | import cats.effect.std.Dispatcher 22 | 23 | enum ConnectionState: 24 | case Connecting( 25 | override val connectionId: String, 26 | var connection: Option[Either[Throwable, Jmx]], 27 | var cancel: () => Future[Unit] 28 | ) 29 | case Connected(jmx: Jmx) 30 | case Disconnected(override val connectionId: String, error: Option[Throwable]) 31 | 32 | def connectionId: String = this match 33 | case Connecting(connectionId, _, _) => connectionId 34 | case Connected(jmx) => jmx.connectionId 35 | case Disconnected(connectionId, _) => connectionId 36 | 37 | object ConnectionState: 38 | 39 | def apply(dispatcher: Dispatcher[IO], connectionId: String): IO[ConnectionState] = 40 | IO.blocking: 41 | val jmx = Jmx.connectByVmId(connectionId) 42 | ConnectionState.unsafeStartConnect(dispatcher, connectionId, jmx) 43 | 44 | def unsafeStartConnect( 45 | dispatcher: Dispatcher[IO], 46 | connectionId: String, 47 | j: IO[Jmx] 48 | ): ConnectionState = 49 | val state: ConnectionState.Connecting = 50 | ConnectionState.Connecting(connectionId, None, () => Future.unit) 51 | val cancel = dispatcher.unsafeRunCancelable(j.attempt.map: cnx => 52 | state.connection = Some(cnx)) 53 | state.cancel = cancel 54 | state 55 | -------------------------------------------------------------------------------- /src/main/scala/cats/effect/shell/Formats.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Typelevel 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package cats.effect.shell 18 | 19 | import scala.concurrent.duration.FiniteDuration 20 | import com.sun.tools.attach.VirtualMachineDescriptor 21 | 22 | object Formats: 23 | 24 | def durationToDaysThroughSeconds(value: FiniteDuration): String = 25 | val totalSeconds = value.toSeconds 26 | val seconds = totalSeconds % 60 27 | val totalMinutes = totalSeconds / 60 28 | val minutes = totalMinutes % 60 29 | val totalHours = totalMinutes / 60 30 | val hours = totalHours % 24 31 | val days = totalHours / 24 32 | val daysStr = if days > 0 then Some(s"${days}d") else None 33 | val hoursStr = if hours > 0 then Some(s"${hours}h") else None 34 | val minutesStr = if minutes > 0 then Some(s"${minutes}m") else None 35 | val secondsStr = if seconds > 0 then Some(s"${seconds}s") else None 36 | List(daysStr, hoursStr, minutesStr, secondsStr).flatten.mkString(" ") 37 | 38 | def giga(value: Long): String = f"${value / 1_000_000_000.0}%.2f" 39 | 40 | def vmDescriptor(vmd: VirtualMachineDescriptor): String = 41 | s"${vmd.id()} ${vmd.displayName()}" 42 | -------------------------------------------------------------------------------- /src/main/scala/cats/effect/shell/Jmx.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Typelevel 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package cats.effect.shell 18 | 19 | import scala.concurrent.duration.* 20 | import scala.jdk.CollectionConverters.* 21 | 22 | import cats.effect.IO 23 | import com.sun.tools.attach.* 24 | import java.lang.management.{ 25 | ManagementFactory, 26 | MemoryMXBean, 27 | RuntimeMXBean, 28 | PlatformManagedObject, 29 | ThreadInfo, 30 | ThreadMXBean 31 | } 32 | import javax.management.MBeanServerConnection 33 | import javax.management.remote.{JMXConnector, JMXConnectorFactory, JMXServiceURL} 34 | import java.io.IOException 35 | import java.rmi.server.RMISocketFactory 36 | import java.net.{Socket, ServerSocket, InetSocketAddress} 37 | 38 | case class Jmx(connection: Option[JMXConnector], mbeanServer: MBeanServerConnection): 39 | def connectionId: String = connection.map(_.getConnectionId()).getOrElse("self") 40 | 41 | private def proxy[A <: PlatformManagedObject](using ct: reflect.ClassTag[A]): A = 42 | ManagementFactory.getPlatformMXBean(mbeanServer, ct.runtimeClass.asInstanceOf[Class[A]]) 43 | 44 | lazy val memory: MemoryMXBean = proxy[MemoryMXBean] 45 | lazy val runtime: RuntimeMXBean = proxy[RuntimeMXBean] 46 | lazy val thread: ThreadMXBean = proxy[ThreadMXBean] 47 | 48 | def threadInfos: Array[ThreadInfo] = 49 | thread.getThreadInfo(thread.getAllThreadIds()).filterNot(_ == null) 50 | 51 | def disconnect(): Unit = connection.foreach(_.close()) 52 | 53 | object Jmx: 54 | def connectByDescriptor(vmd: VirtualMachineDescriptor): IO[Jmx] = 55 | connectByVmId(vmd.id()).recover: 56 | case t: IOException if t.getMessage().contains("Can not attach to current VM") => connectSelf 57 | 58 | def connectByVmId(vmid: String): IO[Jmx] = IO.interruptibleMany: 59 | val vm = VirtualMachine.attach(vmid) 60 | val jmxUrl = JMXServiceURL(vm.startLocalManagementAgent()) 61 | vm.detach() 62 | attemptConfigureRMISocketTimeouts() 63 | val jmxCnx = JMXConnectorFactory.connect(jmxUrl) 64 | val mbeanServer = jmxCnx.getMBeanServerConnection() 65 | Jmx(Some(jmxCnx), mbeanServer) 66 | 67 | def connectSelf: Jmx = 68 | Jmx(None, ManagementFactory.getPlatformMBeanServer()) 69 | 70 | private def attemptConfigureRMISocketTimeouts(): Unit = 71 | val duration = 5.seconds 72 | try 73 | RMISocketFactory.setSocketFactory(new RMISocketFactory: 74 | def createServerSocket(port: Int): ServerSocket = 75 | new ServerSocket(port) 76 | def createSocket(host: String, port: Int): Socket = 77 | val socket = new Socket() 78 | socket.setSoTimeout(duration.toMillis.toInt) 79 | socket.connect(new InetSocketAddress(host, port), duration.toMillis.toInt) 80 | socket 81 | ) 82 | catch case _: IOException => () 83 | def localProcesses: List[VirtualMachineDescriptor] = VirtualMachine.list().asScala.toList 84 | -------------------------------------------------------------------------------- /src/main/scala/cats/effect/shell/Main.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Typelevel 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package cats.effect.shell 18 | 19 | import cats.effect.{IO, IOApp, ExitCode, Resource} 20 | import cats.syntax.all.* 21 | import fs2.{Stream, Chunk} 22 | import tui.* 23 | import tui.crossterm.{Command, CrosstermJni, Duration, Event, KeyCode} 24 | import tui.widgets.* 25 | import tui.widgets.tabs.TabsWidget 26 | import scala.concurrent.duration.* 27 | import cats.effect.std.Dispatcher 28 | import java.lang.management.ThreadInfo 29 | 30 | object Main extends IOApp: 31 | 32 | def run(args: List[String]) = 33 | val prg = for 34 | dispatcher <- Dispatcher.parallel[IO] 35 | cnxState <- args.headOption.traverse(vmid => Resource.eval(ConnectionState(dispatcher, vmid))) 36 | jni <- crosstermJni 37 | terminal <- terminal(jni) 38 | result <- Resource.eval(runDisplayLoop(jni, terminal, cnxState, dispatcher)) 39 | yield result 40 | prg.use_.as(ExitCode.Success) 41 | 42 | def crosstermJni: Resource[IO, CrosstermJni] = 43 | Resource.apply: 44 | IO.blocking: 45 | // From tui's withTerminal 46 | val jni = new CrosstermJni 47 | jni.enableRawMode() 48 | jni.execute(new Command.EnterAlternateScreen(), new Command.EnableMouseCapture()) 49 | val cleanup = IO.blocking: 50 | jni.disableRawMode() 51 | jni.execute(new Command.LeaveAlternateScreen(), new Command.DisableMouseCapture()) 52 | (jni, cleanup) 53 | 54 | def terminal(jni: CrosstermJni): Resource[IO, Terminal] = 55 | Resource.apply: 56 | IO.blocking: 57 | val backend = new CrosstermBackend(jni) 58 | val cleanup = IO.blocking(backend.showCursor()) 59 | (Terminal.init(backend), cleanup) 60 | 61 | def runDisplayLoop( 62 | jni: CrosstermJni, 63 | terminal: Terminal, 64 | optCnxState: Option[ConnectionState], 65 | dispatcher: Dispatcher[IO] 66 | ): IO[Unit] = 67 | optCnxState match 68 | case Some(cnxState) => 69 | val shouldExit = runMonitoringProcess(jni, terminal, cnxState) 70 | if shouldExit then IO.unit else runDisplayLoop(jni, terminal, None, dispatcher) 71 | case None => 72 | runSelect(jni, terminal, dispatcher) match 73 | case cnxState @ Some(_) => runDisplayLoop(jni, terminal, cnxState, dispatcher) 74 | case None => IO.unit 75 | 76 | case class ProcessSelectionState( 77 | list: StatefulList[com.sun.tools.attach.VirtualMachineDescriptor], 78 | var lastRefresh: Long 79 | ): 80 | def possiblyRefresh(): Unit = 81 | if (lastRefresh - System.currentTimeMillis()).abs > 1000L then refresh() 82 | 83 | def refresh(): Unit = 84 | list.setItems(Jmx.localProcesses.toArray) 85 | lastRefresh = System.currentTimeMillis() 86 | 87 | def runSelect( 88 | jni: CrosstermJni, 89 | terminal: Terminal, 90 | dispatcher: Dispatcher[IO] 91 | ): Option[ConnectionState] = 92 | var done = false 93 | var result: Option[ConnectionState] = None 94 | val state = ProcessSelectionState(StatefulList.fromItems(Array.empty), 0L) 95 | while !done do 96 | state.possiblyRefresh() 97 | terminal.draw(f => uiSelect(f, state)) 98 | val polled = jni.poll(Duration(1L, 0)) 99 | if polled then 100 | jni.read() match 101 | case key: Event.Key => 102 | key.keyEvent.code match 103 | case char: KeyCode.Char => 104 | char.c() match 105 | case 'q' => done = true 106 | case 'j' => state.list.next() 107 | case 'k' => state.list.previous() 108 | case _ => () 109 | case _: KeyCode.Down => state.list.next() 110 | case _: KeyCode.Up => state.list.previous() 111 | case char: KeyCode.Enter => 112 | state.list.selectedItem match 113 | case Some(vmd) => 114 | done = true 115 | val connection = 116 | ConnectionState.unsafeStartConnect( 117 | dispatcher, 118 | vmd.id(), 119 | Jmx.connectByDescriptor(vmd) 120 | ) 121 | result = Some(connection) 122 | case None => () 123 | case _ => () 124 | case _ => () 125 | result 126 | 127 | val Bold = Style.DEFAULT.addModifier(Modifier.BOLD) 128 | 129 | def controlsText(controls: (String, String)*): Text = 130 | val controlSpans = Stream 131 | .chunk(Chunk.from(controls)) 132 | .map((k, v) => Stream(Span.styled(k, Bold), Span.nostyle(" = "), Span.nostyle(v))) 133 | .intersperse(Stream(Span.nostyle(", "))) 134 | .flatten 135 | .toList 136 | val spans = Span.nostyle("Controls: ") :: controlSpans 137 | Text.from(spans*) 138 | 139 | def uiSelect(f: Frame, state: ProcessSelectionState): Unit = 140 | val chunks = Layout( 141 | direction = Direction.Vertical, 142 | constraints = Array(Constraint.Min(2), Constraint.Percentage(100)) 143 | ).split(f.size) 144 | f.renderWidget( 145 | ListWidget(items = 146 | Array( 147 | ListWidget.Item(controlsText("↑↓" -> "scroll", "↲" -> "connect", "q" -> "quit")), 148 | ListWidget.Item(Text.from(Span.nostyle("Select a process to monitor:"))) 149 | ) 150 | ), 151 | chunks(0) 152 | ) 153 | val items = 154 | state.list.items.map(vmd => 155 | ListWidget.Item(Text.from(Span.nostyle(Formats.vmDescriptor(vmd)))) 156 | ) 157 | val processes = ListWidget( 158 | block = Some(BlockWidget(title = Some(Spans.nostyle("Processes")), borders = Borders.ALL)), 159 | items = items, 160 | highlightSymbol = Some(">> "), 161 | highlightStyle = Bold 162 | ) 163 | f.renderStatefulWidget(processes, chunks(1))(state.list.state) 164 | 165 | enum ProcessMonitoringTab: 166 | case Threads, Fibers, FiberDump 167 | 168 | extension (pmt: ProcessMonitoringTab) 169 | def humanized: String = pmt match 170 | case ProcessMonitoringTab.FiberDump => "Fiber Dump" 171 | case other => other.toString 172 | 173 | case class ProcessMonitoringState( 174 | jmx: Jmx, 175 | activeTab: ProcessMonitoringTab, 176 | threads: StatefulList[ThreadInfo], 177 | fiberDump: Option[CeJmx.FiberDump], 178 | var lastRefresh: Long 179 | ): 180 | def possiblyRefresh(): Unit = 181 | if (lastRefresh - System.currentTimeMillis()).abs > 1000L then refresh() 182 | 183 | def refresh(): Unit = 184 | threads.setItems(jmx.threadInfos) 185 | lastRefresh = System.currentTimeMillis() 186 | 187 | def runMonitoringProcess( 188 | jni: CrosstermJni, 189 | terminal: Terminal, 190 | cnxState0: ConnectionState 191 | ): Boolean = 192 | var done = false 193 | var shouldExit = false 194 | var cnxState = cnxState0 195 | var monitoringState: ProcessMonitoringState = null 196 | while !done do 197 | cnxState = cnxState match 198 | case ConnectionState.Connecting(_, Some(Right(jmx)), _) => ConnectionState.Connected(jmx) 199 | case ConnectionState.Connecting(id, Some(Left(err)), _) => 200 | ConnectionState.Disconnected(id, Some(err)) 201 | case _ => cnxState 202 | if monitoringState eq null then 203 | cnxState match 204 | case ConnectionState.Connected(jmx) => 205 | monitoringState = ProcessMonitoringState( 206 | jmx, 207 | ProcessMonitoringTab.Threads, 208 | StatefulList.fromItems(Array.empty), 209 | None, 210 | 0L 211 | ) 212 | case _ => () 213 | else if monitoringState.activeTab == ProcessMonitoringTab.FiberDump && monitoringState.fiberDump.isEmpty 214 | then 215 | cnxState match 216 | case ConnectionState.Connected(jmx) => 217 | monitoringState = 218 | monitoringState.copy(fiberDump = CeJmx.snapshotLiveFibers(jmx.mbeanServer)) 219 | case _ => () 220 | else monitoringState.possiblyRefresh() 221 | 222 | terminal.draw(f => 223 | cnxState match 224 | case cnx: ConnectionState.Connected => uiConnected(f, cnx.jmx, monitoringState) 225 | case _ => uiDisconnected(f, cnxState) 226 | ) 227 | val polled = jni.poll(Duration(0L, 100_000_000)) 228 | if polled then 229 | jni.read() match 230 | case key: Event.Key => 231 | key.keyEvent.code match 232 | case char: KeyCode.Char if char.c() == 'q' => 233 | done = true; shouldExit = true 234 | case char: KeyCode.Char if char.c() == 'd' => 235 | cnxState match 236 | case ConnectionState.Connecting(_, _, cancel) => cancel() 237 | case ConnectionState.Connected(jmx) => jmx.disconnect() 238 | case _ => () 239 | done = true 240 | case char: KeyCode.Char if char.c() >= '1' && char.c() <= '9' => 241 | cnxState match 242 | case ConnectionState.Connected(_) => 243 | val ordinal = char.c().toInt - '0' - 1 244 | if ordinal >= 0 && ordinal < ProcessMonitoringTab.values.length then 245 | val newSelection = ProcessMonitoringTab.values(ordinal) 246 | monitoringState = monitoringState.copy(activeTab = newSelection) 247 | case _ => () 248 | case char: KeyCode.Char if char.c() == 'f' => 249 | cnxState match 250 | case ConnectionState.Connected(jmx) => 251 | monitoringState = 252 | monitoringState.copy(fiberDump = CeJmx.snapshotLiveFibers(jmx.mbeanServer)) 253 | case _ => () 254 | case _ => () 255 | case _ => () 256 | shouldExit 257 | 258 | def uiDisconnected(f: Frame, cnxState: ConnectionState): Unit = 259 | val cnxStateSpan = cnxState match 260 | case _: ConnectionState.Connecting => Span.styled(s" (CONNECTING)", Bold.fg(Color.Cyan)) 261 | case _: ConnectionState.Connected => Span.styled(s" (CONNECTED)", Bold.fg(Color.Green)) 262 | case ConnectionState.Disconnected(_, err) => 263 | Span.styled( 264 | s" (DISCONNECTED)", 265 | Bold.fg(if err.isDefined then Color.Red else Color.DarkGray) 266 | ) 267 | val err = cnxState match 268 | case ConnectionState.Disconnected(_, Some(err)) => err.getMessage() 269 | case _ => "" 270 | val summary = ListWidget( 271 | items = Array( 272 | ListWidget.Item( 273 | Text.from(Span.nostyle("Connection: "), Span.nostyle(cnxState.connectionId), cnxStateSpan) 274 | ), 275 | ListWidget.Item(controlsText("d" -> "disconnect", "q" -> "quit")), 276 | ListWidget.Item(Text.from(Span.styled(err, Style.DEFAULT.fg(Color.Red)))) 277 | ) 278 | ) 279 | f.renderWidget(summary, f.size) 280 | 281 | def uiConnected(f: Frame, jmx: Jmx, state: ProcessMonitoringState): Unit = 282 | val chunks = Layout( 283 | direction = Direction.Vertical, 284 | constraints = Array(Constraint.Min(4), Constraint.Length(3), Constraint.Percentage(100)) 285 | ).split(f.size) 286 | 287 | val heap = jmx.memory.getHeapMemoryUsage() 288 | val heapPercentage = (heap.getUsed() / heap.getMax().toDouble) * 100 289 | 290 | val summary = ListWidget( 291 | items = Array( 292 | ListWidget.Item( 293 | Text 294 | .from( 295 | Span.nostyle("Connection: "), 296 | Span.nostyle(jmx.connectionId), 297 | Span.styled(" (CONNECTED)", Bold.fg(Color.Green)) 298 | ) 299 | ), 300 | ListWidget.Item( 301 | Text.from( 302 | Span.styled("Uptime: ", Bold), 303 | Span.nostyle(Formats.durationToDaysThroughSeconds(jmx.runtime.getUptime().millis)) 304 | ) 305 | ), 306 | ListWidget.Item( 307 | Text.from( 308 | Span.styled("Heap: ", Bold), 309 | Span.nostyle( 310 | s"${heapPercentage.toInt}% (${Formats.giga(heap.getUsed)}GB / ${Formats.giga(heap.getMax)}GB)" 311 | ) 312 | ) 313 | ), 314 | ListWidget.Item(controlsText("d" -> "disconnect", "q" -> "quit")) 315 | ) 316 | ) 317 | f.renderWidget(summary, chunks(0)) 318 | 319 | val titles = 320 | ProcessMonitoringTab.values.map(v => Spans.nostyle(s"${v.humanized} [${v.ordinal + 1}]")) 321 | val tabs = TabsWidget( 322 | titles = titles, 323 | block = Some(BlockWidget(borders = Borders.NONE, title = Some(Spans.nostyle("")))), 324 | selected = state.activeTab.ordinal, 325 | highlightStyle = Style(addModifier = Modifier.BOLD, bg = Some(Color.Black)) 326 | ) 327 | f.renderWidget(tabs, chunks(1)) 328 | 329 | state.activeTab match 330 | case ProcessMonitoringTab.Threads => 331 | val threads = ListWidget( 332 | block = Some(BlockWidget(title = Some(Spans.nostyle("Threads")), borders = Borders.ALL)), 333 | items = state.threads.items.map(ti => 334 | ListWidget.Item( 335 | Text.from( 336 | Span.nostyle(s"[${ti.getThreadId()}] ${ti.getThreadName} (${ti.getThreadState()})") 337 | ) 338 | ) 339 | ) 340 | ) 341 | f.renderStatefulWidget(threads, chunks(2))(state.threads.state) 342 | case ProcessMonitoringTab.Fibers => 343 | CeJmx.snapshotComputePoolStats(jmx.mbeanServer) match 344 | case Some(poolStats) => 345 | val poolBlock = ListWidget( 346 | items = Array( 347 | ListWidget.Item( 348 | Text.from( 349 | Span.styled("Worker Threads: ", Bold), 350 | Span.nostyle(poolStats.workerThreadCount.toString), 351 | Span.nostyle(" total, "), 352 | Span.nostyle(poolStats.activeThreadCount.toString), 353 | Span.nostyle(" active, "), 354 | Span.nostyle(poolStats.searchingThreadCount.toString), 355 | Span.nostyle(" searching, "), 356 | Span.styled( 357 | poolStats.blockedWorkerThreadCount.toString, 358 | if poolStats.blockedWorkerThreadCount > 0 then Style.DEFAULT.fg(Color.Red) 359 | else Style.DEFAULT 360 | ), 361 | Span.nostyle(" blocked "), 362 | Span.styled("Fibers: ", Bold), 363 | Span.nostyle(poolStats.localQueueFiberCount.toString), 364 | Span.nostyle(" queued, "), 365 | Span.nostyle(poolStats.suspendedFiberCount.toString), 366 | Span.nostyle(" suspended") 367 | ) 368 | ) 369 | ) 370 | ) 371 | f.renderWidget(poolBlock, chunks(2)) 372 | case None => 373 | f.renderWidget( 374 | ParagraphWidget(Text.from(Span.nostyle("Cats Effect support not detected!"))), 375 | chunks(2) 376 | ) 377 | case ProcessMonitoringTab.FiberDump => 378 | state.fiberDump.foreach: fiberDump => 379 | val text = Text(fiberDump.lines.unsafeArray.map(ln => Spans.from(Span.nostyle(ln)))) 380 | f.renderWidget(ParagraphWidget(text), chunks(2)) 381 | -------------------------------------------------------------------------------- /src/main/scala/cats/effect/shell/StatefulList.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 Typelevel 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package cats.effect.shell 18 | 19 | import tui.widgets.ListWidget 20 | 21 | case class StatefulList[A]( 22 | state: ListWidget.State, 23 | var items: Array[A] 24 | ): 25 | def next(): Unit = 26 | val newIndex = state.selected match 27 | case Some(i) => (i + 1).min(items.length - 1) 28 | case None => 0 29 | state.select(Some(newIndex)) 30 | 31 | def previous(): Unit = 32 | val newIndex = state.selected match 33 | case Some(i) => (i - 1).max(0) 34 | case None => 0 35 | state.select(Some(newIndex)) 36 | 37 | def setItems(newItems: Array[A]): Unit = 38 | val oldSelectedItem = selectedItem 39 | items = newItems 40 | oldSelectedItem.foreach: otm => 41 | val indexOfItemToSelect = items.indexOf(otm) 42 | if indexOfItemToSelect >= 0 then state.select(Some(indexOfItemToSelect)) 43 | else state.select(None) 44 | 45 | def selectedItem: Option[A] = 46 | state.selected.map(items) 47 | 48 | object StatefulList: 49 | def fromItems[A](items: Array[A]): StatefulList[A] = 50 | StatefulList(ListWidget.State(), items) 51 | --------------------------------------------------------------------------------