-
Notifications
You must be signed in to change notification settings - Fork 4
Add BLN3 score calculation with caching #608
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
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
c09b5bf
feat: Add BLN3 score calculation module. Exports `requestBln3Score` (…
SvenVw 8fcf89d
Merge branch 'FDM573' into FDM574
SvenVw bc16545
Merge branch 'development' into FDM574
SvenVw 850b5cd
feat: add abortController for bln3 request
SvenVw c0c4db8
feat: add check for bln3 response status
SvenVw ccee20d
refactor: rename file for consistency
SvenVw 960d951
test: add test for fetching
SvenVw 5414df6
refactor: implement review feedback
SvenVw a9c414d
fix: type error
SvenVw 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| "@nmi-agro/fdm-calculator": minor | ||
| --- | ||
|
|
||
| Add BLN3 score calculation module. Exports `requestBln3Score` (raw NMI API call to `POST /maatwerk/bln3/score/field`), `getBln3Score` (cached wrapper via `withCalculationCache`), and `collectInputForBln3Score` (assembles field inputs from fdm-core: lat/lon from field centroid, soil analysis parameters, cultivations mapped from BRP catalogue codes, and adopted BLN measures). Types exported: `Bln3Score`, `Bln3ScoreInputs`, `Bln3ScoreCollectedInputs`, `Bln3IndicatorResult`, `Bln3AggregationResult`. |
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,265 @@ | ||
| import { | ||
| afterAll, | ||
| afterEach, | ||
| beforeAll, | ||
| describe, | ||
| expect, | ||
| it, | ||
| vi, | ||
| } from "vitest" | ||
| import { getBln3Score, requestBln3Score } from "./index" | ||
| import type { Bln3Score, Bln3ScoreInputs, Bln3ScoreResponse } from "./types" | ||
|
|
||
| const mockBln3ScoreResponse: Bln3ScoreResponse = { | ||
| request_id: "test-uuid", | ||
| success: true, | ||
| status: 200, | ||
| message: null, | ||
| data: { | ||
| indicator: [ | ||
| { | ||
| indicator_id: "C_P", | ||
| status: 4.9398, | ||
| target: 6, | ||
| index: 0.9752, | ||
| impact: 0, | ||
| score: 0.9752, | ||
| }, | ||
| { | ||
| indicator_id: "C_K", | ||
| status: 0.7559, | ||
| target: 30, | ||
| index: 0.1748, | ||
| impact: 0, | ||
| score: 0.1748, | ||
| }, | ||
| ], | ||
| }, | ||
| } | ||
|
|
||
| const baseInputs: Bln3ScoreInputs = { | ||
| nmiApiKey: "mock-api-key", | ||
| a_lat: 51.613, | ||
| a_lon: 5.2, | ||
| } | ||
|
|
||
| describe("requestBln3Score", () => { | ||
| beforeAll(() => { | ||
| vi.stubGlobal("fetch", vi.fn()) | ||
| }) | ||
|
|
||
| afterEach(() => { | ||
| vi.mocked(fetch).mockClear() | ||
| }) | ||
|
|
||
| afterAll(() => { | ||
| vi.restoreAllMocks() | ||
| }) | ||
|
|
||
| it("should throw if nmiApiKey is not provided", async () => { | ||
| const inputs: Bln3ScoreInputs = { ...baseInputs, nmiApiKey: undefined } | ||
| await expect(requestBln3Score(inputs)).rejects.toThrow( | ||
| "NMI API key not provided", | ||
| ) | ||
| expect(fetch).not.toHaveBeenCalled() | ||
| }) | ||
|
|
||
| it("should call the NMI API with correct URL, headers, and body", async () => { | ||
| vi.mocked(fetch).mockResolvedValueOnce({ | ||
| ok: true, | ||
| json: async () => mockBln3ScoreResponse, | ||
| } as Response) | ||
|
|
||
| const inputs: Bln3ScoreInputs = { | ||
| ...baseInputs, | ||
| cultivations: [{ b_lu_brp: 266, b_lu_year: 2025 }], | ||
| measures: [{ measure_id: "BM3", year: 2025 }], | ||
| } | ||
|
|
||
| await requestBln3Score(inputs) | ||
|
|
||
| expect(fetch).toHaveBeenCalledTimes(1) | ||
| expect(fetch).toHaveBeenCalledWith( | ||
| "https://api.nmi-agro.nl/maatwerk/bln3/score/field", | ||
| expect.objectContaining({ | ||
| method: "POST", | ||
| headers: { | ||
| Authorization: "Bearer mock-api-key", | ||
| "Content-Type": "application/json", | ||
| }, | ||
| body: JSON.stringify({ | ||
| a_lat: 51.613, | ||
| a_lon: 5.2, | ||
| cultivations: [{ b_lu_brp: 266, b_lu_year: 2025 }], | ||
| measures: [{ measure_id: "BM3", year: 2025 }], | ||
| }), | ||
| }), | ||
| ) | ||
| }) | ||
|
|
||
| it("should return mapped Bln3Score with indicators (plural)", async () => { | ||
| vi.mocked(fetch).mockResolvedValueOnce({ | ||
| ok: true, | ||
| json: async () => mockBln3ScoreResponse, | ||
| } as Response) | ||
|
|
||
| const result = await requestBln3Score(baseInputs) | ||
|
|
||
| expect(result).toEqual<Bln3Score>({ | ||
| indicators: mockBln3ScoreResponse.data.indicator, | ||
| aggregations: undefined, | ||
| }) | ||
| }) | ||
|
SvenVw marked this conversation as resolved.
|
||
|
|
||
| it("should throw if the NMI API returns a non-ok response", async () => { | ||
| vi.mocked(fetch).mockResolvedValueOnce({ | ||
| ok: false, | ||
| status: 500, | ||
| statusText: "Internal Server Error", | ||
| text: vi.fn().mockResolvedValue("upstream error"), | ||
| } as unknown as Response) | ||
|
|
||
| await expect(requestBln3Score(baseInputs)).rejects.toThrow( | ||
| "BLN3 score request failed with status 500", | ||
| ) | ||
| expect(fetch).toHaveBeenCalledTimes(1) | ||
| }) | ||
|
|
||
| it("should throw if the NMI API returns success: false", async () => { | ||
| vi.mocked(fetch).mockResolvedValueOnce({ | ||
| ok: true, | ||
| json: async () => ({ | ||
| success: false, | ||
| status: 400, | ||
| message: "semantic failure message", | ||
| }), | ||
| } as Response) | ||
|
|
||
| await expect(requestBln3Score(baseInputs)).rejects.toThrow( | ||
| "BLN3 score API returned failure (status 400): semantic failure message", | ||
| ) | ||
| expect(fetch).toHaveBeenCalledTimes(1) | ||
| }) | ||
|
|
||
| it("should throw if the NMI API returns a malformed payload", async () => { | ||
| vi.mocked(fetch).mockResolvedValueOnce({ | ||
| ok: true, | ||
| json: async () => ({ | ||
| success: true, | ||
| status: 200, | ||
| data: {}, // Missing indicator | ||
| }), | ||
| } as Response) | ||
|
|
||
| await expect(requestBln3Score(baseInputs)).rejects.toThrow( | ||
| "BLN3 score API returned a malformed payload", | ||
| ) | ||
| }) | ||
|
|
||
| it("should rethrow network errors from fetch", async () => { | ||
| vi.mocked(fetch).mockRejectedValueOnce(new Error("Network connection lost")) | ||
|
|
||
| await expect(requestBln3Score(baseInputs)).rejects.toThrow( | ||
| "Network connection lost", | ||
| ) | ||
| }) | ||
|
|
||
| it("should map AbortError to a specific timeout message", async () => { | ||
| const abortError = new Error("The operation was aborted") | ||
| abortError.name = "AbortError" | ||
| vi.mocked(fetch).mockRejectedValueOnce(abortError) | ||
|
|
||
| await expect(requestBln3Score(baseInputs)).rejects.toThrow( | ||
| "BLN3 score request timed out (30s). The NMI API did not respond in time.", | ||
| ) | ||
| }) | ||
| }) | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| describe("getBln3Score cache semantics", () => { | ||
| let mockRows: any[] = [] | ||
| const mockFdm = { | ||
| select: vi.fn().mockReturnThis(), | ||
| from: vi.fn().mockReturnThis(), | ||
| where: vi.fn().mockReturnThis(), | ||
| limit: vi.fn().mockImplementation(() => ({ | ||
| then: (cb: any) => Promise.resolve(cb(mockRows)), | ||
| })), | ||
| insert: vi.fn().mockReturnThis(), | ||
| values: vi.fn().mockReturnThis(), | ||
| onConflictDoUpdate: vi.fn().mockReturnThis(), | ||
| catch: vi.fn().mockResolvedValue(undefined), | ||
| } as any | ||
|
|
||
| const mockResult: Bln3Score = { | ||
| indicators: mockBln3ScoreResponse.data.indicator, | ||
| } | ||
|
|
||
| beforeAll(() => { | ||
| vi.stubGlobal("fetch", vi.fn()) | ||
| }) | ||
|
|
||
| afterEach(() => { | ||
| mockRows = [] | ||
| vi.clearAllMocks() | ||
| }) | ||
|
|
||
| afterAll(() => { | ||
| vi.restoreAllMocks() | ||
| }) | ||
|
|
||
| it("should call fetch and store result on cache miss", async () => { | ||
| vi.mocked(fetch).mockResolvedValueOnce({ | ||
| ok: true, | ||
| json: async () => mockBln3ScoreResponse, | ||
| } as Response) | ||
|
|
||
| mockRows = [] // Cache miss | ||
|
|
||
| const result = await getBln3Score(mockFdm, baseInputs) | ||
|
|
||
| expect(result).toEqual(mockResult) | ||
| expect(fetch).toHaveBeenCalledTimes(1) | ||
| expect(mockFdm.select).toHaveBeenCalled() | ||
| expect(mockFdm.insert).toHaveBeenCalled() | ||
| }) | ||
|
|
||
| it("should return cached result on cache hit without calling fetch", async () => { | ||
| mockRows = [{ result: mockResult }] // Cache hit | ||
|
|
||
| const result = await getBln3Score(mockFdm, baseInputs) | ||
|
|
||
| expect(result).toEqual(mockResult) | ||
| expect(fetch).not.toHaveBeenCalled() | ||
| expect(mockFdm.select).toHaveBeenCalled() | ||
| expect(mockFdm.insert).not.toHaveBeenCalled() | ||
| }) | ||
|
|
||
| it("should proceed with calculation and log error if cache read fails", async () => { | ||
| vi.mocked(fetch).mockResolvedValueOnce({ | ||
| ok: true, | ||
| json: async () => mockBln3ScoreResponse, | ||
| } as Response) | ||
|
|
||
| // Mock select chain to throw | ||
| mockFdm.limit.mockImplementationOnce(() => ({ | ||
| then: () => Promise.reject(new Error("DB Error")), | ||
| })) | ||
| const spyConsole = vi.spyOn(console, "error").mockImplementation(() => {}) | ||
|
|
||
| const result = await getBln3Score(mockFdm, baseInputs) | ||
|
|
||
| expect(result).toEqual(mockResult) | ||
| expect(fetch).toHaveBeenCalledTimes(1) | ||
| expect(spyConsole).toHaveBeenCalledWith( | ||
| expect.stringContaining("Failed to read from calculation cache"), | ||
| ) | ||
| spyConsole.mockRestore() | ||
| }) | ||
| }) | ||
|
|
||
| // getBln3Score is the cached wrapper around requestBln3Score via withCalculationCache. | ||
| // Cache behaviour is tested thoroughly in fdm-core/src/calculator.test.ts. | ||
| // We just verify the export exists and has the correct shape. | ||
| it("getBln3Score should be a function", () => { | ||
| expect(typeof getBln3Score).toBe("function") | ||
| }) | ||
|
SvenVw marked this conversation as resolved.
|
||
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,96 @@ | ||
| import { withCalculationCache } from "@nmi-agro/fdm-core" | ||
| import pkg from "../package" | ||
| import type { Bln3Score, Bln3ScoreInputs, Bln3ScoreResponse } from "./types" | ||
|
|
||
| export { collectInputForBln3Score } from "./input" | ||
|
|
||
| /** | ||
| * Requests a BLN3 score from the NMI API for a single field. | ||
| * | ||
| * Calls `POST /maatwerk/bln3/score/field` with the provided field data and | ||
| * returns per-indicator status, target, index, impact, and score values. | ||
| * | ||
| * @param inputs - Field data and NMI API key. Only `a_lat`, `a_lon`, and | ||
| * `nmiApiKey` are required; all other fields improve calculation quality. | ||
| * @returns A promise resolving to a `Bln3Score` with `indicators` and | ||
| * optional `aggregations`. | ||
| * @throws If the NMI API key is not provided or the API request fails. | ||
| */ | ||
| export async function requestBln3Score( | ||
| inputs: Bln3ScoreInputs, | ||
| ): Promise<Bln3Score> { | ||
| const { nmiApiKey, ...fieldData } = inputs | ||
|
|
||
| if (!nmiApiKey) { | ||
| throw new Error("NMI API key not provided") | ||
| } | ||
|
|
||
| const controller = new AbortController() | ||
| const timeout = setTimeout(() => controller.abort(), 30000) // 30s timeout | ||
|
|
||
| try { | ||
| const response = await fetch( | ||
| "https://api.nmi-agro.nl/maatwerk/bln3/score/field", | ||
| { | ||
| method: "POST", | ||
| headers: { | ||
| Authorization: `Bearer ${nmiApiKey}`, | ||
| "Content-Type": "application/json", | ||
| }, | ||
| body: JSON.stringify(fieldData), | ||
| signal: controller.signal, | ||
| }, | ||
| ) | ||
|
|
||
| if (!response.ok) { | ||
| const errorText = await response.text().catch(() => "") | ||
| throw new Error( | ||
| `BLN3 score request failed with status ${response.status}: ${response.statusText} - ${errorText}`, | ||
| ) | ||
| } | ||
|
|
||
| const result: Bln3ScoreResponse = await response.json() | ||
| if (!result.success) { | ||
| throw new Error( | ||
| `BLN3 score API returned failure (status ${result.status}): ${result.message ?? "Unknown error"}`, | ||
| ) | ||
| } | ||
|
|
||
| if (!result.data || !Array.isArray(result.data.indicator)) { | ||
| throw new Error( | ||
| "BLN3 score API returned a malformed payload (missing data or indicator array)", | ||
| ) | ||
| } | ||
|
|
||
| // Map the API's "indicator" (singular) to "indicators" (plural) for ergonomics | ||
| return { | ||
| indicators: result.data.indicator, | ||
| aggregations: result.data.aggregations, | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| } | ||
| } catch (err) { | ||
| if (err instanceof Error && err.name === "AbortError") { | ||
| throw new Error( | ||
| "BLN3 score request timed out (30s). The NMI API did not respond in time.", | ||
| ) | ||
| } | ||
| throw err | ||
| } finally { | ||
| clearTimeout(timeout) | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Cached version of `requestBln3Score`. | ||
| * | ||
| * Uses `withCalculationCache` to store and retrieve results from the | ||
| * `fdm-calculator.calculation_cache` table. The cache key is a SHA-256 hash | ||
| * of the function name, calculator version, and sanitized inputs (API key | ||
| * redacted). Bumping `calculatorVersion` in `package.ts` invalidates all | ||
| * existing cache entries. | ||
| */ | ||
| export const getBln3Score = withCalculationCache( | ||
| requestBln3Score, | ||
| "requestBln3Score", | ||
| pkg.calculatorVersion, | ||
| ["nmiApiKey"], | ||
| ) | ||
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.
You didn't test the case where fetch throws an error.
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.
Resolved in 960d951