pyrpc / pyrpc / message.py

# -*- coding: utf-8 -*-

import zlib
import struct
import cPickle
import time
import random

random.seed(time.time())

class MessageException(Exception): pass
class MessageIncomplete(MessageException): pass
class MessageInvalid(MessageException): pass
class Message(object):
    MAGIC = 0x0815
    HEADER = "!HL"
    HEADER_SIZE = struct.calcsize(HEADER)
    
    def __init__(self, data, job_ident=None):
        self.data = data
    
    def __repr__(self):
        return '<Message data=%s>' % \
            (self.data, )

    def serialize(self):
        data = zlib.compress(cPickle.dumps(self.data))
        header = struct.pack(self.HEADER,
                             self.MAGIC,
                             len(data))
        return "".join([header, data])
    
    @staticmethod
    def parse(buf):
        if len(buf) < Message.HEADER_SIZE:
            raise MessageIncomplete(u'Header not present.')
        
        try:
            magic, datalen = struct.unpack(Message.HEADER, buf[:Message.HEADER_SIZE])
        except struct.error:
            raise MessageInvalid(u'Struct unpack failed.')
        
        buf = buf[Message.HEADER_SIZE:]
        
        if magic != Message.MAGIC:
            raise MessageInvalid(u'Invalid magic.')
        
        if len(buf) < datalen:
            raise MessageIncomplete(u'Data not complete.')
        
        try:
            data = cPickle.loads(zlib.decompress(buf[:datalen]))
        except ValueError:
            raise MessageInvalid(u'Deserialization failed.')
        except zlib.error:
            raise MessageInvalid(u'Decompress failed.')
    
        # What remains from the buffer?
        buf = buf[datalen:]
        
        return data, buf
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.