Skip to content

Conversation

@adityachoudhari26
Copy link
Contributor

@adityachoudhari26 adityachoudhari26 commented Nov 13, 2024

Summary by CodeRabbit

  • New Features
    • Transitioned from using "target" to "resource" across multiple components, enhancing clarity in data handling.
    • Updated filtering logic to utilize "resourceFilter" instead of "targetFilter" for improved data accuracy.
  • Bug Fixes
    • Enhanced error handling and logging for permission issues during resource access.
  • Documentation
    • Updated comments and documentation to reflect changes from target to resource terminology.
  • Refactor
    • Streamlined codebase by renaming variables and methods to align with the new resource-centric model.
  • Tests
    • Adjusted test cases to validate the new resource-based logic and ensure consistent behavior across the application.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 13, 2024

Walkthrough

This pull request implements a comprehensive refactor of the codebase, transitioning from a target-centric model to a resource-centric model. Key changes include renaming parameters and variables from target to resource, updating database schema references, and modifying related logic across multiple components. The adjustments affect how targets are created, retrieved, and managed, particularly in functions and components interacting with Google Kubernetes Engine (GKE) and other target-related features. Enhanced error handling and logging are also introduced to improve clarity during permission issues.

Changes

File Path Change Summary
apps/event-worker/src/target-scan/gke.ts Renamed targetProviderId to resourceProviderId in getGkeTargets, updated error handling in getClustersByProject for clearer logging.
apps/event-worker/src/target-scan/index.ts Renamed targetProvider and targetProviderGoogle to resourceProvider and resourceProviderGoogle, updated database query logic accordingly.
apps/webservice/src/app/[workspaceSlug]/_components/environment-drawer/Filter.tsx Renamed targetFilter to resourceFilter in EditFilterForm component's default values and submission data.
apps/webservice/src/app/[workspaceSlug]/_components/job-condition/JobTargetConditionRender.tsx Updated filter mapping from env.targetFilter to env.resourceFilter.
apps/webservice/src/app/[workspaceSlug]/_components/target-drawer/CreateTargetVariableDialog.tsx Renamed targetId to resourceId in onSubmit function.
apps/webservice/src/app/[workspaceSlug]/_components/target-drawer/EditTargetVariableDialog.tsx Updated invalidate method to use resourceId instead of targetId.
apps/webservice/src/app/[workspaceSlug]/_components/target-drawer/TargetVariableDropdown.tsx Changed targetId prop to resourceId for DeleteTargetVariableDialog.
apps/webservice/src/app/[workspaceSlug]/systems/SystemActionsDropdown.tsx Updated mapping from env.targetFilter to env.resourceFilter.
apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/_components/variables/VariableInputs.tsx Changed filtering logic from targetFilter to resourceFilter.
apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/deployments/TableDeployments.tsx Updated target presence check from isPresent(releaseJobTrigger.targetId) to isPresent(releaseJobTrigger.target.id).
apps/webservice/src/app/api/v1/job-agents/[agentId]/jobs/running/route.ts Renamed target to resource in database schema imports and query logic.
apps/webservice/src/app/api/v1/jobs/[jobId]/route.ts Updated references from target and targetMetadata to resource and resourceMetadata.
apps/webservice/src/app/api/v1/target-providers/[providerId]/set/route.ts Changed targetProvider to resourceProvider in database operations.
apps/webservice/src/app/api/v1/targets/[targetId]/route.ts Updated API route handling to use resource instead of target.
apps/webservice/src/app/api/v1/workspaces/[workspaceId]/target-providers/name/[name]/route.ts Replaced targetProvider with resourceProvider in database operations.
apps/webservice/src/app/api/v1/workspaces/[workspaceId]/targets/identifier/[identifier]/route.ts Updated API routes to reference resource instead of target.
packages/api/src/router/deployment-variable.ts Replaced targetFilter with resourceFilter in deployment variable handling.
packages/api/src/router/deployment.ts Updated methods to replace target with resource across various queries.
packages/api/src/router/environment.ts Renamed targetFilter to resourceFilter in environment schema.
packages/api/src/router/job.ts Replaced target with resource in job-related queries and logic.
packages/api/src/router/release-deploy.ts Updated toTarget mutation to reference resource instead of target.
packages/api/src/router/release.ts Changed targetId to resourceId in releaseJobTrigger table.
packages/api/src/router/target-metadata-group.ts Renamed targetMetadataGroup to resourceMetadataGroup.
packages/api/src/router/target-provider.ts Replaced targetProvider with resourceProvider in various queries.
packages/api/src/router/target.ts Comprehensive renaming from target to resource across multiple functions.
packages/db/drizzle/0037_giant_stardust.sql Added resource_session table, renamed target_id to resource_id in existing tables.
packages/db/src/schema/deployment-variables.ts Renamed targetFilter to resourceFilter in schema definition.
packages/db/src/schema/environment.ts Updated targetFilter to resourceFilter in environment schema.
packages/db/src/schema/job.ts Changed import from target to resource, updated related logic.
packages/db/src/schema/release.ts Renamed targetId to resourceId in releaseJobTrigger table.
packages/db/src/schema/target-agent.ts Renamed targetSession to resourceSession.
packages/db/src/schema/target-group.ts Renamed targetMetadataGroup to resourceMetadataGroup.
packages/db/src/schema/target-provider.ts Renamed targetProvider to resourceProvider and related entities.
packages/db/src/schema/target-session.ts Renamed targetSession to resourceSession.
packages/db/src/schema/target.ts Comprehensive renaming from target to resource.
packages/events/src/triggers/deployment-deleted.ts Updated filtering logic from targetFilter to resourceFilter.
packages/events/src/triggers/environment-deleted.ts Changed references from targetFilter to resourceFilter.
packages/events/src/triggers/target-deleted.ts Updated filtering logic from targetFilter to resourceFilter.
packages/job-dispatch/src/test/job-variables-deployment.test.ts Updated test cases to reflect changes from targetId to resourceId and targetFilter to resourceFilter.
packages/job-dispatch/src/environment-creation.ts Renamed targetFilter to resourceFilter and updated related logic.
packages/job-dispatch/src/job-variables-deployment/job-variables-deployment.ts Updated job target retrieval logic from targetId to resourceId.
packages/job-dispatch/src/job-variables-deployment/utils.ts Changed queries from SCHEMA.target to SCHEMA.resource.
packages/job-dispatch/src/lock-checker.ts Updated joins from target to resource.
packages/job-dispatch/src/pending-job-checker.ts Replaced targetId with resourceId in filtering logic.
packages/job-dispatch/src/policies/gradual-rollout.ts Updated property references from targetId to resourceId.
packages/job-dispatch/src/policies/release-dependency.ts Replaced targetId with resourceId in dependency processing logic.
packages/job-dispatch/src/release-job-trigger.ts Updated job trigger logic to use resource instead of target.
packages/job-dispatch/src/target.ts Updated references from target to resource in various functions.
apps/webservice/next.config.js Removed asynchronous rewrites function defining API route rewrites.

Possibly related PRs

  • fix: Check existence from identifiers #155: The changes in this PR involve modifications to the createTargetScanWorker function, which also deals with target identifiers, similar to the changes in the main PR where targetProviderId is replaced with resourceProviderId.
  • fix: Target variables #170: This PR focuses on enhancing the handling of target variables, which aligns with the main PR's changes regarding the handling of identifiers in target-related functions.
  • fix: Target redeploy #210: The introduction of the RedeployTargetDialog and its integration into the TargetActionsDropdown relates to the overall management of targets, which is a theme in the main PR's changes.
  • fix: Select release channel filter on deployment page #214: This PR modifies the Overview component to manage release filters, which connects to the main PR's focus on handling identifiers and improving the management of target-related data.

Suggested reviewers

  • jsbroks: Suggested for review due to familiarity with the project's structure and the nature of the changes made.

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?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 60

🧹 Outside diff range and nitpick comments (62)
packages/db/src/schema/target-session.ts (1)

Update Required: Incomplete Refactoring of targetId References

Several remaining references to targetId and target_id were found across multiple modules, indicating incomplete refactoring. Please ensure all instances are updated to maintain consistency with the resource-centric model.

🔗 Analysis chain

Line range hint 6-13: LGTM: Schema changes align with the resource-centric model

The table and column renames from target_session to resource_session and targetId to resourceId are consistent with the PR's objective of transitioning to a resource-centric model. The references and constraints are properly maintained.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify no remaining references to the old table name
rg -l "target_session"

# Check for any remaining references to targetId in SQL migrations or schema files
fd -e sql -e ts | xargs rg "targetId|target_id"

Length of output: 16233

packages/db/src/schema/target-group.ts (1)

Old type and helper function references still exist after renaming schema.

  • The following files still reference TargetMetadataGroup:
    • packages/auth/src/utils/rbac.ts
    • packages/validators/src/auth/index.ts
    • packages/db/src/schema/target-group.ts
    • packages/api/src/router/target-metadata-group.ts
    • apps/webservice/src/app/[workspaceSlug]/(targets)/target-metadata-groups/TargetGroupTable.tsx
    • apps/webservice/src/app/[workspaceSlug]/(targets)/target-metadata-groups/page.tsx
    • apps/webservice/src/app/[workspaceSlug]/(targets)/target-metadata-groups/TargetMetadataGroupsGettingStarted.tsx
    • apps/webservice/src/app/[workspaceSlug]/(targets)/target-metadata-groups/[groupId]/page.tsx
    • apps/webservice/src/app/[workspaceSlug]/(targets)/target-metadata-groups/EditMetadataGroupDialog.tsx
  • The helper functions createTargetMetadataGroup and updateTargetMetadataGroup are still referenced in:
    • packages/api/src/router/target-metadata-group.ts
    • packages/db/src/schema/target-group.ts
🔗 Analysis chain

Line range hint 8-33: Verify the impact of schema renaming across the codebase.

The table renaming from target_metadata_group to resource_metadata_group requires verification of database migrations and usage across the codebase.


🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining references to the old table name and type names

# Check for old table name references
echo "Checking for old table name references..."
rg -l "target_metadata_group"

# Check for old type name references
echo "Checking for old type name references..."
rg -l "TargetMetadataGroup"

# Check for helper function references
echo "Checking for helper function references..."
rg -l "createTargetMetadataGroup|updateTargetMetadataGroup"

# Look for potential migration files
echo "Checking for migration files..."
fd -g "*migration*.ts" -g "*migration*.sql"

Length of output: 3115


Script:

#!/bin/bash
# Description: Re-attempt to find migration files with corrected search patterns and verify their contents

# Check for migration files with corrected patterns
echo "Re-checking for migration files with corrected patterns..."
fd -e ts -e sql 'migration' . || echo "No migration files found."

# If migration files are found, display their contents related to the table renaming
echo "Displaying contents of migration files related to 'resource_metadata_group'..."
rg "resource_metadata_group" $(fd 'migration' -e ts -e sql)

Length of output: 1990

packages/events/src/triggers/deployment-deleted.ts (3)

Line range hint 2-3: Update type imports to match the resource-centric model

The imports still use target-centric naming which is inconsistent with the resource-centric model transition:

  • TargetCondition from "@ctrlplane/validators/targets"
  • TargetFilterType from "@ctrlplane/validators/targets"

These types should be renamed to maintain consistency with the resource-centric model. Consider updating the imports to use resource-centric naming:

-import type { TargetCondition } from "@ctrlplane/validators/targets";
+import type { ResourceCondition } from "@ctrlplane/validators/resources";
-import { TargetFilterType } from "@ctrlplane/validators/targets";
+import { ResourceFilterType } from "@ctrlplane/validators/resources";

Also applies to: 8-9


Line range hint 27-31: Update type annotation to match resource-centric model

The systemFilter is still typed as TargetCondition and uses TargetFilterType.

Apply this change to maintain consistency:

-const systemFilter: TargetCondition = {
-  type: TargetFilterType.Comparison,
+const systemFilter: ResourceCondition = {
+  type: ResourceFilterType.Comparison,
   operator: ComparisonOperator.Or,
   conditions: envFilters,
 };

Line range hint 37-40: Update event action to reflect resource-centric model

The event action still uses "deployment.target.removed".

Consider updating the event action name:

 return targets.map((target) => ({
-  action: "deployment.target.removed",
+  action: "deployment.resource.removed",
   payload: { deployment, target },
 }));
apps/webservice/src/app/api/v1/job-agents/[agentId]/jobs/running/route.ts (1)

The review comment is correct and should be implemented

The suggested change aligns with the codebase's migration from a target-centric to resource-centric model, as evidenced by schema migrations and similar patterns in other files. The response mapping should use consistent terminology.

🔗 Analysis chain

Line range hint 47-47: Inconsistent naming in response mapping

The response still uses target as the field name while mapping data from the resource table. This is inconsistent with the PR's objective of transitioning to a resource-centric model.

Apply this fix to maintain consistency:

        ...row.job,
        config: row.release_job_trigger,
        environment: row.environment,
-       target: row.resource,
+       resource: row.resource,
        deployment: row.deployment,
        release: row.release,

Let's verify if this field is used by API consumers:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for API response usage where 'target' field might be accessed
rg -g '!*.{log,lock}' -A 3 'jobs/running.*\.then' 

Length of output: 51


Script:

#!/bin/bash
# Search for any occurrences of 'target' in the codebase excluding specific file types
rg -g '!*.{log,lock}' 'target'

# Additionally, search for 'target' in documentation and test files
rg -g '*.md' 'target'
rg -g '*.test.ts' 'target'

Length of output: 542790


Script:

#!/bin/bash
# Search for the specific route file and related files
rg -g '!*.{log,lock}' -A 5 'apps/webservice/src/app/api/v1/job-agents/\[agentId\]/jobs/running/route'

Length of output: 103


Script:

#!/bin/bash
# Search for the route file and any references to 'target' field in response mapping
rg -g '!*.{log,lock}' -A 3 'target: row.resource'

# Also search for the specific file
fd "route.ts" "apps/webservice/src/app/api/v1/job-agents"

Length of output: 1384

packages/job-dispatch/src/pending-job-checker.ts (1)

Line range hint 7-8: Consider using a more descriptive parameter name

The parameter name wf could be more descriptive. Consider renaming it to workflows or workflowItems for better readability.

 export const isPassingNoPendingJobsPolicy: ReleasePolicyChecker = async (
   db,
-  wf,
+  workflows,
 ) =>
packages/events/src/triggers/target-deleted.ts (1)

Inconsistent event action usage found

The event action "deployment.target.removed" is used in multiple files, but "deployment.target.deleted" is also present in packages/validators/src/events/hooks/index.ts. Please ensure consistent event action naming.

🔗 Analysis chain

Line range hint 48-51: Verify if event action name should be updated

The event action "deployment.target.removed" still uses the target terminology. If there are no backward compatibility concerns, consider updating it to "deployment.resource.removed" to maintain consistency with the resource-centric model.

Let's check for event action usage across the codebase:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for usages of the event action
rg "deployment\.target\.removed" -A 2

Length of output: 1641


Script:

#!/bin/bash
# Corrected search for usages of the event action
rg 'deployment\.target\.removed' -A 2

Length of output: 1547

apps/webservice/src/app/[workspaceSlug]/_components/target-drawer/TargetVariableDropdown.tsx (1)

47-47: Consider updating prop name for consistency

While the change from targetVariable.targetId to targetVariable.resourceId aligns with the resource-centric model, the prop name targetId still uses the old terminology. Consider updating it to resourceId for consistency.

-         targetId={targetVariable.resourceId}
+         resourceId={targetVariable.resourceId}
packages/db/src/schema/target-provider.ts (1)

30-33: Consider renaming the variable for consistency

While the relations are correctly updated, consider renaming the variable to match the new naming pattern:

-export const resourceProviderRelations = relations(
+export const resourceProviderToResourceRelations = relations(
   resourceProvider,
   ({ many }) => ({ resources: many(resource) }),
);
packages/events/src/triggers/environment-deleted.ts (2)

46-46: Consider updating variable names for complete consistency

While the schema references have been properly updated to use resource, consider updating these variable names and types for complete consistency:

  • removedFromSystemTargetsremovedFromSystemResources
  • TargetConditionResourceCondition
- const removedFromSystemTargets =
+ const removedFromSystemResources =
    envFilters.length > 0
      ? await db
          .select()
          .from(SCHEMA.resource)
          .where(
            and(
              SCHEMA.targetMatchesMetadata(db, removedFromSystemFilter),
              inArray(
                SCHEMA.resource.id,
                targets.map((t) => t.id),
              ),
            ),
          )
      : targets;
- if (removedFromSystemTargets.length === 0) return [];
+ if (removedFromSystemResources.length === 0) return [];

Also applies to: 51-51


Update remaining target-related terminology

Multiple instances of "target" terminology still exist in the codebase that need to be updated for consistency:

  1. Function targetMatchesMetadata should be renamed to resourceMatchesMetadata.
  2. Types TargetCondition and TargetFilterType should be updated to ResourceCondition and ResourceFilterType respectively.
  3. Event actions like "deployment.target.removed" should be changed to "deployment.resource.removed".
🔗 Analysis chain

Line range hint 1-65: Consider updating remaining target-related terminology

For complete consistency with the resource-centric model, consider updating these remaining instances:

  1. The helper function targetMatchesMetadata could be renamed to resourceMatchesMetadata
  2. The import TargetFilterType could be updated to ResourceFilterType
  3. The event action "deployment.target.removed" could be changed to "deployment.resource.removed"
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining target-related terminology in the codebase

# Search for target-related function names
echo "Checking for target-related function names..."
rg "targetMatches|TargetFilter|TargetCondition" --type ts

# Search for target-related event actions
echo "Checking for target-related event actions..."
rg "deployment\.target\." --type ts

Length of output: 32974

packages/db/drizzle/0037_giant_stardust.sql (1)

1-5: Consider adding timestamp columns and ON DELETE behavior

The resource_session table structure could benefit from:

  1. Audit columns like created_at and updated_at for tracking session lifecycle
  2. Explicit ON DELETE behavior for resource_id and created_by_id to handle cascading deletes
 CREATE TABLE IF NOT EXISTS "resource_session" (
 	"id" uuid PRIMARY KEY NOT NULL,
 	"resource_id" uuid NOT NULL,
- 	"created_by_id" uuid NOT NULL
+ 	"created_by_id" uuid NOT NULL,
+ 	"created_at" timestamp with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL,
+ 	"updated_at" timestamp with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL
 );
apps/webservice/src/app/api/v1/target-providers/[providerId]/set/route.ts (2)

Line range hint 68-72: Enhance error message clarity

The error message "Provider not found" could be more specific about what type of provider wasn't found.

-        { error: "Provider not found" },
+        { error: "Resource provider not found" },

Inconsistent Migration of API Paths and Permissions

API paths still contain "target-providers" and permissions are using TargetUpdate instead of the updated "resource" terminology. Verify if these should be updated as part of this migration or preserved for backward compatibility.

🔗 Analysis chain

Line range hint 44-47: Verify migration strategy for API paths and permissions

While the database schema has been updated to use "resource" terminology, the API path still contains "target-providers" and the permission is still TargetUpdate. Consider:

  1. Whether these should be updated as part of this change
  2. If there's a planned phase for updating API paths and permissions
  3. If these need to be preserved for backward compatibility
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistency in API paths and permissions

# Check for other API routes using target/resource terminology
echo "Checking API routes..."
fd . "apps/webservice/src/app/api" -t f -E "*.ts" -x rg -l "target-providers|resource-providers"

# Check permission definitions
echo "Checking permissions..."
rg "Permission\." --type ts -A 1

Length of output: 26006

packages/job-dispatch/src/job-variables-deployment/utils.ts (3)

47-47: Consider renaming function for consistency

While the table and column references have been updated to use resource terminology, the function name getTargetVariableValue still uses the old "target" terminology. Consider renaming it to getResourceVariableValue for consistency.

-export const getTargetVariableValue = (tx: Tx, targetId: string, key: string) =>
+export const getResourceVariableValue = (tx: Tx, resourceId: string, key: string) =>

Also applies to: 50-51


70-70: Ensure consistent parameter naming

While the table references have been updated, the function still uses target-centric parameter names:

  • targetId parameter could be renamed to resourceId
  • targetFilter parameter could be renamed to resourceFilter
  • SCHEMA.targetMatchesMetadata helper might need renaming

This would make the API more consistent with the new resource-centric model.

-export const getMatchedTarget = (
-  tx: Tx,
-  targetId: string,
-  targetFilter: TargetCondition | null,
+export const getMatchedResource = (
+  tx: Tx,
+  resourceId: string,
+  resourceFilter: TargetCondition | null,

Also applies to: 73-73


Line range hint 1-89: Consider a more comprehensive rename refactoring

While the database schema references have been successfully updated from target to resource, there's an opportunity to make the API more consistent by:

  1. Renaming all functions to use resource instead of target
  2. Updating parameter names to use resourceId instead of targetId
  3. Updating type names (e.g., TargetCondition) to reflect the new terminology

This would make the codebase more maintainable and prevent confusion between old and new terminology.

apps/webservice/src/app/api/v1/workspaces/[workspaceId]/targets/identifier/[identifier]/route.ts (5)

Line range hint 26-27: Update permission type to match schema changes

The permission check still uses Permission.TargetGet despite the transition to a resource-based model. Consider updating the permission types to maintain consistency with the schema changes.

- .perform(Permission.TargetGet)
+ .perform(Permission.ResourceGet)

Line range hint 44-47: Update error message to reflect resource terminology

The error message still references "Target" despite the schema change to resources. Update the message to maintain consistency with the new terminology.

- { error: "Target not found" },
+ { error: "Resource not found" },

Line range hint 73-74: Update permission type in DELETE endpoint

Similar to the GET endpoint, the DELETE permission check should be updated to use resource-based permissions.

- .perform(Permission.TargetDelete)
+ .perform(Permission.ResourceDelete)

Line range hint 88-91: Update error message in DELETE endpoint

The error message in the DELETE endpoint should also be updated to use resource terminology.

- { error: `Target not found for identifier: ${params.identifier}` },
+ { error: `Resource not found for identifier: ${params.identifier}` },

Update Required in Documentation and Tests

Changing the route from /targets to /resources will require corresponding updates in the documentation and test files to ensure consistency and prevent broken links or tests.

🔗 Analysis chain

Line range hint 1-99: Consider updating the route path

The route is still under the /targets path despite the transition to resources. This might need to be addressed in a separate PR to maintain backward compatibility and handle the migration properly.

Let's check for any API documentation or client usage that might be affected:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for API route usage in documentation and test files
rg -g '*.{md,mdx}' -i 'targets/identifier'
rg -g '*test*' -i 'targets/identifier'

Length of output: 81


Script:

#!/bin/bash
# Broaden the search for any usage of 'targets' in documentation and test files
rg -g '*.{md,mdx}' -i 'targets'
rg -g '*test*' -i 'targets'

Length of output: 14278

apps/event-worker/src/target-scan/index.ts (1)

Line range hint 43-83: Document terminology transition and update variable names

The code mixes "target" and "resource" terminology throughout the implementation:

  1. Variable tp suggests "target provider"
  2. Log messages use both terms
  3. Function names still use "target"

Consider:

  1. Updating variable names for clarity
  2. Documenting the terminology transition
  3. Creating a follow-up task to update related function names
- const tp = await db
+ const resourceProviderData = await db

- logger.error(`Target provider with ID ${targetProviderId} not found.`);
+ logger.error(`Resource provider with ID ${resourceProviderId} not found.`);
packages/job-dispatch/src/environment-creation.ts (1)

86-86: Consider using a more descriptive parameter name

The mapping function uses 't' as the parameter name. Consider using a more descriptive name like 'resource' for better readability.

-    .targets(resources.map((t) => t.id))
+    .targets(resources.map((resource) => resource.id))
apps/webservice/src/app/api/v1/targets/[targetId]/route.ts (1)

Incomplete target-to-resource transition

The transition from "target" to "resource" is not fully completed. Numerous remaining references to "target" were found across the codebase, which may lead to confusion and inconsistency:

  • packages/job-dispatch/src/target.ts
  • packages/db/src/schema/target.ts
  • packages/job-dispatch/src/release-job-trigger.ts
  • packages/validators/src/targets/conditions/index.ts
  • apps/webservice/src/app/api/v1/target-providers/[providerId]/route.ts

Please ensure all instances are updated to maintain architectural consistency.

🔗 Analysis chain

Line range hint 1-107: Consider completing the target-to-resource transition

The codebase appears to be in a transitional state. Several architectural elements still reference the old "target" terminology:

  1. API route path (/targets/[targetId])
  2. Permission enums (TargetGet, TargetUpdate, TargetDelete)
  3. Helper functions (upsertTargets)

This mixed terminology could lead to confusion in the codebase and API documentation.

Let's check for other occurrences of target terminology that might need updating:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for remaining target references in route definitions and permission enums
rg -l 'Permission\.Target|\/targets\/|\btarget\b' --type ts

Length of output: 188


Script:

#!/bin/bash
# Search for remaining target references in route definitions and permission enums
rg -l 'Permission\.Target|/targets/|\btarget\b' --type=ts

Length of output: 14714

packages/db/src/schema/deployment-variables.ts (1)

63-65: LGTM, but consider full terminology alignment

The rename from targetFilter to resourceFilter aligns with the PR objectives. However, note that the underlying type TargetCondition and validator targetCondition still use the old terminology. Consider creating a follow-up PR to rename these as well for complete consistency.

Also applies to: 82-82

packages/api/src/router/workspace-integrations.ts (2)

Line range hint 113-113: Update error message to use resource-centric terminology

The error message still refers to "target providers" which is inconsistent with the resource-centric model being implemented.

-              "Cannot delete Google service account while active target providers exist.",
+              "Cannot delete Google service account while active resource providers exist.",

Inconsistent terminology: "target provider" found in multiple files.

  • integrations/google-compute-scanner/src/index.ts: Lines 1-2
  • integrations/terraform-cloud-scanner/src/scanner.ts: Lines 1-2
  • integrations/kubernetes-job-agent/src/utils.ts: Line 1
  • packages/validators/src/events/index.ts: Line 1
  • packages/validators/src/auth/index.ts: Lines 1-3
  • packages/node-sdk/src/schema.ts: Lines 1-8
  • packages/api/src/router/workspace-integrations.ts: Line 113
  • packages/api/src/router/target-provider.ts: Lines 1-20
  • packages/api/src/router/target.ts: Lines 1-5
  • apps/event-worker/src/target-scan/gke.ts: Lines 1-6
  • apps/event-worker/src/target-scan/index.ts: Lines 1-7
  • apps/webservice/src/app/api/v1/target-providers/.../openapi.ts: Lines 1-7
  • apps/webservice/src/app/[workspaceSlug]/.../page.tsx: Multiple lines
  • apps/webservice/src/app/[workspaceSlug]/(job)/job-agents/integrations/page.tsx: Lines 1-4
  • apps/webservice/src/app/[workspaceSlug]/(targets)/.../index.tsx: Multiple lines
  • apps/docs/pages/core-concepts/targets/_meta.ts: Line 1
🔗 Analysis chain

Line range hint 113-113: Verify consistent terminology across codebase

Let's verify that all occurrences of "target provider" terminology have been updated to "resource provider" across the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining instances of "target provider" terminology
rg -i "target\s*provider" --type ts --type tsx

Length of output: 76


Script:

#!/bin/bash
# Search for any remaining instances of "target provider" in .ts and .tsx files
rg -i "target\s*provider" -g "*.ts" -g "*.tsx"

Length of output: 23671

apps/webservice/src/app/api/v1/jobs/[jobId]/route.ts (1)

119-120: Update variable names to use consistent resource terminology.

While the database query correctly uses the new resourceMetadata table, several variable names still use the old "target" terminology.

Consider updating the variable names for consistency:

    const jobTargetMetadataRows = await db
      .select()
      .from(resourceMetadata)
-     .where(eq(resourceMetadata.resourceId, je.target?.id ?? ""));
+     .where(eq(resourceMetadata.resourceId, je.resource?.id ?? ""));

    const metadata = Object.fromEntries(
-     jobTargetMetadataRows.map((m) => [m.key, m.value]),
+     resourceMetadataRows.map((m) => [m.key, m.value]),
    );

-   const targetWithMetadata = { ...je.target, metadata };
+   const resourceWithMetadata = { ...je.resource, metadata };

    return NextResponse.json({
      ...je.job,
      ...je,
      variables,
-     target: targetWithMetadata,
+     resource: resourceWithMetadata,
      approval,
    });

Also applies to: 122-127, 131-136

apps/webservice/src/app/[workspaceSlug]/_components/job-condition/JobTargetConditionRender.tsx (1)

Line range hint 1-150: Consider completing the target-to-resource terminology migration.

While the environment filter has been updated to use resourceFilter, the component still heavily uses target-centric terminology. Consider completing the migration by:

  1. Renaming the component from JobTargetConditionRender to JobResourceConditionRender
  2. Updating imports from validators/targets to use resource validators
  3. Updating type names (e.g., TargetConditionResourceCondition)
  4. Migrating API calls from api.target.* to api.resource.*
  5. Updating UI text from "target" to "resource"

This would maintain consistency with the resource-centric model being implemented.

Would you like me to help create a follow-up PR to complete this migration?

packages/job-dispatch/src/policies/release-dependency.ts (1)

92-92: Consider updating the column alias for consistency.

While the logic is correct, the column alias targetId is still using target-centric terminology despite referencing resourceId. Consider updating it to maintain consistency with the resource-centric model.

- targetId: schema.releaseJobTrigger.resourceId,
+ resourceId: schema.releaseJobTrigger.resourceId,

Note: If you make this change, ensure to update all references to latestJobSubquery.targetId in the code below.

Also applies to: 97-97

apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/deployments/[deploymentSlug]/page.tsx (1)

Line range hint 127-130: Update component description to reflect resource-centric model.

The description still refers to "target-specific settings" which doesn't align with the transition to a resource-centric model.

Consider updating the text to:

-          Deployment variables allow you to configure target-specific settings
+          Deployment variables allow you to configure resource-specific settings
           for your application. Learn more about variable precedence here.
packages/api/src/router/workspace.ts (1)

226-229: Consider renaming procedure for consistency with resource-centric model

The query changes correctly implement the transition to the resource-centric model. However, for better consistency:

  1. Consider renaming the procedure from targetKinds to resourceKinds
  2. Update the permission check from Permission.TargetList to a resource-based permission

Here's a suggested refactor:

-  targetKinds: protectedProcedure
+  resourceKinds: protectedProcedure
     .meta({
       authorizationCheck: ({ canUser, input }) =>
         canUser
-          .perform(Permission.TargetList)
+          .perform(Permission.ResourceList)
           .on({ type: "workspace", id: input }),
     })
apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/_components/variables/VariableInputs.tsx (1)

Line range hint 1-215: Consider a more comprehensive rename strategy.

The component and its dependencies still heavily use target-centric terminology (e.g., VariableTargetInput, TargetCondition, api.target) while the data model is moving towards a resource-centric approach. This mixed terminology could lead to confusion and maintenance challenges.

Consider:

  1. Renaming this component to VariableResourceInput
  2. Creating new resource-centric types and gradually deprecating target types
  3. Adding API endpoints with resource terminology and deprecating target endpoints
  4. Documenting the migration strategy for other developers

Would you like me to help create a migration plan or generate the renamed component implementation?

apps/webservice/src/app/[workspaceSlug]/_components/target-drawer/CreateTargetVariableDialog.tsx (1)

Refactoring Incomplete: 'target' terminology still present in multiple files.

  • apps/webservice/src/app/[workspaceSlug]/_components/variable-set-drawer/OverviewContent.tsx
  • apps/webservice/src/app/[workspaceSlug]/_components/job-condition/JobConditionBadge.tsx
  • apps/webservice/src/app/[workspaceSlug]/_components/job-drawer/RelationshipsDiagramDependencies.tsx
  • apps/webservice/src/app/[workspaceSlug]/_components/terminal/TerminalSessionsDrawer.tsx
  • apps/webservice/src/app/[workspaceSlug]/_components/job-condition/JobTargetConditionRender.tsx
  • apps/webservice/src/app/[workspaceSlug]/_components/terminal/TerminalSessionsProvider.tsx
  • apps/webservice/src/app/[workspaceSlug]/_components/job-drawer/JobDrawer.tsx
  • apps/webservice/src/app/[workspaceSlug]/_components/terminal/CreateDialogSession.tsx
  • apps/webservice/src/app/[workspaceSlug]/_components/release-drawer/ReleaseDrawer.tsx
  • apps/webservice/src/app/[workspaceSlug]/_components/target-drawer/CreateTargetVariableDialog.tsx
  • ... (additional files listed in the shell script output)
🔗 Analysis chain

Line range hint 1-200: Complete the target → resource renaming refactoring.

For consistency with the resource-centric model transition, consider updating:

  1. Component name from CreateTargetVariableDialog to CreateResourceVariableDialog
  2. Props interface from CreateTargetVariableDialogProps and targetId to CreateResourceVariableDialogProps and resourceId
  3. UI text in DialogHeader from "Create Target Variable" to "Create Resource Variable"
  4. File name and location to reflect the new resource-centric model

This will maintain consistency across the codebase and prevent confusion.

Let's verify the broader refactoring pattern:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if other files follow the same renaming pattern
echo "Files still using 'target' terminology:"
rg -l 'target' --type tsx

echo "\nFiles already using 'resource' terminology:"
rg -l 'resource' --type tsx

echo "\nVerifying mutation usage patterns:"
rg -A 2 'mutateAsync\({.*Id:' --type tsx

Length of output: 553


Script:

#!/bin/bash
# Check if other files follow the same renaming pattern using correct glob pattern
echo "Files still using 'target' terminology:"
rg 'target' --glob '*.tsx' -l

echo "\nFiles already using 'resource' terminology:"
rg 'resource' --glob '*.tsx' -l

echo "\nVerifying mutation usage patterns with corrected regex:"
rg -A 2 'mutateAsync\(\{.*Id:' --glob '*.tsx'

Length of output: 16470

apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/deployments/TableDeployments.tsx (1)

Incomplete resource renaming implementation

Found remaining target references that need to be updated to resource. Examples include:

  • apps/event-worker/src/index.ts
  • apps/webservice/src/app/[workspaceSlug]/SidebarWorkspace.tsx
  • apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/deployments/TableDeployments.tsx
🔗 Analysis chain

Line range hint 1-4: Incomplete resource renaming implementation

The PR objective is to rename resource tables, but this file still uses target-centric terminology in imports and type definitions. Consider updating these references to align with the resource-centric model:

 import type {
   Deployment,
   Environment,
-  Target,
+  Resource,
   Workspace,
 } from "@ctrlplane/db/schema";

Let's verify the extent of the renaming needed:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for remaining target references that need to be updated to resource

# Search for Target type references
ast-grep --pattern 'type { $$$ Target $$$ }'

# Search for target-related variable names and properties
rg -i '\btarget[s]?\b' --type typescript

Length of output: 124


Script:

#!/bin/bash
# Description: Check for remaining target references that need to be updated to resource

# Search for Target type references
ast-grep --pattern 'type { $$$ Target $$$ }'

# Search for target-related variable names and properties
rg -i '\btarget[s]?\b' --type ts --type tsx

Length of output: 120


Script:

#!/bin/bash
# Description: Check for remaining target references that need to be updated to resource

# Search for Target type references
ast-grep --pattern 'type { $$$ Target $$$ }'

# Search for target-related variable names and properties
rg -i '\btarget[s]?\b' -g "*.ts" -g "*.tsx"

Length of output: 138332

apps/event-worker/src/target-scan/gke.ts (1)

Complete the target → resource renaming transition.

There are numerous remaining "target" related names across various parts of the codebase that need to be updated to ensure consistency and prevent confusion.

  • File paths contain "target-scan"
  • Multiple type imports, function names, and variables still use "target"
  • Log messages and other code references mention "targets"
🔗 Analysis chain

Line range hint 1-300: Consider completing the target → resource renaming transition.

While the parameter renaming is correct, there are still many target-related names in the codebase that weren't updated:

  • File path contains "target-scan"
  • Type imports use "Target" prefix
  • Function names and variables use "target"
  • Log messages mention "targets"

This partial transition might cause confusion for developers.

Let's verify the scope of remaining target-related names in the codebase:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for remaining target-related names that might need updating
echo "Files with 'target' in path:"
fd -t f target

echo "\nOccurrences of 'target' in code:"
rg -i '\btarget' --type ts

Length of output: 247179

apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/deployments/[deploymentSlug]/variables/VariableValueDropdown.tsx (2)

Line range hint 28-31: Consider updating imported validators

The imported validators still use target-centric naming which could cause confusion.

Consider updating the imports to use resource-centric naming:

 import {
   defaultCondition,
-  isValidTargetCondition,
-  targetCondition,
+  isValidResourceCondition,
+  resourceCondition,
 } from "@ctrlplane/validators/targets"; // Consider renaming this file as well

Line range hint 156-156: Update TargetConditionRender component name

The TargetConditionRender component should be renamed to maintain consistency with the resource-centric model.

Consider renaming the component and updating its import:

-import { TargetConditionRender } from "~/app/[workspaceSlug]/_components/target-condition/TargetConditionRender";
+import { ResourceConditionRender } from "~/app/[workspaceSlug]/_components/resource-condition/ResourceConditionRender";

And its usage:

-<TargetConditionRender
+<ResourceConditionRender
   condition={value ?? defaultCondition}
   onChange={onChange}
 />
packages/db/src/schema/target.ts (3)

72-82: Consider updating type names for consistency

While the table has been renamed to resource, the type names still use "Target" (e.g., Target, InsertTarget). Consider renaming these to maintain consistency with the new resource-centric model.

-export type Target = InferSelectModel<typeof resource>;
-export type InsertTarget = InferInsertModel<typeof resource>;
+export type Resource = InferSelectModel<typeof resource>;
+export type InsertResource = InferInsertModel<typeof resource>;

Line range hint 200-234: Consider renaming condition-related types and functions

For consistency with the resource-centric model, consider renaming:

  • TargetFilterType to ResourceFilterType
  • targetMatchesMetadata to resourceMatchesMetadata

Line range hint 1-293: Consider a comprehensive type renaming strategy

While the database schema changes from target to resource are thorough and correct, there's an opportunity to improve the codebase's consistency by updating all related type names. This would involve:

  1. Creating a migration plan for dependent code
  2. Updating all type names from Target* to Resource*
  3. Updating related validator types in @ctrlplane/validators
  4. Maintaining temporary type aliases if needed for backward compatibility

This would complete the transition to a fully resource-centric model.

packages/db/src/schema/environment.ts (1)

41-43: Address naming inconsistency between resource/target

While the field has been renamed to resourceFilter, it still uses TargetCondition type. This creates an inconsistency in the naming convention. Consider updating the related types and validators for consistency:

  • TargetConditionResourceCondition
  • isValidTargetConditionisValidResourceCondition
packages/api/src/router/environment.ts (1)

225-230: Consider renaming targetMatchesMetadata function

While the code has been updated to use resourceFilter, the targetMatchesMetadata function name still uses the old terminology. Consider renaming it to resourceMatchesMetadata for consistency.

apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/deployments/[deploymentSlug]/releases/[versionId]/TargetReleaseTable.tsx (1)

Line range hint 1-476: File name and component should be renamed to align with resource-centric model

Based on the PR objectives to transition from target-centric to resource-centric model, this file needs comprehensive renaming:

  1. The file should be renamed from TargetReleaseTable.tsx to ResourceReleaseTable.tsx
  2. The component types and names should be updated:
    • TargetReleaseTablePropsResourceReleaseTableProps
    • TargetReleaseTableResourceReleaseTable
  3. Internal variable names should reflect the new terminology:
    • triggersByTargettriggersByResource
    • expandedTargetsexpandedResources
    • switchTargetExpandedStateswitchResourceExpandedState
    • targetsresources

Would you like me to generate a comprehensive diff for these changes?

packages/api/src/router/target-provider.ts (1)

Line range hint 158-169: Inconsistent parameter naming: targetProviderId should be resourceProviderId

In the update procedure, the parameter targetProviderId is still used. Given the shift to a resource-centric model, consider renaming targetProviderId to resourceProviderId in the input schema and throughout the function for consistency.

packages/job-dispatch/src/target.ts (6)

30-30: Consider renaming getExistingTargetsForProvider to getExistingResourcesForProvider

Since this function now operates on the resource entity, renaming it would improve code clarity and consistency with the new model.

Apply this diff to rename the function:

-const getExistingTargetsForProvider = (db: Tx, providerId: string) =>
+const getExistingResourcesForProvider = (db: Tx, providerId: string) =>

Line range hint 33-58: Rename dispatchNewTargets to dispatchNewResources

This function now deals with resource entities. Renaming it and related variables enhances clarity and consistency.

Apply this diff:

-const dispatchNewTargets = async (db: Tx, newTargets: Target[]) => {
+const dispatchNewResources = async (db: Tx, newResources: Resource[]) => {
   const [firstTarget] = newTargets;
-  if (firstTarget == null) return;
+  const [firstResource] = newResources;
+  if (firstResource == null) return;

-  const workspaceId = firstTarget.workspaceId;
+  const workspaceId = firstResource.workspaceId;

Update all occurrences of newTargets to newResources within the function and adjust any function calls accordingly.


Line range hint 61-108: Rename upsertTargetVariables to upsertResourceVariables

To reflect the shift from target to resource, renaming this function and its internal variables improves readability and maintainability.

Apply this diff:

-const upsertTargetVariables = async (
+const upsertResourceVariables = async (
   tx: Tx,
   targets: Array<
     Target & {
       variables?: Array<{ key: string; value: any; sensitive: boolean }>;
     }
   >,
 ) => {
-  const existingTargetVariables = await tx
+  const existingResourceVariables = await tx
     .select()
     .from(resourceVariable)
     .where(
       inArray(
         resourceVariable.resourceId,
-        targets.map((t) => t.id),
+        resources.map((r) => r.id),
       ),
     )
     .catch((err) => {
-      log.error("Error fetching existing target metadata", { error: err });
+      log.error("Error fetching existing resource variables", { error: err });
       throw err;
     });

Ensure to update all references to targets to resources within the function.


Line range hint 110-149: Rename upsertTargetMetadata to upsertResourceMetadata

Updating the function name and related variables ensures consistency with the new resource model.

Apply this diff:

-const upsertTargetMetadata = async (
+const upsertResourceMetadata = async (
   tx: Tx,
   targets: Array<Target & { metadata?: Record<string, string> }>,
 ) => {
-  const existingTargetMetadata = await tx
+  const existingResourceMetadata = await tx
     .select()
     .from(resourceMetadata)
     .where(
       inArray(
         resourceMetadata.resourceId,
-        targets.map((t) => t.id),
+        resources.map((r) => r.id),
       ),
     )
     .catch((err) => {
-      log.error("Error fetching existing target metadata", { error: err });
+      log.error("Error fetching existing resource metadata", { error: err });
       throw err;
     });

Update all references to targets to resources within the function to maintain consistency.


Line range hint 201-327: Rename upsertTargets to upsertResources and update related variables

Considering the shift from target to resource, renaming this function and internal variables enhances code clarity and aligns with the data model.

Apply this diff:

-export const upsertTargets = async (
+export const upsertResources = async (
   tx: Tx,
-  targetsToInsert: Array<
+  resourcesToInsert: Array<
     InsertTarget & {
       metadata?: Record<string, string>;
       variables?: Array<{ key: string; value: any; sensitive: boolean }>;
     }
   >,
 ) => {
   try {
     log.info("Upserting targets", {
-      targetsToInsertCount: targetsToInsert.length,
+      resourcesToInsertCount: resourcesToInsert.length,
     });
-    const targetsBeforeInsertPromises = _.chain(targetsToInsert)
+    const resourcesBeforeInsertPromises = _.chain(resourcesToInsert)
       .groupBy((t) => t.providerId)
       .filter((t) => t[0]?.providerId != null)
       .map(async (targets) => {
         const providerId = targets[0]?.providerId;

Continue updating all variables from targets... to resources... throughout the function, including targetsBeforeInsert, newTargets, targetsToDelete, and so on.


Line range hint 87-87: Update log messages to reflect resource instead of target

Throughout the code, error log messages still reference target instead of resource. For consistency and clarity, please update log messages to reflect the new terminology.

Apply this diff:

-log.error("Error fetching existing target metadata", { error: err });
+log.error("Error fetching existing resource metadata", { error: err });

-log.error("Error inserting target variables", { error: err });
+log.error("Error inserting resource variables", { error: err });

-log.error("Error deleting target variables", { error: err });
+log.error("Error deleting resource variables", { error: err });

-log.error("Error inserting target metadata", { error: err });
+log.error("Error inserting resource metadata", { error: err });

-log.error("Error deleting target metadata", { error: err });
+log.error("Error deleting resource metadata", { error: err });

-log.error("Error inserting targets", { error: err });
+log.error("Error inserting resources", { error: err });

-log.error("Error upserting targets", { error: err });
+log.error("Error upserting resources", { error: err });

-log.error("Error dispatching new targets", { error: err });
+log.error("Error dispatching new resources", { error: err });

-log.error("Error deleting targets", { error: err });
+log.error("Error deleting resources", { error: err });

Ensure all log messages throughout the file use resource to maintain consistency.

Also applies to: 113-113, 129-129, 147-147, 173-173, 195-195, 257-257, 271-271, 320-320

packages/auth/src/utils/rbac.ts (1)

Line range hint 406-421: Update scope handlers to match renamed functions

After renaming the functions, update the scopeHandlers mapping to use the new function names. For example, change:

-resource: getTargetScopes,
-resourceView: getTargetViewScopes,
-resourceProvider: getTargetProviderScopes,
+resource: getResourceScopes,
+resourceView: getResourceViewScopes,
+resourceProvider: getResourceProviderScopes,
packages/api/src/router/deployment.ts (4)

27-27: Consider renaming 'targetMatchesMetadata' to 'resourceMatchesMetadata' for consistency

The function targetMatchesMetadata is still in use after the transition from target to resource. Renaming it to resourceMatchesMetadata would enhance consistency across the codebase and improve readability.


197-197: Rename variable 'targetId' to 'resourceId' for clarity

The property targetId is assigned the value releaseJobTrigger.resourceId. To reflect the updated terminology from target to resource, consider renaming targetId to resourceId.


475-475: Update property name from 'targetId' to 'resourceId'

The property targetId is set to row.resource.id. Renaming it to resourceId will maintain consistency with the rest of the codebase that now uses the term resource.


443-443: Function name 'targetMatchesMetadata' may need updating

The function targetMatchesMetadata is used in conjunction with resourceFilter. For consistency, consider renaming the function to resourceMatchesMetadata.

packages/api/src/router/target.ts (4)

Line range hint 186-190: Ensure schema.targetMatchesMetadata is compatible with resource.

In this section, schema.targetMatchesMetadata is used with schema.resource. Verify that this function operates correctly with the resource schema or consider renaming it to schema.resourceMatchesMetadata to reflect the new naming convention and prevent potential mismatches.


277-304: Consider renaming targetQuery to resourceQuery for consistency.

To maintain consistency with the resource-centric model, renaming the targetQuery function to resourceQuery would enhance code readability and prevent confusion.


304-307: Rename targetRouter to resourceRouter for clarity.

Given the shift from a target-centric model to a resource-centric model, renaming targetRouter to resourceRouter will align the naming conventions throughout the codebase and improve overall maintainability.


Line range hint 322-332: Update variable names to reflect the resource-centric model.

Within the byId procedure, consider renaming variables such as t to more descriptive names like resource to enhance code clarity and align with the new resource-focused terminology.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 900412a and 981d031.

📒 Files selected for processing (56)
  • apps/event-worker/src/target-scan/gke.ts (3 hunks)
  • apps/event-worker/src/target-scan/index.ts (2 hunks)
  • apps/webservice/src/app/[workspaceSlug]/_components/environment-drawer/Filter.tsx (2 hunks)
  • apps/webservice/src/app/[workspaceSlug]/_components/job-condition/JobTargetConditionRender.tsx (1 hunks)
  • apps/webservice/src/app/[workspaceSlug]/_components/target-drawer/CreateTargetVariableDialog.tsx (1 hunks)
  • apps/webservice/src/app/[workspaceSlug]/_components/target-drawer/EditTargetVariableDialog.tsx (1 hunks)
  • apps/webservice/src/app/[workspaceSlug]/_components/target-drawer/TargetVariableDropdown.tsx (1 hunks)
  • apps/webservice/src/app/[workspaceSlug]/systems/SystemActionsDropdown.tsx (1 hunks)
  • apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/_components/variables/VariableInputs.tsx (1 hunks)
  • apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/deployments/TableDeployments.tsx (1 hunks)
  • apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/deployments/[deploymentSlug]/page.tsx (4 hunks)
  • apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/deployments/[deploymentSlug]/releases/[versionId]/TargetReleaseTable.tsx (1 hunks)
  • apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/deployments/[deploymentSlug]/variables/VariableValueDropdown.tsx (2 hunks)
  • apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/deployments/[deploymentSlug]/variables/page.tsx (4 hunks)
  • apps/webservice/src/app/api/v1/job-agents/[agentId]/jobs/running/route.ts (2 hunks)
  • apps/webservice/src/app/api/v1/jobs/[jobId]/route.ts (3 hunks)
  • apps/webservice/src/app/api/v1/target-providers/[providerId]/set/route.ts (2 hunks)
  • apps/webservice/src/app/api/v1/targets/[targetId]/route.ts (3 hunks)
  • apps/webservice/src/app/api/v1/workspaces/[workspaceId]/target-providers/name/[name]/route.ts (2 hunks)
  • apps/webservice/src/app/api/v1/workspaces/[workspaceId]/targets/identifier/[identifier]/route.ts (5 hunks)
  • packages/api/src/router/deployment-variable.ts (10 hunks)
  • packages/api/src/router/deployment.ts (8 hunks)
  • packages/api/src/router/environment.ts (3 hunks)
  • packages/api/src/router/job.ts (6 hunks)
  • packages/api/src/router/release-deploy.ts (2 hunks)
  • packages/api/src/router/release.ts (2 hunks)
  • packages/api/src/router/target-metadata-group.ts (7 hunks)
  • packages/api/src/router/target-provider.ts (7 hunks)
  • packages/api/src/router/target.ts (19 hunks)
  • packages/api/src/router/workspace-integrations.ts (2 hunks)
  • packages/api/src/router/workspace.ts (2 hunks)
  • packages/auth/src/utils/rbac.ts (6 hunks)
  • packages/db/drizzle/0037_giant_stardust.sql (1 hunks)
  • packages/db/drizzle/meta/_journal.json (1 hunks)
  • packages/db/src/schema/deployment-variables.ts (2 hunks)
  • packages/db/src/schema/environment.ts (2 hunks)
  • packages/db/src/schema/job.ts (2 hunks)
  • packages/db/src/schema/release.ts (2 hunks)
  • packages/db/src/schema/target-agent.ts (1 hunks)
  • packages/db/src/schema/target-group.ts (2 hunks)
  • packages/db/src/schema/target-provider.ts (3 hunks)
  • packages/db/src/schema/target-session.ts (1 hunks)
  • packages/db/src/schema/target.ts (9 hunks)
  • packages/events/src/triggers/deployment-deleted.ts (2 hunks)
  • packages/events/src/triggers/environment-deleted.ts (3 hunks)
  • packages/events/src/triggers/target-deleted.ts (1 hunks)
  • packages/job-dispatch/src/__test__/job-variables-deployment.test.ts (11 hunks)
  • packages/job-dispatch/src/environment-creation.ts (3 hunks)
  • packages/job-dispatch/src/job-variables-deployment/job-variables-deployment.ts (2 hunks)
  • packages/job-dispatch/src/job-variables-deployment/utils.ts (4 hunks)
  • packages/job-dispatch/src/lock-checker.ts (2 hunks)
  • packages/job-dispatch/src/pending-job-checker.ts (3 hunks)
  • packages/job-dispatch/src/policies/gradual-rollout.ts (1 hunks)
  • packages/job-dispatch/src/policies/release-dependency.ts (3 hunks)
  • packages/job-dispatch/src/release-job-trigger.ts (4 hunks)
  • packages/job-dispatch/src/target.ts (13 hunks)
🔇 Additional comments (96)
packages/db/src/schema/target-agent.ts (1)

5-9: LGTM! Table definition changes are consistent

The changes correctly implement the transition from target to resource:

  • Table renamed from "target_session" to "resource_session"
  • Foreign key column renamed from targetId to resourceId
  • Reference updated to point to resource.id
packages/job-dispatch/src/lock-checker.ts (1)

2-2: LGTM: Import statement correctly updated

The import statement has been properly updated to use resource instead of target, maintaining consistency with the new resource-centric model.

packages/db/src/schema/target-group.ts (1)

Line range hint 8-19: LGTM! Table definition correctly renamed to follow resource-centric model.

The table definition has been properly renamed from target_metadata_group to resource_metadata_group while maintaining all the existing schema structure and constraints.

packages/events/src/triggers/deployment-deleted.ts (1)

33-35: LGTM: Database query updated to use resource table

The change from db.query.target to db.query.resource is correct and aligns with the resource-centric model.

Let's verify the schema helper function has been updated:

#!/bin/bash
# Description: Verify that the targetMatchesMetadata helper has been renamed
# Expected: Should find updated references to resourceMatchesMetadata

# Check for the helper function
rg "Matches.*etadata.*=.*" "@ctrlplane/db/schema"
apps/webservice/src/app/api/v1/workspaces/[workspaceId]/target-providers/name/[name]/route.ts (3)

38-42: LGTM! Database operations correctly updated

The database operations have been properly updated to use resourceProvider while maintaining the existing functionality.


Line range hint 1-48: File path needs to be updated for consistency

The file is still located under the target-providers directory despite the transition to resource-centric naming. Consider moving this file to resource-providers to maintain consistency.

#!/bin/bash
# Check for other files/references using the old path pattern
rg -l "target-providers/name/\[name\]"

# Check for any remaining "target-provider" references in the codebase
rg -l "target-provider"

This change will require:

  1. Moving the file to the new location
  2. Updating any references to this API endpoint
  3. Ensuring proper handling of backward compatibility if this is a public API

Would you like assistance in creating a migration plan for this change?


7-8: Verify permission enum naming consistency

While the schema import has been updated to use resourceProvider, the Permission.TargetGet enum still uses the old "Target" prefix. This should be updated to maintain consistency with the resource-centric naming.

✅ Verification successful

Permission enum naming is consistent
All instances of Permission.Target have been updated to Permission.Resource.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for any remaining "Target" prefixes in permission enums
rg -l "enum.*Permission.*Target" 

Length of output: 128


Script:

#!/bin/bash
# Check for any remaining "Target" prefixes in permission enums
rg 'enum.*Permission.*Target'

Length of output: 31

apps/webservice/src/app/api/v1/job-agents/[agentId]/jobs/running/route.ts (2)

12-12: LGTM: Schema import updated correctly

The import change from target to resource aligns with the PR objective of transitioning to a resource-centric model.


30-30: LGTM: Database join updated correctly

The left join operation has been properly updated to use the new resource table instead of the previous target table.

packages/job-dispatch/src/pending-job-checker.ts (2)

15-15: LGTM: Consistent schema field renaming

The change from targetId to resourceId in the selectDistinctOn clause is consistent with the resource-centric model transition.


49-49: LGTM: Consistent filter condition update

The filter predicate correctly uses resourceId for comparison, maintaining the logical integrity of the triple-key match.

packages/events/src/triggers/target-deleted.ts (1)

29-31: Update type definitions to match resource-centric model

The filter mapping has been updated, but the types TargetCondition and TargetFilterType (used below) still reference the old target-centric model.

Let's check if these types have been updated in their definition files:

packages/db/src/schema/target-provider.ts (3)

Line range hint 17-29: Verify database migration for table renaming

The table definition looks correct, but ensure there's a corresponding migration script to handle the rename from "target_provider" to "resource_provider".


Line range hint 40-62: Update remaining target references and verify constraints

  1. The table and foreign key changes look good, but function and type names need updating for consistency:
-export const createTargetProviderGoogle = createInsertSchema(
+export const createResourceProviderGoogle = createInsertSchema(
   resourceProviderGoogle,
   { projectIds: z.array(z.string().min(1)).min(1) },
 ).omit({ id: true });

-export const updateTargetProviderGoogle = createTargetProviderGoogle.partial();
+export const updateResourceProviderGoogle = createResourceProviderGoogle.partial();

-export type TargetProviderGoogle = InferSelectModel<
+export type ResourceProviderGoogle = InferSelectModel<
   typeof resourceProviderGoogle
 >;
  1. Verify the foreign key constraint changes:

14-14: Verify the import path consistency

The import path ./target.js seems inconsistent with the resource-centric model transition.

packages/events/src/triggers/environment-deleted.ts (2)

22-22: LGTM: Schema reference correctly updated

The schema reference has been properly updated from targetFilter to resourceFilter, maintaining consistency with the renaming pattern.


32-32: LGTM: Environment filter mapping updated correctly

The environment filter mapping has been properly updated to use resourceFilter, maintaining the same functionality while following the new naming convention.

packages/db/drizzle/0037_giant_stardust.sql (4)

7-8: LGTM! Column renames are consistent with the resource-centric model

The column renames from target_id to resource_id are properly ordered and align with the PR objectives.


39-40: LGTM! Indexes are properly defined

The unique composite indexes are well-structured with:

  • Appropriate use of IF NOT EXISTS
  • Correct column ordering for the use case

15-37: ⚠️ Potential issue

Review ON DELETE behavior consistency

There's an inconsistency in ON DELETE behavior across foreign key constraints:

  • resource_session: ON DELETE no action
  • resource_metadata and resource_variable: ON DELETE cascade

Please verify if this difference is intentional, as it could lead to unexpected behavior when deleting resources.


9-14: Verify data integrity before applying migration

While the constraint and index drops are properly ordered, ensure that existing data maintains referential integrity before applying this migration.

apps/webservice/src/app/api/v1/target-providers/[providerId]/set/route.ts (1)

62-64: LGTM! Database query changes are consistent

The changes to use resourceProvider in the database query and join conditions are correctly implemented.

packages/job-dispatch/src/job-variables-deployment/utils.ts (1)

32-33: Verify schema migration for target to resource table rename

The table reference change from SCHEMA.target to SCHEMA.resource looks correct. However, we should ensure that the corresponding schema migration exists and handles data transfer appropriately.

apps/webservice/src/app/api/v1/workspaces/[workspaceId]/targets/identifier/[identifier]/route.ts (2)

17-20: LGTM: Database queries correctly updated to use resource schema

The database queries have been properly updated to use the new resource schema while maintaining the same query structure and conditions.

Also applies to: 32-35


94-94: LGTM: Resource deletion correctly implemented

The deletion operation has been properly updated to use the resource schema.

apps/event-worker/src/target-scan/index.ts (1)

Line range hint 1-83: Verify event handling compatibility

Since this file handles events and the event channel is still named TargetScan, verify that the event handling system (producers/consumers) is compatible with these changes.

#!/bin/bash
# Check for event definitions and usage
rg -A 5 "Channel\.TargetScan" --type ts
rg -A 5 "TargetScanEvent" --type ts

# Check for any queue consumers/producers
rg -A 5 "targetScanQueue" --type ts
packages/job-dispatch/src/environment-creation.ts (4)

17-18: LGTM: Variable renaming is consistent with resource-centric model

The renaming from targetFilter to resourceFilter aligns well with the broader refactoring effort.


49-49: LGTM: Consistent variable renaming

The change from targets to resources maintains the same logic while aligning with the new terminology.


86-86: Verify method chain rename consistency

The method chain still uses .targets() instead of .resources(). This might indicate a missed rename in the builder pattern.


40-46: Verify schema function rename consistency

While the table has been renamed from target to resource, the schema function targetMatchesMetadata still uses the old terminology. This might indicate a missed rename.

apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/deployments/[deploymentSlug]/variables/page.tsx (3)

Line range hint 44-53: LGTM: Consistent property renaming

The changes correctly update the null check and filter hash generation to use resourceFilter instead of targetFilter, maintaining the same logical flow.


59-59: LGTM: Filter condition updated correctly

The filter condition correctly uses the new resourceFilter property while maintaining the existing filter logic.


79-79: LGTM: Rest filters mapping updated appropriately

The mapping of rest filters correctly uses the new resourceFilter property while preserving the existing default value handling logic.

packages/api/src/router/workspace-integrations.ts (2)

8-9: LGTM! Import changes align with resource-centric model

The schema imports have been correctly updated to reflect the transition from target-centric to resource-centric model.


101-106: LGTM! Query changes correctly implement resource-centric model

The database query has been properly updated to use the new resource-centric schema tables and join conditions.

packages/job-dispatch/src/job-variables-deployment/job-variables-deployment.ts (2)

37-37: 🛠️ Refactor suggestion

Maintain consistency in resource-centric naming

While the ID parameter has been renamed to resourceId, the surrounding code still uses target-centric terminology. For complete alignment with the resource-centric model, consider renaming:

  • getTarget utility function to getResource
  • jobTarget variable to jobResource

Line range hint 1-170: Consider comprehensive resource-centric renaming

While the immediate changes align with the resource-centric model, there are several other occurrences of target-centric terminology throughout the file that should be updated for consistency:

  1. Type definitions:

    • schema.Target should become schema.Resource
    • TargetVariable should become ResourceVariable
  2. Function names and parameters:

    • getTargetVariableValue should become getResourceVariableValue
    • targetVariableValue should become resourceVariableValue

This would ensure complete alignment with the resource-centric model across the codebase.

apps/webservice/src/app/api/v1/jobs/[jobId]/route.ts (2)

14-15: LGTM: Import changes align with resource table renaming.

The new imports for resource and resourceMetadata correctly reflect the transition from target-centric to resource-centric model.


Line range hint 131-137: Verify API documentation and client compatibility.

The response structure changes from target to resource will be a breaking change for API consumers.

Let's check for API documentation and potential client usage:

packages/api/src/router/release-deploy.ts (2)

12-12: LGTM: Import change aligns with schema refactoring

The addition of the resource import from the schema is consistent with the transition from target to resource-centric model.


Line range hint 91-126: Complete the target-to-resource terminology transition

There are several instances where the old "target" terminology is still being used despite the transition to resources:

  1. The procedure name is still toTarget
  2. The input parameter is still targetId
  3. Permission check uses TargetUpdate but references resource type
  4. Variable name t could be more descriptive

Consider applying these changes for consistency:

-  toTarget: protectedProcedure
+  toResource: protectedProcedure
     .meta({
       authorizationCheck: ({ canUser, input }) =>
         canUser
-          .perform(Permission.ReleaseGet, Permission.TargetUpdate)
+          .perform(Permission.ReleaseGet, Permission.ResourceUpdate)
           .on(
             { type: "release", id: input.releaseId },
-            { type: "resource", id: input.targetId },
+            { type: "resource", id: input.resourceId },
           ),
     })
     .input(
       z.object({
-        targetId: z.string().uuid(),
+        resourceId: z.string().uuid(),
         releaseId: z.string().uuid(),
         environmentId: z.string().uuid(),
         isForcedRelease: z.boolean().optional(),
       }),
     )
     .mutation(async ({ ctx, input }) => {
-      const t = await ctx.db
+      const resource = await ctx.db
         .select()
         .from(resource)
-        .where(eq(resource.id, input.targetId))
+        .where(eq(resource.id, input.resourceId))
         .then(takeFirstOrNull);

Let's verify if there are any remaining "target" references that need to be updated:

packages/job-dispatch/src/policies/release-dependency.ts (2)

66-66: LGTM! Condition updated correctly.

The relationship exclusion condition has been properly updated to use resourceId.


86-86: LGTM! Array construction updated properly.

The unique ID collection logic has been correctly updated to use resourceId.

apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/deployments/[deploymentSlug]/page.tsx (2)

Line range hint 46-55: LGTM! Consistent resource-centric naming.

The changes to null checking and filter hash generation maintain the same logic while adopting the new resource-centric terminology.


36-36: Consider updating type names for consistency with resource-centric model.

While the change from targetFilter to resourceFilter aligns with the resource-centric transition, the types (TargetFilterType, TargetOperator) still use the old target-centric naming convention.

Let's check if these types are being renamed elsewhere in the codebase:

packages/db/drizzle/meta/_journal.json (2)

263-269: LGTM! Migration entry follows the established pattern.

The new migration entry is properly structured and maintains consistency with existing entries. The sequential indexing and timestamps are correct.


263-269: Verify the migration content for table renaming.

Since this PR involves renaming resource tables, let's verify the actual migration SQL.

✅ Verification successful

Migration Content Verified Successfully.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the migration content for table renaming changes

# Look for the migration file corresponding to this journal entry
fd -t f "0037_giant_stardust" packages/db/drizzle/

# If found, examine its content for table renaming operations
if [ $? -eq 0 ]; then
  echo "Migration file content:"
  cat $(fd -t f "0037_giant_stardust" packages/db/drizzle/)
fi

# Look for any references to 'target' or 'resource' in SQL files
echo "Searching for target/resource references in migrations:"
rg -t sql "ALTER TABLE.*target|RENAME.*target|ALTER TABLE.*resource|RENAME.*resource" packages/db/drizzle/

Length of output: 15045

packages/api/src/router/workspace.ts (2)

16-16: LGTM: Import changes align with resource-centric model transition

The addition of the resource import is consistent with the codebase's transition from target-centric to resource-centric model.


226-229: Verify Permission enum updates

Let's verify if the Permission enum has been updated to include the new resource-based permissions.

✅ Verification successful

Permission enum updates verified

All Permission.Target* permissions used in the codebase are correctly defined in the Permission enum.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if Permission enum includes resource-based permissions

# Look for Permission enum definition
rg -A 10 "enum Permission" --type ts

# Check for any remaining target-related permissions
rg "Permission\.Target" --type ts

Length of output: 4220


Script:

#!/bin/bash
# Description: Extract the full definition of the Permission enum

rg -A 50 "enum Permission" --type ts packages/validators/src/auth/index.ts

Length of output: 1658

apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/_components/variables/VariableInputs.tsx (1)

129-130: LGTM, but terminology is inconsistent.

The change from targetFilter to resourceFilter is correct, but it creates a mix of terminology in the codebase where we're using both "target" and "resource" concepts.

Let's verify the consistency of this change across related files:

packages/db/src/schema/job.ts (1)

221-221: Consider updating JobFilterType enum name for consistency.

While the code correctly uses resource.id, the enum type JobFilterType.JobTarget still references "Target". This seems inconsistent with the resource-centric model transition.

#!/bin/bash
# Description: Find all occurrences of JobFilterType.JobTarget to ensure consistent renaming

# Search for JobFilterType enum definition
ast-grep --pattern 'export const JobFilterType = $$$'

# Search for all uses of JobTarget in enum or type definitions
rg "JobTarget" -A 5 -B 5
apps/webservice/src/app/[workspaceSlug]/_components/environment-drawer/Filter.tsx (1)

127-127: ⚠️ Potential issue

Inconsistent terminology between UI and backend

While the backend has transitioned from targetFilter to resourceFilter, the UI components, form fields, and types still use the "target" terminology. This creates a confusing mismatch between the presentation and data layers.

Consider a more comprehensive rename to maintain consistency:

- const filterForm = z.object({
-   targetFilter: targetCondition.optional(),
- });
+ const filterForm = z.object({
+   resourceFilter: targetCondition.optional(),
+ });

  const form = useForm({
    schema: filterForm,
-   defaultValues: { targetFilter: getFilter(environment.resourceFilter) },
+   defaultValues: { resourceFilter: getFilter(environment.resourceFilter) },
  });

- const { targetFilter } = form.watch();
+ const { resourceFilter } = form.watch();

- const filter = targetFilter ?? undefined;
+ const filter = resourceFilter ?? undefined;

  // Update the mutation data
  onSubmit.mutateAsync({
    id: environment.id,
-   data: { ...data, resourceFilter: targetFilter ?? null },
+   data: { ...data, resourceFilter: resourceFilter ?? null },
  })

Additionally, consider renaming:

  1. The TargetViewsCombobox component to ResourceViewsCombobox
  2. The TargetConditionRender component to ResourceConditionRender
  3. Update all related prop names and types

Let's verify the extent of the target-to-resource rename across the codebase:

Also applies to: 144-144

✅ Verification successful

Inconsistent terminology between UI and backend needs to be addressed

The review comment correctly identifies that while the backend has transitioned from targetFilter to resourceFilter, the UI form fields still use the old terminology. This should be fixed to maintain consistency with the broader target-to-resource rename throughout the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for remaining "target" references that might need updating
rg -i "target" --type tsx --type ts

# Search for new "resource" terminology to ensure consistency
rg -i "resource" --type tsx --type ts

Length of output: 129


Script:

#!/bin/bash
# Search for remaining "target" references that might need updating
rg -i "target" --glob "*.tsx" --glob "*.ts"

# Search for new "resource" terminology to ensure consistency
rg -i "resource" --glob "*.tsx" --glob "*.ts"

Length of output: 347553

apps/event-worker/src/target-scan/gke.ts (1)

243-243: LGTM! Parameter renaming aligns with resource-centric model.

The changes correctly update the parameter from targetProviderId to resourceProviderId consistently across all function calls.

Also applies to: 275-275, 286-286

packages/db/src/schema/release.ts (1)

188-190: LGTM! Field rename aligns with the resource-centric model.

The renaming of the field from targetId to resourceId and updating its reference to resource.id is consistent with the refactoring goal. The cascade delete constraint is properly maintained.

apps/webservice/src/app/[workspaceSlug]/systems/[systemSlug]/deployments/[deploymentSlug]/variables/VariableValueDropdown.tsx (1)

Line range hint 1-1: Verify the impact of renaming across the codebase

Let's ensure all related components and files are updated consistently.

✅ Verification successful

No Impact Found

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for remaining target-related terms that need to be updated

# Check for TargetConditionRender component usage
echo "Checking TargetConditionRender component usage:"
rg "TargetConditionRender"

# Check for targetFilter references
echo -e "\nChecking targetFilter references:"
rg "targetFilter"

# Check for target-condition directory
echo -e "\nChecking target-condition directory:"
fd "target-condition"

# Check for validators/targets references
echo -e "\nChecking validators/targets references:"
rg -g "*.{ts,tsx}" "from.*validators/targets"

Length of output: 17533


Script:

#!/bin/bash
# Description: Check if 'schema' is used in files that utilize 'TargetConditionRender' or 'targetFilter'

# Find files that import 'schema'
echo "Searching for 'schema' usage in relevant files:"
fd ".*\.tsx?$" | xargs grep -l "import .*schema"

# Within those files, check for usage of 'TargetConditionRender' or 'targetFilter'
echo -e "\nChecking for 'TargetConditionRender' or 'targetFilter' usage alongside 'schema':"
fd ".*\.tsx?$" | xargs grep -E "schema|TargetConditionRender|targetFilter"

Length of output: 114177

packages/db/src/schema/target.ts (4)

Line range hint 37-61: LGTM: Table definition correctly renamed while maintaining structure

The table definition has been properly renamed from target to resource while maintaining all the necessary columns, constraints, and relationships. The foreign key reference to resourceProvider has been correctly updated.


118-139: LGTM: Metadata table and relations properly renamed

The metadata table and its relations have been correctly renamed while maintaining the existing structure and constraints.


236-293: Update relationship and variable type names

Consider renaming the following types to align with the resource-centric model:

  • TargetRelationshipResourceRelationship
  • TargetVariableResourceVariable

Also, consider updating the create/update function names:

  • createTargetRelationshipcreateResourceRelationship
  • createTargetVariablecreateResourceVariable
#!/bin/bash
# Check for impacts of renaming these types
rg "TargetRelationship|TargetVariable" --type typescript

# Check for any remaining "target" references in schema files
fd "schema" --type f --exec rg "target" --ignore-case {}

Line range hint 100-116: Update condition type to match resource naming

The filter field in resourceView still uses the TargetCondition type. Consider updating this type name to maintain consistency with the resource-centric model.

packages/api/src/router/environment.ts (3)

21-21: LGTM: Schema import aligns with resource-centric model transition

The addition of the resource schema import is consistent with the PR's objective of transitioning from target-centric to resource-centric model.


236-244: Verify the workspaceId filter addition

The addition of the workspaceId check in the resource query is a significant change. Please verify that this additional filter:

  1. Doesn't exclude valid resources that should be included
  2. Is consistent with how workspace filtering is handled in other similar queries
#!/bin/bash
# Description: Check how workspaceId filtering is implemented across the codebase

# Search for similar resource/target queries to compare workspace filtering
echo "Checking resource/target query patterns:"
ast-grep --pattern 'from(resource)
  .where(
    $$$
    workspaceId
    $$$
  )'

158-164: Verify consistent usage of resource terminology

The query has been updated to use the new resource-centric model, but let's verify that all related references have been updated consistently.

packages/api/src/router/release.ts (3)

29-29: LGTM: Import addition is correct

The addition of the resource import aligns with the schema refactoring from target to resource.


107-107: Verify complete schema migration

The join condition has been correctly updated to use the resource table. Let's verify that all related queries have been updated consistently.


Line range hint 119-119: Breaking Change: API Response Structure

The property name change from target to resource in the response object is a breaking change that will affect API clients. Please ensure that:

  1. All API clients are updated to handle the new property name
  2. This change is documented in the API changelog
  3. The version number is bumped appropriately
packages/job-dispatch/src/__test__/job-variables-deployment.test.ts (5)

47-47: LGTM: Consistent rename from targetId to resourceId

The change aligns with the PR objective of transitioning to a resource-centric model.


81-81: LGTM: Consistent rename of filter properties

The changes to resourceFilter are consistently applied across all variable value definitions.

Also applies to: 87-87, 93-93


240-240: LGTM: Environment resource filter updates

The changes consistently rename the filter property across all environment test fixtures.

Also applies to: 308-308, 375-375, 442-442, 509-509, 604-604, 699-699


571-571: LGTM: Target variable property updates

The resourceId property is consistently updated in both sensitive and non-sensitive target variable test cases.

Also applies to: 666-666


Line range hint 1-761: Verify remaining target references

While the property renames look good, we should verify that no target-related terminology was missed in variable names, comments, or test descriptions.

packages/job-dispatch/src/release-job-trigger.ts (1)

18-18: 🛠️ Refactor suggestion

Rename targetMatchesMetadata to resourceMatchesMetadata for consistency

In line with the refactoring from 'target' to 'resource', the imported function targetMatchesMetadata should be renamed to resourceMatchesMetadata for clarity and consistency.

Apply this diff to update the import:

 import {
   deployment,
   environment,
   job,
   jobAgent,
   release,
   releaseJobTrigger,
   resource,
   system,
-  targetMatchesMetadata,
+  resourceMatchesMetadata,
 } from "@ctrlplane/db/schema";

Likely invalid or redundant comment.

packages/api/src/router/target-provider.ts (9)

30-35: LGTM

The query in the byWorkspaceId procedure correctly updates references to resourceProvider and resourceProviderGoogle, aligning with the new resource-centric model.


41-51: LGTM

The providerCounts query correctly updates to use resource and resourceProvider, ensuring accurate counting of resources per provider.


55-67: LGTM

The providerKinds query is appropriately updated to reference resource and resourceProvider. Grouping by kind and version maintains the integrity of the data retrieval.


94-95: LGTM

The byId procedure correctly fetches the resourceProvider by its ID using the updated entity name.


132-132: LGTM

The insertion into resourceProvider correctly reflects the updated model.


137-138: LGTM

The insertion into resourceProviderGoogle accurately assigns the resourceProviderId and aligns with the new data model.


174-178: Duplicate: Inconsistent parameter naming

As previously mentioned, the use of input.targetProviderId should be updated to input.resourceProviderId to maintain consistency with the new resource-centric terminology.


224-225: LGTM

The deletion of resources associated with the provider correctly uses resource and resource.providerId, aligning with the updated model.


228-229: LGTM

The deletion of the resourceProvider is properly executed using the updated entity names.

packages/job-dispatch/src/target.ts (1)

95-95: Confirm encryption logic for sensitive variables

Ensure that the encryption of sensitive variables using variablesAES256().encrypt(JSON.stringify(value)) complies with security best practices.

Run the following script to verify that all sensitive variables are encrypted consistently:

This script checks for the correct encryption pattern across the codebase.

✅ Verification successful

Encryption logic for sensitive variables is properly implemented.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search the codebase for encryption of sensitive variables.

# Search for encryption usage
rg 'variablesAES256\(\)\.encrypt\(JSON\.stringify\('

Length of output: 149

packages/auth/src/utils/rbac.ts (1)

16-19: Approved: Addition of new resource imports

The import statements for resource, resourceMetadataGroup, resourceProvider, and resourceView are appropriately added and align with the resource-centric refactor.

packages/api/src/router/deployment-variable.ts (8)

24-24: Importing 'resource' aligns with the refactoring

The addition of resource to the imports reflects the shift from a target-centric to a resource-centric model.


121-121: Use of environment.resourceFilter ensures consistency

Updating to environment.resourceFilter maintains consistency with the new resource-based approach.


131-131: Correctly mapping conditions using resourceFilter

The expression dep.map((e) => e.resourceFilter).filter(isPresent) appropriately collects resource filters from environments.


220-220: Confirm targetMatchesMetadata function usage

As previously noted, confirm whether targetMatchesMetadata is appropriate for resources or if a resource-specific function should be used.


330-333: Ensure correct function usage with resources

Confirm that targetMatchesMetadata is suitable when used with resources in this context, or consider using an appropriate alternative.


179-181: 🛠️ Refactor suggestion

Rename functions and variables for clarity and consistency

The function getOldTargetFilter and the use of value.resourceFilter mix 'target' and 'resource' terminology. Consider renaming to getOldResourceFilter and updating related variables to reflect the resource-centric model.

Apply this diff to update the function name:

-const getOldTargetFilter = (): TargetCondition | null => {
+const getOldResourceFilter = (): TargetCondition | null => {

And update variable names within the function accordingly.

Likely invalid or redundant comment.


301-302: 🛠️ Refactor suggestion

Rename byTargetId to byResourceId for consistency

The procedure byTargetId operates on resources. Renaming it to byResourceId will enhance clarity and align with the updated terminology.

Apply this diff to rename the procedure:

-export const deploymentVariableRouter = createTRPCRouter({
-  value: valueRouter,
-
-  byTargetId: protectedProcedure
+export const deploymentVariableRouter = createTRPCRouter({
+  value: valueRouter,
+
+  byResourceId: protectedProcedure

Likely invalid or redundant comment.


216-216: Verify the use of targetMatchesMetadata with resources

The function targetMatchesMetadata is used with resources. Ensure this function is intended for resources or replace it with a suitable alternative like resourceMatchesMetadata.

Run the following script to check if a resourceMatchesMetadata function exists:

packages/api/src/router/deployment.ts (1)

429-429: Verify all instances of 'environment.targetFilter' are updated

Ensure that all occurrences of environment.targetFilter have been updated to environment.resourceFilter throughout the codebase to prevent any inconsistencies.

Run the following script to check for any remaining references:

packages/api/src/router/job.ts (5)

47-47: Import Update Aligns with Resource Refactoring

The addition of resource to the imports is appropriate and necessary for the refactoring from target to resource. This ensures that all references to resource are correctly resolved.


69-69: Updated Inner Join to Use 'Resource' Entity

The inner join has been correctly updated to use resource instead of target, aligning with the new data model. This change ensures that the query joins releaseJobTrigger with the resource table based on resourceId.


188-188: Inner Join Updated to Reference 'Resource'

The inner join on resource using releaseJobTrigger.resourceId ensures that the query correctly associates release job triggers with resources. This change is consistent with the shift from target to resource.


437-438: Query Updated to Retrieve Resources

The .from(resource) and .where(inArray(resource.id, allIds)) correctly update the query to select resources based on their IDs. This modification aligns with the refactoring efforts and appears to function as intended.


450-450: Partition Clause Updated with 'Resource' Identifier

The PARTITION BY clause now correctly uses releaseJobTrigger.resourceId in place of targetId, which aligns with the data model changes to use resource. This update ensures correct windowing functions over the new partition key.

import { pgTable, uuid } from "drizzle-orm/pg-core";

import { target } from "./target.js";
import { resource } from "./target.js";
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Import path inconsistency detected

  • The resource.js file does not exist in packages/db/src/schema.
  • Remaining references to target.js found in:
    • packages/db/src/schema/target-session.ts
    • packages/db/src/schema/target-agent.ts
    • packages/db/src/schema/release.ts
    • packages/db/src/schema/target-provider.ts
    • packages/db/src/schema/job.ts
    • packages/db/src/schema/index.ts

Please update the import paths to align with the resource-centric model.

🔗 Analysis chain

Verify the import path naming consistency

The import statement shows resource being imported from target.js, which seems inconsistent with the resource-centric model transition.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if target.js has been renamed to resource.js in the codebase
# and if there are any remaining references to the old filename

# Check if resource.js exists
fd -t f "resource.js" "packages/db/src/schema"

# Check for any remaining references to target.js
rg -l "target\.js" "packages/db/src/schema"

Length of output: 306


import { user } from "./auth.js";
import { target } from "./target.js";
import { resource } from "./target.js";
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Import Path Inconsistency Detected

The import statement in ./target-session.ts still references ./target.js, indicating incomplete refactoring to the resource-centric model.

🔗 Analysis chain

Verify the import path naming consistency

While we're transitioning to a resource-centric model, we're still importing from "./target.js". This seems inconsistent with the refactoring effort.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if the target.js file has been renamed or if there are other files still referencing it
fd target.js
rg -l "from ['\"].*target\.js['\"]"

Length of output: 16233

.select()
.from(releaseJobTrigger)
.innerJoin(target, eq(releaseJobTrigger.targetId, target.id))
.innerJoin(resource, eq(releaseJobTrigger.resourceId, resource.id))
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

References to 'target' table still found in SQL queries. Please ensure all instances are correctly renamed to 'resource'.

  • integrations/terraform-cloud-scanner/src/scanner.ts
  • packages/validators/src/session/session-create.ts
  • packages/validators/src/variables/index.ts
  • apps/webservice/src/app/api/github/webhook/workflow/handler.ts
  • apps/webservice/src/app/[workspaceSlug]/_components/reactflow/edges.ts
  • ...and others.
🔗 Analysis chain

LGTM: Database query properly refactored

The database query has been correctly updated to:

  • Join with the resource table instead of target
  • Reference resource.lockedAt in the null check condition

The changes maintain the same functionality while aligning with the resource-centric model.

Let's verify that all references to the target table have been consistently renamed:

Also applies to: 20-20


[/run_scripts]

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining references to 'target' table in SQL queries
# Expected: No references to 'target' table in SQL queries after the rename

# Search for any remaining SQL queries using the old 'target' table
rg -g '*.ts' -g '*.js' 'from.*target.*join|join.*target\.'

Length of output: 60


Script:

#!/bin/bash
# Description: Re-verify any remaining references to the 'target' table in SQL queries with an improved search pattern
# Expected: No references to 'target' table in SQL queries after the rename

# Search for any remaining SQL queries using the old 'target' table with a broader regex
rg -i -g '*.ts' -g '*.js' '\btarget\b'

Length of output: 32275

Comment on lines +31 to +33
export type TargetMetadataGroup = InferSelectModel<
typeof resourceMetadataGroup
>;
Copy link
Contributor

@coderabbitai coderabbitai bot Nov 13, 2024

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider renaming the type alias for consistency.

The type alias still uses the old 'Target' prefix while inferring from the renamed resourceMetadataGroup.

Apply this diff to maintain consistency:

-export type TargetMetadataGroup = InferSelectModel<
+export type ResourceMetadataGroup = InferSelectModel<
   typeof resourceMetadataGroup
 >;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export type TargetMetadataGroup = InferSelectModel<
typeof resourceMetadataGroup
>;
export type ResourceMetadataGroup = InferSelectModel<
typeof resourceMetadataGroup
>;

Copy link
Member

Choose a reason for hiding this comment

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

I think this is a miss as well?

Copy link
Contributor

Choose a reason for hiding this comment

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

@zacharyblasczyk, understood. We'll keep the type alias as TargetMetadataGroup. Thanks for clarifying!

Comment on lines +21 to 29
export const createTargetMetadataGroup = createInsertSchema(
resourceMetadataGroup,
)
.omit({
id: true,
})
.extend({
keys: z.array(z.string()),
});
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Maintain naming consistency by renaming helper functions.

While the main table has been renamed to use resource, the helper functions still use Target in their names. This creates inconsistency in the codebase.

Apply this diff to maintain consistency:

-export const createTargetMetadataGroup = createInsertSchema(
+export const createResourceMetadataGroup = createInsertSchema(
   resourceMetadataGroup,
 )
   .omit({
     id: true,
   })
   .extend({
     keys: z.array(z.string()),
   });
-export const updateTargetMetadataGroup = createTargetMetadataGroup.partial();
+export const updateResourceMetadataGroup = createResourceMetadataGroup.partial();

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +193 to +195
return updatedValue.resourceFilter;
const conditions = otherValues
.map((v) => v.targetFilter)
.map((v) => v.resourceFilter)
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Update getNewTargetFilter to getNewResourceFilter

For consistency, rename getNewTargetFilter to getNewResourceFilter and adjust variable names to align with the resource-centric changes.

Apply this diff to rename the function:

-const getNewTargetFilter = (): TargetCondition | null => {
+const getNewResourceFilter = (): TargetCondition | null => {

And update associated variables within the function.

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +353 to 356
schema.resource.workspaceId,
input.workspaceId,
);
const targetConditions = schema.targetMatchesMetadata(
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Update usage of schema.targetMatchesMetadata in byWorkspaceId procedure.

The schema.targetMatchesMetadata function is again used with schema.resource. Ensure that this function is compatible with the resource schema or update its implementation and name to align with the resource-centric model.

.select({
id: releaseJobTrigger.id,
targetId: releaseJobTrigger.targetId,
targetId: releaseJobTrigger.resourceId,
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Property Name Inconsistency with 'Resource' Refactoring

The property targetId is assigned the value releaseJobTrigger.resourceId. To maintain consistency and prevent confusion, consider renaming the property to resourceId.

Apply this diff to update the property name:

 const latestJobSubquery = ctx.db
   .select({
     id: releaseJobTrigger.id,
-    targetId: releaseJobTrigger.resourceId,
+    resourceId: releaseJobTrigger.resourceId,
     releaseId: releaseJobTrigger.releaseId,
     status: job.status,
     createdAt: job.createdAt,
     rank: sql<number>`ROW_NUMBER() OVER (
       PARTITION BY ${releaseJobTrigger.resourceId}, ${releaseJobTrigger.releaseId}
       ORDER BY ${job.createdAt} DESC
     )`.as("rank"),
   })

Committable suggestion skipped: line range outside the PR's diff.

v[0]!.environment_policy != null
? rolloutDateFromReleaseJobTrigger(
v[0]!.release_job_trigger.targetId,
v[0]!.release_job_trigger.resourceId,
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Inconsistent Parameter Naming in Function Call

In the call to rolloutDateFromReleaseJobTrigger, the first argument is v[0]!.release_job_trigger.resourceId, but the function parameter is still named targetId. For consistency and clarity, consider renaming the function parameter from targetId to resourceId.

Apply this diff to update the parameter name:

-const rolloutDateFromReleaseJobTrigger = (
-  targetId: string,
+const rolloutDateFromReleaseJobTrigger = (
+  resourceId: string,
   releaseId: string,
   environmentId: string,
   releaseCreatedAt: Date,
   environmentPolicyDuration: number,
   releaseWindows: Array<{
     startTime: Date;
     endTime: Date;
     recurrence: string;
   }>,
 ) => {

Committable suggestion skipped: line range outside the PR's diff.

.query(({ ctx, input }) =>
releaseJobTriggerQuery(ctx.db)
.where(eq(target.id, input))
.where(eq(resource.id, input))
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Procedure Name and Variable Inconsistency

The procedure byTargetId still uses Target in its name, but the query has been updated to use resource.id. For clarity and consistency, consider renaming the procedure to byResourceId and updating any related variable names from target to resource.

Apply this diff to rename the procedure and variables:

-export const jobRouter = createTRPCRouter({
-  byTargetId: protectedProcedure
+export const jobRouter = createTRPCRouter({
+  byResourceId: protectedProcedure
     .meta({
       authorizationCheck: ({ canUser, input }) =>
-        canUser.perform(Permission.SystemList).on({ type: "resource", id: input }),
+        canUser.perform(Permission.SystemList).on({ type: "resource", id: input }),
     })
     .input(z.string())
     .query(({ ctx, input }) =>
       releaseJobTriggerQuery(ctx.db)
         .where(eq(resource.id, input))
         .limit(1_000)
         .orderBy(desc(job.createdAt), desc(releaseJobTrigger.createdAt))
         .then((data) =>
           data.map((t) => ({
             ...t.release_job_trigger,
             job: t.job,
             agent: t.job_agent,
-            target: t.resource,
+            resource: t.resource,
             deployment: t.deployment,
             release: { ...t.release },
             environment: t.environment,
           })),
         ),
     ),
 });

.from(resource)
.where(eq(resource.id, input.targetId))
.then(takeFirstOrNull);
if (!t) throw new Error("Target not found");
Copy link
Member

Choose a reason for hiding this comment

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

I think this is a miss.

.where(eq(resource.id, input))
.limit(1_000)
.orderBy(desc(job.createdAt), desc(releaseJobTrigger.createdAt))
.then((data) =>
Copy link
Member

Choose a reason for hiding this comment

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

I think this is a miss?

Copy link
Member

Choose a reason for hiding this comment

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

"target: t.resource,"

value: deploymentVariableValue.value,
variableId: deploymentVariableValue.variableId,
targetFilter: deploymentVariableValue.targetFilter,
targetFilter: deploymentVariableValue.resourceFilter,
Copy link
Member

Choose a reason for hiding this comment

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

I think this is a miss.

}

await db.delete(schema.target).where(eq(schema.target.id, target.id));
await db.delete(schema.resource).where(eq(schema.resource.id, target.id));
Copy link
Member

Choose a reason for hiding this comment

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

I think this is a miss

.perform(Permission.TargetMetadataGroupCreate)
.on({ type: "workspace", id: input.workspaceId }),
})
.input(createTargetMetadataGroup)
Copy link
Member

Choose a reason for hiding this comment

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

This may be a miss.

.select({ count: count() })
.from(schema.target)
.from(schema.resource)
.where(schema.targetMatchesMetadata(ctx.db, view.filter))
Copy link
Member

Choose a reason for hiding this comment

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

?

schema.resource.workspaceId,
input.workspaceId,
);
const targetConditions = schema.targetMatchesMetadata(
Copy link
Member

Choose a reason for hiding this comment

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

This might be a miss.

where: inArray(schema.resource.id, input),
});
const events = (
await Promise.allSettled(targets.map(getEventsForTargetDeleted))
Copy link
Member

Choose a reason for hiding this comment

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

?

import { jobAgent } from "./job-agent.js";
import { release } from "./release.js";
import { target } from "./target.js";
import { resource } from "./target.js";
Copy link
Member

Choose a reason for hiding this comment

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

Let's rename to resource.js

return eq(environment.id, cond.value);
if (cond.type === FilterType.Version) return buildVersionCondition(cond);
if (cond.type === JobFilterType.JobTarget) return eq(target.id, cond.value);
if (cond.type === JobFilterType.JobTarget) return eq(resource.id, cond.value);
Copy link
Member

Choose a reason for hiding this comment

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

?

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (6)
packages/api/src/router/target-provider.ts (6)

Line range hint 21-23: Update permission enums to match resource-centric model

The permission checks still use target-centric terminology (Permission.TargetList, Permission.TargetProviderUpdate) while the rest of the code has moved to resource-centric naming.

Consider updating the permission enums in @ctrlplane/validators/auth to use resource terminology:

- Permission.TargetList
+ Permission.ResourceList

- Permission.TargetProviderUpdate
+ Permission.ResourceProviderUpdate

Also applies to: 89-92


Line range hint 70-82: Update response property names for consistency

The response structure uses targetCount which doesn't align with the resource-centric model.

Consider updating the property name:

- targetCount:
+ resourceCount:

Line range hint 142-146: Update queue operation parameters

The queue operations still use target-centric terminology (targetProviderId) while the rest of the code has moved to resource-centric naming.

Consider updating the queue parameters:

- { targetProviderId: tg.id }
+ { resourceProviderId: tg.id }

Line range hint 153-161: Update input validation schema properties

The input validation schema still uses target-centric terminology (targetProviderId).

Consider updating the schema properties:

- targetProviderId: z.string().uuid(),
+ resourceProviderId: z.string().uuid(),

Line range hint 208-211: Update permission checks in delete mutation

The permission check still uses target-centric terminology (Permission.TargetDelete).

Consider updating the permission check:

- .perform(Permission.TargetDelete)
+ .perform(Permission.ResourceDelete)

Line range hint 216-217: Update input schema property names

The delete mutation's input schema still uses target-centric terminology (deleteTargets).

Consider updating the property name:

- deleteTargets: z.boolean().optional().default(false),
+ deleteResources: z.boolean().optional().default(false),
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 981d031 and 60f23e2.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (3)
  • apps/webservice/next.config.js (0 hunks)
  • packages/api/src/router/deployment-variable.ts (11 hunks)
  • packages/api/src/router/target-provider.ts (7 hunks)
💤 Files with no reviewable changes (1)
  • apps/webservice/next.config.js
🔇 Additional comments (8)
packages/api/src/router/target-provider.ts (1)

Line range hint 1-240: Verify complete transition to resource-centric terminology

Let's verify that all references to the target-centric model have been identified and updated.

packages/api/src/router/deployment-variable.ts (7)

24-24: LGTM: Import addition aligns with resource model transition

The addition of the resource import is consistent with the codebase's transition from a target-centric to a resource-centric model.


Line range hint 121-131: LGTM: Environment filter property renamed consistently

The renaming from targetFilter to resourceFilter in the environment query and conditions mapping is consistent with the resource model transition while preserving the existing logic.


179-181: LGTM: Property access updated to use resourceFilter

The property access has been correctly updated to use resourceFilter while maintaining the existing logic.


193-195: LGTM: Property access updated to use resourceFilter

The property access has been correctly updated to use resourceFilter while maintaining the existing logic.


216-220: LGTM: Query updated to use resource table

The queries have been correctly updated to use the resource table instead of the target table, maintaining the same logical flow.


Line range hint 363-381: LGTM: Subquery field renamed to resourceFilter

The subquery field has been correctly renamed from targetFilter to resourceFilter while maintaining the existing query structure and logic.


Line range hint 301-333: LGTM with verification: Table references updated to resource model

The table references have been correctly updated to use the resource table. The procedure name retention (byTargetId) appears intentional for API compatibility.

Let's verify that this endpoint is still being used with the old name:

✅ Verification successful

The search results confirm that the byTargetId endpoint is actively used across multiple frontend components, primarily in target-related views and drawers. The endpoint name consistency is important for maintaining these existing frontend integrations. Let me verify if there are any ongoing migrations or TODOs related to this naming:


LGTM: Table references correctly updated while maintaining API compatibility

The changes correctly update the table references from target to resource while intentionally preserving the byTargetId procedure name. This approach maintains compatibility with multiple frontend components that actively use this endpoint across target-related views and drawers.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for API endpoint usage
rg "byTargetId" --type ts

Length of output: 1901


Script:

#!/bin/bash
# Search for any migration or TODO comments related to target/resource renaming
rg -i "todo.*target|target.*migration" --type ts

Length of output: 50

.update(resourceProvider)
.set({ name: input.name })
.where(eq(targetProvider.id, input.targetProviderId))
.where(eq(resourceProvider.id, input.targetProviderId))
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Update variable references in update mutation

Some variable references in the update mutation still use the old terminology.

Consider updating these references:

- .where(eq(resourceProvider.id, input.targetProviderId))
+ .where(eq(resourceProvider.id, input.resourceProviderId))

- resourceProviderGoogle.resourceProviderId,
- input.targetProviderId,
+ resourceProviderGoogle.resourceProviderId,
+ input.resourceProviderId,

Also applies to: 178-180

@adityachoudhari26 adityachoudhari26 merged commit efb1ba1 into main Nov 13, 2024
14 checks passed
@adityachoudhari26 adityachoudhari26 deleted the rename-resource-tables branch November 13, 2024 22:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants