Skip to content
Open
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
12 changes: 7 additions & 5 deletions packages/dsh-weknora/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,10 +142,10 @@ export class WeknoraClient {
return url.toString()
}

private isPublicModeForbidden(error: unknown): boolean {
private isPublicModeForbidden(error: unknown, requestedMode: 'handle' | 'public'): boolean {
// Another request may have switched the client to handle mode while this one was in flight.
return error instanceof WeknoraApiError
&& this.config.resourceUrls === 'public'
&& !this.publicModeBlocked
&& requestedMode === 'public'
&& error.status === 403
&& error.message.includes('resource_urls=public')
}
Expand All @@ -155,10 +155,11 @@ export class WeknoraClient {
init: { method: 'GET' | 'POST', body?: unknown, query?: Record<string, string | number | undefined> },
signal: AbortSignal,
): Promise<Envelope<T>> {
const requestedMode = this.resourceMode()
try {
return await this.fetchJsonOnce(path, init, signal)
} catch (error) {
if (!this.isPublicModeForbidden(error)) throw error
if (!this.isPublicModeForbidden(error, requestedMode)) throw error
this.publicModeBlocked = true
return await this.fetchJsonOnce(path, init, signal)
}
Expand Down Expand Up @@ -308,11 +309,12 @@ export class WeknoraClient {
throw new WeknoraApiError(`POST ${path} failed: ${describeTransportFailure(cause, signal)}`)
}
}
const requestedMode = this.resourceMode()
let response = await open()
if (!response.ok) {
const text = await response.text()
const error = new WeknoraApiError(`POST ${path} failed with HTTP ${response.status}: ${reasonOf(text)}`, response.status)
if (!this.isPublicModeForbidden(error)) throw error
if (!this.isPublicModeForbidden(error, requestedMode)) throw error
this.publicModeBlocked = true
response = await open()
}
Expand Down
36 changes: 36 additions & 0 deletions packages/dsh-weknora/test/client.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,42 @@ test('a knowledge-base-restricted key falls back from public URLs to handles', a
assert.equal(mock.requests.at(-1).query.resource_urls, undefined, 'later calls must not retry public mode')
})

for (const first of ['list', 'chat']) test(`concurrent public-mode requests each fall back when ${first} is refused first`, async (t) => {
const client = new WeknoraClient(resolveConfig({ baseUrl: 'https://weknora.example/api/v1' }))
const publicResponses = new Map()
const retried = []
const answer = 'data: {"response_type":"answer","content":"answer"}\n\ndata: {"response_type":"complete"}\n\n'
t.mock.method(globalThis, 'fetch', (url) => {
const { pathname, searchParams } = new URL(url)
if (searchParams.has('resource_urls')) {
return new Promise(resolve => publicResponses.set(pathname, resolve))
}
retried.push(pathname)
return Promise.resolve(new Response(pathname.includes('agent-chat') ? answer : '{"data":[]}'))
})

const listing = client.listKnowledgeBases(never)
const chat = client.ask(
{ sessionId: 's1', query: 'question', knowledgeBaseIds: [], agentId: 'agent-9', webSearch: false },
never,
)
const forbidden = () => new Response('resource_urls=public is forbidden', { status: 403 })
const listPath = '/api/v1/knowledge-bases'
const chatPath = '/api/v1/agent-chat/s1'
assert.deepEqual([...publicResponses.keys()], [listPath, chatPath])

const paths = first === 'list' ? [listPath, chatPath] : [chatPath, listPath]
const completed = new Map([
[listPath, listing.then(bases => assert.deepEqual(bases, []))],
[chatPath, chat.then(result => assert.equal(result.answer, 'answer'))],
])
for (const path of paths) {
publicResponses.get(path)(forbidden())
await completed.get(path)
}
assert.deepEqual(retried, paths)
})

test('chunk pages carry their pagination envelope', async () => {
const { client } = await harness()
const page = await client.listChunks({ knowledgeId: 'doc-retrieval-pipeline', page: 1, pageSize: 2 }, never)
Expand Down
Loading