|
| 1 | +/* |
| 2 | + * Copyright (c) 2024 Airbyte, Inc., all rights reserved. |
| 3 | + */ |
| 4 | + |
| 5 | +package io.airbyte.cdk.load.toolkits.iceberg.parquet.io |
| 6 | + |
| 7 | +import io.airbyte.cdk.load.command.Dedupe |
| 8 | +import io.airbyte.cdk.load.command.DestinationStream |
| 9 | +import io.airbyte.cdk.load.command.ImportType |
| 10 | +import io.airbyte.cdk.load.data.MapperPipeline |
| 11 | +import io.airbyte.cdk.load.data.NullValue |
| 12 | +import io.airbyte.cdk.load.data.ObjectValue |
| 13 | +import io.airbyte.cdk.load.data.iceberg.parquet.toIcebergRecord |
| 14 | +import io.airbyte.cdk.load.data.iceberg.parquet.toIcebergSchema |
| 15 | +import io.airbyte.cdk.load.data.withAirbyteMeta |
| 16 | +import io.airbyte.cdk.load.message.DestinationRecordAirbyteValue |
| 17 | +import io.airbyte.cdk.load.toolkits.iceberg.parquet.TableIdGenerator |
| 18 | +import io.github.oshai.kotlinlogging.KotlinLogging |
| 19 | +import javax.inject.Singleton |
| 20 | +import org.apache.hadoop.conf.Configuration |
| 21 | +import org.apache.iceberg.CatalogUtil |
| 22 | +import org.apache.iceberg.FileFormat |
| 23 | +import org.apache.iceberg.Schema |
| 24 | +import org.apache.iceberg.SortOrder |
| 25 | +import org.apache.iceberg.Table |
| 26 | +import org.apache.iceberg.TableProperties.DEFAULT_FILE_FORMAT |
| 27 | +import org.apache.iceberg.catalog.Catalog |
| 28 | +import org.apache.iceberg.catalog.SupportsNamespaces |
| 29 | +import org.apache.iceberg.data.Record |
| 30 | +import org.apache.iceberg.exceptions.AlreadyExistsException |
| 31 | + |
| 32 | +private val logger = KotlinLogging.logger {} |
| 33 | + |
| 34 | +const val AIRBYTE_CDC_DELETE_COLUMN = "_ab_cdc_deleted_at" |
| 35 | + |
| 36 | +@Singleton |
| 37 | +class IcebergUtil(private val tableIdGenerator: TableIdGenerator) { |
| 38 | + class InvalidFormatException(message: String) : Exception(message) |
| 39 | + |
| 40 | + private val generationIdRegex = Regex("""ab-generation-id-\d+-e""") |
| 41 | + |
| 42 | + fun assertGenerationIdSuffixIsOfValidFormat(generationId: String) { |
| 43 | + if (!generationIdRegex.matches(generationId)) { |
| 44 | + throw InvalidFormatException( |
| 45 | + "Invalid format: $generationId. Expected format is 'ab-generation-id-<number>-e'", |
| 46 | + ) |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + fun constructGenerationIdSuffix(stream: DestinationStream): String { |
| 51 | + return constructGenerationIdSuffix(stream.generationId) |
| 52 | + } |
| 53 | + |
| 54 | + fun constructGenerationIdSuffix(generationId: Long): String { |
| 55 | + if (generationId < 0) { |
| 56 | + throw IllegalArgumentException( |
| 57 | + "GenerationId must be non-negative. Provided: $generationId", |
| 58 | + ) |
| 59 | + } |
| 60 | + return "ab-generation-id-${generationId}-e" |
| 61 | + } |
| 62 | + /** |
| 63 | + * Builds an Iceberg [Catalog]. |
| 64 | + * |
| 65 | + * @param catalogName The name of the catalog. |
| 66 | + * @param properties The map of catalog configuration properties. |
| 67 | + * @return The configured Iceberg [Catalog]. |
| 68 | + */ |
| 69 | + fun createCatalog(catalogName: String, properties: Map<String, String>): Catalog { |
| 70 | + return CatalogUtil.buildIcebergCatalog(catalogName, properties, Configuration()) |
| 71 | + } |
| 72 | + |
| 73 | + /** Create the namespace if it doesn't already exist. */ |
| 74 | + fun createNamespace(streamDescriptor: DestinationStream.Descriptor, catalog: Catalog) { |
| 75 | + val tableIdentifier = tableIdGenerator.toTableIdentifier(streamDescriptor) |
| 76 | + synchronized(tableIdentifier.namespace()) { |
| 77 | + if ( |
| 78 | + catalog is SupportsNamespaces && |
| 79 | + !catalog.namespaceExists(tableIdentifier.namespace()) |
| 80 | + ) { |
| 81 | + try { |
| 82 | + catalog.createNamespace(tableIdentifier.namespace()) |
| 83 | + logger.info { "Created namespace '${tableIdentifier.namespace()}'." } |
| 84 | + } catch (e: AlreadyExistsException) { |
| 85 | + // This exception occurs when multiple threads attempt to write to the same |
| 86 | + // namespace in parallel. |
| 87 | + // One thread may create the namespace successfully, causing the other threads |
| 88 | + // to encounter this exception |
| 89 | + // when they also try to create the namespace. |
| 90 | + logger.info { |
| 91 | + "Namespace '${tableIdentifier.namespace()}' was likely created by another thread during parallel operations." |
| 92 | + } |
| 93 | + } |
| 94 | + } |
| 95 | + } |
| 96 | + } |
| 97 | + |
| 98 | + /** |
| 99 | + * Builds (if necessary) an Iceberg [Table]. This includes creating the table's namespace if it |
| 100 | + * does not already exist. If the [Table] already exists, it is loaded from the [Catalog]. |
| 101 | + * |
| 102 | + * @param streamDescriptor The [DestinationStream.Descriptor] that contains the Airbyte stream's |
| 103 | + * namespace and name. |
| 104 | + * @param catalog The Iceberg [Catalog] that contains the [Table] or should contain it once |
| 105 | + * created. |
| 106 | + * @param schema The Iceberg [Schema] associated with the [Table]. |
| 107 | + * @param properties The [Table] configuration properties derived from the [Catalog]. |
| 108 | + * @return The Iceberg [Table], created if it does not yet exist. |
| 109 | + */ |
| 110 | + fun createTable( |
| 111 | + streamDescriptor: DestinationStream.Descriptor, |
| 112 | + catalog: Catalog, |
| 113 | + schema: Schema, |
| 114 | + properties: Map<String, String> |
| 115 | + ): Table { |
| 116 | + val tableIdentifier = tableIdGenerator.toTableIdentifier(streamDescriptor) |
| 117 | + return if (!catalog.tableExists(tableIdentifier)) { |
| 118 | + logger.info { "Creating Iceberg table '$tableIdentifier'...." } |
| 119 | + catalog |
| 120 | + .buildTable(tableIdentifier, schema) |
| 121 | + .withProperties(properties) |
| 122 | + .withProperty(DEFAULT_FILE_FORMAT, FileFormat.PARQUET.name.lowercase()) |
| 123 | + .withSortOrder(getSortOrder(schema = schema)) |
| 124 | + .create() |
| 125 | + } else { |
| 126 | + logger.info { "Loading Iceberg table $tableIdentifier ..." } |
| 127 | + catalog.loadTable(tableIdentifier) |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + /** |
| 132 | + * Converts an Airbyte [DestinationRecordAirbyteValue] into an Iceberg [Record]. The converted |
| 133 | + * record will be wrapped to include [Operation] information, which is used by the writer to |
| 134 | + * determine how to write the data to the underlying Iceberg files. |
| 135 | + * |
| 136 | + * @param record The Airbyte [DestinationRecordAirbyteValue] record to be converted for writing |
| 137 | + * by Iceberg. |
| 138 | + * @param stream The Airbyte [DestinationStream] that contains information about the stream. |
| 139 | + * @param tableSchema The Iceberg [Table] [Schema]. |
| 140 | + * @param pipeline The [MapperPipeline] used to convert the Airbyte record to an Iceberg record. |
| 141 | + * @return An Iceberg [Record] representation of the Airbyte [DestinationRecordAirbyteValue]. |
| 142 | + */ |
| 143 | + fun toRecord( |
| 144 | + record: DestinationRecordAirbyteValue, |
| 145 | + stream: DestinationStream, |
| 146 | + tableSchema: Schema, |
| 147 | + pipeline: MapperPipeline |
| 148 | + ): Record { |
| 149 | + val dataMapped = |
| 150 | + pipeline |
| 151 | + .map(record.data, record.meta?.changes) |
| 152 | + .withAirbyteMeta(stream, record.emittedAtMs, true) |
| 153 | + // TODO figure out how to detect the actual operation value |
| 154 | + return RecordWrapper( |
| 155 | + delegate = dataMapped.toIcebergRecord(tableSchema), |
| 156 | + operation = getOperation(record = record, importType = stream.importType) |
| 157 | + ) |
| 158 | + } |
| 159 | + |
| 160 | + fun toIcebergSchema(stream: DestinationStream, pipeline: MapperPipeline): Schema { |
| 161 | + val primaryKeys = |
| 162 | + when (stream.importType) { |
| 163 | + is Dedupe -> (stream.importType as Dedupe).primaryKey |
| 164 | + else -> emptyList() |
| 165 | + } |
| 166 | + return pipeline.finalSchema.withAirbyteMeta(true).toIcebergSchema(primaryKeys) |
| 167 | + } |
| 168 | + |
| 169 | + private fun getSortOrder(schema: Schema): SortOrder { |
| 170 | + val builder = SortOrder.builderFor(schema) |
| 171 | + schema.identifierFieldNames().forEach { builder.asc(it) } |
| 172 | + return builder.build() |
| 173 | + } |
| 174 | + |
| 175 | + private fun getOperation( |
| 176 | + record: DestinationRecordAirbyteValue, |
| 177 | + importType: ImportType, |
| 178 | + ): Operation = |
| 179 | + if ( |
| 180 | + record.data is ObjectValue && |
| 181 | + (record.data as ObjectValue).values[AIRBYTE_CDC_DELETE_COLUMN] != null && |
| 182 | + (record.data as ObjectValue).values[AIRBYTE_CDC_DELETE_COLUMN] !is NullValue |
| 183 | + ) { |
| 184 | + Operation.DELETE |
| 185 | + } else if (importType is Dedupe) { |
| 186 | + Operation.UPDATE |
| 187 | + } else { |
| 188 | + Operation.INSERT |
| 189 | + } |
| 190 | +} |
0 commit comments