mehdi124/chat-service
62.9
Adequate · 21 September 2026
8.1k
lines of production code
Go
primary language
4
measurements over time
What this system is
This system is a real-time chat service built in Go that facilitates private, channel, and group messaging with support for text, files, and media. It manages user authentication, room lifecycle, and message persistence via PostgreSQL, while leveraging Redis for presence tracking and WebSocket delivery, and RabbitMQ for scalable message routing. The service also handles file storage on S3 with automatic media conversion and provides offline push notifications through Google FCM.
Features
Add Redis configuration file with persistence and security settings
A new Redis configuration file has been added to the volumes directory, establishing baseline settings for the Redis instance. This configuration enables password authentication, sets up data persistence via both RDB snapshots (every 5 minutes) and Append-Only File (AOF) logging, and configures memory management with a 256MB limit and LRU eviction policy. It also binds to all network interfaces while keeping protected mode enabled for security.
volumes/config/redis · high confidence
Add shared HTTP response helper for consistent API error handling
A new shared response package has been introduced to standardize how the API formats HTTP responses. This provides helper functions for common scenarios, including successful data returns and specific error states such as internal server errors, bad requests, and unauthorized access, ensuring a consistent JSON structure across the application.
internal/shared/response · high confidence
Added API key and JWT authentication middleware
New middleware functions have been introduced to handle authentication for API routes. The \ApiKeyAuth\ middleware validates requests by checking for a static API key provided in the \x-api-key\ header against a configured value. Additionally, the \Auth\ middleware supports JWT-based user authentication, primarily by parsing the \Authorization\ header for a Bearer token, but also includes a fallback mechanism to accept the token via a \token\ query parameter if the header is absent.
internal/shared/middleware · high confidence
Added Google FCM notification delivery for offline users
The chat service now supports sending push notifications via Google Firebase Cloud Messaging (FCM) to users who are currently offline. This change introduces a new repository implementation in the Google adapter that authenticates using a service account, retrieves the user's FCM device token, and sends a notification payload containing the sender's name and message content. The implementation includes platform-specific configurations for Android, WebPush, and iOS (APNs) to ensure proper delivery and priority handling.
internal/chat/adapter/outbound/repository/google · high confidence
Added JWT token generation and verification utilities
The internal shared JWT package now includes a new \token.go\ file that provides functions to generate signed JSON Web Tokens (using HS256) containing user ID and role claims, and to verify incoming tokens by extracting the user ID. This enables the application to issue and validate authentication tokens for user routes.
internal/shared/jwt · high confidence
Defined core inbound service interfaces for the chat domain
This change introduces the primary inbound port interfaces that define the contract for the chat service's core capabilities. It establishes the \ChatService\ interface for broadcasting messages to rooms and specific users, the \ConnectionService\ for managing WebSocket connections and user online/offline status, and the \MessageService\ for storing, retrieving, searching, and deleting messages. Additionally, it defines interfaces for \RoomService\ (handling room creation, membership, blocking, and searching), \FileService\ (managing uploads, downloads, and pre-signed URLs), \NotificationService\ (sending notifications), and \UserService\ (handling login and profile management). These interfaces serve as the abstraction layer for the application's business logic.
internal/chat/core/port/inboundprt · high confidence
Enable real-time chat via Redis Pub/Sub subscriptions
The chat adapter now uses Redis Pub/Sub to deliver messages to WebSocket clients. A new client initialization component establishes the Redis connection, and a subscription handler listens for messages on user-specific channels, forwarding them to the active WebSocket connection in real-time.
internal/chat/adapter/inbound/redis · high confidence
Entrypoint script sets CONTAINER\_NAME environment variable
The entrypoint script for the chat-go service now automatically detects the Docker container's name via the Docker API and exports it as the CONTAINER\_NAME environment variable, appending this value to the application's .env file before launching the main process.
volumes/entrypoint/chat-go · high confidence
HTTP file upload, download, and presigned URL endpoints
The chat service now exposes HTTP endpoints for managing file attachments within messages. Users can upload files via multipart POST requests to \/file/:message\_id/upload\, which supports chunked uploads and enforces a 20 MB size limit; successful uploads update the message status and broadcast the change. Files can be retrieved via \/file/:message\_id/download\ (with an optional \only\_view\ query parameter) or by generating temporary access links using \/file/:message\_id/generate-presigned-url\. These endpoints are protected by authentication middleware and rely on S3 configuration for storage operations.
internal/chat/adapter/inbound/http/filehttp · high confidence
Initial Nginx reverse proxy configuration for API and WebSocket traffic
This change introduces the initial Nginx configuration file for the \volumes/config/nginx\ location, establishing a reverse proxy setup that terminates SSL (TLS 1.2/1.3) and routes traffic to the \chat\_backend\ upstream. It configures specific handling for API requests at \/api\ and WebSocket connections at \/ws\, including necessary proxy headers, keep-alive settings, and CORS headers for allowed origins. The configuration also enables Gzip compression, sets specific timeouts for WebSocket stability, and includes a health check endpoint at \/health\.
volumes/config/nginx · high confidence
Initial SQL message repository implementation
The SQL outbound repository for chat messages has been implemented, providing the data access layer for the chat service. This includes methods to retrieve individual messages, fetch message lists with pagination and anchor-based navigation, search message content, and manage message lifecycle (store, remove, update status). The implementation handles critical chat behaviors such as marking messages as seen, updating unread message counts in user rooms, and managing parent-child message relationships (replies) within database transactions.
internal/chat/adapter/outbound/repository/sql/messagerepo · high confidence
Initial database schema for chat application
This change introduces the foundational database structure for the chat system, defining the core entities required for messaging functionality. It creates the \users\ table to store account details and privacy settings, the \rooms\ table to manage private, channel, and group conversations with slug-based uniqueness for channels, and the \messages\ table to handle direct, forwarded, and replied messages with content type support (text, file, video, etc.). Additionally, a \user\_rooms\ junction table is established to track user membership, roles (user/admin), and unread message counts within each room, along with necessary foreign keys and indexes to support these relationships.
database · high confidence
Initial domain model and request/response structures for chat service
This change introduces the core domain entities and request/response structures for the chat service, including models for Users, Rooms, Messages, and Members, along with specific request types for operations like adding/removing members, joining/leaving rooms, storing messages, and uploading/downloading files. It also defines the ChatResponse structure for WebSocket communication and a SafeConnection wrapper for thread-safe connection handling.
internal/chat/core/domain · high confidence
Initial implementation of the message service layer
This change introduces the core message service implementation in the \messagesrv\ package, providing the backend logic for chat functionality. It adds capabilities to store new messages (including handling private room creation, channel permissions, and reply/forward logic), retrieve individual messages, list messages via an index, search content, fetch messages around a specific anchor, mark messages as seen, update message status, and remove messages (with associated file cleanup). The service is wired to repository ports for messages, rooms, users, and files, and includes unit tests for the core operations.
internal/chat/core/service/messagesrv · high confidence
Initial infrastructure layer for database, messaging, storage, and API server
This change introduces the core infrastructure components for the application, including a Bun-based PostgreSQL client with transaction support and migration/seed capabilities, a RabbitMQ client with graceful shutdown, a Redis client with health checks, an S3 client for file storage with health checks, and a Fiber-based HTTP server with Swagger documentation and a health endpoint.
infra · high confidence
Initial open-source release with infrastructure and documentation
The repository is now open-source, providing the complete project structure and documentation required to run the Chat Service. This includes a Dockerfile for building the Go application, a comprehensive docker-compose.yaml that orchestrates the full infrastructure stack (PostgreSQL with PgPool load balancing, Redis, RabbitMQ cluster, and Nginx), and a .env.example file detailing all necessary configuration parameters. Additionally, standard open-source governance files such as the MIT License, Code of Conduct, Contributing guidelines, and Security policy have been added to support community adoption.
(repo-wide) · high confidence
Introduce centralized configuration management with Viper
The application now uses a centralized configuration system via the Viper library, defined in the new \config/config.go\ file. This change introduces support for loading settings from environment variables and \.env\ files, covering infrastructure connections for PostgreSQL (including replica support), Redis, S3 storage, RabbitMQ, and Google services, as well as application-level settings like JWT secrets, API prefixes, and upload limits.
config · high confidence
Introduce connection service for managing WebSocket connections and user status
The chat service now includes a dedicated connection service that manages WebSocket connections and user status. This service provides methods to create new connections, retrieve connection details, check user status, close connections, and track total active connections. It also supports setting replica offline status, enabling better control over connection lifecycle and user presence tracking within the chat system.
internal/chat/core/service/connectionsrv · high confidence
Introduce file service for chat room image uploads and management
The chat service now includes a dedicated file service implementation that enables uploading room images with validation (size and MIME type checks), handling multipart uploads with chunking and Redis-based locking, and providing operations for downloading, copying, removing, and generating presigned URLs for files. This change adds the core service logic and repository interactions required to manage file assets within chat rooms.
internal/chat/core/service/filesrv · high confidence
Introduces SQL repository models for chat domain entities
This change adds the SQL adapter models for the chat service's core domain entities, including User, Room, Member, Message, and UserRoom. These new files define the database schema mappings (using Bun ORM tags) and conversion logic between the internal domain models and the relational database structure, enabling the persistence layer to store and retrieve chat rooms, messages, and user memberships.
internal/chat/adapter/outbound/repository/sql/model · high confidence
Introduces chat service with broadcast and notification capabilities
The chat service now supports broadcasting messages to all users, all except the sender, or a specific selection of users within a room. It also includes functionality to bind and unbind user queues and sends notifications for new messages.
internal/chat/core/service/chatsrv · high confidence
Introduces domain value objects for chat entities
This change adds a set of new value objects in the chat core domain to define specific types and statuses for chat features. It introduces constants for message content types (such as file, video, image, voice, text, and announcement), message statuses (sent, sending, failed), and message types (direct, forwarded, replied). It also defines room-related types including room types (private, channel, group), room statuses (block, unblock), and search filters (private, channel). Additionally, it establishes user-related value objects for privacy modes (hidden, visible), room roles (user, admin), and online status (online, offline, last recently), along with an announcement message template and a generic ID type with zero-value checking.
internal/chat/core/domain/valueobject · high confidence
New CLI commands for app execution, database migration, and token generation
The command-line interface now includes structured subcommands for managing the application lifecycle. Users can run the application via the new 'app run' command, manage the database schema with 'migrate up', 'migrate down', and 'migrate seed' commands, and generate JWT tokens for testing using the 'token init' command. All commands support a '--config-file' flag to specify the configuration source.
cmd · high confidence
New HTTP endpoints for message listing, search, deletion, and context retrieval
The chat service now exposes several new HTTP endpoints for managing messages within rooms. Users can list messages in a room using the new index endpoint, which supports pagination via a 'before' timestamp and a limit parameter. A new search endpoint allows users to find messages within a room by text, with input validation requiring at least three characters and allowing alphanumeric, Persian, and space characters. Messages can now be deleted via a remove endpoint, which triggers a broadcast notification to other participants in the room. Additionally, a new 'around anchor' endpoint enables retrieving messages surrounding a specific message ID, supporting 'before' and 'after' counts for context. All these endpoints require user authentication and are grouped under the /message route.
internal/chat/adapter/inbound/http/messagehttp · high confidence
New HTTP endpoints for room lifecycle, membership, and blocking
The chat service now exposes a comprehensive set of HTTP endpoints for managing chat rooms. Users can create rooms with a validated alphanumeric slug and optional image, search for rooms, and list their active rooms. Membership management includes joining, leaving, adding, and removing members, with automatic announcement broadcasts for group changes. Additionally, users can block and unblock rooms, which triggers status updates to relevant clients. All endpoints are secured via authentication middleware and follow a consistent request/response structure.
internal/chat/adapter/inbound/http/roomhttp · high confidence
New HTTP endpoints for user authentication and profile management
This change introduces the HTTP adapter layer for user-related operations, exposing routes for login, retrieving user profiles, and updating user profiles. The \/user/login\ endpoint accepts credentials and returns a JWT token, while the \/setting/set-profile\ and \/setting/get-profile\ endpoints allow authenticated users to manage their profile details such as bio and privacy mode. These endpoints are wired to the existing \UserService\ and protected by API key and JWT authentication middlewares.
internal/chat/adapter/inbound/http/userhttp · high confidence
New domain models and shared validation infrastructure
This change introduces new domain structures for server dependencies (including API and WebSocket routers and middleware definitions) and establishes a set of value objects to standardize naming prefixes for RabbitMQ resources such as channels, consumer tags, exchanges, queues, and routing keys. Additionally, it adds a shared validation package that wraps the go-playground/validator library, providing a reusable struct validation helper and a custom 'valid' validation tag to support consistent input validation across the application.
internal/shared/domain · high confidence
New request body loading and validation middleware
The internal shared dependency layer now includes a new body loading mechanism that automatically parses incoming request bodies and validates them against struct definitions. This change introduces a Loader interface and a BodyLoader function that integrates with the Fiber web framework to handle parsing and validation errors consistently, simplifying how request data is processed and verified before reaching application handlers.
internal/shared/dependency · high confidence
New user service implementation with login and profile capabilities
The internal chat service now includes a new user service implementation located in \internal/chat/core/service/usersrv\. This adds the ability to authenticate users via a \Login\ method that supports creating new users with generated usernames on first access, retrieving users by ID, updating user profiles via \SetProfile\, and fetching full names for multiple user IDs. The service is wired to the existing repository interfaces and includes comprehensive unit tests covering success and error paths for these operations.
internal/chat/core/service/usersrv · high confidence
PostgreSQL configuration for cluster and replication support
Added explicit configuration files for PostgreSQL to support a clustered environment with read replicas. The new postgresql.conf sets memory limits (e.g., 4GB shared buffers), enables WAL replication settings, and configures logging. The new pg\_hba.conf defines access control rules, allowing remote and local connections for the postgres and replicator users, and permitting replication traffic from any IP.
volumes/config/postgres · high confidence
PostgreSQL primary node initialization and replication setup
The PostgreSQL primary container now includes a dedicated entrypoint script that automatically initializes the database if it is not already set up. This process creates the main application database and a dedicated replication user, ensuring the environment is ready for cluster connectivity. The script also ensures the latest pg\_hba.conf is applied before starting PostgreSQL in the foreground.
volumes/entrypoint/postgres · high confidence
RabbitMQ cluster entrypoint script added
A new shell script at volumes/entrypoint/rabbitmq/cluster.sh has been introduced to manage RabbitMQ startup behavior. This script enables cluster formation by checking for a JOIN\_CLUSTER\_HOST environment variable; if present, it joins the node to the specified cluster, otherwise it starts as a standalone server. The script handles process management by waiting for the node to be ready and keeping the container running via a foreground tail command.
volumes/entrypoint/rabbitmq · high confidence
RabbitMQ-based message consumption for chat service
The chat adapter now consumes messages from RabbitMQ queues instead of relying solely on direct WebSocket handling. A new client initializes a RabbitMQ connection and spawns consumers for multiple queues (based on container name and total queue count). Messages are routed to specific users via routing keys, and upon successful consumption, the message body is sent to the user's WebSocket connection via a channel. If a user's connection is unavailable, the message is acknowledged without delivery. This change introduces a pub/sub pattern for chat messages, improving reliability and scalability by decoupling message reception from immediate WebSocket delivery.
internal/chat/adapter/inbound/rabbitmq · high confidence
Redis-backed chunk repository implementation for file uploads
The Redis adapter for the chunk repository has been implemented, providing the underlying storage logic for file upload operations. This includes methods to manage upload IDs and tags (set/get), check existence, delete data, and acquire/release distributed locks to handle concurrent multipart uploads safely. The repository connects to Redis using configured prefixes for upload IDs and tags, ensuring that file chunk metadata is stored and retrieved correctly during the upload lifecycle.
internal/chat/adapter/outbound/repository/redis/chunkrepo · high confidence
Redis-backed connection repository with user status tracking and safe connection handling
The chat service now uses a new Redis-based repository to manage WebSocket connections and user presence. This change introduces safe connection handling with mutex-protected access, tracks user online/offline status in Redis with a one-week expiration, and supports graceful shutdown by marking replica connections as offline. Users benefit from more reliable connection management and accurate presence information.
internal/chat/adapter/outbound/repository/redis/connectionrepo · high confidence
Room management service implementation
The internal chat service now includes a comprehensive room management layer that supports creating, updating, and deleting rooms with optional image uploads, joining and leaving rooms, managing member lists (adding/removing members), blocking and unblocking rooms, and searching rooms by type (channels or private rooms).
internal/chat/core/service/roomsrv · high confidence
S3 file storage adapter with multipart uploads and WebM conversion
The S3 outbound repository now implements a complete file storage workflow, including automatic bucket creation, single-part and multipart uploads, file copying, deletion, and presigned URL generation. A key behavioral addition is the automatic conversion of WebM audio files to MP3 format during both upload and download operations to ensure consistent playback, and presigned URLs now correctly support inline viewing versus attachment download based on request parameters.
internal/chat/adapter/outbound/repository/s3 · high confidence
SQL repository implementation for room management and membership
The SQL outbound repository for chat rooms has been implemented, providing the data access layer for room lifecycle and membership operations. This includes creating rooms with initial members, listing user rooms with unread counts and last message details, and retrieving individual room details. Membership management features allow admins to add or remove members from groups and channels (with max count and admin-presence validation), while regular users can join channels or leave rooms. The repository also supports blocking and unblocking private rooms, updating room metadata (name, slug, description, image), and searching for public channels by name/slug or private users by username/fullname. Unread message counts are tracked and updated per user-room association.
internal/chat/adapter/outbound/repository/sql/roomrepo · high confidence
Architecture
Defined outbound repository interfaces for chat domain
The \internal/chat/core/port/outboundprt\ package now exposes the core data-access contracts for the chat service. New interfaces have been added for Chat, Chunk, Connection, File, Message, Notification, Room, and User repositories, establishing the specific operations (such as message indexing, room membership management, file uploads, and WebSocket connection tracking) that the application layer will use to interact with external storage and messaging systems.
internal/chat/core/port/outboundprt · high confidence
Behavioural changes
Application initialization and dependency injection via Wire
The core application startup logic has been restructured to use Google Wire for dependency injection. The new \app.go\ entry point now explicitly initializes and manages the lifecycles of Redis, S3, and RabbitMQ clients, including background health checks for Redis and S3, and graceful shutdown handling. The \wire.go\ and generated \wire\_gen.go\ files define the dependency graph, wiring together HTTP and WebSocket handlers, services, and repositories (SQL, Redis, S3, RabbitMQ, Google Notifications) to ensure the application starts with a fully configured and connected state.
core · high confidence
RabbitMQ chat repository implements load-balanced pub/sub with message serialization
The RabbitMQ outbound adapter for the chat service has been replaced with a new implementation that supports publish/subscribe messaging across multiple queues. To distribute load, the repository now uses an FNV-1a hash of the user's routing key to deterministically select one of several configured queues (load balancing). Messages are serialized using MsgPack instead of JSON, and the serialization logic automatically injects the current unread message count into the payload for new messages, announcements, seen events, and deletions. The adapter also handles dynamic queue binding and unbinding per user, scoped by a container name configuration.
internal/chat/adapter/outbound/repository/rabbitmq · high confidence
SQL implementation for user repository operations
The chat service now persists user data using a SQL database via the new \userrepo\ package. This change enables users to create accounts, update their profile information (such as bio and privacy settings), and retrieve user details by ID, reference ID, or username. It also supports fetching full names for multiple users at once, replacing any previous in-memory or alternative storage mechanisms for these specific user-related actions.
internal/chat/adapter/outbound/repository/sql/userrepo · high confidence
WebSocket chat adapter with messagepack serialization and thread-safe writes
The WebSocket inbound adapter for chat now uses a new \chatwebsocket\ package that serializes requests and responses with MessagePack and routes writes through a Go channel protected by a mutex to ensure thread safety. Clients can send 'message', 'seen', and 'ping' request types; messages are stored, acknowledged to the sender, and broadcast to other room members, while 'seen' updates are persisted and 'ping' returns a pong. The adapter enforces read deadlines, validates content types and required fields, and manages connection lifecycle (bind/unbind queues and user status) via the connection service.
internal/chat/adapter/inbound/websocket · high confidence
Test coverage
Added generated mock implementations for core repository and service interfaces
The \internal/chat/core/port/mocks\ package now includes generated GoMock stubs for the chat service's core domain interfaces, enabling unit testing of components that depend on these ports. The new files provide mock implementations for \ChatRepository\, \ConnectionRepository\, \FileRepository\, \FileService\, \MessageRepository\, \NotificationRepository\, \RoomRepository\, and \UserRepository\, covering methods such as message storage, room management, file uploads, and user profile updates.
internal/chat/core/port/mocks · high confidence
Dependencies
Initial dependency manifest for chat-service
The project now includes a go.mod and go.sum file defining the Go 1.22.3 module github.com/mehdi124/chat-service. This establishes the direct dependencies required for the service, including the Fiber web framework, RabbitMQ client, Redis client, JWT library, and the Bun SQL toolkit, along with their indirect dependencies.
(dependencies) · high confidence
Written by watchdog.canine.dev from the codebase's own history, inside the signed delivery this page is composed from.
How this codebase got here
Baseline
- First survey — no prior run to compare against. CAI 63.
Lenses
- Code Health 93
- Architecture 65
- Maturity 58
- Readiness 59
- Security 73
- Domain Modelling 93
Changes since last survey
- 212 commits — 89 feature/other, 123 fixes
By area
- internal/chat — 132 commits
- (root) — 30 commits
- volumes/config — 22 commits
- infra/server.go — 8 commits
- database/migration — 4 commits
- core/app — 3 commits
- cmd/migrate.go — 2 commits
- infra/rabbitmq.go — 2 commits
- infra/s3.go — 2 commits
- internal/shared — 2 commits
- sandbox/data — 2 commits
- cmd/root.go — 1 commit
- docs/openapi.yaml — 1 commit
- volumes/data — 1 commit
Notable commits
- fix: fix : s
- fix: fix : s
- fix: fix: Dockerfile
- fix: fix: add .gitignore
- fix: fix: add only view to file presigned url
- fix: fix: add rollback to remove message
- fix: fix: add sign to last_message of room
- fix: fix: add unread message bug
- fix: fix: api key middleware
- fix: fix: bug
- fix: fix: bug
- fix: fix: bug rabbitmq
- fix: fix: c
- fix: fix: chat conetnt limit
- fix: fix: chat request anouncement validation
- fix: fix: completed message response
- fix: fix: consume
- fix: fix: convert webm to mp3
- fix: fix: cor
- fix: fix: cors
- …and 192 more
Written by watchdog.canine.dev from the codebase's own history, inside the signed delivery this page is composed from.
Survey your own repository
mehdi124/chat-service was measured the same way every project in this corpus was: the same rubric, at a pinned commit, with the result published in full. Point a surveyor at a repository you know and see whether you agree with it.
About this page
- The score is its most recent published measurement, taken on 21 September 2026 at a pinned commit. It is not a live figure and does not change until the project is measured again.
- Measured at commit 1258d632dc7360793455ca9969c0343dd99b9daa — the exact code this score is about.
- Scored under rubric-2026.09.15 — the same rubric and the same method as every other entry in this index.
- Measured by watchdog.canine.dev using codehealth-analyzer preprod-28e75b8e3254.