Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: alice_chopper interceptor #185

Merged
merged 3 commits into from
Jun 7, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
143 changes: 51 additions & 92 deletions packages/alice_chopper/lib/alice_chopper_response_interceptor.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import 'dart:async';
import 'dart:convert';
import 'dart:async' show FutureOr;
import 'dart:convert' show utf8;
import 'dart:io' show HttpHeaders;

import 'package:alice/core/alice_adapter.dart';
import 'package:alice/core/alice_utils.dart';
Expand All @@ -12,127 +13,85 @@ import 'package:http/http.dart' as http;
class AliceChopperAdapter with AliceAdapter implements Interceptor {
/// Creates hashcode based on request
int getRequestHashCode(http.BaseRequest baseRequest) {
var hashCodeSum = 0;
hashCodeSum += baseRequest.url.hashCode;
hashCodeSum += baseRequest.method.hashCode;
if (baseRequest.headers.isNotEmpty) {
baseRequest.headers.forEach((key, value) {
hashCodeSum += key.hashCode;
hashCodeSum += value.hashCode;
});
}
if (baseRequest.contentLength != null) {
hashCodeSum += baseRequest.contentLength.hashCode;
}
final int hashCodeSum = baseRequest.url.hashCode +
baseRequest.method.hashCode +
(baseRequest.headers.entries
.map((MapEntry<String, String> header) =>
header.key.hashCode + header.value.hashCode)
.reduce((int value, int hashCode) => value + hashCode)) +
(baseRequest.contentLength?.hashCode ?? 0);

return hashCodeSum.hashCode;
}

/// Handles chopper request and creates alice http call
Future<Request> interceptRequest(Request request) async {
try {
final headers = request.headers;
headers['alice_token'] = DateTime.now().millisecondsSinceEpoch.toString();
final changedRequest = request.copyWith(headers: headers);
final baseRequest = await changedRequest.toBaseRequest();

final call = AliceHttpCall(getRequestHashCode(baseRequest));
var endpoint = '';
var server = '';

final split = request.url.toString().split('/');
if (split.length > 2) {
server = split[1] + split[2];
}
if (split.length > 4) {
endpoint = '/';
for (var splitIndex = 3; splitIndex < split.length; splitIndex++) {
// ignore: use_string_buffers
endpoint += '${split[splitIndex]}/';
}
endpoint = endpoint.substring(0, endpoint.length - 1);
}
@override
FutureOr<Response<BodyType>> intercept<BodyType>(
Chain<BodyType> chain,
) async {
final Response<BodyType> response = await chain.proceed(chain.request);

call
..method = request.method
..endpoint = endpoint
..server = server
try {
final AliceHttpCall call = AliceHttpCall(
getRequestHashCode(
applyHeader(
chain.request,
'alice_token',
DateTime.now().millisecondsSinceEpoch.toString(),
),
),
)
..method = chain.request.method
..endpoint =
chain.request.url.path.isEmpty ? '/' : chain.request.url.path
..server = chain.request.url.host
..secure = chain.request.url.scheme == 'https'
..uri = chain.request.url.toString()
..client = 'Chopper';
if (request.url.toString().contains('https')) {
call.secure = true;
}

final aliceHttpRequest = AliceHttpRequest();
final AliceHttpRequest aliceHttpRequest = AliceHttpRequest();

if (request.body == null) {
if (chain.request.body == null) {
aliceHttpRequest
..size = 0
..body = '';
} else {
aliceHttpRequest
..size = utf8.encode(request.body as String).length
..body = request.body;
..size = utf8.encode(chain.request.body as String).length
..body = chain.request.body;
}
aliceHttpRequest
..time = DateTime.now()
..headers = request.headers;
..headers = chain.request.headers;

String? contentType = 'unknown';
if (request.headers.containsKey('Content-Type')) {
contentType = request.headers['Content-Type'];
if (chain.request.headers.containsKey(HttpHeaders.contentTypeHeader)) {
contentType = chain.request.headers[HttpHeaders.contentTypeHeader];
}
aliceHttpRequest
..contentType = contentType
..queryParameters = request.parameters;
..queryParameters = chain.request.parameters;

call
..request = aliceHttpRequest
..response = AliceHttpResponse();
..response = (AliceHttpResponse()
..status = response.statusCode
..body = response.body ?? ''
..size = response.body != null
? utf8.encode(response.body.toString()).length
: 0
..time = DateTime.now()
..headers = <String, String>{
for (final MapEntry<String, String> entry
in response.headers.entries)
entry.key: entry.value
});

aliceCore.addCall(call);
return changedRequest;
} catch (exception) {
AliceUtils.log(exception.toString());
return request;
}
}

/// Handles chopper response and adds data to existing alice http call
@override
// ignore: strict_raw_type
void interceptResponse(Response response) {
final httpResponse = AliceHttpResponse()..status = response.statusCode;
if (response.body == null) {
httpResponse
..body = ''
..size = 0;
} else {
httpResponse
..body = response.body
..size = utf8.encode(response.body.toString()).length;
}

httpResponse.time = DateTime.now();
final headers = <String, String>{};
response.headers.forEach((header, values) {
headers[header] = values;
});
httpResponse.headers = headers;

if (response.base.request != null) {
aliceCore.addResponse(
httpResponse,
getRequestHashCode(response.base.request!),
);
}
}

@override
FutureOr<Response<BodyType>> intercept<BodyType>(
Chain<BodyType> chain) async {
final request = await interceptRequest(chain.request);
final response = await chain.proceed(request);
interceptResponse(response);
return response;
}
}