OpenCNPJ Documentation
repository·main·Indexed 18 days ago
https://github.com/hitmasu/opencnpjAn automated pipeline for downloading, processing, and publishing Brazilian CNPJ (company) data. The project transforms raw government data into searchable Parquet and NDJSON shards hosted on Cloudflare R2 and BigQuery. It includes a .NET-based ETL processor, a Cloudflare Worker API for efficient data retrieval via binary indices, and a React + TypeScript static SPA for querying company information.
What's inside OpenCNPJ
- OpenCNPJ Worker is a Cloudflare Worker designed to read binary indices published as Static Assets and NDJSON shards published in versioned releases on R2 storage. It provides an API to query CNPJ data efficiently by resolving shards based on CNPJ prefixes.
Project Overview: OpenCNPJ
mainOpenCNPJ is an open project designed to download, process, and publish public data regarding Brazilian companies (CNPJ). The project consists of an ETL pipeline for data processing, a static SPA for querying data, and a Cloudflare Worker that serves data from R2 shards.How Portal da Transparência Integrations Work
mainThe ETL includes an
IDataIntegrationinterface for sub-modules. The Portal da Transparência integration provides several datasets:Current Photographs:
favorecidos_pj,ceis,cepim,cnep,acordos_leniencia,convenios, andemendas_parlamentares.Segmented Historical Datasets:
licitacoes,contratos,renuncias_fiscais,notas_fiscais, andemendas_documentos.Data Availability (Post-2013):
licitacoesandcontratos: Since 2013.renuncias_fiscais: Since 2015.notas_fiscais: Since November 2019.emendas_documentos: Since 2014.
Segmentation Logic: Historical datasets use segments. Closed years are consolidated into a
YYYYsegment, while the current year usesYYYY-MMsegments. The API uses a binary routing index to find which segments contain a specific CNPJ and aggregates them in the response.Optimize Cache Hits for OpenCNPJ Worker
mainThe Worker uses two layers of caching: Cloudflare Workers Cache (first level) and the Cache API (second level). To maximize cache hits and avoid unnecessary Worker invocations, follow these best practices:
- Use unmasked CNPJs: Prefer numeric formats (e.g.,
12345678000195) over masked formats (e.g.,12.345.678/0001-95). - Canonical Dataset Order: Always provide the
datasetsquery parameter in a consistent, canonical order:receita,cno,rntrc.
The full URL, including the query string, composes the cache key. The Worker also maintains a hot in-memory cache within the isolate for recently read shard indices (limited to 32 MiB or a specific count).
- Use unmasked CNPJs: Prefer numeric formats (e.g.,
Develop the Static Query Page
mainThe query interface is a React + TypeScript SPA located in
src/Page. It is entirely static.Commands:
# Install dependencies npm install # Start local development server npm run dev # Build the production static version npm run buildNote: When deploying, use the generated files in
src/Page/dist. Do not use the sourcesrc/Page/index.htmlused by Vite for production.cd src/Page npm install npm run buildRun the ETL Pipeline
mainNavigate to
src/ETL/Processorto execute the pipeline using the .NET CLI.Commands:
# Run the pipeline for the most recent month available on WebDAV dotnet run pipeline # Run the pipeline for a specific month (YYYY-MM) dotnet run pipeline -m 2023-01 # Force a specific remote release ID dotnet run pipeline --release-id abc123... # Run and clean up local temporary artifacts (downloads, extracted CSVs) upon success dotnet run pipeline --cleanup-on-successcd src/ETL/Processor dotnet run pipelineSystem Requirements for OpenCNPJ
mainTo run the OpenCNPJ pipeline and services, ensure the following are installed:
- .NET SDK 10.0+ (for the ETL Processor)
- rclone: Must be installed and authenticated to your target storage (e.g., Backblaze, R2, S3, Azure Storage).
- bq CLI: Required only if
BigQuery.Enabled=truein your configuration. - Disk Space & Connection: High disk availability and a stable connection are required, as the initial execution can take several days.
Deploy the Full Stack via deploy.sh
mainThe
src/script/deploy.shscript orchestrates the entire release process, including running the ETL, validating BigQuery (if enabled), copying assets to the Worker, and deploying the Cloudflare Worker.Deployment Workflow:
- Runs the ETL with a versioned release.
- Validates BigQuery configuration and access via
bq show. - Copies
info.jsonand*.index.bintosrc/Worker/assets. - Runs
npm teston the Worker. - Executes
npx wrangler deploy. - Validates the live
/infoendpoint and CNPJ lookups. - Removes the old release from the bucket only after successful validation.
Run tests for OpenCNPJ Worker
mainTo run the test suite for the Worker, navigate to the
src/Workerdirectory and executenpm test.cd src/Worker && npm testDeploy the OpenCNPJ Worker
mainTo deploy the Worker, follow these steps:
- Ensure you have adjusted the
bucket_nameinwrangler.tomlto match your actual R2 bucket name. - Run the deployment script from the repository root:
./src/scripts/deploy.shOptional: You can pass a
--base-urlflag to the script if you want to validate and clean up an old release using a specific domain.bash ./src/scripts/deploy.sh # Or with an optional base-url ./src/scripts/deploy.sh --base-url https://example.com- Ensure you have adjusted the
Configure the ETL Processor
mainThe ETL behavior is controlled via
src/ETL/Processor/config.json. You can adjust:- Local folder paths
- Storage destinations
- Memory limits
- Parallelism settings
- rclone configurations for your specific storage provider.
Note: The downloader for Receita data currently uses WebDAV via the SERPRO+/Nextcloud public share.
Manage in-memory caches in opencnpj-worker
mainThe
opencnpj-workerpackage provides an in-memory caching mechanism for frequently accessed data to improve performance. The cache handles three main types of data:BinaryShardIndex,SegmentRoutingIndex, and string-based chunks.Caches are managed using a Least Recently Used (LRU) eviction policy based on both the number of entries and the total byte size. Each entry is also subject to a Time-To-Live (TTL) expiration.
Cache Types
- Hot Index Cache: Stores
BinaryShardIndexobjects. - Hot Routing Index Cache: Stores
SegmentRoutingIndexobjects. - Hot Chunk Cache: Stores string values (chunks).
- Runtime Info Cache: Stores
RuntimeInfometadata.
- Hot Index Cache: Stores