summaryrefslogtreecommitdiff
path: root/server/lib/net/protocol.dart
blob: 54328fc74259b2164cd2054a270cef5d578c9c35 (plain)
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
/// JSON wire protocol for X-Haven, shared by the server, its tests and (via
/// mirrored types) the web client.
///
/// See PLAN.md section 3.5 for the protocol design. Phase 0 implements the
/// handshake (hello/welcome/ping/pong/error); the rest of the message types
/// are declared here and added to in later phases.
library;

/// Protocol message type identifiers.
abstract class Protocol {
  Protocol._();

  static const int version = 1;

  // Client -> server message types.
  static const String hello = 'hello';
  static const String claim = 'claim';
  static const String cmd = 'cmd';
  static const String undo = 'undo';
  static const String redo = 'redo';
  static const String ping = 'ping';

  // Server -> client message types.
  static const String welcome = 'welcome';
  static const String update = 'update';
  static const String seats = 'seats';
  static const String error = 'error';
  static const String pong = 'pong';

  // Roles.
  static const String roleSpectator = 'spectator';
  static const String rolePlayer = 'player';

  /// Error codes.
  static const String errBadRequest = 'badRequest';
  static const String errUnknownMessage = 'unknownMessage';
  static const String errRejected = 'rejected';
  static const String errProtocol = 'protocol';

  /// First client message: the handshake. The session id rides in a cookie
  /// (Phase 2); in Phase 0 the server assigns a throwaway session.
  static Map<String, dynamic> helloMessage() => {'t': hello, 'v': version};

  /// Full state snapshot for a new (or reconnecting) connection. [state] is
  /// already serialized for this connection, i.e. with that connection's
  /// secrets included and everyone else's masked (PLAN.md section 3.4).
  static Map<String, dynamic> welcomeMessage({
    required String session,
    required String role,
    required int index,
    required Map<String, dynamic> state,
    required Map<String, dynamic> seats,
    String? description,
    Object? event,
  }) {
    return {
      't': welcome,
      'v': version,
      'session': session,
      'role': role,
      'index': index,
      'description': description,
      'event': event,
      'state': state,
      'seats': seats,
    };
  }

  static Map<String, dynamic> errorMessage(String code, String message) => {
    't': error,
    'code': code,
    'message': message,
  };

  static Map<String, dynamic> pongMessage() => {'t': pong};
}