Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Document ways to cleanup expired sessions #3221

Open
wants to merge 4 commits into
base: minor
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions docs/docs/guides/how-to/expired-session-cleanup/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
---
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should have a more general topic of "how to run scheduled tasks" with a general explanation of the problem and solution and then the session cleanup as the main example. In future we can then add more examples like cleaning up abandoned orders.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

good idea! should I put that into the "Developer Guide" section under "Advanced Topics" just like the "Migrating from v1" topic?
image

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, good idea 👍

title: 'Expired Session Cleanup'
---

# Expired Session Cleanup

As noted in [SessionService](/reference/typescript-api/services/session-service), sessions are not automatically deleted when expired. This means that if you have a large number of sessions, you may need to clean them up periodically to avoid clogging up your database.

This guide aims to demonstrate how to create [Stand-alone CLI Scripts](/guides/developer-guide/stand-alone-scripts/) to automate the process of cleaning up expired sessions.

## Code

This code bootstraps the Vendure Worker, then retrieves the `SessionService` and calls the `cleanupExpiredSessions` method on it, completely removing all expired sessions from the database. It can be easily run from the command-line or scheduled to run periodically.

```ts title="src/expired-session-cleanup.ts"
import { bootstrapWorker, Logger, SessionService, RequestContextService } from '@vendure/core';
import { config } from './vendure-config';

const loggerCtx = 'ExpiredSessionCleanup';

if (require.main === module) {
cleanupExpiredSessions()
.then(() => process.exit(0))
.catch(err => {
Logger.error(err, loggerCtx);
process.exit(1);
});
}

async function cleanupExpiredSessions() {
Logger.info('Session cleanup started.', loggerCtx);

// Bootstrap an instance of the Vendure Worker
const { app } = await bootstrapWorker(config);

// Retrieve the SessionService
const sessionService = app.get(SessionService);

// Create a RequestContext for administrative tasks
const ctx = await app.get(RequestContextService).create({
apiType: 'admin',
});

// Call the cleanup function
await sessionService.cleanupExpiredSessions(ctx);

Logger.info('Session cleanup completed.', loggerCtx);
}
```
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,18 @@ object for permissions data, it can become a bottleneck to go to the database an
SQL query each time. Therefore, we cache the session data only perform the SQL query once and upon
invalidation of the cache.

The Vendure default from v3.1+ is to use a the <a href='/reference/typescript-api/auth/default-session-cache-strategy#defaultsessioncachestrategy'>DefaultSessionCacheStrategy</a>, which delegates
The Vendure default from v3.1+ is to use the <a href='/reference/typescript-api/auth/default-session-cache-strategy#defaultsessioncachestrategy'>DefaultSessionCacheStrategy</a>, which delegates
to the configured <a href='/reference/typescript-api/cache/cache-strategy#cachestrategy'>CacheStrategy</a> to store the session data. This should be suitable
for most use-cases.

:::note

If you are using v3.1 or later, you should not normally need to implement a custom `SessionCacheStrategy`,
If you are using v3.1 or later, you should normally not need to implement a custom `SessionCacheStrategy`,
since this is now handled by the <a href='/reference/typescript-api/auth/default-session-cache-strategy#defaultsessioncachestrategy'>DefaultSessionCacheStrategy</a>.

:::

Prior to v3.1, the default was to use the <a href='/reference/typescript-api/auth/in-memory-session-cache-strategy#inmemorysessioncachestrategy'>InMemorySessionCacheStrategy</a>, which is fast but suitable for
Prior to v3.1, the default was to use the <a href='/reference/typescript-api/auth/in-memory-session-cache-strategy#inmemorysessioncachestrategy'>InMemorySessionCacheStrategy</a>, which is fast but only suitable for
single-instance deployments.

:::info
Expand Down
17 changes: 16 additions & 1 deletion docs/docs/reference/typescript-api/services/session-service.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,19 @@ import MemberDescription from '@site/src/components/MemberDescription';

## SessionService

<GenerationInfo sourceFile="packages/core/src/service/services/session.service.ts" sourceLine="28" packageName="@vendure/core" />
<GenerationInfo sourceFile="packages/core/src/service/services/session.service.ts" sourceLine="44" packageName="@vendure/core" />

Contains methods relating to <a href='/reference/typescript-api/entities/session#session'>Session</a> entities.

:::note

Sessions are neither automatically deleted when expired nor cleaned up periodically by Vendure. The How-to guide
[Expired Session Cleanup](/guides/how-to/expired-session-cleanup/) demonstrates how to create a [Stand-alone CLI
Script](/guides/developer-guide/stand-alone-scripts/) which calls the [cleanupExpiredSessions](#cleanupexpiredsessions)
method to automate this process.

:::

```ts title="Signature"
class SessionService implements EntitySubscriberInterface {
constructor(connection: TransactionalConnection, configService: ConfigService, orderService: OrderService)
Expand All @@ -27,6 +36,7 @@ class SessionService implements EntitySubscriberInterface {
setActiveChannel(serializedSession: CachedSession, channel: Channel) => Promise<CachedSession>;
deleteSessionsByUser(ctx: RequestContext, user: User) => Promise<void>;
deleteSessionsByActiveOrderId(ctx: RequestContext, activeOrderId: ID) => Promise<void>;
cleanupExpiredSessions(ctx: RequestContext) => Promise<void>;
}
```
* Implements: <code>EntitySubscriberInterface</code>
Expand Down Expand Up @@ -86,6 +96,11 @@ Deletes all existing sessions for the given user.
<MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, activeOrderId: <a href='/reference/typescript-api/common/id#id'>ID</a>) => Promise&#60;void&#62;`} />

Deletes all existing sessions with the given activeOrder.
### cleanupExpiredSessions

<MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>) => Promise&#60;void&#62;`} since="3.1.0" />

Deletes all expired sessions.


</div>
2 changes: 1 addition & 1 deletion docs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
"@docusaurus/preset-classic": "^3.4.0",
"@mdx-js/react": "^3.0.0",
"clsx": "^1.2.1",
"docusaurus-theme-search-typesense": "^0.12.0-0",
"docusaurus-theme-search-typesense": "^0.22.0",
"prism-react-renderer": "^1.3.5",
"react": "^18.0.0",
"react-dom": "^18.0.0"
Expand Down
Loading
Loading