Skip to main content

Deep Dive into ReactJS Hooks

· 5 min read

React Hooks, introduced in React 16.8, revolutionized functional components by adding state and lifecycle capabilities, enabling a simpler, more powerful way to manage logic within components. This guide will provide a deep dive into React’s core hooks, detailing how they work, the scenarios in which they shine, and best practices for leveraging them effectively.


Introduction to Hooks​

Hooks allow you to use state, lifecycle methods, and other React features without writing a class. They provide a way to reuse logic across components in a more composable and understandable way, helping developers avoid the complex nesting and lifecycle clutter often encountered with higher-order components and render props.

Why Hooks?​

  • Simplify state and side effect management in functional components.
  • Enhance code reuse with custom hooks.
  • Make components cleaner and more readable.

Basic Hooks​

React offers several core hooks that cover common needs such as state, effects, and references.

useState: Managing State in Functional Components​

useState is used to declare state within functional components. It returns an array with two values: the current state and a function to update it.

Syntax:​

const [state, setState] = useState(initialValue);

Practical Scenario: Toggling a Modal​

import React, { useState } from 'react';

function ModalToggle() {
const [isOpen, setIsOpen] = useState(false);

const toggleModal = () => setIsOpen(!isOpen);

return (
<div>
<button onClick={toggleModal}>Toggle Modal</button>
{isOpen && <Modal />}
</div>
);
}

useEffect: Side Effects and Lifecycle Events​

useEffect manages side effects (such as data fetching, subscriptions, or DOM manipulation). It runs after the component renders and accepts a dependency array that controls when it should re-run.

Syntax:​

useEffect(() => {
// effect code here
return () => {
// cleanup code here
};
}, [dependencies]);

Practical Scenario: Fetching Data on Component Load​

import React, { useState, useEffect } from 'react';

function UserList() {
const [users, setUsers] = useState([]);

useEffect(() => {
async function fetchUsers() {
const response = await fetch('/api/users');
const data = await response.json();
setUsers(data);
}

fetchUsers();
}, []); // Empty array means this runs only once, similar to componentDidMount

return (
<ul>
{users.map(user => <li key={user.id}>{user.name}</li>)}
</ul>
);
}

Tips:​

  • Cleanup: Return a cleanup function to avoid memory leaks (e.g., unsubscribing from a WebSocket).
  • Dependencies: Use the dependency array to specify when the effect should re-run.

Advanced Hooks​

Beyond the basic hooks, React provides additional hooks for managing more specialized situations.

useContext: Accessing Context Values​

useContext allows components to access and consume context values directly without needing to wrap them in a Consumer.

Syntax:​

const contextValue = useContext(MyContext);

Practical Scenario: Global Theme Management​

import React, { useContext } from 'react';
import { ThemeContext } from './ThemeContext';

function ThemedButton() {
const theme = useContext(ThemeContext);

return (
<button style={{ background: theme.background, color: theme.foreground }}>
I am styled by theme context!
</button>
);
}

Additional Hooks​

useReducer: Managing Complex State​

useReducer is an alternative to useState for managing complex state transitions, typically in situations where you would use Redux or other state management libraries.

Syntax:​

const [state, dispatch] = useReducer(reducer, initialState);

Practical Scenario: A Counter with Increment/Decrement​

import React, { useReducer } from 'react';

function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
throw new Error();
}
}

function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });

return (
<div>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
<span>{state.count}</span>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
</div>
);
}

useRef: Persistent Mutable References​

useRef creates a persistent reference that doesn’t cause re-renders, making it ideal for storing mutable values like DOM elements.

Syntax:​

const ref = useRef(initialValue);

Practical Scenario: Focusing an Input Element​

import React, { useRef } from 'react';

function TextInputWithFocus() {
const inputRef = useRef(null);

const handleClick = () => {
inputRef.current.focus();
};

return (
<div>
<input ref={inputRef} type="text" />
<button onClick={handleClick}>Focus the input</button>
</div>
);
}

useMemo: Memoizing Expensive Calculations​

useMemo optimizes performance by memoizing expensive calculations, only recomputing them when dependencies change.

Syntax:​

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

Practical Scenario: Filtering a Large List​

import React, { useState, useMemo } from 'react';

function FilterableList({ items }) {
const [query, setQuery] = useState('');

const filteredItems = useMemo(() => {
return items.filter(item => item.toLowerCase().includes(query.toLowerCase()));
}, [items, query]);

return (
<div>
<input value={query} onChange={e => setQuery(e.target.value)} placeholder="Filter items" />
<ul>
{filteredItems.map(item => <li key={item}>{item}</li>)}
</ul>
</div>
);
}

Custom Hooks​

Custom hooks are functions that allow you to extract and reuse stateful logic across components. They enable you to abstract complex logic in a cleaner, more maintainable way.

Practical Scenario: A useFetch Hook for Data Fetching​

import { useState, useEffect } from 'react';

function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);

useEffect(() => {
async function fetchData() {
setLoading(true);
const response = await fetch(url);
const result = await response.json();
setData(result);
setLoading(false);
}

fetchData();
}, [url]);

return { data, loading };
}

export default useFetch;

Using useFetch in a Component​

import React from 'react';
import useFetch from './useFetch';

function Users() {
const { data, loading } = useFetch('/api/users');

if (loading) return <p>Loading...</p>;
return (
<ul>
{data.map(user => <li key={user.id}>{user.name}</li>)}
</ul>
);
}

Error Handling and Best Practices​

Error Handling in Hooks​

  1. Wrap async operations with a try-catch to handle errors gracefully.
  2. Global error boundaries for handling errors in effects or custom hooks (using libraries like react-error-boundary).

Best Practices​

  • Dependency Arrays: Always add dependencies in useEffect and useMemo dependency arrays to avoid stale closures.
  • Avoid Side Effects in Render: Avoid triggering side effects inside render methods to prevent unexpected behavior.

Conclusion​

React Hooks provide powerful, flexible solutions for managing state, effects, and other logic in functional components. Mastering these core hooks, along with custom hooks, enables you to write cleaner, more maintainable code.

With practical examples, error handling tips, and performance optimizations, you’re now equipped to build complex React applications that harness the full power of hooks.

Kubernetes Node Lifecycle Overview

· 2 min read

A Kubernetes Node is a core component with a lifecycle that includes registration, operation, and decommissioning. This article briefly explains key events in the Node lifecycle.

Kubernetes Node Lifecycle Overview

Node Registration​

Each node must run kubelet, which initiates a registration request to kube-apiserver, creating a node resource object. registerNode (default: true) in the kubelet configuration controls automatic registration. If set to false, nodes must be registered manually.

The nodename is determined by:

  • The cloud provider, if configured.
  • Otherwise, the local hostname, which --hostname-override can modify.

Node Heartbeat Mechanism​

The heartbeat includes updating both .status and a corresponding lease object for the node. nodeStatusUpdateFrequency (default: 10 seconds) triggers kubelet to update .status on changes or every 10 seconds. Additionally, each node maintains a lease object in kube-node-lease with an update frequency set by nodeLeaseDurationSeconds (default: 40 seconds) multiplied by 0.25, or 10 seconds.

Node Health Monitoring​

The node-controller in controller-manager monitors node health. If no issues arise, the node remains active. However, if a node loses connectivity or crashes, node-controller will detect this after a period specified by --node-monitor-grace-period (default: 40 seconds, increasing to 50 in v1.32). After this period, the node status changes to Unknown, and a Taint is applied to prevent new pod scheduling. If heartbeat remains absent for 5 more minutes, the node-controller starts eviction of pods and other resources from the node.

A graceful node shutdown follows a similar procedure: marking taints, rescheduling pods, and decommissioning the node.

Spark as a Service with Spring Boot

· 13 min read
  1. Tech Stack and Target Environment
  2. Architecture Design
  3. Flow Descriptions
  4. Sequence Diagrams
  5. Components Design
  6. Configuration and Code
  7. Job Queue Management
  8. Spark Job Submission
  9. Test Cases
  10. Global Exception Handler
  11. Project Structure

In this article, we will explore the development of a stateless Spring Boot application using Spring WebFlux 3.3.5 and Apache Spark 3.5.4. This application will serve as a Spark-as-a-Service, designed to run in a Kubernetes (K8s) environment with multiple replicas. The application will use a centralized queue in Redis to manage Spark job requests, with a copy of the job queue also maintained in PostgreSQL for job history and tracking. The application will ensure that each job is executed only once, manage job states and statuses correctly, and provide RESTful endpoints for client interaction and monitoring.

Tech Stack and Target Environment​

Spark Cluster​

  • Version: 3.5.4
  • Deployment: Kubernetes namespace whereq-saas-spark
  • Configuration: Default Bitnami Helm chart (1 master, 2 workers)

Spring Boot WebFlux Application​

  • Version: 3.3.5
  • Deployment: Kubernetes namespace whereq-saas-web
  • Replicas: 2
  • Ingress: Exposed for frontend access

Queue and Database​

  • Queue: Redis (for job queue management)
  • Database: PostgreSQL with R2DBC driver
  • Container Orchestration: Kubernetes

Architecture Design​

The application is structured to be stateless and scalable. It integrates with Redis to queue job submissions, PostgreSQL for persistent storage, and the Spark REST API for job submission and tracking.

High-Level Architecture​

graph TD
A[Client] -->|Submit Task| B[Spring Boot Application]
B -->|Store Task Request| C[Redis Queue]
C -->|Sync Job Request| D[PostgreSQL]
D -->|Fetch Job| B
B -->|Check Cluster Status| E[Spark REST API]
E -->|Determine Resources| B
B -->|Submit Job| F[Spark Master]
F -->|Execute Job| G[Spark Worker]
G -->|Store Result| D
B -->|Query Job History| D
B -->|Monitor Job Queue| C

Components​

  • Job Controller: Accepts job submissions via HTTP POST and returns a task ID.
  • Job Queue Service: Handles job insertion into Redis and PostgreSQL.
  • Job Monitor Service: Monitors Redis, submits jobs to Spark, and tracks job status.
  • Spark Service: Interfaces with the Spark REST API for job submission and status updates.
  • State Machine: Manages job state transitions (e.g., ready, running, completed) and status updates (success, failed).

Architecture Diagram​

+---------------+ +---------------------+ +----------------+
| Job Controller| ----> | Job Queue Service | -----> | Redis Queue |
+---------------+ +---------------------+ +----------------+
|
+--------------------------------------------------------+
|
+-------------------+ +------------------+ +------------------+
| Job Monitor | -----> | Spark Service | <-----> | Spark Master Pod |
| (Background Task) | +------------------+ +------------------+
+-------------------+ |
|
+-------------------------------+
| PostgreSQL (Sync Job State) |
+-------------------------------+

Detailed Architecture​

  1. Client: Submits Spark job requests via RESTful endpoints.
  2. Spring Boot Application:
    • Receives job requests.
    • Stores job requests in the Redis queue.
    • Syncs job requests with PostgreSQL.
    • Checks cluster status via Spark REST API.
    • Submits jobs to Spark Master based on available resources.
    • Manages job states and statuses.
    • Provides RESTful endpoints for job history queries and monitoring.
  3. Redis Queue: Stores job requests.
  4. PostgreSQL: Stores job requests and history.
  5. Spark REST API: Provides cluster status information.
  6. Spark Master: Receives job submissions.
  7. Spark Worker: Executes Spark jobs.
  8. PostgreSQL: Stores job results and history.

Flow Descriptions​

Task Submission Flow​

  1. Task Controller receives task requests via HTTP POST.
  2. Task Queue Service validates the request, assigns a task ID, stores it in Redis with a READY state, and syncs it to PostgreSQL.
  3. The service returns a task ID to the client.

Spark Job Submission Flow​

  1. Job Monitor Service picks up jobs in the READY state from the Redis queue using FIFO.
  2. The job is submitted to the Spark master via the Spark Service, and the job state is updated to SUBMITTED.
  3. The state is synced to PostgreSQL.
  4. The Job Monitor Service starts tracking the job status until completion or failure.
  5. The final state (COMPLETED or FAILED) is updated in both Redis and PostgreSQL.

sequenceDiagram
participant Client
participant SpringBootApp
participant RedisQueue
participant PostgreSQL
participant SparkRESTAPI
participant SparkMaster
participant SparkWorker

Client ->> SpringBootApp: Submit Job Request
SpringBootApp ->> RedisQueue: Store Job Request
RedisQueue ->> PostgreSQL: Sync Job Request
SpringBootApp ->> SparkRESTAPI: Check Cluster Status
SparkRESTAPI -->> SpringBootApp: Cluster Status
SpringBootApp ->> SparkMaster: Submit Job
SparkMaster ->> SparkWorker: Execute Job
SparkWorker -->> PostgreSQL: Store Job Result
SpringBootApp -->> Client: Job Status

Job History Query​

sequenceDiagram
participant Client
participant SpringBootApp
participant PostgreSQL

Client ->> SpringBootApp: Query Job History
SpringBootApp ->> PostgreSQL: Fetch Job History
PostgreSQL -->> SpringBootApp: Job History
SpringBootApp -->> Client: Job History

​

Components Design​

1. Job Request Model​

public class JobRequest {
private String id;
private String jobName;
private String jobConfig;
private JobState state;
private JobStatus status;
// Getters and Setters
}

2. Job State and Status Enums​

public enum JobState {
READY, PENDING, RUNNING, COMPLETED
}

public enum JobStatus {
SUCCESS, FAILED
}

3. Redis Queue Service​

@Service
public class RedisQueueService {
private final ReactiveRedisTemplate<String, JobRequest> redisTemplate;

public RedisQueueService(ReactiveRedisTemplate<String, JobRequest> redisTemplate) {
this.redisTemplate = redisTemplate;
}

public Mono<Boolean> enqueueJob(JobRequest jobRequest) {
return redisTemplate.opsForList().rightPush("jobQueue", jobRequest);
}

public Mono<JobRequest> dequeueJob() {
return redisTemplate.opsForList().leftPop("jobQueue");
}

public Mono<Boolean> updateJobStatusInQueue(String jobId, JobState state, JobStatus status) {
return redisTemplate.opsForList().indexOf("jobQueue", jobId)
.flatMap(index -> redisTemplate.opsForList().set(index, new JobRequest(jobId, state, status)));
}
}

4. PostgreSQL Service​

@Service
public class PostgresService {
private final R2dbcEntityTemplate r2dbcEntityTemplate;

public PostgresService(R2dbcEntityTemplate r2dbcEntityTemplate) {
this.r2dbcEntityTemplate = r2dbcEntityTemplate;
}

public Mono<JobRequest> saveJobRequest(JobRequest jobRequest) {
return r2dbcEntityTemplate.insert(jobRequest);
}

public Mono<JobRequest> getJobById(String jobId) {
return r2dbcEntityTemplate.selectOne(Query.query(Criteria.where("id").is(jobId)), JobRequest.class);
}

public Mono<Integer> updateJobStatus(String jobId, JobState state, JobStatus status) {
return r2dbcEntityTemplate.update(JobRequest.class)
.matching(Query.query(Criteria.where("id").is(jobId)))
.apply(Update.update("state", state).set("status", status));
}

public Flux<JobRequest> getJobHistory(Map<String, String> queryParams) {
// Fetch job history from PostgreSQL
return r2dbcEntityTemplate.select(JobRequest.class).all();
}
}

5. Spark REST API Service​

@Service
public class SparkRestApiService {
private final WebClient webClient;

public SparkRestApiService(WebClient.Builder webClientBuilder) {
this.webClient = webClientBuilder.baseUrl("http://spark-master:8080").build();
}

public Mono<ClusterStatus> getClusterStatus() {
return webClient.get()
.uri("/api/v1/applications")
.retrieve()
.bodyToMono(String.class)
.map(response -> {
// Parse response and return ClusterStatus
return new ClusterStatus();
});
}

public Mono<JobStatus> monitorJobStatus(String jobId) {
return webClient.get()
.uri("/api/v1/submissions/status/{jobId}", jobId)
.retrieve()
.bodyToMono(String.class)
.map(response -> {
// Parse response and return JobStatus
return JobStatus.SUCCESS; // Example
});
}
}

6. Job Executor Service​

@Service
public class JobExecutorService {
private final RedisQueueService redisQueueService;
private final PostgresService postgresService;
private final SparkRestApiService sparkRestApiService;
private final WebClient webClient;

public JobExecutorService(RedisQueueService redisQueueService, PostgresService postgresService, SparkRestApiService sparkRestApiService, WebClient.Builder webClientBuilder) {
this.redisQueueService = redisQueueService;
this.postgresService = postgresService;
this.sparkRestApiService = sparkRestApiService;
this.webClient = webClientBuilder.baseUrl("http://spark-master:8080").build();
}

public Mono<Void> executeNextJob() {
return redisQueueService.dequeueJob()
.flatMap(jobRequest -> {
jobRequest.setState(JobState.PENDING);
return postgresService.updateJobStatus(jobRequest.getId(), JobState.PENDING, JobStatus.SUCCESS)
.then(sparkRestApiService.getClusterStatus())
.flatMap(clusterStatus -> {
if (clusterStatus.hasAvailableResources()) {
return submitJobToSpark(jobRequest);
} else {
return redisQueueService.enqueueJob(jobRequest).then();
}
});
});
}

private Mono<Void> submitJobToSpark(JobRequest jobRequest) {
return webClient.post()
.uri("/v1/submissions/create")
.bodyValue(jobRequest)
.retrieve()
.toBodilessEntity()
.flatMap(response -> {
if (response.getStatusCode().is2xxSuccessful()) {
jobRequest.setState(JobState.RUNNING);
return postgresService.updateJobStatus(jobRequest.getId(), JobState.RUNNING, JobStatus.SUCCESS)
.then(monitorJobResult(jobRequest));
} else {
jobRequest.setState(JobState.COMPLETED);
jobRequest.setStatus(JobStatus.FAILED);
return updateJobStatus(jobRequest);
}
});
}

private Mono<Void> monitorJobResult(JobRequest jobRequest) {
return sparkRestApiService.monitorJobStatus(jobRequest.getId())
.flatMap(jobStatus -> {
jobRequest.setState(JobState.COMPLETED);
jobRequest.setStatus(jobStatus);
return updateJobStatus(jobRequest);
});
}

private Mono<Void> updateJobStatus(JobRequest jobRequest) {
return redisQueueService.updateJobStatusInQueue(jobRequest.getId(), jobRequest.getState(), jobRequest.getStatus())
.then(postgresService.updateJobStatus(jobRequest.getId(), jobRequest.getState(), jobRequest.getStatus()))
.then();
}
}

7. RESTful Endpoints​

@RestController
@RequestMapping("/api/jobs")
public class JobController {
private final JobExecutorService jobExecutorService;
private final PostgresService postgresService;

public JobController(JobExecutorService jobExecutorService, PostgresService postgresService) {
this.jobExecutorService = jobExecutorService;
this.postgresService = postgresService;
}

@PostMapping
public Mono<ResponseEntity<String>> submitJob(@RequestBody JobRequest jobRequest) {
return jobExecutorService.submitJob(jobRequest)
.thenReturn(ResponseEntity.ok("Job submitted successfully"));
}

@GetMapping("/history")
public Flux<JobRequest> getJobHistory(@RequestParam Map<String, String> queryParams) {
return postgresService.getJobHistory(queryParams);
}

@GetMapping("/status")
public Mono<ResponseEntity<String>> getJobStatus(@RequestParam String jobId) {
return postgresService.getJobById(jobId)
.map(jobRequest -> ResponseEntity.ok(jobRequest.getStatus().name()));
}
}

​

Configuration and Code​

1. Spring Boot Application Configuration​

spring:
redis:
host: localhost
port: 6379
r2dbc:
url: r2dbc:postgresql://localhost:5432/spark_jobs
username: postgres
password: postgres
webclient:
baseUrl: http://spark-master:8080

2. Spark REST API Configuration​

@Configuration
public class SparkRestApiConfig {
@Bean
public WebClient.Builder webClientBuilder() {
return WebClient.builder();
}
}

3. Redis Configuration​

@Configuration
public class RedisConfig {
@Bean
public ReactiveRedisTemplate<String, JobRequest> reactiveRedisTemplate(ReactiveRedisConnectionFactory factory) {
RedisSerializationContext<String, JobRequest> serializationContext = RedisSerializationContext
.newSerializationContext(new StringRedisSerializer())
.value(new Jackson2JsonRedisSerializer<>(JobRequest.class))
.build();
return new ReactiveRedisTemplate<>(factory, serializationContext);
}
}

4. R2DBC Configuration​

@Configuration
public class R2dbcConfig {
@Bean
public ConnectionFactory connectionFactory(R2dbcProperties properties) {
return ConnectionFactories.get(properties.getUrl());
}

@Bean
public R2dbcEntityTemplate r2dbcEntityTemplate(ConnectionFactory connectionFactory) {
DatabaseClient databaseClient = DatabaseClient.create(connectionFactory);
return new R2dbcEntityTemplate(databaseClient);
}
}

5. Swagger Configuration​

@Configuration
@EnableSwagger2WebFlux
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.sparkasaservice.controller"))
.paths(PathSelectors.any())
.build();
}
}

​

Job Queue Management​

1. Job Queue Service​

The RedisQueueService class is responsible for managing the job queue in Redis.

@Service
public class RedisQueueService {
private final ReactiveRedisTemplate<String, JobRequest> redisTemplate;

public RedisQueueService(ReactiveRedisTemplate<String, JobRequest> redisTemplate) {
this.redisTemplate = redisTemplate;
}

public Mono<Boolean> enqueueJob(JobRequest jobRequest) {
return redisTemplate.opsForList().rightPush("jobQueue", jobRequest);
}

public Mono<JobRequest> dequeueJob() {
return redisTemplate.opsForList().leftPop("jobQueue");
}

public Mono<Boolean> updateJobStatusInQueue(String jobId, JobState state, JobStatus status) {
return redisTemplate.opsForList().indexOf("jobQueue", jobId)
.flatMap(index -> redisTemplate.opsForList().set(index, new JobRequest(jobId, state, status)));
}
}

2. Job State Management​

The JobRequest class includes fields for JobState and JobStatus to manage the state and status of each job.

public class JobRequest {
private String id;
private String jobName;
private String jobConfig;
private JobState state;
private JobStatus status;
// Getters and Setters
}

3. Job Execution​

The JobExecutorService class is responsible for executing jobs from the queue. It ensures that each job is executed only once and updates the job state and status accordingly.

@Service
public class JobExecutorService {
private final RedisQueueService redisQueueService;
private final PostgresService postgresService;
private final SparkRestApiService sparkRestApiService;
private final WebClient webClient;

public JobExecutorService(RedisQueueService redisQueueService, PostgresService postgresService, SparkRestApiService sparkRestApiService, WebClient.Builder webClientBuilder) {
this.redisQueueService = redisQueueService;
this.postgresService = postgresService;
this.sparkRestApiService = sparkRestApiService;
this.webClient = webClientBuilder.baseUrl("http://spark-master:8080").build();
}

public Mono<Void> executeNextJob() {
return redisQueueService.dequeueJob()
.flatMap(jobRequest -> {
jobRequest.setState(JobState.PENDING);
return postgresService.updateJobStatus(jobRequest.getId(), JobState.PENDING, JobStatus.SUCCESS)
.then(sparkRestApiService.getClusterStatus())
.flatMap(clusterStatus -> {
if (clusterStatus.hasAvailableResources()) {
return submitJobToSpark(jobRequest);
} else {
return redisQueueService.enqueueJob(jobRequest).then();
}
});
});
}

private Mono<Void> submitJobToSpark(JobRequest jobRequest) {
return webClient.post()
.uri("/v1/submissions/create")
.bodyValue(jobRequest)
.retrieve()
.toBodilessEntity()
.flatMap(response -> {
if (response.getStatusCode().is2xxSuccessful()) {
jobRequest.setState(JobState.RUNNING);
return postgresService.updateJobStatus(jobRequest.getId(), JobState.RUNNING, JobStatus.SUCCESS)
.then(monitorJobResult(jobRequest));
} else {
jobRequest.setState(JobState.COMPLETED);
jobRequest.setStatus(JobStatus.FAILED);
return updateJobStatus(jobRequest);
}
});
}

private Mono<Void> monitorJobResult(JobRequest jobRequest) {
return sparkRestApiService.monitorJobStatus(jobRequest.getId())
.flatMap(jobStatus -> {
jobRequest.setState(JobState.COMPLETED);
jobRequest.setStatus(jobStatus);
return updateJobStatus(jobRequest);
});
}

private Mono<Void> updateJobStatus(JobRequest jobRequest) {
return redisQueueService.updateJobStatusInQueue(jobRequest.getId(), jobRequest.getState(), jobRequest.getStatus())
.then(postgresService.updateJobStatus(jobRequest.getId(), jobRequest.getState(), jobRequest.getStatus()))
.then();
}
}

​

Spark Job Submission​

1. Job Submission Endpoint​

The JobController class provides an endpoint for submitting jobs. It uses the JobExecutorService to handle job submission.

@RestController
@RequestMapping("/api/jobs")
public class JobController {
private final JobExecutorService jobExecutorService;
private final PostgresService postgresService;

public JobController(JobExecutorService jobExecutorService, PostgresService postgresService) {
this.jobExecutorService = jobExecutorService;
this.postgresService = postgresService;
}

@PostMapping
public Mono<ResponseEntity<String>> submitJob(@RequestBody JobRequest jobRequest) {
return jobExecutorService.submitJob(jobRequest)
.thenReturn(ResponseEntity.ok("Job submitted successfully"));
}

@GetMapping("/history")
public Flux<JobRequest> getJobHistory(@RequestParam Map<String, String> queryParams) {
return postgresService.getJobHistory(queryParams);
}

@GetMapping("/status")
public Mono<ResponseEntity<String>> getJobStatus(@RequestParam String jobId) {
return postgresService.getJobById(jobId)
.map(jobRequest -> ResponseEntity.ok(jobRequest.getStatus().name()));
}
}

2. Job Execution​

The JobExecutorService class is responsible for executing jobs from the queue. It ensures that each job is executed only once and updates the job state and status accordingly.

@Service
public class JobExecutorService {
private final RedisQueueService redisQueueService;
private final PostgresService postgresService;
private final SparkRestApiService sparkRestApiService;
private final WebClient webClient;

public JobExecutorService(RedisQueueService redisQueueService, PostgresService postgresService, SparkRestApiService sparkRestApiService, WebClient.Builder webClientBuilder) {
this.redisQueueService = redisQueueService;
this.postgresService = postgresService;
this.sparkRestApiService = sparkRestApiService;
this.webClient = webClientBuilder.baseUrl("http://spark-master:8080").build();
}

public Mono<Void> executeNextJob() {
return redisQueueService.dequeueJob()
.flatMap(jobRequest -> {
jobRequest.setState(JobState.PENDING);
return postgresService.updateJobStatus(jobRequest.getId(), JobState.PENDING, JobStatus.SUCCESS)
.then(sparkRestApiService.getClusterStatus())
.flatMap(clusterStatus -> {
if (clusterStatus.hasAvailableResources()) {
return submitJobToSpark(jobRequest);
} else {
return redisQueueService.enqueueJob(jobRequest).then();
}
});
});
}

private Mono<Void> submitJobToSpark(JobRequest jobRequest) {
return webClient.post()
.uri("/v1/submissions/create")
.bodyValue(jobRequest)
.retrieve()
.toBodilessEntity()
.flatMap(response -> {
if (response.getStatusCode().is2xxSuccessful()) {
jobRequest.setState(JobState.RUNNING);
return postgresService.updateJobStatus(jobRequest.getId(), JobState.RUNNING, JobStatus.SUCCESS)
.then(monitorJobResult(jobRequest));
} else {
jobRequest.setState(JobState.COMPLETED);
jobRequest.setStatus(JobStatus.FAILED);
return updateJobStatus(jobRequest);
}
});
}

private Mono<Void> monitorJobResult(JobRequest jobRequest) {
return sparkRestApiService.monitorJobStatus(jobRequest.getId())
.flatMap(jobStatus -> {
jobRequest.setState(JobState.COMPLETED);
jobRequest.setStatus(jobStatus);
return updateJobStatus(jobRequest);
});
}

private Mono<Void> updateJobStatus(JobRequest jobRequest) {
return redisQueueService.updateJobStatusInQueue(jobRequest.getId(), jobRequest.getState(), jobRequest.getStatus())
.then(postgresService.updateJobStatus(jobRequest.getId(), jobRequest.getState(), jobRequest.getStatus()))
.then();
}
}

​

Test Cases​

1. Job Submission Test​

@SpringBootTest
@AutoConfigureWebTestClient
public class JobControllerTest {

@Autowired
private WebTestClient webTestClient;

@Test
public void testJobSubmission() {
JobRequest jobRequest = new JobRequest();
jobRequest.setId("1");
jobRequest.setJobName("TestJob");
jobRequest.setJobConfig("SELECT * FROM test_table");

webTestClient.post().uri("/api/jobs")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(jobRequest)
.exchange()
.expectStatus().isOk()
.expectBody(String.class).isEqualTo("Job submitted successfully");
}
}

2. Job Execution Test​

@SpringBootTest
public class JobExecutorServiceTest {

@Autowired
private JobExecutorService jobExecutorService;

@Autowired
private RedisQueueService redisQueueService;

@Autowired
private PostgresService postgresService;

@Test
public void testJobExecution() {
JobRequest jobRequest = new JobRequest();
jobRequest.setId("1");
jobRequest.setJobName("TestJob");
jobRequest.setJobConfig("SELECT * FROM test_table");

StepVerifier.create(redisQueueService.enqueueJob(jobRequest)
.then(jobExecutorService.executeNextJob())
.then(postgresService.getJobById("1")))
.expectNextMatches(executedJob -> {
assertNotNull(executedJob);
assertEquals(JobState.COMPLETED, executedJob.getState());
assertEquals(JobStatus.SUCCESS, executedJob.getStatus());
return true;
})
.verifyComplete();
}
}

3. Job History Query Test​

@SpringBootTest
@AutoConfigureWebTestClient
public class JobControllerTest {

@Autowired
private WebTestClient webTestClient;

@Test
public void testJobHistoryQuery() {
webTestClient.get().uri(uriBuilder -> uriBuilder
.path("/api/jobs/history")
.queryParam("jobName", "TestJob")
.build())
.exchange()
.expectStatus().isOk()
.expectBodyList(JobRequest.class)
.value(jobRequests -> {
assertNotNull(jobRequests);
assertTrue(jobRequests.stream().anyMatch(jobRequest -> "TestJob".equals(jobRequest.getJobName())));
});
}
}

4. Job Status Query Test​

@SpringBootTest
@AutoConfigureWebTestClient
public class JobControllerTest {

@Autowired
private WebTestClient webTestClient;

@Test
public void testJobStatusQuery() {
webTestClient.get().uri("/api/jobs/status?jobId=1")
.exchange()
.expectStatus().isOk()
.expectBody(String.class).isEqualTo("SUCCESS");
}
}

​

Global Exception Handler​

1. Global Exception Handler Configuration​

@ControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleException(Exception ex) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An error occurred: " + ex.getMessage());
}

@ExceptionHandler(WebClientResponseException.class)
public ResponseEntity<String> handleWebClientResponseException(WebClientResponseException ex) {
return ResponseEntity.status(ex.getStatusCode()).body("WebClient error: " + ex.getResponseBodyAsString());
}

@ExceptionHandler(R2dbcDataIntegrityViolationException.class)
public ResponseEntity<String> handleDataIntegrityViolationException(R2dbcDataIntegrityViolationException ex) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Data integrity violation: " + ex.getMessage());
}
}

​

Project Structure​

Project Structure Diagram​

spark-as-a-service/
├── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── example/
│ │ │ └── sparkasaservice/
│ │ │ ├── config/
│ │ │ │ ├── RedisConfig.java
│ │ │ │ ├── SparkRestApiConfig.java
│ │ │ │ ├── R2dbcConfig.java
│ │ │ │ └── SwaggerConfig.java
│ │ │ ├── controller/
│ │ │ │ └── JobController.java
│ │ │ ├── exception/
│ │ │ │ └── GlobalExceptionHandler.java
│ │ │ ├── model/
│ │ │ │ ├── JobRequest.java
│ │ │ │ ├── JobState.java
│ │ │ │ └── JobStatus.java
│ │ │ ├── repository/
│ │ │ │ └── JobRepository.java
│ │ │ ├── service/
│ │ │ │ ├── JobExecutorService.java
│ │ │ │ ├── PostgresService.java
│ │ │ │ ├── RedisQueueService.java
│ │ │ │ └── SparkRestApiService.java
│ │ │ └── SparkAsAServiceApplication.java
│ │ └── resources/
│ │ ├── application.yml
│ │ └── schema.sql
│ └── test/
│ ├── java/
│ │ └── com/
│ │ └── example/
│ │ └── sparkasaservice/
│ │ ├── controller/
│ │ │ └── JobControllerTest.java
│ │ ├── service/
│ │ │ └── JobExecutorServiceTest.java
│ │ └── SparkAsAServiceApplicationTests.java
│ └── resources/
│ └── application-test.yml
└── pom.xml

Listening to Redis Queue​

1. Redis Queue Listener Configuration​

To listen to the Redis queue and trigger the executeNextJob method, we can use Spring Data Redis's reactive support with Lettuce as the Redis client.

2. Redis Queue Listener Service​

@Service
public class RedisQueueListenerService {
private final JobExecutorService jobExecutorService;
private final ReactiveRedisTemplate<String, JobRequest> redisTemplate;

public RedisQueueListenerService(JobExecutorService jobExecutorService, ReactiveRedisTemplate<String, JobRequest> redisTemplate) {
this.jobExecutorService = jobExecutorService;
this.redisTemplate = redisTemplate;
}

@PostConstruct
public void startListening() {
redisTemplate.listenToPattern("__keyevent@*__:rpush")
.doOnNext(message -> {
if (message.getChannel().equals("__keyevent@0__:rpush") && message.getMessage().equals("jobQueue")) {
jobExecutorService.executeNextJob().subscribe();
}
})
.subscribe();
}
}

3. Redis Configuration for Pub/Sub​

@Configuration
public class RedisConfig {
@Bean
public ReactiveRedisTemplate<String, JobRequest> reactiveRedisTemplate(ReactiveRedisConnectionFactory factory) {
RedisSerializationContext<String, JobRequest> serializationContext = RedisSerializationContext
.newSerializationContext(new StringRedisSerializer())
.value(new Jackson2JsonRedisSerializer<>(JobRequest.class))
.build();
return new ReactiveRedisTemplate<>(factory, serializationContext);
}

@Bean
public ReactiveRedisConnectionFactory reactiveRedisConnectionFactory(RedisProperties redisProperties) {
return new LettuceConnectionFactory(redisProperties.getHost(), redisProperties.getPort());
}
}

This article provides a comprehensive guide to developing a stateless Spring Boot application for Spark as a Service, along with detailed explanations of job queue management, Spark job submission, and test cases. Each section is designed to be detailed and actionable, ensuring that readers can implement the concepts effectively.

Best Practices for Java 8 Lambda Expressions

· 6 min read

Java 8 introduced lambda expressions, providing a functional programming capability that simplifies code, improves readability, and makes certain operations more concise. This article outlines best practices for using Java 8 lambda operators in real production scenarios, complete with detailed code samples, design diagrams, and unit tests.

1. High-Level Overview​

Java 8 lambda expressions and the Stream API transform traditional iterative and procedural operations into concise, readable code. Best practices include using functional interfaces, optimizing performance, and ensuring code maintainability.

Lambda Basics​

2.1 Functional Interfaces​

Functional interfaces are interfaces that have exactly one abstract method. They are the foundation of lambda expressions in Java. Some common functional interfaces include Predicate, Function, Consumer, and Supplier.

@FunctionalInterface
interface MyFunctionalInterface {
void doSomething();
}

2.2 Lambda Syntax​

Lambda expressions provide a concise way to represent instances of functional interfaces. The basic syntax is:

(parameters) -> expression
(parameters) -> { statements; }

Example:

MyFunctionalInterface myLambda = () -> System.out.println("Hello, Lambda!");
myLambda.doSomething();

3. Best Practices​

3.1 Simplifying Iterations​

Example: Replacing traditional loops with lambda expressions.

Before:

List<String> items = Arrays.asList("apple", "banana", "orange");
for (String item : items) {
System.out.println(item);
}

After:

items.forEach(System.out::println);

Best Practice: Use forEach() for concise iteration.

3.2 Avoiding Stateful Lambdas​

Stateful lambdas can lead to unpredictable behavior, especially in parallel streams. Prefer stateless lambdas to ensure thread safety.

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
numbers.stream()
.map(n -> n * 2) // Stateless lambda
.forEach(System.out::println);

3.3 Using Lambdas with Streams​

Example: Filtering, mapping, and collecting data using Stream.

Code Sample:

List<String> items = Arrays.asList("apple", "banana", "orange", "pear");
List<String> filteredItems = items.stream()
.filter(item -> item.startsWith("a"))
.map(String::toUpperCase)
.collect(Collectors.toList());

Best Practice: Use Stream to filter and transform data in a functional style.

3.4 Handling Exceptions​

Lambda expressions can’t throw checked exceptions directly. Use a helper method for handling them.

Code Sample:

public static <T> Consumer<T> handleConsumerWithException(Consumer<T> consumer) {
return i -> {
try {
consumer.accept(i);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
};
}

// Usage
items.forEach(handleConsumerWithException(item -> {
if (item.equals("apple")) {
throw new IOException("Test exception");
}
System.out.println(item);
}));
@FunctionalInterface
interface CheckedFunction<T, R> {
R apply(T t) throws Exception;
}

public static <T, R> Function<T, R> wrap(CheckedFunction<T, R> checkedFunction) {
return t -> {
try {
return checkedFunction.apply(t);
} catch (Exception e) {
throw new RuntimeException(e);
}
};
}

List<String> files = Arrays.asList("file1.txt", "file2.txt");
files.stream()
.map(wrap(File::new))
.forEach(System.out::println);

3.5 Using Method References​

Method references make lambda expressions cleaner.

Example:

// Using lambda
items.forEach(item -> System.out.println(item));

// Using method reference
items.forEach(System.out::println);

Best Practice: Use method references when possible for better readability.

3.6 Avoiding State Modifications​

Ensure that lambdas do not modify state, leading to race conditions in parallel streams.

Bad Practice:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int[] sum = {0};
numbers.parallelStream().forEach(num -> sum[0] += num); // Not thread-safe

Good Practice:

int sum = numbers.parallelStream().mapToInt(Integer::intValue).sum();

3.7 Chaining Lambdas​

Combine multiple lambda operations using andThen() or compose() for complex transformations.

Example:

Function<String, String> toUpperCase = String::toUpperCase;
Function<String, String> addExclamation = s -> s + "!";
Function<String, String> transform = toUpperCase.andThen(addExclamation);

System.out.println(transform.apply("hello")); // Output: HELLO!

3.8 Parallel Streams​

Parallel streams can improve performance for large datasets. However, ensure that the operations are thread-safe.

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.parallelStream()
.mapToInt(Integer::intValue)
.sum();
System.out.println("Sum: " + sum);

3.9 Lazy Evaluation​

Streams use lazy evaluation, meaning that operations are not executed until a terminal operation is called. This can optimize performance.

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
Optional<Integer> firstEven = numbers.stream()
.filter(n -> n % 2 == 0)
.findFirst();
System.out.println("First even number: " + firstEven.orElse(-1));

4. Code Samples​

Example: Processing large datasets in a batch processing service.

LambdaUsageExamples.java:

public class LambdaUsageExamples {
public List<String> filterAndTransform(List<String> items) {
return items.stream()
.filter(item -> item.length() > 3)
.map(String::toUpperCase)
.collect(Collectors.toList());
}

public void printItems(List<String> items) {
items.forEach(System.out::println);
}
}

4.1 Filtering and Mapping​

Filtering and mapping are common operations in data processing. Use filter and map methods to transform data.

List<Person> people = Arrays.asList(
new Person("Alice", 30),
new Person("Bob", 25),
new Person("Charlie", 35)
);

List<String> names = people.stream()
.filter(p -> p.getAge() > 25)
.map(Person::getName)
.collect(Collectors.toList());
System.out.println(names);

4.2 Reducing and Collecting​

Reducing and collecting operations aggregate data. Use reduce and collect methods for these operations.

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream()
.reduce(0, Integer::sum);
System.out.println("Sum: " + sum);

Map<String, Integer> nameToAge = people.stream()
.collect(Collectors.toMap(Person::getName, Person::getAge));
System.out.println(nameToAge);

4.3 Sorting and Grouping​

Sorting and grouping are useful for organizing data. Use sorted and groupingBy methods.

List<Person> sortedPeople = people.stream()
.sorted(Comparator.comparing(Person::getAge))
.collect(Collectors.toList());
System.out.println(sortedPeople);

Map<Integer, List<Person>> ageGroups = people.stream()
.collect(Collectors.groupingBy(Person::getAge));
System.out.println(ageGroups);

4.4 Custom Functional Interfaces​

Custom functional interfaces can be used to encapsulate business logic. Define custom interfaces as needed.

@FunctionalInterface
interface AgeChecker {
boolean checkAge(Person person);
}

AgeChecker isAdult = person -> person.getAge() >= 18;
people.stream()
.filter(isAdult::checkAge)
.forEach(System.out::println);

5. Conclusion​

Adhering to best practices with Java 8 lambdas enhances code readability, safety, and maintainability. Avoid modifying state within lambda operations, handle exceptions thoughtfully, and prefer method references for simpler expressions. Implementing these best practices in production scenarios ensures robust and scalable code.

References​


Best Practices for Local Storage Handling in ReactJS

· 11 min read

Introduction​

Local storage is a powerful tool for persisting data in web applications. In ReactJS, local storage can be used to store user preferences, shopping cart items, and other data that needs to persist across sessions. This article will deep dive into best practices for handling local storage in ReactJS with TypeScript, focusing on functional components and the latest version of the tech stack. We will provide real production scenarios with TypeScript code samples, design diagrams, project folder structures, unit test cases, and commands to initialize and add dependencies using Yarn.

1. Local Storage Basics​

1.1 Project Setup​

To get started, we need to set up a React project with TypeScript and add the necessary dependencies using Yarn.

Yarn Commands​

# Create a React project with TypeScript template
yarn create react-app local-storage-app --template typescript

# Navigate into the project directory
cd local-storage-app

# Add any additional dependencies if needed (e.g., testing libraries)
yarn add @testing-library/react @testing-library/jest-dom

1.2 Project Folder Structure​

project-root/
├── src/
│ ├── components/
│ │ ├── UserPreferencesComponent.tsx
│ │ ├── ShoppingCartComponent.tsx
│ ├── hooks/
│ │ └── useLocalStorage.ts
│ ├── utils/
│ │ ├── localStorageUtils.ts
│ ├── App.tsx
│ ├── index.tsx
├── tests/
│ ├── components/
│ │ ├── UserPreferencesComponent.test.tsx
│ │ ├── ShoppingCartComponent.test.tsx
│ ├── utils/
│ │ ├── localStorageUtils.test.ts
├── package.json
├── tsconfig.json
├── yarn.lock

2.1 What is Local Storage?​

Local storage is a web storage API that allows you to store key-value pairs in a web browser. It is a synchronous, persistent storage that allows developers to store data client-side. The data stored in local storage persists even after the browser is closed and reopened. Leveraging local storage in React applications with TypeScript can help maintain user state, save preferences, and reduce API calls.

2.2 Local Storage vs Session Storage​

  • Local Storage: Data persists across browser sessions.
  • Session Storage: Data is cleared when the browser session ends (e.g., when the browser is closed).

3. Local Storage Basics​

3.1 Basic API​

Local storage provides a simple API: setItem(), getItem(), and removeItem(). Data stored in local storage is accessible across browser sessions.

// Setting an item
localStorage.setItem('key', 'value');

// Getting an item
const value = localStorage.getItem('key');

// Removing an item
localStorage.removeItem('key');

3.2 Type Safety​

Use TypeScript to ensure type safety when interacting with local storage. Create utility functions or custom hooks in TypeScript to handle type-safe operations.

interface UserPreferences {
theme: string;
notifications: boolean;
}

const setUserPreferences = (preferences: UserPreferences): void => {
setLocalStorageItem('userPreferences', preferences);
};

const getUserPreferences = (): UserPreferences | null => {
return getLocalStorageItem<UserPreferences>('userPreferences');
};

3.3 Error Handling​

Handle errors gracefully when interacting with local storage. Wrap local storage operations in try-catch blocks to handle any potential errors gracefully.

export const setLocalStorageItem = <T>(key: string, value: T): void => {
try {
localStorage.setItem(key, JSON.stringify(value));
} catch (error) {
console.error(`Error setting local storage item: ${error}`);
}
};

export const getLocalStorageItem = <T>(key: string): T | null => {
try {
const item = localStorage.getItem(key);
return item ? JSON.parse(item) : null;
} catch (error) {
console.error(`Error getting local storage item: ${error}`);
return null;
}
};

3.4 Data Serialization​

Ensure that data is properly serialized and deserialized when storing and retrieving from local storage. Always serialize complex data structures as strings using JSON.stringify().

export const setLocalStorageItem = <T>(key: string, value: T): void => {
localStorage.setItem(key, JSON.stringify(value));
};

export const getLocalStorageItem = <T>(key: string): T | null => {
const item = localStorage.getItem(key);
return item ? JSON.parse(item) : null;
};

3.5 Expiration Handling​

Implement expiration handling for local storage items to ensure that stale data is not used.

interface ExpirableItem<T> {
value: T;
expiration: number;
}

export const setExpirableLocalStorageItem = <T>(key: string, value: T, expirationInMinutes: number): void => {
const expiration = new Date().getTime() + expirationInMinutes * 60 * 1000;
const item: ExpirableItem<T> = { value, expiration };
setLocalStorageItem(key, item);
};

export const getExpirableLocalStorageItem = <T>(key: string): T | null => {
const item = getLocalStorageItem<ExpirableItem<T>>(key);
if (item && item.expiration > new Date().getTime()) {
return item.value;
}
removeLocalStorageItem(key);
return null;
};

4. Best Practices​

4.1 Encapsulating Local Storage Access​

Encapsulate local storage logic inside React hooks or service functions to keep components clean. Encapsulate local storage access within utility functions to avoid code duplication and improve maintainability.

export const setLocalStorageItem = <T>(key: string, value: T): void => {
localStorage.setItem(key, JSON.stringify(value));
};

export const getLocalStorageItem = <T>(key: string): T | null => {
const item = localStorage.getItem(key);
return item ? JSON.parse(item) : null;
};

export const removeLocalStorageItem = (key: string): void => {
localStorage.removeItem(key);
};

5 More Scenarios​

5.1 Scenario 1: User Preferences​

import React, { useState, useEffect } from 'react';
import { setUserPreferences, getUserPreferences } from './localStorageUtils';

interface UserPreferences {
theme: string;
notifications: boolean;
}

const UserPreferencesComponent: React.FC = () => {
const [preferences, setPreferences] = useState<UserPreferences | null>(null);

useEffect(() => {
const storedPreferences = getUserPreferences();
if (storedPreferences) {
setPreferences(storedPreferences);
}
}, []);

const handleThemeChange = (theme: string) => {
const updatedPreferences = { ...preferences, theme } as UserPreferences;
setUserPreferences(updatedPreferences);
setPreferences(updatedPreferences);
};

const handleNotificationsChange = (notifications: boolean) => {
const updatedPreferences = { ...preferences, notifications } as UserPreferences;
setUserPreferences(updatedPreferences);
setPreferences(updatedPreferences);
};

return (
<div>
<h1>User Preferences</h1>
<div>
<label>Theme:</label>
<select value={preferences?.theme} onChange={(e) => handleThemeChange(e.target.value)}>
<option value="light">Light</option>
<option value="dark">Dark</option>
</select>
</div>
<div>
<label>Notifications:</label>
<input
type="checkbox"
checked={preferences?.notifications}
onChange={(e) => handleNotificationsChange(e.target.checked)}
/>
</div>
</div>
);
};

export default UserPreferencesComponent;

5.2 Scenario 2: Shopping Cart​

import React, { useState, useEffect } from 'react';
import { setLocalStorageItem, getLocalStorageItem, removeLocalStorageItem } from './localStorageUtils';

interface CartItem {
id: number;
name: string;
price: number;
}

const ShoppingCartComponent: React.FC = () => {
const [cartItems, setCartItems] = useState<CartItem[]>([]);

useEffect(() => {
const storedCartItems = getLocalStorageItem<CartItem[]>('cartItems');
if (storedCartItems) {
setCartItems(storedCartItems);
}
}, []);

const addToCart = (item: CartItem) => {
const updatedCartItems = [...cartItems, item];
setLocalStorageItem('cartItems', updatedCartItems);
setCartItems(updatedCartItems);
};

const removeFromCart = (id: number) => {
const updatedCartItems = cartItems.filter((item) => item.id !== id);
setLocalStorageItem('cartItems', updatedCartItems);
setCartItems(updatedCartItems);
};

return (
<div>
<h1>Shopping Cart</h1>
<ul>
{cartItems.map((item) => (
<li key={item.id}>
{item.name} - ${item.price}
<button onClick={() => removeFromCart(item.id)}>Remove</button>
</li>
))}
</ul>
<button onClick={() => addToCart({ id: Date.now(), name: 'New Item', price: 10 })}>Add Item</button>
</div>
);
};

export default ShoppingCartComponent;

6-Design Diagrams​

6.1 Component Diagram​

+-------------------+ +-------------------+ +-------------------+
| App | | UserPreferences | | ShoppingCart |
+-------------------+ +-------------------+ +-------------------+
| | |
| (1) User Preferences | |
|-------------------------->| |
| | (2) Shopping Cart |
| |-------------------------->|
| | |
| (3) Local Storage | |
|<--------------------------| |
| | |
+-------------------+ +-------------------+ +-------------------+
| App | | UserPreferences | | ShoppingCart |
+-------------------+ +-------------------+ +-------------------+

6.2 Sequence Diagram​

+-------------------+ +-------------------+ +-------------------+
| User | | UserPreferences | | Local Storage |
+-------------------+ +-------------------+ +-------------------+
| | |
| (1) Change Theme | |
|-------------------------->| |
| | (2) Update Preferences |
| |-------------------------->|
| | |
| (3) Store Preferences | |
|<--------------------------| |
| | |
+-------------------+ +-------------------+ +-------------------+
| User | | UserPreferences | | Local Storage |
+-------------------+ +-------------------+ +-------------------+

7. Unit Test Cases​

7.1 UserPreferencesComponent.test.tsx​

import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import UserPreferencesComponent from '../../src/components/UserPreferencesComponent';
import { setUserPreferences, getUserPreferences } from '../../src/utils/localStorageUtils';

jest.mock('../../src/utils/localStorageUtils', () => ({
setUserPreferences: jest.fn(),
getUserPreferences: jest.fn(),
}));

test('UserPreferencesComponent updates and retrieves preferences', () => {
(getUserPreferences as jest.Mock).mockReturnValue({ theme: 'light', notifications: true });

const { getByLabelText, getByText } = render(<UserPreferencesComponent />);

fireEvent.change(getByLabelText('Theme:'), { target: { value: 'dark' } });
expect(setUserPreferences).toHaveBeenCalledWith({ theme: 'dark', notifications: true });

fireEvent.click(getByLabelText('Notifications:'));
expect(setUserPreferences).toHaveBeenCalledWith({ theme: 'dark', notifications: false });
});

7.2 ShoppingCartComponent.test.tsx​

import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import ShoppingCartComponent from '../../src/components/ShoppingCartComponent';
import { setLocalStorageItem, getLocalStorageItem, removeLocalStorageItem } from '../../src/utils/localStorageUtils';

jest.mock('../../src/utils/localStorageUtils', () => ({
setLocalStorageItem: jest.fn(),
getLocalStorageItem: jest.fn(),
removeLocalStorageItem: jest.fn(),
}));

test('ShoppingCartComponent adds and removes items', () => {
(getLocalStorageItem as jest.Mock).mockReturnValue([{ id: 1, name: 'Item 1', price: 10 }]);

const { getByText } = render(<ShoppingCartComponent />);

fireEvent.click(getByText('Add Item'));
expect(setLocalStorageItem).toHaveBeenCalled();

fireEvent.click(getByText('Remove'));
expect(removeLocalStorageItem).toHaveBeenCalled();
});

8. Commands to Init and Add Dependencies​

# Initialize a new React project with TypeScript
yarn create react-app my-app --template typescript

# Navigate to the project directory
cd my-app

# Add Testing Library
yarn add --dev @testing-library/react @testing-library/jest-dom

9. Conclusion​

Local storage is a powerful tool for persisting data in web applications. This article provided a deep dive into best practices for handling local storage in ReactJS with TypeScript, focusing on functional components and the latest version of the tech stack. We explored real production scenarios with TypeScript code samples, design diagrams, project folder structures, unit test cases, and commands to initialize and add dependencies using Yarn.

By understanding and applying these best practices, developers can effectively manage local storage in their ReactJS applications, ensuring they remain scalable, maintainable, and performant.

10. More Samples​

10.1 Project Setup​

To get started, we need to set up a React project with TypeScript and add the necessary dependencies using Yarn.

Yarn Commands

# Create a React project with TypeScript template
yarn create react-app local-storage-app --template typescript

# Navigate into the project directory
cd local-storage-app

# Add any additional dependencies if needed (e.g., testing libraries)
yarn add @testing-library/react @testing-library/jest-dom

Project Folder Structure

local-storage-app/
├── src/
│ ├── components/
│ │ ├── LocalStorageHandler.tsx
│ │ └── UserPreferences.tsx
│ ├── hooks/
│ │ └── useLocalStorage.ts
│ ├── tests/
│ │ └── LocalStorageHandler.test.tsx
│ ├── App.tsx
│ └── index.tsx
├── public/
└── package.json

useLocalStorage.ts

// src/hooks/useLocalStorage.ts
import { useState } from 'react';

/**
* Custom hook for local storage handling
* @param key - The key under which data is stored in local storage
* @param initialValue - The initial value to use if no value is stored
* @returns A tuple containing the stored value and a function to set the value
*/
function useLocalStorage<T>(key: string, initialValue: T) {
const [storedValue, setStoredValue] = useState<T>(() => {
try {
const item = localStorage.getItem(key);
return item ? (JSON.parse(item) as T) : initialValue;
} catch (error) {
console.error('Error reading from local storage', error);
return initialValue;
}
});

/**
* Sets a new value in local storage
* @param value - The new value to store
*/
const setValue = (value: T) => {
try {
setStoredValue(value);
localStorage.setItem(key, JSON.stringify(value));
} catch (error) {
console.error('Error saving to local storage', error);
}
};

return [storedValue, setValue] as const;
}

export default useLocalStorage;

UserPreferences: Detailed Code for Using useLocalStorage in a Component

// src/components/UserPreferences.tsx
import React from 'react';
import useLocalStorage from '../hooks/useLocalStorage';

const UserPreferences: React.FC = () => {
// Using the custom hook to manage theme preference
const [theme, setTheme] = useLocalStorage<string>('theme', 'light');

// Toggles between 'light' and 'dark' themes
const toggleTheme = () => {
setTheme(theme === 'light' ? 'dark' : 'light');
};

return (
<div>
<h1>User Preferences</h1>
<p>Current theme: {theme}</p>
<button onClick={toggleTheme}>
Toggle Theme
</button>
</div>
);
};

export default UserPreferences;

Type-Safe Local Storage Utility Functions For larger applications, you might prefer having utility functions to handle local storage logic:

// src/utils/localStorageUtils.ts
export const getLocalStorageItem = <T>(key: string, defaultValue: T): T => {
try {
const storedItem = localStorage.getItem(key);
return storedItem ? (JSON.parse(storedItem) as T) : defaultValue;
} catch (error) {
console.error(`Error reading key "${key}" from local storage`, error);
return defaultValue;
}
};

export const setLocalStorageItem = <T>(key: string, value: T): void => {
try {
localStorage.setItem(key, JSON.stringify(value));
} catch (error) {
console.error(`Error setting key "${key}" in local storage`, error);
}
};

Detailed Unit Test Cases

// src/tests/useLocalStorage.test.tsx
import { renderHook, act } from '@testing-library/react';
import useLocalStorage from '../hooks/useLocalStorage';

describe('useLocalStorage hook', () => {
beforeEach(() => {
localStorage.clear();
});

it('should return initial value if no value is stored', () => {
const { result } = renderHook(() => useLocalStorage('testKey', 'initialValue'));
expect(result.current[0]).toBe('initialValue');
});

it('should save and retrieve a value', () => {
const { result } = renderHook(() => useLocalStorage('testKey', 'initialValue'));

act(() => {
result.current[1]('newValue');
});

expect(result.current[0]).toBe('newValue');
expect(localStorage.getItem('testKey')).toBe(JSON.stringify('newValue'));
});

it('should handle JSON parsing errors gracefully', () => {
localStorage.setItem('testKey', '{invalid JSON');
const { result } = renderHook(() => useLocalStorage('testKey', 'defaultValue'));
expect(result.current[0]).toBe('defaultValue');
});
});

Commands to Run Unit Tests

# Run unit tests with Yarn
yarn test

References​


This article provides a comprehensive guide to best practices for local storage handling in ReactJS with TypeScript, including detailed code samples, design diagrams, project folder structures, unit test cases, and commands to initialize and add dependencies using Yarn. By understanding and applying these practices, developers can leverage the full potential of local storage in their ReactJS projects.

Best Practices for Spring Application Health Check and Actuator

· 8 min read

Introduction​

Spring Actuator is a powerful tool for monitoring and managing Spring Boot applications. It provides production-ready features such as health checks, metrics, and tracing. Properly configuring and securing Actuator endpoints is crucial for ensuring the reliability and security of your application.

Key Benefits:

  • Helps detect issues before they affect users.
  • Provides an easy integration with monitoring systems like Prometheus, Grafana, and ELK stack.
  • Customizable to expose only the needed endpoints.

Spring Actuator Basics​

2.1 What is Spring Actuator?​

Spring Actuator is a sub-project of the Spring Boot framework that provides production-ready features for monitoring and managing applications. It exposes various endpoints that can be used to check the health of the application, gather metrics, environment and perform other administrative tasks.

2.2 Key Features​

Spring Boot Actuator offers various endpoints for different purposes:

Endpoint
Health Checks/actuator/healthProvides information about the health status of the application.
Metrics/actuator/metricsExposes various metrics such as memory usage, active threads, HTTP requests, and more.
Info Endpoint/actuator/infoProvides general or arbitrary information about the application.
Environment Endpoint/actuator/envShows properties from the Environment.
Shutdown Endpoint/actuator/shutdownAllows for graceful shutdown of the application.

2.3. Architecture Overview​

The architecture of a Spring Boot application with Actuator enabled can be visualized as follows:

+---------------------+
| Spring Boot App |
| |
| +---------------+ |
| | Actuator | |
| +---------------+ |
| Health Checks |
| Metrics |
| Info Endpoint |
+---------------------+
|
v
+-----------------------------+
| Monitoring System (e.g., |
| Prometheus, Grafana, ELK) |
+-----------------------------+
sequenceDiagram
participant Client
participant Actuator Endpoint
participant Health Indicator(s)

Client->>Actuator Endpoint: GET /actuator/health
Actuator Endpoint->>Health Indicator(s): Evaluate Health
Health Indicator(s)-->>Actuator Endpoint: Return Status
Actuator Endpoint-->>Client: Respond with Health Status

Best Practices​

3.1 Configuring Actuator Endpoints​

Add the following dependency to your pom.xml:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Configure Actuator endpoints to expose only the necessary information. Use the management.endpoints.web.exposure.include property to specify which endpoints should be exposed.

Configure Actuator in application.properties or application.yml:

application.properties

management.endpoints.web.exposure.include=health,info,metrics
management.endpoint.health.show-details=always

application.yaml

management:
endpoints:
web:
exposure:
include: health, metrics, info
endpoint:
health:
show-details: always

3.2 Securing Actuator Endpoints​

It is essential to secure your Actuator endpoints to prevent unauthorized access. Use Spring Security to restrict access to specific endpoints.

application.properties

management.endpoints.web.exposure.include=health,info
management.endpoints.web.base-path=/actuator
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/actuator/health").permitAll()
.antMatchers("/actuator/**").hasRole("ADMIN")
.and()
.httpBasic();
}
}

3.3 Custom Health Indicators​

Spring Boot allows you to create custom health indicators for specific checks, such as database connectivity or third-party service availability. Implement custom health indicators to monitor specific components of your application. Custom health indicators should extend the HealthIndicator interface.

CustomHealthIndicator

import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;

@Component
public class CustomHealthIndicator implements HealthIndicator {

@Override
public Health health() {
// Perform custom health check
boolean isHealthy = checkCustomComponent();
if (isHealthy) {
return Health.up().withDetail("Custom Service", "Available").build();
} else {
return Health.down().withDetail("Custom Service", "Custom component is down").build();
}
}

private boolean checkCustomComponent() {
// Custom health check logic
return true;
}
}

Unit Test for CustomHealthIndicator

import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.actuate.health.Health;

@SpringBootTest
public class CustomHealthIndicatorTest {

@Autowired
private CustomHealthIndicator customHealthIndicator;

@Test
public void healthIndicatorStatusShouldBeUp() {
Health health = customHealthIndicator.health();
assertThat(health.getStatus().getCode()).isEqualTo("UP");
}
}

3.4 Monitoring and Metrics​

Enable and configure metrics to monitor the performance and health of your application. Use the micrometer library to expose metrics to various monitoring systems.

management:
metrics:
export:
prometheus:
enabled: true

3.5 Graceful Shutdown​

Configure graceful shutdown to ensure that your application shuts down cleanly without interrupting ongoing requests.

server:
shutdown: graceful

Production Scenarios​

4.1 Scenario 1: Database Health Check​

Implement a health check for the database to ensure that the application can connect to the database.

import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

@Component
public class DatabaseHealthIndicator implements HealthIndicator {

private final DataSource dataSource;

public DatabaseHealthIndicator(DataSource dataSource) {
this.dataSource = dataSource;
}

@Override
public Health health() {
try (Connection connection = dataSource.getConnection()) {
if (connection.isValid(1000)) {
return Health.up().build();
} else {
return Health.down().withDetail("Error", "Database connection is not valid").build();
}
} catch (SQLException e) {
return Health.down(e).build();
}
}
}

4.2 Scenario 2: Custom Health Indicator​

Implement a custom health indicator to monitor a specific external service.

import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class ExternalServiceHealthIndicator implements HealthIndicator {

private final RestTemplate restTemplate;

public ExternalServiceHealthIndicator(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}

@Override
public Health health() {
try {
restTemplate.getForEntity("https://external-service.com/health", String.class);
return Health.up().build();
} catch (Exception e) {
return Health.down(e).withDetail("Error", "External service is down").build();
}
}
}

5. Architecture Diagrams​

5.1 Component Diagram​

+-------------------+ +-------------------+ +-------------------+
| Spring Boot App | | Spring Actuator | | Monitoring System |
+-------------------+ +-------------------+ +-------------------+
| | |
| (1) Health Check | |
|--------------------------->| |
| | (2) Metrics |
| |-------------------------->|
| | |
| (3) Info Endpoint | |
|<---------------------------| |
| | |
+-------------------+ +-------------------+ +-------------------+
| Spring Boot App | | Spring Actuator | | Monitoring System |
+-------------------+ +-------------------+ +-------------------+

5.2 Sequence Diagram​

+-------------------+ +-------------------+ +-------------------+
| Client | | Spring Boot App | | Spring Actuator |
+-------------------+ +-------------------+ +-------------------+
| | |
| (1) Health Check Request | |
|--------------------------->| |
| | (2) Perform Health Check |
| |-------------------------->|
| | |
| (3) Health Check Response | |
|<---------------------------| |
| | |
+-------------------+ +-------------------+ +-------------------+
| Client | | Spring Boot App | | Spring Actuator |
+-------------------+ +-------------------+ +-------------------+

6. Sample Code and Configuration​

6.1 Dependency Configuration​

Add the necessary dependencies to your pom.xml file.

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
</dependencies>

6.2 Actuator Configuration​

Configure Actuator endpoints in your application.yml file.

management:
endpoints:
web:
exposure:
include: health, metrics, info
metrics:
export:
prometheus:
enabled: true
server:
shutdown: graceful

6.3 Custom Health Indicator Implementation​

Implement a custom health indicator to monitor a specific component.

import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;

@Component
public class CustomHealthIndicator implements HealthIndicator {

@Override
public Health health() {
// Perform custom health check
boolean isHealthy = checkCustomComponent();
if (isHealthy) {
return Health.up().build();
} else {
return Health.down().withDetail("Error", "Custom component is down").build();
}
}

private boolean checkCustomComponent() {
// Custom health check logic
return true;
}
}

7. Key Takeaways​

  • Granular Health Checks: Implement separate health indicators for databases, message brokers, and other critical components.
  • Monitoring Integration: Integrate with monitoring tools like Prometheus and Grafana for visualizing metrics and health data.
  • Security Measures: Ensure only trusted sources can access sensitive health information.
  • Detailed Health Information: Enable detailed health information only for internal access to protect sensitive data.
  • Cluster-Aware Checks: In distributed environments, ensure health checks are cluster-aware and provide insights into individual instance health.

Conclusion​

Spring Actuator is a powerful tool for monitoring and managing Spring Boot applications. By following best practices such as configuring and securing Actuator endpoints, implementing custom health indicators, and enabling monitoring and metrics, you can ensure the reliability and security of your application. This article provided a comprehensive guide to best practices for Spring application health checks and Actuator, including architecture diagrams, sample code, and configuration details.

References​

Deep Dive into State Management in ReactJS

· 12 min read

Introduction​

State management is a critical aspect of building complex ReactJS applications. Proper state management ensures that your application remains scalable, maintainable, and performant. This article will deep dive into state management in ReactJS, focusing on functional components and the latest version of the tech stack. We will explore two main state management options: React Context API and Redux. Additionally, we will provide real production scenarios with TypeScript code samples, design diagrams, project folder structures, unit test cases, and commands to initialize and add dependencies using Yarn.

1. State Management Basics​

1.1 What is State?​

State in ReactJS is an object that represents the dynamic data of a component. It determines how the component renders and behaves. State can be local to a single component or shared across multiple components.

State management refers to managing data that changes over time, ensuring that the user interface updates appropriately. Choosing the right state management solution is crucial for developing scalable and maintainable applications. We'll explore useState and useReducer for local state management and Redux and Zustand for global state management, with detailed TypeScript examples.

1.2 Local State vs Global State​

  • Local State: State that is confined to a single component. It is managed using the useState hook.
  • Global State: State that is shared across multiple components. It is managed using state management libraries like React Context API or Redux.

2. Setting Up the Project​

Initialize the React Project with TypeScript​

Run the following commands to create a new React project with TypeScript and install the necessary dependencies:

# Create a new React app with TypeScript
yarn create react-app react-state-management --template typescript

# Navigate to the project folder
cd react-state-management

# Install Redux and Zustand for state management
yarn add redux react-redux @reduxjs/toolkit zustand

# Install TypeScript types for React and Redux
yarn add -D @types/react-redux

3. State Management Options​

3.1 React Context API​

The React Context API provides a way to pass data through the component tree without having to pass props down manually at every level. It is ideal for small to medium-sized applications.

import React, { createContext, useContext, useState } from 'react';

interface AuthContextType {
isAuthenticated: boolean;
login: () => void;
logout: () => void;
}

const AuthContext = createContext<AuthContextType>({
isAuthenticated: false,
login: () => {},
logout: () => {},
});

export const AuthProvider: React.FC = ({ children }) => {
const [isAuthenticated, setIsAuthenticated] = useState(false);

const login = () => setIsAuthenticated(true);
const logout = () => setIsAuthenticated(false);

return (
<AuthContext.Provider value={{ isAuthenticated, login, logout }}>
{children}
</AuthContext.Provider>
);
};

export const useAuth = () => useContext(AuthContext);

4. Local State Management with useState and useReducer​

4.1 Using useState​

useState is simple to use and ideal for managing local state.

TypeScript Code Sample:

import React, { useState } from 'react';

const Counter: React.FC = () => {
const [count, setCount] = useState<number>(0);

const increment = (): void => {
setCount(prevCount => prevCount + 1);
};

return (
<div>
<p>Current Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
};

export default Counter;

Best Practices:

  • Use useState for simple and straightforward state updates.
  • Type your state variables for better type safety.

4.2 Using useReducer​

useReducer is suitable for managing complex state logic.

TypeScript Code Sample:

import React, { useReducer } from 'react';

interface State {
count: number;
}

interface Action {
type: 'increment' | 'decrement';
}

const initialState: State = { count: 0 };

function reducer(state: State, action: Action): State {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
throw new Error('Unknown action type');
}
}

const Counter: React.FC = () => {
const [state, dispatch] = useReducer(reducer, initialState);

return (
<div>
<p>Current Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
<button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
</div>
);
};

export default Counter;

Best Practices:

  • Use useReducer when state logic is complex or involves multiple sub-values.
  • Type both state and actions for enhanced type safety.

5. Global State Management with Redux​

Redux is a predictable state container for JavaScript apps. It is widely used for managing global state in large-scale applications.

5.1 Architecture of Redux​

Redux Architecture:

+------------+ +---------------+ +-------------+
| Action | --> | Reducer | --> | Store |
+------------+ +---------------+ +-------------+
^ |
| |
+------------------------------------------+

5.2 Redux state machine​

Here's a textual representation of a state machine diagram for a Redux state management flow:

+--------------------+ Action +----------------------+
| | (dispatch) | |
| React Component | -----------------> | Action |
| | | (type & payload) |
+--------------------+ +----------------------+
|
|
Dispatches action
|
v
+----------------+
| |
| Reducer |
| (pure function)|
+----------------+
|
Updates state |
based on action |
v
+----------------+
| |
| Store |
| (holds state) |
+----------------+
|
State subscription |
triggers re-render |
of component |
v
+--------------------+ Updated +----------------------+
| | State | |
| React Component | <----------------- | Store |
| | | |
+--------------------+ +----------------------+

Explanation:​

  • React Component: The UI component where user interactions or events trigger actions.
  • Action: An object describing what type of event occurred (e.g., { type: 'INCREMENT' }).
  • Reducer: A pure function that takes the current state and an action, then returns a new state.
  • Store: The central place where the state is kept, updated, and managed.
  • State Flow: Components subscribe to the store to get updates when the state changes, causing a re-render to reflect new data.

5.2 Redux Samples​

The Simple One

import { createStore } from 'redux';

interface State {
count: number;
}

interface Action {
type: string;
}

const initialState: State = { count: 0 };

const reducer = (state = initialState, action: Action) => {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
case 'DECREMENT':
return { count: state.count - 1 };
default:
return state;
}
};

const store = createStore(reducer);

export default store;

The Sample of Details actions.ts:

export const increment = () => ({ type: 'INCREMENT' } as const);
export const decrement = () => ({ type: 'DECREMENT' } as const);

export type ActionType = ReturnType<typeof increment | typeof decrement>;

reducers.ts:

import { ActionType } from './actions';

interface State {
count: number;
}

const initialState: State = { count: 0 };

export const counterReducer = (state: State = initialState, action: ActionType): State => {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
case 'DECREMENT':
return { count: state.count - 1 };
default:
return state;
}
};

store.ts:

import { createStore } from 'redux';
import { counterReducer } from './reducers';

const store = createStore(counterReducer);

export default store;

App.tsx:

import React from 'react';
import { Provider, useDispatch, useSelector } from 'react-redux';
import store from './state/redux/store';
import { increment, decrement } from './state/redux/actions';

interface RootState {
count: number;
}

const App: React.FC = () => {
const count = useSelector((state: RootState) => state.count);
const dispatch = useDispatch();

return (
<Provider store={store}>
<div>
<p>Current Count: {count}</p>
<button onClick={() => dispatch(increment())}>Increment</button>
<button onClick={() => dispatch(decrement())}>Decrement</button>
</div>
</Provider>
);
};

export default App;

6. Alternative Global State Management with Zustand​

Zustand offers a simple and flexible state management solution without the boilerplate of Redux.

6.1 Architecture of Zustand​

Simple Architecture:

Component --> useStore --> State & Actions

6.2 TypeScript Code Example​

useStore.ts:

import create from 'zustand';

interface StoreState {
count: number;
increment: () => void;
decrement: () => void;
}

const useStore = create<StoreState>(set => ({
count: 0,
increment: () => set(state => ({ count: state.count + 1 })),
decrement: () => set(state => ({ count: state.count - 1 }))
}));

export default useStore;

App.tsx:

import React from 'react';
import useStore from './state/zustand/useStore';

const App

: React.FC = () => {
const { count, increment, decrement } = useStore();

return (
<div>
<p>Current Count: {count}</p>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
};

export default App;

More Scenarios​

7.1 Scenario 1: User Authentication​

React Context API​

import React from 'react';
import { AuthProvider, useAuth } from './AuthContext';

const LoginPage: React.FC = () => {
const { login } = useAuth();

return (
<div>
<h1>Login Page</h1>
<button onClick={login}>Login</button>
</div>
);
};

const Dashboard: React.FC = () => {
const { isAuthenticated, logout } = useAuth();

return (
<div>
<h1>Dashboard</h1>
{isAuthenticated ? (
<button onClick={logout}>Logout</button>
) : (
<p>Please login to access the dashboard.</p>
)}
</div>
);
};

const App: React.FC = () => (
<AuthProvider>
<LoginPage />
<Dashboard />
</AuthProvider>
);

export default App;

Redux​

import React from 'react';
import { Provider, useSelector, useDispatch } from 'react-redux';
import store from './store';

const LoginPage: React.FC = () => {
const dispatch = useDispatch();

const login = () => dispatch({ type: 'LOGIN' });

return (
<div>
<h1>Login Page</h1>
<button onClick={login}>Login</button>
</div>
);
};

const Dashboard: React.FC = () => {
const isAuthenticated = useSelector((state: any) => state.isAuthenticated);
const dispatch = useDispatch();

const logout = () => dispatch({ type: 'LOGOUT' });

return (
<div>
<h1>Dashboard</h1>
{isAuthenticated ? (
<button onClick={logout}>Logout</button>
) : (
<p>Please login to access the dashboard.</p>
)}
</div>
);
};

const App: React.FC = () => (
<Provider store={store}>
<LoginPage />
<Dashboard />
</Provider>
);

export default App;

7.2 Scenario 2: Shopping Cart​

React Context API​

import React, { createContext, useContext, useState } from 'react';

interface CartItem {
id: number;
name: string;
price: number;
}

interface CartContextType {
cartItems: CartItem[];
addToCart: (item: CartItem) => void;
removeFromCart: (id: number) => void;
}

const CartContext = createContext<CartContextType>({
cartItems: [],
addToCart: () => {},
removeFromCart: () => {},
});

export const CartProvider: React.FC = ({ children }) => {
const [cartItems, setCartItems] = useState<CartItem[]>([]);

const addToCart = (item: CartItem) => setCartItems([...cartItems, item]);
const removeFromCart = (id: number) =>
setCartItems(cartItems.filter((item) => item.id !== id));

return (
<CartContext.Provider value={{ cartItems, addToCart, removeFromCart }}>
{children}
</CartContext.Provider>
);
};

export const useCart = () => useContext(CartContext);

Redux​

import { createStore } from 'redux';

interface CartItem {
id: number;
name: string;
price: number;
}

interface State {
cartItems: CartItem[];
}

interface Action {
type: string;
payload?: any;
}

const initialState: State = { cartItems: [] };

const reducer = (state = initialState, action: Action) => {
switch (action.type) {
case 'ADD_TO_CART':
return { cartItems: [...state.cartItems, action.payload] };
case 'REMOVE_FROM_CART':
return {
cartItems: state.cartItems.filter((item) => item.id !== action.payload),
};
default:
return state;
}
};

const store = createStore(reducer);

export default store;

8. Some Diagrams​

+-------------------+ +-------------------+ +-------------------+
| App | | AuthProvider | | CartProvider |
+-------------------+ +-------------------+ +-------------------+
| | |
| (1) Auth Context | |
|--------------------------->| |
| | (2) Cart Context |
| |-------------------------->|
| | |
| (3) LoginPage | |
|<------------ --------------| |
| | |
| (4) Dashboard | |
|<------------ --------------| |
| | |
+-------------------+ +-------------------+ +-------------------+
| App | | AuthProvider | | CartProvider |
+-------------------+ +-------------------+ +-------------------+
+-------------------+ +-------------------+ +-------------------+
| User | | LoginPage | | AuthProvider |
+-------------------+ +-------------------+ +-------------------+
| | |
| (1) Click Login Button | |
|-------------------------->| |
| | (2) Dispatch Login Action |
| |-------------------------->|
| | |
| (3) Update Auth State | |
|<--------------------------| |
| | |
+-------------------+ +-------------------+ +-------------------+
| User | | LoginPage | | AuthProvider |
+-------------------+ +-------------------+ +-------------------+

Project Folder Structure​

project-root/
├── src/
│ ├── components/
│ │ ├── LoginPage.tsx
│ │ ├── Dashboard.tsx
│ ├── contexts/
│ │ ├── AuthContext.tsx
│ │ ├── CartContext.tsx
│ ├── redux/
│ │ ├── store.ts
│ ├── App.tsx
│ ├── index.tsx
├── tests/
│ ├── components/
│ │ ├── LoginPage.test.tsx
│ │ ├── Dashboard.test.tsx
│ ├── contexts/
│ │ ├── AuthContext.test.tsx
│ │ ├── CartContext.test.tsx
│ ├── redux/
│ │ ├── store.test.ts
├── package.json
├── tsconfig.json
├── yarn.lock

Unit Test Cases​

LoginPage.test.tsx​

import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import { AuthProvider, useAuth } from '../../src/contexts/AuthContext';
import LoginPage from '../../src/components/LoginPage';

const TestComponent: React.FC = () => {
const { isAuthenticated } = useAuth();
return <div>{isAuthenticated ? 'Logged In' : 'Logged Out'}</div>;
};

test('LoginPage logs in user', () => {
const { getByText } = render(
<AuthProvider>
<LoginPage />
<TestComponent />
</AuthProvider>
);

fireEvent.click(getByText('Login'));
expect(getByText('Logged In')).toBeInTheDocument();
});

Dashboard.test.tsx​

import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import { AuthProvider, useAuth } from '../../src/contexts/AuthContext';
import Dashboard from '../../src/components/Dashboard';

const TestComponent: React.FC = () => {
const { isAuthenticated } = useAuth();
return <div>{isAuthenticated ? 'Logged In' : 'Logged Out'}</div>;
};

test('Dashboard logs out user', () => {
const { getByText } = render(
<AuthProvider>
<Dashboard />
<TestComponent />
</AuthProvider>
);

fireEvent.click(getByText('Logout'));
expect(getByText('Logged Out')).toBeInTheDocument();
});

Commands to Init and Add Dependencies​

# Initialize a new React project with TypeScript
yarn create react-app my-app --template typescript

# Navigate to the project directory
cd my-app

# Add Redux and React-Redux
yarn add redux react-redux

# Add React Context API (no additional packages needed)

# Add Testing Library
yarn add --dev @testing-library/react @testing-library/jest-dom

Conclusion​

State management is a crucial aspect of building scalable and maintainable ReactJS applications. This article provided a deep dive into state management in ReactJS, focusing on functional components and the latest version of the tech stack. We explored two main state management options: React Context API and Redux. Additionally, we provided real production scenarios with TypeScript code samples, design diagrams, project folder structures, unit test cases, and commands to initialize and add dependencies using Yarn.

By understanding and applying these concepts, developers can effectively manage state in their ReactJS applications, ensuring they remain scalable, maintainable, and performant.

References​


This article provides a comprehensive guide to state management in ReactJS, including detailed code samples, design diagrams, project folder structures, unit test cases, and commands to initialize and add dependencies using Yarn. By understanding and applying these practices, developers can leverage the full potential of state management in their ReactJS projects.

Design Pattern - Template Method

· 9 min read

Introduction​

The Template Method design pattern is a behavioral design pattern that defines the skeleton of an algorithm in a method, deferring some steps to subclasses. It lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure. This pattern is particularly useful when you want to allow customization of parts of an algorithm while keeping the overall structure intact.

This article will deep dive into the Template Method design pattern, including its key components, design diagrams, sample code in Java, and real production scenarios.

Template Method Design Pattern Basics​

2.1 What is the Template Method Pattern?​

The Template Method pattern is a behavioral design pattern that defines the skeleton of an algorithm in a method, deferring some steps to subclasses. It lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.

2.2 Key Components​

  • Abstract Class: Defines the template method and abstract methods that represent the steps of the algorithm.
  • Concrete Class: Extends the abstract class and implements the abstract methods to provide specific behavior.

Design Diagrams​

3.1 Component Diagram​

[Template Method Pattern]
+----------------------------+
| AbstractClass |
| ----------------------- |
| + templateMethod() |
+----------------------------+
|
+---------------+
| |
+----------------+ +----------------+
| ConcreteClassA | | ConcreteClassB |
+----------------+ +----------------+
+-------------------+ +-------------------+ +-------------------+
| Client | | Abstract Class | | Concrete Class |
+-------------------+ +-------------------+ +-------------------+
| | |
| (1) Use Template Method | |
|--------------------------->| |
| | (2) Call Abstract Methods |
| |-------------------------->|
| | |
| (3) Execute Algorithm | |
|<---------------------------| |
| | |
+-------------------+ +-------------------+ +-------------------+
| Client | | Abstract Class | | Concrete Class |
+-------------------+ +-------------------+ +-------------------+

3.2 Class Diagram​

+-------------------+ +-------------------+ +-------------------+
| AbstractClass | | ConcreteClassA | | ConcreteClassB |
+-------------------+ +-------------------+ +-------------------+
| +templateMethod() |<------| +step1() | | +step1() |
| +step1() | | +step2() | | +step2() |
| +step2() | | | | |
+-------------------+ +-------------------+ +-------------------+

Explanation:​

  • AbstractClass: Defines the templateMethod() and other concrete or abstract methods.
  • ConcreteClassA/B: Implements the specific steps defined as abstract in the base class.

4. Implementation Sample​

4.1 Abstract Class​

The abstract class defines the template method and the abstract methods that represent the steps of the algorithm.

abstract class AbstractClass {

// Template method defines the skeleton of an algorithm
public final void templateMethod() {
step1();
step2();
step3();
}

// Abstract methods to be implemented by subclasses
protected abstract void step1();
protected abstract void step2();

// Hook method with default implementation
protected void step3() {
System.out.println("Default implementation of step3");
}
}

4.2 Concrete Classes​

Concrete classes extend the abstract class and implement the abstract methods to provide specific behavior.

class ConcreteClassA extends AbstractClass {

@Override
protected void step1() {
System.out.println("ConcreteClassA: Step 1");
}

@Override
protected void step2() {
System.out.println("ConcreteClassA: Step 2");
}
}

class ConcreteClassB extends AbstractClass {

@Override
protected void step1() {
System.out.println("ConcreteClassB: Step 1");
}

@Override
protected void step2() {
System.out.println("ConcreteClassB: Step 2");
}

@Override
protected void step3() {
System.out.println("ConcreteClassB: Custom implementation of step3");
}
}

4.3 Client Code​

The client code uses the template method to execute the algorithm.

public class Client {

public static void main(String[] args) {
AbstractClass classA = new ConcreteClassA();
classA.templateMethod();

System.out.println();

AbstractClass classB = new ConcreteClassB();
classB.templateMethod();
}
}

Output​

ConcreteClassA: Step 1
ConcreteClassA: Step 2
Default implementation of step3

ConcreteClassB: Step 1
ConcreteClassB: Step 2
ConcreteClassB: Custom implementation of step3

5. Implementation Sample II​

5.1 Abstract Class​

public abstract class DataProcessor {
// Template method defining the algorithm
public final void process() {
readData();
processData();
writeData();
}

// Steps to be implemented by subclasses
protected abstract void readData();
protected abstract void processData();

// Concrete method
protected void writeData() {
System.out.println("Writing data to output...");
}
}

5.2 Concrete Classes​

public class CSVDataProcessor extends DataProcessor {
@Override
protected void readData() {
System.out.println("Reading data from a CSV file...");
}

@Override
protected void processData() {
System.out.println("Processing CSV data...");
}
}

public class JSONDataProcessor extends DataProcessor {
@Override
protected void readData() {
System.out.println("Reading data from a JSON file...");
}

@Override
protected void processData() {
System.out.println("Processing JSON data...");
}
}

5.3 Client Code​

public class Main {
public static void main(String[] args) {
DataProcessor csvProcessor = new CSVDataProcessor();
csvProcessor.process();

System.out.println();

DataProcessor jsonProcessor = new JSONDataProcessor();
jsonProcessor.process();
}
}

Output:​

Reading data from a CSV file...
Processing CSV data...
Writing data to output...

Reading data from a JSON file...
Processing JSON data...
Writing data to output...

6. Scenarios​

5.1 Scenario 1: Document Processing​

In a document processing application, different types of documents (e.g., PDF, Word, Excel) may require different processing steps. The Template Method pattern can be used to define the common processing steps while allowing subclasses to implement document-specific steps.

Abstract Class​

abstract class DocumentProcessor {

// Template method defines the skeleton of the document processing algorithm
public final void processDocument() {
openDocument();
extractContent();
saveDocument();
}

// Abstract methods to be implemented by subclasses
protected abstract void openDocument();
protected abstract void extractContent();

// Hook method with default implementation
protected void saveDocument() {
System.out.println("Saving document to default location");
}
}

Concrete Classes​

class PdfDocumentProcessor extends DocumentProcessor {

@Override
protected void openDocument() {
System.out.println("Opening PDF document");
}

@Override
protected void extractContent() {
System.out.println("Extracting text and images from PDF");
}
}

class WordDocumentProcessor extends DocumentProcessor {

@Override
protected void openDocument() {
System.out.println("Opening Word document");
}

@Override
protected void extractContent() {
System.out.println("Extracting text and tables from Word");
}

@Override
protected void saveDocument() {
System.out.println("Saving Word document to custom location");
}
}

Client Code​

public class DocumentProcessingClient {

public static void main(String[] args) {
DocumentProcessor pdfProcessor = new PdfDocumentProcessor();
pdfProcessor.processDocument();

System.out.println();

DocumentProcessor wordProcessor = new WordDocumentProcessor();
wordProcessor.processDocument();
}
}

Output​

Opening PDF document
Extracting text and images from PDF
Saving document to default location

Opening Word document
Extracting text and tables from Word
Saving Word document to custom location

5.2 Scenario 2: Game Development​

In game development, different types of games (e.g., RPG, Strategy, Puzzle) may have common game loop steps (e.g., initialize, update, render) but require different implementations for each step. The Template Method pattern can be used to define the common game loop while allowing subclasses to implement game-specific steps.

Abstract Class​

abstract class Game {

// Template method defines the skeleton of the game loop
public final void runGame() {
initialize();
while (!isGameOver()) {
update();
render();
}
cleanup();
}

// Abstract methods to be implemented by subclasses
protected abstract void initialize();
protected abstract void update();
protected abstract void render();

// Hook method with default implementation
protected boolean isGameOver() {
return false;
}

// Hook method with default implementation
protected void cleanup() {
System.out.println("Cleaning up game resources");
}
}

Concrete Classes​

class RPGGame extends Game {

@Override
protected void initialize() {
System.out.println("Initializing RPG game");
}

@Override
protected void update() {
System.out.println("Updating RPG game state");
}

@Override
protected void render() {
System.out.println("Rendering RPG game graphics");
}

@Override
protected boolean isGameOver() {
// Custom game over condition for RPG
return false;
}
}

class PuzzleGame extends Game {

@Override
protected void initialize() {
System.out.println("Initializing Puzzle game");
}

@Override
protected void update() {
System.out.println("Updating Puzzle game state");
}

@Override
protected void render() {
System.out.println("Rendering Puzzle game graphics");
}

@Override
protected boolean isGameOver() {
// Custom game over condition for Puzzle
return false;
}

@Override
protected void cleanup() {
System.out.println("Cleaning up Puzzle game resources");
}
}

Client Code​

public class GameClient {

public static void main(String[] args) {
Game rpgGame = new RPGGame();
rpgGame.runGame();

System.out.println();

Game puzzleGame = new PuzzleGame();
puzzleGame.runGame();
}
}

Output​

Initializing RPG game
Updating RPG game state
Rendering RPG game graphics
Updating RPG game state
Rendering RPG game graphics
...
Cleaning up game resources

Initializing Puzzle game
Updating Puzzle game state
Rendering Puzzle game graphics
Updating Puzzle game state
Rendering Puzzle game graphics
...
Cleaning up Puzzle game resources

5.3 Scenario 3: ETL Data Pipeline​

In a production ETL (Extract, Transform, Load) data pipeline, different types of data sources (CSV, JSON, XML, databases) need to be processed uniformly but with some custom parsing or transformation logic. Using the Template Method pattern, you can create a base ETLProcessor class with a template for the steps (extract(), transform(), load()), and concrete classes implement the details for different data formats.

// Abstract Class
public abstract class ETLProcessor {
public final void runETL() {
extract();
transform();
load();
}

protected abstract void extract();
protected abstract void transform();

protected void load() {
System.out.println("Loading data into the target system...");
}
}

// Concrete Classes
public class CSVETLProcessor extends ETLProcessor {
@Override
protected void extract() {
System.out.println("Extracting data from CSV...");
}

@Override
protected void transform() {
System.out.println("Transforming CSV data...");
}
}

// Concrete Classes
public class DatabaseETLProcessor extends ETLProcessor {
@Override
protected void extract() {
System.out.println("Extracting data from Database...");
}

@Override
protected void transform() {
System.out.println("Transforming database records...");
}
}

Consistency: Ensures a consistent ETL workflow across data sources. Customization: Allows specific extraction and transformation logic for each data source while reusing the common load() step.


7. PROS and CONS​

PROS:​

  • Code Reusability: Common parts of the algorithm are implemented in the base class.
  • Enforces Structure: Ensures that subclasses follow the defined structure.
  • Customizability: Subclasses can implement specific steps as needed.

CONS:​

  • Rigid Structure: Changes to the base template can affect all subclasses.
  • Overuse: Overusing the pattern can lead to an overly complex class hierarchy.

8. Conclusion​

The Template Method design pattern is a powerful tool for defining the skeleton of an algorithm while allowing subclasses to provide specific implementations for certain steps. This pattern promotes code reuse and flexibility, enabling you to create extensible and maintainable software.

By understanding the key components, design diagrams, sample code, and real production scenarios provided in this article, you can effectively apply the Template Method pattern in your Java projects.

References​


This article provides a comprehensive guide to the Template Method design pattern, including detailed explanations, design diagrams, sample code in Java, and real production scenarios. By understanding and applying this pattern, developers can create flexible and maintainable software systems.

AI LLM Tool Ollama: Architecture and Conversation Processing Flow Analysis

· 4 min read

Overview of Ollama​

Ollama is a convenient tool for running LLM (Large Language Models) quickly. With Ollama, users can easily interact with large language models without complex environment configurations.

This article will analyze the overall architecture of Ollama and detail the specific processing flow when users engage in conversations with Ollama.

Ollama Architecture​

Ollama Architecture

Ollama employs a classic CS (Client-Server) architecture, where:

  • Client: Interacts with the user via the command line.
  • Server: Can be started via the command line, desktop application (based on the Electron framework), or Docker. Regardless of the startup method, the same executable file is ultimately invoked.
  • Communication: Client and Server communicate using HTTP.

The Ollama Server consists of two core components:

  • ollama-http-server: Handles interactions with the client.
  • llama.cpp: Serves as the LLM inference engine, responsible for loading and running large language models, processing inference requests, and returning results.
  • Interaction: ollama-http-server and llama.cpp also communicate via HTTP.

Note: llama.cpp is an independent open-source project that is cross-platform and hardware-friendly, capable of running on devices without GPUs, including Raspberry Pi.

Ollama Storage Structure​

Ollama Storage Architecture

Ollama uses the default local storage folder path $HOME/.ollama. The file structure is as follows:

$HOME/.ollama/
├── blobs/
├── manifests/
├── logs/
│ └── server.log
├── history
├── id_ed25519
└── id_ed25519.pub

Files can be categorized into three types:

  • Log Files: Includes the history file, which records user conversation inputs, and the logs/server.log server log file.
  • Key Files: Includes the id_ed25519 private key and id_ed25519.pub public key.
  • Model Files: Includes blobs raw data files and manifests metadata files.

The metadata files, such as models/manifests/registry.ollama.ai/library/llama3.2/latest, contain the following content:

llama3.2-latest

{
"digest": "sha256:abcdef1234567890",
"size": 123456789,
"annotations": {
"org.opencontainers.image.title": "llama3.2",
"org.opencontainers.image.version": "latest"
}
}

As shown above, manifests files are in JSON format and draw inspiration from the OCI spec (Open Container Initiative Specification) in cloud-native and container domains. The digest field in manifests corresponds to blobs.

Ollama Conversation Processing Flow​

Ollama Conversation Processing Flow

The general flow of a user conversation with Ollama is as follows:

  1. User Initiates Conversation: The user executes the command ollama run llama3.2 via the CLI to start a conversation (llama3.2 is an open-source large language model; you can also use other LLMs).

  2. Preparation Phase:

    • The CLI client sends an HTTP request to ollama-http-server to fetch model information. The server attempts to read the local manifests metadata files. If not found, it responds with a 404 not found.
    • When the model does not exist, the CLI client requests ollama-http-server to pull the model from the remote repository to the local storage.
    • The CLI client then requests the model information again.
  3. Interactive Conversation Phase:

    • The CLI sends an empty message /api/generate request to ollama-http-server, which internally handles some channel processing (using Go's channels).
    • If the model information contains messages, they are printed. Users can save the current model and session conversation history as a new model, and the conversation history is saved as messages.
    • The conversation officially begins: The CLI calls the /api/chat interface to request ollama-http-server, which relies on the llama.cpp engine to load the model and perform inference (llama.cpp also serves as an HTTP server). ollama-http-server first sends a /health request to llama.cpp to confirm its health status, then sends a /completion request to obtain the conversation response, and finally returns it to the CLI for display.

Through the above steps, Ollama completes the interaction between the user and the large language model.

Conclusion​

Ollama integrates the llama.cpp inference engine and further encapsulates it, making complex LLM technology accessible. It provides developers and technical personnel with an efficient and flexible tool, effectively supporting large language model inference and interaction in various application scenarios.

References:​