Programming Search⌘K

Patterncore

Wire Tap

Also called Wire Tap pattern, message tap, message tracing, firehose.

A wire tap is a fixed recipient list with two outputs; it sends each message on a channel to its normal receiver and a copy to a second channel, where a tool can inspect, log or store it.

Family
integration
Intent
Inspect the messages on a channel, for testing, monitoring or audit, by a step that sends each message on to the main channel and a copy of it to a secondary channel, with no change to the sender or the receiver.
Also called
message tap

Intent

See each message on a channel without a change to the flow. The book asks: "How do you inspect messages that travel on a point-to-point channel?"12 The answer: "Insert a simple Recipient List into the channel that publishes each incoming message to the main channel and a secondary channel."1

Problem

A Point-to-Point Channel gives each message to exactly one consumer. This is the reason to use it for a document that only one receiver must process.1 But for a test, for monitoring or for a fault search, you often want to see all the messages that go through the channel.1

A second consumer on the same channel does not help, because it takes messages away from the real receiver. A change to the sender or the receiver to log each message puts monitoring code into business code, and you must change it again to turn the logging off.

Solution

Put a small step into the channel. The step takes each message from the input channel and sends the message, with no change, to two output channels: the main channel, from which the receiver now reads, and a secondary channel for the tool that inspects it.1 It is a recipient list that never changes and always has the same two outputs.1

                           +--> [ main ] --> receiver
  sender --> [ in ] --> wire tap
                           +--> [ tap ] --> monitor, log or message store

The participants are the input channel, the wire tap, the main channel with the real receiver, and the secondary channel with its consumer. Because the logic that inspects the messages is in a separate component, you can put a generic wire tap into any channel, and the main flow does not change. The book names two results: more reuse, and less risk when you add instruments to a system that already runs.1

On the same thread or not. The tools do this in different ways. Camel sends the tapped copy as a fire-and-forget message in a separate thread, so it runs in parallel with the original.3 Spring Integration does not make the tap asynchronous by default; the type of the output channel of the tap decides. A direct channel runs the handler on the thread of the sender, and a pollable channel or an executor channel moves it to another thread.4 The Spring documentation says that an asynchronous output channel for the tap is the usual choice.4

A copy, but how deep. Camel copies the Exchange, but it does not clone the objects in it, unless you give an onPrepare processor that does. So the copies can share objects with the original.3

The program below models both questions. Ten messages come, one at each tick. The main consumer takes 1 tick for each, and the handler on the tap takes 3 ticks to write an audit record.

# Ten messages, one each tick; the main consumer takes 1 tick for each.
# The handler on the tap channel writes an audit record and takes 3 ticks for each.
N, WORK, TAP = 10, 1, 3


def sync_tap():
    t = 0
    for _ in range(N):
        t += TAP   # the tap channel calls its handler on the same thread
        t += WORK
    return t


def async_tap(capacity):
    queue, free_at, logged, dropped = [], 0, 0, 0
    for i in range(N):
        now = i * WORK
        while queue and free_at <= now:
            queue.pop(0)
            free_at += TAP
            logged += 1
        if free_at <= now and not queue:
            free_at = now + TAP
            logged += 1
        elif len(queue) < capacity:
            queue.append(now)
        else:
            dropped += 1
    tap_done = free_at + TAP * len(queue)
    return N * WORK, logged + len(queue), dropped, tap_done


print("sync tap: main done at tick %d, %d logged, 0 dropped" % (sync_tap(), N))
for cap in (4, 10):
    main, logged, dropped, done = async_tap(cap)
    print("async tap, buffer %d: main done at tick %d, %d logged, %d dropped, tap done at tick %d"
          % (cap, main, logged, dropped, done))

# A shallow copy shares the objects inside the message.
original = {"order": "o1", "card": {"number": "4111111111111111"}}
for name, copy in [("shallow", dict(original)),
                   ("deep", {"order": original["order"], "card": dict(original["card"])})]:
    copy["card"]["number"] = "*" * 12 + copy["card"]["number"][-4:]  # the tap masks the card
    print("%s copy: the main flow sees card %s" % (name, original["card"]["number"]))
    original["card"]["number"] = "4111111111111111"
Output
sync tap: main done at tick 40, 10 logged, 0 dropped
async tap, buffer 4: main done at tick 10, 8 logged, 2 dropped, tap done at tick 24
async tap, buffer 10: main done at tick 10, 10 logged, 0 dropped, tap done at tick 30
shallow copy: the main flow sees card ************1111
deep copy: the main flow sees card 4111111111111111

With a synchronous tap, the slow audit handler makes the main flow four times slower. With an asynchronous tap, the main flow ends at tick 10, but the tap needs a buffer. With a buffer of 4 messages, 2 audit records are lost; with a buffer of 10, none are lost, and the tap ends at tick 30. The last two lines show the copy: when the tap masks the card number in a shallow copy, it also changes the message of the main flow.

Example

Each example file sends 4 orders through a wire tap. The tap puts a deep copy on the audit channel, and the audit consumer masks the card number and adds a header to its copy. After the third order, an operator turns the tap off. The main receiver gets all 4 orders, and none of the changes of the audit consumer.

PythonGitHub
import copy
from collections import deque


class WireTap:
    """A fixed recipient list: each message goes to the main channel and, as a copy, to the tap."""

    def __init__(self, main, tap):
        self.main, self.tap, self.enabled = main, tap, True

    def send(self, msg):
        if self.enabled:
            self.tap.append(copy.deepcopy(msg))  # the tap must not share objects with the main flow
        self.main.append(msg)


main_ch, audit_ch = deque(), deque()
wire = WireTap(main_ch, audit_ch)
orders = [("o1", "4111111111111111", 30), ("o2", "5500000000000004", 12),
          ("o3", "4111111111111111", 7), ("o4", "340000000000009", 45)]
for oid, card, total in orders:
    wire.send({"id": oid, "card": card, "total": total, "headers": {"source": "web"}})
    if oid == "o3":
        wire.enabled = False  # an operator turns the tap off; the main flow does not change

seen = []
while main_ch:
    m = main_ch.popleft()
    seen.append(m)
    print("main: %s card %s total %d" % (m["id"], m["card"], m["total"]))
audited = 0
while audit_ch:
    m = audit_ch.popleft()
    m["card"] = "*" * (len(m["card"]) - 4) + m["card"][-4:]
    m["headers"]["audit"] = "yes"
    audited += 1
    print("audit: %s card %s total %d" % (m["id"], m["card"], m["total"]))
print("main: %d messages, audit: %d messages (tap off after o3)" % (len(seen), audited))
unchanged = all("*" not in m["card"] and "audit" not in m["headers"] for m in seen)
print("main messages unchanged:", str(unchanged).lower())
Output
main: o1 card 4111111111111111 total 30
main: o2 card 5500000000000004 total 12
main: o3 card 4111111111111111 total 7
main: o4 card 340000000000009 total 45
audit: o1 card ************1111 total 30
audit: o2 card ************0004 total 12
audit: o3 card ************1111 total 7
main: 4 messages, audit: 3 messages (tap off after o3)
main messages unchanged: true
  • Verdict: idiom. Two deque objects stand for the channels, and the tap is a small class with one send method.
  • copy.deepcopy gives the audit channel its own headers dict; dict(msg) would share it.
  • The enabled flag plays the part of an operator who turns the tap off; the main channel gets all 4 orders.
JavaGitHub
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;

public class Main {
    static final class Message {
        final String id;
        String card;
        final int total;
        final Map<String, String> headers;

        Message(String id, String card, int total, Map<String, String> headers) {
            this.id = id;
            this.card = card;
            this.total = total;
            this.headers = headers;
        }

        Message deepCopy() {
            return new Message(id, card, total, new HashMap<>(headers));
        }
    }

    static final class WireTap {
        final Queue<Message> main = new ArrayDeque<>();
        final Queue<Message> tap = new ArrayDeque<>();
        boolean enabled = true;

        void send(Message m) {
            if (enabled) {
                tap.add(m.deepCopy());
            }
            main.add(m);
        }
    }

    public static void main(String[] args) {
        var w = new WireTap();
        String[][] orders = {{"o1", "4111111111111111", "30"}, {"o2", "5500000000000004", "12"},
                {"o3", "4111111111111111", "7"}, {"o4", "340000000000009", "45"}};
        for (String[] o : orders) {
            var headers = new HashMap<String, String>();
            headers.put("source", "web");
            w.send(new Message(o[0], o[1], Integer.parseInt(o[2]), headers));
            if (o[0].equals("o3")) {
                w.enabled = false; // an operator turns the tap off
            }
        }
        List<Message> seen = new ArrayList<>();
        for (Message m; (m = w.main.poll()) != null; ) {
            seen.add(m);
            System.out.printf("main: %s card %s total %d%n", m.id, m.card, m.total);
        }
        int audited = 0;
        for (Message m; (m = w.tap.poll()) != null; ) {
            m.card = "*".repeat(m.card.length() - 4) + m.card.substring(m.card.length() - 4);
            m.headers.put("audit", "yes");
            audited++;
            System.out.printf("audit: %s card %s total %d%n", m.id, m.card, m.total);
        }
        System.out.printf("main: %d messages, audit: %d messages (tap off after o3)%n", seen.size(), audited);
        boolean unchanged = seen.stream().noneMatch(m -> m.card.contains("*") || m.headers.containsKey("audit"));
        System.out.println("main messages unchanged: " + unchanged);
    }
}
Output
main: o1 card 4111111111111111 total 30
main: o2 card 5500000000000004 total 12
main: o3 card 4111111111111111 total 7
main: o4 card 340000000000009 total 45
audit: o1 card ************1111 total 30
audit: o2 card ************0004 total 12
audit: o3 card ************1111 total 7
main: 4 messages, audit: 3 messages (tap off after o3)
main messages unchanged: true
  • Verdict: idiom. Two ArrayDeque objects are the channels, and deepCopy makes a new HashMap for the headers.
  • The audit consumer changes card on its copy, and the main messages keep the full number.
  • noneMatch checks that no main message got a change from the tap.
using System;
using System.Collections.Generic;
using System.Linq;

var tap = new WireTap();
var orders = new (string Id, string Card, int Total)[] { ("o1", "4111111111111111", 30), ("o2", "5500000000000004", 12),
                                                         ("o3", "4111111111111111", 7), ("o4", "340000000000009", 45) };
foreach (var o in orders)
{
    tap.Send(new Message(o.Id, o.Card, o.Total, new Dictionary<string, string> { ["source"] = "web" }));
    if (o.Id == "o3")
    {
        tap.Enabled = false; // an operator turns the tap off
    }
}
var seen = new List<Message>();
while (tap.Main.TryDequeue(out var m))
{
    seen.Add(m);
    Console.WriteLine($"main: {m.Id} card {m.Card} total {m.Total}");
}
int audited = 0;
while (tap.Tap.TryDequeue(out var m))
{
    var masked = m with { Card = new string('*', m.Card.Length - 4) + m.Card[^4..] };
    masked.Headers["audit"] = "yes";
    audited++;
    Console.WriteLine($"audit: {masked.Id} card {masked.Card} total {masked.Total}");
}
Console.WriteLine($"main: {seen.Count} messages, audit: {audited} messages (tap off after o3)");
bool unchanged = seen.All(x => !x.Card.Contains('*') && !x.Headers.ContainsKey("audit"));
Console.WriteLine($"main messages unchanged: {unchanged.ToString().ToLowerInvariant()}");

record Message(string Id, string Card, int Total, Dictionary<string, string> Headers);

class WireTap
{
    public Queue<Message> Main { get; } = new();
    public Queue<Message> Tap { get; } = new();
    public bool Enabled { get; set; } = true;

    public void Send(Message m)
    {
        if (Enabled)
        {
            // "with" copies the record, but the dictionary would be shared; copy it too.
            Tap.Enqueue(m with { Headers = new Dictionary<string, string>(m.Headers) });
        }
        Main.Enqueue(m);
    }
}
Output
main: o1 card 4111111111111111 total 30
main: o2 card 5500000000000004 total 12
main: o3 card 4111111111111111 total 7
main: o4 card 340000000000009 total 45
audit: o1 card ************1111 total 30
audit: o2 card ************0004 total 12
audit: o3 card ************1111 total 7
main: 4 messages, audit: 3 messages (tap off after o3)
main messages unchanged: true
  • Verdict: idiom. Two Queue<Message> objects are the channels, and Send adds a copy to the tap queue.
  • A with expression copies a record, but it copies the reference to the dictionary, so the tap makes a new Dictionary too.
  • The masked card goes into a new record, so the copy on the audit channel is not changed in place.
package main

import (
	"fmt"
	"maps"
	"strings"
)

type Message struct {
	ID, Card string
	Total    int
	Headers  map[string]string
}

// WireTap sends each message to the main channel and a copy to the tap channel.
type WireTap struct {
	main, tap chan Message
	enabled   bool
}

func (w *WireTap) Send(m Message) {
	if w.enabled {
		// The struct copy copies the strings and the int, but a map is shared unless it is cloned.
		c := m
		c.Headers = maps.Clone(m.Headers)
		w.tap <- c
	}
	w.main <- m
}

func main() {
	w := &WireTap{main: make(chan Message, 10), tap: make(chan Message, 10), enabled: true}
	orders := []Message{{"o1", "4111111111111111", 30, nil}, {"o2", "5500000000000004", 12, nil},
		{"o3", "4111111111111111", 7, nil}, {"o4", "340000000000009", 45, nil}}
	for _, o := range orders {
		o.Headers = map[string]string{"source": "web"}
		w.Send(o)
		if o.ID == "o3" {
			w.enabled = false // an operator turns the tap off
		}
	}
	close(w.main)
	close(w.tap)
	var seen []Message
	for m := range w.main {
		seen = append(seen, m)
		fmt.Printf("main: %s card %s total %d\n", m.ID, m.Card, m.Total)
	}
	audited := 0
	for m := range w.tap {
		m.Card = strings.Repeat("*", len(m.Card)-4) + m.Card[len(m.Card)-4:]
		m.Headers["audit"] = "yes"
		audited++
		fmt.Printf("audit: %s card %s total %d\n", m.ID, m.Card, m.Total)
	}
	fmt.Printf("main: %d messages, audit: %d messages (tap off after o3)\n", len(seen), audited)
	unchanged := true
	for _, m := range seen {
		if _, ok := m.Headers["audit"]; ok || strings.Contains(m.Card, "*") {
			unchanged = false
		}
	}
	fmt.Println("main messages unchanged:", unchanged)
}
Output
main: o1 card 4111111111111111 total 30
main: o2 card 5500000000000004 total 12
main: o3 card 4111111111111111 total 7
main: o4 card 340000000000009 total 45
audit: o1 card ************1111 total 30
audit: o2 card ************0004 total 12
audit: o3 card ************1111 total 7
main: 4 messages, audit: 3 messages (tap off after o3)
main messages unchanged: true
  • Verdict: idiom. Two buffered channels are the main and the tap channel, and Send writes to both.
  • An assignment of a struct copies its strings, but a map field still points to the same map, so maps.Clone copies the headers.
  • close and range drain each channel after the sends.

Consequences

Benefits.

  • No change to the sender or the receiver. You add a channel and change where the receiver reads from.1
  • One component for many channels. A generic tap can go into any channel.1
  • Easy to turn on and off. In Spring Integration, the tap is an interceptor in the definition of a channel, so you can turn it on or off without a change to the flow.4

Liabilities.

  • One more channel and one more hop. The receiver must read from the new main channel.1
  • Load. The tap makes one more message for each message. RabbitMQ says that its firehose has no effect on performance when it is off, but that performance drops somewhat when it is on.5
  • A slow tap. On the same thread, the tap slows the main flow. On another thread, it needs a buffer and a rule for a full buffer, as the program shows.
  • Shared objects. A shallow copy lets the consumer of the tap change the message of the main flow.3
  • All of the data. The copy has all the data of the message, also personal or payment data, so the consumer of the tap needs the same protection as the receiver. The examples mask the card number for this reason.

When not to use it

When the channel is publish-subscribe. A Publish-Subscribe Channel already gives a copy of each message to each subscriber, so a monitor can be one more subscriber. The wire tap is for a point-to-point channel.1

When you want to change the route. A wire tap only inspects; it does not change where the message goes. The Detour pattern is for this case. The book asks: "How can you route a message through intermediate steps to perform validation, testing or debugging functions?" The answer: "Construct a Detour with a context-based router controlled via the Control Bus".6 In one state, the router sends the messages through the extra steps, and in the other state, it sends them directly to the destination.6

When each copy must be kept. A tap with a full buffer loses records, and a tap on the thread of the sender slows it. When an audit must have each message, a Guaranteed Delivery channel to a Message Store is a better fit. The book asks: "How can we report against message information without disturbing the loosely coupled and transient nature of a messaging system?" The answer: "Use a Message Store to capture information about each message in a central location."7

Message Store. The store gets its data by a duplicate of each message on a special channel, which is the work of a wire tap.7

Firehose. A broker can tap all its channels at once. The RabbitMQ firehose sends a copy of each message that is published and each message that is delivered to the topic exchange amq.rabbitmq.trace, with the routing key publish. or deliver. and the name of the exchange or queue.5 It is off at the start of the server, and an administrator turns it on for one node and one virtual host.5

Logging channel adapter. In Spring Integration, a wire tap with a logging channel adapter as its output writes each message to the log, which is useful for a fault search.4

Related patterns. The EIP page lists Control Bus, Detour, Message Store, Point-to-Point Channel, Publish-Subscribe Channel and Recipient List, among others.1

Known uses

References

  1. Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Wire Tap (problem and solution under CC BY), problem and solution statements; pattern text; related patterns
  2. Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Designing, Building, and Deploying Messaging Solutions, Addison-Wesley, 2003, Chapter 11, System Management, Wire Tap
  3. Apache Camel 4.14.0 documentation source, Wire Tap EIP, introduction; Wire Tap; using Wire Tap
  4. Spring Integration 7.1.1 reference documentation source, Configuring Message Channels, Wire Tap
  5. RabbitMQ documentation, Firehose Tracing, Firehose Tracer overview; turning on firehose; firehose event message format
  6. Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Detour (problem and solution under CC BY), problem and solution statements; pattern text
  7. Gregor Hohpe and Bobby Woolf, Enterprise Integration Patterns, Message Store (problem and solution under CC BY), problem and solution statements; pattern text

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/G6J38R/text.yaml