Exemple #1
0
        /// <summary>
        /// Sends a message synchronously, regardless of its type
        /// </summary>
        /// <param name="message"></param>
        /// <remarks>
        /// added cbrown
        /// due to the extensive use of the sockettransport, and the desire not
        /// to break existing code, this interface is being used to extend the
        /// transport protocol.
        /// usage:
        ///		IRelayTransportExtended xTend = Transport as IRelayTransportExtended;
        ///		if (null == xTend)
        ///		{
        ///			use "tradidional" handling
        ///		}
        ///		else
        ///		{
        ///			use extended handling
        ///		}
        /// </remarks>
        public void SendSyncMessage(RelayMessage message)
        {
            MemoryStream replyStream;
            ResourcePoolItem <MemoryStream> bufferItem = null;

            try
            {
                bufferItem = bufferPool.GetItem();
                // there is not need to check the type, we are FORCING sync handling
                RelayMessageFormatter.WriteRelayMessage(message, bufferItem.Item);
                bufferItem.Item.Seek(0, SeekOrigin.Begin);
                replyStream = _socketClient.SendSync((int)SocketCommand.HandleSyncMessage, bufferItem.Item);
            }
            finally
            {
                if (bufferItem != null)
                {
                    bufferPool.ReleaseItem(bufferItem);
                }
            }
            if (replyStream != null)
            {
                RelayMessage replyMessage = RelayMessageFormatter.ReadRelayMessage(replyStream);
                message.ExtractResponse(replyMessage);
            }
            //this doesn't make any sense, the incoming message already
            //has error occured with no respones? fwise 5/09
            else if (message.ErrorOccurred)
            {
                message.Payload = null;
            }
        }
Exemple #2
0
 private ObjectListForSingles(SerializingObjectStorage storage, DataBuffer keySpace,
                              StorageKey key, Func <T> creator)
 {
     Storage   = storage;
     Key       = key;
     _keySpace = keySpace;
     Creator   = creator;
     _pooled   = storage.StreamPool.GetItem();
 }
Exemple #3
0
        /// <summary>
        ///     <para>Initializes a new instance of the <see cref="ObjectListForSingles{T, THeader}"/> class
        ///		for an existing list.</para>
        /// </summary>
        /// <param name="storage">
        ///     <para>The <see cref="SerializingObjectStorage"/> containing the list.</para>
        /// </param>
        /// <param name="keySpace">
        ///     <para>The <see cref="DataBuffer"/> keyspace the list is stored in.</para>
        /// </param>
        /// <param name="key">
        ///     <para>The single <see cref="StorageKey"/> all the binary entries are
        /// stored under.</para>
        /// </param>
        /// <param name="buffer">
        ///		<para><see cref="DataBuffer"/> that holds the entire list. If
        ///		<see cref="DataBuffer.IsEmpty"/> is true, then the list is read
        ///		from <paramref name="storage"/>.</para>
        /// </param>
        /// <param name="creator">
        ///     <para>The <see cref="Func{T}"/> that produces new <typeparamref name="T"/>
        ///		instances for deserialization.</para>
        /// </param>
        /// <param name="headerCreator">
        ///     <para>The <see cref="Func{THeader}"/> that produces new <typeparamref name="THeader"/>
        ///		instances for deserialization.</para>
        /// </param>
        public ObjectListForSingles(SerializingObjectStorage storage, DataBuffer keySpace,
                                    StorageKey key, DataBuffer buffer, Func <T> creator, Func <THeader> headerCreator)
            : this(storage, keySpace, key, creator)
        {
            ArraySegment <byte> seg;

            if (buffer.IsEmpty)
            {
                _stream = _pooled.Item;
                buffer  = SerializingObjectStorage.GetReadBuffer(_stream);
                var entryLen = storage.Storage.Get(keySpace, key, buffer);
                if (entryLen < 0)
                {
                    throw new ApplicationException(string.Format(
                                                       "No list found for key space '{0}', key '{1}'",
                                                       keySpace, key));
                }
                var bfExcess = SerializingObjectStorage.GetExcessBuffer(_stream, buffer,
                                                                        entryLen);
                if (bfExcess.IsEmpty)
                {
                    buffer = buffer.Restrict(entryLen);
                }
                else
                {
                    if (storage.Storage.SupportsIncompleteReads)
                    {
                        storage.Storage.Get(keySpace, key, buffer.Length,
                                            bfExcess.RestrictOffset(buffer.Length));
                    }
                    else
                    {
                        storage.Storage.Get(keySpace, key, 0, bfExcess);
                    }
                    buffer = bfExcess;
                }
                seg = buffer.ByteArraySegmentValue;
            }
            else
            {
                _pooled.Dispose();
                _pooled = null;
                seg     = buffer.ByteArraySegmentValue;
                _stream = new MemoryStream(seg.Array, seg.Offset, seg.Count);
            }
            var ticks = BitConverter.ToInt64(seg.Array, seg.Offset);

            // expires listed first, since SetExpires can change it by itself
            // and this way it doesn't have to worry about future changes
            // to header
            Expires          = new DateTime(ticks);
            _stream.Position = sizeof(long);
            _header          = headerCreator();
            Serializer.Deserialize(_stream, _header);
            _headerLength = _stream.Position;
        }
 internal void SetValues(int timeout, EventWaitHandle waitHandle, ResourcePoolItem <short> idItem)
 {
     if (Log.IsDebugEnabled)
     {
         Log.DebugFormat("SetValues() Sets WaitHandle");
     }
     this.timeOut    = timeout;
     this.waitHandle = waitHandle;
     this.idItem     = idItem;
 }
Exemple #5
0
 /// <summary>
 ///     <para>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</para>
 /// </summary>
 public void Dispose()
 {
     if (_pooled != null)
     {
         _pooled.Dispose();
         _pooled = null;
     }
     _stream = null;
     Storage = null;
 }
Exemple #6
0
        internal ResourcePoolItem <MemoryStream> ReplyBuffer; //for the reply + header

        internal ProcessState(Socket socket, short commandId, short messageId, ReplyType replyType, ResourcePoolItem <MemoryStream> message, int messageLength)
        {
            Socket         = socket;
            CommandId      = commandId;
            MessageId      = messageId;
            ReplyType      = replyType;
            Message        = message;
            MessageLength  = messageLength;
            RemoteEndpoint = (IPEndPoint)socket.RemoteEndPoint;
        }
        internal ResourcePoolItem <MemoryStream> replyBuffer; //for the reply + header

        internal ProcessState(Socket socket, short commandId, short messageId, bool sendReply, ResourcePoolItem <MemoryStream> message, int messageLength)
        {
            this.socket         = socket;
            this.commandId      = commandId;
            this.messageId      = messageId;
            this.sendReply      = sendReply;
            this.message        = message;
            this.messageLength  = messageLength;
            this.remoteEndpoint = (IPEndPoint)socket.RemoteEndPoint;
        }
		internal ResourcePoolItem<MemoryStream> replyBuffer; //for the reply + header

		internal ProcessState(Socket socket, short commandId, short messageId, bool sendReply, ResourcePoolItem<MemoryStream> message, int messageLength)
		{
			this.socket = socket;
			this.commandId = commandId;
			this.messageId = messageId;
			this.sendReply = sendReply;
			this.message = message;
			this.messageLength = messageLength;
			this.remoteEndpoint = (IPEndPoint)socket.RemoteEndPoint;
		}
Exemple #9
0
 public void PlayAt(AudioClip clip, Vector3 position, float volume = 1f, bool isSpatial = true)
 {
     Source.spatialize = isSpatial;
     if (_resourcePoolItem == null)
         _resourcePoolItem = GetComponent<ResourcePoolItem>();
     _resourcePoolItem.IsAvailable = false;
     Source.clip = clip;
     Source.volume = volume;
     transform.position = position;
     Source.Play();
     StartCoroutine(StopSound(clip.length + 0.1f));
 }
Exemple #10
0
        private MemoryStream SendSync(SocketPool pool, int commandID, MemoryStream messageStream)
        {
            short messageId = (short)1;             //new async scheme doesn't currently need these.
            ResourcePoolItem <MemoryStream> rebufferedStreamItem = CreateSyncMessage((short)commandID, messageId, messageStream, pool);
            MemoryStream rebufferedStream = rebufferedStreamItem.Item;

            ManagedSocket socket      = null;
            MemoryStream  replyStream = null;

            try
            {
                socket = pool.GetSocket();

                // GetBuffer() should be used in preference to ToArray() where possible
                // as it does not allocate a new byte[] like ToArray does().
                socket.Send(rebufferedStream.GetBuffer(), (int)rebufferedStream.Length, SocketFlags.None);
                replyStream = socket.GetReply();
            }
            catch (ThreadAbortException)
            {
                if (socket != null)
                {
                    socket.LastError = SocketError.TimedOut;
                }
                log.Warn("Thread aborted on SocketClient.");
                throw;
            }
            catch (SocketException ex)
            {
                if (socket != null)
                {
                    socket.LastError = ex.SocketErrorCode;
                }
                throw;
            }
            finally
            {
                rebufferedStreamItem.Release();
                if (socket != null)                 //getting the socket can throw a timedout exception due to limiting, in which case the socket will be null
                {
                    socket.Release();
                }
            }

            return(replyStream);
        }
 internal ReplyBucket(int timeout, EventWaitHandle waitHandle, ResourcePoolItem <short> idItem)
 {
     SetValues(timeout, waitHandle, idItem);
 }
Exemple #12
0
    private float _stopDistanceSquared = 100000000f; // 10,000

    #endregion Fields

    #region Methods

    public override void Initialize(GameObject owner, float damage)
    {
        if (_resourcePoolItem == null)
            _resourcePoolItem = GetComponent<ResourcePoolItem>();
        base.Initialize(owner, damage);
    }
Exemple #13
0
 private void Start()
 {
     if (_resourcePoolItem == null)
         _resourcePoolItem = GetComponent<ResourcePoolItem>();
     _resourcePoolItem.IsAvailable = true;
 }
Exemple #14
0
        private ResourcePoolItem <MemoryStream> CreateMessage(short commandId, short messageId, MemoryStream messageStream, bool isSync, SocketPool pool)
        {
            int messageLength = 0;

            if (messageStream != null)
            {
                messageLength = (int)messageStream.Length;
            }
            else
            {
                messageLength = 0;
            }

            bool useNetworkOrder = pool.Settings.UseNetworkOrder;

            byte[] length = BitConverter.GetBytes(GetNetworkOrdered(messageLength + envelopeSize, useNetworkOrder));
            byte[] commandIdBytes;
            byte[] messageIdBytes = null;
            //byte[] code = BitConverter.GetBytes(GetNetworkOrdered(commandId, useNetworkOrder));
            if (messageId != 0)
            {
                commandIdBytes = BitConverter.GetBytes(GetNetworkOrdered(commandId, useNetworkOrder));
                messageIdBytes = BitConverter.GetBytes(GetNetworkOrdered(messageId, useNetworkOrder));
            }
            else
            {
                commandIdBytes = BitConverter.GetBytes(GetNetworkOrdered((int)commandId, useNetworkOrder));
            }

            //MemoryStream rebufferedStream = new MemoryStream(envelopeSize + messageLength);

            ResourcePoolItem <MemoryStream> rebufferedStreamItem = pool.GetPooledStream();

            MemoryStream rebufferedStream = rebufferedStreamItem.Item;

            rebufferedStream.Write(GetMessageStarter(useNetworkOrder), 0, 2);
            rebufferedStream.Write(length, 0, 4);
            //rebufferedStream.Write(code, 0, 4);
            if (messageId != 0)
            {
                if (useNetworkOrder)
                {
                    rebufferedStream.Write(messageIdBytes, 0, 2);
                    rebufferedStream.Write(commandIdBytes, 0, 2);
                }
                else
                {
                    rebufferedStream.Write(commandIdBytes, 0, 2);
                    rebufferedStream.Write(messageIdBytes, 0, 2);
                }
            }
            else             //backwards compatible, just send the command as an int
            {
                rebufferedStream.Write(commandIdBytes, 0, 4);
            }

            if (isSync)
            {
                rebufferedStream.Write(doSendReply, 0, doSendReply.Length);
            }
            else
            {
                rebufferedStream.Write(dontSendReply, 0, dontSendReply.Length);
            }

            if (messageStream != null)
            {
                messageStream.WriteTo(rebufferedStream);
            }
            rebufferedStream.Write(GetMessageTerminator(useNetworkOrder), 0, 2);

            return(rebufferedStreamItem);
        }
Exemple #15
0
        /// <summary>
        /// Gets the CacheIndexInternal.
        /// </summary>
        /// <param name="storeContext">The store context.</param>
        /// <param name="typeId">The type id.</param>
        /// <param name="primaryId">The primary id.</param>
        /// <param name="indexId">The index id.</param>
        /// <param name="extendedIdSuffix">The extended id suffix.</param>
        /// <param name="indexName">Name of the index.</param>
        /// <param name="maxItemsPerIndex">The maxItemsPerIndex.</param>
        /// <param name="filter">The filter.</param>
        /// <param name="inclusiveFilter">if set to <c>true</c> includes the items that pass the filter; otherwise , <c>false</c>.</param>
        /// <param name="indexCondition">The index condition.</param>
        /// <param name="deserializeHeaderOnly">if set to <c>true</c> if just CacheIndexInternal header is to be deserialized; otherwise, <c>false</c>.</param>
        /// <param name="getFilteredItems">if set to <c>true</c> get filtered items; otherwise, <c>false</c>.</param>
        /// <param name="primarySortInfo">The primary sort info.</param>
        /// <param name="localIdentityTagNames">The local identity tag names.</param>
        /// <param name="stringHashCodeDictionary">The string hash code dictionary.</param>
        /// <param name="capCondition">The cap condition.</param>
        /// <param name="isMetadataPropertyCollection">if set to <c>true</c> metadata represents a property collection; otherwise , <c>false</c>.</param>
        /// <param name="metadataPropertyCollection">The MetadataPropertyCollection.</param>
        /// <param name="domainSpecificProcessingType">The DomainSpecificProcessingType.</param>
        /// <param name="domainSpecificConfig">The DomainSpecificConfig.</param>
        /// <param name="getDistinctValuesFieldName">The distinct value field name.</param>
        /// <param name="groupBy">The GroupBy clause.</param>
        /// <param name="forceFullGet">indicate whether or not use full get.</param>
        /// <returns>CacheIndexInternal</returns>
        internal static CacheIndexInternal GetCacheIndexInternal(IndexStoreContext storeContext,
                                                                 short typeId,
                                                                 int primaryId,
                                                                 byte[] indexId,
                                                                 short extendedIdSuffix,
                                                                 string indexName,
                                                                 int maxItemsPerIndex,
                                                                 Filter filter,
                                                                 bool inclusiveFilter,
                                                                 IndexCondition indexCondition,
                                                                 bool deserializeHeaderOnly,
                                                                 bool getFilteredItems,
                                                                 PrimarySortInfo primarySortInfo,
                                                                 List <string> localIdentityTagNames,
                                                                 Dictionary <int, bool> stringHashCodeDictionary,
                                                                 CapCondition capCondition,
                                                                 bool isMetadataPropertyCollection,
                                                                 MetadataPropertyCollection metadataPropertyCollection,
                                                                 DomainSpecificProcessingType domainSpecificProcessingType,
                                                                 DomainSpecificConfig domainSpecificConfig,
                                                                 string getDistinctValuesFieldName,
                                                                 GroupBy groupBy,
                                                                 bool forceFullGet)
        {
            CacheIndexInternal cacheIndexInternal = null;

            byte[] extendedId = FormExtendedId(indexId, extendedIdSuffix);
            //RelayMessage getMsg = new RelayMessage(typeId, primaryId, extendedId, MessageType.Get);
            //storeContext.IndexStorageComponent.HandleMessage(getMsg);

            Stream myStream;

            ResourcePoolItem <MemoryStream> pooledStreamItem = null;
            MemoryStream pooledStream;

            try
            {
                int indexLevelGetSize =
                    storeContext.StorageConfiguration.CacheIndexV3StorageConfig.IndexTypeMappingCollection[typeId].
                    IndexCollection[indexName].PartialGetSizeInBytes;

                bool isFullGet = forceFullGet ? true : (indexLevelGetSize <= 0 && storeContext.PartialGetLength <= 0);

                if (isFullGet)
                {
                    byte[] cacheBytes = BinaryStorageAdapter.Get(
                        storeContext.IndexStorageComponent,
                        typeId,
                        primaryId,
                        extendedId);

                    if (cacheBytes != null)
                    {
                        myStream = new MemoryStream(cacheBytes);
                    }
                    else
                    {
                        return(null);
                    }
                }
                else
                {
                    int partialGetSize = indexLevelGetSize == 0 ? storeContext.PartialGetLength : indexLevelGetSize;

                    // get a memory stream from the memory pool
                    pooledStreamItem = storeContext.MemoryPool.GetItem();
                    pooledStream     = pooledStreamItem.Item;

                    myStream = new SmartStream(
                        storeContext.IndexStorageComponent,
                        typeId,
                        primaryId,
                        extendedId,
                        partialGetSize,
                        pooledStream);

                    BerkeleyBinaryStorePerformanceCounters.Instance.IncrementCounter(
                        BerkeleyBinaryStorePerformanceCounterEnum.PartialGetPerSec,
                        1);
                }

                if (myStream.Length > 0) //CacheIndex exists, this check is just for SmartStream
                {
                    cacheIndexInternal = new CacheIndexInternal
                    {
                        InDeserializationContext =
                            new InDeserializationContext(maxItemsPerIndex,
                                                         indexName,
                                                         indexId,
                                                         typeId,
                                                         filter,
                                                         inclusiveFilter,
                                                         storeContext.TagHashCollection,
                                                         deserializeHeaderOnly,
                                                         getFilteredItems,
                                                         primarySortInfo,
                                                         localIdentityTagNames,
                                                         storeContext.StringHashCollection,
                                                         stringHashCodeDictionary,
                                                         indexCondition,
                                                         capCondition,
                                                         isMetadataPropertyCollection,
                                                         metadataPropertyCollection,
                                                         domainSpecificProcessingType,
                                                         domainSpecificConfig,
                                                         getDistinctValuesFieldName,
                                                         groupBy)
                    };

                    if (!isFullGet)
                    {
                        // skip the bdb entry header
                        myStream.Read(new byte[BdbHeaderSize], 0, BdbHeaderSize);
                    }

                    // This mess is required until Moods 2.0 migrated to have IVersionSerializable version of CacheIndexInternal
                    // ** TBD - Should be removed later
                    if (LegacySerializationUtil.Instance.IsSupported(typeId))
                    {
                        cacheIndexInternal.Deserialize(new CompactBinaryReader(myStream));
                    }
                    else
                    {
                        int version = myStream.ReadByte();

                        try
                        {
                            cacheIndexInternal.Deserialize(new CompactBinaryReader(myStream), version);
                        }
                        catch (Exception ex)
                        {
                            LoggingUtil.Log.ErrorFormat(
                                "The deserialization has an exception: primary id : {0}, index id : {1}, extendedid : {2}, extendedIdSuffix : {3}, version : {4} info : {5}",
                                primaryId,
                                ByteArrayToString(indexId, 0),
                                ByteArrayToString(extendedId, 0),
                                extendedIdSuffix,
                                version,
                                ex.ToString());

                            if (myStream.Length > 0)
                            {
                                myStream.Seek(0, SeekOrigin.Begin);
                                byte[] ba = new byte[10];
                                myStream.Read(ba, 0, 10);

                                LoggingUtil.Log.ErrorFormat("The first 10 bytes of the stream are {0}",
                                                            ByteArrayToString(ba, 0));
                            }

                            throw;
                        }
                    }

                    // update SmartStream perf counters
                    if (!isFullGet)
                    {
                        SmartStream mySmartStream = (SmartStream)myStream;

                        BerkeleyBinaryStorePerformanceCounters.Instance.IncrementCounter(
                            BerkeleyBinaryStorePerformanceCounterEnum.AvgDbGetPerPartialGet,
                            mySmartStream.DatabaseAccessTime);

                        BerkeleyBinaryStorePerformanceCounters.Instance.IncrementCounter(
                            BerkeleyBinaryStorePerformanceCounterEnum.AvgDbGetPerPartialGetBase,
                            1);

                        BerkeleyBinaryStorePerformanceCounters.Instance.IncrementCounter(
                            BerkeleyBinaryStorePerformanceCounterEnum.AvgBytesPerPartialGet,
                            mySmartStream.Position);

                        BerkeleyBinaryStorePerformanceCounters.Instance.IncrementCounter(
                            BerkeleyBinaryStorePerformanceCounterEnum.AvgBytesPerPartialGetBase,
                            1);
                    }
                }
            }
            finally
            {
                // release the pooled stream
                if (storeContext.MemoryPool != null && pooledStreamItem != null)
                {
                    storeContext.MemoryPool.ReleaseItem(pooledStreamItem);
                }
            }

            return(cacheIndexInternal);
        }
Exemple #16
0
 private void Awake()
 {
     ResourcePoolItem = GetComponent<ResourcePoolItem>();
 }
Exemple #17
0
 private void Start()
 {
     _resourcePoolItem = GetComponent<ResourcePoolItem>();
     _resourcePoolItem.OnGetAvaiable = OnGetAvailable;
 }
 internal void WaitForReply(short waitId)
 {
     ResourcePoolItem<short> idItem = this.idItem; //need a reference to this so we can release it LAST and avoid a race condition
     if (Log.IsDebugEnabled)
     {
         Log.DebugFormat("WaitForReply() Waits for waitId {0} to be released.", waitId);
     }
     if (this.waitHandle.WaitOne(timeOut, false))
     {
         if (Log.IsDebugEnabled)
         {
             Log.DebugFormat("WaitForReply() waitId {0} is released.", waitId);
         }
         this.idItem = null;
         idItem.Release();
         this.waitHandle = null;
     }
     else
     {
         this.idItem = null;
         idItem.Release();
         this.waitHandle = null;
         //ApplicationException ex = new ApplicationException("TimeOut exception.");
         if (Log.IsErrorEnabled)
         {
             StringBuilder sb = new StringBuilder();
             sb.AppendFormat("WaitForReply() WaitHandle is timed out for waitId {0}", waitId);
             Log.Error(sb.ToString());
         }
         //throw ex;
     }
 }
 internal void SetValues(int timeout, EventWaitHandle waitHandle, ResourcePoolItem<short> idItem)
 {
     if (Log.IsDebugEnabled)
     {
         Log.DebugFormat("SetValues() Sets WaitHandle");
     }
     this.timeOut = timeout;
     this.waitHandle = waitHandle;
     this.idItem = idItem;
 }
 internal ReplyBucket(int timeout, EventWaitHandle waitHandle, ResourcePoolItem<short> idItem)
 {
     SetValues(timeout, waitHandle, idItem);
 }