@startuml
title Stream — Partner Heartbeat et propagation CRUD Pair A ↔ Pair B

participant "DB Pair A (oc-lib)" as DBA
participant "StreamService A" as StreamA
participant "Node A" as NodeA
participant "Node B" as NodeB
participant "StreamService B" as StreamB
participant "NATS B" as NATSB
participant "DB Pair B (oc-lib)" as DBB
participant "NATS A" as NATSA

note over StreamA: Démarrage → connectToPartners()

StreamA -> DBA: Search(PEER, PARTNER) + PeerIDS config
DBA --> StreamA: [Peer B, ...]

StreamA -> NodeB: Connect (libp2p)
StreamA -> NodeB: NewStream /opencloud/resource/heartbeat/partner/1.0
StreamA -> NodeB: json.Encode(Heartbeat{Name_A, DID_A, PeerID_A, IndexersBinded_A})

NodeB -> StreamB: HandlePartnerHeartbeat(stream)
StreamB -> StreamB: CheckHeartbeat → bandwidth challenge
StreamB -> StreamA: Echo(payload)
StreamB -> StreamB: streams[ProtocolHeartbeatPartner][PeerID_A] = {DID_A, Expiry=now+10s}

StreamA -> StreamA: streams[ProtocolHeartbeatPartner][PeerID_B] = {DID_B, Expiry=now+10s}

note over StreamA,StreamB: Stream partner long-lived établi\nGC toutes les 8s (StreamService A)\nGC toutes les 30s (StreamService B)

note over NATSA: Pair A reçoit PROPALGATION_EVENT{PB_DELETE, dt:"storage", payload:res}

NATSA -> NodeA: ListenNATS → ToPartnerPublishEvent(PB_DELETE, dt, user, payload)
NodeA -> StreamA: ToPartnerPublishEvent(ctx, PB_DELETE, dt_storage, user, payload)

alt dt == PEER (mise à jour relation partenaire)
    StreamA -> StreamA: json.Unmarshal → peer.Peer B updated
    alt B.Relation == PARTNER
        StreamA -> NodeB: ConnectToPartner(B.StreamAddress)
        note over StreamA,NodeB: Reconnexion heartbeat si relation upgrade
    else B.Relation != PARTNER
        loop Tous les protocoles
            StreamA -> StreamA: delete(streams[proto][PeerID_B])
            StreamA -> NodeB: (streams fermés)
        end
    end
else dt != PEER (ressource ordinaire)
    StreamA -> DBA: Search(PEER, PARTNER) → [Pair B, ...]
    loop Pour chaque protocole partner (Create/Update/Delete)
        StreamA -> NodeB: write(PeerID_B, addr_B, dt, user, payload, ProtocolDeleteResource)
        note over NodeB: /opencloud/resource/delete/1.0

        NodeB -> StreamB: HandleResponse → readLoop
        StreamB -> StreamB: handleEventFromPartner(evt, ProtocolDeleteResource)
        StreamB -> NATSB: SetNATSPub(REMOVE_RESOURCE, {DataType, resource JSON})
        NATSB -> DBB: Supprimer ressource dans DB B
    end
end

@enduml
