argos-cli 0.3.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- argos/__init__.py +5 -0
- argos/__main__.py +4 -0
- argos/adapters/__init__.py +9 -0
- argos/adapters/_libreoffice_worker.py +111 -0
- argos/adapters/ai.py +1506 -0
- argos/adapters/ai_remote.py +654 -0
- argos/adapters/attachment_conversion.py +132 -0
- argos/adapters/capabilities.py +31 -0
- argos/adapters/chart_render.py +72 -0
- argos/adapters/docx_pdf.py +2953 -0
- argos/adapters/limesurvey.py +1079 -0
- argos/adapters/model_call.py +274 -0
- argos/adapters/report_publication.py +1530 -0
- argos/adapters/url_fetch.py +146 -0
- argos/adapters/xlsx.py +454 -0
- argos/analytics.py +731 -0
- argos/assets.py +257 -0
- argos/audit_result.py +369 -0
- argos/booleans.py +105 -0
- argos/catalog.py +1205 -0
- argos/cli.py +606 -0
- argos/contracts.py +532 -0
- argos/core.py +325 -0
- argos/default_skills/README.md +23 -0
- argos/default_skills/criar-matriz-planejamento/SKILL.md +200 -0
- argos/default_skills/elaborar-survey-limesurvey/SKILL.md +106 -0
- argos/default_skills/operar-argos/SKILL.md +74 -0
- argos/default_skills/verificar-diretrizes-fiscalizacao/SKILL.md +129 -0
- argos/default_skills/verificar-diretrizes-fiscalizacao/assets/relatorio-avaliacao.md +54 -0
- argos/default_skills/verificar-diretrizes-fiscalizacao/references/contrato-saidas.md +36 -0
- argos/default_skills/verificar-diretrizes-fiscalizacao/references/papeis-das-pastas.md +37 -0
- argos/default_skills/verificar-diretrizes-fiscalizacao/references/roteiro-verificacoes.md +27 -0
- argos/default_skills/verificar-diretrizes-fiscalizacao/scripts/avaliacao.py +253 -0
- argos/engines/__init__.py +3 -0
- argos/engines/adjustments.py +571 -0
- argos/engines/analytics.py +195 -0
- argos/engines/audit.py +2730 -0
- argos/engines/evaluation.py +6088 -0
- argos/engines/index.py +1683 -0
- argos/engines/matrix.py +5736 -0
- argos/engines/matrix_html.py +698 -0
- argos/engines/model_request.py +201 -0
- argos/engines/report_document.py +137 -0
- argos/engines/reports.py +1200 -0
- argos/engines/survey.py +4445 -0
- argos/envfile.py +53 -0
- argos/errors.py +29 -0
- argos/evidence_staging.py +293 -0
- argos/executions.py +565 -0
- argos/findings_matrix.py +2549 -0
- argos/fingerprints.py +487 -0
- argos/index_dsl.py +2100 -0
- argos/matrix_markdown.py +475 -0
- argos/matrix_widths.py +280 -0
- argos/pipeline.py +1745 -0
- argos/products.py +220 -0
- argos/progress.py +221 -0
- argos/project.py +608 -0
- argos/report_config.py +158 -0
- argos/resources/ESPECIFICACAO_MARKDOWN_MATRIZ_ACHADOS.md +539 -0
- argos/resources/ESPECIFICACAO_MARKDOWN_MATRIZ_PLANEJAMENTO.md +1000 -0
- argos/resources/ESPECIFICACAO_UNIFICADA_MATRIZES_V1_3.md +1142 -0
- argos/resources/anexo-evidencias-base.docx +0 -0
- argos/resources/argos-index-dsl-v1.schema.json +539 -0
- argos/resources/argos-report-config-v1.schema.json +113 -0
- argos/resources/diretrizes-projeto.md +476 -0
- argos/resources/env.example +37 -0
- argos/resources/exemplos/matriz_achados_boilerplate.md +61 -0
- argos/resources/exemplos/matriz_achados_draft.md +106 -0
- argos/resources/exemplos/matriz_achados_larguras_v1_3.md +114 -0
- argos/resources/exemplos/matriz_achados_v1_3.md +107 -0
- argos/resources/exemplos/matriz_planejamento_boilerplate.md +64 -0
- argos/resources/exemplos/matriz_planejamento_larguras_v1_3.md +115 -0
- argos/resources/exemplos/matriz_planejamento_v1_3.md +108 -0
- argos/resources/template-base-estilos-sigiloso.docx +0 -0
- argos/resources/template-base-estilos.docx +0 -0
- argos/resources/template-matriz-planejamento.docx +0 -0
- argos/resources/template-relatorio-consolidado-comum.docx +0 -0
- argos/resources/template-relatorio-consolidado-institucional.docx +0 -0
- argos/response_profiles.py +856 -0
- argos/scheduler.py +142 -0
- argos/status.py +367 -0
- argos/store.py +1228 -0
- argos/survey_collection.py +832 -0
- argos/telemetry.py +84 -0
- argos/tui.py +1262 -0
- argos/tui.tcss +827 -0
- argos/tui_models.py +466 -0
- argos/tui_path.py +155 -0
- argos/tui_widgets.py +482 -0
- argos/version.py +3 -0
- argos_cli-0.3.1.dist-info/METADATA +570 -0
- argos_cli-0.3.1.dist-info/RECORD +96 -0
- argos_cli-0.3.1.dist-info/WHEEL +5 -0
- argos_cli-0.3.1.dist-info/entry_points.txt +2 -0
- argos_cli-0.3.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,832 @@
|
|
|
1
|
+
"""Layout, manifesto e store gerenciado da coleta LimeSurvey.
|
|
2
|
+
|
|
3
|
+
Os anexos correntes usam nomes estáveis (``respostas.pdf`` e
|
|
4
|
+
``evidencias.zip``). Como o publicador de produtos do Argos não sobrescreve
|
|
5
|
+
arquivos, a atualização é feita pelo store gerenciado deste módulo: a versão
|
|
6
|
+
anterior é movida para ``.versoes`` e a nova é instalada atomicamente no
|
|
7
|
+
caminho estável.
|
|
8
|
+
|
|
9
|
+
O manifesto de cada execução é um produto imutável. O ``manifesto-geral.xlsx``
|
|
10
|
+
é um índice derivado, reconstruível e gravado fora do ciclo de produtos.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import contextlib
|
|
16
|
+
import hashlib
|
|
17
|
+
import os
|
|
18
|
+
import re
|
|
19
|
+
import shutil
|
|
20
|
+
import tempfile
|
|
21
|
+
import unicodedata
|
|
22
|
+
import uuid
|
|
23
|
+
import zipfile
|
|
24
|
+
from dataclasses import dataclass, field
|
|
25
|
+
from datetime import datetime, timezone
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
from typing import Any, Iterable, Iterator, Mapping, Sequence
|
|
28
|
+
|
|
29
|
+
from .adapters.xlsx import openpyxl_workbook, sheet_records, xlsx_bytes_with_headers
|
|
30
|
+
from .contracts import canonical_json, sha256_bytes, sha256_file
|
|
31
|
+
from .errors import InputValidationError
|
|
32
|
+
|
|
33
|
+
ATTACHMENT_TYPES = frozenset({"pdf", "zip"})
|
|
34
|
+
ATTACHMENT_FILENAMES = {"pdf": "respostas.pdf", "zip": "evidencias.zip"}
|
|
35
|
+
|
|
36
|
+
CURRENT_STATUS_ATUAL = "atual"
|
|
37
|
+
CURRENT_STATUS_SEM_ANEXO = "sem_anexo"
|
|
38
|
+
|
|
39
|
+
REUSE = "reutilizado"
|
|
40
|
+
REVALIDATED = "revalidado"
|
|
41
|
+
DOWNLOADED = "baixado"
|
|
42
|
+
UPDATED = "atualizado"
|
|
43
|
+
NO_ATTACHMENT = "sem_anexo"
|
|
44
|
+
ERROR = "erro"
|
|
45
|
+
|
|
46
|
+
CURRENT_COLUMNS = (
|
|
47
|
+
"survey_id",
|
|
48
|
+
"response_id",
|
|
49
|
+
"auditado",
|
|
50
|
+
"tipo",
|
|
51
|
+
"status",
|
|
52
|
+
"caminho_relativo",
|
|
53
|
+
"sha256",
|
|
54
|
+
"content_fingerprint",
|
|
55
|
+
"source_fingerprint",
|
|
56
|
+
"primeira_execucao",
|
|
57
|
+
"ultima_execucao",
|
|
58
|
+
)
|
|
59
|
+
HISTORY_COLUMNS = (
|
|
60
|
+
"execution_id",
|
|
61
|
+
"coletado_em",
|
|
62
|
+
"survey_id",
|
|
63
|
+
"response_id",
|
|
64
|
+
"auditado",
|
|
65
|
+
"tipo",
|
|
66
|
+
"status",
|
|
67
|
+
"caminho_relativo",
|
|
68
|
+
"sha256",
|
|
69
|
+
"content_fingerprint",
|
|
70
|
+
"source_fingerprint",
|
|
71
|
+
"erro",
|
|
72
|
+
)
|
|
73
|
+
VERSION_COLUMNS = (
|
|
74
|
+
"survey_id",
|
|
75
|
+
"response_id",
|
|
76
|
+
"tipo",
|
|
77
|
+
"sha256",
|
|
78
|
+
"caminho_relativo",
|
|
79
|
+
"arquivado_em",
|
|
80
|
+
"execution_id",
|
|
81
|
+
)
|
|
82
|
+
EXECUTION_COLUMNS = (
|
|
83
|
+
"execution_id",
|
|
84
|
+
"coletado_em",
|
|
85
|
+
"survey_id",
|
|
86
|
+
"snapshot_dir",
|
|
87
|
+
"respostas_sha256",
|
|
88
|
+
"submetidas",
|
|
89
|
+
"reutilizados",
|
|
90
|
+
"revalidados",
|
|
91
|
+
"baixados",
|
|
92
|
+
"atualizados",
|
|
93
|
+
"sem_anexo",
|
|
94
|
+
"erros",
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
_SHA256_RE = re.compile(r"^[0-9a-f]{64}$")
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _text(value: Any) -> str:
|
|
101
|
+
if value is None:
|
|
102
|
+
return ""
|
|
103
|
+
if isinstance(value, float) and value.is_integer():
|
|
104
|
+
return str(int(value))
|
|
105
|
+
return str(value).strip()
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _positive_id(value: Any, field_name: str) -> str:
|
|
109
|
+
text = _text(value)
|
|
110
|
+
if not re.fullmatch(r"[1-9][0-9]*", text):
|
|
111
|
+
raise InputValidationError(f"{field_name} inválido no manifesto: {text!r}")
|
|
112
|
+
return text
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _sha(value: Any, field_name: str, *, allow_empty: bool = False) -> str:
|
|
116
|
+
text = _text(value).lower()
|
|
117
|
+
if not text and allow_empty:
|
|
118
|
+
return ""
|
|
119
|
+
if not _SHA256_RE.fullmatch(text):
|
|
120
|
+
raise InputValidationError(f"{field_name} inválido no manifesto")
|
|
121
|
+
return text
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _attachment_type(value: Any) -> str:
|
|
125
|
+
text = _text(value).lower()
|
|
126
|
+
if text not in ATTACHMENT_TYPES:
|
|
127
|
+
raise InputValidationError(f"tipo de anexo inválido no manifesto: {text!r}")
|
|
128
|
+
return text
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _row_value(row: Mapping[str, Any], key: str) -> str:
|
|
132
|
+
return _text(row.get(key))
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def slugify_auditado(label: Any, response_id: Any) -> str:
|
|
136
|
+
"""Normaliza o nome do auditado para um diretório portátil."""
|
|
137
|
+
normalized = unicodedata.normalize("NFKD", str(label or ""))
|
|
138
|
+
ascii_text = normalized.encode("ascii", "ignore").decode("ascii")
|
|
139
|
+
slug = re.sub(r"[^A-Za-z0-9]+", "-", ascii_text).strip("-").lower()
|
|
140
|
+
slug = slug[:60].strip("-") or "auditado"
|
|
141
|
+
return f"{slug}-r{_positive_id(response_id, 'response_id')}"
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def attachment_filename(tipo: str) -> str:
|
|
145
|
+
try:
|
|
146
|
+
return ATTACHMENT_FILENAMES[tipo]
|
|
147
|
+
except KeyError as exc:
|
|
148
|
+
raise InputValidationError(f"tipo de anexo inválido: {tipo!r}") from exc
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def zip_content_fingerprint(path: Path) -> str:
|
|
152
|
+
"""Fingerprint lógico do ZIP, independente de recompressão.
|
|
153
|
+
|
|
154
|
+
O hash inclui nome, tamanho e SHA-256 de cada membro. Assim, o mesmo
|
|
155
|
+
conteúdo compactado de outra forma continua sendo o mesmo anexo.
|
|
156
|
+
"""
|
|
157
|
+
try:
|
|
158
|
+
with zipfile.ZipFile(path) as archive:
|
|
159
|
+
members: list[dict[str, Any]] = []
|
|
160
|
+
for info in archive.infolist():
|
|
161
|
+
if info.is_dir():
|
|
162
|
+
continue
|
|
163
|
+
digest = hashlib.sha256()
|
|
164
|
+
with archive.open(info) as stream:
|
|
165
|
+
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
|
166
|
+
digest.update(chunk)
|
|
167
|
+
members.append(
|
|
168
|
+
{
|
|
169
|
+
"nome": info.filename.replace("\\", "/"),
|
|
170
|
+
"tamanho": int(info.file_size),
|
|
171
|
+
"sha256": digest.hexdigest(),
|
|
172
|
+
}
|
|
173
|
+
)
|
|
174
|
+
except (OSError, zipfile.BadZipFile, RuntimeError) as exc:
|
|
175
|
+
raise InputValidationError(f"ZIP inválido ou ilegível ({type(exc).__name__})") from None
|
|
176
|
+
members.sort(key=lambda item: (str(item["nome"]), int(item["tamanho"]), str(item["sha256"])))
|
|
177
|
+
return sha256_bytes(canonical_json(members).encode("utf-8"))
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def content_fingerprint(path: Path, tipo: str) -> str:
|
|
181
|
+
"""PDF usa o próprio SHA-256; ZIP usa o fingerprint dos membros."""
|
|
182
|
+
if tipo == "pdf":
|
|
183
|
+
return sha256_file(path)
|
|
184
|
+
if tipo == "zip":
|
|
185
|
+
return zip_content_fingerprint(path)
|
|
186
|
+
raise InputValidationError(f"tipo de anexo inválido: {tipo!r}")
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def resolve_relative(root: Path, value: Any, *, allow_empty: bool = False) -> Path | None:
|
|
190
|
+
"""Resolve um caminho relativo e garante que ele não escape da raiz."""
|
|
191
|
+
text = _text(value)
|
|
192
|
+
if not text:
|
|
193
|
+
if allow_empty:
|
|
194
|
+
return None
|
|
195
|
+
raise InputValidationError("caminho relativo ausente no manifesto")
|
|
196
|
+
candidate = Path(text)
|
|
197
|
+
if candidate.is_absolute() or any(part == ".." for part in candidate.parts):
|
|
198
|
+
raise InputValidationError(f"caminho inválido no manifesto: {text!r}")
|
|
199
|
+
resolved = (root / candidate).resolve()
|
|
200
|
+
root_resolved = root.expanduser().resolve()
|
|
201
|
+
if not resolved.is_relative_to(root_resolved):
|
|
202
|
+
raise InputValidationError(f"caminho fora da pasta do survey: {text!r}")
|
|
203
|
+
return resolved
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _require_under(path: Path | None, base: Path, label: str) -> None:
|
|
207
|
+
if path is None:
|
|
208
|
+
return
|
|
209
|
+
if not path.is_relative_to(base.expanduser().resolve()):
|
|
210
|
+
raise InputValidationError(f"{label} fora da área esperada: {path}")
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def relative_path(root: Path, path: Path) -> str:
|
|
214
|
+
resolved = path.expanduser().resolve()
|
|
215
|
+
root_resolved = root.expanduser().resolve()
|
|
216
|
+
if not resolved.is_relative_to(root_resolved):
|
|
217
|
+
raise InputValidationError(f"caminho fora da pasta do survey: {path}")
|
|
218
|
+
return resolved.relative_to(root_resolved).as_posix()
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
@dataclass(frozen=True)
|
|
222
|
+
class SurveyLayout:
|
|
223
|
+
"""Caminhos de uma coleta. Não cria diretórios."""
|
|
224
|
+
|
|
225
|
+
root: Path
|
|
226
|
+
survey_id: str
|
|
227
|
+
execution_id: str
|
|
228
|
+
collected_at: str
|
|
229
|
+
timestamp: str
|
|
230
|
+
snapshot_dir: Path
|
|
231
|
+
attachments_dir: Path
|
|
232
|
+
versions_root: Path
|
|
233
|
+
corrupted_root: Path
|
|
234
|
+
central_manifest: Path
|
|
235
|
+
derived_dir: Path
|
|
236
|
+
|
|
237
|
+
@classmethod
|
|
238
|
+
def for_execution(
|
|
239
|
+
cls,
|
|
240
|
+
root: Path | str,
|
|
241
|
+
survey_id: str,
|
|
242
|
+
execution_id: str,
|
|
243
|
+
*,
|
|
244
|
+
now: datetime | None = None,
|
|
245
|
+
) -> "SurveyLayout":
|
|
246
|
+
resolved_root = Path(root).expanduser().resolve()
|
|
247
|
+
moment = (now or datetime.now(timezone.utc)).astimezone(timezone.utc)
|
|
248
|
+
timestamp = moment.strftime("%Y-%m-%dT%H%MZ")
|
|
249
|
+
execution_suffix = re.sub(r"[^0-9a-f]", "", execution_id.lower())[:8] or "exec"
|
|
250
|
+
snapshot = resolved_root / "exportacoes_brutas" / f"{timestamp}-{execution_suffix}"
|
|
251
|
+
attachments = resolved_root / "auditados"
|
|
252
|
+
return cls(
|
|
253
|
+
root=resolved_root,
|
|
254
|
+
survey_id=_positive_id(survey_id, "survey_id"),
|
|
255
|
+
execution_id=execution_id,
|
|
256
|
+
collected_at=moment.isoformat(timespec="seconds"),
|
|
257
|
+
timestamp=timestamp,
|
|
258
|
+
snapshot_dir=snapshot,
|
|
259
|
+
attachments_dir=attachments,
|
|
260
|
+
versions_root=attachments / ".versoes",
|
|
261
|
+
corrupted_root=attachments / ".corrompidos",
|
|
262
|
+
central_manifest=resolved_root / "manifesto-geral.xlsx",
|
|
263
|
+
derived_dir=resolved_root / "derivados",
|
|
264
|
+
)
|
|
265
|
+
|
|
266
|
+
def response_dir(self, auditado: Any, response_id: Any) -> Path:
|
|
267
|
+
return self.attachments_dir / slugify_auditado(auditado, response_id)
|
|
268
|
+
|
|
269
|
+
def stable_path(self, auditado: Any, response_id: Any, tipo: str) -> Path:
|
|
270
|
+
return self.response_dir(auditado, response_id) / attachment_filename(tipo)
|
|
271
|
+
|
|
272
|
+
def version_dir(self, response_id: Any, tipo: str, sha256: str) -> Path:
|
|
273
|
+
response = _positive_id(response_id, "response_id")
|
|
274
|
+
digest = _sha(sha256, "sha256")
|
|
275
|
+
return self.versions_root / response / digest[:12]
|
|
276
|
+
|
|
277
|
+
def version_path(self, response_id: Any, tipo: str, sha256: str) -> Path:
|
|
278
|
+
return self.version_dir(response_id, tipo, sha256) / attachment_filename(tipo)
|
|
279
|
+
|
|
280
|
+
def corrupt_path(self, response_id: Any, tipo: str) -> Path:
|
|
281
|
+
response = _positive_id(response_id, "response_id")
|
|
282
|
+
return self.corrupted_root / self.timestamp / f"{response}-{attachment_filename(tipo)}"
|
|
283
|
+
|
|
284
|
+
def derived_evidence_dir(self, auditado: Any, response_id: Any) -> Path:
|
|
285
|
+
return self.derived_dir / "evidencias" / slugify_auditado(auditado, response_id)
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
@dataclass
|
|
289
|
+
class ManifestState:
|
|
290
|
+
current: dict[tuple[str, str, str], dict[str, Any]] = field(default_factory=dict)
|
|
291
|
+
history: list[dict[str, Any]] = field(default_factory=list)
|
|
292
|
+
versions: list[dict[str, Any]] = field(default_factory=list)
|
|
293
|
+
executions: list[dict[str, Any]] = field(default_factory=list)
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
@dataclass(frozen=True)
|
|
297
|
+
class ExecutionManifest:
|
|
298
|
+
observations: tuple[dict[str, Any], ...]
|
|
299
|
+
versions: tuple[dict[str, Any], ...]
|
|
300
|
+
execution: dict[str, Any]
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _validate_headers(headers: Sequence[str], required: Sequence[str], sheet: str) -> None:
|
|
304
|
+
present = {str(header).strip() for header in headers if str(header).strip()}
|
|
305
|
+
missing = [column for column in required if column not in present]
|
|
306
|
+
if missing:
|
|
307
|
+
raise InputValidationError(f"aba {sheet!r} sem colunas obrigatórias: {', '.join(missing)}")
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def _open_workbook(path: Path, sheets: Sequence[str]):
|
|
311
|
+
if not path.is_file():
|
|
312
|
+
raise InputValidationError(f"manifesto ausente: {path}")
|
|
313
|
+
load_workbook = openpyxl_workbook()
|
|
314
|
+
try:
|
|
315
|
+
workbook = load_workbook(path, read_only=True, data_only=True)
|
|
316
|
+
except (OSError, ValueError) as exc:
|
|
317
|
+
raise InputValidationError(f"não foi possível ler o manifesto {path.name}: {exc}") from None
|
|
318
|
+
missing = [sheet for sheet in sheets if sheet not in workbook.sheetnames]
|
|
319
|
+
if missing:
|
|
320
|
+
workbook.close()
|
|
321
|
+
raise InputValidationError(f"manifesto {path.name!r} sem abas: {', '.join(missing)}")
|
|
322
|
+
return workbook
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def _normalize_current(row: Mapping[str, Any], root: Path, survey_id: str) -> dict[str, Any]:
|
|
326
|
+
sid = _positive_id(row.get("survey_id"), "survey_id")
|
|
327
|
+
if sid != survey_id:
|
|
328
|
+
raise InputValidationError(
|
|
329
|
+
f"a pasta pertence ao survey {sid}; a coleta atual usa o survey {survey_id}"
|
|
330
|
+
)
|
|
331
|
+
response_id = _positive_id(row.get("response_id"), "response_id")
|
|
332
|
+
tipo = _attachment_type(row.get("tipo"))
|
|
333
|
+
status = _text(row.get("status"))
|
|
334
|
+
if status not in {CURRENT_STATUS_ATUAL, CURRENT_STATUS_SEM_ANEXO}:
|
|
335
|
+
raise InputValidationError(f"status corrente inválido: {status!r}")
|
|
336
|
+
path = resolve_relative(root, row.get("caminho_relativo"), allow_empty=status == CURRENT_STATUS_SEM_ANEXO)
|
|
337
|
+
sha = _sha(row.get("sha256"), "sha256", allow_empty=status == CURRENT_STATUS_SEM_ANEXO)
|
|
338
|
+
if status == CURRENT_STATUS_ATUAL and (path is None or not sha):
|
|
339
|
+
raise InputValidationError("anexo corrente sem caminho ou sha256")
|
|
340
|
+
_require_under(path, root / "auditados", "anexo corrente")
|
|
341
|
+
if path is not None:
|
|
342
|
+
resolved_path = path.resolve()
|
|
343
|
+
if resolved_path.is_relative_to((root / "auditados" / ".versoes").resolve()) or resolved_path.is_relative_to(
|
|
344
|
+
(root / "auditados" / ".corrompidos").resolve()
|
|
345
|
+
):
|
|
346
|
+
raise InputValidationError("anexo corrente não pode apontar para versões ou quarentena")
|
|
347
|
+
return {
|
|
348
|
+
"survey_id": sid,
|
|
349
|
+
"response_id": response_id,
|
|
350
|
+
"auditado": _row_value(row, "auditado"),
|
|
351
|
+
"tipo": tipo,
|
|
352
|
+
"status": status,
|
|
353
|
+
"caminho_relativo": relative_path(root, path) if path is not None else "",
|
|
354
|
+
"sha256": sha,
|
|
355
|
+
"content_fingerprint": _row_value(row, "content_fingerprint"),
|
|
356
|
+
"source_fingerprint": _row_value(row, "source_fingerprint"),
|
|
357
|
+
"primeira_execucao": _row_value(row, "primeira_execucao"),
|
|
358
|
+
"ultima_execucao": _row_value(row, "ultima_execucao"),
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def _normalize_history(row: Mapping[str, Any], root: Path, survey_id: str) -> dict[str, Any]:
|
|
363
|
+
sid = _positive_id(row.get("survey_id"), "survey_id")
|
|
364
|
+
if sid != survey_id:
|
|
365
|
+
raise InputValidationError(
|
|
366
|
+
f"histórico do manifesto pertence ao survey {sid}; a coleta atual usa {survey_id}"
|
|
367
|
+
)
|
|
368
|
+
tipo = _attachment_type(row.get("tipo"))
|
|
369
|
+
status = _row_value(row, "status")
|
|
370
|
+
if status not in {REUSE, REVALIDATED, DOWNLOADED, UPDATED, NO_ATTACHMENT, ERROR}:
|
|
371
|
+
raise InputValidationError(f"status de histórico inválido: {status!r}")
|
|
372
|
+
path = resolve_relative(root, row.get("caminho_relativo"), allow_empty=True)
|
|
373
|
+
_require_under(path, root / "auditados", "histórico de anexo")
|
|
374
|
+
sha = _sha(row.get("sha256"), "sha256", allow_empty=True)
|
|
375
|
+
return {
|
|
376
|
+
"execution_id": _row_value(row, "execution_id"),
|
|
377
|
+
"coletado_em": _row_value(row, "coletado_em"),
|
|
378
|
+
"survey_id": sid,
|
|
379
|
+
"response_id": _positive_id(row.get("response_id"), "response_id"),
|
|
380
|
+
"auditado": _row_value(row, "auditado"),
|
|
381
|
+
"tipo": tipo,
|
|
382
|
+
"status": status,
|
|
383
|
+
"caminho_relativo": relative_path(root, path) if path is not None else "",
|
|
384
|
+
"sha256": sha,
|
|
385
|
+
"content_fingerprint": _row_value(row, "content_fingerprint"),
|
|
386
|
+
"source_fingerprint": _row_value(row, "source_fingerprint"),
|
|
387
|
+
"erro": _row_value(row, "erro"),
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def _normalize_version(row: Mapping[str, Any], root: Path, survey_id: str) -> dict[str, Any]:
|
|
392
|
+
sid = _positive_id(row.get("survey_id"), "survey_id")
|
|
393
|
+
if sid != survey_id:
|
|
394
|
+
raise InputValidationError(
|
|
395
|
+
f"versão do manifesto pertence ao survey {sid}; a coleta atual usa {survey_id}"
|
|
396
|
+
)
|
|
397
|
+
path = resolve_relative(root, row.get("caminho_relativo"))
|
|
398
|
+
assert path is not None
|
|
399
|
+
_require_under(path, root / "auditados" / ".versoes", "versão arquivada")
|
|
400
|
+
return {
|
|
401
|
+
"survey_id": sid,
|
|
402
|
+
"response_id": _positive_id(row.get("response_id"), "response_id"),
|
|
403
|
+
"tipo": _attachment_type(row.get("tipo")),
|
|
404
|
+
"sha256": _sha(row.get("sha256"), "sha256"),
|
|
405
|
+
"caminho_relativo": relative_path(root, path),
|
|
406
|
+
"arquivado_em": _row_value(row, "arquivado_em"),
|
|
407
|
+
"execution_id": _row_value(row, "execution_id"),
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def _normalize_execution(row: Mapping[str, Any], survey_id: str, root: Path) -> dict[str, Any]:
|
|
412
|
+
sid = _positive_id(row.get("survey_id"), "survey_id")
|
|
413
|
+
if sid != survey_id:
|
|
414
|
+
raise InputValidationError(
|
|
415
|
+
f"execução do manifesto pertence ao survey {sid}; a coleta atual usa {survey_id}"
|
|
416
|
+
)
|
|
417
|
+
result: dict[str, Any] = {}
|
|
418
|
+
for column in EXECUTION_COLUMNS:
|
|
419
|
+
value = row.get(column)
|
|
420
|
+
result[column] = _text(value) if column not in {
|
|
421
|
+
"submetidas", "reutilizados", "revalidados", "baixados", "atualizados", "sem_anexo", "erros"
|
|
422
|
+
} else int(value or 0)
|
|
423
|
+
result["survey_id"] = sid
|
|
424
|
+
if result.get("snapshot_dir"):
|
|
425
|
+
_require_under(
|
|
426
|
+
resolve_relative(root, result["snapshot_dir"]),
|
|
427
|
+
root / "exportacoes_brutas",
|
|
428
|
+
"snapshot da execução",
|
|
429
|
+
)
|
|
430
|
+
return result
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
def load_manifest(path: Path, root: Path, survey_id: str) -> ManifestState:
|
|
434
|
+
"""Carrega o manifesto central, validando estrutura, chaves e caminhos."""
|
|
435
|
+
if not path.exists():
|
|
436
|
+
return ManifestState()
|
|
437
|
+
if not path.is_file():
|
|
438
|
+
raise InputValidationError(f"manifesto central não é arquivo: {path}")
|
|
439
|
+
workbook = _open_workbook(path, ("anexos", "historico", "versoes", "execucoes"))
|
|
440
|
+
try:
|
|
441
|
+
_, anexo_headers, anexo_rows = sheet_records(workbook["anexos"], required=CURRENT_COLUMNS)
|
|
442
|
+
_, history_headers, history_rows = sheet_records(workbook["historico"], required=HISTORY_COLUMNS)
|
|
443
|
+
_, version_headers, version_rows = sheet_records(workbook["versoes"], required=VERSION_COLUMNS)
|
|
444
|
+
_, execution_headers, execution_rows = sheet_records(workbook["execucoes"], required=EXECUTION_COLUMNS)
|
|
445
|
+
_validate_headers(anexo_headers, CURRENT_COLUMNS, "anexos")
|
|
446
|
+
_validate_headers(history_headers, HISTORY_COLUMNS, "historico")
|
|
447
|
+
_validate_headers(version_headers, VERSION_COLUMNS, "versoes")
|
|
448
|
+
_validate_headers(execution_headers, EXECUTION_COLUMNS, "execucoes")
|
|
449
|
+
state = ManifestState(
|
|
450
|
+
history=[_normalize_history(row, root, survey_id) for row in history_rows],
|
|
451
|
+
versions=[_normalize_version(row, root, survey_id) for row in version_rows],
|
|
452
|
+
executions=[_normalize_execution(row, survey_id, root) for row in execution_rows],
|
|
453
|
+
)
|
|
454
|
+
for row in anexo_rows:
|
|
455
|
+
normalized = _normalize_current(row, root, survey_id)
|
|
456
|
+
key = (normalized["survey_id"], normalized["response_id"], normalized["tipo"])
|
|
457
|
+
if key in state.current:
|
|
458
|
+
raise InputValidationError(
|
|
459
|
+
f"manifesto com mais de um anexo corrente para {key[1]} ({key[2]})"
|
|
460
|
+
)
|
|
461
|
+
state.current[key] = normalized
|
|
462
|
+
return state
|
|
463
|
+
finally:
|
|
464
|
+
workbook.close()
|
|
465
|
+
|
|
466
|
+
|
|
467
|
+
def load_execution_manifest(path: Path, root: Path, survey_id: str) -> ExecutionManifest:
|
|
468
|
+
"""Carrega o manifesto imutável de uma execução."""
|
|
469
|
+
workbook = _open_workbook(path, ("coleta", "versoes", "resumo"))
|
|
470
|
+
try:
|
|
471
|
+
_, history_headers, history_rows = sheet_records(workbook["coleta"], required=HISTORY_COLUMNS)
|
|
472
|
+
_, version_headers, version_rows = sheet_records(workbook["versoes"], required=VERSION_COLUMNS)
|
|
473
|
+
_, summary_headers, summary_rows = sheet_records(workbook["resumo"], required=EXECUTION_COLUMNS)
|
|
474
|
+
_validate_headers(history_headers, HISTORY_COLUMNS, "coleta")
|
|
475
|
+
_validate_headers(version_headers, VERSION_COLUMNS, "versoes")
|
|
476
|
+
_validate_headers(summary_headers, EXECUTION_COLUMNS, "resumo")
|
|
477
|
+
if len(summary_rows) != 1:
|
|
478
|
+
raise InputValidationError("manifesto de execução deve ter exatamente uma linha em resumo")
|
|
479
|
+
return ExecutionManifest(
|
|
480
|
+
observations=tuple(_normalize_history(row, root, survey_id) for row in history_rows),
|
|
481
|
+
versions=tuple(_normalize_version(row, root, survey_id) for row in version_rows),
|
|
482
|
+
execution=_normalize_execution(summary_rows[0], survey_id, root),
|
|
483
|
+
)
|
|
484
|
+
finally:
|
|
485
|
+
workbook.close()
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
def _apply_manifest(state: ManifestState, observations: Iterable[Mapping[str, Any]],
|
|
489
|
+
versions: Iterable[Mapping[str, Any]], execution: Mapping[str, Any]) -> None:
|
|
490
|
+
for observation in observations:
|
|
491
|
+
row = dict(observation)
|
|
492
|
+
key = (str(row["survey_id"]), str(row["response_id"]), str(row["tipo"]))
|
|
493
|
+
status = str(row["status"])
|
|
494
|
+
previous = state.current.get(key)
|
|
495
|
+
if status in {REUSE, REVALIDATED, DOWNLOADED, UPDATED}:
|
|
496
|
+
state.current[key] = {
|
|
497
|
+
"survey_id": key[0],
|
|
498
|
+
"response_id": key[1],
|
|
499
|
+
"auditado": row.get("auditado", ""),
|
|
500
|
+
"tipo": key[2],
|
|
501
|
+
"status": CURRENT_STATUS_ATUAL,
|
|
502
|
+
"caminho_relativo": row.get("caminho_relativo", ""),
|
|
503
|
+
"sha256": row.get("sha256", ""),
|
|
504
|
+
"content_fingerprint": row.get("content_fingerprint", ""),
|
|
505
|
+
"source_fingerprint": row.get("source_fingerprint", ""),
|
|
506
|
+
"primeira_execucao": (previous or {}).get("primeira_execucao") or row.get("execution_id", ""),
|
|
507
|
+
"ultima_execucao": row.get("execution_id", ""),
|
|
508
|
+
}
|
|
509
|
+
elif status == NO_ATTACHMENT:
|
|
510
|
+
state.current[key] = {
|
|
511
|
+
"survey_id": key[0],
|
|
512
|
+
"response_id": key[1],
|
|
513
|
+
"auditado": row.get("auditado", ""),
|
|
514
|
+
"tipo": key[2],
|
|
515
|
+
"status": CURRENT_STATUS_SEM_ANEXO,
|
|
516
|
+
"caminho_relativo": "",
|
|
517
|
+
"sha256": "",
|
|
518
|
+
"content_fingerprint": "",
|
|
519
|
+
"source_fingerprint": row.get("source_fingerprint", ""),
|
|
520
|
+
"primeira_execucao": (previous or {}).get("primeira_execucao") or row.get("execution_id", ""),
|
|
521
|
+
"ultima_execucao": row.get("execution_id", ""),
|
|
522
|
+
}
|
|
523
|
+
state.history.append(row)
|
|
524
|
+
known_versions = {
|
|
525
|
+
(str(item.get("survey_id")), str(item.get("response_id")), str(item.get("tipo")), str(item.get("sha256")))
|
|
526
|
+
for item in state.versions
|
|
527
|
+
}
|
|
528
|
+
for version in versions:
|
|
529
|
+
row = dict(version)
|
|
530
|
+
key = (str(row.get("survey_id")), str(row.get("response_id")), str(row.get("tipo")), str(row.get("sha256")))
|
|
531
|
+
if key not in known_versions:
|
|
532
|
+
known_versions.add(key)
|
|
533
|
+
state.versions.append(row)
|
|
534
|
+
state.executions.append(dict(execution))
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
def apply_execution(state: ManifestState, observations: Iterable[Mapping[str, Any]],
|
|
538
|
+
versions: Iterable[Mapping[str, Any]], execution: Mapping[str, Any]) -> None:
|
|
539
|
+
"""Aplica uma execução ao índice central."""
|
|
540
|
+
_apply_manifest(state, observations, versions, execution)
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
def rebuild_from_snapshots(layout: SurveyLayout) -> ManifestState:
|
|
544
|
+
"""Reconstrói o índice central a partir dos manifestos de execução."""
|
|
545
|
+
state = ManifestState()
|
|
546
|
+
snapshot_root = layout.root / "exportacoes_brutas"
|
|
547
|
+
if not snapshot_root.is_dir():
|
|
548
|
+
return state
|
|
549
|
+
manifests = sorted(
|
|
550
|
+
(path / "manifesto.xlsx" for path in snapshot_root.iterdir() if path.is_dir()),
|
|
551
|
+
key=lambda path: path.parent.name,
|
|
552
|
+
)
|
|
553
|
+
for path in manifests:
|
|
554
|
+
if not path.exists():
|
|
555
|
+
continue
|
|
556
|
+
execution = load_execution_manifest(path, layout.root, layout.survey_id)
|
|
557
|
+
_apply_manifest(state, execution.observations, execution.versions, execution.execution)
|
|
558
|
+
return state
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
def load_or_rebuild_manifest(layout: SurveyLayout) -> ManifestState:
|
|
562
|
+
if layout.central_manifest.exists():
|
|
563
|
+
return load_manifest(layout.central_manifest, layout.root, layout.survey_id)
|
|
564
|
+
return rebuild_from_snapshots(layout)
|
|
565
|
+
|
|
566
|
+
|
|
567
|
+
def _ordered_rows(state: ManifestState) -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]]]:
|
|
568
|
+
current = [state.current[key] for key in sorted(state.current)]
|
|
569
|
+
return current, list(state.history), list(state.versions), list(state.executions)
|
|
570
|
+
|
|
571
|
+
|
|
572
|
+
def manifest_bytes(state: ManifestState) -> bytes:
|
|
573
|
+
current, history, versions, executions = _ordered_rows(state)
|
|
574
|
+
return xlsx_bytes_with_headers(
|
|
575
|
+
{
|
|
576
|
+
"anexos": (CURRENT_COLUMNS, current),
|
|
577
|
+
"historico": (HISTORY_COLUMNS, history),
|
|
578
|
+
"versoes": (VERSION_COLUMNS, versions),
|
|
579
|
+
"execucoes": (EXECUTION_COLUMNS, executions),
|
|
580
|
+
}
|
|
581
|
+
)
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
def execution_manifest_bytes(observations: Iterable[Mapping[str, Any]], versions: Iterable[Mapping[str, Any]],
|
|
585
|
+
execution: Mapping[str, Any]) -> bytes:
|
|
586
|
+
return xlsx_bytes_with_headers(
|
|
587
|
+
{
|
|
588
|
+
"coleta": (HISTORY_COLUMNS, observations),
|
|
589
|
+
"versoes": (VERSION_COLUMNS, versions),
|
|
590
|
+
"resumo": (EXECUTION_COLUMNS, (execution,)),
|
|
591
|
+
}
|
|
592
|
+
)
|
|
593
|
+
|
|
594
|
+
|
|
595
|
+
def write_bytes_atomic(path: Path, data: bytes) -> None:
|
|
596
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
597
|
+
temporary = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp")
|
|
598
|
+
try:
|
|
599
|
+
with temporary.open("wb") as stream:
|
|
600
|
+
stream.write(data)
|
|
601
|
+
stream.flush()
|
|
602
|
+
os.fsync(stream.fileno())
|
|
603
|
+
os.replace(temporary, path)
|
|
604
|
+
finally:
|
|
605
|
+
if temporary.exists():
|
|
606
|
+
temporary.unlink()
|
|
607
|
+
|
|
608
|
+
|
|
609
|
+
def verify_file(path: Path, sha256: str) -> bool:
|
|
610
|
+
try:
|
|
611
|
+
return path.is_file() and sha256_file(path) == sha256
|
|
612
|
+
except OSError:
|
|
613
|
+
return False
|
|
614
|
+
|
|
615
|
+
|
|
616
|
+
def _free_path(path: Path) -> Path:
|
|
617
|
+
if not path.exists():
|
|
618
|
+
return path
|
|
619
|
+
for index in range(2, 1000):
|
|
620
|
+
candidate = path.with_name(f"{path.stem}-{index}{path.suffix}")
|
|
621
|
+
if not candidate.exists():
|
|
622
|
+
return candidate
|
|
623
|
+
raise InputValidationError(f"não foi possível reservar um caminho livre para {path.name}")
|
|
624
|
+
|
|
625
|
+
|
|
626
|
+
def archive_current(layout: SurveyLayout, *, response_id: Any, tipo: str, stable_path: Path,
|
|
627
|
+
sha256: str) -> Path | None:
|
|
628
|
+
"""Move o arquivo estável para a versão imutável correspondente."""
|
|
629
|
+
if not stable_path.exists():
|
|
630
|
+
return None
|
|
631
|
+
if not verify_file(stable_path, sha256):
|
|
632
|
+
raise InputValidationError(f"arquivo corrente não confere com o hash esperado: {stable_path.name}")
|
|
633
|
+
target = layout.version_path(response_id, tipo, sha256)
|
|
634
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
635
|
+
if target.exists():
|
|
636
|
+
if not verify_file(target, sha256):
|
|
637
|
+
raise InputValidationError(f"versão arquivada divergente: {target}")
|
|
638
|
+
stable_path.unlink()
|
|
639
|
+
return target
|
|
640
|
+
os.replace(stable_path, target)
|
|
641
|
+
return target
|
|
642
|
+
|
|
643
|
+
|
|
644
|
+
def install_stable(staging: Path, stable_path: Path) -> None:
|
|
645
|
+
"""Instala o staging no nome estável de forma atômica."""
|
|
646
|
+
stable_path.parent.mkdir(parents=True, exist_ok=True)
|
|
647
|
+
temporary = stable_path.with_name(f".{stable_path.name}.{uuid.uuid4().hex}.tmp")
|
|
648
|
+
try:
|
|
649
|
+
with staging.open("rb") as source, temporary.open("wb") as target:
|
|
650
|
+
shutil.copyfileobj(source, target, length=1024 * 1024)
|
|
651
|
+
target.flush()
|
|
652
|
+
os.fsync(target.fileno())
|
|
653
|
+
os.replace(temporary, stable_path)
|
|
654
|
+
finally:
|
|
655
|
+
if temporary.exists():
|
|
656
|
+
temporary.unlink()
|
|
657
|
+
|
|
658
|
+
|
|
659
|
+
def restore_current(layout: SurveyLayout, *, response_id: Any, tipo: str, sha256: str,
|
|
660
|
+
stable_path: Path) -> bool:
|
|
661
|
+
version = layout.version_path(response_id, tipo, sha256)
|
|
662
|
+
if not verify_file(version, sha256):
|
|
663
|
+
return False
|
|
664
|
+
install_stable(version, stable_path)
|
|
665
|
+
return True
|
|
666
|
+
|
|
667
|
+
|
|
668
|
+
def quarantine_current(layout: SurveyLayout, *, response_id: Any, tipo: str,
|
|
669
|
+
stable_path: Path) -> Path | None:
|
|
670
|
+
if not stable_path.exists():
|
|
671
|
+
return None
|
|
672
|
+
target = _free_path(layout.corrupt_path(response_id, tipo))
|
|
673
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
674
|
+
os.replace(stable_path, target)
|
|
675
|
+
return target
|
|
676
|
+
|
|
677
|
+
|
|
678
|
+
def relative_for(layout: SurveyLayout, path: Path) -> str:
|
|
679
|
+
return relative_path(layout.root, path)
|
|
680
|
+
|
|
681
|
+
|
|
682
|
+
def snapshot_manifest(layout: SurveyLayout) -> Path:
|
|
683
|
+
return layout.snapshot_dir / "manifesto.xlsx"
|
|
684
|
+
|
|
685
|
+
|
|
686
|
+
def snapshot_responses(layout: SurveyLayout) -> Path:
|
|
687
|
+
"""Planilha principal da coleta: valores como códigos das alternativas."""
|
|
688
|
+
return layout.snapshot_dir / "respostas.xlsx"
|
|
689
|
+
|
|
690
|
+
|
|
691
|
+
def consolidated_paths(layout: SurveyLayout, name: str) -> tuple[Path, Path]:
|
|
692
|
+
"""Cópias correntes (códigos e rótulos) na raiz do survey, sempre da coleta mais recente."""
|
|
693
|
+
base = str(name or "").strip()
|
|
694
|
+
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*", base) or base.lower().endswith(".xlsx"):
|
|
695
|
+
raise InputValidationError("nome_consolidado deve ser um nome-base simples, sem pasta nem extensão")
|
|
696
|
+
return layout.root / f"{base}.xlsx", layout.root / f"{base}-rotulos.xlsx"
|
|
697
|
+
|
|
698
|
+
|
|
699
|
+
def snapshot_responses_labels(layout: SurveyLayout) -> Path:
|
|
700
|
+
"""Planilha complementar, com o texto por extenso das alternativas."""
|
|
701
|
+
return layout.snapshot_dir / "respostas-rotulos.xlsx"
|
|
702
|
+
|
|
703
|
+
|
|
704
|
+
def execution_row(layout: SurveyLayout, *, responses_sha256: str, submitted: int,
|
|
705
|
+
counts: Mapping[str, int]) -> dict[str, Any]:
|
|
706
|
+
return {
|
|
707
|
+
"execution_id": layout.execution_id,
|
|
708
|
+
"coletado_em": layout.collected_at,
|
|
709
|
+
"survey_id": layout.survey_id,
|
|
710
|
+
"snapshot_dir": relative_for(layout, layout.snapshot_dir),
|
|
711
|
+
"respostas_sha256": responses_sha256,
|
|
712
|
+
"submetidas": int(submitted),
|
|
713
|
+
"reutilizados": int(counts.get(REUSE, 0)),
|
|
714
|
+
"revalidados": int(counts.get(REVALIDATED, 0)),
|
|
715
|
+
"baixados": int(counts.get(DOWNLOADED, 0)),
|
|
716
|
+
"atualizados": int(counts.get(UPDATED, 0)),
|
|
717
|
+
"sem_anexo": int(counts.get(NO_ATTACHMENT, 0)),
|
|
718
|
+
"erros": int(counts.get(ERROR, 0)),
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
|
|
722
|
+
@contextlib.contextmanager
|
|
723
|
+
def survey_lock(root: Path | str) -> Iterator[None]:
|
|
724
|
+
"""Impede duas coletas simultâneas na mesma pasta de survey."""
|
|
725
|
+
root_path = Path(root).expanduser().resolve()
|
|
726
|
+
lock_root = Path(tempfile.gettempdir()) / f"argos-survey-locks-{os.getuid() if hasattr(os, 'getuid') else 'user'}"
|
|
727
|
+
lock_root.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
728
|
+
lock_path = lock_root / f"{sha256_bytes(str(root_path).encode('utf-8'))}.lock"
|
|
729
|
+
stream = lock_path.open("a+b")
|
|
730
|
+
acquired = False
|
|
731
|
+
try:
|
|
732
|
+
try:
|
|
733
|
+
import fcntl
|
|
734
|
+
except ImportError: # pragma: no cover - Windows
|
|
735
|
+
import msvcrt
|
|
736
|
+
|
|
737
|
+
stream.seek(0, os.SEEK_END)
|
|
738
|
+
if stream.tell() == 0:
|
|
739
|
+
stream.write(b"\0")
|
|
740
|
+
stream.flush()
|
|
741
|
+
stream.seek(0)
|
|
742
|
+
try:
|
|
743
|
+
msvcrt.locking(stream.fileno(), msvcrt.LK_NBLCK, 1)
|
|
744
|
+
except OSError:
|
|
745
|
+
raise InputValidationError("outra coleta está em andamento nesta pasta de survey") from None
|
|
746
|
+
else:
|
|
747
|
+
try:
|
|
748
|
+
fcntl.flock(stream.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
749
|
+
except BlockingIOError:
|
|
750
|
+
raise InputValidationError("outra coleta está em andamento nesta pasta de survey") from None
|
|
751
|
+
acquired = True
|
|
752
|
+
yield
|
|
753
|
+
finally:
|
|
754
|
+
if acquired:
|
|
755
|
+
try:
|
|
756
|
+
try:
|
|
757
|
+
import fcntl
|
|
758
|
+
except ImportError: # pragma: no cover - Windows
|
|
759
|
+
import msvcrt
|
|
760
|
+
|
|
761
|
+
stream.seek(0)
|
|
762
|
+
msvcrt.locking(stream.fileno(), msvcrt.LK_UNLCK, 1)
|
|
763
|
+
else:
|
|
764
|
+
fcntl.flock(stream.fileno(), fcntl.LOCK_UN)
|
|
765
|
+
finally:
|
|
766
|
+
stream.close()
|
|
767
|
+
else:
|
|
768
|
+
stream.close()
|
|
769
|
+
|
|
770
|
+
|
|
771
|
+
def observation_row(*, layout: SurveyLayout, row: Mapping[str, Any], tipo: str, status: str,
|
|
772
|
+
path: Path | None, sha256: str = "", content: str = "", erro: str = "") -> dict[str, Any]:
|
|
773
|
+
return {
|
|
774
|
+
"execution_id": layout.execution_id,
|
|
775
|
+
"coletado_em": layout.collected_at,
|
|
776
|
+
"survey_id": layout.survey_id,
|
|
777
|
+
"response_id": str(row["id"]),
|
|
778
|
+
"auditado": str(row.get("auditado") or ""),
|
|
779
|
+
"tipo": tipo,
|
|
780
|
+
"status": status,
|
|
781
|
+
"caminho_relativo": relative_for(layout, path) if path is not None else "",
|
|
782
|
+
"sha256": sha256,
|
|
783
|
+
"content_fingerprint": content,
|
|
784
|
+
"source_fingerprint": str(row.get("source_fingerprint") or ""),
|
|
785
|
+
"erro": erro,
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
|
|
789
|
+
def version_row(*, layout: SurveyLayout, response_id: Any, tipo: str, sha256: str, path: Path) -> dict[str, Any]:
|
|
790
|
+
return {
|
|
791
|
+
"survey_id": layout.survey_id,
|
|
792
|
+
"response_id": str(response_id),
|
|
793
|
+
"tipo": tipo,
|
|
794
|
+
"sha256": sha256,
|
|
795
|
+
"caminho_relativo": relative_for(layout, path),
|
|
796
|
+
"arquivado_em": layout.collected_at,
|
|
797
|
+
"execution_id": layout.execution_id,
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
|
|
801
|
+
def current_key(survey_id: str, response_id: Any, tipo: str) -> tuple[str, str, str]:
|
|
802
|
+
return (str(survey_id), str(response_id), tipo)
|
|
803
|
+
|
|
804
|
+
|
|
805
|
+
def decide_attachment(*, current: Mapping[str, Any] | None, row: Mapping[str, Any], tipo: str,
|
|
806
|
+
stable_path: Path, layout: SurveyLayout, refresh: bool) -> str:
|
|
807
|
+
"""Decide entre reutilizar, restaurar, baixar ou registrar sem anexo."""
|
|
808
|
+
if tipo == "zip" and row.get("has_evidence") is False:
|
|
809
|
+
return NO_ATTACHMENT
|
|
810
|
+
if current is None:
|
|
811
|
+
return DOWNLOADED
|
|
812
|
+
if current.get("status") != CURRENT_STATUS_ATUAL:
|
|
813
|
+
return DOWNLOADED
|
|
814
|
+
if refresh:
|
|
815
|
+
return DOWNLOADED
|
|
816
|
+
if str(current.get("source_fingerprint") or "") != str(row.get("source_fingerprint") or ""):
|
|
817
|
+
return DOWNLOADED
|
|
818
|
+
sha = str(current.get("sha256") or "")
|
|
819
|
+
if sha and verify_file(stable_path, sha):
|
|
820
|
+
return REUSE
|
|
821
|
+
if sha and layout.version_path(row["id"], tipo, sha).is_file():
|
|
822
|
+
return "restaurar"
|
|
823
|
+
return DOWNLOADED
|
|
824
|
+
|
|
825
|
+
|
|
826
|
+
def current_path_for(layout: SurveyLayout, current: Mapping[str, Any] | None, row: Mapping[str, Any],
|
|
827
|
+
tipo: str) -> Path:
|
|
828
|
+
if current and current.get("caminho_relativo"):
|
|
829
|
+
resolved = resolve_relative(layout.root, current["caminho_relativo"], allow_empty=True)
|
|
830
|
+
if resolved is not None:
|
|
831
|
+
return resolved
|
|
832
|
+
return layout.stable_path(row.get("auditado"), row["id"], tipo)
|