LibreSocial · Documentation

Messaging — channels, dispatchers, events and aggregation

Deep-dive page: the framework-level com.p2pframework.message packages (message types, MessageDispatcher, MessageChannel, TopicChannel, AggregationChannel), the application-level com.p2pframework.messagedispatcher bundle, the com.p2pframework.events notification system and com.p2pframework.errorhandling.

Supersession note: the plugin/messaging API as plugins use it today is not the 2008 design. Its core architecture (Information Cache, user-ID resolution, store-for-offline-recipients) goes back to Podrajanski 2008, its OSGi packaging to Alviṭe 2008 and the plugin-notification model to IEEE ISM08 2008. The com.p2pframework.message / messagedispatcher / events layer as it exists in the source was created by the 2011/12 project group (PG 2011), described in Framework Overview 2013, instrumented by Peng 2014 and Schulte 2015, and formalised in Graffi 2020. What follows describes the 2026 source state: Java 17, Gradle/bnd build, the 2026 refactor commits.

Purpose

One precision first, because the component name is misleading: there is no bundle called com.p2pframework.message. That is a package, and it lives inside the framework bundle:

Scope Real path in the repository Role
Message types, channel interfaces, MessageDispatcher Source/com.p2pframework/src/com/p2pframework/message/ overlay-independent abstraction over FreePastry
FreePastry implementation Source/com.p2pframework/src/com/p2pframework/message/scribe/ CommonAPI endpoints + Scribe multicast
Attribute aggregation (SkyEye over-overlay) Source/com.p2pframework/src/com/p2pframework/message/aggregate/ Sensor/Attribute/AggregationServer/Aggregator
Plugin-facing messaging service Source/com.p2pframework.messagedispatcher/ (OSGi bundle) IMessageDispatcher, offline storage, listener registry
Notifications Source/com.p2pframework/src/com/p2pframework/events/ 4-value lifecycle Event enum + EventListener
Error handling Source/com.p2pframework/src/com/p2pframework/errorhandling/ error codes, stack-trace files, p2pErrors.xml lookup

Messaging answers four questions for the rest of the platform: how does one node address another (MessageChannel), how do many nodes share a topic (TopicChannel), how is a network-wide value computed from per-node values (AggregationChannel), and how does a plugin deliver a message to a user who is currently offline (the messagedispatcher bundle plus PAST storage). It is the layer the storage dispatcher and the overlay are built around, and the transport for the distributed data structures (OperationMessage in com.p2pframework.DDS) and for the monitoring system.

Current implementation (as of 2026)

Framework bundle. com.p2pframework.message* is part of the com.p2pframework bundle (Require-Bundle version 0.0.1); nothing in it is an OSGi service of its own — PastryMessageDispatcher is created lazily by Framework.getMessageDispatcher() through PastryClassFactory.

The messagedispatcher bundle is built with bnd/bndtools under Gradle (Source/com.p2pframework.messagedispatcher/bnd.bnd): Bundle-SymbolicName: com.p2pframework.messagedispatcher, version 1.0.0.qualifier, Bundle-RequiredExecutionEnvironment: JavaSE-17, -dsannotations: *, exports com.p2pframework.messagedispatcher and org.lifesocial.messagedispatcher.api, requires rice.freepastry 1.0.0, org.lifesocial.core 1.0.0 and com.p2pframework 0.0.1, plus implementation projects :com.p2pframework, :com.p2pframework.storagedispatcher, :org.lifesocial.core.logger, :org.lifesocial.core.main, :org.lifesocial.core.utilities (Gradle). The generated build/resources/main/OSGI-INF/MessageDispatcher.xml declares the three DS references SD (IStorageDispatcher), LOG (ILogService) and FRAMEWORK, all cardinality 1..1, mandatory, dynamic. A stale build/tmp/jar/MANIFEST.MF still says JavaSE-1.7 — a leftover artifact.

src/com/p2pframework/messagedispatcher/MessageDispatcher.java   462 l   @Component, IMessageDispatcher impl
src/org/lifesocial/messagedispatcher/api/IMessageDispatcher.java        plugin-facing API
src/org/lifesocial/messagedispatcher/api/MessageListener.java           messageReceived / checkForUndeliveredMessages

Message type hierarchy. Message is an interface extending Serializable with getSender/setSender, getReceiver/setReceiver (both framework IDs) and double getSize()/setSize(double).

Class Notes
MessageImpl serialVersionUID = -935892454297735982L; equals/hashCode over sender + receiver only
GenericMessage<Type extends Serializable> the generic payload holder (store field, serialVersionUID 7175261774516292140L); the source comment notes that the generic type argument is erased at runtime, so receivers must downcast
SecureMessage 237 lines; symmetric/asymmetric encryption + ECDSA signature wrapper (see Technical details)
PastryMessage adapter implementing rice.p2p.commonapi.Message and rice.p2p.scribe.ScribeContent; getPriority() returns LOW_PRIORITY
AggregateMessage extends GenericMessage<Hashtable<String,Attribute<Serializable>>>, plus boolean global and long timeOverhead
SocialCachingMessage, TestCaseCommandMessage cache push / test-harness command (with repetitions, priority, recipient list)
AbstractBasicMessage (org.lifesocial.core.data.common) plugin payload; also a rice.p2p.commonapi.Message, LOW_PRIORITY "to prevent interference with overlay maintenance traffic"

MessageDispatcher (interface) → PastryMessageDispatcher. The interface offers createMessageChannel(String[, MessageCallback]), createTopicChannel(String[, SecretKey]), createAggregationChannel(String) and getAllAggregationChannel(). The Pastry implementation requires a PastryNetwork (otherwise IllegalArgumentException("PastryMessageDispatcher needs a PastryNetwork")), keeps three caches (messageCache, topicCache, aggregateCache — the topic cache enforces the documented rule that there must be only one TopicChannel per topic) and owns one ScribeImpl per node, built with the internal topic prefix "com.p2pframework.topic", destroyed on NETWORK_DISCONNECT and rebuilt on NETWORK_PRECONNECT; on rebuild every cached PastryTopicChannel gets the new Scribe via setScribe(). It is itself an EventListener and exports the monitoring attributes MESSAGEDISPATCHER_MESSAGES_SENT, _SENT_RATE, _MESSAGES_RECEIVED, _RECEIVED_RATE, _MESSAGES_LOST, _NULL_POINTER, _OTHER_EXCEPTION.

PastryMessageChannel (304 lines) implements rice.p2p.commonapi.Application, MessageChannel and EventListener. The CommonAPI application name is the channel name prefixed with com.p2pframework.message., i.e. channels are ordinary Pastry endpoints (network.getOwnPastryNode().buildEndpoint(this, this.name), then register()). Sending is endpoint.route(((PastryID) message.getReceiver()).getId(), new PastryMessage(message), null); sendMessageSynchronous() adds a PastryDeliveryNotificationContinuation (semaphore) and calls waitForCompletion(), which throws SendingFailedException. Variants in the 2026 source: sendMessage(Collection<ID>, …), relayMessageToResponsibleNode(hash, …), sendMessageToResponsibleNode[…Synchronous](hash, …) (hash → PastryIdFactory.buildId, receiver set to null, so the responsible node answers — used by the storage/messaging lookup flows), sendMessageDirect() (routes to a NodeHandle instead of an ID), and the two scheduleMessage(message, start[, period]) passthroughs to the Pastry endpoint. On delivery, sender and receiver IDs are re-normalised through network.getPropperID() before callbacks run. Callbacks registered with register()/unregister() are held in a Collections.synchronizedList(new CopyOnWriteArrayList<>()). Attributes: MESSAGECHANNEL_MESSAGES_SENT, MESSAGECHANNEL_MESSAGES_RECEIVED (strategy sum).

PastryTopicChannel (433 lines) implements TopicChannel + ScribeMultiClient. The topic is new Topic(new PastryIdFactory(env), channelName), so topic routing is a DHT-key lookup and delivery is Scribe multicast down the topic tree. Subscription is offered both asynchronously (trySubscribe, four overloads) and synchronously (subscribe, which polls every 100 ms until subscribed(...) fires and then throws SubscriptionFailedException if it never did — the source still carries // TODO: Add a timeout when to cancel subscribing). Unsubscription throws UnsubscriptionFailedException. Anycast is supported separately through TopicChannelAnyCastCallback.acceptAnycast(String topic, Message). If the channel was created with a SecretKey, every publication is wrapped as new SecureMessage(msg, key) before scribe.publish(...) — group topics are therefore encrypted with a shared symmetric key. Attributes: TOPICCHANNEL_MESSAGES_SENT, TOPICCHANNEL_MESSAGES_RECEIVED (sum).

AggregationChannel / AggregationServer. AggregationChannel is a Sensor: getAttributes() returns a Hashtable<String, Attribute<Serializable>> and addSensor(Sensor)/removeSensor(Sensor) pull attributes from other components. Each Attribute carries name, value, unit, an AggregationStrategy and participants (default 1); the 2026 strategy enum is assign, bool, nonInteger, trueToHash, collectionRetainAll, multiMapAddAbortIfNull, multiMapAddAbortIfLeafsComplete, smallestNonNegative, smallest, greatest, sum, mean, joinCollection, orCollection. AggregationServer (386 lines) builds the aggregation tree with splitFactor = 8, timeStep = 5000 ms, timeDelay = 50 ms and numOfCombinedRounds = ConfigLoader.getIntConfigProperty("combineParameter"); domain keys are BigDecimal values getDomainKeyForLevel(l) = start + step/2 with step = 1/splitFactor^l, and a parent is found by scanning levels (l < 1000) with frame.getNetwork().isResponsibleFor(nodeId). Bottom-up AggregateMessage(…, false) updates go to the parent coordinator, the root combines numOfCombinedRounds rounds with its own attributes and pushes global values top-down as AggregateMessage(sender, globalAttributes, true, timeOverhead). One instance per node, created by com.p2pframework.DDS.DataBackend on the shared channel "com.p2pframework.Backend"; the Timer is cancelled on NETWORK_DISCONNECT and addTimerDelay() clamps negative delays to 0 with a stderr warning.

Events. com.p2pframework.events is deliberately tiny: enum Event { NETWORK_PRECONNECT, NETWORK_CONNECT, NETWORK_PREDISCONNECT, NETWORK_DISCONNECT }, EventListener.eventFired(Event, Object source, Object param), EventProvider.fireEvent/addEventListener/removeEventListener. Framework (@Component(name = "Framework", service = Framework.class)) implements EventProvider with a LinkedList<EventListener> and a synchronized fireEvent. Messaging objects react rather than poll: PastryMessageChannel destroys its endpoint on NETWORK_PREDISCONNECT (Destructable) and rebuilds it on NETWORK_PRECONNECT, PastryMessageDispatcher re-creates Scribe on connect, AggregationServer re-arms its timer. Plugin-to-plugin notification is not this enum but the pull model of MessageListener/checkForUndeliveredMessages().

Application-level bundle com.p2pframework.messagedispatcher. The component is @Component(name = "MessageDispatcher", immediate = true, service = IMessageDispatcher.class) and also a framework MessageCallback. In the 2026 code the listener registry is a ConcurrentHashMap<String, MessageListener> messageListeners keyed by plugin id, delivery of cached items runs on Executors.newFixedThreadPool(5), lifecycle is guarded by lifecycleLock + AtomicBoolean started, and the three OSGi references are volatile. sendMessage(usrname, msg, className) resolves the recipient with requestIDForUsername(); if it returns null the message is stored instead of sent — sd.storeSharedItem(msg, className) plus a KeyHolderItem whose storage key is HashKeyBuilder.buildKey(username + pluginId). Online recipients get new SecureMessage(new GenericMessage<>(msg), usrId.getPublicKey(), network.getUserKey().getPrivate(), network.getOwnID()) — encrypt to the recipient's public key and sign with the sender's private key. sendMessageWithoutStoring() skips the store path and dispatches on the thread pool ("to prevent mistakes which happens when receiving and directly send a message"); this is what messagingplugin, notifications (push to the web provider over NotificationSocket), friendsplugin, groups, livechatplugin, voting, wallplugin, webprovider and tester call. Inbound framework messages are decrypted/verified with decryptAndVerify(userKey.getPrivate(), sender.getPublicKey()), unwrapped by extractStoredMessage() (which requires a GenericMessage containing a rice.p2p.commonapi.Message, otherwise ClassCastException("Expected GenericMessage containing rice.p2p.commonapi.Message: …")), then receiveMessage(msg, className) writes them into InformationCache.addMsg(pluginId, msg) + InformationCache.addReceivedMsgToMonitoring(pluginId, msg) and invokes only the listener registered under that plugin id (wrapped in a try/catch so a failing plugin cannot break the dispatcher). A decrypt failure for a message addressed to somebody else is logged as "Received a message for somebody else: … We cannot decrypt it. This can happen when the target is offline and this node becomes responsible." — a direct consequence of routing user messages to the node responsible for the recipient's ID.

Error handling. IErrorHandling (impl ErrorHandling, 269 lines, created lazily by Framework.getErrorHandling()) exposes getAllDetails, getErrorMessage, getErrorCause, displayStackTraceInformation, getErrorStack(int|Exception), errorCorrection(int), errorPrintOnErrorConsole(); it writes stack traces into the configured error-log directory and maps throwables to codes with the generated GetErrorCodeFromClass (775 lines, hundreds of JDK exception classes — codes like C0039N0000F0005E0000). ErrorDatabase parses p2pErrors.xml from Configuration.getErrorLogDirectory() + "/p2pErrors.xml", falling back to ./p2pErrors.xml; the file is not in the repository, so it is an optional runtime dependency. The message layer exception family: MessageException extends P2PFrameworkException, SendingFailedException, SubscriptionFailedException, UnsubscriptionFailedException.

Design options and decision

Decision Chosen Alternatives in the literature Trade-off, as documented
How plugins get new data push over named channels (MessageChannel, TopicChannel, AggregationChannel, StreamChannel wrappers around Pastry) client-side polling of the Information Cache documented decision. The 2011/12 group explicitly replaced polling with push; the chat plug-in was the first converted. Polling costs latency and duplicate work per plugin; push costs a registry per channel and needs the pre/post-connect re-binding seen above (PG 2011)
Plugin notification request-based (plugin calls checkForUndeliveredMessages(), MessageListener.checkForUndeliveredMessages()), while time-critical traffic goes straight through the dispatcher event-triggered callbacks pushed into every plugin documented decision (IEEE ISM08 2008): keeping plugins stateless and simple was worth the extra latency; only latency-critical paths got direct channel access
Network-wide aggregates structured aggregation tree over the DHT ID space mapped to [0,1], domain keys + isResponsibleFor, bottom-up update / top-down global ACK, per-hop retransmission (a) a central monitoring server, (b) unstructured gossip / epidemic aggregation (Astrolabe, Willow, SOMO, SDIMS, T-MAN, CONE, Proactive Epidemic Aggregation), (c) overlay-native or multi-tree designs documented landscape (SkyEye 2008, Gross MA 2009, Graffi 2010, SkyEye journal 2017). A central server is a single point of failure and a bandwidth sink; gossip is churn-tolerant but has no global view and unbounded message cost. The DHT tree is overlay-independent (survives a Pastry replacement), needs only O(1) per-hop state, ~<100 B/s per peer and <165 B/s global at 5 s granularity, but its list-based strategies grow exponentially towards the root unless filtered/incremental, and mean/sum need the participants counter
Recipient addressing framework ID = Pastry node ID; messages are routed to the node responsible for the user's ID name-based directory server; store-and-forward relay peers reconstructed from Podrajanski 2008 and the framework paper 2020: reusing the DHT's location service avoids a second, centralised naming service, at the price of "wrong-node" deliveries that the 2026 code logs as a warning
Offline recipients store the message itself in PAST plus a KeyHolderItem index per (plugin, user) local spool on the sender; a dedicated mail server reconstructed: PAST storage makes offline delivery work from any device the user later logs in on (hence messageAutoDeleted = 0 in the config), at the cost of extra PAST puts and the privacy trade-off of persisting ciphertext
Wire format Java serialization (Message extends Serializable, explicit serialVersionUIDs, ObjectOutputStream inside SecureMessage and the size measurement) XML/JSON, Protobuf reconstructed from the 2020 requirement set (encrypted and signed objects with authenticated IDs) plus the source: objects are stored in PAST as serialized items, so a second encoding would have to be added at both the storage and the messaging layer; the cost is a Java-only ecosystem and brittle serialVersionUID coupling
Transport priority LOW_PRIORITY for all application and AbstractBasicMessage traffic high priority for chat/notification documented in the AbstractBasicMessage comment: low priority prevents interference with overlay maintenance traffic

Technical details

Serialization. Everything crossing a channel is Serializable: Message extends Serializable, PastryMessage (-7281530716278783562L) is the one class satisfying both the framework interface and Pastry's Message/ScribeContent, Attribute carries -8628609883753073943L. SecureMessage.plainSerialize() uses ObjectOutputStream; DataBackend measures its own traffic the same way (traffic += array.length / 1024; messages++), in a block the source marks //----------- remove this!!!!!.

SecureMessage internals. Flags isEncrypted, encryptionMode (true = symmetric), isSigned; payload byte[] encryptedBytes, byte[] signature. The constructor selects the mode: SecretKey — AESSymmetricKey.encryptObject, PublicKey — ECAsymmetricKey.encryptObject, and the (PublicKey, PrivateKey, ID) form used by the plugin dispatcher encrypts to the recipient and signs encryptedBytes with the sender's EC private key. decrypt(SecretKey|PrivateKey), verify(PublicKey) and decryptAndVerify(PrivateKey, PublicKey) undo it. Measured overheads (framework paper 2020): ECC +42-52 bytes, sign/verify 1.6-8.1 ms, AES +3-16 bytes, <1 ms.

Instrumentation keys and the measurement path. PastryMessageChannel and PastryTopicChannel call MeasuringMessageImpl.collect(measuringDataProperty, key, "send"|"receive", msg), with measuringDataProperty = ConfigLoader.getIntConfigProperty("measuringData") (config value 1). Keys: MESSAGEDISPATCHER_MESSAGES_SENT_SIZE, MESSAGEDISPATCHER_MESSAGES_SEND_SIZE (a second, inconsistent spelling for the sync/relay paths), MESSAGEDISPATCHER_MESSAGES_RECEIVED_SIZE, MESSAGEDISPATCHER_MONITORING_MESSAGES_RECEIVED_SIZE, MESSAGEDISPATHCER_MONITORING_MESSAGES_SENT_SIZE (the typo is in the source). Size is measured by serializing under a timeout (callWithTimeout(() -> getSizeOfObject(oTemp), 50, MILLISECONDS), int timeLimit = 40, misses counted in missedCalculation); monitoring messages get a hard-coded 28 000 bytes. AggregationServer keeps combineParameter = 3 rounds in previousRounds and reports timeOverhead.

Parameters that matter in practice.

Parameter Where Value (2026)
measuringData resources/config/LibreSocialConfig.txt → ConfigLoader 1 (enables per-message size collection)
combineParameter AggregationServer.numOfCombinedRounds 3 rounds combined at the root
splitFactor, timeStep, timeDelay AggregationServer fields 8, 5000 ms, 50 ms — hard-coded, not config
rate buffer length RateBuffer(5) in PastryMessageDispatcher code uses 5; Peng 2014 documents a configuration default of 2
thread pool messagedispatcher Executors.newFixedThreadPool(5)
sync-send handshake PastryDeliveryNotificationContinuation semaphore + Thread.sleep(50), commented "needed to make synchronous message sending work on the same machine"
topic subscribe timeout PastryTopicChannel.subscribe() 100 ms poll loop, no timeout
level scan AggregationServer.getParentCoordinator() l < 1000

Metric naming. Peng 2014 defines <component>_<metric>_<unit> with prefixes FRAMEWORK_, MIDWARE_, OVERLAY_, PLUGIN_, STORAGE_, MESSAGEDISPATCHER_; Schulte 2015 catalogues the result (MIDWARE_MESSAGE_RATE_MSG/S, OVERLAY_MESSAGES_SENT_TOTAL_MSG, ...). PastryMessageDispatcher.generateMinMaxMeanAttribute() emits _MIN/_MAX/_MEAN; MonitoringThread implements GlobalAttributeCallback, opens createAggregationChannel(this.getClass().getName()), calls addSensor() for network, message dispatcher and storage dispatcher, and prefixes global attributes GLOBAL_.

Defects and sharp edges in the 2026 source. (a) Aggregator.aggregate has no break after case mean: (line 112), so mean falls through into the bool branch. (b) MeasuringMessage*Impl compare if (type=="receive") by string identity. (c) Static mutable counters (PastryMessageDispatcher.nullCounter, otherExceptionCounter, PastryTopicChannel.registTime) are per-JVM and aggregated with sum. (d) PastryMessageDispatcher line 219 feeds messageReceivedRateBuffer with the sent value, so …_MESSAGES_RECEIVED_RATE tracks the sent rate. (e) Debug output remains (System.out.println("MY ID IS: …"), four System.err.println per sendMessage, a println in SecureMessage.verify). (f) createMessageChannel caches by the bare name while the endpoint uses the com.p2pframework.message. prefix — two namespaces per channel. (g) The MessageDispatcher deadlock documented in Framework Overview 2013 disabled the chat plug-in; the Thread.sleep(50) in the synchronous continuation and the thread-pool indirection in sendMessageWithoutStoring are the surviving workarounds. (h) A 2011-era scratch main() still ships in errorhandling.ErrorCheck.

Evolution and supersession