API-Docker

 view release on metacpan or  search on metacpan

CLAUDE.md  view on Meta::CPAN

lib/API/Docker/Role/Entity.pm           # the client an entity delegates through
lib/API/Docker/Role/Entity/Container.pm # container operations, composed onto ContainerSummary + ContainerInspectResponse
lib/API/Docker/Role/Entity/Image.pm     # image operations, composed onto ImageSummary + ImageInspect
lib/API/Docker/Role/Entity/Network.pm   # network operations, composed onto Type::Network (one class for list and inspect)
lib/API/Docker/Role/Entity/Volume.pm    # volume operations, composed onto Type::Volume (list, inspect and create)
lib/API/Docker/Role/Entity/Plugin.pm    # plugin operations, composed onto Type::Plugin
lib/API/Docker/Role/Entity/Secret.pm    # secret operations, composed onto Type::Secret
lib/API/Docker/Role/Entity/Config.pm    # config operations, composed onto Type::Config
lib/API/Docker/Error/HTTP.pm            # croaked on a status of 400 or above
lib/API/Docker/Error/Stream.pm          # croaked on a failed build/pull/push stream
lib/API/Docker/Error/Timeout.pm         # croaked when a read_timeout or connect_timeout runs out
lib/API/Docker/Error/Truncated.pm       # croaked when the daemon closed before its announced response was complete
maint/spec-to-type.pl                   # generates lib/API/Docker/Type/*.pm from spec/ -- never overwrites
maint/spec-drift-check.pl               # diffs spec/ against the registry, and spec against spec
maint/spec-common.pl                    # the spec loader shared by the two scripts above
maint/spec-to-type-names.yaml           # inline-class naming exceptions the generator and checker share
maint/spec-to-type-prose.yaml           # hand-written POD for fields/classes the swagger describes poorly
maint/spec-drift-exceptions.yaml        # deliberate deviations the drift checker accepts
maint/spec-overlay.yaml                 # named fields of v1.55 grafted onto the v1.51 base model
spec/v1.41.yaml .. v1.55.yaml           # Docker's own swagger, checked in; generation runs against v1.51 plus the overlay
t/                                      # tests (prove -lr t/)

Changes  view on Meta::CPAN

    `::Plugin`, `::Secret`, `::Config`) ship as stubs that croak, naming what
    replaces them.
  - New streaming options `on_event`, `on_frame` and `on_chunk` on the HTTP
    verbs, wired into `system->events`, `containers->logs`/`stats`/`attach`,
    `exec->start`, the `images` build/pull/push/load/get family and the
    `plugins` install/upgrade/push. A callback receives each event, frame or
    chunk as it arrives; `$stop->()` ends the stream early. Without one the
    unbounded endpoints still block.
  - New `read_timeout` and `connect_timeout`, as client attributes and
    per-request options, off by default. `read_timeout` is idle time since
    the last byte; both croak `API::Docker::Error::Timeout`, which carries
    whatever already arrived. A new `TIMEOUTS` section in `API::Docker`
    documents what each bounds. `containers->stats` is deliberately not
    bounded by `read_timeout` -- its stream keeps producing rather than
    going idle.
  - New `API::Docker::Role::Using`: `$docker->containers->using(read_timeout
    => 5)->list` clones a resource class to bound a run of calls. Every
    request the run makes, version negotiation included, carries the bound;
    an explicit `0` turns a client-wide default off.
  - A truncated response is now an exception. A body shorter than its
    Content-Length, a short or malformed chunk, a missing zero chunk, a

MANIFEST  view on Meta::CPAN

lib/API/Docker/API/Images.pm
lib/API/Docker/API/Networks.pm
lib/API/Docker/API/Plugins.pm
lib/API/Docker/API/Secrets.pm
lib/API/Docker/API/System.pm
lib/API/Docker/API/Volumes.pm
lib/API/Docker/Config.pm
lib/API/Docker/Container.pm
lib/API/Docker/Error/HTTP.pm
lib/API/Docker/Error/Stream.pm
lib/API/Docker/Error/Timeout.pm
lib/API/Docker/Error/Truncated.pm
lib/API/Docker/Image.pm
lib/API/Docker/Network.pm
lib/API/Docker/Plugin.pm
lib/API/Docker/Role/Entity.pm
lib/API/Docker/Role/Entity/Config.pm
lib/API/Docker/Role/Entity/Container.pm
lib/API/Docker/Role/Entity/Image.pm
lib/API/Docker/Role/Entity/Network.pm
lib/API/Docker/Role/Entity/Plugin.pm

META.json  view on Meta::CPAN

         "version" : "0.006"
      },
      "API::Docker::Error::HTTP" : {
         "file" : "lib/API/Docker/Error/HTTP.pm",
         "version" : "0.006"
      },
      "API::Docker::Error::Stream" : {
         "file" : "lib/API/Docker/Error/Stream.pm",
         "version" : "0.006"
      },
      "API::Docker::Error::Timeout" : {
         "file" : "lib/API/Docker/Error/Timeout.pm",
         "version" : "0.006"
      },
      "API::Docker::Error::Truncated" : {
         "file" : "lib/API/Docker/Error/Truncated.pm",
         "version" : "0.006"
      },
      "API::Docker::Image" : {
         "file" : "lib/API/Docker/Image.pm",
         "version" : "0.006"
      },

META.yml  view on Meta::CPAN

    version: '0.006'
  API::Docker::Container:
    file: lib/API/Docker/Container.pm
    version: '0.006'
  API::Docker::Error::HTTP:
    file: lib/API/Docker/Error/HTTP.pm
    version: '0.006'
  API::Docker::Error::Stream:
    file: lib/API/Docker/Error/Stream.pm
    version: '0.006'
  API::Docker::Error::Timeout:
    file: lib/API/Docker/Error/Timeout.pm
    version: '0.006'
  API::Docker::Error::Truncated:
    file: lib/API/Docker/Error/Truncated.pm
    version: '0.006'
  API::Docker::Image:
    file: lib/API/Docker/Image.pm
    version: '0.006'
  API::Docker::Network:
    file: lib/API/Docker/Network.pm
    version: '0.006'

lib/API/Docker.pm  view on Meta::CPAN

replaces three earlier failures on the same path -- a non-object body dying in
C<strict refs>, an object with no C<ApiVersion> silently leaving the client
sending every request unversioned, and a malformed C<ApiVersion> being copied
verbatim into the request path.

Options:

=over

=item * C<read_timeout> - Seconds of silence after which the request gives up
and croaks with an L<API::Docker::Error::Timeout>. Off by default; see
L<API::Docker::Role::HTTP/"Bounding a request that never ends">

=item * C<connect_timeout> - Seconds after which opening the connection gives
up and croaks with an L<API::Docker::Error::Timeout> whose C<< ->phase >> is
C<'connect'>. Off by default; see
L<API::Docker::Role::HTTP/"Bounding the connection itself">

=back

Called on its own, with no options, the negotiation is bounded by the
L<API::Docker::Role::HTTP/read_timeout> and
L<API::Docker::Role::HTTP/connect_timeout> attributes of the client, like any
other request. Reached the way it normally is -- automatically, from the first
request -- it inherits that request's own bounds instead; see

lib/API/Docker.pm  view on Meta::CPAN

=item * B<Under TLS, C<read_timeout> is not quite an idle timer on the
plaintext.> It is C<SO_RCVTIMEO> on the socket, which bounds each blocking
receive on the underlying connection, and one plaintext read can consume
several of those while a TLS record arrives in pieces -- so a record dribbling
in slowly enough resets the clock without a byte reaching the caller. It still
bounds the hang, which is what it is for. C<connect_timeout> over TLS bounds
the TCP connect and not the handshake that follows it.

=back

An expiry croaks with an L<API::Docker::Error::Timeout> carrying what did
arrive; it never returns a truncated response.
L<API::Docker::Role::HTTP/"Bounding a request that never ends"> and
L<API::Docker::Role::HTTP/"Bounding the connection itself"> have the
per-transport measurements behind all of this.

=head2 Where a bound applies

Every public method of every resource class that reaches the daemon -- all of
them, with no exception for the ones whose arguments are the request body --
makes its request with the bounds in force. That is what the clone buys: the

lib/API/Docker.pm  view on Meta::CPAN

=item * L<API::Docker::API::Configs> - Swarm configs

=item * L<API::Docker::API::Plugins> - Managed plugins

=item * L<API::Docker::Error::HTTP> - Raised for a status of 400 or above,
carries the status code

=item * L<API::Docker::Error::Stream> - Raised for a failure reported inside a
200 event stream

=item * L<API::Docker::Error::Timeout> - Raised when a request given a
C<read_timeout> or C<connect_timeout> runs out of it

=item * L<API::Docker::Error::Truncated> - Raised when the daemon closed
before the response it announced was complete

=back

=head1 SUPPORT

=head2 Issues

lib/API/Docker/Error/Timeout.pm  view on Meta::CPAN

package API::Docker::Error::Timeout;
# ABSTRACT: Read timeout while waiting for the Docker Engine
our $VERSION = '0.006';
use Moo;
# namespace::clean has to come BEFORE "use overload" here, not after it as
# everywhere else in this distribution -- same reason as in
# API::Docker::Error::Stream and API::Docker::Error::HTTP. It sweeps the
# symbols `overload` installs -- the `("" ` slot among them -- so with the two
# lines in the house order the class ends up not overloaded at all and
# stringifies as API::Docker::Error::Timeout=HASH(0x...). Nothing dies when
# that happens: every caller that only inspects $@ as a string silently starts
# seeing a reference address instead of the reason. Measured, not assumed:
# overload::Overloaded($err) is false with the lines swapped.
use namespace::clean;
use overload
  '""'     => sub { $_[0]->as_string },
  'bool'   => sub { 1 },
  fallback => 1;


lib/API/Docker/Error/Timeout.pm  view on Meta::CPAN

1;

__END__

=pod

=encoding UTF-8

=head1 NAME

API::Docker::Error::Timeout - Read timeout while waiting for the Docker Engine

=head1 VERSION

version 0.006

=head1 SYNOPSIS

    # Stop waiting after two seconds of silence instead of hanging forever.
    my $out = '';
    eval {
        $docker->containers->attach($id,
            stream       => 1,
            stdout       => 1,
            read_timeout => 2,
            on_frame     => sub { $out .= $_[0]{data} },
        );
    };
    if (my $err = $@) {
        die $err unless ref $err
            && $err->isa('API::Docker::Error::Timeout');
        # Every complete frame reached the callback before the timeout; the
        # summary says how many.
        warn 'stopped after ' . $err->summary->{delivered} . ' frames';
    }

=head1 DESCRIPTION

L<API::Docker::Role::HTTP> croaks with an object of this class when a request
was given a L<API::Docker::Role::HTTP/read_timeout> and the daemon then went
quiet for longer than it -- and, with L</phase> set to C<'connect'>, when a

lib/API/Docker/Error/Truncated.pm  view on Meta::CPAN

package API::Docker::Error::Truncated;
# ABSTRACT: The daemon closed before the response it announced was complete
our $VERSION = '0.006';
use Moo;
# namespace::clean has to come BEFORE "use overload" here, not after it as
# everywhere else in this distribution -- same reason as in
# API::Docker::Error::Stream, API::Docker::Error::HTTP and
# API::Docker::Error::Timeout. It sweeps the symbols `overload` installs --
# the `("" ` slot among them -- so with the two lines in the house order the
# class ends up not overloaded at all and stringifies as
# API::Docker::Error::Truncated=HASH(0x...). Nothing dies when that happens:
# every caller that only inspects $@ as a string silently starts seeing a
# reference address instead of the reason. Measured, not assumed:
# overload::Overloaded($err) is false with the lines swapped.
use namespace::clean;
use overload
  '""'     => sub { $_[0]->as_string },
  'bool'   => sub { 1 },

lib/API/Docker/Error/Truncated.pm  view on Meta::CPAN

is not a short one, it is an unfinished one.

A body delimited by nothing but the close -- C<attach>,
C<< logs(follow => 1) >>, C</exec/{id}/start>, the whole
C<application/vnd.docker.raw-stream> family -- announces no end and has no
terminator either, so there an EOF B<is> the end and this is never raised.
Its B<head> is framed like any other, and is checked like any other.

=head2 Why it is fatal

For the same reason L<API::Docker::Error::Timeout> is, and the two are the
same defect reached by different routes: a short body satisfies every return
shape this role promises and is indistinguishable from a complete one.
C<ndjson> promises an ArrayRef of events and gets a shorter one; C<raw>
promises the response bytes and gets fewer of them; the default promises the
decoded body and gets whatever the truncated bytes happened to parse as. A
half tarball that looks whole is the worst of them, and it is the case this
exists for.

Nothing is lost by raising it: L</partial> carries the bytes a buffered read
had collected and L</summary> the count a streamed one had delivered, so a
caller who wants what arrived can have it. What it cannot do any more is
mistake it for everything.

=head2 What it is not

Not a timeout. Nothing waited and nothing expired -- the daemon answered, and
then the stream ended early. L<API::Docker::Error::Timeout> is raised when the
daemon goes B<quiet> for longer than a C<read_timeout>, which is a bound the
caller asked for; this needs no option and is on for every request.

Not a status. Where a status line arrived intact it said 200 and the response
after it did not follow; where L</phase> is C<'status-line'> there was no
usable status to begin with. An engine that reports a failure the normal way
raises L<API::Docker::Error::HTTP>, and one that reports it inside an HTTP 200
stream raises L<API::Docker::Error::Stream>. This is the third thing: no
report at all, because the connection went away mid-sentence.

lib/API/Docker/Error/Truncated.pm  view on Meta::CPAN

The message and the location suffix, concatenated. This is what the
stringification overload returns.

=head1 SEE ALSO

=over

=item * L<API::Docker::Role::HTTP> - Raises this error; see
L<API::Docker::Role::HTTP/"Failure in the middle of a response">

=item * L<API::Docker::Error::Timeout> - Raised instead when the daemon went
quiet for longer than a C<read_timeout>, rather than closing

=item * L<API::Docker::Error::HTTP> - Raised instead when the daemon answered,
completely, with a status of 400 or above

=item * L<API::Docker::Error::Stream> - Raised instead for a failure reported
inside a stream the daemon already answered with HTTP 200

=back

lib/API/Docker/Role/HTTP.pm  view on Meta::CPAN

# stream (EAGAIN/EWOULDBLOCK), and how it says it was interrupted rather than
# either (EINTR). See _pull and _timed_out.
use Errno qw( EAGAIN EWOULDBLOCK EINTR );
use JSON::MaybeXS qw( encode_json decode_json );
use Scalar::Util qw( looks_like_number );
use Path::Tiny;
use Carp qw( croak shortmess );
use Log::Any qw( $log );
use API::Docker::Error::HTTP;
use API::Docker::Error::Stream;
use API::Docker::Error::Timeout;
use API::Docker::Error::Truncated;
use namespace::clean;


requires 'host';
requires 'api_version';
requires 'tls';
requires 'cert_path';
requires 'tls_insecure';

lib/API/Docker/Role/HTTP.pm  view on Meta::CPAN

has _socket => (
  is      => 'lazy',
  clearer => '_clear_socket',
);

# The connect timeout and the endpoint it belongs to, on their way to
# _build__socket. It is a lazy builder and so cannot be handed an argument,
# and the value is per request rather than per client -- hence rw, with
# _reconnect as the only writer, setting it immediately before the build and
# clearing it immediately after. Unset is the whole of the old behaviour: no
# Timeout on any constructor, and the plain croak on a failure.
has _pending_connect => (
  is       => 'rw',
  init_arg => undef,
);

sub _build__socket {
  my ($self) = @_;
  my $host    = $self->host;
  my $pending = $self->_pending_connect;
  my $timeout = $pending ? $pending->{timeout} : undef;

  if ($host =~ m{^unix://(.+)$}) {
    my $path = $1;
    $log->debugf("Connecting to Unix socket: %s", $path);
    my $sock = IO::Socket::UNIX->new(
      Peer => $path,
      Type => SOCK_STREAM,
      $timeout ? (Timeout => $timeout) : (),
    );
    unless ($sock) {
      # Asked before anything else can touch $@ or $!, which is the whole of
      # the evidence; see _connect_expired.
      $self->_croak_connect_timeout($pending, 'unix://' . $path)
        if $self->_connect_expired($timeout);
      croak "Cannot connect to Unix socket $path: $!";
    }
    return $sock;
  }
  elsif ($host =~ m{^tcp://([^:]+):(\d+)$}) {
    my ($addr, $port) = ($1, $2);

    unless ($self->tls) {
      $log->debugf("Connecting to TCP %s:%s", $addr, $port);
      my $sock = IO::Socket::INET->new(
        PeerAddr => $addr,
        PeerPort => $port,
        Proto    => 'tcp',
        $timeout ? (Timeout => $timeout) : (),
      );
      unless ($sock) {
        $self->_croak_connect_timeout($pending, $addr . ':' . $port)
          if $self->_connect_expired($timeout);
        croak "Cannot connect to $addr:$port: $!";
      }
      return $sock;
    }

    # Built before the connection is opened: a cert_path that names nothing,
    # or half a client certificate, is a configuration mistake and the caller
    # should hear about it as one rather than as a handshake failure.
    my %ssl = $self->_ssl_options($addr);

    $log->debugf("Connecting to TCP %s:%s over TLS (verification %s)",
      $addr, $port, $self->tls_insecure ? 'off' : 'on');
    my $sock = IO::Socket::SSL->new(
      PeerAddr => $addr,
      PeerPort => $port,
      Proto    => 'tcp',
      $timeout ? (Timeout => $timeout) : (),
      %ssl,
    );
    unless ($sock) {
      $self->_croak_connect_timeout($pending, $addr . ':' . $port . ' (TLS)')
        if $self->_connect_expired($timeout);
      # $SSL_ERROR carries the handshake failure -- an untrusted certificate,
      # a name that does not match -- and $! the plain connect failure. Both
      # are named because either can be the one that happened. The pragma is
      # for the package variable of a module that is not loaded at compile
      # time, which perl would otherwise report as a probable typo.

lib/API/Docker/Role/HTTP.pm  view on Meta::CPAN

  return $sock;
}

# Whether the connect that has just failed failed because the bound fired.
# Asked with nothing in between, because $@ and $! are the whole of the
# evidence and both are global.
#
# $@ rather than errno: IO::Socket writes 'connect: timeout' there, and only
# there, when its own select() ran out -- measured, against a host that drops
# SYNs, where $! is ETIMEDOUT, which the kernel also produces on its own after
# two minutes with no Timeout set at all.
#
# EAGAIN is the second shape and belongs to unix:// alone. Measured against a
# listener whose backlog is full: with no Timeout the connect blocks
# indefinitely (still blocked after 8s), and with one it fails at once with
# EAGAIN, because IO::Socket does the timed connect non-blocking and an
# AF_UNIX connect has no in-progress state to wait on. So on that transport
# the option does not wait, it refuses -- but a connect that failed with
# EAGAIN is still one the bound ended, and reporting it as anything else would
# name a cause the caller cannot act on.
sub _connect_expired {
  my ($self, $timeout) = @_;

  return 0 unless $timeout;

lib/API/Docker/Role/HTTP.pm  view on Meta::CPAN

  return 1 if $! == EAGAIN || $! == EWOULDBLOCK;
  return 0;
}

sub _croak_connect_timeout {
  my ($self, $pending, $where) = @_;

  my $endpoint = $pending->{endpoint};
  # See _croak_timeout for why the object goes into a variable first and why
  # the location is captured by hand.
  my $error = API::Docker::Error::Timeout->new(
    message  => 'Docker API connect timeout'
      . (defined $endpoint && length $endpoint ? ' (' . $endpoint . ')' : '')
      . ': ' . $where . ' did not accept within ' . $pending->{timeout} . 's',
    location => shortmess(''),
    endpoint => defined $endpoint ? $endpoint : '',
    timeout  => $pending->{timeout},
    phase    => 'connect',
  );
  croak $error;
}

lib/API/Docker/Role/HTTP.pm  view on Meta::CPAN

    : length($partial)
      ? ' after ' . length($partial) . ' byte'
        . (length($partial) == 1 ? '' : 's')
      : ', nothing arrived at all';

  # Carp hands a reference straight back rather than decorating it, so this
  # croak is a die with an object -- hence the location captured by hand,
  # which names the same frame a croak of a plain string would have named.
  # The object goes into a variable first: `croak CLASS->new(...)` is indirect
  # object syntax and parses as CLASS->croak(new(...)).
  my $error = API::Docker::Error::Timeout->new(
    message  => 'Docker API read timeout (' . $ctx->{endpoint} . '): '
      . $ctx->{timeout} . 's of silence' . $after,
    location => shortmess(''),
    endpoint => $ctx->{endpoint},
    timeout  => $ctx->{timeout},
    partial  => $partial,
    summary  => $summary,
  );
  croak $error;
}

lib/API/Docker/Role/HTTP.pm  view on Meta::CPAN

  if ($headers->{'transfer-encoding'}
      && lc($headers->{'transfer-encoding'}) eq 'chunked') {
    return $self->_read_chunked($sock, $ctx);
  }

  if (defined $headers->{'content-length'}) {
    my $len = $self->_assert_content_length($ctx, $headers->{'content-length'});
    return '' unless $len > 0;
    my $body = '';
    # What a timeout hands over instead of dropping: see
    # API::Docker::Error::Timeout/partial. localised so the context goes back
    # to carrying nothing once this body is done with.
    local $ctx->{partial} = \$body;
    # An announced length is a promise, and a stream that ends before it is
    # kept is truncation rather than the end of the body; see _read_exact.
    $self->_read_exact($sock, $len, \$body, $ctx, 'content-length',
      'the body');
    return $body;
  }

  # Read until the daemon closes. This used to be a `local $/; <$sock>` slurp;

lib/API/Docker/Role/HTTP.pm  view on Meta::CPAN

L<Net::SSLeay>, which is XS compiled against libssl, and the C<unix://>
transport -- local Docker, rootless Podman, the default -- never needs any of
it; requiring it would make this client unbuildable on a machine with no
OpenSSL headers for the sake of a transport it is not using. Without it,
C<< tls => 1 >> croaks naming the module and how to install it, at the same
point every other connection failure is reported.

=head2 read_timeout

Seconds of silence after which a request gives up and croaks with an
L<API::Docker::Error::Timeout>. C<undef> -- the default, and what every
existing caller gets -- means no timeout at all and is the behaviour this
distribution has always had. C<0> means the same and is the way to say it
explicitly, so a client carrying a default can be opted out of per request.

    my $docker = API::Docker->new(read_timeout => 30);
    $docker->system->using(read_timeout => 0)->events;   # this one may wait

Per request it is an option of L</get>, L</post>, L</put>, L</delete_request>
and L</head>. A resource class carries it through
L<API::Docker::Role::Using/using>, which clones the class rather than taking
it per method -- up for a slow endpoint, down for a stream that should not
stall, off with C<0>.

See L</"Bounding a request that never ends"> for what it does and does not
cover, and L<API::Docker/"What a timeout covers"> for the same question
asked of both bounds at once.

=head2 connect_timeout

Seconds after which opening the connection gives up and croaks with an
L<API::Docker::Error::Timeout> whose C<< ->phase >> is C<'connect'>. C<undef>
-- the default, and what every existing caller gets -- means no bound and is
the behaviour this distribution has always had; C<0> means the same and is the
way to say it explicitly.

    my $docker = API::Docker->new(connect_timeout => 5);
    $docker->system->using(connect_timeout => 0)->version;  # may wait

Separate from L</read_timeout> rather than folded into it, because the two
bound different things and want different numbers: a connect is either
immediate or broken, while a read is waiting on work the daemon has to do.

lib/API/Docker/Role/HTTP.pm  view on Meta::CPAN


=item * C<response> - HashRef the status line and the response headers are
written into; see L</"Reading the status line and the response headers">

=item * C<on_event>, C<on_frame>, C<on_chunk> - CodeRef called with each unit
of the response as it arrives, instead of the body being buffered and
returned. At most one of the three; see L</"Streaming a response as it
arrives">

=item * C<read_timeout> - Seconds of silence after which this request gives up
and croaks with an L<API::Docker::Error::Timeout>. Overrides the
L</read_timeout> attribute; C<0> means no timeout. See L</"Bounding a request
that never ends">

=item * C<connect_timeout> - Seconds after which opening the connection gives
up and croaks with an L<API::Docker::Error::Timeout> whose C<< ->phase >> is
C<'connect'>. Overrides the L</connect_timeout> attribute; C<0> means no
bound. See L</"Bounding the connection itself">

=item * C<headers> names are validated, not sanitised; see
L</"Header names are rejected, header values are stripped">

=back

=head2 Bounding a request that never ends

lib/API/Docker/Role/HTTP.pm  view on Meta::CPAN

prompt. So no existing call changes behaviour, and picking the number is the
caller's -- who is the only one who knows what the request is for.

For the two endpoints above, if you want a figure to start from: a couple of
seconds is right for C<attach> or C<logs> used to collect what is already
there, and something above the daemon's own emit interval -- Docker sends a
stats reading about once a second -- for C<stats>.

=head3 What happens when it expires

The request croaks, on every path, with an L<API::Docker::Error::Timeout>. It
never returns a truncated response: a short body satisfies every return shape
this role promises and would be indistinguishable from a complete one. The
exception carries what did arrive -- C<< ->partial >> for a buffered request,
C<< ->summary >> for a streamed one -- so collecting what there is and then
stopping is an C<eval>:

    my $out = '';
    eval {
        $docker->containers->using(read_timeout => 2)->attach($id,
            on_frame => sub { $out .= $_[0]{data} });
    };
    die $@ if $@ && !(ref $@
        && $@->isa('API::Docker::Error::Timeout'));

That class's own documentation has the reasoning for why this is fatal even
where the caller already holds every unit.

=head3 What it does not cover

Only reading. Connecting is bounded separately by L</connect_timeout>, and
writing the request is not bounded at all -- which matters only for a large
C</build> context sent to a daemon that has stopped reading.

lib/API/Docker/Role/HTTP.pm  view on Meta::CPAN

has no in-progress state to wait on. So the hang is gone, at the price of not
tolerating even a momentary backlog. A socket path that does not exist is
C<ENOENT> either way and is not affected.

=item * TLS -- bounds the TCP connect only. The handshake that follows it runs
on the connected socket, before L</read_timeout>'s C<SO_RCVTIMEO> is applied,
and is not covered by either.

=back

An expiry croaks with an L<API::Docker::Error::Timeout> carrying
C<< ->phase >> C<'connect'>, C<< ->timeout >> the value that expired and an
empty C<< ->partial >> -- there is no response to have part of. Every other
connect failure croaks with the plain string it always did: a refused
connection, a missing socket path and a rejected certificate are diagnoses,
not timeouts, and rewriting them as one would name a cause the caller cannot
act on.

=head2 Streaming a response as it arrives

Without one of these options a request is read whole, then parsed. That is

lib/API/Docker/Role/HTTP.pm  view on Meta::CPAN

on rootless Podman 5.8.4. So does every other shape either of them produces --
200, 204, 304, C<HEAD>, chunked. Nothing legitimate ends a head without its
blank line.

The same goes for a stream a callback ended with C<< $stop->() >>: the rest of
the response is unread because the caller said so, and every check on the
streaming path is skipped once it has.

=head3 Against a timeout, and against a status

L<API::Docker::Error::Timeout> is the daemon going B<quiet> for longer than a
bound the caller asked for; this is the daemon B<closing> mid-response, and
needs no bound to be noticed. The two share a contract -- neither ever returns
a short body, and both hand over what arrived -- and are separate classes
because only one of them is about an option, and only one of them can fire on
a response that would have completed.

A response whose status is 400 or above raises this rather than an
L<API::Docker::Error::HTTP> when it is B<its> body that was cut short, which
is the rule the timeout already follows in the same place: the transport
cannot tell a caller what the engine said when it did not finish saying it.

lib/API/Docker/Type/ContainerConfig.pm  view on Meta::CPAN


User-defined key/value metadata. B<The keys are the caller's data> and are
never translated.

=head2 stop_signal

Signal to stop a container as a string or unsigned integer.

=head2 stop_timeout

Timeout to stop a container in seconds. The daemon defaults it to 10.

=head2 shell

Shell for when C<RUN>, C<CMD>, and C<ENTRYPOINT> uses a shell.

=head1 SUPPORT

=head2 Issues

Please report bugs and feature requests at

misc/agent-context/CLAUDE.md  view on Meta::CPAN

lib/API/Docker/Role/Entity.pm           # the client an entity delegates through
lib/API/Docker/Role/Entity/Container.pm # container operations, composed onto ContainerSummary + ContainerInspectResponse
lib/API/Docker/Role/Entity/Image.pm     # image operations, composed onto ImageSummary + ImageInspect
lib/API/Docker/Role/Entity/Network.pm   # network operations, composed onto Type::Network (one class for list and inspect)
lib/API/Docker/Role/Entity/Volume.pm    # volume operations, composed onto Type::Volume (list, inspect and create)
lib/API/Docker/Role/Entity/Plugin.pm    # plugin operations, composed onto Type::Plugin
lib/API/Docker/Role/Entity/Secret.pm    # secret operations, composed onto Type::Secret
lib/API/Docker/Role/Entity/Config.pm    # config operations, composed onto Type::Config
lib/API/Docker/Error/HTTP.pm            # croaked on a status of 400 or above
lib/API/Docker/Error/Stream.pm          # croaked on a failed build/pull/push stream
lib/API/Docker/Error/Timeout.pm         # croaked when a read_timeout or connect_timeout runs out
lib/API/Docker/Error/Truncated.pm       # croaked when the daemon closed before its announced response was complete
maint/spec-to-type.pl                   # generates lib/API/Docker/Type/*.pm from spec/ -- never overwrites
maint/spec-drift-check.pl               # diffs spec/ against the registry, and spec against spec
maint/spec-common.pl                    # the spec loader shared by the two scripts above
maint/spec-to-type-names.yaml           # inline-class naming exceptions the generator and checker share
maint/spec-to-type-prose.yaml           # hand-written POD for fields/classes the swagger describes poorly
maint/spec-drift-exceptions.yaml        # deliberate deviations the drift checker accepts
maint/spec-overlay.yaml                 # named fields of v1.55 grafted onto the v1.51 base model
spec/v1.41.yaml .. v1.55.yaml           # Docker's own swagger, checked in; generation runs against v1.51 plus the overlay
t/                                      # tests (prove -lr t/)

t/connect_timeout.t  view on Meta::CPAN

#!/usr/bin/env perl
use strict;
use warnings;
use Test::More;
use Errno;
use File::Temp qw( tempdir );
use IO::Socket::UNIX;
use Time::HiRes qw( time );
use API::Docker;
use API::Docker::Error::Timeout;

# The connect timeout of API::Docker::Role::HTTP (karr k61).
#
# read_timeout (karr k59) bounds reading and nothing else, so a daemon that
# accepts and then says nothing is caught while a socket that never accepts is
# not. connect_timeout is the other half.
#
# Nothing here reaches a Docker daemon and nothing here touches the network:
# the one end-to-end assertion runs against a local Unix listener whose backlog
# has been filled, which is the only way an AF_UNIX connect blocks at all. So
# there is no is_live()/can_write() gating -- it is unconditionally safe with
# no engine installed.

# A client that records what _build__socket was handed instead of connecting,
# so the per-request resolution can be asserted at the seam it has to cross.
package Test::ConnectTimeout::Probe;
use Moo;
extends 'API::Docker';

has seen    => (is => 'ro', required => 1);
has pending => (is => 'ro', default  => sub { [] });

sub _build__socket {
  my ($self) = @_;
  my $pending = $self->_pending_connect;
  push @{ $self->seen },    $pending ? $pending->{timeout} : 'no pending';

t/connect_timeout.t  view on Meta::CPAN


subtest 'a missing socket still croaks the string it always did' => sub {
  my $missing = API::Docker->new(
    host            => 'unix:///nonexistent-api-docker-61.sock',
    api_version     => '1.41',
    connect_timeout => 5,
  );

  eval { $missing->get('/probe') };
  my $err = $@;
  ok !(ref $err && $err->isa('API::Docker::Error::Timeout')),
    'not turned into a timeout by having a connect_timeout set';
  like "$err", qr/Cannot connect to Unix socket/,
    'the diagnosis is the one the caller can act on';
};

# ---------------------------------------------------------------------------
# The one end-to-end assertion. An AF_UNIX connect blocks in exactly one
# situation -- the listener's backlog is full and nobody is accepting --
# measured with Listen => 1 and no accept: still blocked after 8 seconds. So
# the backlog is filled here, and then the bound has something to bound.

t/connect_timeout.t  view on Meta::CPAN

  my $path = $dir . '/backlog.sock';
  my $srv  = IO::Socket::UNIX->new(Local => $path, Listen => 1)
    or plan skip_all => "cannot listen on a Unix socket here: $!";

  # Filled with the same bounded connect the code under test uses, so this
  # loop cannot be the thing that hangs. Nothing ever accepts on $srv.
  my @held;
  my $full = 0;
  for (1 .. 200) {
    my $c = IO::Socket::UNIX->new(
      Peer => $path, Type => SOCK_STREAM, Timeout => 1);
    unless ($c) {
      $full = ($! == Errno::EAGAIN() || $! == Errno::EWOULDBLOCK()) ? 1 : 0;
      last;
    }
    push @held, $c;
  }
  plan skip_all => 'the listen backlog does not fill the way this platform '
    . 'was measured to' unless $full;

  my $blocked = API::Docker->new(
    host            => 'unix://' . $path,
    api_version     => '1.41',
    connect_timeout => 1,
  );

  # The alarm is the harness's own bound, not the one under test: without the
  # Timeout on the constructor this connect blocks forever, and a test that
  # hangs reports nothing. With it, the alarm never fires.
  my $t0 = time;
  eval {
    local $SIG{ALRM} = sub { die "the connect was never bounded at all\n" };
    alarm 10;
    $blocked->get('/probe');
    alarm 0;
    1;
  };
  my $err = $@;
  alarm 0;
  my $elapsed = time - $t0;

  isa_ok $err, 'API::Docker::Error::Timeout';
  is ref $err && $err->phase, 'connect',
    'the phase says the daemon was never reached';
  is ref $err && $err->timeout, 1, 'and names the bound that expired';
  is ref $err && $err->partial, '',
    'with no partial: there is no response to have part of';
  is ref $err && $err->summary, undef, 'and no summary';
  like "$err", qr{\QGET /v1.41/probe\E},
    'the request is named in the string';
  like "$err", qr/connect timeout/, 'and it says which bound this was';
  cmp_ok $elapsed, '<', 5,

t/connect_timeout.t  view on Meta::CPAN

  close $_ for @held;
  close $srv;
};

# ---------------------------------------------------------------------------
subtest 'the per-request option overrides the attribute either way' => sub {
  # What reached _build__socket, read where the constructors read it. Nothing
  # about this can be seen from the outside -- the connect either blocks or it
  # does not -- so the assertion is made at the seam the value has to cross.
  my @seen;
  my $probe = Test::ConnectTimeout::Probe->new(
    host            => 'unix:///nonexistent-api-docker-61.sock',
    api_version     => '1.41',
    connect_timeout => 5,
    seen            => \@seen,
  );

  eval { $probe->get('/probe') };
  eval { $probe->get('/probe', connect_timeout => 2) };
  # Resolved with exists rather than truth, so 0 is "wait as long as it takes"
  # rather than "no opinion", which is how a client-wide default is turned off

t/connect_timeout.t  view on Meta::CPAN

  );

  eval { $missing->get('/probe') };
  is $missing->_pending_connect, undef,
    'cleared even though the connect croaked -- a later socket built by '
    . 'anything but a request must not inherit the last one';
};

subtest 'a read timeout still says it was a read' => sub {
  # The default of the new attribute, asserted where it is cheap: every
  # Error::Timeout raised before this existed described a read.
  my $err = API::Docker::Error::Timeout->new(
    message => 'x', timeout => 2);
  is $err->phase, 'read', 'phase defaults to read';
};

done_testing;

t/read_timeout.t  view on Meta::CPAN

#!/usr/bin/env perl
use strict;
use warnings;
use Test::More;
use Socket;
use Errno;
use Time::HiRes qw( time );
use API::Docker;
use API::Docker::Error::Timeout;

# The read timeout of API::Docker::Role::HTTP (karr k59), in two tiers.
#
# Tier one -- everything down to "the real socket" below -- is the loop logic,
# which is where the risk is. SO_RCVTIMEO does not poison the handle and does
# not end the stream: a read that delivered nothing because the clock ran out
# comes back looking exactly like one that reached the end of the response, and
# errno is the only thing that tells them apart. Every `last unless $n` in the
# readers would otherwise take a timeout for the end of the body and hand back
# a truncated response as a whole one -- turning the hang this option removes

t/read_timeout.t  view on Meta::CPAN

#
# `line` and `bytes` are the same delivery -- to sysread a line and a run of
# bytes are both just bytes -- and are kept apart only so a script reads as the
# wire it stands for.
#
# Running off the end of the script is the clean end, so a scenario only has to
# script as far as the site under test. Every one of these shapes was measured
# on a real socketpair with SO_RCVTIMEO set before being written down here,
# including the one that matters most: a clean end leaves errno untouched and
# returns 0, while an expiry sets EAGAIN and returns undef.
package Test::ReadTimeout::Handle;

sub TIEHANDLE {
  my ($class, $script) = @_;
  return bless { script => $script, i => 0 }, $class;
}

sub _next {
  my ($self) = @_;
  return $self->{script}[ $self->{i}++ ] || {};
}

t/read_timeout.t  view on Meta::CPAN

  host        => 'unix:///nonexistent.sock',
  api_version => '1.41',
);

my $ENDPOINT = 'GET /v1.41/probe';

sub scripted {
  my (@script) = @_;
  no warnings "once";
  my $glob = \do { local *HANDLE };
  tie *$glob, 'Test::ReadTimeout::Handle', \@script;
  return $glob;
}

# A context with the clock running, and one without. The second is what every
# call made before this option existed passes, and it must leave every read
# site behaving exactly as it did.
sub ctx      { return { endpoint => $ENDPOINT, timeout => 2 } }
sub ctx_off  { return { endpoint => $ENDPOINT } }

# Run $code and report whether it raised a timeout, so the two meanings of one
# short read can be asserted side by side.
sub timed_out {
  my ($code) = @_;
  my @out = eval { $code->() };
  my $err = $@;
  return (undef, $err) if $err && ref $err
    && $err->isa('API::Docker::Error::Timeout');
  return (\@out, undef) unless $err;
  return (undef, undef, $err);
}

# Reading an attribute off whatever was raised, so a mutation that stops
# raising one fails the assertion it belongs to instead of dying and taking
# the rest of the file with it -- a red test has to stay readable.
sub attr {
  my ($err, $name) = @_;
  return ref $err && $err->can($name) ? $err->$name : undef;

t/read_timeout.t  view on Meta::CPAN

  my ($name, $make_handle, $drive, %eof) = @_;

  die "site_ok $name: declare exactly one of returns/raises\n"
    unless 1 == grep { $eof{$_} } qw( returns raises );

  subtest $name => sub {
    my ($out, $err, $other) = timed_out(
      sub { $drive->($make_handle->(1), ctx()) });
    ok !$other, 'the expiry raised nothing but a timeout'
      or diag "raised instead: $other";
    ok $err, 'ran out of time -> API::Docker::Error::Timeout';
    is $err && attr($err, "timeout"), 2, 'the error names the timeout that expired'
      if $err;
    is $err && attr($err, "endpoint"), $ENDPOINT, 'and the request it belongs to'
      if $err;

    my ($eof_out, $eof_err, $eof_other) = timed_out(
      sub { $drive->($make_handle->(0), ctx()) });
    ok !$eof_err, 'the same short read at the end of the response is not a '
      . 'timeout';
    if ($eof{raises}) {

t/read_timeout.t  view on Meta::CPAN


# ---------------------------------------------------------------------------
# What the exception carries
# ---------------------------------------------------------------------------
subtest 'the bytes that did arrive come out with the exception' => sub {
  subtest 'a content-length body' => sub {
    my $fh = scripted({ bytes => 'hello ' }, { bytes => 'wor' },
      { timeout => 1 });
    eval { $client->_read_body($fh, { 'content-length' => 11 }, 'GET', ctx()) };
    my $err = $@;
    isa_ok $err, 'API::Docker::Error::Timeout';
    is attr($err, "partial"), 'hello wor',
      'everything read so far, the bytes of the read that expired included';
    is attr($err, "summary"), undef, 'no summary: nothing was streamed';
  };

  subtest 'a chunked body keeps the chunk it stalled inside' => sub {
    my $fh = scripted({ line => "5\r\n" }, { bytes => 'hello' },
      { line => "\r\n" }, { line => "6\r\n" }, { bytes => ' wor' },
      { timeout => 1 });
    eval { $client->_read_chunked($fh, ctx()) };
    my $err = $@;
    isa_ok $err, 'API::Docker::Error::Timeout';
    is attr($err, "partial"), 'hello wor',
      'the completed chunk and the part of the one still arriving';
  };

  subtest 'a close-delimited body' => sub {
    my $fh = scripted({ bytes => 'partial frames' }, { timeout => 1 });
    eval { $client->_read_body($fh, {}, 'GET', ctx()) };
    isa_ok $@, 'API::Docker::Error::Timeout';
    is attr($@, "partial"), 'partial frames', 'the bytes the slurp had collected';
  };

  subtest 'a streamed request carries the summary instead' => sub {
    my @got;
    my $fh = scripted($HEAD_OK, { line => "Transfer-Encoding: chunked\r\n" },
      $BLANK,
      { line => "5\r\n" }, { bytes => 'hello' }, { line => "\r\n" },
      { line => "5\r\n" }, { bytes => 'there' }, { line => "\r\n" },
      { timeout => 1 });
    eval {
      $client->_read_streaming_response($fh, 'GET', chunk_handler(\@got), ctx());
    };
    my $err = $@;
    isa_ok $err, 'API::Docker::Error::Timeout';
    is_deeply attr($err, "summary"), { delivered => 2, stopped => 0 },
      'the units the callback did get, counted the way a clean end counts them';
    is attr($err, "partial"), '',
      'and no body: a streamed request keeps none by design';
    like attr($err, "message"), qr/2 units/, 'the message says so too';
  };

  subtest 'everything that arrived is delivered before the expiry' => sub {
    # This is the shape karr k52 actually has: everything the daemon had to
    # say arrives, and the socket then stays open and silent. Measured against

t/read_timeout.t  view on Meta::CPAN

    # script below has two entries where it used to have one. What is asserted
    # is the property, not the mechanism: at the moment the exception is
    # raised, the caller is holding everything the daemon sent.
    my @got;
    my $fh = scripted($HEAD_OK, $BLANK,
      { bytes => 'frame one and two' }, { timeout => 1 });
    eval {
      $client->_read_streaming_response($fh, 'GET', chunk_handler(\@got), ctx());
    };
    my $err = $@;
    isa_ok $err, 'API::Docker::Error::Timeout';
    is_deeply \@got, ['frame one and two'],
      'the callback got every byte that arrived';
    is_deeply attr($err, 'summary'), { delivered => 1, stopped => 0 },
      'and the summary counts them, so it says what happened rather than '
      . 'undercounting it';
  };

  subtest 'an error body on the way to a >= 400 croak is counted in bytes' => sub {
    # The summary is only armed past the status line, so a timeout while
    # reading the short JSON body of a failure is not reported as units that
    # nothing delivered.
    my @got;
    my $fh = scripted({ line => "HTTP/1.1 500 Internal Server Error\r\n" },
      { line => "Content-Length: 40\r\n" }, $BLANK,
      { bytes => '{"message":"bo' }, { timeout => 1 });
    eval {
      $client->_read_streaming_response($fh, 'GET', chunk_handler(\@got), ctx());
    };
    my $err = $@;
    isa_ok $err, 'API::Docker::Error::Timeout';
    is attr($err, "summary"), undef, 'no summary for a body that was never a stream';
    is attr($err, "partial"), '{"message":"bo', 'the bytes of the error body';
  };

  subtest 'nothing at all is said so, not reported as zero bytes' => sub {
    my $fh = scripted($HEAD_OK, { line => "Content-Length: 11\r\n" }, $BLANK,
      { timeout => 1 });
    eval { $client->_read_response($fh, 'GET', ctx()) };
    my $err = $@;
    isa_ok $err, 'API::Docker::Error::Timeout';
    is attr($err, "partial"), '', 'partial is empty';
    like attr($err, "message"), qr/nothing arrived at all/, 'and the message says so';
  };
};

subtest 'the exception is still the string it replaces' => sub {
  my $fh = scripted({ timeout => 1 });
  eval { $client->_read_head($fh, ctx()) };
  my $err = $@;
  isa_ok $err, 'API::Docker::Error::Timeout';
  ok overload::Overloaded($err),
    'stringification is in place -- namespace::clean before use overload';
  unlike "$err", qr/=HASH\(0x/,
    "stringifies to the reason, not to a reference address";
  like "$err", qr/\Q$ENDPOINT\E/, 'the request is named in the string';
  like "$err", qr/ at \S+ line \d+/, 'with Carp\'s own location suffix';
  ok !!$err, 'and it is true as an exception';
};

# ---------------------------------------------------------------------------

t/read_timeout.t  view on Meta::CPAN


  $client->_apply_read_timeout($ours, 0.2);

  # The peer is open and silent, so without the option in force this read
  # blocks forever and the test never finishes.
  my $t0 = time;
  eval { $client->_read_line($ours, ctx()) };
  my $err     = $@;
  my $elapsed = time - $t0;

  isa_ok $err, 'API::Docker::Error::Timeout';
  cmp_ok $elapsed, '>=', 0.15,
    'it waited for the timeout rather than returning at once ('
    . sprintf('%.2fs', $elapsed) . ')';
  cmp_ok $elapsed, '<', 5, 'and gave up rather than hanging';

  # Not poisoned: the same handle keeps working afterwards, which is what
  # makes this an idle timeout per read rather than a dead connection.
  syswrite $theirs, "still here\n";
  is $client->_read_line($ours, ctx()), "still here\n",
    'and the handle still reads after an expiry';

t/read_timeout.t  view on Meta::CPAN


  is $client->_apply_read_timeout($fh, undef), undef,
    'with no timeout asked for, nothing is attempted and nothing complains';
  close $fh;
};

# ---------------------------------------------------------------------------
# _request: which value ends up on the socket
# ---------------------------------------------------------------------------
{
  package Test::ReadTimeout::Recorder;
  use Moo;
  extends 'API::Docker';

  # A client whose socket is one end of a socketpair with the whole response
  # already in it, so the real _request runs against a real socket -- and
  # whose peer is held open and never written to again, so anything reading
  # past the response is a genuine wait.
  has canned => (is => 'rw', default => sub { '' });
  has peer   => (is => 'rw');
  has armed  => (is => 'rw', default => sub { [] });

t/read_timeout.t  view on Meta::CPAN


  around _apply_read_timeout => sub {
    my ($orig, $self, $sock, $timeout) = @_;
    push @{ $self->armed }, $timeout;
    return $self->$orig($sock, $timeout);
  };
}

sub recorder {
  my (%args) = @_;
  return Test::ReadTimeout::Recorder->new(
    host        => 'unix:///nonexistent.sock',
    api_version => '1.41',
    canned      => "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n{}",
    %args,
  );
}

subtest '_request: the per-call option and the client attribute' => sub {
  subtest 'neither set -- nothing is armed, which is the old behaviour' => sub {
    my $c = recorder();

t/read_timeout.t  view on Meta::CPAN

  my $c = recorder(
    canned       => "HTTP/1.1 200 OK\r\nContent-Length: 40\r\n\r\nhalf a body!!!",
    read_timeout => 0.2,
  );

  my $t0 = time;
  eval { $c->get('/probe') };
  my $err     = $@;
  my $elapsed = time - $t0;

  isa_ok $err, 'API::Docker::Error::Timeout';
  is attr($err, "partial"), 'half a body!!!',
    'the bytes that did arrive are on the exception rather than returned as '
    . 'though they were the whole body';
  is attr($err, "endpoint"), 'GET /v1.41/probe', 'the endpoint, without a query string';
  is attr($err, "timeout"), 0.2, 'the timeout that expired';
  cmp_ok $elapsed, '<', 5, 'it gave up instead of hanging';
  close $c->peer;
};

subtest '_request: a response that is complete is not affected by a timeout'

t/timeout_forwarding.t  view on Meta::CPAN

# the method, because a caller who set a bound and then hangs in a request
# they never wrote has been told something untrue. They need no forwarding of
# their own here: they run on the same resource class, which is the whole
# point of putting the bounds there.
#
# Nothing here reaches a daemon and nothing here opens a socket: _request is
# replaced outright, which takes API::Docker's version-negotiation `around`
# with it, so the paths arrive unprefixed. The negotiation is asserted
# separately at the bottom, where that `around` has to stay in place.

package Test::TimeoutForward::Probe;
use Moo;
extends 'API::Docker';

has calls => (is => 'ro', default => sub { [] });

sub _request {
  my ($self, $method, $path, %opts) = @_;
  push @{ $self->calls }, { method => $method, path => $path, opts => \%opts };

  # Shaped only so the method under test can finish. What it does with the

t/timeout_forwarding.t  view on Meta::CPAN

  return [] if $path =~ m{/stats$};
  # The inspects, which wrap what comes back in an entity object.
  return {} if $path =~ m{/json$};
  return {} if $path =~ m{^/(?:networks|volumes|secrets|configs)/[^/]+$};
  return '';
}

# Records what _build__socket was handed rather than connecting, the way
# t/connect_timeout.t does -- but reached through a resource method, which is
# what the bound exists for.
package Test::TimeoutForward::ConnectProbe;
use Moo;
extends 'API::Docker';

has seen => (is => 'ro', required => 1);

sub _build__socket {
  my ($self) = @_;
  my $pending = $self->_pending_connect;
  push @{ $self->seen }, $pending ? $pending->{timeout} : 'no pending';
  die "no socket here\n";
}

# _request is left alone here so that API::Docker's `around` still runs and
# still triggers the negotiation; only the negotiation itself is intercepted.
package Test::TimeoutForward::NegotiateProbe;
use Moo;
extends 'API::Docker';

has negotiations => (is => 'ro', default => sub { [] });

sub negotiate_version {
  my ($self, %opts) = @_;
  push @{ $self->negotiations }, \%opts;
  # What the real one does on success, so the request that triggered it can
  # go on and only one negotiation is recorded per client.

t/timeout_forwarding.t  view on Meta::CPAN

);

# The option list the named endpoint was requested with, or a string saying
# why there is none -- which is_deeply then reports instead of an empty hash.
# @using is what the resource class is cloned with; empty means it is used as
# it comes off the client.
sub opts_for {
  my ($case, @using) = @_;
  my (undef, $want, $accessor, $code) = @$case;

  my $probe = Test::TimeoutForward::Probe->new(
    host => 'unix:///nonexistent-api-docker-74.sock', api_version => '1.41');

  my $resource = $probe->$accessor;
  $resource = $resource->using(@using) if @using;

  eval { $code->($resource); 1 }
    or return 'the call died before requesting anything: ' . $@;

  my @seen;
  for my $call (@{ $probe->calls }) {

t/timeout_forwarding.t  view on Meta::CPAN

# ---------------------------------------------------------------------------
# Version negotiation is the pre-flight nobody writes: it happens once, before
# the first request of a client with no api_version, and a bound that does not
# reach it leaves that first request unbounded in the one place the caller
# cannot see (karr k72). Two halves, because the `around` and the method are
# separately capable of dropping it.
subtest 'the negotiation inherits the triggering request bounds' => sub {
  for my $args ([ read_timeout => 3, connect_timeout => 7 ],
                [ read_timeout => 0, connect_timeout => 0 ],
                []) {
    my $probe = Test::TimeoutForward::NegotiateProbe->new(
      host => 'unix:///nonexistent-api-docker-74.sock');

    my $containers = $probe->containers;
    $containers = $containers->using(@$args) if @$args;
    eval { $containers->list };

    is_deeply $probe->negotiations, [ { @$args } ],
      'containers->using(' . join(', ', @$args) . ')->list negotiates with the same';
  }
};

# negotiate_version is the one method that still takes the two options
# directly: it is a client method, not a resource one, so ->using cannot reach
# it and a caller bounding the negotiation on its own has nowhere else to say
# so.
subtest 'negotiate_version puts them on the /version request' => sub {
  for my $args ([ read_timeout => 3, connect_timeout => 7 ],
                [ read_timeout => 0, connect_timeout => 0 ],
                []) {
    my $probe = Test::TimeoutForward::Probe->new(
      host => 'unix:///nonexistent-api-docker-74.sock');

    $probe->negotiate_version(@$args);

    my ($call) = grep { $_->{path} eq '/version' } @{ $probe->calls };
    is_deeply
      $call ? bounds_of($call->{opts}) : 'never requested /version',
      { @$args },
      'negotiate_version(' . join(', ', @$args) . ') forwards what it was given';
  }
};

# ---------------------------------------------------------------------------
# The carrying above is only worth anything if the transport reads the option,
# so the other end of the wire is asserted too -- that a value ->using put on
# a resource class reaches the socket constructor. t/connect_timeout.t proves
# what the socket then does with it.
subtest 'the transport picks the carried value up' => sub {
  my @seen;

  my $probe = Test::TimeoutForward::ConnectProbe->new(
    host        => 'unix:///nonexistent-api-docker-74.sock',
    api_version => '1.41',
    seen        => \@seen,
  );

  eval { $probe->images->using(connect_timeout => 7)->pull(fromImage => 'alpine') };
  eval { $probe->system->using(connect_timeout => 2)->events };
  eval { $probe->containers->using(connect_timeout => 0)->logs('c1') };
  eval { $probe->images->get('alpine') };
  eval { $probe->networks->using(connect_timeout => 4)->list };

t/tls_read.t  view on Meta::CPAN

#!/usr/bin/env perl
use strict;
use warnings;
use Test::More;
use Config;
use Path::Tiny;
use Time::HiRes qw( time sleep );
use API::Docker;
use API::Docker::Error::Timeout;

# karr k65. t/tls.t covers option assembly, certificate selection and the
# handshake; nothing in the suite ever reads a byte over TLS. This file is
# that read path, pinned against the three measurements taken by hand
# during the transport rebuild (karr k60), before and after, identical both
# times:
#
#   three writes 0.15s apart      -> 3 on_chunk calls, spaced apart
#   100000 bytes over many records -> every byte arrives, none lost
#   delivered, then silent, read_timeout 1 -> Error::Timeout after ~1s,
#     phase 'read', summary delivered=1, the bytes already with the callback
#
# It matters here specifically because TLS is the one transport where a
# short read is the normal case -- one plaintext record (<= 16384 bytes,
# RFC 8446 5.1) per sysread -- so the "a short read is not an end of
# stream" rule this role depends on (see _pull in
# API::Docker::Role::HTTP) has no margin to be wrong in. And
# IO::Socket::SSL's own read/sysread split -- ssl_read_all on a blocking
# socket for read(), a single Net::SSLeay::read for sysread() -- is exactly
# the distinction karr k60 is built on: get the wrong one and either every

t/tls_read.t  view on Meta::CPAN

      $docker->get('/probe',
        on_chunk     => sub { push @seen, $_[0] },
        read_timeout => 1,
      );
    };
    $@;
  };
  my $elapsed = time - $t0;
  reap($pid);

  isa_ok $err, 'API::Docker::Error::Timeout';
  is $err && $err->phase, 'read', 'the read bound fired, not the connect one';
  is $err && $err->timeout, 1, 'naming the read_timeout that expired';

  is scalar(@seen), 1, 'the chunk that arrived before the stall reached the '
    . 'callback -- a short TLS read must not be mistaken for the end of the '
    . 'stream and swallowed';
  is $seen[0], "first-chunk\n", 'and it is the one the server actually sent';

  is $err && $err->summary && $err->summary->{delivered}, 1,
    'the exception\'s own summary agrees with what the callback saw';



( run in 2.369 seconds using v1.01-cache-2.11-cpan-234fa220139 )