How to use the pyrsistent.pmap_field function in pyrsistent

To help you get started, we’ve selected a few pyrsistent examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ClusterHQ / flocker / flocker / testtools / matchers.py View on Github external
class _Mismatch(PClass):
    """
    Immutable Mismatch that also stores the mismatched object.

    :ivar mismatched: The object that failed to match.
    """

    # XXX: No direct tests.

    # XXX: jml thinks the base testtools mismatch should be extended to
    # include the mismatched object.

    mismatched = field(object)
    _description = field((str, unicode))
    _details = pmap_field((str, unicode), Content)

    def describe(self):
        return self._description

    def get_details(self):
        return self._details


def mismatch(mismatched, description, details):
    """
    Create an immutable Mismatch that also stores the mismatched object.
    """
    return _Mismatch(
        mismatched=mismatched, _description=description, _details=details)
github ClusterHQ / flocker / flocker / apiclient / _client.py View on Github external
class Dataset(PClass):
    """
    A dataset in the configuration.

    :attr UUID primary: The node where the dataset should manifest.
    :attr int|None maximum_size: Size of the dataset in bytes or ``None``
        if no particular size was requested.
    :attr UUID dataset_id: The UUID of the dataset.
    :attr metadata: A mapping between unicode keys and values.
    """
    dataset_id = field(type=UUID, mandatory=True)
    primary = field(type=UUID, mandatory=True)
    maximum_size = field(type=(int, NoneType), mandatory=True)
    metadata = pmap_field(unicode, unicode)


class DatasetState(PClass):
    """
    The state of a dataset in the cluster.

    :attr primary: The ``UUID`` of the node where the dataset is manifest,
        or ``None`` if it has no primary manifestation.
    :attr int|None maximum_size: Maximum size of the dataset in bytes, or
        ``None`` if the maximum size is not set.
    :attr UUID dataset_id: The UUID of the dataset.
    :attr FilePath|None path: Filesytem path where the dataset is mounted,
        or ``None`` if not mounted.
    """
    dataset_id = field(type=UUID, mandatory=True)
    primary = field(type=(UUID, NoneType), mandatory=True)
github itamarst / eliot / eliot / parse.py View on Github external
from ._message import WrittenMessage, TASK_UUID_FIELD
from ._action import (
    TaskLevel,
    WrittenAction,
    ACTION_STATUS_FIELD,
    STARTED_STATUS,
    ACTION_TYPE_FIELD,
)


class Task(PClass):
    """
    A tree of actions with the same task UUID.
    """

    _nodes = pmap_field(TaskLevel, (WrittenAction, WrittenMessage))
    _completed = pset_field(TaskLevel)
    _root_level = TaskLevel(level=[])

    def root(self):
        """
        @return: The root L{WrittenAction}.
        """
        return self._nodes[self._root_level]

    def is_complete(self):
        """
        @return bool: True only if all messages in the task tree have been
        added to it.
        """
        return self._root_level in self._completed
github itamarst / eliot / eliot / _action.py View on Github external
@ivar TaskLevel task_level: The action's task level, e.g. if start
        message has level C{[2, 3, 1]} it will be
        C{TaskLevel(level=[2, 3])}.
    @ivar UUID task_uuid: The UUID of the task to which this action belongs.
    @ivar _children: A L{pmap} from L{TaskLevel} to the L{WrittenAction} and
        L{WrittenMessage} objects that make up this action.
    """

    start_message = field(type=optional(WrittenMessage), mandatory=True,
                          initial=None)
    end_message = field(type=optional(WrittenMessage), mandatory=True,
                        initial=None)
    task_level = field(type=TaskLevel, mandatory=True)
    task_uuid = field(type=unicode, mandatory=True, factory=unicode)
    # Pyrsistent doesn't support pmap_field with recursive types.
    _children = pmap_field(TaskLevel, object)

    @classmethod
    def from_messages(cls, start_message=None, children=pvector(),
                      end_message=None):
        """
        Create a C{WrittenAction} from C{WrittenMessage}s and other
        C{WrittenAction}s.

        @param WrittenMessage start_message: A message that has
            C{ACTION_STATUS_FIELD}, C{ACTION_TYPE_FIELD}, and a C{task_level}
            that ends in C{1}, or C{None} if unavailable.
        @param children: An iterable of C{WrittenMessage} and C{WrittenAction}
        @param WrittenMessage end_message: A message that has the same
            C{action_type} as this action.

        @raise WrongTask: If C{end_message} has a C{task_uuid} that differs
github ClusterHQ / flocker / flocker / node / agents / remotefs.py View on Github external
DatasetStates.MOUNTED: {'mount_point'},
        },
    )


class DesiredDataset(PClass):
    """
    Dataset as requested by configuration and applications.
    """
    state = field(
        invariant=lambda state: (state in DatasetStates.iterconstants(),
                                 "Not a valid state"),
        mandatory=True,
    )
    dataset_id = field(type=UUID, mandatory=True)
    metadata = pmap_field(
        key_type=unicode,
        value_type=unicode,
    )
    mount_point = field(FilePath)

    __invariant__ = TaggedUnionInvariant(
        tag_attribute='state',
        attributes_for_tag={
            DatasetStates.NOT_MOUNTED: {"metadata"},
            DatasetStates.MOUNTED: {"mount_point", "metadata"},
            DatasetStates.DELETED: set(),
        },
    )


API_CHANGE = ActionType(u"remotefs:deployer:action", [], [])
github itamarst / eliot / eliot / parse.py View on Github external
written_message,
                    ["_completed"],
                    lambda s: s.add(self._root_level),
                )
            else:
                return self._ensure_node_parents(written_message)


class Parser(PClass):
    """
    Parse serialized Eliot messages into L{Task} instances.

    @ivar _tasks: Map from UUID to corresponding L{Task}.
    """

    _tasks = pmap_field(unicode, Task)

    def add(self, message_dict):
        """
        Update the L{Parser} with a dictionary containing a serialized Eliot
        message.

        @param message_dict: Dictionary of serialized Eliot message.

        @return: Tuple of (list of completed L{Task} instances, updated
            L{Parser}).
        """
        uuid = message_dict[TASK_UUID_FIELD]
        if uuid in self._tasks:
            task = self._tasks[uuid]
        else:
            task = Task()
github ClusterHQ / flocker / flocker / node / agents / remotefs.py View on Github external
Discovered.NOT_MOUNTED: Destroy,
        Discovered.MOUNTED: Unmount,
    },
})
del Desired, Discovered

# Nothing particularly BlockDevice-specific about the class:
CALCULATOR = BlockDeviceCalculator(
    transitions=DATASET_TRANSITIONS, dataset_states=DatasetStates)


@implementer(ILocalState)
class LocalState(PClass):
    hostname = field(type=unicode, mandatory=True)
    node_uuid = field(type=UUID, mandatory=True)
    datasets = pmap_field(UUID, DiscoveredDataset)

    def shared_state_changes(self):
        """
        Returns the NodeState and the NonManifestDatasets of the local state.
        These are the only parts of the state that need to be sent to the
        control service.
        """
        # XXX The structure of the shared state changes reflects the model
        # currently used by the control service. However, that model doesn't
        # seem to actually match what any consumer wants.
        manifestations = {}
        paths = {}
        nonmanifest_datasets = {}

        for dataset in self.datasets.values():
            dataset_id = dataset.dataset_id
github LeastAuthority / txkube / src / txkube / _authentication.py View on Github external
@implementer(IPolicyForHTTPS)
class ClientCertificatePolicyForHTTPS(PClass):
    """
    ``ClientCertificatePolicyForHTTPS`` selects the correct client certificate
    and trust roots to use for interacting with the Kubernetes API server.

    :ivar credentials: All available client certificates.
    :ivar trust_roots: All available certificate authority certificates.
    """
    credentials = pmap_field(
        NetLocation, TLSCredentials,
    )

    trust_roots = pmap_field(
        NetLocation, pem.Certificate,
    )

    def creatorForNetloc(self, hostname, port):
        """
        Pick from amongst client certs and ca certs to create a proper TLS context
        factory.

        :see: ``twisted.web.iweb.IPolicyForHTTPS``
        """
        hostname = hostname.decode("ascii")

        netloc = NetLocation(host=hostname, port=port)
        client_cert, extra_cert_chain = pick_cert_for_twisted(
            netloc, self.credentials,
        )
github itamarst / eliot / eliot / _message.py View on Github external
stack.
        """
        if logger is None:
            logger = _output._DEFAULT_LOGGER
        logged_dict = self._freeze(action=action)
        logger.write(dict(logged_dict), self._serializer)



class WrittenMessage(PClass):
    """
    A L{Message} that has been logged.

    @ivar _logged_dict: The originally logged dictionary.
    """
    _logged_dict = pmap_field((str, unicode), object)

    @property
    def timestamp(self):
        """
        The Unix timestamp of when the message was logged.
        """
        return self._logged_dict[TIMESTAMP_FIELD]


    @property
    def task_uuid(self):
        """
        The UUID of the task in which the message was logged.
        """
        return self._logged_dict[TASK_UUID_FIELD]
github LeastAuthority / txkube / src / txkube / _swagger.py View on Github external
def pclass_field_for_type(self, required, default):
        # XXX default unimplemented
        # XXX ignores the range's pyrsistent_invariant
        return pmap_field(
            key_type=unicode,
            value_type=self.value_type.python_types,
            optional=not required,
        )