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
// SPDX-License-Identifier: BUSL-1.1
//! MessagePack + JSON ingest formats for timeseries.
use sonic_rs::{JsonContainerTrait, JsonValueTrait};
use super::msgpack_decode::{self, MsgpackValue};
use crate::bridge::envelope::{ErrorCode, Response};
use crate::data::executor::core_loop::CoreLoop;
use crate::data::executor::task::ExecutionTask;
impl CoreLoop {
/// Payload is a msgpack array of maps (same schema as JSON ingest but in msgpack).
/// Converts each row to an ILP line and delegates to the ILP ingest path.
pub(super) fn execute_msgpack_ingest(
&mut self,
task: &ExecutionTask,
tid: crate::types::TenantId,
collection: &str,
payload: &[u8],
wal_lsn: Option<u64>,
now_ms: i64,
) -> Response {
let measurement = collection
.split_once(':')
.map(|(_, name)| name)
.unwrap_or(collection);
// The measurement name carries an optional `<db_id>/` db-qualifier for
// non-default databases (`db_qualified()` in the planner emits this
// shape). The slash is part of the wire-level routing key, not part of
// the user-facing measurement, so allow it alongside the original
// `[a-zA-Z0-9_-]` set.
if !measurement
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '/')
{
return self.response_error(
task,
ErrorCode::Internal {
detail: format!(
"invalid measurement name '{measurement}': only [a-zA-Z0-9_-/] allowed"
),
},
);
}
let rows = match msgpack_decode::decode_msgpack_rows(payload) {
Ok(r) => r,
Err(e) => {
return self.response_error(
task,
ErrorCode::Internal {
detail: format!("msgpack decode error: {e}"),
},
);
}
};
if rows.is_empty() {
return self.response_error(
task,
ErrorCode::Internal {
detail: "empty msgpack rows array".into(),
},
);
}
let mut ilp_buf = String::new();
for row in &rows {
let mut fields = Vec::new();
let mut timestamp_ns: Option<i64> = None;
for (key, val) in row {
let lower = key.to_lowercase();
if lower == "ts" || lower == "timestamp" || lower == "time" {
match val {
MsgpackValue::Str(s) => {
timestamp_ns = parse_ts_string_to_nanos(s);
}
MsgpackValue::Int(n) => {
timestamp_ns = Some(*n * 1_000_000);
}
MsgpackValue::Float(f) => {
timestamp_ns = Some(*f as i64 * 1_000_000);
}
_ => {}
}
continue;
}
match val {
MsgpackValue::Float(f) => fields.push(format!("{key}={f}")),
MsgpackValue::Int(n) => fields.push(format!("{key}={n}i")),
MsgpackValue::Str(s) => {
// SQL parser routes numeric literals with `.`/`e`/`E` through
// `SqlValue::Decimal`, which the standard msgpack writer encodes
// as a string. Recover the numeric type here so timeseries
// schema inference picks `Float64` / `Int64` instead of `Symbol`.
if let Ok(i) = s.parse::<i64>() {
fields.push(format!("{key}={i}i"));
} else if let Ok(f) = s.parse::<f64>()
&& f.is_finite()
{
fields.push(format!("{key}={f}"));
} else {
fields.push(format!("{key}=\"{}\"", s.replace('\"', "\\\"")));
}
}
MsgpackValue::Bool(b) => fields.push(format!("{key}={b}")),
_ => {}
}
}
if fields.is_empty() {
continue;
}
ilp_buf.push_str(measurement);
ilp_buf.push(' ');
ilp_buf.push_str(&fields.join(","));
if let Some(ts) = timestamp_ns {
ilp_buf.push(' ');
ilp_buf.push_str(&ts.to_string());
}
ilp_buf.push('\n');
}
if ilp_buf.is_empty() {
return self.response_error(
task,
ErrorCode::Internal {
detail: "no valid rows in msgpack payload".into(),
},
);
}
self.execute_ilp_ingest(task, tid, collection, ilp_buf.as_bytes(), wal_lsn, now_ms)
}
/// Payload is a JSON array like: `[{"id":"e1","ts":"2024-01-01T00:00:00Z","value":42.0}]`.
/// Converts each row to an ILP line and delegates to the ILP ingest path.
pub(super) fn execute_json_ingest(
&mut self,
task: &ExecutionTask,
tid: crate::types::TenantId,
collection: &str,
payload: &[u8],
wal_lsn: Option<u64>,
now_ms: i64,
) -> Response {
let rows: sonic_rs::Array = match sonic_rs::from_slice(payload) {
Ok(r) => r,
Err(e) => {
return self.response_error(
task,
ErrorCode::Internal {
detail: format!("JSON parse error: {e}"),
},
);
}
};
if rows.is_empty() {
return self.response_error(
task,
ErrorCode::Internal {
detail: "empty JSON rows array".into(),
},
);
}
let measurement = collection
.split_once(':')
.map(|(_, name)| name)
.unwrap_or(collection);
// The measurement name carries an optional `<db_id>/` db-qualifier for
// non-default databases (`db_qualified()` in the planner emits this
// shape). The slash is part of the wire-level routing key, not part of
// the user-facing measurement, so allow it alongside the original
// `[a-zA-Z0-9_-]` set.
if !measurement
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '/')
{
return self.response_error(
task,
ErrorCode::Internal {
detail: format!(
"invalid measurement name '{measurement}': only [a-zA-Z0-9_-/] allowed"
),
},
);
}
let mut ilp_buf = String::new();
for row_val in rows.iter() {
let obj = match row_val.as_object() {
Some(o) => o,
None => continue,
};
let mut fields = Vec::new();
let mut timestamp_ns: Option<i64> = None;
for (key, val) in obj.iter() {
let lower = key.to_lowercase();
if lower == "ts" || lower == "timestamp" || lower == "time" {
if let Some(s) = val.as_str() {
timestamp_ns = parse_ts_string_to_nanos(s);
} else if let Some(n) = val.as_i64() {
timestamp_ns = Some(n * 1_000_000);
} else if let Some(f) = val.as_f64() {
timestamp_ns = Some(f as i64 * 1_000_000);
}
continue;
}
if let Some(f) = val.as_f64() {
fields.push(format!("{key}={f}"));
} else if let Some(n) = val.as_i64() {
fields.push(format!("{key}={n}i"));
} else if let Some(s) = val.as_str() {
fields.push(format!("{key}=\"{}\"", s.replace('\"', "\\\"")));
} else if let Some(b) = val.as_bool() {
fields.push(format!("{key}={b}"));
}
}
if fields.is_empty() {
continue;
}
ilp_buf.push_str(measurement);
ilp_buf.push(' ');
ilp_buf.push_str(&fields.join(","));
if let Some(ts) = timestamp_ns {
ilp_buf.push(' ');
ilp_buf.push_str(&ts.to_string());
}
ilp_buf.push('\n');
}
if ilp_buf.is_empty() {
return self.response_error(
task,
ErrorCode::Internal {
detail: "no valid rows in JSON payload".into(),
},
);
}
self.execute_ilp_ingest(task, tid, collection, ilp_buf.as_bytes(), wal_lsn, now_ms)
}
}
/// Parse a datetime string to nanoseconds since Unix epoch.
///
/// Accepts RFC3339 / ISO8601 with timezone (e.g., "2024-01-01T00:00:00Z"),
/// and common datetime formats without timezone (treated as UTC).
/// Returns nanoseconds since Unix epoch, or `None` if the string cannot be parsed.
fn parse_ts_string_to_nanos(s: &str) -> Option<i64> {
use chrono::{DateTime, NaiveDateTime, TimeZone, Utc};
if let Ok(dt) = DateTime::parse_from_rfc3339(s) {
return dt.timestamp_nanos_opt();
}
let formats = [
"%Y-%m-%d %H:%M:%S%.f",
"%Y-%m-%d %H:%M:%S",
"%Y-%m-%dT%H:%M:%S%.f",
"%Y-%m-%dT%H:%M:%S",
];
for fmt in &formats {
if let Ok(ndt) = NaiveDateTime::parse_from_str(s, fmt) {
return Utc.from_utc_datetime(&ndt).timestamp_nanos_opt();
}
}
None
}