extends Node
var client : NakamaClient
var session : NakamaSession
var socket : NakamaSocket
var username = "example"
var play_service
func _ready():
if Engine.has_singleton("GodotPlayGamesServices"):
play_service = Engine.get_singleton("GodotPlayGamesServices")
play_service.init(true, true, true, "id")
play_service.connect("_on_sign_in_success", self, "ConnectToNakama")
play_service.connect("_on_sign_in_failed", self, "_on_sign_in_failed")
play_service.signIn() # <-
func _on_sign_in_failed(status:int) -> void:
pass
func ConnectToNakama(account_id:String) -> void:
var split = account_id.split('"')
var id = str(split[11])
print(id)
print(username)
client = Nakama.create_client('defaultkey', "ip", 7351,
'http', 3)
session = yield(client.authenticate_device_async(id, username), 'completed')
if session.is_exception():
print("connection has failed " + session.exception.message)
return
socket = Nakama.create_socket_from(client)
yield(socket.connect_async(session), "completed")
print("Connected!")
Server version: 3.14.0+e2df3a29
Godot version: 3.5.1
I get this error code:
DEBUG === Freeing request 1 01-15 22:52:00.542 20046 20263 I godot : === Nakama : DEBUG === Request 1 returned response code: 404, RPC code: 5, error: Not Found 01-15 22:52:00.542 20046 20263 I godot : connection has failed Not Found
I double checked evrything but I can't find the problem help much aprecciated
I've fixed the issue with the help of someone. You just have to change the port from 7351 to 7350 because 7351 is for admins
Related
dear community
I've tried to execute async def in FastAPI app.
the workflow is crate FastAPI service to recieve from end-user requests and send it to another service such as DB Writer service.
first, I've create async def for send request with aiosonic library
Here's the code
import aiosonic
from aiosonic.timeout import Timeouts
async def db_writer_requests(arrival_input, prediction_out) :
client = aiosonic.HTTPClient()
timeouts_settings = Timeouts(sock_connect = 10,sock_read = 10)
await client.post('http://127.0.0.1:8082/api/motor/writer/test1',
headers = {'Content-Type' : 'application/json'},
json = arrival_input,
timeouts = timeouts_settings)
client.shutdown()
Here's main app
#app.post('/api/motor/test')
async def manager_api(raw_input:arrival_requests) :
depart_json = dict(raw_input)
inc_preds, model_error = await predict_requests(depart_json)
if (inc_preds == None) or (inc_preds['status_code'] != 200) :
return inc_preds if model_error == None else model_error
else :
mlid = uuid.uuid4()
pred_output = model_output(
predict_uuid = str(mlid),
net_premium = str(inc_preds["result"]["data"]["net_premium"]),
car_repair = str(inc_preds["result"]["data"]["car_repair"]),
place_repair = str(inc_preds["result"]["data"]["place_repair"]),
insurer_tier = str(inc_preds["result"]["data"]["insurer_tier"])
)
send_msg = good_response_msg(
status = 'OK',
status_code = 200,
result = data(
data = pred_output
)
)
await db_writer_requests(depart_json,dict(pred_output))
return send_msg
when I've tried to send request.
case 1 I've not to use "await", the program not send request to service and not show any response in endpoint service.
case 2 I've use await it worked normally, but if endpoint service not available the main service shown "Internal Server Error".
Thank you for Advance
I'm trying to use access tokens from #azure/identity to connect to azure sql using mssql (which uses tedious behind the scenes). The access tokens don't seem to work as is (quite similar to python - more on this later).
I have the following code:
const identity = require("#azure/identity")
function getConfig(accessToken){
var config = {
"authentication": {
"type": "azure-active-directory-access-token",
"options": {
"token": accessToken
}
},
"server": "dbserver.database.windows.net",
"options": {
"encrypt": true,
"database": "dbname",
}
};
return config;
}
const cred = new identity.DefaultAzureCredential();
const token = await cred.getToken("https://database.windows.net/.default")
const conf = getConfig(token.token)
let pool = await sql.connect(conf)
This always fails with "Login failed for user ''".
I have the following python code which does exactly the same:
def get_token():
creds = identity.DefaultAzureCredential()
token = creds.get_token("https://database.windows.net/.default")
tokenb = bytes(token.token, "UTF-8")
exptoken = b''
for i in tokenb:
exptoken += bytes({i})
exptoken += bytes(1)
tokenstruct = struct.pack("=i", len(exptoken)) + exptoken
return tokenstruct
def execute_query():
access_token = get_token()
print(access_token)
sql_server_name = "db-server"
sql_server_db = "database_name"
SQL_COPT_SS_ACCESS_TOKEN = 1256
connString = f"Driver={{ODBC Driver 17 for SQL Server}};SERVER={sql_server_name}.database.windows.net;DATABASE={sql_server_db}"
conn = pyodbc.connect(connString, attrs_before={
SQL_COPT_SS_ACCESS_TOKEN: access_token})
cursor = conn.cursor()
cursor.execute("SELECT * from SYSOBJECTS")
row = cursor.fetchone()
while row:
print(row)
row = cursor.fetchone()
This works perfectly. I've also noticed the following:
If I take the access token from the node version (printed by console.log) and pass it to the python code in please of access_token, I get the same error from python (Login failed for user '').
If I pass the access token from javascript and pass it to the python code for token.token (in get_token), then it works perfectly.
So I'm guessing the binary padding and packing thing that's working for python needs to be done for the node code to work. Is there some way of doing this? Or is there some better way to pass an access token from azure-identity to tedious?
Doh... I was using node-mssql which is the abandoned 0.0.1 library. Switching to mssql (v6.3.1) uses a recent version of tedious, and the access token works directly.
I'm a newbie to snowflake and trying to connect to the db using python but when executing the code i get this error "snowflake.connector.errors.ProgrammingError: 251005: User is empty"
import snowflake.connector
ctx = snowflake.connector.connect(
username = 'xxx',
password = 'xxxx',
account = 'xxxx'
)
cs = ctx.cursor()
try:
cs.execute(''' some query''')
one_row = cs.fetchone()
print(one_row[0])
finally:
cs.close()
ctx.close()
You should use "user" parameter instead of "username". Here's sample:
con = snowflake.connector.connect(
user='XXXX',
password='XXXX',
account='XXXX'
)
Please check: https://docs.snowflake.com/en/user-guide/python-connector-example.html#setting-session-parameters
Also, it's case sensitive (I had the same error message with USER)
I'm trying to make a dedicated server and a client with godot, I can connect to the server through internet, but when I make an RPC, I get this error :
ERROR: Node not found: gamestate
At: scene/main/node.cpp:1382
ERROR: _process_get_node: Failed to get path from RPC: gamestate
At: core/io/multiplayer_api.cpp:248
ERROR: Invalid packet received. Requested node was not found.
At: core/io/multiplayer_api.cpp:194
Server :
func _client_connected(id):
print('Client ' + str(id) + ' is connected')
var newClient = load("res://remote_client.tscn").instance()
newClient.set_name(str(id))
get_tree().get_root().add_child(newClient)
remote func _register_player_to_server(id, info):
players_server[id] = info
Client :
func connect_to_server(player_nickname, ip):
self_data.name = player_nickname
get_tree().connect('connected_to_server', self, '_connected_to_server')
var peer = NetworkedMultiplayerENet.new()
if ip == null or ip == '':
peer.create_client(DEFAULT_IP, DEFAULT_PORT)
else:
peer.create_client(ip, DEFAULT_PORT)
get_tree().set_network_peer(peer)
func _connected_to_server():
players[get_tree().get_network_unique_id()] = self_data
print("here")
rpc_id(1, '_register_player_to_server', get_tree().get_network_unique_id(), self_data)
print("wtf")
The _conneccted_to_server() func should call the _register_player_to_server() func in the server which then stores the value info of players.
Note that client is in a singleton named gamestate and that the error shows up in the server's console.
My nodes weren't on the path (thus the error).
I am using the following python script to test an application that is running on an AWS instance,
import sys
import requests
import logging
import random
from datetime import datetime
import threading
import os
import time
logger = logging.getLogger('Intrudx')
handle = logging.FileHandler('Intrudx.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
handle.setFormatter(formatter)
logger.addHandler(handle)
logger.setLevel(logging.INFO)
loop_count = int(sys.argv[1])
sleep_time = int(sys.argv[2])
# CHECKING THE HEARTBEAT
def heartbeat(SessionID, SiteID):
logger.info("Starting heartbeat thread")
try:
heart_url = 'http://ec2-instance-address.com/license/heartbeat'
heart_result = requests.post(heart_url, json={
"SessionID":str(SessionID),
"SiteID" : str(SiteID)
})
if heart_result.status_code is 500:
logger.error("Heartbeat Failed with 500")
return "We Got 500"
response_text = heart_result.json()["ResponseText"]
logger.info("Heartbeat: "+str(response_text))
except Exception as e:
logger.error("Heartbeat Failed"+str(e))
# FINDING THE SERVER IP
def ip(SessionID):
logger.info("Starting get server info thread")
try:
get_server_url = 'http://ec2-instance-address.com/server/getStreamingServer'
get_server_result = requests.post(get_server_url, json={"SessionID": str(SessionID)})
result_code = get_server_result.status_code
if result_code is 500:
logger.error("GetStreamingServerInfo: " + "Failed")
return "We Got 500"
response_text = get_server_result.json()["ResponseText"]
logger.info("GetStreamingServerInfo: " + str(response_text))
except Exception as e:
logger.error("GetStreamingServerInfo: " + str(e))
def main():
for i in range(loop_count):
# LOGIN
try:
login_url = 'http://ec2-instance-address.com/user/login'
login_result = requests.post(login_url, json={
"AccountName": "Account1",
"UserID": "user2",
"UserPassword": "test"
})
result_code = login_result.status_code
if result_code is 500:
logger.error("Login: "+"Failed")
return "We Got 500"
SessionID = login_result.json()["SessionID"]
response_text = login_result.json()["ResponseText"]
logger.info("Login: "+str(response_text)+": "+ str(SessionID))
print(str(SessionID)+str(response_text))
except Exception as e:
result_code = str(e)
logger.error("Login: "+str(e))
# GET NEW SITE
try:
get_new_site_url = 'http://ec2-instance-address.com/license/getNewSite'
get_new_site_result = requests.post(get_new_site_url, json={"SessionID": str(SessionID)})
result_code = get_new_site_result.status_code
if result_code is 500:
logger.error("Login: " + "Failed")
return "We Got 500"
response_text = get_new_site_result.json()["ResponseText"]
site_id = get_new_site_result.json()["NewSiteID"]
logger.info("getNewSite: "+str(response_text)+": "+str(site_id))
except Exception as e:
result_code = str(e)
logger.error("getNewSite"+str(e))
# STARTING HEARTBEAT THREAD
try:
threading.Thread(target=heartbeat(SessionID, site_id), args=(SessionID, site_id,)).start()
except Exception as e:
logger.error("Problem starting thread: "+str(e))
# STARTING GET SERVER INFO THREAD
try:
threading.Thread(target=ip(SessionID), args=(SessionID)).start()
except Exception as e:
logger.error("Problem while starting Get Server Info Thread"+str(e))
This script is using just one user, creating one session/connection with the server to make API calls.
In a similar way, I want to test the application with 50 or 100 different users (With different accounts/credentials) connected to the server making API calls. Like 50 or 100 users are concurrently using the application. So I can ensure that the application is handling 50 users properly.
How can I do this kind of testing with a script?
Update: Most of the routes are hidden, they need #login_required.
I recommend you try Bees With Machine Guns. Its a python script that will launch micro EC2 instances and send many requests from these instances to your application. This will simulate a large surge in traffic for performance testing.
I heard about it from AWS training videos on CBT Nuggets. The instructor was effective using it to trigger auto scaling and load test his configuration.
Good luck.
You could try our little tool k6 also: https://github.com/loadimpact/k6
You script the behaviour of the virtual users using JavaScript, so it is quite easy to get 50 different users logging in with different credentials. Would look something like this (this code is going to need debugging though :)
import http from "k6/http";
let login_url = "http://ec2-instance-address.com/user/login";
let get_new_site_url = "http://ec2-instance-address.com/license/getNewSite";
let credentials = [
{ "account": "Account1", "username": "joe", "password": "secret" },
{ "account": "Account2", "username": "jane", "password": "verysecret" }
];
export default function() {
let session_id = doLogin();
let response = doGetNewSite(session_id);
let response_text = response["ResponseText"];
let new_site_id = response["NewSiteID"];
for (i = 0; i < loop_count; i++) {
// do heartbeat stuff?
}
}
function doLogin() {
let index = Math.floor(Math.random() * credentials.length);
let post_body = {
"AccountName": credentials[index]["account"],
"UserID": credentials[index]["username"],
"UserPassword": credentials[index]["password"]
};
let http_headers = { "Content-Type": "application/json" };
let res = http.post(login_url, JSON.stringify(post_body), { headers: http_headers });
check(res, {
"Response code is 200": (r) => r.status == 200,
"Login successful": (r) => JSON.parse(r.body).hasOwnProperty("SessionID")
});
return JSON.parse(res.body)["SessionID"];
}
function doGetNewSite(session_id) {
let http_headers = { "Content-Type": "application/json" };
let post_body = { "SessionID": session_id };
let res = http.post(get_new_site_url, JSON.strjngify(post_body), { headers: http_headers });
check(res, {
"Status code was 200": (r) => r.status == 200,
"Got response text": (r) => JSON.parse(r.body).hasOwnProperty("ResponseText"),
"Got new site id": (r) => JSON.parse(r.body).hasOwnProperty("NewSiteID")
});
return JSON.parse(res.body);
}