0 foreword
This article focuses on how to develop the SDK based on JavaScript. Similar ideas can be applied to any JS-BASED scenario, whether it is mobile H5 or pure NodeJS on the server side. This paper will mention some design principles and implementation skills, and combined with the practical case of YUEying panoramic monitoring platform SDK to show how to apply them.
1 What is the SDK
SDK stands for Software Development Kit, which literally means a set of Software Development tools. In more general terms, it is a software package for developers and specific domains. The Java SDK (JDK), for example, is a software package for the Java domain. It allows developers to quickly build their own Java applications. Standard SDKS typically include several apis, development toolsets, and documentation.
Js-sdk is no different, but due to the characteristics of THE JS language itself, THE SDK based on Ta encapsulation is more common in UI component libraries, statistical analysis, Web services interface encapsulation, front-end stability and performance monitoring and other scenarios. The SDK of Yueying Panoramic monitoring platform mentioned in the previous section belongs to the field of front-end stability and performance monitoring.
2 Design Principles
How you design the SDK really depends more on your scenario, or what the SDK ends up being used for. For example, there are obvious differences between the SDK for implementing a call to a web page and the SDK for the server side, but there are some common principles, or methodologies:
- The principle of minimum availability is to use the least amount of code and not add entities unnecessarily
- The principle of least dependence, that is, the minimum external dependence, if not necessary do not increase dependence
To further elaborate, we build SDKS that meet the following requirements
2.1 Meet functional requirements
SDKS tend to be domain-oriented, so it’s important to have clear responsibilities and boundaries in design and implementation, and to be lean and domain-focused.
2.2 Stable enough
- Never cause the host application to crash. This is the most basic and strict requirement
- Better performance, such as the SDK should be as small and fast as possible
- Testable to protect every change
- Backward compatibility, no Breakchange
2.3 Less dependence, easy to expand
- Minimum third party dependencies, self-implementation as far as possible, and minimum introduction if unavoidable
- Plug-in, maximum support for expansion
- Hook mechanism to meet personalized demands
3 How to Implement it
Below, we will analyze the design process of Yueying front-end monitoring SDK to see how the above design principles are applied to the actual development process.
3.1 Define responsibilities and boundaries
As mentioned in the previous chapter, Yueying front-end monitoring SDK is the SDK for front-end stability and performance monitoring, which is mainly oriented to the front-end H5 field. Therefore, a little analysis can draw the following conclusions
- Front end area, stability is the main concern
- JS abnormal
- Resource loading exception
- API request exception
- White during abnormal
- Performance, core concerns
- Bad time
- Interactive time (TTI)
- The first screen time
- FP/FMP/FCP etc
The above monitoring contents are actually relatively independent, so we can divide them horizontally into the following parts:
Having defined the boundaries of the SDK and the responsibilities of each part, and combined with the features of front-end monitoring, we can begin to design the overall framework of the SDK.
3.2 Build the frame and ram the foundation
As the saying goes, a journey of a thousand miles begins with a single step, so it is important to build a solid foundation. In general, we need to do the following
- First determine the SDK reference form
SDK is a large Module as a whole, and front-end Module has various forms of expression: ES Module, CommonJS, AMD/CMD/UMD, while reference can be roughly divided into CDN and NPM. That is, no matter what kind of module we implement, it is ultimately provided to users for reference through CDN or NPM.
Import wpkReporter from 'wpkReporter' // CommonJS const wpkReporter = require('wpkReporter') // AMD,requireJS reference require.config({ paths: { "wpk": "https://g.alicdn.com/woodpeckerx/jssdk/wpkReporter.js", } }) require(['wpk', 'test'], function (wpk) { // do your business })Copy the code
It’s a little confusing at first glance, but there are a lot of tools in front end engineering today that can help us get there. Webpack, for example, can be easily configured to build a UMD bundle.
module.exports = {
output: {
filename: '[name].js',
path: `${__dirname}/dist`,
globalObject: 'this',
library: '[name]',
libraryTarget: 'umd'
}
}
Copy the code
To sum up, we can use WebPack to build the SDK as a UMD bundle that automatically ADAPTS to all forms of modules. At the same time, we will also provide CDN and NPM reference methods to give users more choices.
- Determine the SDK version management mechanism
The existing more mature version management mechanism should be semantic version number, in the form of {major version}.{minor version}.{patch version}, which is easy to remember and manage. A major change usually triggers a major version number change, and it is likely that the old version is incompatible with the new. This release mainly corresponds to new features or major changes, so breakchanges are also possible. Other minor optimizations or bugfixes are mostly in the patch version number. Does this sound like deja vu? Yes, all NPM modules follow the semantic versioning specification, so in combination with the first point, we can initialize the SDK as an NPM module, and combine webPack capabilities with basic versioning and module building.
- Identify the basic interface for the SDK
Interfaces are the bridge between the SDK and the user. Each interface corresponds to an independent SDK function and has clear input and output. We can first take a look at yueying front-end monitoring SDK core interface?
Wpk.report (logData) wpk.ReportJserror (error) wpk.reportAPIError(apiData) // Configuration change wpk.setConfig(data) // SDK diagnosis Wpk.addplugin (plugin) wpk.addPlugin(plugin)Copy the code
The principles of interface design are summarized as follows
- Responsibility of the single
An interface only does one thing
- Simple and clear naming, parameters as few as possible but extensible
A good interface name is the best comment, and it is obvious that its useful parameters apply to Object encapsulation as much as possible
- Perform parameter verification and logical protection
3.3 Domain analysis and module division
When defining boundaries, we have clearly defined several key parts of the SDK: global exceptions, API exceptions, page performance, and blank screen. In fact, monitoring SDKS often have built-in monitoring of page traffic, so that users can assess the impact of exceptions. Each of these core key components corresponds to a specialized domain, and therefore corresponds to each independent module of the SDK. In addition to these core domain-specific modules, the SDK also needs more basic domain-independent modules, including the SDK kernel (constructors, plug-in mechanisms, interactions with downstream services, reporting queue mechanisms, management of different environments, and so on) and tool-class libraries. We can first look at the overall module division of yueying front-end monitoring SDK:
- The SDK layer provides the basic capabilities, including the kernel mentioned above, the implementation of the plug-in mechanism, the utility class library, and the basic API exposed to the user
- It can be seen that all the modules mentioned above exist in the form of plug-ins, that is, functions in various fields are implemented loosely, which makes the underlying capabilities more universal and has stronger expansion capability. Users can even encapsulate their plug-ins.
- The Biz section is more of a multi-portal adaptation for different host environments, currently supporting browsers, Weex, and NodeJS.
3.4 Test coverage, no worries online
The SDK is a basic service, perhaps more low-level than the front end business. The impact is proportional to the scope of the application, and more users mean more responsibility. So SDK quality assurance is also very important. Yueying front-end monitoring SDK quality assurance strategy is very simple, only two
- 100% unit test coverage of the core interface
- Release point: Even a small release requires integration test regression
In fact, except for the core interface, we have achieved 100% unit test coverage for all functions of the tool class library, and we use the lightweight front-end testing tool Jest.
test('isError: real error', function () {
var err = new Error('this is an error')
expect(util.isError(err)).toBeTruthy()
})
Copy the code
3.5 Details grinding, ultimate experience
- Quick introduction
- Do everything you can to make user references more efficient
- One line of code, fast introduction, enjoy monitoring the whole family bucket function
<script> ! (function(c,i,e,b){var h=i.createElement("script"); var f=i.getElementsByTagName("script")[0]; h.type="text/javascript"; h.crossorigin=true; h.onload=function(){c[b]||(c[b]=new c.wpkReporter({bid:"dta_1_203933078"})); c[b].installAll()}; f.parentNode.insertBefore(h,f); h.src=e})(window,document,"https://g.alicdn.com/woodpeckerx/jssdk/wpkReporter.js","__wpk"); </script>Copy the code
-
The dynamic sampling
- That is, the cloud delivers data sampling rate to control the data reporting frequency of the client
- Better protection monitoring downstream
-
Self diagnosis
- Apart from the interface, the SDK is a black box to the user, so it is easy for the user to be confused when encountering problems (e.g., why the data is not reported).
- The SDK can provide a self-diagnosing interface to quickly troubleshoot underlying problems
- For example, whether the SDK is properly initialized and key parameters are properly set
-
The debugging mode is added to output more detailed process logs for fault locating
-
Progressive guidance documents
- Illustrated and step-by-step
- Introduction, step by step to guide users to know the SDK, appreciate the overview, learn the basic use
- Further, amway SDK in-depth usage to help users better use SDK
4 conclusion
There are many more issues to deal with during SDK design and development, such as how to reference NPM modules locally when they are developed, how to tune the size of bundles built, and so on. However, I still hope to read this article and inspire you. At the same time, if the article is wrong, but also hope to give advice.
Visit yueying panoramic monitoring platform