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 | WhisperTranscriber.constructor | constructor(scope: Construct, id: string, private props: WhisperTranscriberProps) {
super(scope, id, description, {
...props,
queueVisibilityTimeout: cdk.Duration.minutes(30)
});
// Validate the properties.
this.props = this.parse(WhisperTranscriberPropsSchema, props);
///////////////////////////////////////////
///////// Processing Storage //////
///////////////////////////////////////////
this.storage = new CacheStorage(this, 'Storage', {
encryptionKey: this.props.kmsKey
});
///////////////////////////////////////////
///////// ECS Container /////////
///////////////////////////////////////////
// The configuration to use for the specified compute type.
const configuration = this.props.computeType === ComputeType.CPU ?
getCpuConfiguration(this.props.model) :
getGpuConfiguration(this.props.model);
// The container image to provision the ECS tasks with.
const image = ecs.ContainerImage.fromDockerImageAsset(
new assets.DockerImageAsset(this, 'WhisperImage', {
directory: path.resolve(__dirname, 'container'),
file: configuration.container.dockerFile,
platform: configuration.container.platform
})
);
// Use the ECS container middleware pattern to create an
// auto-scaled ECS cluster, an EFS mounted on the cluster's tasks
// and all the components required to manage the cluster.
// This cluster supports both CPU and GPU instances.
const cluster = new EcsCluster(this, 'Cluster', {
vpc: this.props.vpc,
eventQueue: this.eventQueue,
eventBus: this.eventBus,
kmsKey: this.props.kmsKey,
logGroup: this.logGroup,
containerProps: {
image,
containerName: 'whisper-processor',
cpuLimit: configuration.cpuLimit,
memoryLimitMiB: configuration.memoryLimitMiB,
gpuCount: configuration.gpuCount,
environment: {
POWERTOOLS_SERVICE_NAME: description.name,
WHISPER_ENGINE: this.props.engine,
WHISPER_MODEL: this.props.model,
OUTPUT_FORMAT: this.props.outputFormat,
PROCESSED_FILES_BUCKET: this.storage.id()
}
},
autoScaling: {
minInstanceCapacity: 0,
maxInstanceCapacity: this.props.maxInstances,
maxTaskCapacity: this.props.maxInstances,
maxMessagesPerTask: 1
},
launchTemplateProps: {
instanceType: configuration.instanceType,
machineImage: configuration.machineImage,
ebsOptimized: true,
blockDevices: [{
deviceName: '/dev/xvda',
volume: ec2.BlockDeviceVolume.ebs(80)
}],
userData: ec2.UserData.forLinux()
},
fileSystem: {
throughputMode: efs.ThroughputMode.ELASTIC,
readonly: false,
containerPath: '/cache',
accessPoint: {
uid: 1000,
gid: 1000,
permission: 750
}
},
containerInsights: this.props.cloudWatchInsights
});
// Allows this construct to act as a `IGrantable`
// for other middlewares to grant the processing
// lambda permissions to access their resources.
this.grantPrincipal = cluster.taskRole.grantPrincipal;
// Cluster permissions.
this.storage.grantWrite(cluster.taskRole);
super.bind();
} | /**
* Provider constructor.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/audio-processors/whisper-transcriber/src/index.ts#L132-L229 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | WhisperTranscriber.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/audio-processors/whisper-transcriber/src/index.ts#L235-L237 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | WhisperTranscriber.supportedInputTypes | supportedInputTypes(): string[] {
return ([
'audio/mpeg',
'audio/mp4',
'audio/x-m4a',
'audio/wav',
'audio/webm',
'audio/flac',
'audio/x-flac'
]);
} | /**
* @returns an array of mime-types supported as input
* type by this middleware.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/audio-processors/whisper-transcriber/src/index.ts#L243-L253 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | WhisperTranscriber.supportedOutputTypes | supportedOutputTypes(): string[] {
return ([
'application/x-subrip',
'text/vtt',
'text/plain',
'text/tab-separated-values',
'application/json'
]);
} | /**
* @returns an array of mime-types supported as output
* type by the data producer.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/audio-processors/whisper-transcriber/src/index.ts#L259-L267 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | WhisperTranscriber.supportedComputeTypes | supportedComputeTypes(): ComputeType[] {
return ([
ComputeType.GPU,
ComputeType.CPU
]);
} | /**
* @returns the supported compute types by a given
* middleware.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/audio-processors/whisper-transcriber/src/index.ts#L273-L278 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | WhisperTranscriber.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/audio-processors/whisper-transcriber/src/index.ts#L287-L292 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | getGpuInstanceByModel | const getGpuInstanceByModel = (model: WhisperModel) => {
switch (model) {
case 'tiny':
case 'tiny.en':
case 'base':
case 'base.en':
case 'small':
case 'small.en':
case 'medium':
case 'medium.en':
return ({
instanceType: ec2.InstanceType.of(
ec2.InstanceClass.G4DN,
ec2.InstanceSize.XLARGE
),
gpuCount: 1,
cpuLimit: 4096,
memoryLimitMiB: 7168
});
case 'large':
case 'large-v1':
case 'large-v2':
case 'large-v3':
return ({
instanceType: ec2.InstanceType.of(
ec2.InstanceClass.G4DN,
ec2.InstanceSize.XLARGE2
),
gpuCount: 1,
cpuLimit: 8192,
memoryLimitMiB: 14336
});
}
}; | /**
* @return the characteristics of the GPU instance
* to run in the cluster given a Whisper model.
* @param model the Whisper model to evaluate.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/audio-processors/whisper-transcriber/src/definitions/infrastructure.ts#L27-L60 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | getCpuInstanceByModel | const getCpuInstanceByModel = (model: WhisperModel) => {
switch (model) {
case 'tiny':
case 'tiny.en':
case 'base':
case 'base.en':
case 'small':
case 'small.en':
case 'medium':
case 'medium.en':
return ({
instanceType: ec2.InstanceType.of(
ec2.InstanceClass.C6A,
ec2.InstanceSize.XLARGE
),
gpuCount: 0,
cpuLimit: 4096,
memoryLimitMiB: 7168
});
case 'large':
case 'large-v1':
case 'large-v2':
case 'large-v3':
return ({
instanceType: ec2.InstanceType.of(
ec2.InstanceClass.C6A,
ec2.InstanceSize.XLARGE2
),
gpuCount: 0,
cpuLimit: 8192,
memoryLimitMiB: 14336
});
}
}; | /**
* @return the characteristics of the CPU instance
* to run in the cluster given a Whisper model.
* @param model the Whisper model to evaluate.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/audio-processors/whisper-transcriber/src/definitions/infrastructure.ts#L67-L100 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TarDeflateProcessorBuilder.withGzip | public withGzip(gzip: boolean): this {
this.providerProps.gzip = gzip;
return (this);
} | /**
* Sets whether to Gzip the tarball.
* @param gzip whether to Gzip the tarball.
* @returns the builder instance.
* @default true
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/binary-processors/tar-processor/src/impl/tar-deflate/index.ts#L77-L80 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TarDeflateProcessorBuilder.withCompressionLevel | public withCompressionLevel(level: number): this {
this.providerProps.compressionLevel = level;
return (this);
} | /**
* Sets the compression level to use when creating
* Zip archives.
* This is only valid when `gzip` is set to `true`.
* @param level the compression level.
* @returns the builder instance.
* @default 1
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/binary-processors/tar-processor/src/impl/tar-deflate/index.ts#L90-L93 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TarDeflateProcessorBuilder.build | public build(): TarDeflateProcessor {
return (new TarDeflateProcessor(
this.scope,
this.identifier, {
...this.providerProps as TarDeflateProcessorProps,
...this.props
}
));
} | /**
* @returns a new instance of the `TarDeflateProcessor`
* service constructed with the given parameters.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/binary-processors/tar-processor/src/impl/tar-deflate/index.ts#L99-L107 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TarDeflateProcessor.constructor | constructor(scope: Construct, id: string, private props: TarDeflateProcessorProps) {
super(scope, id, description, {
...props,
queueVisibilityTimeout: cdk.Duration.seconds(
3 * PROCESSING_TIMEOUT.toSeconds()
)
});
// Validate the properties.
this.props = this.parse(TarDeflateProcessorPropsSchema, props);
///////////////////////////////////////////
//////// Processing Storage ///////
///////////////////////////////////////////
this.storage = new CacheStorage(this, 'Storage', {
encryptionKey: props.kmsKey
});
///////////////////////////////////////////
////// Middleware Event Handler ////
///////////////////////////////////////////
this.processor = new node.NodejsFunction(this, 'Processor', {
description: 'Creates Tarballs from input documents.',
entry: path.resolve(__dirname, 'lambdas', 'tar', '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,
PROCESSED_FILES_BUCKET: this.storage.id(),
SNS_TARGET_TOPIC: this.eventBus.topicArn,
GZIP_ENABLED: this.props.gzip ? 'true' : 'false',
COMPRESSION_LEVEL: this.props.compressionLevel?.toString()
},
bundling: {
minify: true,
externalModules: [
'@aws-sdk/client-s3',
'@aws-sdk/client-sns',
'@aws-sdk/lib-storage'
]
}
});
// 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 ?? 1,
reportBatchItemFailures: true
}));
// Grant the lambda function permissions to
// write to the post-processing storage.
this.storage.grantWrite(this.processor);
// Grant the lambda function permissions to
// publish to the SNS topic.
this.eventBus.grantPublish(this.processor);
super.bind();
} | /**
* Construct constructor.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/binary-processors/tar-processor/src/impl/tar-deflate/index.ts#L134-L209 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TarDeflateProcessor.grantReadProcessedDocuments | public 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/binary-processors/tar-processor/src/impl/tar-deflate/index.ts#L215-L217 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TarDeflateProcessor.supportedInputTypes | supportedInputTypes(): string[] {
return ([
'*/*'
]);
} | /**
* @returns an array of mime-types supported as input
* type by this middleware.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/binary-processors/tar-processor/src/impl/tar-deflate/index.ts#L223-L227 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TarDeflateProcessor.supportedOutputTypes | supportedOutputTypes(): string[] {
return ([
'application/x-tar',
'application/x-gzip'
]);
} | /**
* @returns an array of mime-types supported as output
* type by the data producer.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/binary-processors/tar-processor/src/impl/tar-deflate/index.ts#L233-L238 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TarDeflateProcessor.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/binary-processors/tar-processor/src/impl/tar-deflate/index.ts#L244-L248 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TarDeflateProcessor.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/binary-processors/tar-processor/src/impl/tar-deflate/index.ts#L257-L262 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.resolveEvents | private async resolveEvents(event: CloudEvent): Promise<CloudEvent[]> {
const document = event.data().document();
if (document.mimeType() === 'application/cloudevents+json') {
const data = JSON.parse((await document
.data()
.asBuffer())
.toString('utf-8')
);
return (data.map((event: string) => CloudEvent.from(event)));
} else {
return ([event]);
}
} | /**
* Resolves the input documents to process.
* This function supports both single and composite events.
* @param event the received event.
* @returns a promise to an array of CloudEvents to process.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/binary-processors/tar-processor/src/impl/tar-deflate/lambdas/tar/index.ts#L97-L110 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.getOpts | private getOpts(): ArchiverOptions {
if (GZIP_ENABLED) {
return ({ gzip: true, gzipOptions: { level: COMPRESSION_LEVEL } });
}
return ({ gzip: false });
} | /**
* @returns the options to use when creating the tarball.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/binary-processors/tar-processor/src/impl/tar-deflate/lambdas/tar/index.ts#L115-L120 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.getOutputType | private getOutputType() {
return (GZIP_ENABLED ? 'application/gzip' : 'application/tar');
} | /**
* @returns the output type to use when creating the tarball.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/binary-processors/tar-processor/src/impl/tar-deflate/lambdas/tar/index.ts#L125-L127 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.getOutputName | private getOutputName() {
return (GZIP_ENABLED ? 'archive.tar.gz' : 'archive.tar');
} | /**
* @returns the output name to use when creating the tarball.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/binary-processors/tar-processor/src/impl/tar-deflate/lambdas/tar/index.ts#L132-L134 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.tar | private async tar(events: CloudEvent[], destBucket: string) {
const outputKey = `${randomUUID()}/${this.getOutputName()}`;
// Create a new archiver instance.
const archive = archiver('tar', this.getOpts());
// Create a write stream to the destination bucket.
const { writeStream, promise } = s3Stream.createS3WriteStream({
bucket: destBucket,
key: outputKey,
contentType: this.getOutputType()
});
// Pipe the archive to the write stream.
archive.pipe(writeStream);
// Append each document read stream to the archive.
for (const event of events) {
const document = event.data().document();
const etag = document.etag();
const name = `${event.data().chainId()}/${etag}-${document.filename().basename()}`;
archive.append(
await document.data().asReadStream(),
{ name }
);
}
// Wait for the process to complete.
await archive.finalize();
const res = await promise;
// Forward the document to the next middlewares.
return (this.onArchiveCreated(res, archive.pointer()));
} | /**
* Processes the given event and creates a tarball with the documents
* associated with it into the bucket passed as `destBucket`.
* @param events the events to process.
* @param destBucket the destination bucket where
* to unzip the resulting files.
* @returns a promise which resolves when the
* unzip process is complete.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/binary-processors/tar-processor/src/impl/tar-deflate/lambdas/tar/index.ts#L145-L178 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.recordHandler | async recordHandler(record: SQSRecord): Promise<any> {
return (this.tar(
await this.resolveEvents(CloudEvent.from(JSON.parse(record.body))),
TARGET_BUCKET
));
} | /**
* Deflates the document associated with the record
* in the target S3 bucket.
* @param record the SQS record associated with
* the document to inflate.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/binary-processors/tar-processor/src/impl/tar-deflate/lambdas/tar/index.ts#L186-L191 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.handler | async handler(event: SQSEvent, _: Context): Promise<SQSBatchResponse> {
return (await processPartialResponse(
event, this.recordHandler.bind(this), processor
));
} | // eslint-disable-next-line @typescript-eslint/no-unused-vars | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/binary-processors/tar-processor/src/impl/tar-deflate/lambdas/tar/index.ts#L201-L205 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TarInflateProcessorBuilder.build | public build(): TarInflateProcessor {
return (new TarInflateProcessor(
this.scope,
this.identifier, {
...this.props
}
));
} | /**
* @returns a new instance of the `TarInflateProcessor`
* service constructed with the given parameters.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/binary-processors/tar-processor/src/impl/tar-inflate/index.ts#L74-L81 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TarInflateProcessor.constructor | constructor(scope: Construct, id: string, props: MiddlewareProps) {
super(scope, id, description, {
...props,
queueVisibilityTimeout: cdk.Duration.seconds(
6 * PROCESSING_TIMEOUT.toSeconds()
)
});
///////////////////////////////////////////
//////// Processing Storage ///////
///////////////////////////////////////////
this.storage = new CacheStorage(this, 'Storage', {
encryptionKey: props.kmsKey
});
///////////////////////////////////////////
////// Middleware Event Handler ////
///////////////////////////////////////////
this.processor = new node.NodejsFunction(this, 'Processor', {
description: 'Inflates tarballs from a source to a destination bucket.',
entry: path.resolve(__dirname, 'lambdas', 'inflater', '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,
PROCESSED_FILES_BUCKET: this.storage.id(),
SNS_TARGET_TOPIC: this.eventBus.topicArn
},
bundling: {
minify: true,
externalModules: [
'@aws-sdk/client-s3',
'@aws-sdk/client-sns',
'@aws-sdk/lib-storage'
]
}
});
// 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 ?? 1,
reportBatchItemFailures: true
}));
// Grant the lambda function permissions to
// write to the post-processing storage.
this.storage.grantWrite(this.processor);
// Grant the lambda function permissions to
// publish to the SNS topic.
this.eventBus.grantPublish(this.processor);
super.bind();
} | /**
* Construct constructor.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/binary-processors/tar-processor/src/impl/tar-inflate/index.ts#L109-L179 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TarInflateProcessor.grantReadProcessedDocuments | public 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/binary-processors/tar-processor/src/impl/tar-inflate/index.ts#L185-L187 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TarInflateProcessor.supportedInputTypes | supportedInputTypes(): string[] {
return ([
'application/x-tar',
'application/x-gzip'
]);
} | /**
* @returns an array of mime-types supported as input
* type by this middleware.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/binary-processors/tar-processor/src/impl/tar-inflate/index.ts#L193-L198 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TarInflateProcessor.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/binary-processors/tar-processor/src/impl/tar-inflate/index.ts#L204-L208 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TarInflateProcessor.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/binary-processors/tar-processor/src/impl/tar-inflate/index.ts#L214-L218 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TarInflateProcessor.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/binary-processors/tar-processor/src/impl/tar-inflate/index.ts#L227-L232 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.createEntryListener | private createEntryListener(event: CloudEvent, destinationBucket: string) {
const emitter = new events.EventEmitter();
const document = event.data().document();
const prefix = `${event.data().chainId()}/${document.etag()}`;
return {
handler: (header: tar.Headers, stream: any, next: tar.Callback) => {
// We signal the end of the entry read to the tar stream.
stream.on('end', next);
if (header.type === 'file') {
const mimeType = mimeTypeFromExtension(header.name);
// Create a write stream to the destination bucket.
const { writeStream, promise } = s3Stream.createS3WriteStream({
bucket: destinationBucket,
key: path.join(prefix, header.name),
contentType: mimeType
});
// Write the unzipped file to the destination bucket.
stream.pipe(writeStream);
// Listens for file write completion events and notify the
// next middlewares.
emitter.emit('write-promise', promise.then((res) => {
return (this.onDocumentCreated(res, mimeType, header.size!, event));
}));
} else {
stream.resume();
}
},
on: (event: string, handler: (...args: any[]) => void) => emitter.on(event, handler)
};
} | /**
* Handles each entry in the archive and pipes
* the entry into the S3 destination stream.
* @param event the CloudEvent to process.
* @param destinationBucket the bucket where to pipe the entry.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/binary-processors/tar-processor/src/impl/tar-inflate/lambdas/inflater/index.ts#L108-L139 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.inflate | private async inflate(event: CloudEvent, destBucket: string) {
const pipeline = util.promisify(stream.pipeline);
const document = event.data().document();
const extract = tar.extract();
const uploads: Promise<any>[] = [];
// Create a read stream to the archive.
const readStream = await document.data().asReadStream();
// Create a listener for each entry in the archive.
const listener = this.createEntryListener(event, destBucket);
// We enqueue the promises from the S3 streams
// into the `uploads` array to be able to wait
// for the successful writes on the destination bucket.
listener.on('write-promise', (p: Promise<any>) => uploads.push(p));
// We listen for each entry in the archive and forward
// them to the listener which will initiate a write to the
// destination bucket.
extract.on('entry', listener.handler);
// Initiate the pipeline and wait for the
// stream to be consumed.
await pipeline(
readStream,
gunzip(),
extract
);
// Wait for all the writes to be completed.
return (Promise.all(uploads));
} | /**
* Processes the given event and inflates the tarball
* associated with the event.
* @param event the event to process.
* @param destBucket the destination bucket where
* to inflate the resulting files.
* @returns a promise which resolves when the
* process is complete.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/binary-processors/tar-processor/src/impl/tar-inflate/lambdas/inflater/index.ts#L150-L182 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.recordHandler | recordHandler(record: SQSRecord): Promise<any> {
return (this.inflate(
CloudEvent.from(JSON.parse(record.body)),
PROCESSED_FILES_BUCKET
));
} | /**
* Inflates the document associated with the record
* in the target S3 bucket.
* @param record the SQS record associated with
* the document to inflate.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/binary-processors/tar-processor/src/impl/tar-inflate/lambdas/inflater/index.ts#L190-L195 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.handler | public async handler(event: SQSEvent, _: Context) {
return (await processPartialResponse(
event, this.recordHandler.bind(this), processor
));
} | // eslint-disable-next-line @typescript-eslint/no-unused-vars | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/binary-processors/tar-processor/src/impl/tar-inflate/lambdas/inflater/index.ts#L205-L209 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ZipDeflateProcessorBuilder.withCompressionLevel | public withCompressionLevel(level: number): this {
this.providerProps.compressionLevel = level;
return (this);
} | /**
* Sets the compression level to use when creating
* Zip archives.
* @param level the compression level.
* @returns the builder instance.
* @default 9
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/binary-processors/zip-processor/src/impl/zip-deflate/index.ts#L78-L81 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ZipDeflateProcessorBuilder.build | public build(): ZipDeflateProcessor {
return (new ZipDeflateProcessor(
this.scope,
this.identifier, {
...this.providerProps as ZipDeflateProcessorProps,
...this.props
}
));
} | /**
* @returns a new instance of the `ZipDeflateProcessor`
* service constructed with the given parameters.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/binary-processors/zip-processor/src/impl/zip-deflate/index.ts#L87-L95 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ZipDeflateProcessor.constructor | constructor(scope: Construct, id: string, private props: ZipDeflateProcessorProps) {
super(scope, id, description, {
...props,
queueVisibilityTimeout: cdk.Duration.seconds(
3 * PROCESSING_TIMEOUT.toSeconds()
)
});
// Validate the properties.
this.props = this.parse(ZipDeflateProcessorPropsSchema, props);
///////////////////////////////////////////
//////// Processing Storage ///////
///////////////////////////////////////////
this.storage = new CacheStorage(this, 'Storage', {
encryptionKey: props.kmsKey
});
///////////////////////////////////////////
////// Middleware Event Handler ////
///////////////////////////////////////////
this.processor = new node.NodejsFunction(this, 'Processor', {
description: 'Creates ZIP archives from input documents.',
entry: path.resolve(__dirname, 'lambdas', 'zip', '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,
PROCESSED_FILES_BUCKET: this.storage.id(),
SNS_TARGET_TOPIC: this.eventBus.topicArn,
COMPRESSION_LEVEL: this.props.compressionLevel?.toString()
},
bundling: {
minify: true,
externalModules: [
'@aws-sdk/client-s3',
'@aws-sdk/client-sns',
'@aws-sdk/lib-storage'
]
}
});
// 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 ?? 1,
reportBatchItemFailures: true
}));
// Grant the lambda function permissions to
// write to the post-processing storage.
this.storage.grantWrite(this.processor);
// Grant the lambda function permissions to
// publish to the SNS topic.
this.eventBus.grantPublish(this.processor);
super.bind();
} | /**
* Construct constructor.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/binary-processors/zip-processor/src/impl/zip-deflate/index.ts#L122-L196 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ZipDeflateProcessor.grantReadProcessedDocuments | public 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/binary-processors/zip-processor/src/impl/zip-deflate/index.ts#L202-L204 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ZipDeflateProcessor.supportedInputTypes | supportedInputTypes(): string[] {
return ([
'*/*'
]);
} | /**
* @returns an array of mime-types supported as input
* type by this middleware.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/binary-processors/zip-processor/src/impl/zip-deflate/index.ts#L210-L214 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ZipDeflateProcessor.supportedOutputTypes | supportedOutputTypes(): string[] {
return ([
'application/zip'
]);
} | /**
* @returns an array of mime-types supported as output
* type by the data producer.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/binary-processors/zip-processor/src/impl/zip-deflate/index.ts#L220-L224 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ZipDeflateProcessor.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/binary-processors/zip-processor/src/impl/zip-deflate/index.ts#L230-L234 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ZipDeflateProcessor.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/binary-processors/zip-processor/src/impl/zip-deflate/index.ts#L243-L248 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.resolveEvents | private async resolveEvents(event: CloudEvent): Promise<CloudEvent[]> {
const document = event.data().document();
if (document.mimeType() === 'application/cloudevents+json') {
const data = JSON.parse((await document
.data()
.asBuffer())
.toString('utf-8')
);
return (data.map((event: string) => CloudEvent.from(event)));
} else {
return ([event]);
}
} | /**
* Resolves the input documents to process.
* This function supports both single and composite events.
* @param event the received event.
* @returns a promise to an array of CloudEvents to process.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/binary-processors/zip-processor/src/impl/zip-deflate/lambdas/zip/index.ts#L95-L108 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.zip | private async zip(events: CloudEvent[], destBucket: string) {
const outputKey = `${randomUUID()}/archive.zip`;
// Create a new archiver instance.
const archive = archiver('zip', {
zlib: { level: COMPRESSION_LEVEL }
});
// Create a write stream to the destination bucket.
const { writeStream, promise } = s3Stream.createS3WriteStream({
bucket: destBucket,
key: outputKey,
contentType: 'application/zip'
});
// Pipe the archive to the write stream.
archive.pipe(writeStream);
// Append each document read stream to the archive.
for (const event of events) {
const document = event.data().document();
const etag = document.etag();
const name = `${event.data().chainId()}/${etag}-${document.filename().basename()}`;
archive.append(await document.data().asReadStream(), { name });
}
// Wait for the process to complete.
await archive.finalize();
const res = await promise;
// Forward the document to the next middlewares.
return (this.onArchiveCreated(res, archive.pointer()));
} | /**
* Processes the given event and zips the documents
* associated with it into the bucket passed as `destBucket`.
* The entire operation happens in streaming to avoid loading
* the entirety of the zip file in memory.
* @param events the events to process.
* @param destBucket the destination bucket where
* to unzip the resulting files.
* @returns a promise which resolves when the
* unzip process is complete.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/binary-processors/zip-processor/src/impl/zip-deflate/lambdas/zip/index.ts#L121-L153 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.recordHandler | async recordHandler(record: SQSRecord): Promise<any> {
return (this.zip(
await this.resolveEvents(CloudEvent.from(JSON.parse(record.body))),
TARGET_BUCKET
));
} | /**
* Deflates the document associated with the record
* in the target S3 bucket.
* @param record the SQS record associated with
* the document to inflate.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/binary-processors/zip-processor/src/impl/zip-deflate/lambdas/zip/index.ts#L161-L166 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.handler | async handler(event: SQSEvent, _: Context): Promise<SQSBatchResponse> {
return (await processPartialResponse(
event, this.recordHandler.bind(this), processor
));
} | // eslint-disable-next-line @typescript-eslint/no-unused-vars | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/binary-processors/zip-processor/src/impl/zip-deflate/lambdas/zip/index.ts#L176-L180 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ZipInflateProcessorBuilder.build | public build(): ZipInflateProcessor {
return (new ZipInflateProcessor(
this.scope,
this.identifier, {
...this.props
}
));
} | /**
* @returns a new instance of the `ZipInflateProcessor`
* service constructed with the given parameters.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/binary-processors/zip-processor/src/impl/zip-inflate/index.ts#L74-L81 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ZipInflateProcessor.constructor | constructor(scope: Construct, id: string, props: MiddlewareProps) {
super(scope, id, description, {
...props,
queueVisibilityTimeout: cdk.Duration.seconds(
3 * PROCESSING_TIMEOUT.toSeconds()
)
});
///////////////////////////////////////////
//////// Processing Storage ///////
///////////////////////////////////////////
this.storage = new CacheStorage(this, 'Storage', {
encryptionKey: props.kmsKey
});
///////////////////////////////////////////
////// Middleware Event Handler ////
///////////////////////////////////////////
this.processor = new node.NodejsFunction(this, 'Processor', {
description: 'Inflates ZIP archives from a source to a destination bucket.',
entry: path.resolve(__dirname, 'lambdas', 'unzip', '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,
PROCESSED_FILES_BUCKET: this.storage.id(),
SNS_TARGET_TOPIC: this.eventBus.topicArn
},
bundling: {
minify: true,
externalModules: [
'@aws-sdk/client-s3',
'@aws-sdk/client-sns',
'@aws-sdk/lib-storage'
]
}
});
// 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 ?? 1,
reportBatchItemFailures: true
}));
// Grant the lambda function permissions to
// write to the post-processing storage.
this.storage.grantWrite(this.processor);
// Grant the lambda function permissions to
// publish to the SNS topic.
this.eventBus.grantPublish(this.processor);
super.bind();
} | /**
* Construct constructor.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/binary-processors/zip-processor/src/impl/zip-inflate/index.ts#L109-L179 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ZipInflateProcessor.grantReadProcessedDocuments | public 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/binary-processors/zip-processor/src/impl/zip-inflate/index.ts#L185-L187 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ZipInflateProcessor.supportedInputTypes | supportedInputTypes(): string[] {
return ([
'application/zip'
]);
} | /**
* @returns an array of mime-types supported as input
* type by this middleware.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/binary-processors/zip-processor/src/impl/zip-inflate/index.ts#L193-L197 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ZipInflateProcessor.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/binary-processors/zip-processor/src/impl/zip-inflate/index.ts#L203-L207 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ZipInflateProcessor.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/binary-processors/zip-processor/src/impl/zip-inflate/index.ts#L213-L217 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ZipInflateProcessor.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/binary-processors/zip-processor/src/impl/zip-inflate/index.ts#L226-L231 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.pipeToS3 | private pipeToS3(event: CloudEvent, destinationBucket: string) {
const document = event.data().document();
const prefix = `${event.data().chainId()}/${document.etag()}`;
return async (entry: Entry) => {
if (entry.type !== 'Directory') {
// Compute the mime type of the file.
const mimeType = mimeTypeFromExtension(entry.path);
// Create a write stream to the destination bucket.
const { writeStream, promise } = s3Stream.createS3WriteStream({
bucket: destinationBucket,
key: path.join(prefix, entry.path),
contentType: mimeType
});
entry.pipe(writeStream);
// Wait for the upload to complete and send the
// extracted document to the next middlewares.
await promise.then((res) => {
// @ts-expect-error
return (this.onDocumentCreated(res, mimeType, entry.vars.uncompressedSize, event));
});
} else {
entry.autodrain();
}
};
} | /**
* Handles each entry in the zip archive and pipes
* the entry into the S3 destination stream.
* @param event the CloudEvent to process.
* @param destinationBucket the bucket where to pipe the entry.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/binary-processors/zip-processor/src/impl/zip-inflate/lambdas/unzip/index.ts#L107-L132 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.unzip | private async unzip(event: CloudEvent, destBucket: string) {
const pipeline = util.promisify(stream.pipeline);
const document = event.data().document();
// Create a read stream to the zip archive.
const readStream = await document.data().asReadStream();
// Unzip the archive in streaming.
return (pipeline(
readStream,
Parse(),
streamz(this.pipeToS3(event, destBucket))
));
} | /**
* Processes the given event and unzips the object
* associated with the document into the bucket
* passed as `destBucket`.
* The entire operation happens in streaming to avoid loading
* the entirety of the zip file in memory.
* @param event the CloudEvent to process.
* @param destBucket the destination bucket where
* to unzip the resulting files.
* @returns a promise which resolves when the
* unzip process is complete.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/binary-processors/zip-processor/src/impl/zip-inflate/lambdas/unzip/index.ts#L146-L159 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.recordHandler | recordHandler(record: SQSRecord): Promise<any> {
return (this.unzip(
CloudEvent.from(JSON.parse(record.body)),
TARGET_BUCKET
));
} | /**
* Inflates the document associated with the record
* in the target S3 bucket.
* @param record the SQS record associated with
* the document to inflate.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/binary-processors/zip-processor/src/impl/zip-inflate/lambdas/unzip/index.ts#L167-L172 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.handler | async handler(event: SQSEvent, _: Context): Promise<SQSBatchResponse> {
return (await processPartialResponse(
event, this.recordHandler.bind(this), processor
));
} | // eslint-disable-next-line @typescript-eslint/no-unused-vars | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/binary-processors/zip-processor/src/impl/zip-inflate/lambdas/unzip/index.ts#L182-L186 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TitanEmbeddingProcessorBuilder.withModel | public withModel(model: TitanEmbeddingModel) {
this.providerProps.model = model;
return (this);
} | /**
* Sets the embedding model to use.
* @param model the embedding model to use.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/embedding-processors/bedrock-embedding-processor/src/impl/amazon-titan/index.ts#L75-L78 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TitanEmbeddingProcessorBuilder.withRegion | public withRegion(region: string) {
this.providerProps.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.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/embedding-processors/bedrock-embedding-processor/src/impl/amazon-titan/index.ts#L86-L89 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TitanEmbeddingProcessorBuilder.withEmbeddingSize | public withEmbeddingSize(size: 256 | 384 | 1024) {
this.providerProps.embeddingSize = size;
return (this);
} | /**
* Sets the size of the embedding to generate.
* @note this is only valid for multimodal models.
* @param size the size of the embedding to generate.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/embedding-processors/bedrock-embedding-processor/src/impl/amazon-titan/index.ts#L96-L99 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TitanEmbeddingProcessorBuilder.build | public build(): TitanEmbeddingProcessor {
return (new TitanEmbeddingProcessor(
this.scope,
this.identifier, {
...this.providerProps as BedrockEmbeddingProps,
...this.props
}
));
} | /**
* @returns a new instance of the `TitanEmbeddingProcessor`
* service constructed with the given parameters.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/embedding-processors/bedrock-embedding-processor/src/impl/amazon-titan/index.ts#L105-L113 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TitanEmbeddingProcessor.constructor | constructor(scope: Construct, id: string, private props: BedrockEmbeddingProps) {
super(scope, id, description, {
...props,
queueVisibilityTimeout: cdk.Duration.seconds(
6 * PROCESSING_TIMEOUT.toSeconds()
)
});
// Validate the properties.
this.props = this.parse(BedrockEmbeddingPropsSchema, props);
// Validate that the selected model does support
// setting the embedding size.
if (this.props.embeddingSize && !this.props.model.props.supportsEmbeddingSize) {
throw new Error('Setting an embedding size is not supported by the given model.');
}
/////////////////////////////////////////
///// Middleware Event Handler /////
/////////////////////////////////////////
this.processor = new node.NodejsFunction(this, 'Compute', {
description: 'A function creating vector embeddings using Amazon Titan models.',
entry: path.resolve(__dirname, 'lambdas', 'vectorizer', '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,
LAKECHAIN_CACHE_STORAGE: this.props.cacheStorage.id(),
EMBEDDING_MODEL: JSON.stringify(this.props.model),
BEDROCK_REGION: this.props.region ?? '',
EMBEDDING_SIZE: this.props.embeddingSize?.toString() ?? ''
},
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.processor.grantPrincipal;
// Allow access to the Bedrock API.
this.processor.addToRolePolicy(new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: [
'bedrock:InvokeModel'
],
resources: [
`arn:${cdk.Aws.PARTITION}:bedrock:${this.props.region}::foundation-model/${this.props.model.name}`
]
}));
// Plug the SQS queue into the lambda function.
this.processor.addEventSource(new sources.SqsEventSource(this.eventQueue, {
batchSize: props.batchSize ?? 2,
maxConcurrency: this.props.maxConcurrency ?? 5,
reportBatchItemFailures: true
}));
// Grant the lambda function permissions to
// publish to the SNS topic.
this.eventBus.grantPublish(this.processor);
super.bind();
} | /**
* Construct constructor.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/embedding-processors/bedrock-embedding-processor/src/impl/amazon-titan/index.ts#L141-L222 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TitanEmbeddingProcessor.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);
}
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/embedding-processors/bedrock-embedding-processor/src/impl/amazon-titan/index.ts#L228-L237 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TitanEmbeddingProcessor.supportedInputTypes | supportedInputTypes(): string[] {
return (this.props.model.props.inputs);
} | /**
* @returns an array of mime-types supported as input
* type by this middleware.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/embedding-processors/bedrock-embedding-processor/src/impl/amazon-titan/index.ts#L243-L245 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TitanEmbeddingProcessor.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/embedding-processors/bedrock-embedding-processor/src/impl/amazon-titan/index.ts#L251-L253 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TitanEmbeddingProcessor.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/embedding-processors/bedrock-embedding-processor/src/impl/amazon-titan/index.ts#L259-L263 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TitanEmbeddingProcessor.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/embedding-processors/bedrock-embedding-processor/src/impl/amazon-titan/index.ts#L272-L277 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TitanEmbeddingModel.of | public static of(name: string, props: TitanModelProps) {
return (new TitanEmbeddingModel(name, props));
} | /**
* Create a new instance of the `TitanEmbeddingModel`
* by name.
* @param name the name of the model.
* @param props the properties of the embedding model.
* @returns a new instance of the `TitanEmbeddingModel`.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/embedding-processors/bedrock-embedding-processor/src/impl/amazon-titan/definitions/embedding-model.ts#L92-L94 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | TitanEmbeddingModel.constructor | constructor(public name: string, public props: TitanModelProps) {} | /**
* `TitanEmbeddingModel` constructor.
* @param name the name of the embedding model.
* @param props the properties of the embedding model.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/embedding-processors/bedrock-embedding-processor/src/impl/amazon-titan/definitions/embedding-model.ts#L101-L101 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.vectorize | private async vectorize(input: string | Buffer): Promise<number[]> {
const body: any = {};
// Set the input text or image.
if (Buffer.isBuffer(input)) {
body['inputImage'] = input.toString('base64');
} else {
body['inputText'] = input;
}
// Set the embedding size if provided.
if (EMBEDDING_SIZE) {
body['embeddingConfig'] = {
outputEmbeddingLength: EMBEDDING_SIZE
};
}
// Invoke the embedding model.
const response = await bedrock.invokeModel({
body: JSON.stringify(body),
modelId: EMBEDDING_MODEL.name,
accept: 'application/json',
contentType: 'application/json'
});
// Parse the response as a JSON object.
return (JSON.parse(response.body.transformToString()).embedding);
} | /**
* Creates vector embeddings for the given input.
* @param input a string or image buffer to vectorize.
* @returns a promise that resolves to the vector embeddings.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/embedding-processors/bedrock-embedding-processor/src/impl/amazon-titan/lambdas/vectorizer/index.ts#L78-L105 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.recordHandler | async recordHandler(record: SQSRecord): Promise<CloudEvent> {
return (await this.processEvent(
CloudEvent.from(JSON.parse(record.body))
));
} | /**
* @param record the SQS record to process that contains
* the EventBridge event providing information about the
* S3 event.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/embedding-processors/bedrock-embedding-processor/src/impl/amazon-titan/lambdas/vectorizer/index.ts#L154-L158 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.handler | public async handler(event: SQSEvent, _: Context) {
return (await processPartialResponse(
event, this.recordHandler.bind(this), processor
));
} | // eslint-disable-next-line @typescript-eslint/no-unused-vars | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/embedding-processors/bedrock-embedding-processor/src/impl/amazon-titan/lambdas/vectorizer/index.ts#L168-L172 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | CohereEmbeddingProcessorBuilder.withModel | public withModel(model: CohereEmbeddingModel) {
this.providerProps.model = model;
return (this);
} | /**
* Sets the embedding model to use.
* @param model the embedding model to use.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/embedding-processors/bedrock-embedding-processor/src/impl/cohere/index.ts#L75-L78 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | CohereEmbeddingProcessorBuilder.withRegion | public withRegion(region: string) {
this.providerProps.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.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/embedding-processors/bedrock-embedding-processor/src/impl/cohere/index.ts#L86-L89 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | CohereEmbeddingProcessorBuilder.build | public build(): CohereEmbeddingProcessor {
return (new CohereEmbeddingProcessor(
this.scope,
this.identifier, {
...this.providerProps as CohereEmbeddingProps,
...this.props
}
));
} | /**
* @returns a new instance of the `CohereEmbeddingProcessor`
* service constructed with the given parameters.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/embedding-processors/bedrock-embedding-processor/src/impl/cohere/index.ts#L95-L103 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | CohereEmbeddingProcessor.constructor | constructor(scope: Construct, id: string, props: CohereEmbeddingProps) {
super(scope, id, description, {
...props,
queueVisibilityTimeout: cdk.Duration.seconds(
6 * PROCESSING_TIMEOUT.toSeconds()
)
});
// Validate the properties.
props = this.parse(CohereEmbeddingPropsSchema, props);
/////////////////////////////////////////
///// Middleware Event Handler /////
/////////////////////////////////////////
this.processor = new node.NodejsFunction(this, 'Compute', {
description: 'A function creating vector embeddings using Cohere models.',
entry: path.resolve(__dirname, 'lambdas', 'vectorizer', '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,
LAKECHAIN_CACHE_STORAGE: props.cacheStorage.id(),
EMBEDDING_MODEL: JSON.stringify(props.model),
BEDROCK_REGION: props.region ?? ''
},
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.processor.grantPrincipal;
// Allow access to the Bedrock API.
this.processor.addToRolePolicy(new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: [
'bedrock:InvokeModel'
],
resources: [
`arn:${cdk.Aws.PARTITION}:bedrock:${props.region}::foundation-model/${props.model.name}`,
]
}));
// Plug the SQS queue into the lambda function.
this.processor.addEventSource(new sources.SqsEventSource(this.eventQueue, {
batchSize: props.batchSize ?? 2,
maxConcurrency: 5,
reportBatchItemFailures: true
}));
// Grant the lambda function permissions to
// publish to the SNS topic.
this.eventBus.grantPublish(this.processor);
super.bind();
} | /**
* Construct constructor.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/embedding-processors/bedrock-embedding-processor/src/impl/cohere/index.ts#L131-L205 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | CohereEmbeddingProcessor.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);
}
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/embedding-processors/bedrock-embedding-processor/src/impl/cohere/index.ts#L211-L220 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | CohereEmbeddingProcessor.supportedInputTypes | supportedInputTypes(): string[] {
return ([
'text/plain',
'text/markdown'
]);
} | /**
* @returns an array of mime-types supported as input
* type by this middleware.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/embedding-processors/bedrock-embedding-processor/src/impl/cohere/index.ts#L226-L231 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | CohereEmbeddingProcessor.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/embedding-processors/bedrock-embedding-processor/src/impl/cohere/index.ts#L237-L239 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | CohereEmbeddingProcessor.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/embedding-processors/bedrock-embedding-processor/src/impl/cohere/index.ts#L245-L249 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | CohereEmbeddingProcessor.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/embedding-processors/bedrock-embedding-processor/src/impl/cohere/index.ts#L258-L263 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | CohereEmbeddingModel.of | public static of(name: string, props?: CohereModelProps) {
return (new CohereEmbeddingModel(name, props));
} | /**
* Create a new instance of the `CohereEmbeddingModel`
* by name.
* @param name the name of the model.
* @param props the properties of the embedding model.
* @returns a new instance of the `CohereEmbeddingModel`.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/embedding-processors/bedrock-embedding-processor/src/impl/cohere/definitions/embedding-model.ts#L64-L66 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.recordHandler | async recordHandler(record: SQSRecord): Promise<CloudEvent> {
return (await this.processEvent(
CloudEvent.from(JSON.parse(record.body))
));
} | /**
* @param record the SQS record to process that contains
* the EventBridge event providing information about the
* S3 event.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/embedding-processors/bedrock-embedding-processor/src/impl/cohere/lambdas/vectorizer/index.ts#L117-L121 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | Lambda.handler | public async handler(event: SQSEvent, _: Context) {
return (await processPartialResponse(
event, this.recordHandler.bind(this), processor
));
} | // eslint-disable-next-line @typescript-eslint/no-unused-vars | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/embedding-processors/bedrock-embedding-processor/src/impl/cohere/lambdas/vectorizer/index.ts#L131-L135 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ClipImageProcessorBuilder.withModel | public withModel(model: ClipModel) {
this.providerProps.model = model;
return (this);
} | /**
* Sets the Clip model to use.
* @param model the Clip model to use.
* @default ViT-B/32
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/embedding-processors/clip-image-processor/src/index.ts#L63-L66 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ClipImageProcessorBuilder.withMaxInstances | public withMaxInstances(maxInstances: number) {
this.providerProps.maxInstances = maxInstances;
return (this);
} | /**
* The maximum amount of instances the
* cluster can have. Keep this number to
* a reasonable value to avoid over-provisioning
* the cluster.
* @param maxInstances the maximum amount of instances.
* @default 5
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/embedding-processors/clip-image-processor/src/index.ts#L76-L79 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ClipImageProcessorBuilder.withLabelExtraction | public withLabelExtraction(extractLabels: boolean) {
this.providerProps.extractLabels = extractLabels;
return (this);
} | /**
* Whether to extract labels from the images
* as keywords in the document metadata.
* @param extractLabels whether to extract labels.
* @default true
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/embedding-processors/clip-image-processor/src/index.ts#L87-L90 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ClipImageProcessorBuilder.build | public build(): ClipImageProcessor {
return (new ClipImageProcessor(
this.scope,
this.identifier, {
...this.providerProps as ClipImageProcessorProps,
...this.props
}
));
} | /**
* @returns a new instance of the `ClipImageProcessor`
* service constructed with the given parameters.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/embedding-processors/clip-image-processor/src/index.ts#L96-L104 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ClipImageProcessor.constructor | constructor(scope: Construct, id: string, private props: ClipImageProcessorProps) {
super(scope, id, description, props);
// Validate the properties.
this.props = this.parse(ClipImageProcessorPropsSchema, props);
///////////////////////////////////////////
///////// ECS Container /////////
///////////////////////////////////////////
const image = ecs.ContainerImage.fromDockerImageAsset(
new assets.DockerImageAsset(this, 'ClipImage', {
directory: path.resolve(__dirname, 'container'),
platform: assets.Platform.LINUX_AMD64
})
);
// Use the ECS container middleware pattern to create an
// auto-scaled ECS cluster, an EFS mounted on the cluster's tasks
// and all the components required to manage the cluster.
const cluster = new EcsCluster(this, 'Cluster', {
vpc: this.props.vpc,
eventQueue: this.eventQueue,
eventBus: this.eventBus,
kmsKey: this.props.kmsKey,
logGroup: this.logGroup,
containerProps: {
image,
containerName: 'clip-image-processor',
cpuLimit: 4096,
memoryLimitMiB: 8192,
gpuCount: 1,
environment: {
POWERTOOLS_SERVICE_NAME: description.name,
CLIP_MODEL: this.props.model,
LAKECHAIN_CACHE_STORAGE: this.props.cacheStorage.id(),
CACHE_DIR: '/cache',
EXTRACT_LABELS: this.props.extractLabels ? 'true' : 'false'
}
},
autoScaling: {
minInstanceCapacity: 0,
maxInstanceCapacity: this.props.maxInstances,
maxTaskCapacity: this.props.maxInstances,
maxMessagesPerTask: 10
},
launchTemplateProps: {
instanceType: DEFAULT_INSTANCE_TYPE,
machineImage: ecs.EcsOptimizedImage.amazonLinux2(
ecs.AmiHardwareType.GPU
),
ebsOptimized: true,
blockDevices: [{
deviceName: '/dev/xvda',
volume: ec2.BlockDeviceVolume.ebs(80)
}],
userData: ec2.UserData.forLinux()
},
fileSystem: {
throughputMode: efs.ThroughputMode.ELASTIC,
readonly: false,
containerPath: '/cache',
accessPoint: {
uid: 1000,
gid: 1000,
permission: 750
}
},
containerInsights: this.props.cloudWatchInsights
});
// Allows this construct to act as a `IGrantable`
// for other middlewares to grant the processing
// lambda permissions to access their resources.
this.grantPrincipal = cluster.taskRole.grantPrincipal;
super.bind();
} | /**
* Provider constructor.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/embedding-processors/clip-image-processor/src/index.ts#L124-L201 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ClipImageProcessor.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);
}
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/embedding-processors/clip-image-processor/src/index.ts#L207-L216 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ClipImageProcessor.supportedInputTypes | supportedInputTypes(): string[] {
return ([
'image/bmp',
'image/gif',
'image/jpeg',
'image/png',
'image/tiff',
'image/webp',
'image/x-pcx'
]);
} | /**
* @returns an array of mime-types supported as input
* type by this middleware.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/embedding-processors/clip-image-processor/src/index.ts#L222-L232 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ClipImageProcessor.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/embedding-processors/clip-image-processor/src/index.ts#L238-L240 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ClipImageProcessor.supportedComputeTypes | supportedComputeTypes(): ComputeType[] {
return ([
ComputeType.GPU
]);
} | /**
* @returns the supported compute types by a given
* middleware.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/embedding-processors/clip-image-processor/src/index.ts#L246-L250 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | ClipImageProcessor.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/embedding-processors/clip-image-processor/src/index.ts#L259-L264 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | OllamaEmbeddingProcessorBuilder.withModel | public withModel(model: OllamaEmbeddingModel) {
this.providerProps.model = model;
return (this);
} | /**
* Sets the Ollama embedding model to use.
* @param model the identifier of the Ollama embedding model to use.
* @see https://ollama.com/library
* @returns the builder instance.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/embedding-processors/ollama-embedding-processor/src/index.ts#L72-L75 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | OllamaEmbeddingProcessorBuilder.withInfrastructure | public withInfrastructure(infrastructure: InfrastructureDefinition) {
this.providerProps.infrastructure = infrastructure;
return (this);
} | /**
* Sets the infrastructure to use to run the ollama model.
* @param instanceType the instance type to use.
* @returns the builder instance.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/embedding-processors/ollama-embedding-processor/src/index.ts#L82-L85 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | OllamaEmbeddingProcessorBuilder.build | public build(): OllamaEmbeddingProcessor {
return (new OllamaEmbeddingProcessor(
this.scope,
this.identifier, {
...this.providerProps as OllamaEmbeddingProcessorProps,
...this.props
}
));
} | /**
* @returns a new instance of the `OllamaEmbeddingProcessor`
* service constructed with the given parameters.
*/ | https://github.com/awslabs/project-lakechain/blob/4285173e80584eedfc1a8424d3d1b6c1a7038088/packages/middlewares/embedding-processors/ollama-embedding-processor/src/index.ts#L91-L99 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | OllamaEmbeddingProcessor.constructor | constructor(scope: Construct, id: string, private props: OllamaEmbeddingProcessorProps) {
super(scope, id, description, {
...props,
queueVisibilityTimeout: cdk.Duration.minutes(2)
});
// Validate the properties.
this.props = this.parse(OllamaEmbeddingProcessorPropsSchema, props);
///////////////////////////////////////////
///////// ECS Container /////////
///////////////////////////////////////////
// Create the configuration for the ECS cluster.
const configuration = getConfiguration(this.props.infrastructure);
// The container image to provision the ECS tasks with.
const image = ecs.ContainerImage.fromDockerImageAsset(
new assets.DockerImageAsset(this, 'OllamaEmbeddingImage', {
directory: path.resolve(__dirname, 'container'),
platform: configuration.container.platform
})
);
// Use the ECS container middleware pattern to create an
// auto-scaled ECS cluster, an EFS mounted on the cluster's tasks
// and all the components required to manage the cluster.
// This cluster supports both CPU and GPU instances.
const cluster = new EcsCluster(this, 'Cluster', {
vpc: this.props.vpc,
eventQueue: this.eventQueue,
eventBus: this.eventBus,
kmsKey: this.props.kmsKey,
logGroup: this.logGroup,
containerProps: {
image,
containerName: 'ollama-embedding-processor',
memoryLimitMiB: configuration.memoryLimitMiB,
gpuCount: configuration.gpuCount,
environment: {
POWERTOOLS_SERVICE_NAME: description.name,
LAKECHAIN_CACHE_STORAGE: this.props.cacheStorage.id(),
OLLAMA_MODEL: `${this.props.model.name}:${this.props.model.definition.tag}`,
OLLAMA_MODELS: '/cache',
OLLAMA_NUM_PARALLEL: `${this.props.batchSize}`,
OLLAMA_MAX_LOADED_MODELS: `${OLLAMA_MAX_LOADED_MODELS}`
}
},
autoScaling: {
minInstanceCapacity: 0,
maxInstanceCapacity: this.props.maxConcurrency,
maxTaskCapacity: this.props.maxConcurrency,
maxMessagesPerTask: this.props.batchSize,
},
launchTemplateProps: {
instanceType: configuration.instanceType,
machineImage: configuration.machineImage,
ebsOptimized: true,
blockDevices: [{
deviceName: '/dev/xvda',
volume: ec2.BlockDeviceVolume.ebs(80)
}],
userData: ec2.UserData.forLinux()
},
fileSystem: {
throughputMode: efs.ThroughputMode.ELASTIC,
readonly: false,
containerPath: '/cache',
accessPoint: {
uid: 1000,
gid: 1000,
permission: 750
}
},
containerInsights: this.props.cloudWatchInsights
});
// Allows this construct to act as a `IGrantable`
// for other middlewares to grant the processing
// lambda permissions to access their resources.
this.grantPrincipal = cluster.taskRole.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/embedding-processors/ollama-embedding-processor/src/index.ts#L116-L203 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
project-lakechain | github_2023 | awslabs | typescript | OllamaEmbeddingProcessor.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);
}
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/embedding-processors/ollama-embedding-processor/src/index.ts#L209-L218 | 4285173e80584eedfc1a8424d3d1b6c1a7038088 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.