Skip to content

Commit

Permalink
Merge pull request #98 from keboola/adamvyborny-CM-782-retry-on-git-c…
Browse files Browse the repository at this point in the history
…lone-race-codinition

Retry on git clone race condition
  • Loading branch information
AdamVyborny authored Nov 6, 2023
2 parents c5677e1 + 47b02a5 commit fa72b19
Show file tree
Hide file tree
Showing 28 changed files with 982 additions and 589 deletions.
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@
"ext-odbc": "*",
"keboola/db-adapter-snowflake": "^1.1",
"keboola/php-component": "^9.1",
"keboola/retry": "^0.5",
"keboola/sandboxes-api-php-client": "^6.21",
"keboola/storage-api-client": "^12.10",
"keboola/storage-api-client": "^14.12",
"keboola/table-backend-utils": "^1.11",
"symfony/filesystem": "^5.4",
"symfony/process": "^5.4",
Expand Down
1,130 changes: 800 additions & 330 deletions composer.lock

Large diffs are not rendered by default.

26 changes: 17 additions & 9 deletions src/Component.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,10 @@
use Keboola\SnowflakeDbAdapter\Connection;
use Keboola\StorageApi\Client as StorageClient;
use Psr\Log\LoggerInterface;
use Retry\Policy\CallableRetryPolicy;
use Retry\RetryProxy;
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Yaml\Yaml;

class Component extends BaseComponent
Expand All @@ -47,23 +50,28 @@ class Component extends BaseComponent
public function __construct(LoggerInterface $logger)
{
parent::__construct($logger);

$retryProxy = new RetryProxy(new CallableRetryPolicy(function (ProcessFailedException $e) {
return str_contains($e->getMessage(), 'shallow file has changed since we read it');
}));

$this->createProfilesFileService = new DbtProfilesYaml;
$this->createSourceFileService = new DbtSourcesYaml;
$this->gitRepositoryService = new GitRepositoryService($this->getDataDir());
$this->gitRepositoryService = new GitRepositoryService($this->getDataDir(), $retryProxy);
$this->storageClient = new StorageClient([
'url' => $this->getConfig()->getStorageApiUrl(),
'token' => $this->getConfig()->getStorageApiToken(),
]);
$this->artifacts = new ArtifactsService(
$this->storageClient,
$this->getDataDir(),
$this->getConfig()->getArtifactsOptions()
$this->getConfig()->getArtifactsOptions(),
);
$this->setProjectPath($this->getDataDir());
$this->dwhProviderFactory = new DwhProviderFactory(
$this->createSourceFileService,
$this->createProfilesFileService,
$this->getLogger()
$this->getLogger(),
);
}

Expand Down Expand Up @@ -104,7 +112,7 @@ public function getOutputManifest(array $workspaceCredentials): OutputManifest
$manifestConverter = new DbtManifestParser($this->projectPath);
$connectionConfig = array_intersect_key(
$workspaceCredentials,
array_flip(['host', 'warehouse', 'database', 'user', 'password'])
array_flip(['host', 'warehouse', 'database', 'user', 'password']),
);
$connection = new Connection($connectionConfig);

Expand All @@ -118,7 +126,7 @@ public function getOutputManifest(array $workspaceCredentials): OutputManifest
$manifestManager,
$manifestConverter,
$this->getLogger(),
$quoteIdentifier
$quoteIdentifier,
);
}

Expand Down Expand Up @@ -168,7 +176,7 @@ protected function cloneRepository(Config $config): void
$config->getGitRepositoryUrl(),
$config->getGitRepositoryBranch(),
$config->getGitRepositoryUsername(),
$config->getGitRepositoryPassword()
$config->getGitRepositoryPassword(),
);

$branch = $this->gitRepositoryService->getCurrentBranch($this->projectPath);
Expand All @@ -177,7 +185,7 @@ protected function cloneRepository(Config $config): void
'Successfully cloned repository %s from branch %s (%s)',
$config->getGitRepositoryUrl(),
$branch['name'],
$branch['ref']
$branch['ref'],
));
}

Expand Down Expand Up @@ -335,7 +343,7 @@ protected function actionGitRepository(): array
$config->getGitRepositoryUrl(),
$config->getGitRepositoryBranch(),
$config->getGitRepositoryUsername(),
$config->getGitRepositoryPassword()
$config->getGitRepositoryPassword(),
);

$branches = $this->gitRepositoryService->listRemoteBranches($this->projectPath);
Expand Down Expand Up @@ -367,7 +375,7 @@ protected function loadConfig(): void
/** @var BaseConfig $config */
$config = new $configClass(
$rawConfig,
new $configDefinitionClass()
new $configDefinitionClass(),
);
$this->config = $config;
} catch (InvalidConfigurationException $e) {
Expand Down
6 changes: 3 additions & 3 deletions src/Configuration/NodeDefinition/DbtNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,18 +46,18 @@ protected function build(): void
->always(function ($executeSteps) {
if (empty($executeSteps)) {
throw new InvalidConfigurationException(
'At least one execute step must be defined'
'At least one execute step must be defined',
);
}
foreach ($executeSteps as $input) {
if (substr($input['step'], 0, 4) !== 'dbt ') {
throw new InvalidConfigurationException(
'Invalid execute step: Command must start with "dbt"'
'Invalid execute step: Command must start with "dbt"',
);
}
if (preg_match('/[|&]/', $input['step'])) {
throw new InvalidConfigurationException(
'Invalid execute step: Command contains disallowed metacharacters'
'Invalid execute step: Command contains disallowed metacharacters',
);
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/DwhProvider/DwhProviderFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ class DwhProviderFactory
public function __construct(
DbtSourcesYaml $createSourceFileService,
DbtProfilesYaml $createProfilesFileService,
LoggerInterface $logger
LoggerInterface $logger,
) {
$this->createProfilesFileService = $createProfilesFileService;
$this->createSourceFileService = $createSourceFileService;
Expand Down Expand Up @@ -72,7 +72,7 @@ public function getProvider(Config $config, string $projectPath): DwhProviderInt
$this->createProfilesFileService,
$this->logger,
$config,
$projectPath
$projectPath,
);
}
}
4 changes: 2 additions & 2 deletions src/DwhProvider/LocalSnowflakeProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public function __construct(
DbtProfilesYaml $createProfilesFileService,
LoggerInterface $logger,
Config $config,
string $projectPath
string $projectPath,
) {
$this->createProfilesFileService = $createProfilesFileService;
$this->createSourceFileService = $createSourceFileService;
Expand Down Expand Up @@ -79,7 +79,7 @@ public function createDbtYamlFiles(array $configurationNames = []): void
$this->createSourceFileService->dumpYaml(
$this->projectPath,
$tablesData,
$this->config->getFreshness()
$this->config->getFreshness(),
);
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/DwhProvider/RemoteBigQueryProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,14 @@ public function __construct(
DbtProfilesYaml $createProfilesFileService,
LoggerInterface $logger,
Config $config,
string $projectPath
string $projectPath,
) {
parent::__construct(
$createSourceFileService,
$createProfilesFileService,
$logger,
$config,
$projectPath
$projectPath,
);

$this->temp = new Temp('dbt-big-query');
Expand Down
2 changes: 1 addition & 1 deletion src/DwhProvider/RemoteSnowflakeProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public function createDbtYamlFiles(array $configurationNames = []): void
{
$this->createProfilesFileService->dumpYaml(
$this->projectPath,
$this->getOutputs($configurationNames, static::getDbtParams())
$this->getOutputs($configurationNames, static::getDbtParams()),
);
$this->setEnvVars();

Expand Down
2 changes: 1 addition & 1 deletion src/FileDumper/DbtProfilesYaml.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public function dumpYaml(string $projectPath, array $outputs): void
'target' => 'dev',
'outputs' => $outputs,
],
], 5)
], 5),
);
}
}
8 changes: 4 additions & 4 deletions src/FileDumper/DbtSourcesYaml.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ class DbtSourcesYaml extends FilesystemAwareDumper
public function dumpYaml(
string $projectPath,
array $tablesData,
array $freshness
array $freshness,
): void {
$modelFolderPath = sprintf('%s/models/_sources/', $projectPath);
$this->createFolderIfNotExist($modelFolderPath);
Expand All @@ -32,14 +32,14 @@ public function dumpYaml(
'freshness' => $freshness,
'database' => sprintf(
'{{ env_var("DBT_KBC_PROD%s_DATABASE") }}',
isset($tables['projectId']) ? ('_' . $tables['projectId']) : ''
isset($tables['projectId']) ? ('_' . $tables['projectId']) : '',
),
'schema' => $bucket,
'loaded_at_field' => '"_timestamp"',
'tables' => array_map($this->formatTableSources(), $tables['tables']),
],
],
], 8)
], 8),
);
}
}
Expand All @@ -64,7 +64,7 @@ static function ($primaryColumn) {
'tests' => ['unique', 'not_null'],
];
},
$table['primaryKey']
$table['primaryKey'],
);
}

Expand Down
16 changes: 8 additions & 8 deletions src/FileDumper/OutputManifest.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public function __construct(
ManifestManager $manifestManager,
DbtManifestParser $dbtManifestParser,
LoggerInterface $logger,
bool $quoteIdentifier = false
bool $quoteIdentifier = false,
) {
$this->manifestManager = $manifestManager;
$this->databaseConfig = $databaseConfig;
Expand Down Expand Up @@ -67,7 +67,7 @@ public function dump(): void
$columnName = $column->getColumnName();
$columnsMetadata->{$columnName} = array_merge(
$column->getColumnDefinition()->toMetadata(),
(array) ($dbtColumnsMetadata[strtolower($columnName)] ?? [])
(array) ($dbtColumnsMetadata[strtolower($columnName)] ?? []),
);
}

Expand All @@ -89,7 +89,7 @@ public function dump(): void
->setColumnMetadata($columnsMetadata)
->setPrimaryKeyColumns($this->getPrimaryKeyColumnNames(
$dbtPrimaryKey,
$tableDef->getColumnsNames()
$tableDef->getColumnsNames(),
))
;

Expand Down Expand Up @@ -129,21 +129,21 @@ private function getTables(array $sourceTables): array
* kind: string,
* type: string,
* default: string,
* 'null?': string
* "null?": string
* }> $columnsMeta */
$columnsMeta = $this->connection->fetchAll(
sprintf(
'DESC TABLE %s',
SnowflakeQuote::createQuotedIdentifierFromParts([
$schema,
$this->quoteIdentifier ? $tableName : strtoupper($tableName),
])
)
]),
),
);
} catch (RuntimeException $e) {
// do nothing for models/tables not existing in the DB
$this->logger->warning(
'Table "%s" specified in dbt manifest was not found in the database.'
'Table "%s" specified in dbt manifest was not found in the database.',
);
continue;
}
Expand All @@ -160,7 +160,7 @@ private function getTables(array $sourceTables): array
$tableName,
false,
new ColumnCollection($columns),
[]
[],
);
}

Expand Down
4 changes: 2 additions & 2 deletions src/FileDumper/OutputManifest/DbtManifestParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public function parse(): array
(string) file_get_contents($this->sourceManifestPath),
true,
512,
JSON_THROW_ON_ERROR
JSON_THROW_ON_ERROR,
);

/** @var array<string, array<string, string|array<string, array<string, array<string, mixed>>>>> $modelNodes */
Expand All @@ -41,7 +41,7 @@ public function parse(): array
function ($node) {
/** @var array<string, mixed> $node */
return $node['resource_type'] === 'model';
}
},
);

foreach ($modelNodes as $tableData) {
Expand Down
4 changes: 2 additions & 2 deletions src/Helper/DbtCompileHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public static function getCompiledSqlFilesContent(string $directory): array
reset($filePaths);

$contents = array_map(fn($sqlFile) => trim(
(string) file_get_contents($sqlFile->getPathname())
(string) file_get_contents($sqlFile->getPathname()),
), $filePaths);

$combineArray = (array) array_combine($filenames, $contents);
Expand All @@ -39,7 +39,7 @@ public static function getCompiledSqlFilesContent(string $directory): array
public static function getCompiledSqlPaths(string $directory): array
{
$compiledDirInfo = new SplFileInfo(
sprintf('%s/%s', $directory, 'compiled')
sprintf('%s/%s', $directory, 'compiled'),
);

try {
Expand Down
2 changes: 1 addition & 1 deletion src/Helper/DbtDocsHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public static function mergeHtml(string $html, string $catalogJson, string $mani
$newStr = sprintf(
'o=[{label: \'manifest\', data: %s},{label: \'catalog\', data: %s}]',
$manifestJson,
$catalogJson
$catalogJson,
);

return (string) str_replace($searchStr, $newStr, $html);
Expand Down
2 changes: 1 addition & 1 deletion src/Helper/ParseLogFileHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public function getSqls(): Generator
foreach ($logs as $log) {
if (!empty($log['data']['sql'])) {
yield $this->queryExcerpt(
trim((string) preg_replace('!/\*.*?\*/!s', '', $log['data']['sql']))
trim((string) preg_replace('!/\*.*?\*/!s', '', $log['data']['sql'])),
);
}
}
Expand Down
Loading

0 comments on commit fa72b19

Please sign in to comment.