1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
//! Inter-server communication protocol
//!
//! Defines message types for server-to-server communication in the cluster.
//! All messages are JSON-serializable for transmission over TCP/WebSocket.
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
/// Inter-server message types
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ServerMessage {
/// Heartbeat ping from peer
HeartbeatPing {
/// Sending server's ID
server_id: String,
/// Sending server's current timestamp (ms since epoch)
timestamp: u64,
/// Server's version/sequence number
sequence: u64,
},
/// Heartbeat pong response
HeartbeatPong {
/// Responding server's ID
server_id: String,
/// Responding server's timestamp
timestamp: u64,
/// Health status of responding server
status: ServerStatus,
},
/// Request to sync service state
SyncServiceRequest {
/// Request ID for tracking
request_id: String,
/// Tenant name
tenant_name: String,
/// Service name
service_name: String,
/// Version of local state (for incremental sync)
from_version: Option<u64>,
/// Checksum of local state (for validation)
from_checksum: Option<String>,
},
/// Response with service state
SyncServiceResponse {
/// Matches the request_id
request_id: String,
/// Tenant name
tenant_name: String,
/// Service name
service_name: String,
/// Current version of this service
version: u64,
/// Overall checksum of service state
checksum: String,
/// Serialized service data (incremental or full)
data: Vec<u8>,
/// Whether this is incremental (true) or full state (false)
is_incremental: bool,
/// If incremental, the range of versions included
version_range: Option<(u64, u64)>,
},
/// Notify peer about client migration
ClientMigration {
/// Client session ID being migrated
client_id: String,
/// Tenant name
tenant_name: String,
/// Reason for migration
reason: MigrationReason,
/// Client's current permissions
permissions: HashMap<String, Vec<String>>,
/// Client's subscriptions
subscriptions: Vec<(String, String)>, // (tenant, service)
},
/// Acknowledge client migration completion
ClientMigrationAck {
/// Matches client_id
client_id: String,
/// Whether migration was accepted
accepted: bool,
/// Message if rejected
reason: Option<String>,
},
/// Request file transfer for service state
FileTransferRequest {
/// Request ID
request_id: String,
/// Tenant name
tenant_name: String,
/// Service name
service_name: String,
/// File name/path on source server
source_filename: String,
/// Starting byte offset (for resume)
offset: u64,
/// Maximum bytes to send in response
chunk_size: u64,
},
/// Response with file chunk
FileTransferChunk {
/// Matches request_id
request_id: String,
/// Byte offset of this chunk
offset: u64,
/// Chunk data
data: Vec<u8>,
/// Total file size
total_size: u64,
/// Whether more chunks follow
has_more: bool,
/// SHA256 checksum of this chunk
checksum: String,
},
/// Exchange server metadata
MetadataExchange {
/// This server's ID
server_id: String,
/// List of tenants this server knows about
tenants: Vec<TenantMetadata>,
/// Total services hosted
total_services: usize,
/// Cluster size this server knows about
cluster_size: usize,
},
/// Response to metadata exchange
MetadataExchangeAck {
/// Responding server's ID
server_id: String,
/// Acknowledgment that metadata was received
acknowledged: bool,
/// Any conflicts or inconsistencies found
conflicts: Vec<String>,
},
/// Error response to any request
Error {
/// Original request ID if applicable
request_id: Option<String>,
/// Error code (e.g., "PEER_NOT_FOUND", "SERVICE_NOT_FOUND")
error_code: String,
/// Human-readable error message
message: String,
},
}
/// Server health status for heartbeat responses
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum ServerStatus {
/// Server is healthy and operational
Healthy,
/// Server is running but degraded (some services down)
Degraded,
/// Server is shutting down
ShuttingDown,
}
impl ServerStatus {
/// Check if server can accept new operations
pub fn is_operational(self) -> bool {
matches!(self, ServerStatus::Healthy | ServerStatus::Degraded)
}
}
/// Reason for client migration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum MigrationReason {
/// This server is shutting down
ServerShutdown,
/// This server lost quorum
QuorumLoss,
/// Load balancing/rebalancing
LoadBalancing,
/// Client disconnected and reconnected to different server
ClientReconnected,
/// Explicit migration by operator
Manual,
}
/// Metadata about a tenant
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TenantMetadata {
/// Tenant name
pub name: String,
/// Number of services in this tenant
pub service_count: usize,
/// Last update timestamp (ms since epoch)
pub last_updated: u64,
/// Whether this server has quorum for this tenant
pub has_quorum: bool,
}
/// Request/response wrapper with metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PeerMessageEnvelope {
/// Message ID for correlation
pub message_id: String,
/// Sending server ID
pub from_server: String,
/// Receiving server ID
pub to_server: String,
/// Unix timestamp (ms since epoch)
pub timestamp: u64,
/// Actual message payload
pub message: ServerMessage,
}
impl PeerMessageEnvelope {
/// Create a new envelope
pub fn new(
from_server: String,
to_server: String,
message: ServerMessage,
) -> Self {
use std::time::{SystemTime, UNIX_EPOCH};
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0);
Self {
message_id: uuid::Uuid::new_v4().to_string(),
from_server,
to_server,
timestamp,
message,
}
}
/// Get message ID for tracking
pub fn message_id(&self) -> &str {
&self.message_id
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_heartbeat_ping_serialization() {
let msg = ServerMessage::HeartbeatPing {
server_id: "server_1".to_string(),
timestamp: 1000000,
sequence: 42,
};
let json = serde_json::to_string(&msg).unwrap();
let deserialized: ServerMessage = serde_json::from_str(&json).unwrap();
match deserialized {
ServerMessage::HeartbeatPing {
server_id,
timestamp,
sequence,
} => {
assert_eq!(server_id, "server_1");
assert_eq!(timestamp, 1000000);
assert_eq!(sequence, 42);
}
_ => panic!("Wrong message type"),
}
}
#[test]
fn test_server_status_operational() {
assert!(ServerStatus::Healthy.is_operational());
assert!(ServerStatus::Degraded.is_operational());
assert!(!ServerStatus::ShuttingDown.is_operational());
}
#[test]
fn test_envelope_creation() {
let msg = ServerMessage::HeartbeatPing {
server_id: "server_1".to_string(),
timestamp: 1000000,
sequence: 1,
};
let envelope = PeerMessageEnvelope::new(
"server_1".to_string(),
"server_2".to_string(),
msg,
);
assert_eq!(envelope.from_server, "server_1");
assert_eq!(envelope.to_server, "server_2");
assert!(!envelope.message_id.is_empty());
}
#[test]
fn test_envelope_serialization() {
let msg = ServerMessage::HeartbeatPing {
server_id: "server_1".to_string(),
timestamp: 1000000,
sequence: 1,
};
let envelope = PeerMessageEnvelope::new(
"server_1".to_string(),
"server_2".to_string(),
msg,
);
let json = serde_json::to_string(&envelope).unwrap();
let deserialized: PeerMessageEnvelope = serde_json::from_str(&json).unwrap();
assert_eq!(deserialized.from_server, "server_1");
assert_eq!(deserialized.to_server, "server_2");
}
#[test]
fn test_error_message() {
let msg = ServerMessage::Error {
request_id: Some("req_123".to_string()),
error_code: "SERVICE_NOT_FOUND".to_string(),
message: "Service does not exist".to_string(),
};
let json = serde_json::to_string(&msg).unwrap();
let deserialized: ServerMessage = serde_json::from_str(&json).unwrap();
match deserialized {
ServerMessage::Error {
request_id,
error_code,
message: _,
} => {
assert_eq!(request_id, Some("req_123".to_string()));
assert_eq!(error_code, "SERVICE_NOT_FOUND");
}
_ => panic!("Wrong message type"),
}
}
#[test]
fn test_migration_reason_serialization() {
let reasons = vec![
MigrationReason::ServerShutdown,
MigrationReason::QuorumLoss,
MigrationReason::LoadBalancing,
];
for reason in reasons {
let json = serde_json::to_string(&reason).unwrap();
let _: MigrationReason = serde_json::from_str(&json).unwrap();
}
}
#[test]
fn test_message_id_accessor() {
let msg = ServerMessage::HeartbeatPing {
server_id: "s1".to_string(),
timestamp: 0,
sequence: 0,
};
let envelope = PeerMessageEnvelope::new("s1".to_string(), "s2".to_string(), msg);
// message_id() must return the same value as the message_id field
assert_eq!(envelope.message_id(), envelope.message_id.as_str());
assert!(!envelope.message_id().is_empty());
}
#[test]
fn test_remaining_server_message_variants_serialization() {
// HeartbeatPong
let msg = ServerMessage::HeartbeatPong {
server_id: "s1".to_string(),
timestamp: 12345,
status: ServerStatus::Healthy,
};
let json = serde_json::to_string(&msg).unwrap();
let decoded: ServerMessage = serde_json::from_str(&json).unwrap();
assert!(matches!(decoded, ServerMessage::HeartbeatPong { .. }));
// SyncServiceRequest
let msg = ServerMessage::SyncServiceRequest {
request_id: "req1".to_string(),
tenant_name: "tenant_a".to_string(),
service_name: "svc_x".to_string(),
from_version: Some(10),
from_checksum: None,
};
let json = serde_json::to_string(&msg).unwrap();
let decoded: ServerMessage = serde_json::from_str(&json).unwrap();
assert!(matches!(decoded, ServerMessage::SyncServiceRequest { .. }));
// SyncServiceResponse
let msg = ServerMessage::SyncServiceResponse {
request_id: "req1".to_string(),
tenant_name: "tenant_a".to_string(),
service_name: "svc_x".to_string(),
version: 11,
checksum: "abc".to_string(),
data: vec![1, 2, 3],
is_incremental: false,
version_range: None,
};
let json = serde_json::to_string(&msg).unwrap();
let decoded: ServerMessage = serde_json::from_str(&json).unwrap();
assert!(matches!(decoded, ServerMessage::SyncServiceResponse { .. }));
// ClientMigration
let msg = ServerMessage::ClientMigration {
client_id: "c1".to_string(),
tenant_name: "t1".to_string(),
reason: MigrationReason::Manual,
permissions: Default::default(),
subscriptions: vec![("t1".to_string(), "svc1".to_string())],
};
let json = serde_json::to_string(&msg).unwrap();
let decoded: ServerMessage = serde_json::from_str(&json).unwrap();
assert!(matches!(decoded, ServerMessage::ClientMigration { .. }));
// ClientMigrationAck
let msg = ServerMessage::ClientMigrationAck {
client_id: "c1".to_string(),
accepted: true,
reason: None,
};
let json = serde_json::to_string(&msg).unwrap();
let decoded: ServerMessage = serde_json::from_str(&json).unwrap();
assert!(matches!(decoded, ServerMessage::ClientMigrationAck { .. }));
// FileTransferRequest
let msg = ServerMessage::FileTransferRequest {
request_id: "r1".to_string(),
tenant_name: "t1".to_string(),
service_name: "s1".to_string(),
source_filename: "file.mem".to_string(),
offset: 0,
chunk_size: 1024 * 1024,
};
let json = serde_json::to_string(&msg).unwrap();
let decoded: ServerMessage = serde_json::from_str(&json).unwrap();
assert!(matches!(decoded, ServerMessage::FileTransferRequest { .. }));
// FileTransferChunk
let msg = ServerMessage::FileTransferChunk {
request_id: "r1".to_string(),
offset: 0,
data: vec![0u8; 16],
total_size: 16,
has_more: false,
checksum: "sha256".to_string(),
};
let json = serde_json::to_string(&msg).unwrap();
let decoded: ServerMessage = serde_json::from_str(&json).unwrap();
assert!(matches!(decoded, ServerMessage::FileTransferChunk { .. }));
// MetadataExchange
let msg = ServerMessage::MetadataExchange {
server_id: "s1".to_string(),
tenants: vec![TenantMetadata {
name: "t1".to_string(),
service_count: 3,
last_updated: 100,
has_quorum: true,
}],
total_services: 3,
cluster_size: 2,
};
let json = serde_json::to_string(&msg).unwrap();
let decoded: ServerMessage = serde_json::from_str(&json).unwrap();
assert!(matches!(decoded, ServerMessage::MetadataExchange { .. }));
// MetadataExchangeAck
let msg = ServerMessage::MetadataExchangeAck {
server_id: "s2".to_string(),
acknowledged: true,
conflicts: vec![],
};
let json = serde_json::to_string(&msg).unwrap();
let decoded: ServerMessage = serde_json::from_str(&json).unwrap();
assert!(matches!(decoded, ServerMessage::MetadataExchangeAck { .. }));
}
}