Skip to content

Latest commit

 

History

History
480 lines (411 loc) · 13.5 KB

File metadata and controls

480 lines (411 loc) · 13.5 KB

Hexagon Feed System - Class Architecture Diagram

Overview

This document provides a comprehensive overview of the class architecture for the Hexagon Feed System, a location-based social feed application using hexagonal spatial indexing (H3) with Spring Boot.

System Architecture Layers

┌─────────────────────────────────────────────────────────────────┐
│                        PRESENTATION LAYER                       │
├─────────────────────────────────────────────────────────────────┤
│  Controllers (REST API Endpoints)                              │
│  • AuthController          • FeedController                    │
│  • PostController          • WebSocket Controllers             │
└─────────────────────────────────────────────────────────────────┘
                                    │
                                    ▼
┌─────────────────────────────────────────────────────────────────┐
│                         SERVICE LAYER                          │
├─────────────────────────────────────────────────────────────────┤
│  Business Logic Services                                       │
│  • FeedAggregationService  • LocationService                   │
│  • PostIngestionService    • RateLimiterService               │
│  • UserService            • AuthenticationService             │
└─────────────────────────────────────────────────────────────────┘
                                    │
                                    ▼
┌─────────────────────────────────────────────────────────────────┐
│                       REPOSITORY LAYER                         │
├─────────────────────────────────────────────────────────────────┤
│  Data Access Layer (JPA Repositories)                         │
│  • UserRepository          • PostRepository                    │
│  • UserSessionRepository   • CacheRepository                   │
└─────────────────────────────────────────────────────────────────┘
                                    │
                                    ▼
┌─────────────────────────────────────────────────────────────────┐
│                          DATA LAYER                            │
├─────────────────────────────────────────────────────────────────┤
│  • PostgreSQL (Primary)    • Redis (Cache)                     │
│  • Kafka (Messaging)       • H3 Spatial Index                 │
└─────────────────────────────────────────────────────────────────┘

Detailed Class Structure

1. Controller Layer (Presentation)

AuthController

@RestController
@RequestMapping("/api/v1/auth")
public class AuthController {
    // Endpoints: /register, /login, /refresh, /verify, /logout
    // Dependencies: UserRepository, PasswordEncoder, JwtUtil
}

FeedController

@RestController
@RequestMapping("/api/v1/feed")
public class FeedController {
    // Endpoints: GET /feed, GET /health
    // Dependencies: FeedAggregationService, LocationService
}

PostController

@RestController
@RequestMapping("/api/v1/posts")
public class PostController {
    // Endpoints: POST /posts, GET /posts/{id}, DELETE /posts/{id}
    // Dependencies: PostIngestionService, RateLimiterService
}

2. Service Layer (Business Logic)

FeedAggregationService

@Service
public class FeedAggregationService {
    // Core Algorithm: K-way merge of 7 hexagons
    // Methods: aggregateFeed(), mergeHexagonFeeds()
    // Dependencies: PostRepository, LocationService, CacheRepository
}

LocationService

@Service
public class LocationService {
    // H3 Spatial Indexing Operations
    // Methods: getHexIdForLocation(), getNeighborHexagons()
    // Dependencies: H3Core library
}

PostIngestionService

@Service
public class PostIngestionService {
    // Post Creation and Management
    // Methods: createPost(), updatePost(), deletePost()
    // Dependencies: PostRepository, LocationService, KafkaProducer
}

RateLimiterService

@Service
public class RateLimiterService {
    // Token Bucket Rate Limiting
    // Methods: checkRateLimit(), consumeToken()
    // Dependencies: RedisTemplate
}

3. Repository Layer (Data Access)

UserRepository

@Repository
public interface UserRepository extends JpaRepository<User, UUID> {
    // Methods: findByUsername(), findByEmail(), existsByUsername()
    // Custom Queries: findActiveUsers(), findByLocation()
}

PostRepository

@Repository
public interface PostRepository extends JpaRepository<Post, UUID> {
    // Methods: findByHexId(), findByUserIdOrderByTimestampDesc()
    // Custom Queries: findPostsInHexagons(), softDeletePost()
}

UserSessionRepository

@Repository
public interface UserSessionRepository extends JpaRepository<UserSession, UUID> {
    // Methods: findByUser_UserId(), findByRefreshTokenHash()
    // Custom Queries: findActiveSessions(), updateLastAccessedTime()
}

4. Model Layer (Entities & DTOs)

Entity Classes

User Entity
@Entity
@Table(name = "users")
public class User {
    @Id @GeneratedValue private UUID userId;
    private String username, email, passwordHash;
    private String firstName, lastName, bio, location;
    private Boolean isActive, isVerified, isPrivate;
    private Integer followersCount, followingCount, postsCount;
    @CreatedDate private LocalDateTime createdAt;
    @LastModifiedDate private LocalDateTime updatedAt;
    private String preferences; // JSONB
}
Post Entity
@Entity
@Table(name = "posts")
public class Post {
    @Id @GeneratedValue private UUID postId;
    @ManyToOne private User user;
    private String content, hexId;
    private Double latitude, longitude;
    private Integer likesCount, repliesCount, viewsCount;
    private Boolean isDeleted;
    @CreatedDate private LocalDateTime createdAt;
    private LocalDateTime deletedAt;
}
UserSession Entity
@Entity
@Table(name = "user_sessions")
public class UserSession {
    @Id @GeneratedValue private UUID sessionId;
    @ManyToOne private User user;
    private String refreshTokenHash, deviceType, ipAddress;
    private Boolean isActive;
    private LocalDateTime expiresAt, lastAccessedAt;
}

DTO Classes

Authentication DTOs
// Request DTOs
public class RegisterRequest {
    private String username, email, password, confirmPassword;
    private String fullName;
    private Boolean acceptTerms, acceptPrivacy;
}

public class LoginRequest {
    private String usernameOrEmail, password;
    private Boolean rememberMe;
}

// Response DTOs
public class AuthResponse {
    private String access_token, refresh_token;
    private UserDTO user;
    private AuthMetadata auth_metadata;
}
Feed DTOs
public class FeedRequest {
    private Double latitude, longitude;
    private Integer page, limit;
    private String cursor;
}

public class FeedResponse {
    private List<PostDTO> posts;
    private PaginationInfo pagination;
    private LocationInfo location;
}

5. Configuration Layer

SecurityConfig

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    // JWT Authentication Configuration
    // Security Filter Chain
    // CORS and CSRF Configuration
}

RedisConfig

@Configuration
public class RedisConfig {
    // RedisTemplate Configuration
    // JSON Serialization Setup
    // Connection Factory
}

KafkaConfig

@Configuration
public class KafkaConfig {
    // Producer Configuration
    // Consumer Configuration
    // Topic Configuration
}

6. Utility Classes

H3Util

@Component
public class H3Util {
    // H3 Library Wrapper
    // Methods: latLngToH3(), h3ToLatLng(), getNeighbors()
}

JwtUtil

@Component
public class JwtUtil {
    // JWT Token Operations
    // Methods: generateToken(), validateToken(), extractClaims()
}

ValidationUtil

@Component
public class ValidationUtil {
    // Input Validation
    // Methods: validateEmail(), validatePassword(), validateLocation()
}

7. Exception Handling

Global Exception Handler

@RestControllerAdvice
public class GlobalExceptionHandler {
    // Centralized Exception Handling
    // Custom Exception Types:
    // - ValidationException (400)
    // - UnauthorizedException (401)
    // - ResourceNotFoundException (404)
    // - RateLimitException (429)
    // - InternalServerException (500)
}

Custom Exceptions

public class ValidationException extends RuntimeException
public class UnauthorizedException extends RuntimeException
public class ResourceNotFoundException extends RuntimeException
public class RateLimitException extends RuntimeException

8. Messaging Layer

PostEventProducer

@Component
public class PostEventProducer {
    // Kafka Message Producer
    // Methods: publishPostCreated(), publishPostDeleted()
}

PostEventConsumer

@Component
public class PostEventConsumer {
    // Kafka Message Consumer
    // Methods: handlePostCreated(), handlePostDeleted()
    // WebSocket Notification Broadcasting
}

9. WebSocket Layer

WebSocketConfig

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig {
    // WebSocket Configuration
    // STOMP Protocol Setup
}

FeedWebSocketController

@Controller
public class FeedWebSocketController {
    // WebSocket Message Handling
    // Real-time Feed Updates
    // User Subscription Management
}

Key Design Patterns

1. Repository Pattern

  • Clean separation between data access and business logic
  • JPA repositories with custom query methods
  • Consistent data access interface

2. Service Layer Pattern

  • Business logic encapsulation
  • Transaction management
  • Service composition

3. DTO Pattern

  • Data transfer between layers
  • Input validation
  • Response formatting

4. Dependency Injection

  • Constructor-based injection
  • Loose coupling between components
  • Testability

5. Strategy Pattern

  • Rate limiting algorithms
  • Authentication strategies
  • Caching strategies

Data Flow Architecture

User Registration Flow

AuthController → UserRepository → PostgreSQL
     ↓
JwtUtil → AuthResponse → Client

Feed Aggregation Flow

FeedController → FeedAggregationService → LocationService
     ↓                    ↓
PostRepository ← K-way Merge Algorithm
     ↓
CacheRepository (Redis) → FeedResponse → Client

Post Creation Flow

PostController → RateLimiterService (Redis Check)
     ↓
PostIngestionService → PostRepository → PostgreSQL
     ↓
PostEventProducer → Kafka → PostEventConsumer
     ↓
WebSocket Broadcasting → Connected Clients

Scalability Considerations

Horizontal Scaling

  • Stateless service design
  • Database partitioning by hex_id
  • Load balancer compatible

Caching Strategy

  • Multi-layer caching (Redis)
  • Cache-aside pattern
  • TTL-based invalidation

Messaging

  • Asynchronous processing
  • Event-driven architecture
  • Kafka partitioning

Database Optimization

  • Composite indexes
  • Connection pooling (HikariCP)
  • Query optimization

Testing Architecture

Unit Tests

  • Service layer testing
  • Repository testing
  • Utility class testing

Integration Tests

  • API endpoint testing
  • Database integration
  • Message queue integration

Test Utilities

  • TestContainers for database testing
  • MockMvc for API testing
  • Custom test data builders

Monitoring and Observability

Logging

  • Structured logging with correlation IDs
  • Different log levels per environment
  • Centralized log aggregation ready

Metrics

  • Spring Boot Actuator endpoints
  • Custom business metrics
  • Performance monitoring

Health Checks

  • Database connectivity
  • Redis connectivity
  • Kafka connectivity
  • Custom health indicators

This architecture provides a robust, scalable, and maintainable foundation for the Hexagon Feed System, following Spring Boot best practices and supporting the requirements for a location-based social feed application.