|
| 1 | +import { |
| 2 | + GetRecordsCommand, |
| 3 | + GetRecordsCommandOutput, |
| 4 | + GetShardIteratorCommand, |
| 5 | + KinesisClient, |
| 6 | + ListShardsCommand, |
| 7 | + Shard, |
| 8 | + ShardIteratorType, |
| 9 | +} from "@aws-sdk/client-kinesis"; |
| 10 | +import { AWS_REGION } from "tests/constants/api-constants"; |
| 11 | + |
| 12 | +export const kinesisClient = new KinesisClient({ region: AWS_REGION }); |
| 13 | + |
| 14 | +/** |
| 15 | + * Wait for a matching record on a Kinesis stream. |
| 16 | + * |
| 17 | + * @param streamARN - existing Kinesis stream ARN |
| 18 | + * @param opts - optional settings |
| 19 | + */ |
| 20 | +export async function retrieveKinesisRecordsAtTimestamp( |
| 21 | + streamARN: string, |
| 22 | + startTimeMs: number, |
| 23 | +): Promise<number> { |
| 24 | + let recordsFound = 0; |
| 25 | + |
| 26 | + const shards: Shard[] = await getShards(streamARN); |
| 27 | + for (const shard of shards) { |
| 28 | + recordsFound += await getAllShardRecords(shard, streamARN, startTimeMs); |
| 29 | + } |
| 30 | + return recordsFound; |
| 31 | +} |
| 32 | + |
| 33 | +async function getShards(streamARN: string) { |
| 34 | + const shardsResp = await kinesisClient.send( |
| 35 | + new ListShardsCommand({ StreamARN: streamARN }), |
| 36 | + ); |
| 37 | + const shards: Shard[] = shardsResp.Shards ?? []; |
| 38 | + if (shards.length === 0) { |
| 39 | + throw new Error(`No shards found for stream ${streamARN}`); |
| 40 | + } |
| 41 | + return shards; |
| 42 | +} |
| 43 | + |
| 44 | +async function getAllShardRecords( |
| 45 | + shard: Shard, |
| 46 | + streamARN: string, |
| 47 | + startTimeMs: number, |
| 48 | +) { |
| 49 | + let shardRecords = 0; |
| 50 | + const iteratorResponse = await kinesisClient.send( |
| 51 | + new GetShardIteratorCommand({ |
| 52 | + StreamARN: streamARN, |
| 53 | + ShardId: shard.ShardId, |
| 54 | + ShardIteratorType: ShardIteratorType.AT_TIMESTAMP, |
| 55 | + Timestamp: new Date(startTimeMs), |
| 56 | + }), |
| 57 | + ); |
| 58 | + |
| 59 | + const shardIterator = iteratorResponse.ShardIterator; |
| 60 | + if (!shardIterator) { |
| 61 | + throw new Error("Failed to obtain shard iterator"); |
| 62 | + } |
| 63 | + |
| 64 | + const recResp: GetRecordsCommandOutput = await kinesisClient.send( |
| 65 | + new GetRecordsCommand({ |
| 66 | + ShardIterator: shardIterator, |
| 67 | + StreamARN: streamARN, |
| 68 | + }), |
| 69 | + ); |
| 70 | + shardRecords += recResp.Records?.length ?? 0; |
| 71 | + |
| 72 | + return shardRecords; |
| 73 | +} |
0 commit comments