Repository navigation
Expand file tree
/
Copy pathsupport.rs
More file actions
1557 lines (1433 loc) · 53.7 KB
/
Copy pathsupport.rs
File metadata and controls
1557 lines (1433 loc) · 53.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::ffi::{OsStr, OsString};
use std::future::Future;
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{TcpStream, ToSocketAddrs};
use std::ops::Deref;
use std::panic::AssertUnwindSafe;
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::process::{Child, Command, Stdio};
use std::sync::LazyLock;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, Instant};
use futures_util::FutureExt;
use github_copilot_sdk::handler::ApproveAllHandler;
use github_copilot_sdk::session::Session;
use github_copilot_sdk::subscription::{EventSubscription, LifecycleSubscription};
use github_copilot_sdk::{
CliProgram, Client, ClientOptions, CopilotRequestHandler, SessionConfig, SessionEvent,
SessionId, SessionLifecycleEvent, Transport,
};
use serde_json::json;
use tokio::sync::{Mutex, Semaphore};
static E2E_CONCURRENCY: LazyLock<Semaphore> = LazyLock::new(|| Semaphore::new(e2e_concurrency()));
static SHARED_E2E_RUNTIME: LazyLock<tokio::runtime::Runtime> = LazyLock::new(|| {
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.thread_name("rust-e2e-shared")
.build()
.expect("create shared E2E runtime")
});
const SHARED_E2E_CLEANUP_TIMEOUT: Duration = Duration::from_secs(10);
const PROXY_STARTUP_TIMEOUT: Duration = Duration::from_secs(30);
pub const DEFAULT_TEST_TOKEN: &str = "rust-e2e-token";
type TestFuture<'a> = Pin<Box<dyn Future<Output = ()> + 'a>>;
/// Fixed client options for one explicitly declared shared E2E group.
pub type SharedClientOptions = fn(&E2eContext) -> ClientOptions;
/// A file- or group-scoped shared E2E runtime.
///
/// This deliberately has no options-keyed registry: every Rust source group owns
/// its own static instance and selects its options at that declaration site.
pub struct SharedE2eGroup {
category: &'static str,
client_options: SharedClientOptions,
expected_invocations: usize,
completed_invocations: AtomicUsize,
state: Mutex<Option<SharedE2eState>>,
}
struct SharedE2eState {
context: E2eContext,
client: Client,
}
/// Test facade over a group's shared context and client.
///
/// It dereferences to [`E2eContext`] for proxy and fixture helpers, while
/// [`Self::start_client`] returns a clone of the group's already-started client.
pub struct SharedE2eContext<'a> {
context: &'a mut E2eContext,
client: Client,
}
/// A clone of a group's shared client.
///
/// `stop` is deliberately a no-op: tests retain their existing local teardown
/// shape without shutting down the next test's runtime. The group stops the
/// actual client after its final expected invocation. Tests that verify
/// stopping or force-stopping a client stay on the dedicated helper.
#[derive(Clone)]
pub struct SharedE2eClient(Client);
impl Deref for SharedE2eClient {
type Target = Client;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl SharedE2eClient {
pub async fn stop(&self) -> std::result::Result<(), github_copilot_sdk::StopErrors> {
Ok(())
}
}
impl Deref for SharedE2eContext<'_> {
type Target = E2eContext;
fn deref(&self) -> &Self::Target {
self.context
}
}
impl SharedE2eContext<'_> {
/// Clone the group client. Shared tests must not call `Client::stop`; the
/// group tears it down after its final expected test invocation.
pub async fn start_client(&self) -> SharedE2eClient {
SharedE2eClient(self.client.clone())
}
}
impl SharedE2eGroup {
pub const fn new(
category: &'static str,
client_options: SharedClientOptions,
expected_invocations: usize,
) -> Self {
Self {
category,
client_options,
expected_invocations,
completed_invocations: AtomicUsize::new(0),
state: Mutex::const_new(None),
}
}
pub const fn standard(category: &'static str, expected_invocations: usize) -> Self {
Self::new(
category,
standard_shared_client_options,
expected_invocations,
)
}
}
/// The standard stdio/default-transport options used by most shared groups.
pub fn standard_shared_client_options(context: &E2eContext) -> ClientOptions {
context.client_options()
}
/// Run a test against an explicitly declared, file/group-scoped shared client.
///
/// Calls using one group serialize, while different groups still use the suite
/// concurrency limit. Before and after every test, sessions are disconnected and
/// deleted, the work directory is emptied, and the proxy is reconfigured for the
/// test's snapshot so exchanges cannot bleed across tests. After the declared
/// number of invocations completes, the group's client and proxy are stopped.
pub async fn with_shared_e2e_context<F>(
group: &'static SharedE2eGroup,
category: &str,
snapshot_name: &str,
test: F,
) where
F: for<'a> FnOnce(&'a mut SharedE2eContext<'a>) -> TestFuture<'a>,
{
assert_eq!(
category, group.category,
"shared E2E group category must match the test's snapshots"
);
let mut state = group.state.lock().await;
let _permit = E2E_CONCURRENCY
.acquire()
.await
.expect("E2E concurrency semaphore should stay open");
let completed = group.completed_invocations.fetch_add(1, Ordering::Relaxed) + 1;
if state.is_none() {
let context = E2eContext::new(group.category, snapshot_name)
.await
.unwrap_or_else(|err| panic!("create shared E2E context: {err}"));
let _env_guard = InProcessEnvGuard::activate(&context);
let options = (group.client_options)(&context);
let mut startup = SHARED_E2E_RUNTIME.spawn(async move {
let client = Client::start(options).await?;
client.start_router_for_test();
Ok::<_, github_copilot_sdk::Error>(client)
});
let client = match tokio::time::timeout(default_test_timeout(), &mut startup).await {
Ok(result) => result
.expect("join shared E2E client startup")
.expect("start shared E2E client"),
Err(_) => {
startup.abort();
let _ = tokio::time::timeout(SHARED_E2E_CLEANUP_TIMEOUT, startup).await;
panic!(
"timed out after {:?} starting shared E2E client",
default_test_timeout()
);
}
};
*state = Some(SharedE2eState { context, client });
}
let _env_guard = InProcessEnvGuard::activate(
&state
.as_ref()
.expect("shared E2E state initialized")
.context,
);
let (result, cleanup_result) = {
let state = state.as_mut().expect("shared E2E state initialized");
let result = match tokio::time::timeout(
SHARED_E2E_CLEANUP_TIMEOUT,
state.prepare_test(group.category, snapshot_name),
)
.await
{
Ok(Ok(())) => Ok({
let mut context = SharedE2eContext {
context: &mut state.context,
client: state.client.clone(),
};
AssertUnwindSafe(tokio::time::timeout(
default_test_timeout(),
test(&mut context),
))
.catch_unwind()
.await
}),
Ok(Err(error)) => Err(error),
Err(_) => Err(std::io::Error::other(format!(
"timed out after {SHARED_E2E_CLEANUP_TIMEOUT:?} preparing shared E2E test"
))),
};
let cleanup_result = match tokio::time::timeout(
SHARED_E2E_CLEANUP_TIMEOUT,
state.cleanup_after_test(),
)
.await
{
Ok(result) => result,
Err(_) => {
state.client.force_stop();
Err(std::io::Error::other(format!(
"timed out after {SHARED_E2E_CLEANUP_TIMEOUT:?} cleaning up shared E2E test"
)))
}
};
(result, cleanup_result)
};
let test_succeeded = matches!(&result, Ok(Ok(Ok(()))));
let skip_writing_cache = !test_succeeded || cleanup_result.is_err();
let teardown_result = if !test_succeeded
|| cleanup_result.is_err()
|| is_filtered_test_run()
|| completed == group.expected_invocations
{
state
.take()
.expect("shared E2E state initialized")
.shutdown_bounded(skip_writing_cache)
.await
} else {
Ok(())
};
match result {
Ok(Ok(Ok(()))) => {
cleanup_result.unwrap_or_else(|error| panic!("clean up shared E2E test: {error}"));
teardown_result.unwrap_or_else(|error| panic!("tear down shared E2E group: {error}"));
}
Ok(Ok(Err(_))) => {
if let Err(error) = cleanup_result {
eprintln!("failed to clean up timed-out shared E2E test: {error}");
}
if let Err(error) = teardown_result {
eprintln!("failed to tear down shared E2E group after timeout: {error}");
}
panic!(
"timed out after {:?} running shared E2E test {}/{}",
default_test_timeout(),
group.category,
snapshot_name
);
}
Ok(Err(payload)) => {
if let Err(error) = cleanup_result {
eprintln!("failed to clean up shared E2E test after panic: {error}");
}
if let Err(error) = teardown_result {
eprintln!("failed to tear down shared E2E group after panic: {error}");
}
std::panic::resume_unwind(payload);
}
Err(error) => {
if let Err(cleanup_error) = cleanup_result {
eprintln!(
"failed to clean up shared E2E test after setup failure: {cleanup_error}"
);
}
if let Err(teardown_error) = teardown_result {
eprintln!(
"failed to tear down shared E2E group after setup failure: {teardown_error}"
);
}
panic!("prepare shared E2E test: {error}");
}
}
}
pub async fn with_dedicated_e2e_context<F>(category: &str, snapshot_name: &str, test: F)
where
F: for<'a> FnOnce(&'a mut E2eContext) -> TestFuture<'a>,
{
let _permit = E2E_CONCURRENCY
.acquire()
.await
.expect("E2E concurrency semaphore should stay open");
let mut ctx = E2eContext::new(category, snapshot_name)
.await
.unwrap_or_else(|err| panic!("create E2E context: {err}"));
// In-process hosting: the runtime loads into this test process and its worker
// inherits the ambient environment (per-client env is not honored in-process, see
// https://github.com/github/copilot-sdk/issues/1934), so mirror this context's env
// onto the process for the duration of the test and restore on drop. Safe because
// E2E_CONCURRENCY is 1 in-process, serializing the whole critical section.
let _env_guard = InProcessEnvGuard::activate(&ctx);
let timed_out = tokio::time::timeout(default_test_timeout(), test(&mut ctx))
.await
.is_err();
ctx.cleanup(timed_out)
.await
.unwrap_or_else(|err| panic!("clean up E2E context: {err}"));
assert!(
!timed_out,
"timed out after {:?} running E2E test {category}/{snapshot_name}",
default_test_timeout()
);
}
pub async fn with_dedicated_group_e2e_context<F>(
_group: &'static SharedE2eGroup,
category: &str,
snapshot_name: &str,
test: F,
) where
F: for<'a> FnOnce(&'a mut E2eContext) -> TestFuture<'a>,
{
with_dedicated_e2e_context(category, snapshot_name, test).await;
}
pub async fn skip_shared_e2e_inprocess(group: &'static SharedE2eGroup, reason: &str) -> bool {
if !skip_inprocess(reason) {
return false;
}
let mut state = group.state.lock().await;
let _permit = E2E_CONCURRENCY
.acquire()
.await
.expect("E2E concurrency semaphore should stay open");
let completed = group.completed_invocations.fetch_add(1, Ordering::Relaxed) + 1;
if completed == group.expected_invocations
&& let Some(state) = state.take()
{
state
.shutdown_bounded(false)
.await
.unwrap_or_else(|error| panic!("tear down shared E2E group after skip: {error}"));
}
true
}
/// Run a dedicated one-client E2E test.
///
/// New tests should call [`with_dedicated_e2e_context`] to make the lifecycle
/// choice visible at the call site. This name remains for existing dedicated
/// tests while they are migrated group by group.
pub async fn with_e2e_context<F>(category: &str, snapshot_name: &str, test: F)
where
F: for<'a> FnOnce(&'a mut E2eContext) -> TestFuture<'a>,
{
with_dedicated_e2e_context(category, snapshot_name, test).await;
}
/// Like [`with_dedicated_e2e_context`] but starts the CapiProxy without loading a
/// recorded snapshot. Used by the LLM inference callback tests, whose
/// registered provider fabricates every model-layer response so no CAPI
/// replay is needed — only the auth/user endpoints are served by the proxy.
pub async fn with_dedicated_e2e_context_no_snapshot<F>(test: F)
where
F: for<'a> FnOnce(&'a mut E2eContext) -> TestFuture<'a>,
{
let _permit = E2E_CONCURRENCY
.acquire()
.await
.expect("E2E concurrency semaphore should stay open");
let mut ctx = E2eContext::new_no_snapshot()
.await
.unwrap_or_else(|err| panic!("create E2E context: {err}"));
// See `with_e2e_context` for why the in-process transport mirrors env onto the
// process (restored on drop).
let _env_guard = InProcessEnvGuard::activate(&ctx);
let timed_out = tokio::time::timeout(default_test_timeout(), test(&mut ctx))
.await
.is_err();
ctx.cleanup(timed_out)
.await
.unwrap_or_else(|err| panic!("clean up E2E context: {err}"));
assert!(
!timed_out,
"timed out after {:?} running no-snapshot E2E test",
default_test_timeout()
);
}
/// Dedicated no-snapshot compatibility helper. See
/// [`with_dedicated_e2e_context_no_snapshot`].
pub async fn with_e2e_context_no_snapshot<F>(test: F)
where
F: for<'a> FnOnce(&'a mut E2eContext) -> TestFuture<'a>,
{
with_dedicated_e2e_context_no_snapshot(test).await;
}
pub struct E2eContext {
repo_root: PathBuf,
cli_path: PathBuf,
home_dir: tempfile::TempDir,
work_dir: tempfile::TempDir,
proxy: Option<CapiProxy>,
}
impl E2eContext {
async fn new(category: &str, snapshot_name: &str) -> std::io::Result<Self> {
let repo_root = repo_root();
let cli_path = cli_path(&repo_root)?;
let home_dir = tempfile::tempdir()?;
let work_dir = tempfile::tempdir()?;
let proxy_root = repo_root.clone();
let proxy = tokio::task::spawn_blocking(move || CapiProxy::start(&proxy_root))
.await
.map_err(|err| std::io::Error::other(format!("proxy startup task failed: {err}")))??;
let mut ctx = Self {
repo_root,
cli_path,
home_dir,
work_dir,
proxy: Some(proxy),
};
ctx.configure(category, snapshot_name)?;
ctx.set_default_copilot_user();
Ok(ctx)
}
async fn new_no_snapshot() -> std::io::Result<Self> {
let repo_root = repo_root();
let cli_path = cli_path(&repo_root)?;
let home_dir = tempfile::tempdir()?;
let work_dir = tempfile::tempdir()?;
let proxy_root = repo_root.clone();
let proxy = tokio::task::spawn_blocking(move || CapiProxy::start(&proxy_root))
.await
.map_err(|err| std::io::Error::other(format!("proxy startup task failed: {err}")))??;
let ctx = Self {
repo_root,
cli_path,
home_dir,
work_dir,
proxy: Some(proxy),
};
// Initialize proxy state without replaying any recorded exchanges: the
// snapshot path intentionally does not exist, so `/copilot_internal/user`
// and the default `/models` catalog are served while all model-layer
// traffic is fabricated by the registered inference callback.
let dummy_snapshot = ctx.work_dir.path().join("__no_snapshot__.yaml");
ctx.proxy()
.configure(&dummy_snapshot, ctx.work_dir.path())
.map_err(|err| {
std::io::Error::other(format!("configure proxy without snapshot failed: {err}"))
})?;
ctx.set_default_copilot_user();
Ok(ctx)
}
pub fn repo_root(&self) -> &Path {
&self.repo_root
}
pub fn work_dir(&self) -> &Path {
self.work_dir.path()
}
pub fn proxy_url(&self) -> &str {
self.proxy().url()
}
pub fn snapshot_path(&self, category: &str, snapshot_name: &str) -> PathBuf {
self.repo_root
.join("test")
.join("snapshots")
.join(category)
.join(format!("{snapshot_name}.yaml"))
}
pub fn client_options(&self) -> ClientOptions {
client_options_for_cli(&self.cli_path, self.work_dir.path(), self.environment())
}
pub fn client_options_with_transport(&self, transport: Transport) -> ClientOptions {
self.client_options().with_transport(transport)
}
pub fn client_options_with_github_token(&self, token: &str) -> ClientOptions {
self.client_options().with_github_token(token)
}
pub async fn start_client(&self) -> Client {
Client::start(self.client_options())
.await
.expect("start E2E client")
}
/// Start a client that hosts the bundled runtime directly in-process over
/// FFI ([`Transport::InProcess`]).
#[cfg_attr(not(feature = "bundled-in-process"), allow(dead_code))]
pub async fn start_inprocess_client(&self) -> Client {
let options = ClientOptions::new().with_transport(Transport::InProcess);
Client::start(options)
.await
.expect("start in-process FFI E2E client")
}
/// Start a client wired to a Copilot request handler, appending `extra_env`
/// to the spawned runtime's environment (used to flip the WebSocket ExP
/// flag for the WS transport tests).
pub async fn start_llm_client<H>(&self, handler: H, extra_env: &[(&str, &str)]) -> Client
where
H: CopilotRequestHandler,
{
let mut env = self.environment();
env.extend(
extra_env
.iter()
.map(|(key, value)| (OsString::from(*key), OsString::from(*value))),
);
let options = client_options_for_cli(&self.cli_path, self.work_dir.path(), env)
.with_request_handler(handler);
Client::start(options).await.expect("start E2E LLM client")
}
#[expect(dead_code, reason = "used by follow-on E2E ports")]
pub async fn start_tcp_client(&self, port: u16, token: &str) -> Client {
Client::start(self.client_options_with_transport(Transport::Tcp {
port,
connection_token: Some(token.to_string()),
}))
.await
.expect("start TCP E2E client")
}
pub fn approve_all_session_config(&self) -> SessionConfig {
SessionConfig::default()
.with_permission_handler(std::sync::Arc::new(ApproveAllHandler))
.with_github_token(DEFAULT_TEST_TOKEN)
}
pub fn set_default_copilot_user(&self) {
self.set_copilot_user_by_token(DEFAULT_TEST_TOKEN);
}
pub fn set_copilot_user_by_token(&self, token: &str) {
self.set_copilot_user_by_token_with_login(token, "rust-e2e-user");
}
pub fn set_copilot_user_by_token_with_login(&self, token: &str, login: &str) {
self.set_copilot_user_by_token_with_login_and_quota(token, login, None);
}
pub fn set_copilot_user_by_token_with_login_and_quota(
&self,
token: &str,
login: &str,
quota_snapshots: Option<serde_json::Value>,
) {
let mut user = json!({
"login": login,
"copilot_plan": "individual_pro",
"endpoints": {
"api": self.proxy_url(),
"telemetry": "https://localhost:1/telemetry"
},
"analytics_tracking_id": "rust-e2e-tracking-id"
});
if let Some(quota_snapshots) = quota_snapshots {
user["quota_snapshots"] = quota_snapshots;
}
self.proxy()
.set_copilot_user_by_token(token, user)
.expect("configure copilot user");
}
pub fn exchanges(&self) -> Vec<serde_json::Value> {
self.proxy()
.get_json("/exchanges")
.expect("get captured proxy exchanges")
}
pub async fn cleanup(&mut self, skip_writing_cache: bool) -> std::io::Result<()> {
if let Some(mut proxy) = self.proxy.take() {
tokio::task::spawn_blocking(move || proxy.stop(skip_writing_cache))
.await
.map_err(|err| {
std::io::Error::other(format!("proxy shutdown task failed: {err}"))
})??;
}
Ok(())
}
fn configure(&mut self, category: &str, snapshot_name: &str) -> std::io::Result<()> {
let snapshot_path = self.snapshot_path(category, snapshot_name);
self.proxy()
.configure(&snapshot_path, self.work_dir.path())
.map_err(|err| {
std::io::Error::other(format!(
"configure proxy for {} failed: {err}",
snapshot_path.display()
))
})
}
fn environment(&self) -> Vec<(OsString, OsString)> {
let mut env = self.proxy().proxy_env();
env.extend([
("COPILOT_API_URL".into(), self.proxy_url().into()),
(
"COPILOT_DEBUG_GITHUB_API_URL".into(),
self.proxy_url().into(),
),
(
"COPILOT_HOME".into(),
canonical_temp_path(self.home_dir.path())
.as_os_str()
.to_owned(),
),
(
"GH_CONFIG_DIR".into(),
canonical_temp_path(self.home_dir.path())
.as_os_str()
.to_owned(),
),
(
"XDG_CONFIG_HOME".into(),
canonical_temp_path(self.home_dir.path())
.as_os_str()
.to_owned(),
),
(
"XDG_STATE_HOME".into(),
canonical_temp_path(self.home_dir.path())
.as_os_str()
.to_owned(),
),
]);
env.extend(isolated_cache_environment(self.home_dir.path()));
env.extend([
("COPILOT_MCP_APPS".into(), "true".into()),
("MCP_APPS".into(), "true".into()),
("GH_TOKEN".into(), DEFAULT_TEST_TOKEN.into()),
("GITHUB_TOKEN".into(), DEFAULT_TEST_TOKEN.into()),
("GH_ENTERPRISE_TOKEN".into(), "".into()),
("GITHUB_ENTERPRISE_TOKEN".into(), "".into()),
("COPILOT_HMAC_KEY".into(), "".into()),
("CAPI_HMAC_KEY".into(), "".into()),
]);
env
}
fn proxy(&self) -> &CapiProxy {
self.proxy.as_ref().expect("proxy already stopped")
}
}
impl SharedE2eState {
async fn prepare_test(&mut self, category: &str, snapshot_name: &str) -> std::io::Result<()> {
self.cleanup_sessions().await?;
clear_directory_contents(self.context.work_dir()).await?;
self.context.configure(category, snapshot_name)?;
self.context.set_default_copilot_user();
Ok(())
}
async fn cleanup_after_test(&mut self) -> std::io::Result<()> {
self.cleanup_sessions().await?;
clear_directory_contents(self.context.work_dir()).await
}
async fn cleanup_sessions(&self) -> std::io::Result<()> {
self.client
.cleanup_sessions_for_test()
.await
.map_err(|err| {
std::io::Error::other(format!("clean up shared E2E sessions failed: {err}"))
})
}
async fn shutdown_bounded(mut self, skip_writing_cache: bool) -> std::io::Result<()> {
let client_result =
match tokio::time::timeout(SHARED_E2E_CLEANUP_TIMEOUT, self.client.stop()).await {
Ok(result) => result.map_err(|err| {
std::io::Error::other(format!("stop shared E2E client failed: {err}"))
}),
Err(_) => {
self.client.force_stop();
Err(std::io::Error::other(format!(
"timed out after {SHARED_E2E_CLEANUP_TIMEOUT:?} stopping shared E2E client"
)))
}
};
let proxy_result = self.context.cleanup(skip_writing_cache).await;
match (client_result, proxy_result) {
(Ok(()), Ok(())) => Ok(()),
(Err(error), Ok(())) | (Ok(()), Err(error)) => Err(error),
(Err(client_error), Err(proxy_error)) => Err(std::io::Error::other(format!(
"{client_error}; stop shared E2E proxy failed: {proxy_error}"
))),
}
}
}
fn wait_for_child_exit(child: &mut Child) -> std::io::Result<()> {
let deadline = Instant::now() + SHARED_E2E_CLEANUP_TIMEOUT;
loop {
if child.try_wait()?.is_some() {
return Ok(());
}
if Instant::now() >= deadline {
kill_and_wait_child(child);
return Err(std::io::Error::other(format!(
"timed out after {SHARED_E2E_CLEANUP_TIMEOUT:?} waiting for child process"
)));
}
std::thread::sleep(Duration::from_millis(25));
}
}
fn kill_and_wait_child(child: &mut Child) {
if let Err(error) = child.kill() {
eprintln!("failed to kill E2E child process: {error}");
}
let deadline = Instant::now() + SHARED_E2E_CLEANUP_TIMEOUT;
loop {
match child.try_wait() {
Ok(Some(_)) => return,
Ok(None) => {}
Err(error) => {
eprintln!("failed to inspect E2E child process after kill: {error}");
return;
}
}
if Instant::now() >= deadline {
eprintln!(
"timed out after {SHARED_E2E_CLEANUP_TIMEOUT:?} waiting for killed E2E child process"
);
return;
}
std::thread::sleep(Duration::from_millis(25));
}
}
fn connect_with_timeout(host: &str, port: u16) -> std::io::Result<TcpStream> {
let mut last_error = None;
for address in (host, port).to_socket_addrs()? {
match TcpStream::connect_timeout(&address, SHARED_E2E_CLEANUP_TIMEOUT) {
Ok(stream) => {
stream.set_read_timeout(Some(SHARED_E2E_CLEANUP_TIMEOUT))?;
stream.set_write_timeout(Some(SHARED_E2E_CLEANUP_TIMEOUT))?;
return Ok(stream);
}
Err(error) => last_error = Some(error),
}
}
Err(last_error.unwrap_or_else(|| {
std::io::Error::other(format!("no socket addresses resolved for {host}:{port}"))
}))
}
fn is_filtered_test_run() -> bool {
std::env::args().skip(1).any(|arg| {
!arg.starts_with('-') || matches!(arg.as_str(), "--ignored" | "--include-ignored")
})
}
async fn clear_directory_contents(directory: &Path) -> std::io::Result<()> {
for entry in std::fs::read_dir(directory)? {
let entry = entry?;
let path = entry.path();
let is_directory = entry.file_type()?.is_dir();
for attempt in 1..=20 {
let result = if is_directory {
std::fs::remove_dir_all(&path)
} else {
std::fs::remove_file(&path)
};
match result {
Ok(()) => break,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => break,
Err(error) if is_transient_windows_file_lock(&error) && attempt < 20 => {
tokio::time::sleep(Duration::from_millis(50)).await;
}
Err(error) => return Err(error),
}
}
}
Ok(())
}
fn is_transient_windows_file_lock(error: &std::io::Error) -> bool {
cfg!(windows) && matches!(error.raw_os_error(), Some(5 | 32 | 145))
}
impl Drop for E2eContext {
fn drop(&mut self) {
if let Some(mut proxy) = self.proxy.take() {
let _ = proxy.stop(true);
}
}
}
pub async fn wait_for_event<P>(
events: EventSubscription,
description: &'static str,
predicate: P,
) -> SessionEvent
where
P: Fn(&SessionEvent) -> bool,
{
wait_for_event_core(events, description, predicate, false).await
}
pub async fn wait_for_event_allowing_rate_limit<P>(
events: EventSubscription,
description: &'static str,
predicate: P,
) -> SessionEvent
where
P: Fn(&SessionEvent) -> bool,
{
wait_for_event_core(events, description, predicate, true).await
}
async fn wait_for_event_core<P>(
mut events: EventSubscription,
description: &'static str,
predicate: P,
allow_rate_limit_error: bool,
) -> SessionEvent
where
P: Fn(&SessionEvent) -> bool,
{
tokio::time::timeout(default_event_timeout(), async {
loop {
let event = events.recv().await.unwrap_or_else(|err| {
panic!("event stream closed while waiting for {description}: {err}")
});
let is_allowed_rate_limit = allow_rate_limit_error
&& event.parsed_type()
== github_copilot_sdk::session_events::SessionEventType::SessionError
&& event.data.get("errorType").and_then(|value| value.as_str())
== Some("rate_limit");
if event.parsed_type()
== github_copilot_sdk::session_events::SessionEventType::SessionError
&& !is_allowed_rate_limit
{
panic!(
"session.error while waiting for {description}: {}",
event.data
);
}
if predicate(&event) {
return event;
}
}
})
.await
.unwrap_or_else(|_| panic!("timed out waiting for {description}"))
}
pub async fn recv_with_timeout<T>(
receiver: &mut tokio::sync::mpsc::UnboundedReceiver<T>,
description: &'static str,
) -> T {
tokio::time::timeout(default_event_timeout(), receiver.recv())
.await
.unwrap_or_else(|_| panic!("timed out waiting for {description}"))
.unwrap_or_else(|| panic!("{description} channel closed"))
}
pub async fn wait_for_lifecycle_event<P>(
mut events: LifecycleSubscription,
description: &'static str,
predicate: P,
) -> SessionLifecycleEvent
where
P: Fn(&SessionLifecycleEvent) -> bool,
{
tokio::time::timeout(default_event_timeout(), async {
loop {
let event = events.recv().await.unwrap_or_else(|err| {
panic!("lifecycle stream closed while waiting for {description}: {err}")
});
if predicate(&event) {
return event;
}
}
})
.await
.unwrap_or_else(|_| panic!("timed out waiting for {description}"))
}
pub async fn wait_for_condition<F, Fut>(description: &'static str, mut predicate: F)
where
F: FnMut() -> Fut,
Fut: Future<Output = bool>,
{
let deadline = tokio::time::Instant::now() + default_event_timeout();
loop {
if predicate().await {
return;
}
assert!(
tokio::time::Instant::now() < deadline,
"timed out waiting for {description}"
);
tokio::time::sleep(Duration::from_millis(100)).await;
}
}
pub async fn collect_until_idle(mut events: EventSubscription) -> Vec<SessionEvent> {
let mut observed = Vec::new();
tokio::time::timeout(default_event_timeout(), async {
loop {
let event = events
.recv()
.await
.unwrap_or_else(|err| panic!("event stream closed while collecting events: {err}"));
let is_idle = event.parsed_type()
== github_copilot_sdk::session_events::SessionEventType::SessionIdle;
if event.parsed_type()
== github_copilot_sdk::session_events::SessionEventType::SessionError
{
panic!("session.error while collecting events: {}", event.data);
}
observed.push(event);
if is_idle {
return;
}
}
})
.await
.expect("timed out collecting events through session.idle");
observed
}
pub fn event_types(events: &[SessionEvent]) -> Vec<&str> {
events
.iter()
.map(|event| event.event_type.as_str())
.collect()
}
#[allow(dead_code, reason = "used by follow-on E2E ports")]
pub async fn wait_for_idle(session: &Session) -> SessionEvent {
wait_for_event(session.subscribe(), "session.idle event", |event| {
event.parsed_type() == github_copilot_sdk::session_events::SessionEventType::SessionIdle
})
.await
}
#[allow(dead_code, reason = "used by follow-on E2E ports")]
pub async fn wait_for_final_assistant_message(session: &Session) -> SessionEvent {
wait_for_idle(session).await;
last_assistant_message(session).await
}
#[allow(dead_code, reason = "used by follow-on E2E ports")]
pub async fn last_assistant_message(session: &Session) -> SessionEvent {
session
.get_events()
.await
.expect("get session messages")
.into_iter()
.rev()
.find(|event| {
event.parsed_type()
== github_copilot_sdk::session_events::SessionEventType::AssistantMessage
})
.expect("assistant.message event")
}
pub fn assistant_message_content(event: &SessionEvent) -> String {
event
.typed_data::<github_copilot_sdk::session_events::AssistantMessageData>()
.expect("assistant.message data")
.content
}