Packed data locations: DataPackages and their components
Concepts
A DataLocation describes where the files for one independently processed publication can be found. It includes the publication's provider identifier(s), a selector for the files, and SHA-256 hashes of the selected files.
A DataPackage describes an archive that contains one or more DataLocations as components:
DeliveryDataPackagerepresents a package received from a provider.NASDataPackagerepresents a package stored permanently on the NAS.UnpackedDeliveryrepresents a source location that already contains exactly one independently processed publication. Despite the name, this location may itself be a ZIP file.
DataPackages
Information on content location
| Python variable | WDMVoc property | description |
|---|---|---|
| self.packageLocation | wdmvoc:packageLocation | Information where the package is found, either as absolute path in the file system or as URL, e.g. sftp://... |
DataPackageComponents
Information on content location and identification
| Python variable | WDMVoc property | description |
|---|---|---|
| self.packageLocation | Information where the package that contains the component is found, either as absolute path in the file system or as URL, e.g. sftp://... | |
| self.contentPath | wdmvoc:contentPath | The internal path in the package the leads to the component in the package structure, might be a subfolder or a name of a contained zip file |
| self.contentFilter | wdmvoc:contentFiler | An additional filter that has to be applied within the contentPath to identify the files belonging to the described component, in the form filtertype:value (see detail section on filtering) |
Unpacked locations
Unpacked location means that the location contains exactly one entity that is supposed to be processed by the workflow independently. The location itself might be package data format (.zip) or just a location on the file system.
Unpacked deliveries
Information on content location
| Python variable | WDMVoc property | description |
|---|---|---|
| self.locationBaseAbs | wdmvoc:locationBaseAbs | A full reference to the location where the files can be found, may be an absolute path on the file system or the reference to a remote location such as the storage box. |
| self.contentPath | wdmvoc:contentPath | The internal path that leads to the content when the base location has been opened. |
| self.contentFilter | wdmvoc:contentFiler | An additional filter that has to be applied within the contentPath to identify the files belonging to the described component, in the form filtertype:value (see detail section on filtering) |
NASProcessingFiles
Information on content location
| Python variable | WDMVoc property | description |
|---|---|---|
| self.locationBaseAbs | wdmvoc:locationBaseAbs | The path to the folder in which all processing of a article or other entity takes place. Modules create their own subfolders there. Will be identical for the different NASProcessingFiles of the same entity |
| self.contentPath | wdmvoc:contentPath | The internal path processing folder that leads to the data after processing by the latest module, typically the module name with a suffix that is based on the last metadata update |
Process to create new packages on the NAS
This section explains how to create NASDataPackage objects and register their source locations through the high-level API in bookkeeping/bookkeeping_managers.py. The complete examples are based on:
bookkeeping/copernicus_addition.py: one article per source ZIP;bookkeeping/mdpi_packer.py: several articles in one source package, selected by path or filename filter.
The normal repacking flow is:
source location/package
|
| select and analyse one publication
v
UnpackedDelivery or DeliveryDataPackageComponent
|
| copy files and preserve provenance
v
NASDataPackageComponent (an inner ZIP)
|
v
NASDataPackage (an outer ZIP registered in bookkeeping)
The relevant RDF location properties are:
| Python attribute | WDM vocabulary property | Meaning |
|---|---|---|
DataPackage.packageLocation |
wdmvoc:packageLocation |
Stable absolute path or URL of a package. |
DataPackageComponent.packageLocation |
inherited from its package | Stable location of the package containing the component. |
DataLocation.locationBaseAbs |
wdmvoc:locationBaseAbs |
Stable absolute path or remote URL of an unpacked location. |
DataLocation.contentPath |
wdmvoc:contentPath |
Path within the base location or package. |
DataLocation.contentFilter |
wdmvoc:contentFilter |
Optional filter applied within contentPath. |
The high-level interfaces
Use the manager classes rather than constructing NewNASDataPackage objects directly:
| Interface | Purpose |
|---|---|
BookkeepingHandler |
Connects to the provider graph and registers packages, locations, files, identifiers, and provenance. |
NASPackageCreator |
Context manager that creates, batches, closes, and registers NAS packages. |
UnpackedDeliveryHandler |
Describes and registers sources that contain one publication each. It can read a ZIP directly from SFTP into memory. |
DeliveryPackageHandler |
Describes and registers source packages containing one or more publication components. It works from a local or temporary local copy. |
Create one BookkeepingHandler and pass the same instance to all managers participating in the operation:
from bookkeeping.bookkeeping_managers import NASPackageCreator
from bookkeeping.bookkeepinghandler import BookkeepingHandler
with (
BookkeepingHandler("provider-name", "my_repacking_flow") as handler,
NASPackageCreator(
nas_path=nas_path,
bookkeeping_handler=handler,
target_size=100 * 1024 * 1024,
max_n_components=20,
) as package_creator,
):
# Add components here.
...
Passing an existing handler is required as all location/package handlers must share the same graph activity.
What NASPackageCreator creates
NASPackageCreator generates a UUIDv7 for each outer package and writes it below nas_path using the final two UUID characters as directory shards:
<nas_path>/<second-last UUID character>/<last UUID character>/<UUID>.zip
The outer package contains one ZIP per publication. The inner filename is derived from the first normalized provider identifier. For example, doi:10.1234/example becomes an inner filename similar to doi_10.1234_example.zip.
A new outer package is started automatically when the first component is added. After each component, the current package is closed if either:
- its compressed size is greater than
target_size; or max_n_componentsis greater than zero and that component count has been reached.
These are rollover thresholds, not strict upper bounds: the component that crosses a threshold remains in that package. A value of 0 for max_n_components disables the count limit.
Leaving the NASPackageCreator context calls shutdown(), which finishes and registers any remaining open package, including when the context exits because of an unhandled exception.
Case 1: one publication per source ZIP
Use UnpackedDeliveryHandler when one source location corresponds to one publication. copernicus_addition.py uses this pattern for ZIP files on SFTP.
import logging
import pathlib
from bookkeeping.bookkeeping_connectors import SFTPConnector
from bookkeeping.bookkeeping_managers import (
UnpackedDeliveryHandler,
NASPackageCreator,
)
from bookkeeping.bookkeepinghandler import BookkeepingHandler
from bookkeeping.exceptions import UnreadableDeliveryArchiveError
logger = logging.getLogger(__name__)
with (
SFTPConnector(
hostname=sftp_host,
port=22,
username=sftp_user,
password=sftp_password,
) as sftp,
BookkeepingHandler("copernicus", "copernicus_repacking") as handler,
NASPackageCreator(
nas_path=nas_path,
bookkeeping_handler=handler,
target_size=100 * 1024 * 1024,
max_n_components=20,
) as package_creator,
UnpackedDeliveryHandler(
bookkeeping_handler=handler,
sftpc=sftp,
sftp_base=sftp.sftp_base,
) as delivery_handler,
):
for filename in sftp.get_sftp_client().listdir():
if not filename.startswith("mr-"):
continue
source_url = f"{sftp.sftp_base}/{filename}"
doi = f"doi:10.5194/{pathlib.Path(filename).stem}"
# The stable source URL is the identity used for duplicate detection.
if delivery_handler.check_prior_location_registration(source_url):
continue
try:
delivery = delivery_handler.switch_to_delivery(
location_base_abs=source_url,
provider_publication_identifiers=doi,
content_path=None,
content_filter=None,
)
except UnreadableDeliveryArchiveError as exc:
logger.warning(str(exc))
continue
if delivery is False:
continue
package_creator.add_component_copy_from_delivery(delivery)
delivery_handler.close_and_submit()
For an sftp:// location, switch_to_delivery uses the supplied SFTPConnector to download the source into an in-memory file and then analyses it. sftp_base must be the prefix of location_base_abs. For a local source, omit the SFTP arguments and pass an absolute local path as location_base_abs.
With the default skip_analysis=False, analysis opens ZIP deliveries and reads every selected member while calculating its SHA-256 hash. If Python reports that the archive cannot be opened or read as a ZIP, switch_to_delivery raises UnreadableDeliveryArchiveError, with the original zipfile.BadZipFile available as its cause. The handler only assigns the candidate to currentDelivery after successful analysis. Consequently, a failed delivery cannot be submitted accidentally when the handler switches to the next source. Catch the exception around each source, as above, when a batch should log and skip corrupt deliveries; leave it uncaught when one unreadable delivery should fail the flow.
ZIP recognition is case-insensitive, so extensions such as .zip, .ZIP, and .Zip are handled identically. Setting skip_analysis=True deliberately bypasses this validation and leaves analysis and error handling to the caller.
The order of the last two calls is intentional:
add_component_copy_from_deliverycreates the NAS component and records itsprov:wasDerivedFromrelationship using the source location's reserved UUID.close_and_submitregisters the sourceUnpackedDeliverywith that UUID.
Case 2: several publications in one source package
Use DeliveryPackageHandler when the source archive contains multiple publications. mdpi_packer.py reads the package's table of contents and turns each article into a component selected by a regular expression.
Remote delivery packages must have a local working copy. Preserve the remote URL as package_location and supply the downloaded file as temp_copy_location:
from bookkeeping.bookkeeping_managers import (
DeliveryPackageHandler,
NASPackageCreator,
)
from bookkeeping.bookkeepinghandler import BookkeepingHandler
with (
BookkeepingHandler("MDPI", "mdpi_repacking") as handler,
NASPackageCreator(
nas_path=nas_path,
bookkeeping_handler=handler,
target_size=250 * 1024 * 1024,
max_n_components=8,
) as package_creator,
DeliveryPackageHandler(bookkeeping_handler=handler) as package_handler,
):
for remote_filename in remote_filenames:
source_url = f"{sftp_base}/{remote_filename}"
if package_handler.check_prior_package_registration(source_url):
continue
local_copy = download_to_temp_directory(remote_filename)
source_package = package_handler.switch_to_package(
package_location=source_url,
temp_copy_location=local_copy,
# Safe because the explicit check above already ran.
skip_prior_registration_check=True,
)
if source_package is False:
continue
for article in read_article_selectors(local_copy):
package_handler.add_component(
content_path=None,
content_filter=article["name_filter"],
provider_publication_identifiers=article["doi"],
)
package_creator.add_component_copy_from_delivery(
package_handler.currentComponent
)
package_handler.close_and_submit_current_package()
local_copy.unlink()
add_component(...) creates a DeliveryDataPackageComponent and, unless skip_analysis=True, records each selected file and its SHA-256 hash. add_component_copy_from_delivery(...) accepts this component even though its parameter is named delivery; both unpacked deliveries and package components expose the required copy and analysis methods.
Call close_and_submit_current_package() before deleting a temporary local copy. The method closes the source archive, writes recovery data, and registers the delivery package and all its components.
Selecting files inside a source package
content_path and content_filter together identify the files of one publication:
content_path=None: start at the outer ZIP root;- a directory path: select relative to that directory;
- a path ending in
.zip: treat that entry as a nested ZIP containing the component; content_filter=None: include everything belowcontent_path;content_filter="regex:<pattern>": include names for which Python'sre.matchmatches the pattern.
Only regex: filters are currently implemented. Filters operate on names relative to content_path. For example:
package_handler.add_component(
content_path=None,
content_filter=r"regex:^article-1234\.",
provider_publication_identifiers="doi:10.1234/article-1234",
)
Use a selector that cannot overlap another publication's selector. Unsafe paths, including absolute paths and .. traversal, are rejected.
Case 3: keep a large existing package instead of repacking it
For a large delivery, it may be cheaper to copy the whole package to permanent NAS storage and register that local copy as an NASDataPackage. mdpi_packer.py uses permanent_copy_location for this case:
from uuid6 import uuid7
reserved_uuid = str(uuid7())
destination = copy_source_package_to_nas(
source_filename,
reserved_uuid=reserved_uuid,
)
package_handler.switch_to_package(
package_location=source_url,
permanent_copy_location=destination,
reserved_uuid=reserved_uuid,
)
for article in read_article_selectors(destination):
package_handler.add_component(
content_path=None,
content_filter=article["name_filter"],
provider_publication_identifiers=article["doi"],
)
delivery_iri, nas_iri = package_handler.close_and_submit_current_package()
In this mode no NASPackageCreator is involved for that source package. On close, DeliveryPackageHandler registers two package descriptions with matching components:
- the provider's delivery package at
package_location; and - an
NASDataPackageatpermanent_copy_location.
In the MDPI flow, reserved_uuid is generated before the copy so it can be used to shard the destination directory and reserve the delivery package's bookkeeping UUID. The registered NAS copy receives its own package UUID; provenance between corresponding components is retained by the handler. Do not delete the permanent copy after registration.
Writing a new component directly
If the files do not already exist as a bookkeeping DataLocation, create a component and write bytes directly:
package_creator.create_next_component(
provider_publication_identifiers="doi:10.1234/example",
derived_from_uuid=source_location_uuid, # optional provenance
)
package_creator.write_to_current_component(
relpath="article.xml",
bytes_to_write=xml_bytes,
)
package_creator.write_to_current_component(
relpath="article.pdf",
bytes_to_write=pdf_bytes,
)
package_creator.finish_component()
For several writes, the archive context avoids repeatedly opening the temporary component ZIP:
package_creator.create_next_component(
provider_publication_identifiers=["doi:10.1234/example", "custom:12345"]
)
with package_creator.get_current_component_open_archive_object() as archive:
archive.writestr("article.xml", xml_bytes)
archive.writestr("article.pdf", pdf_bytes)
package_creator.finish_component()
create_next_component automatically finishes a previous component and creates an outer package if necessary. finish_component embeds the component ZIP, records hashes, removes its temporary object, and applies the package rollover thresholds.
Identifiers, verification, and provenance
Every component needs at least one provider publication identifier. A string or an iterable of strings is accepted. Use the canonical prefix where possible, for example doi:10.1234/example, urn:nbn:..., or a provider-specific custom:... identifier. The bookkeeping layer performs basic DOI and URN normalization, but callers remain responsible for supplying a stable identifier that is unique within the provider.
add_component_copy_from_delivery(...) performs the following checks automatically:
- Calculates the source component's uncompressed size.
- Builds the new component in memory when it is at most 10 MiB, otherwise in the configured temporary archive directory.
- Analyses the copied files and records their SHA-256 hashes.
- Verifies that source and destination file/hash maps are identical.
- Records provenance from the NAS component to the source location UUID.
Ensure that <WDM_DATA_ROOT_TEMP>/bookkeeping/temp_archives exists before copying components larger than 10 MiB. The current manager uses this directory for disk-backed temporary component ZIPs but does not create the directory itself.
Duplicate checks and lifecycle rules
- Use
check_prior_location_registration(...)for one-publication locations andcheck_prior_package_registration(...)for packages. switch_to_delivery(...)andswitch_to_package(...)repeat the relevant check by default and returnFalsewhen the location/package is already known.switch_to_delivery(...)raisesUnreadableDeliveryArchiveErrorfor a ZIP that fails its default analysis. This is distinct from theFalseduplicate result, and the failed candidate is not retained ascurrentDelivery.- Set
skip_prior_registration_check=Trueonly if the same stable location was checked immediately beforehand or duplicate registration is intentionally handled elsewhere. - Opening a new source package normally closes and submits the previous one.
discard_previous=Truedrops the previous in-memory description instead; use it only before that description has been registered. - Always use the context managers, but note the lifecycle difference: leaving
NASPackageCreatorflushes the remaining NAS package, whileDeliveryPackageHandlerandUnpackedDeliveryHandlerstill require an explicit close-and-submit call for each source. - Delete temporary downloads only after their delivery description has been analysed and submitted. Never delete a
permanent_copy_location. - Do not run concurrent manager instances that share the same
recover_dir. Recovery filenames such asNASPackageCreator.json,DPH-Delivery.json, andDPH-LocalCopy.jsonare fixed and would collide.
Recovery and registration
Before registering a completed package, the managers serialize its description to a JSON recovery file under the provider's configured recover_dir. If the first registration attempt fails, NASPackageCreator immediately retries in append mode so that an already partially registered package can be completed. If registration remains interrupted, the next manager instance loads the recovery file and also calls package registration in append mode. Already registered components are skipped.
On successful NAS package completion:
- the outer
.zip.tempfile is closed and renamed once to its final.zippath; - the package description is serialized to the recovery file;
BookkeepingHandler.register_package(...)creates the package and component records and associates components with publications;- the recovery file is renamed with a
-done-<timestamp>suffix.
Registration can create a publication when no existing publication matches a component's provider identifier. Consequently, identifier quality and uniqueness should be validated before packing.
Related implementation files
bookkeeping/bookkeeping_managers.py: supported high-level interface and lifecycle management.bookkeeping/datalocation.py: DataLocation/DataPackage implementations, selection, copying, hashing, and ZIP layout.bookkeeping/bookkeepinghandler.py: RDF registration and duplicate checks.bookkeeping/copernicus_addition.py: single-publication SFTP ZIP example.bookkeeping/mdpi_packer.py: multi-publication package and permanent-copy examples.