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
//! Kinesis -> Lambda event source mapping poller.
//!
//! Honors:
//! - `FilterCriteria` — non-matching records are dropped (advanced past).
//! - `StartingPosition` — `TRIM_HORIZON` (default), `LATEST`, or
//! `AT_TIMESTAMP` paired with `StartingPositionTimestamp` to seed
//! the per-shard checkpoint on first poll.
use std::sync::Arc;
use std::time::Duration;
use base64::Engine;
use chrono::Utc;
use serde_json::{json, Value};
use fakecloud_core::delivery::LambdaDelivery;
use fakecloud_kinesis::state::SharedKinesisState;
use fakecloud_lambda::filter::FilterSet;
use fakecloud_lambda::state::{LambdaInvocation, SharedLambdaState};
#[derive(Clone)]
struct Mapping {
uuid: String,
function_arn: String,
stream_arn: String,
batch_size: i64,
filter: FilterSet,
starting_position: Option<String>,
starting_position_timestamp: Option<f64>,
}
pub struct KinesisLambdaPoller {
kinesis_state: SharedKinesisState,
lambda_state: SharedLambdaState,
lambda_delivery: Option<Arc<dyn LambdaDelivery>>,
}
impl KinesisLambdaPoller {
pub fn new(kinesis_state: SharedKinesisState, lambda_state: SharedLambdaState) -> Self {
Self {
kinesis_state,
lambda_state,
lambda_delivery: None,
}
}
pub fn with_lambda_delivery(mut self, delivery: Arc<dyn LambdaDelivery>) -> Self {
self.lambda_delivery = Some(delivery);
self
}
pub async fn run(self) {
let mut interval = tokio::time::interval(Duration::from_millis(500));
loop {
interval.tick().await;
self.poll().await;
}
}
async fn poll(&self) {
let mappings: Vec<Mapping> = {
let lambda_accounts = self.lambda_state.read();
lambda_accounts
.iter()
.flat_map(|(_, lambda)| {
lambda
.event_source_mappings
.values()
.filter(|m| m.enabled && m.event_source_arn.contains(":kinesis:"))
.map(|m| Mapping {
uuid: m.uuid.clone(),
function_arn: m.function_arn.clone(),
stream_arn: m.event_source_arn.clone(),
batch_size: m.batch_size,
filter: FilterSet::from_strings(m.filter_patterns.iter()),
starting_position: m.starting_position.clone(),
starting_position_timestamp: m.starting_position_timestamp,
})
.collect::<Vec<_>>()
})
.collect()
};
if mappings.is_empty() {
return;
}
for mapping in mappings {
self.process_mapping(&mapping).await;
}
}
async fn process_mapping(&self, mapping: &Mapping) {
// Compute per-shard deliveries: snapshot current shard
// contents, seed missing checkpoints based on StartingPosition,
// then collect a batch from each shard up to batch_size.
let deliveries = {
let mut kinesis_accounts = self.kinesis_state.write();
let account_id = mapping.stream_arn.split(':').nth(4).unwrap_or("");
let kinesis = match kinesis_accounts.get_mut(account_id) {
Some(k) => k,
None => return,
};
let stream_idx = kinesis
.streams
.iter()
.find(|(_, s)| s.stream_arn == mapping.stream_arn)
.map(|(name, _)| name.clone());
let Some(stream_name) = stream_idx else {
return;
};
// Initialize per-shard checkpoints once based on
// StartingPosition. Subsequent polls just read what's already
// there.
let init_pairs: Vec<(String, usize)> = {
let stream = kinesis
.streams
.get(&stream_name)
.expect("stream exists, just looked up");
stream
.shards
.iter()
.filter_map(|shard| {
let key = format!("{}:{}", mapping.uuid, shard.shard_id);
if kinesis.lambda_checkpoints.contains_key(&key) {
return None;
}
let init = match mapping
.starting_position
.as_deref()
.unwrap_or("TRIM_HORIZON")
{
"LATEST" => shard.records.len(),
"AT_TIMESTAMP" => {
let target = mapping
.starting_position_timestamp
.map(|t| t as i64)
.unwrap_or(0);
shard
.records
.iter()
.position(|r| {
r.approximate_arrival_timestamp.timestamp() >= target
})
.unwrap_or(shard.records.len())
}
_ => 0, // TRIM_HORIZON
};
Some((shard.shard_id.clone(), init))
})
.collect()
};
for (shard_id, init) in init_pairs {
kinesis.set_lambda_checkpoint(&mapping.uuid, &shard_id, init);
}
let stream = kinesis
.streams
.get(&stream_name)
.expect("stream exists, just looked up");
let limit = mapping.batch_size.max(1) as usize;
stream
.shards
.iter()
.filter_map(|shard| {
let start = kinesis.lambda_checkpoint(&mapping.uuid, &shard.shard_id);
if start >= shard.records.len() {
return None;
}
let end = shard.records.len().min(start.saturating_add(limit));
let records = shard.records[start..end].to_vec();
Some((shard.shard_id.clone(), end, records))
})
.collect::<Vec<_>>()
};
for (shard_id, end, records) in deliveries {
// Build per-record JSON, then split into matched + dropped
// by FilterCriteria. Dropped records still advance the
// checkpoint — AWS docs say filtered-out records "do not
// count toward batch size and are discarded".
let record_jsons: Vec<Value> = records
.iter()
.map(|record| {
json!({
"awsRegion": "us-east-1",
"eventID": format!("{}:{}", shard_id, record.sequence_number),
"eventName": "aws:kinesis:record",
"eventSource": "aws:kinesis",
"eventSourceARN": mapping.stream_arn,
"eventVersion": "1.0",
"invokeIdentityArn": "arn:aws:iam::123456789012:role/lambda-role",
"kinesis": {
"approximateArrivalTimestamp": record.approximate_arrival_timestamp.timestamp_millis() as f64 / 1000.0,
"data": base64::engine::general_purpose::STANDARD.encode(&record.data),
"kinesisSchemaVersion": "1.0",
"partitionKey": record.partition_key,
"sequenceNumber": record.sequence_number,
}
})
})
.collect();
let matched: Vec<Value> = if mapping.filter.is_empty() {
record_jsons
} else {
record_jsons
.into_iter()
.filter(|r| mapping.filter.matches(r))
.collect()
};
// If the filter dropped every record, advance the
// checkpoint past them — AWS treats filtered-out records
// as consumed and never retries them.
if matched.is_empty() {
let account_id = mapping.stream_arn.split(':').nth(4).unwrap_or("");
let mut kinesis_accounts = self.kinesis_state.write();
let kinesis = kinesis_accounts.get_or_create(account_id);
kinesis.set_lambda_checkpoint(&mapping.uuid, &shard_id, end);
continue;
}
let payload = json!({ "Records": matched }).to_string();
let used_real_delivery = self.lambda_delivery.is_some();
let delivered = if let Some(ref delivery) = self.lambda_delivery {
match delivery
.invoke_lambda(&mapping.function_arn, &payload)
.await
{
Ok(_) => true,
Err(error) => {
tracing::warn!(
function_arn = %mapping.function_arn,
stream_arn = %mapping.stream_arn,
shard_id = %shard_id,
error = %error,
"Kinesis->Lambda: function invocation failed"
);
false
}
}
} else {
true
};
// Only advance the checkpoint after a successful invoke.
// A failed invoke leaves the records pending so the next
// poll retries them — matches AWS's at-least-once guarantee.
if !delivered {
continue;
}
{
let account_id = mapping.stream_arn.split(':').nth(4).unwrap_or("");
let mut kinesis_accounts = self.kinesis_state.write();
let kinesis = kinesis_accounts.get_or_create(account_id);
kinesis.set_lambda_checkpoint(&mapping.uuid, &shard_id, end);
}
if !used_real_delivery {
let fn_account = mapping.function_arn.split(':').nth(4).unwrap_or("");
let mut lambda_accounts = self.lambda_state.write();
let lambda = lambda_accounts.get_or_create(fn_account);
lambda.invocations.push(LambdaInvocation {
function_arn: mapping.function_arn.clone(),
payload,
timestamp: Utc::now(),
source: "aws:kinesis".to_string(),
});
}
}
}
}