Get() public method

public Get ( HystrixRollingNumberEvent type ) : long
type HystrixRollingNumberEvent
return long
        /*
         * Takes as input the HttpContext instance for the current request, the SessionID value for the current request,
         * and the lock identifier for the current request, and releases the lock on an item in the session data store.
         * This method is called when the GetItem or GetItemExclusive method is called and the data store specifies that
         * the requested item is locked, but the lock age has exceeded the ExecutionTimeout value. The lock is cleared by
         * this method, freeing the item for use by other requests.
         * */
        public override void ReleaseItemExclusive(HttpContext context, string id, object lockId)
        {
            CheckKey(ref id);
            _log.TraceFormat("ReleaseItemExclusive called for item {0} with lockId {1}.", id, lockId);

            var original = Bucket.Get <SessionStateItem>(id);
            var item     = original.Value;

            if (original.Success && item.LockId != (uint)lockId)
            {
                return;
            }

            item.Locked          = false;
            item.Expires         = DateTime.UtcNow.AddMinutes(Config.Timeout.TotalMinutes);
            item.SessionId       = id;
            item.ApplicationName = ApplicationName;
            item.LockId          = (uint)lockId;

            var upsert = Bucket.Upsert(id, item, Config.Timeout);

            if (!upsert.Success)
            {
                LogAndOrThrow(upsert, id);
            }
        }
Exemplo n.º 2
0
    // GetKeyValue
    IEnumerator GetKeyValue(Bucket bucket, string key)
    {
        // Get the value for the key
        var getReq = bucket.Get(key);

        yield return(getReq.WaitUntilDone());

        if (getReq.isSuccessful)
        {
            // Try to deserialize the data to a string. If this does not work, use the raw data.
            var encoding = getReq.GetEncoding();
            if (encoding == Encoding.Json)
            {
                var tree = getReq.GetValue <JsonTree>();
                data[key] = new DBValue {
                    text     = tree.ToString(),
                    tree     = tree,
                    encoding = encoding
                };
            }
            else
            {
                data[key] = new DBValue {
                    text     = getReq.GetValueRaw(),
                    tree     = null,
                    encoding = encoding
                };
            }
        }
        else
        {
            Debug.LogError("Error querying value for key: " + key);
        }
    }
        public override void RemoveItem(HttpContext context, string id, object lockId, SessionStateStoreData item)
        {
            CheckKey(ref id);
            _log.TraceFormat("Remove called for item {0} with lockId {1}.", id, lockId);

            var result = Bucket.Get <SessionStateItem>(id);

            if (result.Success)
            {
                var entry = result.Value;
                if (entry.LockId == (uint)lockId)
                {
                    var deleted = Bucket.Remove(id);
                    if (deleted.Success)
                    {
                        return;
                    }
                    LogAndOrThrow(deleted, id);
                }
            }
            else
            {
                LogAndOrThrow(result, id);
            }
        }
        public override void ResetItemTimeout(HttpContext context, string id)
        {
            CheckKey(ref id);
            _log.TraceFormat("ResetItemTimeout called for item {0}.", id);

            var result = Bucket.Get <SessionStateItem>(id);

            if (result.Success)
            {
                var item = result.Value;
                item.Timeout         = Config.Timeout;
                item.SessionId       = id;
                item.ApplicationName = ApplicationName;

                var updated = Bucket.Upsert(id, item, Config.Timeout);
                if (updated.Success)
                {
                    return;
                }
                LogAndOrThrow(updated, id);
            }
            else
            {
                LogAndOrThrow(result, id);
            }
        }
    // CopyULobbyAccounts
    public static IEnumerator CopyULobbyAccounts()
    {
        var emailToIdBucket = new Bucket("uLobby AccountNameToID");

        var request = emailToIdBucket.GetKeys();

        yield return(request.WaitUntilDone());

        if (request.hasFailed)
        {
            yield break;
        }

        foreach (var email in request.GetKeyEnumerable())
        {
            emailToIdBucket.Get(email, Constants.Replication.Default, (req) => {
                var accountId = req.GetValue <string>();
                LogManager.General.Log("Copying account '" + req.key + "' with ID '" + accountId + "'");
                GameDB.instance.StartCoroutine(
                    CreateAccount(
                        accountId,
                        req.key,
                        GameDB.GetRandomString(10)
                        )
                    );
            }, null);
        }
    }
Exemplo n.º 6
0
        /// <summary>
        /// Gets the specified index.
        /// </summary>
        /// <param name="index">The index.</param>
        /// <returns></returns>
        private T Get(int index)
        {
            if (index < 0)
            {
                throw new IndexOutOfRangeException();
            }
            if (index > Count)
            {
                throw new IndexOutOfRangeException();
            }

            // ReSharper disable once InconsistentlySynchronizedField
            var get = Bucket.Get <List <T> >(Key);

            if (!get.Success)
            {
                if (get.Exception != null)
                {
                    throw get.Exception;
                }
                throw new InvalidOperationException(get.Status.ToString());
            }

            var items = get.Value;

            return(items[index]);
        }
Exemplo n.º 7
0
 /// <summary>
 /// Gets a cache item by its key, returning null if the item does not exist within the Cache.
 /// </summary>
 /// <param name="key">The key to lookup the item.</param>
 /// <returns>The cache item if found, otherwise null.</returns>
 public byte[] Get(string key)
 {
     if (key == null)
     {
         throw new ArgumentNullException(nameof(key));
     }
     return(Bucket.Get <byte[]>(key).Value);
 }
        public void ExceptionsAreDifferent()
        {
            // try to get a document that doesn't exist
            IOperationResult <Pizza> doc =
                Bucket.Get <Pizza>(Guid.NewGuid().ToString());

            // exceptions are returned, not thrown
            Assert.That(doc.Message, Is.Not.Null);
            Assert.That(doc.Exception, Is.Not.Null);
        }
Exemplo n.º 9
0
        public void CreateContainers()
        {
            Container container;

            // Test whether default containers have the correct capacity and content.
            container = Bucket.GetDefault();
            Assert.Equal(12, container.Capacity);
            Assert.Equal(0, container.Content);

            container = RainBarrel.Get();
            Assert.Equal(100, container.Capacity);
            Assert.Equal(0, container.Content);

            container = RainBarrel.GetSmall();
            Assert.Equal(80, container.Capacity);
            Assert.Equal(0, container.Content);

            container = RainBarrel.GetLarge();
            Assert.Equal(120, container.Capacity);
            Assert.Equal(0, container.Content);

            container = OilBarrel.Get();
            Assert.Equal(159, container.Capacity);
            Assert.Equal(0, container.Content);

            // Test whether or not an exception is thrown when creating valid/invalid conainers.
            Bucket.GetDefault(11);
            Bucket.GetDefault(12);
            Assert.Throws <ArgumentOutOfRangeException>(() => Bucket.GetDefault(13));

            Bucket.Get(11);
            Bucket.Get(10);
            Assert.Throws <ArgumentOutOfRangeException>(() => Bucket.Get(9));

            Bucket.Get(16, 15);
            Bucket.Get(16, 16);
            Assert.Throws <ArgumentOutOfRangeException>(() => Bucket.Get(16, 17));

            RainBarrel.Get(99);
            RainBarrel.Get(100);
            Assert.Throws <ArgumentOutOfRangeException>(() => RainBarrel.Get(101));

            RainBarrel.GetSmall(79);
            RainBarrel.GetSmall(80);
            Assert.Throws <ArgumentOutOfRangeException>(() => RainBarrel.GetSmall(81));

            RainBarrel.GetLarge(119);
            RainBarrel.GetLarge(120);
            Assert.Throws <ArgumentOutOfRangeException>(() => RainBarrel.GetLarge(121));

            OilBarrel.Get(158);
            OilBarrel.Get(159);
            Assert.Throws <ArgumentOutOfRangeException>(() => OilBarrel.Get(160));
        }
        /**
         * Get the value of the latest (current) bucket in the rolling counter for the given {@link HystrixRollingNumberEvent} type.
         * <p>
         * The {@link HystrixRollingNumberEvent} must be a "counter" type <code>HystrixRollingNumberEvent.isCounter() == true</code>.
         *
         * @param type
         *            HystrixRollingNumberEvent defining which counter to retrieve value from
         * @return
         *         value from latest bucket for given {@link HystrixRollingNumberEvent} counter type
         */
        public long GetValueOfLatestBucket(HystrixRollingNumberEvent type)
        {
            Bucket lastBucket = GetCurrentBucket();

            if (lastBucket == null)
            {
                return(0);
            }
            // we have bucket data so we'll return the lastBucket
            return(lastBucket.Get(type));
        }
        private List <T> GetItems()
        {
            // ReSharper disable once InconsistentlySynchronizedField
            var get = Bucket.Get <List <T> >(Key);

            if (!get.Success)
            {
                if (get.Exception != null)
                {
                    throw get.Exception;
                }
                throw new InvalidOperationException(get.Status.ToString());
            }

            return(get.Value);
        }
Exemplo n.º 12
0
    // SendArtifactRewards
    public static IEnumerator SendArtifactRewards(Player player)
    {
        string accountId = player.accountId;

        // Retrieve inventory
        var bucket     = new Bucket("AccountToArtifactInventory");
        var getRequest = bucket.Get(accountId);

        yield return(getRequest.WaitUntilDone());

        ArtifactInventory artifactInventory;

        if (getRequest.isSuccessful)
        {
            artifactInventory = getRequest.GetValue <ArtifactInventory>();

            LogManager.DB.Log("Queried artifact inventory of account '" + accountId + "' successfully");
        }
        else
        {
            artifactInventory = new ArtifactInventory();

            LogManager.DB.Log("Account " + accountId + " doesn't have any artifact inventory yet");
        }

        // TODO: Skill dependant
        var arti = new Artifact((byte)Random.Range(0, 3));

        artifactInventory.AddArtifact(arti);

        // Let the player know about his reward
        player.networkView.RPC("ReceiveArtifactReward", uLink.RPCMode.Owner, arti.id);

        // Write new stats
        var setRequest = bucket.Set(accountId, artifactInventory, Encoding.Json);

        yield return(setRequest.WaitUntilDone());

        if (setRequest.isSuccessful)
        {
            LogManager.DB.Log("Wrote artifact inventory of '" + accountId + "' successfully");
        }
        else
        {
            LogManager.DB.LogError("Could not write artifact inventory for '" + accountId + "'");
        }
    }
Exemplo n.º 13
0
        /// <summary>
        /// Removes the first occurrence of a specific object from the <see cref="T:System.Collections.Generic.ICollection`1" />.
        /// </summary>
        /// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1" />.</param>
        /// <returns>
        /// true if <paramref name="item" /> was successfully removed from the <see cref="T:System.Collections.Generic.ICollection`1" />; otherwise, false. This method also returns false if <paramref name="item" /> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1" />.
        /// </returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public bool Remove(T item)
        {
            var get = Bucket.Get <List <T> >(Key);

            if (!get.Success)
            {
                if (get.Exception != null)
                {
                    throw get.Exception;
                }
                throw new InvalidOperationException(get.Status.ToString());
            }

            var items = get.Value;

            return(items.Remove(item));
        }
Exemplo n.º 14
0
        public void WhereCanIUseCas()
        {
            // insert a new document
            var id    = Guid.NewGuid().ToString();
            var pizza = new Pizza {
                SizeInches = 14, Toppings = new List <string> {
                    "Pepperoni", "Mushroom"
                }, ExtraCheese = true
            };

            Bucket.Insert(id, pizza);

            // get document with CAS
            IOperationResult <Pizza> getResult = Bucket.Get <Pizza>(id);

            Assert.That(getResult.Cas, Is.GreaterThan(0));

            // replace with CAS
            pizza.ExtraCheese = false;
            var replaceDoc = new Document <Pizza>
            {
                Id      = id,
                Content = pizza,
                Cas     = getResult.Cas
            };
            IDocumentResult <Pizza> replaceResult = Bucket.Replace(replaceDoc);

            Assert.That(replaceResult.Document.Cas,
                        Is.GreaterThan(0));
            Assert.That(replaceResult.Document.Cas,
                        Is.Not.EqualTo(getResult.Cas));

            // upsert with CAS
            pizza.ExtraCheese = true;
            var upsertDoc = new Document <Pizza>
            {
                Id      = id,
                Content = pizza,
                Cas     = replaceDoc.Cas
            };
            IDocumentResult <Pizza> upsertResult = Bucket.Upsert(upsertDoc);

            Assert.That(upsertResult.Success, Is.True);
        }
Exemplo n.º 15
0
        public void GetReturnIsDifferent()
        {
            // insert a document, uses Document<T>
            var doc = new Document <Pizza>();

            doc.Id      = Guid.NewGuid().ToString();
            doc.Content = new Pizza
            {
                SizeInches = 14,
                Toppings   = new List <string> {
                    "Pepperoni", "Mushrooms"
                },
                ExtraCheese = true
            };
            Bucket.Insert(doc);

            // get a document, uses Get<T>
            IOperationResult <Pizza> result = Bucket.Get <Pizza>(doc.Id);
            Pizza myPizza = result.Value;

            Assert.That(doc.Content.SizeInches,
                        Is.EqualTo(myPizza.SizeInches));
        }
Exemplo n.º 16
0
    // Get character stats
    public static IEnumerator GetCharacterStats(Player player)
    {
        LogManager.DB.Log("Getting character stats for account ID '" + player.accountId + "'");

        var bucket  = new Bucket("AccountToCharacterStats");
        var request = bucket.Get(player.accountId);

        yield return(request.WaitUntilDone());

        if (request.isSuccessful)
        {
            player.charStats = request.GetValue <CharacterStats>();
            LogManager.DB.Log("Retrieved character stats of account ID '" + player.accountId + "' successfully: " + player.charStats.ToString());
        }
        else
        {
            player.charStats = new CharacterStats();
            LogManager.DB.LogWarning("Account '" + player.accountId + "' doesn't have any character stats yet, creating default ones");
        }

        // Send other players and myself information about stats
        player.networkView.RPC("ReceiveCharacterStats", uLink.RPCMode.All, player.charStats);
    }
Exemplo n.º 17
0
    // Get
    public static IEnumerator Get <T>(string bucketName, string key, ActionOnResult <T> func)
    {
        var stopWatch = Stopwatch.StartNew();

        var bucket  = new Bucket(bucketName);
        var request = bucket.Get(key);

        yield return(request.WaitUntilDone());

        stopWatch.Stop();

        if (request.isSuccessful)
        {
            T val = request.GetValue <T>();
            LogManager.DB.Log(FormatSuccess(key, "get", bucketName, val) + " (" + stopWatch.ElapsedMilliseconds + " ms)");
            func(val);
        }
        else
        {
            LogManager.DB.LogWarning(FormatFail(key, "get", bucketName) + " (" + stopWatch.ElapsedMilliseconds + " ms)");
            func(default(T));
        }
    }
    // DeleteAllUnactivatedAccounts
    public static IEnumerator DeleteAllUnactivatedAccounts()
    {
        var emailToIdBucket = new Bucket("uLobby AccountNameToID");

        var request = new Bucket("AccountsAwaitingActivation").GetKeys();

        yield return(request.WaitUntilDone());

        if (request.hasFailed)
        {
            yield break;
        }

        foreach (var email in request.GetKeyEnumerable())
        {
            emailToIdBucket.Get(email, Constants.Replication.Default, (req) => {
                var accountId = req.GetValue <string>();
                LogManager.General.Log("Deleting account '" + req.key + "' with ID '" + accountId + "'");
                GameDB.instance.StartCoroutine(DeleteAccount(accountId));
            }, null);
            //yield return req.WaitUntilDone();
        }
    }
Exemplo n.º 19
0
        /// <summary>
        /// Removes and returns the object at the beginning of the <see cref="CouchbaseQueue{T}"/>.
        /// </summary>
        /// <returns>The object that is removed from the beginning of the <see cref="CouchbaseQueue{T}"/>.</returns>
        /// <exception cref="System.InvalidOperationException">The <see cref="CouchbaseQueue{T}"/> is empty.</exception>
        public T Dequeue()
        {
            T item;
            IDocumentResult upsert;

            do
            {
                var get = Bucket.Get <List <T> >(Key);
                if (!get.Success && get.Exception != null)
                {
                    throw get.Exception;
                }

                var items = get.Value;
                if (items.Count < 1)
                {
                    throw new InvalidOperationException("The Queue<T> is empty.");
                }

                const int index = 0;
                item = items[index];
                items.RemoveAt(index);

                upsert = Bucket.Upsert(new Document <List <T> >
                {
                    Id      = Key,
                    Content = items,
                    Cas     = get.Cas
                });

                if (upsert.Success)
                {
                    break;
                }
            } while (upsert.Status == ResponseStatus.KeyExists);
            return(item);
        }
Exemplo n.º 20
0
        private void bCreateBucket_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                double content = tbBucketContent.Text.Length == 0 ? 0 : double.Parse(tbBucketContent.Text);
                Bucket bucket;
                if (tbBucketCapacity.Text.Length == 0)
                {
                    bucket = Bucket.GetDefault(content);
                }
                else
                {
                    bucket = Bucket.Get(double.Parse(tbBucketCapacity.Text), content);
                }

                BucketViewModel bucketViewModel = new BucketViewModel(bucket);
                AddContainer(bucketViewModel);
                viewModel.OtherBuckets.Add(bucketViewModel);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemplo n.º 21
0
    // Retrieves the player information
    IEnumerator RetrievePlayerInformation(uLink.NetworkPlayer networkPlayer, string accountId)
    {
        LogManager.General.Log("Retrieving player information for account " + accountId);

        var bucket  = new Bucket("AccountToName");
        var request = bucket.Get(accountId);

        yield return(request.WaitUntilDone());

        if (request.isSuccessful)
        {
            string playerName = request.GetValue <string>();

            LogManager.General.Log("Queried player name of '" + accountId + "' successfully: " + playerName);

            // Assign party
            int partyId = GetPartyId(accountId);
            var party   = GameServerParty.partyList[partyId];

            // Respawn position
            Vector3 respawnPosition;
            float   cameraYRotation = 0f;

            if (GameManager.isPvE)
            {
                PortalDB.GetPortal(accountId, portalInfo => {
                    // Player did not come via a portal
                    if (portalInfo == null)
                    {
                        PositionsDB.GetPosition(accountId, data => {
                            if (data != null)
                            {
                                respawnPosition = data.ToVector3();
                                LogManager.General.Log("Found player position: Respawning at " + respawnPosition);
                            }
                            else
                            {
                                respawnPosition = party.spawn.GetNextSpawnPosition();
                                LogManager.General.Log("Couldn't find player position: Respawning at " + respawnPosition);

                                // Adjust camera rotation
                                cameraYRotation = party.spawn.cameraYRotation;
                            }

                            // Instantiate the player
                            InstantiatePlayer(networkPlayer, accountId, playerName, respawnPosition, cameraYRotation, partyId);
                        });
                        // Player did come via a portal
                    }
                    else
                    {
                        var portals = GameObject.FindGameObjectsWithTag("Portal");

                        foreach (var portalObject in portals)
                        {
                            var portal = portalObject.GetComponent <Portal>();

                            if (portal.mapName == portalInfo.mapName)
                            {
                                var spawn       = portal.spawns[Random.Range(0, portal.spawns.Length - 1)];
                                respawnPosition = spawn.position;

                                // Respawn
                                LogManager.General.Log("Player came via a portal: Respawning at " + respawnPosition);

                                // Adjust camera rotation
                                cameraYRotation = portal.cameraYRotation;

                                // Update position to be 100% sure our position data is correct now
                                PositionsDB.SetPosition(accountId, respawnPosition);

                                // Delete portal info so we won't use it again
                                PortalDB.RemovePortal(accountId);

                                // Instantiate the player
                                InstantiatePlayer(networkPlayer, accountId, playerName, respawnPosition, cameraYRotation, partyId);

                                break;
                            }
                        }
                    }
                });
            }
            else
            {
                respawnPosition = party.spawn.GetNextSpawnPosition();

                LogManager.General.Log("PvP game: Respawning at " + respawnPosition);

                // Instantiate the player
                InstantiatePlayer(networkPlayer, accountId, playerName, respawnPosition, cameraYRotation, partyId);
            }
        }
        else
        {
            LogManager.General.LogError("Account " + accountId + " doesn't have a player name.");
        }
    }
Exemplo n.º 22
0
    // Get top ranks
    public static IEnumerator GetTopRanks(byte subject, byte page, uint maxPlayerCount, GameDB.ActionOnResult <RankEntry[]> func = null)
    {
        // TODO: Use GameDB.MapReduce

        // Retrieve the highscore list from the database by using MapReduce. The MapReduce request consists of a
        // map phase and a reduce phase. The phases are expressed as JavaScript code in string form. The reduce
        // phase also gets the maximum number of scores to fetch as an argument.
        var bucket = new Bucket("AccountToStats");
        var getHighscoresRequest = bucket.MapReduce(
            new JavaScriptMapPhase(GetHighscoresMapFunction(page)),
            new JavaScriptReducePhase(highscoresReduceFunction, maxPlayerCount)
            );

        // Wait until the request finishes and then update the local list of highscore entries.
        yield return(getHighscoresRequest.WaitUntilDone());

        if (getHighscoresRequest.isSuccessful)
        {
            IEnumerable <RankEntry> rankingEntriesTmp = getHighscoresRequest.GetResult <RankEntry>();

            var rankingEntries = rankingEntriesTmp.ToArray();

            // Get player names
            // TODO: Send X requests at once, then wait for all of them
            var nameBucket    = new Bucket("AccountToName");
            var countryBucket = new Bucket("AccountToCountry");

            var nameRequests    = new GetRequest[rankingEntries.Length];
            var countryRequests = new GetRequest[rankingEntries.Length];

            for (int i = 0; i < rankingEntries.Length; i++)
            {
                var entry = rankingEntries[i];
                entry.rankIndex = i;

                // Name
                string name;
                if (GameDB.accountIdToName.TryGetValue(entry.accountId, out name))
                {
                    entry.name      = name;
                    nameRequests[i] = null;
                }
                else
                {
                    nameRequests[i] = nameBucket.Get(entry.accountId);
                }

                // Country
                string country;
                if (IPInfoServer.accountIdToCountry.TryGetValue(entry.accountId, out country))
                {
                    entry.country      = country;
                    countryRequests[i] = null;
                }
                else
                {
                    countryRequests[i] = countryBucket.Get(entry.accountId);
                }
            }

            for (int i = 0; i < rankingEntries.Length; i++)
            {
                // Name
                var nameRequest = nameRequests[i];
                if (nameRequest != null)
                {
                    yield return(nameRequest.WaitUntilDone());

                    if (nameRequest.isSuccessful)
                    {
                        var entry = rankingEntries[i];
                        entry.name = nameRequest.GetValue <string>();
                        GameDB.accountIdToName[entry.accountId] = entry.name;
                    }
                }

                // Country
                var countryRequest = countryRequests[i];
                if (countryRequest != null)
                {
                    yield return(countryRequest.WaitUntilDone());

                    var entry = rankingEntries[i];

                    if (countryRequest.isSuccessful)
                    {
                        entry.country = countryRequest.GetValue <string>();
                        IPInfoServer.accountIdToCountry[entry.accountId] = entry.country;
                    }
                    else
                    {
                        entry.country = "";
                        IPInfoServer.accountIdToCountry[entry.accountId] = "";
                    }
                }
            }

            // Save in cache
            GameDB.rankingLists[subject][page] = rankingEntries;

            //LogManager.General.Log("Sending the ranking list " + rankingEntries + " with " + rankingEntries.Length + " / " + maxPlayerCount + " entries (" + subject + ", " + page + ")");
            if (func != null)
            {
                func(rankingEntries);
            }
        }
        else
        {
            LogManager.General.LogError("Failed getting the ranking list: " + getHighscoresRequest.GetErrorString());

            if (func != null)
            {
                func(null);
            }
        }
    }
        /*
         * Takes as input the HttpContext instance for the current request and the SessionID value for the current request.
         * Retrieves session values and information from the session data store and locks the session-item data at the data
         * store for the duration of the request. The GetItemExclusive method sets several output-parameter values that inform
         * the calling SessionStateModule about the state of the current session-state item in the data store.
         *
         * If no session item data is found at the data store, the GetItemExclusive method sets the locked output parameter to
         * false and returns null. This causes SessionStateModule to call the CreateNewStoreData method to create a new
         * SessionStateStoreData object for the request.
         *
         * If session-item data is found at the data store but the data is locked, the GetItemExclusive method sets the locked
         * output parameter to true, sets the lockAge output parameter to the current date and time minus the date and time when
         * the item was locked, sets the lockId output parameter to the lock identifier retrieved from the data store, and returns
         * null. This causes SessionStateModule to call the GetItemExclusive method again after a half-second interval, to attempt
         * to retrieve the session-item information and obtain a lock on the data. If the value that the lockAge output parameter
         * is set to exceeds the ExecutionTimeout value, SessionStateModule calls the ReleaseItemExclusive method to clear the lock
         * on the session-item data and then call the GetItemExclusive method again.
         *
         * The actionFlags parameter is used with sessions whose Cookieless property is true, when the regenerateExpiredSessionId
         * attribute is set to true. An actionFlags value set to InitializeItem (1) indicates that the entry in the session data
         * store is a new session that requires initialization. Uninitialized entries in the session data store are created by a
         * call to the CreateUninitializedItem method. If the item from the session data store is already initialized, the
         * actionFlags parameter is set to zero.
         *
         * If your provider supports cookieless sessions, set the actionFlags output parameter to the value returned from the session
         * data store for the current item. If the actionFlags parameter value for the requested session-store item equals the
         * InitializeItem enumeration value (1), the GetItemExclusive method should set the value in the data store to zero after
         * setting the actionFlags out parameter.*/
        private SessionStateStoreData GetSessionStoreItem(bool lockRecord,
                                                          HttpContext context,
                                                          string id,
                                                          out bool locked,
                                                          out TimeSpan lockAge,
                                                          out object lockId,
                                                          out SessionStateActions actions)
        {
            locked  = false;
            lockAge = TimeSpan.Zero;
            lockId  = 0;
            actions = SessionStateActions.None;

            _log.TraceFormat("GetSessionStoreItem called for item {0} with lockId {1}.", id, lockId);
            CheckKey(ref id);

            /*
             * If no session item data is found at the data store, the GetItemExclusive method sets the locked output parameter to
             * false and returns null. This causes SessionStateModule to call the CreateNewStoreData method to create a new
             * SessionStateStoreData object for the request.
             */
            var sessionData = Bucket.Get <SessionStateItem>(id);

            if (sessionData.Status == ResponseStatus.KeyNotFound)
            {
                lockAge = TimeSpan.Zero;
                actions = SessionStateActions.InitializeItem;
                lockId  = null;
                return(null);
            }

            /*
             * * If session-item data is found at the data store but the data is locked, the GetItemExclusive method sets the locked
             * output parameter to true, sets the lockAge output parameter to the current date and time minus the date and time when
             * the item was locked, sets the lockId output parameter to the lock identifier retrieved from the data store, and returns
             * null. This causes SessionStateModule to call the GetItemExclusive method again after a half-second interval, to attempt
             * to retrieve the session-item information and obtain a lock on the data. If the value that the lockAge output parameter
             * is set to exceeds the ExecutionTimeout value, SessionStateModule calls the ReleaseItemExclusive method to clear the lock
             * on the session-item data and then call the GetItemExclusive method again.
             */

            SessionStateStoreData item = null;

            if (sessionData.Status == ResponseStatus.Success)
            {
                if (sessionData.Value.Locked)
                {
                    locked  = true;
                    lockAge = DateTime.UtcNow - sessionData.Value.LockDate;
                    lockId  = sessionData.Value.LockId;
                    actions = sessionData.Value.Actions;
                }
                else
                {
                    lockAge = DateTime.UtcNow - sessionData.Value.LockDate;
                    lockId  = sessionData.Value.LockId;
                    var sessionStateItem = sessionData.Value;

                    if (sessionData.Value.Actions == SessionStateActions.InitializeItem)
                    {
                        //create a new item
                        item = CreateNewStoreData(context, (int)Config.Timeout.TotalMinutes);
                    }
                    else
                    {
                        item = new SessionStateStoreData(Deserialize(sessionStateItem.SessionItems),
                                                         SessionStateUtility.GetSessionStaticObjects(context),
                                                         (int)sessionData.Value.Timeout.TotalMinutes);
                    }
                }

                if (!lockRecord)
                {
                    return(item);
                }

                var upsert = Bucket.Upsert(id, sessionData.Value, Config.Timeout);
                if (!upsert.Success)
                {
                    LogAndOrThrow(upsert, id);
                }
            }
            else
            {
                lockAge = TimeSpan.Zero;
                actions = SessionStateActions.InitializeItem;
                lockId  = null;
            }
            return(item);
        }
Exemplo n.º 24
0
        public static double SetAndGetKetchupSync(int numberOfOperations, Bucket cli)
        {
            var start = DateTime.Now;

            for (var i = 0; i < numberOfOperations; i++)
            {
                var key = "kc" + i;
                var value = key + " value";
                cli.Set(key, value);
            }

            for (var i = 0; i < numberOfOperations; i++)
            {
                var key = "kc" + i;
                var expected = key + " value";
                var actual = cli.Get<string>(key);
                if (actual != expected) Console.WriteLine("Values did not match. expected: " + expected + ". actual: " + actual);
            }

            return (DateTime.Now - start).TotalSeconds;
        }
Exemplo n.º 25
0
        public static double SetAndGetKetchupAsync(int numberOfOperations, Bucket cli)
        {
            var counter = numberOfOperations;
            var start = DateTime.Now;
            var sync = new object();

            //simulate synchronous operation
            TestAsync(180, (success, fail) =>
            {
                for (var i = 0; i < numberOfOperations; i++)
                {
                    var key = "kc" + i;
                    var value = key + " value";
                    var bucket = "default";
                    object asyncState = new DemoAsyncState { Key = key };
                    cli.Set(key, value, s =>
                        {
                            lock (sync)
                            {
                                dynamic state = s;
                                var c = --counter;
                                if (debugAsync) Console.WriteLine(c + ": " + state.Key + ": set");
                                if (c == 0) success(s);
                            }
                        }, fail, asyncState);
                }
            });

            counter = numberOfOperations;
            TestAsync(60, (success, fail) =>
            {
                for (var i = 0; i < numberOfOperations; i++)
                {
                    var key = "kc" + i;
                    var bucket = "default";

                    //get is fired on success return of set
                    var asyncState = new DemoAsyncState { Key = key, Counter = counter };
                    cli.Get<string>(key,
                        (val, s) =>
                        {
                            lock (sync)
                            {
                                dynamic state = s;
                                var c = --counter;
                                if (debugAsync) Console.WriteLine(c + ": " + state.Key + ": " + val);
                                if (c == 0) success(s);
                            }
                        },
                        s1 =>
                        {
                            lock (sync)
                            {
                                dynamic state1 = s1;
                                var c1 = --counter;
                                if (debugAsync) Console.WriteLine(c1 + ": " + state1.Key + ": miss");
                                if (c1 == 0) success(s1);
                            }
                        },
                        fail, asyncState
                    );
                }
            });

            return (DateTime.Now - start).TotalSeconds;
        }
        /*
         * Takes as input the HttpContext instance for the current request, the SessionID value for the current request,
         * a SessionStateStoreData object that contains the current session values to be stored, the lock identifier for
         * the current request, and a value that indicates whether the data to be stored is for a new session or an existing
         * session.
         * If the newItem parameter is true, the SetAndReleaseItemExclusive method inserts a new item into the data store
         * with the supplied values. Otherwise, the existing item in the data store is updated with the supplied values, and
         * any lock on the data is released. Note that only session data for the current application that matches the supplied
         * SessionID value and lock identifier values is updated.
         * After the SetAndReleaseItemExclusive method is called, the ResetItemTimeout method is called by SessionStateModule to
         * update the expiration date and time of the session-item data.
         */
        public override void SetAndReleaseItemExclusive(HttpContext context, string id, SessionStateStoreData item, object lockId,
                                                        bool newItem)
        {
            CheckKey(ref id);
            _log.Trace("SetAndReleaseItemExclusive called.");

            var original = Bucket.Get <SessionStateItem>(id);

            if (original.Success && original.Value.LockId != (uint)lockId)
            {
                return;
            }

            var items         = Serialize(item.Items);
            var totalSize     = items.Length;
            var stringBuilder = new StringBuilder();

            foreach (var key in item.Items.Keys)
            {
                var serializerSetting = new JsonSerializerSettings
                {
                    Error = delegate(object sender, Newtonsoft.Json.Serialization.ErrorEventArgs args)
                    {
                        //errors.Add(args.ErrorContext.Error.Message);
                        args.ErrorContext.Handled = true;
                    }
                };
                if (key.ToString().Contains("__SESSIONVIEWSTATE"))
                {
                    File.AppendAllText($"{FolderPath.SessionStats}\\Stats_{key.ToString()}.log", $"{JsonConvert.SerializeObject(item.Items[key.ToString()],Formatting.Indented, serializerSetting)}\r\n");
                }
                long itemSize = 0;
                using (Stream s = new MemoryStream())
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    var             o         = item.Items[key.ToString()];
                    if (o != null)
                    {
                        formatter.Serialize(s, o);
                        itemSize = s.Length;
                    }
                }
                stringBuilder.Append($"Session Insert: {key} size: {itemSize / 1024.0} kB\r\n");
            }
            stringBuilder.Append($"Session Insert: {id} size: {totalSize / 1024.0} kB\r\n");
            File.AppendAllText($"{FolderPath.SessionStats}\\Stats.log", $"{stringBuilder.ToString()}\r\n");
            if (newItem)
            {
                var expires = DateTime.UtcNow.AddMinutes(item.Timeout);
                var result  = Bucket.Insert(id, new SessionStateItem
                {
                    ApplicationName = ApplicationName,
                    Expires         = expires,
                    SessionId       = id,
                    SessionItems    = items,
                    Locked          = false,
                    Timeout         = Config.Timeout
                }, Config.Timeout);

                if (!result.Success)
                {
                    LogAndOrThrow(result, id);
                }
            }
            else
            {
                var entry = original.Value;
                entry.Expires         = DateTime.UtcNow.AddMinutes(Config.Timeout.TotalMinutes);
                entry.SessionItems    = items;
                entry.Locked          = false;
                entry.SessionId       = id;
                entry.ApplicationName = ApplicationName;
                entry.LockId          = (uint)lockId;
                entry.Actions         = SessionStateActions.None;

                var updated = Bucket.Upsert(new Document <SessionStateItem>
                {
                    Content = entry,
                    Id      = id,
                    Expiry  = (uint)Config.Timeout.TotalMilliseconds
                });

                if (!updated.Success)
                {
                    LogAndOrThrow(updated, id);
                }
            }
        }
Exemplo n.º 27
0
    // InstantiatePlayer
    void InstantiatePlayer(uLink.NetworkPlayer networkPlayer, string accountId, string playerName, Vector3 respawnPosition, float cameraYRotation, int partyId)
    {
        LogManager.General.Log(string.Format("Instantiating player prefabs for '{0}' with account ID '{1}'", playerName, accountId));

        var party = GameServerParty.partyList[partyId];

        // Instantiates an avatar for the player connecting to the server
        // The player will be the "owner" of this object. Read the manual chapter 7 for more
        // info about object roles: Creator, Owner and Proxy.
        GameObject obj = uLink.Network.Instantiate(
            networkPlayer,                                      // Owner
            proxyPrefab,
            ownerPrefab,
            creatorPrefab,
            respawnPosition,
            Cache.quaternionIdentity,
            0,                                                          // Network group
            accountId                                                   // Initial data
            );

        // Player component
        Player player = obj.GetComponent <Player>();

        player.accountId        = accountId;
        networkPlayer.localData = player;

        // Send name
        player.networkView.RPC("ReceivePlayerName", uLink.RPCMode.All, playerName);

        // Async: DB requests
        if (isTestServer)
        {
            // This section is for quick client tests on the test server

            // Send other players and myself information about stats
            player.skillBuild    = SkillBuild.GetStarterBuild();
            player.customization = new CharacterCustomization();

            player.networkView.RPC("ReceiveSkillBuild", uLink.RPCMode.All, player.skillBuild);
            player.networkView.RPC("ReceiveCharacterCustomization", uLink.RPCMode.All, player.customization);
            player.networkView.RPC("ReceiveCharacterStats", uLink.RPCMode.All, new CharacterStats());
            player.networkView.RPC("ReceiveArtifactTree", uLink.RPCMode.All, Jboy.Json.WriteObject(ArtifactTree.GetStarterArtifactTree()));

            // After the skill build has been sent, switch the attunement
            player.networkView.RPC("SwitchWeapon", uLink.RPCMode.All, (byte)0);
            player.networkView.RPC("SwitchAttunement", uLink.RPCMode.All, (byte)0);
        }
        else
        {
            // Experience / Level
            ExperienceDB.GetExperience(
                accountId,
                data => {
                uint exp = 0;

                if (data != null)
                {
                    exp = data.experience;
                }

                player.networkView.RPC("SetExperience", uLink.RPCMode.All, exp);
            }
                );

            // TODO: We need to wait until this is finished in ApplyCharacterStats
            // Skill build
            SkillBuildsDB.GetSkillBuild(
                accountId,
                data => {
                if (data == null)
                {
                    player.skillBuild = SkillBuild.GetStarterBuild();
                }
                else
                {
                    player.skillBuild = data;
                }

                // Send build
                player.networkView.RPC("ReceiveSkillBuild", uLink.RPCMode.All, player.skillBuild);

                // After the build has been sent, switch the attunement
                player.networkView.RPC("SwitchWeapon", uLink.RPCMode.All, (byte)0);
                player.networkView.RPC("SwitchAttunement", uLink.RPCMode.All, (byte)0);
            }
                );

            // Character customization
            CharacterCustomizationDB.GetCharacterCustomization(
                accountId,
                data => {
                if (data == null)
                {
                    player.customization = new CharacterCustomization();
                }
                else
                {
                    player.customization = data;
                }

                // Send customization
                player.networkView.RPC("ReceiveCharacterCustomization", uLink.RPCMode.All, player.customization);
            }
                );

            // Character stats
            StartCoroutine(ServerGameDB.GetCharacterStats(player));

            // Guild
            GuildsDB.GetGuildList(accountId, data => {
                if (data != null)
                {
                    GuildsDB.GetGuild(data.mainGuildId, guild => {
                        if (guild != null)
                        {
                            player.networkView.RPC("ReceiveMainGuildInfo", uLink.RPCMode.All, guild.name, guild.tag);
                        }
                    });
                }
            });

            // Artifacts
            ArtifactsDB.GetArtifactTree(
                accountId,
                data => {
                if (data == null)
                {
                    player.artifactTree = ArtifactTree.GetStarterArtifactTree();
                }
                else
                {
                    player.artifactTree = data;
                }

                player.networkView.RPC("ReceiveArtifactTree", uLink.RPCMode.All, Jboy.Json.WriteObject(player.artifactTree));
            }
                );

            // Retrieve arena stats
            var statsBucket = new Bucket("AccountToStats");
            statsBucket.Get(
                accountId,
                Constants.Replication.Default,
                (request) => {
                var statsInDB = request.GetValue <PlayerStats>();

                LogManager.General.Log("Queried stats of account '" + accountId + "' successfully (Ranking: " + statsInDB.bestRanking + ")");

                // Send ranking
                player.networkView.RPC("ReceiveBestRanking", uLink.RPCMode.All, statsInDB.bestRanking);
            }, (request) => {
                var statsInDB = new PlayerStats();

                LogManager.General.Log("Account '" + accountId + "' aka player '" + playerName + "' doesn't have any player stats yet");

                // Send ranking
                player.networkView.RPC("ReceiveBestRanking", uLink.RPCMode.All, statsInDB.bestRanking);
            }
                );
        }

        if (GameManager.isArena)
        {
            player.networkView.RPC("GameMaxScore", uLink.RPCMode.Owner, gameMode.scoreNeededToWin);
        }

        // Layer
        if (GameManager.isPvP)
        {
            player.networkView.RPC("ChangeParty", uLink.RPCMode.All, partyId);
            player.networkView.RPC("ChangeLayer", uLink.RPCMode.All, party.layer);
        }
        else
        {
            player.networkView.RPC("ChangeLayer", uLink.RPCMode.All, Config.instance.openWorldPvPLayer);
        }

        // Respawn
        player.networkView.RPC("Respawn", uLink.RPCMode.All, respawnPosition);
        player.networkView.RPC("SetCameraYRotation", uLink.RPCMode.Owner, cameraYRotation);

        // On non account restricted servers we start the game instantly
        if (!GameManager.isArena || isTestServer)
        {
            player.networkView.RPC("StartGame", uLink.RPCMode.Owner);
            GameManager.gameStarted = true;
        }

        // Disable encryption in non-ranked games
        //if(!GameManager.isRankedGame)
        //	uLink.Network.UninitializeSecurity(networkPlayer);
    }
Exemplo n.º 28
0
        public void TestGetMissFromBucketThrowException()
        {
            var bucket = new Bucket();

            Assert.Throws <KeyNotFoundException>(() => bucket.Get("omegalulz"));
        }
Exemplo n.º 29
0
    // Send stats for a single account
    public static IEnumerator SendAccountStats(Player player)
    {
        string      accountId     = player.accountId;
        PlayerStats instanceStats = player.stats;

        //LogManager.DB.Log("Going to send player stats of '" + player.GetName() + "' to the database");
        LogManager.DB.Log("Retrieving stats for account " + accountId);

        // Which bucket?
        string bucketName;

        switch (GameManager.serverType)
        {
        case ServerType.Arena:
            bucketName = "AccountToStats";
            break;

        case ServerType.FFA:
            bucketName = "AccountToFFAStats";
            break;

        default:
            LogManager.DB.LogError("Unknown server type " + GameManager.serverType + ", can't select a bucket to save the stats");
            yield break;
        }

        // Retrieve old stats
        LogManager.DB.Log("Using bucket '" + bucketName + "'");
        var bucket     = new Bucket(bucketName);
        var getRequest = bucket.Get(accountId);

        yield return(getRequest.WaitUntilDone());

        PlayerStats statsInDB;

        if (getRequest.isSuccessful)
        {
            statsInDB = getRequest.GetValue <PlayerStats>();

            LogManager.DB.Log("Queried stats of account '" + accountId + "' successfully (Ranking: " + statsInDB.ranking + ")");
        }
        else
        {
            statsInDB = new PlayerStats();

            LogManager.DB.Log("Account " + accountId + " doesn't have any player stats yet");
        }

        // Calculate new stats
        LogManager.DB.Log("Merging account stats of '" + accountId + "'...");

        // Merge database stats with the stats in the instance
        statsInDB.MergeWithMatch(instanceStats);

        if (GameManager.isArena)
        {
            LogManager.DB.Log("Sending new best ranking to '" + accountId + "'...");
            player.newBestRanking = statsInDB.bestRanking;
            player.networkView.RPC("ReceiveNewBestRanking", uLink.RPCMode.Others, player.newBestRanking);
        }

        /*if(ServerInit.instance.isArena) {
         *
         * } else if(ServerInit.instance.isFFA) {
         *      LogManager.DB.Log("Merging account stats of '" + accountId + "' for FFA...");
         *
         *      statsInDB.MergeWithFFA(stats);
         * }*/

        // Write new stats
        LogManager.DB.Log("Writing account stats of '" + accountId + "'...");
        var setRequest = bucket.Set(accountId, statsInDB, Encoding.Json);

        yield return(setRequest.WaitUntilDone());

        if (setRequest.isSuccessful)
        {
            LogManager.DB.Log("Wrote account stats of '" + accountId + "' successfully (Ranking: " + statsInDB.ranking + ", Level: " + statsInDB.level + ")");
        }
        else
        {
            LogManager.DB.LogError("Could not write account stats for '" + accountId + "'");
        }
    }
Exemplo n.º 30
0
    // Retrieves the player information
    IEnumerator RetrievePlayerInformation(uLink.NetworkPlayer networkPlayer, string accountId)
    {
        LogManager.General.Log("Retrieving player information for account " + accountId);

        var bucket = new Bucket("AccountToName");
        var request = bucket.Get(accountId);
        yield return request.WaitUntilDone();

        if(request.isSuccessful) {
            string playerName = request.GetValue<string>();

            LogManager.General.Log("Queried player name of '" + accountId + "' successfully: " + playerName);

            // Retrieve stats
            var statsBucket = new Bucket("AccountToStats");
            var statsRequest = statsBucket.Get(accountId);
            yield return statsRequest.WaitUntilDone();

            PlayerStats statsInDB;

            if(statsRequest.isSuccessful) {
                statsInDB = statsRequest.GetValue<PlayerStats>();

                LogManager.General.Log("Queried stats of account '" + accountId + "' successfully (Ranking: " + statsInDB.bestRanking + ")");
            } else {
                statsInDB = new PlayerStats();

                LogManager.General.Log("Account '" + accountId + "' aka player '" + playerName + "' doesn't have any player stats yet");
            }

            // After we got the name, instantiate it
            InstantiatePlayer(networkPlayer, accountId, playerName, statsInDB);
        } else {
            LogManager.General.LogWarning("Account " + accountId + " doesn't have a player name.");
        }
    }