-
Notifications
You must be signed in to change notification settings - Fork 36
Allow publishing datasets on data.gouv.fr #1202
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Ndpnt
wants to merge
4
commits into
main
Choose a base branch
from
datagouv-release
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,115 @@ | ||
| import fsApi from 'fs'; | ||
| import path from 'path'; | ||
|
|
||
| import FormData from 'form-data'; | ||
| import nodeFetch from 'node-fetch'; | ||
|
|
||
| import * as readme from '../../assets/README.template.js'; | ||
| import logger from '../../logger/index.js'; | ||
|
|
||
| const DATASET_LICENSE = 'odc-odbl'; | ||
| const DEFAULT_RESOURCE_DESCRIPTION = 'See README.md inside the archive for dataset structure and usage information.'; | ||
|
|
||
| export async function updateDatasetMetadata({ apiBaseUrl, headers, datasetId, releaseDate, stats }) { | ||
| const updatePayload = { | ||
| title: readme.title({ releaseDate }), | ||
| description: readme.body(stats), | ||
| license: DATASET_LICENSE, | ||
| }; | ||
|
|
||
| if (stats?.firstVersionDate && stats?.lastVersionDate) { | ||
| updatePayload.temporal_coverage = { | ||
| start: stats.firstVersionDate.toISOString(), | ||
| end: stats.lastVersionDate.toISOString(), | ||
| }; | ||
| } | ||
|
|
||
| const updateResponse = await nodeFetch(`${apiBaseUrl}/datasets/${datasetId}/`, { | ||
| method: 'PUT', | ||
| headers: { | ||
| ...headers, | ||
| 'Content-Type': 'application/json', | ||
| }, | ||
| body: JSON.stringify(updatePayload), | ||
| }); | ||
|
|
||
| if (!updateResponse.ok) { | ||
| const errorText = await updateResponse.text(); | ||
|
|
||
| throw new Error(`Failed to update dataset metadata: ${updateResponse.status} ${updateResponse.statusText} - ${errorText}`); | ||
| } | ||
| } | ||
|
|
||
| export async function uploadResource({ apiBaseUrl, headers, datasetId, archivePath }) { | ||
| logger.info('Uploading dataset archive…'); | ||
|
|
||
| const formData = new FormData(); | ||
| const fileName = path.basename(archivePath); | ||
| const fileStats = fsApi.statSync(archivePath); | ||
|
|
||
| formData.append('file', fsApi.createReadStream(archivePath), { | ||
| filename: fileName, | ||
| contentType: 'application/zip', | ||
| knownLength: fileStats.size, | ||
| }); | ||
|
|
||
| const uploadResponse = await nodeFetch(`${apiBaseUrl}/datasets/${datasetId}/upload/`, { | ||
| method: 'POST', | ||
| headers: { ...formData.getHeaders(), ...headers }, | ||
| body: formData, | ||
| }); | ||
|
|
||
| if (!uploadResponse.ok) { | ||
| const errorText = await uploadResponse.text(); | ||
|
|
||
| throw new Error(`Failed to upload dataset file: ${uploadResponse.status} ${uploadResponse.statusText} - ${errorText}`); | ||
| } | ||
|
|
||
| const uploadResult = await uploadResponse.json(); | ||
|
|
||
| logger.info(`Dataset file uploaded successfully with resource ID: ${uploadResult.id}`); | ||
|
|
||
| return { resourceId: uploadResult.id, fileName }; | ||
| } | ||
|
|
||
| export async function updateResourceMetadata({ apiBaseUrl, headers, datasetId, resourceId, fileName }) { | ||
| logger.info('Updating resource metadata…'); | ||
|
|
||
| const resourceUpdateResponse = await nodeFetch(`${apiBaseUrl}/datasets/${datasetId}/resources/${resourceId}/`, { | ||
| method: 'PUT', | ||
| headers: { ...headers, 'Content-Type': 'application/json' }, | ||
| body: JSON.stringify({ | ||
| title: fileName, | ||
| description: DEFAULT_RESOURCE_DESCRIPTION, | ||
| filetype: 'file', | ||
| format: 'zip', | ||
| mime: 'application/zip', | ||
| }), | ||
| }); | ||
|
|
||
| if (!resourceUpdateResponse.ok) { | ||
| const errorText = await resourceUpdateResponse.text(); | ||
|
|
||
| throw new Error(`Failed to update resource metadata: ${resourceUpdateResponse.status} ${resourceUpdateResponse.statusText} - ${errorText}`); | ||
| } | ||
|
|
||
| logger.info('Resource metadata updated successfully'); | ||
| } | ||
|
|
||
| export async function getDatasetUrl({ apiBaseUrl, headers, datasetId }) { | ||
| const datasetResponse = await nodeFetch(`${apiBaseUrl}/datasets/${datasetId}/`, { | ||
| method: 'GET', | ||
| headers: { ...headers }, | ||
| }); | ||
|
|
||
| if (!datasetResponse.ok) { | ||
| const errorText = await datasetResponse.text(); | ||
|
|
||
| throw new Error(`Failed to retrieve dataset URL: ${datasetResponse.status} ${datasetResponse.statusText} - ${errorText}`); | ||
| } | ||
|
|
||
| const datasetData = await datasetResponse.json(); | ||
| const datasetUrl = datasetData.page; | ||
|
|
||
| return datasetUrl; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| import config from 'config'; | ||
|
|
||
| import logger from '../../logger/index.js'; | ||
|
|
||
| import { updateDatasetMetadata, uploadResource, updateResourceMetadata, getDatasetUrl } from './dataset.js'; | ||
|
|
||
| const PRODUCTION_API_BASE_URL = 'https://www.data.gouv.fr/api/1'; | ||
| const DEMO_API_BASE_URL = 'https://demo.data.gouv.fr/api/1'; | ||
|
|
||
| function loadConfiguration() { | ||
| const apiKey = process.env.OTA_ENGINE_DATAGOUV_API_KEY; | ||
|
|
||
| if (!apiKey) { | ||
| throw new Error('OTA_ENGINE_DATAGOUV_API_KEY environment variable is required for data.gouv.fr publishing'); | ||
| } | ||
|
|
||
| const datasetId = config.get('@opentermsarchive/engine.dataset.datagouv.datasetId'); | ||
|
|
||
| if (!datasetId) { | ||
| throw new Error('datasetId is required in config at @opentermsarchive/engine.dataset.datagouv.datasetId. Run "node scripts/dataset/publish/datagouv/create-dataset.js" to create a dataset first.'); | ||
| } | ||
|
|
||
| const useDemo = config.get('@opentermsarchive/engine.dataset.datagouv.useDemo'); | ||
| const apiBaseUrl = useDemo ? DEMO_API_BASE_URL : PRODUCTION_API_BASE_URL; | ||
|
|
||
| if (useDemo) { | ||
| logger.warn('Using demo.data.gouv.fr environment for testing'); | ||
| } | ||
|
|
||
| const headers = { 'X-API-KEY': apiKey }; | ||
|
|
||
| return { datasetId, apiBaseUrl, headers }; | ||
| } | ||
|
|
||
| export default async function publish({ archivePath, releaseDate, stats }) { | ||
| const config = loadConfiguration(); | ||
|
|
||
| await updateDatasetMetadata({ ...config, releaseDate, stats }); | ||
|
|
||
| const { resourceId, fileName } = await uploadResource({ ...config, archivePath }); | ||
|
|
||
| await updateResourceMetadata({ ...config, resourceId, fileName }); | ||
|
|
||
| const datasetUrl = await getDatasetUrl({ ...config }); | ||
|
|
||
| return datasetUrl; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,15 +1,49 @@ | ||
| import config from 'config'; | ||
|
|
||
| import logger from '../logger/index.js'; | ||
|
|
||
| import publishDataGouv from './datagouv/index.js'; | ||
| import publishGitHub from './github/index.js'; | ||
| import publishGitLab from './gitlab/index.js'; | ||
|
|
||
| export default function publishRelease({ archivePath, releaseDate, stats }) { | ||
| export default async function publishRelease({ archivePath, releaseDate, stats }) { | ||
| const platforms = []; | ||
|
|
||
| // If both GitHub and GitLab tokens are defined, GitHub takes precedence | ||
| if (process.env.OTA_ENGINE_GITHUB_TOKEN) { | ||
| return publishGitHub({ archivePath, releaseDate, stats }); | ||
| platforms.push({ name: 'GitHub', publish: () => publishGitHub({ archivePath, releaseDate, stats }) }); | ||
| } else if (process.env.OTA_ENGINE_GITLAB_TOKEN) { | ||
| platforms.push({ name: 'GitLab', publish: () => publishGitLab({ archivePath, releaseDate, stats }) }); | ||
| } | ||
|
|
||
| if (process.env.OTA_ENGINE_DATAGOUV_API_KEY && config.get('@opentermsarchive/engine.dataset.datagouv.datasetId')) { | ||
| platforms.push({ name: 'data.gouv.fr', publish: () => publishDataGouv({ archivePath, releaseDate, stats }) }); | ||
| } | ||
|
|
||
| if (!platforms.length) { | ||
| throw new Error('No publishing platform configured. Please configure at least one of: GitHub (OTA_ENGINE_GITHUB_TOKEN), GitLab (OTA_ENGINE_GITLAB_TOKEN), or data.gouv.fr (OTA_ENGINE_DATAGOUV_API_KEY + datasetId in config).'); | ||
| } | ||
|
|
||
| if (process.env.OTA_ENGINE_GITLAB_TOKEN) { | ||
| return publishGitLab({ archivePath, releaseDate, stats }); | ||
| const results = await Promise.allSettled(platforms.map(async platform => { | ||
| const url = await platform.publish(); | ||
|
|
||
| return { platform: platform.name, url }; | ||
| })); | ||
|
|
||
| const succeeded = results.filter(result => result.status === 'fulfilled'); | ||
| const failed = results.filter(result => result.status === 'rejected'); | ||
|
|
||
| if (failed.length) { | ||
| let errorMessage = !succeeded.length ? 'All platforms failed to publish:' : 'Some platforms failed to publish:'; | ||
|
|
||
| failed.forEach(rejectedResult => { | ||
| const index = results.indexOf(rejectedResult); | ||
|
|
||
| errorMessage += `\n - ${platforms[index].name}: ${rejectedResult.reason.message}`; | ||
| }); | ||
|
|
||
| logger.error(errorMessage); | ||
| } | ||
|
|
||
| throw new Error('No GitHub nor GitLab token found in environment variables (OTA_ENGINE_GITHUB_TOKEN or OTA_ENGINE_GITLAB_TOKEN). Cannot publish the dataset without authentication.'); | ||
| return succeeded.map(result => result.value); | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.