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
use std::sync::Arc;
use futures::StreamExt;
use tokio::sync::mpsc;
use tokio_stream::wrappers::ReceiverStream;
use tonic::{Request, Response, Status, Streaming};
use tracing::{error, info, warn};
use lago_core::{Journal, Session, SessionConfig, SessionId, event::EventEnvelope as CoreEvent};
use crate::codec;
use crate::proto::{self, ingest_service_server::IngestService};
/// Maximum number of pending WAL entries before backpressure.
const _MAX_PENDING: u64 = 10_000;
pub struct IngestServer<J: Journal> {
journal: Arc<J>,
}
impl<J: Journal> IngestServer<J> {
pub fn new(journal: Arc<J>) -> Self {
Self { journal }
}
}
#[tonic::async_trait]
impl<J: Journal + 'static> IngestService for IngestServer<J> {
type IngestStream = ReceiverStream<Result<proto::IngestResponse, Status>>;
async fn ingest(
&self,
request: Request<Streaming<proto::IngestRequest>>,
) -> Result<Response<Self::IngestStream>, Status> {
let journal = Arc::clone(&self.journal);
let mut in_stream = request.into_inner();
let (tx, rx) = mpsc::channel(256);
tokio::spawn(async move {
while let Some(result) = in_stream.next().await {
match result {
Ok(req) => {
let Some(message) = req.message else {
continue;
};
match message {
proto::ingest_request::Message::Event(proto_event) => {
let event_id = proto_event.event_id.clone();
match codec::event_from_proto(proto_event) {
Ok(event) => match journal.append(event).await {
Ok(seq) => {
let ack = codec::make_ack(&event_id, seq, true, None);
let resp = proto::IngestResponse {
message: Some(
proto::ingest_response::Message::Ack(ack),
),
};
if tx.send(Ok(resp)).await.is_err() {
break;
}
}
Err(e) => {
error!("journal append error: {e}");
let ack = codec::make_ack(
&event_id,
0,
false,
Some(e.to_string()),
);
let resp = proto::IngestResponse {
message: Some(
proto::ingest_response::Message::Ack(ack),
),
};
let _ = tx.send(Ok(resp)).await;
}
},
Err(e) => {
warn!("proto decode error: {e}");
let ack = codec::make_ack(
&event_id,
0,
false,
Some(format!("decode error: {e}")),
);
let resp = proto::IngestResponse {
message: Some(proto::ingest_response::Message::Ack(
ack,
)),
};
let _ = tx.send(Ok(resp)).await;
}
}
}
proto::ingest_request::Message::Heartbeat(_) => {
let hb = codec::make_heartbeat();
let resp = proto::IngestResponse {
message: Some(proto::ingest_response::Message::Heartbeat(hb)),
};
let _ = tx.send(Ok(resp)).await;
}
}
}
Err(e) => {
error!("stream error: {e}");
break;
}
}
}
info!("ingest stream closed");
});
Ok(Response::new(ReceiverStream::new(rx)))
}
async fn create_session(
&self,
request: Request<proto::CreateSessionRequest>,
) -> Result<Response<proto::CreateSessionResponse>, Status> {
let req = request.into_inner();
let session_id = SessionId::from_string(&req.session_id);
let config = req.config.unwrap_or_default();
let session = Session {
session_id: session_id.clone(),
config: SessionConfig {
name: config.name.clone(),
model: config.model.clone(),
params: config.params,
},
created_at: CoreEvent::now_micros(),
branches: vec![],
};
self.journal
.put_session(session)
.await
.map_err(|e| Status::internal(e.to_string()))?;
Ok(Response::new(proto::CreateSessionResponse {
session_id: req.session_id,
created: true,
}))
}
async fn get_session(
&self,
request: Request<proto::GetSessionRequest>,
) -> Result<Response<proto::GetSessionResponse>, Status> {
let req = request.into_inner();
let session_id = SessionId::from_string(&req.session_id);
let session = self
.journal
.get_session(&session_id)
.await
.map_err(|e| Status::internal(e.to_string()))?
.ok_or_else(|| Status::not_found("session not found"))?;
Ok(Response::new(proto::GetSessionResponse {
session_id: req.session_id,
config: Some(proto::SessionConfig {
name: session.config.name,
model: session.config.model,
params: session.config.params,
}),
event_count: 0,
}))
}
}