-
Notifications
You must be signed in to change notification settings - Fork 13
feat(agent-bff): audit reads and action executions #1885
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
nbouliol
wants to merge
1
commit into
main
Choose a base branch
from
feature/prd-1150-bff-activity-logs
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
20 changes: 20 additions & 0 deletions
20
packages/agent-bff/src/activity-log/activity-log-drainer.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| /** | ||
| * Holds the status transitions that are fired without `await`. Nothing else keeps them alive: | ||
| * `server.close()` waits for connections, and a transition sent after the response is attached to | ||
| * none — without this, every deploy would leave entries stuck in `pending`. | ||
| */ | ||
| export default class ActivityLogDrainer { | ||
| private readonly inFlight = new Set<Promise<unknown>>(); | ||
|
|
||
| track<T>(operation: () => Promise<T>): Promise<T> { | ||
| const promise = operation(); | ||
| this.inFlight.add(promise); | ||
| promise.finally(() => this.inFlight.delete(promise)).catch(() => {}); | ||
|
|
||
| return promise; | ||
| } | ||
|
|
||
| async drain(): Promise<void> { | ||
| await Promise.allSettled([...this.inFlight]); | ||
| } | ||
| } |
43 changes: 43 additions & 0 deletions
43
packages/agent-bff/src/activity-log/activity-log-writer.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| import type { ActivityLogContext, BffActivityLogAction } from './activity-logs-creator'; | ||
| import type { ActivityLogsWriter } from './activity-logs-service'; | ||
| import type { Logger } from '../ports/logger-port'; | ||
| import type { Context } from 'koa'; | ||
|
|
||
| import ActivityLogDrainer from './activity-log-drainer'; | ||
| import withActivityLog from './with-activity-log'; | ||
|
|
||
| export interface RecordActivityLogOptions<T> { | ||
| ctx: Context; | ||
| action: BffActivityLogAction; | ||
| context?: ActivityLogContext; | ||
| operation: () => Promise<T>; | ||
| isCompletedDespite?: (error: unknown) => boolean; | ||
| } | ||
|
|
||
| export interface ActivityLogWriter { | ||
| record<T>(options: RecordActivityLogOptions<T>): Promise<T>; | ||
| /** Waits for the status transitions no connection holds. Called when the server stops. */ | ||
| drain(): Promise<void>; | ||
| } | ||
|
|
||
| export interface ActivityLogWriterOptions { | ||
| service: ActivityLogsWriter; | ||
| logger: Logger; | ||
| } | ||
|
|
||
| export default function createActivityLogWriter({ | ||
| service, | ||
| logger, | ||
| }: ActivityLogWriterOptions): ActivityLogWriter { | ||
| const drainer = new ActivityLogDrainer(); | ||
|
|
||
| return { | ||
| record<T>(options: RecordActivityLogOptions<T>): Promise<T> { | ||
| return withActivityLog({ ...options, service, drainer, logger }); | ||
| }, | ||
|
|
||
| drain(): Promise<void> { | ||
| return drainer.drain(); | ||
| }, | ||
| }; | ||
| } |
216 changes: 216 additions & 0 deletions
216
packages/agent-bff/src/activity-log/activity-logs-creator.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,216 @@ | ||
| import type ActivityLogDrainer from './activity-log-drainer'; | ||
| import type { ActivityLogsWriter } from './activity-logs-service'; | ||
| import type { Logger } from '../ports/logger-port'; | ||
| import type { | ||
| ActivityLogAction, | ||
| ActivityLogResponse, | ||
| ActivityLogType, | ||
| } from '@forestadmin/forestadmin-client'; | ||
| import type { Context } from 'koa'; | ||
|
|
||
| import { HttpError, NotFoundError } from '@forestadmin/forestadmin-client'; | ||
|
|
||
| import { | ||
| resolveForestServerToken, | ||
| resolveRenderingId, | ||
| } from '../auth/forest-server-token-middleware'; | ||
| import { sessionExpired } from '../http/bff-http-error'; | ||
| import { | ||
| AUDIT_RETRY_AFTER_SECONDS, | ||
| auditNotAuthorized, | ||
| auditUnavailable, | ||
| } from '../http/bff-local-errors'; | ||
|
|
||
| /** The actions the BFF writes: its data routes read, and its action route writes. */ | ||
| export type BffActivityLogAction = Extract< | ||
| ActivityLogAction, | ||
| 'index' | 'search' | 'filter' | 'listRelatedData' | 'action' | ||
| >; | ||
|
|
||
| /** | ||
| * Fail policy for the audit trail, keyed by action type: a write whose activity log cannot be | ||
| * created is blocked (no unaudited side effect), while a read proceeds with a warning (an audit | ||
| * store outage must not take down the read surface). | ||
| * | ||
| * One case is arbitrated by the cause instead of the action type: an authorization refusal | ||
| * (401/403) propagates for reads too — the read itself is not authorized either. | ||
| */ | ||
| const ACTION_TO_TYPE: Record<BffActivityLogAction, ActivityLogType> = { | ||
| index: 'read', | ||
| search: 'read', | ||
| filter: 'read', | ||
| listRelatedData: 'read', | ||
| action: 'write', | ||
| }; | ||
|
|
||
| const MAX_STATUS_ATTEMPTS = 5; | ||
| const STATUS_RETRY_DELAY_MS = 500; | ||
|
|
||
| const NO_RENDERING_MESSAGE = 'This request carries no usable rendering'; | ||
|
|
||
| export interface ActivityLogContext { | ||
| collectionName?: string; | ||
| recordId?: string | number; | ||
| recordIds?: string[] | number[]; | ||
| label?: string; | ||
| } | ||
|
|
||
| /** | ||
| * The token that created the log is kept for the status transition: the transition is fired after | ||
| * the response, when the session it came from may already be unreachable. | ||
| */ | ||
| export interface PendingActivityLog { | ||
| activityLog: ActivityLogResponse; | ||
| forestServerToken: string; | ||
| } | ||
|
|
||
| export interface CreatePendingActivityLogOptions { | ||
| ctx: Context; | ||
| service: ActivityLogsWriter; | ||
| action: BffActivityLogAction; | ||
| context?: ActivityLogContext; | ||
| logger: Logger; | ||
| } | ||
|
|
||
| interface AuditCredentials { | ||
| forestServerToken: string; | ||
| renderingId: string; | ||
| } | ||
|
|
||
| function describeCause(error: unknown): string { | ||
| return error instanceof Error ? `${error.name}: ${error.message}` : String(error); | ||
| } | ||
|
|
||
| function isAuthorizationRefusal(error: unknown): boolean { | ||
| return error instanceof HttpError && (error.status === 401 || error.status === 403); | ||
| } | ||
|
|
||
| async function resolveCredentials(ctx: Context): Promise<AuditCredentials> { | ||
| const renderingId = resolveRenderingId(ctx); | ||
|
|
||
| if (renderingId === undefined) throw sessionExpired(NO_RENDERING_MESSAGE); | ||
|
|
||
| return { | ||
| forestServerToken: await resolveForestServerToken(ctx), | ||
| renderingId: String(renderingId), | ||
| }; | ||
| } | ||
|
|
||
| export default async function createPendingActivityLog({ | ||
| ctx, | ||
| service, | ||
| action, | ||
| context, | ||
| logger, | ||
| }: CreatePendingActivityLogOptions): Promise<PendingActivityLog | null> { | ||
| const type = ACTION_TO_TYPE[action]; | ||
|
|
||
| let credentials: AuditCredentials; | ||
|
|
||
| try { | ||
| credentials = await resolveCredentials(ctx); | ||
| } catch (error) { | ||
| logger('Error', `Activity log for '${action}' has no credentials to be created with`, { | ||
| cause: describeCause(error), | ||
| }); | ||
|
|
||
| if (type === 'write') throw error; | ||
|
|
||
| return null; | ||
| } | ||
|
|
||
| const { forestServerToken, renderingId } = credentials; | ||
|
|
||
| let activityLog: ActivityLogResponse; | ||
|
|
||
| try { | ||
| activityLog = await service.createMcpActivityLog({ | ||
| forestServerToken, | ||
| renderingId, | ||
| action, | ||
| type, | ||
| collectionName: context?.collectionName, | ||
| recordId: context?.recordId, | ||
| recordIds: context?.recordIds, | ||
| label: context?.label, | ||
| }); | ||
| } catch (error) { | ||
| logger('Error', `Activity log for '${action}' could not be created`, { | ||
| cause: describeCause(error), | ||
| }); | ||
|
|
||
| if (isAuthorizationRefusal(error)) throw auditNotAuthorized(); | ||
| if (type === 'write') throw auditUnavailable(AUDIT_RETRY_AFTER_SECONDS); | ||
|
|
||
| return null; | ||
| } | ||
|
|
||
| if (activityLog?.id === null || activityLog?.id === undefined) { | ||
| if (type === 'write') throw auditUnavailable(AUDIT_RETRY_AFTER_SECONDS); | ||
|
|
||
| logger( | ||
| 'Error', | ||
| `Activity log for '${action}' could not be created: the server answered with no activity ` + | ||
| 'log id, so the audit store dropped the write', | ||
| ); | ||
|
|
||
| return null; | ||
| } | ||
|
|
||
| return { activityLog, forestServerToken }; | ||
| } | ||
|
|
||
| export interface MarkActivityLogOptions { | ||
| service: ActivityLogsWriter; | ||
| drainer: ActivityLogDrainer; | ||
| pending: PendingActivityLog; | ||
| status: 'completed' | 'failed'; | ||
| logger: Logger; | ||
| } | ||
|
|
||
| async function updateStatus(options: MarkActivityLogOptions, attempt = 1): Promise<void> { | ||
| const { service, pending, status, logger } = options; | ||
|
|
||
| try { | ||
| await service.updateActivityLogStatus({ | ||
| forestServerToken: pending.forestServerToken, | ||
| activityLog: pending.activityLog, | ||
| status, | ||
| }); | ||
| } catch (error) { | ||
| // The document may not exist yet when the transition lands, and only then is a retry worth | ||
| // anything: a network failure loses the transition permanently. | ||
| if (error instanceof NotFoundError && attempt < MAX_STATUS_ATTEMPTS) { | ||
| logger('Debug', `Activity log not found, retrying its status transition`, { | ||
| attempt, | ||
| attempts: MAX_STATUS_ATTEMPTS, | ||
| }); | ||
|
|
||
| await new Promise<void>(resolve => { | ||
| setTimeout(resolve, STATUS_RETRY_DELAY_MS); | ||
| }); | ||
|
|
||
| await updateStatus(options, attempt + 1); | ||
|
|
||
| return; | ||
| } | ||
|
|
||
| throw error; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Fire-and-forget on purpose: the caller's response must not wait for the audit store. The drainer | ||
| * holds the promise so a shutdown can wait for it instead. | ||
| */ | ||
| export function markActivityLog(options: MarkActivityLogOptions): void { | ||
| const { drainer, status, logger } = options; | ||
|
|
||
| drainer | ||
| .track(() => updateStatus(options)) | ||
| .catch(error => { | ||
| logger('Error', `Failed to mark the activity log as '${status}'`, { | ||
| cause: describeCause(error), | ||
| }); | ||
| }); | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🟡 Medium
activity-log/activity-logs-creator.ts:183When
updateActivityLogStatusencounters a transient transport or 5xx failure, the activity log remains permanentlypendingeven though the audited operation has finished, corrupting audit status and action-failure statistics.updateStatusretries onlyNotFoundError, so these recoverable failures reach the fire-and-forget catcher immediately; add bounded retries for transient status-update failures while preserving non-retryable errors.🚀 Reply "fix it for me" or copy this AI Prompt for your agent: