Storages

note

Storages - 图1

This help topic is in development and will be updated in the future.

There are two predefined storages: SessionStorageMemory, DirectoryStorage. And another composable storage: CacheStorage.

note

Storages - 图2

DirectoryStorage and CacheStorage are dependent on the io.ktor:ktor-server-sessions:$ktor_version artifact.

In this mode, you are just sending a Session Id instead of the actual session contents. This id is used to store its contents on the server side using a specific SessionStorage. This mode is used when you specify a second argument with a storage in the cookie or header methods.

Example:

  1. install(Sessions) {
  2. cookie<SampleSession>("SESSION_FEATURE_SESSION_ID", SessionStorageMemory()) {
  3. cookie.path = "/"
  4. }
  5. }

Custom SessionStorage

SessionStorage is in charge of storing and retrieving session payload. The interface is suspendable, so you can, and should if it is possible, transfer the data asynchronously.

The data is transferred as a stream and the callee will pass consumers and providers offering the binary payload, and the callee will be in charge of opening and closing those byte channels.

  1. interface SessionStorage {
  2. suspend fun write(id: String, provider: suspend (ByteWriteChannel) -> Unit)
  3. suspend fun invalidate(id: String)
  4. suspend fun <R> read(id: String, consumer: suspend (ByteReadChannel) -> R): R
  5. }

If the storage doesn’t provide a meaningful way to store information as a stream, you might want to use a simplified adaptor that just reads and writes it using ByteArray. It can also be used as an example to know how to deal with the API in its primitive stream-based version.

  1. abstract class SimplifiedSessionStorage : SessionStorage {
  2. abstract suspend fun read(id: String): ByteArray?
  3. abstract suspend fun write(id: String, data: ByteArray?): Unit
  4. override suspend fun invalidate(id: String) {
  5. write(id, null)
  6. }
  7. override suspend fun <R> read(id: String, consumer: suspend (ByteReadChannel) -> R): R {
  8. val data = read(id) ?: throw NoSuchElementException("Session $id not found")
  9. return consumer(ByteReadChannel(data))
  10. }
  11. override suspend fun write(id: String, provider: suspend (ByteWriteChannel) -> Unit) {
  12. return provider(CoroutineScope(Dispatchers.IO).reader(coroutineContext, autoFlush = true) {
  13. write(id, channel.readAvailable())
  14. }.channel)
  15. }
  16. }
  17. suspend fun ByteReadChannel.readAvailable(): ByteArray {
  18. val data = ByteArrayOutputStream()
  19. val temp = ByteArray(1024)
  20. while (!isClosedForRead) {
  21. val read = readAvailable(temp)
  22. if (read <= 0) break
  23. data.write(temp, 0, read)
  24. }
  25. return data.toByteArray()
  26. }