use std::borrow::Cow;
use bytes::Bytes;
use lsp_types::PublishDiagnosticsParams;
use tokio::sync::mpsc::UnboundedSender;
use tracing::{Span, warn};
use crate::documents::Documents;
use crate::raw::{RawMessage, RequestId};
#[derive(Debug, Clone)]
pub struct Context {
pub(crate) request_id: Option<RequestId>,
pub(crate) span: Span,
pub(crate) outgoing: UnboundedSender<RawMessage>,
pub(crate) documents: Documents,
}
impl Context {
pub(crate) fn for_request(
id: RequestId,
span: Span,
outgoing: UnboundedSender<RawMessage>,
documents: Documents,
) -> Self {
Self {
request_id: Some(id),
span,
outgoing,
documents,
}
}
pub(crate) fn for_notification(
span: Span,
outgoing: UnboundedSender<RawMessage>,
documents: Documents,
) -> Self {
Self {
request_id: None,
span,
outgoing,
documents,
}
}
pub fn request_id(&self) -> Option<&RequestId> {
self.request_id.as_ref()
}
pub fn span(&self) -> &Span {
&self.span
}
pub fn documents(&self) -> &Documents {
&self.documents
}
#[doc(hidden)]
pub fn for_test_notification(documents: Documents) -> Self {
let (outgoing, _rx) = tokio::sync::mpsc::unbounded_channel();
Self {
request_id: None,
span: Span::current(),
outgoing,
documents,
}
}
pub fn publish_diagnostics(&self, params: PublishDiagnosticsParams) {
let body = match serde_json::to_vec(¶ms) {
Ok(b) => b,
Err(e) => {
warn!(error = %e, "publish_diagnostics: serialize failed");
return;
}
};
let msg = RawMessage::Notification {
method: Cow::Borrowed("textDocument/publishDiagnostics"),
params: Bytes::from(body),
};
if self.outgoing.send(msg).is_err() {
warn!("publish_diagnostics: outgoing channel closed");
}
}
}