~reedobrien/charmworld/027test-fails

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
__metaclass__ = type

from datetime import (
    datetime,
    timedelta,
)
from email.utils import parseaddr
from inspect import getargspec
from os.path import (
    join,
)
import re
from urllib import unquote

from gridfs.errors import NoFile
import pymongo
from pyramid.httpexceptions import (
    HTTPFound,
    HTTPNotFound,
)
from pyramid.view import view_config
from webob import Response


from charmworld.models import (
    Bundle,
    BundledCharmDescription,
    Charm,
    CharmFileSet,
    DatedMetricSource,
    FeaturedSource,
    getfs,
    QADataSource,
    resolve_charm_from_description,
)
from charmworld.search import (
    BUNDLE,
    CHARM,
    InvalidCharmType,
    NegativeLimit,
)
from charmworld.utils import (
    build_metric_key,
    quote_key,
    timestamp,
)
from charmworld.views.api.proof import proof_deployer_file
from charmworld.views.utils import (
    get_bundle_downloads,
    json_response,
)


@view_config(route_name="search-json-obsolete")
@view_config(route_name="api-obsolete-0")
@view_config(route_name="api-obsolete-1")
def obsolete(request):
    message = 'This API version is no longer supported.'
    return Response(
        message,
        headerlist=[
            ('Access-Control-Allow-Origin', '*'),
            ('Access-Control-Allow-Headers', 'X-Requested-With'),
            ('Content-Type', 'text/plain'),
            ('Cache-Control', 'max-age=86400, public')
        ],
        status_code=410)


class API3:
    """Implementation of API 3.

    This API is unstable. It is under development. Use API2 if you need
    stability.

    All methods whose names do not begin with an underscore are exposed.
    Methods may return a webob Response, which is returned directly, or a
    json-serializable value, which will be returned as a json HTTP response.
    """
    TEST_STATUSES = ('SUCCESS', 'FAILURE', 'UNSTABLE', 'ABORTED')
    ICON_PATH = '/static/img/'
    ICON_TRAILING = 'file/icon.svg'
    API_ROOT = 'api_3'

    def __init__(self, request):
        self.request = request

    def _handle(self, handler, args, kwargs):
        spec = getargspec(handler)
        if spec.keywords is None:
            for key in set(kwargs).difference(spec.args):
                return json_response(406, {
                    'type': 'parameter_not_supported',
                    'parameter': key})
        return handler(*args, **kwargs)

    def __call__(self):
        """Dispatch the request to the appropriate method.

        Find a method with the same name as 'endpoint'.  Raise HTTPNotFound if
        the method doesn't exist or starts with '_'.

        Return a 406 response if the query parameters are not supported by the
        method.
        """
        if self.request.method == 'OPTIONS':
            return json_response(200, None)
        endpoint = self.request.matchdict['endpoint']
        if endpoint.startswith('_'):
            raise HTTPNotFound(self.request.path)
        handler = getattr(self, endpoint, None)
        remainder = self.request.matchdict.get('remainder')
        if handler is None:
            raise HTTPNotFound(self.request.path)
        if remainder:
            args = (remainder,)
        else:
            args = ()
        kwargs = self.request.GET.dict_of_lists()
        try:
            kwargs['type_'] = kwargs.pop('type')
        except KeyError:
            pass
        result = self._handle(handler, args, kwargs)
        if isinstance(result, Response):
            return result
        return json_response(200, result)

    @staticmethod
    def _get_api_id(charm):
        """Return the API ID for a Mongo-formatted charm."""
        return re.sub('^cs:', '', charm.store_url)

    @staticmethod
    def _parsed_email(address):
        name, address = parseaddr(address)
        return {
            'name': name,
            'email': address,
        }

    @classmethod
    def _format_revision(cls, revision):
        created = datetime.utcfromtimestamp(round(revision['created']))
        authors = [cls._parsed_email(author)
                   for author in revision['authors']]
        return{
            'message': revision['message'],
            'revno': revision['revno'],
            'date': timestamp(created),
            'authors': authors,
        }

    @classmethod
    def _charm_result(cls, charm):
        return {
            'charm': cls._format_charm(charm),
            'metadata': {
                'doctype': CHARM,
            }
        }

    @classmethod
    def _bundle_result(cls, bundle, db, route_url):
        """Build standard metadata around a bundle search result."""
        bundle_obj = Bundle(bundle)
        bundle_metadata = cls._build_bundle_metadata(bundle_obj, db, route_url)
        return {
            'bundle': bundle_metadata,
            'metadata': {
                'doctype': BUNDLE,
            }
        }

    def _related_charms(self, charm_data):
        charm = Charm(charm_data)
        charms_provide = set(charm.i_provides)
        charms_require = set(charm.i_requires)
        # Swap provides and requires, so we get the charms which *require*
        # what these charms provide, and the charms that *provide* what these
        # charms require.
        r_requires, r_provides = self.request.index_client.related_charms(
            charms_provide, charms_require, series=charm.series,
            exclude_name=charm.name)
        f_requires = {}
        for key, value in r_requires.items():
            f_requires[key] = [
                self._format_related(payload['data'], payload['weight'])
                for payload in value]
        f_provides = {}
        for key, value in r_provides.items():
            f_provides[key] = [
                self._format_related(payload['data'], payload['weight'])
                for payload in value]
        return f_requires, f_provides

    @classmethod
    def _format_charm(cls, charm, annotations=None):
        """Format the charm for API consumers."""
        mapping = {
            'summary': 'summary',
            'name': 'name',
            'description': 'description',
            'owner': 'owner',
            'downloads': 'downloads',
            'downloads_in_past_30_days': 'downloads_in_past_30_days',
            'distro_series': 'series',
            'revision': 'revision',
            'url': 'store_url',
        }
        output = dict(
            (key, getattr(charm, value)) for key, value in mapping.items())
        tested_providers = {}
        for provider, result in charm.tests.items():
            if result not in cls.TEST_STATUSES:
                raise ValueError('Unsupported test status: %s' % result)
            tested_providers[provider] = result
        maintainers = charm.maintainers
        maintainer = maintainers[0] if maintainers else ''
        bugs_link = 'https://bugs.launchpad.net/charms/+source/%s' % charm.name
        revisions = [cls._format_revision(rev) for rev in charm.changes]
        output.update({
            'id': cls._get_api_id(charm),
            'categories': charm.categories,
            'rating_numerator': 0,
            'rating_denominator': 0,
            'date_created': charm.date_created,
            'code_source': {
                'type': 'bzr',
                'location': charm.bzr_branch,
                'revision': str(charm.last_change['revno']),
                'last_log': charm.last_change['message'],
                'bugs_link': bugs_link,
                'revisions': revisions,
            },
            'maintainer': cls._parsed_email(maintainer),
            'maintainers': [cls._parsed_email(m) for m in maintainers],
            'relations': {
                'provides': charm.provides,
                'requires': charm.requires,
            },
            'options': charm.options,
            'files': [join(entry['subdir'], entry['filename'])
                      for entry in charm.files.values()],
            'is_approved': charm.promulgated,
            'tested_providers': tested_providers,
            'is_subordinate': charm.subordinate
        })
        if annotations is not None:
            output.update({'annotations': annotations})
        return output

    @classmethod
    def _format_related(cls, charm_data, weight, _now=None):
        if _now is None:
            now = datetime.utcnow()
        else:
            now = _now
        since = now - timedelta(30)
        charm = Charm(charm_data)
        icon_key = quote_key('icon.svg')
        result = {
            'id': cls._get_api_id(charm),
            'name': charm.name,
            'code_source': {
                'type': 'bzr',
                'location': charm.bzr_branch,
                'revision': str(charm.last_change['revno']),
                'last_log': charm.last_change['message'],
            },
            'has_icon': icon_key in charm.files,
            'categories': charm.categories,
            'downloads': charm.downloads,
            'downloads_in_past_30_days': charm.downloads_in_past_30_days,
            'commits_in_past_30_days': len(charm.changes_since(since)),
            'weight': weight,
            'is_approved': charm.promulgated,
        }
        return result

    @staticmethod
    def _extract_charm_id(path):
        """Extract the charm API ID from a path.

        Charm API IDs beginning with a '~' are considered to include an owner.
        If the first element of the path appears to be an owner, then the
        charm API ID consists of the first three path elements, otherwise it
        consists of the first two.
        """
        # Determine if the path includes an owner and adjust the split point
        # appropriately.
        if unquote(path[0])[0] == '~':
            split_point = 3
        else:
            split_point = 2
        # Now that we have figured out which path elements constitute the
        # charm API ID we can join them together.
        charm_id = '/'.join(path[:split_point])
        # Any remaining path elements will also be interesting to the caller.
        if len(path) > split_point:
            trailing = '/'.join(path[split_point:])
        else:
            trailing = None
        return charm_id, trailing

    @staticmethod
    def _parse_bundle_id(path):
        """Extract the bundle API ID from a given URL path.

        Bundle API IDs beginning with a '~' are considered to include an owner.
        Bundle IDs can consist of up to 4 parts.

        - owner (optional)
        - basket (required)
        - version (optional)
        - bundle (required)

        """
        if len(path) < 2:
            raise ValueError('The bundle ID does not contain enough elements')

        # Determine if the path includes an owner and adjust the backet index
        # appropriately.
        owner = None
        if unquote(path[0])[0] == '~':
            owner = path[0]
            basket = path[1]
        else:
            basket = path[0]

        # Now check if there's an optional revision section in there after the
        # basket name.
        version_index = 2 if owner else 1
        try:
            version = int(path[version_index])
        except (IndexError, ValueError):
            # If the url isn't long enough to have a version value, or the
            # value in that slot is not an integer, then no version was
            # provided.
            version = None

        if version is not None:
            if owner:
                # URL includes an owner, a basket, and a version.
                bundle = path[3]
            else:
                # URL does not include an owner and only has a basket,
                # version, and bundle name.
                bundle = path[2]
        else:
            if owner:
                # URL includes an owner, a basket, and a bundle name.
                bundle = path[2]
            else:
                # URL only includes a basket name and a bundle name.
                bundle = path[1]

        # So now we can pull out the parts that are the ID and the rest will
        # be the trailing.
        id_length = 2
        if owner:
            id_length = id_length + 1
        if version:
            id_length = id_length + 1
        parsedId = '/'.join(path[0:id_length])
        trailing = path[id_length:]

        return parsedId, trailing, {
            'owner': owner,
            'basket': basket,
            'version': version,
            'bundle': bundle
        }

    @staticmethod
    def _parse_charm_id(charm_id):
        """Split a charm ID into its component parts.

        Returns a tuple of (owner, series, name, revision).
        """
        elements = [unquote(element) for element in charm_id.split('/')]
        if len(elements) < 2:
            raise ValueError('charm ID does not contain enough elements')
        # If the charm ID includes a revision number, parse it out.
        if re.search('-\d+$', elements[-1]):
            name, revision = elements[-1].rsplit('-', 1)
        else:
            name = elements[-1]
            revision = None
        # If the charm ID includes an owner, parse it out.
        if len(elements) == 3:
            owner = elements[0]
            if not owner.startswith('~'):
                raise ValueError('Owner should begin with a "~".')
            else:
                owner = owner[1:]
        else:
            owner = None
        series = elements[-2]
        return owner, series, name, revision

    def _find_charm(self, path):
        charm_id, trailing = self._extract_charm_id(path)
        try:
            owner, series, name, revision = self._parse_charm_id(charm_id)
        except ValueError:
            charm = None
        else:
            query = {
                'series': series,
                'name': name,
            }
            if revision is not None:
                query['store_data.revision'] = int(revision)
            # If no owner is given, this must be a promulgated charm.
            if owner is None:
                query['promulgated'] = True
            else:
                query['promulgated'] = False
                query['owner'] = owner
            charm = self.request.db.charms.find_one(
                query, sort=[('store_data.revision', pymongo.DESCENDING)])
        return charm_id, trailing, charm

    @classmethod
    def _build_bundle_metadata(cls, bundle, db, route_url):
        bundle_dict = dict(bundle)
        # Add the list of files in the bundle.
        bundle_dict['files'] = bundle.get_file_list(db)
        bundle_dict['charm_metadata'] = {}
        bundle_dict['deployer_file_url'] = route_url(
            'personal-bundle-json-revision',
            basket=bundle_dict['basket_name'],
            bundle=bundle_dict['name'],
            owner=bundle_dict['owner'],
            rev=bundle_dict['basket_revision'],
        )

        # Add in download data.
        downloads = get_bundle_downloads(db, bundle.id)
        bundle_dict['downloads'] = downloads.total
        bundle_dict['downloads_in_past_30_days'] = downloads.past_30_days

        mongo_bundle = db.bundles.find_one({'_id': bundle.id})
        mongo_services = mongo_bundle['data']['services']
        service_data = bundle_dict.get('data')
        # Now load the charm information we require for the services in the
        # bundle.
        for service, data in bundle.data['services'].iteritems():
            description = BundledCharmDescription(
                service, data, service_data.get('series'))
            charm = resolve_charm_from_description(db, description)
            if charm:
                annotations = mongo_services[service].get('annotations')
                formatted = cls._format_charm(
                    Charm(charm), annotations=annotations)
                bundle_dict['charm_metadata'][service] = formatted
                if 'annotations' not in data:
                    data['annotations'] = annotations
        return bundle_dict

    def _find_bundle(self, path):
        try:
            bundle_id, trailing, bundle_bits = self._parse_bundle_id(path)
        except ValueError:
            bundle = bundle_id = trailing = bundle_bits = None
        else:
            if bundle_bits['owner'] and bundle_bits['version']:
                # We have all 4 parts needed, just use the ID.
                query = {'_id': bundle_id}
            elif bundle_bits['owner']:
                # This URL includes the owner, basket name, and bundle name.
                # The specified bundle may be promulgated or not.
                owner = bundle_bits['owner'][1:]  # Strip the tilde.
                query = {
                    'owner': owner,
                    'basket_name': bundle_bits['basket'],
                    'name': bundle_bits['bundle'],
                }
            else:
                query = {
                    'basket_name': bundle_bits['basket'],
                    'name': bundle_bits['bundle'],
                    'promulgated': True,
                }

            bundle = Bundle.from_query(query, self.request.db)
        return bundle_id, trailing, bundle

    def charm(self, path=None, **kwargs):
        """Retrieve a charm according to its API ID (the path prefix)."""
        if path is None:
            raise HTTPNotFound(self.request.path)
        charm_id, trailing, charm_data = self._find_charm(path)

        if path[0] == 'resolve-icon':
            return self._resolve_charm_icon_url(path[1:])

        if charm_data is None:
            return json_response(
                404, {'type': 'no_such_charm', 'charm_id': charm_id})

        charm = Charm(charm_data)
        if trailing is None:
            return self._charm_details(charm_data)
        elif trailing == self.ICON_TRAILING:
            return self._charm_icon(charm, kwargs.get('debug', False))
        elif trailing.startswith('file/'):
            return self._charm_file(charm, trailing)
        elif trailing == 'qa':
            return self._charm_qa(charm)
        elif trailing == 'related':
            return self._charm_related(charm_data)
        else:
            raise HTTPNotFound(self.request.path)

    def _bundle_file(self, bundle, filename):
        file_handle = bundle.get_file(self.request.db, filename)
        if file_handle is None:
            return json_response(
                404, {'type': 'no_such_file', 'file': filename})
        headerlist = self._get_file_headers(
            file_handle.md5, file_handle.content_type)
        return Response(
            file_handle.read(),
            headerlist=headerlist,
            status_code=200)

    bundle_metric_types = ('deployments',)

    def _bundle_metric(self, bundle_id, metric_name, operation):
        """Handle a request for a bundle metric.

        The metric_name will be something like "deployments" and the operation
        can be "total" (retrieve the current total) or "increment" (add one
        to the count).
        """
        # The metric names are a controlled vocabulary.
        if metric_name not in self.bundle_metric_types:
            raise HTTPNotFound
        # Define the key that corresponds to the desired metric.
        metric_key = build_metric_key(metric_name, bundle_id)
        # Create a metric source and look up (or create) the metric.
        source = DatedMetricSource.from_db(self.request.db)
        metric = source.retrieve(metric_key, create=True)
        # Do the thing we were asked to do.
        if operation == 'total':
            return metric.get_total()
        elif operation == 'increment':
            metric.increment()
            # Save the newly updated metric to the database.
            source.store(metric, metric_key)
            return
        else:
            raise HTTPNotFound('unexpected operation: %r' % operation)

    def bundle(self, path=None):
        """Retrieve a bundle based on ID."""
        if path is None:
            raise HTTPNotFound(self.request.path)
        path = list(path)

        if path[0] == 'proof':
            return proof_deployer_file(self.request)

        bundle_id, trailing, bundle = self._find_bundle(path)

        if bundle is None:
            status = 404
            result = {'type': 'no_such_bundle', 'bundle_id': '/'.join(path)}
            return json_response(status, result)
        if not trailing:
            bundle = self._build_bundle_metadata(
                bundle, self.request.db, self.request.route_url)
            return json_response(200, bundle)
        elif trailing and '/'.join(trailing) == self.ICON_TRAILING:
            return self._bundle_icon(bundle)
        elif trailing and trailing[0] == 'file':
            return self._bundle_file(bundle, '/'.join(trailing[1:]))
        elif trailing and trailing[0] == 'metric' and len(trailing) == 3:
            return json_response(
                200, self._bundle_metric(bundle_id, *trailing[1:]))
        else:
            raise HTTPNotFound('/'.join(path))

    @staticmethod
    def _get_file_headers(md5sum, content_type=None):
        headerlist = [
            ("Access-Control-Allow-Origin", "*"),
            ("Access-Control-Allow-Headers", "X-Requested-With"),
            ("Cache-Control", "max-age=86400, public"),
            ("Etag", '"%s"' % md5sum),
        ]
        if content_type is not None:
            headerlist.append(('Content-Type', content_type))
        return headerlist

    def _charm_details(self, charm_data):
        h = charm_data.get('hash')
        if h is not None:
            if_none_match = getattr(self.request, 'if_none_match', None)
            if if_none_match is not None and h in if_none_match:
                return Response('', status_code=304)
            result = self._charm_result(Charm(charm_data))
            return json_response(200, result, [('Etag', h)])
        return self._charm_result(Charm(charm_data))

    def _charm_file(self, charm, trailing):
        path = trailing.split('/', 1)[1]
        file_data = charm.files.get(quote_key(path.split('/')[-1]))
        if file_data is not None:
            if_none_match = getattr(self.request, 'if_none_match', None)
            if if_none_match is not None and file_data['md5'] in if_none_match:
                headerlist = self._get_file_headers(
                    file_data['md5'], file_data.get('contentType'))
                return Response('', headerlist=headerlist, status_code=304)
        fs = getfs(self.request.db)
        file_id = CharmFileSet.gen_fileid(charm._representation, path)
        try:
            charm_file = CharmFileSet.get_by_id(fs, file_id)
        except NoFile:
            return json_response(404, {'type': 'no_such_file', 'path': path})
        headerlist = self._get_file_headers(
            charm_file.md5, charm_file.contentType)
        return Response(
            charm_file.read(),
            headerlist=headerlist,
            status_code=200)

    def _charm_icon(self, charm, debug=False):
        if (charm.files and
                charm.files.get(quote_key('icon.svg')) and
                (debug or charm.promulgated)):
            return self._charm_file(charm, '/icon.svg')
        elif charm.categories:
            main_category = charm.categories[0]
            icon_url = "{0}charm-{1}.svg".format(self.ICON_PATH, main_category)
        else:
            icon_url = self.ICON_PATH + 'charm_160.svg'
        return HTTPFound(icon_url)

    def _resolve_charm_icon_url(self, identifiers):
        identifier = '/'.join(identifiers)
        charm_identification = {}
        series = None

        # Build the data the bundle to resolve it.
        if 'cs:' in identifier:
            # We have a charm: cs:....... to find the charm
            charm_identification['charm'] = identifier
        elif 'lp:' in identifier:
            # We have a branch: lp:.... to find the charm
            charm_identification['branch'] = identifier
        else:
            # See if we have a /series/name.
            bits = identifier.split('/')
            if len(bits) == 2:
                charm_identification['charm'] = bits[1]
                series = bits[0]

        # Find the charm
        charm_description = BundledCharmDescription(
            'skip_is_icon', charm_identification, series=series)
        charm = resolve_charm_from_description(
            self.request.db,
            charm_description)

        if charm:
            # Get the id
            charm = Charm(charm)
            icon_path = API3._get_api_id(charm) + '/file/icon.svg'
            icon_root = self.request.route_path(
                self.API_ROOT,
                endpoint='charm'
            )
            icon_url = icon_root + '/' + icon_path
        else:
            # If the charm is not found, use the default icon
            icon_url = self.ICON_PATH + 'charm_160.svg'

        # Redirect to the proper charm icon url for this charm
        return HTTPFound(icon_url)

    def _bundle_icon(self, bundle):
        # The bundle is currently hard coded to only ever have the one generic
        # icon file.
        icon_url = self.ICON_PATH + 'bundle.svg'
        return HTTPFound(icon_url)

    def _charm_related(self, charm_data):
        requires, provides = self._related_charms(charm_data)
        return {'result': {'requires': requires, 'provides': provides}}

    @staticmethod
    def _format_category(category):
        return dict((key, value) for key, value in category.items()
                    if key != '_id')

    def _charm_qa(self, charm):
        qa_data_source = QADataSource.from_db(self.request.db)
        qa_data = qa_data_source.get_qa_data(charm)
        categories = [self._format_category(category) for category
                      in qa_data.qa_categories.values()]
        scores = qa_data.filtered_scores()
        return {'result': {'questions': categories}, 'scores': scores}

    def search(self, path=None, *args, **kwargs):
        if path is None or path == ['']:
            handler = self._search
        elif path[0] == 'interesting':
            handler = self._interesting_charms_and_bundles
        else:
            raise HTTPNotFound(self.request.path)
        return self._handle(handler, args, kwargs)

    def _search(self, limit=None, name=None, series=None, owner=None,
                provides=None, requires=None, type_=None, provider=None,
                scope=None, categories=None, text=None, autocomplete=False,
                doctype=None, min_score=None):
        """Search for charms and bundles matching parameters.

        :limit: A query limit.  (The max number of results.)  Dispatched as a
           list of numeric characters representing an int, e.g. ['4'].
        :min_score: The minimum score for filtering.  Dispatched as a
           list of numeric characters representing a float, e.g. ['1.1'].
        """
        autocomplete = autocomplete == ['true']
        params = dict((key, value) for key, value in locals().items()
                      if key in ('series', 'owner', 'name', 'categories'))
        if text is None:
            text = ['']
        if min_score is not None:
            min_score = float(min_score[0])
        params['i_provides'] = provides
        params['i_requires'] = requires
        filters = dict(item for item in params.items() if item[1] is not None)
        if limit is not None:
            if len(limit) > 1:
                return json_response(406, {
                                     'type': 'multiple_values',
                                     'parameter': 'limit'})
            limit = int(limit[0])
        try:
            results = self.request.index_client.api_search(
                text[0], filters, type_, limit, autocomplete=autocomplete,
                doctype=doctype, min_score=min_score)
        except InvalidCharmType as e:
            return json_response(406, {
                                 'type': 'unsupported_value',
                                 'parameter': 'type',
                                 'value': e[0]})
        except NegativeLimit:
            return json_response(406, {
                                 'type': 'negative_value',
                                 'parameter': 'limit'})
        return {'result': self._item_results(results)}

    def _item_results(self, items):
        results = []
        for item in items:
            if item['doctype'] == BUNDLE:
                result = self._bundle_result(
                    Bundle(item['data'])._representation,
                    self.request.db,
                    self.request.route_url)
            else:
                result = self._charm_result(Charm(item['data']))
            results.append(result)
        return results

    def _interesting_charms_and_bundles(self, doctype=None):
        """Generate a JSON structure of interesting charms.

        Includes featured, new and popular charms.
        """
        db = self.request.db
        popular = self.request.index_client.api_search(
            sort='downloaded', doctype=doctype, limit=10)
        new = self.request.index_client.api_search(
            sort='new', doctype=doctype, limit=10)
        typed_ids = FeaturedSource.from_db(db).get_featured_typed_ids(doctype)
        featured = self.request.index_client.get_items(typed_ids)
        return {
            'result': {
                'new': self._item_results(new),
                'featured': self._item_results(featured),
                'popular': self._item_results(popular),
            }
        }


class API2(API3):
    """Implementation of API 2.

    This API is stable.

    All methods whose names do not begin with an underscore are exposed.
    Methods may return a webob Response, which is returned directly, or a
    json-serializable value, which will be returned as a json HTTP response.
    """
    ICON_TRAILING = 'icon.svg'
    API_ROOT = 'api_2_single'

    def charms(self, path=None, *args, **kwargs):
        kwargs['doctype'] = CHARM
        if path is None or path == ['']:
            handler = self._search
        elif path[0] == 'interesting':
            handler = self._interesting_charms_and_bundles
        else:
            raise HTTPNotFound(self.request.path)
        return self._handle(handler, args, kwargs)

    def _find_charm(self, path):
        charm_id, trailing = self._extract_charm_id(path)
        try:
            owner, series, name, _ = self._parse_charm_id(charm_id)
        except ValueError:
            charm = None
        else:
            if name.endswith('-HEAD'):
                name = name[:-5]
            if owner is None:
                charm = self.request.db.charms.find_one({
                    'promulgated': True,
                    'series': series,
                    'name': name,
                }, sort=[('store_data.revision', pymongo.DESCENDING)])
            else:
                charm = self.request.db.charms.find_one({
                    'owner': owner,
                    'series': series,
                    'name': name,
                }, sort=[('store_data.revision', pymongo.DESCENDING)])
        if charm is not None:
            api_id = self._get_api_id(Charm(charm))
            # Charm ID should match up to, but not including the revision.
            revisionless_charm_id = charm_id.split('-', 1)[0]
            if not api_id.startswith(revisionless_charm_id):
                charm = None
        return charm_id, trailing, charm