Compare commits

..

2 Commits

Author SHA1 Message Date
b8b3d5fca4 docs: fix stale jsdoc on provider failure behavior
Co-authored-by: Ona <no-reply@ona.com>
2026-03-21 22:45:51 +00:00
b0551cb78a feat(session): add per-user source refresh
Add refreshSource(provider) to UserSession so per-user
config changes can re-resolve a source without replacing
the global provider.

- UserSession now carries userId
- Simplify UserSessionManager sessions map
- replaceProvider delegates to session.refreshSource
- Remove updateSessionSource from manager

Co-authored-by: Ona <no-reply@ona.com>
2026-03-21 22:42:19 +00:00
18 changed files with 212 additions and 917 deletions

View File

@@ -25,11 +25,9 @@
"arktype": "^2.1.29",
"better-auth": "^1",
"drizzle-orm": "^0.45.1",
"hono": "^4",
"lodash.merge": "^4.6.2"
"hono": "^4"
},
"devDependencies": {
"@types/lodash.merge": "^4.6.9",
"drizzle-kit": "^0.31.9"
}
}

View File

@@ -1,7 +1,7 @@
import type { ActionDefinition, ContextEntry, FeedItem, FeedSource } from "@aelis/core"
import { describe, expect, mock, test } from "bun:test"
import { Hono } from "hono"
import { describe, expect, test } from "bun:test"
import type { AdminMiddleware } from "../auth/admin-middleware.ts"
import type { AuthSession, AuthUser } from "../auth/session.ts"
@@ -11,39 +11,6 @@ import type { FeedSourceProvider } from "../session/feed-source-provider.ts"
import { UserSessionManager } from "../session/user-session-manager.ts"
import { registerAdminHttpHandlers } from "./http.ts"
let mockEnabledSourceIds: string[] = []
mock.module("../sources/user-sources.ts", () => ({
sources: (_db: Database, _userId: string) => ({
async enabled() {
const now = new Date()
return mockEnabledSourceIds.map((sourceId) => ({
id: crypto.randomUUID(),
userId: _userId,
sourceId,
enabled: true,
config: {},
credentials: null,
createdAt: now,
updatedAt: now,
}))
},
async find(sourceId: string) {
const now = new Date()
return {
id: crypto.randomUUID(),
userId: _userId,
sourceId,
enabled: true,
config: {},
credentials: null,
createdAt: now,
updatedAt: now,
}
},
}),
}))
function createStubSource(id: string): FeedSource {
return {
id,
@@ -96,8 +63,7 @@ function passthroughAdminMiddleware(): AdminMiddleware {
const fakeDb = {} as Database
function createApp(providers: FeedSourceProvider[]) {
mockEnabledSourceIds = providers.map((p) => p.sourceId)
const sessionManager = new UserSessionManager({ db: fakeDb, providers })
const sessionManager = new UserSessionManager({ providers })
const app = new Hono()
registerAdminHttpHandlers(app, {
sessionManager,
@@ -192,4 +158,5 @@ describe("PUT /api/admin/:sourceId/config", () => {
expect(provider!.sourceId).toBe("aelis.weather")
expect(provider).not.toBe(originalProvider)
})
})

View File

@@ -51,6 +51,7 @@ async function handleUpdateProviderConfig(c: Context<Env>) {
}
const sessionManager = c.get("sessionManager")
const db = c.get("db")
let body: unknown
try {
@@ -67,6 +68,7 @@ async function handleUpdateProviderConfig(c: Context<Env>) {
}
const updated = new WeatherSourceProvider({
db,
credentials: parsed.credentials,
})

View File

@@ -1,11 +1,9 @@
import type { ActionDefinition, ContextEntry, FeedItem, FeedSource } from "@aelis/core"
import { contextKey } from "@aelis/core"
import { describe, expect, mock, spyOn, test } from "bun:test"
import { describe, expect, spyOn, test } from "bun:test"
import { Hono } from "hono"
import type { Database } from "../db/index.ts"
import { mockAuthSessionMiddleware } from "../auth/session-middleware.ts"
import { UserSessionManager } from "../session/index.ts"
import { registerFeedHttpHandlers } from "./http.ts"
@@ -52,45 +50,9 @@ function buildTestApp(sessionManager: UserSessionManager, userId?: string) {
return app
}
let mockEnabledSourceIds: string[] = []
mock.module("../sources/user-sources.ts", () => ({
sources: (_db: Database, _userId: string) => ({
async enabled() {
const now = new Date()
return mockEnabledSourceIds.map((sourceId) => ({
id: crypto.randomUUID(),
userId: _userId,
sourceId,
enabled: true,
config: {},
credentials: null,
createdAt: now,
updatedAt: now,
}))
},
async find(sourceId: string) {
const now = new Date()
return {
id: crypto.randomUUID(),
userId: _userId,
sourceId,
enabled: true,
config: {},
credentials: null,
createdAt: now,
updatedAt: now,
}
},
}),
}))
const fakeDb = {} as Database
describe("GET /api/feed", () => {
test("returns 401 without auth", async () => {
mockEnabledSourceIds = []
const manager = new UserSessionManager({ db: fakeDb, providers: [] })
const manager = new UserSessionManager({ providers: [] })
const app = buildTestApp(manager)
const res = await app.request("/api/feed")
@@ -109,9 +71,7 @@ describe("GET /api/feed", () => {
data: { value: 42 },
},
]
mockEnabledSourceIds = ["test"]
const manager = new UserSessionManager({
db: fakeDb,
providers: [
{
sourceId: "test",
@@ -151,9 +111,7 @@ describe("GET /api/feed", () => {
data: { fresh: true },
},
]
mockEnabledSourceIds = ["test"]
const manager = new UserSessionManager({
db: fakeDb,
providers: [
{
sourceId: "test",
@@ -192,9 +150,7 @@ describe("GET /api/feed", () => {
throw new Error("connection timeout")
},
}
mockEnabledSourceIds = ["failing"]
const manager = new UserSessionManager({
db: fakeDb,
providers: [
{
sourceId: "failing",
@@ -217,9 +173,7 @@ describe("GET /api/feed", () => {
})
test("returns 503 when all providers fail", async () => {
mockEnabledSourceIds = ["test"]
const manager = new UserSessionManager({
db: fakeDb,
providers: [
{
sourceId: "test",
@@ -252,9 +206,7 @@ describe("GET /api/context", () => {
const mockUserId = "k7Gx2mPqRvNwYs9TdLfA4bHcJeUo1iZn"
async function buildContextApp(userId?: string) {
mockEnabledSourceIds = ["weather"]
const manager = new UserSessionManager({
db: fakeDb,
providers: [
{
sourceId: "weather",
@@ -270,8 +222,7 @@ describe("GET /api/context", () => {
}
test("returns 401 without auth", async () => {
mockEnabledSourceIds = []
const manager = new UserSessionManager({ db: fakeDb, providers: [] })
const manager = new UserSessionManager({ providers: [] })
const app = buildTestApp(manager)
const res = await app.request('/api/context?key=["aelis.weather","weather"]')

View File

@@ -1,11 +1,26 @@
import { LocationSource } from "@aelis/source-location"
import type { Database } from "../db/index.ts"
import type { FeedSourceProvider } from "../session/feed-source-provider.ts"
import { SourceDisabledError } from "../sources/errors.ts"
import { sources } from "../sources/user-sources.ts"
export class LocationSourceProvider implements FeedSourceProvider {
readonly sourceId = "aelis.location"
private readonly db: Database
constructor(db: Database) {
this.db = db
}
async feedSourceForUser(userId: string): Promise<LocationSource> {
const row = await sources(this.db, userId).find("aelis.location")
if (!row || !row.enabled) {
throw new SourceDisabledError("aelis.location", userId)
}
async feedSourceForUser(_userId: string, _config: unknown): Promise<LocationSource> {
return new LocationSource()
}
}

View File

@@ -12,7 +12,6 @@ import { createLlmClient } from "./enhancement/llm-client.ts"
import { registerLocationHttpHandlers } from "./location/http.ts"
import { LocationSourceProvider } from "./location/provider.ts"
import { UserSessionManager } from "./session/index.ts"
import { registerSourcesHttpHandlers } from "./sources/http.ts"
import { WeatherSourceProvider } from "./weather/provider.ts"
function main() {
@@ -33,10 +32,10 @@ function main() {
}
const sessionManager = new UserSessionManager({
db,
providers: [
new LocationSourceProvider(),
new LocationSourceProvider(db),
new WeatherSourceProvider({
db,
credentials: {
privateKey: process.env.WEATHERKIT_PRIVATE_KEY!,
keyId: process.env.WEATHERKIT_KEY_ID!,
@@ -62,7 +61,6 @@ function main() {
authSessionMiddleware,
})
registerLocationHttpHandlers(app, { sessionManager, authSessionMiddleware })
registerSourcesHttpHandlers(app, { sessionManager, authSessionMiddleware })
registerAdminHttpHandlers(app, { sessionManager, adminMiddleware, db })
process.on("SIGTERM", async () => {

View File

@@ -1,12 +1,7 @@
import type { FeedSource } from "@aelis/core"
import type { type } from "arktype"
export type ConfigSchema = ReturnType<typeof type>
export interface FeedSourceProvider {
/** The source ID this provider is responsible for (e.g., "aelis.location"). */
readonly sourceId: string
/** Arktype schema for validating user-provided config. Omit if the source has no config. */
readonly configSchema?: ConfigSchema
feedSourceForUser(userId: string, config: unknown): Promise<FeedSource>
feedSourceForUser(userId: string): Promise<FeedSource>
}

View File

@@ -2,77 +2,12 @@ import type { ActionDefinition, ContextEntry, FeedItem, FeedSource } from "@aeli
import { LocationSource } from "@aelis/source-location"
import { WeatherSource } from "@aelis/source-weatherkit"
import { beforeEach, describe, expect, mock, spyOn, test } from "bun:test"
import { describe, expect, mock, spyOn, test } from "bun:test"
import type { Database } from "../db/index.ts"
import type { FeedSourceProvider } from "./feed-source-provider.ts"
import { UserSessionManager } from "./user-session-manager.ts"
/**
* Per-user enabled source IDs used by the mocked `sources` module.
* Tests configure this before calling getOrCreate.
* Key = userId (or "*" for a default), value = array of enabled sourceIds.
*/
const enabledByUser = new Map<string, string[]>()
/** Set which sourceIds are enabled for all users. */
function setEnabledSources(sourceIds: string[]) {
enabledByUser.clear()
enabledByUser.set("*", sourceIds)
}
/** Set which sourceIds are enabled for a specific user. */
function setEnabledSourcesForUser(userId: string, sourceIds: string[]) {
enabledByUser.set(userId, sourceIds)
}
function getEnabledSourceIds(userId: string): string[] {
return enabledByUser.get(userId) ?? enabledByUser.get("*") ?? []
}
/**
* Controls what `find()` returns in the mock. When `undefined` (the default),
* `find()` returns a standard enabled row. Set to a specific value (including
* `null`) to override the return value for all `find()` calls.
*/
let mockFindResult: unknown | undefined
// Mock the sources module so UserSessionManager's DB query returns controlled data.
mock.module("../sources/user-sources.ts", () => ({
sources: (_db: Database, userId: string) => ({
async enabled() {
const now = new Date()
return getEnabledSourceIds(userId).map((sourceId) => ({
id: crypto.randomUUID(),
userId,
sourceId,
enabled: true,
config: {},
credentials: null,
createdAt: now,
updatedAt: now,
}))
},
async find(sourceId: string) {
if (mockFindResult !== undefined) return mockFindResult
const now = new Date()
return {
id: crypto.randomUUID(),
userId,
sourceId,
enabled: true,
config: {},
credentials: null,
createdAt: now,
updatedAt: now,
}
},
}),
}))
const fakeDb = {} as Database
function createStubSource(id: string, items: FeedItem[] = []): FeedSource {
return {
id,
@@ -93,8 +28,7 @@ function createStubSource(id: string, items: FeedItem[] = []): FeedSource {
function createStubProvider(
sourceId: string,
factory: (userId: string, config: Record<string, unknown>) => Promise<FeedSource> = async () =>
createStubSource(sourceId),
factory: (userId: string) => Promise<FeedSource> = async () => createStubSource(sourceId),
): FeedSourceProvider {
return { sourceId, feedSourceForUser: factory }
}
@@ -113,15 +47,9 @@ const weatherProvider: FeedSourceProvider = {
},
}
beforeEach(() => {
enabledByUser.clear()
mockFindResult = undefined
})
describe("UserSessionManager", () => {
test("getOrCreate creates session on first call", async () => {
setEnabledSources(["aelis.location"])
const manager = new UserSessionManager({ db: fakeDb, providers: [locationProvider] })
const manager = new UserSessionManager({ providers: [locationProvider] })
const session = await manager.getOrCreate("user-1")
@@ -130,8 +58,7 @@ describe("UserSessionManager", () => {
})
test("getOrCreate returns same session for same user", async () => {
setEnabledSources(["aelis.location"])
const manager = new UserSessionManager({ db: fakeDb, providers: [locationProvider] })
const manager = new UserSessionManager({ providers: [locationProvider] })
const session1 = await manager.getOrCreate("user-1")
const session2 = await manager.getOrCreate("user-1")
@@ -140,8 +67,7 @@ describe("UserSessionManager", () => {
})
test("getOrCreate returns different sessions for different users", async () => {
setEnabledSources(["aelis.location"])
const manager = new UserSessionManager({ db: fakeDb, providers: [locationProvider] })
const manager = new UserSessionManager({ providers: [locationProvider] })
const session1 = await manager.getOrCreate("user-1")
const session2 = await manager.getOrCreate("user-2")
@@ -150,8 +76,7 @@ describe("UserSessionManager", () => {
})
test("each user gets independent source instances", async () => {
setEnabledSources(["aelis.location"])
const manager = new UserSessionManager({ db: fakeDb, providers: [locationProvider] })
const manager = new UserSessionManager({ providers: [locationProvider] })
const session1 = await manager.getOrCreate("user-1")
const session2 = await manager.getOrCreate("user-2")
@@ -163,8 +88,7 @@ describe("UserSessionManager", () => {
})
test("remove destroys session and allows re-creation", async () => {
setEnabledSources(["aelis.location"])
const manager = new UserSessionManager({ db: fakeDb, providers: [locationProvider] })
const manager = new UserSessionManager({ providers: [locationProvider] })
const session1 = await manager.getOrCreate("user-1")
manager.remove("user-1")
@@ -174,16 +98,13 @@ describe("UserSessionManager", () => {
})
test("remove is no-op for unknown user", () => {
setEnabledSources(["aelis.location"])
const manager = new UserSessionManager({ db: fakeDb, providers: [locationProvider] })
const manager = new UserSessionManager({ providers: [locationProvider] })
expect(() => manager.remove("unknown")).not.toThrow()
})
test("registers multiple providers", async () => {
setEnabledSources(["aelis.location", "aelis.weather"])
const manager = new UserSessionManager({
db: fakeDb,
providers: [locationProvider, weatherProvider],
})
@@ -194,8 +115,7 @@ describe("UserSessionManager", () => {
})
test("refresh returns feed result through session", async () => {
setEnabledSources(["aelis.location"])
const manager = new UserSessionManager({ db: fakeDb, providers: [locationProvider] })
const manager = new UserSessionManager({ providers: [locationProvider] })
const session = await manager.getOrCreate("user-1")
const result = await session.engine.refresh()
@@ -207,8 +127,7 @@ describe("UserSessionManager", () => {
})
test("location update via executeAction works", async () => {
setEnabledSources(["aelis.location"])
const manager = new UserSessionManager({ db: fakeDb, providers: [locationProvider] })
const manager = new UserSessionManager({ providers: [locationProvider] })
const session = await manager.getOrCreate("user-1")
await session.engine.executeAction("aelis.location", "update-location", {
@@ -223,8 +142,7 @@ describe("UserSessionManager", () => {
})
test("subscribe receives updates after location push", async () => {
setEnabledSources(["aelis.location"])
const manager = new UserSessionManager({ db: fakeDb, providers: [locationProvider] })
const manager = new UserSessionManager({ providers: [locationProvider] })
const callback = mock()
const session = await manager.getOrCreate("user-1")
@@ -244,8 +162,7 @@ describe("UserSessionManager", () => {
})
test("remove stops reactive updates", async () => {
setEnabledSources(["aelis.location"])
const manager = new UserSessionManager({ db: fakeDb, providers: [locationProvider] })
const manager = new UserSessionManager({ providers: [locationProvider] })
const callback = mock()
const session = await manager.getOrCreate("user-1")
@@ -268,7 +185,6 @@ describe("UserSessionManager", () => {
})
test("creates session with successful providers when some fail", async () => {
setEnabledSources(["aelis.location", "aelis.failing"])
const failingProvider: FeedSourceProvider = {
sourceId: "aelis.failing",
async feedSourceForUser() {
@@ -277,7 +193,6 @@ describe("UserSessionManager", () => {
}
const manager = new UserSessionManager({
db: fakeDb,
providers: [locationProvider, failingProvider],
})
@@ -293,9 +208,7 @@ describe("UserSessionManager", () => {
})
test("throws AggregateError when all providers fail", async () => {
setEnabledSources(["aelis.fail-1", "aelis.fail-2"])
const manager = new UserSessionManager({
db: fakeDb,
providers: [
{
sourceId: "aelis.fail-1",
@@ -316,10 +229,8 @@ describe("UserSessionManager", () => {
})
test("concurrent getOrCreate for same user returns same session", async () => {
setEnabledSources(["aelis.location"])
let callCount = 0
const manager = new UserSessionManager({
db: fakeDb,
providers: [
{
sourceId: "aelis.location",
@@ -342,14 +253,12 @@ describe("UserSessionManager", () => {
})
test("remove during in-flight getOrCreate prevents session from being stored", async () => {
setEnabledSources(["aelis.location"])
let resolveProvider: () => void
const providerGate = new Promise<void>((r) => {
resolveProvider = r
})
const manager = new UserSessionManager({
db: fakeDb,
providers: [
{
sourceId: "aelis.location",
@@ -376,67 +285,10 @@ describe("UserSessionManager", () => {
expect(freshSession).toBeDefined()
expect(freshSession.engine).toBeDefined()
})
test("only invokes providers for sources enabled for the user", async () => {
setEnabledSources(["aelis.location"])
const locationFactory = mock(async () => createStubSource("aelis.location"))
const weatherFactory = mock(async () => createStubSource("aelis.weather"))
const manager = new UserSessionManager({
db: fakeDb,
providers: [
{ sourceId: "aelis.location", feedSourceForUser: locationFactory },
{ sourceId: "aelis.weather", feedSourceForUser: weatherFactory },
],
})
const session = await manager.getOrCreate("user-1")
expect(locationFactory).toHaveBeenCalledTimes(1)
expect(weatherFactory).not.toHaveBeenCalled()
expect(session.getSource("aelis.location")).toBeDefined()
expect(session.getSource("aelis.weather")).toBeUndefined()
})
test("creates empty session when no sources are enabled", async () => {
setEnabledSources([])
const factory = mock(async () => createStubSource("aelis.location"))
const manager = new UserSessionManager({
db: fakeDb,
providers: [{ sourceId: "aelis.location", feedSourceForUser: factory }],
})
const session = await manager.getOrCreate("user-1")
expect(factory).not.toHaveBeenCalled()
expect(session).toBeDefined()
expect(session.getSource("aelis.location")).toBeUndefined()
})
test("per-user enabled sources are respected", async () => {
enabledByUser.clear()
setEnabledSourcesForUser("user-1", ["aelis.location"])
setEnabledSourcesForUser("user-2", ["aelis.weather"])
const manager = new UserSessionManager({
db: fakeDb,
providers: [createStubProvider("aelis.location"), createStubProvider("aelis.weather")],
})
const session1 = await manager.getOrCreate("user-1")
const session2 = await manager.getOrCreate("user-2")
expect(session1.getSource("aelis.location")).toBeDefined()
expect(session1.getSource("aelis.weather")).toBeUndefined()
expect(session2.getSource("aelis.location")).toBeUndefined()
expect(session2.getSource("aelis.weather")).toBeDefined()
})
})
describe("UserSessionManager.replaceProvider", () => {
test("replaces source in all active sessions", async () => {
setEnabledSources(["test"])
const itemsV1: FeedItem[] = [
{
id: "v1",
@@ -457,7 +309,7 @@ describe("UserSessionManager.replaceProvider", () => {
]
const providerV1 = createStubProvider("test", async () => createStubSource("test", itemsV1))
const manager = new UserSessionManager({ db: fakeDb, providers: [providerV1] })
const manager = new UserSessionManager({ providers: [providerV1] })
const session1 = await manager.getOrCreate("user-1")
const session2 = await manager.getOrCreate("user-2")
@@ -478,8 +330,7 @@ describe("UserSessionManager.replaceProvider", () => {
})
test("throws for unknown provider sourceId", async () => {
setEnabledSources(["aelis.location"])
const manager = new UserSessionManager({ db: fakeDb, providers: [locationProvider] })
const manager = new UserSessionManager({ providers: [locationProvider] })
const unknownProvider = createStubProvider("aelis.unknown")
@@ -489,9 +340,8 @@ describe("UserSessionManager.replaceProvider", () => {
})
test("keeps existing source when new provider fails for a user", async () => {
setEnabledSources(["test"])
const providerV1 = createStubProvider("test", async () => createStubSource("test"))
const manager = new UserSessionManager({ db: fakeDb, providers: [providerV1] })
const manager = new UserSessionManager({ providers: [providerV1] })
const session = await manager.getOrCreate("user-1")
expect(session.getSource("test")).toBeDefined()
@@ -510,7 +360,6 @@ describe("UserSessionManager.replaceProvider", () => {
})
test("new sessions use the replaced provider", async () => {
setEnabledSources(["test"])
const itemsV1: FeedItem[] = [
{
id: "v1",
@@ -531,7 +380,7 @@ describe("UserSessionManager.replaceProvider", () => {
]
const providerV1 = createStubProvider("test", async () => createStubSource("test", itemsV1))
const manager = new UserSessionManager({ db: fakeDb, providers: [providerV1] })
const manager = new UserSessionManager({ providers: [providerV1] })
const providerV2 = createStubProvider("test", async () => createStubSource("test", itemsV2))
await manager.replaceProvider(providerV2)
@@ -543,7 +392,6 @@ describe("UserSessionManager.replaceProvider", () => {
})
test("does not affect other providers' sources", async () => {
setEnabledSources(["source-a", "source-b"])
const providerA = createStubProvider("source-a", async () =>
createStubSource("source-a", [
{
@@ -567,7 +415,7 @@ describe("UserSessionManager.replaceProvider", () => {
]),
)
const manager = new UserSessionManager({ db: fakeDb, providers: [providerA, providerB] })
const manager = new UserSessionManager({ providers: [providerA, providerB] })
const session = await manager.getOrCreate("user-1")
// Replace only source-a
@@ -592,7 +440,6 @@ describe("UserSessionManager.replaceProvider", () => {
})
test("updates sessions that are still being created", async () => {
setEnabledSources(["test"])
const itemsV1: FeedItem[] = [
{
id: "v1",
@@ -621,7 +468,7 @@ describe("UserSessionManager.replaceProvider", () => {
await creationGate
return createStubSource("test", itemsV1)
})
const manager = new UserSessionManager({ db: fakeDb, providers: [providerV1] })
const manager = new UserSessionManager({ providers: [providerV1] })
// Start session creation but don't let it finish yet
const sessionPromise = manager.getOrCreate("user-1")
@@ -640,44 +487,4 @@ describe("UserSessionManager.replaceProvider", () => {
const feed = await session.feed()
expect(feed.items[0]!.data.version).toBe(2)
})
test("skips source replacement when source was disabled between creation and replace", async () => {
setEnabledSources(["test"])
const itemsV1: FeedItem[] = [
{
id: "v1",
sourceId: "test",
type: "test",
timestamp: new Date(),
data: { version: 1 },
},
]
const providerV1 = createStubProvider("test", async () => createStubSource("test", itemsV1))
const manager = new UserSessionManager({ db: fakeDb, providers: [providerV1] })
const session = await manager.getOrCreate("user-1")
const feedBefore = await session.feed()
expect(feedBefore.items[0]!.data.version).toBe(1)
// Simulate the source being disabled/deleted between session creation and replace
mockFindResult = null
const providerV2 = createStubProvider("test", async () =>
createStubSource("test", [
{
id: "v2",
sourceId: "test",
type: "test",
timestamp: new Date(),
data: { version: 2 },
},
]),
)
await manager.replaceProvider(providerV2)
// Session should still have v1 — the replace was skipped
const feedAfter = await session.feed()
expect(feedAfter.items[0]!.data.version).toBe(1)
})
})

View File

@@ -1,18 +1,11 @@
import type { FeedSource } from "@aelis/core"
import { type } from "arktype"
import merge from "lodash.merge"
import type { Database } from "../db/index.ts"
import type { FeedEnhancer } from "../enhancement/enhance-feed.ts"
import { InvalidSourceConfigError, SourceNotFoundError } from "../sources/errors.ts"
import { sources } from "../sources/user-sources.ts"
import type { FeedSourceProvider } from "./feed-source-provider.ts"
import { UserSession } from "./user-session.ts"
export interface UserSessionManagerConfig {
db: Database
providers: FeedSourceProvider[]
feedEnhancer?: FeedEnhancer | null
}
@@ -20,18 +13,14 @@ export interface UserSessionManagerConfig {
export class UserSessionManager {
private sessions = new Map<string, UserSession>()
private pending = new Map<string, Promise<UserSession>>()
private readonly db: Database
private readonly providers = new Map<string, FeedSourceProvider>()
private readonly feedEnhancer: FeedEnhancer | null
private readonly db: Database
constructor(config: UserSessionManagerConfig) {
this.db = config.db
for (const provider of config.providers) {
this.providers.set(provider.sourceId, provider)
}
this.feedEnhancer = config.feedEnhancer ?? null
this.db = config.db
}
getProvider(sourceId: string): FeedSourceProvider | undefined {
@@ -72,76 +61,11 @@ export class UserSessionManager {
this.pending.delete(userId)
}
/**
* Merges, validates, and persists a user's source config and/or enabled
* state, then invalidates the cached session.
*
* @throws {SourceNotFoundError} if the source row doesn't exist
* @throws {InvalidSourceConfigError} if the merged config fails schema validation
*/
async updateSourceConfig(
userId: string,
sourceId: string,
update: { enabled?: boolean; config?: unknown },
): Promise<void> {
const provider = this.providers.get(sourceId)
if (!provider) {
throw new SourceNotFoundError(sourceId, userId)
}
// Nothing to update
if (update.enabled === undefined && update.config === undefined) {
// Still validate existence — updateConfig would throw, but
// we can avoid the DB write entirely.
if (!(await sources(this.db, userId).find(sourceId))) {
throw new SourceNotFoundError(sourceId, userId)
}
return
}
// When config is provided, fetch existing to deep-merge before validating.
// NOTE: find + updateConfig is not atomic. A concurrent update could
// read stale config. Use SELECT FOR UPDATE or atomic jsonb merge if
// this becomes a problem.
let mergedConfig: Record<string, unknown> | undefined
if (update.config !== undefined) {
const existing = await sources(this.db, userId).find(sourceId)
const existingConfig = (existing?.config ?? {}) as Record<string, unknown>
mergedConfig = merge({}, existingConfig, update.config)
if (provider.configSchema) {
const validated = provider.configSchema(mergedConfig)
if (validated instanceof type.errors) {
throw new InvalidSourceConfigError(sourceId, validated.summary)
}
}
}
// Throws SourceNotFoundError if the row doesn't exist
await sources(this.db, userId).updateConfig(sourceId, {
enabled: update.enabled,
config: mergedConfig,
})
// Refresh the specific source in the active session instead of
// destroying the entire session.
const session = this.sessions.get(userId)
if (session) {
if (update.enabled === false) {
session.removeSource(sourceId)
} else {
const source = await provider.feedSourceForUser(userId, mergedConfig ?? {})
session.replaceSource(sourceId, source)
}
}
}
/**
* Replaces a provider and updates all active sessions.
* The new provider must have the same sourceId as an existing one.
* For each active session, queries the user's source config from the DB
* and re-resolves the source. If the provider fails for a user, the
* existing source is kept.
* For each active session, re-resolves the source via session.refreshSource.
* If the provider fails for a user, the existing source is kept.
*/
async replaceProvider(provider: FeedSourceProvider): Promise<void> {
if (!this.providers.has(provider.sourceId)) {
@@ -155,7 +79,7 @@ export class UserSessionManager {
const updates: Promise<void>[] = []
for (const [, session] of this.sessions) {
updates.push(this.refreshSessionSource(session, provider))
updates.push(session.refreshSource(provider))
}
// Also update sessions that are currently being created so they
@@ -163,7 +87,7 @@ export class UserSessionManager {
for (const [, pendingPromise] of this.pending) {
updates.push(
pendingPromise
.then((session) => this.refreshSessionSource(session, provider))
.then((session) => session.refreshSource(provider))
.catch(() => {
// Session creation itself failed — nothing to update.
}),
@@ -173,60 +97,23 @@ export class UserSessionManager {
await Promise.all(updates)
}
/**
* Re-resolves a single source for a session by querying the user's config
* from the DB and calling the provider. If the provider fails, the existing
* source is kept.
*/
private async refreshSessionSource(
session: UserSession,
provider: FeedSourceProvider,
): Promise<void> {
if (!session.hasSource(provider.sourceId)) return
try {
const row = await sources(this.db, session.userId).find(provider.sourceId)
if (!row?.enabled) return
const newSource = await provider.feedSourceForUser(session.userId, row.config ?? {})
session.replaceSource(provider.sourceId, newSource)
} catch (err) {
console.error(
`[UserSessionManager] refreshSource("${provider.sourceId}") failed for user ${session.userId}:`,
err,
)
}
}
private async createSession(userId: string): Promise<UserSession> {
const enabledRows = await sources(this.db, userId).enabled()
const results = await Promise.allSettled(
Array.from(this.providers.values()).map((p) => p.feedSourceForUser(userId)),
)
const promises: Promise<FeedSource>[] = []
for (const row of enabledRows) {
const provider = this.providers.get(row.sourceId)
if (provider) {
promises.push(provider.feedSourceForUser(userId, row.config ?? {}))
}
}
if (promises.length === 0) {
return new UserSession(userId, [], this.feedEnhancer)
}
const results = await Promise.allSettled(promises)
const feedSources: FeedSource[] = []
const sources: FeedSource[] = []
const errors: unknown[] = []
for (const result of results) {
if (result.status === "fulfilled") {
feedSources.push(result.value)
sources.push(result.value)
} else {
errors.push(result.reason)
}
}
if (feedSources.length === 0 && errors.length > 0) {
if (sources.length === 0 && errors.length > 0) {
throw new AggregateError(errors, "All feed source providers failed")
}
@@ -234,6 +121,6 @@ export class UserSessionManager {
console.error("[UserSessionManager] Feed source provider failed:", error)
}
return new UserSession(userId, feedSources, this.feedEnhancer)
return new UserSession(userId, sources, this.feedEnhancer)
}
}

View File

@@ -3,6 +3,8 @@ import type { ActionDefinition, ContextEntry, FeedItem, FeedSource } from "@aeli
import { LocationSource } from "@aelis/source-location"
import { describe, expect, spyOn, test } from "bun:test"
import type { FeedSourceProvider } from "./feed-source-provider.ts"
import { UserSession } from "./user-session.ts"
function createStubSource(id: string, items: FeedItem[] = []): FeedSource {
@@ -392,3 +394,73 @@ describe("UserSession.removeSource", () => {
expect(session.getSource("test")).toBeDefined()
})
})
describe("UserSession.refreshSource", () => {
test("replaces existing source via provider", async () => {
const itemsV1: FeedItem[] = [
{
id: "v1",
sourceId: "test",
type: "test",
timestamp: new Date(),
data: { version: 1 },
},
]
const itemsV2: FeedItem[] = [
{
id: "v2",
sourceId: "test",
type: "test",
timestamp: new Date(),
data: { version: 2 },
},
]
const session = new UserSession("test-user", [createStubSource("test", itemsV1)])
const provider: FeedSourceProvider = {
sourceId: "test",
async feedSourceForUser() {
return createStubSource("test", itemsV2)
},
}
await session.refreshSource(provider)
const result = await session.feed()
expect(result.items[0]!.data.version).toBe(2)
})
test("throws when source is not registered", async () => {
const session = new UserSession("test-user", [createStubSource("existing")])
const provider: FeedSourceProvider = {
sourceId: "new-source",
async feedSourceForUser() {
return createStubSource("new-source")
},
}
await expect(session.refreshSource(provider)).rejects.toThrow()
})
test("keeps existing source when provider fails", async () => {
const session = new UserSession("test-user", [createStubSource("test")])
const spy = spyOn(console, "error").mockImplementation(() => {})
const provider: FeedSourceProvider = {
sourceId: "test",
async feedSourceForUser() {
throw new Error("source disabled")
},
}
await session.refreshSource(provider)
expect(session.getSource("test")).toBeDefined()
expect(spy).toHaveBeenCalled()
spy.mockRestore()
})
})

View File

@@ -1,6 +1,7 @@
import { FeedEngine, type FeedItem, type FeedResult, type FeedSource } from "@aelis/core"
import type { FeedEnhancer } from "../enhancement/enhance-feed.ts"
import type { FeedSourceProvider } from "./feed-source-provider.ts"
export class UserSession {
readonly userId: string
@@ -69,8 +70,25 @@ export class UserSession {
return this.sources.get(sourceId) as T | undefined
}
hasSource(sourceId: string): boolean {
return this.sources.has(sourceId)
/**
* Re-resolves a source from its provider using this session's userId.
* The source must already be registered. Throws if it isn't.
* If the provider fails, the existing source is kept.
*/
async refreshSource(provider: FeedSourceProvider): Promise<void> {
if (!this.sources.has(provider.sourceId)) {
throw new Error(`Cannot refresh source "${provider.sourceId}": not registered`)
}
try {
const newSource = await provider.feedSourceForUser(this.userId)
this.replaceSource(provider.sourceId, newSource)
} catch (err) {
console.error(
`[UserSession] refreshSource("${provider.sourceId}") failed for user ${this.userId}:`,
err,
)
}
}
/**

View File

@@ -1,3 +1,21 @@
/**
* Thrown by a FeedSourceProvider when the source is not enabled for a user.
*
* UserSessionManager's Promise.allSettled handles this gracefully —
* the source is excluded from the session without crashing.
*/
export class SourceDisabledError extends Error {
readonly sourceId: string
readonly userId: string
constructor(sourceId: string, userId: string) {
super(`Source "${sourceId}" is not enabled for user "${userId}"`)
this.name = "SourceDisabledError"
this.sourceId = sourceId
this.userId = userId
}
}
/**
* Thrown when an operation targets a user source that doesn't exist.
*/
@@ -12,15 +30,3 @@ export class SourceNotFoundError extends Error {
this.userId = userId
}
}
/**
* Thrown when a source config update fails schema validation.
*/
export class InvalidSourceConfigError extends Error {
readonly sourceId: string
constructor(sourceId: string, summary: string) {
super(summary)
this.sourceId = sourceId
}
}

View File

@@ -1,344 +0,0 @@
import type { ActionDefinition, ContextEntry, FeedItem, FeedSource } from "@aelis/core"
import { describe, expect, mock, spyOn, test } from "bun:test"
import { Hono } from "hono"
import type { Database } from "../db/index.ts"
import type { ConfigSchema, FeedSourceProvider } from "../session/feed-source-provider.ts"
import { mockAuthSessionMiddleware } from "../auth/session-middleware.ts"
import { UserSessionManager } from "../session/user-session-manager.ts"
import { tflConfig } from "../tfl/provider.ts"
import { weatherConfig } from "../weather/provider.ts"
import { SourceNotFoundError } from "./errors.ts"
import { registerSourcesHttpHandlers } from "./http.ts"
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function createStubSource(id: string): FeedSource {
return {
id,
async listActions(): Promise<Record<string, ActionDefinition>> {
return {}
},
async executeAction(): Promise<unknown> {
return undefined
},
async fetchContext(): Promise<readonly ContextEntry[] | null> {
return null
},
async fetchItems(): Promise<FeedItem[]> {
return []
},
}
}
function createStubProvider(sourceId: string, configSchema?: ConfigSchema): FeedSourceProvider {
return {
sourceId,
configSchema,
async feedSourceForUser() {
return createStubSource(sourceId)
},
}
}
const MOCK_USER_ID = "k7Gx2mPqRvNwYs9TdLfA4bHcJeUo1iZn"
type SourceRow = {
userId: string
sourceId: string
enabled: boolean
config: Record<string, unknown>
}
function createInMemoryStore() {
const rows = new Map<string, SourceRow>()
function key(userId: string, sourceId: string) {
return `${userId}:${sourceId}`
}
return {
rows,
seed(userId: string, sourceId: string, data: Partial<SourceRow> = {}) {
rows.set(key(userId, sourceId), {
userId,
sourceId,
enabled: data.enabled ?? true,
config: data.config ?? {},
})
},
forUser(userId: string) {
return {
async enabled() {
return [...rows.values()].filter((r) => r.userId === userId && r.enabled)
},
async find(sourceId: string) {
return rows.get(key(userId, sourceId))
},
async updateConfig(sourceId: string, update: { enabled?: boolean; config?: unknown }) {
const existing = rows.get(key(userId, sourceId))
if (!existing) {
throw new SourceNotFoundError(sourceId, userId)
}
if (update.enabled !== undefined) {
existing.enabled = update.enabled
}
if (update.config !== undefined) {
existing.config = update.config as Record<string, unknown>
}
},
}
},
}
}
let activeStore: ReturnType<typeof createInMemoryStore>
mock.module("../sources/user-sources.ts", () => ({
sources(_db: unknown, userId: string) {
return activeStore.forUser(userId)
},
}))
const fakeDb = {} as Database
function createApp(providers: FeedSourceProvider[], userId?: string) {
const sessionManager = new UserSessionManager({ providers, db: fakeDb })
const app = new Hono()
registerSourcesHttpHandlers(app, {
sessionManager,
authSessionMiddleware: mockAuthSessionMiddleware(userId),
})
return { app, sessionManager }
}
function patch(app: Hono, sourceId: string, body: unknown) {
return app.request(`/api/sources/${sourceId}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
})
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
describe("PATCH /api/sources/:sourceId", () => {
test("returns 401 without auth", async () => {
activeStore = createInMemoryStore()
const { app } = createApp([createStubProvider("aelis.weather", weatherConfig)])
const res = await patch(app, "aelis.weather", { enabled: true })
expect(res.status).toBe(401)
})
test("returns 404 for unknown source", async () => {
activeStore = createInMemoryStore()
const { app } = createApp([createStubProvider("aelis.weather", weatherConfig)], MOCK_USER_ID)
const res = await patch(app, "unknown.source", { enabled: true })
expect(res.status).toBe(404)
const body = (await res.json()) as { error: string }
expect(body.error).toContain("not found")
})
test("returns 404 when user has no existing row for source", async () => {
activeStore = createInMemoryStore()
const { app } = createApp([createStubProvider("aelis.weather", weatherConfig)], MOCK_USER_ID)
const res = await patch(app, "aelis.weather", { enabled: true })
expect(res.status).toBe(404)
const body = (await res.json()) as { error: string }
expect(body.error).toContain("not found")
})
test("returns 204 when body is empty object (no-op) on existing source", async () => {
activeStore = createInMemoryStore()
activeStore.seed(MOCK_USER_ID, "aelis.weather")
const { app } = createApp([createStubProvider("aelis.weather", weatherConfig)], MOCK_USER_ID)
const res = await patch(app, "aelis.weather", {})
expect(res.status).toBe(204)
})
test("returns 404 when body is empty object on nonexistent user source", async () => {
activeStore = createInMemoryStore()
const { app } = createApp([createStubProvider("aelis.weather", weatherConfig)], MOCK_USER_ID)
const res = await patch(app, "aelis.weather", {})
expect(res.status).toBe(404)
})
test("returns 400 for invalid JSON body", async () => {
activeStore = createInMemoryStore()
activeStore.seed(MOCK_USER_ID, "aelis.weather")
const { app } = createApp([createStubProvider("aelis.weather", weatherConfig)], MOCK_USER_ID)
const res = await app.request("/api/sources/aelis.weather", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: "not json",
})
expect(res.status).toBe(400)
const body = (await res.json()) as { error: string }
expect(body.error).toContain("Invalid JSON")
})
test("returns 400 when weather config fails validation", async () => {
activeStore = createInMemoryStore()
activeStore.seed(MOCK_USER_ID, "aelis.weather")
const { app } = createApp([createStubProvider("aelis.weather", weatherConfig)], MOCK_USER_ID)
const res = await patch(app, "aelis.weather", {
config: { units: "invalid" },
})
expect(res.status).toBe(400)
})
test("returns 204 and updates enabled", async () => {
activeStore = createInMemoryStore()
activeStore.seed(MOCK_USER_ID, "aelis.weather", {
enabled: true,
config: { units: "metric" },
})
const { app } = createApp([createStubProvider("aelis.weather", weatherConfig)], MOCK_USER_ID)
const res = await patch(app, "aelis.weather", { enabled: false })
expect(res.status).toBe(204)
const row = activeStore.rows.get(`${MOCK_USER_ID}:aelis.weather`)
expect(row!.enabled).toBe(false)
expect(row!.config).toEqual({ units: "metric" })
})
test("returns 204 and updates config", async () => {
activeStore = createInMemoryStore()
activeStore.seed(MOCK_USER_ID, "aelis.weather", {
config: { units: "metric" },
})
const { app } = createApp([createStubProvider("aelis.weather", weatherConfig)], MOCK_USER_ID)
const res = await patch(app, "aelis.weather", {
config: { units: "imperial" },
})
expect(res.status).toBe(204)
const row = activeStore.rows.get(`${MOCK_USER_ID}:aelis.weather`)
expect(row!.config).toEqual({ units: "imperial" })
})
test("preserves config when only updating enabled", async () => {
activeStore = createInMemoryStore()
activeStore.seed(MOCK_USER_ID, "aelis.tfl", {
enabled: true,
config: { lines: ["bakerloo"] },
})
const { app } = createApp([createStubProvider("aelis.tfl", tflConfig)], MOCK_USER_ID)
const res = await patch(app, "aelis.tfl", { enabled: false })
expect(res.status).toBe(204)
const row = activeStore.rows.get(`${MOCK_USER_ID}:aelis.tfl`)
expect(row!.enabled).toBe(false)
expect(row!.config).toEqual({ lines: ["bakerloo"] })
})
test("deep-merges config on update", async () => {
activeStore = createInMemoryStore()
activeStore.seed(MOCK_USER_ID, "aelis.weather", {
config: { units: "metric", hourlyLimit: 12 },
})
const { app } = createApp([createStubProvider("aelis.weather", weatherConfig)], MOCK_USER_ID)
const res = await patch(app, "aelis.weather", {
config: { dailyLimit: 5 },
})
expect(res.status).toBe(204)
const row = activeStore.rows.get(`${MOCK_USER_ID}:aelis.weather`)
expect(row!.config).toEqual({
units: "metric",
hourlyLimit: 12,
dailyLimit: 5,
})
})
test("refreshes source in active session after config update", async () => {
activeStore = createInMemoryStore()
activeStore.seed(MOCK_USER_ID, "aelis.weather", {
config: { units: "metric" },
})
const { app, sessionManager } = createApp(
[createStubProvider("aelis.weather", weatherConfig)],
MOCK_USER_ID,
)
const session = await sessionManager.getOrCreate(MOCK_USER_ID)
const replaceSpy = spyOn(session, "replaceSource")
const res = await patch(app, "aelis.weather", {
config: { units: "imperial" },
})
expect(res.status).toBe(204)
expect(replaceSpy).toHaveBeenCalled()
replaceSpy.mockRestore()
})
test("removes source from session when disabled", async () => {
activeStore = createInMemoryStore()
activeStore.seed(MOCK_USER_ID, "aelis.weather", {
enabled: true,
config: { units: "metric" },
})
const { app, sessionManager } = createApp(
[createStubProvider("aelis.weather", weatherConfig)],
MOCK_USER_ID,
)
const session = await sessionManager.getOrCreate(MOCK_USER_ID)
const removeSpy = spyOn(session, "removeSource")
const res = await patch(app, "aelis.weather", { enabled: false })
expect(res.status).toBe(204)
expect(removeSpy).toHaveBeenCalledWith("aelis.weather")
removeSpy.mockRestore()
})
test("accepts location source with arbitrary config (no schema)", async () => {
activeStore = createInMemoryStore()
activeStore.seed(MOCK_USER_ID, "aelis.location")
const { app } = createApp([createStubProvider("aelis.location")], MOCK_USER_ID)
const res = await patch(app, "aelis.location", {
config: { something: "value" },
})
expect(res.status).toBe(204)
})
test("updates enabled on location source", async () => {
activeStore = createInMemoryStore()
activeStore.seed(MOCK_USER_ID, "aelis.location", { enabled: true })
const { app } = createApp([createStubProvider("aelis.location")], MOCK_USER_ID)
const res = await patch(app, "aelis.location", { enabled: false })
expect(res.status).toBe(204)
const row = activeStore.rows.get(`${MOCK_USER_ID}:aelis.location`)
expect(row!.enabled).toBe(false)
})
})

View File

@@ -1,85 +0,0 @@
import type { Context, Hono } from "hono"
import { type } from "arktype"
import { createMiddleware } from "hono/factory"
import type { AuthSessionMiddleware } from "../auth/session-middleware.ts"
import type { UserSessionManager } from "../session/index.ts"
import { InvalidSourceConfigError, SourceNotFoundError } from "./errors.ts"
type Env = {
Variables: {
sessionManager: UserSessionManager
}
}
interface SourcesHttpHandlersDeps {
sessionManager: UserSessionManager
authSessionMiddleware: AuthSessionMiddleware
}
const UpdateSourceConfigRequestBody = type({
"enabled?": "boolean",
"config?": "unknown",
})
export function registerSourcesHttpHandlers(
app: Hono,
{ sessionManager, authSessionMiddleware }: SourcesHttpHandlersDeps,
) {
const inject = createMiddleware<Env>(async (c, next) => {
c.set("sessionManager", sessionManager)
await next()
})
app.patch("/api/sources/:sourceId", inject, authSessionMiddleware, handleUpdateSource)
}
async function handleUpdateSource(c: Context<Env>) {
const sourceId = c.req.param("sourceId")
if (!sourceId) {
return c.body(null, 404)
}
const sessionManager = c.get("sessionManager")
// Validate source exists as a registered provider
const provider = sessionManager.getProvider(sourceId)
if (!provider) {
return c.json({ error: `Source "${sourceId}" not found` }, 404)
}
// Parse request body
let body: unknown
try {
body = await c.req.json()
} catch {
return c.json({ error: "Invalid JSON" }, 400)
}
const parsed = UpdateSourceConfigRequestBody(body)
if (parsed instanceof type.errors) {
return c.json({ error: parsed.summary }, 400)
}
const { enabled, config: newConfig } = parsed
const user = c.get("user")!
try {
await sessionManager.updateSourceConfig(user.id, sourceId, {
enabled,
config: newConfig,
})
} catch (err) {
if (err instanceof SourceNotFoundError) {
return c.json({ error: err.message }, 404)
}
if (err instanceof InvalidSourceConfigError) {
return c.json({ error: err.message }, 400)
}
throw err
}
return c.body(null, 204)
}

View File

@@ -52,24 +52,15 @@ export function sources(db: Database, userId: string) {
}
},
/** Updates an existing user source row. Throws if the row doesn't exist. */
async updateConfig(sourceId: string, update: { enabled?: boolean; config?: unknown }) {
const set: Record<string, unknown> = { updatedAt: new Date() }
if (update.enabled !== undefined) {
set.enabled = update.enabled
}
if (update.config !== undefined) {
set.config = update.config
}
const rows = await db
.update(userSources)
.set(set)
.where(and(eq(userSources.userId, userId), eq(userSources.sourceId, sourceId)))
.returning({ id: userSources.id })
if (rows.length === 0) {
throw new SourceNotFoundError(sourceId, userId)
}
/** Creates or updates the config for a source. */
async upsertConfig(sourceId: string, config: Record<string, unknown>) {
await db
.insert(userSources)
.values({ userId, sourceId, config })
.onConflictDoUpdate({
target: [userSources.userId, userSources.sourceId],
set: { config, updatedAt: new Date() },
})
},
/** Updates the encrypted credentials for a source. Throws if the source row doesn't exist. */

View File

@@ -1,31 +1,42 @@
import { TflSource, type ITflApi, type TflLineId } from "@aelis/source-tfl"
import { type } from "arktype"
import type { Database } from "../db/index.ts"
import type { FeedSourceProvider } from "../session/feed-source-provider.ts"
export type TflSourceProviderOptions =
| { apiKey: string; client?: never }
| { apiKey?: never; client: ITflApi }
import { SourceDisabledError } from "../sources/errors.ts"
import { sources } from "../sources/user-sources.ts"
export const tflConfig = type({
export type TflSourceProviderOptions =
| { db: Database; apiKey: string; client?: never }
| { db: Database; apiKey?: never; client: ITflApi }
const tflConfig = type({
"lines?": "string[]",
})
export class TflSourceProvider implements FeedSourceProvider {
readonly sourceId = "aelis.tfl"
readonly configSchema = tflConfig
private readonly db: Database
private readonly apiKey: string | undefined
private readonly client: ITflApi | undefined
constructor(options: TflSourceProviderOptions) {
this.db = options.db
this.apiKey = "apiKey" in options ? options.apiKey : undefined
this.client = "client" in options ? options.client : undefined
}
async feedSourceForUser(_userId: string, config: unknown): Promise<TflSource> {
const parsed = tflConfig(config)
async feedSourceForUser(userId: string): Promise<TflSource> {
const row = await sources(this.db, userId).find("aelis.tfl")
if (!row || !row.enabled) {
throw new SourceDisabledError("aelis.tfl", userId)
}
const parsed = tflConfig(row.config ?? {})
if (parsed instanceof type.errors) {
throw new Error(`Invalid TFL config: ${parsed.summary}`)
throw new Error(`Invalid TFL config for user ${userId}: ${parsed.summary}`)
}
return new TflSource({

View File

@@ -1,14 +1,19 @@
import { WeatherSource, type WeatherSourceOptions } from "@aelis/source-weatherkit"
import { type } from "arktype"
import type { Database } from "../db/index.ts"
import type { FeedSourceProvider } from "../session/feed-source-provider.ts"
import { SourceDisabledError } from "../sources/errors.ts"
import { sources } from "../sources/user-sources.ts"
export interface WeatherSourceProviderOptions {
db: Database
credentials: WeatherSourceOptions["credentials"]
client?: WeatherSourceOptions["client"]
}
export const weatherConfig = type({
const weatherConfig = type({
"units?": "'metric' | 'imperial'",
"hourlyLimit?": "number",
"dailyLimit?": "number",
@@ -16,19 +21,26 @@ export const weatherConfig = type({
export class WeatherSourceProvider implements FeedSourceProvider {
readonly sourceId = "aelis.weather"
readonly configSchema = weatherConfig
private readonly db: Database
private readonly credentials: WeatherSourceOptions["credentials"]
private readonly client: WeatherSourceOptions["client"]
constructor(options: WeatherSourceProviderOptions) {
this.db = options.db
this.credentials = options.credentials
this.client = options.client
}
async feedSourceForUser(_userId: string, config: unknown): Promise<WeatherSource> {
const parsed = weatherConfig(config)
async feedSourceForUser(userId: string): Promise<WeatherSource> {
const row = await sources(this.db, userId).find("aelis.weather")
if (!row || !row.enabled) {
throw new SourceDisabledError("aelis.weather", userId)
}
const parsed = weatherConfig(row.config ?? {})
if (parsed instanceof type.errors) {
throw new Error(`Invalid weather config: ${parsed.summary}`)
throw new Error(`Invalid weather config for user ${userId}: ${parsed.summary}`)
}
return new WeatherSource({

View File

@@ -30,10 +30,8 @@
"better-auth": "^1",
"drizzle-orm": "^0.45.1",
"hono": "^4",
"lodash.merge": "^4.6.2",
},
"devDependencies": {
"@types/lodash.merge": "^4.6.9",
"drizzle-kit": "^0.31.9",
},
},
@@ -1248,10 +1246,6 @@
"@types/json5": ["@types/json5@0.0.29", "", {}, "sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ=="],
"@types/lodash": ["@types/lodash@4.17.24", "", {}, "sha512-gIW7lQLZbue7lRSWEFql49QJJWThrTFFeIMJdp3eH4tKoxm1OvEPg02rm4wCCSHS0cL3/Fizimb35b7k8atwsQ=="],
"@types/lodash.merge": ["@types/lodash.merge@4.6.9", "", { "dependencies": { "@types/lodash": "*" } }, "sha512-23sHDPmzd59kUgWyKGiOMO2Qb9YtqRO/x4IhkgNUiPQ1+5MUVqi6bCZeq9nBJ17msjIMbEIO5u+XW4Kz6aGUhQ=="],
"@types/mdast": ["@types/mdast@4.0.4", "", { "dependencies": { "@types/unist": "*" } }, "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA=="],
"@types/ms": ["@types/ms@2.1.0", "", {}, "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA=="],