Skip to content

refactor(cleanup): Rename from sdk to basic - #42

Merged
SteakFisher merged 1 commit into
mainfrom
refactor/cleanup
May 17, 2026
Merged

refactor(cleanup): Rename from sdk to basic#42
SteakFisher merged 1 commit into
mainfrom
refactor/cleanup

Conversation

@SteakFisher

@SteakFisher SteakFisher commented May 17, 2026

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • Bug Fixes

    • Updated event handling to correctly map cache-related fields and usage type classifications in event storage and processing.
  • Refactor

    • Restructured internal event payload field naming for improved consistency across basic usage event workflows.

Review Change Stack

@coderabbitai

coderabbitai Bot commented May 17, 2026

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This PR renames SDK_CALL terminology to BASIC_USAGE across the event system. Input schemas now accept basicusage payloads with basicusagetype discriminators, event construction uses the new field names, storage adapters route BASIC_USAGE events to dedicated handlers, and gRPC response mapping correctly sets the basicUsageType protobuf field while adding cache field support.

Changes

SDK_CALL to BASIC_USAGE terminology refactor

Layer / File(s) Summary
Input schema and event payload shape
src/zod/event.ts
BasicUsageDataSchema now uses basicusagetype as the discriminator field and the transform maps it to basicUsageType. Event schemas RegisterEventBasicUsage and StreamEventBasicUsage expose the payload under basicusage instead of sdkcall.
Event construction from payload
src/utils/eventHelpers.ts
createEventInstance now sources BASIC_USAGE event data from eventSkeleton.basicusage instead of eventSkeleton.sdkcall.
ClickHouse and Postgres handler naming and routing
src/storage/adapter/clickhouse/ClickHouseAdapter.ts, src/storage/adapter/clickhouse/handlers/*.ts, src/storage/adapter/postgres/postgres.ts, src/storage/adapter/postgres/handlers/*.ts
Handler functions handleAddSdkCall and handlePriceRequestSdkCall renamed to handleAddBasicUsage and handlePriceRequestBasicUsage in both ClickHouse and Postgres implementations. Adapter imports and event routing in add() and price() methods updated to call the renamed handlers. Barrel exports in handler index files updated to re-export the BASIC_USAGE variants.
gRPC query response protobuf mapping
src/routes/gRPC/query/queryEvents.ts
buildEventRow sets basicUsageType protobuf field via setBasicUsageType instead of setSdkCallType, and adds conditional protobuf mappings for inputCacheTokens and inputCacheDebitAmount cache fields when present.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related PRs

  • ScrawnDotDev/Scrawn#41: Adjusts protobuf mappings in buildEventRow for basicUsageType and cache fields, refining the query response layer touched by this PR.
  • ScrawnDotDev/Scrawn#40: Earlier PR that introduced related BASIC_USAGE terminology changes in the same gRPC query response and schema areas.

Poem

🐰 In burrows deep where handlers dwell,
SDK calls bid their farewell,
Now BASIC_USAGE takes the stage,
With cache tokens on every page,
From schema to storage, the names align,
A systematic refactor, oh so fine!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: a systematic refactoring that renames SDK-related terminology to 'basic' across the codebase (handlers, schemas, fields, and function names).
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/cleanup

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint skipped: no ESLint configuration detected in root package.json. To enable, add eslint to devDependencies.


Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/zod/event.ts`:
- Line 41: The transform for BasicUsageDataSchema (the transform that returns {
basicUsageType: v.basicusagetype, debitAmount, metadata: ... }) and the
analogous transform in AITokenUsageDataSchema must not call JSON.parse directly;
instead, wrap the JSON.parse call in a try/catch inside the Zod transform
callback, and on parse failure call ctx.addIssue(...) to report a validation
error and return z.NEVER so the failure flows through Zod; update both
transforms to use the ctx parameter, catch SyntaxError from JSON.parse, add an
appropriate issue via ctx.addIssue, and return z.NEVER when metadata is
malformed, otherwise return the parsed metadata as before.
🪄 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 890a4a46-efd4-4c4f-9c7d-7b390107953d

📥 Commits

Reviewing files that changed from the base of the PR and between 3e8c5bf and 225a62a.

⛔ Files ignored due to path filters (4)
  • src/gen/event/v1/event_pb.d.ts is excluded by !**/gen/**
  • src/gen/event/v1/event_pb.js is excluded by !**/gen/**
  • src/gen/query/v1/query_pb.d.ts is excluded by !**/gen/**
  • src/gen/query/v1/query_pb.js is excluded by !**/gen/**
📒 Files selected for processing (11)
  • src/routes/gRPC/query/queryEvents.ts
  • src/storage/adapter/clickhouse/ClickHouseAdapter.ts
  • src/storage/adapter/clickhouse/handlers/addBasicUsage.ts
  • src/storage/adapter/clickhouse/handlers/index.ts
  • src/storage/adapter/clickhouse/handlers/priceRequestBasicUsage.ts
  • src/storage/adapter/postgres/handlers/addBasicUsage.ts
  • src/storage/adapter/postgres/handlers/index.ts
  • src/storage/adapter/postgres/handlers/priceRequestBasicUsage.ts
  • src/storage/adapter/postgres/postgres.ts
  • src/utils/eventHelpers.ts
  • src/zod/event.ts

Comment thread src/zod/event.ts
debitAmount = v.amount;
}
return { basicUsageType: v.sdkcalltype, debitAmount, metadata: v.metadata ? JSON.parse(v.metadata) as Record<string, unknown> : undefined };
return { basicUsageType: v.basicusagetype, debitAmount, metadata: v.metadata ? JSON.parse(v.metadata) as Record<string, unknown> : undefined };

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

# First, let's read the file to understand the context around line 41
head -50 src/zod/event.ts | cat -n

Repository: ScrawnDotDev/Scrawn

Length of output: 2100


🏁 Script executed:

# Get more context around line 41
sed -n '35,50p' src/zod/event.ts | cat -n

Repository: ScrawnDotDev/Scrawn

Length of output: 833


🏁 Script executed:

# Check the full transform function to understand the scope
sed -n '20,60p' src/zod/event.ts | cat -n

Repository: ScrawnDotDev/Scrawn

Length of output: 1803


🏁 Script executed:

# Search for ctx.addIssue usage in transforms
rg "ctx\.addIssue" --type ts --type tsx

Repository: ScrawnDotDev/Scrawn

Length of output: 91


🏁 Script executed:

# Search for z.NEVER usage
rg "z\.NEVER" --type ts --type tsx

Repository: ScrawnDotDev/Scrawn

Length of output: 91


🏁 Script executed:

# Search for other .transform patterns with ctx parameter
rg "\.transform\s*\(\s*\(.*,\s*ctx\)" --type ts --type tsx -A 3

Repository: ScrawnDotDev/Scrawn

Length of output: 91


🏁 Script executed:

# Check if there are other JSON.parse calls in Zod schemas
rg "JSON\.parse" --type ts --type tsx -B 3 -A 1

Repository: ScrawnDotDev/Scrawn

Length of output: 91


🏁 Script executed:

# Check the Zod version in package.json
cat package.json | grep -A 2 -B 2 '"zod"'

Repository: ScrawnDotDev/Scrawn

Length of output: 138


🏁 Script executed:

# Search for ctx.addIssue usage in transforms (TS files only)
rg "ctx\.addIssue" --type ts -B 2 -A 2

Repository: ScrawnDotDev/Scrawn

Length of output: 45


🏁 Script executed:

# Search for z.NEVER usage
rg "z\.NEVER" --type ts

Repository: ScrawnDotDev/Scrawn

Length of output: 45


🏁 Script executed:

# Search for other .transform patterns with ctx parameter
rg "\.transform\s*\(" --type ts -A 1 | head -40

Repository: ScrawnDotDev/Scrawn

Length of output: 1739


🏁 Script executed:

# Check if there are other JSON.parse calls in Zod schemas
rg "JSON\.parse" --type ts -B 3 -A 1

Repository: ScrawnDotDev/Scrawn

Length of output: 616


🏁 Script executed:

# Check how errors are handled in async transforms
rg "\.transform\(async" --type ts -A 15 | head -60

Repository: ScrawnDotDev/Scrawn

Length of output: 1749


🏁 Script executed:

# Search for catch blocks in transforms or Zod usage
rg "catch" --type ts -B 3 -A 3 | grep -A 5 -B 5 "transform"

Repository: ScrawnDotDev/Scrawn

Length of output: 45


🏁 Script executed:

# Check Zod error handling patterns in the codebase
rg "ZodError|parseAsync|\.parse\(" --type ts -B 2 -A 2 | head -50

Repository: ScrawnDotDev/Scrawn

Length of output: 2723


🏁 Script executed:

# Look for other potential error sources in transforms
rg "fetchTagAmount|parseAndEvaluateExpr" --type ts -B 2 -A 5

Repository: ScrawnDotDev/Scrawn

Length of output: 5667


🏁 Script executed:

# Verify Zod transform signature with ctx parameter in documentation/examples
# Check if there are any .refine patterns that might show error handling
rg "\.refine" --type ts -A 3 | head -30

Repository: ScrawnDotDev/Scrawn

Length of output: 825


🏁 Script executed:

# Check the full AITokenUsageDataSchema transform to see if it also has JSON.parse
sed -n '44,100p' src/zod/event.ts | cat -n

Repository: ScrawnDotDev/Scrawn

Length of output: 2320


🏁 Script executed:

# Look for how errors are currently being caught from the Zod schemas
rg "parseAsync\|\.parse\(" --type ts -B 2 -A 5 | head -50

Repository: ScrawnDotDev/Scrawn

Length of output: 45


🏁 Script executed:

# Get the rest of the AITokenUsageDataSchema transform
sed -n '44,90p' src/zod/event.ts | cat -n

Repository: ScrawnDotDev/Scrawn

Length of output: 1947


🏁 Script executed:

# Check how the schemas are actually used - look for parseAsync calls
rg "EventSchema\|BasicUsageDataSchema\|AITokenUsageDataSchema" --type ts -B 2 -A 5 | head -80

Repository: ScrawnDotDev/Scrawn

Length of output: 45


🏁 Script executed:

# Search for actual error handling around schema validation
rg "try\|catch" --type ts src/routes -A 3 -B 1 | head -60

Repository: ScrawnDotDev/Scrawn

Length of output: 45


🏁 Script executed:

# Check what happens when schemas are parsed - look at the event handler or route
rg "EventSchema" --type ts -A 10 | head -50

Repository: ScrawnDotDev/Scrawn

Length of output: 3325


🏁 Script executed:

# Check if there's a pattern for using parseAsync instead of parse
rg "parseAsync" --type ts -B 3 -A 3

Repository: ScrawnDotDev/Scrawn

Length of output: 995


🏁 Script executed:

# Find where these schemas are parsed/validated
fd -t f "\.ts$" | xargs grep -l "BasicUsageDataSchema\|AITokenUsageDataSchema" | head -10

Repository: ScrawnDotDev/Scrawn

Length of output: 80


🏁 Script executed:

# Check a handler to see error flow
head -80 src/routes/http/addEvent.ts 2>/dev/null || head -80 src/routes/*/addEvent.ts 2>/dev/null || find src -name "*addEvent*" -type f | head -1 | xargs head -80

Repository: ScrawnDotDev/Scrawn

Length of output: 1536


🏁 Script executed:

# Check the full registerEvent handler to see if there's error handling
cat -n src/routes/gRPC/events/registerEvent.ts | head -50

Repository: ScrawnDotDev/Scrawn

Length of output: 2188


🏁 Script executed:

# Check if there's error handling wrapper around parseAsync calls
sed -n '1,70p' src/routes/gRPC/events/registerEvent.ts | cat -n

Repository: ScrawnDotDev/Scrawn

Length of output: 2188


Add error handling to JSON.parse in both schema transforms to comply with validation guidelines.

The JSON.parse() calls in BasicUsageDataSchema (line 41) and AITokenUsageDataSchema will throw SyntaxError for invalid JSON, bypassing Zod's validation error path. Per the coding guidelines, Zod schemas must catch and convert all validation failures properly. Wrap the JSON.parse() calls in ctx.addIssue() with z.NEVER return to ensure malformed metadata is reported as a schema validation issue.

Proposed fix for BasicUsageDataSchema
-  .transform(async (v): Promise<BasicUsageEventData> => {
+  .transform(async (v, ctx): Promise<BasicUsageEventData> => {
     let debitAmount: number;
     if (v.tag) {
       debitAmount = await fetchTagAmount(v.tag, `Tag not found: ${v.tag}`);
     } else if (v.expr) {
       debitAmount = await parseAndEvaluateExpr(v.expr);
     } else {
       debitAmount = v.amount;
     }
-    return { basicUsageType: v.basicusagetype, debitAmount, metadata: v.metadata ? JSON.parse(v.metadata) as Record<string, unknown> : undefined };
+    let metadata: Record<string, unknown> | undefined;
+    if (v.metadata) {
+      try {
+        metadata = JSON.parse(v.metadata) as Record<string, unknown>;
+      } catch {
+        ctx.addIssue({
+          code: z.ZodIssueCode.custom,
+          path: ["metadata"],
+          message: "metadata must be valid JSON",
+        });
+        return z.NEVER;
+      }
+    }
+    return { basicUsageType: v.basicusagetype, debitAmount, metadata };
   });

Apply the same fix to AITokenUsageDataSchema's transform.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/zod/event.ts` at line 41, The transform for BasicUsageDataSchema (the
transform that returns { basicUsageType: v.basicusagetype, debitAmount,
metadata: ... }) and the analogous transform in AITokenUsageDataSchema must not
call JSON.parse directly; instead, wrap the JSON.parse call in a try/catch
inside the Zod transform callback, and on parse failure call ctx.addIssue(...)
to report a validation error and return z.NEVER so the failure flows through
Zod; update both transforms to use the ctx parameter, catch SyntaxError from
JSON.parse, add an appropriate issue via ctx.addIssue, and return z.NEVER when
metadata is malformed, otherwise return the parsed metadata as before.

@SteakFisher
SteakFisher merged commit bbe7cc7 into main May 17, 2026
3 checks passed
@SteakFisher
SteakFisher deleted the refactor/cleanup branch May 22, 2026 13:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant