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 installations subclassing #584

Merged
merged 4 commits into from
Oct 31, 2024
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
40 changes: 31 additions & 9 deletions Samples/Common/Sources/LibraryBridge/InstallBridge.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import Foundation
import Combine
import SwiftUI
import KSCrashRecording
import KSCrashInstallations
import Logging

public enum BasePath: String, CaseIterable {
Expand Down Expand Up @@ -71,6 +72,7 @@ public class InstallBridge: ObservableObject {
@Published public var error: InstallationError?

@Published public var reportStore: CrashReportStore?
@Published public var installation: CrashInstallation?

public init() {
config = .init()
Expand All @@ -81,16 +83,9 @@ public class InstallBridge: ObservableObject {
.store(in: &disposables)
}

public func install() {
guard !installed else {
error = .alreadyInstalled
return
}

private func handleInstallation(_ block: () throws -> Void) {
do {
try KSCrash.shared.install(with: config)
reportStore = KSCrash.shared.reportStore
installed = true
try block()
} catch let error as KSCrashInstallError {
let message = error.localizedDescription
Self.logger.error("Failed to install KSCrash: \(message)")
Expand All @@ -102,6 +97,33 @@ public class InstallBridge: ObservableObject {
}
}

public func install() {
guard !installed else {
error = .alreadyInstalled
return
}

handleInstallation {
try KSCrash.shared.install(with: config)
reportStore = KSCrash.shared.reportStore
installed = true
}
}

public func useInstallation(_ installation: CrashInstallation) {
guard !installed else {
error = .alreadyInstalled
return
}

handleInstallation {
try installation.install(with: config)
reportStore = KSCrash.shared.reportStore
self.installation = installation
installed = true
}
}

public func setupReportsOnly() {
do {
let config = CrashReportStoreConfiguration()
Expand Down
52 changes: 52 additions & 0 deletions Samples/Common/Sources/LibraryBridge/SampleInstallation.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
//
// SampleInstallation.swift
//
// Created by Nikolay Volosatov on 2024-10-27.
//
// Copyright (c) 2012 Karl Stenerud. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall remain in place
// in this source code.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

import KSCrashInstallations
import KSCrashFilters
import Logging

public class SampleInstallation: CrashInstallation {
public enum InstallationError: String, Error {
case missingHeaderMessage
}
private static let logger = Logger(label: "SampleInstallation")

public var headerMessage: String? = "Hello!"

public override func validateSetup() throws {
if headerMessage == nil {
throw InstallationError.missingHeaderMessage
}
}

public override func sink() -> any CrashReportFilter {
Self.logger.info("Header message: \(headerMessage ?? "<undefined>")")
return CrashReportFilterPipeline(filters: [
SampleFilter(),
SampleSink(),
])
}
}
6 changes: 6 additions & 0 deletions Samples/Common/Sources/SampleUI/Screens/InstallView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,12 @@ struct InstallView: View {
}
}

Section(header: Text("Installations")) {
Button("SampleInstallation") {
bridge.useInstallation(SampleInstallation())
}
}

Button("Only set up reports") {
bridge.setupReportsOnly()
}
Expand Down
18 changes: 18 additions & 0 deletions Samples/Common/Sources/SampleUI/Screens/MainView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ struct MainView: View {

@ObservedObject var bridge: InstallBridge

@State var alertMessage: String?
@State var alertIsPresented: Bool = false

var body: some View {
List {
Section {
Expand All @@ -53,6 +56,21 @@ struct MainView: View {
} else {
Text("Reporting is not available")
}
if let installation = bridge.installation {
Button("Send reports via installation") {
installation.sendAllReports { _, error in
alertMessage = error?.localizedDescription
alertIsPresented = error != nil
}
}
}
}
.alert(isPresented: $alertIsPresented) {
Alert(
title: Text("Error"),
message: Text(alertMessage ?? ""),
dismissButton: .default(Text("OK"))
)
}
}
}
10 changes: 0 additions & 10 deletions Sources/KSCrashInstallations/KSCrashInstallation+Private.h
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,6 @@

@interface KSCrashInstallation ()

/** Initializer.
*
* @param requiredProperties Properties that MUST be set when sending reports.
*/
- (id)initWithRequiredProperties:(NSArray *)requiredProperties;

/** Set the key to be used for the specified report property.
*
* @param propertyName The name of the property.
Expand All @@ -73,10 +67,6 @@
*/
- (void)reportFieldForProperty:(NSString *)propertyName setValue:(id)value;

/** Create a new sink. Subclasses must implement this.
*/
- (id<KSCrashReportFilter>)sink;

/** Make an absolute key path if the specified path is not already absolute. */
- (NSString *)makeKeyPath:(NSString *)keyPath;

Expand Down
43 changes: 6 additions & 37 deletions Sources/KSCrashInstallations/KSCrashInstallation.m
Original file line number Diff line number Diff line change
Expand Up @@ -129,21 +129,13 @@ @interface KSCrashInstallation ()
@property(nonatomic, readonly, assign) CrashHandlerData *crashHandlerData;
@property(nonatomic, readwrite, strong) NSMutableData *crashHandlerDataBacking;
@property(nonatomic, readwrite, strong) NSMutableDictionary *fields;
@property(nonatomic, readwrite, copy) NSArray *requiredProperties;
@property(nonatomic, readwrite, strong) KSCrashReportFilterPipeline *prependedFilters;

@end

@implementation KSCrashInstallation

- (id)init
{
[NSException raise:NSInternalInconsistencyException
format:@"%@ does not support init. Subclasses must call initWithRequiredProperties:", [self class]];
return nil;
}

- (id)initWithRequiredProperties:(NSArray *)requiredProperties
- (instancetype)init
{
if ((self = [super init])) {
_isDemangleEnabled = YES;
Expand All @@ -152,7 +144,6 @@ - (id)initWithRequiredProperties:(NSArray *)requiredProperties
[NSMutableData dataWithLength:sizeof(*self.crashHandlerData) +
sizeof(*self.crashHandlerData->reportFields) * kMaxProperties];
_fields = [NSMutableDictionary dictionary];
_requiredProperties = [requiredProperties copy];
_prependedFilters = [KSCrashReportFilterPipeline new];
}
return self;
Expand Down Expand Up @@ -200,32 +191,10 @@ - (void)reportFieldForProperty:(NSString *)propertyName setValue:(id)value
field.value = value;
}

- (NSError *)validateProperties
- (BOOL)validateSetupWithError:(NSError **)error
{
NSMutableString *errors = [NSMutableString string];
for (NSString *propertyName in self.requiredProperties) {
NSString *nextError = nil;
@try {
id value = [self valueForKey:propertyName];
if (value == nil) {
nextError = @"is nil";
}
} @catch (NSException *exception) {
nextError = @"property not found";
}
if (nextError != nil) {
if ([errors length] > 0) {
[errors appendString:@", "];
}
[errors appendFormat:@"%@ (%@)", propertyName, nextError];
}
}
if ([errors length] > 0) {
return [KSNSErrorHelper errorWithDomain:[[self class] description]
code:0
description:@"Installation properties failed validation: %@", errors];
}
return nil;
// In the base class there is no properties to validate.
return YES;
}

- (NSString *)makeKeyPath:(NSString *)keyPath
Expand Down Expand Up @@ -298,8 +267,8 @@ - (BOOL)installWithConfiguration:(KSCrashConfiguration *)configuration error:(NS

- (void)sendAllReportsWithCompletion:(KSCrashReportFilterCompletion)onCompletion
{
NSError *error = [self validateProperties];
if (error != nil) {
NSError *error = nil;
if ([self validateSetupWithError:&error] == NO) {
if (onCompletion != nil) {
onCompletion(nil, error);
}
Expand Down
4 changes: 2 additions & 2 deletions Sources/KSCrashInstallations/KSCrashInstallationConsole.m
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,9 @@ + (instancetype)sharedInstance
return sharedInstance;
}

- (id)init
- (instancetype)init
{
if ((self = [super initWithRequiredProperties:nil])) {
if ((self = [super init])) {
_printAppleFormat = NO;
}
return self;
Expand Down
42 changes: 39 additions & 3 deletions Sources/KSCrashInstallations/KSCrashInstallationEmail.m
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
#import "KSCrashInstallation+Private.h"
#import "KSCrashReportFilterAlert.h"
#import "KSCrashReportSinkEMail.h"
#import "KSNSErrorHelper.h"

@interface KSCrashInstallationEmail ()

Expand All @@ -48,10 +49,9 @@ + (instancetype)sharedInstance
return sharedInstance;
}

- (id)init
- (instancetype)init
{
if ((self = [super
initWithRequiredProperties:[NSArray arrayWithObjects:@"recipients", @"subject", @"filenameFmt", nil]])) {
if ((self = [super init])) {
NSString *bundleName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
_subject = [NSString stringWithFormat:@"Crash Report (%@)", bundleName];
_defaultFilenameFormats = [NSDictionary
Expand All @@ -64,6 +64,42 @@ - (id)init
return self;
}

- (BOOL)validateSetupWithError:(NSError **)error
{
if ([super validateSetupWithError:error] == NO) {
return NO;
}

if (self.recipients.count == 0) {
if (error != NULL) {
*error = [KSNSErrorHelper errorWithDomain:[[self class] description]
code:0
description:@"Empty recepients array"];
}
return NO;
}

if (self.subject.length == 0) {
if (error != NULL) {
*error = [KSNSErrorHelper errorWithDomain:[[self class] description]
code:0
description:@"No email subject provided"];
}
return NO;
}

if (self.filenameFmt.length == 0) {
if (error != NULL) {
*error = [KSNSErrorHelper errorWithDomain:[[self class] description]
code:0
description:@"No filename format provided"];
}
return NO;
}

return YES;
}

- (void)setReportStyle:(KSCrashEmailReportStyle)reportStyle useDefaultFilenameFormat:(BOOL)useDefaultFilenameFormat
{
self.reportStyle = reportStyle;
Expand Down
16 changes: 14 additions & 2 deletions Sources/KSCrashInstallations/KSCrashInstallationStandard.m
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
#import "KSCrashInstallation+Private.h"
#import "KSCrashReportFilterBasic.h"
#import "KSCrashReportSinkStandard.h"
#import "KSNSErrorHelper.h"

@implementation KSCrashInstallationStandard

Expand All @@ -42,9 +43,20 @@ + (instancetype)sharedInstance
return sharedInstance;
}

- (id)init
- (BOOL)validateSetupWithError:(NSError *__autoreleasing _Nullable *)error
{
return [super initWithRequiredProperties:[NSArray arrayWithObjects:@"url", nil]];
if ([super validateSetupWithError:error] == NO) {
return NO;
}

if (self.url == nil) {
if (error != NULL) {
*error = [KSNSErrorHelper errorWithDomain:[[self class] description] code:0 description:@"No URL provided"];
}
return NO;
}

return YES;
}

- (id<KSCrashReportFilter>)sink
Expand Down
Loading
Loading