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
use std::{any::Any, cell::RefCell, collections::VecDeque, rc::Rc, time::Duration};
use ::regex::Regex;
use chrono::NaiveDateTime;
use differential_dataflow::capture::YieldingIter;
use differential_dataflow::Hashable;
use differential_dataflow::{AsCollection, Collection};
use expr::PartitionId;
use futures::executor::block_on;
use mz_avro::{AvroDeserializer, GeneralDeserializer};
use repr::MessagePayload;
use timely::dataflow::channels::pact::{Exchange, Pipeline};
use timely::dataflow::operators::Operator;
use timely::dataflow::{Scope, Stream};
use timely::scheduling::SyncActivator;
use dataflow_types::{
sources::{
encoding::{AvroEncoding, AvroOcfEncoding, DataEncoding, RegexEncoding},
DebeziumMode, IncludedColumnSource, SourceEnvelope,
},
DecodeError, LinearOperator,
};
use interchange::avro::ConfluentAvroResolver;
use repr::Datum;
use repr::{Diff, Row, Timestamp};
use tracing::error;
use self::avro::AvroDecoderState;
use self::csv::CsvDecoderState;
use self::protobuf::ProtobufDecoderState;
use crate::metrics::Metrics;
use crate::source::{DecodeResult, SourceOutput};
mod avro;
mod csv;
mod protobuf;
pub fn decode_cdcv2<G: Scope<Timestamp = Timestamp>>(
stream: &Stream<G, SourceOutput<Option<Vec<u8>>, Option<Vec<u8>>>>,
schema: &str,
registry: Option<ccsr::ClientConfig>,
confluent_wire_format: bool,
) -> (Collection<G, Row, Diff>, Box<dyn Any>) {
let mut resolver = ConfluentAvroResolver::new(schema, registry, confluent_wire_format).unwrap();
let channel = Rc::new(RefCell::new(VecDeque::new()));
let activator: Rc<RefCell<Option<SyncActivator>>> = Rc::new(RefCell::new(None));
let mut vector = Vec::new();
stream.sink(
SourceOutput::<Option<Vec<u8>>, Option<Vec<u8>>>::position_value_contract(),
"CDCv2-Decode",
{
let channel = Rc::clone(&channel);
let activator = Rc::clone(&activator);
move |input| {
input.for_each(|_time, data| {
data.swap(&mut vector);
for data in vector.drain(..) {
let value = match &data.value {
Some(value) => value,
None => continue,
};
let (mut data, schema) = match block_on(resolver.resolve(&*value)) {
Ok(ok) => ok,
Err(e) => {
error!("Failed to get schema info for CDCv2 record: {}", e);
continue;
}
};
let d = GeneralDeserializer {
schema: schema.top_node(),
};
let dec = interchange::avro::cdc_v2::Decoder;
let message = match d.deserialize(&mut data, dec) {
Ok(ok) => ok,
Err(e) => {
error!("Failed to deserialize avro message: {}", e);
continue;
}
};
channel.borrow_mut().push_back(message);
}
});
if let Some(activator) = activator.borrow_mut().as_mut() {
activator.activate().unwrap()
}
}
},
);
struct VdIterator<T>(Rc<RefCell<VecDeque<T>>>);
impl<T> Iterator for VdIterator<T> {
type Item = T;
fn next(&mut self) -> Option<T> {
self.0.borrow_mut().pop_front()
}
}
let (token, stream) =
differential_dataflow::capture::source::build(stream.scope(), move |ac| {
*activator.borrow_mut() = Some(ac);
YieldingIter::new_from(VdIterator(channel), Duration::from_millis(10))
});
(stream.as_collection(), token)
}
#[derive(Debug)]
pub(crate) enum PreDelimitedFormat {
Bytes,
Text,
Regex(Regex, Row),
Protobuf(ProtobufDecoderState),
}
impl PreDelimitedFormat {
pub fn decode(&mut self, bytes: &[u8]) -> Result<Option<Row>, DecodeError> {
match self {
PreDelimitedFormat::Bytes => Ok(Some(Row::pack(Some(Datum::Bytes(bytes))))),
PreDelimitedFormat::Text => {
let s = std::str::from_utf8(bytes)
.map_err(|_| DecodeError::Text("Failed to decode UTF-8".to_string()))?;
Ok(Some(Row::pack(Some(Datum::String(s)))))
}
PreDelimitedFormat::Regex(regex, row_packer) => {
let s = std::str::from_utf8(bytes)
.map_err(|_| DecodeError::Text("Failed to decode UTF-8".to_string()))?;
let captures = match regex.captures(s) {
Some(captures) => captures,
None => return Ok(None),
};
row_packer.extend(
captures
.iter()
.skip(1)
.map(|c| Datum::from(c.map(|c| c.as_str()))),
);
Ok(Some(row_packer.finish_and_reuse()))
}
PreDelimitedFormat::Protobuf(pb) => pb.get_value(bytes).transpose(),
}
}
}
#[derive(Debug)]
pub(crate) enum DataDecoderInner {
Avro(AvroDecoderState),
DelimitedBytes {
delimiter: u8,
format: PreDelimitedFormat,
},
Csv(CsvDecoderState),
PreDelimited(PreDelimitedFormat),
}
#[derive(Debug)]
struct DataDecoder {
inner: DataDecoderInner,
metrics: Metrics,
}
impl DataDecoder {
pub fn next(&mut self, bytes: &mut &[u8]) -> Result<Option<Row>, DecodeError> {
match &mut self.inner {
DataDecoderInner::DelimitedBytes { delimiter, format } => {
let delimiter = *delimiter;
let chunk_idx = match bytes.iter().position(move |&byte| byte == delimiter) {
None => return Ok(None),
Some(i) => i,
};
let data = &bytes[0..chunk_idx];
*bytes = &bytes[chunk_idx + 1..];
format.decode(data)
}
DataDecoderInner::Avro(avro) => avro.decode(bytes),
DataDecoderInner::Csv(csv) => csv.decode(bytes),
DataDecoderInner::PreDelimited(format) => {
let result = format.decode(*bytes);
*bytes = &[];
result
}
}
}
pub fn eof(&mut self, bytes: &mut &[u8]) -> Result<Option<Row>, DecodeError> {
match &mut self.inner {
DataDecoderInner::Csv(csv) => {
let result = csv.decode(bytes);
csv.reset_for_new_object();
result
}
DataDecoderInner::DelimitedBytes { format, .. } => {
let data = std::mem::take(bytes);
if data.is_empty() {
Ok(None)
} else {
format.decode(data)
}
}
_ => Ok(None),
}
}
pub fn log_errors(&self, n: usize) {
self.metrics.count_errors(&self.inner, n);
}
pub fn log_successes(&self, n: usize) {
self.metrics.count_successes(&self.inner, n);
}
}
fn get_decoder(
encoding: DataEncoding,
debug_name: &str,
operators: &mut Option<LinearOperator>,
is_connector_delimited: bool,
metrics: Metrics,
) -> DataDecoder {
match encoding {
DataEncoding::Avro(AvroEncoding {
schema,
schema_registry_config,
confluent_wire_format,
}) => {
let state = avro::AvroDecoderState::new(
&schema,
schema_registry_config,
debug_name.to_string(),
confluent_wire_format,
)
.expect("Failed to create avro decoder, even though we validated ccsr client creation in purification.");
DataDecoder {
inner: DataDecoderInner::Avro(state),
metrics,
}
}
DataEncoding::Text
| DataEncoding::Bytes
| DataEncoding::Protobuf(_)
| DataEncoding::Regex(_) => {
let after_delimiting = match encoding {
DataEncoding::Regex(RegexEncoding { regex }) => {
PreDelimitedFormat::Regex(regex.0, Default::default())
}
DataEncoding::Protobuf(encoding) => {
PreDelimitedFormat::Protobuf(ProtobufDecoderState::new(encoding).expect(
"Failed to create protobuf decoder, even though we validated ccsr \
client creation in purification.",
))
}
DataEncoding::Bytes => PreDelimitedFormat::Bytes,
DataEncoding::Text => PreDelimitedFormat::Text,
_ => unreachable!(),
};
let inner = if is_connector_delimited {
DataDecoderInner::PreDelimited(after_delimiting)
} else {
DataDecoderInner::DelimitedBytes {
delimiter: b'\n',
format: after_delimiting,
}
};
DataDecoder { inner, metrics }
}
DataEncoding::AvroOcf(AvroOcfEncoding { reader_schema }) => {
let state =
avro::AvroDecoderState::new(&reader_schema, None, debug_name.to_string(), false)
.expect("Schema was verified to be correct during purification");
DataDecoder {
inner: DataDecoderInner::Avro(state),
metrics,
}
}
DataEncoding::Csv(enc) => {
let state = CsvDecoderState::new(enc, operators);
DataDecoder {
inner: DataDecoderInner::Csv(state),
metrics,
}
}
DataEncoding::Postgres => {
unreachable!("Postgres sources should not go through the general decoding path.")
}
}
}
fn try_decode(
decoder: &mut DataDecoder,
value: Option<&Vec<u8>>,
) -> Option<Result<Row, DecodeError>> {
let value_buf = &mut value?.as_slice();
let value = decoder.next(value_buf);
if value.is_ok() && !value_buf.is_empty() {
let err = format!(
"Unexpected bytes remaining for decoded value: {:?}",
value_buf
);
return Some(Err(DecodeError::Text(err)));
}
value
.transpose()
.or_else(|| decoder.eof(&mut &[][..]).transpose())
}
pub fn render_decode_delimited<G>(
stream: &Stream<G, SourceOutput<Option<Vec<u8>>, Option<Vec<u8>>>>,
key_encoding: Option<DataEncoding>,
value_encoding: DataEncoding,
debug_name: &str,
envelope: &SourceEnvelope,
metadata_items: Vec<IncludedColumnSource>,
operators: &mut Option<LinearOperator>,
metrics: Metrics,
) -> (Stream<G, DecodeResult>, Option<Box<dyn Any>>)
where
G: Scope,
{
let op_name = format!(
"{}{}DecodeDelimited",
key_encoding
.as_ref()
.map(|key_encoding| key_encoding.op_name())
.unwrap_or(""),
value_encoding.op_name()
);
let mut key_decoder = key_encoding.map(|key_encoding| {
get_decoder(key_encoding, debug_name, operators, true, metrics.clone())
});
let mut value_decoder = get_decoder(value_encoding, debug_name, operators, true, metrics);
let dist: fn(&SourceOutput<Option<Vec<u8>>, Option<Vec<u8>>>) -> _ = match envelope {
SourceEnvelope::Debezium(dbz) => match dbz.mode {
DebeziumMode::Upsert => |x| x.key.hashed(),
_ => |x| x.partition.hashed(),
},
_ => |x| {
if let Some(position) = x.position {
position.hashed()
} else {
x.value.hashed()
}
},
};
let results = stream.unary_frontier(Exchange::new(dist), &op_name, move |_, _| {
move |input, output| {
let mut n_errors = 0;
let mut n_successes = 0;
input.for_each(|cap, data| {
let mut session = output.session(&cap);
for SourceOutput {
key,
value,
position,
upstream_time_millis,
partition,
} in data.iter()
{
let key = key_decoder
.as_mut()
.and_then(|decoder| try_decode(decoder, key.as_ref()));
let value = try_decode(&mut value_decoder, value.as_ref());
if matches!(&key, Some(Err(_))) || matches!(&value, Some(Err(_))) {
n_errors += 1;
} else if matches!(&value, Some(Ok(_))) {
n_successes += 1;
}
session.give(DecodeResult {
key,
value,
position: *position,
upstream_time_millis: *upstream_time_millis,
partition: partition.clone(),
metadata: to_metadata_row(
&metadata_items,
partition.clone(),
*position,
*upstream_time_millis,
),
});
}
});
if n_errors > 0 {
value_decoder.log_errors(n_errors);
}
if n_successes > 0 {
value_decoder.log_successes(n_successes);
}
}
});
(results, None)
}
pub fn render_decode<G>(
stream: &Stream<G, SourceOutput<(), MessagePayload>>,
value_encoding: DataEncoding,
debug_name: &str,
metadata_items: Vec<IncludedColumnSource>,
operators: &mut Option<LinearOperator>,
metrics: Metrics,
) -> (Stream<G, DecodeResult>, Option<Box<dyn Any>>)
where
G: Scope<Timestamp = Timestamp>,
{
let op_name = format!("{}Decode", value_encoding.op_name());
let mut value_decoder = get_decoder(value_encoding, debug_name, operators, false, metrics);
let mut value_buf = vec![];
let mut n_seen = 1..;
let results = stream.unary_frontier(Pipeline, &op_name, move |_, _| {
let metadata_items = metadata_items;
move |input, output| {
let mut n_errors = 0;
let mut n_successes = 0;
input.for_each(|cap, data| {
let mut session = output.session(&cap);
for SourceOutput {
key: _,
value,
position: _,
upstream_time_millis,
partition,
} in data.iter()
{
let value = match value {
MessagePayload::Data(data) => data,
MessagePayload::EOF => {
let data = &mut &value_buf[..];
let mut result = value_decoder.eof(data);
if result.is_ok() && !data.is_empty() {
result = Err(DecodeError::Text(format!(
"Saw unexpected EOF with bytes remaining in buffer: {:?}",
data
)));
}
value_buf.clear();
match result.transpose() {
None => continue,
Some(value) => {
if value.is_err() {
n_errors += 1;
} else if matches!(&value, Ok(_)) {
n_successes += 1;
}
let position = n_seen.next();
let metadata = to_metadata_row(
&metadata_items,
partition.clone(),
position,
*upstream_time_millis,
);
session.give(DecodeResult {
key: None,
value: Some(value),
position,
upstream_time_millis: *upstream_time_millis,
partition: partition.clone(),
metadata,
});
}
}
continue;
}
};
let value = if value_buf.is_empty() {
value
} else {
value_buf.extend_from_slice(&*value);
&value_buf
};
if value.is_empty() {
let metadata = to_metadata_row(
&metadata_items,
partition.clone(),
None,
*upstream_time_millis,
);
session.give(DecodeResult {
key: None,
value: None,
position: None,
upstream_time_millis: *upstream_time_millis,
partition: partition.clone(),
metadata,
});
} else {
let value_bytes_remaining = &mut value.as_slice();
loop {
let old_value_cursor = *value_bytes_remaining;
let value = match value_decoder.next(value_bytes_remaining) {
Err(e) => Err(e),
Ok(None) => {
let leftover = value_bytes_remaining.to_vec();
value_buf = leftover;
break;
}
Ok(Some(value)) => Ok(value),
};
assert!(old_value_cursor != *value_bytes_remaining || value.is_err());
let is_err = value.is_err();
if is_err {
n_errors += 1;
} else if matches!(&value, Ok(_)) {
n_successes += 1;
}
let position = n_seen.next();
let metadata = to_metadata_row(
&metadata_items,
partition.clone(),
position,
*upstream_time_millis,
);
if value_bytes_remaining.is_empty() {
session.give(DecodeResult {
key: None,
value: Some(value),
position,
upstream_time_millis: *upstream_time_millis,
partition: partition.clone(),
metadata,
});
value_buf = vec![];
break;
} else {
session.give(DecodeResult {
key: None,
value: Some(value),
position,
upstream_time_millis: *upstream_time_millis,
partition: partition.clone(),
metadata,
});
}
if is_err {
break;
}
}
}
}
});
if n_errors > 0 {
value_decoder.log_errors(n_errors);
}
if n_successes > 0 {
value_decoder.log_successes(n_errors);
}
}
});
(results, None)
}
fn to_metadata_row(
metadata_items: &[IncludedColumnSource],
partition: PartitionId,
position: Option<i64>,
upstream_time_millis: Option<i64>,
) -> Row {
let mut row = Row::default();
match partition {
PartitionId::Kafka(partition) => {
for item in metadata_items.iter() {
match item {
IncludedColumnSource::Partition => row.push(Datum::from(partition)),
IncludedColumnSource::Offset | IncludedColumnSource::DefaultPosition => row
.push(Datum::from(
position.expect("kafka sources always have position"),
)),
IncludedColumnSource::Timestamp => {
let ts =
upstream_time_millis.expect("kafka sources always have upstream_time");
let (secs, mut millis) = (ts / 1000, (ts.abs() % 1000) as u32);
if secs < 0 {
millis = 1000 - millis;
}
row.push(Datum::from(NaiveDateTime::from_timestamp(
secs,
millis * 1_000_000,
)))
}
IncludedColumnSource::Topic => unreachable!("Topic is not implemented yet"),
}
}
}
PartitionId::None => {
for item in metadata_items.iter() {
match item {
IncludedColumnSource::DefaultPosition => row.push(Datum::from(
position.expect("kafka sources always have position"),
)),
_ => unreachable!("Only Kafka supports non-defaultposition metadata items"),
}
}
}
}
row
}