File: Server.pm

package info (click to toggle)
libtangence-perl 0.33-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 580 kB
  • sloc: perl: 6,076; makefile: 15
file content (612 lines) | stat: -rw-r--r-- 15,568 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
#  You may distribute under the terms of either the GNU General Public License
#  or the Artistic License (the same terms as Perl itself)
#
#  (C) Paul Evans, 2011-2021 -- leonerd@leonerd.org.uk

package Tangence::Server 0.33;

use v5.26;
use warnings;
use experimental 'signatures';

use base qw( Tangence::Stream );

use Carp;

use Scalar::Util qw( weaken );
# TODO: since we're using meta 0.007 we could use set_subname from there but
# it's more awkward to use it this way
use Sub::Util 1.40 qw( set_subname );
use Feature::Compat::Try;

use Tangence::Constants;
use Tangence::Types;
use Tangence::Server::Context;

use Struct::Dumb;
struct CursorObject => [qw( cursor obj )];

# We will accept any version back to 3
use constant VERSION_MINOR_MIN => 3;

=head1 NAME

C<Tangence::Server> - mixin class for building a C<Tangence> server

=head1 SYNOPSIS

This class is a mixin, it cannot be directly constructed

   package Example::Server;
   use base qw( Base::Server Tangence::Server );

   sub new
   {
      my $class = shift;
      my %args = @_;

      my $registry = delete $args{registry};

      my $self = $class->SUPER::new( %args );

      $self->registry( $registry );

      return $self;
   }

   sub tangence_write
   {
      my $self = shift;
      $self->write( $_[0] );
   }

   sub on_read
   {
      my $self = shift;
      $self->tangence_readfrom( $_[0] );
   }

=head1 DESCRIPTION

This module provides mixin to implement a C<Tangence> server connection. It
should be mixed in to an object used to represent a single connection from a
client. It provides a location for the objects in server to store information
about the client connection, and coordinates passing messages between the
client and the objects in the server.

This is a subclass of L<Tangence::Stream> which provides implementations of
the required C<handle_request_> methods. A class mixing in C<Tangence::Server>
must still provide the C<write> method required for sending data to the
client.

For an example of a class that uses this mixin, see
L<Net::Async::Tangence::ServerProtocol>.

=cut

=head1 PROVIDED METHODS

The following methods are provided by this mixin.

=cut

sub subscriptions { shift->{subscriptions} ||= [] }
sub watches       { shift->{watches} ||= [] }

=head2 registry

   $server->registry( $registry )

   $registry = $server->registry

Accessor to set or obtain the L<Tangence::Registry> object for the server.

=cut

sub registry
{
   my $self = shift;
   $self->{registry} = shift if @_;
   return $self->{registry};
}

sub tangence_closed
{
   my $self = shift;
   $self->SUPER::tangence_closed;

   if( my $subscriptions = $self->subscriptions ) {
      foreach my $s ( @$subscriptions ) {
         my ( $object, $event, $id ) = @$s;
         $object->unsubscribe_event( $event, $id );
      }

      undef @$subscriptions;
   }

   if( my $watches = $self->watches ) {
      foreach my $w ( @$watches ) {
         my ( $object, $prop, $id ) = @$w;
         $object->unwatch_property( $prop, $id );
      }

      undef @$watches;
   }

   if( my $cursors = $self->peer_hascursor ) {
      foreach my $cursorobj ( values %$cursors ) {
         $self->drop_cursorobj( $cursorobj );
      }
   }
}

sub get_by_id ( $self, $id )
{
   # Only permit the client to interact with objects they've already been
   # sent, so they cannot gain access by inventing object IDs
   $self->peer_hasobj->{$id} or
      die "Access not allowed to object with id $id\n";

   my $obj = $self->registry->get_by_id( $id ) or
      die "No such object with id $id\n";

   return $obj;
}

sub handle_request_CALL ( $self, $token, $message )
{
   my $ctx = Tangence::Server::Context->new( $self, $token );

   my $response;
   try {
      my $objid = $message->unpack_int();

      my $object = $self->get_by_id( $objid );

      $response = $object->handle_request_CALL( $ctx, $message );
   }
   catch ( $e ) {
      return $ctx->responderr( $e );
   }

   $ctx->respond( $response );
}

sub handle_request_SUBSCRIBE ( $self, $token, $message )
{
   my $ctx = Tangence::Server::Context->new( $self, $token );

   my $response;
   try {
      my $objid = $message->unpack_int();
      my $event = $message->unpack_str();

      my $object = $self->get_by_id( $objid );

      weaken( my $weakself = $self );

      my $id = $object->subscribe_event( $event,
         set_subname "__SUBSCRIBE($event)__" => sub {
            $weakself or return;
            my $object = shift;

            my $message = $object->generate_message_EVENT( $weakself, $event, @_ );
            $weakself->request(
               request     => $message,
               on_response => sub { "IGNORE" },
            );
         }
      );

      push @{ $self->subscriptions }, [ $object, $event, $id ];

      $response = Tangence::Message->new( $self, MSG_SUBSCRIBED )
   }
   catch ( $e ) {
      return $ctx->responderr( $e );
   }

   $ctx->respond( $response );
}

sub handle_request_UNSUBSCRIBE ( $self, $token, $message )
{
   my $ctx = Tangence::Server::Context->new( $self, $token );

   my $response;
   try {
      my $objid = $message->unpack_int();
      my $event = $message->unpack_str();

      my $object = $self->get_by_id( $objid );

      my $edef = $object->can_event( $event ) or
         die "Object cannot respond to event $event\n";

      # Delete from subscriptions and obtain id
      my $id;
      @{ $self->subscriptions } = grep { $_->[0] == $object and $_->[1] eq $event and ( $id = $_->[2], 0 ) or 1 }
                                     @{ $self->subscriptions };
      defined $id or
         die "Not subscribed to $event\n";

      $object->unsubscribe_event( $event, $id );

      $response = Tangence::Message->new( $self, MSG_OK )
   }
   catch ( $e ) {
      return $ctx->responderr( $e );
   }

   $ctx->respond( $response );
}

sub handle_request_GETPROP ( $self, $token, $message )
{
   my $ctx = Tangence::Server::Context->new( $self, $token );

   my $response;
   try {
      my $objid = $message->unpack_int();

      my $object = $self->get_by_id( $objid );

      $response = $object->handle_request_GETPROP( $ctx, $message )
   }
   catch ( $e ) {
      return $ctx->responderr( $e );
   }

   $ctx->respond( $response );
}

sub handle_request_GETPROPELEM ( $self, $token, $message )
{
   my $ctx = Tangence::Server::Context->new( $self, $token );

   my $response;
   try {
      my $objid = $message->unpack_int();

      my $object = $self->get_by_id( $objid );

      $response = $object->handle_request_GETPROPELEM( $ctx, $message )
   }
   catch ( $e ) {
      return $ctx->responderr( $e );
   }

   $ctx->respond( $response );
}

sub handle_request_SETPROP ( $self, $token, $message )
{
   my $ctx = Tangence::Server::Context->new( $self, $token );

   my $response;
   try {
      my $objid = $message->unpack_int();

      my $object = $self->get_by_id( $objid );

      $response = $object->handle_request_SETPROP( $ctx, $message )
   }
   catch ( $e ) {
      return $ctx->responderr( $e );
   }

   $ctx->respond( $response );
}

*handle_request_WATCH      = \&_handle_request_WATCHany;
*handle_request_WATCH_CUSR = \&_handle_request_WATCHany;
sub _handle_request_WATCHany ( $self, $token, $message )
{
   my $ctx = Tangence::Server::Context->new( $self, $token );

   my ( $want_initial, $object, $prop );

   my $response;
   try {
      my $objid = $message->unpack_int();
      $prop     = $message->unpack_str();

      $object = $self->get_by_id( $objid );

      my $pdef = $object->can_property( $prop ) or
         die "Object does not have property $prop\n";

      $self->_install_watch( $object, $prop );

      if( $message->code == MSG_WATCH ) {
         $want_initial = $message->unpack_bool();

         $response = Tangence::Message->new( $self, MSG_WATCHING )
      }
      elsif( $message->code == MSG_WATCH_CUSR ) {
         my $from = $message->unpack_int();

         my $m = "cursor_prop_$prop";
         my $cursor = $object->$m( $from );
         my $id = $self->message_state->{next_cursorid}++;

         $self->peer_hascursor->{$id} = CursorObject( $cursor, $object );
         $response = Tangence::Message->new( $self, MSG_WATCHING_CUSR )
            ->pack_int( $id )
            ->pack_int( 0 ) # first index
            ->pack_int( $#{ $object->${\"get_prop_$prop"} } ) # last index
      }
   }
   catch ( $e ) {
      return $ctx->responderr( $e );
   }

   $ctx->respond( $response );

   $self->_send_initial( $object, $prop ) if $want_initial;
}

sub _send_initial ( $self, $object, $prop )
{
   my $m = "get_prop_$prop";
   return unless( $object->can( $m ) );

   try {
      my $value = $object->$m();
      my $message = $object->generate_message_UPDATE( $self, $prop, CHANGE_SET, $value );
      $self->request(
         request     => $message,
         on_response => sub { "IGNORE" },
      );
   }
   catch ( $e ) {
      warn "$e during initial property fetch";
   }
}

sub handle_request_UNWATCH ( $self, $token, $message )
{
   my $ctx = Tangence::Server::Context->new( $self, $token );

   my $response;
   try {
      my $objid = $message->unpack_int();
      my $prop  = $message->unpack_str();

      my $object = $self->get_by_id( $objid );

      my $pdef = $object->can_property( $prop ) or
         die "Object does not have property $prop\n";

      # Delete from watches and obtain id
      my $id;
      @{ $self->watches } = grep { $_->[0] == $object and $_->[1] eq $prop and ( $id = $_->[2], 0 ) or 1 }
                            @{ $self->watches };
      defined $id or
         die "Not watching $prop\n";

      $object->unwatch_property( $prop, $id );

      $response = Tangence::Message->new( $self, MSG_OK );
   }
   catch ( $e ) {
      return $ctx->responderr( $e );
   }

   $ctx->respond( $response );
}

sub handle_request_CUSR_NEXT ( $self, $token, $message )
{
   my $cursor_id = $message->unpack_int();

   my $ctx = Tangence::Server::Context->new( $self, $token );

   my $cursorobj = $self->peer_hascursor->{$cursor_id} or
      return $ctx->responderr( "No such cursor with id $cursor_id" );

   $cursorobj->cursor->handle_request_CUSR_NEXT( $ctx, $message );
}

sub handle_request_CUSR_DESTROY ( $self, $token, $message )
{
   my $cursor_id = $message->unpack_int();

   my $ctx = Tangence::Server::Context->new( $self, $token );

   my $cursorobj = delete $self->peer_hascursor->{$cursor_id};
   $self->drop_cursorobj( $cursorobj );

   $ctx->respond( Tangence::Message->new( $self, MSG_OK ) );
}

sub drop_cursorobj ( $self, $cursorobj )
{
   my $m = "uncursor_prop_" . $cursorobj->cursor->prop->name;
   $cursorobj->obj->$m( $cursorobj->cursor );
}

sub handle_request_INIT ( $self, $token, $message )
{
   my $major = $message->unpack_int();
   my $minor_max = $message->unpack_int();
   my $minor_min = $message->unpack_int();

   my $ctx = Tangence::Server::Context->new( $self, $token );

   if( $major != VERSION_MAJOR ) {
      return $ctx->responderr( "Major version $major not available" );
   }

   # Don't accept higher than the minor version we recognise
   $minor_max = VERSION_MINOR if $minor_max > VERSION_MINOR;
   $minor_min = VERSION_MINOR_MIN if $minor_min < VERSION_MINOR_MIN;

   if( $minor_max < $minor_min ) {
      return $ctx->responderr( "No suitable minor version available" );
   }

   # For unit tests or other synchronous cases, we need to set the version
   # -before- we send the message. But we'd better construct the response
   # message before setting the version, in case it makes a difference.
   my $response = Tangence::Message->new( $self, MSG_INITED )
      ->pack_int( $major )
      ->pack_int( $minor_max );

   $self->minor_version( $minor_max );

   $ctx->respond( $response );
}

sub handle_request_GETROOT ( $self, $token, $message )
{
   my $identity = TYPE_ANY->unpack_value( $message );

   my $ctx = Tangence::Server::Context->new( $self, $token );

   $self->identity( $identity );

   my $root = $self->rootobj( $identity );

   my $response = Tangence::Message->new( $self, MSG_RESULT );
   TYPE_OBJ->pack_value( $response, $root );

   $ctx->respond( $response );
}

sub handle_request_GETREGISTRY ( $self, $token, $message )
{
   my $ctx = Tangence::Server::Context->new( $self, $token );

   $self->permit_registry or
      return $ctx->responderr( "This client is not permitted access to the registry" );

   my $response = Tangence::Message->new( $self, MSG_RESULT );
   TYPE_OBJ->pack_value( $response, $self->registry );

   $ctx->respond( $response );
}

my %change_values = (
   on_set    => CHANGE_SET,
   on_add    => CHANGE_ADD,
   on_del    => CHANGE_DEL,
   on_push   => CHANGE_PUSH,
   on_shift  => CHANGE_SHIFT,
   on_splice => CHANGE_SPLICE,
   on_move   => CHANGE_MOVE,
);

sub _install_watch ( $self, $object, $prop )
{
   my $pdef = $object->can_property( $prop );
   my $dim = $pdef->dimension;

   weaken( my $weakself = $self );

   my %callbacks;
   foreach my $name ( @{ CHANGETYPES->{$dim} } ) {
      my $how = $change_values{$name};
      $callbacks{$name} = set_subname "__WATCH($prop:$name)__" => sub {
         $weakself or return;
         my $object = shift;

         my $message = $object->generate_message_UPDATE( $weakself, $prop, $how, @_ );
         $weakself->request(
            request     => $message,
            on_response => sub { "IGNORE" },
         );
      };
   }

   my $id = $object->watch_property( $prop, %callbacks );

   push @{ $self->watches }, [ $object, $prop, $id ];
}

sub object_destroyed ( $self, $obj, @rest )
{
   if( my $subs = $self->subscriptions ) {
      my $i = 0;
      while( $i < @$subs ) {
         my $s = $subs->[$i];

         $i++, next unless $s->[0] == $obj;

         my ( undef, $event, $id ) = @$s;
         $obj->unsubscribe_event( $event, $id );

         splice @$subs, $i, 1;
         # No $i++
      }
   }

   if( my $watches = $self->watches ) {
      my $i = 0;
      while( $i < @$watches ) {
         my $w = $watches->[$i];

         $i++, next unless $w->[0] == $obj;

         my ( undef, $prop, $id ) = @$w;
         $obj->unwatch_property( $prop, $id );

         splice @$watches, $i, 1;
         # No $i++
      }
   }

   $self->SUPER::object_destroyed( $obj, @rest );
}

=head1 OVERRIDEABLE METHODS

The following methods are provided but intended to be overridden if the
implementing class wishes to provide different behaviour from the default.

=cut

=head2 rootobj

   $rootobj = $server->rootobj( $identity )

Invoked when a C<GETROOT> message is received from the client, this method
should return a L<Tangence::Object> as root object for the connection.

The default implementation will return the object with ID 1; i.e. the first
object created in the registry.

=cut

sub rootobj
{
   my $self = shift;

   return $self->registry->get_by_id( 1 );
}

=head2 permit_registry

   $allow = $server->permit_registry

Invoked when a C<GETREGISTRY> message is received from the client, this method
should return a boolean to indicate whether the client is allowed to access
the object registry.

The default implementation always permits this, but an overridden method may
decide to disallow it in some situations. When disabled, a client will not be
able to gain access to any serverside objects other than the root object, and
(recursively) any other objects returned by methods, events or properties on
objects already known. This can be used as a security mechanism.

=cut

sub permit_registry { 1; }

=head1 AUTHOR

Paul Evans <leonerd@leonerd.org.uk>

=cut

0x55AA;