-
Notifications
You must be signed in to change notification settings - Fork 2.3k
docs(basics/controllers): clarify session variable usage, locking, best practices #14037
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
Open
joshtrichards
wants to merge
2
commits into
master
Choose a base branch
from
jtr/dev-sessions-clarifications
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+93
−47
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -212,87 +212,133 @@ Headers, files, cookies and environment variables can be accessed directly from | |
|
|
||
| } | ||
|
|
||
| Why should those values be accessed from the request object and not from the global array like $_FILES? Simple: `because it's bad practice <http://c2.com/cgi/wiki?GlobalVariablesAreBad>`_ and will make testing harder. | ||
| Why should those values be accessed from the request object and not from the global array like $_FILES? Simple: | ||
| `because it's bad practice <http://c2.com/cgi/wiki?GlobalVariablesAreBad>`_ and will make testing harder. | ||
|
|
||
| .. _controller-use-session: | ||
|
|
||
| Reading and writing session variables | ||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | ||
| Sessions and session variables | ||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | ||
|
|
||
| Introduction | ||
| ~~~~~~~~~~~~ | ||
|
|
||
| Sessions allow your application to store data specific to a particular user across multiple HTTP | ||
| requests. Variables are saved server-side and tied to a unique session identifier managed via a | ||
| browser cookie. | ||
|
|
||
| Nextcloud uses PHP’s native session handling but adds several performance optimizations and a | ||
| transparent encryption layer via the ``CryptoSessionData`` class. Data written through the | ||
| ``OCP\ISession`` API benefits from these optimizations and is automatically encrypted at rest. | ||
|
|
||
| .. danger:: | ||
| Never use the PHP superglobal ``$_SESSION``. The superglobal bypasses Nextcloud's encryption and | ||
| lifecycle management, leading to race conditions or lost data. | ||
|
|
||
| To set, get or modify session variables, the ISession object has to be injected into the controller. | ||
| Basic usage | ||
| ~~~~~~~~~~~ | ||
|
|
||
| Nextcloud will read existing session data at the beginning of the request lifecycle and close the session afterwards. This means that in order to write to the session, the session has to be opened first. This is done implicitly when calling the set method, but would close immediately afterwards. To prevent this, the session has to be explicitly opened by calling the reopen method. | ||
| Inject the :class:`OCP\\ISession` object via your controller's constructor. | ||
|
|
||
| Alternatively, you can use the ``#[UseSession]`` attribute to automatically open and close the session for you. | ||
| A more complete example: | ||
|
|
||
| .. code-block:: php | ||
| :emphasize-lines: 2,7 | ||
|
|
||
| <?php | ||
| namespace OCA\MyApp\Controller; | ||
|
|
||
| use OCP\AppFramework\Controller; | ||
| use OCP\AppFramework\Http\Attribute\UseSession; | ||
| use OCP\AppFramework\Http\Response; | ||
| use OCP\ISession; | ||
| use OCP\IRequest; | ||
|
|
||
| class PageController extends Controller { | ||
|
|
||
| #[UseSession] | ||
| public function writeASessionVariable(): Response { | ||
| // ... | ||
| public function __construct( | ||
| $appName, | ||
| IRequest $request, | ||
| private ISession $session // PHP 8 property promotion | ||
| ) { | ||
| parent::__construct($appName, $request); | ||
| } | ||
|
|
||
| } | ||
|
|
||
| .. note:: The ``#[UseSession]`` was added in Nextcloud 26 and requires PHP 8.0 or later. If your app targets older releases and PHP 7.x then use the deprecated ``@UseSession`` annotation. | ||
| // Simple (existing) variable retrieval | ||
| public function simpleReads(): Response { | ||
| $this->session->get('last_visit'); | ||
| return new Response(); | ||
| } | ||
|
|
||
| .. code-block:: php | ||
| :emphasize-lines: 2 | ||
| // Default: Implicit locking per write. Good for single operations. | ||
| public function simpleWrite(): Response { | ||
| $this->session->set('last_visit', time()); | ||
| return new Response(); | ||
| } | ||
|
|
||
| /** | ||
| * @UseSession | ||
| */ | ||
| public function writeASessionVariable(): Response { | ||
| // .... | ||
| // Optimization: Keeps session open for the entire method. | ||
| #[UseSession] | ||
| public function batchUpdate(): Response { | ||
| $this->session->set('theme', 'dark'); | ||
| $this->session->set('font_size', '14px'); | ||
| $this->session->remove('fallback_theme'); | ||
| return new Response(); | ||
| } | ||
| } | ||
|
|
||
| When to use ``#[UseSession]`` | ||
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | ||
|
|
||
| In case the session may be read and written by concurrent requests of your application, keeping the session open during your controller method execution may be required to ensure that the session is locked and no other request can write to the session at the same time. When reopening the session, the session data will also get updated with the latest changes from other requests. Using the annotation will keep the session lock for the whole duration of the controller method execution. | ||
| By default, Nextcloud uses an **on-demand locking strategy**: it closes the session immediately after the | ||
| request starts to allow high concurrency, then briefly re-opens and closes it only during a ``set()`` or | ||
| ``remove()`` call. This default "close-early" behavior works for infrequent and standalone writing events | ||
| and prevents one request from blocking another. Developers do not need to do anything special to enable | ||
| this behavior. | ||
|
|
||
| For additional information on how session locking works in PHP see the article about `PHP Session Locking: How To Prevent Sessions Blocking in PHP requests <https://ma.ttias.be/php-session-locking-prevent-sessions-blocking-in-requests/>`_. | ||
| However, in more advanced scenarios (e.g., calling ``set()`` five times in immediate succession) Nextcloud's | ||
| default behavior means the session will open and close five times. This introduces significant I/O | ||
| overhead (even if it does minimize locking). For these cases, Nextcloud supports an optional method-level | ||
| attribute: ``#[UseSession]``. This attribute ensures the session is opened once at the start of your method and | ||
| closed at the end, providing efficiency and correct locking in complex workflows. | ||
|
|
||
| Then session variables can be accessed like this: | ||
| Use the ``#[UseSession]`` attribute when: | ||
|
|
||
| .. note:: The session is closed automatically for writing, unless you add the ``#[UseSession]`` attribute! | ||
| * **Multiple Writes**: You are calling ``set()`` or ``remove()`` multiple times in one method (prevents | ||
| I/O overhead from repeated open/close cycles). | ||
| * **Reference Manipulation**: You need the session to remain open for complex logic or to ensure data | ||
| consistency throughout the method. | ||
| * **Regenerating session ids**: You are elevating a user's privileges (e.g. a valid share password is | ||
| entered and the "access granted" status is stored in the session) or the user performs a sensitive | ||
| alteration (e.g. password change). | ||
|
|
||
| .. code-block:: php | ||
| .. note:: | ||
| The ``#[UseSession]`` attribute was introduced in Nextcloud 26. Previously, this feature used the | ||
| ``@UseSession`` annotation, which is now deprecated but otherwise equivalent. | ||
|
|
||
| <?php | ||
| namespace OCA\MyApp\Controller; | ||
| Performance and concurrency | ||
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~ | ||
|
|
||
| use OCP\ISession; | ||
| use OCP\IRequest; | ||
| use OCP\AppFramework\Controller; | ||
| use OCP\AppFramework\Http\Attribute\UseSession; | ||
| use OCP\AppFramework\Http\Response; | ||
| PHP natively locks the session file while it is open for writing. If a controller keeps a session open | ||
| unnecessarily, it may block other requests from the same user (e.g., parallel browser tabs or AJAX calls), | ||
| resulting in delays or timeouts. | ||
|
|
||
| class PageController extends Controller { | ||
| By keeping sessions closed except during the brief window of an actual write, Nextcloud ensures a | ||
| responsive, multi-tab, and highly concurrent experience. For more technical background, see `PHP Session | ||
| Locking and How to Prevent It <https://ma.ttias.be/php-session-locking-prevent-sessions-blocking-php-requests/>`_. | ||
|
|
||
| private ISession $session; | ||
| .. warning:: | ||
|
|
||
| public function __construct($appName, IRequest $request, ISession $session) { | ||
| parent::__construct($appName, $request); | ||
| $this->session = $session; | ||
| } | ||
| If your controller method aggressively keeps sessions open, it may block other requests from the same user | ||
| or process (for example, a second browser tab, AJAX request, or background job), resulting in delays or | ||
| deadlocks. | ||
|
|
||
| #[UseSession] | ||
| public function writeASessionVariable(): Response { | ||
| // read a session variable | ||
| $value = $this->session['value']; | ||
| **Available ISession Methods:** | ||
|
|
||
| // write a session variable | ||
| $this->session['value'] = 'new value'; | ||
| } | ||
| The entire ``OCP\\ISession`` API: | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Shouldn't duplicate this list here. Just link to the file instead. |
||
|
|
||
| } | ||
| - ``set(key, value)``, ``get(key)``, ``exists(key)``, ``remove(key)``, ``clear()`` | ||
| - ``reopen()``, ``close()`` | ||
| - ``getId()``, ``regenerateId()`` | ||
|
|
||
| See https://github.com/nextcloud/server/blob/master/lib/public/ISession.php for specifics. | ||
|
|
||
| Setting cookies | ||
| ^^^^^^^^^^^^^^^ | ||
|
|
||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Additionally when regenerating session id within the called code.
This should e.g. be done when a user enterd a share password and the "access granted" is now stored in the session, as e.g. done by public shares and talk:
https://github.com/nextcloud/spreed/blob/e1e82531a00c675b4e98c340cea5712401f46b4b/lib/Controller/PageController.php#L230-L231
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Does it make much difference for regenerating?
https://github.com/nextcloud/server/blob/ba99550d06e8c810de4f79874bbf71cf08f13fa0/lib/private/Session/Internal.php#L114-L115
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Added a bulletpoint