blib/lib/Net/BCCN.pm untested

filter: Statementstmt 0.0% 0 / 162 Branchbran 0.0% 0 / 44 Conditioncond 0.0% 0 / 28 MC/DCmcdc 0.0% 0 / 13 Subroutinesub 0.0% 0 / 14 Podpod 0.0% 0 / 9 totaltotal 0.0% 0 / 270 CC 23 SCAR 35.2
CC
23
Cov
0%
__pull_all_available
90.0
stats
42.0
new
12.0
CRAP 33.8
1 ##############################################################################
2 #
3 # Net::BCCN Broadcast Channel Notifications protocol
4 # (c) Vladi Belperchinov-Shabanski "Cade" 2026
5 # http://cade.noxrun.com <cade@noxrun.com>
6 #
7 # GPL
8 #
9 ##############################################################################
10 package Net::BCCN;
11 use strict;
12 use POSIX ":sys_wait_h";
13 use IO::Socket::INET;
14 use IO::Select;
15 use Data::Dumper;
16  
17 our $VERSION = '1.1';
18  
19 $Data::Dumper::Terse = 1;
20 $Data::Dumper::Sortkeys = 1;
21  
22 ##############################################################################
23  
24  
25 # FIXME: sequence in hex?
26 sub parse_notification_msg_data
27 {
28 my $data = shift;
29 return () unless $data =~ /^BCCN(\d+)\[(\d+)(:([a-z_0-9]+)=([a-z_0-9]+))?\]([a-z_0-9\.\?\/]+):(\d+):(\!?[a-z_0-9\.\/]+)\|(.*)/i;
30  
31 # ver len cktype ckval fr seq chan payload
32 return ( $1, $2, $4, $5, $6, $7, $8, $9 );
33 }
34  
35 ##############################################################################
36  
37 # use Sys::Hostname; my $h = hostname();
38  
39 sub new
40 {
41 my $class = shift;
42 $class = ref( $class ) || $class;
43  
44 my %opt = @_;
45  
46 my $self = {
47 NAME => $opt{ 'NAME' } || '?', # local instance name
48 ADDR => $opt{ 'ADDR' } || '255.255.255.255', # broadcast address
49 BIND => $opt{ 'BIND' } || '0.0.0.0', # local bind address
50 PORT => $opt{ 'PORT' }, # which UDP port to listen and send on
51  
52 DEBUG => $opt{ 'DEBUG' }, # debug level, true to enable or positive number for debug level
53 };
54  
55 $self->{ 'DD' } = {} if $opt{ 'DD' }; # dedup requested
56 $self->{ 'SSS' } = {} if $opt{ 'SS' }; # speed stats requested
57 $self->{ 'SSX' } = $opt{ 'SS' }; # max events counting
58  
59 $self->{ 'TQMC' } = {}; # total queue messages count
60  
61 # print Dumper( \%opt, $self );
62  
63 bless $self, $class;
64 return $self;
65 }
66  
67 sub error
68 {
69 my $self = shift;
70  
71 return $self->{ 'ERR' };
72 }
73  
74 sub open
75 {
76 my $self = shift;
77  
78 my $bind = $self->{ 'BIND' };
79 my $port = $self->{ 'PORT' };
80  
81 my $sock = IO::Socket::INET->new
82 (
83 Proto => "udp",
84 LocalAddr => $bind,
85 LocalPort => $port,
86 ReuseAddr => 1,
87 Blocking => 0,
88 Broadcast => 1,
89 );
90  
91 if( ! $sock )
92 {
93 $self->{ 'ERR' } = "udp socket bind $bind:$port failed: $!";
94 return undef;
95 }
96  
97 $self->{ 'SOCK' } = $sock;
98  
99 return 1;
100 }
101  
102 sub notify
103 {
104 my $self = shift;
105  
106 my $chan = shift;
107 my $body = shift;
108  
109 my $sock = $self->{ 'SOCK' } or die "error: cannot notify, udp socket not open, call open() first\n";
110 $self->{ 'ERR' } = undef;
111  
112 my $seq = ++$self->{ 'SQ' }; # send sequence number
113  
114 my $name = $self->{ 'NAME' };
115  
116 my $msg = "$name:$seq:$chan|$body";
117 my $len = length $msg;
118 $msg = "BCCN1[$len]$msg";
119 $len = length $msg;
120  
121 my $to = pack_sockaddr_in( $self->{ 'PORT' }, inet_aton( $self->{ 'ADDR' } ) );
122  
123 my $sl = $sock->send( $msg, 0, $to );
124 if( ! defined( $sl ) )
125 {
126 dr_log("ERR: send failed: $!");
127 $self->{ 'ERR' } = "send to channel [$chan] failed: $!";
128 return undef;
129 }
130  
131 if( $sl != $len )
132 {
133 $self->{ 'ERR' } = "send to channel [$chan] error: short send: expected $len, sent $sl bytes";
134 return undef;
135 }
136  
137 return 1;
138 }
139  
140  
141 sub __pull_all_available
142 {
143 my $self = shift;
144 my $chan = shift;
145 my $opt = shift;
146  
147 $self->{ 'ERR' } = undef;
148  
149 my $sock = $self->{ 'SOCK' } or die "error: cannot notify, udp socket not open, call open() first\n";
150 my $cq = $self->{ 'Q' }{ $chan } ||= []; # channel queue
151  
152 my $to = @$cq ? 0 : $opt->{ 'TIMEOUT' } || 0; # if q has messages, do not wait, just pull whatever waiting
153  
154 my $sel = IO::Select->new;
155 $sel->add( $sock );
156  
157 my $recvc = 0;
158 while (1)
159 {
160 my $msg;
161  
162 my @ready = $sel->can_read( $to );
163 $to = 0;
164  
165 last unless @ready;
166  
167 my $from = $sock->recv( $msg, 65535, 0 );
168  
169 if( ! defined( $from ) )
170 {
171 next if $!{ 'EINTR' };
172 $self->{ 'ERR' } = "recv failed: $!";
173 return undef;
174 }
175  
176 my ( $from_port, $from_ip4_packed ) = unpack_sockaddr_in( $from );
177 my $from_ip4 = inet_ntoa( $from_ip4_packed );
178 my $len = length( $msg );
179  
180 $recvc++;
181 print("recv: #$recvc from $from_ip4:$from_port len=$len [$msg]\n");
182  
183 my @msg = parse_notification_msg_data( $msg );
184 # @msg = ver0 len1 cktype2 ckval3 fr4 seq5 chan6 msg7
185  
186 next unless @msg;
187  
188 if( $self->{ 'DD' } )
189 {
190 my $key = "$from_ip4:$msg[4]:$msg[5]:$msg[6]";
191 next if exists $self->{ 'DD' }{ $key };
192 $self->{ 'DD' }{ $key } = time(); # used by clear_dd_lookup()
193 }
194  
195 my $cq = $self->{ 'Q' }{ $msg[6] } ||= []; # channel queue
196  
197 push @$cq, {
198 FROM => $msg[4],
199 FROM_IP4 => $from_ip4,
200 FROM_PORT => $from_port,
201 CHANNEL => $msg[6],
202 MSG => $msg[7],
203 RTIME => time(), # receive time
204 };
205  
206 $self->{ 'TQMC' }{ '*' }++;
207 $self->{ 'TQMC' }{ $msg[6] }++;
208  
209 if( $self->{ 'SSS' } )
210 {
211 $self->{ 'SSS' }{ '*' } ||= [];
212 $self->{ 'SSS' }{ $msg[6] } ||= [];
213 push @{ $self->{ 'SSS' }{ '*' } }, time();
214 push @{ $self->{ 'SSS' }{ $msg[6] } }, time();
215 shift @{ $self->{ 'SSS' }{ '*' } } while @{ $self->{ 'SSS' }{ '*' } } > $self->{ 'SSX' };
216 shift @{ $self->{ 'SSS' }{ $msg[6] } } while @{ $self->{ 'SSS' }{ $msg[6] } } > $self->{ 'SSX' };
217 }
218 }
219  
220 return $recvc;
221 }
222  
223  
224 sub listen
225 {
226 my $self = shift;
227  
228 my $chan = shift;
229 my $opt = shift;
230  
231 my $cq = $self->{ 'Q' }{ $chan } ||= []; # channel queue
232  
233 my $recvc = $self->__pull_all_available( $chan, $opt );
234  
235 my $qc = @$cq;
236 print "pulled messages in one pass: $recvc, test qc $qc\n";
237  
238 return undef unless @$cq > 0;
239  
240 return shift @$cq;
241 }
242  
243 sub clear_dd_lookup
244 {
245 my $self = shift;
246 my $to = shift; # timeout cleanup, remove all older than $to seconds
247  
248 return unless exists $self->{ 'DD' };
249  
250 for my $key ( keys %{ $self->{ 'DD' } } )
251 {
252 delete $self->{ 'DD' }{ $key } if $self->{ 'DD' }{ $key } < time() - $to;
253 }
254 }
255  
256 sub stats
257 {
258 my $self = shift;
259  
260 my %st;
261  
262 # queues stats, seen, currently active (has messages), counts...
263 my $qsc = 0;
264 while( my ( $k, $v ) = each %{ $self->{ 'Q' } } )
265 {
266 $qsc++;
267 push @{ $st{ 'SEEN_QS' } }, $k;
268 my $mc = @{ $v };
269 push @{ $st{ 'ACTIVE_QS' } }, $k if $mc > 0;
270 $st{ 'QMC' }{ $k } = $mc; # queue message count
271 }
272 $st{ 'QSC' } = $qsc; # queues count
273  
274 # dedup stats
275 if( exists $self->{ 'DD' } )
276 {
277 my $ddc = 0;
278 my $ddo = time();
279 while( my ( $k, $v ) = each %{ $self->{ 'DD' } } )
280 {
281 $ddc++;
282 $ddo = $v if $v < $ddo;
283 }
284 $st{ 'DDC' } = $ddc; # dedup lookup count
285 $st{ 'DDO' } = $ddo; # dedup oldest lookup
286 }
287  
288 # speed stats for last SS events
289 if( exists $self->{ 'SSS' } )
290 {
291 while( my ( $k, $v ) = each %{ $self->{ 'SSS' } } )
292 {
293 $st{ 'SS' }{ $k } = @$v / ( $v->[-1] - $v->[0] ) if @$v > 1 and $v->[-1] - $v->[0] > 0;
294 }
295 }
296  
297 # total queue messages count
298 while( my ( $k, $v ) = each %{ $self->{ 'TQMC' } } )
299 {
300 $st{ 'TQMC' }{ $k } = $v;
301 }
302  
303 return \%st;
304 }
305  
306 1;
307  
308  
309  
310 =pod
311  
312 =head1 NAME
313  
314 Net::BCCN - Broadcast Channel Notifications protocol
315  
316 =head1 SYNOPSIS
317  
318 use Net::BCCN;
319  
320 my $bccn = Net::BCCN->new(
321 NAME => "host1/worker/$$",
322 ADDR => '255.255.255.255',
323 BIND => '0.0.0.0',
324 PORT => 1122,
325 DD => 1, # enable per-message dedup
326 SS => 100, # track speed stats over last 100 messages
327 DEBUG => 0,
328 );
329  
330 $bccn->open() or die "open failed: " . $bccn->error();
331  
332 # publish
333 $bccn->notify( 'supply-channel',
334 'txnid=12345:avail=1234:rc=00' );
335  
336 # listen on a channel (returns one message, or undef if none waiting)
337 while (1)
338 {
339 my $msg = $bccn->listen( 'work-channel', { TIMEOUT => 1 } );
340 next unless $msg;
341 process( $msg );
342 }
343  
344 =head1 DESCRIPTION
345  
346 Net::BCCN implements the BCCN wire protocol - a lightweight
347 LISTEN/NOTIFY-style notification fabric over UDP broadcast on a
348 single network segment. Inspired by PostgreSQL's NOTIFY/LISTEN,
349 but extended across machines and across processes that don't
350 share a database connection.
351  
352 Each datagram has the form:
353  
354 BCCN1[<len><:<algo>=<sum>>?]<src>:<seq>:<chan>|<payload>
355  
356 <len> decimal byte count of the body after "]"
357 <algo> optional integrity algorithm name (e.g. "hmac")
358 <sum> optional integrity check value
359 <src> sender identifier ("from")
360 <seq> sender's per-process sequence counter
361 <chan> channel name ("to")
362 <payload> opaque application-defined bytes
363  
364 The current implementation handles plain BCCN1 datagrams (no
365 integrity check). HMAC and directed-channel addressing are part
366 of the protocol design but not yet implemented in this module.
367  
368 Semantics are fire-and-forget. No acks, no persistence, no
369 replay. Suits notify-fabric use cases where occasional packet
370 loss is acceptable.
371  
372 =head1 CONSTRUCTOR
373  
374 =head2 new( %options )
375  
376 Creates a new BCCN endpoint. Does not open the socket - call
377 open() to do that.
378  
379 Options:
380  
381 =over 4
382  
383 =item NAME
384  
385 The local instance's name string used in outgoing datagrams as source name.
386 Defaults to "?" (the protocol's unknown-sender placeholder).
387 A typical convention is C<< host/program/pid >>, e.g.
388 C<< host4/processor/12345 >>.
389  
390 =item ADDR
391  
392 Broadcast destination address. Defaults to C<255.255.255.255>
393 (limited broadcast - never crosses routers). For directed
394 subnet broadcast, use the subnet's broadcast address such as
395 C<10.0.0.255>.
396  
397 =item BIND
398  
399 Local bind address. Defaults to C<0.0.0.0> (all interfaces).
400  
401 =item PORT
402  
403 UDP port to bind and send on. Required. Sender and listener
404 must agree on the port number.
405  
406 =item DD
407  
408 If true, enable per-message deduplication. The key is the concatenation of
409 (sender IP, src, seq, chan); duplicates within this key set are
410 silently dropped. Useful when the application sends each
411 notification twice for loss reduction. Periodically call
412 clear_dd_lookup() to expire old entries.
413  
414 =item SS
415  
416 If a positive integer N, enable speed statistics tracking over
417 the last N messages. Per-channel and aggregate rates are
418 exposed via stats(). If unset, no speed tracking.
419  
420 =item DEBUG
421  
422 True value or positive integer to enable debug output.
423 Currently used for selective trace prints during recv.
424  
425 =back
426  
427 =head1 METHODS
428  
429 =head2 open()
430  
431 Creates the UDP socket, sets SO_REUSEADDR, SO_BROADCAST, and
432 non-blocking mode, and binds to BIND:PORT. Returns 1 on
433 success, undef on failure (call error() for details).
434  
435 =head2 notify( $chan, $payload )
436  
437 Builds a BCCN1 datagram with the current NAME as src, the next
438 sequence number, the given channel and payload, and broadcasts
439 it. Returns 1 on success, undef on failure (call error()).
440  
441 The channel name is opaque to the protocol; sender and
442 receivers agree on its meaning. Any whitespace-free string is valid.
443  
444 The payload is opaque bytes; format is application's choice.
445 Keep the whole datagram under 1400 bytes to avoid IP
446 fragmentation.
447  
448 =head2 listen( $chan, \%opt )
449  
450 Pulls all currently available datagrams off the socket into
451 per-channel queues, then returns one queued message from the
452 named channel or undef if none is available.
453  
454 Note that even the sender (caller of notify()) will receive its own
455 message if calls listen() on the same channel as notify(). BCCN is
456 just a transport, execution logic is up to the implementation of the
457 client.
458  
459 Options:
460  
461 =over 4
462  
463 =item TIMEOUT
464  
465 Seconds to wait for the first datagram if the channel queue is
466 empty. 0 (default) means non-blocking. Once at least one
467 datagram has been queued, the method drains everything else
468 that's immediately readable without further waiting.
469  
470 =back
471  
472 Returned messages are hashrefs:
473  
474 {
475 FROM => <src>, # sender identifier from datagram
476 FROM_IP4 => <ip address>, # sender IP from recvfrom()
477 FROM_PORT => <udp port>, # sender port from recvfrom()
478 CHANNEL => <chan>,
479 MSG => <payload>,
480 RTIME => <unix time>, # receive time
481 }
482  
483 Note: datagrams for other channels read off the socket in the
484 same pass are queued internally; subsequent listen() calls on
485 those channels will return them.
486  
487 The idea for the TIMEOUT is to allow shortest possible sleep between
488 processing and housekeeping (when no message available and timeout expired).
489 So calling listen() with timeout will check for incoming messages, and if any,
490 will read them all and return either requested channel message or undef if none.
491 When no messages are available it will block until timeout expired or until
492 any new message arrive (regardless the requested channel or not). On returning
493 undef, housekeeping or other work can be done.
494  
495 =head2 error()
496  
497 Returns the last error message, or undef if the last operation
498 succeeded. Cleared at the start of each operation that sets it.
499  
500 =head2 stats()
501  
502 Returns a hashref of runtime statistics:
503  
504 {
505 QSC => <count>, # total queues/channels count
506 SEEN_QS => [ <chan>, ... ], # all queues/channels ever seen
507 ACTIVE_QS => [ <chan>, ... ], # queues/channels with queued messages
508 QMC => { <chan> => <count>, ... }, # per-channel queue length
509  
510 TQMC => { '*' => <count>, # total messages received
511 <chan> => <count>, # per-queue/channel total count
512 ... },
513  
514 DDC => <count>, # dedup table size (if DD enabled)
515 DDO => <unix time>, # oldest dedup entry (unix time)
516  
517 SS => { '*' => <rate>, # messages per second (if SS enabled)
518 <chan> => <rate>, # per-queue/channel speed
519 ... },
520 }
521  
522 =head2 clear_dd_lookup( $seconds )
523  
524 Removes dedup entries older than $seconds. Call periodically
525 when DD is enabled to prevent unbounded growth of the dedup
526 table. Has no effect when DD is disabled. call without argument or 0 to
527 clear the entire table.
528  
529 =head1 PROTOCOL DETAILS
530  
531 The wire format is a printable ASCII envelope plus an opaque
532 payload. The envelope is fixed across protocol versions; only
533 the body interpretation changes between BCCN1, a hypothetical
534 BCCN2, etc. Anything an intermediary needs for routing,
535 authentication, or framing lives in the envelope; everything
536 else is body.
537  
538 This module accepts the optional C<:E<lt>algoE<gt>=E<lt>sumE<gt>>
539 integrity slot in the envelope when parsing (the parser regex
540 allows it) but does not currently verify or generate it.
541  
542 Reserved characters:
543  
544 =over 4
545  
546 =item *
547  
548 Space, tab, CR, LF: not allowed in src or chan.
549  
550 =item *
551  
552 C<|>: separates body header from payload; first occurrence
553 marks the boundary.
554  
555 =item *
556  
557 C<:>: separates src/seq/chan in the body header; not allowed
558 inside src or chan.
559  
560 =item *
561  
562 C<[ ]>: envelope brackets.
563  
564 =item *
565  
566 C<!> as first character of chan: reserved for all-form ("!")
567 and directed-form ("!<target>") delivery. Not implemented in
568 this module yet.
569  
570 =item *
571  
572 C<?> as exact value of src: reserved unknown-sender placeholder.
573  
574 =back
575  
576 =head1 LIMITATIONS
577  
578 This module implements a minimal BCCN1 baseline. Not yet
579 supported:
580  
581 =over 4
582  
583 =item *
584  
585 HMAC or other integrity check (envelope syntax recognised but
586 not verified).
587  
588 =item *
589  
590 C<!>-prefix channel forms: all-broadcast and directed delivery.
591  
592 =item *
593  
594 Sequence-number-based per-sender dedup (only IP+src+seq+chan
595 tuple dedup via the DD option).
596  
597 =item *
598  
599 Multicast delivery. The current revision is broadcast-only on
600 a single L2 segment. Multicast is considered for next releases.
601  
602 =back
603  
604 =head1 EXAMPLE
605  
606 A small publisher/subscriber pair:
607  
608 # publisher.pl
609 use Net::BCCN;
610 my $b = Net::BCCN->new( NAME => "tx-source/$$",
611 PORT => 5400 );
612 $b->open() or die $b->error();
613 my $i = 0;
614 while (1)
615 {
616 $b->notify( 'demo/tick', "i=$i ts=" . time() );
617 $i++;
618 sleep 1;
619 }
620  
621 # subscriber.pl
622 use Net::BCCN;
623 my $b = Net::BCCN->new( NAME => "tx-sink/$$",
624 PORT => 5400,
625 DD => 1 );
626 $b->open() or die $b->error();
627 while (1)
628 {
629 my $msg = $b->listen( 'demo/tick', { TIMEOUT => 1 } );
630 next unless $msg;
631 print "$msg->{FROM_IP4} $msg->{FROM} -> $msg->{MSG}\n";
632 }
633  
634 Run multiple subscribers on the same host - all of them will
635 receive every datagram because the underlying socket has
636 SO_REUSEADDR set.
637  
638 =head1 SEE ALSO
639  
640 PostgreSQL LISTEN/NOTIFY - the inspiration for BCCN's semantics.
641  
642 L<IO::Socket::INET>, L<IO::Select> - the Perl networking
643 primitives used internally.
644  
645 =head1 AUTHOR
646  
647 Vladi Belperchinov-Shabanski "Cade" <cade@noxrun.com>
648 <http://cade.noxrun.com>
649 https://github.com/cade-vs/bccn
650  
651 =head1 COPYRIGHT AND LICENSE
652  
653 Copyright (c) 2026 Vladi Belperchinov-Shabanski.
654  
655 This module is free software; you can redistribute it and/or
656 modify it under the terms of the GNU General Public License,
657 version 2 or, at your option, any later version.
658  
659 =cut