faucet-source-pubsub 1.1.1

Google Cloud Pub/Sub source connector for faucet-stream (streaming pull, ack at durable page boundaries, resumable termination)
Documentation
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
//! The Pub/Sub `Source` implementation: streaming pull, per-message record
//! assembly, cumulative informational bookmark, ack **at durable page
//! boundaries**, and idle / max-messages termination.
//!
//! **SDK-touching module.** All `gcloud-pubsub` calls live here (client
//! construction is in `faucet-common-pubsub`), so a real-compile fixup for a
//! differing SDK version is localised to `pull_messages`, `ack_messages`,
//! `renew_deadlines`,
//! `subscribe`, and `check`.

use crate::config::PubsubSourceConfig;
use crate::convert::{MessageParts, record_with_policy, timestamp_millis};
use crate::state::{PubsubBookmark, state_key};
use faucet_core::lease::LeaseExtender;
use faucet_core::{FaucetError, Stream, StreamPage};
use gcloud_pubsub::client::Client;
use gcloud_pubsub::subscriber::ReceivedMessage;
use gcloud_pubsub::subscription::Subscription;
use serde_json::Value;
use std::pin::Pin;
use std::sync::Mutex;
use std::time::{Duration, Instant};

/// Google Cloud Pub/Sub source. See the crate README for semantics.
pub struct PubsubSource {
    config: PubsubSourceConfig,
    client: Client,
    /// Bookmark applied by the pipeline before streaming — informational only
    /// (Pub/Sub redelivers unacked messages; there is no client-side seek).
    start_bookmark: Mutex<Option<PubsubBookmark>>,
}

impl PubsubSource {
    /// Create a new Pub/Sub source. Validates the config and builds the client.
    pub async fn new(config: PubsubSourceConfig) -> Result<Self, FaucetError> {
        config.validate()?;
        let client = faucet_common_pubsub::build_client(&config.connection).await?;
        Ok(Self {
            config,
            client,
            start_bookmark: Mutex::new(None),
        })
    }

    fn subscription(&self) -> Subscription {
        self.client.subscription(&self.config.subscription)
    }
}

/// Pull up to `max` messages. Thin SDK shim.
async fn pull_messages(
    subscription: &Subscription,
    max: usize,
) -> Result<Vec<ReceivedMessage>, FaucetError> {
    subscription
        .pull(max as i32, None)
        .await
        .map_err(|e| FaucetError::Source(format!("pubsub: pull failed: {e}")))
}

/// Return messages to the subscription for immediate redelivery (a pull
/// response the run will not process). Best-effort. Thin SDK shim.
async fn nack_messages(messages: Vec<ReceivedMessage>) {
    use futures::StreamExt;
    futures::stream::iter(messages)
        .map(|m| async move {
            if let Err(e) = m.nack().await {
                tracing::warn!(error = %e, "pubsub: nack failed; the message redelivers after its ack deadline");
            }
        })
        .buffer_unordered(RENEW_CONCURRENCY)
        .collect::<Vec<()>>()
        .await;
}

/// How many messages one pull asks for: never more than the run still needs,
/// so `max_messages` does not strand a pulled tail that is neither acked nor
/// nacked (#789 MSG-46). Pure.
pub(crate) fn pull_size(per_pull: usize, max_messages: Option<usize>, total: usize) -> usize {
    match max_messages {
        Some(max) => per_pull.min(max.saturating_sub(total)).max(1),
        None => per_pull,
    }
}

/// How long an idle-terminated run waits for a pull response already in
/// flight before cancelling it.
const LATE_PULL_GRACE: Duration = Duration::from_secs(2);

/// Ack ids per `Acknowledge` RPC — well under the request-size limit.
const ACK_BATCH: usize = 500;
/// Concurrent `ModifyAckDeadline` calls while renewing held messages.
const RENEW_CONCURRENCY: usize = 16;

/// Ack a batch of messages with one `Acknowledge` RPC per [`ACK_BATCH`] ids
/// (best-effort — a failed ack means redelivery, i.e. at-least-once, never data
/// loss). Thin SDK shim.
async fn ack_messages(subscription: &Subscription, messages: &[ReceivedMessage]) {
    for chunk in messages.chunks(ACK_BATCH) {
        let ids = chunk.iter().map(|m| m.ack_id().to_string()).collect();
        if let Err(e) = subscription.ack(ids).await {
            tracing::warn!(error = %e, "pubsub: ack failed; messages will be redelivered");
        }
    }
}

/// Renew the ack deadline of every held message. Best-effort. Thin SDK shim.
async fn renew_deadlines(messages: Vec<ReceivedMessage>, secs: i32) {
    use futures::StreamExt;
    futures::stream::iter(messages)
        .map(|m| async move {
            if let Err(e) = m.modify_ack_deadline(secs).await {
                tracing::warn!(error = %e, "pubsub: ack deadline renewal failed");
            }
        })
        .buffer_unordered(RENEW_CONCURRENCY)
        .collect::<Vec<()>>()
        .await;
}

/// How often held messages are renewed: every 5 s, or every third of the
/// window when that is shorter. Pure.
pub(crate) fn renew_every(extension_secs: u32) -> Duration {
    Duration::from_secs(u64::from((extension_secs / 3).clamp(1, 5)))
}

impl PubsubSource {
    /// Epoch-millis publish time of a received message, if the server set it.
    fn publish_millis(m: &ReceivedMessage) -> Option<i64> {
        m.message
            .publish_time
            .as_ref()
            .map(|t| timestamp_millis(t.seconds, t.nanos))
    }
}

#[faucet_core::async_trait]
impl faucet_core::Source for PubsubSource {
    async fn fetch_with_context(
        &self,
        context: &std::collections::HashMap<String, Value>,
    ) -> Result<Vec<Value>, FaucetError> {
        use futures::StreamExt;
        let mut pages = self.stream_pages(context, self.config.batch_size);
        let mut all = Vec::new();
        while let Some(page) = pages.next().await {
            all.extend(page?.records);
        }
        Ok(all)
    }

    fn stream_pages<'a>(
        &'a self,
        _context: &'a std::collections::HashMap<String, Value>,
        _batch_size: usize,
    ) -> Pin<Box<dyn Stream<Item = Result<StreamPage, FaucetError>> + Send + 'a>> {
        let chunk = if self.config.batch_size == 0 {
            usize::MAX
        } else {
            self.config.batch_size
        };
        let idle = self.config.idle_termination_secs.map(Duration::from_secs);
        let max_messages = self.config.max_messages;
        let per_pull = self.config.max_messages_per_pull;
        let format = self.config.value_format;
        let attributes_key = self.config.attributes_key.clone();
        let on_decode_error = self.config.on_decode_error;
        let extension = self.config.ack_deadline_extension_secs;

        Box::pin(async_stream::try_stream! {
            let subscription = self.subscription();
            let lease = (extension > 0).then(|| {
                LeaseExtender::spawn(renew_every(extension), move |held: Vec<ReceivedMessage>| {
                    renew_deadlines(held, extension as i32)
                })
            });
            let hold = |page: &[ReceivedMessage], yielded: &[ReceivedMessage]| {
                if let Some(l) = &lease {
                    l.hold(page.iter().chain(yielded).cloned().collect());
                }
            };

            let mut cumulative = self
                .start_bookmark
                .lock()
                .expect("bookmark mutex poisoned")
                .clone()
                .unwrap_or_default();

            // Messages of pages yielded since the last ack. Acked at the top of
            // the next iteration — by then the pipeline has written each page to
            // the sink and persisted its bookmark, so acking is safe (a crash
            // before the ack redelivers, i.e. at-least-once).
            let mut pending: Vec<ReceivedMessage> = Vec::new();
            let mut buffer: Vec<Value> = Vec::new();
            let mut page_msgs: Vec<ReceivedMessage> = Vec::new();
            let mut total = 0usize;
            let mut last_activity = Instant::now();

            'consume: loop {
                if !pending.is_empty() {
                    ack_messages(&subscription, &pending).await;
                    pending.clear();
                    hold(&page_msgs, &pending);
                }

                let want = pull_size(per_pull, max_messages, total);
                // The pull runs as its own task so an idle timeout does not
                // drop a response the server already leased: the late
                // messages are nacked for prompt redelivery instead of
                // waiting out their ack deadline (#789 MSG-82). Every RPC is
                // bounded by the client's deadline (#789 MSG-60).
                let pull_sub = self.subscription();
                let mut pull = tokio::spawn(async move { pull_messages(&pull_sub, want).await });
                let joined = match idle {
                    Some(window) => match tokio::time::timeout(window, &mut pull).await {
                        Ok(joined) => joined,
                        Err(_) => {
                            tracing::info!(
                                subscription = %self.config.subscription,
                                idle_secs = window.as_secs(),
                                "pubsub: idle termination reached"
                            );
                            // A response already on its way is nacked; a pull
                            // still parked server-side is cancelled, which
                            // leases nothing.
                            match tokio::time::timeout(LATE_PULL_GRACE, &mut pull).await {
                                Ok(Ok(Ok(late))) if !late.is_empty() => nack_messages(late).await,
                                Ok(_) => {}
                                Err(_) => pull.abort(),
                            }
                            break 'consume;
                        }
                    },
                    None => pull.await,
                };
                let messages = joined
                    .map_err(|e| FaucetError::Source(format!("pubsub: pull task failed: {e}")))??;

                if messages.is_empty() {
                    if let Some(window) = idle
                        && last_activity.elapsed() >= window
                    {
                        tracing::info!(
                            subscription = %self.config.subscription,
                            idle_secs = window.as_secs(),
                            "pubsub: idle termination reached"
                        );
                        break 'consume;
                    }
                    // No idle window (max-messages only) and no messages: yield
                    // to the scheduler briefly to avoid a hot spin.
                    tokio::time::sleep(Duration::from_millis(200)).await;
                    continue;
                }
                last_activity = Instant::now();
                if lease.is_some() {
                    let mut pulled = messages.clone();
                    pulled.extend(page_msgs.iter().cloned());
                    hold(&pulled, &pending);
                }

                let mut messages = messages.into_iter();
                while let Some(m) = messages.next() {
                    let record = record_with_policy(
                        &MessageParts {
                            data: &m.message.data,
                            attributes: &m.message.attributes,
                            message_id: &m.message.message_id,
                            ordering_key: &m.message.ordering_key,
                            publish_time_millis: Self::publish_millis(&m),
                        },
                        format,
                        &attributes_key,
                        on_decode_error,
                    )?;
                    cumulative.advance(&m.message.message_id);
                    if let Some(record) = record {
                        buffer.push(record);
                    }
                    page_msgs.push(m);
                    total += 1;

                    if buffer.len() >= chunk {
                        let records = std::mem::take(&mut buffer);
                        pending.append(&mut page_msgs);
                        yield StreamPage {
                            records,
                            bookmark: Some(cumulative.to_value()),
                        };
                    }

                    if let Some(max) = max_messages
                        && total >= max
                    {
                        tracing::info!(
                            subscription = %self.config.subscription,
                            max,
                            "pubsub: max_messages reached"
                        );
                        // Defensive: a server returning more than requested.
                        let rest: Vec<ReceivedMessage> = messages.collect();
                        if !rest.is_empty() {
                            nack_messages(rest).await;
                        }
                        break 'consume;
                    }
                }
            }

            // Flush any buffered-but-un-yielded records as a final page.
            if !buffer.is_empty() {
                let records = std::mem::take(&mut buffer);
                pending.append(&mut page_msgs);
                yield StreamPage {
                    records,
                    bookmark: Some(cumulative.to_value()),
                };
            }
            // Skipped (undecodable) messages after the last page carry no
            // record, so nothing has to be durable before they are acked.
            pending.append(&mut page_msgs);

            // Every remaining page has now resumed past its `yield`, so it is
            // durable — ack it before returning.
            if !pending.is_empty() {
                ack_messages(&subscription, &pending).await;
            }
            drop(lease);

            tracing::info!(
                subscription = %self.config.subscription,
                records = total,
                "pubsub source stream complete"
            );
        })
    }

    fn config_schema(&self) -> Value {
        serde_json::to_value(faucet_core::schema_for!(PubsubSourceConfig))
            .expect("schema serialization")
    }

    fn state_key(&self) -> Option<String> {
        Some(state_key(&self.config.subscription))
    }

    async fn apply_start_bookmark(&self, bookmark: Value) -> Result<(), FaucetError> {
        *self.start_bookmark.lock().expect("bookmark mutex poisoned") =
            Some(PubsubBookmark::from_value(&bookmark));
        Ok(())
    }

    fn consumes_destructively(&self) -> bool {
        true
    }

    fn connector_name(&self) -> &'static str {
        "pubsub"
    }

    fn dataset_uri(&self) -> String {
        format!(
            "pubsub://{}/subscriptions/{}",
            self.config
                .connection
                .project_id
                .as_deref()
                .unwrap_or("default"),
            self.config.subscription
        )
    }

    /// Side-effect-free probe: confirm the subscription exists (no messages
    /// consumed). The default first-page probe could block for the full idle
    /// window on a quiet subscription.
    async fn check(
        &self,
        ctx: &faucet_core::CheckContext,
    ) -> Result<faucet_core::CheckReport, FaucetError> {
        use faucet_core::{CheckReport, Probe};
        let start = std::time::Instant::now();
        let subscription = self.subscription();
        let fut = subscription.exists(None);
        let probe = match tokio::time::timeout(ctx.timeout, fut).await {
            Err(_) => Probe::fail("subscription_exists", start.elapsed(), "timed out"),
            Ok(Ok(true)) => Probe::pass("subscription_exists", start.elapsed()),
            Ok(Ok(false)) => Probe::fail(
                "subscription_exists",
                start.elapsed(),
                format!("subscription '{}' does not exist", self.config.subscription),
            ),
            Ok(Err(e)) => Probe::fail("subscription_exists", start.elapsed(), e.to_string()),
        };
        Ok(CheckReport::single(probe))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // Constructing a live client needs the emulator or real GCP, so the
    // network-bound trait methods are exercised by `tests/integration.rs`
    // (emulator-gated). Here we cover the offline, pure-ish surface.

    #[test]
    fn pulls_never_exceed_what_the_run_still_needs() {
        assert_eq!(pull_size(1000, None, 50), 1000);
        assert_eq!(pull_size(1000, Some(30), 25), 5);
        assert_eq!(pull_size(10, Some(30), 0), 10);
        assert_eq!(pull_size(10, Some(30), 30), 1);
    }

    #[test]
    fn state_key_and_dataset_uri_helpers() {
        // dataset_uri/state_key are built from config strings only.
        assert_eq!(state_key("orders-sub"), "pubsub:orders-sub");
    }

    #[test]
    fn config_schema_exposes_fields() {
        let schema = serde_json::to_value(faucet_core::schema_for!(PubsubSourceConfig)).unwrap();
        assert!(schema["properties"]["subscription"].is_object());
        assert!(schema["properties"]["value_format"].is_object());
    }

    #[tokio::test]
    async fn new_rejects_config_without_termination() {
        // Validation runs before any client build, so this fails offline with a
        // config error (never a network error).
        // `PubsubSource` holds a non-`Debug` SDK subscription, so `unwrap_err`
        // (which needs the `Ok` type to be `Debug`) is unavailable — match.
        let err = match PubsubSource::new(PubsubSourceConfig::new("orders-sub")).await {
            Ok(_) => panic!("expected a termination-config error"),
            Err(e) => e,
        };
        assert!(err.to_string().contains("idle_termination_secs"), "{err}");
    }

    #[test]
    fn renewal_runs_every_five_seconds_or_a_third_of_a_short_window() {
        assert_eq!(renew_every(60), Duration::from_secs(5));
        assert_eq!(renew_every(12), Duration::from_secs(4));
        assert_eq!(renew_every(10), Duration::from_secs(3));
        assert_eq!(renew_every(600), Duration::from_secs(5));
    }
}