-
Notifications
You must be signed in to change notification settings - Fork 523
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
chore: add catch block after every db transaction #2287
Conversation
|
📝 Walkthrough📝 WalkthroughWalkthroughThe pull request modifies several TRPC router functions to enhance transaction handling and error management. Key changes include restructuring transaction blocks for clarity, improving error messages, and ensuring that audit log insertions include necessary context such as Changes
Assessment against linked issues
Possibly related PRs
Suggested reviewers
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
Thank you for following the naming conventions for pull request titles! 🙏 |
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
@harshsbhat is attempting to deploy a commit to the Unkey Team on Vercel. A member of the Team first needs to authorize it. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 5
🧹 Outside diff range and nitpick comments (30)
apps/dashboard/lib/trpc/routers/rbac/upsertPermission.ts (1)
63-68
: Consistent error handling implementation. Approved!The new catch block for
insertAuditLogs
aligns well with the existing error handling pattern in the function. It successfully addresses the PR objective of adding catch blocks after database transactions, enhancing the overall robustness of the code.Consider improving error message specificity
While the error message is consistent with others in the function, it might be helpful to specify that the error occurred during audit log insertion. This could assist in troubleshooting.
Consider updating the error message to:
- "We are unable to upsert the permission. Please contact support using support@unkey.dev" + "We are unable to log the permission upsert action. The permission may have been created successfully. Please contact support using support@unkey.dev"Consider implementing a custom error type for audit log failures
Given the critical nature of audit logs, it might be beneficial to implement a custom error type for audit log failures. This could allow for more specific error handling and potentially different recovery strategies.
Consider creating a custom error type like
AuditLogError
and using it here. This could provide more flexibility in error handling and reporting in the future.apps/dashboard/lib/trpc/routers/key/updateEnabled.ts (1)
38-78
: Improved transaction handling, but consider refining error managementThe restructured transaction block enhances atomicity by including both the key update and audit log insertion in a single transaction. This is a positive change that ensures data consistency.
However, there are a few points to consider:
The inner catch block (lines 46-51) might be redundant given the outer catch block (lines 73-78). Consider removing the inner catch block to simplify the code structure.
The error messages for different failure scenarios (key update vs. audit log insertion) are now identical. This might make debugging more challenging. Consider adding more specific error messages or including error details to differentiate between failure points.
The addition of context information (location and userAgent) to the audit log is a good improvement for traceability.
Consider applying the following changes to refine the error handling:
await db .transaction(async (tx) => { await tx .update(schema.keys) .set({ enabled: input.enabled, }) - .where(eq(schema.keys.id, key.id)) - .catch((_err) => { - throw new TRPCError({ - code: "INTERNAL_SERVER_ERROR", - message: - "We were unable to update enabled on this key. Please contact support using support@unkey.dev", - }); - }); + .where(eq(schema.keys.id, key.id)); await insertAuditLogs(tx, { // ... (keep the existing audit log insertion code) }); }) .catch((err) => { throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", - message: - "We were unable to update enabled on this key. Please contact support using support@unkey.dev", + message: `Failed to update key or insert audit log: ${err.message}. Please contact support using support@unkey.dev`, }); });This change removes the redundant inner catch block and provides more specific error information in the outer catch block.
apps/dashboard/lib/trpc/routers/key/updateName.ts (1)
41-52
: Consider simplifying error handling for key updateThe current implementation includes error handling for both the key update operation and the entire transaction. While this approach ensures robust error management, it might lead to redundant error handling.
Consider simplifying the error handling by removing the inner try-catch block and relying on the outer transaction error handling. This would make the code more concise without compromising on error management.
If you decide to keep both error handlers, ensure that they provide distinct, valuable information to aid in troubleshooting.
apps/dashboard/lib/trpc/routers/api/updateName.ts (2)
39-79
: Approve changes with suggestions for improved error handlingThe restructured transaction block and error handling are good improvements. The code is more readable and robust. However, there are a few suggestions to enhance error handling:
- Consider using different error messages for different scenarios to aid in debugging.
- Log the actual error information before throwing the TRPCError to preserve details for debugging.
Here's a suggested improvement for error handling:
await db .transaction(async (tx) => { await tx .update(schema.apis) .set({ name: input.name, }) .where(eq(schema.apis.id, input.apiId)) .catch((err) => { + console.error("Error updating API name:", err); throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", - message: - "We were unable to update the API name. Please contact support using support@unkey.dev.", + message: "Error updating API name. Please contact support.", }); }); // ... (audit log insertion remains unchanged) }) .catch((err) => { + console.error("Transaction failed:", err); throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", - message: - "We were unable to update the API name. Please contact support using support@unkey.dev.", + message: "Transaction failed. Please contact support.", }); });This change will log the actual error information while still throwing a generic error message to the client, improving debuggability without exposing sensitive information.
54-72
: Changes align well with PR objectivesThe modifications successfully address the PR objectives by adding a catch block after the db transaction and including the audit log insertion within the transaction. This improves error handling and ensures data consistency.
One minor suggestion:
Consider adding a specific catch block for the audit log insertion to handle potential errors separately:
await db .transaction(async (tx) => { // ... (API update code remains unchanged) await insertAuditLogs(tx, { // ... (audit log details remain unchanged) - }); + }).catch((err) => { + console.error("Error inserting audit log:", err); + // Optionally, you can choose to throw an error or handle it silently + }); }) // ... (rest of the code remains unchanged)This change would allow for more granular error handling and logging specific to audit log insertion failures.
apps/dashboard/lib/trpc/routers/api/setDefaultPrefix.ts (2)
35-48
: Improved transaction structure and error handling.The restructuring of the transaction block enhances readability and maintainability. The addition of error handling within the transaction is a good practice for robust error management.
Consider adding more specific error information in the catch block. For example:
- .catch((_err) => { + .catch((err) => { throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: - "We were unable to update the API default prefix. Please contact support using support@unkey.dev.", + `Failed to update API default prefix: ${err.message}. Please contact support using support@unkey.dev.`, }); });This change would provide more detailed error information for debugging purposes while maintaining user-friendly messaging.
70-75
: Additional error handling for transaction execution.The addition of a catch block after the transaction is a good practice to ensure that any errors during transaction execution are properly handled and reported.
Consider enhancing the error handling to provide more specific information about what part of the transaction failed. Here's a suggestion:
- .catch((_err) => { + .catch((err) => { + console.error("Transaction failed:", err); throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: - "We were unable to update the default prefix. Please contact support using support@unkey.dev.", + `Failed to update default prefix: ${err.message}. Please contact support using support@unkey.dev.`, }); });This change would log the error for debugging purposes and provide a more informative error message to the client, while still maintaining a user-friendly message.
apps/dashboard/lib/trpc/routers/workspace/changeName.ts (1)
46-61
: Enhanced audit log insertion with contextThe
insertAuditLogs
function call now includes acontext
property withlocation
anduserAgent
. This change addresses the concerns raised in issue #2274 by ensuring that crucial information is logged for debugging and auditing purposes.Consider destructuring
ctx.audit
for cleaner code:context: { - location: ctx.audit.location, - userAgent: ctx.audit.userAgent, + location, + userAgent, } = ctx.audit,apps/dashboard/lib/trpc/routers/api/setDefaultBytes.ts (2)
39-52
: Improved transaction structure and error handling.The restructuring of the transaction block enhances code readability and maintainability. The addition of specific error handling within the transaction aligns well with the PR objective of improving error management.
Consider a minor improvement in the error message:
- "We were unable to update the API default bytes. Please contact support using support@unkey.dev.", + "Unable to update the API default bytes. Please contact support at support@unkey.dev.",This change makes the message slightly more concise while maintaining clarity.
54-72
: Enhanced audit logging with improved context.The addition of
location
anduserAgent
to the audit log context significantly improves traceability. This change aligns well with the PR objective of enhancing audit log insertions.For consistency, consider using template literals for the description:
- description: `Changed ${keyAuth.workspaceId} default byte size for keys from ${keyAuth.defaultBytes} to ${input.defaultBytes}`, + description: `Changed default byte size for keys from ${keyAuth.defaultBytes} to ${input.defaultBytes} for workspace ${keyAuth.workspaceId}`,This change makes the description more readable and consistent with typical log message formats.
apps/dashboard/lib/trpc/routers/ratelimit/deleteOverride.ts (3)
84-89
: Approved: Error handling added for audit log insertionThe addition of error handling for the
insertAuditLogs
function call is a good improvement. It aligns with the PR objectives and addresses the issue mentioned in #2274.Consider updating the error message to be more specific about the audit log insertion failure:
- "We are unable to delete the override. Please contact support using support@unkey.dev", + "We are unable to log the deletion of the override. The override may have been deleted, but the action was not logged. Please contact support using support@unkey.dev",This change would help distinguish between database update errors and audit log insertion errors, potentially aiding in troubleshooting.
Line range hint
1-89
: Well-structured function with comprehensive error handlingThe
deleteOverride
mutation is well-structured and includes comprehensive error handling for various scenarios. The early checks for override existence and tenant ownership are particularly commendable.To further improve error handling and debugging:
Consider adding unique error codes or more specific error messages for each catch block. This would help in identifying the exact point of failure when an error occurs.
You might want to log the specific error details (while being careful not to expose sensitive information) before throwing the TRPCError. This could aid in debugging without exposing internal details to the client.
Example:
.catch((err) => { console.error("Failed to update ratelimitOverrides:", err); throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "Failed to update the override. Please contact support.", }); });These changes would enhance the ability to troubleshoot issues while maintaining a consistent user-facing error message.
Line range hint
70-89
: Changes align with PR objectives and address linked issueThe addition of the catch block for
insertAuditLogs
directly addresses the concerns raised in issue #2274 and aligns with the PR objectives of improving error handling for database transactions.To further improve the audit log context, consider adding more details to the
description
field of theinsertAuditLogs
call. For example:- description: `Deleted ${override.id}`, + description: `Deleted rate limit override ${override.id} for namespace ${override.namespace.id}`,This change would provide more context in the audit logs, making it easier to track and understand the actions performed.
apps/dashboard/lib/trpc/routers/key/updateRootKeyName.ts (4)
51-64
: Improved transaction structure and error handling.The restructuring of the transaction block enhances readability and maintainability. Moving the catch block to encompass the entire transaction ensures consistent error handling for all operations within the transaction.
Consider improving the error message to provide more specific information about what went wrong. This could help with debugging and support. For example:
.catch((_err) => { throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", - message: - "We are unable to update root key name. Please contact support using support@unkey.dev", + message: `Failed to update root key name: ${_err.message}. Please contact support at support@unkey.dev`, }); });
66-84
: Enhanced audit log with additional context.The addition of
location
anduserAgent
to the audit log context improves traceability and security monitoring. This change aligns well with the PR objectives of enhancing audit log insertions.Consider adding a comment explaining the significance of these new context fields for future maintainers:
context: { location: ctx.audit.location, userAgent: ctx.audit.userAgent, + // These fields enhance security monitoring and aid in tracking user actions across different locations and devices },
86-91
: Additional error handling for the transaction.The addition of this catch block ensures that any errors not caught within the transaction are still handled, which is a good practice for robust error management.
Consider the following improvements:
- Enhance the error message to provide more specific information:
.catch((_err) => { throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", - message: - "We are unable to update root key name. Please contact support using support@unkey.dev", + message: `Transaction failed: ${_err.message}. Please contact support at support@unkey.dev`, }); });
- For consistency, consider using a single error handling function for both catch blocks:
const handleUpdateError = (err: unknown) => { throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: `Failed to update root key name: ${err instanceof Error ? err.message : 'Unknown error'}. Please contact support at support@unkey.dev`, }); }; // Then use it in both catch blocks: // .catch(handleUpdateError)This approach would improve consistency and make it easier to update error handling in the future.
51-91
: Overall improvements in transaction handling and error managementThe changes in this file align well with the PR objectives of adding catch blocks after database transactions and enhancing error handling. The restructuring of the transaction block, addition of context to audit logs, and improved error catching contribute to better code quality and robustness.
Key improvements:
- Restructured transaction block for better readability and maintainability.
- Enhanced audit logs with additional context (location and userAgent).
- Added catch blocks to ensure comprehensive error handling.
While these changes are positive, there are opportunities for further refinement:
- Improving specificity in error messages to aid debugging and support.
- Ensuring consistency in error handling across different catch blocks.
- Adding comments to explain the significance of new additions, like the context fields in audit logs.
These suggestions, if implemented, would further enhance the code quality and maintainability.
Consider creating a centralized error handling utility for TRPC procedures. This could include standardized error messages, logging, and potentially integration with an error tracking service. Such a utility would ensure consistency across the application and make it easier to manage and update error handling practices in the future.
apps/dashboard/lib/trpc/routers/api/create.ts (1)
53-99
: Excellent improvements to transaction handling and error management!The restructured transaction block enhances readability and separates concerns effectively. The addition of specific error handling for API insertion and the catch block after the transaction aligns well with the PR objectives. Including location and userAgent in the audit log context is a valuable improvement.
Consider further improving error handling granularity:
await db .transaction(async (tx) => { await tx .insert(schema.apis) .values({ id: apiId, name: input.name, workspaceId: ws.id, keyAuthId, authType: "key", ipWhitelist: null, createdAt: new Date(), }) - .catch((_err) => { + .catch((err) => { + console.error("Failed to insert API:", err); throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "We are unable to create the API. Please contact support using support@unkey.dev", }); }); await insertAuditLogs(tx, { // ... (audit log details) - }); + }).catch((err) => { + console.error("Failed to insert audit log:", err); + throw new TRPCError({ + code: "INTERNAL_SERVER_ERROR", + message: "Failed to log the API creation. Please contact support using support@unkey.dev", + }); + }); }) - .catch((_err) => { + .catch((err) => { + console.error("Transaction failed:", err); throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "We are unable to create the API. Please contact support using support@unkey.dev", }); });This change would:
- Log specific errors for easier debugging.
- Differentiate between API insertion and audit log insertion failures.
- Provide more informative error messages to the user.
apps/dashboard/lib/trpc/routers/api/updateIpWhitelist.ts (1)
56-96
: Improved transaction handling and error management, with suggestions for further enhancement.The changes have significantly improved the structure and error handling of the transaction block. Here are the key improvements:
- The transaction block is now more readable and maintainable.
- Error handling for the update operation is more specific (lines 64-69).
- Audit log insertion is now part of the transaction, ensuring atomicity (lines 71-89).
- The additional catch block after the transaction (lines 91-96) addresses the PR objective of adding catch blocks after every db transaction.
To further enhance error handling and debugging:
Consider differentiating error messages between the inner catch block (lines 64-69) and the outer catch block (lines 91-96). This will help in identifying whether the error occurred during the update operation or in the overall transaction.
Implement more granular error handling by distinguishing between different types of errors (e.g., database errors vs. other runtime errors). This can be achieved by checking the error type and providing more specific error messages or error codes.
Example implementation:
.catch((err) => { console.error("Error updating API whitelist:", err); if (err instanceof DatabaseError) { throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "Database error occurred while updating the API whitelist. Please try again later.", }); } else { throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "An unexpected error occurred while updating the API whitelist. Please contact support.", }); } });This approach will provide more informative error messages and assist in troubleshooting issues more effectively.
apps/dashboard/lib/trpc/routers/key/updateExpiration.ts (1)
66-71
: Consider differentiating error messages for specific failure pointsWhile the current error handling is good, it might be helpful to differentiate between errors occurring during the key update and those during the audit log insertion. This would provide more specific information for troubleshooting.
Consider updating the error messages as follows:
.catch((_err) => { throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: - "We were unable to update expiration on this key. Please contact support using support@unkey.dev", + "Failed to update key expiration. Please contact support at support@unkey.dev", }); }); // ... (audit log insertion) .catch((_err) => { throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: - "We were unable to update expiration on this key. Please contact support using support@unkey.dev", + "Failed to update key expiration or insert audit log. Please contact support at support@unkey.dev", }); });This change would help distinguish between errors in the key update process and potential issues with the audit log insertion.
Also applies to: 97-102
apps/dashboard/lib/trpc/routers/rbac/connectRoleToKey.ts (3)
64-77
: Improved transaction handling and error management.The restructuring of the transaction block enhances readability and error handling, which aligns well with the PR objectives. Good job on implementing the catch block as requested in issue #2274.
Consider logging the error before throwing the TRPCError. This can help with debugging without exposing sensitive information to the client. For example:
.catch((_err) => { + console.error('Error connecting role and key:', _err); throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "We are unable to connect the role and key. Please contact support using support@unkey.dev.", }); });
79-98
: Enhanced audit logging with additional context.The addition of audit log insertion within the transaction block is a great improvement. Including the location and userAgent in the context provides valuable information for the audit trail.
For consistency with the error handling in the previous block, consider wrapping the
insertAuditLogs
call in a try-catch block:-await insertAuditLogs(tx, { +await insertAuditLogs(tx, { workspaceId: workspace.id, actor: { type: "user", id: ctx.user.id }, event: "authorization.connect_role_and_key", description: `Connect role ${role.id} to ${key.id}`, resources: [ { type: "role", id: role.id, }, { type: "key", id: key.id, }, ], context: { location: ctx.audit.location, userAgent: ctx.audit.userAgent, }, -}); +}).catch((err) => { + console.error('Error inserting audit log:', err); + throw new TRPCError({ + code: "INTERNAL_SERVER_ERROR", + message: "An error occurred while logging the action. Please try again.", + }); +});This ensures that any errors during audit log insertion are properly handled and don't silently fail.
100-105
: Comprehensive error handling for the transaction block.The addition of error handling for the entire transaction block is a good practice, ensuring that any unforeseen errors are caught and reported properly.
For consistency with the previous suggestions and to aid in debugging, consider logging the error:
-.catch((_err) => { +.catch((err) => { + console.error('Transaction failed:', err); throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "We are unable to connect the role to the key. Please contact support using support@unkey.dev", }); });This will help in identifying the root cause of any transaction failures during development or production troubleshooting.
apps/dashboard/lib/trpc/routers/rbac/connectPermissionToRole.ts (3)
64-105
: Improved error handling in the transaction block.The changes align well with the PR objectives by adding a catch block after the database transaction. The error handling is now more robust, with descriptive error messages that include support contact information.
Consider consolidating the error messages to reduce duplication. For example:
const errorMessage = "We are unable to connect this permission to role. Please contact support using support@unkey.dev"; // Use this message in both catch blocksThis would make future updates to the error message easier to maintain.
79-98
: Enhanced audit log with additional context.The audit log insertion has been improved by adding
location
anduserAgent
to the context. This enhancement aligns with best practices for comprehensive logging.For consistency with the rest of the codebase, consider extracting the audit log event name to a constant. For example:
const AUDIT_EVENT = "authorization.connect_role_and_permission"; // Then use it in the insertAuditLogs call event: AUDIT_EVENT,This would make it easier to maintain and reuse the event name if needed elsewhere in the codebase.
64-105
: Overall improvements in error handling and audit logging.The changes in this file successfully address the objectives of the PR by adding proper error handling after database transactions and enhancing audit logging. The code structure has been improved without altering the core logic.
Consider extracting the error handling logic into a separate utility function to promote code reuse and consistency across the codebase. For example:
function handleDatabaseError(operation: string): never { throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: `We are unable to ${operation}. Please contact support using support@unkey.dev`, }); } // Usage .catch(() => handleDatabaseError("connect this permission to role"));This approach would centralize error handling logic and make it easier to maintain consistent error messages throughout the application.
apps/dashboard/lib/trpc/routers/ratelimit/updateOverride.ts (1)
53-100
: Improved transaction handling and error management.The changes effectively address the PR objective of adding catch blocks after database transactions. The restructured code ensures that both the update operation and audit log insertion are part of the same transaction, which is a good practice for maintaining data consistency.
Some positive observations:
- Error handling has been added for both the update operation and audit log insertion.
- The audit log insertion now includes location and userAgent context, enhancing traceability.
- Error messages are consistent and provide clear instructions to contact support.
Consider consolidating the error handling to reduce code duplication. You could create a helper function for throwing TRPCErrors with consistent messaging. For example:
function throwInternalServerError(operation: string) { throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: `We are unable to ${operation}. Please contact support using support@unkey.dev`, }); } // Usage .catch(() => throwInternalServerError("update the override"));This approach would make it easier to maintain consistent error messages across the codebase.
apps/dashboard/lib/trpc/routers/rbac/addPermissionToRootKey.ts (1)
68-115
: Excellent improvements to transaction handling and error management!The changes effectively address the PR objective by adding a catch block after the database transaction. The restructuring of the transaction block improves readability and ensures atomicity of both permission insertion and audit log recording. The addition of the
context
property to the audit log entry enhances the logged information.A minor suggestion for improvement:
Consider consolidating error messages to reduce duplication. You could create a constant for the common error message:
const PERMISSION_ADD_ERROR = "We are unable to add permission to the rootkey. Please contact support using support@unkey.dev"; // Then use it in the catch blocks: throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: PERMISSION_ADD_ERROR, });This would make future updates to the error message easier and ensure consistency.
apps/dashboard/lib/trpc/routers/rbac/createRole.ts (1)
62-81
: Comprehensive audit log insertions with proper contextThe audit log insertions for both role creation and permission assignment are well-implemented, capturing necessary information and including the required context (userAgent and location). This aligns with the PR objectives and addresses the requirements mentioned in the linked issue (#2274).
However, to further improve error handling specifically for audit log insertions:
Consider wrapping each
insertAuditLogs
call in a try-catch block to handle potential errors during audit log insertion without affecting the main transaction. For example:try { await insertAuditLogs(tx, { // ... existing audit log data ... }); } catch (error) { // Log the error or handle it as appropriate without throwing console.error("Failed to insert audit log:", error); }This ensures that even if audit log insertion fails, it won't cause the entire transaction to fail.
Also applies to: 91-114
apps/dashboard/lib/trpc/routers/workspace/changePlan.ts (1)
163-196
: LGTM! Consider enhancing error handling.The restructured code improves readability and correctly implements the transaction to update the workspace and insert audit logs atomically. This aligns well with the PR objectives.
Consider enhancing the error handling to provide more specific information about what failed. This can aid in debugging. For example:
}) - .catch((_err) => { + .catch((err) => { + console.error("Failed to upgrade workspace to pro plan:", err); throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: - "We are unable to change plans. Please contact support using support@unkey.dev", + `Failed to upgrade to pro plan: ${err.message}. Please contact support using support@unkey.dev`, }); });
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (23)
- apps/dashboard/lib/trpc/routers/api/create.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/api/setDefaultBytes.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/api/setDefaultPrefix.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/api/updateDeleteProtection.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/api/updateIpWhitelist.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/api/updateName.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/key/updateEnabled.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/key/updateExpiration.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/key/updateMetadata.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/key/updateName.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/key/updateOwnerId.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/key/updateRootKeyName.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/llmGateway/delete.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/ratelimit/deleteOverride.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/ratelimit/updateOverride.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/rbac/addPermissionToRootKey.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/rbac/connectPermissionToRole.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/rbac/connectRoleToKey.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/rbac/createPermission.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/rbac/createRole.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/rbac/upsertPermission.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/workspace/changeName.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/workspace/changePlan.ts (1 hunks)
🧰 Additional context used
📓 Learnings (1)
apps/dashboard/lib/trpc/routers/api/setDefaultPrefix.ts (1)
Learnt from: chronark PR: unkeyed/unkey#2146 File: apps/dashboard/lib/trpc/routers/api/setDefaultPrefix.ts:80-80 Timestamp: 2024-10-04T17:27:08.666Z Learning: Ensure that audit log descriptions accurately reflect the action being performed, such as updating the `defaultPrefix`, and avoid incorrect references like 'name' when not applicable.
🔇 Additional comments (24)
apps/dashboard/lib/trpc/routers/rbac/upsertPermission.ts (1)
Line range hint
1-73
: Summary: Changes successfully address PR objectives with room for minor enhancementsThe implementation successfully adds error handling for the
insertAuditLogs
function, aligning with the PR objectives. The new catch block is consistent with existing error handling patterns in the function, which is commendable.Next steps to consider:
- Implement the suggested improvement in the error message specificity for audit log failures.
- Evaluate the possibility of introducing a custom error type for audit log failures to allow for more granular error handling in the future.
- Ensure that similar error handling is implemented consistently across other relevant functions in the codebase, as per the original issue Insert Audit logs should have a catch block #2274.
Overall, this change enhances the robustness of the
upsertPermission
function and improves error management for audit log insertions.apps/dashboard/lib/trpc/routers/key/updateName.ts (3)
39-43
: Improved transaction structure and error handlingThe restructuring of the transaction block is a significant improvement:
- It ensures that both the key update and audit log insertion are part of the same transaction, enhancing data consistency.
- The code is more readable with a clear separation of transaction logic.
- The error handling for the entire transaction has been appropriately moved outside the transaction block.
These changes align well with best practices for database transactions and error management.
Also applies to: 73-79
54-72
: Improved audit logging with additional contextThe changes to the audit log insertion are commendable:
- Including the audit log insertion within the transaction ensures data integrity, as it will only be recorded if the key update is successful.
- The addition of
location
anduserAgent
to the audit log context provides valuable information for tracking and security purposes.- The audit log structure follows best practices by including the actor, event, description, and affected resources.
These improvements enhance the traceability and security of the key update operation.
39-79
: Summary: Successful implementation of PR objectivesThe changes in this file successfully address the PR objectives and the issues mentioned in #2274:
- A catch block has been added after the database transaction, improving error handling.
- The transaction structure has been improved, ensuring both key updates and audit log insertions are part of the same transaction.
- Audit logging has been enhanced with additional context (location and userAgent).
These changes contribute to better error management, improved data consistency, and enhanced traceability. The code is now more robust and maintainable.
One minor suggestion for consideration:
- Evaluate the need for the inner try-catch block within the transaction, as it might be redundant with the outer error handling.
Overall, this implementation effectively addresses the intended improvements in error handling and audit logging.
apps/dashboard/lib/trpc/routers/key/updateOwnerId.ts (1)
39-79
: Excellent improvements in transaction handling and error management!The changes in this block significantly enhance the code quality and align well with the PR objectives:
- The transaction block has been restructured for better readability and maintainability.
- A catch block has been added after the db transaction, addressing the main objective of the PR.
- The audit log insertion is now part of the transaction, ensuring atomicity of the operation.
- Error handling is consistent and informative for both the key update and the entire transaction.
- The audit log now includes context (location and userAgent), which is a good practice for comprehensive logging.
These changes improve error handling and maintain a robust audit trail, enhancing the overall reliability of the system.
apps/dashboard/lib/trpc/routers/api/setDefaultPrefix.ts (2)
50-68
: Enhanced audit logging with improved context.The audit logging has been significantly improved by including the
location
anduserAgent
in the context. This enhancement aligns with best practices for comprehensive audit trails.Great job on implementing the feedback from the previous PR (#2146). The audit log description now accurately reflects the action being performed, specifically mentioning the update to the
defaultPrefix
.
35-75
: Overall improvements align with PR objectives.The changes made to this file successfully address the objectives outlined in the PR and the linked issue #2274. The addition of catch blocks, improved error handling, and enhanced audit logging contribute to a more robust and traceable implementation. These modifications will help prevent unhandled errors during audit log insertion and provide better context for troubleshooting.
Great work on implementing these improvements! The code is now more resilient and maintainable.
apps/dashboard/lib/trpc/routers/workspace/changeName.ts (2)
31-68
: Improved code structure and readabilityThe transaction block has been restructured with better indentation and formatting. This change enhances code readability without altering the core functionality, which aligns well with the PR's objective of refactoring and improving code quality.
Line range hint
1-75
: Overall assessment: Improvements align with PR objectivesThe changes in this file successfully address the issues raised in the linked issue #2274 by improving error handling and enhancing code quality. The restructuring of the transaction block, the addition of context to audit logs, and the improved error handling all contribute to a more robust and maintainable codebase.
Consider implementing the suggested refactors to further improve the code:
- Destructure
ctx.audit
for cleaner audit log insertion.- Refactor error handling to avoid duplication.
These changes will make the code even more maintainable and consistent with best practices.
apps/dashboard/lib/trpc/routers/rbac/createPermission.ts (3)
Line range hint
1-86
: Approve overall error handling approachThe error handling throughout the
createPermission
function is well-structured and comprehensive. It covers the main potential failure points:
- Querying for the workspace
- When the workspace is not found
- During the database transaction
The error messages are consistent in style, provide clear instructions to contact support, and use appropriate error codes (INTERNAL_SERVER_ERROR and NOT_FOUND) for the scenarios.
This approach to error handling enhances the robustness of the function and improves the user experience by providing clear error messages.
Line range hint
46-59
: Approve audit logging implementationThe audit logging implementation within the
createPermission
function is well-structured and comprehensive. It addresses the requirements mentioned in the PR objectives by including:
- Relevant information such as event type, actor, description, and resources.
- Context information (userAgent and location) as specified in the linked issue.
- Insertion within the database transaction, ensuring atomicity.
This implementation enhances the traceability of permission creation events and aligns with the goal of improving error handling for audit log insertions.
Line range hint
1-86
: Summary of review findings
- The implementation successfully addresses the main objectives of the PR by improving error handling and including necessary context in audit logs.
- The overall error handling approach is well-structured and comprehensive.
- The audit logging implementation is thorough and aligns with the requirements.
- There's a minor issue with a redundant error handling block at the end of the function that should be removed.
Overall, the changes in this file effectively contribute to the goal of adding catch blocks after database transactions and improving error handling for audit log insertions.
apps/dashboard/lib/trpc/routers/api/updateDeleteProtection.ts (4)
39-52
: Improved transaction block structureThe restructuring of the transaction block enhances code readability and clearly defines the transaction scope. This change aligns well with the PR objective of improving error handling around database transactions.
54-77
: Enhanced audit log with additional contextThe addition of
location
anduserAgent
to the audit log context significantly improves the detail of the logged information. Including the audit log insertion within the transaction block ensures atomicity of the entire operation. These changes align well with the PR objective of enhancing audit log insertions.
79-84
: Improved error handling with consistent messagingThe addition of a catch block after the transaction enhances error handling, aligning with the PR objective. The error message is clear and consistent with other error messages in the file, providing good guidance for users in case of failures.
39-84
: Summary: Successful implementation of PR objectivesThe changes in this file successfully address the PR objectives and the linked issue (#2274). Key improvements include:
- Restructured transaction block for better clarity and error handling.
- Enhanced audit logging with additional context (location and userAgent).
- Improved error handling with consistent error messages.
These changes contribute to a more robust and maintainable codebase, particularly in the areas of transaction management and error handling for audit log insertions.
apps/dashboard/lib/trpc/routers/api/setDefaultBytes.ts (1)
Line range hint
1-79
: Overall assessment: Significant improvements in error handling and audit logging.The changes in this file successfully address the PR objectives by enhancing error handling and improving audit log insertions. The restructured transaction block, addition of specific error messages, and inclusion of more context in audit logs contribute to better code quality and traceability.
A few minor suggestions have been made for further refinement, but these are not critical issues. The implementation effectively solves the problem described in the linked issue #2274.
apps/dashboard/lib/trpc/routers/key/updateMetadata.ts (1)
51-91
: Improved transaction structure and error handlingThe restructured transaction block enhances readability and maintainability. The comprehensive error handling at multiple levels and the inclusion of audit log insertion within the transaction are commendable improvements.
Consider differentiating error messages
While the error handling is thorough, the error messages are identical for different scenarios. Consider customizing the messages to provide more specific information about where the error occurred. This would aid in debugging and troubleshooting.
For example:
// In the update operation catch block throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "Error updating key metadata. Please contact support at support@unkey.dev", }); // In the audit log insertion catch block (if added) throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "Error inserting audit log. Please contact support at support@unkey.dev", }); // In the outer transaction catch block throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "Transaction failed. Please contact support at support@unkey.dev", });Verify necessity of outer catch block
The catch block for the entire transaction (lines 86-91) might be redundant as individual operations already have error handling. Could you clarify if this outer catch block serves a specific purpose that isn't covered by the inner error handling?
To verify the necessity of this outer catch block, we can check if there are any operations within the transaction that don't have their own error handling:
If this script returns any results, it might justify the need for the outer catch block. Otherwise, consider removing it to avoid redundancy.
apps/dashboard/lib/trpc/routers/key/updateExpiration.ts (1)
58-102
: Great job on improving the transaction handling and error management!The changes effectively address the PR objectives by adding proper error handling and structuring the transaction block. The code is now more robust and maintainable. Here are the key improvements:
- Well-structured transaction block separating key update and audit log insertion.
- Comprehensive error handling for both specific operations and the entire transaction.
- Detailed audit log insertion with proper context information.
- Clear and consistent error messages.
apps/dashboard/lib/trpc/routers/rbac/connectRoleToKey.ts (1)
Line range hint
1-105
: Overall assessment: PR objectives met with improved error handling and audit logging.This PR successfully addresses the objectives outlined in issue #2274 by adding catch blocks after database transactions and improving error handling. The changes enhance the robustness of the
connectRoleToKey
mutation by:
- Restructuring the transaction block for better readability.
- Adding comprehensive error handling at multiple levels.
- Incorporating audit logging with additional context (location and userAgent).
These improvements align well with the goal of enhancing error management, particularly for audit log insertions. The code changes contribute to better maintainability and provide a more robust user experience by handling potential errors gracefully.
To ensure that similar improvements have been made consistently across the codebase, please run the following script:
This script will help ensure that the improvements made in this file have been consistently applied across other TRPC routes in the codebase.
✅ Verification successful
Please run the following updated script to verify consistent error handling and audit logging in TRPC routes:
Verification Successful: Consistent error handling and audit logging confirmed across TRPC routes.
The verification scripts identified that all TRPC routes consistently use catch blocks for error handling and include audit log insertions with context. The PR’s enhancements align with these existing practices, ensuring improved robustness without introducing inconsistencies.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify consistent error handling and audit logging in TRPC routes # Test 1: Check for consistent use of catch blocks in database transactions echo "Checking for consistent use of catch blocks in database transactions:" rg --type typescript -g 'apps/dashboard/lib/trpc/routers/**/*.ts' -A 5 'db\.transaction' | rg '\.catch' # Test 2: Verify audit log insertions with context echo "Verifying audit log insertions with context:" rg --type typescript -g 'apps/dashboard/lib/trpc/routers/**/*.ts' -A 10 'insertAuditLogs' | rg 'context:' # Test 3: Check for consistent error messages echo "Checking for consistent error messages:" rg --type typescript -g 'apps/dashboard/lib/trpc/routers/**/*.ts' 'throw new TRPCError'Length of output: 741
Script:
#!/bin/bash # Description: Verify consistent error handling and audit logging in TRPC routes # Test 1: Check for consistent use of catch blocks in database transactions echo "Checking for consistent use of catch blocks in database transactions:" rg --type ts -g 'apps/dashboard/lib/trpc/routers/**/*.ts' -A 5 'db\.transaction' | rg '\.catch' # Test 2: Verify audit log insertions with context echo "Verifying audit log insertions with context:" rg --type ts -g 'apps/dashboard/lib/trpc/routers/**/*.ts' -A 10 'insertAuditLogs' | rg 'context:' # Test 3: Check for consistent error messages echo "Checking for consistent error messages:" rg --type ts -g 'apps/dashboard/lib/trpc/routers/**/*.ts' 'throw new TRPCError'Length of output: 21299
apps/dashboard/lib/trpc/routers/rbac/createRole.ts (3)
45-122
: Improved transaction structure and error handlingThe restructured transaction block enhances clarity and ensures atomicity of operations. The comprehensive error handling at different levels (inside and outside the transaction) aligns well with the PR objective of adding catch blocks after database transactions. This approach provides robust error management for role creation, audit log insertion, and permission assignment.
83-115
: Well-implemented conditional permission assignmentThe permission assignment logic is well-structured and efficient:
- It only executes when permissions are provided (
input.permissionIds && input.permissionIds.length > 0
).- The role-permission relationships are correctly inserted into the database.
- Comprehensive audit logs are generated for each permission assignment.
This implementation ensures accurate role-permission management and traceability.
Line range hint
1-122
: Overall assessment: Well-implemented changes meeting PR objectivesThe modifications to the
createRole
function effectively address the PR objectives and the issues mentioned in the linked issue (#2274):
- Improved transaction handling and error management.
- Comprehensive audit log insertions with proper context.
- Well-structured permission assignment logic.
The changes enhance the robustness and traceability of the role creation process. The only suggested improvement is to add specific error handling for audit log insertions, which is a minor optimization.
apps/dashboard/lib/trpc/routers/workspace/changePlan.ts (1)
185-188
: Correct implementation of audit log context.The audit log insertion now includes the correct context with
location
anduserAgent
. This is a good practice for maintaining detailed audit trails.
await db | ||
.transaction(async (tx) => { | ||
await tx | ||
.delete(schema.llmGateways) | ||
.where(eq(schema.llmGateways.id, input.gatewayId)) | ||
.catch((_err) => { | ||
throw new TRPCError({ | ||
code: "INTERNAL_SERVER_ERROR", | ||
message: | ||
"We are unable to delete the LLM gateway. Please contact support using support@unkey.dev", | ||
}); | ||
}); | ||
}); | ||
await insertAuditLogs(tx, { | ||
workspaceId: llmGateway.workspace.id, | ||
actor: { | ||
type: "user", | ||
id: ctx.user.id, | ||
}, | ||
event: "llmGateway.delete", | ||
description: `Deleted ${llmGateway.id}`, | ||
resources: [ | ||
{ | ||
type: "gateway", | ||
id: llmGateway.id, | ||
await insertAuditLogs(tx, { | ||
workspaceId: llmGateway.workspace.id, | ||
actor: { | ||
type: "user", | ||
id: ctx.user.id, | ||
}, | ||
], | ||
context: { | ||
location: ctx.audit.location, | ||
userAgent: ctx.audit.userAgent, | ||
}, | ||
event: "llmGateway.delete", | ||
description: `Deleted ${llmGateway.id}`, | ||
resources: [ | ||
{ | ||
type: "gateway", | ||
id: llmGateway.id, | ||
}, | ||
], | ||
context: { | ||
location: ctx.audit.location, | ||
userAgent: ctx.audit.userAgent, | ||
}, | ||
}); | ||
}) | ||
.catch((_err) => { | ||
throw new TRPCError({ | ||
code: "INTERNAL_SERVER_ERROR", | ||
message: | ||
"We are unable to delete LLM gateway. Please contact support using support@unkey.dev", | ||
}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Codebase verification
Audit Log Insertion Outside Transaction Blocks Detected.
The insertAuditLogs
function is being invoked outside of transaction blocks in multiple TypeScript files. This practice can lead to audit logs being created even if the primary operation fails, compromising the atomicity and consistency of database operations.
Issues Identified:
-
Lack of Atomicity: Without wrapping
insertAuditLogs
within a transaction, there is no guarantee that the audit logs correspond accurately to successful operations. -
Potential Data Inconsistencies: Operations might fail without corresponding audit logs, or vice versa, leading to discrepancies in tracking and accountability.
Recommendations:
-
Wrap
insertAuditLogs
in Transactions: Ensure that all calls toinsertAuditLogs
are encapsulated within transaction blocks to maintain atomicity. -
Review and Refactor Existing Code: Audit the codebase to identify and rectify instances where
insertAuditLogs
is called outside transactions. -
Enhance Error Handling: Implement robust error handling to manage failures in both primary operations and audit logging seamlessly.
🔗 Analysis chain
Improved transaction structure and error handling.
The restructured transaction block enhances readability and ensures atomicity for both the deletion operation and audit log insertion. The addition of error handling for the entire transaction is a good practice.
Consider the following improvements:
-
Enhance error messages to provide more specific information about what went wrong. This will aid in debugging and support.
-
Consolidate error handling to avoid duplication. The current implementation has error handling both inside and outside the transaction block, which may lead to confusion.
Example of more specific error messages:
catch ((err) => {
console.error("Failed to delete LLM gateway:", err);
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message: `Failed to delete LLM gateway: ${err.message}. Please contact support at support@unkey.dev`,
});
});
To ensure the audit log insertion is working correctly, let's verify its usage across the codebase:
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Verify the usage of insertAuditLogs function
# Test: Search for all occurrences of insertAuditLogs
echo "Occurrences of insertAuditLogs:"
rg --type typescript "insertAuditLogs" -A 5
# Test: Check if insertAuditLogs is always called within a transaction
echo "\nChecking if insertAuditLogs is always within a transaction:"
rg --type typescript "transaction.*insertAuditLogs"
Length of output: 373
Script:
#!/bin/bash
# Description: Verify the usage of insertAuditLogs function within TypeScript files
# Search for all occurrences of insertAuditLogs in .ts and .tsx files
echo "Occurrences of insertAuditLogs in TypeScript files:"
rg "insertAuditLogs" --glob "*.ts" --glob "*.tsx" -A 5
# Check if insertAuditLogs is always called within a transaction block
echo "\nChecking if insertAuditLogs is always within a transaction:"
rg "transaction\s*\(" --glob "*.ts" --glob "*.tsx" -A 10 | rg "insertAuditLogs"
Length of output: 70689
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@chronark, I just checked, and this is inside the transaction block. I'm not sure why the bot is giving me this error.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Outside diff range and nitpick comments (33)
apps/dashboard/lib/trpc/routers/rbac/disconnectRoleFromKey.ts (1)
Line range hint
35-61
: Consider adding specific error handling for audit log insertionWhile the current implementation includes error handling for the entire transaction, it doesn't specifically address potential errors from the audit log insertion. To align with the PR objectives (issue #2274), consider:
- Separating the audit log insertion from the main transaction.
- Adding a specific catch block for the audit log insertion.
This change would improve error handling granularity and align better with the stated PR objectives.
Here's a suggested restructure:
await db .transaction(async (tx) => { await tx .delete(schema.keysRoles) .where( and( eq(schema.keysRoles.workspaceId, workspace.id), eq(schema.keysRoles.roleId, input.roleId), eq(schema.keysRoles.keyId, input.keyId), ), ); }) .catch((err) => { console.error(err); throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "We are unable to disconnect the role from the key. Please contact support using support@unkey.dev", }); }); // Separate try-catch for audit log insertion try { await insertAuditLogs(db, { workspaceId: workspace.id, actor: { type: "user", id: ctx.user.id }, event: "authorization.disconnect_role_and_key", description: `Disconnect role ${input.roleId} from ${input.keyId}`, resources: [ { type: "role", id: input.roleId, }, { type: "key", id: input.keyId, }, ], context: { location: ctx.audit.location, userAgent: ctx.audit.userAgent, }, }); } catch (err) { console.error("Failed to insert audit log:", err); // Decide if you want to throw an error or just log it }This structure allows for more specific error handling for the audit log insertion, as per the PR objectives.
apps/dashboard/lib/trpc/routers/rbac/disconnectPermissionFromRole.ts (3)
31-31
: Approved: Improved error message for better user guidance.The updated error message provides clearer instructions to the user, suggesting a retry before contacting support. This change enhances the user experience.
Consider adding a specific error code or identifier to the message. This would help support staff quickly identify and address the issue if the user does need to contact them. For example:
- "We are unable to find the correct workspace. Please try again or contact support@unkey.dev.", + "We are unable to find the correct workspace. Please try again or contact support@unkey.dev with error code: WORKSPACE_NOT_FOUND.",
Line range hint
46-54
: Add catch block for audit log insertion.While the overall error handling in this file is good, there's an opportunity to improve it further. The
insertAuditLogs
function call inside the transaction doesn't have a specific catch block. This aligns with the issue mentioned in #2274 about adding catch blocks for audit log insertions.Consider adding a specific catch block for the audit log insertion:
await tx .delete(schema.rolesPermissions) .where( and( eq(schema.rolesPermissions.workspaceId, workspace.id), eq(schema.rolesPermissions.roleId, input.roleId), eq(schema.rolesPermissions.permissionId, input.permissionId), ), ); await insertAuditLogs(tx, { workspaceId: workspace.id, actor: { type: "user", id: ctx.user.id }, event: "authorization.disconnect_role_and_permissions", description: `Disconnect role ${input.roleId} from permission ${input.permissionId}`, resources: [ { type: "role", id: input.roleId, }, { type: "permission", id: input.permissionId, }, ], context: { location: ctx.audit.location, userAgent: ctx.audit.userAgent, }, + }).catch((err) => { + console.error('Failed to insert audit log:', err); + // Optionally, you can choose to throw an error or handle it silently + // throw new TRPCError({ + // code: "INTERNAL_SERVER_ERROR", + // message: "Failed to log the action. The operation may have succeeded.", + // }); });This change will ensure that any errors during audit log insertion are properly caught and logged, improving the overall robustness of the system.
Line range hint
1-65
: Overall, the file structure and logic are sound, with room for minor improvements.The changes made in this file align with the PR objectives of improving error handling. The modified error message provides better guidance to users. However, there's an opportunity to further enhance error handling, particularly for audit log insertion.
Key points:
- The error message change is an improvement (line 31).
- Overall error handling is good, but could be enhanced for audit log insertion (lines 46-54).
- The file structure follows TRPC conventions and is well-organized.
Consider implementing a consistent error handling strategy across all similar TRPC procedures, especially for audit log insertions. This would improve the overall robustness and maintainability of the system.
apps/dashboard/lib/trpc/routers/key/delete.ts (2)
39-39
: Consistent improvement in error messagingThe error message for the NOT_FOUND case has been updated to match the style of the previous error message, providing clearer guidance to the user. This change contributes to a more consistent and user-friendly error handling approach.
Consider standardizing the error message format across all error cases in this file. For example, the error message at the end of the file (line 80) could be updated to match this new format:
- "We are unable to delete the key. Please contact support using support@unkey.dev", + "We are unable to delete the key. Please try again or contact support@unkey.dev.",
Line range hint
1-85
: Overall improvements and suggestions for further enhancementsThe changes in this file contribute to better error handling by improving error messages, which partially addresses the PR objectives. However, I have a few suggestions for further improvements:
Consider adding more context to the audit log insertion. Currently, it's not clear what would happen if the audit log insertion fails. You might want to add a specific catch block for the
insertAuditLogs
call to handle potential errors there.The error message at the end of the file (line 80) should be updated to match the new format for consistency.
Consider adding more detailed error logging. For example, you could log the actual error message (not just
_err
) to help with debugging in the future.Here's an example of how you could implement these suggestions:
await db .transaction(async (tx) => { await tx .update(schema.keys) .set({ deletedAt: new Date() }) .where( and( eq(schema.keys.workspaceId, workspace.id), inArray( schema.keys.id, workspace.keys.map((k) => k.id), ), ), ); try { await insertAuditLogs( tx, workspace.keys.map((key) => ({ workspaceId: workspace.id, actor: { type: "user", id: ctx.user.id }, event: "key.delete", description: `Deleted ${key.id}`, resources: [ { type: "key", id: key.id, }, ], context: { location: ctx.audit.location, userAgent: ctx.audit.userAgent, }, })), ); } catch (auditError) { console.error("Failed to insert audit logs:", auditError); // Optionally, you could choose to throw an error here or handle it differently } }) .catch((err) => { console.error("Failed to delete key:", err); throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "We are unable to delete the key. Please try again or contact support@unkey.dev.", }); });These changes would provide more robust error handling and consistency throughout the file.
apps/dashboard/lib/trpc/routers/rbac/deletePermission.ts (1)
Line range hint
50-82
: Consider enhancing audit log error handling.While the overall error handling in this file is good and aligns with the PR objectives, there's an opportunity to improve the handling of potential errors during audit log insertion.
Currently, if an error occurs during the audit log insertion, it will trigger a rollback of the entire transaction, including the permission deletion. This might not always be the desired behavior, especially if the permission deletion was successful.
Consider separating the audit log insertion from the main transaction or adding specific error handling for it. This way, you can ensure that the permission is deleted even if there's an issue with audit logging.
Here's a possible refactoring to separate the audit log insertion:
await db.transaction(async (tx) => { await tx .delete(schema.permissions) .where( and( eq(schema.permissions.id, input.permissionId), eq(schema.permissions.workspaceId, workspace.id), ), ); }); try { await insertAuditLogs(db, { workspaceId: workspace.id, actor: { type: "user", id: ctx.user.id }, event: "permission.delete", description: `Deleted permission ${input.permissionId}`, resources: [ { type: "permission", id: input.permissionId, }, ], context: { location: ctx.audit.location, userAgent: ctx.audit.userAgent, }, }); } catch (err) { console.error("Failed to insert audit log:", err); // Optionally, you can add some notification mechanism here // to alert about the failed audit log insertion }This approach ensures that the permission is deleted even if there's an issue with audit logging, while still capturing any audit log insertion errors.
apps/dashboard/lib/trpc/routers/ratelimit/createNamespace.ts (1)
Line range hint
38-73
: Enhance error handling to align with PR objectivesWhile the current implementation includes error handling within the transaction block, consider the following improvements to better align with the PR objectives:
- Add a specific catch block for the audit log insertion:
await tx.insert(schema.ratelimitNamespaces).values({ // ... existing code ... }); try { await insertAuditLogs(tx, { // ... existing code ... }); } catch (error) { // Log the error or handle it as appropriate console.error("Failed to insert audit log:", error); // Consider whether to throw an error or continue with the transaction }
- Improve the error message for namespace creation failure:
throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "We are unable to create namespace. Please try again or contact support@unkey.dev if the issue persists.", });These changes will improve error handling specificity and maintain consistency with the new error message style.
apps/dashboard/lib/trpc/routers/rbac/deleteRole.ts (3)
76-77
: Improved error message for role deletion failureThe updated error message for role deletion failure is consistent with the other error messages in this file and encourages users to try again before contacting support. This aligns well with the PR objectives.
However, consider that this error occurs after a failed audit log insertion, which might indicate a more serious issue. It may be worth adding more context to the error message or logging additional information to help with troubleshooting.
Consider modifying the error handling to include more context:
- console.error(err); + console.error("Failed to insert audit log for role deletion", err); throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", - message: - "We are unable to delete the role. Please try again or contact support@unkey.dev.", + message: + "We encountered an issue while processing your request. Please try again or contact support@unkey.dev if the problem persists.", });
Line range hint
46-79
: Consider adding a catch block to the main transactionWhile the error messages have been improved throughout the file, the main transaction block doesn't have a catch block, which was one of the PR objectives. Additionally, the error handling for the main deletion operation could be more specific.
To fully meet the PR objectives and further improve error handling, consider the following suggestions:
- Add a catch block to the main transaction:
- await db.transaction(async (tx) => { + await db.transaction(async (tx) => { // ... existing code ... + }).catch((err) => { + console.error("Failed to delete role or insert audit log", err); + throw new TRPCError({ + code: "INTERNAL_SERVER_ERROR", + message: "We encountered an issue while deleting the role. Please try again or contact support@unkey.dev if the problem persists.", + }); });
- Make the error handling for the main deletion operation more specific:
await tx .delete(schema.roles) .where(and(eq(schema.roles.id, input.roleId), eq(schema.roles.workspaceId, workspace.id))) .catch((_err) => { + console.error("Failed to delete role", _err); throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", - message: - "We are unable to delete the role. Please contact support using support@unkey.dev", + message: "We encountered an issue while deleting the role. Please try again or contact support@unkey.dev if the problem persists.", }); });These changes will improve the overall error handling and bring the implementation closer to the PR objectives.
Line range hint
1-79
: Overall assessment of changesThe modifications to this file have improved the error messages, making them more user-friendly and consistent. These changes align well with the PR objectives of enhancing error handling. However, to fully meet the PR objectives, consider implementing the suggested improvements, particularly adding a catch block to the main transaction and making the error handling more specific for the deletion operation.
The changes are a step in the right direction, but there's still room for improvement to fully address the issues raised in #2274.
apps/dashboard/lib/trpc/routers/key/deleteRootKey.ts (2)
Line range hint
48-85
: Improve error handling in the transaction catch block.While there is a catch block after the db transaction, it doesn't fully address the objectives mentioned in the linked issue #2274. Consider the following improvements:
- Update the error message to be consistent with the other changes, encouraging users to try again before contacting support.
- Add specific error handling for audit log insertion failures.
- Consider logging the error details for debugging purposes.
Here's a suggested improvement:
.catch((err) => { console.error("Error in deleteRootKeys transaction:", err); if (err.message.includes("audit")) { throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "Failed to log the action. Please try again or contact support@unkey.dev if the issue persists.", }); } throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "We are unable to delete the root key. Please try again or contact support@unkey.dev if the issue persists.", }); });This change would better align with the PR objectives and address the concerns raised in issue #2274.
Line range hint
1-85
: Summary: Improvements made, but PR objectives not fully metWhile the changes to error messages are positive and improve user experience, the main objective of the PR (adding catch blocks after every db transaction, especially for audit log insertions) has not been fully addressed.
Next steps:
- Implement the suggested improvements to the catch block after the db transaction.
- Review other files in the PR to ensure that catch blocks have been added consistently after all db transactions, particularly for audit log insertions.
- Consider adding unit tests to verify the error handling behavior, especially for audit log insertion failures.
These changes will help fully address the objectives outlined in the PR and the linked issue #2274.
apps/dashboard/lib/trpc/routers/rbac/updateRole.ts (4)
47-47
: Approved: Improved error message for workspace not found.The updated error message is more user-friendly and aligns with the PR objectives. It encourages users to try again before contacting support, which may reduce unnecessary support requests.
Consider adding a brief explanation of why the workspace might not be found, such as:
- "We are unable to find the correct workspace. Please try again or contact support@unkey.dev.", + "We are unable to find the correct workspace. This may be due to a temporary issue. Please try again or contact support@unkey.dev if the problem persists.",This additional context could help users understand the situation better.
54-54
: Approved: Improved error message for role not found.The updated error message is consistent with the previous change and aligns with the PR objectives. It provides a clear instruction for users to try again before contacting support.
For consistency with the previous suggestion, consider adding a brief explanation:
- "We are unable to find the correct role. Please try again or contact support@unkey.dev.", + "We are unable to find the correct role. This may be due to a temporary issue. Please try again or contact support@unkey.dev if the problem persists.",This maintains consistency across error messages and provides additional context to the user.
82-82
: Approved: Improved error message for role update failure.The updated error message is consistent with the previous changes and aligns with the PR objectives. It provides clear instructions for users to try again before contacting support.
For consistency and clarity, consider the following modification:
- "We are unable to update the role. Please try again or contact support@unkey.dev.", + "We encountered an issue while updating the role. This may be due to a temporary problem. Please try again or contact support@unkey.dev if the issue persists.",This change provides more context about the nature of the error and maintains consistency with the previous error messages.
Line range hint
1-84
: Summary: Consistent improvement in error messaging and robust error handling.The changes in this file have successfully improved the error messages across different scenarios, encouraging users to retry before contacting support. This aligns well with the PR objectives to enhance error handling.
Key points:
- Error messages are consistently updated and more user-friendly.
- Proper error handling is implemented, including try-catch blocks for database operations.
- Audit logging is correctly placed within the transaction.
- The overall structure of the
updateRole
mutation follows best practices.Consider implementing a centralized error handling mechanism or a custom error class to manage these types of errors consistently across the application. This could help in maintaining uniform error messages and potentially reduce code duplication.
apps/dashboard/lib/trpc/routers/rbac/updatePermission.ts (1)
90-90
: Consistent error message update, but consider transaction context.This change maintains consistency with the previous error message updates, which is good for user experience. However, since this error occurs after a database transaction failure, encouraging users to "try again" might not always be appropriate or effective.
Consider modifying the message to better reflect the nature of the error:
- "We are unable to update the permission. Please try again or contact support@unkey.dev.", + "We encountered an issue while updating the permission. Please contact support@unkey.dev for assistance.",This change acknowledges the potential severity of a transaction failure without promising that retrying will resolve the issue.
apps/dashboard/lib/trpc/routers/key/updateRemaining.ts (3)
43-43
: Improved error message, consider adding more contextThe updated error message is more user-friendly and aligns with the PR objective of improving error handling. It encourages users to try again before contacting support, which is a good practice.
To further improve error handling, consider adding more context to help users understand why the key might not be found. For example:
- "We are unable to find the correct key. Please try again or contact support@unkey.dev.", + `We are unable to find the key with ID ${input.keyId}. Please verify the key ID and try again. If the issue persists, contact support@unkey.dev.`,This provides users with specific information about which key ID was not found, potentially helping them identify the issue more quickly.
Line range hint
1-101
: Approve overall structure, suggest consistent error handlingThe overall structure of the
updateKeyRemaining
procedure is well-implemented, with proper use of transactions, error handling, and audit logging. This aligns well with the PR objectives.To improve consistency in error handling, consider standardizing the error messages across different catch blocks. For example:
- "We were unable to update remaining on this key. Please contact support using support@unkey.dev", + "We encountered an issue while updating the key. Please try again or contact support@unkey.dev if the problem persists.",Apply this standardized format to all error messages in the file. This will provide a consistent user experience and make it easier to maintain the code in the future.
Line range hint
1-101
: PR objectives met, suggest documenting error handling strategyThe implementation in this file aligns well with the PR objectives. The existing catch block after the database transaction meets the primary goal, and the improvements to error messages enhance overall error handling.
To further improve the codebase:
Consider documenting the error handling strategy used in this file. This could be done through comments or in a separate documentation file, explaining the rationale behind the different types of errors thrown and how they should be handled by the calling code.
If not already present, consider adding unit tests to verify the different error scenarios and ensure that the correct error messages are thrown in each case.
These steps will help maintain consistency across the codebase and make it easier for other developers to understand and follow the established error handling patterns.
apps/dashboard/lib/trpc/routers/rbac/removePermissionFromRootKey.ts (1)
32-32
: Approved: Improved error message for better user experience.The updated error message now suggests users try again before contacting support, which is a good UX improvement. It guides users towards a potential quick fix before escalating the issue.
Consider adding a brief explanation of why the workspace might not be found, if possible. For example:
- "We are unable to find the correct workspace. Please try again or contact support@unkey.dev.", + "We are unable to find the correct workspace. This may be due to a temporary issue. Please try again or contact support@unkey.dev if the problem persists.",This additional context could further improve the user's understanding of the situation.
apps/dashboard/lib/trpc/routers/ratelimit/createOverride.ts (1)
Line range hint
87-102
: Consider adding a separate catch block for audit log insertion.In line with the PR objectives to "add catch block after every db transaction", consider adding a separate catch block for the audit log insertion. This would align with the goal of improving error handling, particularly for audit log insertions.
Here's a suggested implementation:
try { await insertAuditLogs(tx, { // ... existing audit log details ... }); } catch (error) { // Log the error or handle it as appropriate console.error('Failed to insert audit log:', error); // Optionally, you might want to continue the transaction even if audit log insertion fails // If you want to fail the entire transaction on audit log failure, you can re-throw the error here }This change would ensure that any errors during audit log insertion are caught and handled separately, improving the overall robustness of the function.
apps/dashboard/lib/trpc/routers/ratelimit/deleteNamespace.ts (2)
Line range hint
46-114
: Improve error handling for the main database transaction.While some individual database operations have catch blocks, the main transaction (lines 46-114) is not wrapped in a try-catch block. This could lead to unhandled errors and inconsistent behavior. Consider the following improvements:
- Wrap the entire transaction in a try-catch block to ensure all errors are caught and handled appropriately.
- Instead of throwing new errors in the catch blocks, consider logging the error and returning a user-friendly message.
- Ensure that all database operations within the transaction are consistently error-handled.
Here's a suggested structure:
try { await db.transaction(async (tx) => { try { // Existing transaction code } catch (error) { // Log the error console.error("Error in deleteNamespace transaction:", error); // Throw a user-friendly error throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "An error occurred while deleting the namespace. Please try again later.", }); } }); } catch (error) { // Handle any errors that occurred during the transaction console.error("Transaction failed:", error); throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "Failed to delete the namespace. Please contact support.", }); }This structure ensures that all errors are caught and handled appropriately, improving the overall reliability and user experience of the application.
Multiple Database Transactions Lack Proper Error Handling
The shell script identified several instances of
db.transaction(
without accompanyingtry
/catch
blocks across the codebase. Key affected files include:
apps/workflows/jobs/refill-daily.ts
apps/workflows/jobs/refill-monthly.ts
apps/billing/src/lib/serper.ts
apps/dashboard/app/(app)/settings/billing/stripe/success/page.tsx
apps/dashboard/app/new/page.tsx
apps/dashboard/lib/trpc/routers/workspace/changePlan.ts
apps/dashboard/lib/trpc/routers/rbac.ts
apps/dashboard/lib/trpc/routers/vercel.ts
apps/api/src/pkg/key_migration/handler.ts
apps/dashboard/lib/trpc/routers/key/updateRatelimit.ts
apps/dashboard/lib/trpc/routers/ratelimit/updateNamespaceName.ts
Recommendations:
Implement Consistent Error Handling: Wrap all
db.transaction
calls withintry
/catch
blocks to ensure that errors are appropriately handled and logged.Update the PR Scope: Revise the pull request to address the addition of
catch
blocks after every database transaction across all affected files, not just indeleteNamespace.ts
.Conduct a Codebase Review: Perform a thorough review of other parts of the codebase to identify and rectify similar patterns where error handling might be insufficient.
Enhance Testing: Add unit tests to verify that error handling behaves as expected during database transaction failures.
🔗 Analysis chain
Line range hint
1-114
: Summary: Improvements made, but PR objectives not fully addressedWhile the error message improvement on line 40 enhances user experience, this file doesn't fully address the PR objective of "add catch block after every db transaction". Here are the key points:
- The error message change is beneficial but doesn't align with the stated PR objective.
- The main database transaction lacks comprehensive error handling.
- Existing error handling is inconsistent throughout the file.
Recommendations:
- Update the PR description to accurately reflect the changes made.
- Implement the suggested error handling improvements for the main transaction.
- Review other files in this PR to ensure they address the objective of adding catch blocks after every db transaction.
- Consider adding unit tests to verify the error handling behavior.
To ensure consistency across the codebase, let's check for similar patterns in other files:
This will help identify other locations where error handling might need improvement.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for database transactions without try-catch blocks rg --type typescript 'db\.transaction\(' -A 10 -B 5 | grep -vE 'try|catch'Length of output: 111
Script:
#!/bin/bash # Search for database transactions without try-catch blocks in TypeScript files rg 'db\.transaction\(' --glob '*.ts' --glob '*.tsx' -A 10 -B 5 | grep -vE 'try|catch'Length of output: 45801
apps/dashboard/lib/trpc/routers/key/updateRatelimit.ts (4)
37-37
: Approved: Improved error message, but consider adding more specificity.The updated error message is more user-friendly, encouraging users to try again before contacting support. This aligns well with the PR objectives of improving error handling and may help reduce unnecessary support requests.
Consider providing more specific guidance on what "try again" means in this context. For example:
- "We are unable to find the correct key. Please try again or contact support@unkey.dev.", + "We are unable to find the correct key. Please verify the key ID and try again, or contact support@unkey.dev if the issue persists.",This additional detail could further reduce support requests by guiding users to check their input first.
Line range hint
52-84
: Add catch block for enabling rate limit transactionWhile the transaction for disabling the rate limit has proper error handling, the transaction for enabling the rate limit (lines 52-84) is missing a catch block. This oversight could lead to unhandled errors, which is contrary to the PR's objective of adding catch blocks after every db transaction.
Please add a catch block to handle potential errors in the transaction for enabling the rate limit. Here's a suggested implementation:
await db.transaction(async (tx) => { // ... existing code ... }); + .catch((err) => { + console.error(err); + throw new TRPCError({ + code: "INTERNAL_SERVER_ERROR", + message: "We were unable to update ratelimit on this key. Please contact support using support@unkey.dev", + }); + });This addition will ensure consistent error handling across both enabling and disabling rate limit operations, aligning with the PR objectives and improving overall error management.
Line range hint
67-82
: Enhance error handling for audit log insertionsWhile the audit log insertions are properly included in the transactions and contain the required context information (location and userAgent), there's no specific error handling for these insertions. This could lead to silent failures if the audit log insertion fails but the main transaction succeeds.
Consider adding specific error handling for the audit log insertions. Here's a suggested approach:
await insertAuditLogs(tx, { // ... existing code ... }); + .catch((err) => { + console.error('Failed to insert audit log:', err); + // Optionally, you might want to roll back the transaction or take other actions + });Apply this change to both audit log insertions (for enabling and disabling rate limits). This will ensure that any issues with audit log insertions are properly logged and handled, improving the overall robustness of the error handling in line with the PR objectives.
Also applies to: 115-130
Line range hint
1-138
: Summary: Good progress on error handling, with room for further improvementsThis review has identified several areas where the code changes align well with the PR objectives of improving error handling, particularly for audit log insertions. The modified error message provides a more user-friendly experience, and the existing error handling for key lookup and rate limit disabling is good.
However, there are opportunities for further enhancement:
- Adding a catch block for the transaction that enables rate limits.
- Implementing specific error handling for audit log insertions.
- Providing more specific guidance in the error message for key not found.
These suggestions, if implemented, will further strengthen the error handling throughout the function, ensuring that all database transactions and audit log insertions are properly managed. This aligns perfectly with the PR objectives and will contribute to a more robust and maintainable codebase.
Consider creating a helper function for consistent error handling across different operations (e.g., enabling/disabling rate limits, inserting audit logs). This could help standardize error messages and logging practices throughout the codebase.
apps/dashboard/lib/trpc/routers/key/create.ts (1)
Line range hint
134-137
: Corrected support contact information, but consider message consistency.The change correctly updates the support contact information from "support.unkey.dev" to "support@unkey.dev", which is crucial for proper user support. However, to maintain consistency with the other updated error messages in this file, consider modifying the message to include "Please try again" before suggesting to contact support. This would provide a more uniform user experience across different error scenarios.
Consider updating the error message to:
message: "We are unable to create the key. Please try again or contact support@unkey.dev",apps/dashboard/lib/trpc/routers/key/createRootKey.ts (3)
33-33
: Improved error message, consider adding more context.The updated error message is more user-friendly, encouraging users to retry before contacting support. This aligns well with the PR objectives of improving error handling.
Consider adding more context to help users understand why the error occurred. For example:
- "We were unable to create a root key for this workspace. Please try again or contact support@unkey.dev.", + "We encountered an issue while retrieving workspace information. Please try again or contact support@unkey.dev if the problem persists.",
55-55
: Improved error message, consider differentiating from similar errors.The updated error message is more user-friendly, encouraging users to retry before contacting support. This aligns well with the PR objectives of improving error handling.
Consider differentiating this error message from the similar one on line 33 to provide more specific context:
- "We were unable to create a rootkey for this workspace. Please try again or contact support@unkey.dev.", + "We encountered an issue while retrieving API information. Please try again or contact support@unkey.dev if the problem persists.",This change would help users and support staff identify the specific point of failure more easily.
Line range hint
1-214
: Consider adding catch blocks for audit log insertions.The changes made to improve error messages are good and align with the PR objectives. However, the PR description mentions adding catch blocks after every db transaction, particularly for audit log insertions. This file contains complex transaction handling and audit logging, but no such catch blocks were added.
Consider adding a catch block specifically for the audit log insertion to align with the PR objectives:
}); + } catch (err) { + // Log the error internally + console.error("Failed to insert audit logs:", err); + // Optionally, you can choose to throw a new error or handle it silently + // throw new TRPCError({ + // code: "INTERNAL_SERVER_ERROR", + // message: "An error occurred while logging the operation. The operation may have been partially completed.", + // }); } catch (_err) { throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "We are unable to create the rootkey. Please contact support using support@unkey.dev", }); }This change would improve error handling for audit log insertions without affecting the main operation if the audit log insertion fails.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (39)
- apps/dashboard/lib/trpc/routers/api/setDefaultBytes.ts (2 hunks)
- apps/dashboard/lib/trpc/routers/api/setDefaultPrefix.ts (2 hunks)
- apps/dashboard/lib/trpc/routers/api/updateDeleteProtection.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/api/updateIpWhitelist.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/api/updateName.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/key/create.ts (2 hunks)
- apps/dashboard/lib/trpc/routers/key/createRootKey.ts (2 hunks)
- apps/dashboard/lib/trpc/routers/key/delete.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/key/deleteRootKey.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/key/updateEnabled.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/key/updateExpiration.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/key/updateMetadata.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/key/updateName.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/key/updateOwnerId.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/key/updateRatelimit.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/key/updateRemaining.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/key/updateRootKeyName.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/llmGateway/create.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/llmGateway/delete.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/ratelimit/createNamespace.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/ratelimit/createOverride.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/ratelimit/deleteNamespace.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/ratelimit/deleteOverride.ts (2 hunks)
- apps/dashboard/lib/trpc/routers/ratelimit/updateOverride.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/rbac/addPermissionToRootKey.ts (2 hunks)
- apps/dashboard/lib/trpc/routers/rbac/connectPermissionToRole.ts (2 hunks)
- apps/dashboard/lib/trpc/routers/rbac/connectRoleToKey.ts (2 hunks)
- apps/dashboard/lib/trpc/routers/rbac/createPermission.ts (2 hunks)
- apps/dashboard/lib/trpc/routers/rbac/createRole.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/rbac/deletePermission.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/rbac/deleteRole.ts (2 hunks)
- apps/dashboard/lib/trpc/routers/rbac/disconnectPermissionFromRole.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/rbac/disconnectRoleFromKey.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/rbac/removePermissionFromRootKey.ts (1 hunks)
- apps/dashboard/lib/trpc/routers/rbac/updatePermission.ts (2 hunks)
- apps/dashboard/lib/trpc/routers/rbac/updateRole.ts (2 hunks)
- apps/dashboard/lib/trpc/routers/rbac/upsertPermission.ts (2 hunks)
- apps/dashboard/lib/trpc/routers/workspace/changePlan.ts (2 hunks)
- apps/dashboard/lib/trpc/routers/workspace/optIntoBeta.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (21)
- apps/dashboard/lib/trpc/routers/api/setDefaultBytes.ts
- apps/dashboard/lib/trpc/routers/api/setDefaultPrefix.ts
- apps/dashboard/lib/trpc/routers/api/updateDeleteProtection.ts
- apps/dashboard/lib/trpc/routers/api/updateIpWhitelist.ts
- apps/dashboard/lib/trpc/routers/api/updateName.ts
- apps/dashboard/lib/trpc/routers/key/updateEnabled.ts
- apps/dashboard/lib/trpc/routers/key/updateExpiration.ts
- apps/dashboard/lib/trpc/routers/key/updateMetadata.ts
- apps/dashboard/lib/trpc/routers/key/updateName.ts
- apps/dashboard/lib/trpc/routers/key/updateOwnerId.ts
- apps/dashboard/lib/trpc/routers/key/updateRootKeyName.ts
- apps/dashboard/lib/trpc/routers/llmGateway/delete.ts
- apps/dashboard/lib/trpc/routers/ratelimit/deleteOverride.ts
- apps/dashboard/lib/trpc/routers/ratelimit/updateOverride.ts
- apps/dashboard/lib/trpc/routers/rbac/addPermissionToRootKey.ts
- apps/dashboard/lib/trpc/routers/rbac/connectPermissionToRole.ts
- apps/dashboard/lib/trpc/routers/rbac/connectRoleToKey.ts
- apps/dashboard/lib/trpc/routers/rbac/createPermission.ts
- apps/dashboard/lib/trpc/routers/rbac/createRole.ts
- apps/dashboard/lib/trpc/routers/rbac/upsertPermission.ts
- apps/dashboard/lib/trpc/routers/workspace/changePlan.ts
🧰 Additional context used
🔇 Additional comments (24)
apps/dashboard/lib/trpc/routers/rbac/disconnectRoleFromKey.ts (1)
31-31
: Improved error message for better user guidance.The updated error message now suggests users try again before contacting support, which is a good practice for improving user experience and potentially reducing unnecessary support requests.
apps/dashboard/lib/trpc/routers/workspace/optIntoBeta.ts (1)
Line range hint
1-79
: File changes don't align with PR objectives.While the error messages have been improved for better clarity and consistency, the changes in this file don't address the main objective of the PR, which is to add catch blocks after every database transaction. The existing error handling structure remains unchanged, and no new catch blocks were introduced.
Consider revisiting this file to ensure it meets the PR objectives:
- Review the database transactions (e.g., the one starting at line 49) and ensure they have appropriate catch blocks.
- If catch blocks are already present and adequate, consider updating the PR description to reflect the actual changes made.
To help identify other files that might need similar changes, consider running the following command:
This will help ensure consistency across the codebase in line with the PR objectives.
apps/dashboard/lib/trpc/routers/key/delete.ts (1)
32-32
: Improved error message for better user experienceThe updated error message provides clearer guidance to the user, suggesting they try again before contacting support. This change aligns well with the PR objectives of enhancing error handling.
apps/dashboard/lib/trpc/routers/rbac/deletePermission.ts (3)
36-37
: Improved error message for better user experience.The updated error message now encourages users to try the action again before contacting support. This change enhances the user experience by potentially reducing unnecessary support requests.
43-44
: Consistent improvement in error messaging.This change aligns with the previous error message update, maintaining consistency in user communication. It encourages users to retry before contacting support, potentially reducing support load.
Line range hint
1-82
: Overall assessment of deletePermission.tsThe changes in this file improve user communication by updating error messages to be more user-friendly. These modifications align well with good UX practices and don't affect the core functionality of the
deletePermission
mutation.The existing error handling for database operations is generally good and aligns with the PR objectives. However, there's an opportunity to enhance the handling of potential errors during audit log insertion, as suggested in the previous comment.
No other issues were identified, and the overall structure and logic of the mutation remain sound.
apps/dashboard/lib/trpc/routers/ratelimit/createNamespace.ts (1)
33-33
: Approve change with a suggestion for consistency checkThe modified error message provides a more user-friendly approach by suggesting to try again before contacting support. This change could potentially reduce unnecessary support requests and improve user experience.
To ensure consistency across the codebase, let's verify if similar error messages follow this new pattern:
Consider updating other similar error messages to maintain consistency if the results show discrepancies.
✅ Verification successful
Approve Change
The updated error message aligns with the existing patterns in the codebase, enhancing consistency and improving user experience by suggesting users try again before contacting support.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Search for similar error messages in the codebase # Test: Look for error messages mentioning support contact rg --type typescript "unable to find .* (workspace|namespace) .* contact support" # Test: Check for other occurrences of the support email rg --type typescript "support@unkey.dev"Length of output: 194
Script:
#!/bin/bash # Description: Search for similar error messages in the codebase using file extensions # Test: Look for error messages mentioning support contact in .ts and .tsx files rg "unable to find .* (workspace|namespace) .* contact support" --glob "*.ts" --glob "*.tsx" # Test: Check for other occurrences of the support email in .ts and .tsx files rg "support@unkey.dev" --glob "*.ts" --glob "*.tsx"Length of output: 29967
apps/dashboard/lib/trpc/routers/rbac/deleteRole.ts (2)
35-36
: Improved error message for workspace not foundThe updated error message provides clearer guidance to the user, encouraging them to try again before contacting support. This change aligns well with the PR objectives and may help reduce unnecessary support requests.
42-43
: Consistent error message for role not foundThe error message for role not found has been updated to match the style of the workspace not found error. This consistency improves the user experience and maintains a uniform approach to error handling throughout the function.
apps/dashboard/lib/trpc/routers/key/deleteRootKey.ts (2)
32-32
: Consistent improvement in error message, but main PR objective not addressed.This change is consistent with the previous error message update, providing a more user-friendly message that encourages users to try again before contacting support. This improves the overall user experience.
However, like the previous change, this doesn't address the main objective of the PR, which is to add catch blocks after every db transaction. This error handling is for a query result check, not a transaction.
24-24
: Improved error message, but doesn't address main PR objective.The updated error message is more user-friendly, encouraging users to try again before contacting support. This is a positive change that may reduce unnecessary support requests.
However, this change doesn't address the main objective of the PR, which is to add catch blocks after every db transaction. The error handling here is for a query, not a transaction.
To verify if there are any db transactions in this file that might need additional error handling, let's run the following script:
✅ Verification successful
Updating search command to correctly identify TypeScript files.
The previous search failed due to an unrecognized file type. I'll correct the command to properly search within the TypeScript file.
No db transactions found; PR objective addressed.
The search did not find any
db.transaction
calls inapps/dashboard/lib/trpc/routers/key/deleteRootKey.ts
. Therefore, adding catch blocks for db transactions is not required in this file.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Search for db transactions in the file rg --type typescript 'db\.transaction' apps/dashboard/lib/trpc/routers/key/deleteRootKey.tsLength of output: 128
Script:
#!/bin/bash # Description: Search for db transactions in the specified TypeScript file rg 'db\.transaction' apps/dashboard/lib/trpc/routers/key/deleteRootKey.tsLength of output: 75
apps/dashboard/lib/trpc/routers/llmGateway/create.ts (3)
32-32
: Improved error message for better user guidance.The updated error message now suggests users try again before contacting support, which is a good improvement in user experience.
Line range hint
40-76
: Existing error handling aligns with PR objectives.The current implementation already includes a catch block after the database transaction (lines 63-76), which handles both specific error cases (duplicate entry) and general errors. This structure aligns well with the PR objectives of adding catch blocks after every db transaction.
Additionally, the audit log insertion is correctly placed within the transaction (lines 51-61), ensuring atomicity of the operation.
Line range hint
1-85
: Overall, the file meets PR objectives and follows best practices.The
createLlmGateway
procedure is well-structured with comprehensive error handling. It already incorporates a catch block after the database transaction, aligning with the PR objectives. The audit log insertion is properly placed within the transaction, and the error messages provide clear guidance to users.The only change made (improving an error message) enhances user experience without introducing any issues.
apps/dashboard/lib/trpc/routers/rbac/updatePermission.ts (3)
46-46
: Improved error message for workspace not found.The updated error message now encourages users to try again before contacting support, which is a good practice. This change aligns with the PR objective of enhancing error handling and may help reduce unnecessary support requests.
53-53
: Consistent improvement in error message for permission not found.This change maintains consistency with the previous error message update. It provides the same improved guidance to users, encouraging them to try again before contacting support. This consistency in error messaging is a good practice.
Line range hint
1-93
: Overall implementation aligns well with PR objectives.The changes made to this file are consistent with the PR's goal of improving error handling. The existing catch block for the database transaction, which includes error logging and audit log insertion within the transaction, demonstrates good practices for error management and data consistency.
The updated error messages provide more user-friendly guidance, potentially reducing unnecessary support requests. These changes, combined with the existing robust error handling structure, contribute to an improved user experience and easier troubleshooting.
apps/dashboard/lib/trpc/routers/rbac/removePermissionFromRootKey.ts (1)
Line range hint
89-96
: Verify alignment with PR objectives: Catch block for audit log insertion.The file already contains a catch block after the main database transaction, which aligns with the PR objective of adding catch blocks after every db transaction. However, it's worth noting that this catch block doesn't specifically handle errors from the audit log insertion, which was mentioned in the linked issue #2274.
Consider adding a specific catch block for the audit log insertion to align more closely with the issue requirements. Here's a script to verify if other files have implemented such specific error handling:
If other files have implemented specific error handling for audit log insertions, consider applying a similar pattern here.
apps/dashboard/lib/trpc/routers/ratelimit/createOverride.ts (1)
Line range hint
1-124
: Summary: Changes don't fully align with PR objectivesWhile the error message improvement is welcome, the changes in this file don't align with the stated PR objective of "add catch block after every db transaction". The file already had error handling for the main transaction, but there's an opportunity to add more granular error handling for the audit log insertion.
Consider reviewing the PR objectives and ensuring that all relevant files have been updated accordingly. If this file doesn't require further changes, it might be worth updating the PR description to accurately reflect the scope of changes.
To verify if other files in the PR contain the expected changes, you can run:
This will help identify if the catch blocks have been added in other files as per the PR objectives.
apps/dashboard/lib/trpc/routers/key/create.ts (4)
47-47
: Improved error message for better user guidance.The updated error message now includes "Please try again" before suggesting to contact support. This change enhances the user experience by encouraging users to retry the action before seeking assistance, which is in line with the PR objectives to improve error handling.
54-54
: Consistent error message improvement.This change maintains consistency with the previous error message update, providing clear guidance to users when a workspace cannot be found. The addition of "Please try again" before suggesting contacting support is a good practice that aligns with the PR objectives for improved error handling.
69-69
: Consistent error message improvement across scenarios.This change completes the pattern of improved error messaging within the file. By maintaining a consistent approach to error handling across different scenarios, the code provides a more uniform and user-friendly experience. This aligns well with the PR objectives and addresses the concerns raised in issue #2274.
Line range hint
1-137
: Overall improvements align well with PR objectives.The changes in this file successfully address the main objectives of the PR:
- Error messages have been improved to provide better guidance to users.
- A catch block is implemented after the database transaction, addressing the concern raised in issue Insert Audit logs should have a catch block #2274.
- Audit logging is properly included within the transaction, ensuring consistency in error scenarios.
These improvements enhance error handling and user experience without altering the core functionality of key creation and validation. The changes are well-implemented and align closely with the stated PR objectives.
apps/dashboard/lib/trpc/routers/key/createRootKey.ts (1)
40-40
: Improved error message for workspace not found.The updated error message for the case when a workspace is not found is more user-friendly. It encourages users to retry before contacting support, which may help reduce unnecessary support requests while still providing the option for users to reach out if needed.
Awarding harshsbhat: 150 points 🕹️ Well done! Check out your new contribution on oss.gg/harshsbhat |
What does this PR do?
Fixes #2274
Added a catch block after all db transactions.
Type of change
Checklist
Required
pnpm build
pnpm fmt
console.logs
git pull origin main
Appreciated
Summary by CodeRabbit
New Features
Bug Fixes