1
1
import 'dart:async' ;
2
2
import 'dart:convert' as convert;
3
3
import 'dart:io' ;
4
+ import 'dart:math' ;
4
5
5
6
import 'package:http/http.dart' show ByteStream;
6
7
import 'package:shelf/shelf.dart' ;
7
8
import 'package:shelf/shelf_io.dart' as shelf_io;
8
9
import 'package:shelf_router/shelf_router.dart' ;
9
10
10
- Future <HttpServer > createServer () async {
11
- var app = Router ();
11
+ class TestServer {
12
+ late HttpServer server;
13
+ Router app = Router ();
14
+ int connectionCount = 0 ;
15
+ int maxConnectionCount = 0 ;
16
+ int tokenExpiresIn;
12
17
13
- app.post ('/sync/stream' , handleSyncStream);
14
- // Open on an arbitrary open port
15
- var server = await shelf_io.serve (app.call, 'localhost' , 0 );
18
+ TestServer ({this .tokenExpiresIn = 65 });
19
+
20
+ Future <void > init () async {
21
+ app.post ('/sync/stream' , handleSyncStream);
22
+ // Open on an arbitrary open port
23
+ server = await shelf_io.serve (app.call, 'localhost' , 0 );
24
+ }
25
+
26
+ String get endpoint {
27
+ return 'http://${server .address .host }:${server .port }' ;
28
+ }
29
+
30
+ Future <Response > handleSyncStream (Request request) async {
31
+ connectionCount += 1 ;
32
+ maxConnectionCount = max (connectionCount, maxConnectionCount);
33
+
34
+ stream () async * {
35
+ try {
36
+ var blob = "*" * 5000 ;
37
+ for (var i = 0 ; i < 50 ; i++ ) {
38
+ yield {"token_expires_in" : tokenExpiresIn, "blob" : blob};
39
+ await Future .delayed (Duration (microseconds: 1 ));
40
+ }
41
+ } finally {
42
+ connectionCount -= 1 ;
43
+ }
44
+ }
45
+
46
+ return Response .ok (
47
+ encodeNdjson (stream ()),
48
+ headers: {
49
+ 'Content-Type' : 'application/x-ndjson' ,
50
+ },
51
+ context: {
52
+ 'shelf.io.buffer_output' : false ,
53
+ },
54
+ );
55
+ }
56
+
57
+ void close () {
58
+ server.close (force: true ).ignore ();
59
+ }
60
+ }
61
+
62
+ Future <TestServer > createServer () async {
63
+ var server = TestServer ();
64
+ await server.init ();
16
65
return server;
17
66
}
18
67
@@ -22,23 +71,3 @@ ByteStream encodeNdjson(Stream<Object> jsonInput) {
22
71
final byteInput = stringInput.transform (convert.utf8.encoder);
23
72
return ByteStream (byteInput);
24
73
}
25
-
26
- Future <Response > handleSyncStream (Request request) async {
27
- stream () async * {
28
- var blob = "*" * 5000 ;
29
- for (var i = 0 ; i < 50 ; i++ ) {
30
- yield {"token_expires_in" : 5 , "blob" : blob};
31
- await Future .delayed (Duration (microseconds: 1 ));
32
- }
33
- }
34
-
35
- return Response .ok (
36
- encodeNdjson (stream ()),
37
- headers: {
38
- 'Content-Type' : 'application/x-ndjson' ,
39
- },
40
- context: {
41
- 'shelf.io.buffer_output' : false ,
42
- },
43
- );
44
- }
0 commit comments