

# Service Design Specification
**wechess-leaderboard-service** documentation
**Version:** `1.0.21`

## Scope

This document provides a structured architectural overview of the `leaderboard` microservice, detailing its configuration, data model, authorization logic, business rules, and API design. It has been automatically generated based on the service definition within Mindbricks, ensuring that the information reflects the source of truth used during code generation and deployment.

The document is intended to serve multiple audiences:

* **Service architects** can use it to validate design decisions and ensure alignment with broader architectural goals.
* **Developers and maintainers** will find it useful for understanding the structure and behavior of the service, facilitating easier debugging, feature extension, and integration with other systems.
* **Stakeholders and reviewers** can use it to gain a clear understanding of the service's capabilities and domain logic.

> **Note for Frontend Developers**: While this document is valuable for understanding business logic and data interactions, please refer to the [Service API Documentation](#) for endpoint-level specifications and integration details.

> **Note for Backend Developers**: Since the code for this service is automatically generated by Mindbricks, you typically won't need to implement or modify it manually. However, this document is especially valuable when you're building other services—whether within Mindbricks or externally—that need to interact with or depend on this service. It provides a clear reference to the service's data contracts, business rules, and API structure, helping ensure compatibility and correct integration.



## `Leaderboard` Service Settings

Handles ELO/stat computation and leaderboard management for registered players only. Excludes guest users entirely.

### Service Overview

This service is configured to listen for HTTP requests on port `3001`, 
serving both the main API interface and default administrative endpoints.

The following routes are available by default:

* **API Test Interface (API Face):** `/`
* **Swagger Documentation:** `/swagger`
* **Postman Collection Download:** `/getPostmanCollection`
* **Health Checks:** `/health` and `/admin/health`
* **Current Session Info:** `/currentuser`
* **Favicon:** `/favicon.ico`

The service uses a **PostgreSQL** database for data storage, with the database name set to `wechess-leaderboard-service`.

This service is accessible via the following environment-specific URLs:

* **Preview:** `https://wechess.prw.mindbricks.com/leaderboard-api`
* **Staging:** `https://wechess-stage.mindbricks.co/leaderboard-api`
* **Production:** `https://wechess.mindbricks.co/leaderboard-api`

                                 

### Authentication & Security
- **Login Required**: Yes

This service requires user authentication for access. It supports both JWT and RSA-based authentication mechanisms, ensuring secure user sessions and data integrity.
If a crud route also is configured to require login, 
it will check a valid JWT token in the request query/header/bearer/cookie. If the token is valid, it will extract the user information from the token and make the fetched session data available in the request context.

  
### Service Data Objects
The service uses a **PostgreSQL** database for data storage, with the database name set to `wechess-leaderboard-service`.

Data deletion is managed using a **soft delete** strategy. Instead of removing records from the database, they are flagged as inactive by setting the `isActive` field to `false`.



| Object Name | Description | Public Access |
|-------------|-------------|---------------|
| `playerStats` | Stores aggregate stats for a registered chess player: ELO, win/loss history, streak, last game, etc. Excludes guests. One per registered user. | accessPrivate | 
| `leaderboardEntry` | Holds global leaderboard standings for registered players. Rank, ELO, and season support. Excludes guests. | accessProtected | 




## playerStats Data Object

### Object Overview
**Description:** Stores aggregate stats for a registered chess player: ELO, win/loss history, streak, last game, etc. Excludes guests. One per registered user.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. 
It is defined using the `ObjectSettings` pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

### Core Configuration
- **Soft Delete:** Enabled — Determines whether records are marked inactive (`isActive = false`) instead of being physically deleted.
- **Public Access:** accessPrivate — If enabled, anonymous users may access this object’s data depending on API-level rules.




### Composite Indexes

- **playerStats_userId_unique**: [userId] 
This composite index is defined to optimize query performance for complex queries involving multiple fields.

The index also defines a conflict resolution strategy for duplicate key violations.

When a new record would violate this composite index, the following action will be taken:

**On Duplicate**: `throwError`

An error will be thrown, preventing the insertion of conflicting data.






### Properties Schema


| Property | Type | Required | Description |
|----------|------|----------|-------------|
| `userId` | ID | Yes | The registered user this record belongs to (auth:user.id). |
| `eloRating` | Integer | Yes | Current ELO rating for registered player. |
| `totalGames` | Integer | Yes | Total completed games (wins + losses + draws) for this player. |
| `wins` | Integer | Yes | Number of games won by the player. |
| `losses` | Integer | Yes | Number of games lost by the player. |
| `draws` | Integer | Yes | Number of drawn games by the player. |
| `streak` | Integer | Yes | Current win or loss streak. Positive=win streak, negative=loss streak, 0=none/neutral. |
| `lastGameAt` | Date | No | Timestamp of last completed game for user. |
| `username` | String | No | Display name for the player, publicly visible. |
* Required properties are mandatory for creating objects and must be provided in the request body if no default value is set.



### Default Values
Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body.
Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

- **userId**: '00000000-0000-0000-0000-000000000000'
- **eloRating**: 1200


### Constant Properties

`userId`

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object's lifecycle.
A property is set to be constant if the `Allow Update` option is set to `false`.


### Auto Update Properties

`eloRating` `totalGames` `wins` `losses` `draws` `streak` `lastGameAt` `username`

An update crud API created with the option `Auto Params` enabled will automatically update these properties with the provided values in the request body. 
If you want to update any property in your own business logic not by user input, you can set the `Allow Auto Update` option to false.
These properties will be added to the update API's body parameters and can be updated by the user if any value is provided in the request body.

 



 

 

### Elastic Search Indexing

`userId` `eloRating` `totalGames` `wins` `losses` `draws` `streak` `lastGameAt` `username`

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. 
While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.


### Database Indexing

`userId` `eloRating` `totalGames` `wins` `losses` `draws` `streak`

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval.
Make a property indexed in the database if you want to use it frequently in query filters or sorting.


### Unique Properties

`userId`

Unique properties are enforced to have distinct values across all instances of the data object, preventing duplicate entries.
Note that a unique property is automatically indexed in the database so you will not need to set the `Indexed in DB` option.




### Secondary Key Properties

`userId`

Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns.
Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key.


### Relation Properties

`userId`

Mindbricks supports relations between data objects, allowing you to define how objects are linked together.
You can define relations in the data object properties, which will be used to create foreign key constraints in the database.
For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes.
Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together.

- **userId**: ID
Relation to `user`.id

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null
Required: Yes









## leaderboardEntry Data Object

### Object Overview
**Description:** Holds global leaderboard standings for registered players. Rank, ELO, and season support. Excludes guests.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. 
It is defined using the `ObjectSettings` pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

### Core Configuration
- **Soft Delete:** Enabled — Determines whether records are marked inactive (`isActive = false`) instead of being physically deleted.
- **Public Access:** accessProtected — If enabled, anonymous users may access this object’s data depending on API-level rules.




### Composite Indexes

- **leaderboardEntry_userId_unique**: [userId] 
This composite index is defined to optimize query performance for complex queries involving multiple fields.

The index also defines a conflict resolution strategy for duplicate key violations.

When a new record would violate this composite index, the following action will be taken:

**On Duplicate**: `throwError`

An error will be thrown, preventing the insertion of conflicting data.






### Properties Schema


| Property | Type | Required | Description |
|----------|------|----------|-------------|
| `userId` | ID | Yes | The registered user this leaderboard entry represents. |
| `currentRank` | Integer | Yes | Current leaderboard rank (1=top). Lower is better. |
| `eloRating` | Integer | Yes | Player&#39;s current ELO rating (copy from playerStats). |
| `season` | String | No | Leaderboard season identifier (null for all-time/global, can be set for seasonal leaderboards as needed). |
| `lastRankChangeAt` | Date | No | Timestamp of last rank change/leaderboard update. |
| `username` | String | No | Display name for the player, publicly visible on leaderboard. |
* Required properties are mandatory for creating objects and must be provided in the request body if no default value is set.



### Default Values
Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body.
Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

- **userId**: '00000000-0000-0000-0000-000000000000'
- **currentRank**: 0
- **eloRating**: 0


### Constant Properties

`userId`

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object's lifecycle.
A property is set to be constant if the `Allow Update` option is set to `false`.


### Auto Update Properties

`currentRank` `eloRating` `season` `lastRankChangeAt` `username`

An update crud API created with the option `Auto Params` enabled will automatically update these properties with the provided values in the request body. 
If you want to update any property in your own business logic not by user input, you can set the `Allow Auto Update` option to false.
These properties will be added to the update API's body parameters and can be updated by the user if any value is provided in the request body.

 



 

 

### Elastic Search Indexing

`userId` `currentRank` `eloRating` `season` `lastRankChangeAt` `username`

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. 
While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.


### Database Indexing

`userId` `currentRank` `eloRating`

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval.
Make a property indexed in the database if you want to use it frequently in query filters or sorting.


### Unique Properties

`userId`

Unique properties are enforced to have distinct values across all instances of the data object, preventing duplicate entries.
Note that a unique property is automatically indexed in the database so you will not need to set the `Indexed in DB` option.




### Secondary Key Properties

`userId`

Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns.
Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key.


### Relation Properties

`userId`

Mindbricks supports relations between data objects, allowing you to define how objects are linked together.
You can define relations in the data object properties, which will be used to create foreign key constraints in the database.
For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes.
Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together.

- **userId**: ID
Relation to `user`.id

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null
Required: Yes











## Business Logic



leaderboard has got 6 Business APIs to manage its internal and crud logic. 
For the details of each business API refer to its chapter.

* [Create Playerstats](/businessLogic/createplayerstats)

* [Update Playerstats](/businessLogic/updateplayerstats)

* [Get Playerstats](/businessLogic/getplayerstats)

* [Get Leaderboardentry](/businessLogic/getleaderboardentry)

* [List Leaderboardtopn](/businessLogic/listleaderboardtopn)

* [Create Leaderboardentry](/businessLogic/createleaderboardentry)










## Event Subscriptions

leaderboard has 1 Event Subscription configured. Clients connect via WebSocket (Socket.IO) or SSE to receive real-time Kafka event streams with authorization-driven access control.

| Subscription Name | Transport | Topics | Namespace / Endpoint |
|-------------------|-----------|--------|---------------------|
| `gameEvents` | websocket | 1 | /events/gameEvents |


For detailed documentation on each subscription, refer to:

* [gameEvents](/eventSubscriptions/gameevents)










## Service Library


### Functions

#### failIfNotRegisteredPlayer.js
```js
module.exports = async function failIfNotRegisteredPlayer(userId, context=null) {
    // fetch user role via serviceCommon helper
    const { fetchRemoteObjectByMQuery } = require("serviceCommon");
    const user = await fetchRemoteObjectByMQuery("User", { id: userId });
    if (!user) throw new Error("User does not exist.");
    if (user.roleId !== "registeredPlayer" && user.roleId !== "administrator") throw new Error("Leaderboard and stats are only for registered users.");
    return true;
}
```












---

*This document was generated from the service architecture definition and should be kept in sync with implementation changes.*