Files
SD/main/docs/SERIALIZATION_ARCHITECTURE.md
2025-10-23 20:08:26 +01:00

338 lines
21 KiB
Markdown

# Arquitetura de Serialização - Diagrama Visual
## Visão Geral da Arquitetura
```
┌─────────────────────────────────────────────────────────────────┐
│ APPLICATION LAYER │
│ ┌──────────┐ ┌─────────┐ ┌─────────┐ ┌──────────────────┐ │
│ │ Vehicle │ │ Message │ │ Stats │ │ Other Objects │ │
│ └──────────┘ └─────────┘ └─────────┘ └──────────────────┘ │
└────────────────────────────┬────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ SERIALIZATION INTERFACE │
│ │
│ ┌────────────────────────────────────────────────────────────┐ │
│ │ MessageSerializer (interface) │ │
│ │ + byte[] serialize(Object) │ │
│ │ + <T> T deserialize(byte[], Class<T>) │ │
│ │ + String getName() │ │
│ │ + boolean supports(Class<?>) │ │
│ └────────────────────────────────────────────────────────────┘ │
└────────────────────────────┬────────────────────────────────────┘
┌──────────────┴──────────────┐
│ │
▼ ▼
┌─────────────────────────┐ ┌─────────────────────────────┐
│ JsonMessageSerializer │ │ JavaMessageSerializer │
│ (Gson-based) │ │ (ObjectStream-based) │
├─────────────────────────┤ ├─────────────────────────────┤
│ - Gson gson │ │ + serialize(): byte[] │
│ - boolean prettyPrint │ │ + deserialize(): T │
├─────────────────────────┤ ├─────────────────────────────┤
│ + serialize(): byte[] │ │ Uses: │
│ + deserialize(): T │ │ - ObjectOutputStream │
│ │ │ - ObjectInputStream │
│ Uses: │ └─────────────────────────────┘
│ - gson.toJson() │
│ - gson.fromJson() │ │
└─────────────────────────┘ │
│ │
└──────────────┬──────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ NETWORK TRANSPORT │
│ ┌──────────────┐ ┌──────────────┐ │
│ │ Sockets │ <--> │ Sockets │ │
│ │ (Sender) │ │ (Receiver) │ │
│ └──────────────┘ └──────────────┘ │
└─────────────────────────────────────────────────────────────────┘
```
## Factory Pattern
```
┌─────────────────────────────────────────────────────────────┐
│ SerializerFactory │
├─────────────────────────────────────────────────────────────┤
│ │
│ createDefault() │
│ │ │
│ ├─> Check System Property "sd.serialization.type" │
│ │ │
│ └─> Return appropriate serializer │
│ │
│ create(SerializationType) │
│ │ │
│ ├─> JSON -> JsonMessageSerializer │
│ └─> JAVA_NATIVE -> JavaMessageSerializer │
│ │
│ createJsonSerializer(boolean prettyPrint) │
│ └─> new JsonMessageSerializer(prettyPrint) │
│ │
│ createJavaSerializer() │
│ └─> new JavaMessageSerializer() │
│ │
└─────────────────────────────────────────────────────────────┘
```
## Fluxo de Serialização (JSON)
```
┌──────────────┐
│ Object │ (e.g., Vehicle, Message)
│ (in memory) │
└──────┬───────┘
│ serialize()
┌──────────────────────────────┐
│ JsonMessageSerializer │
│ │
│ 1. Validate object != null │
│ 2. gson.toJson(object) │
│ 3. Convert to UTF-8 bytes │
└──────┬───────────────────────┘
│ byte[]
┌──────────────────────────────┐
│ Network Layer │
│ (OutputStream) │
└──────┬───────────────────────┘
│ TCP/IP
┌──────────────────────────────┐
│ Network Layer │
│ (InputStream) │
└──────┬───────────────────────┘
│ byte[]
┌──────────────────────────────┐
│ JsonMessageSerializer │
│ │
│ 1. Validate data != null │
│ 2. Convert to String (UTF-8)│
│ 3. gson.fromJson(json, cls) │
└──────┬───────────────────────┘
│ deserialize()
┌──────────────┐
│ Object │
│ (in memory) │
└──────────────┘
```
## Comparação de Formato de Dados
### JSON Format (Legível)
```json
{
"messageId": "abc-123",
"type": "VEHICLE_TRANSFER",
"senderId": "Cr1",
"destinationId": "Cr2",
"timestamp": 1729595234567,
"payload": {
"id": "V123",
"type": "LIGHT",
"entryTime": 15.7,
"route": ["Cr1", "Cr2", "S"],
"currentRouteIndex": 1,
"totalWaitingTime": 3.2,
"totalCrossingTime": 1.8
}
}
```
**Tamanho**: ~300 bytes
**Legibilidade**: ✅ Alta
**Debugging**: ✅ Fácil
### Java Binary Format (Não Legível)
```
AC ED 00 05 73 72 00 10 73 64 2E 6D 6F 64 65 6C
2E 4D 65 73 73 61 67 65 00 00 00 00 00 00 00 01
02 00 06 4A 00 09 74 69 6D 65 73 74 61 6D 70 4C
...
```
**Tamanho**: ~657 bytes
**Legibilidade**: ❌ Baixa (binário)
**Debugging**: ❌ Difícil
## Uso em Contexto Real
### Cenário: Transferência de Veículo entre Cruzamentos
```
┌──────────────────────────────────────────────────────────────────┐
│ Processo Cr1 │
│ │
│ 1. Vehicle arrives at intersection │
│ 2. Create Message with Vehicle payload │
│ 3. MessageSerializer serializer = SerializerFactory.create() │
│ 4. byte[] data = serializer.serialize(message) │
│ 5. socket.getOutputStream().write(data) │
│ │
└───────────────────────────┬──────────────────────────────────────┘
│ Network (TCP/IP)
│ JSON: 300 bytes
│ Latency: ~1ms
┌───────────────────────────▼──────────────────────────────────────┐
│ Processo Cr2 │
│ │
│ 1. byte[] data = socket.getInputStream().readAllBytes() │
│ 2. MessageSerializer serializer = SerializerFactory.create() │
│ 3. Message msg = serializer.deserialize(data, Message.class) │
│ 4. Vehicle vehicle = msg.getPayloadAs(Vehicle.class) │
│ 5. Process vehicle (add to queue, etc.) │
│ │
└──────────────────────────────────────────────────────────────────┘
```
## Tratamento de Erros
```
┌─────────────────────────────────────────────────────────────────┐
│ Error Handling Flow │
├─────────────────────────────────────────────────────────────────┤
│ │
│ try { │
│ byte[] data = serializer.serialize(object); │
│ send(data); │
│ } │
│ catch (SerializationException e) { │
│ │ │
│ ├─> Log error │
│ ├─> Increment error counter │
│ ├─> Notify monitoring system │
│ └─> Retry with fallback serializer (optional) │
│ } │
│ │
│ try { │
│ byte[] data = receive(); │
│ Message msg = serializer.deserialize(data, Message.class); │
│ } │
│ catch (SerializationException e) { │
│ │ │
│ ├─> Log corrupted data │
│ ├─> Request retransmission │
│ └─> Discard message │
│ } │
│ │
└─────────────────────────────────────────────────────────────────┘
```
## Performance Comparison Diagram
```
Serialization Time (microseconds)
0 10 20 30 40 50
├────────┼────────┼────────┼────────┼────────┤
JSON: ████████████████████████████████████████ 40.79 μs
Java: █████████████████████████████████ 33.34 μs
Difference: 7.45 μs (< 0.01 ms - NEGLIGIBLE)
Message Size (bytes)
0 200 400 600 800
├────────┼────────┼────────┼────────┤
JSON: ██████████████████ 300 bytes
Java: █████████████████████████████████ 657 bytes
Difference: 357 bytes (54% smaller - SIGNIFICANT)
Legibilidade
Low High
├────────────────────────────┤
JSON: ████████████████████████████ High (text)
Java: █ Low (binary)
```
## Decisão Matrix
```
┌─────────────────────────────────────────────────────────┐
│ Serialization Decision Matrix │
├─────────────────┬──────────────┬─────────────┬──────────┤
│ Criteria │ JSON │ Java │ Winner │
├─────────────────┼──────────────┼─────────────┼──────────┤
│ Size │ 300 bytes │ 657 bytes │ ✅ JSON │
│ Performance │ 40.79 μs │ 33.34 μs │ ⚖️ Tie │
│ Readability │ High │ Low │ ✅ JSON │
│ Debugging │ Easy │ Hard │ ✅ JSON │
│ Security │ Better │ Vulnerable │ ✅ JSON │
│ Interop │ Universal │ Java only │ ✅ JSON │
│ Dependencies │ Gson (small) │ None │ ⚖️ Tie │
│ Evolution │ Flexible │ Rigid │ ✅ JSON │
├─────────────────┴──────────────┴─────────────┴──────────┤
│ FINAL SCORE │
│ JSON: 6 | Java: 0 | Tie: 2 │
│ │
│ RECOMMENDATION: JSON (Gson) ✅ │
└─────────────────────────────────────────────────────────┘
```
## Integração Futura
```
┌──────────────────────────────────────────────────────────────┐
│ Current System │
│ │
│ Cruzamento 1 <--[JSON]--> Cruzamento 2 │
│ │ │ │
│ └────────[JSON]──────────────┘ │
│ │
└──────────────────────────────────────────────────────────────┘
Future Extensions (Easy with JSON)
┌──────────────────────────────────────────────────────────────┐
│ Extended System │
│ │
│ Cruzamento 1 <--[JSON]--> Cruzamento 2 │
│ │ │ │
│ ├────────[JSON]──────────────┤ │
│ │ │ │
│ ▼ ▼ │
│ ┌─────────────────────────────────────────┐ │
│ │ Dashboard (Web) │ │
│ │ - React/Vue frontend │ │
│ │ - Consumes JSON directly │ │
│ │ - No conversion needed │ │
│ └─────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────┐ │
│ │ REST API │ │
│ │ - External monitoring │ │
│ │ - JSON responses │ │
│ └─────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────┐ │
│ │ Log Aggregation │ │
│ │ - ELK Stack, Splunk │ │
│ │ - JSON log parsing │ │
│ └─────────────────────────────────────────┘ │
│ │
└──────────────────────────────────────────────────────────────┘
```
---
**Diagrama criado**: 22 de outubro de 2025
**Formato**: ASCII Art (compatível com markdown)
**Licença**: Projeto SD - Trabalho Prático