monocle 1.2.0

A commandline application to search, parse, and process BGP information in public sources.
Documentation
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
# Monocle WebSocket API Design

This document specifies a unified WebSocket interface for third-party applications (web/native UIs, services) to interact with Monocle.

## Overview

Why WebSocket:

- Streaming results for long-running operations (parse/search)
- Real-time progress updates
- Single persistent connection with cancellation

### Design Goals (Keep It Lean)

- **Small protocol surface**: one envelope, fixed response types, consistent semantics.
- **UI-friendly**: streaming/progress + stable operation identifiers.
- **DB-first queries**: query methods must be network-neutral; refresh is explicit and deduplicated.
- **Maintainable**: consistent handler contract across lenses; avoid a growing router match.

## Architecture

Components and responsibilities:

- Clients (Web UI, native UI, CLI, services)
  - maintain one WebSocket connection
  - send requests (`method`, optional `id`, `params`)
  - receive `progress` / `stream` / terminal `result` or `error`
- Monocle server
  - WebSocket endpoint (Axum): connection management, request parsing/validation, routing
  - Lens layer: implements operations (time/ip/rpki/inspect/as2rel/pfx2as/country/parse/search)
  - Data layer: SQLite DB (authoritative local store) + file caches (as applicable)

## Common Types (Referenced by Methods)

To keep the API surface consistent and the spec compact, methods reference these shared types instead of redefining the same shape repeatedly.

### `RequestEnvelope`

```json
{
  "id": "optional-client-request-id",
  "method": "namespace.operation",
  "params": { ... }
}
```

- `id` is optional. If provided, it must be unique among in-flight requests on the same connection.
- The server always echoes `id` in responses (client-provided or server-generated).
- Long-running/streaming operations always return a server-generated `op_id`.

### `ResponseEnvelope`

```json
{
  "id": "request-id",
  "op_id": "server-operation-id",
  "type": "result" | "progress" | "error" | "stream",
  "data": { ... }
}
```

- `op_id` is present for operations that can be cancelled or produce incremental output (streaming/long-running; including refresh).
- Terminal message: exactly one `result` or `error`.

### `Pagination` (for list/query methods)

```json
{
  "limit": 100,
  "offset": 0
}
```

- `limit` (optional): clamp on the server to a safe maximum.
- `offset` (optional): non-negative.

### `QueryFilters` (shared by `parse.start` and `search.start`)

```json
{
  "origin_asn": 13335,
  "prefix": "1.1.1.0/24",
  "include_super": false,
  "include_sub": false,
  "peer_ip": [],
  "peer_asn": null,
  "elem_type": null,
  "start_ts": null,
  "end_ts": null,
  "as_path": null
}
```

Notes:
- `peer_ip` is a list of strings; empty means no filter.
- `start_ts` / `end_ts` accept either RFC3339 strings or `null` (server normalizes internally).
- `include_super` and `include_sub` define prefix match behavior when `prefix` is set.

### `ProgressStage`

To avoid UI drift, stages should use this shared vocabulary:

- `queued`, `running`, `downloading`, `processing`, `finalizing`, `done`

Method-specific details belong in additional fields (e.g., counters, ETA, filenames), not new stage strings.

## Message Protocol

### `op_id` Presence Policy (Strict)
To keep streaming state machine simple and reduce client ambiguity:

- **Non-streaming methods**:
  - `op_id` MUST be absent in all server responses (`result` / `error`).
  - Clients MUST NOT include `op_id` in requests (requests do not have an `op_id` field).
- **Streaming methods**:
  - Server MUST generate an `op_id` and include it in **every** server envelope for that operation:
    - all `progress` messages
    - all `stream` messages
    - the final terminal `result` or `error`
  - Streaming messages without `op_id` are invalid.

This document treats `op_id` as the single, stable identity for a streaming operation across all emitted messages. `id` remains the request correlation identifier.

All messages are JSON-encoded and follow a consistent envelope structure.

### Client → Server (Request)

```json
{
  "id": "optional-client-request-id",
  "method": "namespace.operation",
  "params": { ... }
}
```

| Field    | Type   | Required | Description                                                |
|----------|--------|----------|------------------------------------------------------------|
| `id`     | string | No       | Optional request correlation ID (echoed in responses)       |
| `method` | string | Yes      | Operation to perform (e.g., `rpki.validate`)                |
| `params` | object | No       | Operation-specific parameters                               |

#### Request Semantics

- If `id` is provided, it must be unique among in-flight requests on the same connection.
- Long-running operations return a server-generated `op_id` for cancellation and UI tracking.

### Server → Client (Response)

```json
{
  "id": "request-id",
  "op_id": "server-operation-id",
  "type": "result" | "progress" | "error" | "stream",
  "data": { ... }
}
```

| Field   | Type   | Description                                                                 |
|---------|--------|-----------------------------------------------------------------------------|
| `id`    | string | Request correlation ID (client-provided or server-generated)                |
| `op_id` | string | Server-generated operation identifier (present for streaming/long operations) |
| `type`  | string | Response type (see below)                                                   |
| `data`  | object | Response payload                                                            |

#### Response Types

- **`result`**: Final successful response for the operation (exactly once)
- **`progress`**: Intermediate progress update (0..N times)
- **`stream`**: Streaming data batches (0..N times)
- **`error`**: Error response (terminal; ends the operation)

#### Streaming Contract (UI-Friendly)
For streaming methods (`*.start` that stream), the server follows this exact contract:

- 0..N `progress` messages (each includes `id` and `op_id`)
- 0..N `stream` messages (each includes `id` and `op_id`)
- then **exactly one** terminal message:
  - `result` (includes `id` and `op_id`) OR
  - `error` (includes `id` and `op_id`)

After a terminal message, the operation is finished and no further messages for that `op_id` will be sent.

- For a given request `id` / operation `op_id`, the server may emit:
  - `progress` messages (optional),
  - `stream` messages (optional),
  - and then exactly one terminal message: either `result` or `error`.
- Clients should treat `result`/`error` as completion and release UI resources for that `op_id`.

### Error Response

```json
{
  "id": "request-id",
  "op_id": "server-operation-id",
  "type": "error",
  "data": {
    "code": "ERROR_CODE",
    "message": "Human-readable error message",
    "details": { ... }
  }
}
```

#### Error Codes

| Code                  | Description                                    |
|-----------------------|------------------------------------------------|
| `INVALID_REQUEST`     | Malformed request message                      |
| `UNKNOWN_METHOD`      | Method not found                               |
| `INVALID_PARAMS`      | Invalid or missing parameters                  |
| `OPERATION_FAILED`    | Operation failed during execution              |
| `OPERATION_CANCELLED` | Operation was cancelled by client              |
| `NOT_INITIALIZED`     | Required data not initialized/bootstrapped     |
| `RATE_LIMITED`        | Too many concurrent operations                 |
| `INTERNAL_ERROR`      | Unexpected server error                        |

## API Methods

### Introspection (Recommended for UIs)

#### `system.info`

Returns protocol/server metadata so web/native clients can adapt without hardcoding.

**Request:**
```json
{
  "id": "sys-1",
  "method": "system.info",
  "params": {}
}
```

**Response:**
```json
{
  "id": "sys-1",
  "type": "result",
  "data": {
    "protocol_version": 1,
    "server_version": "1.0.2",
    "build": {
      "git_sha": "unknown",
      "timestamp": "unknown"
    },
    "features": {
      "streaming": true,
      "auth_required": false
    }
  }
}
```

#### `system.methods` (Optional)

Returns a minimal method catalog for discoverability (names + short schemas). Keep this intentionally lightweight to avoid maintaining a full IDL.

---

## API Methods

### Namespace Organization

| Namespace | Description | Feature |
|-----------|-------------|---------|
| `system.*` | Server introspection | server |
| `time.*` | Time parsing utilities | lib |
| `ip.*` | IP information lookup | lib |
| `rpki.*` | RPKI validation and data | lib |
| `as2rel.*` | AS-level relationships | lib |
| `pfx2as.*` | Prefix-to-ASN mapping | lib |
| `country.*` | Country code/name lookup | lib |
| `inspect.*` | Unified AS/prefix inspection | lib |
| `parse.*` | MRT file parsing (streaming) | lib |
| `search.*` | BGP message search (streaming) | lib |
| `database.*` | Database management | lib |

Methods are organized into namespaces matching the lens modules:

- `time.*` - Time parsing and formatting
- `ip.*` - IP information lookup
- `rpki.*` - RPKI validation and ROA/ASPA queries
- `inspect.*` - Unified AS/prefix inspection (replaces as2org)
- `as2rel.*` - AS-level relationships
- `pfx2as.*` - Prefix-to-ASN mappings
- `country.*` - Country code/name lookup
- `parse.*` - MRT file parsing (streaming)
- `search.*` - BGP message search (streaming)
- `database.*` - Database management operations

---

### Time Operations (`time.*`)

#### `time.parse`

Parse time strings into multiple formats.

**Request:**
```json
{
  "id": "1",
  "method": "time.parse",
  "params": {
    "times": ["1697043600", "2023-10-11T00:00:00Z"],
    "format": "table"
  }
}
```

**Response:**
```json
{
  "id": "1",
  "type": "result",
  "data": {
    "results": [
      {
        "unix": 1697043600,
        "rfc3339": "2023-10-11T15:00:00+00:00",
        "human": "about 1 year ago"
      }
    ]
  }
}
```

**Parameters:**

| Field    | Type     | Required | Default   | Description                              |
|----------|----------|----------|-----------|------------------------------------------|
| `times`  | string[] | No       | [now]     | Time strings to parse                    |
| `format` | string   | No       | "table"   | Output format: table, rfc3339, unix, json|

---

### IP Operations (`ip.*`)

#### `ip.lookup`

Look up information about an IP address.

**Request:**
```json
{
  "id": "2",
  "method": "ip.lookup",
  "params": {
    "ip": "1.1.1.1"
  }
}
```

**Response:**
```json
{
  "id": "2",
  "type": "result",
  "data": {
    "ip": "1.1.1.1",
    "asn": 13335,
    "as_name": "CLOUDFLARENET",
    "country": "US",
    "prefix": "1.1.1.0/24"
  }
}
```

#### `ip.public`

Get the public IP address of the server.

**Request:**
```json
{
  "id": "3",
  "method": "ip.public",
  "params": {}
}
```

---

### RPKI Operations (`rpki.*`)

#### `rpki.validate`

Validate a prefix-ASN pair against RPKI data.

**Request:**
```json
{
  "id": "4",
  "method": "rpki.validate",
  "params": {
    "prefix": "1.1.1.0/24",
    "asn": 13335
  }
}
```

**Response:**
```json
{
  "id": "4",
  "type": "result",
  "data": {
    "validation": {
      "prefix": "1.1.1.0/24",
      "asn": 13335,
      "state": "valid",
      "reason": "ROA exists with matching ASN and valid prefix length"
    },
    "covering_roas": [
      {
        "prefix": "1.1.1.0/24",
        "max_length": 24,
        "origin_asn": 13335,
        "ta": "APNIC"
      }
    ]
  }
}
```

**Parameters:**

| Field    | Type   | Required | Description              |
|----------|--------|----------|--------------------------|
| `prefix` | string | Yes      | IP prefix (e.g., 1.1.1.0/24) |
| `asn`    | number | Yes      | AS number to validate    |

#### `rpki.roas`

List ROAs filtered by ASN and/or prefix.

**DB-first policy:** this method reads from the local Monocle database only (no remote fetch).
If RPKI data is not present locally, the server returns a terminal `error` with code `NOT_INITIALIZED`.

**Current support note:** `date` and `source` parameters are accepted for forward compatibility, but **historical snapshots and source selection are not supported in DB-first mode yet**. If `date` is provided, the server returns a terminal `error` with code `INVALID_PARAMS`.

**Request:**
```json
{
  "id": "5",
  "method": "rpki.roas",
  "params": {
    "asn": 13335,
    "prefix": null,
    "date": null,
    "source": "cloudflare"
  }
}
```

**Response:**
```json
{
  "id": "5",
  "type": "result",
  "data": {
    "roas": [
      {
        "prefix": "1.1.1.0/24",
        "max_length": 24,
        "origin_asn": 13335,
        "ta": "APNIC"
      }
    ],
    "count": 1
  }
}
```

**Parameters:**

| Field     | Type   | Required | Default      | Description                           |
|-----------|--------|----------|--------------|---------------------------------------|
| `asn`     | number | No       | null         | Filter by origin ASN                  |
| `prefix`  | string | No       | null         | Filter by prefix                      |
| `date`    | string | No       | null         | Historical date (YYYY-MM-DD). **Not supported in DB-first mode** (request will be rejected). |
| `source`  | string | No       | "cloudflare" | Data source selector. **Not supported in DB-first mode** (ignored today; reserved for future). |

#### `rpki.aspas`

List ASPAs filtered by customer and/or provider ASN.

**DB-first policy:** this method reads from the local Monocle database only (no remote fetch).
If RPKI data is not present locally, the server returns a terminal `error` with code `NOT_INITIALIZED`.

**Current support note:** `date` and `source` parameters are accepted for forward compatibility, but **historical snapshots and source selection are not supported in DB-first mode yet**. If `date` is provided, the server returns a terminal `error` with code `INVALID_PARAMS`.

**Request:**
```json
{
  "id": "6",
  "method": "rpki.aspas",
  "params": {
    "customer_asn": 13335,
    "provider_asn": null
  }
}
```

---

### Inspect Operations (`inspect.*`)

The `inspect` namespace provides unified AS and prefix information lookup, replacing the former `as2org` namespace.

#### `inspect.query`

Query AS or prefix information from multiple data sources.

Search for AS-to-Organization mappings.

**Request:**
```json
{
  "id": "req-12",
  "method": "inspect.query",
  "params": {
    "query": "13335",
    "query_type": "auto",
    "sections": ["basic", "connectivity", "rpki"],
    "limits": {
      "roas": 10,
      "prefixes": 10,
      "connectivity": 5
    }
  }
}
```

**Parameters:**
- `query` (required): ASN (13335, AS13335), prefix (1.1.1.0/24), IP (1.1.1.1), or name (cloudflare)
- `query_type` (optional): "auto" (default), "asn", "prefix", "name"
- `sections` (optional): Array of sections to include: "basic", "prefixes", "connectivity", "rpki", "all"
- `limits` (optional): Limits for each section (default: roas=10, prefixes=10, connectivity=5)

**Response:**
```json
{
  "id": "req-12",
  "type": "result",
  "data": {
    "query": "13335",
    "query_type": "asn",
    "asn": 13335,
    "name": "CLOUDFLARENET",
    "country": "US",
    "sections": {
      "connectivity": {
        "upstreams": [{"asn": 174, "name": "COGENT-174", "percentage": 85.2}],
        "downstreams": [{"asn": 14789, "name": "CLOUDFLARE-CN", "percentage": 95.1}],
        "peers": [{"asn": 6939, "name": "HURRICANE", "percentage": 92.3}]
      },
      "rpki": {
        "roas": [{"prefix": "1.1.1.0/24", "max_length": 24, "ta": "ARIN"}],
        "roa_count": 150
      }
    }
  }
}
```

#### `inspect.search`

Search ASes by name or country.

**Request:**
```json
{
  "id": "req-13",
  "method": "inspect.search",
  "params": {
    "query": "cloudflare",
    "country": null,
    "limit": 20
  }
}
```

**Response:**
```json
{
  "id": "req-13",
  "type": "result",
  "data": {
    "results": [
      {"asn": 13335, "name": "CLOUDFLARENET", "country": "US"},
      {"asn": 14789, "name": "CLOUDFLARE-CN", "country": "CN"}
    ],
    "count": 2
  }
}
```

#### `inspect.refresh`

Bootstrap AS2Org data from bgpkit-commons.
Refresh the ASInfo local database from upstream source.

**Request:**
```json
{
  "id": "req-14",
  "method": "inspect.refresh",
  "params": {
    "force": false
  }
}
```

**Response:**
```json
{
  "id": "req-14",
  "type": "result",
  "data": {
    "refreshed": true,
    "as_count": 120415,
    "message": "ASInfo data refreshed successfully"
  }
}
```

---

### AS2Rel Operations (`as2rel.*`)

#### `as2rel.search`

Search for AS-level relationships.

**Request:**
```json
{
  "id": "9",
  "method": "as2rel.search",
  "params": {
    "asns": [13335],
    "sort_by_asn": false,
    "show_name": true
  }
}
```

**Response:**
```json
{
  "id": "9",
  "type": "result",
  "data": {
    "max_peers_count": 1000,
    "results": [
      {
        "asn1": 13335,
        "asn2": 174,
        "asn2_name": "COGENT-174",
        "connected": "85.3%",
        "peer": "45.2%",
        "as1_upstream": "20.1%",
        "as2_upstream": "20.0%"
      }
    ]
  }
}
```

#### `as2rel.relationship`

Get the relationship between two specific ASNs.

**Request:**
```json
{
  "id": "10",
  "method": "as2rel.relationship",
  "params": {
    "asn1": 13335,
    "asn2": 174
  }
}
```

#### `as2rel.update`

Update AS2Rel data from BGPKIT.

**Request:**
```json
{
  "id": "11",
  "method": "as2rel.update",
  "params": {
    "url": null
  }
}
```

---

### Pfx2as Operations (`pfx2as.*`)

#### `pfx2as.lookup`

Look up the origin AS for a prefix.

**DB-first policy:** this method is **cache-only**. The server MUST NOT fetch remote pfx2as data as part of `pfx2as.lookup`. If the pfx2as cache is missing/stale, clients should call `database.refresh` for `pfx2as-cache` first; otherwise the server returns a terminal `error` with code `NOT_INITIALIZED`.

**Request:**
```json
{
  "id": "12",
  "method": "pfx2as.lookup",
  "params": {
    "prefix": "1.1.1.0/24"
  }
}
```

---

### Country Operations (`country.*`)

#### `country.lookup`

Look up country information by code or name.

**Request:**
```json
{
  "id": "13",
  "method": "country.lookup",
  "params": {
    "query": "US"
  }
}
```

**Response:**
```json
{
  "id": "13",
  "type": "result",
  "data": {
    "countries": [
      {
        "code": "US",
        "name": "United States of America",
        "alpha3": "USA"
      }
    ]
  }
}
```

---

### Parse Operations (`parse.*`) - Streaming

#### `parse.start`

Start parsing an MRT file. Results are streamed back incrementally.

**Request:**
```json
{
  "id": "14",
  "method": "parse.start",
  "params": {
    "file_path": "https://data.ris.ripe.net/rrc00/updates.20231011.1600.gz",
    "filters": { ...QueryFilters... },
    "batch_size": 100,
    "max_results": 10000
  }
}
```

**Progress Response:**
```json
{
  "id": "14",
  "op_id": "op-parse-7c2f",
  "type": "progress",
  "data": {
    "stage": "running",
    "messages_processed": 50000,
    "rate": 15000.5,
    "elapsed_secs": 3.33
  }
}
```

**Stream Response (batch of results):**
```json
{
  "id": "14",
  "op_id": "op-parse-7c2f",
  "type": "stream",
  "data": {
    "elements": [
      {
        "timestamp": 1697043600.0,
        "elem_type": "A",
        "peer_ip": "192.168.1.1",
        "peer_asn": 64496,
        "prefix": "1.1.1.0/24",
        "as_path": "64496 13335",
        "origin_asns": [13335],
        "next_hop": "192.168.1.1"
      }
    ],
    "batch_index": 0,
    "total_so_far": 100
  }
}
```

**Final Response:**
```json
{
  "id": "14",
  "op_id": "op-parse-7c2f",
  "type": "result",
  "data": {
    "total_messages": 1500,
    "duration_secs": 5.2,
    "rate": 288.46
  }
}
```

#### `parse.cancel`

Cancel an ongoing parse operation.

**Request:**
```json
{
  "id": "15",
  "method": "parse.cancel",
  "params": {
    "op_id": "op-parse-7c2f"
  }
}
```

---

### Search Operations (`search.*`) - Streaming

#### `search.start`

Start a BGP message search across multiple MRT files.

**Request:**
```json
{
  "id": "16",
  "method": "search.start",
  "params": {
    "filters": { ...QueryFilters... },
    "collector": "rrc00",
    "project": "riperis",
    "dump_type": "updates",
    "batch_size": 100,
    "max_results": 10000
  }
}
```

**Progress Responses:**

```json
{
  "id": "16",
  "type": "progress",
  "data": {
    "stage": "querying_broker"
  }
}
```

```json
{
  "id": "16",
  "type": "progress",
  "data": {
    "stage": "files_found",
    "count": 5
  }
}
```

```json
{
  "id": "16",
  "type": "progress",
  "data": {
    "stage": "processing",
    "files_completed": 2,
    "total_files": 5,
    "total_messages": 1500,
    "percent_complete": 40.0,
    "elapsed_secs": 10.5,
    "eta_secs": 15.75
  }
}
```

**Stream Response:**
```json
{
  "id": "16",
  "type": "stream",
  "data": {
    "elements": [...],
    "collector": "rrc00",
    "batch_index": 5,
    "total_so_far": 600
  }
}
```

**Final Response:**
```json
{
  "id": "16",
  "type": "result",
  "data": {
    "total_files": 5,
    "successful_files": 5,
    "failed_files": 0,
    "total_messages": 3500,
    "duration_secs": 25.3
  }
}
```

#### `search.cancel`

Cancel an ongoing search operation.

**Request:**
```json
{
  "id": "17",
  "method": "search.cancel",
  "params": {
    "op_id": "op-search-19aa"
  }
}
```

---

### Database Operations (`database.*`)

#### `database.status`

Get the status of all data sources.

**Request:**
```json
{
  "id": "18",
  "method": "database.status",
  "params": {}
}
```

**Response:**
```json
{
  "id": "18",
  "type": "result",
  "data": {
    "sqlite": {
      "path": "/home/user/.local/share/monocle/monocle-data.sqlite3",
      "exists": true,
      "size_bytes": 52428800,
      "asinfo_count": 120415,
      "as2rel_count": 500000,
      "rpki_roa_count": 450000
    },
    "sources": {
      "rpki": {
        "state": "ready",
        "last_updated": "2024-01-15T10:30:00Z",
        "next_refresh_after": "2024-01-15T11:30:00Z"
      }
    },
    "cache": {
      "directory": "/home/user/.cache/monocle",
      "pfx2as_cache_count": 3
    }
  }
}
```

Notes:
- `state` is one of: `absent`, `ready`, `stale`, `refreshing`, `error`.
- UI clients should use `database.status` to decide whether to request `database.refresh`.

#### `database.refresh`

Refresh a specific data source.

**Request:**
```json
{
  "id": "19",
  "method": "database.refresh",
  "params": {
    "source": "rpki",  // "asinfo", "as2rel", "rpki", or "pfx2as"
    "force": false
  }
}
```

**Progress Response:**
```json
{
  "id": "19",
  "op_id": "op-refresh-rpki-3f91",
  "type": "progress",
  "data": {
    "stage": "downloading",
    "message": "Downloading from Cloudflare..."
  }
}
```

DB-first rule:
- All query methods (`rpki.*`, `inspect.*`, `as2rel.*`, `pfx2as.*`, etc.) must be **network-neutral** and **read from local database/cache only**.
- Any network download/refresh must be explicit via `database.refresh` (or a dedicated refresh method if added later).
- The server should deduplicate refresh: if `database.refresh` is called while a refresh for the same `source` is already running and `force=false`, return a response that references the existing `op_id` (and then stream progress for that operation).

---

## Client Libraries

### Examples (kept out of this design doc)

Full runnable client examples live in the repo under `monocle/examples/` to avoid bloating this design document.

- WebSocket client (Rust): `monocle/examples/ws_client_all.rs`
  - Demonstrates calling all currently registered WebSocket methods.
  - Includes the requested `search.start` / `parse.start` request presets as commented blocks (disabled until those endpoints exist).
- WebSocket client (JavaScript/TypeScript): `monocle/examples/ws_client_all.js`
  - Demonstrates calling all currently registered WebSocket methods.
- Library (non-WS) examples:
  - `monocle/examples/search_bgp_messages.rs`

To run the WebSocket client examples:

1) Start the server (in a separate terminal):
- `cargo run --features server --bin monocle -- server --address 127.0.0.1 --port 8080`

2) Ensure the server is healthy:
- `curl http://127.0.0.1:8080/health`

3) Run the examples:
- Rust:
  - `MONOCLE_WS_URL=ws://127.0.0.1:8080/ws cargo run --example ws_client_all`
- JS:
  - `MONOCLE_WS_URL=ws://127.0.0.1:8080/ws node monocle/examples/ws_client_all.js`

## Client Operations

### Cancellation

Clients can cancel long-running operations by sending a cancel request:

```json
{
  "id": "cancel-1",
  "method": "cancel",
  "params": {
    "op_id": "op-parse-7c2f"
  }
}
```

Cancellation rules:
- `cancel` is a generic alias; method-specific cancels (`parse.cancel`, `search.cancel`) are allowed but optional.
- Cancelling an unknown `op_id` should return `error` with `INVALID_PARAMS` (or a dedicated `UNKNOWN_OPERATION` if you decide to add one later).


### Subscription (Future)

For future implementations, clients may subscribe to real-time updates:

```json
{
  "id": "sub-1",
  "method": "subscribe",
  "params": {
    "topic": "rpki.updates"
  }
}
```

---

## Implementation Details

### Maintainability: Handler Traits + (Optional) Macros

Defining a small handler trait is a net positive for maintainability **if** it stays focused on enforcing protocol consistency (envelope, `op_id`, streaming contract, error mapping) and does not try to become a full framework.

The goal is:
- every lens method has a single entry point with consistent validation and error handling,
- streaming methods consistently produce `progress`/`stream` followed by a terminal `result`/`error`,
- the router is data-driven (registry) rather than a growing `match`.

#### Suggested Trait Shape (Minimal)

- A **method handler** describes:
  - method name (`namespace.operation`)
  - whether it is streaming
  - how to parse/validate params
  - how to execute and emit responses

```rust
// src/server/ws/handler.rs
use async_trait::async_trait;
use serde::de::DeserializeOwned;
use serde_json::Value;

#[derive(Clone, Debug)]
pub struct WsRequest {
    pub id: String,
    pub method: String,
    pub params: Value,
}

#[derive(Clone, Debug)]
pub struct WsContext {
    // Holds DB handles, caches, config, rate-limiter, etc.
    // Kept opaque here for design purposes.
}

#[async_trait]
pub trait WsMethod: Send + Sync + 'static {
    /// Fully qualified method name, e.g. "rpki.validate"
    const METHOD: &'static str;

    /// Parameter type for this method.
    type Params: DeserializeOwned + Send;

    /// Called by the router after JSON parsing; implementers should validate inputs here.
    fn validate(params: &Self::Params) -> Result<(), WsError> {
        let _ = params;
        Ok(())
    }

    /// Execute the method. Implementations may emit progress/stream messages via `sink`.
    async fn handle(
        ctx: WsContext,
        req: WsRequest,
        params: Self::Params,
        sink: WsSink,
    ) -> Result<(), WsError>;
}
```

- `WsSink` is an abstraction over the WebSocket sender that only exposes “send typed envelopes”:
  - `send_progress(id, op_id, data)`
  - `send_stream(id, op_id, data)`
  - `send_result(id, op_id, data)`
  - `send_error(id, op_id, code, message, details)`

That single abstraction prevents each handler from re-implementing envelope formatting.

#### Optional Macro (Use Carefully)

A small macro can reduce boilerplate for trivial methods (non-streaming) without hiding important control flow. For example:

- `ws_method!("time.parse", ParamsType, |ctx, params| async move { ... })`

Avoid a macro that generates too much infrastructure; the trait already provides the consistency boundary.

#### Router Registry

Instead of a large `match`, register handlers at startup:

- `HashMap<&'static str, Arc<dyn DynWsHandler>>`
- where `DynWsHandler` is a type-erased adapter that:
  - deserializes `params` into the handler's `Params`,
  - calls `validate`,
  - assigns/generates `op_id` for streaming,
  - invokes `handle`,
  - ensures exactly one terminal `result` or `error`.

This keeps maintenance cost low as method count grows.

### Server Setup

```rust
// Cargo.toml additions
[dependencies]
axum = { version = "0.7", features = ["ws"] }
tokio = { version = "1", features = ["full"] }
tokio-tungstenite = "0.21"
futures = "0.3"
```

### Connection Handling

```rust
// src/server/mod.rs
use axum::{
    extract::ws::{Message, WebSocket, WebSocketUpgrade},
    response::Response,
    routing::get,
    Router,
};

pub fn create_router() -> Router {
    Router::new()
        .route("/ws", get(ws_handler))
}

async fn ws_handler(ws: WebSocketUpgrade) -> Response {
    ws.on_upgrade(handle_socket)
}

async fn handle_socket(socket: WebSocket) {
    let (sender, receiver) = socket.split();
    // Handle incoming messages and route to appropriate handlers
}
```

### Message Routing

```rust
// src/server/router.rs
pub async fn route_message(
    method: &str,
    params: serde_json::Value,
    sender: &mut SplitSink<WebSocket, Message>,
) -> Result<(), Error> {
    match method {
        "time.parse" => handle_time_parse(params, sender).await,
        "rpki.validate" => handle_rpki_validate(params, sender).await,
        "parse.start" => handle_parse_start(params, sender).await,
        // ... other methods
        _ => Err(Error::UnknownMethod(method.to_string())),
    }
}
```

### Progress Streaming

For long-running operations, use channels to stream progress:

```rust
// src/server/handlers/parse.rs
pub async fn handle_parse_start(
    params: ParseParams,
    sender: &mut SplitSink<WebSocket, Message>,
    request_id: String,
) -> Result<(), Error> {
    let (progress_tx, mut progress_rx) = tokio::sync::mpsc::channel(100);
    
    // Spawn parsing task
    let handle = tokio::spawn(async move {
        let lens = ParseLens::new();
        let callback = Arc::new(move |progress| {
            let _ = progress_tx.blocking_send(progress);
        });
        lens.parse_with_progress(&params.filters, &params.file_path, Some(callback))
    });
    
    // Stream progress updates
    while let Some(progress) = progress_rx.recv().await {
        let msg = create_progress_message(&request_id, progress);
        sender.send(Message::Text(msg)).await?;
    }
    
    // Send final result
    let result = handle.await??;
    let msg = create_result_message(&request_id, result);
    sender.send(Message::Text(msg)).await?;
    
    Ok(())
}
```

---

## Configuration

### Server Configuration

```toml
# monocle.toml
[server]
# WebSocket server address
address = "127.0.0.1"
port = 8800

# Maximum concurrent operations per connection
max_concurrent_ops = 5

# Maximum message size (bytes)
max_message_size = 10485760  # 10MB

# Connection timeout (seconds)
connection_timeout = 300

# Ping interval for keepalive (seconds)
ping_interval = 30
```

### Environment Variables

```bash
MONOCLE_SERVER_ADDRESS=0.0.0.0
MONOCLE_SERVER_PORT=8800
MONOCLE_DATA_DIR=~/.local/share/monocle
```

---

## Security Considerations

### Authentication (Future)

For production deployments, authentication should be added:

```json
{
  "id": "auth-1",
  "method": "auth.login",
  "params": {
    "token": "api-key-or-jwt"
  }
}
```

### Rate Limiting

- Maximum concurrent operations per connection: 5
- Maximum connections per IP: 10
- Request rate limit: 100 requests/minute

### Input Validation

All inputs are validated before processing:
- Prefix format validation (valid CIDR notation)
- ASN range validation (1-4294967295)
- Time string parsing validation
- File path/URL validation for parse operations

---

## Client Libraries

### JavaScript/TypeScript Example

```typescript
class MonocleClient {
  private ws: WebSocket;
  private pending: Map<string, { resolve: Function; reject: Function }>;
  private messageId: number = 0;

  constructor(url: string = 'ws://localhost:8800/ws') {
    this.ws = new WebSocket(url);
    this.pending = new Map();
    
    this.ws.onmessage = (event) => {
      const response = JSON.parse(event.data);
      const handler = this.pending.get(response.id);
      
      if (response.type === 'result') {
        handler?.resolve(response.data);
        this.pending.delete(response.id);
      } else if (response.type === 'error') {
        handler?.reject(new Error(response.data.message));
        this.pending.delete(response.id);
      } else if (response.type === 'progress' || response.type === 'stream') {
        // Handle streaming updates
        handler?.onProgress?.(response.data);
      }
    };
  }

  async call(method: string, params: any = {}): Promise<any> {
    const id = String(++this.messageId);
    
    return new Promise((resolve, reject) => {
      this.pending.set(id, { resolve, reject });
      this.ws.send(JSON.stringify({ id, method, params }));
    });
  }

  // Convenience methods
  async validateRpki(prefix: string, asn: number) {
    return this.call('rpki.validate', { prefix, asn });
  }

  async searchAs(query: string) {
    return this.call('as2org.search', { query: [query] });
  }
}
```

### Python Example

```python
import asyncio
import json
import websockets

class MonocleClient:
    def __init__(self, url='ws://localhost:8800/ws'):
        self.url = url
        self.message_id = 0
        
    async def call(self, method: str, params: dict = None):
        async with websockets.connect(self.url) as ws:
            self.message_id += 1
            request = {
                'id': str(self.message_id),
                'method': method,
                'params': params or {}
            }
            await ws.send(json.dumps(request))
            
            while True:
                response = json.loads(await ws.recv())
                if response['type'] == 'result':
                    return response['data']
                elif response['type'] == 'error':
                    raise Exception(response['data']['message'])
                elif response['type'] in ('progress', 'stream'):
                    yield response['data']
    
    async def validate_rpki(self, prefix: str, asn: int):
        return await self.call('rpki.validate', {'prefix': prefix, 'asn': asn})
```

---

## Implementation Tracking

### Implemented Methods

| Method | Status | Notes |
|--------|--------|-------|
| `system.info` || Server introspection |
| `system.methods` || Method listing |
| `time.parse` || Time string parsing |
| `ip.lookup` || IP information |
| `ip.public` || Public IP lookup |
| `rpki.validate` || RFC 6811 validation |
| `rpki.roas` || ROA listing |
| `rpki.aspas` || ASPA listing |
| `as2rel.search` || Relationship search |
| `as2rel.relationship` || Pair relationship |
| `as2rel.update` || Data refresh |
| `pfx2as.lookup` || Prefix-to-ASN mapping |
| `country.lookup` || Country code/name |
| `inspect.query` || Unified AS/prefix lookup |
| `inspect.search` || Name/country search |
| `inspect.refresh` || ASInfo refresh |
| `parse.start` || Streaming MRT parsing |
| `parse.cancel` || Cancel parsing |
| `search.start` || Streaming BGP search |
| `search.cancel` || Cancel search |
| `database.status` || Database info |
| `database.refresh` || Data source refresh |

### Deprecated Methods

| Method | Replacement | Notes |
|--------|-------------|-------|
| `as2org.search` | `inspect.search` | Use unified inspect namespace |
| `as2org.bootstrap` | `inspect.refresh` | Use unified inspect namespace |

---

## Comparison with REST API

| Aspect                | WebSocket                      | REST                           |
|-----------------------|--------------------------------|--------------------------------|
| Connection            | Persistent                     | Per-request                    |
| Streaming             | Native support                 | Requires SSE or polling        |
| Progress updates      | Push from server               | Polling required               |
| Cancellation          | Immediate via message          | Requires separate endpoint     |
| Complexity            | Higher initial setup           | Simpler                        |
| Caching               | Not applicable                 | HTTP caching available         |
| Load balancing        | Sticky sessions needed         | Stateless, easy to scale       |

For Monocle's use case, WebSocket is preferred because:
1. Long-running operations (parse, search) benefit greatly from streaming
2. Real-time progress updates improve user experience
3. Single connection reduces overhead for frequent queries
4. Cancellation is a first-class feature

---

## Future Enhancements

1. **Pub/Sub for Real-time Updates**: Subscribe to RPKI changes, new BGP data
2. **Query Batching**: Send multiple queries in a single message
3. **Binary Protocol**: Option for more efficient binary encoding (MessagePack, CBOR)
4. **GraphQL over WebSocket**: For complex query scenarios
5. **Multiplexing**: Multiple logical channels over single connection