tursodatabase / libsql

libSQL is a fork of SQLite that is both Open Source, and Open Contributions.
https://turso.tech/libsql
MIT License
11.53k stars 286 forks source link

I keep getting `HRANA_WEBSOCKET_ERROR: WebSocket was closed` #1203

Open Tomperez98 opened 8 months ago

Tomperez98 commented 8 months ago

From time to time my server is unable to connect to turso database due to this error: sqlalchemy.exc.DatabaseError: (sqlite3.DatabaseError) HRANA_WEBSOCKET_ERROR: WebSocket was closed

This is the sqlalchemy engine configuration

self.db_engine = create_engine(
                url=f"sqlite+{db_url}/?authToken={db_auth_token}",
                echo=False,
                connect_args={"timeout": 60},
            )

dependencies

libsql-client==0.3.0
    # via sqlalchemy-libsql
sqlalchemy==2.0.28
    # via sqlalchemy-libsql
sqlalchemy-libsql==0.1.0
jsardev commented 7 months ago

Same here, we did setup everything according to Turso docs, but the app stops working after some time (not sure after what period of time tho). Restart fixes the issue.

tmlnv commented 4 months ago

Same with me

CarlosBueno99 commented 4 months ago

same

Thandden commented 4 months ago

Also have the same issue

badbye commented 3 months ago

same issue

devtanna commented 3 months ago

Same issue here, this was not happening before :( Is the issue that the websocket needs to be "kept-alive"? Not sure what the best practices are for starting a keep-alive thread in sqlalchemy

devtanna commented 3 months ago

Adding the following param pool_pre_ping fixed it for me 🙂

create_engine(
  url=f"...",
  pool_pre_ping=True
)
doanhat commented 1 month ago

I had the same issue, this works for me :

import os
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import QueuePool
from dotenv import load_dotenv
from sqlalchemy.ext.declarative import declarative_base
load_dotenv()

# Database setup
TURSO_DATABASE_URL = os.getenv("TURSO_DATABASE_URL")
TURSO_AUTH_TOKEN = os.getenv("TURSO_AUTH_TOKEN")

# Construct special SQLAlchemy URL for Turso
SQLALCHEMY_DATABASE_URL = f"sqlite+{TURSO_DATABASE_URL}/?authToken={TURSO_AUTH_TOKEN}&secure=true"

engine = create_engine(
    SQLALCHEMY_DATABASE_URL,
    poolclass=QueuePool,
    pool_size=5,
    max_overflow=10,
    pool_timeout=30,
    pool_recycle=1800,
    connect_args={"check_same_thread": False},
    echo=True
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

# Dependency
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()