1use std::collections::{BTreeMap, HashMap};
16use std::time::Duration;
17
18use anyhow::anyhow;
19use base64::Engine;
20use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
21use firestore::{FirestoreDb, FirestoreDbOptions};
22use futures::StreamExt;
23use gcloud_sdk::google::firestore::admin::v1::GetDatabaseRequest;
24use gcloud_sdk::google::firestore::admin::v1::database::DatabaseEdition;
25use gcloud_sdk::google::firestore::admin::v1::firestore_admin_client::FirestoreAdminClient;
26use gcloud_sdk::google::firestore::v1::value::ValueType;
27use gcloud_sdk::google::firestore::v1::{
28 ArrayValue, BatchWriteRequest, Document, MapValue, Value, Write, write,
29};
30use prost::Message as _;
31use risingwave_common::array::{Op, RowRef, StreamChunk};
32use risingwave_common::catalog::Schema;
33use risingwave_common::row::Row as _;
34use risingwave_common::types::{DataType, ScalarRefImpl, ToText};
35use risingwave_common::util::iter_util::ZipEqDebug;
36use serde::Deserialize;
37use serde_json::Value as JsonValue;
38use serde_with::{DisplayFromStr, serde_as};
39use thiserror_ext::AsReport;
40use with_options::WithOptions;
41
42use super::log_store::DeliveryFutureManagerAddFuture;
43use super::writer::{
44 AsyncTruncateLogSinkerOf, AsyncTruncateSinkWriter, AsyncTruncateSinkWriterExt,
45};
46use super::{Result, Sink, SinkError, SinkParam, SinkWriterParam};
47use crate::enforce_secret::EnforceSecret;
48
49pub const FIRESTORE_SINK: &str = "firestore";
50
51const DEFAULT_MAX_BATCH_SIZE: usize = 500; const MAX_DOCUMENT_SIZE: usize = 1_048_576;
53const MAX_BATCH_WRITE_BYTES: usize = 9 * 1024 * 1024;
55const DATABASE_METADATA_TIMEOUT: Duration = Duration::from_secs(10);
56
57#[derive(Deserialize, Debug, Clone, Copy, Default, PartialEq, Eq)]
58#[serde(rename_all = "lowercase")]
59pub enum FirestoreDecimalMode {
60 #[default]
61 Decimal128,
62 Double,
63}
64
65impl crate::with_options::WithOptions for FirestoreDecimalMode {}
66
67#[serde_as]
68#[derive(Deserialize, Debug, Clone, WithOptions)]
69pub struct FirestoreConfig {
70 #[serde(rename = "firestore.project_id")]
72 pub project_id: String,
73
74 #[serde(rename = "firestore.collection")]
76 pub collection: String,
77
78 #[serde(rename = "firestore.database_id")]
80 pub database_id: Option<String>,
81
82 #[serde(rename = "firestore.credentials")]
85 pub credentials: Option<String>,
86
87 #[serde(rename = "firestore.document_id_column")]
91 pub document_id_column: Option<String>,
92
93 #[serde(rename = "firestore.skip_invalid_rows", default)]
96 #[serde_as(as = "DisplayFromStr")]
97 pub skip_invalid_rows: bool,
98
99 #[serde(rename = "firestore.decimal_mode", default)]
102 pub decimal_mode: FirestoreDecimalMode,
103
104 #[serde(
106 rename = "firestore.max_batch_size",
107 default = "default_firestore_max_batch_size"
108 )]
109 #[serde_as(as = "DisplayFromStr")]
110 pub max_batch_size: usize,
111
112 #[serde(
115 rename = "firestore.max_future_send_nums",
116 default = "default_firestore_max_future_send_nums"
117 )]
118 #[serde_as(as = "DisplayFromStr")]
119 pub max_future_send_nums: usize,
120}
121
122fn default_firestore_max_batch_size() -> usize {
123 500
124}
125
126fn default_firestore_max_future_send_nums() -> usize {
127 256
128}
129
130impl EnforceSecret for FirestoreConfig {
131 const ENFORCE_SECRET_PROPERTIES: phf::Set<&'static str> = phf::phf_set! {
132 "firestore.credentials",
133 };
134}
135
136impl FirestoreConfig {
137 pub async fn build_client(&self) -> Result<FirestoreDb> {
138 self.build_client_with_emulator(std::env::var("FIRESTORE_EMULATOR_HOST").ok())
139 .await
140 }
141
142 async fn build_client_with_emulator(
143 &self,
144 emulator_host: Option<String>,
145 ) -> Result<FirestoreDb> {
146 let mut options = if let Some(ref database_id) = self.database_id {
147 FirestoreDbOptions::new(self.project_id.clone()).with_database_id(database_id.clone())
148 } else {
149 FirestoreDbOptions::new(self.project_id.clone())
150 };
151
152 if let Some(ref host) = emulator_host {
153 options.firebase_api_url = Some(format!("http://{host}"));
154 }
155 let (scopes, token_source) = self.token_source(emulator_host.is_some());
156 FirestoreDb::with_options_token_source(options, scopes, token_source)
157 .await
158 .map_err(|e| {
159 SinkError::Firestore(anyhow!(e).context("failed to create Firestore client"))
160 })
161 }
162
163 fn token_source(&self, emulator: bool) -> (Vec<String>, gcloud_sdk::TokenSourceType) {
164 use gcloud_sdk::{ExternalJwtFunctionSource, GCP_DEFAULT_SCOPES, Token, TokenSourceType};
165 if emulator {
166 let source = ExternalJwtFunctionSource::new(|| async {
169 Ok(Token::new(
170 "Bearer".to_owned(),
171 "owner".to_owned().into(),
172 (std::time::SystemTime::now() + Duration::from_secs(3600))
173 .try_into()
174 .expect("an hour from now is a valid timestamp"),
175 ))
176 });
177 (vec![], TokenSourceType::ExternalSource(Box::new(source)))
178 } else if let Some(ref cred) = self.credentials {
179 (
180 GCP_DEFAULT_SCOPES.clone(),
181 TokenSourceType::Json(cred.clone()),
182 )
183 } else {
184 (GCP_DEFAULT_SCOPES.clone(), TokenSourceType::Default)
185 }
186 }
187
188 async fn validate_decimal_mode(&self, schema: &Schema, client: &FirestoreDb) -> Result<()> {
189 if self.decimal_mode == FirestoreDecimalMode::Double
190 || !schema
191 .fields()
192 .iter()
193 .any(|field| contains_decimal(&field.data_type))
194 {
195 return Ok(());
196 }
197 let edition =
198 tokio::time::timeout(DATABASE_METADATA_TIMEOUT, self.database_edition(client))
199 .await
200 .map_err(|_| {
201 SinkError::Firestore(anyhow!("Firestore database metadata request timed out"))
202 })??;
203 match edition.and_then(|edition| DatabaseEdition::try_from(edition).ok()) {
204 Some(DatabaseEdition::Standard) => Err(SinkError::Config(anyhow!(
205 "firestore.decimal_mode='decimal128' requires Firestore Enterprise edition; \
206 this database is Standard. Set firestore.decimal_mode='double' to opt into \
207 floating-point conversion (which may lose precision), or cast DECIMAL to VARCHAR"
208 ))),
209 Some(DatabaseEdition::Enterprise) => Ok(()),
210 _ => {
211 tracing::warn!(database = %client.get_database_path(), "Firestore database edition is unknown; keeping firestore.decimal_mode='decimal128', without falling back to double");
212 Ok(())
213 }
214 }
215 }
216
217 async fn database_edition(&self, client: &FirestoreDb) -> Result<Option<i32>> {
218 let options = client.get_options();
219 let (scopes, token_source) = self.token_source(options.firebase_api_url.is_some());
220 let admin = gcloud_sdk::GoogleApi::from_function_with_token_source(
221 FirestoreAdminClient::new,
222 options
223 .firebase_api_url
224 .as_deref()
225 .unwrap_or("https://firestore.googleapis.com"),
226 Some(client.get_database_path().to_owned()),
227 scopes,
228 token_source,
229 )
230 .await
231 .map_err(|error| {
232 SinkError::Firestore(
233 anyhow!(error).context("failed to create Firestore metadata client"),
234 )
235 })?;
236 let mut request = tonic::Request::new(GetDatabaseRequest {
237 name: client.get_database_path().to_owned(),
238 });
239 request.set_timeout(DATABASE_METADATA_TIMEOUT);
240 match admin.get().get_database(request).await {
241 Ok(response) => Ok(Some(response.into_inner().database_edition)),
242 Err(error)
243 if matches!(
244 error.code(),
245 tonic::Code::PermissionDenied | tonic::Code::Unimplemented
246 ) =>
247 {
248 tracing::warn!(database = %client.get_database_path(), code = ?error.code(), "Cannot read Firestore database edition; metadata requires datastore.databases.getMetadata and may be unsupported by the emulator");
249 Ok(None)
250 }
251 Err(error) => Err(SinkError::Firestore(
252 anyhow!(error).context("failed to read Firestore database edition"),
253 )),
254 }
255 }
256
257 fn validate_schema(&self, schema: &Schema, pk_indices: &[usize]) -> Result<Option<usize>> {
258 parse_collection_path(&self.collection, schema)?;
259 for (name, value) in [
260 ("project_id", Some(&self.project_id)),
261 ("database_id", self.database_id.as_ref()),
262 ] {
263 if value.is_some_and(|value| value.is_empty() || value.contains('/')) {
264 return Err(SinkError::Config(anyhow!(
265 "firestore.{} must be a nonempty resource ID without '/'",
266 name
267 )));
268 }
269 }
270 if !(1..=DEFAULT_MAX_BATCH_SIZE).contains(&self.max_batch_size) {
271 return Err(SinkError::Config(anyhow!(
272 "firestore.max_batch_size must be between 1 and {}",
273 DEFAULT_MAX_BATCH_SIZE
274 )));
275 }
276 if self.max_future_send_nums == 0 {
277 return Err(SinkError::Config(anyhow!(
278 "firestore.max_future_send_nums must be greater than 0"
279 )));
280 }
281 for field in schema.fields() {
282 validate_column_type(&field.data_type, &field.name)?;
283 }
284 if let Some(name) = &self.document_id_column {
285 return schema
286 .fields()
287 .iter()
288 .position(|f| &f.name == name)
289 .map(Some)
290 .ok_or_else(|| {
291 SinkError::Config(anyhow!("document_id_column '{}' not found in schema", name))
292 });
293 }
294 if pk_indices.is_empty() {
295 return Err(SinkError::Config(anyhow!(
296 "Either document_id_column or primary key must be specified"
297 )));
298 }
299 Ok(None)
300 }
301
302 fn from_btreemap(values: BTreeMap<String, String>) -> Result<Self> {
303 serde_json::from_value::<FirestoreConfig>(serde_json::to_value(values).unwrap())
304 .map_err(|e| SinkError::Config(anyhow!(e)))
305 }
306}
307
308#[derive(Clone, Debug)]
309pub struct FirestoreSink {
310 pub config: FirestoreConfig,
311 schema: Schema,
312 pk_indices: Vec<usize>,
313}
314
315impl EnforceSecret for FirestoreSink {
316 fn enforce_secret<'a>(
317 prop_iter: impl Iterator<Item = &'a str>,
318 ) -> crate::error::ConnectorResult<()> {
319 for prop in prop_iter {
320 FirestoreConfig::enforce_one(prop)?;
321 }
322 Ok(())
323 }
324}
325
326impl Sink for FirestoreSink {
327 type LogSinker = AsyncTruncateLogSinkerOf<FirestoreSinkWriter>;
328
329 const SINK_NAME: &'static str = FIRESTORE_SINK;
330
331 async fn validate(&self) -> Result<()> {
332 risingwave_common::license::Feature::FirestoreSink
333 .check_available()
334 .map_err(|e| anyhow!(e))?;
335 self.config
336 .validate_schema(&self.schema, &self.pk_indices)?;
337 let client = self.config.build_client().await?;
338 self.config
339 .validate_decimal_mode(&self.schema, &client)
340 .await?;
341
342 Ok(())
343 }
344
345 async fn new_log_sinker(&self, _writer_param: SinkWriterParam) -> Result<Self::LogSinker> {
346 Ok(FirestoreSinkWriter::new(
347 self.config.clone(),
348 self.schema.clone(),
349 self.pk_indices.clone(),
350 )
351 .await?
352 .into_log_sinker(1))
354 }
355}
356
357impl TryFrom<SinkParam> for FirestoreSink {
358 type Error = SinkError;
359
360 fn try_from(param: SinkParam) -> std::result::Result<Self, Self::Error> {
361 let schema = param.schema();
362 let pk_indices = param.downstream_pk_or_empty();
363 let config = FirestoreConfig::from_btreemap(param.properties)?;
364
365 Ok(Self {
366 config,
367 schema,
368 pk_indices,
369 })
370 }
371}
372
373pub struct FirestoreSinkWriter {
374 client: FirestoreDb,
375 config: FirestoreConfig,
376 schema: Schema,
377 pk_indices: Vec<usize>,
378 doc_id_col_idx: Option<usize>,
379 collection_path: Vec<CollectionPathSegment>,
380}
381
382impl FirestoreSinkWriter {
383 pub async fn new(
384 config: FirestoreConfig,
385 schema: Schema,
386 pk_indices: Vec<usize>,
387 ) -> Result<Self> {
388 let doc_id_col_idx = config.validate_schema(&schema, &pk_indices)?;
389 let collection_path = parse_collection_path(&config.collection, &schema)?;
390 let client = config.build_client().await?;
391 config.validate_decimal_mode(&schema, &client).await?;
392
393 Ok(Self {
394 client,
395 config,
396 schema,
397 pk_indices,
398 doc_id_col_idx,
399 collection_path,
400 })
401 }
402
403 fn get_document_id(&self, row: RowRef<'_>) -> Result<String> {
404 if let Some(idx) = self.doc_id_col_idx {
405 let datum = row.datum_at(idx);
407 match datum {
408 Some(scalar) => {
409 let doc_id = scalar.to_text();
410 validate_firestore_document_id(&doc_id)?;
411 Ok(doc_id)
412 }
413 None => Err(SinkError::Firestore(anyhow!(
414 "document_id_column value is null"
415 ))),
416 }
417 } else {
418 let pk_values: Vec<JsonValue> = self
421 .pk_indices
422 .iter()
423 .map(|&idx| {
424 let field = &self.schema.fields()[idx];
425 row.datum_at(idx)
426 .map(|s| JsonValue::String(s.to_text_with_type(&field.data_type)))
427 .unwrap_or(JsonValue::Null)
428 })
429 .collect();
430 encode_pk_document_id(pk_values)
431 }
432 }
433
434 fn format_row(&self, row: RowRef<'_>) -> Result<HashMap<String, Value>> {
435 let mut map = HashMap::new();
436 for (datum, field) in row.iter().zip_eq_debug(self.schema.fields()) {
437 let value = format_datum(datum, &field.data_type, self.config.decimal_mode)?;
438 map.insert(field.name.clone(), value);
439 }
440 Ok(map)
441 }
442
443 fn get_document_path(&self, row: RowRef<'_>) -> Result<String> {
444 let mut segments = Vec::with_capacity(self.collection_path.len() + 1);
445 for segment in &self.collection_path {
446 segments.push(match segment {
447 CollectionPathSegment::Literal(value) => value.clone(),
448 CollectionPathSegment::Column(index) => {
449 let value = row
450 .datum_at(*index)
451 .ok_or_else(|| {
452 SinkError::Firestore(anyhow!("Firestore parent document ID is null"))
453 })?
454 .to_text();
455 validate_firestore_document_id(&value)?;
456 value
457 }
458 });
459 }
460 segments.push(self.get_document_id(row)?);
461 let path = segments.join("/");
462 if self.client.get_documents_path().len() + 1 + path.len() > 6 * 1024 {
463 return Err(SinkError::Firestore(anyhow!(
464 "Firestore document name exceeds 6 KiB"
465 )));
466 }
467 Ok(path)
468 }
469
470 fn write_chunk_inner(&self, chunk: StreamChunk) -> Result<Vec<FirestoreOperation>> {
471 let mut operations = BTreeMap::new();
472
473 for (op, row) in chunk.rows() {
474 let operation: Result<FirestoreOperation> = (|| {
475 let path = self.get_document_path(row)?;
476 Ok(match op {
477 Op::Insert | Op::UpdateInsert => {
478 let data = self.format_row(row)?;
479 validate_document_size(&path, &data)?;
480 FirestoreOperation::Upsert { path, data }
481 }
482 Op::Delete | Op::UpdateDelete => FirestoreOperation::Delete { path },
483 })
484 })();
485 match operation {
486 Ok(operation) => {
487 operations.insert(operation.document_path().to_owned(), operation);
488 }
489 Err(error) if self.config.skip_invalid_rows => {
490 tracing::warn!(error = %error.as_report(), "skipping invalid Firestore row");
491 }
492 Err(error) => return Err(error),
493 }
494 }
495
496 Ok(operations.into_values().collect())
497 }
498
499 async fn write_operations(&self, operations: Vec<FirestoreOperation>) -> Result<()> {
500 let writes = operations
501 .into_iter()
502 .map(|op| {
503 let name = format!(
504 "{}/{}",
505 self.client.get_documents_path(),
506 op.document_path()
507 );
508 let operation = match op {
509 FirestoreOperation::Upsert { data, .. } => write::Operation::Update(Document {
510 name,
511 fields: data,
512 ..Default::default()
513 }),
514 FirestoreOperation::Delete { .. } => write::Operation::Delete(name),
515 };
516 Write {
517 operation: Some(operation),
518 ..Default::default()
519 }
520 })
521 .collect::<Vec<_>>();
522 let batches = split_write_batches(writes, self.config.max_batch_size);
523 let requests = batches.into_iter().map(|writes| self.write_batch(writes));
524
525 futures::stream::iter(requests)
528 .buffer_unordered(self.config.max_future_send_nums)
529 .fold(Ok(()), |result, next| async move { result.and(next) })
530 .await
531 }
532
533 async fn write_batch(&self, writes: Vec<Write>) -> Result<()> {
534 let request = BatchWriteRequest {
535 database: self.client.get_database_path().clone(),
536 writes,
537 ..Default::default()
538 };
539 let response = self
540 .client
541 .client()
542 .get()
543 .batch_write(request.clone())
544 .await;
545 match response {
546 Ok(response) => {
547 let paths = request
548 .writes
549 .iter()
550 .map(write_document_path)
551 .collect::<Vec<_>>();
552 check_batch_statuses(
553 &response.into_inner().status,
554 &paths,
555 self.config.skip_invalid_rows,
556 )
557 }
558 Err(error)
559 if self.config.skip_invalid_rows && is_invalid_row_code(error.code() as i32) =>
560 {
561 for write in request.writes {
564 let path = write_document_path(&write);
565 let response = self
566 .client
567 .client()
568 .get()
569 .batch_write(BatchWriteRequest {
570 database: request.database.clone(),
571 writes: vec![write],
572 ..Default::default()
573 })
574 .await;
575 match response {
576 Ok(response) => {
577 check_batch_statuses(&response.into_inner().status, &[path], true)?
578 }
579 Err(error) if is_invalid_row_code(error.code() as i32) => {
580 tracing::warn!(document = %path, error = %error.as_report(), "skipping rejected Firestore row");
581 }
582 Err(error) => return Err(SinkError::Firestore(anyhow!(error))),
583 }
584 }
585 Ok(())
586 }
587 Err(error) => Err(SinkError::Firestore(
588 anyhow!(error).context("failed to execute Firestore batch write"),
589 )),
590 }
591 }
592}
593
594#[derive(Clone)]
595enum CollectionPathSegment {
596 Literal(String),
597 Column(usize),
598}
599
600fn parse_collection_path(path: &str, schema: &Schema) -> Result<Vec<CollectionPathSegment>> {
601 let segments = path.split('/').collect::<Vec<_>>();
602 if segments.len() % 2 != 1 || segments.len() > 201 {
603 return Err(SinkError::Config(anyhow!(
604 "firestore.collection must be a collection path with at most 100 subcollections"
605 )));
606 }
607 segments
608 .into_iter()
609 .enumerate()
610 .map(|(position, segment)| {
611 if let Some(column) = segment.strip_prefix('{').and_then(|s| s.strip_suffix('}')) {
612 if position % 2 == 0 {
613 return Err(SinkError::Config(anyhow!(
614 "collection placeholders must be parent document segments"
615 )));
616 }
617 let index = schema
618 .fields()
619 .iter()
620 .position(|f| f.name == column)
621 .ok_or_else(|| {
622 SinkError::Config(anyhow!(
623 "collection path column '{}' not found in schema",
624 column
625 ))
626 })?;
627 Ok(CollectionPathSegment::Column(index))
628 } else {
629 if segment.contains(['{', '}']) {
630 return Err(SinkError::Config(anyhow!(
631 "collection placeholders must occupy a complete path segment"
632 )));
633 }
634 validate_firestore_document_id(segment)
635 .map_err(|error| SinkError::Config(anyhow!(error)))?;
636 Ok(CollectionPathSegment::Literal(segment.to_owned()))
637 }
638 })
639 .collect()
640}
641
642fn is_invalid_row_code(code: i32) -> bool {
643 matches!(code, 3 | 11) }
645
646fn write_document_path(write: &Write) -> String {
647 match write
648 .operation
649 .as_ref()
650 .expect("Firestore write has an operation")
651 {
652 write::Operation::Update(document) => document.name.clone(),
653 write::Operation::Delete(path) => path.clone(),
654 write::Operation::Transform(_) => unreachable!("sink only emits upserts and deletes"),
655 }
656}
657
658fn split_write_batches(writes: Vec<Write>, max_count: usize) -> Vec<Vec<Write>> {
659 let mut batches = Vec::new();
660 let mut batch = Vec::new();
661 let mut bytes = 0;
662 for write in writes {
663 let size = write.encoded_len() + 5;
664 if !batch.is_empty() && (batch.len() >= max_count || bytes + size > MAX_BATCH_WRITE_BYTES) {
665 batches.push(std::mem::take(&mut batch));
666 bytes = 0;
667 }
668 bytes += size;
669 batch.push(write);
670 }
671 if !batch.is_empty() {
672 batches.push(batch);
673 }
674 batches
675}
676
677fn firestore_fields_size(fields: &HashMap<String, Value>) -> usize {
680 fields
681 .iter()
682 .map(|(name, value)| name.len() + 1 + firestore_value_size(value))
683 .sum()
684}
685
686fn firestore_value_size(value: &Value) -> usize {
687 match value.value_type.as_ref().expect("encoded Firestore value") {
688 ValueType::NullValue(_) | ValueType::BooleanValue(_) => 1,
689 ValueType::IntegerValue(_) | ValueType::DoubleValue(_) | ValueType::TimestampValue(_) => 8,
690 ValueType::StringValue(value) => value.len() + 1,
691 ValueType::BytesValue(value) => value.len(),
692 ValueType::ArrayValue(value) => value.values.iter().map(firestore_value_size).sum(),
693 ValueType::MapValue(value) => firestore_fields_size(&value.fields) + 32,
694 ValueType::GeoPointValue(_) => 16,
695 ValueType::ReferenceValue(value) => value.len() + 16,
696 ValueType::FieldReferenceValue(_)
697 | ValueType::VariableReferenceValue(_)
698 | ValueType::FunctionValue(_)
699 | ValueType::PipelineValue(_) => {
700 unreachable!("query-only Firestore values are never emitted by the row encoder")
701 }
702 }
703}
704
705fn validate_document_size(path: &str, fields: &HashMap<String, Value>) -> Result<()> {
706 let name_size = path.split('/').map(|part| part.len() + 1).sum::<usize>() + 16;
707 if name_size + firestore_fields_size(fields) + 32 > MAX_DOCUMENT_SIZE {
708 return Err(SinkError::Firestore(anyhow!(
709 "Firestore document exceeds 1 MiB"
710 )));
711 }
712 Ok(())
713}
714
715fn check_batch_statuses(
716 statuses: &[gcloud_sdk::google::rpc::Status],
717 document_ids: &[String],
718 skip_invalid_rows: bool,
719) -> Result<()> {
720 if statuses.len() != document_ids.len() {
721 return Err(SinkError::Firestore(anyhow!(
722 "Firestore batch write returned {} statuses for {} writes",
723 statuses.len(),
724 document_ids.len()
725 )));
726 }
727 for (status, document_id) in statuses.iter().zip_eq_debug(document_ids) {
728 if status.code != 0 {
729 if skip_invalid_rows && is_invalid_row_code(status.code) {
730 tracing::warn!(document = %document_id, code = status.code, message = %status.message, "skipping rejected Firestore row");
731 continue;
732 }
733 return Err(SinkError::Firestore(anyhow!(
734 "Firestore batch write failed for document '{}': code={}, message={}",
735 document_id,
736 status.code,
737 status.message
738 )));
739 }
740 }
741 Ok(())
742}
743
744#[derive(Clone)]
745enum FirestoreOperation {
746 Upsert {
747 path: String,
748 data: HashMap<String, Value>,
749 },
750 Delete {
751 path: String,
752 },
753}
754
755impl FirestoreOperation {
756 fn document_path(&self) -> &str {
757 match self {
758 Self::Upsert { path, .. } | Self::Delete { path } => path,
759 }
760 }
761}
762
763fn format_datum(
766 datum: Option<ScalarRefImpl<'_>>,
767 data_type: &DataType,
768 decimal_mode: FirestoreDecimalMode,
769) -> Result<Value> {
770 format_datum_at_depth(datum, data_type, decimal_mode, 0)
771}
772
773fn validate_column_type(data_type: &DataType, column_path: &str) -> Result<()> {
775 match data_type {
776 DataType::Map(_) | DataType::Vector(_) | DataType::Variant => {
777 Err(SinkError::Config(anyhow!(
778 "Firestore sink column '{}' has unsupported type {}",
779 column_path,
780 data_type
781 )))
782 }
783 DataType::List(inner) if matches!(inner.elem(), DataType::List(_)) => {
784 Err(SinkError::Config(anyhow!(
785 "Firestore sink column '{}' has unsupported type {}: arrays cannot directly contain arrays",
786 column_path,
787 data_type
788 )))
789 }
790 DataType::List(inner) => validate_column_type(inner.elem(), &format!("{column_path}[]")),
791 DataType::Struct(st) => st.iter().try_for_each(|(name, data_type)| {
792 validate_column_type(data_type, &format!("{column_path}.{name}"))
793 }),
794 _ => Ok(()),
795 }
796}
797
798fn contains_decimal(data_type: &DataType) -> bool {
799 match data_type {
800 DataType::Decimal => true,
801 DataType::List(list) => contains_decimal(list.elem()),
802 DataType::Struct(struct_type) => struct_type.types().any(contains_decimal),
803 _ => false,
804 }
805}
806
807fn check_container_depth(depth: usize) -> Result<()> {
808 if depth >= 20 {
809 return Err(SinkError::Firestore(anyhow!(
810 "Firestore maps and arrays must not exceed 20 levels"
811 )));
812 }
813 Ok(())
814}
815
816fn array_value(values: Vec<Value>) -> Result<ValueType> {
817 if values
818 .iter()
819 .any(|v| matches!(v.value_type, Some(ValueType::ArrayValue(_))))
820 {
821 return Err(SinkError::Firestore(anyhow!(
822 "Firestore arrays cannot directly contain arrays"
823 )));
824 }
825 Ok(ValueType::ArrayValue(ArrayValue { values }))
826}
827
828fn format_datum_at_depth(
829 datum: Option<ScalarRefImpl<'_>>,
830 data_type: &DataType,
831 decimal_mode: FirestoreDecimalMode,
832 depth: usize,
833) -> Result<Value> {
834 let Some(scalar) = datum else {
835 return Ok(Value {
836 value_type: Some(ValueType::NullValue(0)),
837 });
838 };
839 let value_type = match data_type {
840 DataType::Boolean => ValueType::BooleanValue(scalar.into_bool()),
841 DataType::Int16 => ValueType::IntegerValue(scalar.into_int16().into()),
842 DataType::Int32 => ValueType::IntegerValue(scalar.into_int32().into()),
843 DataType::Int64 => ValueType::IntegerValue(scalar.into_int64()),
844 DataType::Float32 => ValueType::DoubleValue(scalar.into_float32().0.into()),
845 DataType::Float64 => ValueType::DoubleValue(scalar.into_float64().0),
846 DataType::Decimal => match decimal_mode {
847 FirestoreDecimalMode::Decimal128 => ValueType::MapValue(MapValue {
852 fields: HashMap::from([(
853 "__decimal128__".to_owned(),
854 Value {
855 value_type: Some(ValueType::StringValue(scalar.into_decimal().to_string())),
856 },
857 )]),
858 }),
859 FirestoreDecimalMode::Double => ValueType::DoubleValue(
860 f64::try_from(scalar.into_decimal())
861 .map_err(|error| SinkError::Firestore(anyhow!(error)))?,
862 ),
863 },
864 DataType::Timestamp => {
865 let time = scalar.into_timestamp().0.and_utc();
868 firestore_timestamp(time.timestamp(), time.timestamp_subsec_nanos())?
869 }
870 DataType::Timestamptz => {
871 let time = scalar.into_timestamptz();
872 firestore_timestamp(time.timestamp(), time.timestamp_subsec_nanos())?
873 }
874 DataType::Int256
875 | DataType::Serial
876 | DataType::Interval
877 | DataType::Date
878 | DataType::Time => ValueType::StringValue(scalar.to_text_with_type(data_type)),
879 DataType::Varchar => ValueType::StringValue(scalar.into_utf8().to_owned()),
880 DataType::Bytea => ValueType::StringValue(STANDARD.encode(scalar.into_bytea())),
881 DataType::Jsonb => return format_jsonb(scalar.into_jsonb().into(), depth),
882 DataType::List(inner) => {
883 check_container_depth(depth)?;
884 let values = scalar
885 .into_list()
886 .iter()
887 .map(|item| format_datum_at_depth(item, inner.elem(), decimal_mode, depth + 1))
888 .collect::<Result<Vec<_>>>()?;
889 array_value(values)?
890 }
891 DataType::Struct(st) => {
892 check_container_depth(depth)?;
893 let mut fields = HashMap::new();
894 for (datum, (name, dt)) in scalar
895 .into_struct()
896 .iter_fields_ref()
897 .zip_eq_debug(st.iter())
898 {
899 fields.insert(
900 name.to_owned(),
901 format_datum_at_depth(datum, dt, decimal_mode, depth + 1)?,
902 );
903 }
904 ValueType::MapValue(MapValue { fields })
905 }
906 DataType::Map(_) | DataType::Vector(_) | DataType::Variant => {
907 return Err(SinkError::Firestore(anyhow!(
908 "{} is not supported by Firestore sink",
909 data_type
910 )));
911 }
912 };
913 Ok(Value {
914 value_type: Some(value_type),
915 })
916}
917
918fn firestore_timestamp(seconds: i64, nanos: u32) -> Result<ValueType> {
919 if !(-62_135_596_800..=253_402_300_799).contains(&seconds) || nanos >= 1_000_000_000 {
920 return Err(SinkError::Firestore(anyhow!(
921 "Firestore timestamp must be between years 0001 and 9999"
922 )));
923 }
924 Ok(ValueType::TimestampValue(prost_types::Timestamp {
925 seconds,
926 nanos: (nanos / 1000 * 1000) as i32,
927 }))
928}
929
930fn format_jsonb(value: jsonbb::ValueRef<'_>, depth: usize) -> Result<Value> {
931 let value_type =
932 match value {
933 jsonbb::ValueRef::Null => ValueType::NullValue(0),
934 jsonbb::ValueRef::Bool(v) => ValueType::BooleanValue(v),
935 jsonbb::ValueRef::String(v) => ValueType::StringValue(v.as_str().to_owned()),
936 jsonbb::ValueRef::Number(v) => {
937 if let Some(v) = v.as_i64() {
938 ValueType::IntegerValue(v)
939 } else if v.as_u64().is_some() {
940 return Err(SinkError::Firestore(anyhow!(
941 "JSONB integer exceeds Firestore signed 64-bit range"
942 )));
943 } else {
944 ValueType::DoubleValue(v.as_f64().ok_or_else(|| {
945 SinkError::Firestore(anyhow!("JSONB number out of range"))
946 })?)
947 }
948 }
949 jsonbb::ValueRef::Array(v) => {
950 check_container_depth(depth)?;
951 array_value(
952 v.iter()
953 .map(|v| format_jsonb(v, depth + 1))
954 .collect::<Result<_>>()?,
955 )?
956 }
957 jsonbb::ValueRef::Object(v) => {
958 check_container_depth(depth)?;
959 let fields = v
960 .iter()
961 .map(|(k, v)| Ok((k.to_owned(), format_jsonb(v, depth + 1)?)))
962 .collect::<Result<_>>()?;
963 ValueType::MapValue(MapValue { fields })
964 }
965 };
966 Ok(Value {
967 value_type: Some(value_type),
968 })
969}
970
971fn encode_pk_document_id(pk_values: Vec<JsonValue>) -> Result<String> {
972 let doc_id =
973 URL_SAFE_NO_PAD.encode(serde_json::to_vec(&pk_values).map_err(|e| {
974 SinkError::Firestore(anyhow!(e).context("failed to encode primary key"))
975 })?);
976 validate_firestore_document_id(&doc_id)?;
977 Ok(doc_id)
978}
979
980fn validate_firestore_document_id(doc_id: &str) -> Result<()> {
981 if doc_id.len() > 1500 || (doc_id.starts_with("__") && doc_id.ends_with("__")) {
982 return Err(SinkError::Firestore(anyhow!(
983 "Firestore document ID exceeds 1500 bytes or uses a reserved name"
984 )));
985 }
986 if doc_id.is_empty() {
987 return Err(SinkError::Firestore(anyhow!(
988 "Firestore document ID must not be empty"
989 )));
990 }
991 if doc_id.contains('/') {
992 return Err(SinkError::Firestore(anyhow!(
993 "Firestore document ID must not contain '/'"
994 )));
995 }
996 if doc_id == "." || doc_id == ".." {
997 return Err(SinkError::Firestore(anyhow!(
998 "Firestore document ID must not be '.' or '..'"
999 )));
1000 }
1001 Ok(())
1002}
1003
1004impl AsyncTruncateSinkWriter for FirestoreSinkWriter {
1005 async fn write_chunk<'a>(
1006 &'a mut self,
1007 chunk: StreamChunk,
1008 _add_future: DeliveryFutureManagerAddFuture<'a, Self::DeliveryFuture>,
1009 ) -> Result<()> {
1010 let operations = self.write_chunk_inner(chunk)?;
1011 self.write_operations(operations).await?;
1012 Ok(())
1013 }
1014}
1015
1016#[cfg(test)]
1017mod tests;