team-ljyzipelo

공개
268줄8.2 KB
1use crate::{
2 core::{self, gzip, ustar, zip_create},
3 transport::{DeliveryFault, Transport},
4};
5use std::{
6 any::Any,
7 sync::mpsc::{self, Receiver, SyncSender},
8 thread::{self, JoinHandle},
9};
10
11pub const DEFAULT_CAPACITY: usize = 256;
12pub const PAYLOAD: &[u8] = include_bytes!("../../../tests/rust-ui-memory-app/fixtures/payload.txt");
13pub const GZIP: &[u8] = include_bytes!("../../../tests/rust-ui-memory-app/fixtures/sample.gz");
14pub const USTAR: &[u8] = include_bytes!("../../../tests/rust-ui-memory-app/fixtures/sample.tar");
15
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17pub enum Action {
18 Zip,
19 Ustar,
20 Gzip,
21 InvalidGzip,
22}
23
24#[derive(Debug)]
25pub enum ProgressEvent {
26 Zip(core::Event<zip_create::Checkpoint>),
27 Ustar(core::Event<ustar::Checkpoint>),
28 Gzip(core::Event<gzip::Checkpoint>),
29}
30
31impl ProgressEvent {
32 pub fn validate(
33 &self,
34 receiver: &mut core::Receiver,
35 ) -> Result<core::Delivery, core::DeliveryError> {
36 match self {
37 Self::Zip(e) => receiver.progress(e),
38 Self::Ustar(e) => receiver.progress(e),
39 Self::Gzip(e) => receiver.progress(e),
40 }
41 }
42 pub fn progress(&self) -> Option<core::Progress> {
43 match self {
44 Self::Zip(e) => e.progress,
45 Self::Ustar(e) => e.progress,
46 Self::Gzip(e) => e.progress,
47 }
48 }
49}
50
51#[derive(Debug, PartialEq, Eq)]
52pub struct CallbackFailure(pub &'static str);
53
54#[derive(Debug)]
55pub enum Outcome {
56 Zip(core::Terminal<Vec<u8>, zip_create::Failure>),
57 Ustar(core::Terminal<ustar::Completed, ustar::Error<CallbackFailure>>),
58 Gzip(core::Terminal<gzip::Completed, gzip::Error<CallbackFailure>>),
59}
60
61impl Outcome {
62 pub fn validate(
63 &self,
64 receiver: &mut core::Receiver,
65 ) -> Result<core::Delivery, core::DeliveryError> {
66 match self {
67 Self::Zip(e) => receiver.terminal(e),
68 Self::Ustar(e) => receiver.terminal(e),
69 Self::Gzip(e) => receiver.terminal(e),
70 }
71 }
72 pub fn is_ok(&self) -> bool {
73 match self {
74 Self::Zip(e) => e.result().is_ok(),
75 Self::Ustar(e) => e.result().is_ok(),
76 Self::Gzip(e) => e.result().is_ok(),
77 }
78 }
79 pub fn cancelled(&self) -> bool {
80 match self {
81 Self::Zip(t) => matches!(
82 t.result(),
83 Err(core::Failure {
84 native: Some(zip_create::Failure::Cancelled),
85 ..
86 })
87 ),
88 Self::Ustar(t) => matches!(
89 t.result(),
90 Err(core::Failure {
91 native: Some(ustar::Error::Reader(ustar::Failure::Cancelled)),
92 ..
93 })
94 ),
95 Self::Gzip(t) => matches!(
96 t.result(),
97 Err(core::Failure {
98 native: Some(gzip::Error::Reader(gzip::Failure::Cancelled)),
99 ..
100 })
101 ),
102 }
103 }
104 pub fn next_sequence(&self) -> u64 {
105 match self {
106 Self::Zip(t) => t.stamp().sequence(),
107 Self::Ustar(t) => t.stamp().sequence(),
108 Self::Gzip(t) => t.stamp().sequence(),
109 }
110 }
111}
112
113#[derive(Debug)]
114pub struct Completion {
115 pub outcome: Outcome,
116 pub delivery: Option<DeliveryFault>,
117}
118
119pub fn execute(
120 operation: core::Operation,
121 action: Action,
122 sender: SyncSender<ProgressEvent>,
123) -> Completion {
124 let mut transport = Transport::new(sender);
125 let outcome = match action {
126 Action::Zip => Outcome::Zip(operation.create_zip(
127 zip_create::Request {
128 entries: vec![zip_create::Entry {
129 name: "sample.txt".into(),
130 bytes: PAYLOAD.into(),
131 }],
132 options: zip_create::Options::default(),
133 limits: zip_create::Limits::default(),
134 timeout: std::time::Duration::from_secs(5),
135 },
136 |event| {
137 transport.forward(
138 event.stamp().sequence(),
139 ProgressEvent::Zip(event),
140 Ok(()),
141 || zip_create::Stop::Cancelled,
142 )
143 },
144 )),
145 Action::Ustar => Outcome::Ustar(operation.ustar(
146 ustar::Request {
147 input: USTAR.into(),
148 policy: ustar::NamePolicy::Linux,
149 limits: ustar::Limits::default(),
150 },
151 |entries| Ok(entries.iter().map(|entry| entry.id.clone()).collect()),
152 |event| {
153 transport.forward(
154 event.stamp().sequence(),
155 ProgressEvent::Ustar(event),
156 Ok(()),
157 || ustar::Stop::Cancelled,
158 )
159 },
160 )),
161 Action::Gzip | Action::InvalidGzip => {
162 let input = if action == Action::InvalidGzip {
163 Box::from(&b"invalid"[..])
164 } else {
165 GZIP.into()
166 };
167 let mut budget = gzip::Budget::new(gzip::Limits::default()).expect("고정 기본 예산");
168 Outcome::Gzip(operation.gzip(
169 gzip::Request {
170 input,
171 selected: true,
172 },
173 &mut budget,
174 |event| {
175 transport.forward(
176 event.stamp().sequence(),
177 ProgressEvent::Gzip(event),
178 Ok(()),
179 || gzip::Stop::Cancelled,
180 )
181 },
182 ))
183 }
184 };
185 Completion {
186 outcome,
187 delivery: transport.fault,
188 }
189}
190
191pub fn deliver_completion(
192 sender: &SyncSender<Completion>,
193 completion: Completion,
194) -> Option<Completion> {
195 match sender.try_send(completion) {
196 Ok(()) => None,
197 Err(mpsc::TrySendError::Full(value) | mpsc::TrySendError::Disconnected(value)) => {
198 Some(value)
199 }
200 }
201}
202
203#[derive(Debug)]
204pub enum StartFailure {
205 Capacity,
206 Operation(core::AdapterFailure),
207 Spawn(std::io::Error),
208}
209
210#[must_use = "작업 소유자는 종료까지 핸들을 보존해야 함"]
211pub struct Task {
212 pub id: core::OperationId,
213 pub cancellation: core::Cancellation,
214 pub events: Option<Receiver<ProgressEvent>>,
215 pub completion: Option<Receiver<Completion>>,
216 handle: Option<JoinHandle<Option<Completion>>>,
217}
218
219impl Task {
220 pub fn spawn(action: Action, capacity: usize) -> Result<Self, StartFailure> {
221 Self::spawn_with(capacity, move |op, sender| execute(op, action, sender))
222 }
223 pub fn spawn_with(
224 capacity: usize,
225 work: impl FnOnce(core::Operation, SyncSender<ProgressEvent>) -> Completion + Send + 'static,
226 ) -> Result<Self, StartFailure> {
227 if capacity > DEFAULT_CAPACITY {
228 return Err(StartFailure::Capacity);
229 }
230 let (op, cancellation) = core::Operation::start().map_err(StartFailure::Operation)?;
231 let id = op.id();
232 let (sender, events) = mpsc::sync_channel(capacity);
233 let (done, completion) = mpsc::sync_channel(1);
234 let handle = thread::Builder::new()
235 .name("zipelo-memory".into())
236 .spawn(move || deliver_completion(&done, work(op, sender)))
237 .map_err(StartFailure::Spawn)?;
238 Ok(Self {
239 id,
240 cancellation,
241 events: Some(events),
242 completion: Some(completion),
243 handle: Some(handle),
244 })
245 }
246 pub fn finished(&self) -> bool {
247 self.handle.as_ref().is_none_or(JoinHandle::is_finished)
248 }
249 pub fn joined(&self) -> bool {
250 self.handle.is_none()
251 }
252 pub fn poll_join(&mut self) -> Option<Result<Option<Completion>, Box<dyn Any + Send>>> {
253 if !self.finished() {
254 return None;
255 }
256 self.handle.take().map(JoinHandle::join)
257 }
258}
259
260impl Drop for Task {
261 fn drop(&mut self) {
262 // 정상 frame 경로는 종료 확인 뒤에만 Task를 제거함. 비정상 소유권 폐기도 detach하지 않음.
263 if let Some(handle) = self.handle.take() {
264 self.cancellation.request();
265 let _ = handle.join();
266 }
267 }
268}