A Python-based gRPC service that provides real-time stock price streaming functionality through server-side streaming. The service generates random stock price updates every 5 seconds for various stock symbols.
https://grpc-envoy.unified-origin.comhttps://grpc-envoy.qa.akamai.comThis service supports both native gRPC and gRPC-Web protocols:
50053 (stock-ticker-service direct)grpcurl 8080 (Envoy proxy) / 443 (HTTPS production)curl with custom protobuf encodingWhen using grpcurl to access services through Envoy proxy on port 443, you need to include the x-service-target header:
# List available services (requires x-service-target header)
grpcurl -insecure -servername grpc-envoy.qa.akamai.com \
-H 'x-service-target: stock-ticker' \
localhost:443 list
# Call a service method (requires x-service-target header)
grpcurl -insecure -servername grpc-envoy.qa.akamai.com \
-H 'x-service-target: stock-ticker' \
-d '{"symbol": "AAPL"}' \
localhost:443 stockticker.StockTickerService/GetCurrentPrice
Why the header? Since each backend service has its own gRPC reflection endpoint, the x-service-target header tells Envoy which service to route requests to. This enables grpcurl to discover the service schema before making the actual call.
Note: The -servername flag is required when using localhost with TLS to match the certificate's domain name.
All requests use:
- Content-Type: application/grpc-web+proto
- X-Grpc-Web: 1
- X-User-Agent: grpc-web-javascript/0.1
First, create a helper script to generate protobuf messages:
cat > /tmp/stock_grpc_helper.py << 'EOF'
import struct
import sys
def encode_varint(value):
result = []
while value >= 0x80:
result.append((value & 0x7F) | 0x80)
value >>= 7
result.append(value)
return bytes(result)
def encode_string_field(field_number, value):
string_bytes = value.encode('utf-8')
tag = (field_number << 3) | 2 # Wire type 2 (length-delimited)
return encode_varint(tag) + encode_varint(len(string_bytes)) + string_bytes
def create_grpc_frame(message):
return b'\x00' + struct.pack('>I', len(message)) + message
def create_get_symbols_request():
return create_grpc_frame(b'') # Empty message
def create_get_price_request(symbol):
message = encode_string_field(1, symbol)
return create_grpc_frame(message)
def create_subscribe_request(symbol, client_id):
message = encode_string_field(1, symbol) + encode_string_field(2, client_id)
return create_grpc_frame(message)
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: python stock_grpc_helper.py <command> [args...]")
sys.exit(1)
command = sys.argv[1]
if command == "get_symbols":
data = create_get_symbols_request()
elif command == "get_price":
if len(sys.argv) != 3:
print("Usage: python stock_grpc_helper.py get_price <symbol>")
sys.exit(1)
data = create_get_price_request(sys.argv[2])
elif command == "subscribe":
if len(sys.argv) != 4:
print("Usage: python stock_grpc_helper.py subscribe <symbol> <client_id>")
sys.exit(1)
data = create_subscribe_request(sys.argv[2], sys.argv[3])
else:
print(f"Unknown command: {command}")
sys.exit(1)
sys.stdout.buffer.write(data)
EOF
Add this helper script to decode gRPC-Web responses into readable protobuf:
cat > /tmp/parse_stock_response.py << 'EOF'
import struct
import sys
import subprocess
import os
def _decode_with_protoc(body: bytes, message_type: str, proto_file: str):
"""Helper: attempt to decode a protobuf message using protoc; fall back to hex."""
try:
proto_dir = os.path.dirname(proto_file)
proto_name = os.path.basename(proto_file)
# Handle both absolute and relative paths
if not os.path.isabs(proto_file):
# If relative path, try to resolve from current working directory
proto_dir = os.path.abspath(proto_dir) if proto_dir else os.getcwd()
result = subprocess.run([
"protoc",
f"--proto_path={proto_dir}",
"--decode", message_type,
proto_name
], input=body, capture_output=True, cwd=proto_dir)
if result.returncode == 0:
print(result.stdout.decode('utf-8'))
else:
print(f"protoc decode error: {result.stderr.decode('utf-8').strip()}")
print(f"Raw hex: {body.hex()}")
except FileNotFoundError:
print("protoc not found; raw hex:")
print(body.hex())
def parse_grpc_web_response(response_file, message_type, proto_file="stock-ticker-service/proto/stock_ticker.proto"):
"""Parse a unary gRPC-Web response file and display frames + decoded protobuf."""
with open(response_file, "rb") as f:
data = f.read()
if len(data) < 5:
print("Response too short")
return
i = 0
frame_index = 0
while i < len(data):
if i + 5 > len(data):
break
flag = data[i]
length = struct.unpack(">I", data[i+1:i+5])[0]
i += 5
if i + length > len(data):
break
body = data[i:i+length]
i += length
if flag == 0: # data frame
print(f"=== Frame {frame_index} (Data) ===")
_decode_with_protoc(body, message_type, proto_file)
elif flag == 0x80: # trailers
print(f"=== Frame {frame_index} (Trailers) ===")
trailer_text = body.decode('utf-8', errors='ignore')
for line in trailer_text.split('\r\n'):
if line.strip():
print(line.strip())
else:
print(f"Unknown frame flag 0x{flag:02x} length={length}")
frame_index += 1
def parse_streaming_response(response_file, message_type, proto_file="stock-ticker-service/proto/stock_ticker.proto"):
"""Parse a server-streaming gRPC-Web response file (multiple data frames, optional trailer)."""
# NOTE: Trailers (grpc-status / grpc-message) appear ONLY if the server ends the stream.
# If you terminate with `timeout` or Ctrl-C you won't get trailer frame 0x80.
with open(response_file, "rb") as f:
data = f.read()
i = 0
update_index = 0
while i < len(data):
if i + 5 > len(data):
break
flag = data[i]
length = struct.unpack(">I", data[i+1:i+5])[0]
i += 5
if i + length > len(data):
break
body = data[i:i+length]
i += length
if flag == 0: # data frame
print(f"=== Stock Update {update_index} ===")
_decode_with_protoc(body, message_type, proto_file)
update_index += 1
elif flag == 0x80: # trailer frame
print("=== Stream Trailers ===")
trailer_text = body.decode('utf-8', errors='ignore')
for line in trailer_text.split('\r\n'):
if line.strip():
print(line.strip())
print("(End of stream)\n")
else:
print(f"Unknown frame flag 0x{flag:02x} length={length}")
if __name__ == "__main__":
if len(sys.argv) < 3:
print("Usage: python parse_stock_response.py <response_file> <message_type> [--streaming]")
print("Examples:")
print(" python parse_stock_response.py /tmp/resp.bin stockticker.GetSymbolsResponse")
print(" python parse_stock_response.py /tmp/resp.bin stockticker.StockUpdate --streaming")
sys.exit(1)
response_file = sys.argv[1]
message_type = sys.argv[2]
streaming = "--streaming" in sys.argv
if streaming:
parse_streaming_response(response_file, message_type)
else:
parse_grpc_web_response(response_file, message_type)
EOF
Retrieve a list of all stock symbols available for tracking.
gRPC Definition:
rpc GetAvailableSymbols(GetSymbolsRequest) returns (GetSymbolsResponse);
message GetSymbolsRequest {}
message GetSymbolsResponse {
repeated StockSymbol symbols = 1;
}
message StockSymbol {
string symbol = 1; // Symbol code (e.g., "AAPL")
string company_name = 2; // Company name (e.g., "Apple Inc.")
string sector = 3; // Business sector
double base_price = 4; // Starting price for simulation
}
# List all available services
grpcurl -plaintext localhost:50053 list
# Get available symbols - simplest method
grpcurl -plaintext localhost:50053 stockticker.StockTickerService/GetAvailableSymbols
# Via HTTPS proxy (production) - requires x-service-target header
grpcurl -insecure -servername grpc-envoy.qa.akamai.com \
-H 'x-service-target: stock-ticker' \
localhost:443 stockticker.StockTickerService/GetAvailableSymbols
# Create the request
python3 /tmp/stock_grpc_helper.py get_symbols > /tmp/get_symbols.bin
# Send the request and save response
curl -s -X POST \
https://grpc-envoy.qa.akamai.com/stockticker.StockTickerService/GetAvailableSymbols \
-H "Content-Type: application/grpc-web+proto" \
-H "X-Grpc-Web: 1" \
-H "X-User-Agent: grpc-web-javascript/0.1" \
-H "x-service-target: stock-ticker" \
--data-binary @/tmp/get_symbols.bin \
--output /tmp/get_symbols_response.bin
# Parse the response
python3 /tmp/parse_stock_response.py /tmp/get_symbols_response.bin stockticker.GetSymbolsResponse
Sample Response:
{
"symbols": [
{
"symbol": "AKAM",
"companyName": "Akamai Technologies Inc.",
"sector": "Technology",
"basePrice": 75.30
},
{
"symbol": "AAPL",
"companyName": "Apple Inc.",
"sector": "Technology",
"basePrice": 230.50
},
{
"symbol": "GOOGL",
"companyName": "Alphabet Inc.",
"sector": "Technology",
"basePrice": 250.75
}
]
}
Get the current price and market data for a specific stock symbol.
gRPC Definition:
rpc GetCurrentPrice(GetPriceRequest) returns (GetPriceResponse);
message GetPriceRequest {
string symbol = 1;
}
message GetPriceResponse {
StockUpdate current_price = 1;
bool success = 2;
string error_message = 3;
}
message StockUpdate {
string symbol = 1; // Stock symbol
double price = 2; // Current price
double change = 3; // Price change from previous update
double change_percent = 4; // Percentage change
int64 timestamp = 5; // Unix timestamp
int64 volume = 6; // Trading volume (simulated)
string market_status = 7; // "OPEN", "CLOSED", "PRE_MARKET", "AFTER_HOURS"
}
# Get current price for AAPL
grpcurl -plaintext -d '{"symbol": "AAPL"}' \
localhost:50053 stockticker.StockTickerService/GetCurrentPrice
# Get prices for different stocks
grpcurl -plaintext -d '{"symbol": "GOOGL"}' localhost:50053 stockticker.StockTickerService/GetCurrentPrice
grpcurl -plaintext -d '{"symbol": "TSLA"}' localhost:50053 stockticker.StockTickerService/GetCurrentPrice
# Via HTTPS proxy (production) - requires x-service-target header
grpcurl -insecure -servername grpc-envoy.qa.akamai.com \
-H 'x-service-target: stock-ticker' \
-d '{"symbol": "AAPL"}' \
localhost:443 stockticker.StockTickerService/GetCurrentPrice
# Get current price for AAPL
python3 /tmp/stock_grpc_helper.py get_price "AAPL" > /tmp/get_price.bin
curl -s -X POST \
https://grpc-envoy.qa.akamai.com/stockticker.StockTickerService/GetCurrentPrice \
-H "Content-Type: application/grpc-web+proto" \
-H "X-Grpc-Web: 1" \
-H "X-User-Agent: grpc-web-javascript/0.1" \
-H "x-service-target: stock-ticker" \
--data-binary @/tmp/get_price.bin \
--output /tmp/get_price_response.bin
# Parse the response
python3 /tmp/parse_stock_response.py /tmp/get_price_response.bin stockticker.GetPriceResponse
Sample Response:
{
"currentPrice": {
"symbol": "AAPL",
"price": 267.33,
"change": 3.53,
"changePercent": 1.34,
"timestamp": "1761754300",
"volume": 919948,
"marketStatus": "AFTER_HOURS"
},
"success": true
}
Subscribe to real-time stock price updates for a specific symbol. This endpoint uses server-side streaming to continuously send price updates every 5 seconds.
gRPC Definition:
rpc SubscribeToTicker(SubscribeRequest) returns (stream StockUpdate);
message SubscribeRequest {
string symbol = 1; // Stock symbol (e.g., "AAPL")
string client_id = 2; // Unique client identifier
}
message StockUpdate {
string symbol = 1; // Stock symbol
double price = 2; // Current price
double change = 3; // Price change from previous update
double change_percent = 4; // Percentage change
int64 timestamp = 5; // Unix timestamp
int64 volume = 6; // Trading volume (simulated)
string market_status = 7; // "OPEN", "CLOSED", "PRE_MARKET", "AFTER_HOURS"
}
# Subscribe to AAPL updates (use timeout to limit stream duration)
timeout 30s grpcurl -plaintext -d '{"symbol": "AAPL", "client_id": "test_client_123"}' \
localhost:50053 stockticker.StockTickerService/SubscribeToTicker
# Subscribe to different stocks
timeout 15s grpcurl -plaintext -d '{"symbol": "TSLA", "client_id": "client_456"}' \
localhost:50053 stockticker.StockTickerService/SubscribeToTicker
# Via HTTPS proxy (production) - requires x-service-target header
timeout 30s grpcurl -insecure -servername grpc-envoy.qa.akamai.com \
-H 'x-service-target: stock-ticker' \
-d '{"symbol": "AAPL", "client_id": "test_client_123"}' \
localhost:443 stockticker.StockTickerService/SubscribeToTicker
# Note: Server streaming works best with grpcurl
# curl example for reference (may not stream properly):
python3 /tmp/stock_grpc_helper.py subscribe "AAPL" "web_client_123" > /tmp/subscribe.bin
# This requires HTTP/2 and may not work as expected with curl
timeout 30s curl -s -N -X POST \
https://grpc-envoy.qa.akamai.com/stockticker.StockTickerService/SubscribeToTicker \
-H "Content-Type: application/grpc-web+proto" \
-H "X-Grpc-Web: 1" \
-H "X-User-Agent: grpc-web-javascript/0.1" \
-H "x-service-target: stock-ticker" \
--data-binary @/tmp/subscribe.bin \
--output /tmp/subscribe_response.bin
# For streaming, parse with --streaming flag
python3 /tmp/parse_stock_response.py /tmp/subscribe_response.bin stockticker.StockUpdate --streaming
# RECOMMENDED: Use grpcurl (Method B) for reliable streaming
"""
Why you might NOT see grpc-status / grpc-message with the curl streaming example:
1. Indefinite Stream: SubscribeToTicker is a long-lived stream. The server keeps sending updates and does not finish on its own, so trailers (grpc-status/grpc-message) are never sent until it decides to close.
2. Forced Termination: Using `timeout 30s` kills the client connection before the server ends the stream, preventing trailer delivery.
3. Parser Limitation (fixed now): The previous streaming parser only decoded data frames and ignored trailer frames. The updated parser handles flag 0x80 and prints trailers when present.
4. Envoy / HTTP/2 Behavior: gRPC-Web trailers are encoded as a final 0x80 frame, not standard HTTP headers. They only appear when the stream is properly closed.
How to observe trailers:
• Use the new SYMBOL:COUNT suffix (e.g. AAPL:5) supported by the server to terminate after COUNT updates.
• OR run without `timeout` and wait for a server-driven completion (not typical for infinite feeds).
• OR future enhancement: add a dedicated proto field (e.g. max_updates) for explicit control.
Example to force natural termination and see trailers:
```bash
python3 /tmp/stock_grpc_helper.py subscribe "AAPL:5" "web_client_123" > /tmp/subscribe_limited.bin
curl -s -N -X POST \
https://grpc-envoy.qa.akamai.com/stockticker.StockTickerService/SubscribeToTicker \
-H "Content-Type: application/grpc-web+proto" \
-H "X-Grpc-Web: 1" \
-H "X-User-Agent: grpc-web-javascript/0.1" \
-H "x-service-target: stock-ticker" \
--data-binary @/tmp/subscribe_limited.bin \
--output /tmp/subscribe_limited_response.bin -k
python3 /tmp/parse_stock_response.py /tmp/subscribe_limited_response.bin stockticker.StockUpdate --streaming
Expected parser tail:
=== Stream Trailers ===
grpc-status: 0
grpc-message: OK
(End of stream)
"""
**Sample Streaming Response:**
```json
{
"symbol": "AAPL",
"price": 251.99,
"change": -3.69,
"changePercent": -1.44,
"timestamp": "1761754311",
"volume": 970018,
"marketStatus": "AFTER_HOURS"
}
{
"symbol": "AAPL",
"price": 244.59,
"change": -7.40,
"changePercent": -2.94,
"timestamp": "1761754312",
"volume": 1119725,
"marketStatus": "AFTER_HOURS"
}
{
"symbol": "AAPL",
"price": 250.77,
"change": 6.18,
"changePercent": 2.53,
"timestamp": "1761754317",
"volume": 1582710,
"marketStatus": "AFTER_HOURS"
}
JavaScript gRPC-Web Client Example:
// For proper streaming support in browsers
const request = new SubscribeRequest();
request.setSymbol('AAPL');
request.setClientId('browser_client_' + Date.now());
const stream = client.subscribeToTicker(request);
stream.on('data', (response) => {
console.log('Stock Update:', {
symbol: response.getSymbol(),
price: response.getPrice(),
change: response.getChange(),
changePercent: response.getChangePercent(),
volume: response.getVolume(),
marketStatus: response.getMarketStatus(),
timestamp: new Date(response.getTimestamp() * 1000)
});
});
stream.on('error', (err) => {
console.error('Stream error:', err);
});
stream.on('end', () => {
console.log('Stream ended');
});
Here's a complete script that demonstrates the full workflow:
#!/bin/bash
# stock_ticker_automation.sh
ENDPOINT="https://grpc-envoy.qa.akamai.com"
CLIENT_ID="demo_client_$(date +%s)"
echo "=== Stock Ticker Service Automation Demo ==="
echo "Using client ID: $CLIENT_ID"
# Step 1: Get available stock symbols
echo "1. Getting available stock symbols..."
python3 /tmp/stock_grpc_helper.py get_symbols > /tmp/get_symbols.bin
curl -s -X POST "$ENDPOINT/stockticker.StockTickerService/GetAvailableSymbols" \
-H "Content-Type: application/grpc-web+proto" \
-H "X-Grpc-Web: 1" \
-H "X-User-Agent: grpc-web-javascript/0.1" \
-H "x-service-target: stock-ticker" \
--data-binary @/tmp/get_symbols.bin \
--output /tmp/get_symbols_response.bin
python3 /tmp/parse_stock_response.py /tmp/get_symbols_response.bin stockticker.GetSymbolsResponse
echo
# Step 2: Get current price for AAPL
echo "2. Getting current price for AAPL..."
python3 /tmp/stock_grpc_helper.py get_price "AAPL" > /tmp/get_price_aapl.bin
curl -s -X POST "$ENDPOINT/stockticker.StockTickerService/GetCurrentPrice" \
-H "Content-Type: application/grpc-web+proto" \
-H "X-Grpc-Web: 1" \
-H "X-User-Agent: grpc-web-javascript/0.1" \
-H "x-service-target: stock-ticker" \
--data-binary @/tmp/get_price_aapl.bin \
--output /tmp/get_price_aapl_response.bin
python3 /tmp/parse_stock_response.py /tmp/get_price_aapl_response.bin stockticker.GetPriceResponse
echo
# Step 3: Get current price for GOOGL
echo "3. Getting current price for GOOGL..."
python3 /tmp/stock_grpc_helper.py get_price "GOOGL" > /tmp/get_price_googl.bin
curl -s -X POST "$ENDPOINT/stockticker.StockTickerService/GetCurrentPrice" \
-H "Content-Type: application/grpc-web+proto" \
-H "X-Grpc-Web: 1" \
-H "X-User-Agent: grpc-web-javascript/0.1" \
-H "x-service-target: stock-ticker" \
--data-binary @/tmp/get_price_googl.bin \
--output /tmp/get_price_googl_response.bin
python3 /tmp/parse_stock_response.py /tmp/get_price_googl_response.bin stockticker.GetPriceResponse
echo
# Step 4: Get current price for TSLA
echo "4. Getting current price for TSLA..."
python3 /tmp/stock_grpc_helper.py get_price "TSLA" > /tmp/get_price_tsla.bin
curl -s -X POST "$ENDPOINT/stockticker.StockTickerService/GetCurrentPrice" \
-H "Content-Type: application/grpc-web+proto" \
-H "X-Grpc-Web: 1" \
-H "X-User-Agent: grpc-web-javascript/0.1" \
-H "x-service-target: stock-ticker" \
--data-binary @/tmp/get_price_tsla.bin \
--output /tmp/get_price_tsla_response.bin
python3 /tmp/parse_stock_response.py /tmp/get_price_tsla_response.bin stockticker.GetPriceResponse
echo
# Step 5: Subscribe to AAPL updates for 15 seconds using grpcurl (recommended)
echo "5. Subscribing to AAPL real-time updates for 15 seconds..."
echo " (Using grpcurl for reliable streaming)"
timeout 15s grpcurl -insecure -servername grpc-envoy.qa.akamai.com \
-H 'x-service-target: stock-ticker' \
-d "{\"symbol\": \"AAPL\", \"client_id\": \"$CLIENT_ID\"}" \
localhost:443 stockticker.StockTickerService/SubscribeToTicker
echo
# Step 6: Get current price for AKAM
echo "6. Getting current price for AKAM..."
python3 /tmp/stock_grpc_helper.py get_price "AKAM" > /tmp/get_price_akam.bin
curl -s -X POST "$ENDPOINT/stockticker.StockTickerService/GetCurrentPrice" \
-H "Content-Type: application/grpc-web+proto" \
-H "X-Grpc-Web: 1" \
-H "X-User-Agent: grpc-web-javascript/0.1" \
-H "x-service-target: stock-ticker" \
--data-binary @/tmp/get_price_akam.bin \
--output /tmp/get_price_akam_response.bin
python3 /tmp/parse_stock_response.py /tmp/get_price_akam_response.bin stockticker.GetPriceResponse
echo
echo "=== Stock Ticker Demo Complete ==="
All responses are in gRPC-Web format: - First 5 bytes: gRPC frame header (compression flag + 4-byte length) - Remaining bytes: Protobuf message data - Trailers: gRPC status and message headers
chmod +x /tmp/stock_grpc_helper.py
chmod +x /tmp/parse_stock_response.py
chmod +x stock_ticker_automation.sh
# Create the helper scripts first
python3 /tmp/stock_grpc_helper.py get_symbols > /tmp/test.bin
# Test protobuf parsing
curl -s -X POST https://grpc-envoy.qa.akamai.com/stockticker.StockTickerService/GetAvailableSymbols \
-H "Content-Type: application/grpc-web+proto" \
-H "X-Grpc-Web: 1" \
-H "X-User-Agent: grpc-web-javascript/0.1" \
-H "x-service-target: stock-ticker" \
--data-binary @/tmp/test.bin \
--output /tmp/test_response.bin
python3 /tmp/parse_stock_response.py /tmp/test_response.bin stockticker.GetSymbolsResponse
# Run the full automation
./stock_ticker_automation.sh
The protobuf parser will show readable output like:
=== Frame 0 (Data) ===
symbols {
symbol: "AKAM"
company_name: "Akamai Technologies Inc."
sector: "Technology"
base_price: 75.3
}
symbols {
symbol: "AAPL"
company_name: "Apple Inc."
sector: "Technology"
base_price: 230.5
}
=== Frame 1 (Trailers) ===
grpc-status:0
grpc-message:
For streaming updates:
=== Stock Update 0 ===
symbol: "AAPL"
price: 251.99
change: -3.69
change_percent: -1.44
timestamp: 1761754311
volume: 970018
market_status: "AFTER_HOURS"
=== Stock Update 1 ===
symbol: "AAPL"
price: 244.59
change: -7.4
change_percent: -2.94
timestamp: 1761754312
volume: 1119725
market_status: "AFTER_HOURS"
This automation script demonstrates: 1. ✅ Get available stock symbols 2. ✅ Check current prices for multiple stocks 3. ✅ Subscribe to real-time price updates 4. ✅ Handle streaming data with proper timeouts