Example #1
0
        public Task EmptyCartAsync(string userId)
        {
            logger.Info($"EmptyCartAsync called with userId={userId}");
            userCartItems[userId] = new Hipstershop.Cart();

            return(Task.CompletedTask);
        }
Example #2
0
        public Task EmptyCartAsync(string userId)
        {
            Console.WriteLine($"EmptyCartAsync called with userId={userId}");
            userCartItems[userId] = new Hipstershop.Cart();

            return(Task.CompletedTask);
        }
        public Task AddItemAsync(string userId, string productId, int quantity)
        {
            Console.WriteLine($"AddItemAsync called with userId={userId}, productId={productId}, quantity={quantity}");
            var newCart = new Hipstershop.Cart
            {
                UserId = userId,
                Items  = { new Hipstershop.CartItem {
                               ProductId = productId, Quantity = quantity
                           } }
            };

            userCartItems.AddOrUpdate(userId, newCart,
                                      (k, exVal) =>
            {
                // If the item exists, we update its quantity
                var existingItem = exVal.Items.SingleOrDefault(item => item.ProductId == productId);
                if (existingItem != null)
                {
                    existingItem.Quantity += quantity;
                }
                else
                {
                    exVal.Items.Add(new Hipstershop.CartItem {
                        ProductId = productId, Quantity = quantity
                    });
                }

                return(exVal);
            });

            return(Task.CompletedTask);
        }
Example #4
0
        public YSQLCartStore(string ysqlAddress)
        {
            // Serialize empty cart into byte array.
            var cart = new Hipstershop.Cart();

            emptyCartBytes       = cart.ToByteArray();
            ysqlconnectionString = $"Server={ysqlAddress};Port=5433;Database=sample;User Id=yugabyte;Password=yugabyte;No Reset On Close=true;Pooling=true;";
        }
Example #5
0
        public RedisCartStore(ConnectionMultiplexer connection)
        {
            redis = connection;
            // Serialize empty cart into byte array.
            var cart = new Hipstershop.Cart();

            emptyCartBytes = cart.ToByteArray();
        }
Example #6
0
        public Task EmptyCartAsync(string userId)
        {
            using (GlobalTracer.Instance.BuildSpan("EmptyCartAsync").StartActive())
            {
                Console.WriteLine($"EmptyCartAsync called with userId={userId}");
                userCartItems[userId] = new Hipstershop.Cart();

                return(Task.CompletedTask);
            }
        }
Example #7
0
        public async Task AddItemAsync(string userId, string productId, int quantity)
        {
            Log.Information("AddItemAsync called with userId={userId}, productId={productId}, quantity={quantity}", userId, productId, quantity);
            var   transaction = Elastic.Apm.Agent.Tracer.CurrentTransaction;
            ISpan span        = transaction.StartSpan("AddItemAsync", ApiConstants.TypeDb, ApiConstants.ActionQuery);

            span.Labels["userId"]    = userId;
            span.Labels["productId"] = productId;
            span.Labels["quantity"]  = quantity.ToString();
            try
            {
                EnsureRedisConnected();

                var db = redis.GetDatabase();

                // Access the cart from the cache
                var value = await db.HashGetAsync(userId, CART_FIELD_NAME);

                Hipstershop.Cart cart;
                if (value.IsNull)
                {
                    cart        = new Hipstershop.Cart();
                    cart.UserId = userId;
                    cart.Items.Add(new Hipstershop.CartItem {
                        ProductId = productId, Quantity = quantity
                    });
                }
                else
                {
                    cart = Hipstershop.Cart.Parser.ParseFrom(value);
                    var existingItem = cart.Items.SingleOrDefault(i => i.ProductId == productId);
                    if (existingItem == null)
                    {
                        cart.Items.Add(new Hipstershop.CartItem {
                            ProductId = productId, Quantity = quantity
                        });
                    }
                    else
                    {
                        existingItem.Quantity += quantity;
                    }
                }

                await db.HashSetAsync(userId, new[] { new HashEntry(CART_FIELD_NAME, cart.ToByteArray()) });
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Can't access cart storage");
                span.CaptureException(ex);
                throw new RpcException(new Status(StatusCode.FailedPrecondition, $"Can't access cart storage. {ex}"));
            }
            finally {
                span.End();
            }
        }
Example #8
0
        public RedisCartStore(ConnectionMultiplexer connection)
        {
            redis = connection;
            // Serialize empty cart into byte array.
            var cart = new Hipstershop.Cart();

            emptyCartBytes = cart.ToByteArray();

            _tracer = Program.tracerProvider.GetTracer("cartservice");
            _random = new Random();
        }
        public Task <Hipstershop.Cart> GetCartAsync(string userId)
        {
            Console.WriteLine($"GetCartAsync called with userId={userId}");
            Hipstershop.Cart cart = null;
            if (!userCartItems.TryGetValue(userId, out cart))
            {
                Console.WriteLine($"No carts for user {userId}");
                return(Task.FromResult(emptyCart));
            }

            return(Task.FromResult(cart));
        }
        public async Task AddItemAsync(string userId, string productId, int quantity)
        {
            Console.WriteLine($"AddItemAsync called with userId={userId}, productId={productId}, quantity={quantity}");

            try
            {
                EnsureRedisConnected();



                var db = redis.GetDatabase();

                // Access the cart from the cache
                var dbTracer = oneAgentSdk.TraceSQLDatabaseRequest(dbInfo, "GET " + CART_FIELD_NAME);
                var value    = await dbTracer.TraceAsync(() => db.HashGetAsync(userId, CART_FIELD_NAME));

                Hipstershop.Cart cart;
                if (value.IsNull)
                {
                    cart        = new Hipstershop.Cart();
                    cart.UserId = userId;
                    cart.Items.Add(new Hipstershop.CartItem {
                        ProductId = productId, Quantity = quantity
                    });
                }
                else
                {
                    cart = Hipstershop.Cart.Parser.ParseFrom(value);
                    var existingItem = cart.Items.SingleOrDefault(i => i.ProductId == productId);
                    if (existingItem == null)
                    {
                        cart.Items.Add(new Hipstershop.CartItem {
                            ProductId = productId, Quantity = quantity
                        });
                    }
                    else
                    {
                        existingItem.Quantity += quantity;
                    }
                }


                var dbTracerUpd = oneAgentSdk.TraceSQLDatabaseRequest(dbInfo, "SET " + CART_FIELD_NAME);
                await dbTracerUpd.TraceAsync(() => db.HashSetAsync(userId, new[] { new HashEntry(CART_FIELD_NAME, cart.ToByteArray()) }));
            }
            catch (Exception ex)
            {
                throw new RpcException(new Status(StatusCode.FailedPrecondition, $"Can't access cart storage. {ex}"));
            }
        }
        public async Task AddItemAsync(string userId, string productId, int quantity)
        {
            using (GlobalTracer.Instance.BuildSpan("AddItemAsync").StartActive())
            {
                Console.WriteLine($"AddItemAsync called with userId={userId}, productId={productId}, quantity={quantity}");

                try
                {
                    EnsureRedisConnected();

                    var db = redis.GetDatabase();

                    // Access the cart from the cache
                    var value = await db.HashGetAsync(userId, CART_FIELD_NAME);

                    Hipstershop.Cart cart;
                    if (value.IsNull)
                    {
                        cart        = new Hipstershop.Cart();
                        cart.UserId = userId;
                        cart.Items.Add(new Hipstershop.CartItem {
                            ProductId = productId, Quantity = quantity
                        });
                    }
                    else
                    {
                        cart = Hipstershop.Cart.Parser.ParseFrom(value);
                        var existingItem = cart.Items.SingleOrDefault(i => i.ProductId == productId);
                        if (existingItem == null)
                        {
                            cart.Items.Add(new Hipstershop.CartItem {
                                ProductId = productId, Quantity = quantity
                            });
                        }
                        else
                        {
                            existingItem.Quantity += quantity;
                        }
                    }

                    await db.HashSetAsync(userId, new[] { new HashEntry(CART_FIELD_NAME, cart.ToByteArray()) });
                }
                catch (Exception ex)
                {
                    throw new RpcException(new Status(StatusCode.FailedPrecondition, $"Can't access cart storage. {ex}"));
                }
                updateUserProfile();
            }
        }
Example #12
0
        public Task <Hipstershop.Cart> GetCartAsync(string userId)
        {
            using (GlobalTracer.Instance.BuildSpan("GetCartAsync").StartActive())
            {
                Console.WriteLine($"GetCartAsync called with userId={userId}");
                Hipstershop.Cart cart = null;
                if (!userCartItems.TryGetValue(userId, out cart))
                {
                    Console.WriteLine($"No carts for user {userId}");
                    return(Task.FromResult(emptyCart));
                }

                return(Task.FromResult(cart));
            }
        }
Example #13
0
        public Task <Hipstershop.Cart> GetCartAsync(string userId)
        {
            var transaction = Elastic.Apm.Agent.Tracer.CurrentTransaction;

            Hipstershop.Cart cart = null;
            return(transaction.CaptureSpan("GetCartAsync", ApiConstants.TypeDb, (s) => {
                Log.Information("GetCartAsync called with userId={userId}", userId);
                s.Labels["userId"] = userId;
                if (!userCartItems.TryGetValue(userId, out cart))
                {
                    Log.Warning("No carts for user {userId}", userId);
                    return Task.FromResult(emptyCart);
                }
                return Task.FromResult(cart);
            }));
        }
        public RedisCartStore(string redisAddress)
        {
            // Serialize empty cart into byte array.
            var cart = new Hipstershop.Cart();

            emptyCartBytes   = cart.ToByteArray();
            connectionString = $"{redisAddress},ssl=false,allowAdmin=true,connectRetry=5";

            redisConnectionOptions = ConfigurationOptions.Parse(connectionString);

            // Try to reconnect if first retry failed (up to 5 times with exponential backoff)
            redisConnectionOptions.ConnectRetry         = REDIS_RETRY_NUM;
            redisConnectionOptions.ReconnectRetryPolicy = new ExponentialRetry(100);

            redisConnectionOptions.KeepAlive = 180;
        }
        public RedisCartStore(string redisAddress)
        {
            // Serialize empty cart into byte array.
            var cart = new Hipstershop.Cart();

            emptyCartBytes   = cart.ToByteArray();
            connectionString = $"{redisAddress},ssl=false,allowAdmin=true,connectRetry=5";

            redisConnectionOptions = ConfigurationOptions.Parse(connectionString);

            // Try to reconnect if first retry failed (up to 5 times with exponential backoff)
            redisConnectionOptions.ConnectRetry         = REDIS_RETRY_NUM;
            redisConnectionOptions.ReconnectRetryPolicy = new ExponentialRetry(100);

            redisConnectionOptions.KeepAlive = 180;

            oneAgentSdk = OneAgentSdkFactory.CreateInstance();
            dbInfo      = oneAgentSdk.CreateDatabaseInfo("Cache", "Redis", ChannelType.TCP_IP, redisAddress);
        }
Example #16
0
        public async Task <Hipstershop.Cart> GetCartAsync(string userId)
        {
            Console.WriteLine($"GetCartAsync called with userId={userId}");

            try
            {
                Hipstershop.Cart cart = new Hipstershop.Cart();
                // Access cart from YSQL
                using (var conn = new NpgsqlConnection(ysqlconnectionString))
                {
                    conn.Open();
                    using (var command = new NpgsqlCommand("SELECT * FROM carts WHERE userid = @n", conn))
                    {
                        command.Parameters.AddWithValue("n", userId);
                        var reader = command.ExecuteReader();
                        int count  = 0;
                        cart.UserId = userId;
                        while (reader.Read())
                        {
                            count++;
                            Console.Out.WriteLine("get cart " + reader.GetString(2) + " q " + reader.GetInt32(3).ToString());
                            cart.Items.Add(new Hipstershop.CartItem {
                                ProductId = reader.GetString(2), Quantity = reader.GetInt32(3)
                            });
                        }
                        if (count == 0)
                        {
                            conn.Close();
                            return(new Hipstershop.Cart());
                        }
                    }
                    conn.Close();
                    return(cart);
                }
            }
            catch (Exception ex)
            {
                throw new RpcException(new Status(StatusCode.FailedPrecondition, $"Can't access cart storage. {ex}"));
            }
        }
Example #17
0
        public Task AddItemAsync(string userId, string productId, int quantity)
        {
            var transaction = Elastic.Apm.Agent.Tracer.CurrentTransaction;

            return(transaction.CaptureSpan("AddItemAsync", ApiConstants.TypeDb, (s) =>
            {
                s.Labels["userId"] = userId;
                s.Labels["productId"] = productId;
                s.Labels["quantity"] = quantity.ToString();
                Log.Information("AddItemAsync called with userId={userId}, productId={productId}, quantity={quantity}", userId, productId, quantity);
                var newCart = new Hipstershop.Cart
                {
                    UserId = userId,
                    Items = { new Hipstershop.CartItem {
                                  ProductId = productId, Quantity = quantity
                              } }
                };
                userCartItems.AddOrUpdate(userId, newCart,
                                          (k, exVal) =>
                {
                    // If the item exists, we update its quantity
                    var existingItem = exVal.Items.SingleOrDefault(item => item.ProductId == productId);
                    if (existingItem != null)
                    {
                        existingItem.Quantity += quantity;
                    }
                    else
                    {
                        exVal.Items.Add(new Hipstershop.CartItem {
                            ProductId = productId, Quantity = quantity
                        });
                    }

                    return exVal;
                });
                return Task.CompletedTask;
            }));
        }
Example #18
0
        public RedisCartStore(string redisAddress)
        {
            // Serialize empty cart into byte array.
            var cart = new Hipstershop.Cart();

            emptyCartBytes   = cart.ToByteArray();
            connectionString = $"{redisAddress},ssl=false,allowAdmin=true,connectRetry=5";

            redisConnectionOptions = ConfigurationOptions.Parse(connectionString);

            // Try to reconnect if first retry failed (up to 5 times with exponential backoff)
            redisConnectionOptions.ConnectRetry         = REDIS_RETRY_NUM;
            redisConnectionOptions.ReconnectRetryPolicy = new ExponentialRetry(100);

            redisConnectionOptions.KeepAlive = 180;

            getCartRequestCount = 0;

            badProductIdCart = new Hipstershop.Cart();
            cart.UserId      = "user";
            cart.Items.Add(new Hipstershop.CartItem {
                ProductId = "xxxxxdnexx", Quantity = 10
            });
        }
Example #19
0
        public async Task AddItemAsync(string userId, string productId, int quantity)
        {
            Console.WriteLine($"AddItemAsync called with userId={userId}, productId={productId}, quantity={quantity}");

            try
            {
                Hipstershop.Cart cart = new Hipstershop.Cart();
                int  count            = 0;
                bool existingitem     = false;
                bool emptycart        = true;

                // Access cart from YSQL
                using (var conn = new NpgsqlConnection(ysqlconnectionString))
                {
                    conn.Open();
                    using (var command = new NpgsqlCommand("SELECT * FROM carts WHERE userid = @n", conn))
                    {
                        command.Parameters.AddWithValue("n", userId);
                        var reader = command.ExecuteReader();
                        cart.UserId = userId;
                        while (reader.Read())
                        {
                            emptycart = false;
                            Console.Out.WriteLine("add to cart " + reader.GetString(2) + " q " + reader.GetInt32(3).ToString());
                            if (productId == reader.GetString(2))
                            {
                                count++;
                                existingitem = true;
                                quantity    += reader.GetInt32(3);
                                // ready to add new quantity to object
                                cart.Items.Add(new Hipstershop.CartItem {
                                    ProductId = reader.GetString(2), Quantity = quantity
                                });
                            }
                            else
                            {
                                // adding old quantity back into object
                                cart.Items.Add(new Hipstershop.CartItem {
                                    ProductId = reader.GetString(2), Quantity = reader.GetInt32(3)
                                });
                            }
                        }
                    }
                    conn.Close();
                }
                //cart is prepped
                if (existingitem)
                {
                    using (var conn = new NpgsqlConnection(ysqlconnectionString))
                    {
                        conn.Open();
                        using (var command = new NpgsqlCommand("UPDATE carts SET quantity = @q WHERE userId = @n AND productId = @p", conn))
                        {
                            command.Parameters.AddWithValue("n", userId);
                            command.Parameters.AddWithValue("p", productId);
                            command.Parameters.AddWithValue("q", quantity);

                            int nRows = command.ExecuteNonQuery();
                            Console.Out.WriteLine(String.Format("Number of rows updated={0}", nRows));
                        }
                        conn.Close();
                    }
                }
                else // new item
                {
                    if (emptycart)
                    {
                        // add new product and quantity into object
                        cart.Items.Add(new Hipstershop.CartItem {
                            ProductId = productId, Quantity = quantity
                        });
                    }
                    using (var conn = new NpgsqlConnection(ysqlconnectionString))
                    {
                        conn.Open();
                        cart.Items.Add(new Hipstershop.CartItem {
                            ProductId = productId, Quantity = quantity
                        });
                        using (var command = new NpgsqlCommand("INSERT INTO carts (userId, productId, quantity) VALUES (@n1, @p1, @q1)", conn))
                        {
                            command.Parameters.AddWithValue("n1", userId);
                            command.Parameters.AddWithValue("p1", productId);
                            command.Parameters.AddWithValue("q1", quantity);
                            int nRows = command.ExecuteNonQuery();
                            Console.Out.WriteLine(String.Format("Number of rows inserted={0}", nRows));
                        }
                        conn.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                throw new RpcException(new Status(StatusCode.FailedPrecondition, $"Can't access cart storage. {ex}"));
            }
        }
Example #20
0
        public async Task AddItemAsync(string userId, string productId, int quantity)
        {
            Console.WriteLine($"AddItemAsync called with userId={userId}, productId={productId}, quantity={quantity}");

            try
            {
                var db = redis.GetDatabase();

                // Access the cart from the cache
                var value = await db.HashGetAsync(userId, CART_FIELD_NAME);

                Hipstershop.Cart cart;
                if (value.IsNull)
                {
                    cart        = new Hipstershop.Cart();
                    cart.UserId = userId;
                    cart.Items.Add(new Hipstershop.CartItem {
                        ProductId = productId, Quantity = quantity
                    });
                }
                else
                {
                    cart = Hipstershop.Cart.Parser.ParseFrom(value);
                    var existingItem = cart.Items.SingleOrDefault(i => i.ProductId == productId);
                    if (existingItem == null)
                    {
                        cart.Items.Add(new Hipstershop.CartItem {
                            ProductId = productId, Quantity = quantity
                        });
                    }
                    else
                    {
                        existingItem.Quantity += quantity;
                    }
                }

                await db.HashSetAsync(userId, new[] { new HashEntry(CART_FIELD_NAME, cart.ToByteArray()) });

                // Attempt to access "external database" some percentage of the time
                if (_random.NextDouble() < EXTERNAL_DB_ACCESS_RATE)
                {
                    using (var span = _tracer.StartActiveSpan("Cart.DbQuery.UpdateCart", SpanKind.Client))
                    {
                        span
                        .SetAttribute("db.system", "postgres")
                        .SetAttribute("db.type", "postgres")
                        .SetAttribute("peer.service", EXTERNAL_DB_NAME + ":98321");

                        if (_random.NextDouble() < EXTERNAL_DB_ERROR_RATE)
                        {
                            span.SetAttribute("error", "true");
                        }

                        Thread.Sleep(TimeSpan.FromMilliseconds(_random.Next(0, EXTERNAL_DB_MAX_DURATION_MILLIS)));
                        span.End();
                    }
                }
            }
            catch (Exception ex)
            {
                throw new RpcException(new Grpc.Core.Status(Grpc.Core.StatusCode.FailedPrecondition, $"Can't access cart storage. {ex}"));
            }
        }