Skip to content
This repository was archived by the owner on Aug 25, 2023. It is now read-only.

Fix for #22: Only write to cache for an HTTP 200, sweep empty png files. - #23

Merged
incanus merged 1 commit into
masterfrom
unknown repository
Feb 25, 2014
Merged

incanus merged 1 commit into
masterfrom
unknown repository

Conversation

@ghost

@ghost ghost commented Jan 22, 2014

Copy link
Copy Markdown

This addresses issue #22 where empty PNG files were getting written to cache for tiles which failed to load while the app was running in airplane mode. There are two parts to the change:

  1. For tiles that aren't in the cache, loadTileAtPath:result: now takes a closer look at the type of response generated by the tile request. Anything other than an HTTP 200 is treated as an error (i.e. don't write file to cache, call result(data,error) with nil data and an NSError describing the problem).
  2. sweepCache now deletes any cached images which have a size of 0 bytes. For devices with an existing cache folder, this should clean up any debris which may have been created by the old loadTileAtPath:result: code.

@ghost

ghost commented Feb 17, 2014

Copy link
Copy Markdown
Author

I'm gonna close this for now as I've incorporated it into a new branch over at #38.

@ghost ghost closed this Feb 17, 2014
@incanus incanus added this to the 0.2.0 milestone Feb 21, 2014
@incanus incanus reopened this Feb 21, 2014
incanus added a commit that referenced this pull request Feb 21, 2014
 * define constant error domain
 * cleanup some comments
 * avoid early return
 * valid HTTP responses should already check for status 200
@incanus

incanus commented Feb 21, 2014

Copy link
Copy Markdown
Contributor

I made some changes in the above commit f7c3b73 and associated branch 23-cache-fixes that I'd like to talk over with you @wsnook.

  • If we're going to use a custom NSError domain, we ought to make it a constant string. For now, with one error code (see next point), we probably don't have to worry about defining that.
  • I love the check for a valid NSHTTPURLResponse as a hedge against airplane mode or other weirdness. However, in the case of a non-200 response, isn't the completion block error argument going to exist anyway? Why not just pass that through? Also, related to that, I tried to avoid an early return inside of a conditional.
  • Some minor stuff around comments. I like to punctuate properly in this project, and I generally like to avoid specific issue mentions in comments as you can always retrace these steps with git blame if you like. It just keeps comments to what the code is about now, not any past baggage associated with it.

Thoughts?

@ghost

ghost commented Feb 21, 2014

Copy link
Copy Markdown
Author

Hmm... be careful with that. Looking at your commit, I don't think that's gonna work. I tested that stuff pretty thoroughly to account for a number of edge cases (see comments). For instance, have you tested what your modified code does if the response is an HTTP 404 or a 500?

If we're going to use a custom NSError domain, we ought to make it a constant string.

The critical thing is that result(nil, error) must get invoked in order for the MKTileOverlayRenderer and MKMapView to respond appropriately. Exactly how that NSError gets initialized doesn't matter much to me. None of the existing NSError domains seemed applicable, and [NSError + errorWithDomain:code:userInfo:] requires you to pass in something, so I just made stuff up. If you've got some convention you'd like to use there, that's great.

However, in the case of a non-200 response, isn't the completion block error argument going to exist anyway? Why not just pass that through?

Maybe I'm confused, but I'm pretty sure it doesn't work like that. If the HTTP request completes in any fashion, you get an NSHTTPURLResponse, and you have to check the statusCode and make your own decisions about which ones are acceptable. My intent with if ([((NSHTTPURLResponse *)response) statusCode] != 200) was to make sure that the only thing which gets written to cache, in the case when the HTTP request completes, is a PNG or JSON file that came from an HTTP 200. In airplane mode, the HTTP request doesn't complete at all, so instead of an NSHTTPURLResponse, you get a NSHTTPURLResponse [edit: a different kind of NSURLResponse]. I'm cool if you want to change stuff around, but it will need to go through another round of careful testing. That particular section of code is definitely on the critical and fragile side.

Some minor stuff around comments...

I tried to mimic your style as best I could. Please edit away and I'll keep your changes in mind for later.

@incanus

incanus commented Feb 21, 2014

Copy link
Copy Markdown
Contributor

Cool, not doubting your original code, just discussing via alternate code. I will do some poking then on my stuff.

@ghost

ghost commented Feb 21, 2014

Copy link
Copy Markdown
Author

Cool. Also, in case you didn't notice my edit above about NSHTTPURLResponse vs. NSURLResponse, I made a kinda significant copy and paste mistake in my original comment.

@ghost

ghost commented Feb 21, 2014

Copy link
Copy Markdown
Author

You got me wondering about all this...

I made a little test app to explore the permutations of data, response, and error. Here's the view controller with - (IBAction)actionDoDownload:(id)sender getting invoked by a button in the storyboard.

#import "ViewController.h"

@interface ViewController ()
@property (nonatomic) NSURLSession *dataSession;
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
    _dataSession = [NSURLSession sessionWithConfiguration:sessionConfiguration];
}


- (void)makeRequestForURL:(NSURL *)url
{
    [[_dataSession dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
    {
        if([response isKindOfClass:[NSHTTPURLResponse class]]) {
            long status = [((NSHTTPURLResponse *)response) statusCode];
            NSString *dataStr = data!=nil ? [NSString stringWithFormat:@"%ld bytes",[data length]] : @"nil";
            NSLog(@"\n== HTTP %ld: ==\n data: %@\n status: %@\n error: %@", status, dataStr, [response class], error);

        } else {
            NSString *dataStr = data!=nil ? [NSString stringWithFormat:@"%ld bytes",[data length]] : @"nil";
            NSLog(@"\n== non-HTTP response ==\n data: %@\n response: %@\n error:%@", dataStr, response, error);
        }
    }] resume];
}


- (IBAction)actionDoDownload:(id)sender {
    NSURL *url200 = [NSURL URLWithString:@"http://mapbox.com"];
    NSURL *url403 = [NSURL URLWithString:@"http://mapbox.com/i-do-not-exist-234lkj23l4j"];

    // Demonstrate a 200...
    [self makeRequestForURL:url200];

    // Demonstrate an HTTP 403 with data containing HTML content which claims to be a 404...
    [self makeRequestForURL:url403];
}

@end

Running that with a network connection yields this log:

2014-02-20 22:19:04.517 urlTest[3693:3707] 
== HTTP 200: ==
 data: 23293 bytes
 status: NSHTTPURLResponse
 error: (null)
2014-02-20 22:19:04.755 urlTest[3693:460b] 
== HTTP 403: ==
 data: 6997 bytes
 status: NSHTTPURLResponse
 error: (null)

... and running it in airplane mode does this:

2014-02-20 22:25:08.326 urlTest[3705:3707] 
== non-HTTP response ==
 data: 0 bytes
 response: (null)
 error:Error Domain=NSURLErrorDomain Code=-1009 "The Internet connection appears to be offline." UserInfo=0x1700e3380 {NSUnderlyingError=0x17004c990 "The Internet connection appears to be offline.", NSErrorFailingURLStringKey=http://mapbox.com/i-do-not-exist-234lkj23l4j, NSErrorFailingURLKey=http://mapbox.com/i-do-not-exist-234lkj23l4j, NSLocalizedDescription=The Internet connection appears to be offline.}
2014-02-20 22:25:08.333 urlTest[3705:460b] 
== non-HTTP response ==
 data: 0 bytes
 response: (null)
 error:Error Domain=NSURLErrorDomain Code=-1009 "The Internet connection appears to be offline." UserInfo=0x1780e4700 {NSUnderlyingError=0x178052360 "The Internet connection appears to be offline.", NSErrorFailingURLStringKey=http://mapbox.com, NSErrorFailingURLKey=http://mapbox.com, NSLocalizedDescription=The Internet connection appears to be offline.}

That summarizes to...

what happened data response error
HTTP 200 23293 bytes NSHTTPURLResponse (null)
HTTP 403 6997 bytes NSHTTPURLResponse (null)
Airplane mode 0 bytes (null) "The Internet connection appears to be offline"

@ghost

ghost commented Feb 21, 2014

Copy link
Copy Markdown
Author

To me that looks like your intuition about something being redundant was correct, but it was actually the airplane mode stuff which was the problem.

Now I'm of the opinion that the logic should flow like this:

if (error != nil)
{
  // This covers airplane mode
  result(nil, error);
}
else if (statusCode != 200)
{
  // Initialize an appropriate NSError indicating we got a 404 or whatever
  NSError *customError = ...
  result(nil, customError);
}
else
{
  // Okay, now we should have a valid image, so write it to cache, etc
  ...
  result(data, nil);
}

@incanus

incanus commented Feb 21, 2014

Copy link
Copy Markdown
Contributor

If, in airplane mode, the data was coming up empty and an error was registering, then how would it have been getting cached to disk? The current release would have skipped over it.

@incanus

incanus commented Feb 21, 2014

Copy link
Copy Markdown
Contributor

Ah, I think I see. Need to test, but I think airplane mode gives a zero length but otherwise valid data.

@ghost

ghost commented Feb 21, 2014

Copy link
Copy Markdown
Author

Correct. For anything that I've tested in this context, data == nil always comes up false. So asking if (data) in loadTileAtPath:result doesn't yield any meaningful answers. See

if (data)

@incanus

incanus commented Feb 24, 2014

Copy link
Copy Markdown
Contributor

Cool. I am going to rework my branch a bit based on these tests, then post back about it here and we can discuss some more, then merge.

@incanus

incanus commented Feb 24, 2014

Copy link
Copy Markdown
Contributor

For anything that I've tested in this context, data == nil always comes up false.

I think I was misremembering something here related instead to old NSURLConnection behavior. From -[NSURLConnection sendAsynchronousRequest:queue:completionHandler:]:

If the request completes successfully, the data parameter of the handler block contains the resource data, and the error parameter is nil. If the request fails, the data parameter is nil and the error parameter contain information about the failure.

@incanus

incanus commented Feb 24, 2014

Copy link
Copy Markdown
Contributor

I just pushed b28f574 to my branch, which incorporates what we've talked about around the three conditions.

On the NSError front, I'm either passing the NSURLSession error, creating a new object with our custom domain and -1 for the code, or of course not returning an error. For the localized reason stuff, I just used the NSHTTPURLResponse class method designed for that purpose.

Could you give the branch a swing @wsnook and let me know what you think?

@ghost

ghost commented Feb 25, 2014

Copy link
Copy Markdown
Author

Could you give the branch a swing @wsnook and let me know what you think?

Reading through that, it looks good. I haven't tried compiling or testing it though. There's one issue with casting b28f574#commitcomment-5477699 which could be handled by returning another custom NSError if response somehow turns up as not nil and also not an NSHTTPURLResponse. However, I'm fine with the idea of ignoring that that edge case for now. Getting this stuff in place as-is ought to be a big improvement over the existing state of things.

If you want me to test your branch, I can do that, but my inclination would be to just merge this, then do some thorough testing across the board once you're finished merging, then patch as needed to get it into shape for a release.

@incanus

incanus commented Feb 25, 2014

Copy link
Copy Markdown
Contributor

If you want me to test your branch, I can do that, but my inclination would be to just merge this, then do some thorough testing across the board once you're finished merging, then patch as needed to get it into shape for a release.

Agree here 👍 I will get this guy merged this morning.

@incanus
incanus merged commit af8a45f into mapbox:master Feb 25, 2014
@incanus

incanus commented Feb 25, 2014

Copy link
Copy Markdown
Contributor

4b7ee29 also fixes the edge case you mention above about non-HTTP responses.

@ghost
ghost deleted the issue22 branch February 26, 2014 01:58
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants