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 22 commits into
base: minor
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
14f8d62
feat(core): Add cleanupExpiredSessions method in SessionService
pujux Nov 20, 2024
94e8cae
docs: Fix docusaurus-theme-search-typesense package version
pujux Nov 20, 2024
129aada
docs: Update SessionService documentation and wording fix for Session…
pujux Nov 20, 2024
545eeaa
docs: Add how-to guide for creating expired session cleanup script
pujux Nov 20, 2024
69a1de0
fix(core): Include variant custom fields when duplicating a product (…
mschipperheyn Dec 18, 2024
8c6e48e
@Ankish76 has signed the CLA in vendure-ecommerce/vendure#3282
github-actions[bot] Dec 20, 2024
17c7d21
@ankitdev10 has signed the CLA in vendure-ecommerce/vendure#3288
github-actions[bot] Dec 21, 2024
7d462a0
@HerclasNido has signed the CLA in vendure-ecommerce/vendure#3298
github-actions[bot] Dec 27, 2024
0bf4186
chore: Add GPL exception for Vendure plugins (#3280)
michaelbromley Dec 30, 2024
ba3c875
refactor(payments-plugin): Use some instead of find (#3292)
twlite Dec 30, 2024
e61abe6
chore: Changed demo website (#3283)
oidt Dec 30, 2024
f362a4b
fix(common): Contract multiple sequential replacers to just one in no…
jezzzm Dec 30, 2024
95e9bcd
@xtul9 has signed the CLA in vendure-ecommerce/vendure#3309
github-actions[bot] Jan 7, 2025
cdde217
@markbmullins has signed the CLA in vendure-ecommerce/vendure#3308
github-actions[bot] Jan 9, 2025
82787cf
fix(admin-ui): Update Polish localization (#3309)
xtul9 Jan 9, 2025
b631781
fix(core): Improvements to Redis cache plugin (#3303)
jacobfrantz1 Jan 9, 2025
779ebd2
docs(elasticsearch-plugin): Changed the reference to shop-api (#3307)
oidt Jan 9, 2025
9bb155b
docs(elasticsearch-plugin): Added missing inStock field for SearchInp…
Winne4r Jan 9, 2025
4349ef8
fix(payments-plugin): Stripe plugin supports correct languageCode (#3…
HerclasNido Jan 9, 2025
889dd72
@wpplumber has signed the CLA in vendure-ecommerce/vendure#3313
github-actions[bot] Jan 10, 2025
55883df
Merge branch 'vendure-ecommerce:master' into feat/cleanup-expired-ses…
pujux Jan 13, 2025
0cd2a2b
fix(core): Run delete query directly for sessions
pujux Jan 14, 2025
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
5 changes: 5 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@ GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.

Additional permission under GNU GPL version 3 section 7:

An additional exception under section 7 of the GPL is included in the plugin-exception.txt file,
which allows you to distribute Vendure plugins (i.e. extensions) under a different license.

## Vendure Commercial License (VCL)

Alternatively, commercial and supported versions of the program - also known as
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ An open-source headless commerce platform built on [Node.js](https://nodejs.org)
### [www.vendure.io](https://www.vendure.io/)

* [Getting Started](https://docs.vendure.io/guides/getting-started/installation/): Get Vendure up and running locally in a matter of minutes with a single command
* [Live Demo](https://demo.vendure.io/)
* [Request Demo](https://vendure.io/demo)
* [Vendure Discord](https://www.vendure.io/community): Join us on Discord for support and answers to your questions

## Branches
Expand Down
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);
}
```
6 changes: 3 additions & 3 deletions docs/docs/guides/how-to/publish-plugin/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,9 @@ is using a compatible version of Vendure.

### License

Your plugin **must** use a license that is compatible with the GPL v3 license that Vendure uses. This means your package.json
file should include `"license": "GPL-3.0-or-later"`, and your repository should include a license file (usually named `LICENSE.txt`) containing the
[full text of the GPL v3 license](https://www.gnu.org/licenses/gpl-3.0.txt).
You are free to license your plugin as you wish. Although Vendure itself is licensed under the GPLv3, there is
a special exception for plugins which allows you to distribute them under a different license. See the
[plugin exception](https://github.com/vendure-ecommerce/vendure/blob/master/license/plugin-exception.txt) for more details.

## Publishing to npm

Expand Down
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