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

Parse Event for OnSend Callbacks #1517

Merged
merged 5 commits into from
Nov 22, 2021
Merged
Show file tree
Hide file tree
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
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ public class Breadcrumb implements JsonStream.Streamable {
final BreadcrumbInternal impl;
private final Logger logger;

Breadcrumb(@NonNull BreadcrumbInternal impl, @NonNull Logger logger) {
this.impl = impl;
this.logger = logger;
}

Breadcrumb(@NonNull String message, @NonNull Logger logger) {
this.impl = new BreadcrumbInternal(message);
this.logger = logger;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,92 @@ internal class BugsnagEventMapper(
private val logger: Logger
) {

@Suppress("UNCHECKED_CAST")
internal fun convertToEventImpl(map: Map<in String, Any?>, apiKey: String): EventInternal {
val event = EventInternal(apiKey)

// populate exceptions. check this early to avoid unnecessary serialization if
// no stacktrace was gathered.
val exceptions = map["exceptions"] as? List<MutableMap<String, Any?>>
exceptions?.mapTo(event.errors) { Error(convertErrorInternal(it), this.logger) }

// populate user
event.userImpl = convertUser(map.readEntry("user"))

// populate metadata
val metadataMap: Map<String, Map<String, Any?>> = map.readEntry("metaData")
metadataMap.forEach { (key, value) ->
event.addMetadata(key, value)
}

// populate breadcrumbs
val breadcrumbList: List<MutableMap<String, Any?>> = map.readEntry("breadcrumbs")
breadcrumbList.mapTo(event.breadcrumbs) {
Breadcrumb(
convertBreadcrumbInternal(it),
logger
)
}

// populate context
event.context = map["context"] as? String

// populate groupingHash
event.groupingHash = map["groupingHash"] as? String

// populate app
event.app = convertAppWithState(map.readEntry("app"))

// populate device
event.device = convertDeviceWithState(map.readEntry("device"))

// populate session
val sessionMap = map["session"] as? Map<String, Any?>
sessionMap?.let {
event.session = Session(it, logger)
}

// populate threads
val threads = map["threads"] as? List<Map<String, Any?>>
threads?.mapTo(event.threads) { Thread(convertThread(it), logger) }

// populate projectPackages
val projectPackages = map["projectPackages"] as? List<String>
projectPackages?.let {
event.projectPackages = projectPackages
}

// populate severity
val severityStr: String = map.readEntry("severity")
val severity = Severity.fromDescriptor(severityStr)
val unhandled: Boolean = map.readEntry("unhandled")
val reason = deserializeSeverityReason(map, unhandled, severity)
event.updateSeverityReasonInternal(reason)
event.normalizeStackframeErrorTypes()

return event
}

internal fun convertErrorInternal(error: Map<String, Any?>): ErrorInternal {
return ErrorInternal(
error.readEntry("errorClass"),
error["message"] as? String,
type = error.readEntry<String>("type").let { type ->
ErrorType.fromDescriptor(type)
?: throw IllegalArgumentException("unknown ErrorType: '$type'")
},
stacktrace = convertStacktrace(error.readEntry("stacktrace"))
)
}

internal fun convertUser(user: Map<String, Any?>): User {
return User(
user["id"] as? String,
user["email"] as? String,
user["name"] as? String
)
}

@Suppress("UNCHECKED_CAST")
internal fun convertBreadcrumbInternal(breadcrumb: Map<String, Any?>): BreadcrumbInternal {
return BreadcrumbInternal(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.bugsnag.android;

import com.bugsnag.android.internal.ImmutableConfig;
import com.bugsnag.android.internal.MarshalledEventSource;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
Expand Down Expand Up @@ -204,7 +203,7 @@ private void deliverEventPayload(File eventFile, EventPayload payload) {

@Nullable
private EventPayload createEventPayload(File eventFile, String apiKey) {
MarshalledEventSource eventSource = new MarshalledEventSource(eventFile);
MarshalledEventSource eventSource = new MarshalledEventSource(eventFile, apiKey, logger);

try {
if (!callbackState.runOnSendTasks(eventSource, logger)) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
package com.bugsnag.android.internal
package com.bugsnag.android

import com.bugsnag.android.Event
import com.bugsnag.android.internal.JsonHelper
import java.io.File

internal class MarshalledEventSource(private val eventFile: File) : () -> Event {
internal class MarshalledEventSource(
private val eventFile: File,
private val apiKey: String,
private val logger: Logger
) : () -> Event {

/**
* The parsed and possibly processed event. This field remains `null` if the `EventSource`
Expand All @@ -27,8 +31,12 @@ internal class MarshalledEventSource(private val eventFile: File) : () -> Event
event = null
}

@Suppress("StopShip")
private fun unmarshall(): Event {
TODO("Not yet implemented")
val eventMapper = BugsnagEventMapper(logger)
val jsonMap = JsonHelper.deserialize(eventFile)
return Event(
eventMapper.convertToEventImpl(jsonMap, apiKey),
logger
)
}
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
package com.bugsnag.android;

import com.bugsnag.android.internal.DateUtils;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

Expand Down Expand Up @@ -40,6 +43,23 @@ static Session copySession(Session session) {
return copy;
}

Session(Map<String, Object> map, Logger logger) {
this(null, null, logger);
setId((String) map.get("id"));

String timestamp = (String) map.get("startedAt");
setStartedAt(DateUtils.fromIso8601(timestamp));

@SuppressWarnings("unchecked")
Map<String, Object> events = (Map<String, Object>) map.get("events");

Number handled = (Number) events.get("handled");
handledCount.set(handled.intValue());

Number unhandled = (Number) events.get("unhandled");
unhandledCount.set(unhandled.intValue());
}

Session(String id, Date startedAt, User user, boolean autoCaptured,
Notifier notifier, Logger logger) {
this(null, notifier, logger);
Expand All @@ -60,9 +80,14 @@ static Session copySession(Session session) {
Session(File file, Notifier notifier, Logger logger) {
this.file = file;
this.logger = logger;
Notifier copy = new Notifier(notifier.getName(), notifier.getVersion(), notifier.getUrl());
copy.setDependencies(new ArrayList<>(notifier.getDependencies()));
this.notifier = copy;
if (notifier != null) {
Notifier copy = new Notifier(notifier.getName(),
notifier.getVersion(), notifier.getUrl());
copy.setDependencies(new ArrayList<>(notifier.getDependencies()));
this.notifier = copy;
} else {
this.notifier = null;
}
}

private void logNull(String property) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,8 @@ enum class Severity(private val str: String) : JsonStream.Streamable {
override fun toStream(writer: JsonStream) {
writer.value(str)
}

internal companion object {
internal fun fromDescriptor(desc: String) = values().find { it.str == desc }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ public class Thread implements JsonStream.Streamable {
this.logger = logger;
}

Thread(@NonNull ThreadInternal impl, @NonNull Logger logger) {
this.impl = impl;
this.logger = logger;
}

private void logNull(String property) {
logger.e("Invalid null value supplied to thread." + property + ", ignoring");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,21 +40,38 @@ internal class EventSerializationTest {
createEvent {
val stacktrace = Stacktrace(arrayOf(), emptySet(), NoopLogger)
it.threads.clear()
it.threads.add(Thread(5, "main", ThreadType.ANDROID, true, Thread.State.RUNNABLE, stacktrace, NoopLogger))
it.threads.add(
Thread(
5,
"main",
ThreadType.ANDROID,
true,
Thread.State.RUNNABLE,
stacktrace,
NoopLogger
)
)
},

// threads included
createEvent {
it.addMetadata("app", "foo", 55)
it.addMetadata("device", "bar", true)
it.addMetadata("wham", "some_key", "A value")
it.addMetadata("wham", "some_key", "Avalue")
it.setUser(null, null, "Jamie")

val crumb = Breadcrumb("hello world", BreadcrumbType.MANUAL, mutableMapOf(), Date(0), NoopLogger)
val crumb = Breadcrumb(
"helloworld",
BreadcrumbType.MANUAL,
mutableMapOf(),
Date(0),
NoopLogger
)
it.breadcrumbs = listOf(crumb)

val stacktrace = Stacktrace(arrayOf(), emptySet(), NoopLogger)
val err = Error(ErrorInternal("WhoopsException", "Whoops", stacktrace), NoopLogger)
val err =
Error(ErrorInternal("WhoopsException", "Whoops", stacktrace), NoopLogger)
it.errors.clear()
it.errors.add(err)
}
Expand All @@ -80,6 +97,18 @@ internal class EventSerializationTest {
@Parameter
lateinit var testCase: Pair<Event, String>

private val eventMapper = BugsnagEventMapper(NoopLogger)

@Test
fun testJsonSerialisation() = verifyJsonMatches(testCase.first, testCase.second)

@Test
fun testJsonDeserializion() {
verifyJsonParser(testCase.first, testCase.second) {
Event(
eventMapper.convertToEventImpl(it, "5d1ec5bd39a74caa1267142706a7fb21"),
NoopLogger
)
}
}
}