Chloe  Butler

Chloe Butler

1667570280

Promises Perl: an Implementation Of Promises in Perl

Promises for Perl

This module is an implementation of the "Promise/A+" pattern for asynchronous programming. Promises are meant to be a way to better deal with the resulting callback spaghetti that can often result in asynchronous programs.

SYNOPSIS

use AnyEvent::HTTP;
use JSON::XS qw[ decode_json ];
use Promises qw[ collect deferred ];

sub fetch_it {
    my ($uri) = @_;
    my $d = deferred;
    http_get $uri => sub {
        my ($body, $headers) = @_;
        $headers->{Status} == 200
            ? $d->resolve( decode_json( $body ) )
            : $d->reject( $body )
    };
    $d->promise;
}

my $cv = AnyEvent->condvar;

collect(
    fetch_it('http://rest.api.example.com/-/product/12345'),
    fetch_it('http://rest.api.example.com/-/product/suggestions?for_sku=12345'),
    fetch_it('http://rest.api.example.com/-/product/reviews?for_sku=12345'),
)->then(
    sub {
        my ($product, $suggestions, $reviews) = @_;
        $cv->send({
            product     => $product,
            suggestions => $suggestions,
            reviews     => $reviews,
        })
    },
    sub { $cv->croak( 'ERROR' ) }
);

my $all_product_info = $cv->recv;

INSTALLATION

To install this module from its CPAN tarball, type the following:

perl Makefile.PL make make test make install

If you cloned the github repo, the branch releases has the same code than the one living in CPAN, so the same Makefile dance will work. The master branch, however, needs to be built using Dist::Zilla:

dzil install

Be warned that the Dist::Zilla configuration is fine-tuned to my needs, so the dependency list to get it running is ludicrously huge. If you want a quick and dirty install, you can also do:

git checkout releases -- Makefile.PL
perl Makefile.PL
make test
make install

DEPENDENCIES

This module requires these other modules and libraries:

Test::More

This module optionally requires these other modules and libraries in order to support some specific features.

AnyEvent
Mojo::IOLoop
EV
IO::Async

SEE ALSO

COPYRIGHT AND LICENCE

Copyright (C) 2012-2014 Infinity Interactive, Inc.

http://www.iinteractive.com

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.


Download Details:

Author: stevan
Source Code: https://github.com/stevan/promises-perl

#perl 

What is GEEK

Buddha Community

Promises Perl: an Implementation Of Promises in Perl

Promise.allSettled() vs Promise.all()

Promise.allSetlled() is recently introduced in ECMA 2020.
Check out how it is different from Promise.all()

https://www.geekstutorialpoint.com/2020/05/promiseallsettled-vs-promiseall.html

#javascript #promise.all #promise.allsettled #ecma #promise #jquery

Chloe  Butler

Chloe Butler

1667570280

Promises Perl: an Implementation Of Promises in Perl

Promises for Perl

This module is an implementation of the "Promise/A+" pattern for asynchronous programming. Promises are meant to be a way to better deal with the resulting callback spaghetti that can often result in asynchronous programs.

SYNOPSIS

use AnyEvent::HTTP;
use JSON::XS qw[ decode_json ];
use Promises qw[ collect deferred ];

sub fetch_it {
    my ($uri) = @_;
    my $d = deferred;
    http_get $uri => sub {
        my ($body, $headers) = @_;
        $headers->{Status} == 200
            ? $d->resolve( decode_json( $body ) )
            : $d->reject( $body )
    };
    $d->promise;
}

my $cv = AnyEvent->condvar;

collect(
    fetch_it('http://rest.api.example.com/-/product/12345'),
    fetch_it('http://rest.api.example.com/-/product/suggestions?for_sku=12345'),
    fetch_it('http://rest.api.example.com/-/product/reviews?for_sku=12345'),
)->then(
    sub {
        my ($product, $suggestions, $reviews) = @_;
        $cv->send({
            product     => $product,
            suggestions => $suggestions,
            reviews     => $reviews,
        })
    },
    sub { $cv->croak( 'ERROR' ) }
);

my $all_product_info = $cv->recv;

INSTALLATION

To install this module from its CPAN tarball, type the following:

perl Makefile.PL make make test make install

If you cloned the github repo, the branch releases has the same code than the one living in CPAN, so the same Makefile dance will work. The master branch, however, needs to be built using Dist::Zilla:

dzil install

Be warned that the Dist::Zilla configuration is fine-tuned to my needs, so the dependency list to get it running is ludicrously huge. If you want a quick and dirty install, you can also do:

git checkout releases -- Makefile.PL
perl Makefile.PL
make test
make install

DEPENDENCIES

This module requires these other modules and libraries:

Test::More

This module optionally requires these other modules and libraries in order to support some specific features.

AnyEvent
Mojo::IOLoop
EV
IO::Async

SEE ALSO

COPYRIGHT AND LICENCE

Copyright (C) 2012-2014 Infinity Interactive, Inc.

http://www.iinteractive.com

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.


Download Details:

Author: stevan
Source Code: https://github.com/stevan/promises-perl

#perl 

Chloe  Butler

Chloe Butler

1667619300

Perl 5 Cucumber: Minimal Implementation Of Cucumber in Perl5

Perl 5 Cucumber

This is a minimal implementation of Cucumber in Perl5

To learn about Cucumber take a look at:
http://wiki.gihub.com/aslakhellesoy/cucumber

Example:

Story

Feature: Dealing with mushrooms
  In order to test the effect of evil poisonous mushrooms
  As an evil scientist
  I want to test effects of eating mushrooms on little children

  Scenario: Mushrooms are bad for you, they kill boys
    Given a live boy in a forest
    When he ate a mushroom
    Then he was a dead boy in a forest

  Scenario: Mushrooms are bad for girls too
    Given a live girl in a forest
    When she ate a mushroom
    Then she was a dead girl in a forest

Code


Given qr/(.*) in (.*)/, sub {
  my ($description,$location) = @_;
  $state{human} = $description;
  $state{location} = $location;
};

When qr/s?he ate (.*)/, sub {
  my $item = shift;
  if ($item eq 'a mushroom') {
    $state{human} =~ s/live/dead/;
  }
};

Then qr/s?he was (.*) in (.*)/, sub {
  my ($description,$location) = @_;
  is($state{human},$description,$description);
  is($state{location},$location,$location);
};

Execution output

$ perl p5-cucumber.pl
Feature: Dealing with mushrooms
  In order to test the effect of evil poisonous mushrooms
  As an evil scientist
  I want to test effects of eating mushrooms on little children

  Scenario: Mushrooms are bad for you, they kill boys
    Given a live boy in a forest
    When he ate a mushroom
    Then he was a dead boy in a forest
ok 1 - a dead boy
ok 2 - a forest

  Scenario: Mushrooms are bad for girls too
    Given a live girl in a forest
    When she ate a mushroom
    Then she was a dead girl in the sea
ok 3 - a dead girl
not ok 4 - the sea
#   Failed test 'the sea'
#   at ./p5-cucumber.pl line 82.
#          got: 'a forest'
#     expected: 'the sea'
1..4
# Looks like you failed 1 test of 4.

(exitcode is 1 for failure)

And when we fix the story:

$ perl p5-cucumber.pl
Feature: Dealing with mushrooms
  In order to test the effect of evil poisonous mushrooms
  As an evil scientist
  I want to test effects of eating mushrooms on little children

  Scenario: Mushrooms are bad for you, they kill boys
    Given a live boy in a forest
    When he ate a mushroom
    Then he was a dead boy in a forest
ok 1 - a dead boy
ok 2 - a forest

  Scenario: Mushrooms are bad for girls too
    Given a live girl in a forest
    When she ate a mushroom
    Then she was a dead girl in a forest
ok 3 - a dead girl
ok 4 - a forest
1..4

(exitcode is 0 for success)

Thanks

Great thank you for the perl-il and perl-qa mailing lists
for helping me with some high level perl concepts that make
this code so beautiful like it is.

Another huge thank you to the people in #perl @freenode.net
who helped me with sticky dereferencing and scalar/list
problems.


Download Details:

Author: kesor
Source Code: https://github.com/kesor/p5-cucumber

#perl 

Graphql Perl: Perl Implementation Of GraphQL

NAME

GraphQL - Perl implementation of GraphQL

PROJECT STATUS

OSBuild status
LinuxBuild Status

SYNOPSIS

use GraphQL::Schema;
use GraphQL::Type::Object;
use GraphQL::Type::Scalar qw($String);
use GraphQL::Execution qw(execute);

my $schema = GraphQL::Schema->from_doc(<<'EOF');
type Query {
  helloWorld: String
}
EOF
post '/graphql' => sub {
  send_as JSON => execute(
    $schema,
    body_parameters->{query},
    { helloWorld => 'Hello world!' },
    undef,
    body_parameters->{variables},
    body_parameters->{operationName},
    undef,
  );
};

The above is from the sample Dancer 2 applet.

DESCRIPTION

This module is a port of the GraphQL reference implementation, graphql-js, to Perl 5.

It now supports Promises, allowing asynchronous operation. See Mojolicious::Plugin::GraphQL for an example of how to take advantage of this.

As of 0.39, supports GraphQL subscriptions.

See GraphQL::Type for description of how to create GraphQL types.

Introduction to GraphQL

GraphQL is a technology that lets clients talk to APIs via a single endpoint, which acts as a single "source of the truth". This means clients do not need to seek the whole picture from several APIs. Additionally, it makes this efficient in network traffic, time, and programming effort:

Network traffic

The request asks for exactly what it wants, which it gets, and no more. No wasted traffic.

Time

It gets all the things it needs in one go, including any connected resources, so it does not need to make several requests to fill its information requirement.

Programming effort

With "fragments" that can be attached to user-interface components, keeping track of what information a whole page needs to request can be automated. See Relay or Apollo for more on this.

Basic concepts

GraphQL implements a system featuring a schema, which features various classes of types, some of which are objects. Special objects provide the roots of queries (mandatory), and mutations and subscriptions (both optional).

Objects have fields, each of which can be specified to take arguments, and which have a return type. These are effectively the properties and/or methods on the type. If they return an object, then a query can specify subfields of that object, and so on - as alluded to in the "time-saving" point above.

For more, see the JavaScript tutorial in "SEE ALSO".

Hooking your system up to GraphQL

You will need to decide how to model your system in GraphQL terms. This will involve deciding on what output object types you have, what fields they have, and what arguments and return-types those fields have.

Additionally, you will need to design mutations if you want to be able to update/create/delete data. This requires some thought for return types, to ensure you can get all the information you need to proceed to avoid extra round-trips.

The easiest way to achieve these things is to make a GraphQL::Plugin::Convert subclass, to encapsulate the specifics of your system. See the documentation for further information.

Finally, you should consider whether you need "subscriptions". These are designed to hook into WebSockets. Apollo has a JavaScript module for this.

Specifying types and fields is straightforward. See the document for how to make resolvers.

DEBUGGING

To debug, set environment variable GRAPHQL_DEBUG to a true value.

EXPORT

None yet.

SEE ALSO

SQL::Translator::Producer::GraphQL - produce GraphQL schemas from a DBIx::Class::Schema (or in fact any SQL database)

GraphQL::Plugin::Convert::DBIC - produce working GraphQL schema from a DBIx::Class::Schema

GraphQL::Plugin::Convert::OpenAPI - produce working GraphQL schema from an OpenAPI specification

Sample Mojolicious OpenAPI to GraphQL applet

Sample Dancer 2 applet

Sample Mojolicious applet

Dancer2::Plugin::GraphQL

Mojolicious::Plugin::GraphQL

http://facebook.github.io/graphql/ - GraphQL specification

http://graphql.org/graphql-js/ - Tutorial on the JavaScript version, highly recommended. Translation to graphql-perl.

AUTHOR

Ed J, <etj at cpan.org>

BUGS

Please report any bugs or feature requests on https://github.com/graphql-perl/graphql-perl/issues.

Or, if you prefer email and/or RT: to bug-graphql at rt.cpan.org, or through the web interface at http://rt.cpan.org/NoAuth/ReportBug.html?Queue=GraphQL. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.

ACKNOWLEDGEMENTS

The creation of this work has been sponsored by Perl Careers: https://perl.careers/.

Artur Khabibullin <rtkh at cpan.org> contributed valuable ports of the JavaScript tests.

The creation of the subscriptions functionality in this work has been sponsored by Sanctus.app: https://sanctus.app.

LICENSE AND COPYRIGHT

Copyright 2017 Ed J.

This program is free software; you can redistribute it and/or modify it under the terms of the the Artistic License (2.0). You may obtain a copy of the full license at:

http://www.perlfoundation.org/artistic_license_2_0


Download Details:

Author: graphql-perl
Source Code: https://github.com/graphql-perl/graphql-perl

#graphql  #perl  

Ruth  Gleason

Ruth Gleason

1667496660

Msgpack Perl: MessagePack Serializer Implementation for Perl

NAME

Data::MessagePack - MessagePack serializing/deserializing

SYNOPSIS

use Data::MessagePack;

my $mp = Data::MessagePack->new();
$mp->canonical->utf8->prefer_integer if $needed;

my $packed   = $mp->pack($dat);
my $unpacked = $mp->unpack($dat);

DESCRIPTION

This module converts Perl data structures to MessagePack and vice versa.

ABOUT MESSAGEPACK FORMAT

MessagePack is a binary-based efficient object serialization format. It enables to exchange structured objects between many languages like JSON. But unlike JSON, it is very fast and small.

ADVANTAGES

PORTABLE

The MessagePack format does not depend on language nor byte order.

SMALL IN SIZE

  say length(JSON::XS::encode_json({a=>1, b=>2}));   # => 13
  say length(Storable::nfreeze({a=>1, b=>2}));       # => 21
  say length(Data::MessagePack->pack({a=>1, b=>2})); # => 7

The MessagePack format saves memory than JSON and Storable format.

STREAMING DESERIALIZER

MessagePack supports streaming deserializer. It is useful for networking such as RPC. See Data::MessagePack::Unpacker for details.

If you want to get more information about the MessagePack format, please visit to http://msgpack.org/.

METHODS

my $packed = Data::MessagePack->pack($data[, $max_depth]);

Pack the $data to messagepack format string.

This method throws an exception when the perl structure is nested more than $max_depth levels(default: 512) in order to detect circular references.

Data::MessagePack->pack() throws an exception when encountering a blessed perl object, because MessagePack is a language-independent format.

my $unpacked = Data::MessagePack->unpack($msgpackstr);

unpack the $msgpackstr to a MessagePack format string.

my $mp = Data::MesssagePack->new()

Creates a new MessagePack instance.

$mp = $mp->prefer_integer([ $enable ])

$enabled = $mp->get_prefer_integer()

If $enable is true (or missing), then the pack method tries a string as an integer if the string looks like an integer.

$mp = $mp->canonical([ $enable ])

$enabled = $mp->get_canonical()

If $enable is true (or missing), then the pack method will output packed data by sorting their keys. This is adding a comparatively high overhead.

$mp = $mp->utf8([ $enable ])

$enabled = $mp->get_utf8()

If $enable is true (or missing), then the pack method will apply utf8::encode() to all the string values.

In other words, this property tell $mp to deal with text strings. See perlunifaq for the meaning of text string.

$packed = $mp->pack($data)

$packed = $mp->encode($data)

Same as Data::MessagePack->pack(), but properties are respected.

$data = $mp->unpack($data)

$data = $mp->decode($data)

Same as Data::MessagePack->unpack(), but properties are respected.

Configuration Variables (DEPRECATED)

$Data::MessagePack::PreferInteger

Packs a string as an integer, when it looks like an integer.

This variable is deprecated. Use $msgpack->prefer_integer property instead.

SPEED

This is a result of benchmark/serialize.pl and benchmark/deserialize.pl on my SC440(Linux 2.6.32-23-server #37-Ubuntu SMP). (You should benchmark them with your data if the speed matters, of course.)

-- serialize
JSON::XS: 2.3
Data::MessagePack: 0.24
Storable: 2.21
Benchmark: running json, mp, storable for at least 1 CPU seconds...
      json:  1 wallclock secs ( 1.00 usr +  0.01 sys =  1.01 CPU) @ 141939.60/s (n=143359)
        mp:  1 wallclock secs ( 1.06 usr +  0.00 sys =  1.06 CPU) @ 355500.94/s (n=376831)
  storable:  1 wallclock secs ( 1.12 usr +  0.00 sys =  1.12 CPU) @ 38399.11/s (n=43007)
             Rate storable     json       mp
storable  38399/s       --     -73%     -89%
json     141940/s     270%       --     -60%
mp       355501/s     826%     150%       --

-- deserialize
JSON::XS: 2.3
Data::MessagePack: 0.24
Storable: 2.21
Benchmark: running json, mp, storable for at least 1 CPU seconds...
      json:  0 wallclock secs ( 1.05 usr +  0.00 sys =  1.05 CPU) @ 179442.86/s (n=188415)
        mp:  0 wallclock secs ( 1.01 usr +  0.00 sys =  1.01 CPU) @ 212909.90/s (n=215039)
  storable:  2 wallclock secs ( 1.14 usr +  0.00 sys =  1.14 CPU) @ 114974.56/s (n=131071)
             Rate storable     json       mp
storable 114975/s       --     -36%     -46%
json     179443/s      56%       --     -16%
mp       212910/s      85%      19%       --

CAVEAT

Unpacking 64 bit integers

This module can unpack 64 bit integers even if your perl does not support them (i.e. where perl -V:ivsize is 4), but you cannot calculate these values unless you use Math::BigInt.

TODO

Error handling

MessagePack cannot deal with complex scalars such as object references, filehandles, and code references. We should report the errors more kindly.

Streaming deserializer

The current implementation of the streaming deserializer does not have internal buffers while some other bindings (such as Ruby binding) does. This limitation will astonish those who try to unpack byte streams with an arbitrary buffer size (e.g. while(read($socket, $buffer, $arbitrary_buffer_size)) { ... }). We should implement the internal buffer for the unpacker.

FAQ

Why does Data::MessagePack have pure perl implementations?

msgpack C library uses C99 feature, VC++6 does not support C99. So pure perl version is needed for VC++ users.

AUTHORS

Tokuhiro Matsuno

Makamaka Hannyaharamitu

gfx

THANKS TO

Jun Kuriyama

Dan Kogai

FURUHASHI Sadayuki

hanekomu

Kazuho Oku

syohex

LICENSE

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

SEE ALSO

http://msgpack.org/ is the official web site for the MessagePack format.

Data::MessagePack::Unpacker

AnyEvent::MPRPC


Download Details:

Author: msgpack
Source Code: https://github.com/msgpack/msgpack-perl

License: View license

#perl