|
| 1 | +/* |
| 2 | + * Copyright (c) 2024 Airbyte, Inc., all rights reserved. |
| 3 | + */ |
| 4 | + |
| 5 | +package io.airbyte.integrations.base.destination.operation |
| 6 | + |
| 7 | +import io.airbyte.cdk.integrations.destination.StreamSyncSummary |
| 8 | +import io.airbyte.cdk.integrations.destination.async.model.PartialAirbyteMessage |
| 9 | +import io.airbyte.integrations.base.destination.typing_deduping.DestinationInitialStatus |
| 10 | +import io.airbyte.integrations.base.destination.typing_deduping.InitialRawTableStatus |
| 11 | +import io.airbyte.integrations.base.destination.typing_deduping.StreamConfig |
| 12 | +import io.airbyte.integrations.base.destination.typing_deduping.migrators.MinimumDestinationState |
| 13 | +import io.airbyte.protocol.models.v0.DestinationSyncMode |
| 14 | +import io.github.oshai.kotlinlogging.KotlinLogging |
| 15 | +import java.util.Optional |
| 16 | +import java.util.stream.Stream |
| 17 | + |
| 18 | +abstract class AbstractStreamOperation<DestinationState : MinimumDestinationState, Data>( |
| 19 | + private val storageOperation: StorageOperation<Data>, |
| 20 | + destinationInitialStatus: DestinationInitialStatus<DestinationState>, |
| 21 | + private val disableTypeDedupe: Boolean = false |
| 22 | +) : StreamOperation<DestinationState> { |
| 23 | + private val log = KotlinLogging.logger {} |
| 24 | + |
| 25 | + // State maintained to make decision between async calls |
| 26 | + private val finalTmpTableSuffix: String |
| 27 | + private val initialRawTableStatus: InitialRawTableStatus = |
| 28 | + destinationInitialStatus.initialRawTableStatus |
| 29 | + |
| 30 | + /** |
| 31 | + * After running any sync setup code, we may update the destination state. This field holds that |
| 32 | + * updated destination state. |
| 33 | + */ |
| 34 | + final override val updatedDestinationState: DestinationState |
| 35 | + |
| 36 | + init { |
| 37 | + val stream = destinationInitialStatus.streamConfig |
| 38 | + storageOperation.prepareStage(stream.id, stream.destinationSyncMode) |
| 39 | + if (!disableTypeDedupe) { |
| 40 | + storageOperation.createFinalNamespace(stream.id) |
| 41 | + // Prepare final tables based on sync mode. |
| 42 | + finalTmpTableSuffix = prepareFinalTable(destinationInitialStatus) |
| 43 | + } else { |
| 44 | + log.info { "Typing and deduping disabled, skipping final table initialization" } |
| 45 | + finalTmpTableSuffix = NO_SUFFIX |
| 46 | + } |
| 47 | + updatedDestinationState = destinationInitialStatus.destinationState.withSoftReset(false) |
| 48 | + } |
| 49 | + |
| 50 | + companion object { |
| 51 | + private const val NO_SUFFIX = "" |
| 52 | + private const val TMP_OVERWRITE_TABLE_SUFFIX = "_airbyte_tmp" |
| 53 | + } |
| 54 | + |
| 55 | + private fun prepareFinalTable( |
| 56 | + initialStatus: DestinationInitialStatus<DestinationState> |
| 57 | + ): String { |
| 58 | + val stream = initialStatus.streamConfig |
| 59 | + // No special handling if final table doesn't exist, just create and return |
| 60 | + if (!initialStatus.isFinalTablePresent) { |
| 61 | + log.info { |
| 62 | + "Final table does not exist for stream ${initialStatus.streamConfig.id.finalName}, creating." |
| 63 | + } |
| 64 | + storageOperation.createFinalTable(stream, NO_SUFFIX, false) |
| 65 | + return NO_SUFFIX |
| 66 | + } |
| 67 | + |
| 68 | + log.info { "Final Table exists for stream ${stream.id.finalName}" } |
| 69 | + // The table already exists. Decide whether we're writing to it directly, or |
| 70 | + // using a tmp table. |
| 71 | + when (stream.destinationSyncMode) { |
| 72 | + DestinationSyncMode.OVERWRITE -> return prepareFinalTableForOverwrite(initialStatus) |
| 73 | + DestinationSyncMode.APPEND, |
| 74 | + DestinationSyncMode.APPEND_DEDUP -> { |
| 75 | + if ( |
| 76 | + initialStatus.isSchemaMismatch || |
| 77 | + initialStatus.destinationState.needsSoftReset() |
| 78 | + ) { |
| 79 | + // We're loading data directly into the existing table. |
| 80 | + // Make sure it has the right schema. |
| 81 | + // Also, if a raw table migration wants us to do a soft reset, do that |
| 82 | + // here. |
| 83 | + log.info { "Executing soft-reset on final table of stream $stream" } |
| 84 | + storageOperation.softResetFinalTable(stream) |
| 85 | + } |
| 86 | + return NO_SUFFIX |
| 87 | + } |
| 88 | + } |
| 89 | + } |
| 90 | + |
| 91 | + private fun prepareFinalTableForOverwrite( |
| 92 | + initialStatus: DestinationInitialStatus<DestinationState> |
| 93 | + ): String { |
| 94 | + val stream = initialStatus.streamConfig |
| 95 | + if (!initialStatus.isFinalTableEmpty || initialStatus.isSchemaMismatch) { |
| 96 | + // overwrite an existing tmp table if needed. |
| 97 | + storageOperation.createFinalTable(stream, TMP_OVERWRITE_TABLE_SUFFIX, true) |
| 98 | + log.info { |
| 99 | + "Using temp final table for table ${stream.id.finalName}, this will be overwritten at end of sync" |
| 100 | + } |
| 101 | + // We want to overwrite an existing table. Write into a tmp table. |
| 102 | + // We'll overwrite the table at the |
| 103 | + // end of the sync. |
| 104 | + return TMP_OVERWRITE_TABLE_SUFFIX |
| 105 | + } |
| 106 | + |
| 107 | + log.info { |
| 108 | + "Final Table for stream ${stream.id.finalName} is empty and matches the expected v2 format, writing to table directly" |
| 109 | + } |
| 110 | + return NO_SUFFIX |
| 111 | + } |
| 112 | + |
| 113 | + /** Write records will be destination type specific, Insert vs staging based on format */ |
| 114 | + abstract override fun writeRecords( |
| 115 | + streamConfig: StreamConfig, |
| 116 | + stream: Stream<PartialAirbyteMessage> |
| 117 | + ) |
| 118 | + |
| 119 | + override fun finalizeTable(streamConfig: StreamConfig, syncSummary: StreamSyncSummary) { |
| 120 | + // Delete staging directory, implementation will handle if it has to do it or not or a No-OP |
| 121 | + storageOperation.cleanupStage(streamConfig.id) |
| 122 | + if (disableTypeDedupe) { |
| 123 | + log.info { |
| 124 | + "Typing and deduping disabled, skipping final table finalization. " + |
| 125 | + "Raw records can be found at ${streamConfig.id.rawNamespace}.${streamConfig.id.rawName}" |
| 126 | + } |
| 127 | + return |
| 128 | + } |
| 129 | + |
| 130 | + // Legacy logic that if recordsWritten or not tracked then it could be non-zero |
| 131 | + val isNotOverwriteSync = streamConfig.destinationSyncMode != DestinationSyncMode.OVERWRITE |
| 132 | + // Legacy logic that if recordsWritten or not tracked then it could be non-zero. |
| 133 | + // But for OVERWRITE syncs, we don't need to look at old records. |
| 134 | + val shouldRunTypingDeduping = |
| 135 | + syncSummary.recordsWritten.map { it > 0 }.orElse(true) || |
| 136 | + (initialRawTableStatus.hasUnprocessedRecords && isNotOverwriteSync) |
| 137 | + if (!shouldRunTypingDeduping) { |
| 138 | + log.info { |
| 139 | + "Skipping typing and deduping for stream ${streamConfig.id.originalNamespace}.${streamConfig.id.originalName} " + |
| 140 | + "because it had no records during this sync and no unprocessed records from a previous sync." |
| 141 | + } |
| 142 | + } else { |
| 143 | + // In overwrite mode, we want to read all the raw records. Typically, this is equivalent |
| 144 | + // to filtering on timestamp, but might as well be explicit. |
| 145 | + val timestampFilter = |
| 146 | + if (isNotOverwriteSync) { |
| 147 | + initialRawTableStatus.maxProcessedTimestamp |
| 148 | + } else { |
| 149 | + Optional.empty() |
| 150 | + } |
| 151 | + storageOperation.typeAndDedupe(streamConfig, timestampFilter, finalTmpTableSuffix) |
| 152 | + } |
| 153 | + |
| 154 | + // For overwrite, it's wasteful to do T+D, so we don't do soft-reset in prepare. Instead, we |
| 155 | + // do |
| 156 | + // type-dedupe |
| 157 | + // on a suffixed table and do a swap here when we have to for schema mismatches |
| 158 | + if ( |
| 159 | + streamConfig.destinationSyncMode == DestinationSyncMode.OVERWRITE && |
| 160 | + finalTmpTableSuffix.isNotBlank() |
| 161 | + ) { |
| 162 | + storageOperation.overwriteFinalTable(streamConfig, finalTmpTableSuffix) |
| 163 | + } |
| 164 | + } |
| 165 | +} |
0 commit comments