Dokumentation aktualisiert auf quarkus und besser strukturiert
This commit is contained in:
166
agent-backend/docs/Architecture.md
Normal file
166
agent-backend/docs/Architecture.md
Normal file
@@ -0,0 +1,166 @@
|
||||
# Architektur — Dateieingang Service
|
||||
|
||||
## Überblick
|
||||
|
||||
Der Service empfängt einen HTTP-Trigger von der APEX Automation, verbindet sich mit einem
|
||||
SFTP-Server, lädt neue ZIP-Dateien herunter, entpackt sie und lädt den Inhalt in OCI Object
|
||||
Storage hoch. Anschließend wird der ORDS-Endpunkt `pck_auto_import.p_process_incoming_files`
|
||||
aufgerufen, der die DB-Verarbeitung anstößt. Das Scheduling bleibt bei APEX — der Service
|
||||
selbst hat keinen eigenen Scheduler.
|
||||
|
||||
## Datenfluss
|
||||
|
||||
```
|
||||
APEX Automation (stündlich)
|
||||
│
|
||||
▼ HTTP POST /api/process-incoming (Header: X-Api-Key)
|
||||
FileProcessingResource
|
||||
│ 202 Accepted (sofort)
|
||||
▼
|
||||
FileProcessingPipeline [ManagedExecutor — Hintergrund-Thread]
|
||||
│
|
||||
│ für jede *.zip auf dem SFTP-Server:
|
||||
│
|
||||
├─→ SftpService.listZipFiles() [SSHJ]
|
||||
├─→ SftpService.download() [SSHJ]
|
||||
│
|
||||
├─→ ZipExtractionService.extract() [Apache Commons Compress]
|
||||
│ └─ ProcessingContext mit List<FileEntry>
|
||||
│
|
||||
├─→ OciUploadService.upload() [OCI SDK]
|
||||
│ └─ Dateien in eingang/<zip-name>/ + Marker
|
||||
│
|
||||
├─→ SftpService.renameRemote() [SSHJ]
|
||||
│ └─ .processed (Erfolg) oder .error (Fehler)
|
||||
│
|
||||
├─→ OrdsNotificationService.notify() [MicroProfile REST Client]
|
||||
│ └─ POST pck_auto_import.p_process_incoming_files
|
||||
│
|
||||
└─→ Cleanup: lokale Dateien löschen [immer, im finally]
|
||||
│
|
||||
▼
|
||||
Oracle DB (pck_auto_import verarbeitet eingang/<zip-name>/)
|
||||
```
|
||||
|
||||
## Pipeline-Steps
|
||||
|
||||
| Step-Name | Klasse | Paket | Bibliothek |
|
||||
|---|---|---|---|
|
||||
| `api-trigger` | `FileProcessingResource` | `api` | Quarkus REST |
|
||||
| `sftp-list` | `SftpService` | `sftp` | SSHJ |
|
||||
| `sftp-download` | `SftpService` | `sftp` | SSHJ |
|
||||
| `zip-extract` | `ZipExtractionService` | `zip` | Apache Commons Compress |
|
||||
| `oci-upload` | `OciUploadService` | `oci` | OCI Java SDK |
|
||||
| `sftp-rename` | `SftpService` | `sftp` | SSHJ |
|
||||
| `ords-notify` | `OrdsNotificationService` | `ords` | MicroProfile REST Client |
|
||||
| `cleanup` | `FileProcessingPipeline` | `pipeline` | pure Java |
|
||||
|
||||
## Orchestrierung
|
||||
|
||||
`FileProcessingPipeline` ist der einzige Orchestrierer — kein Framework-Routing.
|
||||
Die Pipeline läuft in einem `ManagedExecutor`-Thread (Quarkus Context Propagation),
|
||||
damit MDC-Kontext und CDI-Scope im Hintergrund-Thread verfügbar bleiben.
|
||||
|
||||
```
|
||||
FileProcessingResource [REST-Thread]
|
||||
│ 202 sofort
|
||||
▼
|
||||
FileProcessingPipeline [ManagedExecutor-Thread]
|
||||
│ AtomicBoolean verhindert Doppelläufe
|
||||
│
|
||||
└─ processAll()
|
||||
└─ für jede ZIP: try { ... } finally { cleanup(); MDC.clear(); }
|
||||
```
|
||||
|
||||
Der `AtomicBoolean isRunning`-Guard stellt sicher, dass ein zweiter APEX-Trigger während
|
||||
eines laufenden Durchgangs mit `409 Conflict` abgewiesen wird, statt einen zweiten Lauf zu starten.
|
||||
|
||||
## Konfiguration (`application.properties`)
|
||||
|
||||
```properties
|
||||
# API-Absicherung
|
||||
galabau.api.key=${GALABAU_API_KEY}
|
||||
|
||||
# SFTP
|
||||
galabau.sftp.host=sftp.lieferant.de
|
||||
galabau.sftp.port=22
|
||||
galabau.sftp.username=sftp_user
|
||||
galabau.sftp.password=${GALABAU_SFTP_PASSWORD}
|
||||
galabau.sftp.host-key-fingerprint=SHA256:... # ssh-keyscan host | ssh-keygen -lf -
|
||||
galabau.sftp.remote-path=/outgoing
|
||||
galabau.sftp.local-work-dir=/tmp/sftp-work
|
||||
# galabau.sftp.private-key-path=/etc/secrets/sftp-key
|
||||
# galabau.sftp.private-key-passphrase=${SFTP_KEY_PASSPHRASE}
|
||||
|
||||
# OCI Object Storage
|
||||
galabau.oci.namespace=mycompany
|
||||
galabau.oci.region=eu-frankfurt-1
|
||||
galabau.oci.bucket=my-bucket
|
||||
galabau.oci.tenant-prefix=mandant_42/
|
||||
galabau.oci.incoming-prefix=eingang/
|
||||
galabau.oci.tenancy-id=${OCI_TENANCY_ID}
|
||||
galabau.oci.user-id=${OCI_USER_ID}
|
||||
galabau.oci.fingerprint=${OCI_FINGERPRINT}
|
||||
galabau.oci.private-key-path=${OCI_PRIVATE_KEY_PATH}
|
||||
|
||||
# ORDS
|
||||
galabau.ords.base-url=http://ords:8080
|
||||
galabau.ords.process-incoming-path=/ords/.../auto_import/process_incoming
|
||||
galabau.ords.api-key=${GALABAU_ORDS_API_KEY}
|
||||
quarkus.rest-client.ords-client.url=${galabau.ords.base-url}
|
||||
|
||||
# Retry
|
||||
galabau.retry.max-attempts=3
|
||||
galabau.retry.backoff-ms=1000
|
||||
```
|
||||
|
||||
## Fehlerbehandlung
|
||||
|
||||
| Fehler | Typ | Handling |
|
||||
|---|---|---|
|
||||
| SFTP-Verbindung fehlgeschlagen | transient | Pipeline bricht ab, nächster APEX-Lauf (1h) |
|
||||
| ZIP beschädigt | persistent | SFTP-Rename zu `.error`, Log, weiter mit nächster ZIP |
|
||||
| OCI 503 | transient | `@Retry` (3x mit Backoff) |
|
||||
| OCI 403 Auth Failed | persistent | SFTP-Rename zu `.error`, Log — Credentials prüfen! |
|
||||
| ORDS-Aufruf fehlgeschlagen | transient | Marker liegt vor, APEX findet ihn nächsten Lauf |
|
||||
|
||||
## OCI-Authentifizierung
|
||||
|
||||
`SimpleAuthenticationDetailsProvider` mit Credentials aus Umgebungsvariablen (skalare Werte)
|
||||
und gemounteter PEM-Datei (Private Key via Kubernetes Secret Volume).
|
||||
|
||||
```java
|
||||
SimpleAuthenticationDetailsProvider auth =
|
||||
SimpleAuthenticationDetailsProvider.builder()
|
||||
.tenantId(config.tenancyId())
|
||||
.userId(config.userId())
|
||||
.fingerprint(config.fingerprint())
|
||||
.region(Region.fromRegionId(config.region()))
|
||||
.privateKeySupplier(new FilePrivateKeySupplier(config.privateKeyPath()))
|
||||
.build();
|
||||
```
|
||||
|
||||
## Datenmodell
|
||||
|
||||
### `ProcessingContext`
|
||||
|
||||
| Feld | Typ | Beschreibung |
|
||||
|---|---|---|
|
||||
| `runId` | `UUID` | Eindeutige ID dieses Verarbeitungslaufs (MDC-Kontext) |
|
||||
| `zipFilename` | `String` | z.B. `export_2026-04-08.zip` |
|
||||
| `zipNameWithoutExt` | `String` | z.B. `export_2026-04-08` |
|
||||
| `localZipPath` | `Path` | Lokale ZIP-Datei (für Cleanup) |
|
||||
| `localExtractDir` | `Path` | Lokales Entpack-Verzeichnis (für Cleanup) |
|
||||
| `extractedFiles` | `List<FileEntry>` | Liste der entpackten Dateien |
|
||||
| `markerUploaded` | `boolean` | Marker in OCI hochgeladen? |
|
||||
| `startTime` | `LocalDateTime` | Startzeitpunkt |
|
||||
| `status` | `ProcessingStatus` | `PENDING / PARTIALLY_UPLOADED / MARKER_UPLOADED / ORDS_NOTIFIED / FAILED` |
|
||||
|
||||
### `FileEntry`
|
||||
|
||||
| Feld | Typ | Beschreibung |
|
||||
|---|---|---|
|
||||
| `relativePath` | `String` | z.B. `subdir/file.csv` |
|
||||
| `ociKey` | `String` | z.B. `eingang/export_2026-04-08/subdir/file.csv` |
|
||||
| `fileSize` | `long` | Dateigröße in Bytes |
|
||||
| `isMarker` | `boolean` | `true` nur für `_READY_FOR_DB_PROCESSING_` |
|
||||
126
agent-backend/docs/Logging.md
Normal file
126
agent-backend/docs/Logging.md
Normal file
@@ -0,0 +1,126 @@
|
||||
# Logging — Dateieingang Service
|
||||
|
||||
## Stack
|
||||
|
||||
### Entwicklung (Dev Services)
|
||||
|
||||
Quarkus startet den gesamten Observability-Stack automatisch über Dev Services.
|
||||
|
||||
**Maven-Profil** (`pom.xml`):
|
||||
```xml
|
||||
<profile>
|
||||
<id>grafana</id>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>io.quarkus</groupId>
|
||||
<artifactId>quarkus-observability-devservices-lgtm</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</profile>
|
||||
```
|
||||
|
||||
Mit `./mvnw quarkus:dev -Pgrafana` startet automatisch:
|
||||
- **Loki** — Log-Aggregation
|
||||
- **Grafana** — Visualisierung / Dashboards (http://localhost:3000, admin/admin)
|
||||
- **Tempo** — Distributed Tracing (optional nutzbar)
|
||||
- **Mimir** — Metriken (optional nutzbar)
|
||||
|
||||
**Laufzeit-Dependency** (immer aktiv):
|
||||
```xml
|
||||
<dependency>
|
||||
<groupId>io.quarkus</groupId>
|
||||
<artifactId>quarkus-opentelemetry</artifactId>
|
||||
</dependency>
|
||||
```
|
||||
|
||||
Quarkus schickt Logs via **OTLP** direkt an den LGTM-Stack — kein Promtail, kein Log-File-Scraping.
|
||||
|
||||
### Produktion
|
||||
|
||||
Einen OTLP-fähigen Collector vor dem produktiven Loki/Grafana-Stack betreiben:
|
||||
- **Grafana Alloy** (Nachfolger von Promtail, OTLP-nativ)
|
||||
- **OpenTelemetry Collector**
|
||||
|
||||
Quarkus-Konfiguration bleibt identisch — nur der OTLP-Endpoint-URL ändert sich.
|
||||
|
||||
---
|
||||
|
||||
## Log-Hierarchie (MDC-Felder)
|
||||
|
||||
Ein ZIP-Verarbeitungslauf erzeugt Logs auf zwei Ebenen:
|
||||
|
||||
```
|
||||
runId → ein ZIP-Verarbeitungslauf (gesetzt am Anfang jeder ZIP)
|
||||
step → aktueller Pipeline-Step (gesetzt zu Beginn jedes Steps)
|
||||
```
|
||||
|
||||
`zipFilename` wird zusätzlich als menschenlesbarer Kontext geloggt, ist aber kein MDC-Feld
|
||||
(kein Filter-Kriterium, da runId eindeutiger ist).
|
||||
|
||||
### MDC-Felder im Detail
|
||||
|
||||
| Feld | Typ | Beispielwert | Gesetzt in | Gelöscht in |
|
||||
|---|---|---|---|---|
|
||||
| `runId` | UUID | `a1b2c3d4-...` | Beginn ZIP-Verarbeitung | `finally` nach ZIP |
|
||||
| `step` | String | `oci-upload` | Beginn jedes Pipeline-Steps | Ende jedes Steps |
|
||||
|
||||
`MDC.clear()` wird **immer im `finally`-Block** nach jeder ZIP aufgerufen —
|
||||
kein Kontext sickert in die nächste ZIP.
|
||||
|
||||
### Filtermöglichkeiten in Grafana (LogQL)
|
||||
|
||||
```logql
|
||||
# Alle Logs eines Verarbeitungslaufs
|
||||
{service="dateieingang"} | json | runId="a1b2c3d4"
|
||||
|
||||
# Alle Logs eines Pipeline-Steps über alle Läufe
|
||||
{service="dateieingang"} | json | step="oci-upload"
|
||||
|
||||
# Nur Fehler
|
||||
{service="dateieingang"} | json | level="ERROR"
|
||||
|
||||
# Fehler in einem bestimmten Lauf
|
||||
{service="dateieingang"} | json | runId="a1b2c3d4" | level="ERROR"
|
||||
```
|
||||
|
||||
**Loki-Labels** (wenige, statische Werte — keine hohe Kardinalität):
|
||||
- `service` = `dateieingang`
|
||||
- `level` = `INFO` / `WARN` / `ERROR`
|
||||
- `environment` = `dev` / `prod`
|
||||
|
||||
Alle anderen Felder (`runId`, `step`) werden per `| json` im Query-Body gefiltert, nicht als Label.
|
||||
|
||||
---
|
||||
|
||||
## Log-Events pro Step
|
||||
|
||||
| Step | Level | Event / Inhalt |
|
||||
|---|---|---|
|
||||
| `api-trigger` | INFO | "Processing triggered by APEX, starting async pipeline" |
|
||||
| `api-trigger` | WARN | "Pipeline already running, rejecting trigger (409)" |
|
||||
| `sftp-list` | INFO | "`N` new ZIP files found on SFTP" |
|
||||
| `sftp-list` | INFO | "No new ZIP files found on SFTP" |
|
||||
| `sftp-download` | INFO | "ZIP `<filename>` downloaded (`X` bytes)" |
|
||||
| `zip-extract` | INFO | "ZIP `<filename>` extracted: `N` files, `M` directories" |
|
||||
| `zip-extract` | ERROR | "ZIP `<filename>` is corrupt or unreadable" |
|
||||
| `oci-upload` | INFO | "Uploaded `N` files + marker to OCI in `X`ms" |
|
||||
| `oci-upload` | WARN | "OCI upload attempt `N`/3 failed (503), retrying..." |
|
||||
| `oci-upload` | ERROR | "OCI upload permanently failed (403) — check credentials" |
|
||||
| `sftp-rename` | INFO | "SFTP rename: `<file>` → `<file>.processed`" |
|
||||
| `sftp-rename` | INFO | "SFTP rename: `<file>` → `<file>.error`" |
|
||||
| `ords-notify` | INFO | "ORDS endpoint called, HTTP 200" |
|
||||
| `ords-notify` | WARN | "ORDS call failed (attempt `N`/3), retrying..." |
|
||||
| `ords-notify` | WARN | "ORDS notification failed — marker is present, APEX will pick up next run" |
|
||||
| `cleanup` | DEBUG | "Local files deleted: `<path>`" |
|
||||
| Alle | ERROR | Fehler mit vollem MDC-Kontext, Exception-Message (nie Passwörter/Keys loggen) |
|
||||
|
||||
---
|
||||
|
||||
## Fehlerverhalten (Logging-Perspektive)
|
||||
|
||||
- Fehler werden **immer vor** dem Rename zu `.error` geloggt — damit der Log-Eintrag
|
||||
auch dann vorhanden ist, wenn das Rename selbst fehlschlägt
|
||||
- Der `runId`-Kontext bleibt für den gesamten ZIP-Verarbeitungslauf erhalten —
|
||||
alle Logs einer ZIP sind in Grafana über `runId` filterbar
|
||||
- Retry-Verhalten: siehe `Architecture.md` — Abschnitt Fehlerbehandlung
|
||||
595
agent-backend/docs/Plan.md
Normal file
595
agent-backend/docs/Plan.md
Normal file
@@ -0,0 +1,595 @@
|
||||
# Plan: n8n Workflow → Quarkus Backend ersetzen
|
||||
|
||||
**Stand:** 2026-04-08
|
||||
**Basis:** Avise-Tool Quarkus Backend (agent-backend/) — angepasst für SFTP → OCI Object Storage → DB-Workflow
|
||||
|
||||
---
|
||||
|
||||
## Ziel
|
||||
|
||||
Ersetze den n8n-Workflow (derzeit: SFTP-Poll → ZIP-Entpacken → OCI-Upload → ORDS-Trigger) durch einen nativen Quarkus-Backend-Service.
|
||||
|
||||
**Vorteil:**
|
||||
- Keine externe Workflow-Engine-Abhängigkeit (n8n)
|
||||
- Single-Responsibility: Ein Service für eine Aufgabe (Dateieingang)
|
||||
- Bessere Observability (OTLP → Loki/Grafana)
|
||||
- Volle Kontrolle über Fehlerbehandlung und Retry-Logik
|
||||
- Einfacheres Deployment (JAR statt n8n-Instanz)
|
||||
|
||||
---
|
||||
|
||||
## Architektur-Überblick
|
||||
|
||||
Das Scheduling übernimmt weiterhin die APEX Automation (stündlich). Sie ruft den Quarkus-Service
|
||||
per HTTP POST auf — wie bisher den n8n-Webhook. Der Service selbst hat keinen eigenen Scheduler.
|
||||
|
||||
```
|
||||
APEX Automation (stündlich)
|
||||
│
|
||||
▼ HTTP POST /api/process-incoming (Header: X-Api-Key)
|
||||
FileProcessingResource [Quarkus REST Endpoint]
|
||||
│ gibt sofort 202 Accepted zurück (async, fire & forget)
|
||||
▼
|
||||
FileProcessingPipeline [Hintergrund-Thread — für jede neue ZIP]
|
||||
│
|
||||
├─→ SftpService [SSHJ — list, download, rename]
|
||||
│
|
||||
├─→ ZipExtractionService [Apache Commons Compress]
|
||||
│
|
||||
├─→ OciUploadService [OCI SDK — Instance Principal Auth]
|
||||
│
|
||||
└─→ OrdsNotificationService [MicroProfile REST Client]
|
||||
│
|
||||
▼
|
||||
Oracle DB (eingang/, zielordner)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Projektstruktur (Maven)
|
||||
|
||||
```
|
||||
backend-n8n-replacement/
|
||||
├── pom.xml (Java 25, Quarkus 3.x LTS)
|
||||
│
|
||||
├── src/main/java/de/galabau/
|
||||
│ │
|
||||
│ ├── api/
|
||||
│ │ └── FileProcessingResource.java (@Path("/api/process-incoming"), @POST, API-Key-Check)
|
||||
│ │
|
||||
│ ├── sftp/
|
||||
│ │ ├── SftpConfig.java (@ConfigMapping)
|
||||
│ │ └── SftpService.java (SSHJ — list, download, rename)
|
||||
│ │
|
||||
│ ├── zip/
|
||||
│ │ └── ZipExtractionService.java (Apache Commons Compress)
|
||||
│ │
|
||||
│ ├── oci/
|
||||
│ │ ├── OciConfig.java
|
||||
│ │ └── OciUploadService.java (OCI SDK, Instance Principal, Marker-Handling)
|
||||
│ │
|
||||
│ ├── ords/
|
||||
│ │ ├── OrdsClient.java (MicroProfile REST Client)
|
||||
│ │ └── OrdsNotificationService.java (Retry via @Retry annotation)
|
||||
│ │
|
||||
│ ├── pipeline/
|
||||
│ │ └── FileProcessingPipeline.java (Extract → Upload → Notify → Cleanup)
|
||||
│ │
|
||||
│ ├── model/
|
||||
│ │ ├── ProcessingContext.java (runId, Dateien, Status)
|
||||
│ │ └── OrdsRequest.java (DTO)
|
||||
│ │
|
||||
│ ├── config/
|
||||
│ │ └── ApplicationConfig.java (zentrale @ConfigMapping)
|
||||
│ │
|
||||
│ └── exception/
|
||||
│ ├── SftpException.java
|
||||
│ ├── ZipException.java
|
||||
│ ├── OciException.java
|
||||
│ └── OrdsException.java
|
||||
│
|
||||
├── src/main/resources/
|
||||
│ ├── application.properties
|
||||
│ └── application-dev.properties
|
||||
│
|
||||
└── docs/
|
||||
├── SETUP.md
|
||||
├── Architecture.md
|
||||
├── Configuration.md
|
||||
└── ErrorHandling.md
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Pipeline-Steps
|
||||
|
||||
| Step | Komponente | Bibliothek | Beschreibung |
|
||||
|---|---|---|---|
|
||||
| `api-trigger` | `FileProcessingResource` | Quarkus REST | Empfängt POST von APEX Automation, prüft API-Key, startet Pipeline async |
|
||||
| `sftp-list` | `SftpService` | SSHJ | Listet `*.zip`-Dateien im Remote-Verzeichnis |
|
||||
| `sftp-download` | `SftpService` | SSHJ | Lädt ZIP in lokales Arbeitsverzeichnis |
|
||||
| `zip-extract` | `ZipExtractionService` | Apache Commons Compress | Entpackt ZIP, preserviert Ordnerstruktur |
|
||||
| `oci-upload` | `OciUploadService` | OCI SDK | Lädt Dateien + Marker zu OCI Object Storage |
|
||||
| `sftp-rename` | `SftpService` | SSHJ | Remote-Rename zu `.processed` oder `.error` |
|
||||
| `ords-notify` | `OrdsNotificationService` | MicroProfile REST Client | Ruft ORDS-Endpunkt auf |
|
||||
| `cleanup` | `FileProcessingPipeline` | pure Java | Löscht lokale Arbeitsdateien (ZIP + entpackte Dateien) |
|
||||
|
||||
---
|
||||
|
||||
## Konfiguration (`application.properties`)
|
||||
|
||||
```properties
|
||||
# API-Absicherung
|
||||
galabau.api.key=${GALABAU_API_KEY}
|
||||
|
||||
# SFTP
|
||||
galabau.sftp.host=sftp.lieferant.de
|
||||
galabau.sftp.port=22
|
||||
galabau.sftp.username=sftp_user
|
||||
galabau.sftp.password=${GALABAU_SFTP_PASSWORD}
|
||||
galabau.sftp.host-key-fingerprint=SHA256:AbCdEfGh... # ssh-keyscan host | ssh-keygen -lf -
|
||||
galabau.sftp.remote-path=/outgoing
|
||||
galabau.sftp.local-work-dir=/tmp/sftp-work
|
||||
|
||||
# Alternative: Public-Key-Auth (empfohlen für Produktion)
|
||||
# galabau.sftp.private-key-path=/etc/secrets/sftp-key
|
||||
# galabau.sftp.private-key-passphrase=${SFTP_KEY_PASSPHRASE}
|
||||
|
||||
# OCI Object Storage — Auth via Credentials (Key als gemountetes Kubernetes Secret)
|
||||
galabau.oci.namespace=mycompany
|
||||
galabau.oci.region=eu-frankfurt-1
|
||||
galabau.oci.bucket=my-bucket
|
||||
galabau.oci.tenant-prefix=mandant_42/
|
||||
galabau.oci.incoming-prefix=eingang/
|
||||
# Scalar Credentials aus Env-Vars:
|
||||
galabau.oci.tenancy-id=${OCI_TENANCY_ID}
|
||||
galabau.oci.user-id=${OCI_USER_ID}
|
||||
galabau.oci.fingerprint=${OCI_FINGERPRINT}
|
||||
# Private Key als gemountetes Kubernetes Secret (Dateipfad, kein Env-Var-String):
|
||||
galabau.oci.private-key-path=${OCI_PRIVATE_KEY_PATH} # z.B. /etc/oci/private-key.pem
|
||||
|
||||
# ORDS
|
||||
galabau.ords.base-url=http://ords:8080
|
||||
galabau.ords.process-incoming-path=/ords/.../net_storage/process_incoming
|
||||
galabau.ords.api-key=${GALABAU_ORDS_API_KEY}
|
||||
|
||||
# Fehlerbehandlung
|
||||
galabau.retry.max-attempts=3
|
||||
galabau.retry.backoff-ms=1000
|
||||
```
|
||||
|
||||
**Credential-Strategie:**
|
||||
- Alle Passwörter und API-Keys über `${ENV_VAR_NAME}` — Quarkus liest Umgebungsvariablen nativ
|
||||
- OCI-Auth via **Instance Principal** — kein Key-Management, keine Rotation (empfohlen auf OKE)
|
||||
- Deployment: Kubernetes Secrets → Environment Injection für Passwörter/API-Keys
|
||||
|
||||
---
|
||||
|
||||
## REST Endpoint
|
||||
|
||||
```java
|
||||
@Path("/api/process-incoming")
|
||||
@ApplicationScoped
|
||||
public class FileProcessingResource {
|
||||
|
||||
@Inject
|
||||
ApplicationConfig config;
|
||||
|
||||
@Inject
|
||||
FileProcessingPipeline pipeline;
|
||||
|
||||
@POST
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public Response triggerProcessing(@HeaderParam("X-Api-Key") String apiKey) {
|
||||
if (!config.api().key().equals(apiKey)) {
|
||||
return Response.status(Response.Status.UNAUTHORIZED).build();
|
||||
}
|
||||
// Async: Pipeline im Hintergrund, APEX bekommt sofort 202
|
||||
pipeline.processAllAsync();
|
||||
return Response.accepted().build();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Aufruf durch APEX Automation:**
|
||||
```sql
|
||||
apex_web_service.make_rest_request(
|
||||
p_url => 'http://backend:8080/api/process-incoming',
|
||||
p_http_method => 'POST',
|
||||
p_http_headers => apex_util.string_to_table('X-Api-Key:' || <secret>)
|
||||
);
|
||||
```
|
||||
|
||||
**Concurrency Guard:** `FileProcessingPipeline` hält ein `AtomicBoolean isRunning`-Flag.
|
||||
Kommt ein zweiter Trigger während eine Pipeline läuft → 409 Conflict zurückgeben, kein doppelter Lauf.
|
||||
|
||||
---
|
||||
|
||||
## Async-Verhalten
|
||||
|
||||
```java
|
||||
@ApplicationScoped
|
||||
public class FileProcessingPipeline {
|
||||
|
||||
private final AtomicBoolean isRunning = new AtomicBoolean(false);
|
||||
|
||||
@Inject
|
||||
ManagedExecutor executor; // Quarkus Managed Executor
|
||||
|
||||
public Response processAllAsync() {
|
||||
if (!isRunning.compareAndSet(false, true)) {
|
||||
return Response.status(409).entity("Pipeline already running").build();
|
||||
}
|
||||
executor.submit(() -> {
|
||||
try {
|
||||
processAll();
|
||||
} finally {
|
||||
isRunning.set(false);
|
||||
}
|
||||
});
|
||||
return Response.accepted().build();
|
||||
}
|
||||
|
||||
void processAll() { ... } // eigentliche Logik
|
||||
}
|
||||
```
|
||||
|
||||
Fehler im Hintergrund-Thread landen im Log (OTLP → Grafana) — APEX bekommt sie
|
||||
nicht als HTTP-Fehler, da die Antwort bereits weg ist. Das entspricht dem bisherigen
|
||||
n8n fire-and-forget-Verhalten.
|
||||
|
||||
---
|
||||
|
||||
## Fehlerbehandlung & Retry
|
||||
|
||||
### Fehlerklassen
|
||||
|
||||
| Fehler | Typ | Retry | Verhalten |
|
||||
|---|---|---|---|
|
||||
| SFTP-Verbindung fehlgeschlagen | transient | nein | Nächster APEX-Lauf (1h) versucht es |
|
||||
| ZIP beschädigt | persistent | nein | ZIP auf SFTP umbenennen zu `.error`, Log |
|
||||
| OCI-Verbindung fehlgeschlagen (z.B. 503) | transient | ja (exponential backoff) | @Retry |
|
||||
| OCI-Upload einer Datei schlägt fehl | persistent | nein | Bereits hochgeladene löschen, ZIP belassen, Log |
|
||||
| ORDS-Aufruf schlägt fehl | transient | ja (2-3x) | Marker liegt vor → APEX Automation schlägt beim nächsten Lauf ein |
|
||||
| Allgemein technischer Fehler | fallabhängig | siehe SmallRye Fault Tolerance | Exception-Log |
|
||||
|
||||
### Retry-Strategie (SmallRye Fault Tolerance)
|
||||
|
||||
```java
|
||||
@Retry(maxRetries = 3, delay = 1000, delayUnit = ChronoUnit.MILLIS)
|
||||
@Timeout(value = 10, unit = ChronoUnit.SECONDS)
|
||||
public void notifyOrds(ProcessingContext context) { ... }
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Datenmodelle
|
||||
|
||||
### `ProcessingContext`
|
||||
|
||||
```java
|
||||
public class ProcessingContext {
|
||||
public UUID runId; // eindeutige Lauf-ID
|
||||
public String zipFilename; // z.B. "export_2026-04-08.zip"
|
||||
public String zipNameWithoutExt; // z.B. "export_2026-04-08"
|
||||
public Path localZipPath; // lokale ZIP-Datei (für Cleanup)
|
||||
public Path localExtractDir; // lokales Entpack-Verzeichnis (für Cleanup)
|
||||
public List<FileEntry> extractedFiles; // Verzeichnis + Datei-Namen
|
||||
public boolean markerUploaded;
|
||||
public LocalDateTime startTime;
|
||||
public ProcessingStatus status;
|
||||
}
|
||||
|
||||
public enum ProcessingStatus {
|
||||
PENDING, PARTIALLY_UPLOADED, MARKER_UPLOADED, ORDS_NOTIFIED, FAILED
|
||||
}
|
||||
```
|
||||
|
||||
### `FileEntry`
|
||||
|
||||
```java
|
||||
public class FileEntry {
|
||||
public String relativePath; // "subdir/file.csv"
|
||||
public String ociKey; // "eingang/export_2026-04-08/subdir/file.csv"
|
||||
public long fileSize;
|
||||
public boolean isMarker; // true nur für "_READY_FOR_DB_PROCESSING_"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## SFTP-Verarbeitung mit SSHJ
|
||||
|
||||
Siehe `plan_camel_integration.md` für Details zur SSHJ-Integration (Host-Key-Verification,
|
||||
Credentials, Fehlerbehandlung).
|
||||
|
||||
### Verarbeitungslogik
|
||||
|
||||
```
|
||||
Pipeline.processAll():
|
||||
1. SftpService.listZipFiles() → ["export_2026-04-08.zip", ...]
|
||||
2. für jede ZIP:
|
||||
a. SftpService.download(zip) → lokale Datei
|
||||
b. ZipExtractionService.extract() → ProcessingContext mit FileEntry-Liste
|
||||
c. OciUploadService.upload() → Dateien + Marker in OCI
|
||||
d. SftpService.renameRemote(.processed oder .error)
|
||||
e. OrdsNotificationService.notify()
|
||||
f. cleanup: lokale ZIP + Entpack-Verzeichnis löschen ← immer, auch bei Fehler
|
||||
```
|
||||
|
||||
**Cleanup (Schritt f) läuft immer** — in einem `finally`-Block — damit kein Disk-Vollaufen
|
||||
bei Fehlern oder großen ZIPs.
|
||||
|
||||
---
|
||||
|
||||
## OCI-Authentifizierung (SimpleAuthenticationDetailsProvider)
|
||||
|
||||
Credentials kommen aus Umgebungsvariablen (skalare Werte) und einem gemounteten
|
||||
Kubernetes Secret (Private Key als PEM-Datei).
|
||||
|
||||
```java
|
||||
@ApplicationScoped
|
||||
public class OciUploadService {
|
||||
|
||||
private final ObjectStorage client;
|
||||
|
||||
@Inject
|
||||
OciConfig config;
|
||||
|
||||
@PostConstruct
|
||||
void init() {
|
||||
SimpleAuthenticationDetailsProvider auth =
|
||||
SimpleAuthenticationDetailsProvider.builder()
|
||||
.tenantId(config.tenancyId())
|
||||
.userId(config.userId())
|
||||
.fingerprint(config.fingerprint())
|
||||
.region(Region.fromRegionId(config.region()))
|
||||
.privateKeySupplier(new FilePrivateKeySupplier(config.privateKeyPath()))
|
||||
.build();
|
||||
|
||||
this.client = ObjectStorageClient.builder().build(auth);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Kubernetes Deployment:**
|
||||
- Skalare Werte (`tenancyId`, `userId`, `fingerprint`) → Kubernetes Secret → Env-Vars
|
||||
- Private Key PEM-Datei → Kubernetes Secret → Volume Mount unter `/etc/oci/private-key.pem`
|
||||
- `OCI_PRIVATE_KEY_PATH=/etc/oci/private-key.pem` als Env-Var
|
||||
|
||||
---
|
||||
|
||||
## ORDS-Integration
|
||||
|
||||
### REST-Client
|
||||
|
||||
```java
|
||||
@RegisterRestClient(configKey = "ords-client")
|
||||
public interface OrdsClient {
|
||||
|
||||
@POST
|
||||
@Path("${galabau.ords.process-incoming-path}")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
Response processIncoming(ProcessIncomingRequest request);
|
||||
}
|
||||
|
||||
// application.properties:
|
||||
// quarkus.rest-client.ords-client.url=${galabau.ords.base-url}
|
||||
|
||||
public class ProcessIncomingRequest {
|
||||
public String zipName; // "export_2026-04-08"
|
||||
public String runId; // für Logging-Korrelation
|
||||
public LocalDateTime uploadedAt;
|
||||
}
|
||||
```
|
||||
|
||||
### Fehlerbehandlung
|
||||
|
||||
- Schlägt der ORDS-Aufruf fehl → Marker liegt trotzdem vor
|
||||
- APEX Automation findet beim nächsten Stundenlauf den Marker und verarbeitet
|
||||
- **Keine** Versuche, den Fehler lokal zu beheben
|
||||
|
||||
---
|
||||
|
||||
## Abhängigkeiten (pom.xml)
|
||||
|
||||
```xml
|
||||
<properties>
|
||||
<java.version>25</java.version>
|
||||
<quarkus.platform.version><!-- aktuelle LTS auf code.quarkus.io prüfen --></quarkus.platform.version>
|
||||
</properties>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>io.quarkus.platform</groupId>
|
||||
<artifactId>quarkus-bom</artifactId>
|
||||
<version>${quarkus.platform.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<dependencies>
|
||||
<!-- Quarkus Core -->
|
||||
<dependency>
|
||||
<groupId>io.quarkus</groupId>
|
||||
<artifactId>quarkus-arc</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- REST Endpoint (eingehend von APEX) -->
|
||||
<dependency>
|
||||
<groupId>io.quarkus</groupId>
|
||||
<artifactId>quarkus-rest</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- REST Client (ausgehend zu ORDS) -->
|
||||
<dependency>
|
||||
<groupId>io.quarkus</groupId>
|
||||
<artifactId>quarkus-rest-client-jackson</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Managed Executor (für Async-Pipeline) -->
|
||||
<dependency>
|
||||
<groupId>io.quarkus</groupId>
|
||||
<artifactId>quarkus-smallrye-context-propagation</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- SFTP: SSHJ — moderner Java SFTP/SSH Client -->
|
||||
<!-- Aktuelle Version prüfen: https://mvnrepository.com/artifact/com.hierynomus/sshj -->
|
||||
<dependency>
|
||||
<groupId>com.hierynomus</groupId>
|
||||
<artifactId>sshj</artifactId>
|
||||
<version>0.38.0</version>
|
||||
</dependency>
|
||||
|
||||
<!-- OCI Object Storage SDK -->
|
||||
<!-- Aktuelle Version prüfen: https://mvnrepository.com/artifact/com.oracle.oci.sdk/oci-java-sdk-objectstorage -->
|
||||
<dependency>
|
||||
<groupId>com.oracle.oci.sdk</groupId>
|
||||
<artifactId>oci-java-sdk-objectstorage</artifactId>
|
||||
<version>3.44.0</version>
|
||||
</dependency>
|
||||
|
||||
<!-- ZIP -->
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-compress</artifactId>
|
||||
<version>1.26.1</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Observability -->
|
||||
<dependency>
|
||||
<groupId>io.quarkus</groupId>
|
||||
<artifactId>quarkus-opentelemetry</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Fault Tolerance -->
|
||||
<dependency>
|
||||
<groupId>io.quarkus</groupId>
|
||||
<artifactId>quarkus-smallrye-fault-tolerance</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Tests -->
|
||||
<dependency>
|
||||
<groupId>io.quarkus</groupId>
|
||||
<artifactId>quarkus-junit5</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
```
|
||||
|
||||
**Hinweis:** `oci-java-sdk-objectstorage` und `sshj` liegen nicht im Quarkus BOM —
|
||||
Versionen beim Projektstart auf Maven Central prüfen. Quarkus-eigene Artefakte (`quarkus-*`)
|
||||
brauchen keine `<version>`, da das BOM sie bereitstellt.
|
||||
|
||||
---
|
||||
|
||||
## Observability & Logging
|
||||
|
||||
### MDC-Hierarchie
|
||||
|
||||
```
|
||||
runId → ein ZIP-Verarbeitungslauf (gesetzt am Anfang jeder ZIP)
|
||||
step → aktueller Pipeline-Step
|
||||
fileIdx → welche Datei in diesem Schritt (optional)
|
||||
```
|
||||
|
||||
MDC nach jeder ZIP mit `MDC.clear()` leeren — damit kein Kontext in die nächste ZIP sickert.
|
||||
|
||||
### Log-Level
|
||||
|
||||
| Schritt | Level | Beispiel |
|
||||
|---|---|---|
|
||||
| `api-trigger` | INFO | "Processing triggered by APEX, starting async pipeline" |
|
||||
| `sftp-list` | INFO | "5 new ZIP files found on SFTP" |
|
||||
| `zip-extract` | INFO | "ZIP 'export_2026-04-08.zip' extracted: 12 files, 5 directories" |
|
||||
| `oci-upload` | INFO | "Uploaded 12 files + marker to OCI in 3.2s" |
|
||||
| `ords-notify` | INFO | "ORDS endpoint called, HTTP 200" |
|
||||
| `cleanup` | DEBUG | "Local files deleted: /tmp/sftp-work/export_2026-04-08.zip" |
|
||||
| Fehler | ERROR | Mit vollem MDC-Context und Exception |
|
||||
|
||||
**Stack:** OTLP → Loki/Grafana (Entwicklung: Dev Services, Produktion: externer Collector)
|
||||
|
||||
---
|
||||
|
||||
## Migrations-Schritte
|
||||
|
||||
1. **Phase 1: Entwicklung**
|
||||
- Projekt-Setup (Java 25, Quarkus 3.x, SSHJ)
|
||||
- REST Endpoint (`FileProcessingResource`) mit API-Key-Auth + Concurrency Guard
|
||||
- SFTP-Operationen (SSHJ: list, download, rename) mit Fingerprint-Verification
|
||||
- ZIP-Entpacken (Apache Commons Compress)
|
||||
- OCI-Upload (OCI SDK, Instance Principal, Marker-Handling)
|
||||
- ORDS-Benachrichtigung (REST Client + Retry)
|
||||
- Lokaler Cleanup (always in finally)
|
||||
- Fehlerbehandlung + OTLP-Logging
|
||||
- Package `pck_auto_import` mit `p_process_incoming_files` auf DB-Seite implementieren
|
||||
- Unit-Tests + Integration-Tests
|
||||
|
||||
2. **Phase 2: Testing & Deployment**
|
||||
- E2E-Tests mit echtem SFTP / OCI / ORDS
|
||||
- Parallel-Run: n8n und Quarkus-Backend gleichzeitig aktiv
|
||||
- **APEX Automation aktualisieren:** URL von n8n-Webhook auf `http://backend:8080/api/process-incoming` ändern, `X-Api-Key`-Header ergänzen
|
||||
- Grafana Dashboards + Alerts aufsetzen
|
||||
|
||||
3. **Phase 3: Cutover**
|
||||
- n8n deaktivieren / entfernen
|
||||
- Monitoring etablieren
|
||||
|
||||
---
|
||||
|
||||
## Deployment-Constraints
|
||||
|
||||
- **Einzelinstanz:** Der Service läuft als Einzelinstanz. Kein Clustering.
|
||||
Mehrere Instanzen würden dieselben SFTP-Dateien gleichzeitig verarbeiten.
|
||||
Der `AtomicBoolean`-Guard schützt nur innerhalb einer Instanz.
|
||||
Solange APEX Automation den Webhook nur einmal pro Lauf aufruft, kein Problem.
|
||||
|
||||
- **Idempotenz:** OCI PUT ist idempotent. Bei abgebrochenem Lauf ohne Marker:
|
||||
nächster Trigger lädt ZIP erneut, Dateien werden überschrieben — kein korrupter Zustand.
|
||||
|
||||
- **Disk-Space:** Lokales Arbeitsverzeichnis `/tmp/sftp-work` — Cleanup läuft immer im finally.
|
||||
Maximale gleichzeitige Belegung: eine ZIP + entpackte Dateien (sequenzielle Verarbeitung).
|
||||
Capacity Planning erforderlich (→ offene Frage).
|
||||
|
||||
---
|
||||
|
||||
## Vorteile gegenüber n8n
|
||||
|
||||
| Aspekt | n8n | Quarkus Backend |
|
||||
|---|---|---|
|
||||
| **Abhängigkeiten** | Externe SaaS/self-hosted | Ein JAR |
|
||||
| **Fehlerbehandlung** | UI-basiert konfigurieren | Java Code, testbar |
|
||||
| **Observability** | n8n-Logs + externe Integrationen | OTLP → Loki/Grafana nativ |
|
||||
| **Sicherheit** | Credentials in n8n-DB | Env-Variablen / Secrets |
|
||||
| **Trigger** | n8n-Webhook | REST Endpoint (identisches Muster) |
|
||||
| **Wartbarkeit** | Workflow-Änderungen in UI | Code-Reviews, Git-History |
|
||||
| **Skalierung** | Horizontale Skalierung komplex | Standard Quarkus/Kubernetes |
|
||||
|
||||
---
|
||||
|
||||
## Architektur-Entscheidungen ✅
|
||||
|
||||
- [x] Trigger: **REST Endpoint** (von APEX Automation aufgerufen, identisch zu bisherigem n8n-Webhook)
|
||||
- [x] Scheduling: **APEX Automation** (bleibt unverändert — kein eigener Scheduler im Service)
|
||||
- [x] Async: **fire & forget** (202 Accepted sofort, Pipeline im Hintergrund — wie n8n)
|
||||
- [x] Endpoint-Auth: **X-Api-Key Header** (einfach, funktioniert mit APEX Web Service Calls)
|
||||
- [x] Concurrency Guard: **AtomicBoolean** (kein Doppellauf bei schnellen APEX-Retries)
|
||||
- [x] SFTP-Lösung: **SSHJ** (`com.hierynomus:sshj`) — leichtgewichtiger SFTP-Client
|
||||
- [x] SFTP Host-Key: **Fingerprint-basiert** via `galabau.sftp.host-key-fingerprint` in Config
|
||||
- [x] OCI Auth: **SimpleAuthenticationDetailsProvider** (Credentials via Env-Vars + gemountetes Kubernetes Secret für Private Key)
|
||||
- [x] OCI SDK: **OCI Java SDK** (HTTP Signature V1 automatisch)
|
||||
- [x] ZIP: **Apache Commons Compress**
|
||||
- [x] REST Clients: **MicroProfile REST Client** (configKey-basiert)
|
||||
- [x] Credentials: **`${ENV_VAR}`** in application.properties — Quarkus liest nativ aus Umgebungsvariablen
|
||||
- [x] Java: **25**
|
||||
- [x] Cleanup: **immer im finally** nach jeder ZIP
|
||||
|
||||
## Offene Fragen
|
||||
|
||||
- [ ] Disk-Space: Wie groß dürfen ZIPs maximal sein? → Capacity Planning
|
||||
- [ ] SFTP-Auth: Password oder Public-Key für Produktion? → Public-Key empfohlen
|
||||
- [ ] Monitoring: Welche Grafana-Alerts sind Pflicht? → TBD mit OPS-Team
|
||||
291
agent-backend/docs/SFTP-Integration.md
Normal file
291
agent-backend/docs/SFTP-Integration.md
Normal file
@@ -0,0 +1,291 @@
|
||||
# SSHJ SFTP — Architektur-Übersicht
|
||||
|
||||
**Projekt:** n8n Replacement für Dateieingang-Verarbeitung
|
||||
**Stand:** 2026-04-08
|
||||
|
||||
---
|
||||
|
||||
## Warum SSHJ statt Camel Quarkus FTP?
|
||||
|
||||
Camel Quarkus FTP ist ein EIP-/Routing-Framework, das intern selbst eine SFTP-Bibliothek
|
||||
wrapped. Da der Trigger ein REST-Endpoint ist (kein eigenes Scheduling, kein Message Routing),
|
||||
bringt Camel nur Overhead:
|
||||
|
||||
| | Camel Quarkus FTP | SSHJ |
|
||||
|---|---|---|
|
||||
| **Zweck** | EIP-Framework (Routing, EIP-Patterns, Scheduling) | SFTP/SSH Client |
|
||||
| **Größe** | Camel Core + FTP-Komponente (~10+ MByte Abhängigkeiten) | Leichtgewichtig |
|
||||
| **API** | Camel Exchange, RouteBuilder, Endpoints | Einfache Java API |
|
||||
| **Wartbarkeit** | Camel-Kenntnisse nötig | Standard Java I/O-Konzepte |
|
||||
| **Quarkus-Integration** | Native Extension vorhanden | Plain CDI-Bean |
|
||||
| **Eignet sich für** | Komplexe Routing-Szenarien | SFTP-Operationen (list, get, rename) |
|
||||
|
||||
Für diesen Use-Case (list ZIPs, download, rename nach Verarbeitung) ist SSHJ die richtige Wahl.
|
||||
|
||||
---
|
||||
|
||||
## Abhängigkeit
|
||||
|
||||
```xml
|
||||
<!-- Aktuelle Version prüfen: https://mvnrepository.com/artifact/com.hierynomus/sshj -->
|
||||
<dependency>
|
||||
<groupId>com.hierynomus</groupId>
|
||||
<artifactId>sshj</artifactId>
|
||||
<version>0.38.0</version>
|
||||
</dependency>
|
||||
```
|
||||
|
||||
SSHJ bringt Bouncy Castle als transitive Abhängigkeit mit (für Kryptografie).
|
||||
Das ist kein Problem — Bouncy Castle ist weit verbreitet und gut gepflegt.
|
||||
|
||||
---
|
||||
|
||||
## Pipeline-Architektur
|
||||
|
||||
```
|
||||
REST POST /api/process-incoming (X-Api-Key Header)
|
||||
│
|
||||
▼ 202 Accepted (sofort)
|
||||
FileProcessingPipeline.processAllAsync()
|
||||
│ Hintergrund-Thread (ManagedExecutor)
|
||||
│
|
||||
├─ SftpService.listZipFiles()
|
||||
│ └─ sftp.ls(remotePath) → ["export_2026-04-08.zip", ...]
|
||||
│
|
||||
└─ für jede ZIP:
|
||||
│
|
||||
├─ SftpService.download(filename)
|
||||
│ └─ sftp.get(remotePath/file, localPath)
|
||||
│
|
||||
├─ ZipExtractionService.extract(localFile)
|
||||
│ └─ ProcessingContext mit List<FileEntry>
|
||||
│
|
||||
├─ OciUploadService.upload(context)
|
||||
│ └─ Dateien + Marker in OCI (SimpleAuthenticationDetailsProvider)
|
||||
│
|
||||
├─ SftpService.renameRemote(file, file + ".processed") ← bei Erfolg
|
||||
│ SftpService.renameRemote(file, file + ".error") ← bei Fehler
|
||||
│
|
||||
├─ OrdsNotificationService.notify(context)
|
||||
│
|
||||
└─ cleanup: lokale ZIP + Entpack-Verzeichnis löschen ← immer (finally)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## SftpConfig (@ConfigMapping)
|
||||
|
||||
```java
|
||||
@ConfigMapping(prefix = "galabau.sftp")
|
||||
public interface SftpConfig {
|
||||
String host();
|
||||
int port();
|
||||
String username();
|
||||
String password();
|
||||
String hostKeyFingerprint(); // z.B. "SHA256:AbCdEfGh..."
|
||||
String remotePath();
|
||||
String localWorkDir();
|
||||
Optional<String> privateKeyPath();
|
||||
Optional<String> privateKeyPassphrase();
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## SftpService — Implementierungsstruktur
|
||||
|
||||
```java
|
||||
@ApplicationScoped
|
||||
public class SftpService {
|
||||
|
||||
@Inject
|
||||
SftpConfig config;
|
||||
|
||||
/**
|
||||
* Stellt eine SFTP-Verbindung her, führt die Operation aus und trennt danach sauber.
|
||||
* Host-Key wird gegen konfigurierten Fingerprint geprüft — kein PromiscuousVerifier.
|
||||
*/
|
||||
private <T> T withSftp(SftpOperation<T> operation) throws SftpException {
|
||||
try (SSHClient ssh = new SSHClient()) {
|
||||
// Fingerprint-basierte Host-Key-Verifikation (konfigurierbar, sicher)
|
||||
ssh.addHostKeyVerifier(new FingerprintVerifier(config.hostKeyFingerprint()));
|
||||
ssh.connect(config.host(), config.port());
|
||||
|
||||
if (config.privateKeyPath().isPresent()) {
|
||||
// Public-Key-Auth (bevorzugt für Produktion)
|
||||
ssh.authPublickey(config.username(), config.privateKeyPath().get());
|
||||
} else {
|
||||
// Password-Auth (Fallback / Entwicklung)
|
||||
ssh.authPassword(config.username(), config.password());
|
||||
}
|
||||
|
||||
try (SFTPClient sftp = ssh.newSFTPClient()) {
|
||||
return operation.execute(sftp);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new SftpException("SFTP operation failed: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
public List<String> listZipFiles() throws SftpException {
|
||||
return withSftp(sftp ->
|
||||
sftp.ls(config.remotePath()).stream()
|
||||
.filter(entry -> entry.getName().endsWith(".zip"))
|
||||
.map(RemoteResourceInfo::getName)
|
||||
.toList()
|
||||
);
|
||||
}
|
||||
|
||||
public Path download(String filename) throws SftpException {
|
||||
Path localFile = Path.of(config.localWorkDir(), filename);
|
||||
withSftp(sftp -> {
|
||||
sftp.get(config.remotePath() + "/" + filename, localFile.toString());
|
||||
return null;
|
||||
});
|
||||
return localFile;
|
||||
}
|
||||
|
||||
public void renameRemote(String filename, String newFilename) throws SftpException {
|
||||
withSftp(sftp -> {
|
||||
sftp.rename(
|
||||
config.remotePath() + "/" + filename,
|
||||
config.remotePath() + "/" + newFilename
|
||||
);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
interface SftpOperation<T> {
|
||||
T execute(SFTPClient sftp) throws IOException;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Host-Key-Fingerprint ermitteln
|
||||
|
||||
Einmalig ausführen (z.B. aus WSL oder Git Bash), bevor der Service deployed wird:
|
||||
|
||||
```bash
|
||||
# Alle Host Keys des Servers anzeigen (SHA256 Fingerprints):
|
||||
ssh-keyscan sftp.lieferant.de 2>/dev/null | ssh-keygen -lf -
|
||||
|
||||
# Ausgabe z.B.:
|
||||
# 256 SHA256:AbCdEfGhIjKlMnOpQrStUv... sftp.lieferant.de (ED25519)
|
||||
# 2048 SHA256:XyZaBcDeFgHiJk... sftp.lieferant.de (RSA)
|
||||
```
|
||||
|
||||
Den `SHA256:...`-Teil in `galabau.sftp.host-key-fingerprint` eintragen.
|
||||
**ED25519 bevorzugen** (stärker und kürzer als RSA).
|
||||
|
||||
---
|
||||
|
||||
## Fehlerbehandlung
|
||||
|
||||
### SFTP-Verbindungsfehler (transient)
|
||||
|
||||
```
|
||||
IOException beim connect/auth/ls
|
||||
→ SftpException (transient)
|
||||
→ Pipeline bricht ab
|
||||
→ Nächster APEX-Lauf (1h) versucht es erneut
|
||||
→ Alle ZIPs bleiben auf SFTP unverändert
|
||||
```
|
||||
|
||||
### Fehler während ZIP-Verarbeitung
|
||||
|
||||
```
|
||||
ZIP entpackbar?
|
||||
Nein → ZIP umbenennen zu .error, weiter mit nächster ZIP
|
||||
|
||||
OCI Upload erfolgreich?
|
||||
Nein (transient 503) → @Retry (3x), danach ZIP zu .error
|
||||
Nein (persistent 403) → ZIP zu .error, Log — Credentials prüfen!
|
||||
|
||||
ORDS-Aufruf fehlgeschlagen?
|
||||
Marker liegt vor → kein Problem, APEX Automation findet ihn nächsten Lauf
|
||||
```
|
||||
|
||||
### Cleanup (immer)
|
||||
|
||||
```java
|
||||
try {
|
||||
// ... Verarbeitung ...
|
||||
} finally {
|
||||
// Lokale Dateien immer löschen — egal ob Erfolg oder Fehler
|
||||
Files.deleteIfExists(context.localZipPath);
|
||||
deleteDirectory(context.localExtractDir);
|
||||
MDC.clear();
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Transient vs. Persistent Fehler
|
||||
|
||||
| Fehler | Typ | Handling |
|
||||
|---|---|---|
|
||||
| SFTP-Verbindung timeout/refused | transient | Nächster APEX-Lauf |
|
||||
| OCI 503 Service Unavailable | transient | @Retry (3x mit Backoff) |
|
||||
| ZIP beschädigt | persistent | `.error`, Log |
|
||||
| OCI 403 Auth Failed | persistent | `.error`, Log — Config prüfen! |
|
||||
| SFTP-Rename fehlgeschlagen | transient | Log, ZIP bleibt — nächster Lauf |
|
||||
|
||||
---
|
||||
|
||||
## n8n → Quarkus Service: Feature-Mapping
|
||||
|
||||
| n8n | Quarkus/SSHJ | Anmerkung |
|
||||
|---|---|---|
|
||||
| SFTP Trigger (Polling) | entfällt — REST Endpoint | Scheduling bleibt bei APEX Automation |
|
||||
| SFTP Download | `SftpService.download()` | SSHJ `sftp.get()` |
|
||||
| Unzip | `ZipExtractionService` | Apache Commons Compress |
|
||||
| HTTP PUT (OCI) | `OciUploadService` | OCI SDK, Instance Principal |
|
||||
| HTTP POST (ORDS) | `OrdsNotificationService` | MicroProfile REST Client |
|
||||
| Try/Catch | Try/Catch + @Retry | Kein Framework-Overhead |
|
||||
| Rename | `SftpService.renameRemote()` | SSHJ `sftp.rename()` |
|
||||
| Error Notification | Log + OTLP | Loki/Grafana Alert |
|
||||
|
||||
---
|
||||
|
||||
## Wartungs-Punkte
|
||||
|
||||
### Code-Organisation
|
||||
- **`SftpService`:** Nur SFTP-Operationen (list, download, rename) — keine Business-Logik
|
||||
- **`FileProcessingPipeline`:** Einziger Orchestrierer — kennt alle Services, steuert den Ablauf
|
||||
- **Services:** Keine Abhängigkeiten untereinander — jeder isoliert testbar
|
||||
- **Config:** `@ConfigMapping` — alle Werte aus `application.properties` / Umgebungsvariablen
|
||||
|
||||
### Testing-Strategie
|
||||
- `SftpService`: Testcontainers + echtem SFTP-Container (`atmoz/sftp` auf Docker Hub)
|
||||
- `ZipExtractionService`, `OciUploadService`: Unit-Tests mit Testdaten / Mocks
|
||||
- `FileProcessingPipeline`: Integration-Test mit Mock-Services
|
||||
- E2E: gegen Staging-SFTP und Staging-OCI
|
||||
|
||||
### Monitoring
|
||||
- OTLP → Loki (via Quarkus OpenTelemetry)
|
||||
- Dashboards: ZIP-Verarbeitungsrate, Fehler-Rate, Latenz pro Step
|
||||
- Alerts: `.error`-Dateien > Schwellwert, ORDS-Ausfälle, Pipeline-Laufzeit > Schwellwert
|
||||
|
||||
---
|
||||
|
||||
## Konfiguration (Zusammenfassung)
|
||||
|
||||
```properties
|
||||
# Host-Key Fingerprint (ssh-keyscan host | ssh-keygen -lf -)
|
||||
galabau.sftp.host-key-fingerprint=SHA256:AbCdEfGh...
|
||||
|
||||
# Password aus Env-Var (Quarkus löst ${...} nativ auf)
|
||||
galabau.sftp.password=${GALABAU_SFTP_PASSWORD}
|
||||
|
||||
# OCI: Credentials aus Env-Vars, Private Key als gemountetes Kubernetes Secret
|
||||
# galabau.oci.tenancy-id, user-id, fingerprint aus ${ENV_VAR}
|
||||
# galabau.oci.private-key-path zeigt auf gemountete PEM-Datei
|
||||
|
||||
# API-Absicherung des Endpoints
|
||||
galabau.api.key=${GALABAU_API_KEY}
|
||||
```
|
||||
|
||||
Siehe `plan_n8n_replacement_quarkus.md` für vollständige Konfigurationsübersicht.
|
||||
Reference in New Issue
Block a user