Skip to content
Closed
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
6 changes: 3 additions & 3 deletions .claude/skills/lightning-server.md
Original file line number Diff line number Diff line change
Expand Up @@ -427,11 +427,11 @@ Server.typedEndpoint.test("pathArg", auth = auth, input = RequestData(...))

⚠️ **Duplicate UploadEarlyEndpoint Declarations**

If you create multiple instances of `UploadEarlyEndpoint` (e.g., in different modules or endpoints), they will have *
If you create multiple instances of `GlobalUploadEndpoints` (e.g., in different modules or endpoints), they will have *
*conflicting declarations for how `ServerFile` is serialized**. This causes runtime serialization errors that manifest
as `500 Internal Server Error` responses in tests, even though the code compiles successfully.

**Solution:** Only instantiate `UploadEarlyEndpoint` once in your server definition:
**Solution:** Only instantiate `GlobalUploadEndpoints` once in your server definition:

```kotlin
object Server : ServerBuilder() {
Expand All @@ -445,7 +445,7 @@ object Server : ServerBuilder() {
}
```

If you need multiple upload endpoints, reuse the same `UploadEarlyEndpoint` instance or use different endpoint patterns.
If you need multiple upload endpoints, reuse the same `GlobalUploadEndpoints` instance or use different endpoint patterns.

## Common Patterns

Expand Down
4 changes: 2 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,12 +107,12 @@ calls encode their output.

#### Common Testing Pitfalls

**Duplicate UploadEarlyEndpoint declarations**: If you create multiple instances of `UploadEarlyEndpoint` (e.g., in
**Duplicate UploadEarlyEndpoint declarations**: If you create multiple instances of `GlobalUploadEndpoints` (e.g., in
different modules or test files), they will have conflicting declarations for how `ServerFile` is serialized. This
causes runtime serialization errors that manifest as `500 Internal Server Error` responses in tests, even though the
code compiles successfully.

**Solution**: Only instantiate `UploadEarlyEndpoint` once in your server definition and reference it from tests. Do not
**Solution**: Only instantiate `GlobalUploadEndpoints` once in your server definition and reference it from tests. Do not
create separate instances for testing.

## Architecture
Expand Down
2 changes: 1 addition & 1 deletion REVIEW-GUIDE-5.4.md
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,7 @@ Opt-in. Nothing outside the modules depends on them, the demo doesn't use them,
## 3. Fallout (skim)

- **`@Queryable`** replaces `@Serializable @GenerateDataClassPaths` on all models (last commit, `9f39ebba1`). Mechanical; it relies on `@Queryable` implying `@Serializable`.
- **`context(ServerRuntime)` → `context(Engine)`** for setup-only APIs: settings, `Runtime`, `ResolvedPath`, `Authentication(...)`, `testAuth`, SDK generation, `DatabaseTableRegistration`, `UploadEarlyEndpoint`. `SDK.Runtime` now extends `EngineBase`.
- **`context(ServerRuntime)` → `context(Engine)`** for setup-only APIs: settings, `Runtime`, `ResolvedPath`, `Authentication(...)`, `testAuth`, SDK generation, `DatabaseTableRegistration`, `GlobalUploadEndpoints`. `SDK.Runtime` now extends `EngineBase`.
- **Interceptor ports:** `AccessLogInterceptor` and `OriginRecording` are `ExecutionInterceptor`s (id suffix now from `execution.logicalId`). CORS, Gzip and SecurityHeaders are physical `HttpInterceptor`/`WebSocketInterceptor`s. `RateLimitInterceptor` is both an `ExecutionInterceptor`, which charges each request a client made (bulk parts and virtual sockets included, internal calls excluded), and an `HttpInterceptor`, which adds its headers.
- **`ApiWebSocketHandler` builder lambdas** became `suspend context(ServerRuntime) Connection.() -> …`. `ConnectionWrapper` is now local. `ModelRestUpdatesWebsocket` closes with reason text.
- **Small moves:** `ApiHttpHandler` factories moved verbatim to [ApiHttpHandler.builder.kt](typed/src/main/kotlin/com/lightningkite/lightningserver/typed/ApiHttpHandler.builder.kt). `CacheMutex` lost its stored server. `MetaEndpoints` bulk uses `serverRuntime.handle`.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import com.lightningkite.lightningserver.definition.builder.*
import com.lightningkite.lightningserver.demo.endpoints.*
import com.lightningkite.lightningserver.demo.models.User
import com.lightningkite.lightningserver.files.Files
import com.lightningkite.lightningserver.files.UploadEarlyEndpoint
import com.lightningkite.lightningserver.files.GlobalUploadEndpoints
import com.lightningkite.lightningserver.http.*
import com.lightningkite.lightningserver.pathing.PathSpec0
import com.lightningkite.lightningserver.pathing.fullUrl
Expand Down Expand Up @@ -130,7 +130,7 @@ object Server : ServerBuilder() {


val user = path.path("user") include UserEndpoints
val uploadEarly = path.path("upload") module UploadEarlyEndpoint(files, database, Runtime.Constant(listOf()))
val uploadEarly = path.path("upload") module GlobalUploadEndpoints(files, database, Runtime.Constant(listOf()))

/**
* Basic Examples - Simple HTTP endpoints demonstrating fundamental patterns.
Expand Down
14 changes: 7 additions & 7 deletions docs-guide/drafts/files.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

Lightning Server provides a unified abstraction for file storage through `ExternalFileSystem`. Files are
addressed server-side as `ExternalFile` values and serialized to clients as `ServerFile` URLs. The
`UploadEarlyEndpoint` handles the standard upload workflow where a client uploads a file before
`GlobalUploadEndpoints` handles the standard upload workflow where a client uploads a file before
referencing it in a subsequent API call.

## Imports
Expand Down Expand Up @@ -43,7 +43,7 @@ Converting between the two:
- `fileObject.serverFile` — wraps the `ExternalFile`'s internal URL in a `ServerFile`
(available everywhere; no runtime needed).
- `serverFile.fileObject` — resolves a `ServerFile` back to a `ExternalFile` using the contextual
serializer registered by `UploadEarlyEndpoint`. Requires a `ServerRuntime` context; throws
serializer registered by `GlobalUploadEndpoints`. Requires a `ServerRuntime` context; throws
`IllegalStateException` if no serializer is configured.

## Declaring the Files Setting
Expand All @@ -69,20 +69,20 @@ object FileServer : ServerBuilder() {
}
```

> **Singleton rule:** Instantiate `UploadEarlyEndpoint` exactly **once** per server. The endpoint
> **Singleton rule:** Instantiate `GlobalUploadEndpoints` exactly **once** per server. The endpoint
> registers a contextual serializer for `ServerFile`; a second instance registers a conflicting
> serializer and causes runtime serialization errors (500 responses) that are difficult to trace.
> See also: CLAUDE.md testing pitfalls.

`UploadEarlyEndpoint` constructor parameters (all optional beyond `files` and `database`):
`GlobalUploadEndpoints` constructor parameters (all optional beyond `files` and `database`):

| Parameter | Default | Purpose |
|---|---|---|
| `fileScanner` | — | `Runtime<List<FileScanner>>` — scanners run before files leave jail |
| `jailFilePath` | `"upload-jail"` | subdirectory for freshly-uploaded, unscanned files |
| `filePath` | `"uploaded"` | subdirectory for scanned, ready-to-use files |
| `expiration` | `1.days` | how long upload tokens remain valid |
| `authOptions` | `noAuth` | require authentication on the upload endpoint |
| `auth` | `noAuth` | require authentication on the upload endpoint |

## The Upload-Early Flow

Expand Down Expand Up @@ -171,7 +171,7 @@ data class Post(
) : HasId<Uuid>
```

When `Post` is returned by an endpoint within the same server that contains `UploadEarlyEndpoint`,
When `Post` is returned by an endpoint within the same server that contains `GlobalUploadEndpoints`,
`image` is automatically signed before it reaches the client. When a client submits a `Post` with
`image` set to a `futureCallToken`, the serializer validates, resolves, and cleans up the token.

Expand Down Expand Up @@ -281,5 +281,5 @@ external database is needed.
[Media Processing](media.md).
- **Validation** — annotate `ServerFile` fields with `@MimeType(…)` and register
`AnnotationValidators.Files` to enforce file type and size limits at the model layer.
- **Cleanup** — `UploadEarlyEndpoint` includes a built-in `cleanupSchedule` that runs daily and
- **Cleanup** — `GlobalUploadEndpoints` includes a built-in `cleanupSchedule` that runs daily and
removes expired upload records and their associated files.
12 changes: 6 additions & 6 deletions docs-guide/drafts/serialization.md
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ object Server : ServerBuilder() {

When your server includes sub-builders (via `include`), their `externalSerialization`
and `internalSerialization` are merged with the root at `build()` time.
`UploadEarlyEndpoint` (see [ServerFile](#serverfile-serialization) below) uses this
`GlobalUploadEndpoints` (see [ServerFile](#serverfile-serialization) below) uses this
mechanism to inject the `ExternalServerFileSerializer` contextual entry.

## Polymorphic and Sealed Types
Expand Down Expand Up @@ -252,7 +252,7 @@ defers to whatever serializer is registered in the current `SerializersModule` f
`ServerFile::class`. On the client side (where no contextual override is present),
`DirectServerFileSerializer` kicks in — it reads and writes the raw URL string unchanged.

**On the server side**, `UploadEarlyEndpoint` overrides `externalSerialization` to
**On the server side**, `GlobalUploadEndpoints` overrides `externalSerialization` to
inject `ExternalServerFileSerializer` as the contextual entry:

```kotlin
Expand All @@ -264,7 +264,7 @@ override val externalSerialization: Runtime<SerializersModule> = Runtime.Cached
}
```

This means **any endpoint that shares a ServerBuilder tree with an `UploadEarlyEndpoint`
This means **any endpoint that shares a ServerBuilder tree with an `GlobalUploadEndpoints`
gets the secure serializer automatically**. You do not register it manually.

### What ExternalServerFileSerializer Does
Expand Down Expand Up @@ -299,16 +299,16 @@ recommended in production.
request body. `ExternalServerFileSerializer.deserialize` validates the token and
resolves it to the final internal URL.

> **Gotcha: one `UploadEarlyEndpoint` per server tree.** If you declare multiple
> **Gotcha: one `GlobalUploadEndpoints` per server tree.** If you declare multiple
> instances in the same `ServerBuilder` tree they will both try to register a
> contextual serializer for `ServerFile`, which causes a
> `ConflictingSerializerException` at startup. Declare it once and share the
> `ConflictingSerializerException` at startup. Declare it once and share the
> reference.

## What's Next

- **Files** — how to declare `ExternalFileSystem.Settings()`, wire a file system backend,
and configure `UploadEarlyEndpoint` for your server (see the files draft chapter).
and configure `GlobalUploadEndpoints` for your server (see the files draft chapter).
- **Typed Endpoints** — typed endpoints call `registerBasicMediaTypeCoders()` and use
`parse`/`toTypedData` automatically; you usually only need to read this chapter when
working with raw `HttpHandler`s or custom wire formats.
Expand Down
2 changes: 1 addition & 1 deletion docs-guide/guide/project-structure.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ modules. These are what you reference in your dependency blocks.

| Module | Type | What it provides |
|---|---|---|
| `files` | JVM | `UploadEarlyEndpoint`, signed-URL generation, multi-backend file storage |
| `files` | JVM | `GlobalUploadEndpoints`, signed-URL generation, multi-backend file storage |
| `files-shared` | KMP | `ServerFile`, `ServerFileWithMetadata` types |
| `media` | JVM | Image processing (resize, crop, convert) via Scrimage |
| `media-shared` | KMP | Media operation types |
Expand Down
12 changes: 6 additions & 6 deletions docs/files.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,9 +126,9 @@ When a `ServerFile` is serialized out to a client, its URL is automatically sign
file stays private as long as you only serialize references to it for people you want to be able to read it. Do not
build a public file-sharing feature on top of this behavior by accident.

## The `UploadEarlyEndpoint` (recommended upload flow)
## The `GlobalUploadEndpoints` (recommended upload flow)

`UploadEarlyEndpoint` is an opinionated group of endpoints for the common "upload now, reference later" pattern. It
`GlobalUploadEndpoints` is an opinionated group of endpoints for the common "upload now, reference later" pattern. It
lets a client upload a file before the request that actually uses it, without turning your file system into an open
file-sharing service.

Expand Down Expand Up @@ -177,15 +177,15 @@ Verifying up front also makes the subsequent request faster, since the scan has

With an empty scanner list, uploads go straight to the ready location and are certified as already scanned.

### ⚠️ Only one `UploadEarlyEndpoint` per server
### ⚠️ Only one `GlobalUploadEndpoints` per server

`UploadEarlyEndpoint` registers a **contextual serializer for `ServerFile`** (via its `externalSerialization`) so
that upload tokens can be decoded as `ServerFile` values. If you instantiate `UploadEarlyEndpoint` more than once
`GlobalUploadEndpoints` registers a **contextual serializer for `ServerFile`** (via its `externalSerialization`) so
that upload tokens can be decoded as `ServerFile` values. If you instantiate `GlobalUploadEndpoints` more than once
(for example, a separate instance created only for a test), the multiple instances register **conflicting
`ServerFile` serializers**. This does not fail at compile time — it surfaces at runtime as serialization errors,
typically appearing as `500 Internal Server Error` responses.

**Instantiate `UploadEarlyEndpoint` exactly once in your server definition and reference that single instance
**Instantiate `GlobalUploadEndpoints` exactly once in your server definition and reference that single instance
everywhere, including from tests.**

## Available Backends
Expand Down
3 changes: 2 additions & 1 deletion docs/files/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

This package provides primitives and endpoints for working with user-provided files.

- files-shared: Common models used across platforms (UploadForNextRequest, UploadInformation).
- files-shared: Common models and the client interface used across platforms (UploadTarget, UnverifiedUpload,
ClientFileUploadEndpoints).
- files: JVM server endpoints and helpers for serving files and implementing the early-upload workflow.

Contents
Expand Down
2 changes: 1 addition & 1 deletion docs/migration-v4-to-v5.md
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ See [WebSockets](websockets.md) for the current API.
needs `context(runtime: ServerRuntime)`.
- **`collection()` unresolved.** Replace `.collection()`/`.baseCollection()` with `.table()`/`.baseTable()`.
- **Wrong `Instant` import.** Use `kotlin.time.Instant`, not `kotlinx.datetime.Instant`.
- **Duplicate `UploadEarlyEndpoint`.** Instantiate it exactly once; multiple instances register conflicting
- **Duplicate `GlobalUploadEndpoints`.** Instantiate it exactly once; multiple instances register conflicting
`ServerFile` serializers and cause runtime 500s. See [File Systems](files.md).

## Client and KiteUI migration
Expand Down
13 changes: 0 additions & 13 deletions files-shared/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import org.jetbrains.kotlin.gradle.dsl.JvmTarget

plugins {
alias(libs.plugins.kotlin.multiplatform)
alias(libs.plugins.ksp)
alias(libs.plugins.kotlin.serialization)
alias(libs.plugins.androidKmpLibrary)
alias(libs.plugins.dokka)
Expand Down Expand Up @@ -54,29 +53,17 @@ kotlin {
api(libs.services.files.client)
api(libs.services.database.shared)
}
kotlin {
srcDir(file("build/generated/ksp/common/commonMain/kotlin"))
}
}
val commonTest = getByName("commonTest") {
dependencies {
implementation(libs.kotlin.test)
}
kotlin {
srcDir(file("build/generated/ksp/common/commonTest/kotlin"))
}
}
val jvmMain = getByName("jvmMain") {}
val jvmTest = getByName("jvmTest") {}
}
}

dependencies {
configurations.filter { it.name.startsWith("ksp") && it.name != "ksp" }.forEach {
add(it.name, libs.services.database.processor)
}
}

dependencies {
coreLibraryDesugaring(libs.androidDesugaring)
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package com.lightningkite.lightningserver.files

import com.lightningkite.lightningserver.HttpMethod
import com.lightningkite.lightningserver.typed.Fetcher
import com.lightningkite.lightningserver.typed.LiveVersion
import com.lightningkite.services.files.DirectServerFileSerializer
import com.lightningkite.services.files.ServerFile
import kotlinx.serialization.builtins.serializer

/**
* Client for a server's `UploadEndpoints` or `GlobalUploadEndpoints` module.
*
* To send a file: call [getFileUploadUrl], PUT the bytes to [UploadTarget.uploadUrl], pass
* [UploadTarget.token] to [verifyUpload], then put the [ServerFile] it returns wherever a request
* expects a file.
*/
@LiveVersion(LiveClientFileUploadEndpoints::class)
public interface ClientFileUploadEndpoints {
/**
* Returns a URL to PUT a file to, and a token that refers to that file.
*
* Both expire, usually within a day; upload and verify promptly.
*/
public suspend fun getFileUploadUrl(): UploadTarget

/**
* Scans the file [upload] refers to, and returns it as a [ServerFile] a later request can use.
*
* It expires like the upload it came from, so use it promptly.
*
* Verify every upload, even on servers with no scanners: there the call is a cheap no-op.
*/
public suspend fun verifyUpload(upload: UnverifiedUploadToken): ServerFile

@Suppress("DEPRECATION")
@Deprecated("Renamed to getFileUploadUrl.", ReplaceWith("getFileUploadUrl()"))
public suspend fun uploadFileForRequest(): UploadInformation =
getFileUploadUrl().let { UploadInformation(it.uploadUrl, it.token.raw) }

@Deprecated("Use verifyUpload.", ReplaceWith("verifyUpload(UnverifiedUpload(input)).location"))
public suspend fun verifyUploadedFile(input: String): String = verifyUpload(UnverifiedUploadToken(input)).location
}

public open class LiveClientFileUploadEndpoints(
public val fetcher: Fetcher,
public val subpath: String,
) : ClientFileUploadEndpoints {
override suspend fun getFileUploadUrl(): UploadTarget =
fetcher(subpath, HttpMethod.GET, Unit.serializer(), Unit, UploadTarget.serializer())

override suspend fun verifyUpload(upload: UnverifiedUploadToken): ServerFile =
fetcher("$subpath/verify", HttpMethod.POST, UnverifiedUploadToken.serializer(), upload, DirectServerFileSerializer)
}

@Deprecated("Renamed", ReplaceWith("com.lightningkite.lightningserver.files.ClientFileUploadEndpoints"))
public typealias ClientUploadEarlyEndpoints = ClientFileUploadEndpoints

@Deprecated("Renamed", ReplaceWith("com.lightningkite.lightningserver.files.LiveClientFileUploadEndpoints"))
public typealias LiveClientUploadEarlyEndpoints = LiveClientFileUploadEndpoints

This file was deleted.

This file was deleted.

Loading
Loading