├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── doc └── intro.md ├── project.clj ├── src └── inspector │ ├── core.clj │ ├── fn_find.clj │ ├── inspector.clj │ ├── middleware │ ├── capture.clj │ └── export.clj │ ├── printer.clj │ ├── track.clj │ └── utils.clj └── test └── inspector └── test ├── core_test.clj ├── inspector_test.clj ├── middleware ├── capture_test.clj └── export_test.clj ├── printer_test.clj └── track_test.clj /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /classes 3 | /checkouts 4 | profiles.clj 5 | pom.xml 6 | pom.xml.asc 7 | *.jar 8 | *.class 9 | /.lein-* 10 | /.nrepl-port 11 | /.prepl-port 12 | .hgignore 13 | .hg/ 14 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | 3 | ## 0.4.0 - 2023-10-12 4 | ### Added 5 | - Initial commit. -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Eclipse Public License - v 2.0 2 | 3 | THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE 4 | PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION 5 | OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. 6 | 7 | 1. DEFINITIONS 8 | 9 | "Contribution" means: 10 | 11 | a) in the case of the initial Contributor, the initial content 12 | Distributed under this Agreement, and 13 | 14 | b) in the case of each subsequent Contributor: 15 | i) changes to the Program, and 16 | ii) additions to the Program; 17 | where such changes and/or additions to the Program originate from 18 | and are Distributed by that particular Contributor. A Contribution 19 | "originates" from a Contributor if it was added to the Program by 20 | such Contributor itself or anyone acting on such Contributor's behalf. 21 | Contributions do not include changes or additions to the Program that 22 | are not Modified Works. 23 | 24 | "Contributor" means any person or entity that Distributes the Program. 25 | 26 | "Licensed Patents" mean patent claims licensable by a Contributor which 27 | are necessarily infringed by the use or sale of its Contribution alone 28 | or when combined with the Program. 29 | 30 | "Program" means the Contributions Distributed in accordance with this 31 | Agreement. 32 | 33 | "Recipient" means anyone who receives the Program under this Agreement 34 | or any Secondary License (as applicable), including Contributors. 35 | 36 | "Derivative Works" shall mean any work, whether in Source Code or other 37 | form, that is based on (or derived from) the Program and for which the 38 | editorial revisions, annotations, elaborations, or other modifications 39 | represent, as a whole, an original work of authorship. 40 | 41 | "Modified Works" shall mean any work in Source Code or other form that 42 | results from an addition to, deletion from, or modification of the 43 | contents of the Program, including, for purposes of clarity any new file 44 | in Source Code form that contains any contents of the Program. Modified 45 | Works shall not include works that contain only declarations, 46 | interfaces, types, classes, structures, or files of the Program solely 47 | in each case in order to link to, bind by name, or subclass the Program 48 | or Modified Works thereof. 49 | 50 | "Distribute" means the acts of a) distributing or b) making available 51 | in any manner that enables the transfer of a copy. 52 | 53 | "Source Code" means the form of a Program preferred for making 54 | modifications, including but not limited to software source code, 55 | documentation source, and configuration files. 56 | 57 | "Secondary License" means either the GNU General Public License, 58 | Version 2.0, or any later versions of that license, including any 59 | exceptions or additional permissions as identified by the initial 60 | Contributor. 61 | 62 | 2. GRANT OF RIGHTS 63 | 64 | a) Subject to the terms of this Agreement, each Contributor hereby 65 | grants Recipient a non-exclusive, worldwide, royalty-free copyright 66 | license to reproduce, prepare Derivative Works of, publicly display, 67 | publicly perform, Distribute and sublicense the Contribution of such 68 | Contributor, if any, and such Derivative Works. 69 | 70 | b) Subject to the terms of this Agreement, each Contributor hereby 71 | grants Recipient a non-exclusive, worldwide, royalty-free patent 72 | license under Licensed Patents to make, use, sell, offer to sell, 73 | import and otherwise transfer the Contribution of such Contributor, 74 | if any, in Source Code or other form. This patent license shall 75 | apply to the combination of the Contribution and the Program if, at 76 | the time the Contribution is added by the Contributor, such addition 77 | of the Contribution causes such combination to be covered by the 78 | Licensed Patents. The patent license shall not apply to any other 79 | combinations which include the Contribution. No hardware per se is 80 | licensed hereunder. 81 | 82 | c) Recipient understands that although each Contributor grants the 83 | licenses to its Contributions set forth herein, no assurances are 84 | provided by any Contributor that the Program does not infringe the 85 | patent or other intellectual property rights of any other entity. 86 | Each Contributor disclaims any liability to Recipient for claims 87 | brought by any other entity based on infringement of intellectual 88 | property rights or otherwise. As a condition to exercising the 89 | rights and licenses granted hereunder, each Recipient hereby 90 | assumes sole responsibility to secure any other intellectual 91 | property rights needed, if any. For example, if a third party 92 | patent license is required to allow Recipient to Distribute the 93 | Program, it is Recipient's responsibility to acquire that license 94 | before distributing the Program. 95 | 96 | d) Each Contributor represents that to its knowledge it has 97 | sufficient copyright rights in its Contribution, if any, to grant 98 | the copyright license set forth in this Agreement. 99 | 100 | e) Notwithstanding the terms of any Secondary License, no 101 | Contributor makes additional grants to any Recipient (other than 102 | those set forth in this Agreement) as a result of such Recipient's 103 | receipt of the Program under the terms of a Secondary License 104 | (if permitted under the terms of Section 3). 105 | 106 | 3. REQUIREMENTS 107 | 108 | 3.1 If a Contributor Distributes the Program in any form, then: 109 | 110 | a) the Program must also be made available as Source Code, in 111 | accordance with section 3.2, and the Contributor must accompany 112 | the Program with a statement that the Source Code for the Program 113 | is available under this Agreement, and informs Recipients how to 114 | obtain it in a reasonable manner on or through a medium customarily 115 | used for software exchange; and 116 | 117 | b) the Contributor may Distribute the Program under a license 118 | different than this Agreement, provided that such license: 119 | i) effectively disclaims on behalf of all other Contributors all 120 | warranties and conditions, express and implied, including 121 | warranties or conditions of title and non-infringement, and 122 | implied warranties or conditions of merchantability and fitness 123 | for a particular purpose; 124 | 125 | ii) effectively excludes on behalf of all other Contributors all 126 | liability for damages, including direct, indirect, special, 127 | incidental and consequential damages, such as lost profits; 128 | 129 | iii) does not attempt to limit or alter the recipients' rights 130 | in the Source Code under section 3.2; and 131 | 132 | iv) requires any subsequent distribution of the Program by any 133 | party to be under a license that satisfies the requirements 134 | of this section 3. 135 | 136 | 3.2 When the Program is Distributed as Source Code: 137 | 138 | a) it must be made available under this Agreement, or if the 139 | Program (i) is combined with other material in a separate file or 140 | files made available under a Secondary License, and (ii) the initial 141 | Contributor attached to the Source Code the notice described in 142 | Exhibit A of this Agreement, then the Program may be made available 143 | under the terms of such Secondary Licenses, and 144 | 145 | b) a copy of this Agreement must be included with each copy of 146 | the Program. 147 | 148 | 3.3 Contributors may not remove or alter any copyright, patent, 149 | trademark, attribution notices, disclaimers of warranty, or limitations 150 | of liability ("notices") contained within the Program from any copy of 151 | the Program which they Distribute, provided that Contributors may add 152 | their own appropriate notices. 153 | 154 | 4. COMMERCIAL DISTRIBUTION 155 | 156 | Commercial distributors of software may accept certain responsibilities 157 | with respect to end users, business partners and the like. While this 158 | license is intended to facilitate the commercial use of the Program, 159 | the Contributor who includes the Program in a commercial product 160 | offering should do so in a manner which does not create potential 161 | liability for other Contributors. Therefore, if a Contributor includes 162 | the Program in a commercial product offering, such Contributor 163 | ("Commercial Contributor") hereby agrees to defend and indemnify every 164 | other Contributor ("Indemnified Contributor") against any losses, 165 | damages and costs (collectively "Losses") arising from claims, lawsuits 166 | and other legal actions brought by a third party against the Indemnified 167 | Contributor to the extent caused by the acts or omissions of such 168 | Commercial Contributor in connection with its distribution of the Program 169 | in a commercial product offering. The obligations in this section do not 170 | apply to any claims or Losses relating to any actual or alleged 171 | intellectual property infringement. In order to qualify, an Indemnified 172 | Contributor must: a) promptly notify the Commercial Contributor in 173 | writing of such claim, and b) allow the Commercial Contributor to control, 174 | and cooperate with the Commercial Contributor in, the defense and any 175 | related settlement negotiations. The Indemnified Contributor may 176 | participate in any such claim at its own expense. 177 | 178 | For example, a Contributor might include the Program in a commercial 179 | product offering, Product X. That Contributor is then a Commercial 180 | Contributor. If that Commercial Contributor then makes performance 181 | claims, or offers warranties related to Product X, those performance 182 | claims and warranties are such Commercial Contributor's responsibility 183 | alone. Under this section, the Commercial Contributor would have to 184 | defend claims against the other Contributors related to those performance 185 | claims and warranties, and if a court requires any other Contributor to 186 | pay any damages as a result, the Commercial Contributor must pay 187 | those damages. 188 | 189 | 5. NO WARRANTY 190 | 191 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT 192 | PERMITTED BY APPLICABLE LAW, THE PROGRAM IS PROVIDED ON AN "AS IS" 193 | BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR 194 | IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF 195 | TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR 196 | PURPOSE. Each Recipient is solely responsible for determining the 197 | appropriateness of using and distributing the Program and assumes all 198 | risks associated with its exercise of rights under this Agreement, 199 | including but not limited to the risks and costs of program errors, 200 | compliance with applicable laws, damage to or loss of data, programs 201 | or equipment, and unavailability or interruption of operations. 202 | 203 | 6. DISCLAIMER OF LIABILITY 204 | 205 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT 206 | PERMITTED BY APPLICABLE LAW, NEITHER RECIPIENT NOR ANY CONTRIBUTORS 207 | SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 208 | EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST 209 | PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 210 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 211 | ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE 212 | EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE 213 | POSSIBILITY OF SUCH DAMAGES. 214 | 215 | 7. GENERAL 216 | 217 | If any provision of this Agreement is invalid or unenforceable under 218 | applicable law, it shall not affect the validity or enforceability of 219 | the remainder of the terms of this Agreement, and without further 220 | action by the parties hereto, such provision shall be reformed to the 221 | minimum extent necessary to make such provision valid and enforceable. 222 | 223 | If Recipient institutes patent litigation against any entity 224 | (including a cross-claim or counterclaim in a lawsuit) alleging that the 225 | Program itself (excluding combinations of the Program with other software 226 | or hardware) infringes such Recipient's patent(s), then such Recipient's 227 | rights granted under Section 2(b) shall terminate as of the date such 228 | litigation is filed. 229 | 230 | All Recipient's rights under this Agreement shall terminate if it 231 | fails to comply with any of the material terms or conditions of this 232 | Agreement and does not cure such failure in a reasonable period of 233 | time after becoming aware of such noncompliance. If all Recipient's 234 | rights under this Agreement terminate, Recipient agrees to cease use 235 | and distribution of the Program as soon as reasonably practicable. 236 | However, Recipient's obligations under this Agreement and any licenses 237 | granted by Recipient relating to the Program shall continue and survive. 238 | 239 | Everyone is permitted to copy and distribute copies of this Agreement, 240 | but in order to avoid inconsistency the Agreement is copyrighted and 241 | may only be modified in the following manner. The Agreement Steward 242 | reserves the right to publish new versions (including revisions) of 243 | this Agreement from time to time. No one other than the Agreement 244 | Steward has the right to modify this Agreement. The Eclipse Foundation 245 | is the initial Agreement Steward. The Eclipse Foundation may assign the 246 | responsibility to serve as the Agreement Steward to a suitable separate 247 | entity. Each new version of the Agreement will be given a distinguishing 248 | version number. The Program (including Contributions) may always be 249 | Distributed subject to the version of the Agreement under which it was 250 | received. In addition, after a new version of the Agreement is published, 251 | Contributor may elect to Distribute the Program (including its 252 | Contributions) under the new version. 253 | 254 | Except as expressly stated in Sections 2(a) and 2(b) above, Recipient 255 | receives no rights or licenses to the intellectual property of any 256 | Contributor under this Agreement, whether expressly, by implication, 257 | estoppel or otherwise. All rights in the Program not expressly granted 258 | under this Agreement are reserved. Nothing in this Agreement is intended 259 | to be enforceable by any entity that is not a Contributor or Recipient. 260 | No third-party beneficiary rights are created under this Agreement. 261 | 262 | Exhibit A - Form of Secondary Licenses Notice 263 | 264 | "This Source Code may also be made available under the following 265 | Secondary Licenses when the conditions for such availability set forth 266 | in the Eclipse Public License, v. 2.0 are satisfied: GNU General Public 267 | License as published by the Free Software Foundation, either version 2 268 | of the License, or (at your option) any later version, with the GNU 269 | Classpath Exception which is available at 270 | https://www.gnu.org/software/classpath/license.html." 271 | 272 | Simply including a copy of this Agreement, including this Exhibit A 273 | is not sufficient to license the Source Code under Secondary Licenses. 274 | 275 | If it is not possible or desirable to put the notice in a particular 276 | file, then You may include the notice in a location (such as a LICENSE 277 | file in a relevant directory) where a recipient would be likely to 278 | look for such a notice. 279 | 280 | You may add additional accurate notices of copyright ownership. 281 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # inspector 2 | 3 | [![Clojars Project](https://img.shields.io/clojars/v/org.clojars.akshay/inspector.svg)](https://clojars.org/org.clojars.akshay/inspector) 4 | [![Clojars Project](https://img.shields.io/clojars/v/org.clojars.akshay/inspector.svg?include_prereleases)](https://clojars.org/org.clojars.akshay/inspector) 5 | 6 | **Inspector** is a tool for profiling, debugging, tracing, and visualizing function call hierarchies in Clojure applications. It provides insights into who is calling whom, with what arguments, what was returned, execution time, and more. 7 | 8 | # Table of Contents 9 | - [Add dependency](#Add-dependency) 10 | - [Features](#Features) 11 | - [Basic Usage](#Basic-Usage) 12 | - [Setup](#Setup) 13 | - [Normal mode](#Normal-mode) 14 | - [Omnipresent mode](#Omnipresent-mode) 15 | - [Important Notes](#Important-Notes) 16 | - [Detailed Usage](#Detailed-Usage) 17 | - [Normal Mode: Output](#Normal-Mode-Output) 18 | - [Normal Mode: Raw Data](#Normal-Mode-Raw-Data) 19 | - [Omnipresent Mode: REPL](#Omnipresent-Mode-REPL) 20 | - [Tracking Specific Functions or Namespaces](#Tracking-Specific-Functions-or-Namespaces) 21 | - [Skipping Function Tracking](#Skipping-Function-Tracking) 22 | - [Middleware](#Middleware) 23 | 24 | ## Add dependency 25 | Add the following dependency to your project: 26 | ### Leiningen 27 | ```clojure 28 | [org.clojars.akshay/inspector "1.1.3"] 29 | ``` 30 | 31 | ### Clojure CLI/deps.edn 32 | ```clojure 33 | org.clojars.akshay/inspector {:mvn/version "1.1.3"} 34 | ``` 35 | 36 | ## Features 37 | - **Minimal API**: `get-vars`, `iprint`, `ispit`, `stream-raw`. 38 | - **Fine-grained control**: Track specific functions and namespaces. 39 | - **Low performance overhead**. 40 | - **Multiple Modes**: 41 | - **Normal Mode**: Get human-readable output for specific function calls. (`iprint`, `ispit`) 42 | - **Omnipresent Mode**: Continuously capture function calls across all threads. (`stream-raw`) 43 | - **Middleware**: Inject custom code before and after tracked functions executions. 44 | - **Detailed Insights for Each Function Call**: 45 | - `:fn-name`: Namespace-qualified function name. 46 | - `:time`: Execution time (in nanoseconds). 47 | - `:fn-args`: Arguments passed. 48 | - `:fn-rv`: Return value. 49 | - `:e`: Errors (if any). 50 | - `:id`: Unique ID for the function call. 51 | - `:tid`: Thread ID. 52 | - `:c-id`: Caller’s ID. 53 | - `:c-tid`: Caller’s thread ID. 54 | - `:c-chain`: Call chain (vector of function ids). 55 | - `:uuid`: All function calls resulting from a top-level function invocation have same uuid. 56 | 57 | 58 | ## Basic Usage 59 | 60 | ### Setup 61 | Start by requiring the necessary namespace: 62 | ```clojure 63 | (require '[inspector.inspector :as i]) 64 | ``` 65 | Next, define the functions you want to track using get-vars: 66 | ```clojure 67 | (def tracked-vars (i/get-vars #"project-prefix.*")) 68 | ``` 69 | 70 | ### Normal mode 71 | To print function calls in a readable format, use: 72 | ```clojure 73 | (i/iprint tracked-vars #(my-fn arg1 arg2 argn)) 74 | ``` 75 | Or, write the output to a file: 76 | ```clojure 77 | (i/ispit "/tmp/hierarchy.log" tracked-vars #(my-fn arg1 arg2 argn)) 78 | ``` 79 | Example output from `inspector.test.inspector-test`: 80 | ```roomsql 81 | Time: Tue Jan 23 16:28:30 IST 2024 82 | Г-- inspector.test.inspector-test/parallel (1) <-- arguments 83 | | Г-- inspector.test.inspector-test/simple (0) 84 | | | Г-- inspector.test.inspector-test/simplest (0) 85 | | | L-- 0 86 | | L-- 0 87 | | Г-- inspector.test.inspector-test/simple (1) 88 | | | Г-- inspector.test.inspector-test/simplest (1) 89 | | | L-- 1 90 | | L-- 1 91 | L-- [0 1] <-- return value 92 | ``` 93 | 94 | ### Omnipresent mode 95 | To capture data continuously: 96 | ```clojure 97 | (defn ^:i-skip export 98 | [{:keys [:fn-name :fn-args :fn-rv :e :time :id :tid :c-id :c-tid :c-chain :uuid]} :as record] 99 | ;; Handle the captured data (e.g., log it, send to a database, etc.) 100 | (clojure.tools.logging/info (dissoc record :fn-args :fn-rv))) 101 | 102 | ;; export will be called every time a function execution completes 103 | ;; place it somewhere near the top of -main function 104 | (i/stream-raw tracked-vars export) 105 | ``` 106 | 107 | ### Important Notes 108 | - **Normal Mode** (`iprint`, `ispit`): Use for targeted debugging of specific top level function. 109 | - **Omnipresent Mode** (`stream-raw`): Use for continuous data collection. When running **via repl** in a remote environment (staging/production), restore the environment as described in [Omnipresent Mode: REPL](#Omnipresent-Mode-REPL). 110 | 111 | 112 | ## Detailed Usage 113 | ### Normal Mode: Output 114 | Customize the output of `iprint` and `ispit` using options. 115 | ```clojure 116 | (i/iprint tracked-vars #(my-fn arg1 arg2) {:start [:time :fn-args]}) 117 | ``` 118 | Output: 119 | ```roomsql 120 | Г-- fn-name time fn-args 121 | | Г-- fn-name time fn-args 122 | | | Г-- fn-name time fn-args 123 | | | L-- fn-rv 124 | | L-- fn-rv 125 | | Г-- fn-name time fn-args 126 | | L-- fn-rv 127 | L-- fn-rv 128 | ``` 129 | 130 | Another example 131 | ```clojure 132 | (i/iprint tracked-vars #(my-fn arg1 arg2) {:expanded-view? false 133 | :start [:time :fn-rv]}) 134 | ``` 135 | Output: 136 | ```roomsql 137 | --> fn-name time fn-rv 138 | --> fn-name time fn-rv 139 | --> fn-name time fn-rv 140 | --> fn-name time fn-rv 141 | ``` 142 | You can further tweak the output by providing different options to control indentation, markers, and more. 143 | Check `i/parse-opts` to see all possible options. 144 | 145 | ### Normal Mode: Raw Data 146 | Get raw data for advanced processing: 147 | ```clojure 148 | ; rv is return value of (my-fn arg1 arg2 argn) 149 | (let [{:keys [e rv records]} (i/export-raw tracked-vars #(my-fn arg1 arg2 argn)] 150 | records) 151 | ``` 152 | 153 | Example output from `inspector.test.capture-test`: 154 | ```clojure 155 | [{:c-chain [1 2] :id 4 :c-id 2 :fn-name "inspector.test.capture-test/simplest" :fn-args (0) :tid 30 :c-tid 30 :uuid #uuid "4c3bf13a-7899-4202-ade6-cfa0dfc3955e" :time 6584 :fn-rv 0} 156 | {:c-chain [1] :id 2 :c-id 1 :fn-name "inspector.test.capture-test/simple" :fn-args (0) :tid 30 :c-tid 34 :uuid #uuid "4c3bf13a-7899-4202-ade6-cfa0dfc3955e" :time 49583 :fn-rv 0} 157 | {:c-chain [1 3] :id 5 :c-id 3 :fn-name "inspector.test.capture-test/simplest" :fn-args (1) :tid 29 :c-tid 29 :uuid #uuid "4c3bf13a-7899-4202-ade6-cfa0dfc3955e" :time 1625 :fn-rv 1} 158 | {:c-chain [1] :id 3 :c-id 1 :fn-name "inspector.test.capture-test/simple" :fn-args (1) :tid 29 :c-tid 34 :uuid #uuid "4c3bf13a-7899-4202-ade6-cfa0dfc3955e" :time 42625 :fn-rv 1} 159 | {:c-chain [] :id 1 :c-id nil :fn-name "inspector.test.capture-test/parallel" :fn-args (1) :tid 34 :c-tid nil :uuid #uuid "4c3bf13a-7899-4202-ade6-cfa0dfc3955e" :time 431833 :fn-rv [0 1]}] 160 | ``` 161 | 162 | ### Omnipresent Mode: REPL 163 | If you're tracking function calls in a remote environment via REPL by using `stream-raw`, make sure to restore the original function definitions once done: 164 | ```clojure 165 | (inspector.track/un-track tracked-vars) 166 | ``` 167 | 168 | ## Tracking Specific Functions or Namespaces 169 | Use `get-vars` (which returns a set) to collect vars from specific namespaces. Then pass them to `iprint`, `ispit`, or `stream-raw` to start tracking them. 170 | 171 | ```clojure 172 | (i/get-vars #"project-prefix.*") ; set of all functions from all namespaces. 173 | 174 | (i/get-vars #"project-prefix.c") ; set of all functions from project-prefix.c namespace 175 | 176 | (clojure.set/difference ; set of all functions except those defined in project-prefix.c namespace 177 | (i/get-vars #"project-prefix.*") 178 | (i/get-vars #"project-prefix.c")) 179 | 180 | (set/difference ; set of all functions except function project-prefix.c/c-2 181 | (i/get-vars #"project-prefix.*") 182 | #{#'dummy.c/c-2}) 183 | ``` 184 | **Note**:
185 | If the function call sequence is `a -> b -> c` and only `a` and `c` are being tracked, you'll still receive information showing `a -> c`. 186 | 187 | ## Skipping Function Tracking 188 | To skip tracking a specific function, you can either remove its var from tracked-vars or add :`i-skip` metadata: 189 | ```clojure 190 | (defn ^:i-skip foo 191 | [args] 192 | ...) 193 | ``` 194 | 195 | ## Middleware 196 | You can use middleware to run custom code before and after the execution of every tracked function. 197 | 198 | ```clojure 199 | (defn nano->ms-middleware 200 | "Converts execution time from nanoseconds to milliseconds." 201 | [handler] 202 | (fn [{:keys [fn-args fn-meta fn-rv e time id tid c-id c-tid c-chain uuid] :as state}] 203 | (let [new-state (handler state)] 204 | (update new-state :time nano->ms)))) 205 | ``` 206 | To wrap tracked functions with your custom middleware, check out: 207 | - `stream-raw` : for omnipresent mode. 208 | - `export-raw` : for normal mode. 209 | 210 | ## License 211 | 212 | This program and the accompanying materials are made available under the 213 | terms of the Eclipse Public License 2.0 which is available at 214 | http://www.eclipse.org/legal/epl-2.0. 215 | 216 | This Source Code may also be made available under the following Secondary 217 | Licenses when the conditions for such availability set forth in the Eclipse 218 | Public License, v. 2.0 are satisfied: GNU General Public License as published by 219 | the Free Software Foundation, either version 2 of the License, or (at your 220 | option) any later version, with the GNU Classpath Exception which is available 221 | at https://www.gnu.org/software/classpath/license.html. 222 | -------------------------------------------------------------------------------- /doc/intro.md: -------------------------------------------------------------------------------- 1 | # Introduction to inspector 2 | 3 | TODO: write [great documentation](http://jacobian.org/writing/what-to-write/) 4 | -------------------------------------------------------------------------------- /project.clj: -------------------------------------------------------------------------------- 1 | (defproject org.clojars.akshay/inspector "1.1.3" 2 | :description "See when your functions are called. See function call hierarchy, db data used when a particular function is called, and export data" 3 | :url "https://github.com/withjak/inspector" 4 | :license {:name "EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0" 5 | :url "https://www.eclipse.org/legal/epl-2.0/"} 6 | :dependencies [[org.clojure/clojure "1.11.1"]] 7 | :deploy-repositories [["clojars" {:url "https://repo.clojars.org/" 8 | :creds :gpg}]] 9 | :repl-options {:init-ns inspector.core}) -------------------------------------------------------------------------------- /src/inspector/core.clj: -------------------------------------------------------------------------------- 1 | (ns inspector.core) 2 | 3 | (defn get-thread-id 4 | [] 5 | (let [t (Thread/currentThread)] 6 | (try (.threadId t) 7 | (catch Exception e (.getId t))))) 8 | 9 | (def ^:dynamic *modify* 10 | "Visible only to current thread (and threads it spawns)" 11 | false) 12 | 13 | (def modify 14 | "Visible to all threads" 15 | (atom false)) 16 | 17 | ; *state* is dynamic, dynamic is thread local. And in a thread execution is sequential. 18 | (def ^:dynamic *state* 19 | "Contains information that need to be shared in a thread and all its children threads." 20 | nil) 21 | 22 | (def id 23 | "Unique identifier for each function call. 24 | Same fn called with same arguments, will be assigned different id each time its called." 25 | (atom 0)) 26 | 27 | (defn nano-time 28 | [] 29 | (. System (nanoTime))) 30 | 31 | (defn handler 32 | [{:keys [fn-value fn-args] :as state}] 33 | (let [start-time (nano-time) 34 | {:keys [rv e]} (try 35 | {:rv (apply fn-value fn-args)} 36 | (catch Exception e 37 | {:e e})) 38 | time (- (nano-time) start-time) 39 | new-state (assoc state :time time :fn-rv rv :e e)] 40 | new-state)) 41 | 42 | (defn get-handler 43 | [middlewares] 44 | ((apply comp middlewares) handler)) 45 | 46 | (defn get-modified-fn 47 | "Return new value which replaces the original value pointed to by function's var" 48 | ([handler fn-var] 49 | (get-modified-fn handler (deref fn-var) (meta fn-var))) 50 | ([handler fn-value fn-meta] 51 | ; fn-value is the original function value 52 | (fn modified-value 53 | [& args] 54 | (if (or @modify *modify*) 55 | (let [{:keys [id tid uuid c-chain] :as shared-state} {:c-chain (or (:c-chain *state*) []) 56 | :c-tid (:c-tid *state*) ; c-id is sufficient to deduce c-tid, keeping it anyway. 57 | :c-id (:c-id *state*) 58 | :uuid (or (:uuid *state*) (random-uuid)) 59 | :tid (get-thread-id) 60 | :id (swap! id inc) 61 | 62 | :fn-args args 63 | :fn-value fn-value 64 | :fn-meta fn-meta}] 65 | ;; for fns that "f" calls, f's id will be their c-id 66 | (binding [*state* {:c-id id :c-tid tid :uuid uuid :c-chain (conj c-chain id)}] 67 | (let [{:keys [fn-rv e]} (handler shared-state)] 68 | (if e 69 | (throw e) 70 | fn-rv)))) 71 | (apply fn-value args))))) 72 | 73 | (defn with-modify-fns 74 | "In context of current thread (and any children it spawns), 75 | modify `fn-vars` and then call `f` in this modified environment." 76 | [fn-vars f middlewares] 77 | (let [handler (get-handler middlewares)] 78 | (binding [*modify* true] 79 | (with-redefs-fn 80 | (zipmap fn-vars 81 | (map (partial get-modified-fn handler) fn-vars)) ;; modify all given functions 82 | f)))) 83 | 84 | (defn alter-fns 85 | "Alter root binding of `fn-vars` to point to new value which is a wrapper over the original value" 86 | [fn-vars middlewares] 87 | (let [handler (get-handler middlewares)] 88 | (doseq [fn-var fn-vars] 89 | (when-not (or (:i-skip (meta fn-var)) 90 | (:i-original (meta fn-var))) 91 | (alter-meta! fn-var assoc :i-original (deref fn-var)) ; for restoring vars if needed 92 | (alter-var-root fn-var (fn [fn-value] (get-modified-fn handler fn-value (meta fn-var)))))))) 93 | 94 | (defn restore-altered-fns 95 | [fn-vars] 96 | (doseq [fn-var fn-vars] 97 | (when-let [original-value (:i-original (meta fn-var))] 98 | (alter-meta! fn-var dissoc :i-original) 99 | (alter-var-root fn-var (fn [_] original-value))))) 100 | 101 | (comment 102 | ; can you call a: 103 | ; symbol? 104 | ; var? 105 | ; value? 106 | 107 | (defn foo 108 | [a] 109 | (/ 1 a)) 110 | 111 | (defn type-of-thing 112 | [thing] 113 | (cond 114 | (symbol? thing) :symbol 115 | (var? thing) :var 116 | :else :value)) 117 | (map type-of-thing [foo #'foo 'foo]) 118 | (map type [foo #'foo 'foo]) 119 | 120 | ; calling 121 | (#'foo :a) 122 | (foo :a) 123 | ('foo :a) ; ?? 124 | ; interesting 125 | ; https://clojure.org/reference/data_structures#Symbols 126 | ; symbols are just like keywords 127 | ('foo {'foo 1}) 128 | (:a nil) 129 | 130 | ;; Conclusion 131 | ; Function call can be made using either value or var. 132 | ; Symbol cant be used to make a function call directly. See fn resolve 133 | ; ------------------------------- 134 | 135 | ; can we change the value of var in way that metadata of var is not affected? 136 | (meta (var foo)) 137 | (meta #'foo) 138 | 139 | (with-redefs-fn {#'foo (fn [x] :a)} 140 | (fn [] 141 | (println (foo 1)) 142 | ; proves that binding is actually changes 143 | (println (('foo (ns-interns *ns*)) 1)) 144 | ; but metadata has not changes 145 | (meta ('foo (ns-interns *ns*))))) 146 | :conclusion 147 | ; metadata stays unchanged when using with-redefs-fn 148 | ) 149 | -------------------------------------------------------------------------------- /src/inspector/fn_find.clj: -------------------------------------------------------------------------------- 1 | (ns inspector.fn-find) 2 | 3 | (defn matching-ns 4 | "All namespaces whose string representation matches regex." 5 | [regex] 6 | (filter #(re-matches regex (str %)) (all-ns))) 7 | 8 | (defn is-var-fn? 9 | [a-var] 10 | (fn? (deref a-var))) 11 | 12 | (defn macro? 13 | [a-var] 14 | (get (meta a-var) :macro)) 15 | 16 | (defn fn-vars-from-ns 17 | "Returns all var corresponding to function's available in given namespace `ns`" 18 | [ns] 19 | (->> (vals (ns-interns ns)) 20 | (filter is-var-fn?) 21 | (filter #(not (macro? %))))) 22 | 23 | (defn get-vars 24 | "Returns all function vars available in namespaces, 25 | whose string representation matches `regex`." 26 | [regex] 27 | (set 28 | (apply 29 | concat 30 | (map fn-vars-from-ns (matching-ns regex))))) 31 | -------------------------------------------------------------------------------- /src/inspector/inspector.clj: -------------------------------------------------------------------------------- 1 | (ns inspector.inspector 2 | (:require [clojure.set :as s] 3 | [inspector.fn-find :as fn-find] 4 | [inspector.middleware.capture :as capture] 5 | [inspector.middleware.export :as export] 6 | [inspector.track :as track] 7 | [inspector.printer :as printer])) 8 | 9 | (defn get-vars 10 | "Returns all function vars available in namespaces, 11 | whose string representation matches `regex`." 12 | [regex] 13 | (fn-find/get-vars regex)) 14 | 15 | (def inspector-fn-vars 16 | (reduce s/union 17 | (map fn-find/get-vars 18 | [#"inspector.core" 19 | #"inspector.fn-find" 20 | #"inspector.middleware.*" 21 | #"inspector.track" 22 | #"inspector.utils" 23 | #"inspector.printer" 24 | #"inspector.inspector" 25 | #"inspector.test.*"]))) 26 | 27 | (defn remove-inspector-fn-vars 28 | [vars] 29 | (s/difference vars inspector-fn-vars)) 30 | 31 | ;; Omnipresent mode -------------------------------------------------------------- 32 | (defn stream-raw 33 | [vars export-fn] 34 | (track/track 35 | [(partial export/export-middleware export-fn)] 36 | (remove-inspector-fn-vars vars))) 37 | 38 | ;; Normal mode -------------------------------------------------------------- 39 | (defn export-raw 40 | [vars f] 41 | (let [store (atom []) 42 | middlewares [(partial capture/capture-middleware store)]] 43 | (track/with-track 44 | middlewares store 45 | (remove-inspector-fn-vars vars) 46 | f))) 47 | 48 | (defn iprint 49 | [vars f & [opts]] 50 | (let [{:keys [rv e records]} (export-raw vars f)] 51 | (printer/print-call-tree println opts records) 52 | (if e 53 | (throw e) 54 | rv))) 55 | 56 | (defn ispit 57 | [file vars f & [opts]] 58 | (let [{:keys [rv e records]} (export-raw vars f)] 59 | (printer/print-call-tree 60 | (partial printer/print-to-file file) 61 | opts 62 | records) 63 | (if e 64 | (throw e) 65 | rv))) 66 | 67 | #_(defn export 68 | "WIP 69 | Same as `export-raw` with stringify non primitive types present in. 70 | In progress not complete yet" 71 | [vars f] 72 | (let [{:keys [rv records]} (capture/run (remove-inspector-fn-vars vars) f)] 73 | {:rv rv :records (utils/stringify-non-primitives records)})) 74 | 75 | 76 | -------------------------------------------------------------------------------- /src/inspector/middleware/capture.clj: -------------------------------------------------------------------------------- 1 | (ns inspector.middleware.capture 2 | (:require [inspector.utils :as utils])) 3 | 4 | (defn capture-middleware 5 | [store handler] 6 | (fn [state] 7 | (let [new-state (handler state) 8 | record (utils/prepare-fn-record new-state)] 9 | ; store is supposed to be shared between all middlewares 10 | ; so when storing data in store, middleware must always associate its name in the data. 11 | (swap! store conj (assoc record :m-name :capture-middleware)) 12 | new-state))) 13 | -------------------------------------------------------------------------------- /src/inspector/middleware/export.clj: -------------------------------------------------------------------------------- 1 | (ns inspector.middleware.export 2 | (:require [inspector.utils :as utils])) 3 | 4 | (defn export-middleware 5 | [export-fn handler] 6 | (fn [state] 7 | (let [new-state (handler state) 8 | record (utils/prepare-fn-record new-state)] 9 | (export-fn record) 10 | new-state))) 11 | -------------------------------------------------------------------------------- /src/inspector/printer.clj: -------------------------------------------------------------------------------- 1 | (ns inspector.printer 2 | (:require [clojure.string :as str]) 3 | (:import java.util.Date)) 4 | 5 | (defn flatten-tree 6 | "Returns a depth-first traversal of the tree. Where :start and :end represents 7 | the start or end of a node's exploration. 8 | 9 | adjacency-list: map => { parent-node [child child ...], ... }. 10 | node: this node will be explored using depth first search. 11 | 12 | (flatten-tree 13 | {1 [2 3] 14 | 2 [4] 15 | 3 [5]} 16 | 1) 17 | 18 | => [[1 :start 0] 19 | [2 :start 1] 20 | [4 :start 2] 21 | [4 :end 2] 22 | [2 :end 1] 23 | [3 :start 1] 24 | [5 :start 2] 25 | [5 :end 2] 26 | [3 :end 1] 27 | [1 :end 0]] 28 | 29 | [node start/end depth] 30 | node: unique index of each node. 31 | start/end: 32 | [[node1 :start] ... [node1 :end]] 33 | everything in between are children of node1 34 | depth: depth of node in the tree 35 | " 36 | [adjacency-list node] 37 | (letfn [(flatten-tree 38 | [node depth] 39 | (let [children (get adjacency-list node)] 40 | (concat 41 | [node :start depth] 42 | (mapcat #(flatten-tree % (inc depth)) children) 43 | [node :end depth])))] 44 | (partition 3 (flatten-tree node 0)))) 45 | 46 | (defn parse-opts 47 | [opts] 48 | (let [expanded-view? (if (contains? opts :expanded-view?) 49 | (:expanded-view? opts) 50 | true) 51 | expanded-view {:start [:fn-name :fn-args] 52 | :expanded-view? true 53 | :end [:fn-rv] 54 | :indent "| " 55 | :marker {:start "Г--" 56 | :end "L--"}} 57 | collapsed-view {:start [:fn-name :fn-args :fn-rv] 58 | :expanded-view? false 59 | :indent " " 60 | :marker {:start "-->"}}] 61 | (if expanded-view? 62 | (merge expanded-view opts) 63 | (merge collapsed-view opts)))) 64 | 65 | (defn get-indicator 66 | "Returns 67 | Г-- 68 | L-- 69 | | Г-- 70 | | L-- 71 | --> 72 | -->" 73 | [depth indent marker exploration] 74 | (str (str/join (repeat depth indent)) (exploration marker))) 75 | 76 | (defn skip-escape-sequences 77 | [record k] 78 | (if (or (= k :fn-args) (= k :fn-rv)) 79 | (with-out-str 80 | (pr (k record))) 81 | (k record))) 82 | 83 | (defn format-values 84 | "`fn-args` and `fn-rv` might contain strings with escape sequences such as \n. 85 | They need to be properly escaped, else the output spans to multiple lines." 86 | [record opts exploration] 87 | (map (partial skip-escape-sequences record) (exploration opts))) 88 | 89 | (defn create-line 90 | [[_ exploration depth] 91 | {:keys [indent marker] :as opts} 92 | record] 93 | (flatten 94 | [(get-indicator depth indent marker exploration) 95 | (format-values record opts exploration)])) 96 | 97 | (defn infer-execution-order 98 | [records] 99 | (let [adjacency-list (-> (group-by :c-id records) 100 | (update-vals #(map :id %))) ; {1 [2 3], 2 [4]} 101 | root (first (get adjacency-list nil))] 102 | (flatten-tree adjacency-list root))) 103 | 104 | (defn print-call-tree 105 | [printer opts records] 106 | (let [dft (infer-execution-order records) 107 | record-map (->> (map #(vector (:id %) %) records) 108 | (into {}))] 109 | 110 | (printer (str "Time: " (Date.))) 111 | (let [{:keys [expanded-view?] :as opts} (parse-opts opts)] 112 | 113 | (doseq [node dft] 114 | (let [[id exploration _] node 115 | record (get record-map id)] 116 | (if (= exploration :start) 117 | (apply printer (create-line node opts record)) 118 | (when expanded-view? 119 | (apply printer (create-line node opts record))))))))) 120 | 121 | (defn print-to-file 122 | [file & args] 123 | (spit file (str (str/join " " args) "\n") :append true)) 124 | -------------------------------------------------------------------------------- /src/inspector/track.clj: -------------------------------------------------------------------------------- 1 | (ns inspector.track 2 | (:require [inspector.core :as core])) 3 | 4 | ; normal mode 5 | (defn with-track 6 | "Arguments: 7 | `store`: A place to save data for normal mode middlewares. 8 | As we would generally want to so some processing on the data after execution of function f. 9 | `middlewares`: vector of middlewares, which may or may not save data in `store`." 10 | [middlewares store vars f] 11 | (let [{:keys [rv e]} (try 12 | {:rv (core/with-modify-fns vars f middlewares)} 13 | (catch Exception e 14 | {:e e}))] 15 | {:rv rv :e e :records @store})) 16 | 17 | ; omnipresent mode 18 | (defn track 19 | [middlewares vars] 20 | (reset! core/modify true) 21 | (core/alter-fns vars middlewares)) 22 | 23 | (defn un-track 24 | [vars] 25 | (reset! core/modify false) 26 | (core/restore-altered-fns vars)) 27 | 28 | 29 | -------------------------------------------------------------------------------- /src/inspector/utils.clj: -------------------------------------------------------------------------------- 1 | (ns inspector.utils 2 | (:require [clojure.walk :as walk])) 3 | 4 | (defn full-name 5 | [fn-meta] 6 | (str (:ns fn-meta) "/" (:name fn-meta))) 7 | 8 | (defn prepare-fn-record 9 | [{:keys [c-tid tid c-id c-chain id uuid time e fn-rv fn-meta fn-args]}] 10 | (merge 11 | {:fn-name (full-name fn-meta) 12 | :fn-args fn-args 13 | :id id 14 | :tid tid 15 | :c-id c-id 16 | :c-tid c-tid 17 | :c-chain c-chain 18 | :uuid uuid 19 | :time time 20 | :fn-rv fn-rv} 21 | (when e {:e (Throwable->map e)}))) 22 | 23 | #_(defn walk-n-replace 24 | "Applies f to each non-collection thing. 25 | Non-collection thing is replaced by the return value." 26 | [f form] 27 | (walk/walk 28 | (partial walk-n-replace f) 29 | (fn [form] 30 | (if (coll? form) form (f form))) 31 | form)) 32 | 33 | #_(defn stringify-non-primitives 34 | [data] 35 | (let [check-primitive [keyword? number? string? char? nil? boolean? symbol?] 36 | stringify (fn [form] 37 | (cond 38 | (some #(% form) check-primitive) form 39 | (= (type form) clojure.lang.Atom) (deref form) 40 | :else (do 41 | (prn :type (type form)) 42 | (str form))))] 43 | (walk-n-replace stringify data))) 44 | 45 | (comment 46 | ; to get the datatype map 47 | (walk-n-replace (fn [form] (vector form (type form))) data)) 48 | -------------------------------------------------------------------------------- /test/inspector/test/core_test.clj: -------------------------------------------------------------------------------- 1 | (ns inspector.test.core-test 2 | (:require [clojure.test :refer :all] 3 | [inspector.core :as core])) 4 | 5 | ; get-modified-fn tests --------------------------------------------- 6 | 7 | (defn foo [x] x) 8 | (defn foo-error [x] (/ x 0)) 9 | 10 | (deftest handler-test 11 | (testing "function get executed and return value is returned" 12 | (let [new-state (core/handler {:fn-value foo :fn-args (list [1 2])}) 13 | k (set (keys new-state))] 14 | (is (contains? k :time)) 15 | (is (contains? k :e)) 16 | (is (contains? k :fn-rv)) 17 | (is (= [1 2] (:fn-rv new-state))) 18 | (is (= nil (:e new-state))))) 19 | 20 | (testing "function get executed and error is returned" 21 | (let [new-state (core/handler {:fn-value foo-error :fn-args (list 2)}) 22 | k (set (keys new-state))] 23 | (is (contains? k :time)) 24 | (is (contains? k :e)) 25 | (is (contains? k :fn-rv)) 26 | (is (= nil (:fn-rv new-state))) 27 | (is (= "Divide by zero" (-> (:e new-state) 28 | Throwable->map 29 | :cause)))))) 30 | 31 | (defn handler [store state] 32 | (let [new-state (core/handler state)] 33 | (swap! store conj new-state) 34 | new-state)) 35 | 36 | (deftest get-modified-fn-test-no-modification 37 | ; handler should not be invoked, i.e. store should remain empty. 38 | (let [store (atom []) 39 | new-fn (core/get-modified-fn (partial handler store) #'foo)] 40 | 41 | (is (= [1 2] (new-fn [1 2]))) 42 | (is (= [] @store))) 43 | 44 | (let [store (atom []) 45 | new-fn (core/get-modified-fn (partial handler store) #'foo-error)] 46 | 47 | ; not sure why but clojure.test thrown? is not being resolved 48 | (is (= "Divide by zero" (try (new-fn 1) 49 | (catch ArithmeticException e 50 | (-> e Throwable->map :cause))))) 51 | (is (= [] @store)))) 52 | 53 | (defn all-keys-present 54 | [record] 55 | (= #{:fn-meta :fn-args :fn-rv :e :id :tid :c-id :c-tid :c-chain :time :uuid} 56 | (-> record keys set (disj :fn-value)))) 57 | 58 | (deftest get-modified-fn-test-set-*modify* 59 | (testing "fn ran and return return value" 60 | (let [store (atom []) 61 | new-fn (core/get-modified-fn (partial handler store) #'foo)] 62 | 63 | (is (= [1 2] (binding [core/*modify* true] 64 | (new-fn [1 2])))) 65 | (is (= 1 (count @store))) 66 | (is (true? (all-keys-present (first @store)))))) 67 | 68 | (testing "fn rain and failed. Data was captured successfully and exception was thrown" 69 | (let [store (atom []) 70 | new-fn (core/get-modified-fn (partial handler store) #'foo-error)] 71 | 72 | (is (= "Divide by zero" (try (binding [core/*modify* true] 73 | (new-fn 1)) 74 | (catch ArithmeticException e 75 | (-> e Throwable->map :cause))))) 76 | (is (= 1 (count @store))) 77 | (is (true? (all-keys-present (first @store))))))) 78 | 79 | (deftest get-modified-fn-test-set-modify 80 | (let [store (atom []) 81 | new-fn (core/get-modified-fn (partial handler store) #'foo)] 82 | (reset! core/modify true) 83 | 84 | (is (= [1 2] (new-fn [1 2]))) 85 | (is (= 1 (count @store))) 86 | (is (true? (all-keys-present (first @store)))) 87 | 88 | ; keep it 89 | (reset! core/modify false))) 90 | 91 | (defn middleware 92 | [store handler] 93 | (fn [state] 94 | (let [new-state (handler state)] 95 | (swap! store conj new-state) 96 | new-state))) 97 | 98 | (deftest middlewares-test 99 | (testing "2 different middlewares" 100 | (let [store-1 (atom []) 101 | store-2 (atom []) 102 | m1 (partial middleware store-1) 103 | m2 (partial middleware store-2) 104 | handler ((comp m1 m2) core/handler) 105 | new-fn (core/get-modified-fn handler #'foo)] 106 | (is (= [1 2] (binding [core/*modify* true] 107 | (new-fn [1 2])))) 108 | (is (= 1 (count @store-1))) 109 | (is (= 1 (count @store-2))) 110 | (is (true? (all-keys-present (first @store-1)))) 111 | (is (true? (all-keys-present (first @store-2))))))) 112 | 113 | ; with-modify-fns test ----------------------------------------- 114 | (defn boo [x] (foo (str x))) 115 | (defn ooo [x] (boo (inc x))) 116 | 117 | (defn get-fs-data 118 | [store sym] 119 | (first (filter #(= sym (get-in % [:fn-meta :name])) store))) 120 | 121 | (deftest with-modify-fns-test 122 | (let [store (atom []) 123 | middlewares [(partial middleware store)] 124 | tracked-vars #{#'foo #'ooo}] 125 | (is (= "2" (core/with-modify-fns tracked-vars #(ooo 1) middlewares))) 126 | (is (= 2 (count @store))) 127 | (is (every? all-keys-present @store)) 128 | 129 | (let [ooo-data (get-fs-data @store 'ooo) 130 | foo-data (get-fs-data @store 'foo)] 131 | 132 | (is (not= nil ooo-data)) 133 | (is (not= nil foo-data)) 134 | 135 | ; relations 136 | (is (= (:uuid foo-data) (:uuid ooo-data))) 137 | (is (= (:c-id foo-data) (:id ooo-data))) 138 | (is (= (:tid foo-data) (:tid ooo-data))) 139 | (is (= (dec (:id foo-data)) (:id ooo-data))) 140 | (is (= (:c-chain foo-data) [(:id ooo-data)])) 141 | (is (<= (:time foo-data) (:time ooo-data))) 142 | 143 | ; foo 144 | (is (= (:e foo-data) nil)) 145 | (is (= (:fn-rv foo-data) "2")) 146 | (is (= (:fn-args foo-data) '("2"))) 147 | 148 | ; ooo 149 | (is (= (:e ooo-data) nil)) 150 | (is (= (:fn-rv ooo-data) "2")) 151 | (is (= (:fn-args ooo-data) '(1))) 152 | 153 | (is (= (:c-chain ooo-data) [])) 154 | (is (= (:c-id ooo-data) nil)) 155 | (is (= (:c-tid ooo-data) nil))))) 156 | 157 | ; TODO: repeat above test but with functions running in different threads. 158 | 159 | (deftest restore-altered-fns-test 160 | (let [tracked-var #'foo 161 | original-value @#'foo] 162 | (core/alter-fns #{tracked-var} []) 163 | (is (contains? (meta #'foo) :i-original)) 164 | (is (not= original-value @#'foo)) 165 | 166 | (core/restore-altered-fns #{tracked-var}) 167 | (is (false? (contains? (meta #'foo) :i-original))) 168 | (is (= original-value @#'foo)))) 169 | 170 | (deftest alter-fns-test 171 | (let [store (atom []) 172 | middlewares [(partial middleware store)] 173 | tracked-vars #{#'foo #'ooo}] 174 | 175 | (core/alter-fns tracked-vars middlewares) 176 | (reset! core/modify true) 177 | (is (= "2" (ooo 1))) 178 | 179 | (is (= 2 (count @store))) 180 | (is (every? all-keys-present @store)) 181 | 182 | (let [ooo-data (get-fs-data @store 'ooo) 183 | foo-data (get-fs-data @store 'foo)] 184 | 185 | (is (not= nil ooo-data)) 186 | (is (not= nil foo-data)) 187 | 188 | ; relations 189 | (is (= (:uuid foo-data) (:uuid ooo-data))) 190 | (is (= (:c-id foo-data) (:id ooo-data))) 191 | (is (= (:tid foo-data) (:tid ooo-data))) 192 | (is (= (dec (:id foo-data)) (:id ooo-data))) 193 | (is (= (:c-chain foo-data) [(:id ooo-data)])) 194 | (is (<= (:time foo-data) (:time ooo-data))) 195 | 196 | ; foo 197 | (is (= (:e foo-data) nil)) 198 | (is (= (:fn-rv foo-data) "2")) 199 | (is (= (:fn-args foo-data) '("2"))) 200 | 201 | ; ooo 202 | (is (= (:e ooo-data) nil)) 203 | (is (= (:fn-rv ooo-data) "2")) 204 | (is (= (:fn-args ooo-data) '(1))) 205 | 206 | (is (= (:c-chain ooo-data) [])) 207 | (is (= (:c-id ooo-data) nil)) 208 | (is (= (:c-tid ooo-data) nil))) 209 | 210 | (reset! core/modify false) 211 | (core/restore-altered-fns tracked-vars))) 212 | 213 | (defn boo-error [x] (foo-error (inc x))) 214 | (defn ooo-error [x] (boo-error (inc x))) 215 | 216 | (deftest with-modify-fns-test-error 217 | (let [store (atom []) 218 | middlewares [(partial middleware store)] 219 | tracked-vars #{#'foo-error #'ooo-error}] 220 | (is (= "Divide by zero" 221 | (try 222 | (core/with-modify-fns tracked-vars #(ooo-error 1) middlewares) 223 | (catch ArithmeticException e 224 | (-> e Throwable->map :cause))))) 225 | (is (= 2 (count @store))) 226 | (is (every? all-keys-present @store)) 227 | 228 | (let [ooo-data (get-fs-data @store 'ooo-error) 229 | foo-data (get-fs-data @store 'foo-error)] 230 | 231 | (is (not= nil ooo-data)) 232 | (is (not= nil foo-data)) 233 | 234 | ; relations 235 | (is (= (:uuid foo-data) (:uuid ooo-data))) 236 | (is (= (:c-id foo-data) (:id ooo-data))) 237 | (is (= (:tid foo-data) (:tid ooo-data))) 238 | (is (= (dec (:id foo-data)) (:id ooo-data))) 239 | (is (= (:c-chain foo-data) [(:id ooo-data)])) 240 | (is (<= (:time foo-data) (:time ooo-data))) 241 | 242 | ; foo 243 | (is (= (-> foo-data :e Throwable->map :cause) "Divide by zero")) 244 | (is (= (:fn-rv foo-data) nil)) 245 | (is (= (:fn-args foo-data) '(3))) 246 | 247 | ; ooo 248 | (is (= (-> ooo-data :e Throwable->map :cause) "Divide by zero")) 249 | (is (= (:fn-rv ooo-data) nil)) 250 | (is (= (:fn-args ooo-data) '(1))) 251 | 252 | (is (= (:c-chain ooo-data) [])) 253 | (is (= (:c-id ooo-data) nil)) 254 | (is (= (:c-tid ooo-data) nil))))) 255 | 256 | 257 | 258 | (comment 259 | (defn simplest [i] i) 260 | (defn simple [i] (simplest i)) 261 | (defn parallel [_] (vec (pmap simple (range 2)))) 262 | 263 | 264 | (defn simplest-fail [i] (/ i 0)) 265 | (defn simple-fail [i] (simplest-fail i)) 266 | (defn parallel-fail [_] (vec (pmap simple-fail (range 2))))) 267 | -------------------------------------------------------------------------------- /test/inspector/test/inspector_test.clj: -------------------------------------------------------------------------------- 1 | (ns inspector.test.inspector-test 2 | (:require [clojure.test :refer :all] 3 | [clojure.string :as str] 4 | [clojure.java.io :as io] 5 | [inspector.inspector :as i])) 6 | 7 | (def file "/tmp/inspector_test.log") 8 | 9 | ;; Fixture 10 | (defn delete-file [f] 11 | (spit file "") 12 | (f) 13 | (io/delete-file file)) 14 | 15 | (use-fixtures :each delete-file) 16 | 17 | (defn simplest [i] i) 18 | 19 | (defn simple [i] (simplest i)) 20 | 21 | (defn parallel [_] (vec (pmap simple (range 2)))) 22 | 23 | (def parallel-call-hierarchy-output-1 24 | "Time: Tue Jan 23 16:28:30 IST 2024 25 | Г-- inspector.test.inspector-test/parallel (1) 26 | | Г-- inspector.test.inspector-test/simple (0) 27 | | | Г-- inspector.test.inspector-test/simplest (0) 28 | | | L-- 0 29 | | L-- 0 30 | | Г-- inspector.test.inspector-test/simple (1) 31 | | | Г-- inspector.test.inspector-test/simplest (1) 32 | | | L-- 1 33 | | L-- 1 34 | L-- [0 1] 35 | ") 36 | 37 | (def parallel-call-hierarchy-output-2 38 | "Time: Tue Jan 23 16:28:30 IST 2024 39 | Г-- inspector.test.inspector-test/parallel (1) 40 | | Г-- inspector.test.inspector-test/simple (1) 41 | | | Г-- inspector.test.inspector-test/simplest (1) 42 | | | L-- 1 43 | | L-- 1 44 | | Г-- inspector.test.inspector-test/simple (0) 45 | | | Г-- inspector.test.inspector-test/simplest (0) 46 | | | L-- 0 47 | | L-- 0 48 | L-- [0 1] 49 | ") 50 | 51 | (deftest print-captured-data-test 52 | (let [my-project-vars #{#'simplest #'simple #'parallel} 53 | output (with-out-str (i/iprint my-project-vars #(parallel 1)))] 54 | (is (or 55 | (= (rest (str/split-lines parallel-call-hierarchy-output-1)) 56 | (rest (str/split-lines output))) 57 | (= (rest (str/split-lines parallel-call-hierarchy-output-2)) 58 | (rest (str/split-lines output))))))) 59 | 60 | (deftest spit-captured-data-test 61 | (let [my-project-vars #{#'simplest #'simple #'parallel} 62 | rv (i/ispit file my-project-vars #(parallel 1)) 63 | output (slurp file)] 64 | (is (or 65 | (= (rest (str/split-lines parallel-call-hierarchy-output-1)) 66 | (rest (str/split-lines output))) 67 | (= (rest (str/split-lines parallel-call-hierarchy-output-2)) 68 | (rest (str/split-lines output))))))) 69 | 70 | -------------------------------------------------------------------------------- /test/inspector/test/middleware/capture_test.clj: -------------------------------------------------------------------------------- 1 | (ns inspector.test.middleware.capture-test 2 | (:require [clojure.test :refer :all] 3 | [inspector.middleware.capture :as capture])) 4 | 5 | (deftest capture-middleware-test 6 | (let [store (atom []) 7 | new-handler (capture/capture-middleware store identity) 8 | state {:fn-meta {:name "foo" :ns "dummy"} 9 | :fn-args '(1 2) 10 | :id 29 11 | :tid 10 12 | :c-id 9 13 | :c-tid 10 14 | :c-chain [6 7 8 9] 15 | :uuid (random-uuid) 16 | :time 10000 17 | :fn-rv 3} 18 | result (new-handler state)] 19 | (is (fn? new-handler)) 20 | (is (= state result)) 21 | (is (= (-> state 22 | (assoc :fn-name "dummy/foo") 23 | (assoc :m-name :capture-middleware) 24 | (dissoc :fn-meta) 25 | vector) 26 | @store)))) 27 | -------------------------------------------------------------------------------- /test/inspector/test/middleware/export_test.clj: -------------------------------------------------------------------------------- 1 | (ns inspector.test.middleware.export-test 2 | (:require [clojure.test :refer :all] 3 | [inspector.middleware.export :as export])) 4 | 5 | (deftest export-middleware-test 6 | (let [store (atom []) 7 | capture (fn [record] 8 | (swap! store conj record)) 9 | new-handler (export/export-middleware capture identity) 10 | state {:fn-meta {:name "foo" :ns "dummy"} 11 | :fn-args '(1 2) 12 | :id 29 13 | :tid 10 14 | :c-id 9 15 | :c-tid 10 16 | :c-chain [6 7 8 9] 17 | :uuid (random-uuid) 18 | :time 10000 19 | :fn-rv 3} 20 | result (new-handler state)] 21 | (is (fn? new-handler)) 22 | (is (= state result)) 23 | (is (= (-> state 24 | (assoc :fn-name "dummy/foo") 25 | (dissoc :fn-meta) 26 | vector) 27 | @store)))) -------------------------------------------------------------------------------- /test/inspector/test/printer_test.clj: -------------------------------------------------------------------------------- 1 | (ns inspector.test.printer-test 2 | (:require [clojure.test :refer :all] 3 | [inspector.printer :as printer])) 4 | 5 | (deftest flatten-tree-test 6 | (is (= [[1 :start 0] 7 | [2 :start 1] 8 | [4 :start 2] 9 | [4 :end 2] 10 | [2 :end 1] 11 | [3 :start 1] 12 | [5 :start 2] 13 | [5 :end 2] 14 | [3 :end 1] 15 | [1 :end 0]] 16 | (printer/flatten-tree 17 | {1 [2 3] 18 | 2 [4] 19 | 3 [5]} 20 | 1)))) 21 | -------------------------------------------------------------------------------- /test/inspector/test/track_test.clj: -------------------------------------------------------------------------------- 1 | (ns inspector.test.track-test 2 | (:require [clojure.test :refer :all] 3 | [inspector.track :as track])) 4 | 5 | (defn foo [x] x) 6 | (defn boo [x] (foo (inc x))) 7 | 8 | (defn middleware 9 | [store handler] 10 | (fn [state] 11 | (let [new-state (handler state)] 12 | (swap! store conj (assoc new-state :m-name :test-middleware)) 13 | new-state))) 14 | 15 | (deftest with-track-test 16 | (let [store (atom []) 17 | middlewares [(partial middleware store)] 18 | tracked-vars #{#'foo #'boo} 19 | {:keys [rv e records]} (track/with-track 20 | middlewares store 21 | tracked-vars 22 | #(boo 2))] 23 | (is (= 3 rv)) 24 | (is (= nil e)) 25 | (is (= [:test-middleware :test-middleware] (map :m-name records))) 26 | (is (= 2 (count records))))) 27 | --------------------------------------------------------------------------------