Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions api/src/catalogs/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ router.post('/', requireOperationScope('postCatalog'), async (req, res) => {
Object.assign(validCatalog, await prepareCatalog(validCatalog))
await mongo.catalogs.insertOne(validCatalog)

sendCatalogEvent(validCatalog, 'a été créé', 'create', sessionState)
sendCatalogEvent(validCatalog, 'create', sessionState)
delete validCatalog.secrets // Do not return secrets in the response
res.status(201).json(validCatalog)
})
Expand Down Expand Up @@ -169,8 +169,7 @@ router.delete('/:id', requireOperationScope('deleteCatalog'), async (req, res) =
// Delete all imports for this catalog but not the imported datasets
await mongo.imports.deleteMany({ 'catalog.id': req.params.id })

const msg = deletePublications ? 'a été supprimé avec ses publications' : 'a été supprimé'
sendCatalogEvent(catalog, msg, 'delete', sessionState)
sendCatalogEvent(catalog, 'delete', sessionState, deletePublications ? 'delete-with-publications' : 'delete')
res.status(204).send()
})

Expand Down
28 changes: 18 additions & 10 deletions api/src/catalogs/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,21 +8,29 @@ import { getPlugin } from '../plugins/service.ts'
import config from '#config'
import mongo from '#mongo'

const catalogTitles = {
create: (title: string) => ({ en: `The catalog ${title} was created`, fr: `Le catalogue ${title} a été créé` }),
patch: (title: string) => ({ en: `The catalog ${title} was updated`, fr: `Le catalogue ${title} a été modifié` }),
delete: (title: string) => ({ en: `The catalog ${title} was deleted`, fr: `Le catalogue ${title} a été supprimé` }),
'delete-with-publications': (title: string) => ({
en: `The catalog ${title} was deleted along with its publications`,
fr: `Le catalogue ${title} a été supprimé avec ses publications`
})
}

/**
* Helper function to send events related to catalogs
* @param catalog The catalog object
* @param actionText The text describing the action (e.g. "a été créé")
* @param topicAction The action part of the topic key (e.g. "create", "delete")
* @param sessionState Optional session state for authentication
* Send an event about a catalog.
* @param topicAction The action part of the topic key
* @param textAction The text of the title, when it is more precise than the topic action
*/
export const sendCatalogEvent = (
catalog: Catalog,
actionText: string,
topicAction: string,
sessionState?: SessionStateAuthenticated
topicAction: 'create' | 'patch' | 'delete',
sessionState?: SessionStateAuthenticated,
textAction: keyof typeof catalogTitles = topicAction
) => {
eventsQueue.pushEvent({
title: `Le catalogue ${catalog.title} ${actionText}`,
title: catalogTitles[textAction](catalog.title),
topic: { key: `catalogs:catalog-${topicAction}:${catalog._id}` },
sender: catalog.owner,
resource: {
Expand Down Expand Up @@ -106,7 +114,7 @@ export const updateCatalog = async (catalog: Catalog, changes: Record<string, an
Object.assign(patchedCatalog, preparedCatalog)

await mongo.catalogs.updateOne({ _id: catalog._id }, patch)
sendCatalogEvent(patchedCatalog, 'a été modifié', 'patch', sessionState)
sendCatalogEvent(patchedCatalog, 'patch', sessionState)
delete patchedCatalog.secrets // Do not return secrets in the response
return patchedCatalog
}
6 changes: 3 additions & 3 deletions api/src/imports/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ router.post('/', requireOperationScope('postImport'), async (req, res) => {
})
if (existingImport && getAccountRole(sessionState, existingImport.owner) === 'admin') {
await mongo.imports.deleteOne({ _id: existingImport._id })
sendImportEvent(existingImport, 'a été supprimé (remplacé par un nouvel import)', 'delete', sessionState)
sendImportEvent(existingImport, 'delete', sessionState, 'replace')
}
}

Expand All @@ -94,7 +94,7 @@ router.post('/', requireOperationScope('postImport'), async (req, res) => {
const validImport = await validateImport(imp)
await mongo.imports.insertOne(validImport)

sendImportEvent(validImport, 'a été créé', 'create', sessionState)
sendImportEvent(validImport, 'create', sessionState)
res.status(201).json(validImport)
})

Expand Down Expand Up @@ -141,7 +141,7 @@ router.delete('/:id', requireOperationScope('deleteImport'), async (req, res) =>
assertAccountRole(sessionState, importDoc.owner, 'admin')

await mongo.imports.deleteOne({ _id: req.params.id })
sendImportEvent(importDoc, 'a été supprimé', 'delete', sessionState)
sendImportEvent(importDoc, 'delete', sessionState)

res.status(204).send()
})
Expand Down
30 changes: 19 additions & 11 deletions api/src/imports/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,27 +6,35 @@ import type { SessionStateAuthenticated } from '@data-fair/lib-express'
import { getNextImportDate } from '@data-fair/catalogs-shared/cron.ts'
import mongo from '#mongo'

const importTitles = {
create: (title: string) => ({ en: `The import of the resource ${title} was created`, fr: `L'import de la ressource ${title} a été créé` }),
update: (title: string) => ({ en: `The import of the resource ${title} was updated`, fr: `L'import de la ressource ${title} a été modifié` }),
delete: (title: string) => ({ en: `The import of the resource ${title} was deleted`, fr: `L'import de la ressource ${title} a été supprimé` }),
replace: (title: string) => ({
en: `The import of the resource ${title} was deleted (replaced by a new import)`,
fr: `L'import de la ressource ${title} a été supprimé (remplacé par un nouvel import)`
})
}

/**
* Helper function to send events related to catalogs
* @param catalog The catalog object
* @param actionText The text describing the action (e.g. "a été créé")
* @param topicAction The action part of the topic key (e.g. "create", "delete")
* @param sessionState Optional session state for authentication
* Send an event about an import (its errors are sent by the worker).
* @param topicAction The action part of the topic key
* @param textAction The text of the title, when it is more precise than the topic action
*/
export const sendImportEvent = (
imp: Import,
actionText: string,
topicAction: string,
sessionState: SessionStateAuthenticated
topicAction: 'create' | 'update' | 'delete',
sessionState: SessionStateAuthenticated,
textAction: keyof typeof importTitles = topicAction
) => {
eventsQueue.pushEvent({
title: `L'import de la resource ${imp.remoteResource.title} ${actionText}`,
title: importTitles[textAction](imp.remoteResource.title || imp.remoteResource.id),
topic: { key: `catalogs:import-${topicAction}:${imp._id}` },
sender: imp.owner,
resource: {
type: 'catalog',
id: imp.catalog.id,
title: 'Catalogue associé : ' + imp.catalog.title,
title: imp.catalog.title,
}
}, sessionState)
}
Expand Down Expand Up @@ -70,7 +78,7 @@ export const updateImport = async (importDoc: Import, changes: Record<string, an
const patchedImport = await validateImport(merged)
await mongo.imports.updateOne({ _id: importDoc._id }, patch)

sendImportEvent(patchedImport, 'a été modifié', 'update', sessionState)
sendImportEvent(patchedImport, 'update', sessionState)
await wsEmit(`import/${importDoc._id}`, patchedImport)
return patchedImport
}
10 changes: 7 additions & 3 deletions api/src/publications/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,15 +97,19 @@ router.post('/', requireOperationScope('postPublication'), async (req, res) => {
await mongo.publications.insertOne(validPublication)
await wsEmit(`publication/${validPublication._id}`, validPublication)

// Emit an event for the publication
// Emit an event for the publication (its errors are sent by the worker)
const datasetTitle = validPublication.dataFairDataset.title || validPublication.dataFairDataset.id
eventsQueue.pushEvent({
title: `La publication pour le jeu de données ${validPublication.dataFairDataset.title || validPublication.dataFairDataset.id} a été créée`,
title: {
en: `The publication of the dataset ${datasetTitle} was created`,
fr: `La publication du jeu de données ${datasetTitle} a été créée`
},
topic: { key: `catalogs:publication-create:${validPublication._id}` },
sender: validPublication.owner,
resource: {
type: 'catalog',
id: validPublication.catalog.id,
title: 'Catalogue associé : ' + validPublication.catalog.title,
title: validPublication.catalog.title,
}
}, sessionState)
res.status(201).json(validPublication)
Expand Down
3 changes: 3 additions & 0 deletions ui/src/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,7 @@ import uiNotif from '@data-fair/lib-vuetify/ui-notif.vue'
import { useFrameServer } from '@data-fair/lib-vue-agents'

useFrameServer('catalogs')

const session = useSession()
watchEffect(() => { document.documentElement.lang = session.lang.value ?? 'fr' })
</script>
2 changes: 1 addition & 1 deletion ui/src/components/logs.vue
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ const getIcon = (logs: Log[]) => {
return mdiCheckCircle
}

const formatDate = (date: string) => dayjs(date).format('DD/MM/YYYY HH:mm')
const formatDate = (date: string) => dayjs(date).format('L LT')

const iconsByStatus = {
waiting: mdiClock,
Expand Down
4 changes: 2 additions & 2 deletions ui/src/components/resources-explorer.vue
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@
</template>

<template #item.size="{ item }">
<span class="text-no-wrap">{{ item.type === 'resource' && item.size ? formatBytes(item.size) : '-' }}</span>
<span class="text-no-wrap">{{ item.type === 'resource' && item.size ? formatBytes(item.size, locale) : '-' }}</span>
</template>

<template #item.format="{ item }">
Expand All @@ -131,7 +131,7 @@ import formatBytes from '@data-fair/lib-vue/format/bytes.js'
import { until } from '@vueuse/core'
import { useAgentTool } from '@data-fair/lib-vue-agents'

const { t } = useI18n()
const { t, locale } = useI18n()
const { dayjs } = useLocaleDayjs()
const session = useSessionAuthenticated()
const { catalog, plugin, mode } = defineProps<{
Expand Down
2 changes: 1 addition & 1 deletion ui/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import App from './App.vue'
...vuetifySessionOptions(session, $cspNonce),
icons: { defaultSet: 'mdi', aliases, sets: { mdi } }
})
const i18n = createI18n({ locale: session.state.lang })
const i18n = createI18n({ locale: session.state.lang, fallbackLocale: 'en' })

createApp(App)
.use(router)
Expand Down
36 changes: 36 additions & 0 deletions worker/src/lib/events.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import type { Import, Publication } from '#api/types'

import eventsQueue from '@data-fair/lib-node/events-queue.js'

const errorTitles = {
import: (title: string) => ({ en: `The import of the resource ${title} failed`, fr: `L'import de la ressource ${title} a échoué` }),
publication: (title: string) => ({ en: `The publication of the dataset ${title} failed`, fr: `La publication du jeu de données ${title} a échoué` })
}

/**
* Send the failure event of an import or a publication.
* @param resourceTitle The title of the imported resource or of the published dataset
*/
export const sendTaskErrorEvent = (type: keyof typeof errorTitles, task: Import | Publication, resourceTitle: string) => {
eventsQueue.pushEvent({
title: errorTitles[type](resourceTitle),
topic: { key: `catalogs:${type}-error:${task._id}` },
sender: task.owner,
resource: {
type: 'catalog',
id: task.catalog.id,
title: task.catalog.title
},
originator: {
internalProcess: {
id: 'catalogs-worker',
title: 'Catalogs Worker'
}
},
urlParams: {
catalogId: task.catalog.id,
type: type + 's',
itemId: task._id
}
})
}
24 changes: 2 additions & 22 deletions worker/src/lib/import.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import fs from 'fs-extra'
import FormData from 'form-data'
import tmp from 'tmp-promise'
import { emit as wsEmit } from '@data-fair/lib-node/ws-emitter.js'
import eventsQueue from '@data-fair/lib-node/events-queue.js'
import { sendTaskErrorEvent } from './events.ts'
import log from '@data-fair/lib-node/log.js'
import { decipherSecrets } from '@data-fair/catalogs-shared/cipher.ts'
// data-fair is a service of our own infrastructure (configured private URL, not user input)
Expand Down Expand Up @@ -36,27 +36,7 @@ const handleImportError = async (type: 'upload' | 'download', imp: Import, err:
// download: the remote catalog failed (upstream, warn); upload: data-fair, our own infrastructure (error)
if (type === 'download') log.warn('failed to download the resource file', { code: 'worker-download-failed', err })
else log.error('failed to upload the resource file', { code: 'worker-upload-failed', err })
eventsQueue.pushEvent({
title: `L'import de la resource ${imp.remoteResource.title} à échoué`,
topic: { key: `catalogs:import-error:${imp._id}` },
sender: imp.owner,
resource: {
type: 'catalog',
id: imp.catalog.id,
title: 'Catalogue associé : ' + imp.catalog.title
},
originator: {
internalProcess: {
id: 'catalogs-worker',
name: 'Catalogs Worker'
}
},
urlParams: {
catalogId: imp.catalog.id,
type: 'imports',
itemId: imp._id
}
})
sendTaskErrorEvent('import', imp, imp.remoteResource.title || imp.remoteResource.id)
}

/**
Expand Down
24 changes: 2 additions & 22 deletions worker/src/lib/publication.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type { AxiosRequestConfig } from 'axios'

import { emit as wsEmit } from '@data-fair/lib-node/ws-emitter.js'
import log from '@data-fair/lib-node/log.js'
import eventsQueue from '@data-fair/lib-node/events-queue.js'
import { sendTaskErrorEvent } from './events.ts'
import { decipherSecrets } from '@data-fair/catalogs-shared/cipher.ts'
// data-fair is a service of our own infrastructure (configured private URL, not user input)
import { privateAxiosInstance as axios } from '@data-fair/lib-node/axios.js'
Expand Down Expand Up @@ -51,27 +51,7 @@ export const process = async (catalog: Catalog, plugin: CatalogPlugin, pub: Publ
const errorMsg = "You don't have permission to publish this dataset in this catalog. This may be due to a change of ownership for the dataset or the catalog."
await mongo.publications.updateOne({ _id: pub._id }, { $set: { status: 'error', logs: [{ date: new Date().toISOString(), msg: errorMsg, type: 'error' }] } })
await wsEmit(`publication/${pub._id}`, { status: 'error', logs: [{ date: new Date().toISOString(), msg: errorMsg, type: 'error' }] })
eventsQueue.pushEvent({
title: `La publication du jeu de données ${dataFairDataset?.title || pub.dataFairDataset.title} a échoué`,
topic: { key: `catalogs:publication-error:${pub._id}` },
sender: pub.owner,
resource: {
type: 'catalog',
id: pub.catalog.id,
title: 'Catalogue associé : ' + pub.catalog.title
},
originator: {
internalProcess: {
id: 'catalogs-worker',
name: 'Catalogs Worker'
}
},
urlParams: {
catalogId: pub.catalog.id,
type: 'publications',
itemId: pub._id
}
})
sendTaskErrorEvent('publication', pub, dataFairDataset?.title || pub.dataFairDataset.title || pub.dataFairDataset.id)
// the owner lost its permissions on the dataset, expected and reported to the owner
return log.warn(errorMsg, { code: 'worker-missing-permissions' })
}
Expand Down
25 changes: 4 additions & 21 deletions worker/src/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { importPluginModule } from '@data-fair/catalogs-shared/plugin-load.ts'
import { getNextImportDate } from '@data-fair/catalogs-shared/cron.ts'
import importTask from './lib/import.ts'
import publicationTask from './lib/publication.ts'
import { sendTaskErrorEvent } from './lib/events.ts'
import log, { withLogContext } from '@data-fair/lib-node/log.js'
import { taskLogFields } from '@data-fair/catalogs-shared/log-fields.ts'
import config, { registryCacheDir } from '#config'
Expand Down Expand Up @@ -192,27 +193,9 @@ async function processTask (catalog: Catalog, plugin: CatalogPlugin, task: Task,
})
await wsEmit(`${type}/${task._id}`, { status: 'error' })
// Push an event to the queue
eventsQueue.pushEvent({
title: `${type === 'import' ? "L'import de la resource" : 'La publication du jeu de données'} ${type === 'import' ? (task as Import).remoteResource?.title : (task as Publication).dataFairDataset?.title} a échoué`,
topic: { key: `catalogs:${type}-error:${task._id}` },
sender: task.owner,
resource: {
type: 'catalog',
id: task.catalog.id,
title: 'Catalogue associé : ' + task.catalog.title
},
originator: {
internalProcess: {
id: 'catalogs-worker',
name: 'Catalogs Worker'
}
},
urlParams: {
catalogId: task.catalog.id,
type: type + 's',
itemId: task._id
}
})
sendTaskErrorEvent(type, task, type === 'import'
? ((task as Import).remoteResource?.title || (task as Import).remoteResource?.id)
: ((task as Publication).dataFairDataset?.title || (task as Publication).dataFairDataset?.id))
}
}

Expand Down
Loading