Computers – Page 2 – Template de site Internet

Étiquette : Computers

  • Socle V004 – Architecture

    02 – Architecture du Socle V4

    Version : 4.0.0 Date : 2025-01-25

    1. Vue d’ensemble

    ┌─────────────────────────────────────────────────────────────────┐
    │                         SOCLE V4                                │
    │                                                                 │
    │  ┌─────────────────────────────────────────────────────────┐   │
    │  │                    MOP (inchangé)                        │   │
    │  │  - Orchestration Workers                                 │   │
    │  │  - Lifecycle management                                  │   │
    │  │  - Scheduling doWork()                                   │   │
    │  └─────────────────────────────────────────────────────────┘   │
    │                              │                                  │
    │  ┌───────────┬───────────┬───┴───────┬─────────────┐           │
    │  │           │           │           │             │           │
    │  ▼           ▼           ▼           ▼             ▼           │
    │ ┌─────┐  ┌───────┐  ┌────────┐  ┌─────────┐  ┌──────────┐     │
    │ │KvBus│  │Shared │  │Supervi-│  │ HTTP    │  │ Workers  │     │
    │ │     │  │Data   │  │sor     │  │ Worker  │  │ métier   │     │
    │ └─────┘  └───────┘  └────────┘  └─────────┘  └──────────┘     │
    │                                                                 │
    │  ════════════════════ NOUVEAUTÉS V4 ════════════════════════   │
    │                                                                 │
    │  ┌─────────────┐  ┌─────────────┐  ┌─────────────────────┐     │
    │  │ H2 TechDB   │  │ Log4j2 +    │  │ Clients centraux    │     │
    │  │ (embarqué)  │  │ LogForwarder│  │ - SocleAuthClient   │     │
    │  │             │  │             │  │ - WorkerRegistry    │     │
    │  └─────────────┘  └─────────────┘  └─────────────────────┘     │
    │                                                                 │
    │  ┌─────────────┐  ┌─────────────────────────────────────┐      │
    │  │ Status      │  │ Pipeline V2                          │      │
    │  │ Dashboard   │  │ (Queue/Claim/Ack, DLQ, at-least-once)│      │
    │  │ (port 9374) │  │                                      │      │
    │  └─────────────┘  └─────────────────────────────────────┘      │
    │                                                                 │
    └─────────────────────────────────────────────────────────────────┘
    

    2. Architecture en couches

    ┌─────────────────────────────────────────────────────────────────┐
    │                    COUCHE APPLICATION                           │
    │  Workers métier + Contrôleurs REST                              │
    ├─────────────────────────────────────────────────────────────────┤
    │                    COUCHE FRAMEWORK (SOCLE)                     │
    │  MOP + Core Components + Nouveautés V4                          │
    ├─────────────────────────────────────────────────────────────────┤
    │                    COUCHE INFRASTRUCTURE                        │
    │  Tomcat (HTTP), H2 (TechDB), Redis (KV), Kafka/NATS (Msg)      │
    └─────────────────────────────────────────────────────────────────┘
    

    3. Structure des packages

    eu.lmvi.socle/
    │
    │  ══════ COMPOSANTS V3 (conservés) ══════
    ├── mop/
    │   └── MainOrchestratorProcess.java    # Orchestrateur central
    ├── worker/
    │   └── Worker.java                     # Interface de base
    ├── config/
    │   └── SocleConfiguration.java         # Configuration centralisée
    ├── kv/
    │   ├── KvBus.java                      # Abstraction KV
    │   ├── KvImplementation.java           # Interface implémentation
    │   ├── InMemoryKvImplementation.java   # Implémentation mémoire
    │   └── RedisKvImplementation.java      # Implémentation Redis
    ├── shared/
    │   └── SharedDataRegistry.java         # Registre données partagées
    ├── supervisor/
    │   └── Supervisor.java                 # Monitoring heartbeats
    ├── http/
    │   ├── HttpWorker.java                 # Worker HTTP
    │   ├── TomcatManager.java              # Gestion Tomcat
    │   └── GracefulShutdownFilter.java     # Filtre drain
    ├── admin/
    │   └── AdminRestApi.java               # API REST admin
    ├── metrics/
    │   └── SocleMetrics.java               # Métriques
    ├── pipeline/
    │   └── PipelineEngine.java             # Traitement asynchrone
    ├── resilience/
    │   ├── CircuitBreaker.java             # Circuit Breaker
    │   └── RetryExecutor.java              # Retry avec backoff
    ├── scheduler/
    │   ├── WorkerScheduler.java            # Scheduler
    │   └── CronExpression.java             # Parser cron
    ├── security/
    │   ├── AdminAuthFilter.java            # Auth admin
    │   └── RateLimitFilter.java            # Rate limiting
    │
    │  ══════ NOUVEAUX COMPOSANTS V4 ══════
    ├── techdb/
    │   ├── TechDbManager.java              # Gestionnaire H2
    │   ├── TechDbConfig.java               # Configuration Spring
    │   └── TechDbRepository.java           # Repository
    ├── logging/
    │   ├── SocleLogForwarderAppender.java  # Appender Log4j2
    │   ├── LogTransport.java               # Interface transport
    │   ├── HttpLogTransport.java           # Transport HTTP
    │   ├── NatsLogTransport.java           # Transport NATS
    │   └── H2FallbackStorage.java          # Fallback H2
    └── client/
        ├── auth/
        │   ├── SocleAuthClient.java        # Interface auth
        │   ├── AuthTokenManager.java       # Gestion tokens
        │   └── AuthTokens.java             # DTO tokens
        └── registry/
            ├── WorkerRegistryClient.java   # Client registry
            ├── WorkerRegistration.java     # DTO registration
            └── WorkerHeartbeat.java        # DTO heartbeat
    

    4. Flux de démarrage

    1. Spring Boot initialise
    2. SocleConfiguration charge la config (.env + YAML)
    3. Spring crée les beans @Component
    4. MOP.start() appelé (ApplicationReadyEvent)
       │
       ├── 4.1 [V4] TechDbManager.initialize()
       │         └── Création tables H2
       │         └── Restauration offsets
       │
       ├── 4.2 [V4] SocleAuthClient.login()
       │         └── Obtention JWT
       │
       ├── 4.3 [V4] WorkerRegistryClient.register()
       │         └── Enregistrement au Registry
       │
       ├── 4.4 SharedDataRegistry.initialize()
       ├── 4.5 KvBus.initialize()
       ├── 4.6 Supervisor.start()
       ├── 4.7 Metrics.start()
       │
       ├── 4.8 Workers triés par START_PRIORITY
       │   └── Pour chaque worker:
       │       ├── worker.initialize()
       │       ├── worker.start()
       │       ├── Register avec Supervisor
       │       └── Schedule si isScheduled()
       │
       ├── 4.9 HttpWorker.start() [priorité 1000 = dernier]
       └── 4.10 Boucle principale doWork()
    

    5. Flux de shutdown

    1. Signal SIGTERM (ou /admin/shutdown)
    2. MOP.stop() appelé
    3. État → DRAINING
       │
       ├── 3.1 HttpWorker.startDraining()
       │         └── Refuse nouvelles connexions
       ├── 3.2 HttpWorker.awaitDrain(timeout)
       │         └── Attente requêtes en cours
       │
       ├── 3.3 Workers par STOP_PRIORITY (petit = premier)
       │   ├── HttpWorker.stop() [priorité 0]
       │   └── Autres workers [priorités 1-999]
       │
       ├── 3.4 [V4] WorkerRegistryClient.unregister()
       ├── 3.5 [V4] TechDbManager.close()
       │
       ├── 3.6 Supervisor.shutdown()
       ├── 3.7 SharedData.close()
       └── 3.8 État → STOPPED
    

    6. Dépendances entre composants

    ┌──────────────────────────────────────────────────────────────┐
    │                        MOP (orchestrateur)                    │
    │                              │                                │
    │         ┌────────────────────┼────────────────────┐          │
    │         │                    │                    │          │
    │         ▼                    ▼                    ▼          │
    │   ┌───────────┐       ┌───────────┐       ┌───────────┐     │
    │   │ TechDB    │◄──────│ Supervisor│───────►│ Workers   │     │
    │   │ Manager   │       │           │        │           │     │
    │   └─────┬─────┘       └─────┬─────┘        └─────┬─────┘     │
    │         │                   │                    │           │
    │         │                   ▼                    │           │
    │         │            ┌───────────┐               │           │
    │         │            │ Worker    │◄──────────────┘           │
    │         │            │ Registry  │                           │
    │         │            │ Client    │                           │
    │         │            └─────┬─────┘                           │
    │         │                  │                                 │
    │         ▼                  ▼                                 │
    │   ┌───────────┐     ┌───────────┐                           │
    │   │ H2        │     │ SocleAuth │                           │
    │   │ Database  │     │ Client    │                           │
    │   └───────────┘     └─────┬─────┘                           │
    │                           │                                  │
    │                           ▼                                  │
    │                    ┌─────────────┐                           │
    │                    │ LogForwarder│──► HTTP/NATS (sortant)   │
    │                    │ Appender    │                           │
    │                    └─────────────┘                           │
    └──────────────────────────────────────────────────────────────┘
    

    7. Architecture du Logging V4

    ┌─────────────────────────────────────────────────────────────┐
    │                      Application                             │
    │                                                              │
    │  Logger.info("message")                                      │
    │         │                                                    │
    │         ▼                                                    │
    │  ┌─────────────────────────────────────────────────────┐    │
    │  │              Log4j2 AsyncLoggers                     │    │
    │  │              (LMAX Disruptor)                        │    │
    │  └────────────────────┬────────────────────────────────┘    │
    │                       │                                      │
    │         ┌─────────────┼─────────────┐                       │
    │         ▼             ▼             ▼                       │
    │  ┌───────────┐ ┌───────────┐ ┌─────────────────────┐       │
    │  │  Console  │ │  File     │ │ SocleLogForwarder   │       │
    │  │  Appender │ │  Appender │ │ Appender            │       │
    │  └───────────┘ └───────────┘ └──────────┬──────────┘       │
    │                                         │                   │
    └─────────────────────────────────────────┼───────────────────┘
                                              │
                        ┌─────────────────────┴─────────────────────┐
                        │                                           │
                        ▼                                           ▼
                ┌──────────────┐                           ┌──────────────┐
                │ HTTP Transport│                           │ NATS Transport│
                │ → LogHub     │                           │ → JetStream  │
                └──────┬───────┘                           └──────┬───────┘
                       │                                          │
                       │  (si échec)                              │
                       ▼                                          │
                ┌──────────────┐                                  │
                │ H2 Fallback  │◄─────────────────────────────────┘
                │ Storage      │
                └──────────────┘
    

    8. Patterns de conception

    Pattern Composant Usage
    Orchestrator MOP Orchestre tout le lifecycle
    Observer KvBus pub/sub Communication inter-workers
    Strategy KvImplementation In-memory ou Redis
    Registry SharedDataRegistry État partagé
    Circuit Breaker CircuitBreaker Résilience pannes
    Factory Spring DI Création composants
    Builder Configuration Construction config

    9. Thread Safety

    Mécanisme Usage
    ConcurrentHashMap Maps partagées
    AtomicLong/Boolean Compteurs atomiques
    ReentrantReadWriteLock Opérations complexes
    BlockingQueue Queues thread-safe
    CompletableFuture Opérations async
    ScheduledExecutorService Scheduling
    LMAX Disruptor Ring buffer logging

    10. Points d’extension

    Créer un nouveau Worker

    @Component
    public class MonWorker implements Worker {
        // Implémenter l'interface Worker
    }
    

    Ajouter une implémentation KvBus

    public class MonKvImplementation implements KvImplementation {
        // Implémenter l'interface
    }
    

    Créer un Pipeline Stage

    public class MonStage implements PipelineStage<MonType> {
        // Implémenter le traitement
    }
    

    11. Références

  • Socle V004 – Migration V3 vers V4

    25 – Guide de Migration V3 → V4

    Version : 4.0.0 Date : 2025-12-09

    1. Résumé des changements

    1.1 Ce qui change

    Aspect V3 V4
    Logging Logback Log4j2 + LogForwarder
    Persistance technique In-memory/Redis + H2 TechDB
    Auth AdminAuthFilter local + SocleAuthClient JWT
    Registry Supervisor local + WorkerRegistryClient

    1.2 Ce qui ne change PAS

    • Architecture MOP
    • Interface Worker
    • KvBus (in_memory / Redis)
    • SharedDataRegistry
    • Supervisor
    • HttpWorker
    • AdminRestApi
    • PipelineEngine
    • CircuitBreaker / Retry
    • Scheduler

    2. Checklist de migration

    □ Phase 1: Préparation
      □ Lire ce guide en entier
      □ Backup du projet V3
      □ Créer branche migration-v4
    
    □ Phase 2: Dépendances Maven
      □ Mettre à jour pom.xml
      □ Exclure Logback
      □ Ajouter Log4j2
      □ Ajouter H2
    
    □ Phase 3: Configuration
      □ Créer log4j2.xml
      □ Créer log4j2.component.properties
      □ Supprimer logback-spring.xml
      □ Mettre à jour application.yml
    
    □ Phase 4: Code (optionnel)
      □ Intégrer TechDbManager
      □ Intégrer SocleAuthClient
      □ Intégrer WorkerRegistryClient
    
    □ Phase 5: Tests
      □ Compiler
      □ Exécuter les tests
      □ Vérifier les logs
      □ Valider H2 Console
    
    □ Phase 6: Déploiement
      □ Variables d'environnement
      □ Test en staging
      □ Déploiement production
    

    3. Phase 1 : Préparation

    3.1 Backup

    # Backup du projet V3
    cp -r socle-v003 socle-v003-backup
    
    # Créer branche
    cd socle-v003
    git checkout -b migration-v4
    

    3.2 Version cible

    <version>4.0.0</version>
    

    4. Phase 2 : Dépendances Maven

    4.1 Modifications pom.xml

    <!-- AVANT (V3) -->
    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
    </dependency>
    <dependency>
        <groupId>net.logstash.logback</groupId>
        <artifactId>logstash-logback-encoder</artifactId>
    </dependency>
    
    <!-- APRÈS (V4) -->
    <!-- Exclure Logback de Spring Boot -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    
    <!-- Log4j2 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-log4j2</artifactId>
    </dependency>
    
    <!-- LMAX Disruptor -->
    <dependency>
        <groupId>com.lmax</groupId>
        <artifactId>disruptor</artifactId>
        <version>4.0.0</version>
    </dependency>
    
    <!-- H2 Database -->
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <version>2.2.224</version>
    </dependency>
    

    4.2 Vérifier les exclusions

    S’assurer que Logback est exclu de TOUTES les dépendances Spring Boot :

    mvn dependency:tree | grep logback
    # Ne doit rien retourner
    

    5. Phase 3 : Configuration

    5.1 Créer log4j2.xml

    Créer src/main/resources/log4j2.xml :

    <?xml version="1.0" encoding="UTF-8"?>
    <Configuration status="WARN" monitorInterval="30">
        <Properties>
            <Property name="LOG_DIR">${env:LOG_DIR:-./logs}</Property>
            <Property name="APP_NAME">${env:APP_NAME:-socle-v4}</Property>
        </Properties>
    
        <Appenders>
            <Console name="Console" target="SYSTEM_OUT">
                <PatternLayout pattern="%d{ISO8601} %-5level [%thread] %logger{36} - %msg%n"/>
            </Console>
    
            <RollingFile name="File"
                         fileName="${LOG_DIR}/${APP_NAME}.log"
                         filePattern="${LOG_DIR}/${APP_NAME}-%d{yyyy-MM-dd}-%i.log.gz">
                <PatternLayout pattern="%d{ISO8601} %-5level [%thread] %logger{36} - %msg%n"/>
                <Policies>
                    <TimeBasedTriggeringPolicy interval="1"/>
                    <SizeBasedTriggeringPolicy size="100MB"/>
                </Policies>
                <DefaultRolloverStrategy max="30"/>
            </RollingFile>
        </Appenders>
    
        <Loggers>
            <Logger name="eu.lmvi.socle" level="${env:LOG_LEVEL:-INFO}" additivity="false">
                <AppenderRef ref="Console"/>
                <AppenderRef ref="File"/>
            </Logger>
            <Logger name="org.springframework" level="WARN"/>
            <Root level="INFO">
                <AppenderRef ref="Console"/>
                <AppenderRef ref="File"/>
            </Root>
        </Loggers>
    </Configuration>
    

    5.2 Créer log4j2.component.properties

    Créer src/main/resources/log4j2.component.properties :

    Log4jContextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector
    AsyncLogger.RingBufferSize=262144
    AsyncLogger.WaitStrategy=Sleep
    log4j2.formatMsgNoLookups=true
    

    5.3 Supprimer logback-spring.xml

    rm src/main/resources/logback-spring.xml
    

    5.4 Mettre à jour application.yml

    Ajouter les nouvelles configurations V4 :

    # Ajouter à application.yml existant
    
    socle:
      # ... config V3 existante ...
    
      # NOUVEAU V4: H2 TechDB
      techdb:
        enabled: ${TECHDB_ENABLED:true}
        url: jdbc:h2:file:${TECHDB_PATH:./data/socle-techdb};MODE=PostgreSQL;DB_CLOSE_DELAY=-1
        username: socle
        password: ${TECHDB_PASSWORD:socle}
        console:
          enabled: ${H2_CONSOLE_ENABLED:false}
          path: /h2-console
    
      # NOUVEAU V4: LogForwarder (optionnel)
      logging:
        forwarder:
          enabled: ${LOG_FORWARDER_ENABLED:false}
          transport-mode: ${LOG_TRANSPORT_MODE:http}
          log-hub-url: ${LOG_HUB_URL:}
    
      # NOUVEAU V4: Auth Client (optionnel)
      auth:
        enabled: ${AUTH_ENABLED:false}
        server-url: ${AUTH_SERVER_URL:}
        api-key: ${API_KEY:}
    
      # NOUVEAU V4: Worker Registry (optionnel)
      worker-registry:
        enabled: ${WORKER_REGISTRY_ENABLED:false}
        server-url: ${WORKER_REGISTRY_URL:}
    
    # Logging
    logging:
      config: classpath:log4j2.xml
    

    6. Phase 4 : Code (optionnel)

    Les composants V4 sont optionnels et activés via configuration. Aucune modification de code n’est obligatoire.

    6.1 Si vous voulez utiliser TechDB

    @Autowired(required = false)
    private TechDbManager techDbManager;
    
    // Utilisation
    if (techDbManager != null) {
        techDbManager.saveOffset("kafka", "topic-0", offset, null);
    }
    

    6.2 Si vous voulez utiliser AuthClient

    @Autowired(required = false)
    private SocleAuthClient authClient;
    
    // Utilisation
    if (authClient != null && authClient.isAuthenticated()) {
        String token = authClient.getValidAccessToken();
    }
    

    6.3 Si vous voulez utiliser WorkerRegistry

    @Autowired(required = false)
    private WorkerRegistryClient registryClient;
    
    // L'intégration MOP est automatique si enabled
    

    7. Phase 5 : Tests

    7.1 Compilation

    mvn clean compile
    

    Erreurs possibles :

    • package ch.qos.logback does not exist → Logback pas complètement exclu
    • cannot find symbol: class Logger → Import SLF4J correct ?

    7.2 Tests unitaires

    mvn test
    

    7.3 Vérification logs

    mvn spring-boot:run
    

    Vérifier :

    • Logs apparaissent en console
    • Format correct
    • Pas d’erreur Log4j2

    7.4 H2 Console

    Si H2_CONSOLE_ENABLED=true :

    1. Ouvrir http://localhost:8080/h2-console
    2. JDBC URL: jdbc:h2:file:./data/socle-techdb
    3. Vérifier les tables créées

    8. Phase 6 : Déploiement

    8.1 Variables d’environnement (minimum)

    # Existantes V3 (inchangées)
    APP_NAME=my-app
    ENV_NAME=PROD
    HTTP_PORT=8080
    
    # Nouvelles V4 (optionnelles)
    TECHDB_ENABLED=true
    TECHDB_PATH=./data/techdb
    H2_CONSOLE_ENABLED=false
    LOG_FORWARDER_ENABLED=false
    AUTH_ENABLED=false
    WORKER_REGISTRY_ENABLED=false
    

    8.2 Docker

    Mettre à jour le Dockerfile si nécessaire :

    # Pas de changement requis si vous utilisez le JAR
    FROM eclipse-temurin:21-jre
    COPY target/socle-v004-4.0.0.jar app.jar
    ENTRYPOINT ["java", "-jar", "app.jar"]
    

    8.3 Kubernetes

    Mettre à jour les ConfigMaps/Secrets avec les nouvelles variables.

    9. Mapping des configurations

    9.1 Logback → Log4j2

    Logback Log4j2
    <appender class="ConsoleAppender"> <Console name="...">
    <appender class="RollingFileAppender"> <RollingFile name="...">
    <encoder><pattern> <PatternLayout pattern="...">
    <root level="INFO"> <Root level="INFO">
    <logger name="..." level="..."> <Logger name="..." level="...">

    9.2 Pattern identique

    Le pattern de log reste identique :

    %d{ISO8601} %-5level [%thread] %logger{36} - %msg%n
    

    10. Rollback

    En cas de problème, pour revenir à V3 :

    # Restaurer le pom.xml V3
    git checkout HEAD~1 -- pom.xml
    
    # Restaurer logback-spring.xml
    git checkout HEAD~1 -- src/main/resources/logback-spring.xml
    
    # Supprimer fichiers V4
    rm src/main/resources/log4j2.xml
    rm src/main/resources/log4j2.component.properties
    
    # Rebuild
    mvn clean package
    

    11. FAQ

    Q: Dois-je modifier mon code de logging ?

    Non. Le code reste identique :

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    private static final Logger log = LoggerFactory.getLogger(MyClass.class);
    log.info("Message");
    

    Q: Les MDC fonctionnent-ils ?

    Oui. MDC fonctionne de manière identique avec Log4j2.

    Q: Puis-je activer les fonctionnalités V4 progressivement ?

    Oui. Toutes les fonctionnalités V4 sont optionnelles :

    • TECHDB_ENABLED=false → Pas de H2
    • LOG_FORWARDER_ENABLED=false → Pas de LogForwarder
    • AUTH_ENABLED=false → Pas d’auth JWT
    • WORKER_REGISTRY_ENABLED=false → Pas de registry

    Q: Performance : V4 est-il plus rapide ?

    Oui pour le logging. Log4j2 avec AsyncLoggers (LMAX Disruptor) est 6-68x plus rapide que Logback en mode async.

    12. Références

  • Socle V004 – Janino

    29 – Janino (Compilateur Java Dynamique)

    Version : 4.0.0 Date : 2026-01-17

    1. Introduction

    Janino est un compilateur Java embarqué qui permet de compiler du code source Java en bytecode JVM à la volée. Contrairement au ScriptEngine existant (interprété), Janino offre des performances natives car le code est réellement compilé.

    Positionnement

    ┌─────────────────────────────────────────────────────────────────┐
    │                      Socle V004 Scripts                          │
    ├─────────────────────────────────────────────────────────────────┤
    │                                                                  │
    │  ┌─────────────────────┐       ┌─────────────────────┐          │
    │  │    ScriptEngine     │       │   JaninoEngine      │          │
    │  │    (existant)       │       │   (NOUVEAU)         │          │
    │  ├─────────────────────┤       ├─────────────────────┤          │
    │  │ - JavaScript        │       │ - Java pur          │          │
    │  │ - BeanShell         │       │ - Bytecode natif    │          │
    │  │ - Interprété        │       │ - Haute performance │          │
    │  │ - Typage dynamique  │       │ - Typage statique   │          │
    │  └─────────────────────┘       └─────────────────────┘          │
    │                                                                  │
    └─────────────────────────────────────────────────────────────────┘
    

    Cas d’usage

    Situation Recommandation
    Calculs financiers (frais, taxes) Janino
    Validations métier complexes Janino
    Transformations haute performance Janino
    Scripts simples, prototypage ScriptEngine
    Formules configurables Janino

    2. Architecture

    2.1 Composants

    eu.lmvi.socle.janino/
    ├── JaninoEngine.java              # Moteur principal
    ├── JaninoWorker.java              # Worker de gestion
    ├── JaninoScript.java              # Script compilé
    ├── JaninoClassLoader.java         # ClassLoader sécurisé
    ├── JaninoConfiguration.java       # Configuration Spring
    ├── JaninoCompilationException.java # Exception
    └── interfaces/
        ├── Calculator.java            # Interface calculateur
        ├── Executable.java            # Interface exécutable
        ├── Validator.java             # Interface validateur
        └── ValidationResult.java      # Résultat validation
    

    2.2 Diagramme de classes

    ┌───────────────────────┐
    │   JaninoWorker        │  (implements Worker)
    │   @Component          │
    ├───────────────────────┤
    │ - janinoEngine        │
    │ - config              │
    │ - techDb              │
    │ - supervisor          │
    ├───────────────────────┤
    │ + execute()           │
    │ + compileScript()     │
    │ + forceReload()       │
    │ + getEngine()         │
    └───────────┬───────────┘
                │
                ▼
    ┌───────────────────────┐
    │   JaninoEngine        │
    │   @Component          │
    ├───────────────────────┤
    │ - scriptCache         │
    │ - classLoader         │
    ├───────────────────────┤
    │ + compile()           │
    │ + execute()           │
    │ + reload()            │
    │ + getStats()          │
    └───────────┬───────────┘
                │
                ▼
    ┌───────────────────────┐
    │   JaninoScript        │
    ├───────────────────────┤
    │ - name                │
    │ - compiledClass       │
    │ - executionCount      │
    │ - avgExecutionTimeNs  │
    └───────────────────────┘
    

    3. Configuration

    3.1 application.yml

    socle:
      janino:
        # Activer Janino (défaut: false)
        enabled: ${JANINO_ENABLED:false}
    
        # Répertoire des scripts Java
        scripts-path: ${JANINO_SCRIPTS_PATH:./repository/scripts/java}
    
        # Intervalle de rechargement (défaut: 5 minutes)
        reload-interval-ms: ${JANINO_RELOAD_INTERVAL:300000}
    
        # Nombre max de classes en cache
        max-cached-classes: ${JANINO_MAX_CACHED:100}
    
        # Sécurité
        security:
          # Packages bloqués dans les scripts
          blocked-packages:
            - java.io
            - java.net
            - java.lang.reflect
            - java.lang.invoke
            - sun.
            - com.sun.
    
          # Timeout d'exécution max
          max-execution-time-ms: ${JANINO_MAX_EXEC_TIME:5000}
    

    3.2 Variables d’environnement

    Variable Description Défaut
    JANINO_ENABLED Activer Janino false
    JANINO_SCRIPTS_PATH Répertoire scripts ./repository/scripts/java
    JANINO_RELOAD_INTERVAL Intervalle reload (ms) 300000
    JANINO_MAX_CACHED Max classes en cache 100
    JANINO_MAX_EXEC_TIME Timeout exécution (ms) 5000

    4. Interfaces de Scripts

    Les scripts Java doivent implémenter une des interfaces suivantes :

    4.1 Calculator

    Pour les calculs (frais, taxes, conversions).

    package eu.lmvi.socle.janino.interfaces;
    
    public interface Calculator<T> {
        T calculate(Map<String, Object> context);
    }
    

    Exemple :

    import eu.lmvi.socle.janino.interfaces.Calculator;
    import java.math.BigDecimal;
    import java.math.RoundingMode;
    import java.util.Map;
    
    public class FeeCalculator implements Calculator<BigDecimal> {
    
        private static final BigDecimal FEE_RATE = new BigDecimal("0.0026");
    
        @Override
        public BigDecimal calculate(Map<String, Object> context) {
            BigDecimal amount = (BigDecimal) context.get("amount");
            String side = (String) context.get("side");
    
            BigDecimal rate = "MAKER".equals(side)
                ? new BigDecimal("0.0016")
                : FEE_RATE;
    
            return amount.multiply(rate).setScale(8, RoundingMode.HALF_UP);
        }
    }
    

    4.2 Executable

    Pour les exécutions génériques.

    package eu.lmvi.socle.janino.interfaces;
    
    public interface Executable {
        Object execute(Map<String, Object> context);
    }
    

    Exemple :

    import eu.lmvi.socle.janino.interfaces.Executable;
    import java.util.Map;
    
    public class OrderProcessor implements Executable {
    
        @Override
        public Object execute(Map<String, Object> context) {
            String orderId = (String) context.get("orderId");
            Double amount = (Double) context.get("amount");
    
            // Logique de traitement...
    
            return Map.of(
                "status", "PROCESSED",
                "orderId", orderId,
                "processedAmount", amount * 0.99
            );
        }
    }
    

    4.3 Validator

    Pour les validations métier.

    package eu.lmvi.socle.janino.interfaces;
    
    public interface Validator {
        ValidationResult validate(Object input);
    }
    

    Exemple :

    import eu.lmvi.socle.janino.interfaces.Validator;
    import eu.lmvi.socle.janino.interfaces.ValidationResult;
    import java.math.BigDecimal;
    
    public class OrderValidator implements Validator {
    
        private static final BigDecimal MIN_AMOUNT = new BigDecimal("10.00");
        private static final BigDecimal MAX_AMOUNT = new BigDecimal("100000.00");
    
        @Override
        public ValidationResult validate(Object input) {
            Order order = (Order) input;
            ValidationResult result = new ValidationResult();
    
            if (order.getAmount().compareTo(MIN_AMOUNT) < 0) {
                result.addError("AMOUNT_TOO_LOW",
                    "Amount must be >= " + MIN_AMOUNT);
            }
    
            if (order.getAmount().compareTo(MAX_AMOUNT) > 0) {
                result.addError("AMOUNT_TOO_HIGH",
                    "Amount must be <= " + MAX_AMOUNT);
            }
    
            if (order.getPair() == null || order.getPair().isEmpty()) {
                result.addError("INVALID_PAIR", "Trading pair is required");
            }
    
            return result;
        }
    }
    

    5. Utilisation

    5.1 Structure des scripts

    repository/scripts/java/
    ├── fees/
    │   ├── KrakenFeeCalculator.java
    │   ├── BinanceFeeCalculator.java
    │   └── CryptoComFeeCalculator.java
    ├── validators/
    │   ├── OrderValidator.java
    │   └── AmountValidator.java
    └── processors/
        ├── OrderProcessor.java
        └── TradeProcessor.java
    

    5.2 Injection dans un Worker

    @Component
    public class TradingWorker implements Worker {
    
        @Autowired
        private JaninoWorker janinoWorker;
    
        @Override
        public void doWork() {
            // Exécuter un calculateur
            Map<String, Object> context = Map.of(
                "amount", new BigDecimal("1000.00"),
                "side", "TAKER"
            );
    
            BigDecimal fee = janinoWorker.execute(
                "KrakenFeeCalculator",
                context,
                BigDecimal.class
            );
    
            log.info("Fee calculated: {}", fee);
        }
    }
    

    5.3 Compilation à la volée

    @Autowired
    private JaninoWorker janinoWorker;
    
    public void compileCustomScript() {
        String source = """
            import eu.lmvi.socle.janino.interfaces.Calculator;
            import java.math.BigDecimal;
            import java.util.Map;
    
            public class CustomCalculator implements Calculator<BigDecimal> {
                @Override
                public BigDecimal calculate(Map<String, Object> context) {
                    BigDecimal value = (BigDecimal) context.get("value");
                    return value.multiply(new BigDecimal("1.05"));
                }
            }
            """;
    
        janinoWorker.compileScript("CustomCalculator", source);
    
        // Exécuter
        BigDecimal result = janinoWorker.execute(
            "CustomCalculator",
            Map.of("value", new BigDecimal("100")),
            BigDecimal.class
        );
    }
    

    5.4 Accès direct au moteur

    @Autowired
    private JaninoWorker janinoWorker;
    
    public void advancedUsage() {
        JaninoEngine engine = janinoWorker.getEngine();
    
        // Vérifier si un script est compilé
        boolean ready = engine.isCompiled("FeeCalculator");
    
        // Liste des scripts compilés
        Set<String> scripts = engine.getCompiledScripts();
    
        // Statistiques détaillées
        Map<String, Map<String, Object>> stats = engine.getScriptStats();
    
        // Forcer le rechargement
        janinoWorker.forceReload();
    }
    

    6. Hot-Reload

    Le JaninoWorker surveille automatiquement les modifications des fichiers .java dans le répertoire configuré.

    Fonctionnement

    1. À chaque cycle (reload-interval-ms), le worker scanne le répertoire
    2. Pour chaque fichier modifié (timestamp changé), le script est recompilé
    3. Le nouveau bytecode remplace l’ancien dans le cache
    4. Les prochaines exécutions utilisent la nouvelle version

    Logs

    [exec:xxx][step:janino_reloaded] Reloaded script: FeeCalculator
    [exec:xxx][step:janino_reload_cycle] Reload cycle completed (5 scripts)
    

    Forcer le rechargement

    // Recharger tous les scripts
    janinoWorker.forceReload();
    

    7. Securite

    7.1 Validation des Imports (Source-Level)

    Le JaninoEngine valide les imports avant la compilation pour bloquer l’acces aux packages dangereux. Cette approche (validation au niveau du code source) est plus compatible avec les fat-jars Spring Boot que la precedente approche ClassLoader.

    Package bloque Raison
    java.io Acces fichiers
    java.net Acces reseau
    java.lang.reflect Reflection
    java.lang.invoke MethodHandles
    sun.* Classes internes
    com.sun.* Classes internes

    7.2 Fonctionnement

    Source Java → validateSourceSecurity() → Compilation Janino → Execution
                         ↓
                  Analyse des imports
                         ↓
                Blocage si package interdit
    

    Le moteur analyse les declarations import dans le code source et rejette le script si un package bloque est detecte.

    7.3 Tentative d’acces bloque

    // Ce script sera bloque AVANT compilation
    import java.io.File;  // BLOQUE!
    
    public class MaliciousScript implements Executable {
        @Override
        public Object execute(Map<String, Object> context) {
            File file = new File("/etc/passwd");
            return null;
        }
    }
    

    Erreur :

    JaninoCompilationException: Security violation in script 'MaliciousScript':
    Import of blocked package 'java.io' is not allowed. Blocked import: java.io.File
    

    7.4 Configuration personnalisee

    socle:
      janino:
        security:
          blocked-packages:
            - java.io
            - java.net
            - java.lang.reflect
            - java.lang.invoke
            - sun.
            - com.sun.
            - com.mycompany.internal  # Packages internes custom
    

    8. Métriques et Monitoring

    8.1 Stats du Worker

    Map<String, Object> stats = janinoWorker.getStats();
    
    // Résultat:
    {
        "name": "janino_worker",
        "running": true,
        "healthy": true,
        "scripts_path": "./repository/scripts/java",
        "reload_interval_ms": 300000,
        "reload_count": 15,
        "last_reload_at": "2026-01-17T10:30:00Z",
        "scripts_compiled": 5,
        "compilation_count": 8,
        "compilation_errors": 0,
        "execution_count": 1234,
        "execution_errors": 2
    }
    

    8.2 Stats par script

    Map<String, Map<String, Object>> scriptStats = janinoWorker.getEngine().getScriptStats();
    
    // Résultat:
    {
        "KrakenFeeCalculator": {
            "class": "KrakenFeeCalculator",
            "compiled_at": 1705487400000,
            "execution_count": 500,
            "avg_execution_us": 12
        },
        "BinanceFeeCalculator": {
            "class": "BinanceFeeCalculator",
            "compiled_at": 1705487400000,
            "execution_count": 300,
            "avg_execution_us": 8
        }
    }
    

    8.3 TechDB

    Le worker persiste ses stats dans la table janino_stats :

    SELECT * FROM janino_stats;
    
    -- worker_name | scripts_count | compilation_count | execution_count | reload_count | last_reload
    -- janino_worker | 5 | 8 | 1234 | 15 | 2026-01-17 10:30:00
    

    9. Comparaison avec ScriptEngine

    Critère ScriptEngine JaninoEngine
    Langages JavaScript, BeanShell Java pur
    Exécution Interprétée Compilée (bytecode)
    Performance ~1000x plus lent Native JVM
    Typage Dynamique Statique
    IDE Support Limité Complet (Java)
    Debug Difficile Standard Java
    Hot-reload Non Oui
    Sécurité Sandbox complexe ClassLoader isolation
    Courbe apprentissage Nouveau langage Java existant

    Quand utiliser quoi ?

    Situation Recommandation
    Calculs critiques (frais, taxes) JaninoEngine
    Validations complexes JaninoEngine
    Scripts simples, one-liners ScriptEngine
    Prototypage rapide ScriptEngine
    Logique métier complexe JaninoEngine
    Transformations JSON basiques ScriptEngine

    10. Dépannage

    10.1 Script non compilé

    Erreur :

    IllegalStateException: Script not compiled: MyScript
    

    Solution :

    • Vérifier que le fichier existe dans scripts-path
    • Vérifier l’extension .java
    • Consulter les logs pour les erreurs de compilation

    10.2 Erreur de compilation

    Erreur :

    JaninoCompilationException: Failed to compile script: MyScript
    

    Solution :

    • Vérifier la syntaxe Java
    • Vérifier les imports
    • Vérifier que la classe implémente une interface valide

    10.3 Classe non trouvée

    Erreur :

    Cannot find class name in source
    

    Solution :

    • Le source doit contenir public class NomDeLaClasse
    • Le nom de la classe doit correspondre au nom du fichier

    10.4 Package bloque

    Erreur :

    JaninoCompilationException: Security violation in script 'MyScript':
    Import of blocked package 'java.io' is not allowed
    

    Solution :

    • Utiliser uniquement les packages autorises
    • Si necessaire, modifier la config blocked-packages

    10.5 Cannot load simple types (Fat-Jar Spring Boot)

    Erreur :

    org.codehaus.commons.compiler.CompileException: Cannot load simple types
    

    Cause : Ce probleme survient dans les fat-jars Spring Boot car le classloader personnalise casse la resolution des modules Java 9+.

    Solution : Cette erreur a ete corrigee dans le socle V4. Le JaninoEngine utilise maintenant le context classloader directement :

    // JaninoEngine.java - ligne 117-121
    ClassLoader contextLoader = Thread.currentThread().getContextClassLoader();
    if (contextLoader == null) {
        contextLoader = getClass().getClassLoader();
    }
    compiler.setParentClassLoader(contextLoader);
    

    Si vous rencontrez encore cette erreur, verifiez que vous utilisez la derniere version du socle.

    10.6 Assignment conversion not possible from Object

    Erreur :

    Line 35, Column 41: Assignment conversion not possible from type "java.lang.Object" to type "java.math.BigDecimal"
    

    Cause : Janino ne supporte pas l’inference de type pour Map.get().

    Solution : Ajouter un cast explicite :

    // AVANT (erreur)
    BigDecimal rate = myMap.get(key);
    
    // APRES (correct)
    BigDecimal rate = (BigDecimal) myMap.get(key);
    

    10.7 Invalid escape sequence

    Erreur :

    Line 27, Column 35: Invalid escape sequence
    

    Cause : Les sequences d’echappement regex (\s, \d, \{) doivent etre double-echappees.

    Solution :

    // AVANT (erreur)
    Pattern p = Pattern.compile("\s+");
    
    // APRES (correct)
    Pattern p = Pattern.compile("\\s+");
    

    10.8 Invocation of static interface methods

    Erreur :

    Invocation of static interface methods only available for target version 8+
    

    Cause : Janino ne supporte pas Map.of(), Set.of(), List.of() (Java 9+).

    Solution : Utiliser des blocs static :

    // AVANT (erreur)
    private static final Map<String, String> DATA = Map.of("a", "b");
    
    // APRES (correct)
    private static final Map<String, String> DATA = new HashMap<>();
    static {
        DATA.put("a", "b");
    }
    

    11. Bonnes Pratiques

    DO

    • Implémenter une des interfaces (Calculator, Executable, Validator)
    • Utiliser des types explicites (pas de var)
    • Gérer les exceptions dans le script
    • Tester les scripts avant déploiement
    • Utiliser des noms de classes descriptifs

    DON’T

    • Ne pas utiliser java.io, java.net, java.lang.reflect
    • Ne pas stocker d’état entre les exécutions (stateless)
    • Ne pas faire d’opérations bloquantes longues
    • Ne pas utiliser de dépendances externes non disponibles

    12. Limitations Janino et Compatibilite

    Janino est un compilateur Java simplifie qui ne supporte pas toutes les fonctionnalites du langage Java moderne. Cette section documente les limitations et les solutions.

    12.1 Fonctionnalites Non Supportees

    Fonctionnalite Version Java Statut Janino
    Methodes generiques <T> Java 5+ NON SUPPORTE
    Map.of(), Set.of(), List.of() Java 9+ NON SUPPORTE
    switch expressions Java 14+ NON SUPPORTE
    var (inference de type) Java 10+ NON SUPPORTE
    Records Java 16+ NON SUPPORTE
    Pattern matching Java 16+ NON SUPPORTE
    Text blocks """ Java 15+ NON SUPPORTE

    12.2 Solutions et Contournements

    A. Pas de methodes generiques

    // INTERDIT - Ne compile pas
    private <T extends Number> T extractValue(String json, String key, Class<T> type) {
        // ...
    }
    
    // CORRECT - Methodes specifiques par type
    private Integer extractIntValue(String json, String key) {
        // implementation pour Integer
    }
    
    private Double extractDoubleValue(String json, String key) {
        // implementation pour Double
    }
    

    B. Pas de Map.of() / Set.of() / List.of()

    // INTERDIT - Ne compile pas
    private static final Map<String, BigDecimal> RATES = Map.of(
        "FR", new BigDecimal("0.015"),
        "DE", new BigDecimal("0.018")
    );
    
    // CORRECT - Bloc static avec HashMap
    private static final Map<String, BigDecimal> RATES = new HashMap<>();
    static {
        RATES.put("FR", new BigDecimal("0.015"));
        RATES.put("DE", new BigDecimal("0.018"));
    }
    
    // CORRECT - Pour Set
    private static final Set<String> COUNTRIES = new HashSet<>();
    static {
        COUNTRIES.add("FR");
        COUNTRIES.add("DE");
    }
    

    C. Cast explicite pour Map.get()

    // INTERDIT - "Assignment conversion not possible from Object to BigDecimal"
    BigDecimal rate = RATES.get(country);
    
    // CORRECT - Cast explicite
    BigDecimal rate = (BigDecimal) RATES.get(country);
    if (rate == null) rate = BigDecimal.ZERO;
    

    D. Pas de switch expressions

    // INTERDIT - Ne compile pas
    String result = switch (status) {
        case "A" -> "Active";
        case "I" -> "Inactive";
        default -> "Unknown";
    };
    
    // CORRECT - Switch statement classique
    String result;
    switch (status) {
        case "A": result = "Active"; break;
        case "I": result = "Inactive"; break;
        default: result = "Unknown";
    }
    

    E. Double echappement des regex

    // INTERDIT - "Invalid escape sequence"
    Pattern p = Pattern.compile("\s+");
    Pattern p2 = Pattern.compile("\{.*\}");
    
    // CORRECT - Double echappement
    Pattern p = Pattern.compile("\\s+");
    Pattern p2 = Pattern.compile("\\{.*\\}");
    

    12.3 Template de Script Compatible

    Voici un template de script qui fonctionne avec Janino :

    import eu.lmvi.socle.janino.interfaces.Calculator;
    import java.math.BigDecimal;
    import java.math.RoundingMode;
    import java.util.Map;
    import java.util.HashMap;
    import java.util.Set;
    import java.util.HashSet;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class MyCalculator implements Calculator<BigDecimal> {
    
        // Collections statiques avec bloc static
        private static final Map<String, BigDecimal> RATES = new HashMap<>();
        private static final Set<String> VALID_CODES = new HashSet<>();
    
        static {
            RATES.put("A", new BigDecimal("0.10"));
            RATES.put("B", new BigDecimal("0.20"));
    
            VALID_CODES.add("X");
            VALID_CODES.add("Y");
        }
    
        @Override
        public BigDecimal calculate(Map<String, Object> context) {
            // Extraction avec cast explicite
            BigDecimal amount = extractAmount(context.get("amount"));
            String code = (String) context.get("code");
            if (code == null) code = "A";
    
            // Acces Map avec cast
            BigDecimal rate = (BigDecimal) RATES.get(code);
            if (rate == null) rate = new BigDecimal("0.15");
    
            return amount.multiply(rate).setScale(2, RoundingMode.HALF_UP);
        }
    
        // Methode d'extraction type-safe (pas de generiques)
        private BigDecimal extractAmount(Object value) {
            if (value == null) return BigDecimal.ZERO;
            if (value instanceof BigDecimal) return (BigDecimal) value;
            if (value instanceof Number) {
                return BigDecimal.valueOf(((Number) value).doubleValue());
            }
            try {
                return new BigDecimal(value.toString());
            } catch (NumberFormatException e) {
                return BigDecimal.ZERO;
            }
        }
    }
    

    12.4 Checklist de Compatibilite

    Avant de deployer un script Janino, verifiez :

    • [ ] Pas de <T> dans les signatures de methodes
    • [ ] Pas de Map.of(), Set.of(), List.of()
    • [ ] Pas de var pour les declarations
    • [ ] Pas de switch expressions (fleches ->)
    • [ ] Cast explicite (Type) pour tous les Map.get()
    • [ ] Double echappement \\ dans les regex
    • [ ] Pas de text blocks """
    • [ ] Imports explicites (pas de wildcards import java.util.*)

    13. Exemple Complet

    13.1 Script : TradingFeeCalculator.java

    import eu.lmvi.socle.janino.interfaces.Calculator;
    import java.math.BigDecimal;
    import java.math.RoundingMode;
    import java.util.Map;
    import java.util.HashMap;
    
    /**
     * Calculateur de frais de trading multi-exchange.
     * Compatible Janino (pas de switch expressions, pas de Map.of)
     */
    public class TradingFeeCalculator implements Calculator<BigDecimal> {
    
        // Taux MAKER par exchange
        private static final Map<String, BigDecimal> MAKER_RATES = new HashMap<>();
        // Taux TAKER par exchange
        private static final Map<String, BigDecimal> TAKER_RATES = new HashMap<>();
    
        static {
            MAKER_RATES.put("KRAKEN", new BigDecimal("0.0016"));
            MAKER_RATES.put("BINANCE", new BigDecimal("0.0010"));
            MAKER_RATES.put("COINBASE", new BigDecimal("0.0040"));
    
            TAKER_RATES.put("KRAKEN", new BigDecimal("0.0026"));
            TAKER_RATES.put("BINANCE", new BigDecimal("0.0010"));
            TAKER_RATES.put("COINBASE", new BigDecimal("0.0060"));
        }
    
        private static final BigDecimal DEFAULT_RATE = new BigDecimal("0.0025");
    
        @Override
        public BigDecimal calculate(Map<String, Object> context) {
            String exchange = (String) context.get("exchange");
            BigDecimal amount = (BigDecimal) context.get("amount");
            String side = (String) context.get("side");
    
            if (exchange == null) exchange = "DEFAULT";
            if (side == null) side = "TAKER";
    
            BigDecimal feeRate = getFeeRate(exchange.toUpperCase(), side.toUpperCase());
    
            return amount.multiply(feeRate).setScale(8, RoundingMode.HALF_UP);
        }
    
        private BigDecimal getFeeRate(String exchange, String side) {
            boolean isMaker = "MAKER".equals(side);
    
            // Cast explicite requis par Janino
            BigDecimal rate;
            if (isMaker) {
                rate = (BigDecimal) MAKER_RATES.get(exchange);
            } else {
                rate = (BigDecimal) TAKER_RATES.get(exchange);
            }
    
            if (rate == null) {
                rate = DEFAULT_RATE;
            }
            return rate;
        }
    }
    

    13.2 Worker utilisant le script

    Note : Ce Worker est du code Java standard compile par javac/Maven, pas un script Janino. Il peut donc utiliser List.of(), Map.of() et les fonctionnalites Java modernes.

    @Component
    public class FeeWorker implements Worker {
    
        private static final Logger log = LoggerFactory.getLogger(FeeWorker.class);
    
        @Autowired
        private JaninoWorker janinoWorker;
    
        @Override
        public String getName() {
            return "fee-worker";
        }
    
        @Override
        public void doWork() {
            // Calculer les frais pour différents exchanges
            List<String> exchanges = List.of("KRAKEN", "BINANCE", "COINBASE");
            BigDecimal amount = new BigDecimal("10000.00");
    
            for (String exchange : exchanges) {
                Map<String, Object> context = Map.of(
                    "exchange", exchange,
                    "amount", amount,
                    "side", "TAKER"
                );
    
                BigDecimal fee = janinoWorker.execute(
                    "TradingFeeCalculator",
                    context,
                    BigDecimal.class
                );
    
                log.info("Fee for {} on amount {}: {}",
                    exchange, amount, fee);
            }
        }
    
        // ... autres méthodes Worker
    }
    

    14. References

  • Socle V004 – Scheduler

    12 – Scheduler

    Version : 4.0.0 Date : 2025-12-09

    1. Introduction

    Le Scheduler permet d’exécuter des Workers selon des expressions cron ou à intervalles réguliers.

    Caractéristiques

    • Support des expressions cron standard
    • Exécution à intervalle fixe
    • Gestion du chevauchement
    • Intégration avec le MOP

    2. Configuration

    2.1 application.yml

    socle:
      scheduler:
        enabled: ${SCHEDULER_ENABLED:true}
        thread-pool-size: ${SCHEDULER_POOL_SIZE:4}
        default-timezone: ${SCHEDULER_TIMEZONE:Europe/Paris}
    

    2.2 Variables d’environnement

    Variable Description Défaut
    SCHEDULER_ENABLED Activer le scheduler true
    SCHEDULER_POOL_SIZE Taille du thread pool 4
    SCHEDULER_TIMEZONE Timezone par défaut Europe/Paris

    3. Types de scheduling

    3.1 Cron

    Expressions cron standard (6 champs) :

    ┌───────────── seconde (0-59)
    │ ┌───────────── minute (0-59)
    │ │ ┌───────────── heure (0-23)
    │ │ │ ┌───────────── jour du mois (1-31)
    │ │ │ │ ┌───────────── mois (1-12)
    │ │ │ │ │ ┌───────────── jour de la semaine (0-6, 0=dimanche)
    │ │ │ │ │ │
    * * * * * *
    

    Exemples :

    • 0 0 6 * * ? : Tous les jours à 6h00
    • 0 */15 * * * ? : Toutes les 15 minutes
    • 0 0 0 1 * ? : Premier jour de chaque mois à minuit
    • 0 30 8 ? * MON-FRI : 8h30 du lundi au vendredi

    3.2 Intervalle fixe

    Exécution périodique simple :

    @Override
    public long getCycleIntervalMs() {
        return 60000;  // Toutes les minutes
    }
    

    4. Worker schedulé

    4.1 Avec expression cron

    @Component
    public class DailyReportWorker implements Worker {
    
        private static final Logger log = LoggerFactory.getLogger(DailyReportWorker.class);
    
        @Override
        public String getName() {
            return "daily-report-worker";
        }
    
        @Override
        public String getSchedule() {
            return "0 0 6 * * ?";  // Tous les jours à 6h
        }
    
        @Override
        public boolean isScheduled() {
            return true;
        }
    
        @Override
        public void doWork() {
            log.info("Generating daily report...");
            generateReport();
        }
    
        private void generateReport() {
            // Génération du rapport
        }
    
        // Autres méthodes Worker...
    }
    

    4.2 Avec intervalle

    @Component
    public class HealthCheckWorker implements Worker {
    
        @Override
        public String getName() {
            return "health-check-worker";
        }
    
        @Override
        public String getSchedule() {
            return null;  // Pas de cron
        }
    
        @Override
        public boolean isScheduled() {
            return false;  // Pas schedulé par cron
        }
    
        @Override
        public long getCycleIntervalMs() {
            return 30000;  // Toutes les 30 secondes
        }
    
        @Override
        public void doWork() {
            checkHealth();
        }
    }
    

    5. Interface Scheduler

    package eu.lmvi.socle.scheduler;
    
    public interface Scheduler {
    
        /**
         * Planifie un job cron
         */
        void scheduleCron(String jobId, String cronExpression, Runnable task);
    
        /**
         * Planifie un job à intervalle fixe
         */
        void scheduleInterval(String jobId, long intervalMs, Runnable task);
    
        /**
         * Planifie un job à intervalle fixe avec délai initial
         */
        void scheduleInterval(String jobId, long initialDelayMs, long intervalMs, Runnable task);
    
        /**
         * Planifie un job one-shot
         */
        void scheduleOnce(String jobId, long delayMs, Runnable task);
    
        /**
         * Annule un job
         */
        void cancel(String jobId);
    
        /**
         * Vérifie si un job est planifié
         */
        boolean isScheduled(String jobId);
    
        /**
         * Liste les jobs planifiés
         */
        List<ScheduledJob> getScheduledJobs();
    
        /**
         * Démarre le scheduler
         */
        void start();
    
        /**
         * Arrête le scheduler
         */
        void stop();
    }
    

    6. Implémentation

    package eu.lmvi.socle.scheduler;
    
    @Component
    public class DefaultScheduler implements Scheduler {
    
        private static final Logger log = LoggerFactory.getLogger(DefaultScheduler.class);
    
        private final ScheduledExecutorService executor;
        private final ConcurrentHashMap<String, ScheduledFuture<?>> jobs = new ConcurrentHashMap<>();
        private final ConcurrentHashMap<String, ScheduledJob> jobInfo = new ConcurrentHashMap<>();
        private final ZoneId timezone;
    
        public DefaultScheduler(SocleConfiguration config) {
            int poolSize = config.getScheduler().getThreadPoolSize();
            this.executor = Executors.newScheduledThreadPool(poolSize,
                r -> new Thread(r, "scheduler-" + System.currentTimeMillis()));
            this.timezone = ZoneId.of(config.getScheduler().getDefaultTimezone());
        }
    
        @Override
        public void scheduleCron(String jobId, String cronExpression, Runnable task) {
            CronExpression cron = CronExpression.parse(cronExpression);
    
            Runnable scheduledTask = () -> {
                log.debug("Executing cron job: {}", jobId);
                try {
                    task.run();
                } catch (Exception e) {
                    log.error("Error executing job {}: {}", jobId, e.getMessage(), e);
                }
                // Replanifier la prochaine exécution
                scheduleNextCronExecution(jobId, cron, task);
            };
    
            scheduleNextCronExecution(jobId, cron, task);
    
            jobInfo.put(jobId, new ScheduledJob(jobId, "cron", cronExpression, null, Instant.now()));
            log.info("Scheduled cron job: {} with expression: {}", jobId, cronExpression);
        }
    
        private void scheduleNextCronExecution(String jobId, CronExpression cron, Runnable task) {
            ZonedDateTime now = ZonedDateTime.now(timezone);
            ZonedDateTime next = cron.next(now);
    
            if (next != null) {
                long delayMs = Duration.between(now, next).toMillis();
    
                ScheduledFuture<?> future = executor.schedule(() -> {
                    task.run();
                    scheduleNextCronExecution(jobId, cron, task);
                }, delayMs, TimeUnit.MILLISECONDS);
    
                jobs.put(jobId, future);
            }
        }
    
        @Override
        public void scheduleInterval(String jobId, long intervalMs, Runnable task) {
            scheduleInterval(jobId, 0, intervalMs, task);
        }
    
        @Override
        public void scheduleInterval(String jobId, long initialDelayMs, long intervalMs, Runnable task) {
            Runnable wrappedTask = () -> {
                log.debug("Executing interval job: {}", jobId);
                try {
                    task.run();
                } catch (Exception e) {
                    log.error("Error executing job {}: {}", jobId, e.getMessage(), e);
                }
            };
    
            ScheduledFuture<?> future = executor.scheduleAtFixedRate(
                wrappedTask, initialDelayMs, intervalMs, TimeUnit.MILLISECONDS);
    
            jobs.put(jobId, future);
            jobInfo.put(jobId, new ScheduledJob(jobId, "interval", null, intervalMs, Instant.now()));
    
            log.info("Scheduled interval job: {} every {}ms", jobId, intervalMs);
        }
    
        @Override
        public void scheduleOnce(String jobId, long delayMs, Runnable task) {
            ScheduledFuture<?> future = executor.schedule(() -> {
                log.debug("Executing one-shot job: {}", jobId);
                try {
                    task.run();
                } finally {
                    jobs.remove(jobId);
                    jobInfo.remove(jobId);
                }
            }, delayMs, TimeUnit.MILLISECONDS);
    
            jobs.put(jobId, future);
            jobInfo.put(jobId, new ScheduledJob(jobId, "once", null, delayMs, Instant.now()));
    
            log.info("Scheduled one-shot job: {} in {}ms", jobId, delayMs);
        }
    
        @Override
        public void cancel(String jobId) {
            ScheduledFuture<?> future = jobs.remove(jobId);
            if (future != null) {
                future.cancel(false);
                jobInfo.remove(jobId);
                log.info("Cancelled job: {}", jobId);
            }
        }
    
        @Override
        public boolean isScheduled(String jobId) {
            return jobs.containsKey(jobId);
        }
    
        @Override
        public List<ScheduledJob> getScheduledJobs() {
            return new ArrayList<>(jobInfo.values());
        }
    
        @Override
        public void start() {
            log.info("Scheduler started");
        }
    
        @Override
        public void stop() {
            log.info("Stopping scheduler...");
            jobs.values().forEach(f -> f.cancel(false));
            jobs.clear();
            executor.shutdown();
            try {
                if (!executor.awaitTermination(30, TimeUnit.SECONDS)) {
                    executor.shutdownNow();
                }
            } catch (InterruptedException e) {
                executor.shutdownNow();
                Thread.currentThread().interrupt();
            }
            log.info("Scheduler stopped");
        }
    }
    

    7. Gestion du chevauchement

    7.1 Éviter le chevauchement

    @Component
    public class LongRunningWorker implements Worker {
    
        private final AtomicBoolean running = new AtomicBoolean(false);
    
        @Override
        public void doWork() {
            // Éviter l'exécution concurrente
            if (!running.compareAndSet(false, true)) {
                log.warn("Previous execution still running, skipping");
                return;
            }
    
            try {
                doLongWork();
            } finally {
                running.set(false);
            }
        }
    
        private void doLongWork() {
            // Traitement long
        }
    }
    

    7.2 Avec verrou distribué (multi-instances)

    @Component
    public class DistributedScheduledWorker implements Worker {
    
        @Autowired
        private KvBus kvBus;
    
        @Override
        public void doWork() {
            String lockKey = "lock:job:" + getName();
    
            // Tenter d'acquérir le lock
            if (!kvBus.putIfAbsent(lockKey, "locked", Duration.ofMinutes(10))) {
                log.debug("Job already running on another instance");
                return;
            }
    
            try {
                executeJob();
            } finally {
                kvBus.delete(lockKey);
            }
        }
    }
    

    8. Intégration MOP

    Le MOP intègre automatiquement les workers schedulés :

    // Dans MainOrchestratorProcess
    private void startScheduledWorkers() {
        for (Worker worker : workers) {
            if (worker.isScheduled() && worker.getSchedule() != null) {
                scheduler.scheduleCron(
                    "worker:" + worker.getName(),
                    worker.getSchedule(),
                    () -> {
                        if (worker.isHealthy()) {
                            worker.doWork();
                        }
                    }
                );
            }
        }
    }
    

    9. API Admin

    @RestController
    @RequestMapping("/admin/scheduler")
    public class SchedulerController {
    
        @Autowired
        private Scheduler scheduler;
    
        @GetMapping("/jobs")
        public List<ScheduledJob> listJobs() {
            return scheduler.getScheduledJobs();
        }
    
        @PostMapping("/jobs/{jobId}/cancel")
        public ResponseEntity<Void> cancelJob(@PathVariable String jobId) {
            if (scheduler.isScheduled(jobId)) {
                scheduler.cancel(jobId);
                return ResponseEntity.ok().build();
            }
            return ResponseEntity.notFound().build();
        }
    
        @PostMapping("/jobs/{jobId}/trigger")
        public ResponseEntity<Void> triggerJob(@PathVariable String jobId) {
            // Exécution immédiate one-shot
            scheduler.scheduleOnce(jobId + "-manual-" + System.currentTimeMillis(), 0, () -> {
                // Trouver et exécuter le worker correspondant
            });
            return ResponseEntity.accepted().build();
        }
    }
    

    10. Expressions Cron communes

    Expression Description
    0 0 * * * ? Toutes les heures
    0 */15 * * * ? Toutes les 15 minutes
    0 0 6 * * ? Tous les jours à 6h
    0 0 0 * * ? Tous les jours à minuit
    0 0 0 * * SUN Tous les dimanches à minuit
    0 0 0 1 * ? Premier jour du mois
    0 0 8 ? * MON-FRI 8h en semaine
    0 0 */2 * * ? Toutes les 2 heures

    11. Bonnes pratiques

    DO

    • Utiliser des noms de jobs uniques et descriptifs
    • Gérer le chevauchement pour les jobs longs
    • Utiliser des locks distribués en multi-instances
    • Logger le début et la fin des jobs
    • Monitorer l’exécution des jobs

    DON’T

    • Ne pas planifier des jobs trop fréquents sans nécessité
    • Ne pas ignorer les erreurs dans les jobs
    • Ne pas créer trop de threads
    • Ne pas bloquer indéfiniment dans un job

    12. Références

  • Socle V004 – EventBus et Workers

    30 – EventBus et Workers Push

    Version : 4.1.0 Date : 2026-01-23 Statut : Specification

    1. Introduction

    Ce document introduit le nouveau systeme EventBus et les Workers Push dans le Socle V004. Ce mecanisme remplace avantageusement le polling par un systeme de notification instantanee.

    1.1 Motivation

    Le mecanisme actuel des workers event-driven (AbstractEventDrivenWorker) utilise un polling avec timeout :

    // Ancien mecanisme (DEPRECIE)
    while (running) {
        event = queue.poll(100, TimeUnit.MILLISECONDS);  // Verifie toutes les 100ms
        if (event != null) processEvent(event);
    }
    

    Problemes :

    • Latence de 0 a 100ms avant traitement
    • Consommation CPU constante (meme si faible)
    • Pas de vrai mecanisme push

    1.2 Nouveau mecanisme Push

    // Nouveau mecanisme (RECOMMANDE)
    while (running) {
        event = queue.take();  // Dort jusqu'a ce qu'un event arrive
        processEvent(event);   // Reveil instantane
    }
    

    Avantages :

    • Latence ~0ms (reveil instantane)
    • Zero CPU quand idle
    • Vrai mecanisme push event-driven

    2. Depreciation des anciens Workers

    2.1 Classes depreciees

    Classe Statut Remplacement
    AbstractEventDrivenWorker<T> DEPRECIE AbstractPushWorker<T>
    KafkaEventWorker<K,V> DEPRECIE KafkaPushWorker<K,V>

    2.2 Migration

    Les anciens workers continuent de fonctionner mais ne doivent plus etre utilises pour les nouveaux developpements.

    // DEPRECIE - Ne plus utiliser
    @Deprecated(since = "4.1.0", forRemoval = true)
    public abstract class AbstractEventDrivenWorker<T> implements Worker { ... }
    
    // RECOMMANDE - Utiliser ceci
    public abstract class AbstractPushWorker<T> implements Worker { ... }
    

    2.3 Calendrier de depreciation

    Version Action
    4.1.0 Introduction EventBus + Workers Push, depreciation des anciens
    4.2.0 Warnings de compilation pour les anciens workers
    5.0.0 Suppression des anciens workers (breaking change)

    3. Architecture EventBus

    3.1 Vue d’ensemble

    ┌─────────────────────────────────────────────────────────────────────┐
    │                              MOP                                     │
    │                                                                      │
    │  ┌──────────────────────────────────────────────────────────────┐   │
    │  │                        EventBus                               │   │
    │  │                                                               │   │
    │  │   Channels:                                                   │   │
    │  │     "orders.created"   ──► [Worker1.queue, Worker2.queue]     │   │
    │  │     "orders.updated"   ──► [Worker1.queue]                    │   │
    │  │     "alerts.*"         ──► [AlertWorker.queue]                │   │
    │  │                                                               │   │
    │  └──────────────────────────────────────────────────────────────┘   │
    │                              │                                       │
    │         publish("orders.created", event)                            │
    │                              │                                       │
    │                              ▼                                       │
    │  ┌────────────────┐  ┌────────────────┐  ┌────────────────┐        │
    │  │ PushWorker 1   │  │ PushWorker 2   │  │ PushWorker 3   │        │
    │  │                │  │                │  │                │        │
    │  │ queue.take()   │  │ queue.take()   │  │ queue.take()   │        │
    │  │ (dort)         │  │ (dort)         │  │ (dort)         │        │
    │  │      ↓         │  │      ↓         │  │                │        │
    │  │ REVEIL!        │  │ REVEIL!        │  │ (pas abonne)   │        │
    │  └────────────────┘  └────────────────┘  └────────────────┘        │
    │                                                                      │
    └─────────────────────────────────────────────────────────────────────┘
    

    3.2 Composants

    Composant Role
    EventBus Bus central de publication/souscription
    BusEvent<T> Enveloppe d’evenement avec metadata
    AbstractPushWorker<T> Worker reveille par EventBus
    KafkaPushWorker<K,V> Worker Kafka avec push interne
    EventBusWorker Worker qui gere le lifecycle de l’EventBus

    4. Interface EventBus

    4.1 Definition

    package eu.lmvi.socle.event;
    
    /**
     * Bus d'evenements central avec mecanisme push.
     *
     * <p>L'EventBus permet la communication entre workers via un systeme
     * de publication/souscription avec reveil instantane.</p>
     */
    public interface EventBus {
    
        // ==================== Publication ====================
    
        /**
         * Publie un evenement sur un channel.
         * Les subscribers sont reveilles instantanement.
         *
         * @param channel Nom du channel (ex: "orders.created")
         * @param payload Contenu de l'evenement
         */
        void publish(String channel, Object payload);
    
        /**
         * Publie un evenement avec metadata personnalisees.
         *
         * @param channel  Nom du channel
         * @param payload  Contenu de l'evenement
         * @param metadata Metadata additionnelles
         */
        void publish(String channel, Object payload, Map<String, String> metadata);
    
        /**
         * Publication asynchrone avec confirmation.
         *
         * @return Future completee quand tous les subscribers ont recu l'event
         */
        CompletableFuture<PublishResult> publishAsync(String channel, Object payload);
    
        // ==================== Souscription ====================
    
        /**
         * S'abonne a un channel et retourne une queue pour reception.
         * Utiliser queue.take() pour attendre les evenements (push).
         *
         * @param channel   Nom du channel
         * @param eventType Type attendu du payload
         * @return Queue sur laquelle faire take()
         */
        <T> Subscription<T> subscribe(String channel, Class<T> eventType);
    
        /**
         * S'abonne avec un pattern glob (ex: "orders.*", "*.created").
         *
         * @param pattern   Pattern glob
         * @param eventType Type attendu du payload
         * @return Subscription avec queue
         */
        <T> Subscription<T> subscribePattern(String pattern, Class<T> eventType);
    
        /**
         * S'abonne avec un handler callback (execution immediate).
         *
         * @param channel Nom du channel
         * @param handler Handler appele pour chaque evenement
         * @return ID de souscription pour unsubscribe
         */
        String subscribe(String channel, EventHandler handler);
    
        /**
         * Se desabonne.
         *
         * @param subscriptionId ID retourne par subscribe
         */
        void unsubscribe(String subscriptionId);
    
        // ==================== Lifecycle ====================
    
        /**
         * Demarre l'EventBus.
         */
        void start();
    
        /**
         * Arrete l'EventBus proprement.
         * Les queues sont videes, les subscribers notifies.
         */
        void stop();
    
        /**
         * Verifie la sante de l'EventBus.
         */
        boolean isHealthy();
    
        // ==================== Stats ====================
    
        /**
         * Statistiques globales.
         */
        EventBusStats getStats();
    
        /**
         * Statistiques par channel.
         */
        Map<String, ChannelStats> getChannelStats();
    }
    

    4.2 Classes de support

    package eu.lmvi.socle.event;
    
    /**
     * Evenement transporte par l'EventBus.
     */
    public record BusEvent<T>(
        String id,                      // UUID unique
        String channel,                 // Channel de publication
        Instant timestamp,              // Timestamp de publication
        String source,                  // Source (worker name)
        T payload,                      // Contenu metier
        Map<String, String> metadata    // Metadata additionnelles
    ) {
        /**
         * Cree un evenement simple.
         */
        public static <T> BusEvent<T> of(String channel, T payload) {
            return new BusEvent<>(
                UUID.randomUUID().toString(),
                channel,
                Instant.now(),
                null,
                payload,
                Map.of()
            );
        }
    }
    
    /**
     * Souscription a un channel.
     */
    public interface Subscription<T> {
    
        /**
         * ID unique de la souscription.
         */
        String getId();
    
        /**
         * Channel ou pattern souscrit.
         */
        String getChannelOrPattern();
    
        /**
         * Queue de reception des evenements.
         * Utiliser take() pour attendre (bloquant, reveil instantane).
         * Utiliser poll(timeout) si besoin d'un timeout.
         */
        BlockingQueue<BusEvent<T>> getQueue();
    
        /**
         * Se desabonner.
         */
        void unsubscribe();
    
        /**
         * Nombre d'evenements en attente dans la queue.
         */
        int getPendingCount();
    }
    
    /**
     * Handler pour souscription callback.
     */
    @FunctionalInterface
    public interface EventHandler {
        void onEvent(BusEvent<?> event);
    }
    
    /**
     * Resultat de publication.
     */
    public record PublishResult(
        String eventId,
        int deliveredCount,
        int failedCount,
        Duration duration
    ) {}
    
    /**
     * Statistiques EventBus.
     */
    public record EventBusStats(
        long totalPublished,
        long totalDelivered,
        long totalFailed,
        int activeSubscriptions,
        int activeChannels,
        Instant startedAt
    ) {}
    
    /**
     * Statistiques par channel.
     */
    public record ChannelStats(
        String channel,
        long publishedCount,
        int subscriberCount,
        long lastPublishedAt
    ) {}
    

    5. Implementations EventBus

    5.1 InMemoryEventBus

    Implementation pour mono-instance (dev, tests, applications simples).

    package eu.lmvi.socle.event.impl;
    
    @Component
    @ConditionalOnProperty(name = "socle.eventbus.mode", havingValue = "in_memory", matchIfMissing = true)
    public class InMemoryEventBus implements EventBus {
    
        private static final Logger log = LoggerFactory.getLogger(InMemoryEventBus.class);
    
        // Subscriptions par channel exact
        private final Map<String, Set<SubscriptionImpl<?>>> channelSubs = new ConcurrentHashMap<>();
    
        // Subscriptions par pattern
        private final Map<Pattern, Set<SubscriptionImpl<?>>> patternSubs = new ConcurrentHashMap<>();
    
        // Index pour lookup rapide
        private final Map<String, SubscriptionImpl<?>> subsIndex = new ConcurrentHashMap<>();
    
        // Compteurs
        private final AtomicLong idGen = new AtomicLong();
        private final AtomicLong publishedCount = new AtomicLong();
        private final AtomicLong deliveredCount = new AtomicLong();
        private final AtomicLong failedCount = new AtomicLong();
    
        // Etat
        private volatile boolean running = false;
        private Instant startedAt;
    
        // ==================== Lifecycle ====================
    
        @Override
        public void start() {
            running = true;
            startedAt = Instant.now();
            log.info("InMemoryEventBus started");
        }
    
        @Override
        public void stop() {
            running = false;
    
            // Notifier tous les subscribers (poison pill)
            for (SubscriptionImpl<?> sub : subsIndex.values()) {
                sub.notifyShutdown();
            }
    
            log.info("InMemoryEventBus stopped. Published={}, Delivered={}, Failed={}",
                publishedCount.get(), deliveredCount.get(), failedCount.get());
        }
    
        @Override
        public boolean isHealthy() {
            return running;
        }
    
        // ==================== Publish ====================
    
        @Override
        public void publish(String channel, Object payload) {
            publish(channel, payload, Map.of());
        }
    
        @Override
        public void publish(String channel, Object payload, Map<String, String> metadata) {
            if (!running) {
                log.warn("EventBus not running, event dropped on channel '{}'", channel);
                return;
            }
    
            BusEvent<?> event = new BusEvent<>(
                "evt-" + idGen.incrementAndGet(),
                channel,
                Instant.now(),
                resolveSource(),
                payload,
                metadata
            );
    
            int delivered = 0;
            int failed = 0;
    
            // Livraison aux subscriptions exactes
            Set<SubscriptionImpl<?>> exact = channelSubs.get(channel);
            if (exact != null) {
                for (SubscriptionImpl<?> sub : exact) {
                    if (deliverToSubscription(sub, event)) {
                        delivered++;
                    } else {
                        failed++;
                    }
                }
            }
    
            // Livraison aux subscriptions par pattern
            for (Map.Entry<Pattern, Set<SubscriptionImpl<?>>> entry : patternSubs.entrySet()) {
                if (entry.getKey().matcher(channel).matches()) {
                    for (SubscriptionImpl<?> sub : entry.getValue()) {
                        if (deliverToSubscription(sub, event)) {
                            delivered++;
                        } else {
                            failed++;
                        }
                    }
                }
            }
    
            publishedCount.incrementAndGet();
            deliveredCount.addAndGet(delivered);
            failedCount.addAndGet(failed);
    
            log.debug("Published event {} to channel '{}': delivered={}, failed={}",
                event.id(), channel, delivered, failed);
        }
    
        @Override
        public CompletableFuture<PublishResult> publishAsync(String channel, Object payload) {
            return CompletableFuture.supplyAsync(() -> {
                Instant start = Instant.now();
                publish(channel, payload);
                // Simplification: on ne trace pas le detail ici
                return new PublishResult(
                    "evt-" + idGen.get(),
                    1, 0,
                    Duration.between(start, Instant.now())
                );
            });
        }
    
        @SuppressWarnings("unchecked")
        private boolean deliverToSubscription(SubscriptionImpl<?> sub, BusEvent<?> event) {
            try {
                BlockingQueue<BusEvent<?>> queue = (BlockingQueue<BusEvent<?>>) sub.getQueue();
    
                // offer avec timeout pour eviter blocage infini
                boolean offered = queue.offer(event, 100, TimeUnit.MILLISECONDS);
    
                if (!offered) {
                    log.warn("Queue full for subscription {}, event dropped", sub.getId());
                    return false;
                }
    
                return true;
    
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return false;
            } catch (Exception e) {
                log.error("Error delivering to subscription {}: {}", sub.getId(), e.getMessage());
                return false;
            }
        }
    
        private String resolveSource() {
            // Recuperer le nom du worker courant si possible
            String threadName = Thread.currentThread().getName();
            return threadName;
        }
    
        // ==================== Subscribe ====================
    
        @Override
        public <T> Subscription<T> subscribe(String channel, Class<T> eventType) {
            String subId = "sub-" + idGen.incrementAndGet();
            SubscriptionImpl<T> sub = new SubscriptionImpl<>(subId, channel, null, this);
    
            channelSubs
                .computeIfAbsent(channel, k -> ConcurrentHashMap.newKeySet())
                .add(sub);
    
            subsIndex.put(subId, sub);
    
            log.info("Subscription {} created on channel '{}'", subId, channel);
            return sub;
        }
    
        @Override
        public <T> Subscription<T> subscribePattern(String pattern, Class<T> eventType) {
            String subId = "sub-" + idGen.incrementAndGet();
    
            // Convertir glob en regex
            String regex = pattern
                .replace(".", "\\.")
                .replace("*", "[^.]*")
                .replace(">", ".*");
            Pattern compiled = Pattern.compile("^" + regex + "$");
    
            SubscriptionImpl<T> sub = new SubscriptionImpl<>(subId, pattern, compiled, this);
    
            patternSubs
                .computeIfAbsent(compiled, k -> ConcurrentHashMap.newKeySet())
                .add(sub);
    
            subsIndex.put(subId, sub);
    
            log.info("Subscription {} created on pattern '{}'", subId, pattern);
            return sub;
        }
    
        @Override
        public String subscribe(String channel, EventHandler handler) {
            // Implementation simplifiee: on cree une subscription normale
            // et un thread qui consomme et appelle le handler
            Subscription<Object> sub = subscribe(channel, Object.class);
    
            Thread.ofVirtual()
                .name("handler-" + sub.getId())
                .start(() -> {
                    while (running) {
                        try {
                            BusEvent<Object> event = sub.getQueue().take();
                            if (event.payload() == null) break; // Poison pill
                            handler.onEvent(event);
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                            break;
                        } catch (Exception e) {
                            log.error("Handler error on {}: {}", channel, e.getMessage());
                        }
                    }
                });
    
            return sub.getId();
        }
    
        @Override
        public void unsubscribe(String subscriptionId) {
            SubscriptionImpl<?> sub = subsIndex.remove(subscriptionId);
            if (sub == null) {
                log.warn("Subscription {} not found", subscriptionId);
                return;
            }
    
            // Retirer des maps
            if (sub.pattern == null) {
                Set<SubscriptionImpl<?>> subs = channelSubs.get(sub.channelOrPattern);
                if (subs != null) subs.remove(sub);
            } else {
                Set<SubscriptionImpl<?>> subs = patternSubs.get(sub.pattern);
                if (subs != null) subs.remove(sub);
            }
    
            sub.notifyShutdown();
            log.info("Subscription {} removed", subscriptionId);
        }
    
        // ==================== Stats ====================
    
        @Override
        public EventBusStats getStats() {
            return new EventBusStats(
                publishedCount.get(),
                deliveredCount.get(),
                failedCount.get(),
                subsIndex.size(),
                channelSubs.size(),
                startedAt
            );
        }
    
        @Override
        public Map<String, ChannelStats> getChannelStats() {
            Map<String, ChannelStats> stats = new HashMap<>();
    
            for (Map.Entry<String, Set<SubscriptionImpl<?>>> entry : channelSubs.entrySet()) {
                stats.put(entry.getKey(), new ChannelStats(
                    entry.getKey(),
                    0, // TODO: compteur par channel
                    entry.getValue().size(),
                    0
                ));
            }
    
            return stats;
        }
    
        // ==================== Subscription Implementation ====================
    
        private static class SubscriptionImpl<T> implements Subscription<T> {
    
            private final String id;
            private final String channelOrPattern;
            private final Pattern pattern;
            private final BlockingQueue<BusEvent<T>> queue;
            private final InMemoryEventBus bus;
    
            SubscriptionImpl(String id, String channelOrPattern, Pattern pattern, InMemoryEventBus bus) {
                this.id = id;
                this.channelOrPattern = channelOrPattern;
                this.pattern = pattern;
                this.queue = new LinkedBlockingQueue<>(10_000); // Capacite par defaut
                this.bus = bus;
            }
    
            @Override
            public String getId() {
                return id;
            }
    
            @Override
            public String getChannelOrPattern() {
                return channelOrPattern;
            }
    
            @Override
            public BlockingQueue<BusEvent<T>> getQueue() {
                return queue;
            }
    
            @Override
            public void unsubscribe() {
                bus.unsubscribe(id);
            }
    
            @Override
            public int getPendingCount() {
                return queue.size();
            }
    
            void notifyShutdown() {
                // Injecter un poison pill pour debloquer les take()
                try {
                    queue.offer(new BusEvent<>(null, null, null, null, null, null));
                } catch (Exception ignored) {}
            }
        }
    }
    

    5.2 RedisEventBus

    Implementation pour multi-instances (production).

    package eu.lmvi.socle.event.impl;
    
    @Component
    @ConditionalOnProperty(name = "socle.eventbus.mode", havingValue = "redis")
    public class RedisEventBus implements EventBus {
    
        private final JedisPool jedisPool;
        private final ObjectMapper mapper;
        private final String prefix;
        private final ExecutorService listenerExecutor;
    
        // Subscriptions locales (une queue locale par subscription)
        private final Map<String, LocalSubscription<?>> localSubs = new ConcurrentHashMap<>();
    
        // JedisPubSub par channel (partage entre subscriptions locales)
        private final Map<String, RedisPubSubListener> redisListeners = new ConcurrentHashMap<>();
    
        // ... Implementation similaire avec Redis Pub/Sub ...
    
        @Override
        public void publish(String channel, Object payload) {
            try (Jedis jedis = jedisPool.getResource()) {
                BusEvent<?> event = BusEvent.of(channel, payload);
                String json = mapper.writeValueAsString(event);
                jedis.publish(prefix + channel, json);
            } catch (Exception e) {
                log.error("Redis publish error: {}", e.getMessage());
            }
        }
    
        // Redis SUBSCRIBE dans un thread dedie
        // Dispatch vers les queues locales
    }
    

    6. AbstractPushWorker

    6.1 Definition

    package eu.lmvi.socle.worker.push;
    
    /**
     * Worker reveille instantanement par l'EventBus.
     *
     * <p>Contrairement a {@link AbstractEventDrivenWorker} (DEPRECIE) qui utilise
     * un polling avec timeout, ce worker utilise un mecanisme push avec reveil
     * instantane via {@link BlockingQueue#take()}.</p>
     *
     * <h3>Avantages</h3>
     * <ul>
     *   <li>Latence ~0ms (reveil instantane)</li>
     *   <li>Zero CPU quand idle</li>
     *   <li>Integration native avec EventBus</li>
     * </ul>
     *
     * <h3>Exemple d'utilisation</h3>
     * <pre>{@code
     * @Component
     * public class OrderWorker extends AbstractPushWorker<OrderEvent> {
     *
     *     public OrderWorker() {
     *         super("orders.created", "orders.updated");
     *     }
     *
     *     @Override
     *     public String getName() {
     *         return "order_worker";
     *     }
     *
     *     @Override
     *     protected Class<OrderEvent> getEventType() {
     *         return OrderEvent.class;
     *     }
     *
     *     @Override
     *     protected void processEvent(OrderEvent event) {
     *         // Traitement instantane des que l'event arrive
     *     }
     * }
     * }</pre>
     *
     * @param <T> Type du payload des evenements
     */
    public abstract class AbstractPushWorker<T> implements Worker {
    
        protected final Logger logger = LoggerFactory.getLogger(getClass());
    
        // ==================== Injection ====================
    
        @Autowired
        protected EventBus eventBus;
    
        // ==================== Configuration ====================
    
        private final String[] channels;
        private final int concurrency;
        private final int queueCapacity;
        private final Duration shutdownTimeout;
    
        // ==================== Etat ====================
    
        protected final AtomicBoolean running = new AtomicBoolean(false);
        protected ExecutorService executor;
        protected List<Subscription<T>> subscriptions = new ArrayList<>();
        protected BlockingQueue<BusEvent<T>> mergedQueue;
    
        // ==================== Metriques ====================
    
        protected final AtomicLong processedCount = new AtomicLong(0);
        protected final AtomicLong errorCount = new AtomicLong(0);
        protected final AtomicLong totalDurationNs = new AtomicLong(0);
        protected volatile Instant lastExecution;
        protected volatile Instant startedAt;
    
        // ==================== Constructeurs ====================
    
        /**
         * Cree un worker push mono-thread.
         *
         * @param channels Channels a ecouter
         */
        protected AbstractPushWorker(String... channels) {
            this(1, channels);
        }
    
        /**
         * Cree un worker push avec concurrence.
         *
         * @param concurrency Nombre de threads de traitement
         * @param channels    Channels a ecouter
         */
        protected AbstractPushWorker(int concurrency, String... channels) {
            this(concurrency, 10_000, Duration.ofSeconds(30), channels);
        }
    
        /**
         * Cree un worker push avec configuration complete.
         *
         * @param concurrency     Nombre de threads de traitement
         * @param queueCapacity   Capacite de la queue interne
         * @param shutdownTimeout Timeout d'arret gracieux
         * @param channels        Channels a ecouter
         */
        protected AbstractPushWorker(int concurrency, int queueCapacity,
                                      Duration shutdownTimeout, String... channels) {
            this.concurrency = Math.max(1, concurrency);
            this.queueCapacity = queueCapacity;
            this.shutdownTimeout = shutdownTimeout;
            this.channels = channels;
    
            if (channels == null || channels.length == 0) {
                throw new IllegalArgumentException("At least one channel is required");
            }
        }
    
        // ==================== Worker Interface ====================
    
        @Override
        public final String getSchedule() {
            return "PUSH";
        }
    
        @Override
        public final long getCycleIntervalMs() {
            return -1;
        }
    
        @Override
        public final boolean isPassive() {
            return true;
        }
    
        @Override
        public int getStartPriority() {
            return 200;  // Apres l'EventBus (100)
        }
    
        @Override
        public int getStopPriority() {
            return 200;  // Avant l'EventBus
        }
    
        @Override
        public void initialize() {
            logger.info("[{}] Initializing push worker", getName());
            logger.info("[{}] Channels: {}", getName(), Arrays.toString(channels));
            logger.info("[{}] Concurrency: {}", getName(), concurrency);
    
            // Queue fusionnee pour tous les channels
            mergedQueue = new LinkedBlockingQueue<>(queueCapacity);
    
            onInitialize();
        }
    
        @Override
        public void start() {
            if (running.getAndSet(true)) {
                logger.warn("[{}] Already running", getName());
                return;
            }
    
            startedAt = Instant.now();
    
            // S'abonner aux channels
            for (String channel : channels) {
                if (channel.contains("*") || channel.contains(">")) {
                    // Pattern subscription
                    Subscription<T> sub = eventBus.subscribePattern(channel, getEventType());
                    subscriptions.add(sub);
                    startForwarder(sub);
                } else {
                    // Exact subscription
                    Subscription<T> sub = eventBus.subscribe(channel, getEventType());
                    subscriptions.add(sub);
                    startForwarder(sub);
                }
            }
    
            // Demarrer les workers de traitement
            executor = Executors.newThreadPerTaskExecutor(
                Thread.ofVirtual().name(getName() + "-push-", 0).factory()
            );
    
            for (int i = 0; i < concurrency; i++) {
                final int workerId = i;
                executor.submit(() -> pushLoop(workerId));
            }
    
            onStarted();
            logger.info("[{}] Started with {} workers on {} channels",
                getName(), concurrency, channels.length);
        }
    
        /**
         * Demarre un thread qui forward les events d'une subscription vers la queue fusionnee.
         */
        private void startForwarder(Subscription<T> sub) {
            Thread.ofVirtual()
                .name(getName() + "-fwd-" + sub.getId())
                .start(() -> {
                    while (running.get()) {
                        try {
                            BusEvent<T> event = sub.getQueue().take();
    
                            // Verifier poison pill
                            if (event.id() == null) break;
    
                            // Forward vers la queue fusionnee
                            if (!mergedQueue.offer(event, 1, TimeUnit.SECONDS)) {
                                logger.warn("[{}] Merged queue full, event dropped", getName());
                            }
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                            break;
                        }
                    }
                });
        }
    
        @Override
        public void stop() {
            if (!running.getAndSet(false)) {
                logger.warn("[{}] Not running", getName());
                return;
            }
    
            logger.info("[{}] Stopping...", getName());
            onStopping();
    
            // Se desabonner (injecte des poison pills)
            for (Subscription<T> sub : subscriptions) {
                try {
                    sub.unsubscribe();
                } catch (Exception e) {
                    logger.warn("[{}] Error unsubscribing: {}", getName(), e.getMessage());
                }
            }
            subscriptions.clear();
    
            // Injecter poison pills dans la queue fusionnee
            for (int i = 0; i < concurrency; i++) {
                mergedQueue.offer(new BusEvent<>(null, null, null, null, null, null));
            }
    
            // Attendre la fin des workers
            if (executor != null) {
                executor.shutdown();
                try {
                    if (!executor.awaitTermination(shutdownTimeout.toMillis(), TimeUnit.MILLISECONDS)) {
                        logger.warn("[{}] Forcing shutdown", getName());
                        executor.shutdownNow();
                    }
                } catch (InterruptedException e) {
                    executor.shutdownNow();
                    Thread.currentThread().interrupt();
                }
            }
    
            onStopped();
    
            long uptime = Duration.between(startedAt, Instant.now()).toSeconds();
            logger.info("[{}] Stopped after {}s. Processed={}, Errors={}",
                getName(), uptime, processedCount.get(), errorCount.get());
        }
    
        @Override
        public void doWork() {
            // Non utilise en mode PUSH
        }
    
        @Override
        public boolean isHealthy() {
            return running.get() && executor != null && !executor.isShutdown();
        }
    
        @Override
        public Map<String, Object> getStats() {
            long uptime = startedAt != null
                ? Duration.between(startedAt, Instant.now()).toMillis()
                : 0;
    
            double avgDurationMs = processedCount.get() > 0
                ? (totalDurationNs.get() / 1_000_000.0) / processedCount.get()
                : 0;
    
            double throughput = uptime > 0
                ? processedCount.get() * 1000.0 / uptime
                : 0;
    
            Map<String, Object> stats = new HashMap<>();
    
            // Cles standardisees
            stats.put("state", running.get() ? "running" : "stopped");
            stats.put("schedule", "PUSH");
            stats.put("execution_count", processedCount.get());
            stats.put("errors_count", errorCount.get());
            stats.put("last_execution", lastExecution != null ? lastExecution.toString() : null);
    
            // Cles specifiques
            stats.put("channels", channels);
            stats.put("concurrency", concurrency);
            stats.put("queue_size", mergedQueue != null ? mergedQueue.size() : 0);
            stats.put("queue_capacity", queueCapacity);
            stats.put("uptime_ms", uptime);
            stats.put("avg_duration_ms", Math.round(avgDurationMs * 100) / 100.0);
            stats.put("throughput_per_sec", Math.round(throughput * 100) / 100.0);
    
            // Stats des subscriptions
            stats.put("subscriptions", subscriptions.stream()
                .map(s -> Map.of(
                    "id", s.getId(),
                    "channel", s.getChannelOrPattern(),
                    "pending", s.getPendingCount()
                ))
                .toList());
    
            return stats;
        }
    
        // ==================== Push Loop ====================
    
        private void pushLoop(int workerId) {
            logger.debug("[{}] Push loop #{} started", getName(), workerId);
    
            while (running.get()) {
                try {
                    // BLOQUE jusqu'a reception d'un event (reveil instantane)
                    BusEvent<T> event = mergedQueue.take();
    
                    // Verifier poison pill
                    if (event.id() == null) {
                        logger.debug("[{}] Push loop #{} received shutdown signal", getName(), workerId);
                        break;
                    }
    
                    // Traiter l'event
                    processEventSafe(event, workerId);
    
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    logger.debug("[{}] Push loop #{} interrupted", getName(), workerId);
                    break;
                } catch (Exception e) {
                    logger.error("[{}] Unexpected error in push loop #{}: {}",
                        getName(), workerId, e.getMessage(), e);
                }
            }
    
            logger.debug("[{}] Push loop #{} stopped", getName(), workerId);
        }
    
        private void processEventSafe(BusEvent<T> event, int workerId) {
            long startNs = System.nanoTime();
    
            try {
                processEvent(event.payload(), event);
                processedCount.incrementAndGet();
            } catch (Exception e) {
                errorCount.incrementAndGet();
                handleError(event, e, workerId);
            } finally {
                long durationNs = System.nanoTime() - startNs;
                totalDurationNs.addAndGet(durationNs);
                lastExecution = Instant.now();
            }
        }
    
        // ==================== Methodes abstraites ====================
    
        /**
         * Type du payload des evenements.
         * Utilise pour le typage de la souscription.
         */
        protected abstract Class<T> getEventType();
    
        /**
         * Traite un evenement.
         *
         * @param payload Contenu de l'evenement
         * @param event   Evenement complet (avec metadata)
         */
        protected abstract void processEvent(T payload, BusEvent<T> event);
    
        /**
         * Version simplifiee sans acces a l'enveloppe.
         * Surcharger processEvent(T, BusEvent) pour avoir acces aux metadata.
         */
        protected void processEvent(T payload) {
            // Par defaut, appelle la version complete
        }
    
        // ==================== Hooks ====================
    
        /**
         * Hook d'initialisation.
         */
        protected void onInitialize() {}
    
        /**
         * Hook post-demarrage.
         */
        protected void onStarted() {}
    
        /**
         * Hook pre-arret.
         */
        protected void onStopping() {}
    
        /**
         * Hook post-arret.
         */
        protected void onStopped() {}
    
        /**
         * Gestion des erreurs.
         * Par defaut, log l'erreur. Surcharger pour DLQ, retry, etc.
         */
        protected void handleError(BusEvent<T> event, Exception e, int workerId) {
            logger.error("[{}] Worker #{} error processing event {}: {}",
                getName(), workerId, event.id(), e.getMessage(), e);
        }
    
        // ==================== Utilitaires ====================
    
        /**
         * Publie un evenement sur l'EventBus.
         * Raccourci pratique pour les workers qui produisent aussi des events.
         */
        protected void publish(String channel, Object payload) {
            eventBus.publish(channel, payload);
        }
    
        /**
         * Retourne le nombre d'evenements en attente.
         */
        public long getBacklog() {
            int pending = mergedQueue != null ? mergedQueue.size() : 0;
            for (Subscription<T> sub : subscriptions) {
                pending += sub.getPendingCount();
            }
            return pending;
        }
    }
    

    6.2 Version simplifiee (single channel)

    /**
     * Version simplifiee pour un seul channel.
     */
    public abstract class SimplePushWorker<T> extends AbstractPushWorker<T> {
    
        protected SimplePushWorker(String channel) {
            super(channel);
        }
    
        protected SimplePushWorker(int concurrency, String channel) {
            super(concurrency, channel);
        }
    
        @Override
        protected void processEvent(T payload, BusEvent<T> event) {
            processEvent(payload);
        }
    
        /**
         * Traite le payload directement.
         */
        protected abstract void processEvent(T payload);
    }
    

    7. Configuration

    7.1 application.yml

    socle:
      eventbus:
        # Activer l'EventBus
        enabled: ${EVENTBUS_ENABLED:true}
    
        # Mode: in_memory | redis
        mode: ${EVENTBUS_MODE:in_memory}
    
        # Configuration commune
        common:
          # Capacite par defaut des queues de subscription
          default_queue_capacity: ${EVENTBUS_QUEUE_CAPACITY:10000}
    
          # Timeout pour offer() quand queue pleine
          offer_timeout_ms: ${EVENTBUS_OFFER_TIMEOUT:100}
    
        # Configuration InMemory
        in_memory:
          # Rien de special
    
        # Configuration Redis
        redis:
          host: ${REDIS_HOST:localhost}
          port: ${REDIS_PORT:6379}
          password: ${REDIS_PASSWORD:}
          database: ${REDIS_DATABASE:0}
          prefix: ${EVENTBUS_REDIS_PREFIX:socle:eventbus}
    
          # Pool de connexions
          pool:
            max_total: ${EVENTBUS_REDIS_POOL_MAX:16}
            max_idle: ${EVENTBUS_REDIS_POOL_MAX_IDLE:8}
            min_idle: ${EVENTBUS_REDIS_POOL_MIN_IDLE:2}
    
        # Metriques
        metrics:
          enabled: ${EVENTBUS_METRICS_ENABLED:true}
          prefix: socle_eventbus
    

    7.2 Variables d’environnement

    Variable Description Defaut
    EVENTBUS_ENABLED Activer l’EventBus true
    EVENTBUS_MODE Mode (in_memory / redis) in_memory
    EVENTBUS_QUEUE_CAPACITY Capacite des queues 10000
    REDIS_HOST Host Redis localhost
    REDIS_PORT Port Redis 6379

    8. Exemples d’utilisation

    8.1 Worker simple

    @Component
    public class OrderNotificationWorker extends SimplePushWorker<OrderEvent> {
    
        @Autowired
        private NotificationService notificationService;
    
        public OrderNotificationWorker() {
            super(2, "orders.created");  // 2 workers concurrents
        }
    
        @Override
        public String getName() {
            return "order_notification_worker";
        }
    
        @Override
        protected Class<OrderEvent> getEventType() {
            return OrderEvent.class;
        }
    
        @Override
        protected void processEvent(OrderEvent event) {
            notificationService.notifyOrderCreated(event.orderId(), event.customerEmail());
        }
    }
    

    8.2 Worker multi-channels

    @Component
    public class AuditWorker extends AbstractPushWorker<Object> {
    
        @Autowired
        private AuditRepository auditRepository;
    
        public AuditWorker() {
            super(4, "orders.*", "payments.*", "users.*");  // Pattern matching
        }
    
        @Override
        public String getName() {
            return "audit_worker";
        }
    
        @Override
        protected Class<Object> getEventType() {
            return Object.class;  // Accepte tout
        }
    
        @Override
        protected void processEvent(Object payload, BusEvent<Object> event) {
            // Acces aux metadata
            AuditEntry entry = new AuditEntry(
                event.id(),
                event.channel(),
                event.timestamp(),
                event.source(),
                payload
            );
            auditRepository.save(entry);
        }
    }
    

    8.3 Publication d’evenements

    @Service
    public class OrderService {
    
        @Autowired
        private EventBus eventBus;
    
        @Autowired
        private OrderRepository orderRepository;
    
        public Order createOrder(CreateOrderRequest request) {
            // Logique metier
            Order order = orderRepository.save(new Order(request));
    
            // Publication sur l'EventBus
            // Tous les workers abonnes a "orders.created" sont reveilles instantanement
            eventBus.publish("orders.created", new OrderEvent(
                order.getId(),
                order.getCustomerEmail(),
                order.getTotal()
            ));
    
            return order;
        }
    
        public void updateOrderStatus(String orderId, OrderStatus newStatus) {
            Order order = orderRepository.updateStatus(orderId, newStatus);
    
            eventBus.publish("orders.updated", new OrderStatusEvent(
                orderId,
                newStatus
            ));
        }
    }
    

    8.4 Worker avec gestion d’erreur personnalisee

    @Component
    public class PaymentWorker extends AbstractPushWorker<PaymentEvent> {
    
        @Autowired
        private PaymentService paymentService;
    
        @Autowired
        private DeadLetterQueue dlq;
    
        public PaymentWorker() {
            super(2, "payments.process");
        }
    
        @Override
        public String getName() {
            return "payment_worker";
        }
    
        @Override
        protected Class<PaymentEvent> getEventType() {
            return PaymentEvent.class;
        }
    
        @Override
        protected void processEvent(PaymentEvent payload, BusEvent<PaymentEvent> event) {
            paymentService.processPayment(payload);
        }
    
        @Override
        protected void handleError(BusEvent<PaymentEvent> event, Exception e, int workerId) {
            logger.error("[{}] Payment processing failed for {}: {}",
                getName(), event.payload().paymentId(), e.getMessage());
    
            // Envoyer en DLQ pour retry ulterieur
            dlq.send("payments.dlq", event, e);
        }
    }
    

    9. Solutions aux questions ouvertes

    9.1 Arret propre des workers en take()

    Probleme : BlockingQueue.take() bloque indefiniment. Comment arreter proprement ?

    Solution : Poison Pill Pattern

    // A l'arret, injecter un evenement "poison" reconnaissable
    @Override
    public void stop() {
        running.set(false);
    
        // Injecter N poison pills (un par worker)
        for (int i = 0; i < concurrency; i++) {
            queue.offer(new BusEvent<>(null, null, null, null, null, null));
        }
    }
    
    // Dans la boucle, verifier le poison
    private void pushLoop(int workerId) {
        while (running.get()) {
            BusEvent<T> event = queue.take();
    
            // Detecter le poison pill (id == null)
            if (event.id() == null) {
                break;  // Sortir proprement
            }
    
            processEvent(event);
        }
    }
    

    9.2 Backpressure (queue bornee vs illimitee)

    Probleme : Que faire si les events arrivent plus vite qu’ils ne sont traites ?

    Solution : Queue bornee avec politique de debordement

    // Queue bornee (recommande)
    BlockingQueue<BusEvent<T>> queue = new LinkedBlockingQueue<>(10_000);
    
    // Lors du publish, gerer le debordement
    private boolean deliver(Subscription sub, BusEvent event) {
        // offer() avec timeout - ne bloque pas indefiniment
        boolean offered = queue.offer(event, 100, TimeUnit.MILLISECONDS);
    
        if (!offered) {
            // Politique de debordement:
            // Option 1: Drop (log + metrique)
            log.warn("Queue full, event dropped");
            droppedCount.incrementAndGet();
    
            // Option 2: Envoyer en DLQ
            dlq.send("overflow", event);
    
            // Option 3: Alerter
            alertService.queueOverflow(sub.getId());
        }
    
        return offered;
    }
    

    Metriques a surveiller :

    • socle_eventbus_queue_size : Taille actuelle
    • socle_eventbus_queue_capacity : Capacite max
    • socle_eventbus_dropped_total : Events perdus

    9.3 Multi-channel avec une seule queue

    Probleme : Un worker ecoute plusieurs channels, comment fusionner ?

    Solution : Queue fusionnee avec forwarders

    // Queue fusionnee
    BlockingQueue<BusEvent<T>> mergedQueue = new LinkedBlockingQueue<>();
    
    // Un forwarder par subscription
    for (String channel : channels) {
        Subscription<T> sub = eventBus.subscribe(channel, eventType);
    
        // Thread qui forward vers la queue fusionnee
        Thread.ofVirtual().start(() -> {
            while (running.get()) {
                BusEvent<T> event = sub.getQueue().take();
                mergedQueue.offer(event);
            }
        });
    }
    
    // Les workers consomment la queue fusionnee
    void pushLoop() {
        while (running.get()) {
            BusEvent<T> event = mergedQueue.take();
            // event.channel() permet de savoir d'ou il vient
            processEvent(event);
        }
    }
    

    9.4 Ordre des evenements

    Probleme : Les evenements doivent-ils etre traites dans l’ordre ?

    Solution : Depends du cas d’usage

    Mode Garantie Implementation
    Aucune Pas d’ordre garanti Concurrency > 1
    Par channel Ordre par channel Concurrency = 1 par channel
    Par cle Ordre par cle metier Partitioning sur la cle
    // Pour garantir l'ordre par cle (ex: par orderId)
    public class OrderedPushWorker extends AbstractPushWorker<OrderEvent> {
    
        // Une queue par partition (hash de la cle)
        private final BlockingQueue<BusEvent<OrderEvent>>[] partitionQueues;
        private final int partitions = 8;
    
        @Override
        protected void processEvent(OrderEvent payload, BusEvent<OrderEvent> event) {
            // Le hash garantit que les events du meme orderId vont dans la meme partition
            int partition = Math.abs(payload.orderId().hashCode()) % partitions;
            partitionQueues[partition].offer(event);
        }
    
        // Un worker par partition = ordre garanti par partition
    }
    

    9.5 Retry et DLQ

    Probleme : Que faire si le traitement echoue ?

    Solution : Retry avec backoff puis DLQ

    @Component
    public class ResilientPushWorker extends AbstractPushWorker<MyEvent> {
    
        @Autowired
        private EventBus eventBus;
    
        private static final int MAX_RETRIES = 3;
    
        @Override
        protected void processEvent(MyEvent payload, BusEvent<MyEvent> event) {
            int retryCount = getRetryCount(event);
    
            try {
                doProcess(payload);
            } catch (RetryableException e) {
                if (retryCount < MAX_RETRIES) {
                    // Re-publier avec retry count incremente
                    scheduleRetry(event, retryCount + 1);
                } else {
                    // Max retries atteint -> DLQ
                    sendToDlq(event, e);
                }
            }
        }
    
        private void scheduleRetry(BusEvent<MyEvent> event, int retryCount) {
            // Backoff exponentiel
            long delayMs = (long) Math.pow(2, retryCount) * 1000;
    
            // Re-publier apres le delai
            scheduler.schedule(() -> {
                Map<String, String> metadata = new HashMap<>(event.metadata());
                metadata.put("retry_count", String.valueOf(retryCount));
                eventBus.publish(event.channel(), event.payload(), metadata);
            }, delayMs, TimeUnit.MILLISECONDS);
        }
    
        private int getRetryCount(BusEvent<MyEvent> event) {
            return Integer.parseInt(event.metadata().getOrDefault("retry_count", "0"));
        }
    
        private void sendToDlq(BusEvent<MyEvent> event, Exception e) {
            eventBus.publish("dlq." + event.channel(), new DlqEntry(event, e));
        }
    }
    

    10. Migration des workers existants

    10.1 Avant (AbstractEventDrivenWorker)

    // DEPRECIE
    @Component
    public class OldOrderWorker extends AbstractEventDrivenWorker<OrderEvent> {
    
        private final BlockingQueue<OrderEvent> queue = new LinkedBlockingQueue<>();
    
        public OldOrderWorker() {
            super(4);
        }
    
        @Override
        public String getName() {
            return "order_worker";
        }
    
        @Override
        protected OrderEvent pollEvent() throws InterruptedException {
            return queue.poll(100, TimeUnit.MILLISECONDS);  // Polling!
        }
    
        @Override
        protected void processEvent(OrderEvent event) {
            // Traitement
        }
    
        // Methode externe pour recevoir les events
        public void onOrderReceived(OrderEvent event) {
            queue.offer(event);
        }
    }
    

    10.2 Apres (AbstractPushWorker)

    // RECOMMANDE
    @Component
    public class NewOrderWorker extends AbstractPushWorker<OrderEvent> {
    
        public NewOrderWorker() {
            super(4, "orders.created");  // Specifie le channel
        }
    
        @Override
        public String getName() {
            return "order_worker";
        }
    
        @Override
        protected Class<OrderEvent> getEventType() {
            return OrderEvent.class;
        }
    
        @Override
        protected void processEvent(OrderEvent payload, BusEvent<OrderEvent> event) {
            // Meme traitement
        }
    
        // Plus besoin de methode externe - l'EventBus gere tout
    }
    

    10.3 Etapes de migration

    1. Ajouter la dependance EventBus au worker
    2. Changer la classe parente : AbstractEventDrivenWorker → AbstractPushWorker
    3. Specifier les channels dans le constructeur
    4. Implementer getEventType()
    5. Adapter processEvent() pour accepter BusEvent
    6. Supprimer la queue interne et pollEvent()
    7. Modifier les producteurs pour utiliser eventBus.publish()
    8. Tester le comportement

    11. Metriques Prometheus

    # EventBus
    socle_eventbus_published_total{channel="orders.created"}
    socle_eventbus_delivered_total{channel="orders.created"}
    socle_eventbus_failed_total{channel="orders.created"}
    socle_eventbus_subscriptions_active{channel="orders.created"}
    socle_eventbus_queue_size{subscription="sub-123"}
    
    # Push Workers
    socle_push_worker_processed_total{worker="order_worker"}
    socle_push_worker_errors_total{worker="order_worker"}
    socle_push_worker_queue_size{worker="order_worker"}
    socle_push_worker_duration_seconds{worker="order_worker", quantile="0.99"}
    

    12. API REST Admin

    GET  /admin/eventbus/stats              → Statistiques globales
    GET  /admin/eventbus/channels           → Liste des channels actifs
    GET  /admin/eventbus/subscriptions      → Liste des subscriptions
    
    POST /admin/eventbus/publish            → Publier un event (debug)
         Body: {"channel": "test", "payload": {...}}
    

    13. Voir aussi

    Socle V004 – EventBus et Workers Push

  • Socle V004 – Kubernetes

    16 – Kubernetes

    Version : 4.0.0 Date : 2025-12-09

    1. Introduction

    Guide de déploiement du Socle V4 sur Kubernetes.

    2. Image Docker

    2.1 Dockerfile

    FROM eclipse-temurin:21-jre-alpine
    
    LABEL maintainer="your-team@company.com"
    LABEL version="4.0.0"
    
    WORKDIR /app
    
    # Non-root user
    RUN addgroup -S socle && adduser -S socle -G socle
    USER socle
    
    # Copy application
    COPY --chown=socle:socle target/socle-v004-4.0.0.jar app.jar
    
    # Health check
    HEALTHCHECK --interval=30s --timeout=10s --retries=3 \
      CMD wget -qO- http://localhost:8080/admin/health/live || exit 1
    
    # Default environment
    ENV JAVA_OPTS="-XX:+UseContainerSupport -XX:MaxRAMPercentage=75.0"
    
    EXPOSE 8080
    
    ENTRYPOINT ["sh", "-c", "java $JAVA_OPTS -jar app.jar"]
    

    2.2 Build et Push

    # Build
    docker build -t gcr.io/my-project/socle-v4:4.0.0 .
    
    # Push
    docker push gcr.io/my-project/socle-v4:4.0.0
    

    3. Manifests Kubernetes

    3.1 Namespace

    apiVersion: v1
    kind: Namespace
    metadata:
      name: socle
      labels:
        name: socle
    

    3.2 ConfigMap

    apiVersion: v1
    kind: ConfigMap
    metadata:
      name: socle-config
      namespace: socle
    data:
      APP_NAME: "socle-v4"
      ENV_NAME: "PROD"
      REGION: "europe-west1"
      HTTP_PORT: "8080"
      KVBUS_MODE: "redis"
      REDIS_HOST: "redis-master.redis.svc.cluster.local"
      TECHDB_ENABLED: "true"
      LOG_FORWARDER_ENABLED: "true"
      LOG_TRANSPORT_MODE: "http"
      SCHEDULER_ENABLED: "true"
      ADMIN_ENABLED: "true"
      ADMIN_AUTH_ENABLED: "true"
    

    3.3 Secret

    apiVersion: v1
    kind: Secret
    metadata:
      name: socle-secrets
      namespace: socle
    type: Opaque
    stringData:
      REDIS_PASSWORD: "your-redis-password"
      ADMIN_PASSWORD: "your-admin-password"
      API_KEY: "your-api-key"
      TECHDB_PASSWORD: "your-techdb-password"
    

    3.4 Deployment

    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: socle-v4
      namespace: socle
      labels:
        app: socle-v4
        version: "4.0.0"
    spec:
      replicas: 2
      selector:
        matchLabels:
          app: socle-v4
      strategy:
        type: RollingUpdate
        rollingUpdate:
          maxSurge: 1
          maxUnavailable: 0
      template:
        metadata:
          labels:
            app: socle-v4
            version: "4.0.0"
          annotations:
            prometheus.io/scrape: "true"
            prometheus.io/path: "/actuator/prometheus"
            prometheus.io/port: "8080"
        spec:
          serviceAccountName: socle-sa
          securityContext:
            runAsNonRoot: true
            runAsUser: 1000
            fsGroup: 1000
          containers:
            - name: socle
              image: gcr.io/my-project/socle-v4:4.0.0
              imagePullPolicy: Always
              ports:
                - name: http
                  containerPort: 8080
                  protocol: TCP
              envFrom:
                - configMapRef:
                    name: socle-config
                - secretRef:
                    name: socle-secrets
              env:
                - name: POD_NAME
                  valueFrom:
                    fieldRef:
                      fieldPath: metadata.name
                - name: POD_NAMESPACE
                  valueFrom:
                    fieldRef:
                      fieldPath: metadata.namespace
                - name: EXEC_ID
                  value: "$(POD_NAME)"
              resources:
                requests:
                  cpu: "250m"
                  memory: "512Mi"
                limits:
                  cpu: "1000m"
                  memory: "1Gi"
              livenessProbe:
                httpGet:
                  path: /admin/health/live
                  port: 8080
                initialDelaySeconds: 30
                periodSeconds: 10
                timeoutSeconds: 5
                failureThreshold: 3
              readinessProbe:
                httpGet:
                  path: /admin/health/ready
                  port: 8080
                initialDelaySeconds: 10
                periodSeconds: 5
                timeoutSeconds: 3
                failureThreshold: 3
              volumeMounts:
                - name: data
                  mountPath: /app/data
                - name: logs
                  mountPath: /app/logs
          volumes:
            - name: data
              emptyDir: {}
            - name: logs
              emptyDir: {}
          affinity:
            podAntiAffinity:
              preferredDuringSchedulingIgnoredDuringExecution:
                - weight: 100
                  podAffinityTerm:
                    labelSelector:
                      matchLabels:
                        app: socle-v4
                    topologyKey: kubernetes.io/hostname
    

    3.5 Service

    apiVersion: v1
    kind: Service
    metadata:
      name: socle-v4
      namespace: socle
      labels:
        app: socle-v4
    spec:
      type: ClusterIP
      ports:
        - name: http
          port: 80
          targetPort: 8080
          protocol: TCP
      selector:
        app: socle-v4
    

    3.6 Ingress

    apiVersion: networking.k8s.io/v1
    kind: Ingress
    metadata:
      name: socle-v4
      namespace: socle
      annotations:
        kubernetes.io/ingress.class: nginx
        nginx.ingress.kubernetes.io/ssl-redirect: "true"
        cert-manager.io/cluster-issuer: letsencrypt-prod
    spec:
      tls:
        - hosts:
            - socle.example.com
          secretName: socle-tls
      rules:
        - host: socle.example.com
          http:
            paths:
              - path: /
                pathType: Prefix
                backend:
                  service:
                    name: socle-v4
                    port:
                      number: 80
    

    3.7 HorizontalPodAutoscaler

    apiVersion: autoscaling/v2
    kind: HorizontalPodAutoscaler
    metadata:
      name: socle-v4
      namespace: socle
    spec:
      scaleTargetRef:
        apiVersion: apps/v1
        kind: Deployment
        name: socle-v4
      minReplicas: 2
      maxReplicas: 10
      metrics:
        - type: Resource
          resource:
            name: cpu
            target:
              type: Utilization
              averageUtilization: 70
        - type: Resource
          resource:
            name: memory
            target:
              type: Utilization
              averageUtilization: 80
    

    3.8 PodDisruptionBudget

    apiVersion: policy/v1
    kind: PodDisruptionBudget
    metadata:
      name: socle-v4
      namespace: socle
    spec:
      minAvailable: 1
      selector:
        matchLabels:
          app: socle-v4
    

    3.9 ServiceAccount

    apiVersion: v1
    kind: ServiceAccount
    metadata:
      name: socle-sa
      namespace: socle
    

    4. Persistence avec PVC

    4.1 PersistentVolumeClaim

    apiVersion: v1
    kind: PersistentVolumeClaim
    metadata:
      name: socle-data
      namespace: socle
    spec:
      accessModes:
        - ReadWriteOnce
      storageClassName: standard
      resources:
        requests:
          storage: 10Gi
    

    4.2 Deployment avec PVC

    # Dans le Deployment
    spec:
      template:
        spec:
          containers:
            - name: socle
              volumeMounts:
                - name: data
                  mountPath: /app/data
          volumes:
            - name: data
              persistentVolumeClaim:
                claimName: socle-data
    

    5. Network Policies

    apiVersion: networking.k8s.io/v1
    kind: NetworkPolicy
    metadata:
      name: socle-network-policy
      namespace: socle
    spec:
      podSelector:
        matchLabels:
          app: socle-v4
      policyTypes:
        - Ingress
        - Egress
      ingress:
        # Allow from ingress controller
        - from:
            - namespaceSelector:
                matchLabels:
                  name: ingress-nginx
          ports:
            - port: 8080
        # Allow from Prometheus
        - from:
            - namespaceSelector:
                matchLabels:
                  name: monitoring
          ports:
            - port: 8080
      egress:
        # Allow to Redis
        - to:
            - namespaceSelector:
                matchLabels:
                  name: redis
          ports:
            - port: 6379
        # Allow to DNS
        - to:
            - namespaceSelector: {}
              podSelector:
                matchLabels:
                  k8s-app: kube-dns
          ports:
            - port: 53
              protocol: UDP
    

    6. Helm Chart

    6.1 Chart.yaml

    apiVersion: v2
    name: socle-v4
    description: Socle V4 Framework
    version: 4.0.0
    appVersion: "4.0.0"
    

    6.2 values.yaml

    replicaCount: 2
    
    image:
      repository: gcr.io/my-project/socle-v4
      tag: "4.0.0"
      pullPolicy: Always
    
    service:
      type: ClusterIP
      port: 80
    
    ingress:
      enabled: true
      className: nginx
      hosts:
        - host: socle.example.com
          paths:
            - path: /
              pathType: Prefix
      tls:
        - secretName: socle-tls
          hosts:
            - socle.example.com
    
    resources:
      requests:
        cpu: 250m
        memory: 512Mi
      limits:
        cpu: 1000m
        memory: 1Gi
    
    autoscaling:
      enabled: true
      minReplicas: 2
      maxReplicas: 10
      targetCPUUtilizationPercentage: 70
    
    config:
      APP_NAME: socle-v4
      ENV_NAME: PROD
      KVBUS_MODE: redis
    
    secrets:
      REDIS_PASSWORD: ""
      ADMIN_PASSWORD: ""
      API_KEY: ""
    

    6.3 Installation

    # Install
    helm install socle-v4 ./socle-v4-chart -n socle --create-namespace -f values-prod.yaml
    
    # Upgrade
    helm upgrade socle-v4 ./socle-v4-chart -n socle -f values-prod.yaml
    
    # Uninstall
    helm uninstall socle-v4 -n socle
    

    7. Observability

    7.1 ServiceMonitor (Prometheus Operator)

    apiVersion: monitoring.coreos.com/v1
    kind: ServiceMonitor
    metadata:
      name: socle-v4
      namespace: socle
      labels:
        release: prometheus
    spec:
      selector:
        matchLabels:
          app: socle-v4
      endpoints:
        - port: http
          path: /actuator/prometheus
          interval: 15s
    

    7.2 PrometheusRule

    apiVersion: monitoring.coreos.com/v1
    kind: PrometheusRule
    metadata:
      name: socle-v4-alerts
      namespace: socle
    spec:
      groups:
        - name: socle-v4
          rules:
            - alert: SocleHighErrorRate
              expr: rate(socle_errors_total[5m]) > 0.1
              for: 5m
              labels:
                severity: warning
              annotations:
                summary: High error rate
    

    8. Déploiement Multi-région

    8.1 Structure

    clusters/
    ├── europe-west1/
    │   ├── kustomization.yaml
    │   └── config-patch.yaml
    ├── us-central1/
    │   ├── kustomization.yaml
    │   └── config-patch.yaml
    └── base/
        ├── kustomization.yaml
        ├── deployment.yaml
        ├── service.yaml
        └── configmap.yaml
    

    8.2 Kustomize overlay

    # clusters/europe-west1/kustomization.yaml
    apiVersion: kustomize.config.k8s.io/v1beta1
    kind: Kustomization
    bases:
      - ../../base
    patchesStrategicMerge:
      - config-patch.yaml
    configMapGenerator:
      - name: socle-config
        behavior: merge
        literals:
          - REGION=europe-west1
    

    9. Troubleshooting

    Commandes utiles

    # Logs
    kubectl logs -f deployment/socle-v4 -n socle
    
    # Describe pod
    kubectl describe pod -l app=socle-v4 -n socle
    
    # Port forward
    kubectl port-forward svc/socle-v4 8080:80 -n socle
    
    # Exec into pod
    kubectl exec -it deployment/socle-v4 -n socle -- sh
    
    # Check events
    kubectl get events -n socle --sort-by='.lastTimestamp'
    

    10. Références

  • Socle V004 – Plugins

    20 – Plugins

    Version : 4.0.0 Date : 2025-12-09

    1. Introduction

    Le Socle V4 supporte une architecture de plugins pour étendre les fonctionnalités de base. Les plugins sont des modules Spring Boot qui s’intègrent automatiquement.

    2. Architecture des plugins

    ┌──────────────────────────────────────────────────────────┐
    │                    Application                            │
    │                                                           │
    │  ┌─────────────────────────────────────────────────────┐ │
    │  │                   Socle V4 Core                      │ │
    │  │  MOP | Workers | KvBus | TechDB | Logging | etc.    │ │
    │  └─────────────────────────────────────────────────────┘ │
    │                          │                                │
    │         ┌────────────────┼────────────────┐              │
    │         ▼                ▼                ▼              │
    │  ┌────────────┐   ┌────────────┐   ┌────────────┐       │
    │  │   Plugin   │   │   Plugin   │   │   Plugin   │       │
    │  │   Kafka    │   │   NATS     │   │   Custom   │       │
    │  └────────────┘   └────────────┘   └────────────┘       │
    │                                                           │
    └──────────────────────────────────────────────────────────┘
    

    3. Créer un plugin

    3.1 Structure Maven

    <?xml version="1.0" encoding="UTF-8"?>
    <project>
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>com.mycompany</groupId>
        <artifactId>socle-plugin-myplugin</artifactId>
        <version>1.0.0</version>
    
        <dependencies>
            <!-- Dépendance Socle -->
            <dependency>
                <groupId>eu.lmvi</groupId>
                <artifactId>socle-v004</artifactId>
                <version>4.0.0</version>
                <scope>provided</scope>
            </dependency>
        </dependencies>
    </project>
    

    3.2 Auto-configuration

    package com.mycompany.plugin;
    
    import org.springframework.boot.autoconfigure.AutoConfiguration;
    import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
    import org.springframework.context.annotation.ComponentScan;
    
    @AutoConfiguration
    @ConditionalOnProperty(name = "socle.plugins.myplugin.enabled", havingValue = "true")
    @ComponentScan(basePackages = "com.mycompany.plugin")
    public class MyPluginAutoConfiguration {
        // Configuration automatique
    }
    

    3.3 Fichier spring.factories

    # src/main/resources/META-INF/spring.factories
    org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
    com.mycompany.plugin.MyPluginAutoConfiguration
    

    Ou pour Spring Boot 3.x :

    # src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
    com.mycompany.plugin.MyPluginAutoConfiguration
    

    4. Types de plugins

    4.1 Plugin Worker

    package com.mycompany.plugin.worker;
    
    import eu.lmvi.socle.worker.Worker;
    import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
    import org.springframework.stereotype.Component;
    
    @Component
    @ConditionalOnProperty(name = "socle.plugins.myplugin.enabled", havingValue = "true")
    public class MyPluginWorker implements Worker {
    
        @Override
        public String getName() {
            return "my-plugin-worker";
        }
    
        @Override
        public void initialize() {
            // Initialisation
        }
    
        @Override
        public void start() {
            // Démarrage
        }
    
        @Override
        public void doWork() {
            // Traitement
        }
    
        @Override
        public void stop() {
            // Arrêt
        }
    
        @Override
        public boolean isHealthy() {
            return true;
        }
    
        @Override
        public Map<String, Object> getStats() {
            return Map.of();
        }
    }
    

    4.2 Plugin KvBus

    package com.mycompany.plugin.kv;
    
    import eu.lmvi.socle.kv.KvBus;
    import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
    import org.springframework.stereotype.Component;
    
    @Component
    @ConditionalOnProperty(name = "socle.kvbus.mode", havingValue = "custom")
    public class CustomKvBus implements KvBus {
    
        @Override
        public void put(String key, String value) {
            // Implémentation custom
        }
    
        @Override
        public Optional<String> get(String key) {
            // Implémentation custom
            return Optional.empty();
        }
    
        // ... autres méthodes
    }
    

    4.3 Plugin Transport (LogForwarder)

    package com.mycompany.plugin.logging;
    
    import eu.lmvi.socle.logging.LogTransport;
    import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
    import org.springframework.stereotype.Component;
    
    @Component
    @ConditionalOnProperty(name = "socle.logging.forwarder.transport-mode", havingValue = "custom")
    public class CustomLogTransport implements LogTransport {
    
        @Override
        public void send(List<LogEntry> entries) throws Exception {
            // Envoyer les logs vers votre système
        }
    
        @Override
        public boolean isAvailable() {
            return true;
        }
    
        @Override
        public void close() {
            // Cleanup
        }
    }
    

    5. Plugin Kafka (exemple complet)

    5.1 Structure

    socle-plugin-kafka/
    ├── pom.xml
    ├── src/main/java/eu/lmvi/socle/plugin/kafka/
    │   ├── KafkaPluginAutoConfiguration.java
    │   ├── KafkaPluginConfiguration.java
    │   ├── KafkaConsumerWorker.java
    │   ├── KafkaProducerService.java
    │   └── KafkaHealthIndicator.java
    └── src/main/resources/
        └── META-INF/spring/
            └── org.springframework.boot.autoconfigure.AutoConfiguration.imports
    

    5.2 Configuration

    @ConfigurationProperties(prefix = "socle.plugins.kafka")
    public class KafkaPluginConfiguration {
        private boolean enabled = false;
        private String bootstrapServers = "localhost:9092";
        private String groupId = "socle-group";
        private List<String> topics = new ArrayList<>();
        private Map<String, String> consumerProperties = new HashMap<>();
        private Map<String, String> producerProperties = new HashMap<>();
    
        // Getters/Setters
    }
    

    5.3 Auto-configuration

    @AutoConfiguration
    @ConditionalOnProperty(name = "socle.plugins.kafka.enabled", havingValue = "true")
    @EnableConfigurationProperties(KafkaPluginConfiguration.class)
    @ComponentScan(basePackages = "eu.lmvi.socle.plugin.kafka")
    public class KafkaPluginAutoConfiguration {
    
        @Bean
        public KafkaConsumer<String, String> kafkaConsumer(KafkaPluginConfiguration config) {
            Properties props = new Properties();
            props.put("bootstrap.servers", config.getBootstrapServers());
            props.put("group.id", config.getGroupId());
            props.putAll(config.getConsumerProperties());
            return new KafkaConsumer<>(props);
        }
    
        @Bean
        public KafkaProducer<String, String> kafkaProducer(KafkaPluginConfiguration config) {
            Properties props = new Properties();
            props.put("bootstrap.servers", config.getBootstrapServers());
            props.putAll(config.getProducerProperties());
            return new KafkaProducer<>(props);
        }
    }
    

    5.4 Worker

    @Component
    @ConditionalOnProperty(name = "socle.plugins.kafka.enabled", havingValue = "true")
    public class KafkaConsumerWorker extends AbstractWorker {
    
        private final KafkaConsumer<String, String> consumer;
        private final KafkaPluginConfiguration config;
        private final TechDbManager techDb;
    
        @Override
        public String getName() {
            return "kafka-consumer-plugin";
        }
    
        @Override
        protected void doInitialize() {
            consumer.subscribe(config.getTopics());
        }
    
        @Override
        protected void doProcess() {
            ConsumerRecords<String, String> records = consumer.poll(Duration.ofSeconds(1));
            for (ConsumerRecord<String, String> record : records) {
                processRecord(record);
            }
        }
    
        @Override
        protected void doStop() {
            consumer.close();
        }
    }
    

    5.5 Utilisation

    # application.yml
    socle:
      plugins:
        kafka:
          enabled: true
          bootstrap-servers: kafka:9092
          group-id: my-app
          topics:
            - orders
            - events
    

    6. Plugin NATS (exemple)

    6.1 Configuration

    @ConfigurationProperties(prefix = "socle.plugins.nats")
    public class NatsPluginConfiguration {
        private boolean enabled = false;
        private String url = "nats://localhost:4222";
        private List<String> subjects = new ArrayList<>();
        private String streamName;
        private String consumerName;
    }
    

    6.2 Worker

    @Component
    @ConditionalOnProperty(name = "socle.plugins.nats.enabled", havingValue = "true")
    public class NatsConsumerWorker extends AbstractWorker {
    
        private final NatsPluginConfiguration config;
        private Connection natsConnection;
        private JetStream jetStream;
    
        @Override
        protected void doInitialize() {
            natsConnection = Nats.connect(config.getUrl());
            jetStream = natsConnection.jetStream();
        }
    
        @Override
        protected void doProcess() {
            for (String subject : config.getSubjects()) {
                Message msg = jetStream.pullSubscribe(subject, config.getConsumerName())
                    .fetch(100, Duration.ofSeconds(1))
                    .stream()
                    .findFirst()
                    .orElse(null);
    
                if (msg != null) {
                    processMessage(msg);
                    msg.ack();
                }
            }
        }
    }
    

    7. Extension des APIs Admin

    7.1 Controller additionnel

    @RestController
    @RequestMapping("/admin/plugins/kafka")
    @ConditionalOnProperty(name = "socle.plugins.kafka.enabled", havingValue = "true")
    public class KafkaAdminController {
    
        @Autowired
        private KafkaConsumerWorker worker;
    
        @GetMapping("/status")
        public Map<String, Object> status() {
            return Map.of(
                "connected", worker.isHealthy(),
                "stats", worker.getStats()
            );
        }
    
        @GetMapping("/offsets")
        public Map<String, Long> offsets() {
            return worker.getCurrentOffsets();
        }
    
        @PostMapping("/seek/{topic}/{partition}/{offset}")
        public void seek(
                @PathVariable String topic,
                @PathVariable int partition,
                @PathVariable long offset) {
            worker.seekTo(topic, partition, offset);
        }
    }
    

    8. Métriques du plugin

    @Component
    @ConditionalOnProperty(name = "socle.plugins.kafka.enabled", havingValue = "true")
    public class KafkaPluginMetrics {
    
        private final Counter messagesReceived;
        private final Counter messagesProcessed;
        private final Timer processingTime;
    
        public KafkaPluginMetrics(MeterRegistry registry) {
            this.messagesReceived = Counter.builder("socle_kafka_messages_received_total")
                .description("Total Kafka messages received")
                .register(registry);
    
            this.messagesProcessed = Counter.builder("socle_kafka_messages_processed_total")
                .description("Total Kafka messages processed")
                .register(registry);
    
            this.processingTime = Timer.builder("socle_kafka_processing_duration_seconds")
                .description("Kafka message processing duration")
                .register(registry);
        }
    
        public void recordReceived() {
            messagesReceived.increment();
        }
    
        public void recordProcessed(Duration duration) {
            messagesProcessed.increment();
            processingTime.record(duration);
        }
    }
    

    9. Test du plugin

    @SpringBootTest
    @TestPropertySource(properties = {
        "socle.plugins.kafka.enabled=true",
        "socle.plugins.kafka.bootstrap-servers=localhost:9092"
    })
    class KafkaPluginTest {
    
        @Autowired
        private KafkaConsumerWorker worker;
    
        @Test
        void workerShouldBeRegistered() {
            assertNotNull(worker);
            assertEquals("kafka-consumer-plugin", worker.getName());
        }
    
        @Test
        void workerShouldStart() {
            worker.initialize();
            worker.start();
            assertTrue(worker.isHealthy());
        }
    }
    

    10. Publication du plugin

    10.1 Maven deploy

    <distributionManagement>
        <repository>
            <id>releases</id>
            <url>https://nexus.mycompany.com/repository/maven-releases/</url>
        </repository>
    </distributionManagement>
    
    mvn clean deploy
    

    10.2 Utilisation dans une application

    <dependency>
        <groupId>eu.lmvi</groupId>
        <artifactId>socle-plugin-kafka</artifactId>
        <version>1.0.0</version>
    </dependency>
    

    11. Bonnes pratiques

    DO

    • Utiliser @ConditionalOnProperty pour activer/désactiver
    • Exposer la configuration via @ConfigurationProperties
    • Implémenter des health indicators
    • Exposer des métriques
    • Documenter les options de configuration

    DON’T

    • Ne pas forcer l’activation par défaut
    • Ne pas dupliquer les fonctionnalités du core
    • Ne pas utiliser de dépendances en conflit avec le Socle
    • Ne pas bloquer le démarrage de l’application si le plugin échoue

    12. Références

  • Socle V004 – KV-Bus

    06 – KvBus (Key-Value Bus)

    Version : 4.0.0 Date : 2025-12-09

    1. Introduction

    KvBus est une abstraction de stockage clé-valeur avec deux implémentations :

    • in_memory : HashMap pour le développement local
    • redis : Redis pour la production multi-instances

    Caractéristiques

    • Interface unifiée
    • TTL (Time-To-Live) configurable
    • Opérations atomiques
    • Support JSON pour les objets complexes
    • Patterns pub/sub (Redis uniquement)

    2. Configuration

    2.1 application.yml

    socle:
      kvbus:
        mode: ${KVBUS_MODE:in_memory}
        redis:
          host: ${REDIS_HOST:localhost}
          port: ${REDIS_PORT:6379}
          password: ${REDIS_PASSWORD:}
          database: ${REDIS_DATABASE:0}
          prefix: ${REDIS_PREFIX:socle}
          connect-timeout-ms: ${REDIS_CONNECT_TIMEOUT:5000}
          read-timeout-ms: ${REDIS_READ_TIMEOUT:5000}
          pool:
            max-total: ${REDIS_POOL_MAX:16}
            max-idle: ${REDIS_POOL_MAX_IDLE:8}
            min-idle: ${REDIS_POOL_MIN_IDLE:2}
    

    2.2 Variables d’environnement

    Variable Description Défaut
    KVBUS_MODE Mode (in_memory/redis) in_memory
    REDIS_HOST Hôte Redis localhost
    REDIS_PORT Port Redis 6379
    REDIS_PASSWORD Mot de passe –
    REDIS_DATABASE Database number 0
    REDIS_PREFIX Préfixe des clés socle

    3. Interface KvBus

    package eu.lmvi.socle.kv;
    
    public interface KvBus {
    
        // === CRUD basique ===
    
        /**
         * Stocke une valeur
         */
        void put(String key, String value);
    
        /**
         * Stocke une valeur avec TTL
         */
        void put(String key, String value, Duration ttl);
    
        /**
         * Récupère une valeur
         */
        Optional<String> get(String key);
    
        /**
         * Supprime une clé
         */
        void delete(String key);
    
        /**
         * Vérifie l'existence d'une clé
         */
        boolean exists(String key);
    
        // === TTL ===
    
        /**
         * Définit le TTL d'une clé existante
         */
        void setTtl(String key, Duration ttl);
    
        /**
         * Récupère le TTL restant
         */
        Optional<Duration> getTtl(String key);
    
        // === Opérations atomiques ===
    
        /**
         * Incrémente une valeur numérique
         */
        long increment(String key);
    
        /**
         * Incrémente avec delta
         */
        long increment(String key, long delta);
    
        /**
         * Set if not exists
         */
        boolean putIfAbsent(String key, String value);
    
        /**
         * Set if not exists avec TTL
         */
        boolean putIfAbsent(String key, String value, Duration ttl);
    
        // === Opérations en lot ===
    
        /**
         * Récupère plusieurs clés
         */
        Map<String, String> getAll(Collection<String> keys);
    
        /**
         * Stocke plusieurs valeurs
         */
        void putAll(Map<String, String> entries);
    
        /**
         * Supprime plusieurs clés
         */
        void deleteAll(Collection<String> keys);
    
        // === Pattern matching ===
    
        /**
         * Liste les clés correspondant à un pattern
         */
        Set<String> keys(String pattern);
    
        // === JSON helpers ===
    
        /**
         * Stocke un objet en JSON
         */
        <T> void putJson(String key, T object);
    
        /**
         * Récupère un objet depuis JSON
         */
        <T> Optional<T> getJson(String key, Class<T> type);
    
        // === Lifecycle ===
    
        /**
         * Vérifie la santé de la connexion
         */
        boolean isHealthy();
    
        /**
         * Ferme les connexions
         */
        void close();
    }
    

    4. Implémentation InMemoryKvBus

    package eu.lmvi.socle.kv;
    
    @Component
    @ConditionalOnProperty(name = "socle.kvbus.mode", havingValue = "in_memory", matchIfMissing = true)
    public class InMemoryKvBus implements KvBus {
    
        private final ConcurrentHashMap<String, Entry> store = new ConcurrentHashMap<>();
        private final ScheduledExecutorService cleaner;
    
        public InMemoryKvBus() {
            // Nettoyage des entrées expirées toutes les minutes
            cleaner = Executors.newSingleThreadScheduledExecutor();
            cleaner.scheduleAtFixedRate(this::cleanExpired, 1, 1, TimeUnit.MINUTES);
        }
    
        @Override
        public void put(String key, String value) {
            store.put(key, new Entry(value, null));
        }
    
        @Override
        public void put(String key, String value, Duration ttl) {
            Instant expiry = Instant.now().plus(ttl);
            store.put(key, new Entry(value, expiry));
        }
    
        @Override
        public Optional<String> get(String key) {
            Entry entry = store.get(key);
            if (entry == null) return Optional.empty();
            if (entry.isExpired()) {
                store.remove(key);
                return Optional.empty();
            }
            return Optional.of(entry.value);
        }
    
        @Override
        public void delete(String key) {
            store.remove(key);
        }
    
        @Override
        public boolean exists(String key) {
            return get(key).isPresent();
        }
    
        @Override
        public long increment(String key) {
            return increment(key, 1);
        }
    
        @Override
        public long increment(String key, long delta) {
            Entry entry = store.compute(key, (k, v) -> {
                long current = (v == null) ? 0 : Long.parseLong(v.value);
                return new Entry(String.valueOf(current + delta), v != null ? v.expiry : null);
            });
            return Long.parseLong(entry.value);
        }
    
        @Override
        public boolean putIfAbsent(String key, String value) {
            return store.putIfAbsent(key, new Entry(value, null)) == null;
        }
    
        @Override
        public Set<String> keys(String pattern) {
            String regex = pattern.replace("*", ".*");
            return store.keySet().stream()
                .filter(k -> k.matches(regex))
                .collect(Collectors.toSet());
        }
    
        @Override
        public boolean isHealthy() {
            return true;
        }
    
        @Override
        public void close() {
            cleaner.shutdown();
            store.clear();
        }
    
        private void cleanExpired() {
            store.entrySet().removeIf(e -> e.getValue().isExpired());
        }
    
        private record Entry(String value, Instant expiry) {
            boolean isExpired() {
                return expiry != null && Instant.now().isAfter(expiry);
            }
        }
    }
    

    5. Implémentation RedisKvBus

    package eu.lmvi.socle.kv;
    
    @Component
    @ConditionalOnProperty(name = "socle.kvbus.mode", havingValue = "redis")
    public class RedisKvBus implements KvBus {
    
        private static final Logger log = LoggerFactory.getLogger(RedisKvBus.class);
    
        private final JedisPool jedisPool;
        private final String prefix;
        private final ObjectMapper objectMapper;
    
        public RedisKvBus(SocleConfiguration config) {
            JedisPoolConfig poolConfig = new JedisPoolConfig();
            poolConfig.setMaxTotal(config.getKvbus().getRedis().getPool().getMaxTotal());
            poolConfig.setMaxIdle(config.getKvbus().getRedis().getPool().getMaxIdle());
            poolConfig.setMinIdle(config.getKvbus().getRedis().getPool().getMinIdle());
    
            this.jedisPool = new JedisPool(
                poolConfig,
                config.getKvbus().getRedis().getHost(),
                config.getKvbus().getRedis().getPort(),
                config.getKvbus().getRedis().getConnectTimeoutMs(),
                config.getKvbus().getRedis().getPassword(),
                config.getKvbus().getRedis().getDatabase()
            );
    
            this.prefix = config.getKvbus().getRedis().getPrefix() + ":";
            this.objectMapper = new ObjectMapper();
    
            log.info("RedisKvBus initialized: {}:{}",
                config.getKvbus().getRedis().getHost(),
                config.getKvbus().getRedis().getPort());
        }
    
        private String prefixedKey(String key) {
            return prefix + key;
        }
    
        @Override
        public void put(String key, String value) {
            try (Jedis jedis = jedisPool.getResource()) {
                jedis.set(prefixedKey(key), value);
            }
        }
    
        @Override
        public void put(String key, String value, Duration ttl) {
            try (Jedis jedis = jedisPool.getResource()) {
                jedis.setex(prefixedKey(key), ttl.toSeconds(), value);
            }
        }
    
        @Override
        public Optional<String> get(String key) {
            try (Jedis jedis = jedisPool.getResource()) {
                return Optional.ofNullable(jedis.get(prefixedKey(key)));
            }
        }
    
        @Override
        public void delete(String key) {
            try (Jedis jedis = jedisPool.getResource()) {
                jedis.del(prefixedKey(key));
            }
        }
    
        @Override
        public boolean exists(String key) {
            try (Jedis jedis = jedisPool.getResource()) {
                return jedis.exists(prefixedKey(key));
            }
        }
    
        @Override
        public long increment(String key) {
            try (Jedis jedis = jedisPool.getResource()) {
                return jedis.incr(prefixedKey(key));
            }
        }
    
        @Override
        public long increment(String key, long delta) {
            try (Jedis jedis = jedisPool.getResource()) {
                return jedis.incrBy(prefixedKey(key), delta);
            }
        }
    
        @Override
        public boolean putIfAbsent(String key, String value) {
            try (Jedis jedis = jedisPool.getResource()) {
                return jedis.setnx(prefixedKey(key), value) == 1;
            }
        }
    
        @Override
        public boolean putIfAbsent(String key, String value, Duration ttl) {
            try (Jedis jedis = jedisPool.getResource()) {
                String result = jedis.set(prefixedKey(key), value,
                    SetParams.setParams().nx().ex(ttl.toSeconds()));
                return "OK".equals(result);
            }
        }
    
        @Override
        public Set<String> keys(String pattern) {
            try (Jedis jedis = jedisPool.getResource()) {
                Set<String> rawKeys = jedis.keys(prefixedKey(pattern));
                return rawKeys.stream()
                    .map(k -> k.substring(prefix.length()))
                    .collect(Collectors.toSet());
            }
        }
    
        @Override
        public <T> void putJson(String key, T object) {
            try {
                String json = objectMapper.writeValueAsString(object);
                put(key, json);
            } catch (JsonProcessingException e) {
                throw new RuntimeException("Failed to serialize object", e);
            }
        }
    
        @Override
        public <T> Optional<T> getJson(String key, Class<T> type) {
            return get(key).map(json -> {
                try {
                    return objectMapper.readValue(json, type);
                } catch (JsonProcessingException e) {
                    throw new RuntimeException("Failed to deserialize object", e);
                }
            });
        }
    
        @Override
        public boolean isHealthy() {
            try (Jedis jedis = jedisPool.getResource()) {
                return "PONG".equals(jedis.ping());
            } catch (Exception e) {
                return false;
            }
        }
    
        @Override
        public void close() {
            jedisPool.close();
        }
    }
    

    6. Utilisation

    6.1 Injection

    @Service
    public class MonService {
    
        @Autowired
        private KvBus kvBus;
    
        public void process() {
            // Utiliser kvBus...
        }
    }
    

    6.2 CRUD basique

    // Stocker
    kvBus.put("user:123:name", "John");
    kvBus.put("session:abc", "data", Duration.ofHours(1));
    
    // Récupérer
    Optional<String> name = kvBus.get("user:123:name");
    name.ifPresent(n -> log.info("Name: {}", n));
    
    // Vérifier
    if (kvBus.exists("user:123:name")) {
        // ...
    }
    
    // Supprimer
    kvBus.delete("user:123:name");
    

    6.3 JSON

    // Stocker un objet
    Order order = new Order("123", "PENDING", List.of("item1", "item2"));
    kvBus.putJson("order:123", order);
    
    // Récupérer un objet
    Optional<Order> retrieved = kvBus.getJson("order:123", Order.class);
    

    6.4 Compteurs atomiques

    // Incrémenter
    long newValue = kvBus.increment("stats:requests:total");
    long newValue2 = kvBus.increment("stats:bytes:total", 1024);
    
    // Compteur avec reset quotidien
    String dailyKey = "stats:requests:" + LocalDate.now();
    kvBus.increment(dailyKey);
    kvBus.setTtl(dailyKey, Duration.ofDays(1));
    

    6.5 Lock distribué (Redis)

    public boolean tryLock(String resource, Duration timeout) {
        String lockKey = "lock:" + resource;
        return kvBus.putIfAbsent(lockKey, "locked", timeout);
    }
    
    public void unlock(String resource) {
        kvBus.delete("lock:" + resource);
    }
    
    // Utilisation
    if (tryLock("order-processing", Duration.ofMinutes(5))) {
        try {
            processOrders();
        } finally {
            unlock("order-processing");
        }
    }
    

    6.6 Cache avec TTL

    public Order getOrder(String orderId) {
        String cacheKey = "cache:order:" + orderId;
    
        // Check cache
        Optional<Order> cached = kvBus.getJson(cacheKey, Order.class);
        if (cached.isPresent()) {
            return cached.get();
        }
    
        // Load from DB
        Order order = orderRepository.findById(orderId);
    
        // Cache for 5 minutes
        kvBus.putJson(cacheKey, order);
        kvBus.setTtl(cacheKey, Duration.ofMinutes(5));
    
        return order;
    }
    

    7. Patterns avancés

    7.1 Rate limiting

    public boolean isRateLimited(String userId, int maxRequests, Duration window) {
        String key = "ratelimit:" + userId + ":" + Instant.now().truncatedTo(ChronoUnit.MINUTES);
    
        long count = kvBus.increment(key);
        if (count == 1) {
            kvBus.setTtl(key, window);
        }
    
        return count > maxRequests;
    }
    

    7.2 Session management

    public void createSession(String sessionId, User user) {
        kvBus.putJson("session:" + sessionId, user);
        kvBus.setTtl("session:" + sessionId, Duration.ofHours(24));
    }
    
    public Optional<User> getSession(String sessionId) {
        return kvBus.getJson("session:" + sessionId, User.class);
    }
    
    public void refreshSession(String sessionId) {
        kvBus.setTtl("session:" + sessionId, Duration.ofHours(24));
    }
    
    public void destroySession(String sessionId) {
        kvBus.delete("session:" + sessionId);
    }
    

    7.3 Feature flags

    public boolean isFeatureEnabled(String feature) {
        return kvBus.get("feature:" + feature)
            .map(Boolean::parseBoolean)
            .orElse(false);
    }
    
    public void setFeatureFlag(String feature, boolean enabled) {
        kvBus.put("feature:" + feature, String.valueOf(enabled));
    }
    

    8. KvBus vs TechDB (V4)

    Aspect KvBus TechDB (H2)
    Cas d’usage Cache, sessions, locks Offsets, état persistant
    Survie restart Non (in_memory) / Oui (Redis) Oui (fichier)
    Multi-instances Non (in_memory) / Oui (Redis) Non (par instance)
    Performance Ultra rapide Rapide
    Requêtes Clé simple SQL, JSON

    Règle de choix

    • KvBus : Données temporaires, cache, sessions, compteurs temps réel
    • TechDB : Offsets, checkpoints, état qui doit survivre au restart

    9. Monitoring

    9.1 Métriques

    socle_kvbus_operations_total{operation="get"}
    socle_kvbus_operations_total{operation="put"}
    socle_kvbus_operations_total{operation="delete"}
    socle_kvbus_latency_seconds{operation="get"}
    socle_kvbus_keys_count
    

    9.2 Health Check

    @Component
    public class KvBusHealthIndicator implements HealthIndicator {
    
        @Autowired
        private KvBus kvBus;
    
        @Override
        public Health health() {
            if (kvBus.isHealthy()) {
                return Health.up().build();
            }
            return Health.down().withDetail("error", "KvBus not responding").build();
        }
    }
    

    10. Bonnes pratiques

    DO

    • Utiliser des préfixes de clés cohérents (user:, session:, cache:)
    • Toujours définir un TTL pour les caches
    • Utiliser putIfAbsent pour les locks
    • Préférer Redis en production multi-instances

    DON’T

    • Ne pas stocker de données volumineuses (> 1MB)
    • Ne pas utiliser keys("*") en production (scan)
    • Ne pas oublier de fermer les connexions
    • Ne pas utiliser in_memory pour les données critiques en prod

    11. Références

  • Socle V004 – Log4j2 et LogForwarder

    22 – Log4j2 et LogForwarder (Nouveauté V4)

    Version : 4.0.0 Date : 2025-12-09

    1. Introduction

    Le Socle V4 remplace Logback par Log4j2 pour le logging, avec un LogForwarder intégré pour la centralisation des logs.

    Pourquoi Log4j2 ?

    Critère Logback (V3) Log4j2 (V4)
    Async natif AsyncAppender (wrapper) AsyncLoggers (LMAX Disruptor)
    Performance Bon 6-68x plus rapide
    Garbage-free Non Oui
    Custom Appender Complexe Plugin system simple
    JSON natif Via encoder externe JsonTemplateLayout intégré

    2. Architecture

    ┌─────────────────────────────────────────────────────────────┐
    │                      Application                             │
    │                                                              │
    │  Logger.info("message")                                      │
    │         │                                                    │
    │         ▼                                                    │
    │  ┌─────────────────────────────────────────────────────┐    │
    │  │              Log4j2 AsyncLoggers                     │    │
    │  │              (LMAX Disruptor)                        │    │
    │  └────────────────────┬────────────────────────────────┘    │
    │                       │                                      │
    │         ┌─────────────┼─────────────┐                       │
    │         ▼             ▼             ▼                       │
    │  ┌───────────┐ ┌───────────┐ ┌─────────────────────┐       │
    │  │  Console  │ │  File     │ │ SocleLogForwarder   │       │
    │  │  Appender │ │  Appender │ │ Appender            │       │
    │  └───────────┘ └───────────┘ └──────────┬──────────┘       │
    │                                         │                   │
    └─────────────────────────────────────────┼───────────────────┘
                                              │
                        ┌─────────────────────┴─────────────────────┐
                        │                                           │
                        ▼                                           ▼
                ┌──────────────┐                           ┌──────────────┐
                │ HTTP Transport│                           │ NATS Transport│
                │ → LogHub     │                           │ → JetStream  │
                └──────┬───────┘                           └──────┬───────┘
                       │                                          │
                       │  (si échec)                              │
                       ▼                                          │
                ┌──────────────┐                                  │
                │ H2 Fallback  │◄─────────────────────────────────┘
                │ Storage      │
                └──────────────┘
    

    3. Configuration

    3.1 Dépendances Maven

    <!-- Exclure Logback de Spring Boot -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    
    <!-- Log4j2 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-log4j2</artifactId>
    </dependency>
    
    <!-- LMAX Disruptor (AsyncLoggers) -->
    <dependency>
        <groupId>com.lmax</groupId>
        <artifactId>disruptor</artifactId>
        <version>4.0.0</version>
    </dependency>
    
    <!-- JSON Template Layout -->
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-layout-template-json</artifactId>
        <version>2.22.1</version>
    </dependency>
    

    3.2 log4j2.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <Configuration status="WARN" monitorInterval="30">
    
        <Properties>
            <Property name="LOG_DIR">${env:LOG_DIR:-./logs}</Property>
            <Property name="APP_NAME">${env:APP_NAME:-socle-v4}</Property>
            <Property name="REGION">${env:REGION:-local}</Property>
        </Properties>
    
        <Appenders>
            <!-- Console (dev) -->
            <Console name="Console" target="SYSTEM_OUT">
                <PatternLayout pattern="%d{ISO8601} %highlight{%-5level} [%thread] %logger{36} - %msg%n"/>
            </Console>
    
            <!-- Fichier rotatif -->
            <RollingFile name="File"
                         fileName="${LOG_DIR}/${APP_NAME}.log"
                         filePattern="${LOG_DIR}/${APP_NAME}-%d{yyyy-MM-dd}-%i.log.gz">
                <PatternLayout pattern="%d{ISO8601} %-5level [%thread] %logger{36} - %msg%n"/>
                <Policies>
                    <TimeBasedTriggeringPolicy interval="1"/>
                    <SizeBasedTriggeringPolicy size="100MB"/>
                </Policies>
                <DefaultRolloverStrategy max="30"/>
            </RollingFile>
    
            <!-- LogForwarder (centralisation) -->
            <SocleLogForwarder name="LogForwarder"
                               transportMode="${env:LOG_TRANSPORT_MODE:-http}"
                               logHubUrl="${env:LOG_HUB_URL:-http://localhost:8080/api/ingest-logs}"
                               natsUrl="${env:NATS_URL:-nats://localhost:4222}"
                               batchSize="100"
                               flushIntervalMs="5000"
                               queueCapacity="10000"
                               serviceName="${APP_NAME}"
                               region="${REGION}">
                <ThresholdFilter level="INFO"/>
            </SocleLogForwarder>
        </Appenders>
    
        <Loggers>
            <!-- Socle -->
            <Logger name="eu.lmvi.socle" level="${env:LOG_LEVEL:-INFO}" additivity="false">
                <AppenderRef ref="Console"/>
                <AppenderRef ref="File"/>
                <AppenderRef ref="LogForwarder"/>
            </Logger>
    
            <!-- Frameworks (moins verbeux) -->
            <Logger name="org.springframework" level="WARN"/>
            <Logger name="org.apache.kafka" level="WARN"/>
            <Logger name="io.nats" level="WARN"/>
    
            <!-- Root -->
            <Root level="INFO">
                <AppenderRef ref="Console"/>
                <AppenderRef ref="File"/>
                <AppenderRef ref="LogForwarder"/>
            </Root>
        </Loggers>
    
    </Configuration>
    

    3.3 log4j2.component.properties

    # Activer AsyncLoggers globalement (LMAX Disruptor)
    Log4jContextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector
    
    # Ring buffer (puissance de 2)
    AsyncLogger.RingBufferSize=262144
    
    # Politique d'attente
    AsyncLogger.WaitStrategy=Sleep
    
    # Sécurité (Log4Shell)
    log4j2.formatMsgNoLookups=true
    

    3.4 application.yml

    socle:
      logging:
        forwarder:
          enabled: ${LOG_FORWARDER_ENABLED:false}
          transport-mode: ${LOG_TRANSPORT_MODE:http}
          log-hub-url: ${LOG_HUB_URL:http://localhost:8080/api/ingest-logs}
          nats-url: ${NATS_URL:nats://localhost:4222}
          nats-subject-prefix: ${LOG_NATS_SUBJECT:logs}
          batch-size: ${LOG_BATCH_SIZE:100}
          flush-interval-ms: ${LOG_FLUSH_INTERVAL_MS:5000}
          queue-capacity: ${LOG_QUEUE_CAPACITY:10000}
    
    logging:
      config: classpath:log4j2.xml
    

    4. Variables d’environnement

    Variable Description Défaut
    LOG_LEVEL Niveau de log INFO
    LOG_DIR Répertoire des logs ./logs
    LOG_FORWARDER_ENABLED Activer LogForwarder false
    LOG_TRANSPORT_MODE Mode transport (http/nats) http
    LOG_HUB_URL URL du LogHub –
    NATS_URL URL NATS –
    LOG_BATCH_SIZE Taille des batches 100
    LOG_FLUSH_INTERVAL_MS Intervalle flush (ms) 5000

    5. Utilisation

    5.1 Logging standard

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    public class MonService {
        private static final Logger log = LoggerFactory.getLogger(MonService.class);
    
        public void process() {
            log.debug("Processing started");
            log.info("Processing item: {}", itemId);
            log.warn("Slow processing detected");
            log.error("Processing failed", exception);
        }
    }
    

    5.2 MDC (Mapped Diagnostic Context)

    import org.slf4j.MDC;
    
    public class MonService {
        public void process(String correlationId) {
            MDC.put("correlationId", correlationId);
            MDC.put("worker", "order-processor");
            try {
                log.info("Processing order");
                // Les logs incluront correlationId et worker
            } finally {
                MDC.clear();
            }
        }
    }
    

    5.3 Structured logging

    // Les logs JSON incluent automatiquement :
    // - timestamp
    // - level
    // - logger
    // - thread
    // - message
    // - MDC (correlationId, execId, etc.)
    // - exception (si présente)
    
    log.info("Order processed: orderId={}, amount={}", orderId, amount);
    

    6. LogForwarder

    6.1 Principe

    Le LogForwarder :

    1. Collecte les logs dans une queue interne (non-bloquant)
    2. Envoie les logs en batch vers le LogHub (HTTP ou NATS)
    3. Stocke en H2 si le réseau est indisponible
    4. Rejoue automatiquement à la reconnexion

    6.2 Mode HTTP

    socle:
      logging:
        forwarder:
          enabled: true
          transport-mode: http
          log-hub-url: https://logs.mycompany.com/api/ingest-logs
    

    Les logs sont envoyés en POST avec JWT :

    POST /api/ingest-logs
    Authorization: Bearer <jwt>
    Content-Type: application/json
    
    [
      {"timestamp": "...", "level": "INFO", "message": "...", ...},
      {"timestamp": "...", "level": "ERROR", "message": "...", ...}
    ]
    

    6.3 Mode NATS

    socle:
      logging:
        forwarder:
          enabled: true
          transport-mode: nats
          nats-url: nats://nats.mycompany.com:4222
          nats-subject-prefix: logs
    

    Les logs sont publiés sur logs.<region>.<service> :

    logs.mtq.order-service
    logs.gua.sync-agent
    

    6.4 Fallback H2

    Si le transport échoue, les logs sont stockés dans socle_log_fallback :

    SELECT COUNT(*) FROM socle_log_fallback;  -- Logs en attente
    

    Ils sont automatiquement rejoués quand le transport redevient disponible.

    7. Format JSON des logs

    {
      "timestamp": "2025-12-09T10:30:00.123Z",
      "level": "INFO",
      "logger": "eu.lmvi.socle.mop.MainOrchestratorProcess",
      "thread": "main",
      "message": "MOP démarré avec succès",
      "service": "socle-v4",
      "region": "MTQ",
      "instanceId": "nuc-mtq-001",
      "execId": "20251209-1030-abc123",
      "correlationId": "MTQ-2025-12-09-000001",
      "mdc": {
        "worker": "http_worker",
        "phase": "startup"
      },
      "exception": null
    }
    

    8. Profils de configuration

    8.1 Développement

    <!-- log4j2-dev.xml -->
    <Configuration status="WARN">
        <Appenders>
            <Console name="Console" target="SYSTEM_OUT">
                <PatternLayout pattern="%d{HH:mm:ss.SSS} %highlight{%-5level} [%thread] %logger{36} - %msg%n"/>
            </Console>
        </Appenders>
        <Loggers>
            <Root level="DEBUG">
                <AppenderRef ref="Console"/>
            </Root>
        </Loggers>
    </Configuration>
    

    8.2 Production

    <!-- log4j2-prod.xml -->
    <Configuration status="ERROR">
        <Appenders>
            <Console name="ConsoleJson" target="SYSTEM_OUT">
                <JsonTemplateLayout eventTemplateUri="classpath:socle-log-template.json"/>
            </Console>
            <SocleLogForwarder name="LogForwarder" .../>
        </Appenders>
        <Loggers>
            <Root level="INFO">
                <AppenderRef ref="ConsoleJson"/>
                <AppenderRef ref="LogForwarder"/>
            </Root>
        </Loggers>
    </Configuration>
    

    8.3 Sélection du profil

    logging:
      config: classpath:log4j2-${spring.profiles.active}.xml
    

    9. Performances

    AsyncLoggers vs Sync

    Mode Throughput Latence
    Sync ~1M logs/sec Variable
    Async (LMAX) ~18M logs/sec Stable

    Bonnes pratiques

    // BON - Lazy evaluation
    log.debug("Processing: {}", () -> expensiveToString());
    
    // MAUVAIS - Toujours évalué
    log.debug("Processing: " + expensiveToString());
    

    10. Troubleshooting

    Logs non visibles

    1. Vérifier log4j2.xml dans src/main/resources/
    2. Vérifier les niveaux de log
    3. Vérifier logging.config dans application.yml

    AsyncLoggers non activés

    Vérifier que log4j2.component.properties existe et contient :

    Log4jContextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector
    

    LogForwarder queue pleine

    WARN - Log queue full, storing to fallback
    

    Solutions :

    • Augmenter queue-capacity
    • Réduire batch-size
    • Vérifier la connectivité réseau

    Logs en fallback non rejoués

    -- Vérifier les logs en attente
    SELECT COUNT(*) FROM socle_log_fallback;
    
    -- Forcer le replay (via API admin)
    POST /admin/logforwarder/replay
    

    11. Sécurité

    Log4Shell (CVE-2021-44228)

    Log4j2 2.22.1 est protégé contre Log4Shell. De plus :

    # Désactiver les lookups JNDI
    log4j2.formatMsgNoLookups=true
    

    Données sensibles

    // NE PAS logger de données sensibles
    log.info("User logged in: {}", user.getEmail());  // OK
    log.info("Password: {}", password);  // INTERDIT
    

    12. Références

  • Socle V004 – H2 et TechDB

    21 – H2 TechDB (Nouveaute V4)

    Version : 4.0.2 Date : 2026-01-15

    1. Introduction

    La H2 TechDB est une base de donnees embarquee introduite dans le Socle V4 pour stocker l’etat technique de maniere persistante.

    Pourquoi H2 ?

    Critere H2 Nitrite (ancien)
    Embarque ✅ ✅
    ARM/AMD64 ✅ ⚠️ Problemes
    UI debug ✅ H2 Console ❌
    JSON SQL ✅ JSON_VALUE ❌
    Stabilite ✅ ⚠️ v4 instable

    Nouveautes V4.0.1

    • Standard de tables x_ : Nouvelle structure avec champs techniques standardises
    • H2 Console sur port 9376 : Interface web dediee pour explorer la base
    • TechDbReaderWorker : Worker passif de lecture des donnees
    • TechDbPurgeWorker : Purge automatique des donnees obsoletes

    Nouveautes V4.0.2

    • API SQL REST : Nouveau endpoint /techdb/query pour requetes SQL via HTTP
    • Authentification Basic Auth : Securisation de l’acces API
    • Rate Limiting : Protection contre les abus (60 req/min/IP par defaut)
    • Mode Readonly : Protection contre les modifications accidentelles

    2. Cas d’usage

    La TechDB stocke :

    • Offsets/sequences : Position dans Kafka, NATS, DB2
    • Etat local des workers : Statut, derniere execution
    • Evenements techniques : Logs importants
    • Fallback logs : Logs non envoyes (LogForwarder)
    • Cle-valeur : Donnees generiques avec TTL

    3. Configuration

    3.1 application.yml

    socle:
      techdb:
        enabled: ${TECHDB_ENABLED:true}
        url: jdbc:h2:file:${TECHDB_PATH:./data/socle-techdb};MODE=PostgreSQL;DB_CLOSE_DELAY=-1;AUTO_SERVER=TRUE
        username: ${TECHDB_USERNAME:LMVI}
        password: ${TECHDB_PASSWORD:LMVI-SOCLEV004}
    
        # H2 Console Web (port 9376)
        console:
          enabled: ${TECHDB_CONSOLE_ENABLED:true}
          port: ${TECHDB_CONSOLE_PORT:9376}
          bind_address: ${TECHDB_CONSOLE_BIND:}
          allow_remote: ${TECHDB_CONSOLE_ALLOW_REMOTE:false}
    
        # Purge automatique des donnees anciennes
        purge:
          enabled: ${TECHDB_PURGE_ENABLED:true}
          schedule: ${TECHDB_PURGE_SCHEDULE:0 0 3 * * ?}  # 3h du matin
          events_retention_days: ${TECHDB_PURGE_EVENTS_DAYS:7}
          logs_retention_days: ${TECHDB_PURGE_LOGS_DAYS:3}
    

    3.2 Variables d’environnement

    Variable Description Defaut
    TECHDB_ENABLED Activer TechDB true
    TECHDB_PATH Chemin fichier H2 ./data/socle-techdb
    TECHDB_USERNAME Nom d’utilisateur LMVI
    TECHDB_PASSWORD Mot de passe LMVI-SOCLEV004
    TECHDB_CONSOLE_ENABLED Activer console web true
    TECHDB_CONSOLE_PORT Port console 9376
    TECHDB_CONSOLE_ALLOW_REMOTE Acces distant false
    TECHDB_PURGE_ENABLED Activer purge auto true
    TECHDB_PURGE_EVENTS_DAYS Retention events 7
    TECHDB_PURGE_LOGS_DAYS Retention logs 3

    3.3 Personnalisation des identifiants par environnement

    Les identifiants par defaut (LMVI / LMVI-SOCLEV004) conviennent pour le developpement et les tests. Pour la production, il est recommande de personnaliser via variables d’environnement.

    Docker Compose :

    services:
      mon-app:
        environment:
          - TECHDB_USERNAME=MonUserProd
          - TECHDB_PASSWORD=MonMotDePasseSecurise123!
    

    Java direct :

    export TECHDB_USERNAME=MonUserProd
    export TECHDB_PASSWORD=MonMotDePasseSecurise123!
    java -jar mon-application.jar
    

    Kubernetes :

    env:
      - name: TECHDB_USERNAME
        valueFrom:
          secretKeyRef:
            name: techdb-credentials
            key: username
      - name: TECHDB_PASSWORD
        valueFrom:
          secretKeyRef:
            name: techdb-credentials
            key: password
    

    Note : Si vous changez les identifiants sur une base existante, vous devez supprimer le fichier socle-techdb.mv.db et laisser l’application recreer la base.

    4. Schéma de base

    Les tables sont créées automatiquement au démarrage :

    -- Offsets / séquences
    CREATE TABLE IF NOT EXISTS socle_offsets (
        id IDENTITY PRIMARY KEY,
        source_name VARCHAR(200) NOT NULL,
        partition_key VARCHAR(200) NOT NULL,
        last_sequence BIGINT NOT NULL,
        last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        extra JSON,
        UNIQUE(source_name, partition_key)
    );
    
    -- État local des workers
    CREATE TABLE IF NOT EXISTS socle_worker_state (
        id IDENTITY PRIMARY KEY,
        worker_id VARCHAR(200) NOT NULL UNIQUE,
        status VARCHAR(20) NOT NULL,
        last_heartbeat TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        metadata JSON
    );
    
    -- Événements techniques
    CREATE TABLE IF NOT EXISTS socle_events (
        id IDENTITY PRIMARY KEY,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        type VARCHAR(100) NOT NULL,
        payload JSON
    );
    
    -- Fallback logs (LogForwarder)
    CREATE TABLE IF NOT EXISTS socle_log_fallback (
        id IDENTITY PRIMARY KEY,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        log_entry JSON NOT NULL,
        retry_count INT DEFAULT 0
    );
    

    5. Interface TechDbManager

    package eu.lmvi.socle.techdb;
    
    @Component
    public class TechDbManager {
    
        // ===== Lifecycle =====
    
        /**
         * Initialise la base H2 et crée les tables
         */
        public void initialize();
    
        /**
         * Ferme proprement la connexion
         */
        public void close();
    
        /**
         * Vérifie la santé de la base
         */
        public boolean isHealthy();
    
        // ===== Offsets =====
    
        /**
         * Sauvegarde un offset
         */
        public void saveOffset(String sourceName, String partitionKey,
                               long sequence, Map<String, Object> extra);
    
        /**
         * Récupère un offset
         */
        public OptionalLong getOffset(String sourceName, String partitionKey);
    
        /**
         * Liste tous les offsets d'une source
         */
        public List<OffsetRecord> getOffsets(String sourceName);
    
        // ===== Worker State =====
    
        /**
         * Sauvegarde l'état d'un worker
         */
        public void saveWorkerState(String workerId, String status,
                                    Map<String, Object> metadata);
    
        /**
         * Récupère l'état d'un worker
         */
        public Optional<WorkerState> getWorkerState(String workerId);
    
        // ===== Events =====
    
        /**
         * Enregistre un événement technique
         */
        public void logEvent(String type, Map<String, Object> payload);
    
        /**
         * Récupère les événements
         */
        public List<TechEvent> getEvents(String type, Instant since, int limit);
    
        // ===== Generic KV =====
    
        public void put(String key, String value);
        public Optional<String> get(String key);
        public void delete(String key);
    }
    

    6. Utilisation

    6.1 Injection

    @Service
    public class MonWorker implements Worker {
    
        @Autowired
        private TechDbManager techDb;
    
        @Override
        public void doWork() {
            // Récupérer le dernier offset
            OptionalLong lastOffset = techDb.getOffset("kafka", "my-topic-0");
            long startFrom = lastOffset.orElse(0L);
    
            // Traiter les messages...
            long newOffset = processMessages(startFrom);
    
            // Sauvegarder le nouvel offset
            techDb.saveOffset("kafka", "my-topic-0", newOffset,
                Map.of("processed", true));
        }
    }
    

    6.2 Gestion des offsets

    // Sauvegarder
    techDb.saveOffset("nats", "events.orders", 123456789L,
        Map.of("consumer", "order-processor"));
    
    // Récupérer
    OptionalLong offset = techDb.getOffset("nats", "events.orders");
    if (offset.isPresent()) {
        log.info("Dernier offset: {}", offset.getAsLong());
    }
    
    // Lister tous les offsets NATS
    List<OffsetRecord> offsets = techDb.getOffsets("nats");
    offsets.forEach(o -> log.info("{}: {}", o.partitionKey(), o.lastSequence()));
    

    6.3 État des workers

    // Sauvegarder l'état
    techDb.saveWorkerState("kafka-consumer-001", "RUNNING",
        Map.of(
            "lastProcessed", Instant.now(),
            "messagesPerMinute", 523
        ));
    
    // Récupérer l'état
    Optional<WorkerState> state = techDb.getWorkerState("kafka-consumer-001");
    state.ifPresent(s -> {
        log.info("Worker {} - Status: {}", s.workerId(), s.status());
    });
    

    6.4 Événements techniques

    // Logger un événement
    techDb.logEvent("PIPELINE_ERROR", Map.of(
        "pipeline", "order-processing",
        "error", "Connection timeout",
        "messageId", "msg-123"
    ));
    
    // Récupérer les événements récents
    List<TechEvent> errors = techDb.getEvents(
        "PIPELINE_ERROR",
        Instant.now().minus(1, ChronoUnit.HOURS),
        100
    );
    

    7. H2 Console Web (Port 9376)

    Le Socle V4 expose une console H2 dediee sur le port 9376 via le TechDbConsoleWorker.

    Acces

    http://localhost:9376
    

    Informations de connexion

    Champ Valeur
    JDBC URL jdbc:h2:./data/socle-techdb (local) ou jdbc:h2:/app/data/socle-techdb (Docker)
    User LMVI (defaut, personnalisable via TECHDB_USERNAME)
    Password LMVI-SOCLEV004 (defaut, personnalisable via TECHDB_PASSWORD)
    Driver org.h2.Driver

    Configuration

    socle:
      techdb:
        console:
          enabled: true       # Activer/desactiver
          port: 9376          # Port dedie
          bind_address: ""    # Vide = toutes interfaces
          allow_remote: false # Securite: localhost only
    

    Requetes utiles

    -- Voir tous les offsets
    SELECT * FROM techdb_offsets ORDER BY x_dateCreated DESC;
    
    -- Offsets Kafka uniquement
    SELECT * FROM techdb_offsets WHERE topic LIKE 'kafka%';
    
    -- Etat des workers
    SELECT worker_name, state, last_run_at, error_count FROM techdb_worker_state;
    
    -- Evenements non traites
    SELECT * FROM techdb_events WHERE processed = FALSE ORDER BY x_dateCreated;
    
    -- Logs non envoyes
    SELECT COUNT(*) as pending FROM techdb_log_buffer WHERE forwarded = FALSE;
    
    -- Cles KV avec expiration
    SELECT kv_key, value_type, expires_at FROM techdb_kv WHERE expires_at IS NOT NULL;
    

    8. API SQL REST (Nouveaute V4.0.2)

    Le Socle V4 expose une API REST permettant d’executer des requetes SQL sur la TechDB. Cette API est distincte de la console H2 et offre un acces programmatique securise.

    8.1 Configuration

    socle:
      techdb:
        sql_api:
          enabled: ${TECHDB_SQL_API_ENABLED:false}
          auth:
            user: ${TECHDB_API_USER:admin}
            password: ${TECHDB_API_PASSWORD:}
          security:
            readonly: ${TECHDB_SQL_API_READONLY:true}
            blocked_tables: ${TECHDB_SQL_API_BLOCKED_TABLES:}
          limits:
            max_rows: ${TECHDB_SQL_API_MAX_ROWS:1000}
            timeout_seconds: ${TECHDB_SQL_API_TIMEOUT:30}
            rate_limit_per_minute: ${TECHDB_SQL_API_RATE_LIMIT:60}
          logging:
            log_queries: ${TECHDB_SQL_API_LOG_QUERIES:true}
    

    8.2 Variables d’environnement

    Variable Description Defaut
    TECHDB_SQL_API_ENABLED Activer l’API SQL false
    TECHDB_API_USER Utilisateur Basic Auth admin
    TECHDB_API_PASSWORD Mot de passe (vide = pas d’auth) « 
    TECHDB_SQL_API_READONLY Mode lecture seule true
    TECHDB_SQL_API_BLOCKED_TABLES Tables interdites (CSV) « 
    TECHDB_SQL_API_MAX_ROWS Limite de lignes 1000
    TECHDB_SQL_API_TIMEOUT Timeout requetes (sec) 30
    TECHDB_SQL_API_RATE_LIMIT Requetes/minute/IP 60

    8.3 Endpoints

    Methode Path Description
    POST /techdb/query Executer une requete SQL
    GET /techdb/tables Liste des tables
    GET /techdb/tables/{name} Details d’une table
    GET /techdb/stats Statistiques DB

    8.4 Authentification

    L’API utilise Basic Auth. Si un mot de passe est configure, toutes les requetes doivent inclure l’en-tete:

    Authorization: Basic base64(user:password)
    

    Exemple avec curl:

    # Sans authentification (si TECHDB_API_PASSWORD vide)
    curl http://localhost:8080/techdb/tables
    
    # Avec authentification
    curl -u admin:monmotdepasse http://localhost:8080/techdb/query \
      -H "Content-Type: application/json" \
      -d '{"sql": "SELECT * FROM techdb_kv LIMIT 10"}'
    

    8.5 Executer une requete SQL

    Requete:

    curl -X POST http://localhost:8080/techdb/query \
      -H "Content-Type: application/json" \
      -u admin:secret \
      -d '{
        "sql": "SELECT * FROM techdb_events WHERE event_type = ?",
        "params": ["WORKER_START"],
        "maxRows": 100
      }'
    

    Reponse succes:

    {
      "success": true,
      "timestamp": 1705312800000,
      "executionTimeMs": 12,
      "rowCount": 15,
      "columns": ["X_ID", "X_DATECREATED", "EVENT_TYPE", "SOURCE", "DATAS"],
      "rows": [
        {"X_ID": 1, "X_DATECREATED": "2025-01-15T10:00:00", "EVENT_TYPE": "WORKER_START", ...},
        ...
      ],
      "truncated": false
    }
    

    Reponse erreur:

    {
      "success": false,
      "timestamp": 1705312800000,
      "error": {
        "code": "SQL_SYNTAX_ERROR",
        "message": "Syntax error in SQL statement"
      }
    }
    

    8.6 Codes d’erreur

    Code HTTP Status Description
    SQL_SYNTAX_ERROR 400 Erreur de syntaxe SQL
    DDL_NOT_ALLOWED 403 Operation DDL interdite
    READONLY_VIOLATION 403 Non-SELECT en mode readonly
    TABLE_BLOCKED 403 Table bloquee par config
    QUERY_TIMEOUT 408 Timeout depasse
    UNAUTHORIZED 401 Authentification requise
    RATE_LIMITED 429 Limite requetes depassee
    TECHDB_DISABLED 503 TechDB non disponible

    8.7 Securite

    Operations toujours interdites:

    • DDL: DROP, ALTER, CREATE, TRUNCATE, GRANT, REVOKE
    • Commandes dangereuses: SHUTDOWN, SCRIPT, BACKUP, RESTORE

    Mode readonly (defaut):

    • Seuls les SELECT sont autorises
    • INSERT, UPDATE, DELETE interdits

    Tables bloquees:

    socle:
      techdb:
        sql_api:
          security:
            blocked_tables: techdb_log_buffer,techdb_kv  # CSV
    

    8.8 Rate Limiting

    L’API applique un rate limiting par IP (sliding window par minute).

    Par defaut: 60 requetes/minute/IP

    Depassement = HTTP 429 Too Many Requests

    8.9 Metriques Prometheus

    techdb_sql_api_queries_total{status="success|error|timeout"}
    techdb_sql_api_queries_duration_seconds
    techdb_sql_api_auth_failures_total
    techdb_sql_api_rate_limited_total
    

    8.10 Exemples pratiques

    Lister les tables:

    curl http://localhost:8080/techdb/tables
    

    Details d’une table:

    curl http://localhost:8080/techdb/tables/TECHDB_EVENTS
    

    Statistiques DB:

    curl http://localhost:8080/techdb/stats
    

    Requete avec parametres:

    curl -X POST http://localhost:8080/techdb/query \
      -H "Content-Type: application/json" \
      -d '{
        "sql": "SELECT worker_name, state, error_count FROM techdb_worker_state WHERE state = ?",
        "params": ["RUNNING"]
      }'
    

    9. Workers TechDB

    Le Socle V4 inclut 3 workers dedies a la gestion de TechDB:

    9.1 TechDbReaderWorker

    Worker PASSIVE exposant des methodes de lecture.

    @Autowired
    private TechDbReaderWorker reader;
    
    // Recuperer tous les offsets
    List<Map<String, Object>> offsets = reader.getAllOffsets();
    
    // Recuperer les evenements recents
    List<Map<String, Object>> events = reader.getRecentEvents(100);
    
    // Executer une requete personnalisee
    List<Map<String, Object>> results = reader.executeCustomQuery(
        "SELECT * FROM techdb_worker_state WHERE state = 'RUNNING'"
    );
    

    9.2 TechDbPurgeWorker

    Worker CRON qui purge automatiquement les donnees obsoletes.

    socle:
      techdb:
        purge:
          enabled: true
          schedule: "0 0 3 * * ?"  # 3h du matin
          events_retention_days: 7
          logs_retention_days: 3
    

    Donnees purgees :

    • Evenements traites > 7 jours
    • Logs forwardes > 3 jours
    • Cles KV expirees

    9.3 TechDbConsoleWorker

    Worker PASSIVE qui demarre la console H2 sur le port 9376.

    @Autowired
    private TechDbConsoleWorker console;
    
    // Verifier si la console est accessible
    boolean running = console.isConsoleRunning();
    
    // Obtenir les infos de connexion
    Map<String, String> info = console.getConnectionInfo();
    

    10. Fonctions JSON H2

    H2 2.x supporte les fonctions JSON SQL standard :

    -- Extraction de valeur
    SELECT JSON_VALUE('{"name":"John","age":30}', '$.name');
    -- Résultat: John
    
    -- Extraction d'objet
    SELECT JSON_QUERY('{"data":{"items":[1,2,3]}}', '$.data');
    -- Résultat: {"items":[1,2,3]}
    
    -- Test d'existence
    SELECT JSON_EXISTS('{"name":"John"}', '$.name');
    -- Résultat: TRUE
    
    -- Construction JSON
    SELECT JSON_OBJECT('name': 'John', 'age': 30);
    -- Résultat: {"name":"John","age":30}
    
    -- Filtrage sur JSON
    SELECT * FROM socle_events
    WHERE JSON_VALUE(payload, '$.severity') = 'ERROR';
    

    11. Integration avec SharedDataRegistry

    TechDB complète SharedDataRegistry :

    Aspect SharedDataRegistry TechDbManager
    Scope Runtime (mémoire) Persistant (fichier)
    Survie restart Non Oui
    Performance Ultra rapide Rapide
    Usage Métriques live Offsets, état

    Exemple de synergie

    @Service
    public class MonService {
    
        @Autowired
        private TechDbManager techDb;
    
        @Autowired
        private SharedDataRegistry sharedData;
    
        public void initialize() {
            // Restaurer l'offset depuis TechDB
            OptionalLong persisted = techDb.getOffset("kafka", "topic-0");
    
            // Créer le compteur en mémoire
            sharedData.createSequence("kafka.offset.topic-0",
                persisted.orElse(0L),
                HealthLevel.CRITICAL);
        }
    
        public void onMessage(long offset) {
            // Mettre à jour en mémoire (rapide)
            sharedData.setSequence("kafka.offset.topic-0", offset);
    
            // Persister périodiquement (moins fréquent)
            if (offset % 1000 == 0) {
                techDb.saveOffset("kafka", "topic-0", offset, null);
            }
        }
    }
    

    12. Bonnes pratiques

    DO

    • ✅ Utiliser TechDB pour les données qui doivent survivre au restart
    • ✅ Persister les offsets périodiquement (pas à chaque message)
    • ✅ Utiliser JSON pour les métadonnées flexibles
    • ✅ Activer H2 Console uniquement en dev

    DON’T

    • ❌ Stocker des données volumineuses (utiliser PostgreSQL)
    • ❌ Faire des requêtes complexes en boucle doWork()
    • ❌ Activer H2 Console en production
    • ❌ Utiliser pour du cache haute fréquence (utiliser KvBus)

    13. Troubleshooting

    Base corrompue

    # Supprimer et recréer
    rm -rf ./data/socle-techdb.*
    # Redémarrer l'application
    

    Fichier verrouillé

    Database may be already in use: "locked by another process"
    

    Solution : Arrêter l’autre instance ou utiliser AUTO_SERVER=TRUE dans l’URL.

    Console H2 inaccessible

    1. Vérifier socle.techdb.console.enabled: true
    2. Vérifier que l’application tourne
    3. Essayer avec le chemin complet du fichier

    14. References

    Socle V004 – TechDB H2

Gérer mes cookies