# Web::Session

[![Build Status](https://github.com/linagora/perl-Web-Session/actions/workflows/ci.yml/badge.svg)](https://github.com/linagora/perl-Web-Session/actions/workflows/ci.yml)

[Web::Session](https://metacpan.org/dist/Web-Session) is a fork of
[Apache::Session::Browseable](https://metacpan.org/dist/Apache-Session-Browseable),
which itself extends [Apache::Session](https://metacpan.org/dist/Apache-Session):
sessions are stored in a database and can be searched, listed and purged
through indexes (`searchOn()`, `searchOnExpr()`, `searchLt()`, `searchGt()`,
`get_key_from_all_sessions()`, `deleteIfLowerThan()`).

- **Fully compatible with Apache::Session**: every backend is an
  Apache::Session implementation (`tie %session, 'Web::Session::PgJSON', $id, $args`).
- **Includes many fixes still pending in Apache::Session::Browseable**: SQL
  injections, `deleteIfLowerThan()` rules, UTF-8 handling, Redis index
  cleanup, identifier quoting, performance of full scans, connection reuse...
- **Faster and more resilient**: connections are reused, round trips and
  commits are cut down, and a lost database or Redis server is detected and
  replaced instead of blocking or failing every session (see
  [Performance](#performance)).
- **Better tested**: the backends are tested in CI against real servers
  (PostgreSQL, MySQL, two MariaDB versions, Redis, OpenLDAP), with a shared
  SQL test suite and `EXPLAIN` checks that the documented indexes are really
  used.
- **Open to AI-assisted contributions**: pull requests written with the help
  of AI tools are welcome, as long as they come with tests and are reviewed
  like any other contribution.

It has been written to increase the performance of
[LemonLDAP::NG](https://lemonldap-ng.org).

## Backends

| Database   | Module                                                                            |
| ---------- | --------------------------------------------------------------------------------- |
| PostgreSQL | `Web::Session::PgJSON` (alias: `Web::Session::Postgres`), `Web::Session::Patroni` |
| MySQL      | `Web::Session::MySQLJSON` (alias: `Web::Session::MySQL`)                          |
| MariaDB    | `Web::Session::MariaDBJSON` (alias: `Web::Session::MariaDB`)                      |
| SQLite     | `Web::Session::SQLite`                                                            |
| Redis      | `Web::Session::Redis`                                                             |
| Cassandra  | `Web::Session::Cassandra`                                                         |
| LDAP       | `Web::Session::LDAP`                                                              |
| Files      | `Web::Session::File`                                                              |

Read the documentation of the chosen module to create the table and the
indexes: `perldoc Web::Session::PgJSON`, for example.

## Example

```perl
use Web::Session::PgJSON;

my $args = {
    DataSource => 'dbi:Pg:dbname=sessions',
    UserName   => $user,
    Password   => $password,
    Commit     => 1,    # needed by the connection pool (default)
};

# Use it like Apache::Session
tie my %session, 'Web::Session::PgJSON', undef, $args;
$session{uid} = 'dwho';
my $id = $session{_session_id};
untie %session;

# Search sessions
my $sessions =
  Web::Session::PgJSON->searchOn( $args, 'uid', 'dwho', '_utime' );

# Purge old sessions
Web::Session::PgJSON->deleteIfLowerThan( $args,
    { or => { _utime => time - 7200 } } );
```

## Performance

[LemonLDAP::NG](https://lemonldap-ng.org/) under a load test (30 requests/s
of logins, logouts and portal pages, sessions in PostgreSQL), with only the
PostgreSQL session store changed from Apache::Session::Browseable to the
connection pool of Web::Session:

|                                 | [Apache::Session::Browseable](https://metacpan.org/dist/Apache-Session-Browseable) | [Web::Session](https://metacpan.org/dist/Web-Session) |
| ------------------------------- | ---------------------------------------------------------------------------------- | ----------------------------------------------------- |
| PostgreSQL connections opened   | 10,282 (one per tied session)                                                      | almost none (pool)                                    |
| PostgreSQL CPU                  | 52% of a core                                                                      | 9% of a core                                          |
| Login, median / 99th percentile | 189 ms / 249 ms                                                                    | 127 ms / 166 ms                                       |

Access to one session (tie, read or write, untie) by one process, with the
database on the same host (Docker), a 60-key session and 3 indexed fields
for Redis, in microseconds (Apache::Session::Browseable 1.3.19 →
Web::Session):

| Backend        | create        | read        | update                 |
| -------------- | ------------- | ----------- | ---------------------- |
| PgJSON         | 6,200 → 190   | 5,900 → 130 | 6,300 → 240            |
| Patroni        | 6,700 → 1,000 | 6,200 → 150 | 6,600 → 990            |
| MySQLJSON      | 4,800 → 2,200 | 440 → 160   | unchanged (one commit) |
| Redis, `reuse` | 300 → 120     | 120 → 85    | 290 → 145              |
| Redis          | 430 → 270     | unchanged   | 410 → 310              |

Apache::Session::Browseable opens a PostgreSQL connection for each tied
session; Web::Session keeps them in a pool and saves the `ping`, the
transaction that protects nothing, and the second write of a new session.
With MySQL, MariaDB and Patroni, a write waits for the disk at commit: a new
session is now written with one commit instead of two, and a Patroni session
that was only read no longer waits for the disk. Redis commands are
pipelined, and with `reuse` the database is selected once. On a real
network, each round trip saved weighs more than on one host. Web::Session's
Redis updates also check for concurrent updates and merge them, which
Apache::Session::Browseable doesn't.

Searches and purge on 100,000 Redis sessions (the 9 indexed fields of a
production [LemonLDAP::NG](https://lemonldap-ng.org/)), Redis on the same
host, in seconds:

| Class method                                                | [Apache::Session::Browseable](https://metacpan.org/dist/Apache-Session-Browseable) | [Web::Session](https://metacpan.org/dist/Web-Session) |
| ----------------------------------------------------------- | ---------------------------------------------------------------------------------- | ----------------------------------------------------- |
| `get_key_from_all_sessions()`                               | 8.9                                                                                | 1.2                                                   |
| `searchOn()`, field not indexed                             | 8.8                                                                                | 1.1                                                   |
| `searchOnExpr()`, indexed field                             | 0.66                                                                               | 0.05                                                  |
| `deleteIfLowerThan()` (LLNG purge, 50,000 sessions deleted) | 18.2                                                                               | 2.9                                                   |
| `searchLt()`                                                | not available                                                                      | 1.6                                                   |

Apache::Session::Browseable sends a `TYPE` and a `GET` for each key, then
a command for each index entry and for each session to delete, one at a
time: about 480,000 round trips for this purge. Web::Session reads 1,000
keys per `SCAN` with `MGET` and pipelines the deletions: a few hundred round
trips. With 0.3 ms per
round trip on a real network, that purge would take about 2 minutes 30
seconds with Apache::Session::Browseable instead of a few seconds.

## Migrating from Apache::Session::Browseable

- Replace `Apache::Session::Browseable::` by `Web::Session::` in module
  names ([LemonLDAP::NG](https://lemonldap-ng.org/): `globalStorage`,
  `persistentStorage`...).
- `Postgres` and `MySQL` are now aliases of `PgJSON` and `MySQLJSON`:
  sessions are stored as JSON, indexes are expression indexes or generated
  columns. Tables created for the former column backends must be converted
  (see `perldoc Web::Session::Postgres` and `perldoc Web::Session::MySQL`).
- The Oracle, Informix, Sybase and PgHstore backends were removed.
- `Apache::Session::Serialize::JSON` and `Apache::Session::Generate::SHA256`
  are now `Web::Session::Serialize::JSON` and `Web::Session::Generate::SHA256`.

See [Changes](Changes) for the full list of changes.

## Installation

```
perl Build.PL
./Build
./Build test
./Build install
```

Run the tests through `./Build test` (or `prove -b` after `./Build`), not
`prove -l`: some modules use AutoLoader, and their autosplit files exist only
in `blib/`.

Tests of database backends run only when the database is available: see
`t/lib/SQLBackendTests.pm` and `.github/workflows/ci.yml` for the
environment variables (`PG_DSN`, `MYSQL_DSN`, `MARIADB_DSN`, `REDIS_URL`,
`LDAP_URL`...).

## License

This library is free software; you can redistribute it and/or modify it under
the same terms as Perl itself, either Perl version 5.10.1 or, at your option,
any later version of Perl 5 you may have available. See [COPYRIGHT](COPYRIGHT)
and [LICENSE](LICENSE).
