n_plus_insight 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: b64b2190f32d5bd69dc972654ccb46add8d3a2a4bacc9938a3e0bf5b7035004f
4
+ data.tar.gz: 9af66e38cdbe1676aece5a7cf193f6eae284589163b845e58adf9bef36a5ef66
5
+ SHA512:
6
+ metadata.gz: e6ed0f4ad2dacf35a5e9c52ba9d7597c6d536d05f2930d1798082da89bd811d4e6bb7b63a60b1f9f10608c63b2fbbc982b799038410acf5b46d2b5224c862170
7
+ data.tar.gz: f9c71aa555d723bb1b2d109e572c8f49458c361196de2ee48d6f734158ba55bafba84d4ef0fe418aea10559f994ef751eb3407ac29d4035a0923d54e56ae837b
data/CHANGELOG.md ADDED
@@ -0,0 +1,11 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 - 2026-07-28
4
+
5
+ - Detect repeated Active Record query shapes within a request.
6
+ - Identify relevant application source files, line numbers, and code excerpts.
7
+ - Visualize affected models and associations.
8
+ - Recommend eager-loading and strict-loading remediations.
9
+ - Provide an optional on-page status indicator and findings panel.
10
+ - Provide a full mounted findings dashboard.
11
+ - Support environment-neutral activation and deployment.
data/LICENSE.txt ADDED
@@ -0,0 +1,15 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 NPlusInsight contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.
data/README.md ADDED
@@ -0,0 +1,70 @@
1
+ # NPlusInsight
2
+
3
+ NPlusInsight is a Rails gem that detects repeated query
4
+ shapes within a request and turns them into a useful debugging report:
5
+
6
+ - the exact application file and line that issued the query;
7
+ - a model/association graph for the tables involved;
8
+ - normalized SQL, repetition count, and total query time;
9
+ - suggested `includes` and `strict_loading` fixes.
10
+
11
+ ## Install
12
+
13
+ Add the gem in every environment where you may enable it:
14
+
15
+ ```ruby
16
+ gem "n_plus_insight"
17
+ ```
18
+
19
+ Run `bundle install`, then configure NPlusInsight for the environments where it
20
+ should be active.
21
+
22
+ Then configure activation from the environment rather than tying it to a Rails
23
+ environment name:
24
+
25
+ ```ruby
26
+ # config/initializers/n_plus_insight.rb
27
+ if Rails.env.development?
28
+ NPlusInsight.configure do |config|
29
+ config.minimum_repetitions = 2
30
+ config.mount_path = "/n_plus_insight"
31
+ config.on_page = true
32
+ config.max_events = 100
33
+ config.raise_on_detection = false
34
+ end
35
+ end
36
+ ```
37
+ With `on_page` enabled, every HTML page also gets a small status circle in the
38
+ bottom-right corner. It turns red and shows a count when the current request
39
+ contains N+1 query patterns. Select it to inspect source lines, the affected
40
+ model graph, and suggested fixes without leaving the page. Set
41
+ `config.on_page = false` to remove the on-page tool while retaining collection
42
+ and the full dashboard.
43
+
44
+ ## How detection works
45
+
46
+ The gem listens to `sql.active_record` events during each web request. It
47
+ removes literal values from SQL and groups matching shapes. A shape repeated at
48
+ least `minimum_repetitions` times is reported. Framework, gem, schema, cached,
49
+ transaction, and asset requests are excluded.
50
+
51
+ This deliberately reports evidence rather than patching source automatically.
52
+ Suggested fixes should be reviewed because scopes, polymorphic associations,
53
+ and intentionally lazy-loaded data can change the best eager-loading strategy.
54
+
55
+ ## CI mode
56
+
57
+ To turn findings into failures in a test or staging environment:
58
+
59
+ ```ruby
60
+ config.raise_on_detection = true
61
+ ```
62
+
63
+ The dashboard is not restricted to a particular Rails environment. If it is
64
+ enabled on an internet-facing deployment, protect `/n_plus_insight` with your
65
+ application's authentication, authorization, VPN, or reverse-proxy access
66
+ controls because findings contain source paths, code excerpts, and SQL shapes.
67
+
68
+ ## License
69
+
70
+ MIT
data/RELEASING.md ADDED
@@ -0,0 +1,47 @@
1
+ # Releasing NPlusInsight
2
+
3
+ ## First release
4
+
5
+ 1. Create or sign in to your account at https://rubygems.org.
6
+ 2. Enable MFA for the account.
7
+ 3. Confirm that `n_plus_insight` is still available:
8
+
9
+ ```sh
10
+ gem search --remote --exact n_plus_insight
11
+ ```
12
+
13
+ No output means there is no published gem with that exact name.
14
+
15
+ 4. Authenticate without putting an API key in the repository:
16
+
17
+ ```sh
18
+ gem signin
19
+ ```
20
+
21
+ 5. Run the tests and build the package:
22
+
23
+ ```sh
24
+ bundle install
25
+ bundle exec rake test
26
+ bundle exec rake build
27
+ ```
28
+
29
+ 6. Publish the built package:
30
+
31
+ ```sh
32
+ gem push pkg/n_plus_insight-0.1.0.gem
33
+ ```
34
+
35
+ 7. Verify the release:
36
+
37
+ ```sh
38
+ gem info n_plus_insight --remote
39
+ ```
40
+
41
+ ## Later releases
42
+
43
+ Update `NPlusInsight::VERSION` in `lib/n_plus_insight/version.rb`, add the
44
+ release notes to `CHANGELOG.md`, rerun the tests, build, and push the new
45
+ version. RubyGems does not allow replacing an existing version.
46
+
47
+ Never commit `.gem/credentials`, an API key, or an OTP recovery code.
@@ -0,0 +1,130 @@
1
+ #n1v-root {
2
+ --n1v-bg: #ffffff;
3
+ --n1v-surface: #f7f7f9;
4
+ --n1v-text: #18181b;
5
+ --n1v-muted: #667085;
6
+ --n1v-border: #e4e7ec;
7
+ --n1v-accent: #6941c6;
8
+ --n1v-accent-soft: #f1ebff;
9
+ --n1v-danger: #d92d20;
10
+ --n1v-success: #079455;
11
+ --n1v-code: #101828;
12
+ position: fixed !important;
13
+ right: 20px !important;
14
+ bottom: 20px !important;
15
+ z-index: 2147483646 !important;
16
+ color: var(--n1v-text) !important;
17
+ font: 14px/1.45 ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif !important;
18
+ text-align: left !important;
19
+ }
20
+
21
+ @media (prefers-color-scheme: dark) {
22
+ #n1v-root {
23
+ --n1v-bg: #17191d;
24
+ --n1v-surface: #22252b;
25
+ --n1v-text: #f4f4f5;
26
+ --n1v-muted: #a8b0bd;
27
+ --n1v-border: #363b44;
28
+ --n1v-accent: #c4b5fd;
29
+ --n1v-accent-soft: #30284a;
30
+ --n1v-danger: #ff766d;
31
+ --n1v-success: #47cd89;
32
+ --n1v-code: #0b0c0f;
33
+ }
34
+ }
35
+
36
+ #n1v-root, #n1v-root * { box-sizing: border-box !important; }
37
+
38
+ #n1v-root .n1v-launcher {
39
+ position: relative !important;
40
+ display: grid !important;
41
+ place-items: center !important;
42
+ width: 52px !important;
43
+ height: 52px !important;
44
+ margin: 0 0 0 auto !important;
45
+ padding: 0 !important;
46
+ border: 0 !important;
47
+ border-radius: 999px !important;
48
+ background: var(--n1v-success) !important;
49
+ color: #fff !important;
50
+ box-shadow: 0 8px 28px rgba(16, 24, 40, .24) !important;
51
+ cursor: pointer !important;
52
+ font: 700 15px/1 ui-sans-serif, system-ui, sans-serif !important;
53
+ }
54
+
55
+ #n1v-root .n1v-launcher.n1v-has-alert {
56
+ background: var(--n1v-danger) !important;
57
+ animation: n1v-pulse 1.8s ease-out 2;
58
+ }
59
+
60
+ #n1v-root .n1v-count {
61
+ position: absolute !important;
62
+ top: -5px !important;
63
+ right: -5px !important;
64
+ min-width: 21px !important;
65
+ height: 21px !important;
66
+ padding: 0 5px !important;
67
+ border: 2px solid var(--n1v-bg) !important;
68
+ border-radius: 999px !important;
69
+ background: var(--n1v-bg) !important;
70
+ color: var(--n1v-danger) !important;
71
+ font: 700 11px/17px ui-sans-serif, system-ui, sans-serif !important;
72
+ }
73
+
74
+ #n1v-root .n1v-panel {
75
+ position: absolute !important;
76
+ right: 0 !important;
77
+ bottom: 64px !important;
78
+ display: none !important;
79
+ width: min(620px, calc(100vw - 32px)) !important;
80
+ max-height: min(760px, calc(100vh - 110px)) !important;
81
+ overflow: auto !important;
82
+ border: 1px solid var(--n1v-border) !important;
83
+ border-radius: 14px !important;
84
+ background: var(--n1v-bg) !important;
85
+ color: var(--n1v-text) !important;
86
+ box-shadow: 0 20px 50px rgba(16, 24, 40, .28) !important;
87
+ }
88
+
89
+ #n1v-root .n1v-panel[aria-hidden="false"] { display: block !important; }
90
+ #n1v-root .n1v-header { position: sticky !important; top: 0 !important; z-index: 2 !important; display: flex !important; align-items: center !important; justify-content: space-between !important; gap: 12px !important; padding: 15px 18px !important; border-bottom: 1px solid var(--n1v-border) !important; background: var(--n1v-bg) !important; }
91
+ #n1v-root .n1v-title { margin: 0 !important; color: var(--n1v-text) !important; font: 650 16px/1.3 ui-sans-serif, system-ui, sans-serif !important; }
92
+ #n1v-root .n1v-subtitle { margin: 2px 0 0 !important; color: var(--n1v-muted) !important; font: 12px/1.4 ui-sans-serif, system-ui, sans-serif !important; }
93
+ #n1v-root .n1v-close { width: 32px !important; height: 32px !important; padding: 0 !important; border: 1px solid var(--n1v-border) !important; border-radius: 8px !important; background: transparent !important; color: var(--n1v-text) !important; cursor: pointer !important; font: 20px/1 ui-sans-serif, system-ui, sans-serif !important; }
94
+ #n1v-root .n1v-body { padding: 16px 18px 20px !important; }
95
+ #n1v-root .n1v-tabs { display: flex !important; gap: 8px !important; overflow-x: auto !important; margin: 0 0 16px !important; padding: 0 0 4px !important; }
96
+ #n1v-root .n1v-tab { flex: 0 0 auto !important; padding: 7px 10px !important; border: 1px solid var(--n1v-border) !important; border-radius: 8px !important; background: transparent !important; color: var(--n1v-text) !important; cursor: pointer !important; font: 600 12px/1 ui-sans-serif, system-ui, sans-serif !important; }
97
+ #n1v-root .n1v-tab[aria-selected="true"] { border-color: var(--n1v-accent) !important; background: var(--n1v-accent-soft) !important; }
98
+ #n1v-root .n1v-section { margin: 0 0 18px !important; padding: 0 !important; border: 0 !important; background: transparent !important; }
99
+ #n1v-root .n1v-section:last-child { margin-bottom: 0 !important; }
100
+ #n1v-root .n1v-heading { margin: 0 0 8px !important; color: var(--n1v-text) !important; font: 650 13px/1.3 ui-sans-serif, system-ui, sans-serif !important; }
101
+ #n1v-root .n1v-location { margin: 0 0 8px !important; color: var(--n1v-muted) !important; overflow-wrap: anywhere !important; font: 12px/1.4 ui-monospace, SFMono-Regular, Consolas, monospace !important; }
102
+ #n1v-root .n1v-code { display: block !important; max-width: 100% !important; margin: 0 !important; padding: 10px 0 !important; overflow: auto !important; border-radius: 8px !important; background: var(--n1v-code) !important; color: #e4e7ec !important; font: 12px/1.5 ui-monospace, SFMono-Regular, Consolas, monospace !important; white-space: pre !important; }
103
+ #n1v-root .n1v-line { display: grid !important; grid-template-columns: 38px minmax(0, 1fr) !important; min-width: max-content !important; padding: 0 12px !important; }
104
+ #n1v-root .n1v-line.n1v-active { background: rgba(217, 45, 32, .28) !important; }
105
+ #n1v-root .n1v-line-number { color: #98a2b3 !important; user-select: none !important; }
106
+ #n1v-root .n1v-graph { display: flex !important; align-items: center !important; gap: 7px !important; min-height: 74px !important; overflow-x: auto !important; padding: 8px 0 !important; }
107
+ #n1v-root .n1v-node { flex: 0 0 auto !important; min-width: 130px !important; padding: 10px 12px !important; border: 1px solid var(--n1v-accent) !important; border-radius: 9px !important; background: var(--n1v-accent-soft) !important; color: var(--n1v-text) !important; text-align: center !important; }
108
+ #n1v-root .n1v-node strong, #n1v-root .n1v-node small { display: block !important; color: inherit !important; }
109
+ #n1v-root .n1v-node small { margin-top: 2px !important; color: var(--n1v-muted) !important; font-size: 11px !important; }
110
+ #n1v-root .n1v-edge { flex: 0 0 auto !important; color: var(--n1v-muted) !important; text-align: center !important; font-size: 11px !important; }
111
+ #n1v-root .n1v-fix { margin: 0 !important; padding: 12px 0 !important; border-top: 1px solid var(--n1v-border) !important; }
112
+ #n1v-root .n1v-fix:first-of-type { padding-top: 0 !important; border-top: 0 !important; }
113
+ #n1v-root .n1v-fix-title { margin: 0 0 4px !important; color: var(--n1v-text) !important; font: 650 13px/1.4 ui-sans-serif, system-ui, sans-serif !important; }
114
+ #n1v-root .n1v-copy { float: right !important; margin-left: 8px !important; padding: 4px 7px !important; border: 1px solid var(--n1v-border) !important; border-radius: 6px !important; background: transparent !important; color: var(--n1v-text) !important; cursor: pointer !important; font: 11px/1 ui-sans-serif, system-ui, sans-serif !important; }
115
+ #n1v-root .n1v-empty { padding: 28px 8px !important; color: var(--n1v-muted) !important; text-align: center !important; }
116
+ #n1v-root button:focus-visible { outline: 3px solid var(--n1v-accent) !important; outline-offset: 2px !important; }
117
+
118
+ @keyframes n1v-pulse {
119
+ 0% { box-shadow: 0 0 0 0 rgba(217, 45, 32, .45), 0 8px 28px rgba(16, 24, 40, .24); }
120
+ 100% { box-shadow: 0 0 0 16px rgba(217, 45, 32, 0), 0 8px 28px rgba(16, 24, 40, .24); }
121
+ }
122
+
123
+ @media (max-width: 560px) {
124
+ #n1v-root { right: 10px !important; bottom: 10px !important; }
125
+ #n1v-root .n1v-panel { width: calc(100vw - 20px) !important; max-height: calc(100vh - 84px) !important; bottom: 62px !important; }
126
+ }
127
+
128
+ @media (prefers-reduced-motion: reduce) {
129
+ #n1v-root .n1v-launcher { animation: none !important; }
130
+ }
@@ -0,0 +1,173 @@
1
+ (function () {
2
+ "use strict";
3
+
4
+ var root = document.getElementById("n1v-root");
5
+ if (!root || root.dataset.initialized === "true") return;
6
+ root.dataset.initialized = "true";
7
+
8
+ function element(tag, className, text) {
9
+ var node = document.createElement(tag);
10
+ if (className) node.className = className;
11
+ if (text !== undefined) node.textContent = text;
12
+ return node;
13
+ }
14
+
15
+ function decodePayload(value) {
16
+ try {
17
+ var bytes = Uint8Array.from(atob(value), function (character) {
18
+ return character.charCodeAt(0);
19
+ });
20
+ return JSON.parse(new TextDecoder().decode(bytes));
21
+ } catch (_error) {
22
+ return [];
23
+ }
24
+ }
25
+
26
+ var findings = decodePayload(root.dataset.payload || "");
27
+ var launcher = element("button", "n1v-launcher" + (findings.length ? " n1v-has-alert" : ""), "N+1");
28
+ launcher.type = "button";
29
+ launcher.setAttribute("aria-label", findings.length ? "Open NPlusInsight: " + findings.length + " detected" : "Open NPlusInsight: no detections");
30
+ launcher.setAttribute("aria-expanded", "false");
31
+
32
+ if (findings.length) {
33
+ var count = element("span", "n1v-count", String(findings.length));
34
+ count.setAttribute("aria-hidden", "true");
35
+ launcher.appendChild(count);
36
+ }
37
+
38
+ var panel = element("aside", "n1v-panel");
39
+ panel.id = "n1v-panel";
40
+ panel.setAttribute("aria-hidden", "true");
41
+ panel.setAttribute("aria-label", "N+1 query details");
42
+ launcher.setAttribute("aria-controls", panel.id);
43
+
44
+ var header = element("div", "n1v-header");
45
+ var headingWrap = element("div");
46
+ headingWrap.appendChild(element("h2", "n1v-title", findings.length ? "N+1 detected" : "No N+1 queries"));
47
+ headingWrap.appendChild(element("p", "n1v-subtitle", findings.length ? findings.length + " repeated query pattern" + (findings.length === 1 ? "" : "s") + " on this page" : "This request is clear"));
48
+ header.appendChild(headingWrap);
49
+
50
+ var close = element("button", "n1v-close", "×");
51
+ close.type = "button";
52
+ close.setAttribute("aria-label", "Close NPlusInsight");
53
+ header.appendChild(close);
54
+ panel.appendChild(header);
55
+
56
+ var body = element("div", "n1v-body");
57
+ panel.appendChild(body);
58
+
59
+ function appendCode(container, code) {
60
+ var pre = element("pre", "n1v-code");
61
+ pre.appendChild(element("code", "", code || ""));
62
+ container.appendChild(pre);
63
+ }
64
+
65
+ function renderSource(container, finding) {
66
+ var section = element("section", "n1v-section");
67
+ section.appendChild(element("h3", "n1v-heading", "Relevant source"));
68
+ if (!finding.location) {
69
+ section.appendChild(element("p", "n1v-location", "No application stack frame was captured."));
70
+ container.appendChild(section);
71
+ return;
72
+ }
73
+ section.appendChild(element("p", "n1v-location", finding.location.path + ":" + finding.location.line));
74
+ var pre = element("pre", "n1v-code");
75
+ var code = element("code");
76
+ (finding.location.snippet || []).forEach(function (sourceLine) {
77
+ var row = element("span", "n1v-line" + (sourceLine.active ? " n1v-active" : ""));
78
+ row.appendChild(element("span", "n1v-line-number", String(sourceLine.line)));
79
+ row.appendChild(element("span", "", sourceLine.text));
80
+ code.appendChild(row);
81
+ });
82
+ pre.appendChild(code);
83
+ section.appendChild(pre);
84
+ container.appendChild(section);
85
+ }
86
+
87
+ function renderGraph(container, finding) {
88
+ var section = element("section", "n1v-section");
89
+ section.appendChild(element("h3", "n1v-heading", "Affected models"));
90
+ var graph = element("div", "n1v-graph");
91
+ graph.setAttribute("role", "img");
92
+ graph.setAttribute("aria-label", "Model associations involved in the repeated query");
93
+ (finding.models || []).forEach(function (model, index) {
94
+ if (index > 0) {
95
+ var edge = (finding.edges || [])[index - 1];
96
+ graph.appendChild(element("span", "n1v-edge", (edge && edge.association ? edge.association + " " : "") + "→"));
97
+ }
98
+ var node = element("div", "n1v-node");
99
+ node.appendChild(element("strong", "", model.name));
100
+ node.appendChild(element("small", "", model.table));
101
+ graph.appendChild(node);
102
+ });
103
+ section.appendChild(graph);
104
+ container.appendChild(section);
105
+ }
106
+
107
+ function renderFixes(container, finding) {
108
+ var section = element("section", "n1v-section");
109
+ section.appendChild(element("h3", "n1v-heading", "Remediation"));
110
+ (finding.suggestions || []).forEach(function (suggestion) {
111
+ var fix = element("div", "n1v-fix");
112
+ var copy = element("button", "n1v-copy", "Copy");
113
+ copy.type = "button";
114
+ copy.addEventListener("click", function () {
115
+ navigator.clipboard.writeText(suggestion.code).then(function () {
116
+ copy.textContent = "Copied";
117
+ window.setTimeout(function () { copy.textContent = "Copy"; }, 1200);
118
+ });
119
+ });
120
+ fix.appendChild(copy);
121
+ fix.appendChild(element("h4", "n1v-fix-title", suggestion.title));
122
+ appendCode(fix, suggestion.code);
123
+ section.appendChild(fix);
124
+ });
125
+ container.appendChild(section);
126
+ }
127
+
128
+ function renderFinding(index) {
129
+ body.textContent = "";
130
+ if (!findings.length) {
131
+ body.appendChild(element("div", "n1v-empty", "No repeated Active Record query shapes were captured while rendering this page."));
132
+ return;
133
+ }
134
+
135
+ if (findings.length > 1) {
136
+ var tabs = element("div", "n1v-tabs");
137
+ tabs.setAttribute("role", "tablist");
138
+ findings.forEach(function (finding, tabIndex) {
139
+ var tab = element("button", "n1v-tab", "#" + (tabIndex + 1) + " · " + finding.query_count + " queries");
140
+ tab.type = "button";
141
+ tab.setAttribute("role", "tab");
142
+ tab.setAttribute("aria-selected", String(tabIndex === index));
143
+ tab.addEventListener("click", function () { renderFinding(tabIndex); });
144
+ tabs.appendChild(tab);
145
+ });
146
+ body.appendChild(tabs);
147
+ }
148
+
149
+ var finding = findings[index];
150
+ renderSource(body, finding);
151
+ renderGraph(body, finding);
152
+ renderFixes(body, finding);
153
+ }
154
+
155
+ function setOpen(open) {
156
+ panel.setAttribute("aria-hidden", String(!open));
157
+ launcher.setAttribute("aria-expanded", String(open));
158
+ if (open) close.focus();
159
+ else launcher.focus();
160
+ }
161
+
162
+ launcher.addEventListener("click", function () {
163
+ setOpen(panel.getAttribute("aria-hidden") === "true");
164
+ });
165
+ close.addEventListener("click", function () { setOpen(false); });
166
+ document.addEventListener("keydown", function (event) {
167
+ if (event.key === "Escape" && panel.getAttribute("aria-hidden") === "false") setOpen(false);
168
+ });
169
+
170
+ renderFinding(0);
171
+ root.appendChild(panel);
172
+ root.appendChild(launcher);
173
+ }());
@@ -0,0 +1,5 @@
1
+ module NPlusInsight
2
+ class ApplicationController < ActionController::Base
3
+ protect_from_forgery with: :exception
4
+ end
5
+ end
@@ -0,0 +1,22 @@
1
+ module NPlusInsight
2
+ class AssetsController < ApplicationController
3
+ skip_forgery_protection
4
+
5
+ ASSET_ROOT = NPlusInsight::Engine.root.join("app", "assets", "n_plus_insight")
6
+
7
+ def stylesheet
8
+ send_asset("overlay.css", "text/css")
9
+ end
10
+
11
+ def script
12
+ send_asset("overlay.js", "application/javascript")
13
+ end
14
+
15
+ private
16
+
17
+ def send_asset(name, type)
18
+ response.headers["Cache-Control"] = "no-store"
19
+ send_data File.binread(ASSET_ROOT.join(name).to_s), type: type, disposition: "inline"
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,12 @@
1
+ module NPlusInsight
2
+ class DetectionsController < ApplicationController
3
+ def index
4
+ @detections = Store.all
5
+ end
6
+
7
+ def show
8
+ @detection = Store.find(params[:id])
9
+ return head :not_found unless @detection
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,39 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>NPlusInsight</title>
7
+ <style>
8
+ :root { color-scheme: light dark; --bg:#f6f7f9; --panel:#fff; --text:#17202a; --muted:#65707d; --line:#dfe3e8; --accent:#6750a4; --accent-soft:#eee9fa; --bad:#b42318; --code:#111827; }
9
+ @media (prefers-color-scheme: dark) { :root { --bg:#11151a; --panel:#1a2027; --text:#edf1f5; --muted:#aab4c0; --line:#303944; --accent:#c4b5fd; --accent-soft:#302a47; --bad:#ff8a80; --code:#0b0e12; } }
10
+ * { box-sizing:border-box; }
11
+ body { margin:0; background:var(--bg); color:var(--text); font:15px/1.5 ui-sans-serif,system-ui,-apple-system,sans-serif; }
12
+ header { border-bottom:1px solid var(--line); background:var(--panel); }
13
+ header div, main { width:min(1120px, calc(100% - 32px)); margin:auto; }
14
+ header div { display:flex; align-items:center; justify-content:space-between; min-height:64px; }
15
+ h1,h2,h3,p { margin-top:0; } h1 { font-size:20px; margin:0; } h2 { font-size:18px; }
16
+ a { color:var(--accent); } .brand { color:var(--text); text-decoration:none; font-weight:650; }
17
+ main { padding:32px 0 56px; }
18
+ .muted { color:var(--muted); } .empty { text-align:center; padding:72px 24px; border:1px dashed var(--line); border-radius:12px; }
19
+ .list { display:grid; gap:12px; } .card { display:block; background:var(--panel); border:1px solid var(--line); border-radius:12px; padding:18px; color:var(--text); text-decoration:none; }
20
+ .card:hover { border-color:var(--accent); } .row { display:flex; align-items:flex-start; justify-content:space-between; gap:16px; }
21
+ .badge { display:inline-flex; padding:2px 8px; border-radius:999px; background:var(--accent-soft); color:var(--text); font-size:12px; }
22
+ .danger { color:var(--bad); font-weight:650; } .meta { display:flex; flex-wrap:wrap; gap:8px 18px; color:var(--muted); font-size:13px; }
23
+ .grid { display:grid; grid-template-columns:minmax(0,1.25fr) minmax(280px,.75fr); gap:20px; align-items:start; }
24
+ .stack { display:grid; gap:16px; } section { background:var(--panel); border:1px solid var(--line); border-radius:12px; padding:20px; }
25
+ pre { margin:0; overflow:auto; padding:14px; border-radius:8px; background:var(--code); color:#e5e7eb; font:13px/1.55 ui-monospace,SFMono-Regular,Consolas,monospace; }
26
+ .source { padding:0; } .source div { display:grid; grid-template-columns:44px 1fr; padding:1px 14px; }
27
+ .source div.active { background:rgba(180,35,24,.28); } .source b { color:#9ca3af; font-weight:400; user-select:none; }
28
+ .graph { width:100%; min-height:240px; } .graph line { stroke:var(--line); stroke-width:2; }
29
+ .graph rect { fill:var(--accent-soft); stroke:var(--accent); } .graph text { fill:var(--text); font:13px ui-sans-serif,system-ui; }
30
+ .suggestion + .suggestion { border-top:1px solid var(--line); padding-top:18px; margin-top:18px; }
31
+ .crumb { display:inline-block; margin-bottom:18px; }
32
+ @media (max-width:760px) { .grid { grid-template-columns:1fr; } main, header div { width:min(100% - 20px,1120px); } .row { flex-direction:column; } }
33
+ </style>
34
+ </head>
35
+ <body>
36
+ <header><div><a class="brand" href="<%= root_path %>">NPlusInsight</a><span class="badge">Development only</span></div></header>
37
+ <main><%= yield %></main>
38
+ </body>
39
+ </html>
@@ -0,0 +1,32 @@
1
+ <div class="row">
2
+ <div>
3
+ <h1>Detected N+1 queries</h1>
4
+ <p class="muted">Repeated query shapes grouped by request, with the application frame that triggered them.</p>
5
+ </div>
6
+ <span class="badge"><%= @detections.length %> finding<%= "s" unless @detections.one? %></span>
7
+ </div>
8
+
9
+ <% if @detections.empty? %>
10
+ <div class="empty">
11
+ <h2>No N+1 queries captured yet</h2>
12
+ <p class="muted">Use your application normally, then refresh this page.</p>
13
+ </div>
14
+ <% else %>
15
+ <div class="list">
16
+ <% @detections.each do |detection| %>
17
+ <a class="card" href="<%= detection_path(detection.id) %>">
18
+ <div class="row">
19
+ <div>
20
+ <div><span class="danger"><%= detection.query_count %> repeated queries</span> on <strong><%= detection.method %> <%= detection.path %></strong></div>
21
+ <div class="meta">
22
+ <span><%= detection.total_ms %> ms</span>
23
+ <% if detection.location %><span><%= detection.location.path %>:<%= detection.location.line %></span><% end %>
24
+ <span><%= detection.models.map { |model| model[:name] }.join(" → ") %></span>
25
+ </div>
26
+ </div>
27
+ <span aria-hidden="true">→</span>
28
+ </div>
29
+ </a>
30
+ <% end %>
31
+ </div>
32
+ <% end %>
@@ -0,0 +1,56 @@
1
+ <a class="crumb" href="<%= root_path %>">← All detections</a>
2
+ <div class="row">
3
+ <div>
4
+ <h1><%= @detection.method %> <%= @detection.path %></h1>
5
+ <p class="muted"><%= @detection.query_count %> repeated queries · <%= @detection.total_ms %> ms total · <%= @detection.created_at %></p>
6
+ </div>
7
+ <span class="badge">N+1 detected</span>
8
+ </div>
9
+
10
+ <div class="grid">
11
+ <div class="stack">
12
+ <section>
13
+ <h2>Exact source location</h2>
14
+ <% if @detection.location %>
15
+ <p><%= @detection.location.path %>:<%= @detection.location.line %></p>
16
+ <pre class="source"><% @detection.location.snippet.each do |line| %><div class="<%= "active" if line[:active] %>"><b><%= line[:line] %></b><span><%= line[:text] %></span></div><% end %></pre>
17
+ <% else %>
18
+ <p class="muted">The query was captured, but no application stack frame was available.</p>
19
+ <% end %>
20
+ </section>
21
+
22
+ <section>
23
+ <h2>Repeated SQL shape</h2>
24
+ <pre><%= @detection.sql %></pre>
25
+ </section>
26
+
27
+ <section>
28
+ <h2>Suggested fixes</h2>
29
+ <% @detection.suggestions.each do |suggestion| %>
30
+ <div class="suggestion">
31
+ <div class="row"><h3><%= suggestion[:title] %></h3><span class="badge"><%= suggestion[:confidence] %> confidence</span></div>
32
+ <p class="muted"><%= suggestion[:explanation] %></p>
33
+ <pre><%= suggestion[:code] %></pre>
34
+ </div>
35
+ <% end %>
36
+ </section>
37
+ </div>
38
+
39
+ <section>
40
+ <h2>Affected model graph</h2>
41
+ <% models = @detection.models.presence || [{ name: "Unknown model", table: "unknown" }] %>
42
+ <% height = [models.length * 100, 240].max %>
43
+ <svg class="graph" viewBox="0 0 360 <%= height %>" role="img" aria-label="Models involved in the repeated query">
44
+ <% models.each_with_index do |model, index| %>
45
+ <% y = 25 + index * 100 %>
46
+ <% if index.positive? %><line x1="180" y1="<%= y - 50 %>" x2="180" y2="<%= y %>"/><% end %>
47
+ <rect x="70" y="<%= y %>" width="220" height="58" rx="9"/>
48
+ <text x="180" y="<%= y + 25 %>" text-anchor="middle"><%= model[:name] %></text>
49
+ <text x="180" y="<%= y + 44 %>" text-anchor="middle" opacity=".65"><%= model[:table] %></text>
50
+ <% end %>
51
+ <% @detection.edges.each_with_index do |edge, index| %>
52
+ <text x="190" y="<%= 20 + (index + 1) * 100 %>" opacity=".7"><%= edge[:association] %></text>
53
+ <% end %>
54
+ </svg>
55
+ </section>
56
+ </div>
data/config/routes.rb ADDED
@@ -0,0 +1,6 @@
1
+ NPlusInsight::Engine.routes.draw do
2
+ root "detections#index"
3
+ get "assets/overlay.css", to: "assets#stylesheet"
4
+ get "assets/overlay.js", to: "assets#script"
5
+ resources :detections, only: [:show]
6
+ end
@@ -0,0 +1,117 @@
1
+ module NPlusInsight
2
+ class Analyzer
3
+ def initialize(request:, queries:)
4
+ @request = request
5
+ @queries = queries
6
+ end
7
+
8
+ def call
9
+ groups = @queries.group_by(&:binds_signature)
10
+ groups.filter_map do |_shape, queries|
11
+ next if queries.length < NPlusInsight.configuration.minimum_repetitions
12
+ build_detection(queries)
13
+ end
14
+ end
15
+
16
+ private
17
+
18
+ def build_detection(queries)
19
+ tables = queries.flat_map(&:tables).uniq
20
+ model_map = model_map_for(tables)
21
+ location = queries.filter_map(&:location).group_by { |item| [item.path, item.line] }.max_by { |_key, values| values.length }&.last&.first
22
+ inferred = infer_owner(model_map.values, location)
23
+ graph_models = ([inferred&.fetch(:owner, nil)] + model_map.values).compact.uniq
24
+ models = graph_models.map { |model| { table: model.table_name, name: model.name, primary: tables.include?(model.table_name) } }
25
+ models = tables.map { |table| { table: table, name: table.classify, primary: true } } if models.empty?
26
+ edges = inferred ? [{ from: inferred[:owner].name, to: inferred[:target].name, association: inferred[:reflection].name, macro: inferred[:reflection].macro }] : association_edges(model_map)
27
+
28
+ Detection.new(
29
+ id: SecureRandom.uuid,
30
+ request_id: @request[:request_id],
31
+ method: @request[:method],
32
+ path: @request[:path],
33
+ created_at: Time.now.utc.iso8601,
34
+ query_count: queries.length,
35
+ total_ms: queries.sum(&:duration_ms).round(2),
36
+ sql: queries.first.normalized_sql,
37
+ location: location,
38
+ models: models,
39
+ edges: edges,
40
+ suggestions: suggestions(model_map, tables, location, inferred)
41
+ )
42
+ end
43
+
44
+ def model_map_for(tables)
45
+ return {} unless defined?(ActiveRecord::Base)
46
+ Rails.application.eager_load! if Rails.application.config.eager_load && ActiveRecord::Base.descendants.empty?
47
+ ActiveRecord::Base.descendants.each_with_object({}) do |model, map|
48
+ map[model.table_name] = model unless model.abstract_class?
49
+ rescue StandardError
50
+ next
51
+ end.slice(*tables)
52
+ end
53
+
54
+ def association_edges(model_map)
55
+ model_map.values.flat_map do |model|
56
+ model.reflect_on_all_associations.filter_map do |reflection|
57
+ target = reflection.klass rescue nil
58
+ next unless target && model_map.value?(target)
59
+ { from: model.name, to: target.name, association: reflection.name, macro: reflection.macro }
60
+ end
61
+ end.uniq
62
+ end
63
+
64
+ def infer_owner(targets, location)
65
+ return unless defined?(ActiveRecord::Base)
66
+ candidates = ActiveRecord::Base.descendants.flat_map do |owner|
67
+ owner.reflect_on_all_associations.filter_map do |reflection|
68
+ target = reflection.klass rescue nil
69
+ { owner: owner, target: target, reflection: reflection } if targets.include?(target)
70
+ end
71
+ rescue StandardError
72
+ []
73
+ end
74
+ source = location&.snippet.to_a.map { |line| line[:text] }.join(" ")
75
+ receiver_match = candidates.find do |item|
76
+ owner_name = item[:owner].model_name.element
77
+ association_name = item[:reflection].name
78
+ source.match?(/(?:@|\b)#{Regexp.escape(owner_name)}\.#{Regexp.escape(association_name.to_s)}\b/i)
79
+ end
80
+ receiver_match ||
81
+ candidates.find { |item| source.match?(/\b#{Regexp.escape(item[:reflection].name.to_s)}\b/) } ||
82
+ candidates.first
83
+ end
84
+
85
+ def suggestions(model_map, tables, location, inferred)
86
+ edges = inferred ? [{ from: inferred[:owner].name, association: inferred[:reflection].name }] : association_edges(model_map)
87
+ association = edges.first&.fetch(:association, nil)
88
+ owner = edges.first&.fetch(:from, nil)
89
+ relation = owner || "ParentModel"
90
+ eager_load = association ? "#{relation}.includes(:#{association})" : "ParentModel.includes(:association)"
91
+
92
+ results = [
93
+ {
94
+ title: "Eager-load the association",
95
+ code: eager_load,
96
+ explanation: "Load related rows in a bounded number of queries before the loop renders them.",
97
+ confidence: association ? "high" : "medium"
98
+ },
99
+ {
100
+ title: "Use strict loading to prevent regressions",
101
+ code: "#{relation}.strict_loading",
102
+ explanation: "Rails will raise when code lazily loads an association that was not preloaded.",
103
+ confidence: "medium"
104
+ }
105
+ ]
106
+ if location
107
+ results.unshift(
108
+ title: "Change the relation feeding this line",
109
+ code: "# #{location.path}:#{location.line}\n#{eager_load}",
110
+ explanation: "Apply eager loading where the parent relation is constructed, not inside the iteration.",
111
+ confidence: association ? "high" : "medium"
112
+ )
113
+ end
114
+ results
115
+ end
116
+ end
117
+ end
@@ -0,0 +1,17 @@
1
+ module NPlusInsight
2
+ class Configuration
3
+ attr_accessor :enabled, :minimum_repetitions, :max_events, :mount_path,
4
+ :ignore_paths, :ignore_sql, :raise_on_detection, :on_page
5
+
6
+ def initialize
7
+ @enabled = ENV.fetch("NPLUS_INSIGHT_ENABLED", "false").match?(/\A(?:1|true|yes|on)\z/i)
8
+ @minimum_repetitions = 2
9
+ @max_events = 100
10
+ @mount_path = "/n_plus_insight"
11
+ @ignore_paths = [%r{\A/assets}, %r{\A/packs}, %r{\A/rails/active_storage}]
12
+ @ignore_sql = [/\A(?:BEGIN|COMMIT|ROLLBACK|SAVEPOINT|RELEASE)/i, /schema_migrations/i, /ar_internal_metadata/i]
13
+ @raise_on_detection = false
14
+ @on_page = true
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,13 @@
1
+ module NPlusInsight
2
+ module Current
3
+ KEY = :__n_plus_insight_collector
4
+
5
+ class << self
6
+ def collector = Thread.current[KEY]
7
+
8
+ def collector=(value)
9
+ Thread.current[KEY] = value
10
+ end
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,10 @@
1
+ module NPlusInsight
2
+ Detection = Struct.new(
3
+ :id, :request_id, :method, :path, :created_at, :query_count, :total_ms,
4
+ :sql, :location, :models, :edges, :suggestions, keyword_init: true
5
+ ) do
6
+ def as_json(*)
7
+ members.to_h { |member| [member, public_send(member)] }
8
+ end
9
+ end
10
+ end
@@ -0,0 +1,16 @@
1
+ module NPlusInsight
2
+ class Engine < ::Rails::Engine
3
+ isolate_namespace NPlusInsight
4
+
5
+ initializer "n_plus_insight.middleware" do |app|
6
+ Subscriber.install!
7
+ app.middleware.insert_after ActionDispatch::RequestId, NPlusInsight::Middleware
8
+ end
9
+
10
+ initializer "n_plus_insight.routes" do |app|
11
+ app.routes.append do
12
+ mount NPlusInsight::Engine => NPlusInsight.configuration.mount_path
13
+ end
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,71 @@
1
+ module NPlusInsight
2
+ class Middleware
3
+ def initialize(app) = @app = app
4
+
5
+ def call(env)
6
+ previous = Current.collector
7
+ config = NPlusInsight.configuration
8
+ return @app.call(env) unless config.enabled
9
+ return @app.call(env) if env["PATH_INFO"].to_s.start_with?(config.mount_path)
10
+ return @app.call(env) if config.ignore_paths.any? { |pattern| pattern.match?(env["PATH_INFO"].to_s) }
11
+
12
+ queries = []
13
+ Current.collector = queries
14
+ status, headers, body = @app.call(env)
15
+
16
+ if injectable_html?(headers, config)
17
+ chunks = []
18
+ body.each { |chunk| chunks << chunk }
19
+ body.close if body.respond_to?(:close)
20
+ detections = analyze(env, queries, config)
21
+ html = chunks.join
22
+ html = inject(html, Overlay.render(detections))
23
+ headers.delete("Content-Length")
24
+ headers.delete("content-length")
25
+ headers["Content-Length"] = html.bytesize.to_s
26
+ [status, headers, [html]]
27
+ else
28
+ analyze(env, queries, config)
29
+ [status, headers, body]
30
+ end
31
+ ensure
32
+ Current.collector = previous
33
+ end
34
+
35
+ private
36
+
37
+ def injectable_html?(headers, config)
38
+ config.on_page &&
39
+ header_value(headers, "content-type").include?("text/html") &&
40
+ header_value(headers, "content-encoding").empty?
41
+ end
42
+
43
+ def header_value(headers, name)
44
+ pair = headers.find { |key, _value| key.to_s.downcase == name }
45
+ pair ? pair.last.to_s : ""
46
+ end
47
+
48
+ def analyze(env, queries, config)
49
+ request = {
50
+ request_id: env["action_dispatch.request_id"],
51
+ method: env["REQUEST_METHOD"],
52
+ path: env["PATH_INFO"]
53
+ }
54
+ detections = Analyzer.new(request: request, queries: queries).call
55
+ detections.each { |detection| Store.add(detection) }
56
+ if config.raise_on_detection && detections.any?
57
+ first = detections.first
58
+ raise "N+1 query detected at #{first.location&.path}:#{first.location&.line}"
59
+ end
60
+ detections
61
+ end
62
+
63
+ def inject(html, overlay)
64
+ if html.match?(%r{</body>}i)
65
+ html.sub(%r{</body>}i, "#{overlay}</body>")
66
+ else
67
+ "#{html}#{overlay}"
68
+ end
69
+ end
70
+ end
71
+ end
@@ -0,0 +1,33 @@
1
+ module NPlusInsight
2
+ module Overlay
3
+ class << self
4
+ def render(detections)
5
+ payload = Base64.strict_encode64(JSON.generate(detections.map { |detection| serialize(detection) }))
6
+ mount_path = NPlusInsight.configuration.mount_path.chomp("/")
7
+
8
+ <<~HTML
9
+ <div id="n1v-root" data-payload="#{payload}"></div>
10
+ <link rel="stylesheet" href="#{mount_path}/assets/overlay.css">
11
+ <script src="#{mount_path}/assets/overlay.js" defer></script>
12
+ HTML
13
+ end
14
+
15
+ private
16
+
17
+ def serialize(detection)
18
+ {
19
+ id: detection.id,
20
+ method: detection.method,
21
+ path: detection.path,
22
+ query_count: detection.query_count,
23
+ total_ms: detection.total_ms,
24
+ sql: detection.sql,
25
+ location: detection.location&.as_json,
26
+ models: detection.models,
27
+ edges: detection.edges,
28
+ suggestions: detection.suggestions
29
+ }
30
+ end
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,16 @@
1
+ module NPlusInsight
2
+ Query = Struct.new(:sql, :name, :duration_ms, :cached, :location, :tables, keyword_init: true) do
3
+ def normalized_sql
4
+ sql.to_s
5
+ .gsub(/'(?:[^']|'')*'/, "?")
6
+ .gsub(/\b\d+(?:\.\d+)?\b/, "?")
7
+ .gsub(/\bIN\s*\((?:\s*\?,?\s*)+\)/i, "IN (?)")
8
+ .gsub(/\s+/, " ")
9
+ .strip
10
+ end
11
+
12
+ def binds_signature
13
+ normalized_sql
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,35 @@
1
+ module NPlusInsight
2
+ SourceLocation = Struct.new(:path, :line, :label, :snippet, keyword_init: true) do
3
+ FRAME_PATTERN = /\A(.+?):(\d+)(?::in [`'](.+)[`'])?\z/
4
+
5
+ def self.from(caller_lines)
6
+ root = defined?(Rails) && Rails.respond_to?(:root) && Rails.root ? Rails.root.to_s.tr("\\", "/") : nil
7
+ frame = caller_lines.find do |entry|
8
+ path = entry.to_s.tr("\\", "/")
9
+ root ? path.start_with?("#{root}/app/", "#{root}/lib/") : !path.include?("/gems/")
10
+ end
11
+ return unless frame
12
+
13
+ match = FRAME_PATTERN.match(frame.to_s)
14
+ return unless match
15
+
16
+ path, line, label = match.captures
17
+ line = line.to_i
18
+ new(path: path, line: line, label: label, snippet: read_snippet(path, line))
19
+ end
20
+
21
+ def self.read_snippet(path, line)
22
+ lines = File.readlines(path)
23
+ first = [line - 3, 0].max
24
+ lines[first, 5].to_a.each_with_index.map do |text, index|
25
+ { line: first + index + 1, text: text.chomp, active: first + index + 1 == line }
26
+ end
27
+ rescue SystemCallError, ArgumentError
28
+ []
29
+ end
30
+
31
+ def as_json(*)
32
+ { path: path, line: line, label: label, snippet: snippet }
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,21 @@
1
+ require "monitor"
2
+
3
+ module NPlusInsight
4
+ module Store
5
+ @events = []
6
+ @lock = Monitor.new
7
+
8
+ class << self
9
+ def add(event)
10
+ @lock.synchronize do
11
+ @events.unshift(event)
12
+ @events = @events.first(NPlusInsight.configuration.max_events)
13
+ end
14
+ end
15
+
16
+ def all = @lock.synchronize { @events.dup }
17
+ def find(id) = @lock.synchronize { @events.find { |event| event.id == id } }
18
+ def clear = @lock.synchronize { @events.clear }
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,33 @@
1
+ module NPlusInsight
2
+ module Subscriber
3
+ TABLE_PATTERN = /\b(?:FROM|JOIN)\s+["`]?([a-zA-Z_][\w.]*)["`]?/i
4
+
5
+ class << self
6
+ def install!
7
+ return if @subscriber
8
+ @subscriber = ActiveSupport::Notifications.subscribe("sql.active_record") do |_name, started, finished, _id, payload|
9
+ record(started, finished, payload)
10
+ end
11
+ end
12
+
13
+ def record(started, finished, payload)
14
+ collector = Current.collector
15
+ return unless collector
16
+ sql = payload[:sql].to_s
17
+ config = NPlusInsight.configuration
18
+ return if payload[:cached] || payload[:name].to_s == "SCHEMA"
19
+ return unless sql.lstrip.match?(/\ASELECT\b/i)
20
+ return if config.ignore_sql.any? { |pattern| pattern.match?(sql) }
21
+
22
+ collector << Query.new(
23
+ sql: sql,
24
+ name: payload[:name],
25
+ duration_ms: (finished - started) * 1000,
26
+ cached: payload[:cached],
27
+ location: SourceLocation.from(caller),
28
+ tables: sql.scan(TABLE_PATTERN).flatten.map { |table| table.split(".").last.delete('"`') }.uniq
29
+ )
30
+ end
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,3 @@
1
+ module NPlusInsight
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,38 @@
1
+ require "active_support"
2
+ require "active_support/notifications"
3
+ require "active_support/core_ext/string/inflections"
4
+ require "base64"
5
+ require "json"
6
+ require "securerandom"
7
+ require "time"
8
+
9
+ require_relative "n_plus_insight/version"
10
+ require_relative "n_plus_insight/configuration"
11
+ require_relative "n_plus_insight/current"
12
+ require_relative "n_plus_insight/query"
13
+ require_relative "n_plus_insight/source_location"
14
+ require_relative "n_plus_insight/detection"
15
+ require_relative "n_plus_insight/analyzer"
16
+ require_relative "n_plus_insight/store"
17
+ require_relative "n_plus_insight/overlay"
18
+ require_relative "n_plus_insight/subscriber"
19
+ require_relative "n_plus_insight/middleware"
20
+
21
+ module NPlusInsight
22
+ class << self
23
+ def configuration
24
+ @configuration ||= Configuration.new
25
+ end
26
+
27
+ def configure
28
+ yield(configuration)
29
+ end
30
+
31
+ def reset!
32
+ @configuration = Configuration.new
33
+ Store.clear
34
+ end
35
+ end
36
+ end
37
+
38
+ require_relative "n_plus_insight/engine" if defined?(Rails::Engine)
metadata ADDED
@@ -0,0 +1,92 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: n_plus_insight
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - NPlusInsight contributors
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2026-07-28 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rails
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '7.0'
20
+ - - "<"
21
+ - !ruby/object:Gem::Version
22
+ version: '9'
23
+ type: :runtime
24
+ prerelease: false
25
+ version_requirements: !ruby/object:Gem::Requirement
26
+ requirements:
27
+ - - ">="
28
+ - !ruby/object:Gem::Version
29
+ version: '7.0'
30
+ - - "<"
31
+ - !ruby/object:Gem::Version
32
+ version: '9'
33
+ description: A Rails engine that detects repeated query shapes per request, pinpoints
34
+ the application code responsible, visualizes affected Active Record models, and
35
+ recommends eager-loading fixes.
36
+ email:
37
+ executables: []
38
+ extensions: []
39
+ extra_rdoc_files: []
40
+ files:
41
+ - CHANGELOG.md
42
+ - LICENSE.txt
43
+ - README.md
44
+ - RELEASING.md
45
+ - app/assets/n_plus_insight/overlay.css
46
+ - app/assets/n_plus_insight/overlay.js
47
+ - app/controllers/n_plus_insight/application_controller.rb
48
+ - app/controllers/n_plus_insight/assets_controller.rb
49
+ - app/controllers/n_plus_insight/detections_controller.rb
50
+ - app/views/layouts/n_plus_insight/application.html.erb
51
+ - app/views/n_plus_insight/detections/index.html.erb
52
+ - app/views/n_plus_insight/detections/show.html.erb
53
+ - config/routes.rb
54
+ - lib/n_plus_insight.rb
55
+ - lib/n_plus_insight/analyzer.rb
56
+ - lib/n_plus_insight/configuration.rb
57
+ - lib/n_plus_insight/current.rb
58
+ - lib/n_plus_insight/detection.rb
59
+ - lib/n_plus_insight/engine.rb
60
+ - lib/n_plus_insight/middleware.rb
61
+ - lib/n_plus_insight/overlay.rb
62
+ - lib/n_plus_insight/query.rb
63
+ - lib/n_plus_insight/source_location.rb
64
+ - lib/n_plus_insight/store.rb
65
+ - lib/n_plus_insight/subscriber.rb
66
+ - lib/n_plus_insight/version.rb
67
+ homepage:
68
+ licenses:
69
+ - MIT
70
+ metadata:
71
+ allowed_push_host: https://rubygems.org
72
+ rubygems_mfa_required: 'true'
73
+ post_install_message:
74
+ rdoc_options: []
75
+ require_paths:
76
+ - lib
77
+ required_ruby_version: !ruby/object:Gem::Requirement
78
+ requirements:
79
+ - - ">="
80
+ - !ruby/object:Gem::Version
81
+ version: '3.1'
82
+ required_rubygems_version: !ruby/object:Gem::Requirement
83
+ requirements:
84
+ - - ">="
85
+ - !ruby/object:Gem::Version
86
+ version: '0'
87
+ requirements: []
88
+ rubygems_version: 3.5.22
89
+ signing_key:
90
+ specification_version: 4
91
+ summary: Detect, locate, visualize, and fix Rails N+1 queries
92
+ test_files: []