Spaces:
Sleeping
Sleeping
File size: 12,073 Bytes
1c8e50c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 |
# Task Service
## Overview
The **Task Service** is a microservice component of the Task Management System that handles all task-related operations. It provides a RESTful API for creating, reading, updating, deleting, and managing tasks within the system.
## Purpose
This service is responsible for:
- **Task CRUD Operations**: Create, retrieve, update, and delete tasks
- **Task Assignment**: Assign tasks to specific users
- **Task Status Management**: Track task progression (PENDING β ASSIGNED β DONE)
- **Task Filtering & Sorting**: Filter tasks by status and sort by deadline or creation date
- **User Integration**: Communicates with User Service for authentication and authorization
- **Admin Controls**: Only administrators can create tasks
## Architecture
### Technology Stack
- **Framework**: Spring Boot 3.2.2
- **Language**: Java 17
- **Database**: MongoDB
- **Service Discovery**: Netflix Eureka Client
- **Inter-Service Communication**: OpenFeign
- **Distributed Tracing**: Zipkin with Micrometer
- **Build Tool**: Gradle
### Key Components
1. **Controllers**
- `TaskController`: Handles all task-related REST endpoints
- `HomeController`: Provides health check and welcome endpoints
2. **Services**
- `TaskService`: Interface defining task operations
- `TaskServiceImplementation`: Business logic implementation
- `UserService`: Feign client for User Service integration
3. **Repository**
- `TaskRepository`: MongoDB repository for task persistence
4. **Models**
- `Task`: Main task entity
- `UserDTO`: User data transfer object
- `TaskStatus`: Enum for task states (PENDING, ASSIGNED, DONE)
5. **Exception Handling**
- `GlobalExceptionHandler`: Centralized exception handling
- `TaskNotFoundException`: Custom exception for task not found scenarios
## Database Schema
### Task Collection
```json
{
"_id": "string",
"title": "string",
"description": "string",
"imageUrl": "string",
"assignedUserId": "string",
"status": "PENDING | ASSIGNED | DONE",
"deadline": "LocalDateTime",
"createAt": "LocalDateTime",
"tags": ["string"]
}
```
## API Endpoints
### Base URL
```
http://localhost:8082/api/tasks
```
### Endpoints
#### 1. Create Task (Admin Only)
```http
POST /api/tasks
Headers:
Authorization: Bearer <JWT_TOKEN>
Body:
{
"title": "Task Title",
"description": "Task Description",
"imageUrl": "https://example.com/image.png",
"deadline": "2024-12-31T23:59:59",
"tags": ["tag1", "tag2"]
}
Response: 201 CREATED
```
#### 2. Get Task by ID
```http
GET /api/tasks/{id}
Headers:
Authorization: Bearer <JWT_TOKEN>
Response: 200 OK
```
#### 3. Get All Tasks
```http
GET /api/tasks?status=PENDING&sortByDeadline=asc&sortByCreatedAt=desc
Headers:
Authorization: Bearer <JWT_TOKEN>
Query Parameters:
- status: PENDING | ASSIGNED | DONE (optional)
- sortByDeadline: asc | desc (optional)
- sortByCreatedAt: asc | desc (optional)
Response: 200 OK
```
#### 4. Get Assigned User Tasks
```http
GET /api/tasks/user?status=ASSIGNED&sortByDeadline=asc
Headers:
Authorization: Bearer <JWT_TOKEN>
Query Parameters:
- status: PENDING | ASSIGNED | DONE (optional)
- sortByDeadline: asc | desc (optional)
- sortByCreatedAt: asc | desc (optional)
Response: 200 OK
```
#### 5. Assign Task to User
```http
PUT /api/tasks/{taskId}/user/{userId}/assigned
Headers:
Authorization: Bearer <JWT_TOKEN>
Response: 200 OK
```
#### 6. Update Task
```http
PUT /api/tasks/{id}
Headers:
Authorization: Bearer <JWT_TOKEN>
Body:
{
"title": "Updated Title",
"description": "Updated Description",
"status": "ASSIGNED",
"deadline": "2024-12-31T23:59:59"
}
Response: 200 OK
```
#### 7. Delete Task
```http
DELETE /api/tasks/{id}
Response: 204 NO CONTENT
```
#### 8. Complete Task
```http
PUT /api/tasks/{id}/complete
Response: 200 OK
```
#### 9. Health Check
```http
GET /tasks
Response: 200 OK - "Welcome to Task Service"
```
## Configuration
### application.properties
```properties
# Server Configuration
server.port=8082
# MongoDB Configuration
spring.data.mongodb.uri=mongodb://localhost:27017/tasks
# Application Name
spring.application.name=TASK-SERVICE
# Eureka Client Configuration
eureka.instance.prefer-ip-address=true
eureka.client.fetch-registry=true
eureka.client.register-with-eureka=true
eureka.client.service-url.defaultZone=http://localhost:8085/eureka
# Zipkin Tracing Configuration
spring.zipkin.base-url=http://localhost:9411
spring.sleuth.sampler.probability=1.0
```
## Prerequisites
Before running the Task Service, ensure you have:
1. **Java 17** or higher installed
2. **MongoDB** installed and running on `localhost:27017`
3. **Eureka Server** running on `http://localhost:8085`
4. **User Service** running on `http://localhost:8081` (for Feign client)
5. **Zipkin Server** (optional) running on `http://localhost:9411` for distributed tracing
## How to Run
### Method 1: Using Gradle Wrapper
#### 1. Navigate to TaskService directory
```bash
cd TaskService
```
#### 2. Build the application
```bash
./gradlew clean build
```
#### 3. Run the application
```bash
./gradlew bootRun
```
### Method 2: Using JAR file
#### 1. Build the JAR
```bash
./gradlew clean build
```
#### 2. Run the JAR
```bash
java -jar build/libs/TaskService-0.0.1-SNAPSHOT.jar
```
### Method 3: Using Docker
#### 1. Build the Docker image
```bash
docker build -t task-service:latest .
```
#### 2. Run the Docker container
```bash
docker run -p 8082:8082 \
-e SPRING_DATA_MONGODB_URI=mongodb://host.docker.internal:27017/tasks \
-e EUREKA_CLIENT_SERVICE_URL_DEFAULTZONE=http://host.docker.internal:8085/eureka \
task-service:latest
```
### Method 4: Using Docker Compose (Recommended)
From the root directory of the project:
```bash
docker-compose up task-service
```
## Verification
Once the service is running, verify it's working:
### 1. Check Service Health
```bash
curl http://localhost:8082/tasks
```
Expected response: `"Welcome to Task Service"`
### 2. Check Eureka Registration
Visit `http://localhost:8085` and verify that `TASK-SERVICE` is registered.
### 3. Check MongoDB Connection
Ensure the MongoDB database `tasks` is created and accessible.
## Integration with Other Services
### User Service Integration
The Task Service communicates with the User Service using OpenFeign:
- **URL**: `http://localhost:8081`
- **Endpoint**: `/api/users/profile`
- **Purpose**: Fetch user profile information for authentication and authorization
### Eureka Service Discovery
The Task Service registers itself with Eureka Server for service discovery:
- **Service Name**: `TASK-SERVICE`
- **Eureka Server**: `http://localhost:8085/eureka`
### Zipkin Tracing
Distributed tracing is enabled for monitoring:
- **Zipkin URL**: `http://localhost:9411`
- **Sampling Probability**: 100% (all requests are traced)
## Authentication & Authorization
All endpoints (except the health check) require JWT authentication:
- **Header**: `Authorization: Bearer <JWT_TOKEN>`
- **Admin Role**: Required for creating tasks (`ROLE_ADMIN`)
- **User Verification**: JWT is validated via User Service
## Error Handling
The service includes comprehensive error handling:
### Common Error Responses
#### 400 Bad Request
```json
{
"timestamp": "2024-11-10T10:30:00",
"message": "Invalid request parameters",
"status": 400,
"error": "Bad Request"
}
```
#### 401 Unauthorized
```json
{
"timestamp": "2024-11-10T10:30:00",
"message": "JWT required...",
"status": 401,
"error": "Unauthorized"
}
```
#### 404 Not Found
```json
{
"timestamp": "2024-11-10T10:30:00",
"message": "Task not found with id: 12345",
"status": 404,
"error": "Task Not Found"
}
```
#### 500 Internal Server Error
```json
{
"timestamp": "2024-11-10T10:30:00",
"message": "Internal server error",
"status": 500,
"error": "Internal Server Error"
}
```
## Task Lifecycle
1. **PENDING**: Task is created (by admin only)
2. **ASSIGNED**: Task is assigned to a user
3. **DONE**: Task is marked as completed
## Development
### Project Structure
```
TaskService/
βββ src/
β βββ main/
β β βββ java/in/garvit/tasks/
β β β βββ TaskServiceApplication.java
β β β βββ controller/
β β β β βββ HomeController.java
β β β β βββ TaskController.java
β β β βββ service/
β β β β βββ TaskService.java
β β β β βββ TaskServiceImplementation.java
β β β β βββ UserService.java
β β β βββ repository/
β β β β βββ TaskRepository.java
β β β βββ taskModel/
β β β β βββ Task.java
β β β β βββ UserDTO.java
β β β βββ enums/
β β β β βββ TaskStatus.java
β β β βββ exception/
β β β βββ GlobalExceptionHandler.java
β β β βββ TaskNotFoundException.java
β β βββ resources/
β β βββ application.properties
β βββ test/
β βββ java/in/garvit/tasks/
β βββ TaskServiceApplicationTests.java
βββ build.gradle
βββ Dockerfile
βββ README.md
```
### Building from Source
```bash
# Clone the repository
git clone <repository-url>
# Navigate to TaskService
cd TaskService
# Build the project
./gradlew clean build
# Run tests
./gradlew test
# Run the application
./gradlew bootRun
```
## Testing
### Run Unit Tests
```bash
./gradlew test
```
### Test Coverage
```bash
./gradlew test jacocoTestReport
```
## Troubleshooting
### Common Issues
#### 1. MongoDB Connection Failed
**Error**: `Connection refused to MongoDB`
**Solution**: Ensure MongoDB is running:
```bash
# Start MongoDB
sudo systemctl start mongod
# Check status
sudo systemctl status mongod
```
#### 2. Eureka Registration Failed
**Error**: `Cannot register with Eureka`
**Solution**: Ensure Eureka Server is running on port 8085
#### 3. User Service Communication Failed
**Error**: `Feign client error`
**Solution**: Ensure User Service is running on port 8081
#### 4. Port Already in Use
**Error**: `Port 8082 is already in use`
**Solution**: Change the port in `application.properties` or kill the process:
```bash
# Find process using port 8082
lsof -i :8082
# Kill the process
kill -9 <PID>
```
## Performance Considerations
- **Database Indexing**: Consider adding indexes on frequently queried fields (e.g., `assignedUserId`, `status`)
- **Caching**: Implement caching for frequently accessed tasks
- **Pagination**: Add pagination for large result sets
- **Connection Pooling**: MongoDB connection pool is managed by Spring Data
## Security Considerations
- All endpoints require JWT authentication
- Only admins can create tasks
- User validation is performed via User Service
- Sensitive data should be encrypted at rest
- HTTPS should be used in production
## Monitoring
### Health Check Endpoint
```bash
curl http://localhost:8082/actuator/health
```
### Metrics Endpoint
```bash
curl http://localhost:8082/actuator/metrics
```
### Zipkin Dashboard
Access Zipkin UI at: `http://localhost:9411`
## Future Enhancements
- [ ] Add pagination support for task listings
- [ ] Implement task comments/notes feature
- [ ] Add task priority levels
- [ ] Implement recurring tasks
- [ ] Add file attachments to tasks
- [ ] Implement task notifications
- [ ] Add task templates
- [ ] Implement task categories
- [ ] Add advanced search capabilities
## Contributing
1. Fork the repository
2. Create a feature branch
3. Commit your changes
4. Push to the branch
5. Create a Pull Request
## License
This project is part of the Task Management System microservices architecture.
## Contact
**Author**: Garvit Pathak (garvitpathak27)
**Email**: [Your Email]
**GitHub**: [Your GitHub Profile]
---
**Note**: This service is part of a larger microservices ecosystem. Ensure all dependent services are running for full functionality.
|