Skip to content

Commit bbc1179

Browse files
committed
feat(arch): design SQL Server 2022 E/R model and integrate into architecture spec (EN/ES)
1 parent 42fd4bd commit bbc1179

4 files changed

Lines changed: 362 additions & 4 deletions

File tree

architecture/blueprints-es/architecture-spec.md

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@ La siguiente tabla define los entregables obligatorios, el alcance estratégico
1717
| **2** | [Definición del Core de la Plataforma](#-7-arquitectura-del-motor-de-autorización-centralizado-peppdppappip) | Estrategia que identifica capacidades transversales (Identidad, Datos Maestros, Bus de Eventos, API Gateway), su propósito común y principios de reutilización. Justifica las inversiones en componentes compartidos. |
1818
| **3** | [Diagrama C4 (Contexto, Contenedor, Componente)](#-2-modelo-c4) | Visión arquitectónica en los niveles 1 y 2: sistemas externos, contenedores grandes y comunicación entre ellos. Dimensiona la complejidad técnica y permite estimar el esfuerzo sin detallar clases o componentes internos. |
1919
| **4** | [Estrategia de Base de Datos](#-8-estrategia-de-base-de-datos-y-aislamiento-multitenant-rls) | Sustenta la elección del patrón de persistencia (Base de datos por módulo), pautas para transacciones distribuidas y políticas generales de respaldo y recuperación. Detalla el impacto en costos y operaciones. |
20-
| **5** | [Modelo de Dominio de Eventos (Event Storming)](#-10-modelo-de-comunicación-asíncrona-y-eventos) | Mapa de eventos de negocio relevantes, sus productores y consumidores, junto con los principios de entrega y ordenamiento. Guía la integración y el esfuerzo asociado con la orquestación/coreografía. |
20+
| **5** | [Modelo Entidad-Relación (E/R)](./database-design-er.md) | Representación lógica y física de las entidades de UMS (Identidad, RBAC, Multi-tenancy) optimizada para SQL Server 2022. |
21+
| **6** | [Modelo de Dominio de Eventos (Event Storming)](#-10-modelo-de-comunicación-asíncrona-y-eventos) | Mapa de eventos de negocio relevantes, sus productores y consumidores, junto con los principios de entrega y ordenamiento. Guía la integración y el esfuerzo asociado con la orquestación/coreografía. |
2122
| **6** | [Estrategia de Observabilidad Extremo a Extremo](#-9-estrategia-de-observabilidad-y-telemetría-distribuida) | Enfoque para la telemetría distribuida: trazabilidad de procesos de negocio completos, métricas clave y modelos de registro (logging) a nivel arquitectónico. Se utiliza para estimar herramientas de monitoreo y costos. |
2223
| **7** | [Diseño de Identidad y Autorización](#-7-arquitectura-del-motor-de-autorización-centralizado-peppdppappip) | Estrategia para el modelo de identidad y autorización: Proveedor de Identidad (IdP), flujo de autenticación entre contextos y pautas de sesión. Ayuda a dimensionar la seguridad en todos los dominios. |
2324
| **8** | Requerimientos No Funcionales Documentados (NFRs) | Definición de requisitos no funcionales medibles que condicionan la arquitectura: latencia, rendimiento (throughput), disponibilidad y mecanismos de degradación controlada. Representa los objetivos contractuales que el diseño debe cumplir. |
@@ -365,5 +366,15 @@ graph TD
365366
Para garantizar que los cambios en un contexto no rompan a sus consumidores, se implementan pruebas de contrato automatizadas.
366367

367368
- **Pruebas de Unidad**: Lógica pura en `Ums.Domain`.
368-
- **Pruebas de Integración**: Uso de **Testcontainers** para validar el comportamiento real con PostgreSQL y Redis.
369+
- **Pruebas de Integración**: Uso de **Testcontainers** para validar el comportamiento real con SQL Server y Redis.
369370
- **Pruebas de Contrato**: Validación de esquemas OpenAPI y eventos asíncronos.
371+
372+
---
373+
374+
## 🗄️ 13. Modelado de Datos y Persistencia (E/R)
375+
376+
La estructura lógica de persistencia está diseñada para soportar las complejidades de un sistema de gestión de identidades empresarial con aislamiento de datos nativo. El modelo separa claramente las preocupaciones de identidad, credenciales, perfiles y autorización jerárquica.
377+
378+
Para ver el diseño detallado, tipos de datos específicos de SQL Server y políticas de seguridad implementadas, consulte:
379+
👉 **[Diseño Detallado del Modelo E/R (SQL Server 2022)](./database-design-er.md)**
380+
Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,168 @@
1+
# 🗄️ Modelo Entidad-Relación (E/R) - SQL Server 2022
2+
3+
**Tipo de Documento:** Diseño de Base de Datos
4+
**Estatus:** Propuesto
5+
**Arquitectura:** Multi-tenancy (Esquema Compartido + RLS)
6+
**Motor:** SQL Server 2022
7+
8+
## 1. Introducción
9+
Este documento detalla el diseño del modelo de datos para el **User Management System (UMS)**. El diseño está optimizado para **SQL Server 2022**, utilizando tipos de datos modernos y una estructura que facilita el aislamiento de datos mediante **Row-Level Security (RLS)** y el uso de `SESSION_CONTEXT`.
10+
11+
---
12+
13+
## 2. Diagrama E/R (Mermaid)
14+
15+
```mermaid
16+
erDiagram
17+
TENANT ||--o{ USER : "pertenece_a"
18+
TENANT ||--o{ ROLE : "define"
19+
TENANT ||--o{ BRANCH : "posee"
20+
TENANT ||--o{ AUDIT_LOG : "genera"
21+
22+
USER ||--|| USER_CREDENTIAL : "tiene"
23+
USER ||--|| PROFILE : "tiene"
24+
USER ||--o{ USER_ROLE : "asignado_a"
25+
USER ||--o{ USER_BRANCH : "opera_en"
26+
27+
ROLE ||--o{ ROLE_PERMISSION : "contiene"
28+
ROLE ||--o{ USER_ROLE : "asignado_a"
29+
30+
PERMISSION ||--o{ ROLE_PERMISSION : "asociado_a"
31+
32+
BRANCH ||--o{ USER_BRANCH : "asociado_a"
33+
34+
TENANT {
35+
uniqueidentifier TenantId PK
36+
nvarchar Name "NOT NULL"
37+
nvarchar Code "UK, NOT NULL"
38+
int Status "NOT NULL"
39+
datetimeoffset CreatedAt "DEFAULT GETDATE()"
40+
}
41+
42+
USER {
43+
uniqueidentifier UserId PK
44+
uniqueidentifier TenantId FK "RLS"
45+
nvarchar Username "UK, NOT NULL"
46+
nvarchar Email "UK, NOT NULL"
47+
bit IsActive "DEFAULT 1"
48+
bit IsServiceAccount "DEFAULT 0"
49+
datetimeoffset CreatedAt
50+
}
51+
52+
USER_CREDENTIAL {
53+
uniqueidentifier CredentialId PK
54+
uniqueidentifier UserId FK "UK"
55+
nvarchar PasswordHash "NOT NULL"
56+
nvarchar SecurityStamp
57+
datetimeoffset LastChangedAt
58+
}
59+
60+
PROFILE {
61+
uniqueidentifier ProfileId PK
62+
uniqueidentifier UserId FK "UK"
63+
nvarchar FirstName
64+
nvarchar LastName
65+
nvarchar Attributes "JSON (ABAC)"
66+
}
67+
68+
ROLE {
69+
uniqueidentifier RoleId PK
70+
uniqueidentifier TenantId FK
71+
nvarchar Name "NOT NULL"
72+
nvarchar Description
73+
bit IsSystemRole "DEFAULT 0"
74+
}
75+
76+
PERMISSION {
77+
uniqueidentifier PermissionId PK
78+
nvarchar Code "UK, NOT NULL"
79+
nvarchar Name "NOT NULL"
80+
nvarchar Category
81+
}
82+
83+
ROLE_PERMISSION {
84+
uniqueidentifier RoleId PK, FK
85+
uniqueidentifier PermissionId PK, FK
86+
}
87+
88+
USER_ROLE {
89+
uniqueidentifier UserId PK, FK
90+
uniqueidentifier RoleId PK, FK
91+
}
92+
93+
BRANCH {
94+
uniqueidentifier BranchId PK
95+
uniqueidentifier TenantId FK
96+
nvarchar Name "NOT NULL"
97+
nvarchar Code "NOT NULL"
98+
}
99+
100+
USER_BRANCH {
101+
uniqueidentifier UserId PK, FK
102+
uniqueidentifier BranchId PK, FK
103+
}
104+
105+
AUDIT_LOG {
106+
bigint LogId PK "IDENTITY"
107+
uniqueidentifier TenantId FK
108+
uniqueidentifier UserId FK
109+
nvarchar Action "NOT NULL"
110+
nvarchar EntityName "NOT NULL"
111+
nvarchar EntityId
112+
nvarchar OldValue "JSON"
113+
nvarchar NewValue "JSON"
114+
datetimeoffset Timestamp "DEFAULT GETDATE()"
115+
}
116+
```
117+
118+
---
119+
120+
## 3. Diccionario de Datos y Tipos SQL Server
121+
122+
### 3.1 Estándares de Tipos
123+
* **Identificadores (PK/FK):** `uniqueidentifier` utilizando `NEWSEQUENTIALID()` en SQL Server para evitar fragmentación de índices.
124+
* **Fechas:** `datetimeoffset` para garantizar precisión en zonas horarias globales.
125+
* **Cadenas:** `nvarchar(n)` para soporte Unicode completo.
126+
* **Metadatos/ABAC:** `nvarchar(max)` con validación `ISJSON()` para flexibilidad de atributos dinámicos.
127+
128+
### 3.2 Tablas Principales
129+
130+
| Tabla | Propósito | Estrategia de Índice |
131+
| :--- | :--- | :--- |
132+
| `Tenants` | Maestro de inquilinos. | Clustered en `TenantId`. Unique en `Code`. |
133+
| `Users` | Identidades de usuario. | Clustered en `UserId`. Non-clustered en `TenantId` (RLS Optimization). |
134+
| `Roles` | Definición de roles por tenant. | Filtrado por `TenantId`. |
135+
| `AuditLogs` | Trazabilidad de cambios. | Clustered en `LogId` (bigint identity). Particionado por `Timestamp` si la escala aumenta. |
136+
137+
---
138+
139+
## 4. Implementación de Multi-tenancy (RLS)
140+
141+
Para SQL Server, la propuesta de aislamiento se basa en el uso de **Security Policies** y **Inline Table-Valued Functions (iTVF)**.
142+
143+
### Función de Filtro Predicado
144+
```sql
145+
CREATE FUNCTION Security.fn_tenantSecurityPredicate(@TenantId uniqueidentifier)
146+
RETURNS TABLE
147+
WITH SCHEMABINDING
148+
AS
149+
RETURN SELECT 1 AS fn_security_predicate_result
150+
WHERE @TenantId = CAST(SESSION_CONTEXT(N'TenantId') AS uniqueidentifier)
151+
OR CAST(SESSION_CONTEXT(N'IsSuperAdmin') AS bit) = 1;
152+
```
153+
154+
### Política de Seguridad
155+
```sql
156+
CREATE SECURITY POLICY Security.TenantIdFilter
157+
ADD FILTER PREDICATE Security.fn_tenantSecurityPredicate(TenantId) ON dbo.Users,
158+
ADD FILTER PREDICATE Security.fn_tenantSecurityPredicate(TenantId) ON dbo.Roles,
159+
ADD FILTER PREDICATE Security.fn_tenantSecurityPredicate(TenantId) ON dbo.AuditLogs
160+
WITH (STATE = ON);
161+
```
162+
163+
---
164+
165+
## 5. Consideraciones para el Blueprint
166+
1. **Escalabilidad:** Se recomienda el uso de **Indexes Columnstore** en la tabla `AuditLogs` si el volumen de auditoría supera los millones de registros.
167+
2. **Integridad:** Todas las relaciones N:M se manejan mediante tablas de unión con claves compuestas para optimizar la navegación.
168+
3. **Seguridad:** Los hashes de contraseña nunca deben almacenarse en la tabla `Users`, sino en `UserCredentials` para permitir la rotación de secretos y múltiples métodos de autenticación (ej. MFA).

architecture/blueprints/architecture-spec.md

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@ The following table defines the mandatory deliverables, strategic scope, and con
1717
| **2** | [Platform Core Definition](#-7-centralized-authorization-engine-architecture-peppdppappip) | Strategy that identifies cross-cutting capabilities (Identity, Master Data, Event Bus, API Gateway), their common purpose, and reuse principles. Justifies investments in shared components. |
1818
| **3** | [C4 Diagram (Context, Container, Component)](#-2-c4-model) | Architectural vision at levels 1 and 2: external systems, large containers, and communication between them. Sizes technical complexity and allows estimating effort without detailing classes or internal components. |
1919
| **4** | [Database Strategy](#-8-database-strategy--multi-tenant-isolation-rls) | Substantiates the choice of persistence pattern (Database-per-Module), guidelines for distributed transactions, and general backup and recovery policies. Details the impact on costs and operations. |
20-
| **5** | [Event Domain Model (Event Storming)](#-10-asynchronous-communication--event-model) | Map of relevant business events, their producers, and consumers, along with delivery and ordering principles. Guides integration and the effort associated with orchestration/choreography. |
20+
| **5** | [Entity-Relationship (E/R) Model](./database-design-er.md) | Logical and physical representation of UMS entities (Identity, RBAC, Multi-tenancy) optimized for SQL Server 2022. |
21+
| **6** | [Event Domain Model (Event Storming)](#-10-asynchronous-communication--event-model) | Map of relevant business events, their producers, and consumers, along with delivery and ordering principles. Guides integration and the effort associated with orchestration/choreography. |
2122
| **6** | [End-to-End Observability Strategy](#-9-observability--distributed-telemetry-strategy) | Approach to distributed telemetry: traceability of complete business processes, key metrics, and logging models at the architectural level. Used to estimate monitoring tools and costs. |
2223
| **7** | [Identity & Authorization Design](#-7-centralized-authorization-engine-architecture-peppdppappip) | Strategy for the identity and authorization model: Identity Provider (IdP), authentication flow between contexts, and session guidelines. Helps size security across all domains. |
2324
| **8** | Documented Non-Functional Requirements (NFRs) | Definition of measurable non-functional requirements that condition the architecture: latency, throughput, availability, and graceful degradation mechanisms. Represents contractual targets that the design must meet. |
@@ -367,8 +368,18 @@ graph TD
367368
To ensure that changes in one context do not break its consumers, automated contract tests are implemented.
368369

369370
- **Unit Tests**: Pure logic in `Ums.Domain`.
370-
- **Integration Tests**: Using **Testcontainers** to validate real behavior with PostgreSQL and Redis.
371+
- **Integration Tests**: Using **Testcontainers** to validate real behavior with SQL Server and Redis.
371372
- **Contract Tests**: Validation of OpenAPI schemas and asynchronous events.
372373

374+
---
375+
376+
## 🗄️ 13. Data Modeling & Persistence (E/R)
377+
378+
The logical persistence structure is designed to support the complexities of an enterprise identity management system with native data isolation. The model clearly separates identity, credentials, profiles, and hierarchical authorization concerns.
379+
380+
To view the detailed design, SQL Server specific data types, and implemented security policies, consult:
381+
👉 **[Detailed E/R Model Design (SQL Server 2022)](./database-design-er.md)**
382+
383+
373384

374385

Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,168 @@
1+
# 🗄️ Entity-Relationship (E/R) Model - SQL Server 2022
2+
3+
**Document Type:** Database Design
4+
**Status:** Proposed
5+
**Architecture:** Multi-tenancy (Shared Schema + RLS)
6+
**Engine:** SQL Server 2022
7+
8+
## 1. Introduction
9+
This document details the data model design for the **User Management System (UMS)**. The design is optimized for **SQL Server 2022**, utilizing modern data types and a structure that facilitates data isolation through **Row-Level Security (RLS)** and the use of `SESSION_CONTEXT`.
10+
11+
---
12+
13+
## 2. E/R Diagram (Mermaid)
14+
15+
```mermaid
16+
erDiagram
17+
TENANT ||--o{ USER : "belongs_to"
18+
TENANT ||--o{ ROLE : "defines"
19+
TENANT ||--o{ BRANCH : "owns"
20+
TENANT ||--o{ AUDIT_LOG : "generates"
21+
22+
USER ||--|| USER_CREDENTIAL : "has"
23+
USER ||--|| PROFILE : "has"
24+
USER ||--o{ USER_ROLE : "assigned_to"
25+
USER ||--o{ USER_BRANCH : "operates_in"
26+
27+
ROLE ||--o{ ROLE_PERMISSION : "contains"
28+
ROLE ||--o{ USER_ROLE : "assigned_to"
29+
30+
PERMISSION ||--o{ ROLE_PERMISSION : "associated_with"
31+
32+
BRANCH ||--o{ USER_BRANCH : "associated_with"
33+
34+
TENANT {
35+
uniqueidentifier TenantId PK
36+
nvarchar Name "NOT NULL"
37+
nvarchar Code "UK, NOT NULL"
38+
int Status "NOT NULL"
39+
datetimeoffset CreatedAt "DEFAULT GETDATE()"
40+
}
41+
42+
USER {
43+
uniqueidentifier UserId PK
44+
uniqueidentifier TenantId FK "RLS"
45+
nvarchar Username "UK, NOT NULL"
46+
nvarchar Email "UK, NOT NULL"
47+
bit IsActive "DEFAULT 1"
48+
bit IsServiceAccount "DEFAULT 0"
49+
datetimeoffset CreatedAt
50+
}
51+
52+
USER_CREDENTIAL {
53+
uniqueidentifier CredentialId PK
54+
uniqueidentifier UserId FK "UK"
55+
nvarchar PasswordHash "NOT NULL"
56+
nvarchar SecurityStamp
57+
datetimeoffset LastChangedAt
58+
}
59+
60+
PROFILE {
61+
uniqueidentifier ProfileId PK
62+
uniqueidentifier UserId FK "UK"
63+
nvarchar FirstName
64+
nvarchar LastName
65+
nvarchar Attributes "JSON (ABAC)"
66+
}
67+
68+
ROLE {
69+
uniqueidentifier RoleId PK
70+
uniqueidentifier TenantId FK
71+
nvarchar Name "NOT NULL"
72+
nvarchar Description
73+
bit IsSystemRole "DEFAULT 0"
74+
}
75+
76+
PERMISSION {
77+
uniqueidentifier PermissionId PK
78+
nvarchar Code "UK, NOT NULL"
79+
nvarchar Name "NOT NULL"
80+
nvarchar Category
81+
}
82+
83+
ROLE_PERMISSION {
84+
uniqueidentifier RoleId PK, FK
85+
uniqueidentifier PermissionId PK, FK
86+
}
87+
88+
USER_ROLE {
89+
uniqueidentifier UserId PK, FK
90+
uniqueidentifier RoleId PK, FK
91+
}
92+
93+
BRANCH {
94+
uniqueidentifier BranchId PK
95+
uniqueidentifier TenantId FK
96+
nvarchar Name "NOT NULL"
97+
nvarchar Code "NOT NULL"
98+
}
99+
100+
USER_BRANCH {
101+
uniqueidentifier UserId PK, FK
102+
uniqueidentifier BranchId PK, FK
103+
}
104+
105+
AUDIT_LOG {
106+
bigint LogId PK "IDENTITY"
107+
uniqueidentifier TenantId FK
108+
uniqueidentifier UserId FK
109+
nvarchar Action "NOT NULL"
110+
nvarchar EntityName "NOT NULL"
111+
nvarchar EntityId
112+
nvarchar OldValue "JSON"
113+
nvarchar NewValue "JSON"
114+
datetimeoffset Timestamp "DEFAULT GETDATE()"
115+
}
116+
```
117+
118+
---
119+
120+
## 3. Data Dictionary & SQL Server Types
121+
122+
### 3.1 Type Standards
123+
* **Identifiers (PK/FK):** `uniqueidentifier` using `NEWSEQUENTIALID()` in SQL Server to avoid index fragmentation.
124+
* **Dates:** `datetimeoffset` to ensure precision across global time zones.
125+
* **Strings:** `nvarchar(n)` for full Unicode support.
126+
* **Metadata/ABAC:** `nvarchar(max)` with `ISJSON()` validation for dynamic attribute flexibility.
127+
128+
### 3.2 Primary Tables
129+
130+
| Table | Purpose | Index Strategy |
131+
| :--- | :--- | :--- |
132+
| `Tenants` | Tenant master. | Clustered on `TenantId`. Unique on `Code`. |
133+
| `Users` | User identities. | Clustered on `UserId`. Non-clustered on `TenantId` (RLS Optimization). |
134+
| `Roles` | Role definition per tenant. | Filtered by `TenantId`. |
135+
| `AuditLogs` | Change traceability. | Clustered on `LogId` (bigint identity). Partitioned by `Timestamp` if scale increases. |
136+
137+
---
138+
139+
## 4. Multi-tenancy Implementation (RLS)
140+
141+
For SQL Server, the isolation proposal is based on the use of **Security Policies** and **Inline Table-Valued Functions (iTVF)**.
142+
143+
### Predicate Filter Function
144+
```sql
145+
CREATE FUNCTION Security.fn_tenantSecurityPredicate(@TenantId uniqueidentifier)
146+
RETURNS TABLE
147+
WITH SCHEMABINDING
148+
AS
149+
RETURN SELECT 1 AS fn_security_predicate_result
150+
WHERE @TenantId = CAST(SESSION_CONTEXT(N'TenantId') AS uniqueidentifier)
151+
OR CAST(SESSION_CONTEXT(N'IsSuperAdmin') AS bit) = 1;
152+
```
153+
154+
### Security Policy
155+
```sql
156+
CREATE SECURITY POLICY Security.TenantIdFilter
157+
ADD FILTER PREDICATE Security.fn_tenantSecurityPredicate(TenantId) ON dbo.Users,
158+
ADD FILTER PREDICATE Security.fn_tenantSecurityPredicate(TenantId) ON dbo.Roles,
159+
ADD FILTER PREDICATE Security.fn_tenantSecurityPredicate(TenantId) ON dbo.AuditLogs
160+
WITH (STATE = ON);
161+
```
162+
163+
---
164+
165+
## 5. Blueprint Considerations
166+
1. **Scalability:** The use of **Columnstore Indexes** on the `AuditLogs` table is recommended if audit volume exceeds millions of records.
167+
2. **Integrity:** All N:M relationships are handled through junction tables with composite keys to optimize navigation.
168+
3. **Security:** Password hashes must never be stored in the `Users` table, but in `UserCredentials` to allow for secret rotation and multiple authentication methods (e.g., MFA).

0 commit comments

Comments
 (0)