-
Notifications
You must be signed in to change notification settings - Fork 2.6k
feat: Knowledge base workflow supports terminating execution #4535
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
|
Adding the "do-not-merge/release-note-label-needed" label because no release-note block was detected, please follow our release note process to remove it. DetailsInstructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository. |
|
[APPROVALNOTIFIER] This PR is NOT APPROVED This pull-request has been approved by: The full list of commands accepted by this bot can be found here. DetailsNeeds approval from an approver in each of these files:Approvers can indicate their approval by writing |
| } | ||
| const changeFilterHandle = () => { | ||
| query.value = { user_name: '', status: '' } | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The code provided looks generally clean and functional. However, there are a few minor improvements and checks that can be made:
-
Button Placement: Ensure the "cancel" button is properly positioned and readable within the table column. Consider adjusting its styling or placement if necessary.
-
Event Handling:
- The
toDetailsfunction should have proper parameter validation ensure it receives an object with expected properties. - Add error handling in the
cancelfunction to manage any potential errors from the API call.
- The
-
Documentation and Comments: Adding more documentation and comments can help clarify the purpose of each part of the codebase. This includes explaining how buttons interact with backend operations and what actions they trigger.
Here are some specific suggestions with examples:
<template>
<!-- ... existing template content ... -->
</template>
<script>
import { ref } from 'vue';
// Import other components and utilities here
export default {
setup() {
// Existing variables and methods ...
const loadSharedApi = (params: any) => {
// Function implementation ...
};
const cancel = async (row: any) => {
try {
await loadSharedApi({ type: 'knowledge', systemType: apiType.value }).cancelWorkflowAction(
active_knowledge_id.value,
row.id,
loading
);
// Handle successful cancellation if needed
} catch (error) {
console.error('Error cancelling workflow:', error);
$message.error($t('common.errors.generic'));
}
};
return {
// ..., existing data and functions ...
toDetails,
cancel,
};
},
};
</script>
<style scoped>
/* ... existing CSS styles ... */
.flex {
display: flex;
justify-content: space-between;
}
</style>By focusing on improving event handling and adding documentation, the code will be more robust and easier to maintain.
|
|
||
|
|
||
| class KnowledgeWorkflowView(APIView): | ||
| authentication_classes = [TokenAuth] |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The provided Python code snippet seems to be part of an API for managing knowledge workflows in a workspace. It includes two views: get and Cancel. Below is a brief analysis and some optimizations/considerations:
Analysis
-
Endpoint
/api/knowledge/workflow/<workspace_id>/<knowledge_id>:- This endpoint uses the
DetailViewpattern, which typically handles GET requests to fetch a specific resource (e.g., a document). - The method signature indicates it takes
request,workspace_id,knowledge_id, andknowledge_action_idas arguments.
- This endpoint uses the
-
Class
Cancel:- Uses the
APIView, allowing both POST and other HTTP methods but likely only supports POST at this level. - Extends Django REST Framework's
@extend_schemadecorator to define Swagger/OpenAPI schema information. - Requires appropriate permissions using
can_has_permissions. - Cancels a knowledge workflow action with given ID.
- Uses the
-
Class
KnowledgeWorkflowView:- Also extends
APIView. - Similar functionality to the root
getmethod but likely handles more generic knowledge workflow operations.
- Also extends
Optimizations/Suggestions
-
Model Method Redundancy:
- In
getview, you're creating multiple querysets (datadictionaries) before returning results. Instead, consider retrieving all necessary data in one go and then passing those into the serializer directly.
- In
-
Method Naming Consistency:
- In the
postmethod ofCancelclass, call.cancel()on an instance returned from.operate(). Ensure consistency here too; if possible, chain these calls together instead of storing intermediate variables.
- In the
-
Validation and Error Handling:
- Consider adding input validation checks in
getor before initiating the cancel process to ensure correct IDs are being passed. - Add error handling around database queries and method executions within the
viewset.
- Consider adding input validation checks in
-
Consistent Response Formatting:
- Always use
result.success()method consistently throughout the module to format success responses uniformly. Ensure thatDefaultResultSerializerformats correctly as expected.
- Always use
-
Code Readability:
- Use clear naming conventions across classes and functions for better readability and maintainability.
Overall, while the code appears functional, improving its efficiency, clarity, and robustness through proper separation of concerns and adherence to best practices would significantly enhance its quality.
|
|
||
|
|
||
| class KnowledgeWorkflowSerializer(serializers.Serializer): | ||
| class Datasource(serializers.Serializer): |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I will review the code for potential issues and suggest improvements. Here's a brief summary of my findings:
1. Cache Version Import
from maxkb.const import CONFIG
Instead, it should be:
```python
from django.core.cache import cache
2. Pagination Query Set Method
- The method
pagedoes not use Django's built-inPagefunctionality but directly queries all items into a list before returning. This can be inefficient for large datasets.
Replace page_search() with a pagination-aware queryset.
For example:
def page(self, current_page: int, page_size: int, instance: Dict) -> QuerySet[Dict]:
query_set = (
QuerySet(KnowledgeAction)
.filter(knowledge_id=self.data.get('knowledge_id'))
.annotate(run_time_datetime=F('run_time').cast(DateTZDateTimeField()))
.values('id', 'knowledge_id', "state", 'meta', 'details', 'run_time_datetime')
)
# Optionally add ordering based on 'run_time_datetime' or another relevant column(s)
Paginator(query_set, page_size).get_page(current_page)3. Conditional Field Lookup in Action Method
- There are multiple instances where fields like
run_time,create_time, and others are retrieved conditionally (e.g., using.get()) which could cause problems if those values don't exist.
Consider handling these cases more safely, e.g., using .first() instead when only checking existence and defaulting to None/empty dict/slice.
4. Meta Validation in Action Methods
- In both
actionandcancel, there are direct calls toqueryset.update(...). While this works, validation should ideally occur separately from execution to ensure robustness.
Move metadata updates into a separate function after ensuring the necessary permissions and conditions are met.
5. Exception Handling
- Ensure appropriate exception handling throughout the workflow methods (
one,cancel, etc.). Catch exceptions properly and return meaningful error responses to avoid silent failures.
Example:
try:
response_data = some_function()
except SomeError as e:
raise AppApiException(str(e)) from eGeneral Recommendations
-
DRY Principle: Identify repeated patterns across similar methods such as querying, validating, processing, and updating records, and refactor them out into reusable functions.
Example:
def perform_common_operations(action_instance): meta_to_update = {key: value for key, value in self.validated_data.items()} knowledge_action_id = action_instance.id cache.set(Cache_Version.KNOWLEDGE_WORKFLOW_INTERRUPTED.get_key(action_id=knowledge_action_id), True, version=Cache_Version.KNOWLEDGE_WORKFLWO_INTERRUPTED.get_version()) updated_fields = ['details', 'status'] # List of fields you want to update here for field in updated_fields: setattr(knowledge_instance, field, meta_to_update[field]) # Commit changes knowledge_instance.save(update_fields=['details', 'status'])
-
Security Considerations: Always validate incoming data thoroughly and sanitize it appropriately to prevent injection attacks.
Use libraries like
Pydanticfor schema-based validation rather than raw JSON serialisation/deserialisation. -
Testing: Incorporate appropriate unit tests for each method that handles significant business logic steps. Test edge cases and boundary conditions thoroughly, including invalid inputs.
By addressing these concerns, your API becomes more robust, efficient, and secure.
feat: Knowledge base workflow supports terminating execution