API-Docker

 view release on metacpan or  search on metacpan

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

package API::Docker::Type;
# ABSTRACT: The DSL and attribute registry behind the generated Docker types
our $VERSION = '0.006';
our %REGISTRY;
use Moo ();
use Moo::Role ();
use Carp qw( croak );
use Import::Into;
use Module::Runtime qw( use_module );
use Package::Stash;
use Scalar::Util qw( blessed );
use Types::Standard qw( Any ArrayRef Bool HashRef InstanceOf Int Maybe Num Str );
use API::Docker::Role::Type ();
use JSON::MaybeXS ();
use namespace::clean;


my %SCALAR_TYPE = (
  Str  => Str,
  Int  => Int,
  Num  => Num,
  Bool => Bool,
);

# Names API::Docker::Role::Type already occupies. A generated attribute that
# collided with one of these would silently replace it, so it is refused
# instead -- the generator has to pick another Perl name and say so with an
# explicit `wire`.
my %RESERVED = map { ($_ => 1) } qw(
  new BUILDARGS unknown_fields rejected_fields from_data from_json TO_JSON to_json
  docker_attributes docker_attribute_order docker docker_extends
);

sub import {
  my ($class) = @_;
  $class->_setup_class(scalar caller);
  return;
}

# Per-class state that has to outlive the class's own compilation, because a
# generated class ends its body with `use namespace::clean`. That pragma takes
# a snapshot of the package's subs when it is reached and strips every one of
# them at the end of the class's compilation -- the imported Moo and type
# sugar, the two DSL keywords, AND anything a role composed at that point had
# already installed. Two consequences shape the setup below.
#
#   has / extends -- The runtime `docker ...;` and `docker_extends ...;` lines
#     fire after that cleanup, so by then `has` and `extends` are gone from the
#     class and `$target->can('has')` returns undef. The `docker` keyword and
#     the `Str`/`Int`/... it is handed survive the same cleanup only because
#     Perl bound their CV into the call site at compile time; a name the DSL
#     looks up by string at runtime has no such binding, so the two it resolves
#     that way are captured here while they are still imported.
#
#   the role -- API::Docker::Role::Type is NOT composed here. Composed at
#     import (a BEGIN action) its methods and its two attributes would sit in
#     namespace::clean's snapshot and be stripped with the sugar. So it is
#     composed on the first `docker`/`docker_extends` call instead -- at
#     runtime, after the cleanup, exactly as a `with 'Role'` line in a Moo
#     class body would run. Every generated class issues at least one such
#     call, and the composition lands before any object of the class is built.
my %CLASS_SUGAR;

sub _setup_class {
  my ($class, $target) = @_;
  Moo->import::into($target);
  Types::Standard->import::into($target, qw( Any Bool Int Num Str ));
  $CLASS_SUGAR{$target} = {
    has     => $target->can('has'),
    extends => $target->can('extends'),
  };
  my $stash = Package::Stash->new($target);
  $stash->add_symbol('&docker'         => sub { $class->_docker($target, @_) });
  $stash->add_symbol('&docker_extends' => sub { $class->_docker_extends($target, @_) });
  return;
}

# Compose API::Docker::Role::Type once, on the first DSL call the class makes.
# Runtime, so it outlasts the class's `use namespace::clean`; idempotent, so
# the second and later DSL calls are a cheap flag check.
sub _ensure_role {
  my ($target) = @_;
  return if $CLASS_SUGAR{$target}{role_composed};
  $CLASS_SUGAR{$target}{role_composed} = 1;
  Moo::Role->apply_roles_to_package($target, 'API::Docker::Role::Type');
  return;
}

# The one place a short class name becomes a full one. 'Mount' is
# API::Docker::Type::Mount; a name that already starts with the prefix is
# left alone; a leading + means "this is the full name, take it as it is".
# Docker's definitions are flat -- there are no groups to map, which is why
# there is no prefix table here and only this one rule.
sub _expand_class {
  my ($short) = @_;
  return substr($short, 1) if $short =~ /\A\+/;
  return $short if $short =~ /\AAPI::Docker::Type::/;
  return 'API::Docker::Type::' . $short;
}

# PortBindings <- port_bindings. One direction only; see the POD above.
sub _wire_from_perl {
  my ($name) = @_;
  return join '', map { ucfirst } split /_/, $name;
}

sub _is_type_tiny { return blessed($_[0]) && $_[0]->isa('Type::Tiny') }

# A type spec becomes a descriptor, recursively:
#   { kind => 'scalar', scalar => 'Str' }
#   { kind => 'object', class  => 'API::Docker::Type::PortBinding' }
#   { kind => 'array',  inner  => <descriptor> }
#   { kind => 'hash',   inner  => <descriptor> }   keys are caller data
#   { kind => 'any' }
# One recursive shape rather than a flag per combination, so { Str,
# ['PortBinding'] } and [[Str]] need no cases of their own anywhere.
sub _parse_type {
  my ($spec, $where) = @_;
  if (_is_type_tiny($spec)) {
    my $name = $spec->name;
    return { kind => 'any' } if $name eq 'Any';
    return { kind => 'scalar', scalar => $name } if $SCALAR_TYPE{$name};
    croak __PACKAGE__ . ": $where has unsupported type " . $name;
  }

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

C<< wire => '...' >> and the Perl name is chosen by hand.

A wire name belongs to one field. C<docker> refuses a declaration asking for
a name an earlier field in the same class already has, the way it refuses a
duplicate Perl name: both halves of the pair have to be unique, or inflation
would reach one of the two fields and C<TO_JSON> would write both to that one
key.

=head2 What C<since> can and cannot say

C<spec/> holds v1.41, v1.44, v1.51 and v1.55. The C<--from>/C<--to> mode of
C<maint/spec-drift-check.pl> diffs the first three to produce these values --
the swagger itself carries no per-field version at all. So C<< since =>
'1.51' >> means "not in v1.44, present in v1.51", not "introduced in v1.51":
the field appeared somewhere in v1.45 .. v1.51.

The fields grafted from v1.55 onto the v1.51 base, listed in
C<maint/spec-overlay.yaml>, carry C<< since => '1.55' >> from the overlay
itself. That means "not in v1.51, present in v1.55": the field appeared
somewhere in v1.52 .. v1.55. An attribute with no C<since> is already in
v1.41, the oldest spec checked in here.

=head2 C<since> is documentation

C<since> records which API version introduced a field. Nothing is checked,
warned about or dropped at runtime, ever. Podman serves fields its announced
version does not promise and refuses ones it does; we are not the authority
on what an engine can do. The value is visible in the C<since> key of each
field's declaration in its class's source, and in the registry.

C<required> is recorded from the swagger's C<required:> list and is likewise
not enforced: the same engines omit fields the specification calls required,
and croaking on a response we could otherwise use is not an improvement.

=head2 Keys that are the caller's data

The hash form marks a field whose I<keys> the user chose:

    docker labels        => { Str, Str };
    docker port_bindings => { Str, [ 'PortBinding' ] };

Those keys are passed through byte for byte in both directions. C<Labels>,
C<Annotations>, C<ExposedPorts>, C<PortBindings>, C<Volumes>, C<StorageOpt>,
C<Tmpfs>, C<Sysctls>, C<DriverOpts> and C<Options> are all of this shape --
in the swagger they are the fields carrying C<additionalProperties>, which
is the marker to check before deciding a hash's keys are structure. Turning
a label C<com.example.Some-Label> into something the caller never wrote is
the single most damaging mistake this model could make.

=head2 Unknown fields survive

Anything arriving under a name the registry does not know is kept verbatim
in L<API::Docker::Role::Type/unknown_fields> and written back out unchanged.
A caller whose engine is newer than the swagger we generated from still
reaches the daemon, and so does a field an engine sends that the swagger
does not describe. Which names count as known depends on the entry point --
C<from_data> reads an engine response and takes wire names only, C<new>
builds a request and takes either spelling; see that role for the reasoning.

A null is where the two name spaces part. A field the registry knows that
arrives as C<null> is read as unset and its key does not come back, because
the daemon cannot tell an explicit null from an absent field in either
direction; a field the registry does not know keeps its null, because
without a declared type there is no zero value to read it as. The
measurement and the three shapes it produces are in
L<API::Docker::Role::Type/"A null on a known field is read as unset">.

=head2 C<allOf> becomes inheritance

Two definitions in v1.51 are composed with C<allOf>, and both have the same
shape -- one C<$ref> plus one inline schema:

    HostConfig: allOf [ $ref Resources, { 39 properties } ]
    Swarm:      allOf [ $ref ClusterInfo, { 1 property } ]

The C<$ref> becomes a superclass and only the inline schema's properties are
declared in the child:

    package API::Docker::Type::HostConfig;
    use API::Docker::Type;

    docker_extends 'Resources';

C<allOf> in swagger means composition, and Perl inheritance says exactly
that. Nothing is duplicated: the parent's fields, their POD and the inline
classes declared inside the parent all stay in one place, and the merged
registry in L<API::Docker::Role::Type> presents C<HostConfig> with all ~70
fields. The alternative -- copying the parent's declarations into the child
-- would duplicate 31 attributes and their C<=attr> blocks and force the
inline classes underneath them to be named twice.

An C<allOf> holding a single C<$ref> and nothing else is not composition at
all; it is swagger's way of hanging a description on a C<$ref>
(C<Mount.Type> and C<MountPoint.Type> both do it). Such a field takes the
type of what it references, which for C<MountType> is C<Str>.

=head2 Inline objects become classes

A property whose schema is an object with its own C<properties>, or an array
whose C<items> are such an object, becomes a class named after the
definition that declares it:

    Mount.BindOptions             -> API::Docker::Type::Mount::BindOptions
    Mount.VolumeOptions.DriverConfig
                                  -> API::Docker::Type::Mount::VolumeOptions::DriverConfig
    Resources.Ulimits[]           -> API::Docker::Type::Resources::Ulimit

The last one is the exception to the mechanical rule: an array of inline
objects is named for one element, and turning C<Ulimits> into C<Ulimit> is a
judgement call, not a derivation. Those names live in
C<maint/spec-drift-exceptions.yaml> so the checker and a generator agree on
them.

=head2 A generated class loads what it references

Each class carries a plain C<use> for every other type class it names, so
loading C<API::Docker::Type::HostConfig> brings its whole subtree with it.
The declaration itself does B<not> load anything: a class named in a
C<docker> line is loaded lazily, on the first hashref that has to be
inflated into it. That is deliberate belt and braces -- v1.51's definitions
happen to have no reference cycles, and if a later version grows one the
C<use> for the back edge is what a generator has to leave out, while the
model keeps working either way.

=head1 THE TYPE VOCABULARY



( run in 0.371 second using v1.01-cache-2.11-cpan-234fa220139 )