repo_name string | dataset string | owner string | lang string | func_name string | code string | docstring string | url string | sha string |
|---|---|---|---|---|---|---|---|---|
project-lakechain | github_2023 | awslabs | typescript | TimeWindowStrategy.name | public name() {
return (this.props.reduceType);
} | /**
* @returns the strategy name.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/reducer/src/definitions/strategies/time-window-strategy/index.ts#L128-L130 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TimeWindowStrategy.jitter | public jitter() {
return (this.props.jitter);
} | /**
* @returns the jitter value to apply to the time window.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/reducer/src/definitions/strategies/time-window-strategy/index.ts#L135-L137 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TimeWindowStrategy.compile | public compile() {
return (this.toJSON());
} | /**
* @returns an object describing the strategy.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/reducer/src/definitions/strategies/time-window-strategy/index.ts#L142-L144 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TimeWindowStrategy.from | public static from(props: any) {
return (new TimeWindowStrategy(TimeWindowStrategyPropsSchema.parse(props)));
} | /**
* Creates a new instance of the `TimeWindowStrategy` class.
* @param props the task properties.
* @returns a new instance of the `TimeWindowStrategy` class.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/reducer/src/definitions/strategies/time-window-strategy/index.ts#L151-L153 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TimeWindowStrategy.toJSON | public toJSON() {
return ({
reduceType: this.props.reduceType,
timeWindow: this.props.timeWindow.toSeconds(),
jitter: this.props.jitter?.toSeconds()
});
} | /**
* @returns the JSON representation of the task.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/reducer/src/definitions/strategies/time-window-strategy/index.ts#L158-L164 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ConditionalStrategyConstruct.constructor | constructor(scope: Construct, id: string, reducer: Reducer, props: ReducerProps) {
super(scope, id);
// Reducer middleware properties.
const queue = reducer.getQueue();
const eventBus = reducer.getEventBus();
const logGroup = reducer.getLogGroup();
const strategy = props.strategy.compile();
///////////////////////////////////////////
/////// Event Storage ///////
///////////////////////////////////////////
this.table = new dynamodb.Table(this, 'Table', {
partitionKey: {
name: 'pk',
type: dynamodb.AttributeType.STRING
},
sortKey: {
name: 'sk',
type: dynamodb.AttributeType.STRING
},
timeToLiveAttribute: 'ttl',
billingMode: dynamodb.BillingMode.PAY_PER_REQUEST,
stream: dynamodb.StreamViewType.NEW_IMAGE,
removalPolicy: cdk.RemovalPolicy.DESTROY,
encryptionKey: props.kmsKey
});
///////////////////////////////////////////
/////// De-duplication Queue ///////
///////////////////////////////////////////
// The SQS FIFO queue used to de-duplicate the events.
this.deduplicationQueue = new sqs.Queue(this, 'DeduplicationQueue', {
fifo: true,
contentBasedDeduplication: true,
encryptionMasterKey: props.kmsKey,
encryption: props.kmsKey ?
sqs.QueueEncryption.KMS :
sqs.QueueEncryption.SQS_MANAGED,
visibilityTimeout: props.queueVisibilityTimeout,
enforceSSL: true
});
///////////////////////////////////////////
////// De-duplication Function //////
///////////////////////////////////////////
this.deduplicationFn = new node.NodejsFunction(this, 'Deduplication', {
description: 'A function used to insert events in the de-duplication queue.',
entry: path.resolve(__dirname, 'lambdas', 'deduplication', 'index.js'),
vpc: props.vpc,
timeout: cdk.Duration.seconds(10),
runtime: EXECUTION_RUNTIME,
architecture: lambda.Architecture.ARM_64,
tracing: lambda.Tracing.ACTIVE,
environmentEncryption: props.kmsKey,
logGroup,
insightsVersion: props.cloudWatchInsights ?
LAMBDA_INSIGHTS_VERSION :
undefined,
environment: {
POWERTOOLS_SERVICE_NAME: reducer.name(),
POWERTOOLS_METRICS_NAMESPACE: NAMESPACE,
SQS_DEDUPLICATION_QUEUE_URL: this.deduplicationQueue.queueUrl
},
bundling: {
minify: true,
externalModules: [
'@aws-sdk/client-sqs'
]
}
});
// Allows the reducer to act as a `IGrantable`
// for other middlewares to grant the processing
// lambda permissions to access their resources.
reducer.grantPrincipal = this.deduplicationFn.grantPrincipal;
// Allow the function to consume messages from the input queue.
queue.grantConsumeMessages(this.deduplicationFn);
// Allow the function to send messages to the de-duplication queue.
this.deduplicationQueue.grantSendMessages(this.deduplicationFn);
// Plug the SQS queue into the deduplication function.
this.deduplicationFn.addEventSource(new sources.SqsEventSource(queue, {
batchSize: 1,
maxBatchingWindow: props.batchingWindow
}));
///////////////////////////////////////////
/////// Insertion Function ///////
///////////////////////////////////////////
this.insertionProcessor = new node.NodejsFunction(this, 'Compute', {
description: 'A function inserting events in DynamoDB.',
entry: path.resolve(__dirname, 'lambdas', 'insertion', 'index.js'),
vpc: props.vpc,
timeout: cdk.Duration.seconds(10),
runtime: EXECUTION_RUNTIME,
architecture: lambda.Architecture.ARM_64,
tracing: lambda.Tracing.ACTIVE,
environmentEncryption: props.kmsKey,
logGroup,
insightsVersion: props.cloudWatchInsights ?
LAMBDA_INSIGHTS_VERSION :
undefined,
environment: {
POWERTOOLS_SERVICE_NAME: reducer.name(),
POWERTOOLS_METRICS_NAMESPACE: NAMESPACE,
TABLE_NAME: this.table.tableName
},
bundling: {
minify: true,
externalModules: [
'@aws-sdk/client-dynamodb'
]
}
});
// Plug the SQS queue into the lambda function.
this.insertionProcessor.addEventSource(new sources.SqsEventSource(this.deduplicationQueue, {
batchSize: 10
}));
// Allow the function to insert items in the DynamoDB table.
this.table.grantWriteData(this.insertionProcessor);
///////////////////////////////////////////
/////// Evaluation Function //////
///////////////////////////////////////////
this.evaluationFn = new node.NodejsFunction(this, 'Evaluation', {
description: 'A function evaluating a conditional expression.',
entry: path.resolve(__dirname, 'lambdas', 'evaluation', 'index.js'),
vpc: props.vpc,
timeout: cdk.Duration.seconds(30),
runtime: EXECUTION_RUNTIME,
architecture: lambda.Architecture.ARM_64,
tracing: lambda.Tracing.ACTIVE,
environmentEncryption: props.kmsKey,
logGroup,
insightsVersion: props.cloudWatchInsights ?
LAMBDA_INSIGHTS_VERSION :
undefined,
environment: {
POWERTOOLS_SERVICE_NAME: reducer.name(),
POWERTOOLS_METRICS_NAMESPACE: NAMESPACE,
CONDITIONAL_TYPE: strategy.type,
CONDITIONAL: strategy.expression,
CONDITIONAL_SYMBOL: strategy.symbol,
TABLE_NAME: this.table.tableName
},
bundling: {
minify: true,
externalModules: [
'@aws-sdk/client-dynamodb'
]
}
});
// Function permissions.
this.table.grantReadWriteData(this.evaluationFn);
// Allow the function to evaluate the conditional expression
// if it is a lambda function.
if (strategy.type === 'lambda') {
this.evaluationFn.addToRolePolicy(new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ['lambda:InvokeFunction'],
resources: [strategy.expression]
}));
}
// Plug the DynamoDB stream into the lambda function.
this.evaluationFn.addEventSource(new sources.DynamoEventSource(this.table, {
startingPosition: lambda.StartingPosition.LATEST,
batchSize: 1,
parallelizationFactor: 10,
retryAttempts: props.maxRetry,
filters: [
lambda.FilterCriteria.filter({
eventName: lambda.FilterRule.isEqual('INSERT'),
dynamodb: {
Keys: {
sk: {
S: lambda.FilterRule.beginsWith('EVENT##')
}
}
}
})
]
}));
///////////////////////////////////////////
/////// Reducer Function //////
///////////////////////////////////////////
this.reducerFn = new node.NodejsFunction(this, 'Reducer', {
description: 'A function reducing events.',
entry: path.resolve(__dirname, 'lambdas', 'reducer', 'index.js'),
vpc: props.vpc,
timeout: cdk.Duration.seconds(30),
runtime: EXECUTION_RUNTIME,
architecture: lambda.Architecture.ARM_64,
tracing: lambda.Tracing.ACTIVE,
environmentEncryption: props.kmsKey,
logGroup,
insightsVersion: props.cloudWatchInsights ?
LAMBDA_INSIGHTS_VERSION :
undefined,
environment: {
POWERTOOLS_SERVICE_NAME: reducer.name(),
POWERTOOLS_METRICS_NAMESPACE: NAMESPACE,
SNS_TARGET_TOPIC: eventBus.topicArn,
PROCESSED_FILES_BUCKET: reducer.storage.id(),
TABLE_NAME: this.table.tableName
},
bundling: {
minify: true,
externalModules: [
'@aws-sdk/client-dynamodb',
'@aws-sdk/client-s3',
'@aws-sdk/client-sns'
]
}
});
// Function permissions.
this.table.grantReadWriteData(this.reducerFn);
reducer.storage.grantWrite(this.reducerFn);
eventBus.grantPublish(this.reducerFn);
// Plug the DynamoDB stream into the lambda function.
this.reducerFn.addEventSource(new sources.DynamoEventSource(this.table, {
startingPosition: lambda.StartingPosition.LATEST,
batchSize: 1,
parallelizationFactor: 10,
maxBatchingWindow: cdk.Duration.seconds(30),
retryAttempts: props.maxRetry,
filters: [
lambda.FilterCriteria.filter({
eventName: lambda.FilterRule.notEquals('REMOVE'),
dynamodb: {
Keys: {
sk: {
S: lambda.FilterRule.isEqual('STATUS')
}
},
NewImage: {
status: {
S: lambda.FilterRule.isEqual('processed')
}
}
}
})
]
}));
} | /**
* Provider constructor.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/reducer/src/impl/conditional-strategy/index.ts#L81-L341 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.handler | async handler(event: SQSEvent, _: Context): Promise<any> {
try {
const events = event.Records.map((record) => {
return (CloudEvent.from(record.body));
});
// Forward the received batch of events to the deduplication queue.
await sqs.send(new SendMessageBatchCommand({
QueueUrl: process.env.SQS_DEDUPLICATION_QUEUE_URL,
Entries: events.map((event) => {
return ({
Id: randomUUID(),
MessageBody: JSON.stringify(event),
MessageGroupId: event.data().chainId()
});
})
}));
} catch (error) {
logger.error(error as any);
throw error;
}
} | // eslint-disable-next-line @typescript-eslint/no-unused-vars | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/reducer/src/impl/conditional-strategy/lambdas/deduplication/index.ts#L48-L69 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | evaluateLambda | const evaluateLambda = async (
event: Readonly<CloudEvent>,
storedEvents: Readonly<CloudEvent[]>
): Promise<boolean> => {
const res = await lambda.send(new InvokeCommand({
FunctionName: CONDITIONAL,
Payload: JSON.stringify({
event: event.toJSON(),
storedEvents: storedEvents.map((e) => e.toJSON())
})
}));
// If the function failed to execute, we throw an error.
if (res.FunctionError) {
throw new Error(res.FunctionError);
}
// Parse the result of the lambda function into a boolean value.
const payload = JSON.parse(
new TextDecoder().decode(res.Payload as Uint8Array)
);
return (payload === true);
}; | /**
* Synchronously invokes the conditional lambda function and
* returns its boolean result.
* @param event the event that was received.
* @param storedEvents the list of events stored in the table.
* @returns a promise to the boolean result of the conditional.
* @throws an error if the conditional function failed to execute.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/reducer/src/impl/conditional-strategy/lambdas/evaluation/evaluate.ts#L34-L57 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | evaluateExpression | const evaluateExpression = async (
event: Readonly<CloudEvent>,
storedEvents: Readonly<CloudEvent[]>,
opts?: RunningCodeOptions
): Promise<boolean> => {
const context = createContext({
console,
require,
setTimeout,
setInterval,
setImmediate,
event,
storedEvents
});
// Run the expression within a VM.
const res = runInContext(`${CONDITIONAL}\n${CONDITIONAL_SYMBOL}(event, storedEvents);`, context, {
timeout: 10_000,
...opts
});
// If the expression did not return a promise, we throw an error.
if (!res.then) {
throw new Error(`
Invalid conditional expression return type, a promise is expected.
`);
}
return ((await res) === true);
}; | /**
* Evaluates the given conditional expression and returns
* its boolean result.
* @param event the event that was received.
* @param storedEvents the list of events stored in the table.
* @param opts execution options.
* @returns a promise to the boolean result of the conditional.
* @throws an error if the conditional expression is invalid.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/reducer/src/impl/conditional-strategy/lambdas/evaluation/evaluate.ts#L68-L97 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.getAggregatedEvents | private async getAggregatedEvents(chainId: string) {
const results = await dynamoDb.send(new QueryCommand({
TableName: TABLE_NAME,
KeyConditionExpression: '#pk = :pk AND begins_with(#sk, :prefix)',
ConsistentRead: true,
ExpressionAttributeNames: {
'#pk': 'pk',
'#sk': 'sk'
},
ExpressionAttributeValues: {
':pk': { S: chainId },
':prefix': { S: 'EVENT##' }
}
}));
return ((results.Items || []).map((item) => {
return (CloudEvent.from(JSON.parse(item.event.S as string)));
}));
} | /**
* Fetches all the events associated with the given `chainId`
* and returns them as an array of `CloudEvent`.
* @param chainId the chain identifier.
* @returns an array of `CloudEvent`.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/reducer/src/impl/conditional-strategy/lambdas/evaluation/index.ts#L56-L74 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.handler | async handler(event: DynamoDBStreamEvent, _: Context): Promise<any> {
try {
const e = CloudEvent.from(event.Records[0].dynamodb!.NewImage!.event.S!);
// Retrieve all the events stored in the table.
const events = await this.getAggregatedEvents(e.data().chainId());
// Evaluate the conditional expression.
let result: boolean;
try {
result = await evaluate(e, events);
} catch (error) {
logger.error(error as any);
result = false;
}
if (result) {
// Set the state of the aggregation to `processed` if it
// is not already set. This is to indicate that the reduce
// operation can be triggered, and to ensure that it only
// happens once.
try {
await dynamoDb.send(new UpdateItemCommand({
TableName: TABLE_NAME,
Key: {
pk: { S: e.data().chainId() },
sk: { S: 'STATUS' }
},
UpdateExpression: `
SET #status = :status
`,
ConditionExpression: 'attribute_not_exists(#status) OR #status <> :status',
ExpressionAttributeNames: {
'#status': 'status'
},
ExpressionAttributeValues: {
':status': { S: 'processed' }
}
}));
} catch (error) {
// This might indicate that we received events after
// the aggregation has been processed.
logger.error(error as any);
}
}
} catch (error) {
logger.error(error as any);
throw error;
}
} | // eslint-disable-next-line @typescript-eslint/no-unused-vars | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/reducer/src/impl/conditional-strategy/lambdas/evaluation/index.ts#L84-L133 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | getTtl | const getTtl = () => {
const SECONDS_IN_AN_HOUR = 60 * 60;
return (Math.round(Date.now() / 1000) + (48 * SECONDS_IN_AN_HOUR));
}; | /**
* This method computes the time-to-live value for events stored in DynamoDB.
* The purpose is to ensure that elements within the table are automatically
* deleted after a certain amount of time.
* @returns a time-to-live value for events stored in DynamoDB.
* @default 48 hours.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/reducer/src/impl/conditional-strategy/lambdas/insertion/index.ts#L47-L50 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.handler | async handler(event: SQSEvent, _: Context): Promise<any> {
try {
await dynamoDb.send(new BatchWriteItemCommand({
RequestItems: {
[TABLE_NAME]: event.Records.map((record) => {
const event = CloudEvent.from(record.body);
const uuid = randomUUID();
return ({
PutRequest: {
Item: {
pk: { S: event.data().chainId() },
sk: { S: `EVENT##${new Date().toISOString()}##${uuid}` },
type: { S: 'event' },
event: { S: JSON.stringify(event) },
ttl: { N: getTtl().toString() }
}
}
})
})
}
}));
} catch (error) {
logger.error(error as any);
throw error;
}
} | // eslint-disable-next-line @typescript-eslint/no-unused-vars | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/reducer/src/impl/conditional-strategy/lambdas/insertion/index.ts#L68-L93 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.handler | async handler(event: any, _: Context): Promise<any> {
try {
// The primary key of the event.
const chainId = event.Records[0].dynamodb!.NewImage!.pk.S!;
// Retrieve all the events to reduce from the table.
const results = await dynamoDb.send(new QueryCommand({
TableName: TABLE_NAME,
KeyConditionExpression: '#pk = :pk AND begins_with(#sk, :prefix)',
ConsistentRead: true,
Limit: COUNTER_THRESHOLD,
ExpressionAttributeNames: {
'#pk': 'pk',
'#sk': 'sk'
},
ExpressionAttributeValues: {
':pk': { S: chainId },
':prefix': { S: 'EVENT##' }
}
}));
// Reduce the events.
await this.reduceEvents(chainId, results.Items?.map((item) => {
return (CloudEvent.from(JSON.parse(item.event.S as string)));
}) ?? []);
} catch (error) {
logger.error(error as any);
throw error;
}
} | // eslint-disable-next-line @typescript-eslint/no-unused-vars | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/reducer/src/impl/conditional-strategy/lambdas/reducer/index.ts#L101-L130 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | StaticCounterStrategyConstruct.constructor | constructor(scope: Construct, id: string, reducer: Reducer, props: ReducerProps) {
super(scope, id);
// Reducer middleware properties.
const queue = reducer.getQueue();
const eventBus = reducer.getEventBus();
const logGroup = reducer.getLogGroup();
const eventCount = props.strategy.compile().eventCount;
console.log('eventCount', eventCount);
///////////////////////////////////////////
/////// Event Storage ///////
///////////////////////////////////////////
this.table = new dynamodb.Table(this, 'Table', {
partitionKey: {
name: 'pk',
type: dynamodb.AttributeType.STRING
},
sortKey: {
name: 'sk',
type: dynamodb.AttributeType.STRING
},
timeToLiveAttribute: 'ttl',
billingMode: dynamodb.BillingMode.PAY_PER_REQUEST,
stream: dynamodb.StreamViewType.NEW_IMAGE,
removalPolicy: cdk.RemovalPolicy.DESTROY,
encryptionKey: props.kmsKey
});
///////////////////////////////////////////
/////// De-duplication Queue ///////
///////////////////////////////////////////
// The SQS FIFO queue used to de-duplicate the events.
this.deduplicationQueue = new sqs.Queue(this, 'DeduplicationQueue', {
fifo: true,
contentBasedDeduplication: true,
encryptionMasterKey: props.kmsKey,
encryption: props.kmsKey ?
sqs.QueueEncryption.KMS :
sqs.QueueEncryption.SQS_MANAGED,
visibilityTimeout: props.queueVisibilityTimeout,
enforceSSL: true
});
///////////////////////////////////////////
////// De-duplication Function //////
///////////////////////////////////////////
this.deduplicationFn = new node.NodejsFunction(this, 'Deduplication', {
description: 'A function used to insert events in the de-duplication queue.',
entry: path.resolve(__dirname, 'lambdas', 'deduplication', 'index.js'),
vpc: props.vpc,
timeout: cdk.Duration.seconds(10),
runtime: EXECUTION_RUNTIME,
architecture: lambda.Architecture.ARM_64,
tracing: lambda.Tracing.ACTIVE,
environmentEncryption: props.kmsKey,
logGroup,
insightsVersion: props.cloudWatchInsights ?
LAMBDA_INSIGHTS_VERSION :
undefined,
environment: {
POWERTOOLS_SERVICE_NAME: reducer.name(),
POWERTOOLS_METRICS_NAMESPACE: NAMESPACE,
SQS_DEDUPLICATION_QUEUE_URL: this.deduplicationQueue.queueUrl
},
bundling: {
minify: true,
externalModules: [
'@aws-sdk/client-sqs'
]
}
});
// Allows the reducer to act as a `IGrantable`
// for other middlewares to grant the processing
// lambda permissions to access their resources.
reducer.grantPrincipal = this.deduplicationFn.grantPrincipal;
// Allow the function to consume messages from the input queue.
queue.grantConsumeMessages(this.deduplicationFn);
// Allow the function to send messages to the de-duplication queue.
this.deduplicationQueue.grantSendMessages(this.deduplicationFn);
// Plug the SQS queue into the deduplication function.
this.deduplicationFn.addEventSource(new sources.SqsEventSource(queue, {
batchSize: 1,
maxBatchingWindow: props.batchingWindow
}));
///////////////////////////////////////////
/////// Insertion Function ///////
///////////////////////////////////////////
this.insertionProcessor = new node.NodejsFunction(this, 'Compute', {
description: 'A function inserting events in DynamoDB.',
entry: path.resolve(__dirname, 'lambdas', 'insertion', 'index.js'),
vpc: props.vpc,
timeout: cdk.Duration.seconds(10),
runtime: EXECUTION_RUNTIME,
architecture: lambda.Architecture.ARM_64,
tracing: lambda.Tracing.ACTIVE,
environmentEncryption: props.kmsKey,
logGroup,
insightsVersion: props.cloudWatchInsights ?
LAMBDA_INSIGHTS_VERSION :
undefined,
environment: {
POWERTOOLS_SERVICE_NAME: reducer.name(),
POWERTOOLS_METRICS_NAMESPACE: NAMESPACE,
TABLE_NAME: this.table.tableName
},
bundling: {
minify: true,
externalModules: [
'@aws-sdk/client-dynamodb'
]
}
});
// Plug the SQS queue into the lambda function.
this.insertionProcessor.addEventSource(new sources.SqsEventSource(this.deduplicationQueue, {
batchSize: 10
}));
// Allow the function to insert items in the DynamoDB table.
this.table.grantWriteData(this.insertionProcessor);
///////////////////////////////////////////
/////// Counter Function //////
///////////////////////////////////////////
this.counterFn = new node.NodejsFunction(this, 'Counter', {
description: 'A function counting the number of events for a chain identifier.',
entry: path.resolve(__dirname, 'lambdas', 'counter', 'index.js'),
vpc: props.vpc,
timeout: cdk.Duration.seconds(10),
runtime: EXECUTION_RUNTIME,
architecture: lambda.Architecture.ARM_64,
tracing: lambda.Tracing.ACTIVE,
environmentEncryption: props.kmsKey,
logGroup,
insightsVersion: props.cloudWatchInsights ?
LAMBDA_INSIGHTS_VERSION :
undefined,
environment: {
POWERTOOLS_SERVICE_NAME: reducer.name(),
POWERTOOLS_METRICS_NAMESPACE: NAMESPACE,
TABLE_NAME: this.table.tableName
},
bundling: {
minify: true,
externalModules: [
'@aws-sdk/client-dynamodb'
]
}
});
// Function permissions.
this.table.grantWriteData(this.counterFn);
// Plug the DynamoDB stream into the lambda function.
this.counterFn.addEventSource(new sources.DynamoEventSource(this.table, {
startingPosition: lambda.StartingPosition.LATEST,
batchSize: 1,
parallelizationFactor: 10,
retryAttempts: props.maxRetry,
filters: [
lambda.FilterCriteria.filter({
eventName: lambda.FilterRule.isEqual('INSERT'),
dynamodb: {
Keys: {
sk: {
S: lambda.FilterRule.beginsWith('EVENT##')
}
}
}
})
]
}));
///////////////////////////////////////////
/////// Reducer Function //////
///////////////////////////////////////////
this.reducerFn = new node.NodejsFunction(this, 'Reducer', {
description: 'A function reducing events.',
entry: path.resolve(__dirname, 'lambdas', 'reducer', 'index.js'),
vpc: props.vpc,
timeout: cdk.Duration.seconds(30),
runtime: EXECUTION_RUNTIME,
architecture: lambda.Architecture.ARM_64,
tracing: lambda.Tracing.ACTIVE,
environmentEncryption: props.kmsKey,
logGroup,
insightsVersion: props.cloudWatchInsights ?
LAMBDA_INSIGHTS_VERSION :
undefined,
environment: {
POWERTOOLS_SERVICE_NAME: reducer.name(),
POWERTOOLS_METRICS_NAMESPACE: NAMESPACE,
SNS_TARGET_TOPIC: eventBus.topicArn,
PROCESSED_FILES_BUCKET: reducer.storage.id(),
TABLE_NAME: this.table.tableName
},
bundling: {
minify: true,
externalModules: [
'@aws-sdk/client-dynamodb',
'@aws-sdk/client-s3',
'@aws-sdk/client-sns'
]
}
});
// Function permissions.
this.table.grantReadWriteData(this.reducerFn);
reducer.storage.grantWrite(this.reducerFn);
eventBus.grantPublish(this.reducerFn);
// Plug the DynamoDB stream into the lambda function with a filter
// that evaluates the counter value to trigger the reduction.
this.reducerFn.addEventSource(new sources.DynamoEventSource(this.table, {
startingPosition: lambda.StartingPosition.LATEST,
batchSize: 1,
parallelizationFactor: 1,
retryAttempts: props.maxRetry,
filters: [
lambda.FilterCriteria.filter({
eventName: lambda.FilterRule.or(
'INSERT',
'MODIFY'
),
dynamodb: {
Keys: {
sk: {
S: lambda.FilterRule.isEqual('COUNTER')
}
},
NewImage: {
count: {
N: [`${eventCount}`]
}
}
}
})
]
}));
} | /**
* Provider constructor.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/reducer/src/impl/static-counter-strategy/index.ts#L79-L331 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.handler | async handler(event: DynamoDBStreamEvent, _: Context): Promise<any> {
try {
const e = CloudEvent.from(event.Records[0].dynamodb!.NewImage!.event.S!);
// Increment the event counter atomically.
await dynamoDb.send(new UpdateItemCommand({
TableName: TABLE_NAME,
Key: {
pk: { S: e.data().chainId() },
sk: { S: 'COUNTER' }
},
UpdateExpression: `
SET #count = if_not_exists(#count, :initialValue) + :inc
`,
ExpressionAttributeNames: {
'#count': 'count'
},
ExpressionAttributeValues: {
':initialValue': {
N: '0'
},
':inc': {
N: '1'
}
}
}));
} catch (error) {
logger.error(error as any);
throw error;
}
} | // eslint-disable-next-line @typescript-eslint/no-unused-vars | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/reducer/src/impl/static-counter-strategy/lambdas/counter/index.ts#L56-L86 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.handler | async handler(event: SQSEvent, _: Context): Promise<any> {
try {
const events = event.Records.map((record) => {
return (CloudEvent.from(record.body));
});
// Forward the received batch of events to the deduplication queue.
await sqs.send(new SendMessageBatchCommand({
QueueUrl: process.env.SQS_DEDUPLICATION_QUEUE_URL,
Entries: events.map((event) => {
return ({
Id: randomUUID(),
MessageBody: JSON.stringify(event),
MessageGroupId: event.data().chainId()
});
})
}));
} catch (error) {
logger.error(error as any);
throw error;
}
} | // eslint-disable-next-line @typescript-eslint/no-unused-vars | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/reducer/src/impl/static-counter-strategy/lambdas/deduplication/index.ts#L48-L69 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | getTtl | const getTtl = () => {
const SECONDS_IN_AN_HOUR = 60 * 60;
return (Math.round(Date.now() / 1000) + (48 * SECONDS_IN_AN_HOUR));
}; | /**
* This method computes the time-to-live value for events stored in DynamoDB.
* The purpose is to ensure that elements within the table are automatically
* deleted after a certain amount of time.
* @returns a time-to-live value for events stored in DynamoDB.
* @default 48 hours.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/reducer/src/impl/static-counter-strategy/lambdas/insertion/index.ts#L47-L50 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.handler | async handler(event: SQSEvent, _: Context): Promise<any> {
try {
await dynamoDb.send(new BatchWriteItemCommand({
RequestItems: {
[TABLE_NAME]: event.Records.map((record) => {
const event = CloudEvent.from(record.body);
const uuid = randomUUID();
return ({
PutRequest: {
Item: {
pk: { S: event.data().chainId() },
sk: { S: `EVENT##${new Date().toISOString()}##${uuid}` },
type: { S: 'event' },
event: { S: JSON.stringify(event) },
ttl: { N: getTtl().toString() }
}
}
})
})
}
}));
} catch (error) {
logger.error(error as any);
throw error;
}
} | // eslint-disable-next-line @typescript-eslint/no-unused-vars | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/reducer/src/impl/static-counter-strategy/lambdas/insertion/index.ts#L68-L93 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.handler | async handler(event: DynamoDBStreamEvent, _: Context): Promise<any> {
try {
// The primary key of the event.
const chainId = event.Records[0].dynamodb!.NewImage!.pk.S!;
// Retrieve all the events to reduce from the table.
const results = await dynamoDb.send(new QueryCommand({
TableName: TABLE_NAME,
KeyConditionExpression: '#pk = :pk AND begins_with(#sk, :prefix)',
ConsistentRead: true,
Limit: COUNTER_THRESHOLD,
ExpressionAttributeNames: {
'#pk': 'pk',
'#sk': 'sk'
},
ExpressionAttributeValues: {
':pk': { S: chainId },
':prefix': { S: 'EVENT##' }
}
}));
// Reduce the events.
await this.reduceEvents(chainId, results.Items?.map((item) => {
return (CloudEvent.from(JSON.parse(item.event.S as string)));
}) ?? []);
} catch (error) {
logger.error(error as any);
throw error;
}
} | // eslint-disable-next-line @typescript-eslint/no-unused-vars | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/reducer/src/impl/static-counter-strategy/lambdas/reducer/index.ts#L101-L130 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TimeWindowStrategyConstruct.constructor | constructor(scope: Construct, id: string, reducer: Reducer, props: ReducerProps) {
super(scope, id);
///////////////////////////////////////////
/////// Event Storage ///////
///////////////////////////////////////////
this.table = new dynamodb.Table(this, 'Table', {
partitionKey: {
name: 'pk',
type: dynamodb.AttributeType.STRING
},
sortKey: {
name: 'sk',
type: dynamodb.AttributeType.STRING
},
timeToLiveAttribute: 'ttl',
billingMode: dynamodb.BillingMode.PAY_PER_REQUEST,
stream: dynamodb.StreamViewType.NEW_IMAGE,
removalPolicy: cdk.RemovalPolicy.DESTROY,
encryptionKey: props.kmsKey
});
///////////////////////////////////////////
/////// De-duplication Queue ///////
///////////////////////////////////////////
// The SQS FIFO queue used to de-duplicate the events.
this.deduplicationQueue = new sqs.Queue(this, 'DeduplicationQueue', {
fifo: true,
contentBasedDeduplication: true,
encryptionMasterKey: props.kmsKey,
encryption: props.kmsKey ?
sqs.QueueEncryption.KMS :
sqs.QueueEncryption.SQS_MANAGED,
visibilityTimeout: props.queueVisibilityTimeout,
enforceSSL: true
});
///////////////////////////////////////////
////// De-duplication Function //////
///////////////////////////////////////////
this.deduplicationFn = new node.NodejsFunction(this, 'Deduplication', {
description: 'A function used to insert events in the de-duplication queue.',
entry: path.resolve(__dirname, 'lambdas', 'deduplication', 'index.js'),
vpc: props.vpc,
timeout: cdk.Duration.seconds(10),
runtime: EXECUTION_RUNTIME,
architecture: lambda.Architecture.ARM_64,
tracing: lambda.Tracing.ACTIVE,
environmentEncryption: props.kmsKey,
logGroup: reducer.getLogGroup(),
insightsVersion: props.cloudWatchInsights ?
LAMBDA_INSIGHTS_VERSION :
undefined,
environment: {
POWERTOOLS_SERVICE_NAME: reducer.name(),
POWERTOOLS_METRICS_NAMESPACE: NAMESPACE,
SQS_DEDUPLICATION_QUEUE_URL: this.deduplicationQueue.queueUrl
},
bundling: {
minify: true,
externalModules: [
'@aws-sdk/client-sqs'
]
}
});
// Allows the reducer to act as a `IGrantable`
// for other middlewares to grant the processing
// lambda permissions to access their resources.
reducer.grantPrincipal = this.deduplicationFn.grantPrincipal;
// Allow the function to consume messages from the input queue.
reducer.getQueue().grantConsumeMessages(this.deduplicationFn);
// Allow the function to send messages to the de-duplication queue.
this.deduplicationQueue.grantSendMessages(this.deduplicationFn);
// Plug the SQS queue into the deduplication function.
this.deduplicationFn.addEventSource(new sources.SqsEventSource(reducer.getQueue(), {
batchSize: 10,
maxBatchingWindow: props.batchingWindow
}));
///////////////////////////////////////////
/////// Insertion Function ///////
///////////////////////////////////////////
this.insertionProcessor = new node.NodejsFunction(this, 'Compute', {
description: 'A function inserting events in DynamoDB.',
entry: path.resolve(__dirname, 'lambdas', 'insertion', 'index.js'),
vpc: props.vpc,
timeout: cdk.Duration.seconds(10),
runtime: EXECUTION_RUNTIME,
architecture: lambda.Architecture.ARM_64,
tracing: lambda.Tracing.ACTIVE,
environmentEncryption: props.kmsKey,
logGroup: reducer.getLogGroup(),
insightsVersion: props.cloudWatchInsights ?
LAMBDA_INSIGHTS_VERSION :
undefined,
environment: {
POWERTOOLS_SERVICE_NAME: reducer.name(),
POWERTOOLS_METRICS_NAMESPACE: NAMESPACE,
TABLE_NAME: this.table.tableName
},
bundling: {
minify: true,
externalModules: [
'@aws-sdk/client-dynamodb'
]
}
});
// Plug the SQS queue into the lambda function.
this.insertionProcessor.addEventSource(new sources.SqsEventSource(this.deduplicationQueue, {
batchSize: 10
}));
// Allow the function to insert items in the DynamoDB table.
this.table.grantWriteData(this.insertionProcessor);
///////////////////////////////////////////
/////// Stream Consumer ///////
///////////////////////////////////////////
this.streamConsumer = new node.NodejsFunction(this, 'StreamConsumer', {
description: 'A function consuming events from the DynamoDB stream.',
entry: path.resolve(__dirname, 'lambdas', 'stream-consumer', 'index.js'),
vpc: props.vpc,
timeout: cdk.Duration.minutes(1),
runtime: EXECUTION_RUNTIME,
architecture: lambda.Architecture.ARM_64,
tracing: lambda.Tracing.ACTIVE,
environmentEncryption: props.kmsKey,
logGroup: reducer.getLogGroup(),
insightsVersion: props.cloudWatchInsights ?
LAMBDA_INSIGHTS_VERSION :
undefined,
environment: {
POWERTOOLS_SERVICE_NAME: reducer.name(),
POWERTOOLS_METRICS_NAMESPACE: NAMESPACE,
TABLE_NAME: this.table.tableName
},
bundling: {
minify: true,
externalModules: [
'@aws-sdk/client-dynamodb'
]
}
});
// Function permissions.
this.table.grantStreamRead(this.streamConsumer);
this.table.grantReadWriteData(this.streamConsumer);
// Plug the DynamoDB stream into the lambda function.
this.streamConsumer.addEventSource(new sources.DynamoEventSource(this.table, {
startingPosition: lambda.StartingPosition.LATEST,
batchSize: 50,
parallelizationFactor: 1,
retryAttempts: props.maxRetry,
filters: [
lambda.FilterCriteria.filter({
dynamodb: {
NewImage: {
type: { S: lambda.FilterRule.isEqual('event') }
}
}
})
]
}));
///////////////////////////////////////////
/////// Reducer Function //////
///////////////////////////////////////////
this.reducerFn = new node.NodejsFunction(this, 'Reducer', {
description: 'A function reducing events.',
entry: path.resolve(__dirname, 'lambdas', 'reducer', 'index.js'),
vpc: props.vpc,
timeout: cdk.Duration.seconds(30),
runtime: EXECUTION_RUNTIME,
architecture: lambda.Architecture.ARM_64,
tracing: lambda.Tracing.ACTIVE,
environmentEncryption: props.kmsKey,
logGroup: reducer.getLogGroup(),
insightsVersion: props.cloudWatchInsights ?
LAMBDA_INSIGHTS_VERSION :
undefined,
environment: {
POWERTOOLS_SERVICE_NAME: reducer.name(),
POWERTOOLS_METRICS_NAMESPACE: NAMESPACE,
SNS_TARGET_TOPIC: reducer.getEventBus().topicArn,
PROCESSED_FILES_BUCKET: reducer.storage.id(),
TABLE_NAME: this.table.tableName
},
bundling: {
minify: true,
externalModules: [
'@aws-sdk/client-scheduler',
'@aws-sdk/client-dynamodb',
'@aws-sdk/client-s3'
]
}
});
// Function permissions.
this.table.grantReadWriteData(this.reducerFn);
reducer.storage.grantWrite(this.reducerFn);
reducer.getEventBus().grantPublish(this.reducerFn);
///////////////////////////////////////////
/////// Scheduler Function //////
///////////////////////////////////////////
// The IAM role allowing the scheduler to invoke the reducer function.
const role = new iam.Role(this, 'ReducerInvocationRole', {
assumedBy: new iam.ServicePrincipal('scheduler.amazonaws.com')
});
this.reducerFn.grantInvoke(role);
// The scheduler function.
this.schedulerFn = new node.NodejsFunction(this, 'Scheduler', {
description: 'A function scheduling reduce operations.',
entry: path.resolve(__dirname, 'lambdas', 'scheduler', 'index.js'),
vpc: props.vpc,
timeout: cdk.Duration.minutes(1),
runtime: EXECUTION_RUNTIME,
architecture: lambda.Architecture.ARM_64,
tracing: lambda.Tracing.ACTIVE,
environmentEncryption: props.kmsKey,
logGroup: reducer.getLogGroup(),
insightsVersion: props.cloudWatchInsights ?
LAMBDA_INSIGHTS_VERSION :
undefined,
environment: {
POWERTOOLS_SERVICE_NAME: reducer.name(),
POWERTOOLS_METRICS_NAMESPACE: NAMESPACE,
REDUCER_FUNCTION_ARN: this.reducerFn.functionArn,
INVOCATION_ROLE_ARN: role.roleArn,
REDUCER_STRATEGY: JSON.stringify(
props.strategy.compile()
)
},
bundling: {
minify: true,
externalModules: [
'@aws-sdk/client-scheduler'
]
}
});
// Function permissions.
this.table.grantStreamRead(this.streamConsumer);
this.table.grantWriteData(this.streamConsumer);
// Allow the scheduler to create schedules.
this.schedulerFn.addToRolePolicy(new iam.PolicyStatement({
actions: [
'scheduler:CreateSchedule'
],
resources: ['*']
}));
// Allow the scheduler to pass the IAM role to the scheduler service.
this.schedulerFn.addToRolePolicy(new iam.PolicyStatement({
actions: [
'iam:PassRole'
],
resources: [role.roleArn]
}));
// Plug the DynamoDB stream into the lambda function.
this.schedulerFn.addEventSource(new sources.DynamoEventSource(this.table, {
startingPosition: lambda.StartingPosition.LATEST,
batchSize: 10,
parallelizationFactor: 1,
retryAttempts: props.maxRetry,
reportBatchItemFailures: true,
filters: [
lambda.FilterCriteria.filter({
dynamodb: {
NewImage: {
type: { S: lambda.FilterRule.isEqual('status') },
status: { S: lambda.FilterRule.isEqual('pending') }
}
}
})
]
}));
} | /**
* Provider constructor.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/reducer/src/impl/time-window-strategy/index.ts#L85-L378 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.handler | async handler(event: SQSEvent, _: Context): Promise<any> {
try {
const events = event.Records.map((record) => {
return (CloudEvent.from(record.body));
});
// Forward the received batch of events to the deduplication queue.
await sqs.send(new SendMessageBatchCommand({
QueueUrl: process.env.SQS_DEDUPLICATION_QUEUE_URL,
Entries: events.map((event) => {
return ({
Id: randomUUID(),
MessageBody: JSON.stringify(event),
MessageGroupId: event.data().chainId()
});
})
}));
} catch (error) {
logger.error(error as any);
throw error;
}
} | // eslint-disable-next-line @typescript-eslint/no-unused-vars | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/reducer/src/impl/time-window-strategy/lambdas/deduplication/index.ts#L48-L69 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | getTtl | const getTtl = () => {
const SECONDS_IN_AN_HOUR = 60 * 60;
return (Math.round(Date.now() / 1000) + (48 * SECONDS_IN_AN_HOUR));
}; | /**
* This method computes the time-to-live value for events stored in DynamoDB.
* The purpose is to ensure that elements within the table are automatically
* deleted after a certain amount of time.
* @returns a time-to-live value for events stored in DynamoDB.
* @default 48 hours.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/reducer/src/impl/time-window-strategy/lambdas/insertion/index.ts#L44-L47 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.handler | async handler(event: SQSEvent, _: Context): Promise<any> {
try {
await dynamoDb.send(new BatchWriteItemCommand({
RequestItems: {
[TABLE_NAME]: event.Records.map((record) => {
const event = CloudEvent.from(record.body);
const uuid = randomUUID();
return ({
PutRequest: {
Item: {
pk: { S: event.data().chainId() },
sk: { S: `EVENT##${new Date().toISOString()}##${uuid}` },
type: { S: 'event' },
event: { S: JSON.stringify(event) },
ttl: { N: getTtl().toString() }
}
}
})
})
}
}));
} catch (error) {
logger.error(error as any);
throw error;
}
} | // eslint-disable-next-line @typescript-eslint/no-unused-vars | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/reducer/src/impl/time-window-strategy/lambdas/insertion/index.ts#L65-L90 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | getTtl | const getTtl = () => {
const SECONDS_IN_AN_HOUR = 60 * 60;
return (Math.round(Date.now() / 1000) + (48 * SECONDS_IN_AN_HOUR));
}; | /**
* This method computes the time-to-live value for events stored in DynamoDB.
* The purpose is to ensure that elements within the table are automatically
* deleted after a certain amount of time.
* @returns a time-to-live value for events stored in DynamoDB.
* @default 48 hours.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/reducer/src/impl/time-window-strategy/lambdas/reducer/index.ts#L57-L60 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.handler | async handler(event: any, _: Context): Promise<any> {
try {
// Retrieve all events matching the `chainId`, and where
// the sort key starts with `EVENT##`.
const results = await dynamoDb.send(new QueryCommand({
TableName: TABLE_NAME,
KeyConditionExpression: '#pk = :pk AND begins_with(#sk, :prefix)',
ExpressionAttributeNames: {
'#pk': 'pk',
'#sk': 'sk'
},
ExpressionAttributeValues: {
':pk': { S: event.chainId },
':prefix': { S: 'EVENT##' }
}
}));
// Parse the events and reduce them in a single event.
const events = results.Items?.map((item) => {
return (CloudEvent.from(JSON.parse(item.event.S as string)));
});
if (events && events?.length > 0) {
await this.reduceEvents(event.chainId, events);
}
// Set the status to `processed` for the given `chainId`.
await dynamoDb.send(new PutItemCommand({
TableName: TABLE_NAME,
Item: {
pk: { S: event.chainId },
sk: { S: 'STATUS' },
type: { S: 'status' },
status: { S: 'processed' },
ttl: { N: getTtl().toString() }
}
}));
} catch (error) {
logger.error(error as any);
throw error;
}
} | // eslint-disable-next-line @typescript-eslint/no-unused-vars | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/reducer/src/impl/time-window-strategy/lambdas/reducer/index.ts#L113-L153 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | getNextTime | const getNextTime = (
offset = REDUCER_STRATEGY.timeWindow,
jitter = REDUCER_STRATEGY.jitter ?? 0
) => {
const value = (offset + Math.floor(Math.random() * jitter)) * 1000;
return (new Date(Date.now() + value)
.toISOString()
.substring(0, 19)
);
}; | /**
* A helper function that generates a date representing the next time
* an event should be scheduled. It generates that time based on the
* given `offset` and adds a random delta to it between 0 and `maxDelta`.
* @param offset the time offset in seconds to wait before scheduling
* the reduce function.
* @param jitter a jitter value in seconds to apply to the offset.
* @returns the date at which the next event should be scheduled.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/reducer/src/impl/time-window-strategy/lambdas/scheduler/index.ts#L57-L66 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.processRecord | async processRecord(record: DynamoDBRecord) {
const chainId = record.dynamodb?.NewImage?.pk?.S;
if (chainId) {
await scheduler.send(new CreateScheduleCommand({
Name: randomUUID(),
ScheduleExpression: `at(${getNextTime()})`,
ActionAfterCompletion: 'DELETE',
FlexibleTimeWindow: {
Mode: 'OFF'
},
Target: {
RoleArn: process.env.INVOCATION_ROLE_ARN,
Arn: process.env.REDUCER_FUNCTION_ARN,
Input: JSON.stringify({ chainId })
}
}));
}
} | /**
* Creates a new schedule to run the reducer function
* in response to a new pending status created for a
* specific `chainId` in DynamoDB.
* @param record the DynamoDB record to process.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/reducer/src/impl/time-window-strategy/lambdas/scheduler/index.ts#L82-L100 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.handler | async handler(event: any, _: Context): Promise<any> {
return (await processPartialResponse(event, this.processRecord.bind(this), processor));
} | // eslint-disable-next-line @typescript-eslint/no-unused-vars | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/reducer/src/impl/time-window-strategy/lambdas/scheduler/index.ts#L110-L112 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | groupBy | const groupBy = <T, K extends keyof any>(arr: T[], key: (i: T) => K) =>
arr.reduce((groups, item) => {
(groups[key(item)] ||= []).push(item);
return groups;
}, {} as Record<K, T[]>
); | /**
* Group an array of elements by a given key.
* @param arr the array to group.
* @param key the key to group by.
* @returns a record mapping the given key to the
* elements of the array.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/reducer/src/impl/time-window-strategy/lambdas/stream-consumer/index.ts#L43-L48 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.handler | async handler(event: any, _: Context): Promise<any> {
try {
// Group all records by `chainId`.
const records = groupBy(event.Records, (record: any) => {
return (CloudEvent
.from(record.dynamodb.NewImage.event.S)
.data()
.chainId()
);
});
// For each `chainId` create a new entry with a sort key of `STATUS`
// if does not exist. We ignore the error if the sort key for that
// `chainId` already exists.
for (const chainId in records) {
try {
await dynamoDb.send(new PutItemCommand({
TableName: TABLE_NAME,
Item: {
pk: { S: chainId },
sk: { S: 'STATUS' },
type: { S: 'status' },
status: { S: 'pending' }
},
ConditionExpression: 'attribute_not_exists(sk)'
}));
} catch (error: any) {
if (error.name !== 'ConditionalCheckFailedException') {
// A status already exists for this partition key.
throw error;
}
}
}
} catch (error) {
logger.error(error as any);
throw error;
}
} | // eslint-disable-next-line @typescript-eslint/no-unused-vars | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/reducer/src/impl/time-window-strategy/lambdas/stream-consumer/index.ts#L66-L103 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TransformBuilder.withTransformExpression | public withTransformExpression(expression: TransformExpression | lambda.IFunction) {
this.providerProps.expression = expression;
return (this);
} | /**
* Sets a function evaluated in the cloud to transform
* input documents.
* @param expression the transform expression.
* @returns the builder instance.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/transform/src/index.ts#L89-L92 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TransformBuilder.build | public build(): Transform {
return (new Transform(
this.scope,
this.identifier, {
...this.providerProps as TransformProps,
...this.props
}
));
} | /**
* @returns a new instance of the `Transform`
* service constructed with the given parameters.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/transform/src/index.ts#L98-L106 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Transform.constructor | constructor(scope: Construct, id: string, props: TransformProps) {
super(scope, id, description, {
...props,
queueVisibilityTimeout: cdk.Duration.seconds(
3 * PROCESSING_TIMEOUT.toSeconds()
)
});
// Validating the properties.
props = this.parse(TransformPropsSchema, props);
///////////////////////////////////////////
//////// Processing Storage ///////
///////////////////////////////////////////
this.storage = new CacheStorage(this, 'Storage', {
encryptionKey: props.kmsKey
});
///////////////////////////////////////////
////// Transform Expression //////
///////////////////////////////////////////
let expression: string;
// If the transform expression is a Lambda function,
// we give it the permission to read the processed
// documents generated by the previous middlewares.
if (props.expression instanceof lambda.Function) {
expression = props.expression.functionArn;
this.grantReadProcessedDocuments(props.expression);
// If it is a function expression, we serialize it for the
// processing function to evaluate it.
} else if (typeof props.expression === 'function') {
expression = this.serializeFn(props.expression);
// Otherwise, we throw an error.
} else {
throw new Error(`
Invalid or transform expression in transform middleware.
`);
}
///////////////////////////////////////////
/////// Processing Function ///////
///////////////////////////////////////////
this.eventProcessor = new node.NodejsFunction(this, 'Compute', {
description: 'A function evaluating a transform expression.',
entry: path.resolve(__dirname, 'lambdas', 'transform', 'index.js'),
vpc: props.vpc,
memorySize: props.maxMemorySize ?? DEFAULT_MEMORY_SIZE,
timeout: PROCESSING_TIMEOUT,
runtime: EXECUTION_RUNTIME,
architecture: lambda.Architecture.ARM_64,
tracing: lambda.Tracing.ACTIVE,
environmentEncryption: props.kmsKey,
logGroup: this.logGroup,
insightsVersion: props.cloudWatchInsights ?
LAMBDA_INSIGHTS_VERSION :
undefined,
environment: {
POWERTOOLS_SERVICE_NAME: description.name,
POWERTOOLS_METRICS_NAMESPACE: NAMESPACE,
SNS_TARGET_TOPIC: this.eventBus.topicArn,
PROCESSED_FILES_BUCKET: this.storage.id(),
LAKECHAIN_CACHE_STORAGE: props.cacheStorage.id(),
TRANSFORM_EXPRESSION_TYPE: props.expression instanceof lambda.Function ?
'lambda' :
'expression',
TRANSFORM_EXPRESSION: expression,
TRANSFORM_EXPRESSION_SYMBOL
},
bundling: {
minify: true,
externalModules: [
'@aws-sdk/client-s3',
'@aws-sdk/client-sns'
]
}
});
// Allows this construct to act as a `IGrantable`
// for other middlewares to grant the processing
// lambda permissions to access their resources.
this.grantPrincipal = this.eventProcessor.grantPrincipal;
// If the expression is a lambda function, grant
// the processing lambda the permission to invoke it.
if (props.expression instanceof lambda.Function) {
props.expression.grantInvoke(this.eventProcessor);
}
// Allow the function to publish to the SNS topic.
this.eventBus.grantPublish(this.eventProcessor);
// Allow the function to write to the S3 bucket.
this.storage.grantReadWrite(this.eventProcessor);
// Plug the SQS queue into the lambda function.
this.eventProcessor.addEventSource(new sources.SqsEventSource(this.eventQueue, {
batchSize: props.batchSize ?? 10,
maxBatchingWindow: props.batchingWindow,
reportBatchItemFailures: true
}));
super.bind();
} | /**
* Provider constructor.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/transform/src/index.ts#L133-L241 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Transform.serializeFn | private serializeFn(fn: TransformExpression, opts?: esbuild.TransformOptions): string {
const res = esbuild.transformSync(`const ${TRANSFORM_EXPRESSION_SYMBOL} = ${serialize(fn)}\n`, {
minify: true,
...opts
});
return (res.code);
} | /**
* A helper used to serialize the different types of JavaScript
* functions that the user can provide (e.g functions, arrow functions,
* async functions, etc.) into a string.
* This function also uses `esbuild` to validate the syntax of the
* provided function and minify it.
* @param fn the function to serialize.
* @param opts the esbuild transform options.
* @returns the serialized function.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/transform/src/index.ts#L253-L259 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Transform.grantReadProcessedDocuments | grantReadProcessedDocuments(grantee: iam.IGrantable): iam.Grant {
// Since this middleware simply passes through the data
// from the previous middleware, we grant any subsequent
// middlewares in the pipeline to have read access to the
// data of all source middlewares.
for (const source of this.sources) {
source.grantReadProcessedDocuments(grantee);
}
// We also grant the grantee the permission to read from
// the middleware storage containing transformed documents.
this.storage.grantRead(grantee);
return ({} as iam.Grant);
} | /**
* Allows a grantee to read from the processed documents
* generated by this middleware.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/transform/src/index.ts#L265-L277 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Transform.supportedInputTypes | supportedInputTypes(): string[] {
return ([
'*/*'
]);
} | /**
* @returns an array of mime-types supported as input
* type by the data producer.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/transform/src/index.ts#L283-L287 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Transform.supportedOutputTypes | supportedOutputTypes(): string[] {
return ([
'*/*'
]);
} | /**
* @returns an array of mime-types supported as output
* type by the data producer.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/transform/src/index.ts#L293-L297 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Transform.supportedComputeTypes | supportedComputeTypes(): ComputeType[] {
return ([
ComputeType.CPU
]);
} | /**
* @returns the supported compute types by a given
* middleware.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/transform/src/index.ts#L303-L307 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Transform.conditional | conditional() {
return (super
.conditional()
.and(when('type').equals('document-created'))
);
} | /**
* @returns the middleware conditional statement defining
* in which conditions this middleware should be executed.
* In this case, we want the middleware to only be invoked
* when the document mime-type is supported, and the event
* type is `document-created`.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/transform/src/index.ts#L316-L321 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | evaluateLambda | const evaluateLambda = async (event: sdk.CloudEvent[]): Promise<sdk.CloudEvent[]> => {
const res = await lambda.send(new InvokeCommand({
FunctionName: TRANSFORM_EXPRESSION,
Payload: JSON.stringify(event.map((e) => e.toJSON()))
}));
// If the function failed to execute, we throw an error.
if (res.FunctionError) {
throw new Error(res.FunctionError);
}
// Parse the result of the lambda function into a an array of cloud events.
const payload = JSON.parse(
new TextDecoder().decode(res.Payload as Uint8Array)
);
return (payload.map((e: any) => sdk.CloudEvent.from(e)));
}; | /**
* Synchronously invokes the transform lambda function and
* returns its result.
* @param event the events to process.
* @returns a promise to an array of output events.
* @throws an error if the conditional function failed to execute.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/transform/src/lambdas/transform/evaluate.ts#L35-L52 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | evaluateExpression | const evaluateExpression = async (events: sdk.CloudEvent[], opts?: RunningCodeOptions): Promise<sdk.CloudEvent[] | sdk.CloudEvent> => {
const context = createContext({
console,
require,
setTimeout,
clearTimeout,
process,
Buffer,
events,
sdk,
env: {
STORAGE_BUCKET,
LAKECHAIN_CACHE_STORAGE
}
});
// Run the expression within a VM.
const res = runInContext(`${TRANSFORM_EXPRESSION}\n${TRANSFORM_EXPRESSION_SYMBOL}(events, sdk, env);`, context, {
...opts
});
// If the expression did not return a promise, we throw an error.
if (!res.then) {
throw new Error('Invalid transform expression, a promise was expected.');
}
return (res);
}; | /**
* Evaluates the given transform expression and returns
* its result.
* @param event the events to process.
* @param opts execution options.
* @returns a promise to an array of output events.
* @throws an error if the conditional expression is invalid.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/transform/src/lambdas/transform/evaluate.ts#L62-L89 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.processEvents | async processEvents(events: CloudEvent[], originalEvent: CloudEvent) {
const results = await evaluate(events);
if (originalEvent.data().document().mimeType() === 'application/cloudevents+json') {
if (Array.isArray(results)) {
await nextAsync(
await this.aggregate(results, originalEvent)
);
} else {
await nextAsync(results);
}
} else {
// If the event is not aggregated, we publish the results produced
// by the transform expression to the next middlewares.
if (Array.isArray(results)) {
for (const event of results) {
await nextAsync(event);
}
} else {
await nextAsync(results);
}
}
} | /**
* Evaluates the transform expression with the
* given input events.
* @param events the input events to transform.
* @param originalEvent the original event that triggered the transformation.
* @returns a promise with the transformed events.
* @throws if the condition cannot be evaluated.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/transform/src/lambdas/transform/index.ts#L100-L122 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.processEvent | async processEvent(event: CloudEvent) {
const document = event.data().document();
let events: CloudEvent[] = [];
if (document.mimeType() === 'application/cloudevents+json') {
const data = JSON.parse((await document
.data()
.asBuffer())
.toString('utf-8')
);
events = data.map((event: string) => CloudEvent.from(event));
} else {
events = [event];
}
return (this.processEvents(events, event));
} | /**
* Handles the given input event. If the event is an aggregated
* event, it will be parsed into individual events and passed
* to the `processEvents` method.
* @param event the input event to process.
* @returns a promise with the processed event.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/transform/src/lambdas/transform/index.ts#L131-L147 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.handler | async handler(event: SQSEvent, _: Context): Promise<SQSBatchResponse> {
return (await processPartialResponse(
event,
(record: SQSRecord) => this.processEvent(
CloudEvent.from(JSON.parse(record.body))
),
processor
));
} | // eslint-disable-next-line @typescript-eslint/no-unused-vars | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/flow-control/transform/src/lambdas/transform/index.ts#L157-L165 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TitanImageGeneratorBuilder.withImageModel | public withImageModel(model: TitanImageModel) {
this.middlewareProps.imageModel = model;
return (this);
} | /**
* Sets the Titan image model to use for generating images.
* @param model the Titan image model to use.
* @returns the current builder instance.
* @default TitanImageModel.TITAN_IMAGE_GENERATOR_V2
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/index.ts#L86-L89 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TitanImageGeneratorBuilder.withTask | public withTask(task: TextToImageTask
| ImageInpaintingTask
| ImageOutpaintingTask
| ImageVariationTask
| BackgroundRemovalTask
| ColorGuidedGenerationTask) {
this.middlewareProps.task = task;
return (this);
} | /**
* Sets the parameters to execute by the image model.
* @param task the task to execute by the image model.
* @returns the current builder instance.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/index.ts#L96-L104 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TitanImageGeneratorBuilder.withRegion | public withRegion(region: string) {
this.middlewareProps.region = region;
return (this);
} | /**
* Sets the AWS region in which the model
* will be invoked.
* @param region the AWS region in which the model
* will be invoked.
* @returns the current builder instance.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/index.ts#L113-L116 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TitanImageGeneratorBuilder.build | public build(): TitanImageGenerator {
return (new TitanImageGenerator(
this.scope,
this.identifier, {
...this.middlewareProps as TitanImageGeneratorProps,
...this.props
}
));
} | /**
* @returns a new instance of the `TitanImageGenerator`
* service constructed with the given parameters.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/index.ts#L122-L130 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TitanImageGenerator.constructor | constructor(scope: Construct, id: string, private props: TitanImageGeneratorProps) {
super(scope, id, description, {
...props,
queueVisibilityTimeout: cdk.Duration.seconds(
2 * PROCESSING_TIMEOUT.toSeconds()
)
});
// Validate the properties.
this.props = this.parse(TitanImageGeneratorPropsSchema, props);
///////////////////////////////////////////
//////// Processing Storage ///////
///////////////////////////////////////////
this.storage = new CacheStorage(this, 'Storage', {
encryptionKey: this.props.kmsKey
});
///////////////////////////////////////////
////// Middleware Event Handler ////
///////////////////////////////////////////
this.eventProcessor = new node.NodejsFunction(this, 'Compute', {
description: 'Generates images using Amazon Titan models on Amazon Bedrock.',
entry: path.resolve(__dirname, 'lambdas', 'handler', 'index.js'),
vpc: this.props.vpc,
memorySize: this.props.maxMemorySize ?? DEFAULT_MEMORY_SIZE,
timeout: PROCESSING_TIMEOUT,
runtime: EXECUTION_RUNTIME,
architecture: lambda.Architecture.ARM_64,
tracing: lambda.Tracing.ACTIVE,
environmentEncryption: this.props.kmsKey,
logGroup: this.logGroup,
insightsVersion: this.props.cloudWatchInsights ?
LAMBDA_INSIGHTS_VERSION :
undefined,
environment: {
POWERTOOLS_SERVICE_NAME: description.name,
POWERTOOLS_METRICS_NAMESPACE: NAMESPACE,
SNS_TARGET_TOPIC: this.eventBus.topicArn,
PROCESSED_FILES_BUCKET: this.storage.id(),
IMAGE_MODEL: this.props.imageModel.name,
BEDROCK_REGION: this.props.region ?? '',
TASK: JSON.stringify(this.props.task)
},
bundling: {
minify: true,
externalModules: [
'@aws-sdk/client-s3',
'@aws-sdk/client-sns',
'@aws-sdk/client-bedrock-runtime'
]
}
});
// Allows this construct to act as a `IGrantable`
// for other middlewares to grant the processing
// lambda permissions to access their resources.
this.grantPrincipal = this.eventProcessor.grantPrincipal;
// Plug the SQS queue into the lambda function.
this.eventProcessor.addEventSource(new sources.SqsEventSource(this.eventQueue, {
batchSize: this.props.batchSize ?? 1,
maxConcurrency: this.props.maxConcurrency ?? 2,
reportBatchItemFailures: true
}));
// Allow access to the Bedrock API.
this.eventProcessor.addToRolePolicy(new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: [
'bedrock:InvokeModel'
],
resources: [
`arn:${cdk.Aws.PARTITION}:bedrock:${this.props.region ?? cdk.Aws.REGION}::foundation-model/${this.props.imageModel.name}`,
]
}));
// Grant the compute type permissions to
// write to the post-processing bucket.
this.storage.grantWrite(this.grantPrincipal);
// Grant the compute type permissions to
// publish to the SNS topic.
this.eventBus.grantPublish(this.grantPrincipal);
super.bind();
} | /**
* Construct constructor.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/index.ts#L157-L245 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TitanImageGenerator.grantReadProcessedDocuments | grantReadProcessedDocuments(grantee: iam.IGrantable): iam.Grant {
return (this.storage.grantRead(grantee));
} | /**
* Allows a grantee to read from the processed documents
* generated by this middleware.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/index.ts#L251-L253 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TitanImageGenerator.supportedInputTypes | supportedInputTypes(): string[] {
return ([
'text/plain',
'image/png',
'image/jpeg',
'application/json+scheduler'
]);
} | /**
* @returns an array of mime-types supported as input
* type by this middleware.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/index.ts#L259-L266 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TitanImageGenerator.supportedOutputTypes | supportedOutputTypes(): string[] {
return ([
'image/png'
]);
} | /**
* @returns an array of mime-types supported as output
* type by the data producer.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/index.ts#L272-L276 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TitanImageGenerator.supportedComputeTypes | supportedComputeTypes(): ComputeType[] {
return ([
ComputeType.CPU
]);
} | /**
* @returns the supported compute types by a given
* middleware.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/index.ts#L282-L286 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TitanImageGenerator.conditional | conditional() {
return (super
.conditional()
.and(when('type').equals('document-created'))
);
} | /**
* @returns the middleware conditional statement defining
* in which conditions this middleware should be executed.
* In this case, we want the middleware to only be invoked
* when the document mime-type is supported, and the event
* type is `document-created`.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/index.ts#L295-L300 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ImageGenerationParametersBuilder.withNumberOfImages | public withNumberOfImages(numberOfImages: number) {
this.props.numberOfImages = numberOfImages;
return (this);
} | /**
* Sets the number of images to generate.
* @param numberOfImages the number of images to generate.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/image-generation-props.ts#L100-L103 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ImageGenerationParametersBuilder.withQuality | public withQuality(quality: 'standard' | 'premium') {
this.props.quality = quality;
return (this);
} | /**
* Sets the quality of the generated images.
* @param quality the quality of the generated images.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/image-generation-props.ts#L109-L112 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ImageGenerationParametersBuilder.withHeight | public withHeight(height: number) {
this.props.height = height;
return (this);
} | /**
* Sets the desired height of the generated images.
* @param height the desired height of the generated images.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/image-generation-props.ts#L118-L121 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ImageGenerationParametersBuilder.withWidth | public withWidth(width: number) {
this.props.width = width;
return (this);
} | /**
* Sets the desired width of the generated images.
* @param width the desired width of the generated images.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/image-generation-props.ts#L127-L130 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ImageGenerationParametersBuilder.withCfgScale | public withCfgScale(cfgScale: number) {
this.props.cfgScale = cfgScale;
return (this);
} | /**
* Sets the scale of the configuration.
* @param cfgScale the scale of the configuration.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/image-generation-props.ts#L136-L139 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ImageGenerationParametersBuilder.withSeed | public withSeed(seed: number) {
this.props.seed = seed;
return (this);
} | /**
* Sets the seed for the generation.
* @param seed the seed for the generation.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/image-generation-props.ts#L145-L148 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ImageGenerationParametersBuilder.build | public build(): ImageGenerationParameters {
return (ImageGenerationParameters.from(this.props));
} | /**
* @returns a new instance of the `ImageGenerationParameters`
* service constructed with the given parameters.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/image-generation-props.ts#L154-L156 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ImageGenerationParameters.constructor | constructor(public props: ImageGenerationParametersProps) {} | /**
* Image generation parameters constructor.
* @param props the properties associated with the image generation.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/image-generation-props.ts#L173-L173 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ImageGenerationParameters.numberOfImages | public numberOfImages() {
return (this.props.numberOfImages);
} | /**
* @returns the number of images to generate.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/image-generation-props.ts#L178-L180 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ImageGenerationParameters.quality | public quality() {
return (this.props.quality);
} | /**
* @returns the quality of the generated images.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/image-generation-props.ts#L185-L187 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ImageGenerationParameters.height | public height() {
return (this.props.height);
} | /**
* @returns the desired height of the generated images.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/image-generation-props.ts#L192-L194 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ImageGenerationParameters.width | public width() {
return (this.props.width);
} | /**
* @returns the desired width of the generated images.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/image-generation-props.ts#L199-L201 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ImageGenerationParameters.cfgScale | public cfgScale() {
return (this.props.cfgScale);
} | /**
* @returns the scale of the configuration.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/image-generation-props.ts#L206-L208 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ImageGenerationParameters.seed | public seed() {
return (this.props.seed);
} | /**
* @returns the seed for the generation.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/image-generation-props.ts#L213-L215 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ImageGenerationParameters.from | public static from(data: any): ImageGenerationParameters {
return (new ImageGenerationParameters(ImageGenerationParametersSchema.parse(data)));
} | /**
* @returns a new instance of the `ImageGenerationParameters`.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/image-generation-props.ts#L220-L222 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ImageGenerationParameters.toJSON | public toJSON() {
return (this.props);
} | /**
* @returns the JSON representation of the image generation parameters.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/image-generation-props.ts#L227-L229 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TitanImageModel.of | public static of(name: string) {
return (new TitanImageModel(name));
} | /**
* Create a new instance of the `TitanImageModel`
* by name.
* @param name the name of the model.
* @returns a new instance of the `TitanImageModel`.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/image-model.ts#L40-L42 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TitanImageModel.constructor | constructor(public name: string) {} | /**
* `TitanImageModel` constructor.
* @param name the name of the model.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/image-model.ts#L48-L48 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | BackgroundRemovalTaskBuilder.withImage | public withImage(image: dsl.IReference<any>) {
this.props.image = image;
return (this);
} | /**
* @param image sets a reference to the image to use.
* @returns the current builder instance.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/tasks/background-removal-task.ts#L66-L69 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | BackgroundRemovalTaskBuilder.withImageGenerationParameters | public withImageGenerationParameters(imageGenerationParameters: ImageGenerationParameters) {
this.props.imageGenerationParameters = imageGenerationParameters;
return (this);
} | /**
* @param imageGenerationParameters the image generation parameters.
* @returns the current builder instance.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/tasks/background-removal-task.ts#L75-L78 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | BackgroundRemovalTaskBuilder.build | public build(): BackgroundRemovalTask {
return (BackgroundRemovalTask.from(this.props));
} | /**
* @returns a new instance of the `BackgroundRemovalTask`
* service constructed with the given parameters.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/tasks/background-removal-task.ts#L84-L86 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | BackgroundRemovalTask.constructor | constructor(public props: BackgroundRemovalProps) {} | /**
* Creates a new instance of the `BackgroundRemovalTask` class.
* @param props the task properties.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/tasks/background-removal-task.ts#L103-L103 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | BackgroundRemovalTask.image | public image() {
return (this.props.image);
} | /**
* @returns the image to remove the background from.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/tasks/background-removal-task.ts#L108-L110 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | BackgroundRemovalTask.imageGenerationParameters | public imageGenerationParameters() {
return (this.props.imageGenerationParameters);
} | /**
* @returns the image generation parameters.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/tasks/background-removal-task.ts#L115-L117 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | BackgroundRemovalTask.from | public static from(props: any) {
return (new BackgroundRemovalTask(BackgroundRemovalTaskPropsSchema.parse(props)));
} | /**
* Creates a new instance of the `BackgroundRemovalTask` class.
* @param props the task properties.
* @returns a new instance of the `BackgroundRemovalTask` class.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/tasks/background-removal-task.ts#L124-L126 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | BackgroundRemovalTask.toJSON | public toJSON() {
return (this.props);
} | /**
* @returns the JSON representation of the task.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/tasks/background-removal-task.ts#L131-L133 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ColorGuidedGenerationTaskBuilder.withTextPrompt | public withTextPrompt(prompt: string | dsl.IReference<any>) {
let reference = null;
if (typeof prompt === 'string') {
reference = dsl.reference(dsl.value(prompt));
} else {
reference = prompt;
}
this.props.text = reference;
return (this);
} | /**
* @param prompt the text prompt to use.
* @returns the current builder instance.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/tasks/color-guided-generation-task.ts#L89-L100 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ColorGuidedGenerationTaskBuilder.withTextNegativePrompt | public withTextNegativePrompt(negativePrompt: string | dsl.IReference<any>) {
let reference = null;
if (typeof negativePrompt === 'string') {
reference = dsl.reference(dsl.value(negativePrompt));
} else {
reference = negativePrompt;
}
this.props.negativeText = reference;
return (this);
} | /**
* @param negativePrompt the negative text prompt to use.
* @returns the current builder instance.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/tasks/color-guided-generation-task.ts#L106-L117 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ColorGuidedGenerationTaskBuilder.withReferenceImage | public withReferenceImage(referenceImage: dsl.IReference<any>) {
this.props.referenceImage = referenceImage;
return (this);
} | /**
* @param referenceImage sets a reference image to use.
* @returns the current builder instance.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/tasks/color-guided-generation-task.ts#L123-L126 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ColorGuidedGenerationTaskBuilder.withColors | public withColors(colors: string[]) {
this.props.colors = colors;
return (this);
} | /**
* @param colors the colors to use for the generation.
* @returns the current builder instance.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/tasks/color-guided-generation-task.ts#L132-L135 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ColorGuidedGenerationTaskBuilder.withImageGenerationParameters | public withImageGenerationParameters(imageGenerationParameters: ImageGenerationParameters) {
this.props.imageGenerationParameters = imageGenerationParameters;
return (this);
} | /**
* @param imageGenerationParameters the image generation parameters.
* @returns the current builder instance.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/tasks/color-guided-generation-task.ts#L141-L144 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ColorGuidedGenerationTaskBuilder.build | public build(): ColorGuidedGenerationTask {
return (ColorGuidedGenerationTask.from(this.props));
} | /**
* @returns a new instance of the `ColorGuidedGenerationTask`
* service constructed with the given parameters.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/tasks/color-guided-generation-task.ts#L150-L152 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ColorGuidedGenerationTask.constructor | constructor(public props: ColorGuidedGenerationProps) {} | /**
* Creates a new instance of the `ColorGuidedGenerationTask` class.
* @param props the task properties.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/tasks/color-guided-generation-task.ts#L169-L169 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ColorGuidedGenerationTask.text | public text() {
return (this.props.text);
} | /**
* @returns the text prompt.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/tasks/color-guided-generation-task.ts#L174-L176 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ColorGuidedGenerationTask.negativeText | public negativeText() {
return (this.props.negativeText);
} | /**
* @returns the negative text prompt.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/tasks/color-guided-generation-task.ts#L181-L183 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ColorGuidedGenerationTask.referenceImage | public referenceImage() {
return (this.props.referenceImage);
} | /**
* @returns the reference image.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/tasks/color-guided-generation-task.ts#L188-L190 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ColorGuidedGenerationTask.colors | public colors() {
return (this.props.colors);
} | /**
* @returns the colors to use for the generation.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/tasks/color-guided-generation-task.ts#L195-L197 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ColorGuidedGenerationTask.imageGenerationParameters | public imageGenerationParameters() {
return (this.props.imageGenerationParameters);
} | /**
* @returns the image generation parameters.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/tasks/color-guided-generation-task.ts#L202-L204 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ColorGuidedGenerationTask.from | public static from(props: any) {
return (new ColorGuidedGenerationTask(ColorGuidedGenerationTaskPropsSchema.parse(props)));
} | /**
* Creates a new instance of the `ColorGuidedGenerationTask` class.
* @param props the task properties.
* @returns a new instance of the `ColorGuidedGenerationTask` class.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/tasks/color-guided-generation-task.ts#L211-L213 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ColorGuidedGenerationTask.toJSON | public toJSON() {
return (this.props);
} | /**
* @returns the JSON representation of the task.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/tasks/color-guided-generation-task.ts#L218-L220 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ImageInpaintingTaskBuilder.withTextPrompt | public withTextPrompt(prompt: string | dsl.IReference<any>) {
let reference = null;
if (typeof prompt === 'string') {
reference = dsl.reference(dsl.value(prompt));
} else {
reference = prompt;
}
this.props.text = reference;
return (this);
} | /**
* @param prompt the text prompt to use.
* @returns the current builder instance.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/tasks/image-inpainting-task.ts#L94-L105 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ImageInpaintingTaskBuilder.withTextNegativePrompt | public withTextNegativePrompt(negativePrompt: string | dsl.IReference<any>) {
let reference = null;
if (typeof negativePrompt === 'string') {
reference = dsl.reference(dsl.value(negativePrompt));
} else {
reference = negativePrompt;
}
this.props.negativeText = reference;
return (this);
} | /**
* @param negativePrompt the negative text prompt to use.
* @returns the current builder instance.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/tasks/image-inpainting-task.ts#L111-L122 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ImageInpaintingTaskBuilder.withImage | public withImage(image: dsl.IReference<any>) {
this.props.image = image;
return (this);
} | /**
* @param image sets a reference to the image to use.
* @returns the current builder instance.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/tasks/image-inpainting-task.ts#L128-L131 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ImageInpaintingTaskBuilder.withMaskPrompt | public withMaskPrompt(maskPrompt: string | dsl.IReference<any>) {
let reference = null;
if (typeof maskPrompt === 'string') {
reference = dsl.reference(dsl.value(maskPrompt));
} else {
reference = maskPrompt;
}
this.props.maskPrompt = reference;
return (this);
} | /**
* @param maskPrompt the mask prompt to use.
* @returns the current builder instance.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/tasks/image-inpainting-task.ts#L137-L148 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ImageInpaintingTaskBuilder.withMaskImage | public withMaskImage(maskImage: dsl.IReference<any>) {
this.props.maskImage = maskImage;
return (this);
} | /**
* @param maskImage the mask image to use.
* @returns the current builder instance.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/image-processors/bedrock-image-generators/src/impl/amazon/definitions/tasks/image-inpainting-task.ts#L154-L157 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.