Serverpod Sessions#
ํ๋ง๋๋ก (๋น๊ฐ๋ฐ์์ฉ)#
์ธ์ (Session)์ ์๋ฒ๊ฐ ํ ๊ฐ์ง ์ผ์ ์ฒ๋ฆฌํ๋ ๋์ ๋ค๊ณ ๋ค๋๋ "์ถ์ ์ฆ ๊ฒธ ์์ ๊ฐ๋ฐฉ"์ด๋ผ๊ณ ๋ณด๋ฉด ๋ฉ๋๋ค. ์ด ๊ฐ๋ฐฉ ์์๋ ๋ฐ์ดํฐ๋ฒ ์ด์ค, ์บ์, ์ ์ฅ์, ๋ก๊ทธ ๊ฐ์ ๋๊ตฌ๊ฐ ๋ค์ด ์์ด, ์๋ฒ๊ฐ ์์ฒญ ํ๋๋ฅผ ๋๋ผ ๋๊น์ง ํ์ํ ๊ฒ๋ค์ ๊บผ๋ด ์๋๋ค. ๋ณดํต์ ์๋ฒ๊ฐ ์์์ ๊ฐ๋ฐฉ์ ์ฑ๊ฒจ์ฃผ๊ณ ๋๋๋ฉด ๋ฐ๋ฉํ์ง๋ง, ์ง์ ๋ง๋ ๊ฐ๋ฐฉ(InternalSession)์ ์ฌ๋์ด ์์ ๋ฐ๋ฉํด์ผ ํฉ๋๋ค. ์ด ๋ฌธ์๋ ๊ทธ ๊ฐ๋ฐฉ์ ์ธ์ ๋ง๋ค๊ณ ์ด๋ป๊ฒ ์ ๋๋ก ๋ซ๋์ง๋ฅผ ์ค๋ช ํฉ๋๋ค.
๋ฌด์์ยท์ธ์ (๋น๊ฐ๋ฐ์์ฉ)#
- ๋ฌด์์ ํด์ฃผ๋: ์ธ์ ์ ์ข ๋ฅ, ์์ฑยท์ข ๋ฃ(์๋ช ์ฃผ๊ธฐ), ์ง์ ๋ง๋๋ InternalSession, ๋ซํ๊ธฐ ์ง์ ์ฒ๋ฆฌ(cleanup) ๋ฐฉ๋ฒ์ ์ ๋ฆฌํด ์ค๋๋ค.
-
์ธ์ ์ฐ๋:
- ์ง์ (์๋์ผ๋ก) ์ธ์ ์ ๋ง๋ค์ด์ผ ํ ๋
- "์ธ์ ์ด ์ด๋ฏธ ๋ซํ๋ค"๋ ์ค๋ฅ๋ฅผ ๋ง๋ ์์ธ์ ์ฐพ์ ๋
- ์ธ์ ์ด ์ธ์ ๋ง๋ค์ด์ง๊ณ ์ธ์ ๋ซํ๋์ง ํ๋ฆ์ ์ดํดํ๊ณ ์ถ์ ๋
- ํต์ฌ ์ฃผ์: ์ง์ ๋ง๋ ์ธ์ ์ ๋ซ์ง ์์ผ๋ฉด ๋ฉ๋ชจ๋ฆฌ๊ฐ ์๊ณ ๊ธฐ๋ก(๋ก๊ทธ)๋ ๋จ์ง ์์ต๋๋ค. ๊ทธ๋์ "ํญ์ ๋ซ๊ธฐ"๊ฐ ์ค์ํฉ๋๋ค.
ํต์ฌ ์ฉ์ด (๋น๊ฐ๋ฐ์์ฉ)#
| ์ฉ์ด | ์ฌ์ด ์ค๋ช |
|---|---|
| Session(์ธ์ ) | ์๋ฒ๊ฐ ํ ์์ ์ ์ฒ๋ฆฌํ๋ ๋์ ์ฐ๋ ๋๊ตฌ ๋ฌถ์(๊ฐ๋ฐฉ). ๋๋๋ฉด ๋ฐ๋ฉ(๋ซ๊ธฐ)ํจ |
| InternalSession | ์ฌ๋์ด ์ง์ ๋ง๋ค๊ณ ์ง์ ๋ซ์์ผ ํ๋ ์ธ์ |
| lifecycle(์๋ช ์ฃผ๊ธฐ) | ์ธ์ ์ด ์๊ธฐ๊ณ ์ด์ ์๋ค๊ฐ ๋ซํ๋ ์ ์ฒด ํ๋ฆ |
| cleanup callback | ์ธ์ ์ด ๋ซํ๊ธฐ ์ง์ ์ ์๋์ผ๋ก ์คํ๋๋ ๋ง๋ฌด๋ฆฌ ์ฒ๋ฆฌ |
| StateError | ์ด๋ฏธ ๋ซํ ์ธ์ ์ ๋ค์ ์ฐ๋ ค ํ ๋ ๋๋ ์ค๋ฅ |
| future call | ๋์ค์(์ง์ฐ ํ) ์คํํ๋๋ก ์์ฝํ๋ ์์ . ๋ซํ ์ธ์ ์ ๋ถ์ก๋ ๋์ ์ฌ์ฉ |
A Session provides access to database, cache, storage, messages, passwords, and logging. The framework creates and closes sessions automatically; only InternalSession requires manual management.
Session types#
| Type | Created for | Lifetime |
|---|---|---|
| MethodCallSession | Endpoint methods | Single request |
| WebCallSession | Web server routes | Single request |
| MethodStreamSession | Stream methods | Stream duration |
| StreamingSession | WebSocket connections | Connection duration |
| FutureCallSession | Future calls | Task execution |
| InternalSession | Manual creation | Until closed |
Manual sessions (InternalSession)#
Always close in a finally block:
var session = await Serverpod.instance.createSession();
try {
await doWork(session);
} finally {
await session.close();
}
Unclosed sessions leak memory and never persist logs. Using a closed session throws StateError.
Cleanup callbacks#
session.addWillCloseListener((session) async {
// Runs just before session closes (all session types)
});
Common pitfall: using session after method returns#
Sessions close when the endpoint returns. Do not capture for later use:
// BAD โ session already closed when callback runs
Timer(Duration(seconds: 5), () => user.updateLastSeen(session));
Fix: Use a future call (session.serverpod.futureCalls.callWithDelay(...)) or create a new InternalSession inside the callback.