tibba_state/app_state.rs
1// Copyright 2025 Tree xie.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::sync::atomic::{AtomicBool, AtomicI32, Ordering};
16use std::time::SystemTime;
17
18/// Application state management structure
19/// Provides thread-safe tracking of:
20/// - Application status (running/stopped)
21/// - Concurrent request processing
22/// - Processing limits
23/// - Application start time
24pub struct AppState {
25 // Maximum number of concurrent requests allowed
26 processing_limit: i32,
27 // Current application status (running/stopped)
28 running: AtomicBool,
29 // Current number of requests being processed
30 processing: AtomicI32,
31 // Application start timestamp
32 started_at: SystemTime,
33 // Application commit id
34 commit_id: String,
35}
36
37impl AppState {
38 /// Creates a new AppState instance with specified processing limit
39 pub fn new(processing_limit: i32, commit_id: String) -> Self {
40 Self {
41 processing_limit,
42 running: AtomicBool::new(false),
43 processing: AtomicI32::new(0),
44 started_at: SystemTime::now(),
45 commit_id,
46 }
47 }
48
49 /// Returns the configured processing limit
50 pub fn get_processing_limit(&self) -> i32 {
51 self.processing_limit
52 }
53
54 /// Returns the application commit id
55 pub fn get_commit_id(&self) -> &str {
56 &self.commit_id
57 }
58
59 /// Atomically increments the processing counter
60 /// Returns the previous value
61 pub fn inc_processing(&self) -> i32 {
62 self.processing.fetch_add(1, Ordering::Relaxed)
63 }
64
65 /// Atomically decrements the processing counter
66 /// Returns the previous value
67 pub fn dec_processing(&self) -> i32 {
68 self.processing.fetch_sub(1, Ordering::Relaxed)
69 }
70
71 /// Returns the current number of requests being processed
72 pub fn get_processing(&self) -> i32 {
73 self.processing.load(Ordering::Relaxed)
74 }
75
76 /// Checks if the application is currently running
77 pub fn is_running(&self) -> bool {
78 self.running.load(Ordering::Relaxed)
79 }
80
81 /// Sets the application status to running
82 pub fn run(&self) {
83 self.running.store(true, Ordering::Relaxed)
84 }
85
86 /// Sets the application status to stopped
87 pub fn stop(&self) {
88 self.running.store(false, Ordering::Relaxed)
89 }
90
91 /// Returns the application start time
92 pub fn get_started_at(&self) -> SystemTime {
93 self.started_at
94 }
95}