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
use crate::{
    custom_requests::{
        ApolloCanComposeNotification, ApolloCanComposeNotificationParams,
        ApolloComposeServicesParams, ApolloComposeServicesRequest, ApolloComposeServicesResponse,
        ApolloConfigureAutoCompositionNotification, ApolloConfigureAutoCompositionParams,
        APOLLO_COMPOSITION_PROGRESS_TOKEN,
    },
    graph::{
        supergraph::{KnownSubgraphs, Supergraph},
        Graph, GraphConfig,
    },
    semantic_tokens::{incomplete_tokens_to_deltas, LEGEND_TYPE},
    telemetry::{AnalyticsEvent, CompositionTiming, TelemetryEvent},
};
use apollo_composition::Issue;
use apollo_federation_types::{config::SchemaSource, javascript::SubgraphDefinition};
use debounced::debounced;
use futures::{
    channel::mpsc::{channel, Receiver, Sender},
    future::join_all,
    lock::Mutex,
    SinkExt, StreamExt,
};
use serde::{Deserialize, Serialize};
use std::{borrow::Cow, collections::HashMap};
use std::{sync::Arc, time::Duration};
use tower_lsp::{
    async_trait, jsonrpc,
    lsp_types::{self as lsp, notification::Notification, request::Request},
    Client, ClientSocket, LanguageServer, LspService,
};

#[cfg(all(feature = "wasm", not(test)))]
use wasm_bindgen_futures::spawn_local as spawn;

#[cfg(any(feature = "tokio", test))]
use tokio::spawn;

pub const LANGUAGE_IDS: [&str; 2] = ["apollo-graphql", "graphql"];

/// Configuration options for the Apollo Language Server.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase", default)]
pub struct Config {
    /// The root URI for the workspace.
    pub root_uri: String,
    /// Whether to enable auto composition. This can also be configured at runtime by the client via the `apollo/configureAutoComposition` notification (with params `{ "enabled": boolean }`).
    pub enable_auto_composition: bool,
    /// Forces the server to treat all graphs as subgraphs
    pub force_federation: bool,
    /// Whether to disable telemetry. The language server does not submit telemetry itself, it only sends telemetry events to the client. The client is responsible for submitting telemetry to the telemetry service.
    pub disable_telemetry: bool,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            root_uri: "/".to_string(),
            enable_auto_composition: false,
            force_federation: false,
            disable_telemetry: false,
        }
    }
}

/// The Apollo Language Server.
#[derive(Clone)]
pub struct ApolloLanguageServer {
    state: Arc<State>,
}

struct State {
    graph: Mutex<Option<Graph>>,
    client: Mutex<Client>,
    request_composition: Mutex<Sender<Vec<SubgraphDefinition>>>,
    config: Mutex<Config>,
    document_change_queue_sender: Mutex<Sender<lsp::DidChangeTextDocumentParams>>,
}

const DOCUMENT_SIZE_DEBOUNCE_THRESHOLD: usize = 50_000;
const DOCUMENT_UPDATE_DEBOUNCE_INTERVAL: Duration = Duration::from_millis(150);

impl ApolloLanguageServer {
    fn new(
        client: Client,
        request_composition: Sender<Vec<SubgraphDefinition>>,
        config: Config,
        known_subgraphs: KnownSubgraphs,
    ) -> Self {
        let (document_change_queue_sender, document_change_queue_receiver) =
            channel::<lsp::DidChangeTextDocumentParams>(1);

        // If we have known subgraphs, we should initialize a supergraph
        let graph = (!known_subgraphs.by_name.is_empty()).then_some(Graph::Supergraph(Box::new(
            Supergraph::new(known_subgraphs),
        )));

        let state = State {
            graph: Mutex::new(graph),
            client: Mutex::new(client),
            request_composition: Mutex::new(request_composition),
            config: Mutex::new(config),
            document_change_queue_sender: Mutex::new(document_change_queue_sender),
        };
        let state = Arc::new(state);
        State::initialize_document_update_debouncer(state.clone(), document_change_queue_receiver);

        Self { state }
    }

    /// Construct a new `LspService<ApolloLanguageServer>` with related channels
    /// given the provided `Config`. This returns a tuple of:
    /// - The built tower-lsp `LspService` instance.
    /// - The `ClientSocket` instance.
    /// - The `Receiver` for the composition request channel.
    ///
    /// Example:
    /// ```no_run
    /// use std::collections::HashMap;
    /// use apollo_language_server::{ApolloLanguageServer, Config};
    /// use tower_lsp::Server;
    ///
    /// let (service, client_socket, composition_request_receiver) = ApolloLanguageServer::build_service(Config::default(), HashMap::new());
    /// let input = tokio::io::stdin();
    /// let output = tokio::io::stdout();
    /// Server::new(input, output, client_socket)
    ///     .serve(service);
    /// ```
    pub fn build_service(
        config: Config,
        known_subgraphs: HashMap<String, SchemaSource>,
    ) -> (
        LspService<Self>,
        ClientSocket,
        Receiver<Vec<SubgraphDefinition>>,
    ) {
        let (composition_request_sender, composition_request_receiver) =
            channel::<Vec<SubgraphDefinition>>(1);

        let known_subgraphs = KnownSubgraphs {
            root_uri: config.root_uri.clone(),
            by_name: known_subgraphs
                .iter()
                .map(|(name, source)| (name.clone(), source.clone()))
                .collect(),
            by_uri: known_subgraphs
                .iter()
                .filter_map(|(name, source)| match source {
                    SchemaSource::File { file } => {
                        let uri = if file.is_relative() {
                            // build a uri from config.root_uri and file path
                            let url = lsp::Url::from_directory_path(&config.root_uri)
                                .expect("Failed to parse URL");
                            url.join(file.as_str()).expect("Failed to join URL")
                        } else {
                            lsp::Url::from_file_path(file).expect("Failed to convert path to URL")
                        };

                        Some((uri, name.clone()))
                    }
                    _ => None,
                })
                .collect(),
        };
        let (service, client_socket) = LspService::build(|client| {
            ApolloLanguageServer::new(client, composition_request_sender, config, known_subgraphs)
        })
        .custom_method(
            ApolloConfigureAutoCompositionNotification::METHOD,
            ApolloLanguageServer::configure_auto_composition,
        )
        .custom_method(
            ApolloComposeServicesRequest::METHOD,
            ApolloLanguageServer::request_recompose,
        )
        .finish();
        (service, client_socket, composition_request_receiver)
    }

    fn capabilities() -> lsp::InitializeResult {
        lsp::InitializeResult {
            capabilities: lsp::ServerCapabilities {
                text_document_sync: Some(lsp::TextDocumentSyncCapability::Options(
                    lsp::TextDocumentSyncOptions {
                        change: Some(lsp::TextDocumentSyncKind::FULL),
                        open_close: Some(true),
                        ..Default::default()
                    },
                )),
                completion_provider: Some(lsp::CompletionOptions {
                    // Trigger characters force the completions prompt to show as soon as that character is typed in the case
                    // that we need to show items when the user types a special character.
                    trigger_characters: Some(vec![
                        // `@` in order to properly show completions for directives.
                        "@".to_string(),
                        // `|` in order to properly show completions for directive locations.
                        "|".to_string(),
                        // `&` in order to properly show completions for implementing interfaces.
                        "&".to_string(),
                    ]),
                    ..Default::default()
                }),
                semantic_tokens_provider: Some(
                    lsp::SemanticTokensServerCapabilities::SemanticTokensOptions(
                        lsp::SemanticTokensOptions {
                            work_done_progress_options: lsp::WorkDoneProgressOptions {
                                work_done_progress: None,
                            },
                            legend: lsp::SemanticTokensLegend {
                                token_types: LEGEND_TYPE.into(),
                                token_modifiers: vec![],
                            },
                            range: Some(false),
                            full: Some(lsp::SemanticTokensFullOptions::Delta { delta: Some(true) }),
                        },
                    ),
                ),
                hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
                definition_provider: Some(lsp::OneOf::Left(true)),
                ..Default::default()
            },
            ..Default::default()
        }
    }

    async fn request_recompose(
        &self,
        _params: ApolloComposeServicesParams,
    ) -> jsonrpc::Result<ApolloComposeServicesResponse> {
        let did_compose = self.state.maybe_recompose().await;
        Ok(ApolloComposeServicesResponse { did_compose })
    }

    async fn configure_auto_composition(&self, params: ApolloConfigureAutoCompositionParams) {
        {
            let mut config = self.state.config.lock().await;
            config.enable_auto_composition = params.enabled;
        }
        self.state.maybe_auto_recompose().await;
    }

    /// This method must be called by the host when composition begins in order
    /// to notify the language client with a `WorkDoneProgressBegin` event. The
    /// corresponding `WorkDoneProgressEnd` event will be sent by the language
    /// server in `composition_did_update`.
    pub async fn composition_did_start(&self) {
        self.state
            .client
            .lock()
            .await
            .send_notification::<lsp::notification::Progress>(lsp::ProgressParams {
                token: lsp::ProgressToken::String(APOLLO_COMPOSITION_PROGRESS_TOKEN.to_string()),
                value: lsp::ProgressParamsValue::WorkDone(lsp::WorkDoneProgress::Begin(
                    lsp::WorkDoneProgressBegin {
                        title: "Composing services".to_string(),
                        cancellable: Some(false),
                        message: None,
                        percentage: None,
                    },
                )),
            })
            .await;
    }

    /// This method must be called by the host of the language server after
    /// completing a composition request. It will update the supergraph and
    /// subsequently publish diagnostics for each subgraph.
    /// > Note: A `WorkDoneProgressEnd` event will be sent after this completes.
    /// > The `composition_did_start` method must be called before this method
    /// > in order to send the matching `WorkDoneProgressBegin` event.
    pub async fn composition_did_update(
        &self,
        _supergraph_sdl: Option<String>,
        issues: Vec<Issue>,
        timing: Option<Duration>,
    ) {
        self.state.composition_did_update(issues).await;
        if let Some(timing) = timing {
            self.send_telemetry_if_enabled(TelemetryEvent::Analytics(
                AnalyticsEvent::CompositionTimeInMs(CompositionTiming {
                    value: timing.as_millis() as u64,
                }),
            ))
            .await;
        }
    }

    /// This method must be called by the host of the language server when a new
    /// subgraph is added to the supergraph. Concretely, when a new subgraph is
    /// added to the supergraph.yaml, this method should be called.
    pub async fn add_subgraph(&self, name: String, source: SchemaSource) {
        let Some(Graph::Supergraph(supergraph)) = &mut *self.state.graph.lock().await else {
            panic!("Graph is unexpectedly not a supergraph");
        };

        supergraph.add_known_subgraph(name, source).await;
    }

    /// This method must be called by the host of the language server when a
    /// subgraph is removed from the supergraph. Concretely, when a subgraph is
    /// removed from the supergraph.yaml, this method should be called.
    pub async fn remove_subgraph(&self, name: &str) {
        let Some(Graph::Supergraph(supergraph)) = &mut *self.state.graph.lock().await else {
            panic!("Graph is unexpectedly not a supergraph");
        };

        supergraph.remove_known_subgraph(name).await;
    }

    /// The host can call this method to publish diagnostics for a given URI.
    pub async fn publish_diagnostics(&self, uri: lsp::Url, diagnostics: Vec<lsp::Diagnostic>) {
        let graph = self.state.graph.lock().await;
        let version = graph.as_ref().and_then(|graph| graph.version_for_uri(&uri));

        self.state
            .client
            .lock()
            .await
            .publish_diagnostics(uri, diagnostics, version)
            .await;
    }

    async fn send_telemetry_if_enabled(&self, event: TelemetryEvent) {
        if !self.state.config.lock().await.disable_telemetry {
            self.state.client.lock().await.telemetry_event(event).await;
        }
    }

    #[cfg(test)]
    async fn config(&self) -> Config {
        self.state.config.lock().await.clone()
    }
}

impl State {
    async fn maybe_auto_recompose(&self) {
        if !self.config.lock().await.enable_auto_composition {
            return;
        }
        self.maybe_recompose().await;
    }

    async fn maybe_send_can_compose_notification(&self) {
        let invalid_subgraph_names = if let Some(Some(supergraph)) =
            self.graph.lock().await.as_ref().map(Graph::supergraph)
        {
            // We only want to allow recomposition if none of the subgraphs have
            // any parse/validation errors. We know those will need to be
            // addressed before we can attempt to compose.
            supergraph.get_invalid_subgraph_uris()
        } else {
            return;
        };

        self.client
            .lock()
            .await
            .send_notification::<ApolloCanComposeNotification>(ApolloCanComposeNotificationParams {
                can_compose: invalid_subgraph_names.is_empty(),
                subgraphs_with_errors: invalid_subgraph_names,
            })
            .await;
    }

    async fn maybe_recompose(&self) -> bool {
        let subgraph_definitions = if let Some(Some(supergraph)) =
            self.graph.lock().await.as_ref().map(Graph::supergraph)
        {
            // We only want to recompose if none of the subgraphs have any
            // parse/validation errors. We know those will need to be addressed
            // before we can attempt to compose.
            if !supergraph.subgraphs_are_invalid() {
                supergraph.subgraph_definitions()
            } else {
                return false;
            }
        } else {
            return false;
        };

        self.request_composition
            .lock()
            .await
            .send(subgraph_definitions)
            .await
            .expect("Failed to send message");
        true
    }

    async fn composition_did_update(&self, issues: Vec<Issue>) {
        let (diagnostics_by_subgraph, unattributed_diagnostics) = {
            let graph = self.graph.lock().await;
            match graph.as_ref() {
                Some(Graph::Supergraph(supergraph)) => supergraph.diagnostics_for_composition(issues),
                _ => panic!("Programming error: called `composition_did_update` when graph is not a supergraph."),
            }
        };

        let client = self.client.lock().await;
        join_all(
            diagnostics_by_subgraph
                .into_iter()
                .map(|(url, (diagnostics, version))| {
                    client.publish_diagnostics(url, diagnostics, Some(version))
                }),
        )
        .await;

        client
            .publish_diagnostics(
                lsp::Url::parse(&self.config.lock().await.root_uri).expect("Failed to parse URL"),
                unattributed_diagnostics,
                0.into(),
            )
            .await;

        client
            .send_notification::<lsp::notification::Progress>(lsp::ProgressParams {
                token: lsp::ProgressToken::String(APOLLO_COMPOSITION_PROGRESS_TOKEN.to_string()),
                value: lsp::ProgressParamsValue::WorkDone(lsp::WorkDoneProgress::End(
                    lsp::WorkDoneProgressEnd { message: None },
                )),
            })
            .await;
    }

    fn initialize_document_update_debouncer(
        state: Arc<State>,
        document_change_queue_receiver: Receiver<lsp::DidChangeTextDocumentParams>,
    ) {
        spawn(async move {
            let mut debounced_document_change_queue = debounced(
                document_change_queue_receiver,
                DOCUMENT_UPDATE_DEBOUNCE_INTERVAL,
            );

            while let Some(data) = debounced_document_change_queue.next().await {
                state.handle_document_update(data).await;
            }
        });
    }

    async fn handle_document_update(&self, data: lsp::DidChangeTextDocumentParams) {
        let lsp::DidChangeTextDocumentParams {
            text_document,
            content_changes,
        } = data;
        let lsp::VersionedTextDocumentIdentifier { uri, version } = text_document;
        let text = content_changes
            .into_iter()
            .next()
            .expect("Expected at least one content change")
            .text;

        let graph_config = {
            let config = self.config.lock().await;

            GraphConfig {
                force_federation: config.force_federation,
            }
        };

        let (diagnostics, version) = {
            let mut graph = self.graph.lock().await;

            let Some(graph) = graph.as_mut() else {
                panic!("Attempted to change a document that hasn't been opened");
            };
            graph.update(uri.clone(), text, version, graph_config);

            graph.diagnostics_for_uri(&uri)
        };

        self.client
            .lock()
            .await
            .publish_diagnostics(uri.clone(), diagnostics, Some(version))
            .await;

        self.maybe_auto_recompose().await;
        self.maybe_send_can_compose_notification().await;
    }
}

#[async_trait]
impl LanguageServer for ApolloLanguageServer {
    async fn initialize(
        &self,
        initialize_params: lsp::InitializeParams,
    ) -> jsonrpc::Result<lsp::InitializeResult> {
        let options: Option<Config> = initialize_params
            .initialization_options
            .map(|options| {
                serde_json::from_value(options).map_err(|err| jsonrpc::Error {
                    message: Cow::from(err.to_string()),
                    code: jsonrpc::ErrorCode::InvalidParams,
                    data: None,
                })
            })
            .transpose()?;

        let mut config = self.state.config.lock().await;
        if let Some(options) = options {
            *config = options;
        }
        config.root_uri = initialize_params
            .root_uri
            .map(|uri| uri.to_string())
            .unwrap_or("inmemory://".to_string());

        Ok(ApolloLanguageServer::capabilities())
    }

    async fn initialized(&self, _: lsp::InitializedParams) {
        self.send_telemetry_if_enabled(TelemetryEvent::Analytics(AnalyticsEvent::Initialized))
            .await;
    }

    async fn shutdown(&self) -> jsonrpc::Result<()> {
        Ok(())
    }

    async fn did_open(&self, params: lsp::DidOpenTextDocumentParams) {
        let lsp::TextDocumentItem {
            uri,
            version,
            text,
            language_id,
        } = params.text_document;

        if !LANGUAGE_IDS.contains(&language_id.as_str()) {
            return;
        }

        let graph_config = {
            let config = self.state.config.lock().await;
            GraphConfig {
                force_federation: config.force_federation,
            }
        };

        // This step applies to both monolith and supergraph. Capture any
        // diagnostics for the new document. We'll publish them after the block
        // so as not to hold the lock across an `await`.
        let (diagnostics_for_uri, version) = {
            let mut graph = self.state.graph.lock().await;
            if graph.is_some() {
                graph
                    .as_mut()
                    .unwrap()
                    .update(uri.clone(), text, version, graph_config);
            } else {
                let new_graph =
                    Graph::new(uri.clone(), text, KnownSubgraphs::default(), graph_config);
                *graph = Some(new_graph);
            };

            graph.as_ref().unwrap().diagnostics_for_uri(&uri)
        };

        if !diagnostics_for_uri.is_empty() {
            self.state
                .client
                .lock()
                .await
                .publish_diagnostics(uri, diagnostics_for_uri, Some(version))
                .await;
        }

        self.state.maybe_auto_recompose().await;
        self.state.maybe_send_can_compose_notification().await;
    }

    async fn did_change(&self, params: lsp::DidChangeTextDocumentParams) {
        if params.content_changes[0].text.len() < DOCUMENT_SIZE_DEBOUNCE_THRESHOLD {
            self.state.handle_document_update(params).await;
        } else {
            self.state
                .document_change_queue_sender
                .lock()
                .await
                .send(params.clone())
                .await
                .expect("Failed to send message")
        }
    }

    async fn did_close(&self, params: lsp::DidCloseTextDocumentParams) {
        {
            let mut graph = self.state.graph.lock().await;
            match &mut *graph {
                Some(Graph::Monolith(_)) => {
                    *graph = None;
                }
                Some(Graph::Supergraph(supergraph)) => {
                    if supergraph.remove(&params.text_document.uri).is_none() {
                        panic!("Subgraph is unexpectedly None");
                    }
                }
                None => panic!("Graph is unexpectedly None"),
            }
        }
        self.state.maybe_auto_recompose().await;
        self.state.maybe_send_can_compose_notification().await;
    }

    async fn completion(
        &self,
        params: lsp::CompletionParams,
    ) -> jsonrpc::Result<Option<lsp::CompletionResponse>> {
        let graph = self.state.graph.lock().await;

        Ok(graph.as_ref().and_then(|graph| {
            graph.completions(
                &params.text_document_position.text_document.uri,
                params.text_document_position.position,
            )
        }))
    }

    async fn semantic_tokens_full(
        &self,
        params: lsp::SemanticTokensParams,
    ) -> jsonrpc::Result<Option<lsp::SemanticTokensResult>> {
        let graph = self.state.graph.lock().await;
        Ok(graph.as_ref().map(|graph| {
            let tokens = graph
                .semantic_tokens_full(&params.text_document.uri)
                .unwrap_or_default();
            lsp::SemanticTokensResult::Tokens(lsp::SemanticTokens {
                result_id: None,
                data: incomplete_tokens_to_deltas(tokens),
            })
        }))
    }

    async fn hover(&self, params: lsp::HoverParams) -> jsonrpc::Result<Option<lsp::Hover>> {
        let graph = self.state.graph.lock().await;
        Ok(graph.as_ref().and_then(|graph| {
            graph.on_hover(
                &params.text_document_position_params.text_document.uri,
                &params.text_document_position_params.position,
            )
        }))
    }

    async fn goto_definition(
        &self,
        params: lsp::GotoDefinitionParams,
    ) -> jsonrpc::Result<Option<lsp::GotoDefinitionResponse>> {
        let graph = self.state.graph.lock().await;
        Ok(graph.as_ref().map(|graph| {
            lsp::GotoDefinitionResponse::from(
                graph
                    .goto_definition(
                        &params.text_document_position_params.text_document.uri,
                        &params.text_document_position_params.position,
                    )
                    .unwrap_or_default(),
            )
        }))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use apollo_composition::{Severity, SubgraphLocation};
    use lsp::{InitializeParams, PublishDiagnosticsParams};
    use serde_json::{from_value, json, to_value};
    use tokio::{sync::Mutex, task::yield_now};
    use tower::{Service, ServiceExt};
    use tower_lsp::{jsonrpc, LspService, Server};

    fn initialize_request(id: i64) -> jsonrpc::Request {
        jsonrpc::Request::build("initialize")
            .params(json!({"capabilities":{}}))
            .id(id)
            .finish()
    }

    fn initialize_request_with_server_configurations(id: i64) -> jsonrpc::Request {
        jsonrpc::Request::build("initialize")
            .params(
                to_value(InitializeParams {
                    initialization_options: Some(json!({
                        "enableAutoComposition": true,
                        "disableTelemetry": true,
                    })),
                    process_id: None,
                    root_uri: Some(lsp::Url::from_directory_path("/path/to/project").unwrap()),
                    ..Default::default()
                })
                .unwrap(),
            )
            .id(id)
            .finish()
    }

    fn initialized_notification() -> jsonrpc::Request {
        jsonrpc::Request::build("initialized")
            .params(json!({}))
            .finish()
    }

    fn shutdown_request() -> jsonrpc::Request {
        jsonrpc::Request::build("shutdown").finish()
    }

    fn server_capabilities() -> serde_json::Value {
        serde_json::to_value(ApolloLanguageServer::capabilities()).unwrap()
    }

    async fn request(
        server: &mut LspService<ApolloLanguageServer>,
        request: jsonrpc::Request,
    ) -> Option<jsonrpc::Response> {
        server.ready().await.unwrap().call(request).await.unwrap()
    }

    #[allow(clippy::type_complexity)]
    fn listen_to_channels(
        mut socket: ClientSocket,
        mut composition_listener: Receiver<Vec<SubgraphDefinition>>,
    ) -> (
        Arc<Mutex<Vec<jsonrpc::Request>>>,
        Arc<Mutex<Vec<Vec<SubgraphDefinition>>>>,
    ) {
        let socket_messages = Arc::new(Mutex::new(Vec::default()));
        let composition_listener_messages = Arc::new(Mutex::new(Vec::default()));

        let socket_messages_inner = socket_messages.clone();
        let composition_listener_messages_inner = composition_listener_messages.clone();
        tokio::spawn(async move {
            while let Some(data) = socket.next().await {
                socket_messages_inner.lock().await.push(data)
            }
        });
        tokio::spawn(async move {
            while let Some(data) = composition_listener.next().await {
                composition_listener_messages_inner.lock().await.push(data)
            }
        });

        (socket_messages, composition_listener_messages)
    }

    #[tokio::test]
    async fn initialization_and_shutdown() {
        let (mut server, ..) =
            ApolloLanguageServer::build_service(Config::default(), HashMap::new());

        assert_eq!(
            request(&mut server, initialize_request(1)).await,
            Some(jsonrpc::Response::from_ok(1.into(), server_capabilities()))
        );

        assert_eq!(request(&mut server, initialized_notification()).await, None);

        // TODO: something isn't working here, should be an error after 2nd shutdown request
        // and our shutdown method isn't being called at all
        assert_eq!(request(&mut server, shutdown_request()).await, None);
        assert_eq!(request(&mut server, shutdown_request()).await, None);
    }

    #[tokio::test]
    async fn initialization_with_client_config() {
        let (mut server, ..) =
            ApolloLanguageServer::build_service(Config::default(), HashMap::new());

        assert_eq!(
            request(
                &mut server,
                initialize_request_with_server_configurations(1)
            )
            .await,
            Some(jsonrpc::Response::from_ok(1.into(), server_capabilities()))
        );

        assert!(server.inner().config().await.enable_auto_composition);
        assert_eq!(
            server.inner().config().await.root_uri,
            "file:///path/to/project/".to_string()
        );

        assert_eq!(request(&mut server, initialized_notification()).await, None);
    }

    #[tokio::test]
    async fn initialization_without_root_uri_specified() {
        let (mut server, ..) =
            ApolloLanguageServer::build_service(Config::default(), HashMap::new());

        assert_eq!(
            request(&mut server, initialize_request(1)).await,
            Some(jsonrpc::Response::from_ok(1.into(), server_capabilities()))
        );

        assert_eq!(
            server.inner().state.config.lock().await.root_uri,
            "inmemory://".to_string()
        );

        assert_eq!(request(&mut server, initialized_notification()).await, None);
    }

    #[tokio::test]
    async fn diagnostics() {
        let (mut server, socket, composition_listener) =
            ApolloLanguageServer::build_service(Config::default(), HashMap::new());

        let (socket_messages, composition_listener_messages) =
            listen_to_channels(socket, composition_listener);

        request(
            &mut server,
            // enable composition for this test
            initialize_request_with_server_configurations(1),
        )
        .await;
        request(&mut server, initialized_notification()).await;

        // On didOpen, we don't expect any diagnostics to be published when the
        // document is valid. Further down, on didChange, we expect empty diagnostics
        // to be published to clear any existing ones.
        request(
            &mut server,
            jsonrpc::Request::build("textDocument/didOpen")
                .params(json!({
                    "textDocument": {
                        "uri": "file:///path/to/file",
                        "version": 1,
                        "languageId": "apollo-graphql",
                        "text": "extend schema @link(url: \"https://specs.apollo.dev/federation/v2.10\")\ntype Query { hello: String }"
                    }
                }))
                .finish(),
        )
        .await;

        request(
            &mut server,
            jsonrpc::Request::build("textDocument/didChange")
                .params(json!({
                    "textDocument": {
                        "uri": "file:///path/to/file",
                        "version": 2,
                    },
                    "contentChanges": [{
                        "text": "extend schema @link(url: \"https://specs.apollo.dev/federation/v2.10\")\ntype Query { hello: String! }"
                    }]
                }))
                .finish(),
        )
        .await;

        // Wait for the client and composition channel to send their messages
        yield_now().await;

        let messages = &*socket_messages.lock().await;
        assert_eq!(
            messages,
            &[
                // no diagnostics published on didOpen, since the document is valid
                jsonrpc::Request::build("apollo/canCompose")
                    .params(json!({"canCompose": true, "subgraphsWithErrors": []}))
                    .finish(),
                // empty diagnostics published on didChange to clear any existing ones
                jsonrpc::Request::build("textDocument/publishDiagnostics")
                    .params(json!({"uri": "file:///path/to/file", "diagnostics": [], "version": 2}))
                    .finish(),
                jsonrpc::Request::build("apollo/canCompose")
                    .params(json!({"canCompose": true, "subgraphsWithErrors": []}))
                    .finish(),
            ]
        );

        let composition_messages = &*composition_listener_messages.lock().await;
        assert_eq!(composition_messages, &[
            [
                SubgraphDefinition {
                    name: "file:///path/to/file".into(), 
                    url: "file:///path/to/file".into(), 
                    sdl: "extend schema @link(url: \"https://specs.apollo.dev/federation/v2.10\")\ntype Query { hello: String }".into() 
                }
            ],[
                SubgraphDefinition {
                    name: "file:///path/to/file".into(), 
                    url: "file:///path/to/file".into(), 
                    sdl: "extend schema @link(url: \"https://specs.apollo.dev/federation/v2.10\")\ntype Query { hello: String! }".into() 
                }
            ]
        ]);
    }

    #[tokio::test]
    async fn runs_in_tower_lsp_server() {
        fn mock_msg(msg: &str) -> String {
            format!("Content-Length: {}\r\n\r\n{}", msg.len(), msg)
        }

        let mock_request = mock_msg(
            r#"{"jsonrpc":"2.0","method":"initialize","params":{"capabilities":{}},"id":0}"#,
        );

        let mock_response = mock_msg(
            &serde_json::to_string(&jsonrpc::Response::from_ok(0.into(), server_capabilities()))
                .unwrap(),
        );

        let (sender, _) = channel::<Vec<SubgraphDefinition>>(1);
        let (service, socket) = LspService::new(|client| {
            ApolloLanguageServer::new(client, sender, Config::default(), Default::default())
        });

        let mut stdout = Vec::new();

        Server::new(&mut mock_request.as_bytes(), &mut stdout, socket)
            .serve(service)
            .await;

        let stdout = String::from_utf8(stdout).unwrap();
        assert_eq!(stdout, mock_response);
    }

    #[tokio::test]
    async fn did_close() {
        let (mut server, _, mut composition_listener) =
            ApolloLanguageServer::build_service(Config::default(), HashMap::new());

        request(
            &mut server,
            // enable composition for this test
            initialize_request_with_server_configurations(1),
        )
        .await;
        request(&mut server, initialized_notification()).await;

        // On didOpen, we don't expect any diagnostics to be published when the
        // document is valid.
        request(
            &mut server,
            jsonrpc::Request::build("textDocument/didOpen")
                .params(json!({
                    "textDocument": {
                        "uri": "file:///path/to/file1",
                        "version": 1,
                        "languageId": "apollo-graphql",
                        "text": "extend schema @link(url: \"https://specs.apollo.dev/federation/v2.10\")\ntype Query { hello: String }"
                    }
                }))
                .finish(),
        )
        .await;

        // The server will hang / wait for this message to be consumed. For this
        // test we don't really need to do anything with it.
        composition_listener.next().await.unwrap();

        request(
            &mut server,
            jsonrpc::Request::build("textDocument/didOpen")
                .params(json!({
                    "textDocument": {
                        "uri": "file:///path/to/file2",
                        "version": 1,
                        "languageId": "apollo-graphql",
                        "text": "extend schema @link(url: \"https://specs.apollo.dev/federation/v2.10\")\ntype Query { goodbye: String! }"
                    },
                }))
                .finish(),
        )
        .await;

        // The server will hang / wait for this message to be consumed. For this
        // test we don't really need to do anything with it.
        composition_listener.next().await.unwrap();

        request(
            &mut server,
            jsonrpc::Request::build("textDocument/didClose")
                .params(json!({
                    "textDocument": {
                        "uri": "file:///path/to/file1",
                    }
                }))
                .finish(),
        )
        .await;

        // On didClose, we expect composition to be requested again. If it
        // doesn't, this test will hang.
        composition_listener.next().await.unwrap();
    }

    #[tokio::test]
    async fn custom_notification_toggle_auto_composition() {
        let (mut server, _, _) =
            ApolloLanguageServer::build_service(Config::default(), HashMap::new());

        request(
            &mut server,
            initialize_request_with_server_configurations(1),
        )
        .await;
        request(&mut server, initialized_notification()).await;

        assert!(server.inner().config().await.enable_auto_composition);
        request(
            &mut server,
            jsonrpc::Request::build(ApolloConfigureAutoCompositionNotification::METHOD)
                .params(json!({"enabled": false}))
                .finish(),
        )
        .await;
        assert!(!server.inner().config().await.enable_auto_composition);
        request(
            &mut server,
            jsonrpc::Request::build(ApolloConfigureAutoCompositionNotification::METHOD)
                .params(json!({"enabled": true}))
                .finish(),
        )
        .await;
        assert!(server.inner().config().await.enable_auto_composition);
    }

    #[tokio::test]
    async fn custom_notification_trigger_recomposition() {
        let (mut server, socket, composition_listener) =
            ApolloLanguageServer::build_service(Config::default(), HashMap::new());

        let (socket_messages, composition_listener_messages) =
            listen_to_channels(socket, composition_listener);

        request(
            &mut server,
            initialize_request_with_server_configurations(1),
        )
        .await;

        request(&mut server, initialized_notification()).await;

        request(
            &mut server,
            jsonrpc::Request::build("textDocument/didOpen")
                .params(json!({
                    "textDocument": {
                        "uri": "file:///path/to/file1",
                        "version": 1,
                        "languageId": "apollo-graphql",
                        "text": "extend schema @link(url: \"https://specs.apollo.dev/federation/v2.10\")\ntype Query { hello: String }"
                    }
                }))
                .finish(),
        ).await;

        request(
            &mut server,
            jsonrpc::Request::build(ApolloComposeServicesRequest::METHOD)
                .id(100)
                .params(json!({}))
                .finish(),
        )
        .await;

        let messages = &*socket_messages.lock().await;
        assert_eq!(
            messages,
            &[jsonrpc::Request::build("apollo/canCompose")
                .params(json!({"canCompose": true, "subgraphsWithErrors": []}))
                .finish(),]
        );

        let composition_messages = &*composition_listener_messages.lock().await;
        assert_eq!(composition_messages, &[
            [
                SubgraphDefinition {
                    name: "file:///path/to/file1".into(), 
                    url: "file:///path/to/file1".into(), 
                    sdl: "extend schema @link(url: \"https://specs.apollo.dev/federation/v2.10\")\ntype Query { hello: String }".into() 
                }
            ],
            // the manual request
            [
                SubgraphDefinition {
                    name: "file:///path/to/file1".into(), 
                    url: "file:///path/to/file1".into(), 
                    sdl: "extend schema @link(url: \"https://specs.apollo.dev/federation/v2.10\")\ntype Query { hello: String }".into() 
                }
            ]
        ]);
    }

    #[tokio::test]
    async fn with_graphql_language_id() {
        let (mut server, _, mut composition_listener) =
            ApolloLanguageServer::build_service(Config::default(), HashMap::new());

        request(
            &mut server,
            // enable composition for this test
            initialize_request_with_server_configurations(1),
        )
        .await;
        request(&mut server, initialized_notification()).await;

        // On didOpen, we don't expect any diagnostics to be published when the
        // document is valid.
        request(
            &mut server,
            jsonrpc::Request::build("textDocument/didOpen")
                .params(json!({
                    "textDocument": {
                        "uri": "file:///path/to/file1",
                        "version": 1,
                        "languageId": "graphql",
                        "text": "extend schema @link(url: \"https://specs.apollo.dev/federation/v2.10\")\ntype Query { hello: String }"
                    }
                }))
                .finish(),
        )
        .await;

        // The server will hang / wait for this message to be consumed. For this
        // test we don't really need to do anything with it.
        composition_listener.next().await.unwrap();

        request(
            &mut server,
            jsonrpc::Request::build("textDocument/didChange")
                .params(json!({
                    "textDocument": {
                        "uri": "file:///path/to/file1",
                        "version": 2,
                    },
                    "contentChanges": [{
                        "text": "extend schema @link(url: \"https://specs.apollo.dev/federation/v2.10\")\ntype Query { hello: String! }"
                    }]
                }))
                .finish(),
        )
        .await;

        // The server will hang / wait for this message to be consumed. For this
        // test we don't really need to do anything with it.
        composition_listener.next().await.unwrap();

        request(
            &mut server,
            jsonrpc::Request::build("textDocument/didClose")
                .params(json!({
                    "textDocument": {
                        "uri": "file:///path/to/file1",
                    }
                }))
                .finish(),
        )
        .await;

        // On didClose, we expect composition to be requested again. If it
        // doesn't, this test will hang.
        composition_listener.next().await.unwrap();
    }

    #[tokio::test]
    async fn publishing_diagnostics_to_known_subgraphs() {
        // Initialize the server with known subgraphs.
        // Note that `remote` has no URI - its composition diagnostics should be published to the root URI.
        // The other two subgraphs should have their diagnostics published to their respective URIs.
        let (mut service, socket, composition_listener) = ApolloLanguageServer::build_service(
            Config {
                root_uri: "/path/to/project".into(),
                ..Default::default()
            },
            [
                (
                    "local".into(),
                    SchemaSource::File {
                        file: "local.graphql".into(),
                    },
                ),
                (
                    "local_relative".into(),
                    SchemaSource::File {
                        file: "../../local_relative.graphql".into(),
                    },
                ),
                (
                    "remote".into(),
                    SchemaSource::Subgraph {
                        graphref: "testing@current".into(),
                        subgraph: "remote".into(),
                    },
                ),
            ]
            .into_iter()
            .collect(),
        );

        let (socket_messages, _) = listen_to_channels(socket, composition_listener);

        request(
            &mut service,
            initialize_request_with_server_configurations(1),
        )
        .await;

        request(&mut service, initialized_notification()).await;

        // didOpen request for local subgraph
        request(&mut service, jsonrpc::Request::build("textDocument/didOpen")
                .params(json!({
                    "textDocument": {
                        "uri": "file:///path/to/project/local.graphql",
                        "version": 1,
                        "languageId": "graphql",
                        "text": "extend schema @link(url: \"https://specs.apollo.dev/federation/v2.10\")\ntype Query { hello: String }"
                    }
                }))
                .finish()).await;

        // didOpen request for local_relative subgraph
        request(&mut service, jsonrpc::Request::build("textDocument/didOpen")
                .params(json!({
                    "textDocument": {
                        "uri": "file:///path/local_relative.graphql",
                        "version": 1,
                        "languageId": "graphql",
                        "text": "extend schema @link(url: \"https://specs.apollo.dev/federation/v2.10\")\ntype Query { hello2: String }"
                    }
                }))
                .finish()).await;

        service
            .inner()
            .composition_did_update(
                None,
                vec![
                    Issue {
                        code: "TEST_REMOTE".into(),
                        message: "Test issue".into(),
                        locations: vec![SubgraphLocation {
                            subgraph: Some("remote".into()),
                            range: None,
                        }],
                        severity: Severity::Error,
                    },
                    Issue {
                        code: "TEST_LOCAL".into(),
                        message: "Test issue".into(),
                        locations: vec![SubgraphLocation {
                            subgraph: Some("local".into()),
                            range: None,
                        }],
                        severity: Severity::Error,
                    },
                    Issue {
                        code: "TEST_LOCAL_RELATIVE".into(),
                        message: "Test issue".into(),
                        locations: vec![SubgraphLocation {
                            subgraph: Some("local_relative".into()),
                            range: None,
                        }],
                        severity: Severity::Error,
                    },
                ],
                None,
            )
            .await;

        let lock = socket_messages.lock().await;
        let diagnostics = lock
            .iter()
            .filter(|msg| msg.method() == "textDocument/publishDiagnostics")
            .map(|msg| {
                from_value::<PublishDiagnosticsParams>(msg.params().unwrap().clone()).unwrap()
            })
            .collect::<Vec<_>>();

        assert_eq!(diagnostics.len(), 3);
        assert!(diagnostics
            .iter()
            .any(|diag| diag.uri.as_str() == "file:///path/to/project/"));
        assert!(diagnostics
            .iter()
            .any(|diag| diag.uri.as_str() == "file:///path/to/project/local.graphql"));
        assert!(diagnostics
            .iter()
            .any(|diag| diag.uri.as_str() == "file:///path/local_relative.graphql"));
    }

    #[tokio::test]
    async fn publishing_diagnostics_to_known_subgraphs_without_opening_files() {
        // Initialize the server with known subgraphs.
        // Note that `remote` has no URI - its composition diagnostics should be published to the root URI.
        // The other two subgraphs should have their diagnostics published to their respective URIs.
        let (mut service, socket, composition_listener) = ApolloLanguageServer::build_service(
            Config {
                root_uri: "/path/to/project".into(),
                ..Default::default()
            },
            [
                (
                    "local".into(),
                    SchemaSource::File {
                        file: "local.graphql".into(),
                    },
                ),
                (
                    "local_relative".into(),
                    SchemaSource::File {
                        file: "../../local_relative.graphql".into(),
                    },
                ),
                (
                    "remote".into(),
                    SchemaSource::Subgraph {
                        graphref: "testing@current".into(),
                        subgraph: "remote".into(),
                    },
                ),
            ]
            .into_iter()
            .collect(),
        );

        let (socket_messages, _) = listen_to_channels(socket, composition_listener);

        request(
            &mut service,
            initialize_request_with_server_configurations(1),
        )
        .await;

        request(&mut service, initialized_notification()).await;

        service
            .inner()
            .composition_did_update(
                None,
                vec![
                    Issue {
                        code: "TEST_REMOTE".into(),
                        message: "Test issue".into(),
                        locations: vec![SubgraphLocation {
                            subgraph: Some("remote".into()),
                            range: None,
                        }],
                        severity: Severity::Error,
                    },
                    Issue {
                        code: "TEST_LOCAL".into(),
                        message: "Test issue".into(),
                        locations: vec![SubgraphLocation {
                            subgraph: Some("local".into()),
                            range: None,
                        }],
                        severity: Severity::Error,
                    },
                    Issue {
                        code: "TEST_LOCAL_RELATIVE".into(),
                        message: "Test issue".into(),
                        locations: vec![SubgraphLocation {
                            subgraph: Some("local_relative".into()),
                            range: None,
                        }],
                        severity: Severity::Error,
                    },
                ],
                None,
            )
            .await;

        let lock = socket_messages.lock().await;
        let diagnostics = lock
            .iter()
            .filter(|msg| msg.method() == "textDocument/publishDiagnostics")
            .map(|msg| {
                from_value::<PublishDiagnosticsParams>(msg.params().unwrap().clone()).unwrap()
            })
            .collect::<Vec<_>>();

        assert_eq!(diagnostics.len(), 3);
        assert!(diagnostics
            .iter()
            .any(|diag| diag.uri.as_str() == "file:///path/to/project/"));
        assert!(diagnostics
            .iter()
            .any(|diag| diag.uri.as_str() == "file:///path/to/project/local.graphql"));
        assert!(diagnostics
            .iter()
            .any(|diag| diag.uri.as_str() == "file:///path/local_relative.graphql"));
    }

    #[tokio::test]
    async fn host_can_publish_diagnostics() {
        let (mut service, socket, composition_listener) = ApolloLanguageServer::build_service(
            Config {
                root_uri: "/path/to/project".into(),
                ..Default::default()
            },
            HashMap::new(),
        );

        let (socket_messages, _) = listen_to_channels(socket, composition_listener);

        request(
            &mut service,
            initialize_request_with_server_configurations(1),
        )
        .await;

        request(&mut service, initialized_notification()).await;

        let diagnostics = vec![lsp::Diagnostic::new_simple(
            lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 0)),
            "supergraph.yaml missing fields".into(),
        )];

        service
            .inner()
            .publish_diagnostics(
                lsp::Url::from_file_path("/path/to/project/supergraph.yaml").unwrap(),
                diagnostics,
            )
            .await;

        yield_now().await;

        let lock = socket_messages.lock().await;
        let diagnostics_published_to_client = lock
            .iter()
            .filter(|msg| msg.method() == "textDocument/publishDiagnostics")
            .map(|msg| {
                from_value::<PublishDiagnosticsParams>(msg.params().unwrap().clone()).unwrap()
            })
            .collect::<Vec<_>>();

        assert_eq!(diagnostics_published_to_client.len(), 1);
        assert_eq!(
            diagnostics_published_to_client[0].uri.as_str(),
            "file:///path/to/project/supergraph.yaml"
        );
    }
}