docs(production): standardiserad produktionsberedskap och gap-analys
Lägger docs/production-readiness.md och siax/production-gaps.json enligt SIAX Master Definition of Done. Underlag: git-, kod- och live-evidens 2026-11-11. Nivån är evidensbaserad, inte ett leveransgodkännande.
This commit is contained in:
@@ -1,91 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
import { resetManualSyncThrottle } from '@/lib/connect/instance/manual-sync-throttle'
|
||||
|
||||
let selfHosted = true
|
||||
vi.mock('@/lib/env/public-flags', () => ({ isSelfHosted: () => selfHosted }))
|
||||
|
||||
const captured = vi.hoisted(() => ({ options: undefined as { requireWrite?: boolean } | undefined }))
|
||||
vi.mock('@/lib/api/with-route-context', () => ({
|
||||
withRouteContext: (
|
||||
_op: string,
|
||||
handler: (req: unknown, ctx: unknown) => unknown,
|
||||
options?: { requireWrite?: boolean },
|
||||
) => {
|
||||
captured.options = options
|
||||
return (req: unknown) =>
|
||||
handler(req, {
|
||||
supabase: {},
|
||||
companyId: 'company-1',
|
||||
user: { id: 'u1' },
|
||||
log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
|
||||
})
|
||||
},
|
||||
}))
|
||||
|
||||
const syncMock = vi.fn()
|
||||
vi.mock('@/lib/connect/instance/sync', () => ({
|
||||
syncConnectorEntitlements: (...args: unknown[]) => syncMock(...args),
|
||||
}))
|
||||
vi.mock('@/lib/supabase/server', () => ({ createServiceClient: () => ({ __service: true }) }))
|
||||
|
||||
import { POST } from '../route'
|
||||
|
||||
const run = () => POST(createMockRequest('/api/connector/sync', { method: 'POST' }), { params: Promise.resolve({}) })
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
resetManualSyncThrottle()
|
||||
selfHosted = true
|
||||
vi.stubEnv('GNUBOK_CONNECTOR_KEY', 'gnubok_ck_secretsecret')
|
||||
syncMock.mockResolvedValue({ outcome: 'synced', companies: 2, grantsUpserted: 4, grantsDeleted: 0, scopes: ['bank_sync'] })
|
||||
})
|
||||
afterEach(() => vi.unstubAllEnvs())
|
||||
|
||||
describe('POST /api/connector/sync', () => {
|
||||
it('requires a non-viewer role', () => {
|
||||
expect(captured.options).toEqual({ requireWrite: true })
|
||||
})
|
||||
|
||||
it('answers not_configured on hosted without running the sync', async () => {
|
||||
selfHosted = false
|
||||
const { status, body } = await parseJsonResponse<{ data: { outcome: string } }>(await run())
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.outcome).toBe('not_configured')
|
||||
expect(syncMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('answers not_configured when no connector key is set', async () => {
|
||||
vi.stubEnv('GNUBOK_CONNECTOR_KEY', '')
|
||||
const { body } = await parseJsonResponse<{ data: { outcome: string } }>(await run())
|
||||
expect(body.data.outcome).toBe('not_configured')
|
||||
expect(syncMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('runs the entitlement sync with the service client and returns the result', async () => {
|
||||
const { status, body } = await parseJsonResponse<{ data: { outcome: string; grantsUpserted: number } }>(await run())
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.outcome).toBe('synced')
|
||||
expect(body.data.grantsUpserted).toBe(4)
|
||||
expect(syncMock).toHaveBeenCalledTimes(1)
|
||||
expect(syncMock.mock.calls[0][0]).toEqual({ __service: true })
|
||||
expect(Object.keys(syncMock.mock.calls[0][1] as object)).toEqual(
|
||||
expect.arrayContaining(['instanceUrl', 'appVersion']),
|
||||
)
|
||||
})
|
||||
|
||||
it('refuses a second run inside the cooldown window', async () => {
|
||||
await run()
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(await run())
|
||||
expect(status).toBe(429)
|
||||
expect(body.error.code).toBe('CONNECTOR_SYNC_COOLDOWN')
|
||||
expect(syncMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('keeps the cooldown even when the sync throws', async () => {
|
||||
syncMock.mockRejectedValueOnce(new Error('db down'))
|
||||
await expect(run()).rejects.toThrow('db down')
|
||||
const { status } = await parseJsonResponse<{ error: { code: string } }>(await run())
|
||||
expect(status).toBe(429)
|
||||
})
|
||||
})
|
||||
@@ -1,54 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
|
||||
const h = vi.hoisted(() => ({
|
||||
logInfo: vi.fn(),
|
||||
logError: vi.fn(),
|
||||
sync: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/api/with-cron-context', () => ({
|
||||
withCronContext:
|
||||
(_name: string, handler: (req: Request, ctx: unknown) => Promise<Response>) =>
|
||||
(req: Request) =>
|
||||
handler(req, { log: { info: h.logInfo, error: h.logError, warn: vi.fn() }, requestId: 'cron_test' }),
|
||||
}))
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createServiceClient: () => ({ from: vi.fn() }),
|
||||
}))
|
||||
vi.mock('@/lib/connect/instance/sync', () => ({
|
||||
syncConnectorEntitlements: (...args: unknown[]) => h.sync(...args),
|
||||
}))
|
||||
|
||||
import { GET } from '../route'
|
||||
|
||||
beforeEach(() => vi.clearAllMocks())
|
||||
afterEach(() => vi.unstubAllEnvs())
|
||||
|
||||
describe('GET /api/connector/sync/cron', () => {
|
||||
it('answers not_configured without a key and never calls the sync', async () => {
|
||||
vi.stubEnv('GNUBOK_CONNECTOR_KEY', '')
|
||||
const res = await GET(new Request('http://localhost:3000/api/connector/sync/cron'))
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ data: { outcome: 'not_configured' } })
|
||||
expect(h.sync).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('runs the sync with the instance origin and returns its result', async () => {
|
||||
vi.stubEnv('GNUBOK_CONNECTOR_KEY', 'gnubok_ck_x')
|
||||
vi.stubEnv('NEXT_PUBLIC_APP_URL', 'https://bokforing.example.se')
|
||||
h.sync.mockResolvedValue({ outcome: 'synced', companies: 2, grantsUpserted: 8, grantsDeleted: 0 })
|
||||
const res = await GET(new Request('http://localhost:3000/api/connector/sync/cron'))
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ data: { outcome: 'synced', companies: 2, grantsUpserted: 8, grantsDeleted: 0 } })
|
||||
expect(h.sync).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ instanceUrl: 'https://bokforing.example.se' }))
|
||||
expect(h.logInfo).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('logs and returns an error envelope when the sync throws', async () => {
|
||||
vi.stubEnv('GNUBOK_CONNECTOR_KEY', 'gnubok_ck_x')
|
||||
h.sync.mockRejectedValue(new Error('Failed to upsert connector grants: boom'))
|
||||
const res = await GET(new Request('http://localhost:3000/api/connector/sync/cron'))
|
||||
expect(res.status).toBeGreaterThanOrEqual(500)
|
||||
expect(h.logError).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -1,37 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withCronContext } from '@/lib/api/with-cron-context'
|
||||
import { createServiceClient } from '@/lib/supabase/server'
|
||||
import { getConnectorConfig } from '@/lib/connect/instance/config'
|
||||
import { syncConnectorEntitlements } from '@/lib/connect/instance/sync'
|
||||
import { errorResponse } from '@/lib/errors/get-structured-error'
|
||||
|
||||
/**
|
||||
* GET /api/connector/sync/cron: hourly on SELF-HOSTED deployments only
|
||||
* (docker/crontab.self-hosted via EXTRA_JOBS in scripts/generate-crontabs.ts;
|
||||
* deliberately not in vercel.json, hosted has no connector key).
|
||||
*
|
||||
* Validates GNUBOK_CONNECTOR_KEY against the hosted connector service,
|
||||
* reports the active company count, and refreshes the source='connector'
|
||||
* capability grants for every company on this instance. Grant expiry
|
||||
* (min(now + 72h, period_end + 3d)) is the offline grace: a hosted outage
|
||||
* shorter than that changes nothing here. An instance without a key answers
|
||||
* 200 with outcome not_configured, so the schedule costs one cheap request.
|
||||
*/
|
||||
export const maxDuration = 60
|
||||
|
||||
export const GET = withCronContext('cron.connector_sync', async (_request, ctx) => {
|
||||
if (!getConnectorConfig()) {
|
||||
return NextResponse.json({ data: { outcome: 'not_configured' } })
|
||||
}
|
||||
try {
|
||||
const result = await syncConnectorEntitlements(createServiceClient(), {
|
||||
instanceUrl: process.env.NEXT_PUBLIC_APP_URL?.trim() || null,
|
||||
appVersion: process.env.npm_package_version ?? null,
|
||||
})
|
||||
ctx.log.info('connector sync run', { ...result })
|
||||
return NextResponse.json({ data: result })
|
||||
} catch (err) {
|
||||
ctx.log.error('connector sync failed', err)
|
||||
return errorResponse(err, ctx.log, { requestId: ctx.requestId })
|
||||
}
|
||||
})
|
||||
@@ -1,55 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { isSelfHosted } from '@/lib/env/public-flags'
|
||||
import { createServiceClient } from '@/lib/supabase/server'
|
||||
import { getConnectorConfig } from '@/lib/connect/instance/config'
|
||||
import { syncConnectorEntitlements } from '@/lib/connect/instance/sync'
|
||||
import {
|
||||
endManualSync,
|
||||
tryBeginManualSync,
|
||||
} from '@/lib/connect/instance/manual-sync-throttle'
|
||||
|
||||
/**
|
||||
* POST /api/connector/sync: operator-triggered run of the same entitlement
|
||||
* sync the hourly self-hosted cron performs (/api/connector/sync/cron),
|
||||
* for the "Synka nu" row in Settings -> Abonnemang. Runs with the service
|
||||
* client because grants are instance-wide (every company on the instance),
|
||||
* so the caller must hold a non-viewer role (requireWrite) and runs are
|
||||
* cooldown-gated: each one reports to the hosted entitlements endpoint.
|
||||
*
|
||||
* Hosted (or an instance without a key) answers 200 not_configured rather
|
||||
* than an error: the settings row is hidden there and this is the backstop.
|
||||
*/
|
||||
export const maxDuration = 60
|
||||
|
||||
export const POST = withRouteContext(
|
||||
'connector.sync',
|
||||
async (_request, { log }) => {
|
||||
if (!isSelfHosted() || !getConnectorConfig()) {
|
||||
return NextResponse.json({ data: { outcome: 'not_configured' } })
|
||||
}
|
||||
if (!tryBeginManualSync()) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'CONNECTOR_SYNC_COOLDOWN',
|
||||
message: 'En synkronisering kördes nyss. Vänta en minut och försök igen.',
|
||||
message_en: 'A sync just ran. Wait a minute and try again.',
|
||||
},
|
||||
},
|
||||
{ status: 429, headers: { 'Retry-After': '60' } },
|
||||
)
|
||||
}
|
||||
try {
|
||||
const result = await syncConnectorEntitlements(createServiceClient(), {
|
||||
instanceUrl: process.env.NEXT_PUBLIC_APP_URL?.trim() || null,
|
||||
appVersion: process.env.npm_package_version ?? null,
|
||||
})
|
||||
log.info('manual connector sync run', { ...result })
|
||||
return NextResponse.json({ data: result })
|
||||
} finally {
|
||||
endManualSync()
|
||||
}
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
Reference in New Issue
Block a user