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 | SubtitleProcessor.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/text-processors/subtitle-processor/src/index.ts#L230-L234 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | SubtitleProcessor.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/text-processors/subtitle-processor/src/index.ts#L243-L248 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.createEvent | async createEvent(text: string, type: string, event: CloudEvent): Promise<CloudEvent> {
const cloned = event.clone();
const chainId = cloned.data().chainId();
// Determine the extension based on the mime type.
const ext = type === 'text/plain' ? 'txt' : 'json';
// Create a new document with the processed text.
cloned.data().props.document = await Document.create({
url: new S3DocumentDescriptor.Builder()
.withBucket(TARGET_BUCKET)
.withKey(`${chainId}/${cloned.data().document().etag()}.${ext}`)
.build()
.asUri(),
type,
data: Buffer.from(text, 'utf-8')
});
return (cloned);
} | /**
* Creates a new event for the specified output format.
* @param text the text associated with the new document.
* @param type the mime type of the new document.
* @param event the original event.
* @returns a new cloud event with the processed document.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/subtitle-processor/src/lambdas/parser/index.ts#L64-L83 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.processEvent | async processEvent(event: CloudEvent): Promise<CloudEvent> {
const document = event.data().document();
// We load the subtitle document in memory.
const text = (await document.data().asBuffer()).toString('utf-8');
// For each specified output formats, we create a new document
// and forward it to the next middlewares.
for (const format of OUTPUT_FORMATS) {
let result: CloudEvent;
// VTT.
if (document.mimeType() === 'text/vtt') {
if (format === 'text') {
result = await this.createEvent(vttToText(text), 'text/plain', event);
} else if (format === 'json') {
result = await this.createEvent(vttToJson(text), 'application/json', event);
}
// SRT.
} else if (document.mimeType() === 'application/x-subrip') {
if (format === 'text') {
result = await this.createEvent(srtToText(text), 'text/plain', event);
} else if (format === 'json') {
result = await this.createEvent(srtToJson(text), 'application/json', event);
}
}
// Forward the new event to the next middlewares.
await nextAsync(result!);
}
return (event);
} | /**
* @param event the event to process.
* @note the next decorator will automatically forward the
* returned cloud event to the next middlewares
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/subtitle-processor/src/lambdas/parser/index.ts#L90-L123 | 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/text-processors/subtitle-processor/src/lambdas/parser/index.ts#L132-L140 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | secondsToVttTime | const secondsToVttTime = (seconds: number) => {
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
const secondsPart = Math.floor(seconds % 60);
const milliseconds = Math.floor((seconds % 1) * 1000);
// Format each part to ensure it has the correct number of digits
const hoursStr = hours.toString().padStart(2, '0');
const minutesStr = minutes.toString().padStart(2, '0');
const secondsStr = secondsPart.toString().padStart(2, '0');
const millisecondsStr = milliseconds.toString().padStart(3, '0');
// Construct and return the VTT time format
return (`${hoursStr}:${minutesStr}:${secondsStr}.${millisecondsStr}`);
}; | /**
* Converts the number of seconds relative to the start of the video
* to a VTT time format.
* @param seconds the number of seconds relative to the start of the video.
* @returns a string representing the VTT time format.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/subtitle-processor/src/lambdas/parser/vtt.ts#L9-L23 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | SyndicationFeedProcessorBuilder.build | public build(): SyndicationFeedProcessor {
return (new SyndicationFeedProcessor(
this.scope,
this.identifier, {
...this.props
}));
} | /**
* @returns a new instance of the `SyndicationFeedProcessor`
* service constructed with the given parameters.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/syndication-feed-processor/src/index.ts#L73-L79 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | SyndicationFeedProcessor.constructor | constructor(scope: Construct, id: string, props: MiddlewareProps) {
super(scope, id, description, {
...props,
queueVisibilityTimeout: cdk.Duration.seconds(
6 * PROCESSING_TIMEOUT.toSeconds()
)
});
// Validate the properties.
props = this.parse(MiddlewarePropsSchema, props);
///////////////////////////////////////////
/////// Processing Function ///////
///////////////////////////////////////////
// Processing function.
this.eventProcessor = new lambda.Function(this, 'Compute', {
description: 'A function that parses RSS and Atom syndication feeds.',
code: lambda.Code.fromAsset(
path.join(__dirname, 'lambdas', 'parser'), {
bundling: {
image: lambda.Runtime.PYTHON_3_11.bundlingImage,
command: [
'bash', '-c', [
'pip install -r requirements.txt -t /asset-output',
'cp -au . /asset-output'
].join(' && ')
]
}
}),
vpc: props.vpc,
handler: 'index.lambda_handler',
memorySize: props.maxMemorySize ?? DEFAULT_MEMORY_SIZE,
runtime: EXECUTION_RUNTIME,
timeout: PROCESSING_TIMEOUT,
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
}
});
// 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: props.batchSize ?? 2,
maxBatchingWindow: props.batchingWindow,
reportBatchItemFailures: true
}));
// Function permissions.
this.eventBus.grantPublish(this.eventProcessor);
super.bind();
} | /**
* Construct constructor.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/syndication-feed-processor/src/index.ts#L100-L165 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | SyndicationFeedProcessor.grantReadProcessedDocuments | grantReadProcessedDocuments(grantee: iam.IGrantable): iam.Grant {
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/text-processors/syndication-feed-processor/src/index.ts#L171-L173 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | SyndicationFeedProcessor.supportedInputTypes | supportedInputTypes(): string[] {
return ([
'application/rss+xml',
'application/atom+xml'
]);
} | /**
* @returns an array of mime-types supported as input
* type by this middleware.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/syndication-feed-processor/src/index.ts#L179-L184 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | SyndicationFeedProcessor.supportedOutputTypes | supportedOutputTypes(): string[] {
return ([
'text/html'
]);
} | /**
* @returns an array of mime-types supported as output
* type by the data producer.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/syndication-feed-processor/src/index.ts#L190-L194 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | SyndicationFeedProcessor.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/text-processors/syndication-feed-processor/src/index.ts#L200-L204 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | SyndicationFeedProcessor.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/text-processors/syndication-feed-processor/src/index.ts#L213-L218 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TextTransformProcessorBuilder.withIntent | public withIntent(intent: Intent) {
this.providerProps.intent = intent;
return (this);
} | /**
* @param intent the NLP intent to apply.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/text-transform-processor/src/index.ts#L75-L78 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TextTransformProcessorBuilder.build | public build(): TextTransformProcessor {
return (new TextTransformProcessor(
this.scope,
this.identifier, {
...this.providerProps as TextTransformProcessorProps,
...this.props
}
));
} | /**
* @returns a new instance of the `TextTransformProcessor`
* service constructed with the given parameters.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/text-transform-processor/src/index.ts#L84-L92 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TextTransformProcessor.constructor | constructor(scope: Construct, id: string, private props: TextTransformProcessorProps) {
super(scope, id, description, {
...props,
queueVisibilityTimeout: cdk.Duration.seconds(
6 * PROCESSING_TIMEOUT.toSeconds()
)
});
// Validate the properties.
this.props = this.parse(TextTransformProcessorPropsSchema, props);
///////////////////////////////////////////
///////// Processing Storage //////
///////////////////////////////////////////
this.storage = new CacheStorage(this, 'Storage', {
encryptionKey: props.kmsKey
});
///////////////////////////////////////////
/////// Processing Function ///////
///////////////////////////////////////////
// The lambda function.
this.eventProcessor = new node.NodejsFunction(this, 'Compute', {
description: 'Applies text transformations on text documents.',
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(),
LAKECHAIN_CACHE_STORAGE: this.props.cacheStorage.id(),
INTENT: this.props.intent.compile()
},
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;
// Plug the SQS queue into the lambda function.
this.eventProcessor.addEventSource(new sources.SqsEventSource(this.eventQueue, {
batchSize: this.props.batchSize ?? 2,
maxConcurrency: 5,
reportBatchItemFailures: true
}));
// Function permissions.
this.eventBus.grantPublish(this.eventProcessor);
this.storage.grantReadWrite(this.grantPrincipal);
super.bind();
} | /**
* Construct constructor.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/text-transform-processor/src/index.ts#L120-L192 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TextTransformProcessor.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/text-processors/text-transform-processor/src/index.ts#L198-L200 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TextTransformProcessor.supportedInputTypes | supportedInputTypes(): string[] {
return ([
'text/plain',
'text/html',
'text/markdown',
'text/csv',
'text/xml',
'application/json'
]);
} | /**
* @returns an array of mime-types supported as input
* type by this middleware.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/text-transform-processor/src/index.ts#L206-L215 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TextTransformProcessor.supportedOutputTypes | supportedOutputTypes(): string[] {
return (this.supportedInputTypes());
} | /**
* @returns an array of mime-types supported as output
* type by the data producer.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/text-transform-processor/src/index.ts#L221-L223 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TextTransformProcessor.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/text-processors/text-transform-processor/src/index.ts#L229-L233 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TextTransformProcessor.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/text-processors/text-transform-processor/src/index.ts#L242-L247 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TextTransformOperations.replace | replace(subject: string, value: string, opts = { caseSensitive: true }): TextTransformOperations {
const type = 'string';
this.ops.push({ name: 'replace', params: { type, subject, value, ...opts }});
return (this);
} | /**
* Replaces a subject in the text document with
* a given value.
* @returns the current instance.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/text-transform-processor/src/definitions/index.ts#L71-L75 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TextTransformOperations.redact | redact(...subjects: Array<Subject>): TextTransformOperations {
if (!subjects.length) {
throw new Error('At least one subject must be specified to redact');
}
this.ops.push({ name: 'redact', params: { subjects }});
return (this);
} | /**
* Redacts a subject in the text document.
* @returns the current instance.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/text-transform-processor/src/definitions/index.ts#L81-L87 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TextTransformOperations.substring | substring(startIdx: number, endIdx: number): TextTransformOperations {
this.ops.push({ name: 'substring', params: { startIdx, endIdx }});
return (this);
} | /**
* Extracts a substring from the text document and
* returns it.
* @returns the current instance.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/text-transform-processor/src/definitions/index.ts#L94-L97 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TextTransformOperations.base64 | base64() {
this.ops.push({ name: 'base64', params: {}});
return (this);
} | /**
* Transforms the text document to base64.
* @returns the current instance.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/text-transform-processor/src/definitions/index.ts#L103-L106 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TextTransformOperations.compile | compile(): string {
if (!this.ops.length) {
throw new Error('At least one operation must be specified');
}
return (JSON.stringify(this.ops));
} | /**
* Compiles the intent into a string
* representation.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/text-transform-processor/src/definitions/index.ts#L112-L117 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.handler | async handler(event: SQSEvent, _: Context) {
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/text-processors/text-transform-processor/src/lambdas/handler/index.ts#L106-L114 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | getPii | const getPii = async (event: CloudEvent, filters?: any): Promise<Pii[]> => {
const metadata = event.data().metadata();
if (metadata.properties?.kind !== 'text'
|| !metadata.properties?.attrs.pii) {
return ([]);
}
// Resolve the PII entities.
let pii = await metadata.properties.attrs.pii.resolve();
// Filter the PII by type if filters are defined.
if (filters?.length > 0) {
pii = pii.filter(p => filters.some((f: string) => f === p.type()));
}
return (pii);
}; | /**
* @param event the event associated with the received document.
* @param filters an optional array of filters to apply on the
* PII types.
* @returns an array of PII entities.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/text-transform-processor/src/lambdas/handler/transformation/redact.ts#L25-L42 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | getEntities | const getEntities = async (event: CloudEvent, filters?: any): Promise<Entity[]> => {
const metadata = event.data().metadata();
if (metadata.properties?.kind !== 'text'
|| !metadata.properties?.attrs.entities) {
return ([]);
}
// Resolve the entities.
let entities = await metadata.properties.attrs.entities.resolve();
// Filter the entities by type if filters are defined.
if (filters?.length > 0) {
entities = entities.filter(p => filters.some((f: string) => f === p.type()));
}
return (entities);
} | /**
* @param event the event associated with the received document.
* @param filters an optional array of filters to apply on the
* entity types.
* @returns an array of entities.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/text-transform-processor/src/lambdas/handler/transformation/redact.ts#L50-L67 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | replaceString | const replaceString = (text: string, _: CloudEvent, params: any): string => {
const options = `${params.caseSensitive ? '' : 'i'}g`;
return (text.replace(new RegExp(params.subject.value, options), params.value));
}; | /**
* Replaces a string in the text.
* @param text the text to transform.
* @param _ the event that triggered the transformation.
* @param params the transformation parameters.
* @returns the transformed text.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/text-transform-processor/src/lambdas/handler/transformation/replace.ts#L31-L34 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TilingTextSplitterBuilder.withPseudoSentenceSize | public withPseudoSentenceSize(pseudoSentenceSize: number) {
this.providerProps.pseudoSentenceSize = pseudoSentenceSize;
return (this);
} | /**
* Sets the pseudo sentence size for the tiling
* algorithm.
* @param pseudoSentenceSize the pseudo sentence size.
* @returns the builder itself.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/tiling-text-splitter/src/index.ts#L71-L74 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TilingTextSplitterBuilder.build | public build(): TilingTextSplitter {
return (new TilingTextSplitter(
this.scope,
this.identifier, {
...this.providerProps as TilingTextSplitterProps,
...this.props
}
));
} | /**
* @returns a new instance of the `TilingTextSplitter`
* service constructed with the given parameters.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/tiling-text-splitter/src/index.ts#L80-L88 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TilingTextSplitter.constructor | constructor(scope: Construct, id: string, props: TilingTextSplitterProps) {
super(scope, id, description, {
...props,
queueVisibilityTimeout: cdk.Duration.seconds(
6 * PROCESSING_TIMEOUT.toSeconds()
)
});
// Validate the properties.
props = this.parse(TilingTextSplitterPropsSchema, props);
///////////////////////////////////////////
///////// Processing Storage //////
///////////////////////////////////////////
this.storage = new CacheStorage(this, 'Storage', {
encryptionKey: props.kmsKey
});
///////////////////////////////////////////
////// Middleware Event Handler ////
///////////////////////////////////////////
this.processor = new lambda.DockerImageFunction(this, 'Compute', {
description: 'A function splitting text documents into tiles.',
code: lambda.DockerImageCode.fromImageAsset(
path.resolve(__dirname, 'lambdas', 'text-splitter')
),
vpc: props.vpc,
memorySize: props.maxMemorySize ?? DEFAULT_MEMORY_SIZE,
timeout: PROCESSING_TIMEOUT,
architecture: lambda.Architecture.X86_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(),
PSEUDO_SENTENCE_SIZE: `${props.pseudoSentenceSize}`,
CACHE_DIR: '/tmp'
}
});
// Allows this construct to act as a `IGrantable`
// for other middlewares to grant the processing
// lambda permissions to access their resources.
this.grantPrincipal = this.processor.grantPrincipal;
// Plug the SQS queue into the lambda function.
this.processor.addEventSource(new sources.SqsEventSource(this.eventQueue, {
batchSize: props.batchSize ?? 5,
reportBatchItemFailures: true
}));
// Function permissions.
this.storage.grantWrite(this.processor);
this.eventBus.grantPublish(this.processor);
super.bind();
} | /**
* Construct constructor.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/tiling-text-splitter/src/index.ts#L115-L179 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TilingTextSplitter.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/text-processors/tiling-text-splitter/src/index.ts#L185-L187 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TilingTextSplitter.supportedInputTypes | supportedInputTypes(): string[] {
return ([
'text/plain'
]);
} | /**
* @returns an array of mime-types supported as input
* type by this middleware.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/tiling-text-splitter/src/index.ts#L193-L197 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TilingTextSplitter.supportedOutputTypes | supportedOutputTypes(): string[] {
return ([
'text/plain'
]);
} | /**
* @returns an array of mime-types supported as output
* type by the data producer.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/tiling-text-splitter/src/index.ts#L203-L207 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TilingTextSplitter.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/text-processors/tiling-text-splitter/src/index.ts#L213-L217 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TilingTextSplitter.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/text-processors/tiling-text-splitter/src/index.ts#L226-L231 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TrafilaturaParserBuilder.build | public build(): TrafilaturaParser {
return (new TrafilaturaParser(
this.scope,
this.identifier, {
...this.props
}));
} | /**
* @returns a new instance of the `TrafilaturaParser`
* service constructed with the given parameters.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/trafilatura/src/index.ts#L69-L75 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TrafilaturaParser.constructor | constructor(scope: Construct, id: string, props: MiddlewareProps) {
super(scope, id, description, {
...props,
queueVisibilityTimeout: cdk.Duration.seconds(
3 * PROCESSING_TIMEOUT.toSeconds()
)
});
// Validate the properties.
props = this.parse(MiddlewarePropsSchema, props);
///////////////////////////////////////////
//////// Processing Storage ///////
///////////////////////////////////////////
this.storage = new CacheStorage(this, 'Storage', {
encryptionKey: props.kmsKey
});
///////////////////////////////////////////
/////// Processing Function ///////
///////////////////////////////////////////
this.eventProcessor = new lambda.DockerImageFunction(this, 'TextConverter', {
description: 'A function that converts HTML documents into plain text and extracts their metadata.',
code: lambda.DockerImageCode.fromImageAsset(
path.resolve(__dirname, 'lambdas', 'parser')
),
vpc: props.vpc,
memorySize: props.maxMemorySize ?? DEFAULT_MEMORY_SIZE,
timeout: PROCESSING_TIMEOUT,
architecture: lambda.Architecture.X86_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(),
CACHE_DIR: '/tmp'
}
});
// 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: props.batchSize ?? 10,
maxBatchingWindow: props.batchingWindow,
reportBatchItemFailures: true
}));
// Function permissions.
this.storage.grantWrite(this.eventProcessor);
this.eventBus.grantPublish(this.eventProcessor);
super.bind();
} | /**
* Construct constructor.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/trafilatura/src/index.ts#L103-L167 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TrafilaturaParser.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/text-processors/trafilatura/src/index.ts#L173-L175 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TrafilaturaParser.supportedInputTypes | supportedInputTypes(): string[] {
return ([
'text/html'
]);
} | /**
* @returns an array of mime-types supported as input
* type by this middleware.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/trafilatura/src/index.ts#L181-L185 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TrafilaturaParser.supportedOutputTypes | supportedOutputTypes(): string[] {
return ([
'text/plain'
]);
} | /**
* @returns an array of mime-types supported as output
* type by the data producer.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/trafilatura/src/index.ts#L191-L195 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TrafilaturaParser.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/text-processors/trafilatura/src/index.ts#L201-L205 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TrafilaturaParser.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/text-processors/trafilatura/src/index.ts#L214-L219 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TranslateTextProcessorBuilder.withOutputLanguages | public withOutputLanguages(languages: TranslateLanguage[]) {
this.providerProps.outputLanguages = languages;
return (this);
} | /**
* Sets the output languages in which the translation
* should be produced.
* @param formats the output formats to use as
* an output of the translation.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/translate-text-processor/src/index.ts#L77-L80 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TranslateTextProcessorBuilder.withFormalityTone | public withFormalityTone(formality: Formality) {
this.providerProps.formality = formality;
return (this);
} | /**
* Specifies a formality tone to use in the
* translation results.
* @default false
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/translate-text-processor/src/index.ts#L87-L90 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TranslateTextProcessorBuilder.withProfanityRedaction | public withProfanityRedaction(value: boolean) {
this.providerProps.profanityRedaction = value;
return (this);
} | /**
* Whether to mask profane words in the
* translation results.
* @default false
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/translate-text-processor/src/index.ts#L97-L100 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TranslateTextProcessorBuilder.build | public build(): TranslateTextProcessor {
return (new TranslateTextProcessor(
this.scope,
this.identifier, {
...this.providerProps as TranslateTextProcessorProps,
...this.props
}
));
} | /**
* @returns a new instance of the `TranslateTextProcessor`
* service constructed with the given parameters.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/translate-text-processor/src/index.ts#L106-L114 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TranslateTextProcessor.constructor | constructor(scope: Construct, id: string, private props: TranslateTextProcessorProps) {
super(scope, id, description, {
...props,
queueVisibilityTimeout: cdk.Duration.seconds(
6 * PROCESSING_TIMEOUT.toSeconds()
)
});
// Validate the properties.
this.props = this.parse(TranslateTextProcessorSchema, props);
///////////////////////////////////////////
///////// Processing Storage //////
///////////////////////////////////////////
this.storage = new CacheStorage(this, 'Storage', {
encryptionKey: props.kmsKey
});
///////////////////////////////////////////
//////// Processing Database //////
///////////////////////////////////////////
// The table holding mappings between translation jobs
// and document event metadata.
this.table = new dynamodb.Table(this, 'Table', {
partitionKey: {
name: 'TranslationJobId',
type: dynamodb.AttributeType.STRING
},
timeToLiveAttribute: 'ttl',
billingMode: dynamodb.BillingMode.PAY_PER_REQUEST,
removalPolicy: cdk.RemovalPolicy.DESTROY,
stream: dynamodb.StreamViewType.NEW_IMAGE,
encryptionKey: props.kmsKey
});
///////////////////////////////////////////
////// Amazon Translate Role //////
///////////////////////////////////////////
// The role allowing Amazon Translate to access
// documents.
this.translateRole = new iam.Role(this, 'TranslateRole', {
assumedBy: new iam.ServicePrincipal('translate.amazonaws.com')
});
// Allow the Amazon Translate service to read and write
// from the internal storage.
this.storage.grantReadWrite(this.translateRole);
///////////////////////////////////////////
///// Event Handler Function ///////
///////////////////////////////////////////
this.processor = new node.NodejsFunction(this, 'Compute', {
description: 'Creates asynchronous translations for documents.',
entry: path.resolve(__dirname, 'lambdas', 'event-handler', 'index.js'),
vpc: this.props.vpc,
timeout: PROCESSING_TIMEOUT,
runtime: EXECUTION_RUNTIME,
memorySize: 192,
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(),
PROFANITY_REDACTION: this.props.profanityRedaction ? 'true' : 'false',
FORMALITY: this.props.formality?.toString() ?? 'NONE',
OUTPUT_LANGUAGES: JSON.stringify(this.props.outputLanguages),
TRANSLATE_ROLE_ARN: this.translateRole.roleArn,
MAPPING_TABLE: this.table.tableName
},
bundling: {
minify: true,
externalModules: [
'@aws-sdk/client-s3',
'@aws-sdk/client-dynamodb',
'@aws-sdk/client-translate'
]
}
});
// Plug the SQS queue into the lambda function.
this.processor.addEventSource(new sources.SqsEventSource(this.eventQueue, {
batchSize: props.batchSize ?? 1,
maxConcurrency: 2,
reportBatchItemFailures: true
}));
// Allows this construct to act as a `IGrantable`
// for other middlewares to grant the processing
// lambda permissions to access their resources.
this.grantPrincipal = this.processor.grantPrincipal;
// Allowing the function to use Amazon Translate,
// and Amazon Comprehend for language detection.
this.processor.addToRolePolicy(new iam.PolicyStatement({
actions: [
'translate:TranslateDocument',
'translate:StartTextTranslationJob',
'comprehend:DetectDominantLanguage'
],
resources: ['*']
}));
// Function permissions.
this.storage.grantWrite(this.processor);
this.table.grantWriteData(this.processor);
this.eventBus.grantPublish(this.processor);
this.translateRole.grantPassRole(this.processor.grantPrincipal);
///////////////////////////////////////////
////// Result Handler Function /////
///////////////////////////////////////////
this.resultHandler = new node.NodejsFunction(this, 'ResultHandler', {
description: 'Handles translation results from Amazon Translate.',
entry: path.resolve(__dirname, 'lambdas', 'result-handler', 'index.js'),
vpc: this.props.vpc,
timeout: cdk.Duration.seconds(10),
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(),
MAPPING_TABLE: this.table.tableName
},
bundling: {
minify: true,
externalModules: [
'@aws-sdk/client-s3',
'@aws-sdk/client-sns',
'@aws-sdk/client-dynamodb'
]
}
});
// We listen for new translation jobs to complete for each translated language,
// to do that we listen for the creation of the metadata for each languages,
// by Amazon Translate.
this.resultHandler.addEventSource(new eventsources.S3EventSource(
this.storage.getBucket() as s3.Bucket, {
events: [
s3.EventType.OBJECT_CREATED
],
filters: [{
prefix: 'outputs/',
suffix: '.auxiliary-translation-details.json'
}]
}));
// Function permissions.
this.eventBus.grantPublish(this.resultHandler);
this.table.grantReadData(this.resultHandler);
this.storage.grantRead(this.resultHandler);
// If a KMS key is provided, grant the function
// permissions to decrypt the documents.
if (props.kmsKey) {
props.kmsKey.grantEncryptDecrypt(this.resultHandler);
}
super.bind();
} | /**
* Provider constructor.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/translate-text-processor/src/index.ts#L158-L337 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TranslateTextProcessor.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/text-processors/translate-text-processor/src/index.ts#L343-L345 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TranslateTextProcessor.supportedInputTypes | supportedInputTypes(): string[] {
return ([
'text/plain',
'text/html',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/x-xliff+xml'
]);
} | /**
* @returns an array of mime-types supported as input
* type by the data producer.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/translate-text-processor/src/index.ts#L351-L360 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TranslateTextProcessor.supportedOutputTypes | supportedOutputTypes(): string[] {
return (this.supportedInputTypes());
} | /**
* @returns an array of mime-types supported as output
* type by the data producer.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/translate-text-processor/src/index.ts#L366-L368 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TranslateTextProcessor.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/text-processors/translate-text-processor/src/index.ts#L374-L378 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TranslateTextProcessor.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/text-processors/translate-text-processor/src/index.ts#L387-L392 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | getTtl | const getTtl = () => {
const SECONDS_IN_AN_HOUR = 60 * 60;
return (Math.round(Date.now() / 1000) + (24 * 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 24 hours.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/translate-text-processor/src/lambdas/event-handler/async-translation.ts#L51-L54 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | toUri | const toUri = (bucket: string, key: string): URL => {
return (new S3DocumentDescriptor({ bucket, key }).asUri());
}; | /**
* @param bucket the bucket name to encode.
* @param key the key name to encode.
* @returns the URI for the specified bucket and key.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/translate-text-processor/src/lambdas/event-handler/async-translation.ts#L61-L63 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.processEvent | async processEvent(event: CloudEvent): Promise<any> {
const document = event.data().document();
const size = document.size();
const type = document.mimeType();
// If the input document type is compatible with synchronous translation
// and is smaller than 100 kb, we process it synchronously.
// Otherwise, we process it using the asynchronous API.
if (SYNC_MIME_TYPES.includes(type) && size && size < 100 * 1024) {
return (processSync(event));
} else {
return (processAsync(event));
}
} | /**
* This method routes the received document to the appropriate
* processing function based on its attributes.
* @param event the event to process.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/translate-text-processor/src/lambdas/event-handler/index.ts#L54-L67 | 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/text-processors/translate-text-processor/src/lambdas/event-handler/index.ts#L76-L84 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | toUri | const toUri = (bucket: string, key: string): URL => {
return (new S3DocumentDescriptor({ bucket, key }).asUri());
}; | /**
* @param bucket the bucket name to encode.
* @param key the key name to encode.
* @returns the URI for the specified bucket and key.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/translate-text-processor/src/lambdas/event-handler/sync-translation.ts#L42-L44 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | unquote | const unquote = (key: string): string => {
return (decodeURIComponent(key.replace(/\+/g, " ")));
}; | /**
* When S3 emits an event, it will encode the object key
* in the event record using quote-encoding.
* This function restores the object key in its unencoded
* form and returns the event record with the unquoted object key.
* @param event the S3 event record.
* @returns the S3 event record with the unquoted object key.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/translate-text-processor/src/lambdas/result-handler/index.ts#L59-L61 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | toUri | const toUri = (bucket: string, key: string): URL => {
return (new S3DocumentDescriptor({ bucket, key }).asUri());
}; | /**
* @param bucket the bucket name to encode.
* @param key the key name to encode.
* @returns the URI for the specified bucket and key.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/translate-text-processor/src/lambdas/result-handler/index.ts#L68-L70 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.getJobEvent | private async getJobEvent(jobName: string): Promise<CloudEvent> {
const { Item } = await dynamodb.send(new GetItemCommand({
TableName: process.env.MAPPING_TABLE,
Key: {
TranslationJobId: { S: jobName }
}
}));
return (CloudEvent.from(JSON.parse(Item?.event.S as string)));
} | /**
* @param jobName the Amazon Translate job name
* associated with the cloud event to retrieve.
* @returns the cloud event associated with the given
* Amazon Translate job identifier.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/translate-text-processor/src/lambdas/result-handler/index.ts#L86-L94 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.toEvents | async toEvents(metadata: TranslationDetails) {
const outputPrefix = new URL(metadata.outputDataPrefix);
const paths = outputPrefix.pathname.split('/').slice(1);
const event = await this.getJobEvent(paths[1]);
const events = [];
for (const detail of metadata.details) {
const clone = event.clone();
const document = clone.data().document();
const key = path.join(...paths, detail.targetFile);
// Get information about the translated document.
const data = await s3.send(new HeadObjectCommand({
Bucket: outputPrefix.hostname,
Key: key
}));
// Update the document.
document.props.url = toUri(outputPrefix.hostname, key);
document.props.etag = data.ETag?.replace(/"/g, '');
document.props.size = data.ContentLength;
// Update the metadata.
merge(clone.data().props.metadata, {
language: metadata.targetLanguageCode,
properties: {
kind: 'text',
attrs: {}
}
});
events.push(clone);
}
return (events);
} | /**
* This method takes a `TranslationDetails` object and returns
* an array of cloud events associated with the translated documents.
* @param metadata the metadata file issued by Amazon Translate.
* @note we are expecting in the metadata file a `outputDataPrefix`
* property containing the prefix of the produced documents that looks as follows:
* s3://${bucket}/outputs/${jobName}/${accountId}-TranslateText-${jobId}
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/translate-text-processor/src/lambdas/result-handler/index.ts#L104-L139 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.onS3Event | async onS3Event(record: S3EventRecord): Promise<S3EventRecord> {
const key = unquote(record.s3.object.key);
// Amazon Translate creates a job description which is initially empty.
// We ignore any empty file.
if (record.s3.object.size === 0) {
return (record);
}
try {
// Load the metadata file in memory.
const data = await (await s3.send(new GetObjectCommand({
Bucket: record.s3.bucket.name,
Key: key
}))).Body?.transformToString();
// Try to parse the metadata.
const metadata: TranslationDetails = JSON.parse(data as string);
// Resolve the cloud event associated with each translated document.
const events = await this.toEvents(metadata);
// Forward the new documents to the next middlewares.
for (const event of events) {
await nextAsync(event);
}
} catch (err) {
logger.error(err as any);
}
return (record);
} | /**
* This method attempts to parse the translation metadata file
* created by Amazon Translate containing the files produced
* by the translation job.
* @param record the S3 event record to process containing
* information about the produced metadata file by Amazon Translate.
* @returns a promise to the S3 event record.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/translate-text-processor/src/lambdas/result-handler/index.ts#L149-L180 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.handler | handler(event: S3Event, _: Context): Promise<any> {
return (Promise.all(
event.Records.map((record) => this.onS3Event(record))
));
} | // eslint-disable-next-line @typescript-eslint/no-unused-vars | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/text-processors/translate-text-processor/src/lambdas/result-handler/index.ts#L189-L193 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | S3EventTriggerBuilder.withBucket | public withBucket(input: SourceDescriptor | s3.IBucket) {
let source: SourceDescriptor;
if (input instanceof s3.Bucket) {
// If the input is an S3 bucket, we create a
// source descriptor from it without prefix.
source = { bucket: input };
} else {
source = input as SourceDescriptor;
}
if (!this.triggerProps.buckets) {
this.triggerProps.buckets = [source];
} else {
this.triggerProps.buckets.push(source);
}
return (this);
} | /**
* Adds a new bucket to monitor by the trigger.
* @param input the description of the bucket to monitor,
* or a reference to an S3 bucket.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/triggers/s3-event-trigger/src/index.ts#L71-L88 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | S3EventTriggerBuilder.withBuckets | public withBuckets(sources: Array<SourceDescriptor | s3.IBucket>) {
sources.forEach((source) => this.withBucket(source));
return (this);
} | /**
* Adds a list of buckets to monitor by the trigger.
* @param sources an array of buckets or source descriptors to monitor.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/triggers/s3-event-trigger/src/index.ts#L94-L97 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | S3EventTriggerBuilder.withFetchMetadata | public withFetchMetadata(value: boolean) {
this.triggerProps.fetchMetadata = value;
return (this);
} | /**
* Sets whether to fetch the metadata of the S3 objects to
* enrich the document metadata.
* @param value whether to fetch the metadata.
* @default false
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/triggers/s3-event-trigger/src/index.ts#L105-L108 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | S3EventTriggerBuilder.build | public build(): S3EventTrigger {
return (new S3EventTrigger(
this.scope,
this.identifier, {
...this.triggerProps as S3EventTriggerProps,
...this.props
}
));
} | /**
* @returns a new instance of the `S3EventTrigger`
* service constructed with the given parameters.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/triggers/s3-event-trigger/src/index.ts#L114-L122 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | S3EventTrigger.constructor | constructor(scope: Construct, id: string, private props: S3EventTriggerProps) {
super(scope, id, description, props);
// Validating the properties.
this.props = this.parse(S3EventTriggerPropsSchema, props);
///////////////////////////////////////////
/////// Processing Function ///////
///////////////////////////////////////////
this.eventProcessor = new node.NodejsFunction(this, 'Compute', {
description: 'Forwards S3 events to other middlewares in a pipeline.',
entry: path.resolve(__dirname, 'lambdas', 'event-handler', 'index.js'),
memorySize: this.props.maxMemorySize ?? DEFAULT_MEMORY_SIZE,
vpc: this.props.vpc,
timeout: PROCESSING_TIMEOUT,
runtime: EXECUTION_RUNTIME,
architecture: lambda.Architecture.ARM_64,
tracing: lambda.Tracing.ACTIVE,
environmentEncryption: this.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,
FETCH_METADATA: this.props.fetchMetadata ? 'true' : 'false'
},
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;
// 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
}));
// Function permissions.
this.eventBus.grantPublish(this.eventProcessor);
///////////////////////////////////////////
////// Bucket Event Listeners //////
///////////////////////////////////////////
for (const descriptor of this.props.buckets) {
const filters: s3.NotificationKeyFilter[] = [];
// If filters are specified, we add them into
// the list of filters to apply to the bucket.
if (descriptor.prefix || descriptor.suffix) {
filters.push({
prefix: descriptor.prefix,
suffix: descriptor.suffix
});
}
// Listen to object creation events.
descriptor.bucket.addEventNotification(
s3.EventType.OBJECT_CREATED,
new notifications.SqsDestination(this.eventQueue),
...filters
);
// Listen to object deletion events.
descriptor.bucket.addEventNotification(
s3.EventType.OBJECT_REMOVED,
new notifications.SqsDestination(this.eventQueue),
...filters
);
// Grant the bucket read permissions.
if (descriptor.prefix) {
descriptor.bucket.grantRead(this.eventProcessor, `${descriptor.prefix}/*`);
} else {
descriptor.bucket.grantRead(this.eventProcessor);
}
}
super.bind();
} | /**
* Provider constructor.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/triggers/s3-event-trigger/src/index.ts#L144-L237 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | S3EventTrigger.grantReadProcessedDocuments | grantReadProcessedDocuments(grantee: iam.IGrantable): iam.Grant {
for (const description of this.props.buckets) {
description.bucket.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/triggers/s3-event-trigger/src/index.ts#L243-L248 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | S3EventTrigger.supportedInputTypes | supportedInputTypes(): string[] {
return ([
'application/json+s3-event'
]);
} | /**
* @returns an array of mime-types supported as input
* type by the data producer.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/triggers/s3-event-trigger/src/index.ts#L254-L258 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | S3EventTrigger.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/triggers/s3-event-trigger/src/index.ts#L264-L268 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | S3EventTrigger.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/triggers/s3-event-trigger/src/index.ts#L274-L278 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | createUrl | const createUrl = (bucket: S3Bucket, obj: S3Object): URL => {
return (new S3DocumentDescriptor({
bucket: bucket.name,
key: obj.key
}).asUri());
}; | /**
* @param bucket the bucket associated with the S3 object.
* @param obj the object information.
* @returns a URL associated with the given S3 bucket
* and S3 object.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/triggers/s3-event-trigger/src/lambdas/event-handler/get-document.ts#L73-L78 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | onCreated | const onCreated = async (bucket: S3Bucket, obj: S3Object): Promise<Document> => {
let mimeType: string | undefined;
const url = createUrl(bucket, obj);
// Create the document builder.
const builder = new Document.Builder()
.withUrl(url)
.withEtag(obj.eTag)
.withSize(obj.size);
// We first try to compute the mime type from the object
// using its extension.
mimeType = mimeTypeFromExtension(obj.key);
// If the mime type could not be computed, we fallback
// to determining the file type from its content.
if (!mimeType) {
mimeType = await mimeTypeFromBuffer(bucket, obj);
}
// If the notification is about the creation of an S3
// directory, we throw an error.
if (isDirectory(obj.key, mimeType)) {
throw new InvalidDocumentObjectException(obj.key);
}
return (builder
.withType(mimeType || DEFAULT_MIME_TYPES[0])
.build());
}; | /**
* Handles created S3 object creation events.
* @param bucket the bucket information.
* @param obj the object information.
* @returns a new document instance with the
* object information.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/triggers/s3-event-trigger/src/lambdas/event-handler/get-document.ts#L134-L163 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | onDeleted | const onDeleted = (bucket: S3Bucket, obj: S3Object): Document => {
// If the event is not an object created event, we
// fallback to determining the file type from its name,
// as the S3 object will not be available anymore.
const mimeType = mimeTypeFromExtension(obj.key) ?? DEFAULT_MIME_TYPES[0];
// If the notification is about the creation of an S3
// directory, we throw an error.
if (isDirectory(obj.key, mimeType)) {
throw new InvalidDocumentObjectException(obj.key);
}
// Return the constructed document.
return (new Document.Builder()
.withUrl(createUrl(bucket, obj))
.withEtag(obj.eTag)
.withSize(obj.size)
.withType(mimeType)
.build());
}; | /**
* Handles created S3 object removal events.
* @param bucket the bucket information.
* @param obj the object information.
* @returns a new document instance with the
* object information.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/triggers/s3-event-trigger/src/lambdas/event-handler/get-document.ts#L172-L191 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | getEventType | const getEventType = (type: string): DocumentEvent => {
if (type.startsWith('ObjectCreated')) {
return (DocumentEvent.DOCUMENT_CREATED);
} else if (type.startsWith('ObjectRemoved')) {
return (DocumentEvent.DOCUMENT_DELETED);
} else {
throw new Error(`Unsupported S3 event type: ${type}`);
}
}; | /**
* @param type the S3 event type.
* @returns the corresponding event type in the context of
* the cloud event specification.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/triggers/s3-event-trigger/src/lambdas/event-handler/index.ts#L60-L68 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | unquote | const unquote = (event: S3EventRecord): S3EventRecord => {
event.s3.object.key = decodeURIComponent(event.s3.object.key.replace(/\+/g, " "));
return (event);
}; | /**
* When S3 emits an event, it will encode the object key
* in the event record using quote-encoding.
* This function restores the object key in its unencoded
* form and returns the event record with the unquoted object key.
* @param event the S3 event record.
* @returns the S3 event record with the unquoted object key.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/triggers/s3-event-trigger/src/lambdas/event-handler/index.ts#L78-L81 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.sqsRecordHandler | async sqsRecordHandler(record: SQSRecord): Promise<any> {
const event = JSON.parse(record.body) as S3Event;
// Filter out invalid events.
if (!Array.isArray(event.Records)) {
return (Promise.resolve());
}
// For each record in the S3 event, we forward them
// in a normalized way to the next middlewares.
for (const record of event.Records) {
try {
await this.s3RecordHandler(record);
} catch (err) {
logger.error(err as any);
if (err instanceof ObjectNotFoundException
|| err instanceof InvalidDocumentObjectException) {
// If the S3 object was not found, or is not a file,
// the event should be ignored.
continue;
} else {
throw err;
}
}
}
} | /**
* @param record an SQS record to process. This SQS record
* contains at least an S3 event.
* @return a promise that resolves when all the S3 events
* contained in the SQS record have been processed.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/triggers/s3-event-trigger/src/lambdas/event-handler/index.ts#L137-L162 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.handler | async handler(event: SQSEvent, _: Context): Promise<SQSBatchResponse> {
return (await processPartialResponse(
event, this.sqsRecordHandler.bind(this), processor
));
} | // eslint-disable-next-line @typescript-eslint/no-unused-vars | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/triggers/s3-event-trigger/src/lambdas/event-handler/index.ts#L173-L177 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | InvalidDocumentObjectException.getKey | public getKey(): string {
return (this.key);
} | /**
* @returns the name of the object that is not
* a document.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/triggers/s3-event-trigger/src/lambdas/event-handler/exceptions/invalid-document-object.ts#L34-L36 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ObjectNotFoundException.getUrl | public getUrl(): string {
return (this.key);
} | /**
* @returns the URL of the object that could not
* be found.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/triggers/s3-event-trigger/src/lambdas/event-handler/exceptions/object-not-found.ts#L33-L35 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | SchedulerEventTriggerBuilder.withSchedule | public withSchedule(scheduleExpression: scheduler.ScheduleExpression) {
this.triggerProps.scheduleExpression = scheduleExpression;
return (this);
} | /**
* Specifies the schedule expression that triggers the pipeline.
* @param scheduleExpression the schedule expression to use.
* @returns the builder instance.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/triggers/scheduler-event-trigger/src/index.ts#L76-L79 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | SchedulerEventTriggerBuilder.withDocuments | public withDocuments(documents: string[]) {
this.triggerProps.documents = documents;
return (this);
} | /**
* Sets the documents to inject in the pipeline.
* @param documents an array of document URIs.
* @returns the builder instance.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/triggers/scheduler-event-trigger/src/index.ts#L86-L89 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | SchedulerEventTriggerBuilder.build | public build(): SchedulerEventTrigger {
return (new SchedulerEventTrigger(
this.scope,
this.identifier, {
...this.triggerProps as SchedulerEventTriggerProps,
...this.props
}
));
} | /**
* @returns a new instance of the `SchedulerEventTrigger`
* service constructed with the given parameters.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/triggers/scheduler-event-trigger/src/index.ts#L95-L103 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | SchedulerEventTrigger.constructor | constructor(scope: Construct, id: string, private props: SchedulerEventTriggerProps) {
super(scope, id, description, props);
// Validating the properties.
this.props = this.parse(SchedulerEventTriggerPropsSchema, props);
///////////////////////////////////////////
///////// Processing Storage //////
///////////////////////////////////////////
this.storage = new CacheStorage(this, 'Storage', {
encryptionKey: this.props.kmsKey
});
///////////////////////////////////////////
/////// Processing Function ///////
///////////////////////////////////////////
this.eventProcessor = new node.NodejsFunction(this, 'Compute', {
description: 'Translates scheduler events into CloudEvents.',
entry: path.resolve(__dirname, 'lambdas', 'event-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: props.cloudWatchInsights ?
LAMBDA_INSIGHTS_VERSION :
undefined,
environment: {
POWERTOOLS_SERVICE_NAME: description.name,
POWERTOOLS_METRICS_NAMESPACE: NAMESPACE,
SNS_TARGET_TOPIC: this.eventBus.topicArn,
STORAGE_BUCKET: this.storage.id(),
DOCUMENT_URIS: JSON.stringify(this.props.documents)
},
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;
// Creating the schedule using the provided schedule
// expression.
new scheduler.Schedule(this, 'Schedule', {
description: 'Triggers a pipeline based on the configured schedule.',
schedule: this.props.scheduleExpression,
target: new targets.LambdaInvoke(this.eventProcessor, {})
});
// Function permissions.
this.eventBus.grantPublish(this.eventProcessor);
///////////////////////////////////////////
///// Placeholder Document Upload /////
///////////////////////////////////////////
// Upload the placeholder document in the internal storage.
const uris = new s3deploy.BucketDeployment(this, 'Uris', {
sources: [s3deploy.Source.jsonData('placeholder.json', '{}')],
destinationBucket: this.storage.getBucket()
});
// Ensure that the event processor is deployed.
uris.node.addDependency(this.eventProcessor);
super.bind();
} | /**
* Provider constructor.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/triggers/scheduler-event-trigger/src/index.ts#L130-L208 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | SchedulerEventTrigger.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/triggers/scheduler-event-trigger/src/index.ts#L214-L216 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | SchedulerEventTrigger.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/triggers/scheduler-event-trigger/src/index.ts#L222-L224 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | SchedulerEventTrigger.supportedOutputTypes | supportedOutputTypes(): string[] {
return ([
this.props.documents.length > 0 ?
'*/*' :
'application/json+scheduler'
]);
} | /**
* @returns an array of mime-types supported as output
* type by the data producer.
* @note when specifying documents to the Scheduler,
* it will attempt to infer the mime-types associated
* with these documents. If no documents are specified,
* the Scheduler will send a placeholder document to the
* next middlewares having a mime-type of `application/json+scheduler`.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/triggers/scheduler-event-trigger/src/index.ts#L235-L241 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | SchedulerEventTrigger.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/triggers/scheduler-event-trigger/src/index.ts#L247-L251 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.handler | async handler(_1: any, _2: Context): Promise<any> {
let results = [];
// If there are no given documents, it means that we're simply
// looking to send a trigger to the next middlewares. To do so,
// we send out a placeholder document with a specific mime-type.
if (DOCUMENT_URIS.length === 0) {
results = [
await getDocument(PLACEHOLDER, 'application/json+scheduler')
];
// Otherwise, we simply process the given documents to find their
// mime-types and forward them to the next middlewares.
} else {
results = await Promise.all(
DOCUMENT_URIS.map((uri: string) => {
return (getDocument(uri));
})
);
}
// We forward each document to the next middlewares.
for (const result of results) {
await this.onDocument(result);
}
} | // eslint-disable-next-line @typescript-eslint/no-unused-vars | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/triggers/scheduler-event-trigger/src/lambdas/event-handler/index.ts#L74-L98 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | SqsEventTriggerBuilder.withQueue | public withQueue(queue: sqs.Queue) {
if (!this.triggerProps.queues) {
this.triggerProps.queues = [queue];
} else {
this.triggerProps.queues.push(queue);
}
return (this);
} | /**
* Adds a new queue to monitor for events.
* @param queue the SQS queue to monitor.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/triggers/sqs-event-trigger/src/index.ts#L68-L75 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | SqsEventTriggerBuilder.withQueues | public withQueues(queues: sqs.Queue[]) {
queues.forEach((queue) => this.withQueue(queue));
return (this);
} | /**
* Adds a list of SQS queues to monitor by the trigger.
* @param queues an array of SQS queues to monitor.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/triggers/sqs-event-trigger/src/index.ts#L81-L84 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | SqsEventTriggerBuilder.build | public build(): SqsEventTrigger {
return (new SqsEventTrigger(
this.scope,
this.identifier, {
...this.triggerProps as SqsEventTriggerProps,
...this.props
}
));
} | /**
* @returns a new instance of the `SqsEventTrigger`
* service constructed with the given parameters.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/triggers/sqs-event-trigger/src/index.ts#L90-L98 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | SqsEventTrigger.constructor | constructor(scope: Construct, id: string, private props: SqsEventTriggerProps) {
super(scope, id, description, props);
// Validating the properties.
this.props = this.parse(SqsEventTriggerPropsSchema, props);
///////////////////////////////////////////
/////// Processing Function ///////
///////////////////////////////////////////
// The lambda function.
this.eventProcessor = new node.NodejsFunction(this, 'Compute', {
description: 'Forwards SQS events to other middlewares in a pipeline.',
entry: path.resolve(__dirname, 'lambdas', 'event-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: props.cloudWatchInsights ?
LAMBDA_INSIGHTS_VERSION :
undefined,
environment: {
POWERTOOLS_SERVICE_NAME: description.name,
POWERTOOLS_METRICS_NAMESPACE: NAMESPACE,
SNS_TARGET_TOPIC: this.eventBus.topicArn
},
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;
// Plug the input queues into the lambda function.
for (const queue of this.props.queues) {
this.eventProcessor.addEventSource(new sources.SqsEventSource(queue, {
batchSize: props.batchSize ?? 10,
maxBatchingWindow: props.batchingWindow,
reportBatchItemFailures: true
}));
}
// Function permissions.
this.eventBus.grantPublish(this.eventProcessor);
super.bind();
} | /**
* Provider constructor.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/triggers/sqs-event-trigger/src/index.ts#L120-L177 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | SqsEventTrigger.grantReadProcessedDocuments | grantReadProcessedDocuments(grantee: iam.IGrantable): iam.Grant {
for (const queue of this.props.queues) {
queue.grantConsumeMessages(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/triggers/sqs-event-trigger/src/index.ts#L183-L188 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | SqsEventTrigger.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/triggers/sqs-event-trigger/src/index.ts#L194-L196 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | SqsEventTrigger.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/triggers/sqs-event-trigger/src/index.ts#L202-L206 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.