Знакомство с ESI - Новым API для EVE ONLINE
Опубликован: 2016-11-08 18:44
Внимание: Этот блог в первую очередь предназначен для разработчиков сторонних приложений EVE ONLINE и пилотов интересующихся технической реализацией аспектов игры. Если используемый технический жаргон хочется пропустить, то всю информацию можно найти в конце сообщения в разделе TL;DR.
Вас приветствует команда Tech Co! И у нас есть для вас интересный разговор о том, как Сделать API Снова Великим (Прим. пер. - Отсылка к слогану Трампа в предвыборной гонке 2016 года Make Amerika Great Again)
Предыстория
Когда впервые был представлен XML API ( eXtensible Markup Language Application Programming Interface - Интерфейс программирования приложений использующий расширяемый язык разметки), то это было что-то совершенно новаторское решение. Ни одна игра на тот момент не предоставляла такой обширный доступ к своим данным и разработчики создали потрясающие вещим с этим API. EVEMon и EFT - вот те легендарные программы которые поддерживали EVE долгие годы. Они вошли в состав целой плеяды новых и мощных инструментов созданных пользователями EVE на основе XML API. При этом API был весьма ограничен, давал доступ только к небольшому перечню данных, работал только на чтение и временами несвоевременно получал данные об изменении произошедших в игре. Что самое важное документация по этому API была просто ужасна и всегда не соответствовала текущему состоянию разработки.
Так что дальше мы представили CREST и это так же было чем-то совершенно новый новаторский инструмент. В нём был представлен более чистый формат данных, использовался интерфейс на основе REST архитектуры и реализован более быстрый доступ к оперативным данным данным. В конечном итоге CREST дал возможность реализовать доступные для записи конечные точки API (Конечные точки - структуры API непосредственно хранящие / обеспечивающие доступ к данным) - неслыханное дело для игровой индустрии. В результате на основе CREST были созданы просто потрясающие решения использующие большую часть заложенных в него возможностей, кстати количество новых решений постоянно растёт.
Так же CREST в идеале должен был быть самодокументируемым. Комбинация автоматически генерируемых вызовов опций и используемой парадигмы ссылок от корня API казалось бы создала полностью самодокументируемый API. Но это было не совсем так. Конечно, обходя ветки дерева CREST API пользователи могли узнать его лучше, но в то же время большая часть древа могла быть им недоступна если только не выполнялись определенные игровые условия, например пилоту были установлены правильные роли в корпорации или он был владельцем цитадели. Так же были проблемы с тем, что на которые ресурсы не были правильно установлены ссылки. Было сложно получить объяснение тому почему невозможно получить доступ к объекту. Разработчикам приходилось постоянно пользоваться сторонними описаниями API. Это была хорошая попытка, но кой-чего не хватало.
Компания ССР всегда была на переднем крае игровой индустрии в разработке API, и они точно не собираются останавливаться на достигнутом и почивать на лаврах. Они создали хорошие вещи CREST и XML API, внимательно проанализировали выявленные недостатки и вот теперь время их модернизировать! Читаем дальше…
Тем временем, в широкой промышленности…
Последние несколько лет остальные участники индустрии разработки ПО были заняты разработкой различных API и согласовывая из дизайн. Из хаоса различных самодельных стандартов основанных на JSON-схеме (JavaScript Object Notation - текстовый формат обмена данными, основанный на JavaScript) родилась спецификация Swagger (Теперь известная как OpenAPI). Эта спецификация и лежит в основе ESI. Вот как описывают разработчики спецификацию Swagger:
Swagger™ это проект используемый для описания и генерации документации различных API основанных на архитектуре REST.
Спецификация Swagger определяет набор файлов требуемых для описания таких API. Эти файлы потом могут быть использованы проектом Swagger-UserInterface для отображения API, а так же с помощью Swagger-Codegen генерировать клиентов на различных языках программирования. Так же эти файлы могут использовать и другие утилиты, например утилиты для тестирования кода.
Swagger уже широко распространенный стандарт описания API и поддерживается несколькими уважаемыми организациями, что вселяет уверенность в его долговечности и то что он и далее будет поддерживаться в различных библиотеках, пользовательских интерфейсах и прочих инструментах. Адаптация этой спецификации для нужд EVE позволит снять с разработчиков большой объем работы и в то же время позволяет определить где начинается разработка каких-либо дополнительных решений по интеграции.
It is on this foundation that we’ve chosen to build the EVE Swagger Interface, a framework which aggregates partial specs from multiple Kubernetes services into a cohesive front facing spec, while also handling the routing, authentication, input/output validation, and more. The EVE Swagger Interface (ESI for short and pronounced “easy”) uses Flask and Python 3.4+ internally, and should be generic enough to power any oauth-backed (or unauthed), multi-tenant API running in a Kubernetes cluster. There are also options for running ESI locally with either Docker or directly with local Python.
Что значит ESI для нас?
В течении последних нескольких месяцев мы использовали и параллельно вели разработку фреймворка ESI для построения нового API с нуля. Интерфейс ESI основан на архитектуре REST, Использует для аунтетификации SSO, документирован, горизонтально маштабируем,
Over the last few months, we’ve been using and developing the ESI framework to build a new API from the ground up. The ESI API is a RESTful, SSO authenticated, documentation first, buzzword compliant, horizontally scalable, read/write API. It’s currently backing the EVE Mobile app and running on a Kubernetes cluster in Google Cloud (Kubernetes is awesome btw). What the devil does that all mean?
RESTful and SSO authenticated means that you interact with it largely the same way you do with CREST. You’ll use HTTPS requests with bearer authorisation tokens if the endpoint requires auth. If you’ve ever done CREST development this will be like sitting down in a comfortable armchair for you.
Documentation first means that internally, we use the Swagger spec to generate our APIs. Step one of creating or updating an endpoint is creating or updating the spec, that defines all our internal data structures for processing incoming requests to that endpoint, and that means the documentation is always up to date because it’s an integral part of coding an endpoint, guaranteed. Don’t look now, but we might have solved this documentation gremlin. Additionally, the Swagger spec allows the third party community to use code generators to create native code interfaces for the ESI API in their language of choice. Large amounts of engineering time that have been spent laboriously hand-constructing interfaces for CREST and the XML API can now be freed from this boilerplate work. (We’re replacing you with robots, sorry.)
Buzzword compliant means we’re using industry standard tooling. The custom glue holding this ship together is as minimal as possible, and we swap out the custom stuff for off-the-shelf open source technology when solutions become available. No EVE API has ever been this maintainable or scalable, and this provides new capabilities we’ve never had before. Minor patches can go from a developers computer to live production in minutes, and if need be can be rolled back just as fast with zero downtime in either direction.
Horizontal scalability is a neat capability we get from Kubernetes. Because all ESI code that doesn’t specifically need to be running inside Tranquility is both stateless and running in Google Cloud, we can manage load by spinning up new ESI containers on a per endpoint basis as needed, and shut them down again when they are no longer needed.
Read/write, of course, means we’re planning on making writeable API endpoints just like CREST, including some of the ones that have been problematic until now, like sending mail. Basically, it’s like CREST, but better.
Что будет с XML API и CREST?
This is the part where you don’t panic. We’re not here to announce that we’re killing all your applications and you need to rewrite things immediately, but we do need to talk about sanity and fragmentation. Supporting three API’s with similar but non-overlapping functionality increases the technical difficulty of making an EVE API enabled application, and it pulls the engineering time of Tech Co away from features and towards maintenance. It reduces agility and increases uncertainty, and it’s not a good long term plan.
Once we replicate all current CREST and XML API functionality in ESI, we will be shutting down both services. We are targeting 18 months from the release of this blog to achieve functional equivalence and work with application developers to upgrade their applications. Removing the need to use the XML API will be our first priority. We will be monitoring use of the XML API and CREST to both identify and assist third party developers in their migration efforts.
This is going to be an orderly and measured winding down of operations. As the first step of that, developers should know that as of the release of this blog, CREST and the XML API are officially in maintenance only mode. We will continue to deploy security updates and critical bug fixes to them, but any new feature requests will be implemented in the ESI API.
Early access
Over the past month or so, we’ve been working closely with several active members of the third party developer community, including:
Steve Ronuken, CSM member and creator of fuzzwork.co.uk
Lucia Denniard, prolific #devfleet poster and pizza-auth/timerboard.net developer
Squizz Caphinator, creator of zkillboard.com and evewho.com
We coordinated with this team, similar as with a focus group, to gain feedback on the early development cycles and some initial design decisions. Here’s what they have to say about their experiences so far:
The introduction of ESI, while a new API, is similar enough to how CREST works, that conversion should be relatively simple. It also solves one of the huge bugbears of EVE API development. A lack of documentation and examples. The use of Swagger makes this a lot easier to work with, and some inconsistencies are being cleaned up as development happens. Finally opening up the ability to send EVEMail, as well as receive it, is a major deal, allowing for some automated services which couldn’t otherwise be done.
- Steve Ronuken
ESI is a solution to a problem that CCP has had for several years: the inability to quickly and easily update the API for 3rd parties. Over the last few weeks the devs I have worked with have demonstrated that ESI is adaptable and have demonstrated the ability to implement new features quickly. I know many 3rd party developers will not be happy about having to rewrite many of their tools, I am one of them, but this is the price for the technical debt we have incurred. CCP is looking to move past technical debt and bring us a modern approach. EveWho.com is already utilizing ESI and I’m quite happy with the results so far.
- Squizz Caphinator
The EVE Swagger Interface combines the usability of the XML API with the features of CREST while introducing documentation as an official feature. CREST’s crawlable type system enabled people to do some great things with dynamic languages, ESI closes that gap for those of us using statically typed languages; providing much stronger interface definitions and improving on the usability aspects of CREST. I believe that this project is the perfect follow-up to improve on CREST, modernize the XML API, and make EVE development easier for newcomers.
- Lucia Denniard
TL;DR
Это новый API для EVE, который назвали ESI. Он основан на спецификации OpenAPI, которая отлично документирована и облегчит жизнь разработчикам приложений для EVE Online. В течении следующих нескольких месяцев будет наращиваться его производительность, уже сейчас этот интерфейс обслуживает до четырёх с половиной миллионов запросов в сутки.
Для простых пользователей EVE запуск нового интерфейса приведёт к тому что в ближайшие год-два приложения начнут меньше использовать api-ключи и мигрировать на использование SSO метода для авторизации. SSO - это более безопасный метод авторизации, к тому же его проще реализовать в разрабатываемых приложениях.
ESI уже используется в новом мобильном приложении EVE, а ещё несколькими сторонними разработчиками. Посмотреть поближе на новый интерфейс вживую можно уже сейчас на http://esi.tech.ccp.is/
PS: Если у Вас есть заинтересованность более подробно узнать о дизайне ESI, то это можно cделать в статье “Знакомство с API ESI”
Источник EVE Dev Blog