Repository navigation
[Feature] NerdyData search engine - #723
Conversation
Neo - PR Security ReviewNo security issues found Comment |
WalkthroughAdds NerdyData as a supported search provider: docs/config updates, an integration test, CLI flag and engine handling, provider key loading, rate-limit entry, a new NerdyData agent package (request/response types, pagination and retry logic), and service registration. Changes
Sequence DiagramsequenceDiagram
participant Client as Client
participant Service as Service
participant Agent as NerdyDataAgent
participant RateLimiter as RateLimiter
participant API as NerdyDataAPI
participant Stream as ResultStream
Client->>Service: Start nerdydata query
Service->>Agent: Query(session, query)
loop per page
Agent->>RateLimiter: Take("nerdydata")
RateLimiter-->>Agent: Permit
Agent->>API: GET (api_key header, page cursor)
alt 202 Accepted
API-->>Agent: 202 Accepted
Agent->>Agent: Backoff & retry
else 200 OK
API-->>Agent: 200 + JSON
Agent->>Agent: Unmarshal Response
loop per Site
Agent->>Stream: Emit Result{Host, Url, Raw}
end
alt next_page present
Agent->>Agent: set cursor = next_page
else
Agent->>Stream: Close channel
end
else error
API-->>Agent: Error
Agent->>Stream: Emit Result{Error} & Close channel
end
end
Stream-->>Service: Streamed results
Service-->>Client: Return results
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (1)
sources/agent/nerdydata/request.go (1)
27-32: Consider handling thejson.Marshalerror.While
json.Marshalis unlikely to fail for this simple map structure, ignoring the error silently could mask unexpected issues in edge cases. Consider logging or returning an error if marshaling fails.🔧 Proposed defensive handling
- wrapped, _ := json.Marshal(map[string]any{ + wrapped, err := json.Marshal(map[string]any{ "all": []map[string]string{ {"type": "code", "value": r.Query}, }, }) + if err != nil { + // Fallback: use query as-is (should never happen) + params.Set("search", r.Query) + params.Set("facets", "false") + if r.Page != "" { + params.Set("page", r.Page) + } + return baseURL + baseEndpoint + "?" + params.Encode() + } params.Set("search", string(wrapped))🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@sources/agent/nerdydata/request.go` around lines 27 - 32, Handle the error returned by json.Marshal instead of discarding it: check the error from json.Marshal when creating wrapped (which includes r.Query), and on failure either return the error from the enclosing function or log it before returning so you don't call params.Set("search", string(wrapped)) with an invalid value; update the code around the json.Marshal call (wrapped, err := json.Marshal(...)) and the subsequent params.Set usage to only proceed when err == nil.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@integration-tests/source-test.go`:
- Line 300: The os.WriteFile call currently discards its error; update the
NerdyData test setup where ConfigFile is written with []byte(nerdydataToken) to
check the returned error and fail the test on error (e.g., if err :=
os.WriteFile(ConfigFile, []byte(nerdydataToken), 0644); err != nil {
t.Fatalf("failed to write config file: %v", err) } or use your test
helper/assertion equivalent), ensuring the test surface reports setup failures
instead of silently continuing.
In `@README.md`:
- Line 53: Replace the tracked NerdyData link in the README entry
"**[NerdyData](https://www.nerdydata.com/?utm_source=projectdiscovery/uncover)**"
with the canonical provider URL by removing the utm_source query string so it
becomes "**[NerdyData](https://www.nerdydata.com/)**"; update the Markdown link
text in README.md accordingly to keep docs neutral and stable.
In `@sources/agent/nerdydata/nerdydata.go`:
- Around line 44-48: The 202 handling currently loops forever; change the logic
in the function handling the HTTP response (the block that checks
resp.StatusCode == http.StatusAccepted) to implement a bounded retry: add a
maxRetries counter (e.g., max202Retries) and an increasing backoff delay
(exponential with jitter) between retries, incrementing the counter each time
you close resp.Body and retry; if maxRetries is exceeded return a clear error
instead of continuing forever. Use the existing request context (ctx) or check
ctx.Done() during sleeps so retries are cancelable, and ensure resp.Body.Close()
is still called on each attempt.
In `@sources/provider.go`:
- Line 180: The code appends an empty NERDYDATA_API_KEY when the env var is
present but blank; update the logic so provider.NerdyData is only appended when
the value is non-empty by changing the call/site around provider.NerdyData =
appendIfExists(provider.NerdyData, "NERDYDATA_API_KEY") (or modify
appendIfExists) to treat empty strings as missing (use os.LookupEnv or check
value != "" before appending) so blank env values are skipped.
---
Nitpick comments:
In `@sources/agent/nerdydata/request.go`:
- Around line 27-32: Handle the error returned by json.Marshal instead of
discarding it: check the error from json.Marshal when creating wrapped (which
includes r.Query), and on failure either return the error from the enclosing
function or log it before returning so you don't call params.Set("search",
string(wrapped)) with an invalid value; update the code around the json.Marshal
call (wrapped, err := json.Marshal(...)) and the subsequent params.Set usage to
only proceed when err == nil.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 0e0e3a3e-6a85-4f24-aad2-00a4ed46183c
📒 Files selected for processing (11)
README.mdintegration-tests/integration-test.gointegration-tests/source-test.gorunner/options.gosources/agent/nerdydata/nerdydata.gosources/agent/nerdydata/request.gosources/agent/nerdydata/response.gosources/keys.gosources/provider.gosources/session.gouncover.go
| return errors.New("missing NerdyData api key") | ||
| } | ||
| nerdydataToken := fmt.Sprintf(`nerdydata: [%s]`, token) | ||
| _ = os.WriteFile(ConfigFile, []byte(nerdydataToken), 0644) |
There was a problem hiding this comment.
Handle config write errors in the NerdyData testcase.
Line 300 ignores os.WriteFile errors, which can hide test setup failures.
Proposed fix
- _ = os.WriteFile(ConfigFile, []byte(nerdydataToken), 0644)
+ if err := os.WriteFile(ConfigFile, []byte(nerdydataToken), 0644); err != nil {
+ return err
+ }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@integration-tests/source-test.go` at line 300, The os.WriteFile call
currently discards its error; update the NerdyData test setup where ConfigFile
is written with []byte(nerdydataToken) to check the returned error and fail the
test on error (e.g., if err := os.WriteFile(ConfigFile, []byte(nerdydataToken),
0644); err != nil { t.Fatalf("failed to write config file: %v", err) } or use
your test helper/assertion equivalent), ensuring the test surface reports setup
failures instead of silently continuing.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
sources/agent/nerdydata/nerdydata.go (1)
42-54: Consider reducing the exponential backoff base value.The current backoff formula
30*(1<<attempt)yields wait times of 30s, 60s, 120s, 240s, and 480s per retry, totaling ~15 minutes in the worst case. This is unusually aggressive for client-side retry logic and may significantly impact user experience when the NerdyData API is under load.Additionally, the
time.Sleepdoesn't respect context cancellation, so a cancelled operation will still block until the sleep completes.♻️ Suggested improvement with shorter backoff and cancellation support
+import "context" + func (agent *Agent) Query(session *sources.Session, query *sources.Query) (chan sources.Result, error) { + ctx := context.Background() // or accept context as parameter // ... existing validation ... go func() { defer close(results) const maxRetries = 5 // ... for attempt := 0; attempt < maxRetries; attempt++ { resp, err = agent.queryURL(session, nerdydataRequest.buildURL(), session.Keys.NerdyDataToken) // ... error handling ... if resp.StatusCode != http.StatusAccepted { break } resp.Body.Close() - time.Sleep(time.Duration(30*(1<<attempt)) * time.Second) + backoff := time.Duration(2*(1<<attempt)) * time.Second // 2s, 4s, 8s, 16s, 32s + select { + case <-ctx.Done(): + results <- sources.Result{Source: agent.Name(), Error: ctx.Err()} + return + case <-time.After(backoff): + } }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@sources/agent/nerdydata/nerdydata.go` around lines 42 - 54, The retry backoff in the loop that calls agent.queryURL(session, nerdydataRequest.buildURL(), session.Keys.NerdyDataToken) is too large and ignores cancellation; replace the current exponential multiplier 30*(1<<attempt) with a much smaller base and a max cap (e.g., base 2–5 seconds with a maxBackoff), and change the unconditional time.Sleep to a context-aware wait (select on time.After(backoff) and ctx.Done()) so retries stop promptly if the calling context is cancelled; keep the existing retry loop structure, using attempt/maxRetries and closing resp.Body before waiting.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@sources/agent/nerdydata/nerdydata.go`:
- Around line 42-54: The retry backoff in the loop that calls
agent.queryURL(session, nerdydataRequest.buildURL(),
session.Keys.NerdyDataToken) is too large and ignores cancellation; replace the
current exponential multiplier 30*(1<<attempt) with a much smaller base and a
max cap (e.g., base 2–5 seconds with a maxBackoff), and change the unconditional
time.Sleep to a context-aware wait (select on time.After(backoff) and
ctx.Done()) so retries stop promptly if the calling context is cancelled; keep
the existing retry loop structure, using attempt/maxRetries and closing
resp.Body before waiting.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: f6a6a622-c7b9-4489-80f0-27b9c96e61ab
📒 Files selected for processing (1)
sources/agent/nerdydata/nerdydata.go
… full sleep duration
|
Hi @knakul853 @ShubhamRasal Let me know if you'd also like an API key to test this out with as you review, or if you have any questions. |
|
@davidbielik Could you share the API key with the reviewers? My discord handle is the same as GitHub one. |
| case <-ctx.Done(): | ||
| results <- sources.Result{Source: agent.Name(), Error: ctx.Err()} |
There was a problem hiding this comment.
nit: ctx := context.Background() at nerdydata.go:31 means the select { case <-ctx.Done(): … } at line
67 can never fire. So the "retries abort on cancellation" behavior isn't actually happening
There was a problem hiding this comment.
Thanks - just removed
ShubhamRasal
left a comment
There was a problem hiding this comment.
Suggested a small fix, we can drop the ctx for now. This needs a refactor across all providers, tracked here: #724
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@sources/agent/nerdydata/nerdydata.go`:
- Around line 44-86: The resp.Body.Close() calls are redundant and their errors
are ignored; consolidate cleanup to a single explicit discard of the Close()
error. After the retry loop and once you decide to stop using resp (before any
returns or decoding), call _ = resp.Body.Close() exactly once (or ensure a
single defer/cleanup path) and remove the other resp.Body.Close() calls; update
the 202 retry-exhausted and non-200 error paths to rely on that single cleanup
and ensure the json.Decoder use happens before closing (use symbols resp,
queryURL, nerdydataRequest.buildURL, Response, maxRetries to locate the logic).
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 8d8e0cb5-9d36-427f-a094-877bbefb1ed4
📒 Files selected for processing (1)
sources/agent/nerdydata/nerdydata.go
| for attempt := 0; attempt < maxRetries; attempt++ { | ||
| resp, err = agent.queryURL(session, nerdydataRequest.buildURL(), session.Keys.NerdyDataToken) | ||
| if err != nil { | ||
| results <- sources.Result{Source: agent.Name(), Error: err} | ||
| return | ||
| } | ||
| if resp.StatusCode != http.StatusAccepted { | ||
| break | ||
| } | ||
| // 202 = server-side timeout; back off and retry with same cursor | ||
| resp.Body.Close() | ||
| backoff := baseBackoff * (1 << attempt) | ||
| if backoff > maxBackoff { | ||
| backoff = maxBackoff | ||
| } | ||
| time.Sleep(backoff) | ||
| } | ||
| if resp.StatusCode == http.StatusAccepted { | ||
| resp.Body.Close() | ||
| results <- sources.Result{ | ||
| Source: agent.Name(), | ||
| Error: fmt.Errorf("server returned 202 after %d retries", maxRetries), | ||
| } | ||
| return | ||
| } | ||
|
|
||
| if resp.StatusCode != http.StatusOK { | ||
| body, _ := io.ReadAll(resp.Body) | ||
| resp.Body.Close() | ||
| results <- sources.Result{ | ||
| Source: agent.Name(), | ||
| Error: fmt.Errorf("unexpected status %d: %s", resp.StatusCode, body), | ||
| } | ||
| return | ||
| } | ||
|
|
||
| var apiResponse Response | ||
| if err := json.NewDecoder(resp.Body).Decode(&apiResponse); err != nil { | ||
| resp.Body.Close() | ||
| results <- sources.Result{Source: agent.Name(), Error: err} | ||
| return | ||
| } | ||
| resp.Body.Close() |
There was a problem hiding this comment.
Tighten the 202 cleanup path.
The last accepted response is already closed inside the retry loop, so the post-loop Close() is redundant. All of the Close() calls in this block also ignore their errors, which is what the linter is flagging. Please collapse this into a single cleanup point or explicitly discard the error once with _ = resp.Body.Close() so the intent is clear.
♻️ Suggested cleanup
if resp.StatusCode != http.StatusAccepted {
break
}
// 202 = server-side timeout; back off and retry with same cursor
- resp.Body.Close()
+ _ = resp.Body.Close()
backoff := baseBackoff * (1 << attempt)
if backoff > maxBackoff {
backoff = maxBackoff
}
time.Sleep(backoff)
}
if resp.StatusCode == http.StatusAccepted {
- resp.Body.Close()
results <- sources.Result{
Source: agent.Name(),
Error: fmt.Errorf("server returned 202 after %d retries", maxRetries),
}
return
}
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
- resp.Body.Close()
+ _ = resp.Body.Close()
results <- sources.Result{
Source: agent.Name(),
Error: fmt.Errorf("unexpected status %d: %s", resp.StatusCode, body),
}
return
}
@@
var apiResponse Response
if err := json.NewDecoder(resp.Body).Decode(&apiResponse); err != nil {
- resp.Body.Close()
+ _ = resp.Body.Close()
results <- sources.Result{Source: agent.Name(), Error: err}
return
}
- resp.Body.Close()
+ _ = resp.Body.Close()🧰 Tools
🪛 golangci-lint (2.11.4)
[error] 54-54: Error return value of resp.Body.Close is not checked
(errcheck)
[error] 62-62: Error return value of resp.Body.Close is not checked
(errcheck)
[error] 72-72: Error return value of resp.Body.Close is not checked
(errcheck)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@sources/agent/nerdydata/nerdydata.go` around lines 44 - 86, The
resp.Body.Close() calls are redundant and their errors are ignored; consolidate
cleanup to a single explicit discard of the Close() error. After the retry loop
and once you decide to stop using resp (before any returns or decoding), call _
= resp.Body.Close() exactly once (or ensure a single defer/cleanup path) and
remove the other resp.Body.Close() calls; update the 202 retry-exhausted and
non-200 error paths to rely on that single cleanup and ensure the json.Decoder
use happens before closing (use symbols resp, queryURL,
nerdydataRequest.buildURL, Response, maxRetries to locate the logic).
[Feature] NerdyData search engine
[Feature] NerdyData search engine
NerdyData has been around since 2012, and is a popular crawler and search engine for web source code.
NerdyData scans millions of websites, fully renders javascript in a headless browser, and makes the following code fingerprints available for search:
Feature:
-nerdydata/-ndflags or-e nerdydata./livewire/livewire.js)--rawoptionNew files
sources/agent/nerdydata/nerdydata.go— Agent implementation with cursor-based pagination and retry logicsources/agent/nerdydata/request.go— URL builder; wraps plain strings as code-search JSON, passes through raw JSON objects unchangedsources/agent/nerdydata/response.go— Response types (Response, Site)Modified files
sources/keys.go— AddedNerdyDataTokenfieldsources/provider.go— Added NerdyData provider config, env var (NERDYDATA_API_KEY), and HasKeys()support
sources/session.go— Added nerdydata rate limit entryuncover.go— Registered agent in New() switch and AllAgents()runner/options.go— Added -nd/-nerdydata CLI flagintegration-tests/— Added nerdydataTestcases and registered in test mapAPI details
https://api.nerdydata.com/searchapi_keyrequest headernext_pageresponse fieldLocal test instructions
Summary by CodeRabbit
New Features
Tests
Documentation