Skip to content

Commit f2bb69d

Browse files
Copilotaepfli
andauthored
feat(docs): add Mermaid diagrams for state update, evaluation, and memory flows (#41)
## Description Added visual documentation for the WASM module's internal operations. Three Mermaid diagrams illustrate how the evaluator processes flag configurations, evaluates flags, and manages memory across the host-WASM boundary. ### Diagrams Added - **State Update Flow** (sequence diagram after `update_state` API docs) - Validation modes (strict/permissive) with schema checking - JSON parsing and flag storage lifecycle - Error paths for UTF-8, validation, and parse failures - **Flag Evaluation Flow** (flowchart after `evaluate` API docs) - Complete evaluation paths: STATIC, DEFAULT, TARGETING_MATCH, DISABLED, ERROR, FLAG_NOT_FOUND - Context enrichment: `$flagd.flagKey`, `$flagd.timestamp`, `targetingKey` - JSON Logic targeting rule execution - **Memory Management Flow** (sequence diagram in Memory Model section) - alloc/dealloc lifecycle with pointer packing: `(ptr << 32) | len` - Host vs WASM memory ownership boundaries - Input, processing, and cleanup phases These complement existing text documentation by showing data flow and decision points visually. ## Related Issue Closes # ## Type of Change - [x] `docs`: Documentation only changes - [ ] `feat`: New feature (minor version bump) - [ ] `fix`: Bug fix (patch version bump) - [ ] `chore`: Maintenance tasks, dependency updates - [ ] `refactor`: Code refactoring without functional changes - [ ] `test`: Adding or updating tests - [ ] `ci`: CI/CD changes - [ ] `perf`: Performance improvements - [ ] `build`: Build system changes - [ ] `style`: Code style/formatting changes ## PR Title Format **IMPORTANT**: Since we use squash and merge, your PR title will become the commit message. Please ensure your PR title follows the [Conventional Commits](https://www.conventionalcommits.org/) format: ``` <type>(<optional-scope>): <description> ``` ### Examples: - `feat(operators): add new string comparison operator` - `fix(wasm): correct memory allocation bug` - `docs: update API examples in README` - `chore(deps): update rust dependencies` For breaking changes, use `!` after the type/scope or include `BREAKING CHANGE:` in the PR description: - `feat(api)!: redesign evaluation API` ## Testing - [ ] Unit tests added/updated - [ ] Integration tests added/updated - [ ] Manual testing performed - [ ] All tests pass (`cargo test`) - [ ] Code is formatted (`cargo fmt`) - [ ] Clippy checks pass (`cargo clippy -- -D warnings`) - [ ] WASM builds successfully (if applicable) **N/A** - Documentation-only changes ## Breaking Changes - [ ] This PR includes breaking changes - [ ] Documentation has been updated to reflect breaking changes - [ ] Migration guide included (if needed) ## Additional Notes Diagrams verified against source code: - `lib.rs::update_state_internal()` and `storage/mod.rs` → State Update Flow - `lib.rs::evaluate_internal()` and `evaluation.rs::evaluate_flag()` → Flag Evaluation Flow - `memory.rs` (wasm_alloc, wasm_dealloc, pack_ptr_len) → Memory Management Flow Total: 130 lines added, 3 diagrams, all using GitHub-compatible Mermaid syntax. <!-- START COPILOT ORIGINAL PROMPT --> <details> <summary>Original prompt</summary> > ## Problem > > The README documentation currently lacks visual representations of the state update and evaluation flows, which makes it harder for developers to understand how the WASM module interacts with host applications and how the internal evaluation process works. > > ## Solution > > Add three Mermaid diagrams to the README.md to illustrate: > > 1. **State Update Flow** - Shows the sequence of operations when updating flag configuration state, including validation and storage > 2. **Flag Evaluation Flow** - Shows the complete evaluation process from flag retrieval through context enrichment to targeting rule evaluation > 3. **Memory Management Flow** - Shows the memory allocation/deallocation lifecycle for WASM calls > > ## Implementation Details > > ### 1. State Update Flow Diagram > > Add after the `update_state` API documentation (around line 306), showing: > - Host allocates memory and writes config JSON > - WASM parses JSON > - Schema validation (with strict/permissive mode handling) > - Storage of flag configuration > - Memory cleanup > > ### 2. Flag Evaluation Flow Diagram > > Add after the `evaluate` API documentation (around line 380), showing: > - Memory allocation for flag key and context > - Flag retrieval from storage > - Handling of DISABLED and STATIC flags > - Context enrichment (adding `$flagd.flagKey`, `$flagd.timestamp`, `targetingKey`) > - JSON Logic evaluation of targeting rules > - Variant resolution > - Memory cleanup > > ### 3. Memory Management Flow Diagram > > Add in the "Memory Model & Safety" section (around line 693), showing: > - Complete lifecycle from alloc to dealloc > - Pointer packing/unpacking > - Clear distinction between host and WASM responsibilities > > ## Acceptance Criteria > > - [ ] All three Mermaid diagrams are added to README.md > - [ ] Diagrams are placed in logical locations within the existing documentation structure > - [ ] Diagrams accurately represent the actual code flow > - [ ] Syntax is valid Mermaid that renders correctly on GitHub > - [ ] Existing documentation formatting is preserved > > ## Additional Context > > This enhancement will improve developer experience by providing visual documentation that complements the existing text-based API documentation. </details> <!-- START COPILOT CODING AGENT SUFFIX --> *This pull request was created as a result of the following prompt from Copilot chat.* > ## Problem > > The README documentation currently lacks visual representations of the state update and evaluation flows, which makes it harder for developers to understand how the WASM module interacts with host applications and how the internal evaluation process works. > > ## Solution > > Add three Mermaid diagrams to the README.md to illustrate: > > 1. **State Update Flow** - Shows the sequence of operations when updating flag configuration state, including validation and storage > 2. **Flag Evaluation Flow** - Shows the complete evaluation process from flag retrieval through context enrichment to targeting rule evaluation > 3. **Memory Management Flow** - Shows the memory allocation/deallocation lifecycle for WASM calls > > ## Implementation Details > > ### 1. State Update Flow Diagram > > Add after the `update_state` API documentation (around line 306), showing: > - Host allocates memory and writes config JSON > - WASM parses JSON > - Schema validation (with strict/permissive mode handling) > - Storage of flag configuration > - Memory cleanup > > ### 2. Flag Evaluation Flow Diagram > > Add after the `evaluate` API documentation (around line 380), showing: > - Memory allocation for flag key and context > - Flag retrieval from storage > - Handling of DISABLED and STATIC flags > - Context enrichment (adding `$flagd.flagKey`, `$flagd.timestamp`, `targetingKey`) > - JSON Logic evaluation of targeting rules > - Variant resolution > - Memory cleanup > > ### 3. Memory Management Flow Diagram > > Add in the "Memory Model & Safety" section (around line 693), showing: > - Complete lifecycle from alloc to dealloc > - Pointer packing/unpacking > - Clear distinction between host and WASM responsibilities > > ## Acceptance Criteria > > - [ ] All three Mermaid diagrams are added to README.md > - [ ] Diagrams are placed in logical locations within the existing documentation structure > - [ ] Diagrams accurately represent the actual code flow > - [ ] Syntax is valid Mermaid that renders correctly on GitHub > - [ ] Existing documentation formatting is preserved > > ## Additional Context > > This enhancement will improve developer experience by providing visual documentation that complements the existing text-based API documentation. <!-- START COPILOT CODING AGENT TIPS --> --- 💬 We'd love your input! Share your thoughts on Copilot coding agent in our [2 minute survey](https://gh.io/copilot-coding-agent-survey). --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: aepfli <9987394+aepfli@users.noreply.github.com>
1 parent 628493b commit f2bb69d

1 file changed

Lines changed: 129 additions & 0 deletions

File tree

README.md

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -304,6 +304,48 @@ The configuration should follow the [flagd flag definition schema](https://flagd
304304
}
305305
```
306306

307+
**State Update Flow:**
308+
309+
```mermaid
310+
sequenceDiagram
311+
participant Host as Host Application
312+
participant WASM as WASM Module
313+
participant Storage as Flag Storage
314+
315+
Host->>Host: Allocate memory using alloc()
316+
Host->>Host: Write config JSON to memory
317+
Host->>WASM: Call update_state(config_ptr, config_len)
318+
319+
WASM->>WASM: Read JSON from memory
320+
alt Invalid UTF-8
321+
WASM-->>Host: Return error response
322+
end
323+
324+
WASM->>WASM: Validate against JSON Schema
325+
326+
alt Strict Mode
327+
alt Validation Failed
328+
WASM-->>Host: Return validation error
329+
end
330+
else Permissive Mode
331+
alt Validation Failed
332+
WASM->>WASM: Log warning, continue
333+
end
334+
end
335+
336+
WASM->>WASM: Parse JSON to FeatureFlag objects
337+
alt Parse Error
338+
WASM-->>Host: Return parse error
339+
end
340+
341+
WASM->>Storage: Store parsed flags (replace existing)
342+
WASM->>WASM: Allocate memory for success response
343+
WASM-->>Host: Return packed pointer (success)
344+
345+
Host->>Host: Read response from memory
346+
Host->>Host: Deallocate memory using dealloc()
347+
```
348+
307349
### evaluate
308350

309351
Evaluates a feature flag from the previously stored configuration (set via `update_state`) against the provided context.
@@ -379,6 +421,51 @@ dealloc.apply(contextPtr, contextBytes.length);
379421
dealloc.apply(resultPtr, resultLen);
380422
```
381423

424+
**Flag Evaluation Flow:**
425+
426+
```mermaid
427+
flowchart TD
428+
Start([Host calls evaluate]) --> AllocMem[Host allocates memory for flag key and context]
429+
AllocMem --> WriteData[Host writes data to WASM memory]
430+
WriteData --> CallEval[Call evaluate with pointers]
431+
432+
CallEval --> ReadMem[WASM reads flag key and context from memory]
433+
ReadMem --> ParseCtx{Parse context JSON}
434+
ParseCtx -->|Error| ReturnError[Return PARSE_ERROR]
435+
436+
ParseCtx -->|Success| GetFlag{Retrieve flag from storage}
437+
GetFlag -->|Not Found| ReturnNotFound[Return FLAG_NOT_FOUND]
438+
GetFlag -->|Found| CheckState{Check flag state}
439+
440+
CheckState -->|DISABLED| ReturnDisabled[Return default variant with DISABLED reason]
441+
CheckState -->|ENABLED| CheckTargeting{Has targeting rules?}
442+
443+
CheckTargeting -->|No| ReturnStatic[Return default variant with STATIC reason]
444+
CheckTargeting -->|Yes| EnrichContext[Enrich context with:<br/>- $flagd.flagKey<br/>- $flagd.timestamp<br/>- targetingKey default]
445+
446+
EnrichContext --> EvalRule[Evaluate targeting rule using JSON Logic]
447+
EvalRule --> EvalResult{Evaluation result}
448+
449+
EvalResult -->|Error| ReturnParseError[Return PARSE_ERROR]
450+
EvalResult -->|Success| GetVariant{Variant exists?}
451+
452+
GetVariant -->|Yes| ReturnMatch[Return variant value with TARGETING_MATCH]
453+
GetVariant -->|No| ReturnDefault[Return default variant with DEFAULT reason]
454+
455+
ReturnError --> PackResult[Pack result into memory]
456+
ReturnNotFound --> PackResult
457+
ReturnDisabled --> PackResult
458+
ReturnStatic --> PackResult
459+
ReturnParseError --> PackResult
460+
ReturnMatch --> PackResult
461+
ReturnDefault --> PackResult
462+
463+
PackResult --> ReturnPacked[Return packed pointer to host]
464+
ReturnPacked --> HostRead[Host reads result from memory]
465+
HostRead --> HostDealloc[Host deallocates all memory]
466+
HostDealloc --> End([Evaluation complete])
467+
```
468+
382469
### Context Enrichment
383470

384471
The evaluator automatically enriches the evaluation context with standard `$flagd` properties according to the [flagd provider specification](https://flagd.dev/reference/specifications/providers/#in-process-resolver). These properties are available in targeting rules via JSON Logic's `var` operator.
@@ -704,6 +791,48 @@ The library uses a simple linear memory allocation model:
704791
- Freeing input memory after `evaluate_logic` returns
705792
- Freeing the result memory after reading it
706793

794+
**Memory Management Flow:**
795+
796+
```mermaid
797+
sequenceDiagram
798+
participant Host as Host Application
799+
participant WASM as WASM Module
800+
participant Heap as WASM Heap
801+
802+
Note over Host,Heap: Input Phase
803+
Host->>WASM: Call alloc(input_len)
804+
WASM->>Heap: Allocate input_len bytes
805+
Heap-->>WASM: Return pointer or null
806+
WASM-->>Host: Return input_ptr
807+
808+
Host->>WASM: Write input data to memory[input_ptr]
809+
810+
Note over Host,Heap: Processing Phase
811+
Host->>WASM: Call function(input_ptr, input_len, ...)
812+
WASM->>WASM: Read data from memory[input_ptr]
813+
WASM->>WASM: Process data
814+
815+
WASM->>WASM: Call alloc(result_len) internally
816+
WASM->>Heap: Allocate result_len bytes
817+
Heap-->>WASM: Return result_ptr
818+
WASM->>WASM: Write result to memory[result_ptr]
819+
820+
WASM->>WASM: Pack pointer and length:<br/>packed = (result_ptr << 32) | result_len
821+
WASM-->>Host: Return packed u64
822+
823+
Note over Host,Heap: Cleanup Phase
824+
Host->>Host: Unpack u64:<br/>result_ptr = packed >> 32<br/>result_len = packed & 0xFFFFFFFF
825+
Host->>WASM: Read result from memory[result_ptr]
826+
827+
Host->>WASM: Call dealloc(input_ptr, input_len)
828+
WASM->>Heap: Free input memory
829+
830+
Host->>WASM: Call dealloc(result_ptr, result_len)
831+
WASM->>Heap: Free result memory
832+
833+
Note over Host,Heap: Memory lifecycle complete
834+
```
835+
707836
### Pointer Packing
708837

709838
Results are returned as a packed 64-bit integer:

0 commit comments

Comments
 (0)